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/file_util.h"
16 #include "base/linux_util.h"
17 #include "base/logging.h"
18 #include "base/pickle.h"
19 #include "base/posix/eintr_wrapper.h"
20 #include "base/posix/global_descriptors.h"
21 #include "base/posix/unix_domain_socket_linux.h"
22 #include "base/process/kill.h"
23 #include "content/common/child_process_sandbox_support_impl_linux.h"
24 #include "content/common/sandbox_linux.h"
25 #include "content/common/set_process_title.h"
26 #include "content/common/zygote_commands_linux.h"
27 #include "content/public/common/content_descriptors.h"
28 #include "content/public/common/result_codes.h"
29 #include "content/public/common/sandbox_linux.h"
30 #include "content/public/common/zygote_fork_delegate_linux.h"
31 #include "ipc/ipc_channel.h"
32 #include "ipc/ipc_switches.h"
34 // See http://code.google.com/p/chromium/wiki/LinuxZygote
40 // NOP function. See below where this handler is installed.
41 void SIGCHLDHandler(int signal
) {
46 Zygote::Zygote(int sandbox_flags
,
47 ZygoteForkDelegate
* helper
)
48 : sandbox_flags_(sandbox_flags
),
50 initial_uma_sample_(0),
51 initial_uma_boundary_value_(0) {
53 helper_
->InitialUMA(&initial_uma_name_
,
55 &initial_uma_boundary_value_
);
62 bool Zygote::ProcessRequests() {
63 // A SOCK_SEQPACKET socket is installed in fd 3. We get commands from the
65 // A SOCK_DGRAM is installed in fd 5. This is the sandbox IPC channel.
66 // See http://code.google.com/p/chromium/wiki/LinuxSandboxIPC
68 // We need to accept SIGCHLD, even though our handler is a no-op because
69 // otherwise we cannot wait on children. (According to POSIX 2001.)
70 struct sigaction action
;
71 memset(&action
, 0, sizeof(action
));
72 action
.sa_handler
= &SIGCHLDHandler
;
73 CHECK(sigaction(SIGCHLD
, &action
, NULL
) == 0);
75 if (UsingSUIDSandbox()) {
76 // Let the ZygoteHost know we are ready to go.
77 // The receiving code is in content/browser/zygote_host_linux.cc.
78 std::vector
<int> empty
;
79 bool r
= UnixDomainSocket::SendMsg(kZygoteSocketPairFd
,
81 sizeof(kZygoteHelloMessage
), empty
);
82 #if defined(OS_CHROMEOS)
83 LOG_IF(WARNING
, !r
) << "Sending zygote magic failed";
84 // Exit normally on chromeos because session manager may send SIGTERM
85 // right after the process starts and it may fail to send zygote magic
86 // number to browser process.
88 _exit(RESULT_CODE_NORMAL_EXIT
);
90 CHECK(r
) << "Sending zygote magic failed";
95 // This function call can return multiple times, once per fork().
96 if (HandleRequestFromBrowser(kZygoteSocketPairFd
))
101 bool Zygote::GetProcessInfo(base::ProcessHandle pid
,
102 ZygoteProcessInfo
* process_info
) {
103 DCHECK(process_info
);
104 const ZygoteProcessMap::const_iterator it
= process_info_map_
.find(pid
);
105 if (it
== process_info_map_
.end()) {
108 *process_info
= it
->second
;
112 bool Zygote::UsingSUIDSandbox() const {
113 return sandbox_flags_
& kSandboxLinuxSUID
;
116 bool Zygote::HandleRequestFromBrowser(int fd
) {
117 std::vector
<int> fds
;
118 char buf
[kZygoteMaxMessageLength
];
119 const ssize_t len
= UnixDomainSocket::RecvMsg(fd
, buf
, sizeof(buf
), &fds
);
121 if (len
== 0 || (len
== -1 && errno
== ECONNRESET
)) {
122 // EOF from the browser. We should die.
128 PLOG(ERROR
) << "Error reading message from browser";
132 Pickle
pickle(buf
, len
);
133 PickleIterator
iter(pickle
);
136 if (pickle
.ReadInt(&iter
, &kind
)) {
138 case kZygoteCommandFork
:
139 // This function call can return multiple times, once per fork().
140 return HandleForkRequest(fd
, pickle
, iter
, fds
);
142 case kZygoteCommandReap
:
145 HandleReapRequest(fd
, pickle
, iter
);
147 case kZygoteCommandGetTerminationStatus
:
150 HandleGetTerminationStatus(fd
, pickle
, iter
);
152 case kZygoteCommandGetSandboxStatus
:
153 HandleGetSandboxStatus(fd
, pickle
, iter
);
161 LOG(WARNING
) << "Error parsing message from browser";
162 for (std::vector
<int>::const_iterator
163 i
= fds
.begin(); i
!= fds
.end(); ++i
)
168 // TODO(jln): remove callers to this broken API. See crbug.com/274855.
169 void Zygote::HandleReapRequest(int fd
,
170 const Pickle
& pickle
,
171 PickleIterator iter
) {
172 base::ProcessId child
;
174 if (!pickle
.ReadInt(&iter
, &child
)) {
175 LOG(WARNING
) << "Error parsing reap request from browser";
179 ZygoteProcessInfo child_info
;
180 if (!GetProcessInfo(child
, &child_info
)) {
181 LOG(ERROR
) << "Child not found!";
186 if (!child_info
.started_from_helper
) {
187 // TODO(jln): this old code is completely broken. See crbug.com/274855.
188 base::EnsureProcessTerminated(child_info
.internal_pid
);
190 // For processes from the helper, send a GetTerminationStatus request
191 // with known_dead set to true.
192 // This is not perfect, as the process may be killed instantly, but is
193 // better than ignoring the request.
194 base::TerminationStatus status
;
196 bool got_termination_status
=
197 GetTerminationStatus(child
, true /* known_dead */, &status
, &exit_code
);
198 DCHECK(got_termination_status
);
200 process_info_map_
.erase(child
);
203 bool Zygote::GetTerminationStatus(base::ProcessHandle real_pid
,
205 base::TerminationStatus
* status
,
208 ZygoteProcessInfo child_info
;
209 if (!GetProcessInfo(real_pid
, &child_info
)) {
210 LOG(ERROR
) << "Zygote::GetTerminationStatus for unknown PID "
215 // We know about |real_pid|.
216 const base::ProcessHandle child
= child_info
.internal_pid
;
217 if (child_info
.started_from_helper
) {
218 // Let the helper handle the request.
220 if (!helper_
->GetTerminationStatus(child
, known_dead
, status
, exit_code
)) {
224 // Handle the request directly.
226 // If we know that the process is already dead and the kernel is cleaning
227 // it up, we do want to wait until it becomes a zombie and not risk
228 // returning eroneously that it is still running. However, we do not
229 // want to risk a bug where we're told a process is dead when it's not.
230 // By sending SIGKILL, we make sure that WaitForTerminationStatus will
231 // return quickly even in this case.
232 if (kill(child
, SIGKILL
)) {
233 PLOG(ERROR
) << "kill (" << child
<< ")";
235 *status
= base::WaitForTerminationStatus(child
, exit_code
);
237 // We don't know if the process is dying, so get its status but don't
239 *status
= base::GetTerminationStatus(child
, exit_code
);
242 // Successfully got a status for |real_pid|.
243 if (*status
!= base::TERMINATION_STATUS_STILL_RUNNING
) {
244 // Time to forget about this process.
245 process_info_map_
.erase(real_pid
);
250 void Zygote::HandleGetTerminationStatus(int fd
,
251 const Pickle
& pickle
,
252 PickleIterator iter
) {
254 base::ProcessHandle child_requested
;
256 if (!pickle
.ReadBool(&iter
, &known_dead
) ||
257 !pickle
.ReadInt(&iter
, &child_requested
)) {
258 LOG(WARNING
) << "Error parsing GetTerminationStatus request "
263 base::TerminationStatus status
;
266 bool got_termination_status
=
267 GetTerminationStatus(child_requested
, known_dead
, &status
, &exit_code
);
268 if (!got_termination_status
) {
269 // Assume that if we can't find the child in the sandbox, then
270 // it terminated normally.
272 status
= base::TERMINATION_STATUS_NORMAL_TERMINATION
;
273 exit_code
= RESULT_CODE_NORMAL_EXIT
;
277 write_pickle
.WriteInt(static_cast<int>(status
));
278 write_pickle
.WriteInt(exit_code
);
280 HANDLE_EINTR(write(fd
, write_pickle
.data(), write_pickle
.size()));
281 if (written
!= static_cast<ssize_t
>(write_pickle
.size()))
282 PLOG(ERROR
) << "write";
285 int Zygote::ForkWithRealPid(const std::string
& process_type
,
286 std::vector
<int>& fds
,
287 const std::string
& channel_switch
,
288 std::string
* uma_name
,
290 int* uma_boundary_value
) {
291 const bool use_helper
= (helper_
&& helper_
->CanHelp(process_type
,
294 uma_boundary_value
));
297 int pipe_fds
[2] = { -1, -1 };
298 base::ProcessId pid
= 0;
300 dummy_fd
= socket(PF_UNIX
, SOCK_DGRAM
, 0);
302 LOG(ERROR
) << "Failed to create dummy FD";
305 if (!base::FileDescriptorGetInode(&dummy_inode
, dummy_fd
)) {
306 LOG(ERROR
) << "Failed to get inode for dummy FD";
309 if (pipe(pipe_fds
) != 0) {
310 LOG(ERROR
) << "Failed to create pipe";
315 fds
.push_back(dummy_fd
);
316 fds
.push_back(pipe_fds
[0]);
317 pid
= helper_
->Fork(fds
);
323 } else if (pid
== 0) {
324 // In the child process.
326 base::ProcessId real_pid
;
327 // Wait until the parent process has discovered our PID. We
328 // should not fork any child processes (which the seccomp
329 // sandbox does) until then, because that can interfere with the
330 // parent's discovery of our PID.
331 if (!file_util::ReadFromFD(pipe_fds
[0],
332 reinterpret_cast<char*>(&real_pid
),
334 LOG(FATAL
) << "Failed to synchronise with parent zygote process";
337 LOG(FATAL
) << "Invalid pid from parent zygote";
339 #if defined(OS_LINUX)
340 // Sandboxed processes need to send the global, non-namespaced PID when
341 // setting up an IPC channel to their parent.
342 IPC::Channel::SetGlobalPid(real_pid
);
343 // Force the real PID so chrome event data have a PID that corresponds
344 // to system trace event data.
345 base::debug::TraceLog::GetInstance()->SetProcessID(
346 static_cast<int>(real_pid
));
352 // In the parent process.
357 base::ProcessId real_pid
;
358 if (UsingSUIDSandbox()) {
359 uint8_t reply_buf
[512];
361 request
.WriteInt(LinuxSandbox::METHOD_GET_CHILD_WITH_INODE
);
362 request
.WriteUInt64(dummy_inode
);
364 const ssize_t r
= UnixDomainSocket::SendRecvMsg(
365 GetSandboxFD(), reply_buf
, sizeof(reply_buf
), NULL
,
368 LOG(ERROR
) << "Failed to get child process's real PID";
372 Pickle
reply(reinterpret_cast<char*>(reply_buf
), r
);
373 PickleIterator
iter(reply
);
374 if (!reply
.ReadInt(&iter
, &real_pid
))
377 // METHOD_GET_CHILD_WITH_INODE failed. Did the child die already?
378 LOG(ERROR
) << "METHOD_GET_CHILD_WITH_INODE failed";
382 // If no SUID sandbox is involved then no pid translation is
387 // Now set-up this process to be tracked by the Zygote.
388 if (process_info_map_
.find(real_pid
) != process_info_map_
.end()) {
389 LOG(ERROR
) << "Already tracking PID " << real_pid
;
392 process_info_map_
[real_pid
].internal_pid
= pid
;
393 process_info_map_
[real_pid
].started_from_helper
= use_helper
;
396 if (!helper_
->AckChild(pipe_fds
[1], channel_switch
)) {
397 LOG(ERROR
) << "Failed to synchronise with zygote fork helper";
402 HANDLE_EINTR(write(pipe_fds
[1], &real_pid
, sizeof(real_pid
)));
403 if (written
!= sizeof(real_pid
)) {
404 LOG(ERROR
) << "Failed to synchronise with child process";
414 if (waitpid(pid
, NULL
, WNOHANG
) == -1)
415 LOG(ERROR
) << "Failed to wait for process";
419 if (pipe_fds
[0] >= 0)
421 if (pipe_fds
[1] >= 0)
426 base::ProcessId
Zygote::ReadArgsAndFork(const Pickle
& pickle
,
428 std::vector
<int>& fds
,
429 std::string
* uma_name
,
431 int* uma_boundary_value
) {
432 std::vector
<std::string
> args
;
435 base::GlobalDescriptors::Mapping mapping
;
436 std::string process_type
;
437 std::string channel_id
;
438 const std::string channel_id_prefix
= std::string("--")
439 + switches::kProcessChannelID
+ std::string("=");
441 if (!pickle
.ReadString(&iter
, &process_type
))
443 if (!pickle
.ReadInt(&iter
, &argc
))
446 for (int i
= 0; i
< argc
; ++i
) {
448 if (!pickle
.ReadString(&iter
, &arg
))
451 if (arg
.compare(0, channel_id_prefix
.length(), channel_id_prefix
) == 0)
455 if (!pickle
.ReadInt(&iter
, &numfds
))
457 if (numfds
!= static_cast<int>(fds
.size()))
460 for (int i
= 0; i
< numfds
; ++i
) {
461 base::GlobalDescriptors::Key key
;
462 if (!pickle
.ReadUInt32(&iter
, &key
))
464 mapping
.push_back(std::make_pair(key
, fds
[i
]));
467 mapping
.push_back(std::make_pair(
468 static_cast<uint32_t>(kSandboxIPCChannel
), GetSandboxFD()));
470 // Returns twice, once per process.
471 base::ProcessId child_pid
= ForkWithRealPid(process_type
, fds
, channel_id
,
472 uma_name
, uma_sample
,
475 // This is the child process.
477 close(kZygoteSocketPairFd
); // Our socket from the browser.
478 if (UsingSUIDSandbox())
479 close(kZygoteIdFd
); // Another socket from the browser.
480 base::GlobalDescriptors::GetInstance()->Reset(mapping
);
482 // Reset the process-wide command line to our new command line.
483 CommandLine::Reset();
484 CommandLine::Init(0, NULL
);
485 CommandLine::ForCurrentProcess()->InitFromArgv(args
);
487 // Update the process title. The argv was already cached by the call to
488 // SetProcessTitleFromCommandLine in ChromeMain, so we can pass NULL here
489 // (we don't have the original argv at this point).
490 SetProcessTitleFromCommandLine(NULL
);
491 } else if (child_pid
< 0) {
492 LOG(ERROR
) << "Zygote could not fork: process_type " << process_type
493 << " numfds " << numfds
<< " child_pid " << child_pid
;
498 bool Zygote::HandleForkRequest(int fd
,
499 const Pickle
& pickle
,
501 std::vector
<int>& fds
) {
502 std::string uma_name
;
504 int uma_boundary_value
;
505 base::ProcessId child_pid
= ReadArgsAndFork(pickle
, iter
, fds
,
506 &uma_name
, &uma_sample
,
507 &uma_boundary_value
);
510 for (std::vector
<int>::const_iterator
511 i
= fds
.begin(); i
!= fds
.end(); ++i
)
513 if (uma_name
.empty()) {
514 // There is no UMA report from this particular fork.
515 // Use the initial UMA report if any, and clear that record for next time.
516 // Note the swap method here is the efficient way to do this, since
517 // we know uma_name is empty.
518 uma_name
.swap(initial_uma_name_
);
519 uma_sample
= initial_uma_sample_
;
520 uma_boundary_value
= initial_uma_boundary_value_
;
522 // Must always send reply, as ZygoteHost blocks while waiting for it.
524 reply_pickle
.WriteInt(child_pid
);
525 reply_pickle
.WriteString(uma_name
);
526 if (!uma_name
.empty()) {
527 reply_pickle
.WriteInt(uma_sample
);
528 reply_pickle
.WriteInt(uma_boundary_value
);
530 if (HANDLE_EINTR(write(fd
, reply_pickle
.data(), reply_pickle
.size())) !=
531 static_cast<ssize_t
> (reply_pickle
.size()))
532 PLOG(ERROR
) << "write";
536 bool Zygote::HandleGetSandboxStatus(int fd
,
537 const Pickle
& pickle
,
538 PickleIterator iter
) {
539 if (HANDLE_EINTR(write(fd
, &sandbox_flags_
, sizeof(sandbox_flags_
))) !=
540 sizeof(sandbox_flags_
)) {
541 PLOG(ERROR
) << "write";
547 } // namespace content