Change next_proto member type.
[chromium-blink-merge.git] / content / browser / zygote_host / zygote_host_impl_linux.cc
blobc2f1c908c0a50bb9b22f587f4729009e8a8d13a7
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 <string.h>
8 #include <sys/socket.h>
9 #include <sys/stat.h>
10 #include <sys/types.h>
11 #include <unistd.h>
13 #include "base/base_switches.h"
14 #include "base/command_line.h"
15 #include "base/environment.h"
16 #include "base/files/file_enumerator.h"
17 #include "base/files/file_util.h"
18 #include "base/files/scoped_file.h"
19 #include "base/linux_util.h"
20 #include "base/logging.h"
21 #include "base/memory/linked_ptr.h"
22 #include "base/memory/scoped_ptr.h"
23 #include "base/memory/scoped_vector.h"
24 #include "base/metrics/histogram.h"
25 #include "base/path_service.h"
26 #include "base/posix/eintr_wrapper.h"
27 #include "base/posix/unix_domain_socket_linux.h"
28 #include "base/process/launch.h"
29 #include "base/process/memory.h"
30 #include "base/process/process_handle.h"
31 #include "base/strings/string_number_conversions.h"
32 #include "base/strings/string_util.h"
33 #include "base/strings/utf_string_conversions.h"
34 #include "base/time/time.h"
35 #include "content/browser/renderer_host/render_sandbox_host_linux.h"
36 #include "content/common/child_process_sandbox_support_impl_linux.h"
37 #include "content/common/zygote_commands_linux.h"
38 #include "content/public/browser/content_browser_client.h"
39 #include "content/public/common/content_switches.h"
40 #include "content/public/common/result_codes.h"
41 #include "sandbox/linux/suid/client/setuid_sandbox_client.h"
42 #include "sandbox/linux/suid/common/sandbox.h"
43 #include "ui/base/ui_base_switches.h"
44 #include "ui/gfx/switches.h"
46 #if defined(USE_TCMALLOC)
47 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
48 #endif
50 namespace content {
52 // Receive a fixed message on fd and return the sender's PID.
53 // Returns true if the message received matches the expected message.
54 static bool ReceiveFixedMessage(int fd,
55 const char* expect_msg,
56 size_t expect_len,
57 base::ProcessId* sender_pid) {
58 char buf[expect_len + 1];
59 ScopedVector<base::ScopedFD> fds_vec;
61 const ssize_t len = UnixDomainSocket::RecvMsgWithPid(
62 fd, buf, sizeof(buf), &fds_vec, sender_pid);
63 if (static_cast<size_t>(len) != expect_len)
64 return false;
65 if (memcmp(buf, expect_msg, expect_len) != 0)
66 return false;
67 if (!fds_vec.empty())
68 return false;
69 return true;
72 // static
73 ZygoteHost* ZygoteHost::GetInstance() {
74 return ZygoteHostImpl::GetInstance();
77 ZygoteHostImpl::ZygoteHostImpl()
78 : control_fd_(-1),
79 control_lock_(),
80 pid_(-1),
81 init_(false),
82 using_suid_sandbox_(false),
83 sandbox_binary_(),
84 have_read_sandbox_status_word_(false),
85 sandbox_status_(0),
86 child_tracking_lock_(),
87 list_of_running_zygote_children_(),
88 should_teardown_after_last_child_exits_(false) {}
90 ZygoteHostImpl::~ZygoteHostImpl() { TearDown(); }
92 // static
93 ZygoteHostImpl* ZygoteHostImpl::GetInstance() {
94 return Singleton<ZygoteHostImpl>::get();
97 void ZygoteHostImpl::Init(const std::string& sandbox_cmd) {
98 DCHECK(!init_);
99 init_ = true;
101 base::FilePath chrome_path;
102 CHECK(PathService::Get(base::FILE_EXE, &chrome_path));
103 base::CommandLine cmd_line(chrome_path);
105 cmd_line.AppendSwitchASCII(switches::kProcessType, switches::kZygoteProcess);
107 int fds[2];
108 CHECK(socketpair(AF_UNIX, SOCK_SEQPACKET, 0, fds) == 0);
109 CHECK(UnixDomainSocket::EnableReceiveProcessId(fds[0]));
110 base::FileHandleMappingVector fds_to_map;
111 fds_to_map.push_back(std::make_pair(fds[1], kZygoteSocketPairFd));
113 base::LaunchOptions options;
114 const base::CommandLine& browser_command_line =
115 *base::CommandLine::ForCurrentProcess();
116 if (browser_command_line.HasSwitch(switches::kZygoteCmdPrefix)) {
117 cmd_line.PrependWrapper(
118 browser_command_line.GetSwitchValueNative(switches::kZygoteCmdPrefix));
120 // Append any switches from the browser process that need to be forwarded on
121 // to the zygote/renderers.
122 // Should this list be obtained from browser_render_process_host.cc?
123 static const char* kForwardSwitches[] = {
124 switches::kAllowSandboxDebugging,
125 switches::kDisableSeccompFilterSandbox,
126 switches::kEnableLogging, // Support, e.g., --enable-logging=stderr.
127 // Zygote process needs to know what resources to have loaded when it
128 // becomes a renderer process.
129 switches::kForceDeviceScaleFactor,
130 switches::kLoggingLevel,
131 switches::kNoSandbox,
132 switches::kPpapiInProcess,
133 switches::kRegisterPepperPlugins,
134 switches::kV,
135 switches::kVModule,
137 cmd_line.CopySwitchesFrom(browser_command_line, kForwardSwitches,
138 arraysize(kForwardSwitches));
140 GetContentClient()->browser()->AppendExtraCommandLineSwitches(&cmd_line, -1);
142 sandbox_binary_ = sandbox_cmd.c_str();
144 // A non empty sandbox_cmd means we want a SUID sandbox.
145 using_suid_sandbox_ = !sandbox_cmd.empty();
147 // Start up the sandbox host process and get the file descriptor for the
148 // renderers to talk to it.
149 const int sfd = RenderSandboxHostLinux::GetInstance()->GetRendererSocket();
150 fds_to_map.push_back(std::make_pair(sfd, GetSandboxFD()));
152 base::ScopedFD dummy_fd;
153 if (using_suid_sandbox_) {
154 scoped_ptr<sandbox::SetuidSandboxClient>
155 sandbox_client(sandbox::SetuidSandboxClient::Create());
156 sandbox_client->PrependWrapper(&cmd_line);
157 sandbox_client->SetupLaunchOptions(&options, &fds_to_map, &dummy_fd);
158 sandbox_client->SetupLaunchEnvironment();
161 base::ProcessHandle process = -1;
162 options.fds_to_remap = &fds_to_map;
163 base::LaunchProcess(cmd_line.argv(), options, &process);
164 CHECK(process != -1) << "Failed to launch zygote process";
165 dummy_fd.reset();
167 if (using_suid_sandbox_) {
168 // The SUID sandbox will execute the zygote in a new PID namespace, and
169 // the main zygote process will then fork from there. Watch now our
170 // elaborate dance to find and validate the zygote's PID.
172 // First we receive a message from the zygote boot process.
173 base::ProcessId boot_pid;
174 CHECK(ReceiveFixedMessage(
175 fds[0], kZygoteBootMessage, sizeof(kZygoteBootMessage), &boot_pid));
177 // Within the PID namespace, the zygote boot process thinks it's PID 1,
178 // but its real PID can never be 1. This gives us a reliable test that
179 // the kernel is translating the sender's PID to our namespace.
180 CHECK_GT(boot_pid, 1)
181 << "Received invalid process ID for zygote; kernel might be too old? "
182 "See crbug.com/357670 or try using --"
183 << switches::kDisableSetuidSandbox << " to workaround.";
185 // Now receive the message that the zygote's ready to go, along with the
186 // main zygote process's ID.
187 CHECK(ReceiveFixedMessage(
188 fds[0], kZygoteHelloMessage, sizeof(kZygoteHelloMessage), &pid_));
189 CHECK_GT(pid_, 1);
191 if (process != pid_) {
192 // Reap the sandbox.
193 base::EnsureProcessGetsReaped(process);
195 } else {
196 // Not using the SUID sandbox.
197 pid_ = process;
200 close(fds[1]);
201 control_fd_ = fds[0];
203 Pickle pickle;
204 pickle.WriteInt(kZygoteCommandGetSandboxStatus);
205 if (!SendMessage(pickle, NULL))
206 LOG(FATAL) << "Cannot communicate with zygote";
207 // We don't wait for the reply. We'll read it in ReadReply.
210 void ZygoteHostImpl::TearDownAfterLastChild() {
211 bool do_teardown = false;
213 base::AutoLock lock(child_tracking_lock_);
214 should_teardown_after_last_child_exits_ = true;
215 do_teardown = list_of_running_zygote_children_.empty();
217 if (do_teardown) {
218 TearDown();
222 // Note: this is also called from the destructor.
223 void ZygoteHostImpl::TearDown() {
224 base::AutoLock lock(control_lock_);
225 if (control_fd_ > -1) {
226 // Closing the IPC channel will act as a notification to exit
227 // to the Zygote.
228 if (IGNORE_EINTR(close(control_fd_))) {
229 PLOG(ERROR) << "Could not close Zygote control channel.";
230 NOTREACHED();
232 control_fd_ = -1;
236 void ZygoteHostImpl::ZygoteChildBorn(pid_t process) {
237 base::AutoLock lock(child_tracking_lock_);
238 bool new_element_inserted =
239 list_of_running_zygote_children_.insert(process).second;
240 DCHECK(new_element_inserted);
243 void ZygoteHostImpl::ZygoteChildDied(pid_t process) {
244 bool do_teardown = false;
246 base::AutoLock lock(child_tracking_lock_);
247 size_t num_erased = list_of_running_zygote_children_.erase(process);
248 DCHECK_EQ(1U, num_erased);
249 do_teardown = should_teardown_after_last_child_exits_ &&
250 list_of_running_zygote_children_.empty();
252 if (do_teardown) {
253 TearDown();
257 bool ZygoteHostImpl::SendMessage(const Pickle& data,
258 const std::vector<int>* fds) {
259 DCHECK_NE(-1, control_fd_);
260 CHECK(data.size() <= kZygoteMaxMessageLength)
261 << "Trying to send too-large message to zygote (sending " << data.size()
262 << " bytes, max is " << kZygoteMaxMessageLength << ")";
263 CHECK(!fds || fds->size() <= UnixDomainSocket::kMaxFileDescriptors)
264 << "Trying to send message with too many file descriptors to zygote "
265 << "(sending " << fds->size() << ", max is "
266 << UnixDomainSocket::kMaxFileDescriptors << ")";
268 return UnixDomainSocket::SendMsg(control_fd_,
269 data.data(), data.size(),
270 fds ? *fds : std::vector<int>());
273 ssize_t ZygoteHostImpl::ReadReply(void* buf, size_t buf_len) {
274 DCHECK_NE(-1, control_fd_);
275 // At startup we send a kZygoteCommandGetSandboxStatus request to the zygote,
276 // but don't wait for the reply. Thus, the first time that we read from the
277 // zygote, we get the reply to that request.
278 if (!have_read_sandbox_status_word_) {
279 if (HANDLE_EINTR(read(control_fd_, &sandbox_status_,
280 sizeof(sandbox_status_))) !=
281 sizeof(sandbox_status_)) {
282 return -1;
284 have_read_sandbox_status_word_ = true;
287 return HANDLE_EINTR(read(control_fd_, buf, buf_len));
290 pid_t ZygoteHostImpl::ForkRequest(const std::vector<std::string>& argv,
291 scoped_ptr<FileDescriptorInfo> mapping,
292 const std::string& process_type) {
293 DCHECK(init_);
294 Pickle pickle;
296 int raw_socks[2];
297 PCHECK(0 == socketpair(AF_UNIX, SOCK_SEQPACKET, 0, raw_socks));
298 base::ScopedFD my_sock(raw_socks[0]);
299 base::ScopedFD peer_sock(raw_socks[1]);
300 CHECK(UnixDomainSocket::EnableReceiveProcessId(my_sock.get()));
302 pickle.WriteInt(kZygoteCommandFork);
303 pickle.WriteString(process_type);
304 pickle.WriteInt(argv.size());
305 for (std::vector<std::string>::const_iterator
306 i = argv.begin(); i != argv.end(); ++i)
307 pickle.WriteString(*i);
309 // Fork requests contain one file descriptor for the PID oracle, and one
310 // more for each file descriptor mapping for the child process.
311 const size_t num_fds_to_send = 1 + mapping->GetMappingSize();
312 pickle.WriteInt(num_fds_to_send);
314 std::vector<int> fds;
316 // First FD to send is peer_sock.
317 // TODO(morrita): Ideally, this should be part of the mapping so that
318 // FileDescriptorInfo can manages its lifetime.
319 fds.push_back(peer_sock.get());
321 // The rest come from mapping.
322 for (size_t i = 0; i < mapping->GetMappingSize(); ++i) {
323 pickle.WriteUInt32(mapping->GetIDAt(i));
324 fds.push_back(mapping->GetFDAt(i));
327 // Sanity check that we've populated |fds| correctly.
328 DCHECK_EQ(num_fds_to_send, fds.size());
330 pid_t pid;
332 base::AutoLock lock(control_lock_);
333 if (!SendMessage(pickle, &fds))
334 return base::kNullProcessHandle;
335 mapping.reset();
336 peer_sock.reset();
339 char buf[sizeof(kZygoteChildPingMessage) + 1];
340 ScopedVector<base::ScopedFD> recv_fds;
341 base::ProcessId real_pid;
343 ssize_t n = UnixDomainSocket::RecvMsgWithPid(
344 my_sock.get(), buf, sizeof(buf), &recv_fds, &real_pid);
345 if (n != sizeof(kZygoteChildPingMessage) ||
346 0 != memcmp(buf,
347 kZygoteChildPingMessage,
348 sizeof(kZygoteChildPingMessage))) {
349 // Zygote children should still be trustworthy when they're supposed to
350 // ping us, so something's broken if we don't receive a valid ping.
351 LOG(ERROR) << "Did not receive ping from zygote child";
352 NOTREACHED();
353 real_pid = -1;
355 my_sock.reset();
357 // Always send PID back to zygote.
358 Pickle pid_pickle;
359 pid_pickle.WriteInt(kZygoteCommandForkRealPID);
360 pid_pickle.WriteInt(real_pid);
361 if (!SendMessage(pid_pickle, NULL))
362 return base::kNullProcessHandle;
365 // Read the reply, which pickles the PID and an optional UMA enumeration.
366 static const unsigned kMaxReplyLength = 2048;
367 char buf[kMaxReplyLength];
368 const ssize_t len = ReadReply(buf, sizeof(buf));
370 Pickle reply_pickle(buf, len);
371 PickleIterator iter(reply_pickle);
372 if (len <= 0 || !reply_pickle.ReadInt(&iter, &pid))
373 return base::kNullProcessHandle;
375 // If there is a nonempty UMA name string, then there is a UMA
376 // enumeration to record.
377 std::string uma_name;
378 int uma_sample;
379 int uma_boundary_value;
380 if (reply_pickle.ReadString(&iter, &uma_name) &&
381 !uma_name.empty() &&
382 reply_pickle.ReadInt(&iter, &uma_sample) &&
383 reply_pickle.ReadInt(&iter, &uma_boundary_value)) {
384 // We cannot use the UMA_HISTOGRAM_ENUMERATION macro here,
385 // because that's only for when the name is the same every time.
386 // Here we're using whatever name we got from the other side.
387 // But since it's likely that the same one will be used repeatedly
388 // (even though it's not guaranteed), we cache it here.
389 static base::HistogramBase* uma_histogram;
390 if (!uma_histogram || uma_histogram->histogram_name() != uma_name) {
391 uma_histogram = base::LinearHistogram::FactoryGet(
392 uma_name, 1,
393 uma_boundary_value,
394 uma_boundary_value + 1,
395 base::HistogramBase::kUmaTargetedHistogramFlag);
397 uma_histogram->Add(uma_sample);
400 if (pid <= 0)
401 return base::kNullProcessHandle;
404 #if !defined(OS_OPENBSD)
405 // This is just a starting score for a renderer or extension (the
406 // only types of processes that will be started this way). It will
407 // get adjusted as time goes on. (This is the same value as
408 // chrome::kLowestRendererOomScore in chrome/chrome_constants.h, but
409 // that's not something we can include here.)
410 const int kLowestRendererOomScore = 300;
411 AdjustRendererOOMScore(pid, kLowestRendererOomScore);
412 #endif
414 ZygoteChildBorn(pid);
415 return pid;
418 #if !defined(OS_OPENBSD)
419 void ZygoteHostImpl::AdjustRendererOOMScore(base::ProcessHandle pid,
420 int score) {
421 // 1) You can't change the oom_score_adj of a non-dumpable process
422 // (EPERM) unless you're root. Because of this, we can't set the
423 // oom_adj from the browser process.
425 // 2) We can't set the oom_score_adj before entering the sandbox
426 // because the zygote is in the sandbox and the zygote is as
427 // critical as the browser process. Its oom_adj value shouldn't
428 // be changed.
430 // 3) A non-dumpable process can't even change its own oom_score_adj
431 // because it's root owned 0644. The sandboxed processes don't
432 // even have /proc, but one could imagine passing in a descriptor
433 // from outside.
435 // So, in the normal case, we use the SUID binary to change it for us.
436 // However, Fedora (and other SELinux systems) don't like us touching other
437 // process's oom_score_adj (or oom_adj) values
438 // (https://bugzilla.redhat.com/show_bug.cgi?id=581256).
440 // The offical way to get the SELinux mode is selinux_getenforcemode, but I
441 // don't want to add another library to the build as it's sure to cause
442 // problems with other, non-SELinux distros.
444 // So we just check for files in /selinux. This isn't foolproof, but it's not
445 // bad and it's easy.
447 static bool selinux;
448 static bool selinux_valid = false;
450 if (!selinux_valid) {
451 const base::FilePath kSelinuxPath("/selinux");
452 base::FileEnumerator en(kSelinuxPath, false, base::FileEnumerator::FILES);
453 bool has_selinux_files = !en.Next().empty();
455 selinux = access(kSelinuxPath.value().c_str(), X_OK) == 0 &&
456 has_selinux_files;
457 selinux_valid = true;
460 if (using_suid_sandbox_ && !selinux) {
461 #if defined(USE_TCMALLOC)
462 // If heap profiling is running, these processes are not exiting, at least
463 // on ChromeOS. The easiest thing to do is not launch them when profiling.
464 // TODO(stevenjb): Investigate further and fix.
465 if (IsHeapProfilerRunning())
466 return;
467 #endif
468 std::vector<std::string> adj_oom_score_cmdline;
469 adj_oom_score_cmdline.push_back(sandbox_binary_);
470 adj_oom_score_cmdline.push_back(sandbox::kAdjustOOMScoreSwitch);
471 adj_oom_score_cmdline.push_back(base::Int64ToString(pid));
472 adj_oom_score_cmdline.push_back(base::IntToString(score));
474 base::ProcessHandle sandbox_helper_process;
475 base::LaunchOptions options;
477 // sandbox_helper_process is a setuid binary.
478 options.allow_new_privs = true;
480 if (base::LaunchProcess(adj_oom_score_cmdline, options,
481 &sandbox_helper_process)) {
482 base::EnsureProcessGetsReaped(sandbox_helper_process);
484 } else if (!using_suid_sandbox_) {
485 if (!base::AdjustOOMScore(pid, score))
486 PLOG(ERROR) << "Failed to adjust OOM score of renderer with pid " << pid;
489 #endif
491 void ZygoteHostImpl::EnsureProcessTerminated(pid_t process) {
492 DCHECK(init_);
493 Pickle pickle;
495 pickle.WriteInt(kZygoteCommandReap);
496 pickle.WriteInt(process);
497 if (!SendMessage(pickle, NULL))
498 LOG(ERROR) << "Failed to send Reap message to zygote";
499 ZygoteChildDied(process);
502 base::TerminationStatus ZygoteHostImpl::GetTerminationStatus(
503 base::ProcessHandle handle,
504 bool known_dead,
505 int* exit_code) {
506 DCHECK(init_);
507 Pickle pickle;
508 pickle.WriteInt(kZygoteCommandGetTerminationStatus);
509 pickle.WriteBool(known_dead);
510 pickle.WriteInt(handle);
512 static const unsigned kMaxMessageLength = 128;
513 char buf[kMaxMessageLength];
514 ssize_t len;
516 base::AutoLock lock(control_lock_);
517 if (!SendMessage(pickle, NULL))
518 LOG(ERROR) << "Failed to send GetTerminationStatus message to zygote";
519 len = ReadReply(buf, sizeof(buf));
522 // Set this now to handle the error cases.
523 if (exit_code)
524 *exit_code = RESULT_CODE_NORMAL_EXIT;
525 int status = base::TERMINATION_STATUS_NORMAL_TERMINATION;
527 if (len == -1) {
528 LOG(WARNING) << "Error reading message from zygote: " << errno;
529 } else if (len == 0) {
530 LOG(WARNING) << "Socket closed prematurely.";
531 } else {
532 Pickle read_pickle(buf, len);
533 int tmp_status, tmp_exit_code;
534 PickleIterator iter(read_pickle);
535 if (!read_pickle.ReadInt(&iter, &tmp_status) ||
536 !read_pickle.ReadInt(&iter, &tmp_exit_code)) {
537 LOG(WARNING)
538 << "Error parsing GetTerminationStatus response from zygote.";
539 } else {
540 if (exit_code)
541 *exit_code = tmp_exit_code;
542 status = tmp_status;
546 if (status != base::TERMINATION_STATUS_STILL_RUNNING) {
547 ZygoteChildDied(handle);
549 return static_cast<base::TerminationStatus>(status);
552 pid_t ZygoteHostImpl::GetPid() const {
553 return pid_;
556 int ZygoteHostImpl::GetSandboxStatus() const {
557 if (have_read_sandbox_status_word_)
558 return sandbox_status_;
559 return 0;
562 } // namespace content