Roll src/third_party/WebKit 39f20ce:dc6c7bc (svn 202561:202563)
[chromium-blink-merge.git] / content / zygote / zygote_linux.cc
blob0a333e38843bf6b76d297efd1d63368b36b90b92
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"
7 #include <fcntl.h>
8 #include <string.h>
9 #include <sys/socket.h>
10 #include <sys/types.h>
11 #include <sys/wait.h>
13 #include "base/command_line.h"
14 #include "base/files/file_util.h"
15 #include "base/linux_util.h"
16 #include "base/logging.h"
17 #include "base/macros.h"
18 #include "base/memory/scoped_vector.h"
19 #include "base/pickle.h"
20 #include "base/posix/eintr_wrapper.h"
21 #include "base/posix/global_descriptors.h"
22 #include "base/posix/unix_domain_socket_linux.h"
23 #include "base/process/kill.h"
24 #include "base/process/launch.h"
25 #include "base/process/process.h"
26 #include "base/process/process_handle.h"
27 #include "base/trace_event/trace_event.h"
28 #include "content/common/child_process_sandbox_support_impl_linux.h"
29 #include "content/common/sandbox_linux/sandbox_linux.h"
30 #include "content/common/set_process_title.h"
31 #include "content/common/zygote_commands_linux.h"
32 #include "content/public/common/content_descriptors.h"
33 #include "content/public/common/result_codes.h"
34 #include "content/public/common/sandbox_linux.h"
35 #include "content/public/common/send_zygote_child_ping_linux.h"
36 #include "content/public/common/zygote_fork_delegate_linux.h"
37 #include "ipc/ipc_channel.h"
38 #include "ipc/ipc_switches.h"
39 #include "sandbox/linux/services/credentials.h"
40 #include "sandbox/linux/services/namespace_sandbox.h"
42 // See http://code.google.com/p/chromium/wiki/LinuxZygote
44 namespace content {
46 namespace {
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;
57 return -1;
60 void CreatePipe(base::ScopedFD* read_pipe, base::ScopedFD* write_pipe) {
61 int raw_pipe[2];
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) {
68 if (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";
75 return;
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)));
84 } // namespace
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) {}
95 Zygote::~Zygote() {
98 bool Zygote::ProcessRequests() {
99 // A SOCK_SEQPACKET socket is installed in fd 3. We get commands from the
100 // browser on it.
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 PCHECK(sigaction(SIGCHLD, &action, NULL) == 0);
111 if (UsingSUIDSandbox() || UsingNSSandbox()) {
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 = base::UnixDomainSocket::SendMsg(kZygoteSocketPairFd,
115 kZygoteHelloMessage,
116 sizeof(kZygoteHelloMessage),
117 std::vector<int>());
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.
123 if (!r)
124 _exit(RESULT_CODE_NORMAL_EXIT);
125 #else
126 CHECK(r) << "Sending zygote magic failed";
127 #endif
130 for (;;) {
131 // This function call can return multiple times, once per fork().
132 if (HandleRequestFromBrowser(kZygoteSocketPairFd))
133 return true;
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()) {
142 return false;
144 *process_info = it->second;
145 return true;
148 bool Zygote::UsingSUIDSandbox() const {
149 return sandbox_flags_ & kSandboxLinuxSUID;
152 bool Zygote::UsingNSSandbox() const {
153 return sandbox_flags_ & kSandboxLinuxUserNS;
156 bool Zygote::HandleRequestFromBrowser(int fd) {
157 ScopedVector<base::ScopedFD> fds;
158 char buf[kZygoteMaxMessageLength];
159 const ssize_t len = base::UnixDomainSocket::RecvMsg(
160 fd, buf, sizeof(buf), &fds);
162 if (len == 0 || (len == -1 && errno == ECONNRESET)) {
163 // EOF from the browser. We should die.
164 // TODO(earthdok): call __sanititizer_cov_dump() here to obtain code
165 // coverage for the Zygote. Currently it's not possible because of
166 // confusion over who is responsible for closing the file descriptor.
167 for (std::vector<int>::iterator it = extra_fds_.begin();
168 it < extra_fds_.end(); ++it) {
169 PCHECK(0 == IGNORE_EINTR(close(*it)));
171 #if !defined(SANITIZER_COVERAGE)
172 // TODO(earthdok): add watchdog thread before using this in builds not
173 // using sanitizer coverage.
174 CHECK(extra_children_.empty());
175 #endif
176 for (std::vector<base::ProcessHandle>::iterator it =
177 extra_children_.begin();
178 it < extra_children_.end(); ++it) {
179 PCHECK(*it == HANDLE_EINTR(waitpid(*it, NULL, 0)));
181 _exit(0);
182 return false;
185 if (len == -1) {
186 PLOG(ERROR) << "Error reading message from browser";
187 return false;
190 base::Pickle pickle(buf, len);
191 base::PickleIterator iter(pickle);
193 int kind;
194 if (iter.ReadInt(&kind)) {
195 switch (kind) {
196 case kZygoteCommandFork:
197 // This function call can return multiple times, once per fork().
198 return HandleForkRequest(fd, iter, fds.Pass());
200 case kZygoteCommandReap:
201 if (!fds.empty())
202 break;
203 HandleReapRequest(fd, iter);
204 return false;
205 case kZygoteCommandGetTerminationStatus:
206 if (!fds.empty())
207 break;
208 HandleGetTerminationStatus(fd, iter);
209 return false;
210 case kZygoteCommandGetSandboxStatus:
211 HandleGetSandboxStatus(fd, iter);
212 return false;
213 case kZygoteCommandForkRealPID:
214 // This shouldn't happen in practice, but some failure paths in
215 // HandleForkRequest (e.g., if ReadArgsAndFork fails during depickling)
216 // could leave this command pending on the socket.
217 LOG(ERROR) << "Unexpected real PID message from browser";
218 NOTREACHED();
219 return false;
220 default:
221 NOTREACHED();
222 break;
226 LOG(WARNING) << "Error parsing message from browser";
227 return false;
230 // TODO(jln): remove callers to this broken API. See crbug.com/274855.
231 void Zygote::HandleReapRequest(int fd, base::PickleIterator iter) {
232 base::ProcessId child;
234 if (!iter.ReadInt(&child)) {
235 LOG(WARNING) << "Error parsing reap request from browser";
236 return;
239 ZygoteProcessInfo child_info;
240 if (!GetProcessInfo(child, &child_info)) {
241 LOG(ERROR) << "Child not found!";
242 NOTREACHED();
243 return;
246 if (!child_info.started_from_helper) {
247 // Do not call base::EnsureProcessTerminated() under ThreadSanitizer, as it
248 // spawns a separate thread which may live until the call to fork() in the
249 // zygote. As a result, ThreadSanitizer will report an error and almost
250 // disable race detection in the child process.
251 // Not calling EnsureProcessTerminated() may result in zombie processes
252 // sticking around. This will only happen during testing, so we can live
253 // with this for now.
254 #if !defined(THREAD_SANITIZER)
255 // TODO(jln): this old code is completely broken. See crbug.com/274855.
256 base::EnsureProcessTerminated(base::Process(child_info.internal_pid));
257 #else
258 LOG(WARNING) << "Zygote process omitting a call to "
259 << "base::EnsureProcessTerminated() for child pid " << child
260 << " under ThreadSanitizer. See http://crbug.com/274855.";
261 #endif
262 } else {
263 // For processes from the helper, send a GetTerminationStatus request
264 // with known_dead set to true.
265 // This is not perfect, as the process may be killed instantly, but is
266 // better than ignoring the request.
267 base::TerminationStatus status;
268 int exit_code;
269 bool got_termination_status =
270 GetTerminationStatus(child, true /* known_dead */, &status, &exit_code);
271 DCHECK(got_termination_status);
273 process_info_map_.erase(child);
276 bool Zygote::GetTerminationStatus(base::ProcessHandle real_pid,
277 bool known_dead,
278 base::TerminationStatus* status,
279 int* exit_code) {
281 ZygoteProcessInfo child_info;
282 if (!GetProcessInfo(real_pid, &child_info)) {
283 LOG(ERROR) << "Zygote::GetTerminationStatus for unknown PID "
284 << real_pid;
285 NOTREACHED();
286 return false;
288 // We know about |real_pid|.
289 const base::ProcessHandle child = child_info.internal_pid;
290 if (child_info.started_from_helper) {
291 if (!child_info.started_from_helper->GetTerminationStatus(
292 child, known_dead, status, exit_code)) {
293 return false;
295 } else {
296 // Handle the request directly.
297 if (known_dead) {
298 *status = base::GetKnownDeadTerminationStatus(child, exit_code);
299 } else {
300 // We don't know if the process is dying, so get its status but don't
301 // wait.
302 *status = base::GetTerminationStatus(child, exit_code);
305 // Successfully got a status for |real_pid|.
306 if (*status != base::TERMINATION_STATUS_STILL_RUNNING) {
307 // Time to forget about this process.
308 process_info_map_.erase(real_pid);
311 if (WIFEXITED(*exit_code)) {
312 const int exit_status = WEXITSTATUS(*exit_code);
313 if (exit_status == sandbox::NamespaceSandbox::SignalExitCode(SIGINT) ||
314 exit_status == sandbox::NamespaceSandbox::SignalExitCode(SIGTERM)) {
315 *status = base::TERMINATION_STATUS_PROCESS_WAS_KILLED;
319 return true;
322 void Zygote::HandleGetTerminationStatus(int fd, base::PickleIterator iter) {
323 bool known_dead;
324 base::ProcessHandle child_requested;
326 if (!iter.ReadBool(&known_dead) || !iter.ReadInt(&child_requested)) {
327 LOG(WARNING) << "Error parsing GetTerminationStatus request "
328 << "from browser";
329 return;
332 base::TerminationStatus status;
333 int exit_code;
335 bool got_termination_status =
336 GetTerminationStatus(child_requested, known_dead, &status, &exit_code);
337 if (!got_termination_status) {
338 // Assume that if we can't find the child in the sandbox, then
339 // it terminated normally.
340 NOTREACHED();
341 status = base::TERMINATION_STATUS_NORMAL_TERMINATION;
342 exit_code = RESULT_CODE_NORMAL_EXIT;
345 base::Pickle write_pickle;
346 write_pickle.WriteInt(static_cast<int>(status));
347 write_pickle.WriteInt(exit_code);
348 ssize_t written =
349 HANDLE_EINTR(write(fd, write_pickle.data(), write_pickle.size()));
350 if (written != static_cast<ssize_t>(write_pickle.size()))
351 PLOG(ERROR) << "write";
354 int Zygote::ForkWithRealPid(const std::string& process_type,
355 const base::GlobalDescriptors::Mapping& fd_mapping,
356 const std::string& channel_id,
357 base::ScopedFD pid_oracle,
358 std::string* uma_name,
359 int* uma_sample,
360 int* uma_boundary_value) {
361 ZygoteForkDelegate* helper = NULL;
362 for (ScopedVector<ZygoteForkDelegate>::iterator i = helpers_.begin();
363 i != helpers_.end();
364 ++i) {
365 if ((*i)->CanHelp(process_type, uma_name, uma_sample, uma_boundary_value)) {
366 helper = *i;
367 break;
371 base::ScopedFD read_pipe, write_pipe;
372 base::ProcessId pid = 0;
373 if (helper) {
374 int ipc_channel_fd = LookUpFd(fd_mapping, kPrimaryIPCChannel);
375 if (ipc_channel_fd < 0) {
376 DLOG(ERROR) << "Failed to find kPrimaryIPCChannel in FD mapping";
377 return -1;
379 std::vector<int> fds;
380 fds.push_back(ipc_channel_fd); // kBrowserFDIndex
381 fds.push_back(pid_oracle.get()); // kPIDOracleFDIndex
382 pid = helper->Fork(process_type, fds, channel_id);
384 // Helpers should never return in the child process.
385 CHECK_NE(pid, 0);
386 } else {
387 CreatePipe(&read_pipe, &write_pipe);
388 if (sandbox_flags_ & kSandboxLinuxPIDNS &&
389 sandbox_flags_ & kSandboxLinuxUserNS) {
390 pid = sandbox::NamespaceSandbox::ForkInNewPidNamespace(
391 /*drop_capabilities_in_child=*/true);
392 } else {
393 pid = sandbox::Credentials::ForkAndDropCapabilitiesInChild();
397 if (pid == 0) {
398 // If the process is the init process inside a PID namespace, it must have
399 // explicit signal handlers.
400 if (getpid() == 1) {
401 static const int kTerminationSignals[] = {
402 SIGINT, SIGTERM, SIGHUP, SIGQUIT, SIGABRT, SIGPIPE, SIGUSR1, SIGUSR2};
403 for (const int sig : kTerminationSignals) {
404 sandbox::NamespaceSandbox::InstallTerminationSignalHandler(
405 sig, sandbox::NamespaceSandbox::SignalExitCode(sig));
409 // In the child process.
410 write_pipe.reset();
412 // Ping the PID oracle socket so the browser can find our PID.
413 CHECK(SendZygoteChildPing(pid_oracle.get()));
415 // Now read back our real PID from the zygote.
416 base::ProcessId real_pid;
417 if (!base::ReadFromFD(read_pipe.get(),
418 reinterpret_cast<char*>(&real_pid),
419 sizeof(real_pid))) {
420 LOG(FATAL) << "Failed to synchronise with parent zygote process";
422 if (real_pid <= 0) {
423 LOG(FATAL) << "Invalid pid from parent zygote";
425 #if defined(OS_LINUX)
426 // Sandboxed processes need to send the global, non-namespaced PID when
427 // setting up an IPC channel to their parent.
428 IPC::Channel::SetGlobalPid(real_pid);
429 // Force the real PID so chrome event data have a PID that corresponds
430 // to system trace event data.
431 base::trace_event::TraceLog::GetInstance()->SetProcessID(
432 static_cast<int>(real_pid));
433 #endif
434 return 0;
437 // In the parent process.
438 read_pipe.reset();
439 pid_oracle.reset();
441 // Always receive a real PID from the zygote host, though it might
442 // be invalid (see below).
443 base::ProcessId real_pid;
445 ScopedVector<base::ScopedFD> recv_fds;
446 char buf[kZygoteMaxMessageLength];
447 const ssize_t len = base::UnixDomainSocket::RecvMsg(
448 kZygoteSocketPairFd, buf, sizeof(buf), &recv_fds);
449 CHECK_GT(len, 0);
450 CHECK(recv_fds.empty());
452 base::Pickle pickle(buf, len);
453 base::PickleIterator iter(pickle);
455 int kind;
456 CHECK(iter.ReadInt(&kind));
457 CHECK(kind == kZygoteCommandForkRealPID);
458 CHECK(iter.ReadInt(&real_pid));
461 // Fork failed.
462 if (pid < 0) {
463 return -1;
466 // If we successfully forked a child, but it crashed without sending
467 // a message to the browser, the browser won't have found its PID.
468 if (real_pid < 0) {
469 KillAndReap(pid, helper);
470 return -1;
473 // If we're not using a helper, send the PID back to the child process.
474 if (!helper) {
475 ssize_t written =
476 HANDLE_EINTR(write(write_pipe.get(), &real_pid, sizeof(real_pid)));
477 if (written != sizeof(real_pid)) {
478 KillAndReap(pid, helper);
479 return -1;
483 // Now set-up this process to be tracked by the Zygote.
484 if (process_info_map_.find(real_pid) != process_info_map_.end()) {
485 LOG(ERROR) << "Already tracking PID " << real_pid;
486 NOTREACHED();
488 process_info_map_[real_pid].internal_pid = pid;
489 process_info_map_[real_pid].started_from_helper = helper;
491 return real_pid;
494 base::ProcessId Zygote::ReadArgsAndFork(base::PickleIterator iter,
495 ScopedVector<base::ScopedFD> fds,
496 std::string* uma_name,
497 int* uma_sample,
498 int* uma_boundary_value) {
499 std::vector<std::string> args;
500 int argc = 0;
501 int numfds = 0;
502 base::GlobalDescriptors::Mapping mapping;
503 std::string process_type;
504 std::string channel_id;
505 const std::string channel_id_prefix = std::string("--")
506 + switches::kProcessChannelID + std::string("=");
508 if (!iter.ReadString(&process_type))
509 return -1;
510 if (!iter.ReadInt(&argc))
511 return -1;
513 for (int i = 0; i < argc; ++i) {
514 std::string arg;
515 if (!iter.ReadString(&arg))
516 return -1;
517 args.push_back(arg);
518 if (arg.compare(0, channel_id_prefix.length(), channel_id_prefix) == 0)
519 channel_id = arg.substr(channel_id_prefix.length());
522 if (!iter.ReadInt(&numfds))
523 return -1;
524 if (numfds != static_cast<int>(fds.size()))
525 return -1;
527 // First FD is the PID oracle socket.
528 if (fds.size() < 1)
529 return -1;
530 base::ScopedFD pid_oracle(fds[0]->Pass());
532 // Remaining FDs are for the global descriptor mapping.
533 for (int i = 1; i < numfds; ++i) {
534 base::GlobalDescriptors::Key key;
535 if (!iter.ReadUInt32(&key))
536 return -1;
537 mapping.push_back(base::GlobalDescriptors::Descriptor(key, fds[i]->get()));
540 mapping.push_back(base::GlobalDescriptors::Descriptor(
541 static_cast<uint32_t>(kSandboxIPCChannel), GetSandboxFD()));
543 // Returns twice, once per process.
544 base::ProcessId child_pid = ForkWithRealPid(process_type,
545 mapping,
546 channel_id,
547 pid_oracle.Pass(),
548 uma_name,
549 uma_sample,
550 uma_boundary_value);
551 if (!child_pid) {
552 // This is the child process.
554 // Our socket from the browser.
555 PCHECK(0 == IGNORE_EINTR(close(kZygoteSocketPairFd)));
557 // Pass ownership of file descriptors from fds to GlobalDescriptors.
558 for (ScopedVector<base::ScopedFD>::iterator i = fds.begin(); i != fds.end();
559 ++i)
560 ignore_result((*i)->release());
561 base::GlobalDescriptors::GetInstance()->Reset(mapping);
563 // Reset the process-wide command line to our new command line.
564 base::CommandLine::Reset();
565 base::CommandLine::Init(0, NULL);
566 base::CommandLine::ForCurrentProcess()->InitFromArgv(args);
568 // Update the process title. The argv was already cached by the call to
569 // SetProcessTitleFromCommandLine in ChromeMain, so we can pass NULL here
570 // (we don't have the original argv at this point).
571 SetProcessTitleFromCommandLine(NULL);
572 } else if (child_pid < 0) {
573 LOG(ERROR) << "Zygote could not fork: process_type " << process_type
574 << " numfds " << numfds << " child_pid " << child_pid;
576 return child_pid;
579 bool Zygote::HandleForkRequest(int fd,
580 base::PickleIterator iter,
581 ScopedVector<base::ScopedFD> fds) {
582 std::string uma_name;
583 int uma_sample;
584 int uma_boundary_value;
585 base::ProcessId child_pid = ReadArgsAndFork(
586 iter, fds.Pass(), &uma_name, &uma_sample, &uma_boundary_value);
587 if (child_pid == 0)
588 return true;
589 // If there's no UMA report for this particular fork, then check if any
590 // helpers have an initial UMA report for us to send instead.
591 while (uma_name.empty() && initial_uma_index_ < helpers_.size()) {
592 helpers_[initial_uma_index_++]->InitialUMA(
593 &uma_name, &uma_sample, &uma_boundary_value);
595 // Must always send reply, as ZygoteHost blocks while waiting for it.
596 base::Pickle reply_pickle;
597 reply_pickle.WriteInt(child_pid);
598 reply_pickle.WriteString(uma_name);
599 if (!uma_name.empty()) {
600 reply_pickle.WriteInt(uma_sample);
601 reply_pickle.WriteInt(uma_boundary_value);
603 if (HANDLE_EINTR(write(fd, reply_pickle.data(), reply_pickle.size())) !=
604 static_cast<ssize_t> (reply_pickle.size()))
605 PLOG(ERROR) << "write";
606 return false;
609 bool Zygote::HandleGetSandboxStatus(int fd, base::PickleIterator iter) {
610 if (HANDLE_EINTR(write(fd, &sandbox_flags_, sizeof(sandbox_flags_))) !=
611 sizeof(sandbox_flags_)) {
612 PLOG(ERROR) << "write";
615 return false;
618 } // namespace content