1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/zygote/zygote_linux.h"
9 #include <sys/socket.h>
10 #include <sys/types.h>
13 #include "base/command_line.h"
14 #include "base/debug/trace_event.h"
15 #include "base/files/file_util.h"
16 #include "base/linux_util.h"
17 #include "base/logging.h"
18 #include "base/macros.h"
19 #include "base/memory/scoped_vector.h"
20 #include "base/pickle.h"
21 #include "base/posix/eintr_wrapper.h"
22 #include "base/posix/global_descriptors.h"
23 #include "base/posix/unix_domain_socket_linux.h"
24 #include "base/process/kill.h"
25 #include "content/common/child_process_sandbox_support_impl_linux.h"
26 #include "content/common/sandbox_linux/sandbox_linux.h"
27 #include "content/common/set_process_title.h"
28 #include "content/common/zygote_commands_linux.h"
29 #include "content/public/common/content_descriptors.h"
30 #include "content/public/common/result_codes.h"
31 #include "content/public/common/sandbox_linux.h"
32 #include "content/public/common/send_zygote_child_ping_linux.h"
33 #include "content/public/common/zygote_fork_delegate_linux.h"
34 #include "ipc/ipc_channel.h"
35 #include "ipc/ipc_switches.h"
36 #include "sandbox/linux/services/syscall_wrappers.h"
38 #if defined(ADDRESS_SANITIZER)
39 #include <sanitizer/asan_interface.h>
42 // See http://code.google.com/p/chromium/wiki/LinuxZygote
48 // NOP function. See below where this handler is installed.
49 void SIGCHLDHandler(int signal
) {
52 int LookUpFd(const base::GlobalDescriptors::Mapping
& fd_mapping
, uint32_t key
) {
53 for (size_t index
= 0; index
< fd_mapping
.size(); ++index
) {
54 if (fd_mapping
[index
].key
== key
)
55 return fd_mapping
[index
].fd
;
60 void CreatePipe(base::ScopedFD
* read_pipe
, base::ScopedFD
* write_pipe
) {
62 PCHECK(0 == pipe(raw_pipe
));
63 read_pipe
->reset(raw_pipe
[0]);
64 write_pipe
->reset(raw_pipe
[1]);
67 void KillAndReap(pid_t pid
, ZygoteForkDelegate
* helper
) {
69 // Helper children may be forked in another PID namespace, so |pid| might
70 // be meaningless to us; or we just might not be able to directly send it
71 // signals. So we can't kill it.
72 // Additionally, we're not its parent, so we can't reap it anyway.
73 // TODO(mdempsky): Extend the ZygoteForkDelegate API to handle this.
74 LOG(WARNING
) << "Unable to kill or reap helper children";
78 // Kill the child process in case it's not already dead, so we can safely
79 // perform a blocking wait.
80 PCHECK(0 == kill(pid
, SIGKILL
));
81 PCHECK(pid
== HANDLE_EINTR(waitpid(pid
, NULL
, 0)));
86 Zygote::Zygote(int sandbox_flags
, ScopedVector
<ZygoteForkDelegate
> helpers
,
87 const std::vector
<base::ProcessHandle
>& extra_children
,
88 const std::vector
<int>& extra_fds
)
89 : sandbox_flags_(sandbox_flags
),
90 helpers_(helpers
.Pass()),
91 initial_uma_index_(0),
92 extra_children_(extra_children
),
93 extra_fds_(extra_fds
) {}
98 bool Zygote::ProcessRequests() {
99 // A SOCK_SEQPACKET socket is installed in fd 3. We get commands from the
101 // A SOCK_DGRAM is installed in fd 5. This is the sandbox IPC channel.
102 // See http://code.google.com/p/chromium/wiki/LinuxSandboxIPC
104 // We need to accept SIGCHLD, even though our handler is a no-op because
105 // otherwise we cannot wait on children. (According to POSIX 2001.)
106 struct sigaction action
;
107 memset(&action
, 0, sizeof(action
));
108 action
.sa_handler
= &SIGCHLDHandler
;
109 CHECK(sigaction(SIGCHLD
, &action
, NULL
) == 0);
111 if (UsingSUIDSandbox()) {
112 // Let the ZygoteHost know we are ready to go.
113 // The receiving code is in content/browser/zygote_host_linux.cc.
114 bool r
= UnixDomainSocket::SendMsg(kZygoteSocketPairFd
,
116 sizeof(kZygoteHelloMessage
),
118 #if defined(OS_CHROMEOS)
119 LOG_IF(WARNING
, !r
) << "Sending zygote magic failed";
120 // Exit normally on chromeos because session manager may send SIGTERM
121 // right after the process starts and it may fail to send zygote magic
122 // number to browser process.
124 _exit(RESULT_CODE_NORMAL_EXIT
);
126 CHECK(r
) << "Sending zygote magic failed";
131 // This function call can return multiple times, once per fork().
132 if (HandleRequestFromBrowser(kZygoteSocketPairFd
))
137 bool Zygote::GetProcessInfo(base::ProcessHandle pid
,
138 ZygoteProcessInfo
* process_info
) {
139 DCHECK(process_info
);
140 const ZygoteProcessMap::const_iterator it
= process_info_map_
.find(pid
);
141 if (it
== process_info_map_
.end()) {
144 *process_info
= it
->second
;
148 bool Zygote::UsingSUIDSandbox() const {
149 return sandbox_flags_
& kSandboxLinuxSUID
;
152 bool Zygote::HandleRequestFromBrowser(int fd
) {
153 ScopedVector
<base::ScopedFD
> fds
;
154 char buf
[kZygoteMaxMessageLength
];
155 const ssize_t len
= UnixDomainSocket::RecvMsg(fd
, buf
, sizeof(buf
), &fds
);
157 if (len
== 0 || (len
== -1 && errno
== ECONNRESET
)) {
158 // EOF from the browser. We should die.
159 // TODO(earthdok): call __sanititizer_cov_dump() here to obtain code
160 // coverage for the Zygote. Currently it's not possible because of
161 // confusion over who is responsible for closing the file descriptor.
162 for (std::vector
<int>::iterator it
= extra_fds_
.begin();
163 it
< extra_fds_
.end(); ++it
) {
164 PCHECK(0 == IGNORE_EINTR(close(*it
)));
166 #if !defined(ADDRESS_SANITIZER)
167 // TODO(earthdok): add watchdog thread before using this in non-ASAN builds.
168 CHECK(extra_children_
.empty());
170 for (std::vector
<base::ProcessHandle
>::iterator it
=
171 extra_children_
.begin();
172 it
< extra_children_
.end(); ++it
) {
173 PCHECK(*it
== HANDLE_EINTR(waitpid(*it
, NULL
, 0)));
180 PLOG(ERROR
) << "Error reading message from browser";
184 Pickle
pickle(buf
, len
);
185 PickleIterator
iter(pickle
);
188 if (iter
.ReadInt(&kind
)) {
190 case kZygoteCommandFork
:
191 // This function call can return multiple times, once per fork().
192 return HandleForkRequest(fd
, iter
, fds
.Pass());
194 case kZygoteCommandReap
:
197 HandleReapRequest(fd
, iter
);
199 case kZygoteCommandGetTerminationStatus
:
202 HandleGetTerminationStatus(fd
, iter
);
204 case kZygoteCommandGetSandboxStatus
:
205 HandleGetSandboxStatus(fd
, iter
);
207 case kZygoteCommandForkRealPID
:
208 // This shouldn't happen in practice, but some failure paths in
209 // HandleForkRequest (e.g., if ReadArgsAndFork fails during depickling)
210 // could leave this command pending on the socket.
211 LOG(ERROR
) << "Unexpected real PID message from browser";
220 LOG(WARNING
) << "Error parsing message from browser";
224 // TODO(jln): remove callers to this broken API. See crbug.com/274855.
225 void Zygote::HandleReapRequest(int fd
,
226 PickleIterator iter
) {
227 base::ProcessId child
;
229 if (!iter
.ReadInt(&child
)) {
230 LOG(WARNING
) << "Error parsing reap request from browser";
234 ZygoteProcessInfo child_info
;
235 if (!GetProcessInfo(child
, &child_info
)) {
236 LOG(ERROR
) << "Child not found!";
241 if (!child_info
.started_from_helper
) {
242 // Do not call base::EnsureProcessTerminated() under ThreadSanitizer, as it
243 // spawns a separate thread which may live until the call to fork() in the
244 // zygote. As a result, ThreadSanitizer will report an error and almost
245 // disable race detection in the child process.
246 // Not calling EnsureProcessTerminated() may result in zombie processes
247 // sticking around. This will only happen during testing, so we can live
248 // with this for now.
249 #if !defined(THREAD_SANITIZER)
250 // TODO(jln): this old code is completely broken. See crbug.com/274855.
251 base::EnsureProcessTerminated(base::Process(child_info
.internal_pid
));
253 LOG(WARNING
) << "Zygote process omitting a call to "
254 << "base::EnsureProcessTerminated() for child pid " << child
255 << " under ThreadSanitizer. See http://crbug.com/274855.";
258 // For processes from the helper, send a GetTerminationStatus request
259 // with known_dead set to true.
260 // This is not perfect, as the process may be killed instantly, but is
261 // better than ignoring the request.
262 base::TerminationStatus status
;
264 bool got_termination_status
=
265 GetTerminationStatus(child
, true /* known_dead */, &status
, &exit_code
);
266 DCHECK(got_termination_status
);
268 process_info_map_
.erase(child
);
271 bool Zygote::GetTerminationStatus(base::ProcessHandle real_pid
,
273 base::TerminationStatus
* status
,
276 ZygoteProcessInfo child_info
;
277 if (!GetProcessInfo(real_pid
, &child_info
)) {
278 LOG(ERROR
) << "Zygote::GetTerminationStatus for unknown PID "
283 // We know about |real_pid|.
284 const base::ProcessHandle child
= child_info
.internal_pid
;
285 if (child_info
.started_from_helper
) {
286 if (!child_info
.started_from_helper
->GetTerminationStatus(
287 child
, known_dead
, status
, exit_code
)) {
291 // Handle the request directly.
293 *status
= base::GetKnownDeadTerminationStatus(child
, exit_code
);
295 // We don't know if the process is dying, so get its status but don't
297 *status
= base::GetTerminationStatus(child
, exit_code
);
300 // Successfully got a status for |real_pid|.
301 if (*status
!= base::TERMINATION_STATUS_STILL_RUNNING
) {
302 // Time to forget about this process.
303 process_info_map_
.erase(real_pid
);
308 void Zygote::HandleGetTerminationStatus(int fd
,
309 PickleIterator iter
) {
311 base::ProcessHandle child_requested
;
313 if (!iter
.ReadBool(&known_dead
) || !iter
.ReadInt(&child_requested
)) {
314 LOG(WARNING
) << "Error parsing GetTerminationStatus request "
319 base::TerminationStatus status
;
322 bool got_termination_status
=
323 GetTerminationStatus(child_requested
, known_dead
, &status
, &exit_code
);
324 if (!got_termination_status
) {
325 // Assume that if we can't find the child in the sandbox, then
326 // it terminated normally.
328 status
= base::TERMINATION_STATUS_NORMAL_TERMINATION
;
329 exit_code
= RESULT_CODE_NORMAL_EXIT
;
333 write_pickle
.WriteInt(static_cast<int>(status
));
334 write_pickle
.WriteInt(exit_code
);
336 HANDLE_EINTR(write(fd
, write_pickle
.data(), write_pickle
.size()));
337 if (written
!= static_cast<ssize_t
>(write_pickle
.size()))
338 PLOG(ERROR
) << "write";
341 int Zygote::ForkWithRealPid(const std::string
& process_type
,
342 const base::GlobalDescriptors::Mapping
& fd_mapping
,
343 const std::string
& channel_id
,
344 base::ScopedFD pid_oracle
,
345 std::string
* uma_name
,
347 int* uma_boundary_value
) {
348 ZygoteForkDelegate
* helper
= NULL
;
349 for (ScopedVector
<ZygoteForkDelegate
>::iterator i
= helpers_
.begin();
352 if ((*i
)->CanHelp(process_type
, uma_name
, uma_sample
, uma_boundary_value
)) {
358 base::ScopedFD read_pipe
, write_pipe
;
359 base::ProcessId pid
= 0;
361 int ipc_channel_fd
= LookUpFd(fd_mapping
, kPrimaryIPCChannel
);
362 if (ipc_channel_fd
< 0) {
363 DLOG(ERROR
) << "Failed to find kPrimaryIPCChannel in FD mapping";
366 std::vector
<int> fds
;
367 fds
.push_back(ipc_channel_fd
); // kBrowserFDIndex
368 fds
.push_back(pid_oracle
.get()); // kPIDOracleFDIndex
369 pid
= helper
->Fork(process_type
, fds
, channel_id
);
371 // Helpers should never return in the child process.
374 CreatePipe(&read_pipe
, &write_pipe
);
375 // This is roughly equivalent to a fork(). We are using ForkWithFlags mainly
376 // to give it some more diverse test coverage.
377 pid
= base::ForkWithFlags(SIGCHLD
, nullptr, nullptr);
381 // In the child process.
384 // Ping the PID oracle socket so the browser can find our PID.
385 CHECK(SendZygoteChildPing(pid_oracle
.get()));
387 // Now read back our real PID from the zygote.
388 base::ProcessId real_pid
;
389 if (!base::ReadFromFD(read_pipe
.get(),
390 reinterpret_cast<char*>(&real_pid
),
392 LOG(FATAL
) << "Failed to synchronise with parent zygote process";
395 LOG(FATAL
) << "Invalid pid from parent zygote";
397 #if defined(OS_LINUX)
398 // Sandboxed processes need to send the global, non-namespaced PID when
399 // setting up an IPC channel to their parent.
400 IPC::Channel::SetGlobalPid(real_pid
);
401 // Force the real PID so chrome event data have a PID that corresponds
402 // to system trace event data.
403 base::debug::TraceLog::GetInstance()->SetProcessID(
404 static_cast<int>(real_pid
));
409 // In the parent process.
413 // Always receive a real PID from the zygote host, though it might
414 // be invalid (see below).
415 base::ProcessId real_pid
;
417 ScopedVector
<base::ScopedFD
> recv_fds
;
418 char buf
[kZygoteMaxMessageLength
];
419 const ssize_t len
= UnixDomainSocket::RecvMsg(
420 kZygoteSocketPairFd
, buf
, sizeof(buf
), &recv_fds
);
422 CHECK(recv_fds
.empty());
424 Pickle
pickle(buf
, len
);
425 PickleIterator
iter(pickle
);
428 CHECK(iter
.ReadInt(&kind
));
429 CHECK(kind
== kZygoteCommandForkRealPID
);
430 CHECK(iter
.ReadInt(&real_pid
));
438 // If we successfully forked a child, but it crashed without sending
439 // a message to the browser, the browser won't have found its PID.
441 KillAndReap(pid
, helper
);
445 // If we're not using a helper, send the PID back to the child process.
448 HANDLE_EINTR(write(write_pipe
.get(), &real_pid
, sizeof(real_pid
)));
449 if (written
!= sizeof(real_pid
)) {
450 KillAndReap(pid
, helper
);
455 // Now set-up this process to be tracked by the Zygote.
456 if (process_info_map_
.find(real_pid
) != process_info_map_
.end()) {
457 LOG(ERROR
) << "Already tracking PID " << real_pid
;
460 process_info_map_
[real_pid
].internal_pid
= pid
;
461 process_info_map_
[real_pid
].started_from_helper
= helper
;
466 base::ProcessId
Zygote::ReadArgsAndFork(PickleIterator iter
,
467 ScopedVector
<base::ScopedFD
> fds
,
468 std::string
* uma_name
,
470 int* uma_boundary_value
) {
471 std::vector
<std::string
> args
;
474 base::GlobalDescriptors::Mapping mapping
;
475 std::string process_type
;
476 std::string channel_id
;
477 const std::string channel_id_prefix
= std::string("--")
478 + switches::kProcessChannelID
+ std::string("=");
480 if (!iter
.ReadString(&process_type
))
482 if (!iter
.ReadInt(&argc
))
485 for (int i
= 0; i
< argc
; ++i
) {
487 if (!iter
.ReadString(&arg
))
490 if (arg
.compare(0, channel_id_prefix
.length(), channel_id_prefix
) == 0)
491 channel_id
= arg
.substr(channel_id_prefix
.length());
494 if (!iter
.ReadInt(&numfds
))
496 if (numfds
!= static_cast<int>(fds
.size()))
499 // First FD is the PID oracle socket.
502 base::ScopedFD
pid_oracle(fds
[0]->Pass());
504 // Remaining FDs are for the global descriptor mapping.
505 for (int i
= 1; i
< numfds
; ++i
) {
506 base::GlobalDescriptors::Key key
;
507 if (!iter
.ReadUInt32(&key
))
509 mapping
.push_back(base::GlobalDescriptors::Descriptor(key
, fds
[i
]->get()));
512 mapping
.push_back(base::GlobalDescriptors::Descriptor(
513 static_cast<uint32_t>(kSandboxIPCChannel
), GetSandboxFD()));
515 // Returns twice, once per process.
516 base::ProcessId child_pid
= ForkWithRealPid(process_type
,
524 // This is the child process.
526 // Our socket from the browser.
527 PCHECK(0 == IGNORE_EINTR(close(kZygoteSocketPairFd
)));
529 // Pass ownership of file descriptors from fds to GlobalDescriptors.
530 for (ScopedVector
<base::ScopedFD
>::iterator i
= fds
.begin(); i
!= fds
.end();
532 ignore_result((*i
)->release());
533 base::GlobalDescriptors::GetInstance()->Reset(mapping
);
535 // Reset the process-wide command line to our new command line.
536 base::CommandLine::Reset();
537 base::CommandLine::Init(0, NULL
);
538 base::CommandLine::ForCurrentProcess()->InitFromArgv(args
);
540 // Update the process title. The argv was already cached by the call to
541 // SetProcessTitleFromCommandLine in ChromeMain, so we can pass NULL here
542 // (we don't have the original argv at this point).
543 SetProcessTitleFromCommandLine(NULL
);
544 } else if (child_pid
< 0) {
545 LOG(ERROR
) << "Zygote could not fork: process_type " << process_type
546 << " numfds " << numfds
<< " child_pid " << child_pid
;
551 bool Zygote::HandleForkRequest(int fd
,
553 ScopedVector
<base::ScopedFD
> fds
) {
554 std::string uma_name
;
556 int uma_boundary_value
;
557 base::ProcessId child_pid
= ReadArgsAndFork(
558 iter
, fds
.Pass(), &uma_name
, &uma_sample
, &uma_boundary_value
);
561 // If there's no UMA report for this particular fork, then check if any
562 // helpers have an initial UMA report for us to send instead.
563 while (uma_name
.empty() && initial_uma_index_
< helpers_
.size()) {
564 helpers_
[initial_uma_index_
++]->InitialUMA(
565 &uma_name
, &uma_sample
, &uma_boundary_value
);
567 // Must always send reply, as ZygoteHost blocks while waiting for it.
569 reply_pickle
.WriteInt(child_pid
);
570 reply_pickle
.WriteString(uma_name
);
571 if (!uma_name
.empty()) {
572 reply_pickle
.WriteInt(uma_sample
);
573 reply_pickle
.WriteInt(uma_boundary_value
);
575 if (HANDLE_EINTR(write(fd
, reply_pickle
.data(), reply_pickle
.size())) !=
576 static_cast<ssize_t
> (reply_pickle
.size()))
577 PLOG(ERROR
) << "write";
581 bool Zygote::HandleGetSandboxStatus(int fd
,
582 PickleIterator iter
) {
583 if (HANDLE_EINTR(write(fd
, &sandbox_flags_
, sizeof(sandbox_flags_
))) !=
584 sizeof(sandbox_flags_
)) {
585 PLOG(ERROR
) << "write";
591 } // namespace content