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/browser/zygote_host/zygote_host_impl_linux.h"
7 #include <sys/socket.h>
12 #include "base/base_switches.h"
13 #include "base/command_line.h"
14 #include "base/environment.h"
15 #include "base/file_util.h"
16 #include "base/files/file_enumerator.h"
17 #include "base/files/scoped_file.h"
18 #include "base/linux_util.h"
19 #include "base/logging.h"
20 #include "base/memory/linked_ptr.h"
21 #include "base/memory/scoped_ptr.h"
22 #include "base/metrics/histogram.h"
23 #include "base/path_service.h"
24 #include "base/posix/eintr_wrapper.h"
25 #include "base/posix/unix_domain_socket_linux.h"
26 #include "base/process/launch.h"
27 #include "base/process/memory.h"
28 #include "base/strings/string_number_conversions.h"
29 #include "base/strings/string_util.h"
30 #include "base/strings/utf_string_conversions.h"
31 #include "base/time/time.h"
32 #include "content/browser/renderer_host/render_sandbox_host_linux.h"
33 #include "content/common/child_process_sandbox_support_impl_linux.h"
34 #include "content/common/zygote_commands_linux.h"
35 #include "content/public/browser/content_browser_client.h"
36 #include "content/public/common/content_switches.h"
37 #include "content/public/common/result_codes.h"
38 #include "sandbox/linux/suid/client/setuid_sandbox_client.h"
39 #include "sandbox/linux/suid/common/sandbox.h"
40 #include "ui/base/ui_base_switches.h"
41 #include "ui/gfx/switches.h"
43 #if defined(USE_TCMALLOC)
44 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
50 ZygoteHost
* ZygoteHost::GetInstance() {
51 return ZygoteHostImpl::GetInstance();
54 ZygoteHostImpl::ZygoteHostImpl()
59 using_suid_sandbox_(false),
61 have_read_sandbox_status_word_(false),
63 child_tracking_lock_(),
64 list_of_running_zygote_children_(),
65 should_teardown_after_last_child_exits_(false) {}
67 ZygoteHostImpl::~ZygoteHostImpl() { TearDown(); }
70 ZygoteHostImpl
* ZygoteHostImpl::GetInstance() {
71 return Singleton
<ZygoteHostImpl
>::get();
74 void ZygoteHostImpl::Init(const std::string
& sandbox_cmd
) {
78 base::FilePath chrome_path
;
79 CHECK(PathService::Get(base::FILE_EXE
, &chrome_path
));
80 CommandLine
cmd_line(chrome_path
);
82 cmd_line
.AppendSwitchASCII(switches::kProcessType
, switches::kZygoteProcess
);
85 #if defined(OS_FREEBSD) || defined(OS_OPENBSD)
86 // The BSDs often don't support SOCK_SEQPACKET yet, so fall back to
87 // SOCK_DGRAM if necessary.
88 if (socketpair(PF_UNIX
, SOCK_SEQPACKET
, 0, fds
) != 0)
89 CHECK(socketpair(PF_UNIX
, SOCK_DGRAM
, 0, fds
) == 0);
91 CHECK(socketpair(PF_UNIX
, SOCK_SEQPACKET
, 0, fds
) == 0);
93 base::FileHandleMappingVector fds_to_map
;
94 fds_to_map
.push_back(std::make_pair(fds
[1], kZygoteSocketPairFd
));
96 const CommandLine
& browser_command_line
= *CommandLine::ForCurrentProcess();
97 if (browser_command_line
.HasSwitch(switches::kZygoteCmdPrefix
)) {
98 cmd_line
.PrependWrapper(
99 browser_command_line
.GetSwitchValueNative(switches::kZygoteCmdPrefix
));
101 // Append any switches from the browser process that need to be forwarded on
102 // to the zygote/renderers.
103 // Should this list be obtained from browser_render_process_host.cc?
104 static const char* kForwardSwitches
[] = {
105 switches::kAllowSandboxDebugging
,
106 switches::kLoggingLevel
,
107 switches::kEnableLogging
, // Support, e.g., --enable-logging=stderr.
110 switches::kRegisterPepperPlugins
,
111 switches::kDisableSeccompFilterSandbox
,
113 // Zygote process needs to know what resources to have loaded when it
114 // becomes a renderer process.
115 switches::kForceDeviceScaleFactor
,
116 switches::kTouchOptimizedUI
,
118 switches::kNoSandbox
,
120 cmd_line
.CopySwitchesFrom(browser_command_line
, kForwardSwitches
,
121 arraysize(kForwardSwitches
));
123 GetContentClient()->browser()->AppendExtraCommandLineSwitches(&cmd_line
, -1);
125 sandbox_binary_
= sandbox_cmd
.c_str();
127 // A non empty sandbox_cmd means we want a SUID sandbox.
128 using_suid_sandbox_
= !sandbox_cmd
.empty();
130 if (using_suid_sandbox_
) {
132 if (stat(sandbox_binary_
.c_str(), &st
) != 0) {
133 LOG(FATAL
) << "The SUID sandbox helper binary is missing: "
134 << sandbox_binary_
<< " Aborting now.";
137 if (access(sandbox_binary_
.c_str(), X_OK
) == 0 &&
139 (st
.st_mode
& S_ISUID
) &&
140 (st
.st_mode
& S_IXOTH
)) {
141 cmd_line
.PrependWrapper(sandbox_binary_
);
143 scoped_ptr
<sandbox::SetuidSandboxClient
>
144 sandbox_client(sandbox::SetuidSandboxClient::Create());
145 sandbox_client
->SetupLaunchEnvironment();
147 LOG(FATAL
) << "The SUID sandbox helper binary was found, but is not "
148 "configured correctly. Rather than run without sandboxing "
149 "I'm aborting now. You need to make sure that "
150 << sandbox_binary_
<< " is owned by root and has mode 4755.";
154 // Start up the sandbox host process and get the file descriptor for the
155 // renderers to talk to it.
156 const int sfd
= RenderSandboxHostLinux::GetInstance()->GetRendererSocket();
157 fds_to_map
.push_back(std::make_pair(sfd
, GetSandboxFD()));
160 if (using_suid_sandbox_
) {
161 dummy_fd
= socket(PF_UNIX
, SOCK_DGRAM
, 0);
162 CHECK(dummy_fd
>= 0);
163 fds_to_map
.push_back(std::make_pair(dummy_fd
, kZygoteIdFd
));
166 base::ProcessHandle process
= -1;
167 base::LaunchOptions options
;
168 options
.fds_to_remap
= &fds_to_map
;
169 base::LaunchProcess(cmd_line
.argv(), options
, &process
);
170 CHECK(process
!= -1) << "Failed to launch zygote process";
172 if (using_suid_sandbox_
) {
173 // In the SUID sandbox, the real zygote is forked from the sandbox.
174 // We need to look for it.
175 // But first, wait for the zygote to tell us it's running.
176 // The sending code is in content/browser/zygote_main_linux.cc.
177 std::vector
<int> fds_vec
;
178 const int kExpectedLength
= sizeof(kZygoteHelloMessage
);
179 char buf
[kExpectedLength
];
180 const ssize_t len
= UnixDomainSocket::RecvMsg(fds
[0], buf
, sizeof(buf
),
182 CHECK(len
== kExpectedLength
) << "Incorrect zygote magic length";
183 CHECK(0 == strcmp(buf
, kZygoteHelloMessage
))
184 << "Incorrect zygote hello";
186 std::string inode_output
;
188 // Figure out the inode for |dummy_fd|, close |dummy_fd| on our end,
189 // and find the zygote process holding |dummy_fd|.
190 if (base::FileDescriptorGetInode(&inode
, dummy_fd
)) {
192 std::vector
<std::string
> get_inode_cmdline
;
193 get_inode_cmdline
.push_back(sandbox_binary_
);
194 get_inode_cmdline
.push_back(base::kFindInodeSwitch
);
195 get_inode_cmdline
.push_back(base::Int64ToString(inode
));
196 CommandLine
get_inode_cmd(get_inode_cmdline
);
197 if (base::GetAppOutput(get_inode_cmd
, &inode_output
)) {
198 base::StringToInt(inode_output
, &pid_
);
201 CHECK(pid_
> 0) << "Did not find zygote process (using sandbox binary "
202 << sandbox_binary_
<< ")";
204 if (process
!= pid_
) {
206 base::EnsureProcessGetsReaped(process
);
209 // Not using the SUID sandbox.
214 control_fd_
= fds
[0];
217 pickle
.WriteInt(kZygoteCommandGetSandboxStatus
);
218 if (!SendMessage(pickle
, NULL
))
219 LOG(FATAL
) << "Cannot communicate with zygote";
220 // We don't wait for the reply. We'll read it in ReadReply.
223 void ZygoteHostImpl::TearDownAfterLastChild() {
224 bool do_teardown
= false;
226 base::AutoLock
lock(child_tracking_lock_
);
227 should_teardown_after_last_child_exits_
= true;
228 do_teardown
= list_of_running_zygote_children_
.empty();
235 // Note: this is also called from the destructor.
236 void ZygoteHostImpl::TearDown() {
237 base::AutoLock
lock(control_lock_
);
238 if (control_fd_
> -1) {
239 // Closing the IPC channel will act as a notification to exit
241 if (IGNORE_EINTR(close(control_fd_
))) {
242 PLOG(ERROR
) << "Could not close Zygote control channel.";
249 void ZygoteHostImpl::ZygoteChildBorn(pid_t process
) {
250 base::AutoLock
lock(child_tracking_lock_
);
251 bool new_element_inserted
=
252 list_of_running_zygote_children_
.insert(process
).second
;
253 DCHECK(new_element_inserted
);
256 void ZygoteHostImpl::ZygoteChildDied(pid_t process
) {
257 bool do_teardown
= false;
259 base::AutoLock
lock(child_tracking_lock_
);
260 size_t num_erased
= list_of_running_zygote_children_
.erase(process
);
261 DCHECK_EQ(1U, num_erased
);
262 do_teardown
= should_teardown_after_last_child_exits_
&&
263 list_of_running_zygote_children_
.empty();
270 bool ZygoteHostImpl::SendMessage(const Pickle
& data
,
271 const std::vector
<int>* fds
) {
272 DCHECK_NE(-1, control_fd_
);
273 CHECK(data
.size() <= kZygoteMaxMessageLength
)
274 << "Trying to send too-large message to zygote (sending " << data
.size()
275 << " bytes, max is " << kZygoteMaxMessageLength
<< ")";
276 CHECK(!fds
|| fds
->size() <= UnixDomainSocket::kMaxFileDescriptors
)
277 << "Trying to send message with too many file descriptors to zygote "
278 << "(sending " << fds
->size() << ", max is "
279 << UnixDomainSocket::kMaxFileDescriptors
<< ")";
281 return UnixDomainSocket::SendMsg(control_fd_
,
282 data
.data(), data
.size(),
283 fds
? *fds
: std::vector
<int>());
286 ssize_t
ZygoteHostImpl::ReadReply(void* buf
, size_t buf_len
) {
287 DCHECK_NE(-1, control_fd_
);
288 // At startup we send a kZygoteCommandGetSandboxStatus request to the zygote,
289 // but don't wait for the reply. Thus, the first time that we read from the
290 // zygote, we get the reply to that request.
291 if (!have_read_sandbox_status_word_
) {
292 if (HANDLE_EINTR(read(control_fd_
, &sandbox_status_
,
293 sizeof(sandbox_status_
))) !=
294 sizeof(sandbox_status_
)) {
297 have_read_sandbox_status_word_
= true;
300 return HANDLE_EINTR(read(control_fd_
, buf
, buf_len
));
303 pid_t
ZygoteHostImpl::ForkRequest(
304 const std::vector
<std::string
>& argv
,
305 const std::vector
<FileDescriptorInfo
>& mapping
,
306 const std::string
& process_type
) {
310 pickle
.WriteInt(kZygoteCommandFork
);
311 pickle
.WriteString(process_type
);
312 pickle
.WriteInt(argv
.size());
313 for (std::vector
<std::string
>::const_iterator
314 i
= argv
.begin(); i
!= argv
.end(); ++i
)
315 pickle
.WriteString(*i
);
317 pickle
.WriteInt(mapping
.size());
319 std::vector
<int> fds
;
320 // Scoped pointers cannot be stored in containers, so we have to use a
322 std::vector
<linked_ptr
<base::ScopedFD
> > autodelete_fds
;
323 for (std::vector
<FileDescriptorInfo
>::const_iterator
324 i
= mapping
.begin(); i
!= mapping
.end(); ++i
) {
325 pickle
.WriteUInt32(i
->id
);
326 fds
.push_back(i
->fd
.fd
);
327 if (i
->fd
.auto_close
) {
328 // Auto-close means we need to close the FDs after they have been passed
329 // to the other process.
330 linked_ptr
<base::ScopedFD
> ptr(new base::ScopedFD(fds
.back()));
331 autodelete_fds
.push_back(ptr
);
337 base::AutoLock
lock(control_lock_
);
338 if (!SendMessage(pickle
, &fds
))
339 return base::kNullProcessHandle
;
341 // Read the reply, which pickles the PID and an optional UMA enumeration.
342 static const unsigned kMaxReplyLength
= 2048;
343 char buf
[kMaxReplyLength
];
344 const ssize_t len
= ReadReply(buf
, sizeof(buf
));
346 Pickle
reply_pickle(buf
, len
);
347 PickleIterator
iter(reply_pickle
);
348 if (len
<= 0 || !reply_pickle
.ReadInt(&iter
, &pid
))
349 return base::kNullProcessHandle
;
351 // If there is a nonempty UMA name string, then there is a UMA
352 // enumeration to record.
353 std::string uma_name
;
355 int uma_boundary_value
;
356 if (reply_pickle
.ReadString(&iter
, &uma_name
) &&
358 reply_pickle
.ReadInt(&iter
, &uma_sample
) &&
359 reply_pickle
.ReadInt(&iter
, &uma_boundary_value
)) {
360 // We cannot use the UMA_HISTOGRAM_ENUMERATION macro here,
361 // because that's only for when the name is the same every time.
362 // Here we're using whatever name we got from the other side.
363 // But since it's likely that the same one will be used repeatedly
364 // (even though it's not guaranteed), we cache it here.
365 static base::HistogramBase
* uma_histogram
;
366 if (!uma_histogram
|| uma_histogram
->histogram_name() != uma_name
) {
367 uma_histogram
= base::LinearHistogram::FactoryGet(
370 uma_boundary_value
+ 1,
371 base::HistogramBase::kUmaTargetedHistogramFlag
);
373 uma_histogram
->Add(uma_sample
);
377 return base::kNullProcessHandle
;
380 #if !defined(OS_OPENBSD)
381 // This is just a starting score for a renderer or extension (the
382 // only types of processes that will be started this way). It will
383 // get adjusted as time goes on. (This is the same value as
384 // chrome::kLowestRendererOomScore in chrome/chrome_constants.h, but
385 // that's not something we can include here.)
386 const int kLowestRendererOomScore
= 300;
387 AdjustRendererOOMScore(pid
, kLowestRendererOomScore
);
390 ZygoteChildBorn(pid
);
394 #if !defined(OS_OPENBSD)
395 void ZygoteHostImpl::AdjustRendererOOMScore(base::ProcessHandle pid
,
397 // 1) You can't change the oom_score_adj of a non-dumpable process
398 // (EPERM) unless you're root. Because of this, we can't set the
399 // oom_adj from the browser process.
401 // 2) We can't set the oom_score_adj before entering the sandbox
402 // because the zygote is in the sandbox and the zygote is as
403 // critical as the browser process. Its oom_adj value shouldn't
406 // 3) A non-dumpable process can't even change its own oom_score_adj
407 // because it's root owned 0644. The sandboxed processes don't
408 // even have /proc, but one could imagine passing in a descriptor
411 // So, in the normal case, we use the SUID binary to change it for us.
412 // However, Fedora (and other SELinux systems) don't like us touching other
413 // process's oom_score_adj (or oom_adj) values
414 // (https://bugzilla.redhat.com/show_bug.cgi?id=581256).
416 // The offical way to get the SELinux mode is selinux_getenforcemode, but I
417 // don't want to add another library to the build as it's sure to cause
418 // problems with other, non-SELinux distros.
420 // So we just check for files in /selinux. This isn't foolproof, but it's not
421 // bad and it's easy.
424 static bool selinux_valid
= false;
426 if (!selinux_valid
) {
427 const base::FilePath
kSelinuxPath("/selinux");
428 base::FileEnumerator
en(kSelinuxPath
, false, base::FileEnumerator::FILES
);
429 bool has_selinux_files
= !en
.Next().empty();
431 selinux
= access(kSelinuxPath
.value().c_str(), X_OK
) == 0 &&
433 selinux_valid
= true;
436 if (using_suid_sandbox_
&& !selinux
) {
437 #if defined(USE_TCMALLOC)
438 // If heap profiling is running, these processes are not exiting, at least
439 // on ChromeOS. The easiest thing to do is not launch them when profiling.
440 // TODO(stevenjb): Investigate further and fix.
441 if (IsHeapProfilerRunning())
444 std::vector
<std::string
> adj_oom_score_cmdline
;
445 adj_oom_score_cmdline
.push_back(sandbox_binary_
);
446 adj_oom_score_cmdline
.push_back(sandbox::kAdjustOOMScoreSwitch
);
447 adj_oom_score_cmdline
.push_back(base::Int64ToString(pid
));
448 adj_oom_score_cmdline
.push_back(base::IntToString(score
));
450 base::ProcessHandle sandbox_helper_process
;
451 if (base::LaunchProcess(adj_oom_score_cmdline
, base::LaunchOptions(),
452 &sandbox_helper_process
)) {
453 base::EnsureProcessGetsReaped(sandbox_helper_process
);
455 } else if (!using_suid_sandbox_
) {
456 if (!base::AdjustOOMScore(pid
, score
))
457 PLOG(ERROR
) << "Failed to adjust OOM score of renderer with pid " << pid
;
462 void ZygoteHostImpl::EnsureProcessTerminated(pid_t process
) {
466 pickle
.WriteInt(kZygoteCommandReap
);
467 pickle
.WriteInt(process
);
468 if (!SendMessage(pickle
, NULL
))
469 LOG(ERROR
) << "Failed to send Reap message to zygote";
470 ZygoteChildDied(process
);
473 base::TerminationStatus
ZygoteHostImpl::GetTerminationStatus(
474 base::ProcessHandle handle
,
479 pickle
.WriteInt(kZygoteCommandGetTerminationStatus
);
480 pickle
.WriteBool(known_dead
);
481 pickle
.WriteInt(handle
);
483 static const unsigned kMaxMessageLength
= 128;
484 char buf
[kMaxMessageLength
];
487 base::AutoLock
lock(control_lock_
);
488 if (!SendMessage(pickle
, NULL
))
489 LOG(ERROR
) << "Failed to send GetTerminationStatus message to zygote";
490 len
= ReadReply(buf
, sizeof(buf
));
493 // Set this now to handle the error cases.
495 *exit_code
= RESULT_CODE_NORMAL_EXIT
;
496 int status
= base::TERMINATION_STATUS_NORMAL_TERMINATION
;
499 LOG(WARNING
) << "Error reading message from zygote: " << errno
;
500 } else if (len
== 0) {
501 LOG(WARNING
) << "Socket closed prematurely.";
503 Pickle
read_pickle(buf
, len
);
504 int tmp_status
, tmp_exit_code
;
505 PickleIterator
iter(read_pickle
);
506 if (!read_pickle
.ReadInt(&iter
, &tmp_status
) ||
507 !read_pickle
.ReadInt(&iter
, &tmp_exit_code
)) {
509 << "Error parsing GetTerminationStatus response from zygote.";
512 *exit_code
= tmp_exit_code
;
517 if (status
!= base::TERMINATION_STATUS_STILL_RUNNING
) {
518 ZygoteChildDied(handle
);
520 return static_cast<base::TerminationStatus
>(status
);
523 pid_t
ZygoteHostImpl::GetPid() const {
527 pid_t
ZygoteHostImpl::GetSandboxHelperPid() const {
528 return RenderSandboxHostLinux::GetInstance()->pid();
531 int ZygoteHostImpl::GetSandboxStatus() const {
532 if (have_read_sandbox_status_word_
)
533 return sandbox_status_
;
537 } // namespace content