Refactors gesture conversion functions to ui/events/blink
[chromium-blink-merge.git] / content / zygote / zygote_linux.cc
blob5944f87aa1258dff7a908eb6d5a2d55cea93a05f
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"
40 // See http://code.google.com/p/chromium/wiki/LinuxZygote
42 namespace content {
44 namespace {
46 // NOP function. See below where this handler is installed.
47 void SIGCHLDHandler(int signal) {
50 int LookUpFd(const base::GlobalDescriptors::Mapping& fd_mapping, uint32_t key) {
51 for (size_t index = 0; index < fd_mapping.size(); ++index) {
52 if (fd_mapping[index].key == key)
53 return fd_mapping[index].fd;
55 return -1;
58 void CreatePipe(base::ScopedFD* read_pipe, base::ScopedFD* write_pipe) {
59 int raw_pipe[2];
60 PCHECK(0 == pipe(raw_pipe));
61 read_pipe->reset(raw_pipe[0]);
62 write_pipe->reset(raw_pipe[1]);
65 void KillAndReap(pid_t pid, ZygoteForkDelegate* helper) {
66 if (helper) {
67 // Helper children may be forked in another PID namespace, so |pid| might
68 // be meaningless to us; or we just might not be able to directly send it
69 // signals. So we can't kill it.
70 // Additionally, we're not its parent, so we can't reap it anyway.
71 // TODO(mdempsky): Extend the ZygoteForkDelegate API to handle this.
72 LOG(WARNING) << "Unable to kill or reap helper children";
73 return;
76 // Kill the child process in case it's not already dead, so we can safely
77 // perform a blocking wait.
78 PCHECK(0 == kill(pid, SIGKILL));
79 PCHECK(pid == HANDLE_EINTR(waitpid(pid, NULL, 0)));
82 } // namespace
84 Zygote::Zygote(int sandbox_flags, ScopedVector<ZygoteForkDelegate> helpers,
85 const std::vector<base::ProcessHandle>& extra_children,
86 const std::vector<int>& extra_fds)
87 : sandbox_flags_(sandbox_flags),
88 helpers_(helpers.Pass()),
89 initial_uma_index_(0),
90 extra_children_(extra_children),
91 extra_fds_(extra_fds) {}
93 Zygote::~Zygote() {
96 bool Zygote::ProcessRequests() {
97 // A SOCK_SEQPACKET socket is installed in fd 3. We get commands from the
98 // browser on it.
99 // A SOCK_DGRAM is installed in fd 5. This is the sandbox IPC channel.
100 // See http://code.google.com/p/chromium/wiki/LinuxSandboxIPC
102 // We need to accept SIGCHLD, even though our handler is a no-op because
103 // otherwise we cannot wait on children. (According to POSIX 2001.)
104 struct sigaction action;
105 memset(&action, 0, sizeof(action));
106 action.sa_handler = &SIGCHLDHandler;
107 CHECK(sigaction(SIGCHLD, &action, NULL) == 0);
109 if (UsingSUIDSandbox() || UsingNSSandbox()) {
110 // Let the ZygoteHost know we are ready to go.
111 // The receiving code is in content/browser/zygote_host_linux.cc.
112 bool r = UnixDomainSocket::SendMsg(kZygoteSocketPairFd,
113 kZygoteHelloMessage,
114 sizeof(kZygoteHelloMessage),
115 std::vector<int>());
116 #if defined(OS_CHROMEOS)
117 LOG_IF(WARNING, !r) << "Sending zygote magic failed";
118 // Exit normally on chromeos because session manager may send SIGTERM
119 // right after the process starts and it may fail to send zygote magic
120 // number to browser process.
121 if (!r)
122 _exit(RESULT_CODE_NORMAL_EXIT);
123 #else
124 CHECK(r) << "Sending zygote magic failed";
125 #endif
128 for (;;) {
129 // This function call can return multiple times, once per fork().
130 if (HandleRequestFromBrowser(kZygoteSocketPairFd))
131 return true;
135 bool Zygote::GetProcessInfo(base::ProcessHandle pid,
136 ZygoteProcessInfo* process_info) {
137 DCHECK(process_info);
138 const ZygoteProcessMap::const_iterator it = process_info_map_.find(pid);
139 if (it == process_info_map_.end()) {
140 return false;
142 *process_info = it->second;
143 return true;
146 bool Zygote::UsingSUIDSandbox() const {
147 return sandbox_flags_ & kSandboxLinuxSUID;
150 bool Zygote::UsingNSSandbox() const {
151 return sandbox_flags_ & kSandboxLinuxUserNS;
154 bool Zygote::HandleRequestFromBrowser(int fd) {
155 ScopedVector<base::ScopedFD> fds;
156 char buf[kZygoteMaxMessageLength];
157 const ssize_t len = UnixDomainSocket::RecvMsg(fd, buf, sizeof(buf), &fds);
159 if (len == 0 || (len == -1 && errno == ECONNRESET)) {
160 // EOF from the browser. We should die.
161 // TODO(earthdok): call __sanititizer_cov_dump() here to obtain code
162 // coverage for the Zygote. Currently it's not possible because of
163 // confusion over who is responsible for closing the file descriptor.
164 for (std::vector<int>::iterator it = extra_fds_.begin();
165 it < extra_fds_.end(); ++it) {
166 PCHECK(0 == IGNORE_EINTR(close(*it)));
168 #if !defined(SANITIZER_COVERAGE)
169 // TODO(earthdok): add watchdog thread before using this in builds not
170 // using sanitizer coverage.
171 CHECK(extra_children_.empty());
172 #endif
173 for (std::vector<base::ProcessHandle>::iterator it =
174 extra_children_.begin();
175 it < extra_children_.end(); ++it) {
176 PCHECK(*it == HANDLE_EINTR(waitpid(*it, NULL, 0)));
178 _exit(0);
179 return false;
182 if (len == -1) {
183 PLOG(ERROR) << "Error reading message from browser";
184 return false;
187 Pickle pickle(buf, len);
188 PickleIterator iter(pickle);
190 int kind;
191 if (iter.ReadInt(&kind)) {
192 switch (kind) {
193 case kZygoteCommandFork:
194 // This function call can return multiple times, once per fork().
195 return HandleForkRequest(fd, iter, fds.Pass());
197 case kZygoteCommandReap:
198 if (!fds.empty())
199 break;
200 HandleReapRequest(fd, iter);
201 return false;
202 case kZygoteCommandGetTerminationStatus:
203 if (!fds.empty())
204 break;
205 HandleGetTerminationStatus(fd, iter);
206 return false;
207 case kZygoteCommandGetSandboxStatus:
208 HandleGetSandboxStatus(fd, iter);
209 return false;
210 case kZygoteCommandForkRealPID:
211 // This shouldn't happen in practice, but some failure paths in
212 // HandleForkRequest (e.g., if ReadArgsAndFork fails during depickling)
213 // could leave this command pending on the socket.
214 LOG(ERROR) << "Unexpected real PID message from browser";
215 NOTREACHED();
216 return false;
217 default:
218 NOTREACHED();
219 break;
223 LOG(WARNING) << "Error parsing message from browser";
224 return false;
227 // TODO(jln): remove callers to this broken API. See crbug.com/274855.
228 void Zygote::HandleReapRequest(int fd,
229 PickleIterator iter) {
230 base::ProcessId child;
232 if (!iter.ReadInt(&child)) {
233 LOG(WARNING) << "Error parsing reap request from browser";
234 return;
237 ZygoteProcessInfo child_info;
238 if (!GetProcessInfo(child, &child_info)) {
239 LOG(ERROR) << "Child not found!";
240 NOTREACHED();
241 return;
244 if (!child_info.started_from_helper) {
245 // Do not call base::EnsureProcessTerminated() under ThreadSanitizer, as it
246 // spawns a separate thread which may live until the call to fork() in the
247 // zygote. As a result, ThreadSanitizer will report an error and almost
248 // disable race detection in the child process.
249 // Not calling EnsureProcessTerminated() may result in zombie processes
250 // sticking around. This will only happen during testing, so we can live
251 // with this for now.
252 #if !defined(THREAD_SANITIZER)
253 // TODO(jln): this old code is completely broken. See crbug.com/274855.
254 base::EnsureProcessTerminated(base::Process(child_info.internal_pid));
255 #else
256 LOG(WARNING) << "Zygote process omitting a call to "
257 << "base::EnsureProcessTerminated() for child pid " << child
258 << " under ThreadSanitizer. See http://crbug.com/274855.";
259 #endif
260 } else {
261 // For processes from the helper, send a GetTerminationStatus request
262 // with known_dead set to true.
263 // This is not perfect, as the process may be killed instantly, but is
264 // better than ignoring the request.
265 base::TerminationStatus status;
266 int exit_code;
267 bool got_termination_status =
268 GetTerminationStatus(child, true /* known_dead */, &status, &exit_code);
269 DCHECK(got_termination_status);
271 process_info_map_.erase(child);
274 bool Zygote::GetTerminationStatus(base::ProcessHandle real_pid,
275 bool known_dead,
276 base::TerminationStatus* status,
277 int* exit_code) {
279 ZygoteProcessInfo child_info;
280 if (!GetProcessInfo(real_pid, &child_info)) {
281 LOG(ERROR) << "Zygote::GetTerminationStatus for unknown PID "
282 << real_pid;
283 NOTREACHED();
284 return false;
286 // We know about |real_pid|.
287 const base::ProcessHandle child = child_info.internal_pid;
288 if (child_info.started_from_helper) {
289 if (!child_info.started_from_helper->GetTerminationStatus(
290 child, known_dead, status, exit_code)) {
291 return false;
293 } else {
294 // Handle the request directly.
295 if (known_dead) {
296 *status = base::GetKnownDeadTerminationStatus(child, exit_code);
297 } else {
298 // We don't know if the process is dying, so get its status but don't
299 // wait.
300 *status = base::GetTerminationStatus(child, exit_code);
303 // Successfully got a status for |real_pid|.
304 if (*status != base::TERMINATION_STATUS_STILL_RUNNING) {
305 // Time to forget about this process.
306 process_info_map_.erase(real_pid);
308 return true;
311 void Zygote::HandleGetTerminationStatus(int fd,
312 PickleIterator iter) {
313 bool known_dead;
314 base::ProcessHandle child_requested;
316 if (!iter.ReadBool(&known_dead) || !iter.ReadInt(&child_requested)) {
317 LOG(WARNING) << "Error parsing GetTerminationStatus request "
318 << "from browser";
319 return;
322 base::TerminationStatus status;
323 int exit_code;
325 bool got_termination_status =
326 GetTerminationStatus(child_requested, known_dead, &status, &exit_code);
327 if (!got_termination_status) {
328 // Assume that if we can't find the child in the sandbox, then
329 // it terminated normally.
330 NOTREACHED();
331 status = base::TERMINATION_STATUS_NORMAL_TERMINATION;
332 exit_code = RESULT_CODE_NORMAL_EXIT;
335 Pickle write_pickle;
336 write_pickle.WriteInt(static_cast<int>(status));
337 write_pickle.WriteInt(exit_code);
338 ssize_t written =
339 HANDLE_EINTR(write(fd, write_pickle.data(), write_pickle.size()));
340 if (written != static_cast<ssize_t>(write_pickle.size()))
341 PLOG(ERROR) << "write";
344 int Zygote::ForkWithRealPid(const std::string& process_type,
345 const base::GlobalDescriptors::Mapping& fd_mapping,
346 const std::string& channel_id,
347 base::ScopedFD pid_oracle,
348 std::string* uma_name,
349 int* uma_sample,
350 int* uma_boundary_value) {
351 ZygoteForkDelegate* helper = NULL;
352 for (ScopedVector<ZygoteForkDelegate>::iterator i = helpers_.begin();
353 i != helpers_.end();
354 ++i) {
355 if ((*i)->CanHelp(process_type, uma_name, uma_sample, uma_boundary_value)) {
356 helper = *i;
357 break;
361 base::ScopedFD read_pipe, write_pipe;
362 base::ProcessId pid = 0;
363 if (helper) {
364 int ipc_channel_fd = LookUpFd(fd_mapping, kPrimaryIPCChannel);
365 if (ipc_channel_fd < 0) {
366 DLOG(ERROR) << "Failed to find kPrimaryIPCChannel in FD mapping";
367 return -1;
369 std::vector<int> fds;
370 fds.push_back(ipc_channel_fd); // kBrowserFDIndex
371 fds.push_back(pid_oracle.get()); // kPIDOracleFDIndex
372 pid = helper->Fork(process_type, fds, channel_id);
374 // Helpers should never return in the child process.
375 CHECK_NE(pid, 0);
376 } else {
377 CreatePipe(&read_pipe, &write_pipe);
378 // This is roughly equivalent to a fork(). We are using ForkWithFlags mainly
379 // to give it some more diverse test coverage.
380 pid = base::ForkWithFlags(SIGCHLD, nullptr, nullptr);
383 if (pid == 0) {
384 // In the child process.
385 write_pipe.reset();
387 // Ping the PID oracle socket so the browser can find our PID.
388 CHECK(SendZygoteChildPing(pid_oracle.get()));
390 // Now read back our real PID from the zygote.
391 base::ProcessId real_pid;
392 if (!base::ReadFromFD(read_pipe.get(),
393 reinterpret_cast<char*>(&real_pid),
394 sizeof(real_pid))) {
395 LOG(FATAL) << "Failed to synchronise with parent zygote process";
397 if (real_pid <= 0) {
398 LOG(FATAL) << "Invalid pid from parent zygote";
400 #if defined(OS_LINUX)
401 // Sandboxed processes need to send the global, non-namespaced PID when
402 // setting up an IPC channel to their parent.
403 IPC::Channel::SetGlobalPid(real_pid);
404 // Force the real PID so chrome event data have a PID that corresponds
405 // to system trace event data.
406 base::trace_event::TraceLog::GetInstance()->SetProcessID(
407 static_cast<int>(real_pid));
408 #endif
409 return 0;
412 // In the parent process.
413 read_pipe.reset();
414 pid_oracle.reset();
416 // Always receive a real PID from the zygote host, though it might
417 // be invalid (see below).
418 base::ProcessId real_pid;
420 ScopedVector<base::ScopedFD> recv_fds;
421 char buf[kZygoteMaxMessageLength];
422 const ssize_t len = UnixDomainSocket::RecvMsg(
423 kZygoteSocketPairFd, buf, sizeof(buf), &recv_fds);
424 CHECK_GT(len, 0);
425 CHECK(recv_fds.empty());
427 Pickle pickle(buf, len);
428 PickleIterator iter(pickle);
430 int kind;
431 CHECK(iter.ReadInt(&kind));
432 CHECK(kind == kZygoteCommandForkRealPID);
433 CHECK(iter.ReadInt(&real_pid));
436 // Fork failed.
437 if (pid < 0) {
438 return -1;
441 // If we successfully forked a child, but it crashed without sending
442 // a message to the browser, the browser won't have found its PID.
443 if (real_pid < 0) {
444 KillAndReap(pid, helper);
445 return -1;
448 // If we're not using a helper, send the PID back to the child process.
449 if (!helper) {
450 ssize_t written =
451 HANDLE_EINTR(write(write_pipe.get(), &real_pid, sizeof(real_pid)));
452 if (written != sizeof(real_pid)) {
453 KillAndReap(pid, helper);
454 return -1;
458 // Now set-up this process to be tracked by the Zygote.
459 if (process_info_map_.find(real_pid) != process_info_map_.end()) {
460 LOG(ERROR) << "Already tracking PID " << real_pid;
461 NOTREACHED();
463 process_info_map_[real_pid].internal_pid = pid;
464 process_info_map_[real_pid].started_from_helper = helper;
466 return real_pid;
469 base::ProcessId Zygote::ReadArgsAndFork(PickleIterator iter,
470 ScopedVector<base::ScopedFD> fds,
471 std::string* uma_name,
472 int* uma_sample,
473 int* uma_boundary_value) {
474 std::vector<std::string> args;
475 int argc = 0;
476 int numfds = 0;
477 base::GlobalDescriptors::Mapping mapping;
478 std::string process_type;
479 std::string channel_id;
480 const std::string channel_id_prefix = std::string("--")
481 + switches::kProcessChannelID + std::string("=");
483 if (!iter.ReadString(&process_type))
484 return -1;
485 if (!iter.ReadInt(&argc))
486 return -1;
488 for (int i = 0; i < argc; ++i) {
489 std::string arg;
490 if (!iter.ReadString(&arg))
491 return -1;
492 args.push_back(arg);
493 if (arg.compare(0, channel_id_prefix.length(), channel_id_prefix) == 0)
494 channel_id = arg.substr(channel_id_prefix.length());
497 if (!iter.ReadInt(&numfds))
498 return -1;
499 if (numfds != static_cast<int>(fds.size()))
500 return -1;
502 // First FD is the PID oracle socket.
503 if (fds.size() < 1)
504 return -1;
505 base::ScopedFD pid_oracle(fds[0]->Pass());
507 // Remaining FDs are for the global descriptor mapping.
508 for (int i = 1; i < numfds; ++i) {
509 base::GlobalDescriptors::Key key;
510 if (!iter.ReadUInt32(&key))
511 return -1;
512 mapping.push_back(base::GlobalDescriptors::Descriptor(key, fds[i]->get()));
515 mapping.push_back(base::GlobalDescriptors::Descriptor(
516 static_cast<uint32_t>(kSandboxIPCChannel), GetSandboxFD()));
518 // Returns twice, once per process.
519 base::ProcessId child_pid = ForkWithRealPid(process_type,
520 mapping,
521 channel_id,
522 pid_oracle.Pass(),
523 uma_name,
524 uma_sample,
525 uma_boundary_value);
526 if (!child_pid) {
527 // This is the child process.
529 // Our socket from the browser.
530 PCHECK(0 == IGNORE_EINTR(close(kZygoteSocketPairFd)));
532 // Pass ownership of file descriptors from fds to GlobalDescriptors.
533 for (ScopedVector<base::ScopedFD>::iterator i = fds.begin(); i != fds.end();
534 ++i)
535 ignore_result((*i)->release());
536 base::GlobalDescriptors::GetInstance()->Reset(mapping);
538 // Reset the process-wide command line to our new command line.
539 base::CommandLine::Reset();
540 base::CommandLine::Init(0, NULL);
541 base::CommandLine::ForCurrentProcess()->InitFromArgv(args);
543 // Update the process title. The argv was already cached by the call to
544 // SetProcessTitleFromCommandLine in ChromeMain, so we can pass NULL here
545 // (we don't have the original argv at this point).
546 SetProcessTitleFromCommandLine(NULL);
547 } else if (child_pid < 0) {
548 LOG(ERROR) << "Zygote could not fork: process_type " << process_type
549 << " numfds " << numfds << " child_pid " << child_pid;
551 return child_pid;
554 bool Zygote::HandleForkRequest(int fd,
555 PickleIterator iter,
556 ScopedVector<base::ScopedFD> fds) {
557 std::string uma_name;
558 int uma_sample;
559 int uma_boundary_value;
560 base::ProcessId child_pid = ReadArgsAndFork(
561 iter, fds.Pass(), &uma_name, &uma_sample, &uma_boundary_value);
562 if (child_pid == 0)
563 return true;
564 // If there's no UMA report for this particular fork, then check if any
565 // helpers have an initial UMA report for us to send instead.
566 while (uma_name.empty() && initial_uma_index_ < helpers_.size()) {
567 helpers_[initial_uma_index_++]->InitialUMA(
568 &uma_name, &uma_sample, &uma_boundary_value);
570 // Must always send reply, as ZygoteHost blocks while waiting for it.
571 Pickle reply_pickle;
572 reply_pickle.WriteInt(child_pid);
573 reply_pickle.WriteString(uma_name);
574 if (!uma_name.empty()) {
575 reply_pickle.WriteInt(uma_sample);
576 reply_pickle.WriteInt(uma_boundary_value);
578 if (HANDLE_EINTR(write(fd, reply_pickle.data(), reply_pickle.size())) !=
579 static_cast<ssize_t> (reply_pickle.size()))
580 PLOG(ERROR) << "write";
581 return false;
584 bool Zygote::HandleGetSandboxStatus(int fd,
585 PickleIterator iter) {
586 if (HANDLE_EINTR(write(fd, &sandbox_flags_, sizeof(sandbox_flags_))) !=
587 sizeof(sandbox_flags_)) {
588 PLOG(ERROR) << "write";
591 return false;
594 } // namespace content