Battery Status API: add UMA logging for Linux.
[chromium-blink-merge.git] / content / browser / zygote_host / zygote_host_impl_linux.cc
blob2c3467e0ecb281828b79eddb31b4902280c75105
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/file_util.h"
17 #include "base/files/file_enumerator.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::kLoggingLevel,
126 switches::kEnableLogging, // Support, e.g., --enable-logging=stderr.
127 switches::kV,
128 switches::kVModule,
129 switches::kRegisterPepperPlugins,
130 switches::kDisableSeccompFilterSandbox,
132 // Zygote process needs to know what resources to have loaded when it
133 // becomes a renderer process.
134 switches::kForceDeviceScaleFactor,
136 switches::kNoSandbox,
138 cmd_line.CopySwitchesFrom(browser_command_line, kForwardSwitches,
139 arraysize(kForwardSwitches));
141 GetContentClient()->browser()->AppendExtraCommandLineSwitches(&cmd_line, -1);
143 sandbox_binary_ = sandbox_cmd.c_str();
145 // A non empty sandbox_cmd means we want a SUID sandbox.
146 using_suid_sandbox_ = !sandbox_cmd.empty();
148 // Start up the sandbox host process and get the file descriptor for the
149 // renderers to talk to it.
150 const int sfd = RenderSandboxHostLinux::GetInstance()->GetRendererSocket();
151 fds_to_map.push_back(std::make_pair(sfd, GetSandboxFD()));
153 base::ScopedFD dummy_fd;
154 if (using_suid_sandbox_) {
155 scoped_ptr<sandbox::SetuidSandboxClient>
156 sandbox_client(sandbox::SetuidSandboxClient::Create());
157 sandbox_client->PrependWrapper(&cmd_line);
158 sandbox_client->SetupLaunchOptions(&options, &fds_to_map, &dummy_fd);
159 sandbox_client->SetupLaunchEnvironment();
162 base::ProcessHandle process = -1;
163 options.fds_to_remap = &fds_to_map;
164 base::LaunchProcess(cmd_line.argv(), options, &process);
165 CHECK(process != -1) << "Failed to launch zygote process";
166 dummy_fd.reset();
168 if (using_suid_sandbox_) {
169 // The SUID sandbox will execute the zygote in a new PID namespace, and
170 // the main zygote process will then fork from there. Watch now our
171 // elaborate dance to find and validate the zygote's PID.
173 // First we receive a message from the zygote boot process.
174 base::ProcessId boot_pid;
175 CHECK(ReceiveFixedMessage(
176 fds[0], kZygoteBootMessage, sizeof(kZygoteBootMessage), &boot_pid));
178 // Within the PID namespace, the zygote boot process thinks it's PID 1,
179 // but its real PID can never be 1. This gives us a reliable test that
180 // the kernel is translating the sender's PID to our namespace.
181 CHECK_GT(boot_pid, 1)
182 << "Received invalid process ID for zygote; kernel might be too old? "
183 "See crbug.com/357670 or try using --"
184 << switches::kDisableSetuidSandbox << " to workaround.";
186 // Now receive the message that the zygote's ready to go, along with the
187 // main zygote process's ID.
188 CHECK(ReceiveFixedMessage(
189 fds[0], kZygoteHelloMessage, sizeof(kZygoteHelloMessage), &pid_));
190 CHECK_GT(pid_, 1);
192 if (process != pid_) {
193 // Reap the sandbox.
194 base::EnsureProcessGetsReaped(process);
196 } else {
197 // Not using the SUID sandbox.
198 pid_ = process;
201 close(fds[1]);
202 control_fd_ = fds[0];
204 Pickle pickle;
205 pickle.WriteInt(kZygoteCommandGetSandboxStatus);
206 if (!SendMessage(pickle, NULL))
207 LOG(FATAL) << "Cannot communicate with zygote";
208 // We don't wait for the reply. We'll read it in ReadReply.
211 void ZygoteHostImpl::TearDownAfterLastChild() {
212 bool do_teardown = false;
214 base::AutoLock lock(child_tracking_lock_);
215 should_teardown_after_last_child_exits_ = true;
216 do_teardown = list_of_running_zygote_children_.empty();
218 if (do_teardown) {
219 TearDown();
223 // Note: this is also called from the destructor.
224 void ZygoteHostImpl::TearDown() {
225 base::AutoLock lock(control_lock_);
226 if (control_fd_ > -1) {
227 // Closing the IPC channel will act as a notification to exit
228 // to the Zygote.
229 if (IGNORE_EINTR(close(control_fd_))) {
230 PLOG(ERROR) << "Could not close Zygote control channel.";
231 NOTREACHED();
233 control_fd_ = -1;
237 void ZygoteHostImpl::ZygoteChildBorn(pid_t process) {
238 base::AutoLock lock(child_tracking_lock_);
239 bool new_element_inserted =
240 list_of_running_zygote_children_.insert(process).second;
241 DCHECK(new_element_inserted);
244 void ZygoteHostImpl::ZygoteChildDied(pid_t process) {
245 bool do_teardown = false;
247 base::AutoLock lock(child_tracking_lock_);
248 size_t num_erased = list_of_running_zygote_children_.erase(process);
249 DCHECK_EQ(1U, num_erased);
250 do_teardown = should_teardown_after_last_child_exits_ &&
251 list_of_running_zygote_children_.empty();
253 if (do_teardown) {
254 TearDown();
258 bool ZygoteHostImpl::SendMessage(const Pickle& data,
259 const std::vector<int>* fds) {
260 DCHECK_NE(-1, control_fd_);
261 CHECK(data.size() <= kZygoteMaxMessageLength)
262 << "Trying to send too-large message to zygote (sending " << data.size()
263 << " bytes, max is " << kZygoteMaxMessageLength << ")";
264 CHECK(!fds || fds->size() <= UnixDomainSocket::kMaxFileDescriptors)
265 << "Trying to send message with too many file descriptors to zygote "
266 << "(sending " << fds->size() << ", max is "
267 << UnixDomainSocket::kMaxFileDescriptors << ")";
269 return UnixDomainSocket::SendMsg(control_fd_,
270 data.data(), data.size(),
271 fds ? *fds : std::vector<int>());
274 ssize_t ZygoteHostImpl::ReadReply(void* buf, size_t buf_len) {
275 DCHECK_NE(-1, control_fd_);
276 // At startup we send a kZygoteCommandGetSandboxStatus request to the zygote,
277 // but don't wait for the reply. Thus, the first time that we read from the
278 // zygote, we get the reply to that request.
279 if (!have_read_sandbox_status_word_) {
280 if (HANDLE_EINTR(read(control_fd_, &sandbox_status_,
281 sizeof(sandbox_status_))) !=
282 sizeof(sandbox_status_)) {
283 return -1;
285 have_read_sandbox_status_word_ = true;
288 return HANDLE_EINTR(read(control_fd_, buf, buf_len));
291 pid_t ZygoteHostImpl::ForkRequest(
292 const std::vector<std::string>& argv,
293 const std::vector<FileDescriptorInfo>& mapping,
294 const std::string& process_type) {
295 DCHECK(init_);
296 Pickle pickle;
298 int raw_socks[2];
299 PCHECK(0 == socketpair(AF_UNIX, SOCK_SEQPACKET, 0, raw_socks));
300 base::ScopedFD my_sock(raw_socks[0]);
301 base::ScopedFD peer_sock(raw_socks[1]);
302 CHECK(UnixDomainSocket::EnableReceiveProcessId(my_sock.get()));
304 pickle.WriteInt(kZygoteCommandFork);
305 pickle.WriteString(process_type);
306 pickle.WriteInt(argv.size());
307 for (std::vector<std::string>::const_iterator
308 i = argv.begin(); i != argv.end(); ++i)
309 pickle.WriteString(*i);
311 // Fork requests contain one file descriptor for the PID oracle, and one
312 // more for each file descriptor mapping for the child process.
313 const size_t num_fds_to_send = 1 + mapping.size();
314 pickle.WriteInt(num_fds_to_send);
316 std::vector<int> fds;
317 ScopedVector<base::ScopedFD> autoclose_fds;
319 // First FD to send is peer_sock.
320 fds.push_back(peer_sock.get());
321 autoclose_fds.push_back(new base::ScopedFD(peer_sock.Pass()));
323 // The rest come from mapping.
324 for (std::vector<FileDescriptorInfo>::const_iterator
325 i = mapping.begin(); i != mapping.end(); ++i) {
326 pickle.WriteUInt32(i->id);
327 fds.push_back(i->fd.fd);
328 if (i->fd.auto_close) {
329 // Auto-close means we need to close the FDs after they have been passed
330 // to the other process.
331 autoclose_fds.push_back(new base::ScopedFD(i->fd.fd));
335 // Sanity check that we've populated |fds| correctly.
336 DCHECK_EQ(num_fds_to_send, fds.size());
338 pid_t pid;
340 base::AutoLock lock(control_lock_);
341 if (!SendMessage(pickle, &fds))
342 return base::kNullProcessHandle;
343 autoclose_fds.clear();
346 char buf[sizeof(kZygoteChildPingMessage) + 1];
347 ScopedVector<base::ScopedFD> recv_fds;
348 base::ProcessId real_pid;
350 ssize_t n = UnixDomainSocket::RecvMsgWithPid(
351 my_sock.get(), buf, sizeof(buf), &recv_fds, &real_pid);
352 if (n != sizeof(kZygoteChildPingMessage) ||
353 0 != memcmp(buf,
354 kZygoteChildPingMessage,
355 sizeof(kZygoteChildPingMessage))) {
356 // Zygote children should still be trustworthy when they're supposed to
357 // ping us, so something's broken if we don't receive a valid ping.
358 LOG(ERROR) << "Did not receive ping from zygote child";
359 NOTREACHED();
360 real_pid = -1;
362 my_sock.reset();
364 // Always send PID back to zygote.
365 Pickle pid_pickle;
366 pid_pickle.WriteInt(kZygoteCommandForkRealPID);
367 pid_pickle.WriteInt(real_pid);
368 if (!SendMessage(pid_pickle, NULL))
369 return base::kNullProcessHandle;
372 // Read the reply, which pickles the PID and an optional UMA enumeration.
373 static const unsigned kMaxReplyLength = 2048;
374 char buf[kMaxReplyLength];
375 const ssize_t len = ReadReply(buf, sizeof(buf));
377 Pickle reply_pickle(buf, len);
378 PickleIterator iter(reply_pickle);
379 if (len <= 0 || !reply_pickle.ReadInt(&iter, &pid))
380 return base::kNullProcessHandle;
382 // If there is a nonempty UMA name string, then there is a UMA
383 // enumeration to record.
384 std::string uma_name;
385 int uma_sample;
386 int uma_boundary_value;
387 if (reply_pickle.ReadString(&iter, &uma_name) &&
388 !uma_name.empty() &&
389 reply_pickle.ReadInt(&iter, &uma_sample) &&
390 reply_pickle.ReadInt(&iter, &uma_boundary_value)) {
391 // We cannot use the UMA_HISTOGRAM_ENUMERATION macro here,
392 // because that's only for when the name is the same every time.
393 // Here we're using whatever name we got from the other side.
394 // But since it's likely that the same one will be used repeatedly
395 // (even though it's not guaranteed), we cache it here.
396 static base::HistogramBase* uma_histogram;
397 if (!uma_histogram || uma_histogram->histogram_name() != uma_name) {
398 uma_histogram = base::LinearHistogram::FactoryGet(
399 uma_name, 1,
400 uma_boundary_value,
401 uma_boundary_value + 1,
402 base::HistogramBase::kUmaTargetedHistogramFlag);
404 uma_histogram->Add(uma_sample);
407 if (pid <= 0)
408 return base::kNullProcessHandle;
411 #if !defined(OS_OPENBSD)
412 // This is just a starting score for a renderer or extension (the
413 // only types of processes that will be started this way). It will
414 // get adjusted as time goes on. (This is the same value as
415 // chrome::kLowestRendererOomScore in chrome/chrome_constants.h, but
416 // that's not something we can include here.)
417 const int kLowestRendererOomScore = 300;
418 AdjustRendererOOMScore(pid, kLowestRendererOomScore);
419 #endif
421 ZygoteChildBorn(pid);
422 return pid;
425 #if !defined(OS_OPENBSD)
426 void ZygoteHostImpl::AdjustRendererOOMScore(base::ProcessHandle pid,
427 int score) {
428 // 1) You can't change the oom_score_adj of a non-dumpable process
429 // (EPERM) unless you're root. Because of this, we can't set the
430 // oom_adj from the browser process.
432 // 2) We can't set the oom_score_adj before entering the sandbox
433 // because the zygote is in the sandbox and the zygote is as
434 // critical as the browser process. Its oom_adj value shouldn't
435 // be changed.
437 // 3) A non-dumpable process can't even change its own oom_score_adj
438 // because it's root owned 0644. The sandboxed processes don't
439 // even have /proc, but one could imagine passing in a descriptor
440 // from outside.
442 // So, in the normal case, we use the SUID binary to change it for us.
443 // However, Fedora (and other SELinux systems) don't like us touching other
444 // process's oom_score_adj (or oom_adj) values
445 // (https://bugzilla.redhat.com/show_bug.cgi?id=581256).
447 // The offical way to get the SELinux mode is selinux_getenforcemode, but I
448 // don't want to add another library to the build as it's sure to cause
449 // problems with other, non-SELinux distros.
451 // So we just check for files in /selinux. This isn't foolproof, but it's not
452 // bad and it's easy.
454 static bool selinux;
455 static bool selinux_valid = false;
457 if (!selinux_valid) {
458 const base::FilePath kSelinuxPath("/selinux");
459 base::FileEnumerator en(kSelinuxPath, false, base::FileEnumerator::FILES);
460 bool has_selinux_files = !en.Next().empty();
462 selinux = access(kSelinuxPath.value().c_str(), X_OK) == 0 &&
463 has_selinux_files;
464 selinux_valid = true;
467 if (using_suid_sandbox_ && !selinux) {
468 #if defined(USE_TCMALLOC)
469 // If heap profiling is running, these processes are not exiting, at least
470 // on ChromeOS. The easiest thing to do is not launch them when profiling.
471 // TODO(stevenjb): Investigate further and fix.
472 if (IsHeapProfilerRunning())
473 return;
474 #endif
475 std::vector<std::string> adj_oom_score_cmdline;
476 adj_oom_score_cmdline.push_back(sandbox_binary_);
477 adj_oom_score_cmdline.push_back(sandbox::kAdjustOOMScoreSwitch);
478 adj_oom_score_cmdline.push_back(base::Int64ToString(pid));
479 adj_oom_score_cmdline.push_back(base::IntToString(score));
481 base::ProcessHandle sandbox_helper_process;
482 base::LaunchOptions options;
484 // sandbox_helper_process is a setuid binary.
485 options.allow_new_privs = true;
487 if (base::LaunchProcess(adj_oom_score_cmdline, options,
488 &sandbox_helper_process)) {
489 base::EnsureProcessGetsReaped(sandbox_helper_process);
491 } else if (!using_suid_sandbox_) {
492 if (!base::AdjustOOMScore(pid, score))
493 PLOG(ERROR) << "Failed to adjust OOM score of renderer with pid " << pid;
496 #endif
498 void ZygoteHostImpl::EnsureProcessTerminated(pid_t process) {
499 DCHECK(init_);
500 Pickle pickle;
502 pickle.WriteInt(kZygoteCommandReap);
503 pickle.WriteInt(process);
504 if (!SendMessage(pickle, NULL))
505 LOG(ERROR) << "Failed to send Reap message to zygote";
506 ZygoteChildDied(process);
509 base::TerminationStatus ZygoteHostImpl::GetTerminationStatus(
510 base::ProcessHandle handle,
511 bool known_dead,
512 int* exit_code) {
513 DCHECK(init_);
514 Pickle pickle;
515 pickle.WriteInt(kZygoteCommandGetTerminationStatus);
516 pickle.WriteBool(known_dead);
517 pickle.WriteInt(handle);
519 static const unsigned kMaxMessageLength = 128;
520 char buf[kMaxMessageLength];
521 ssize_t len;
523 base::AutoLock lock(control_lock_);
524 if (!SendMessage(pickle, NULL))
525 LOG(ERROR) << "Failed to send GetTerminationStatus message to zygote";
526 len = ReadReply(buf, sizeof(buf));
529 // Set this now to handle the error cases.
530 if (exit_code)
531 *exit_code = RESULT_CODE_NORMAL_EXIT;
532 int status = base::TERMINATION_STATUS_NORMAL_TERMINATION;
534 if (len == -1) {
535 LOG(WARNING) << "Error reading message from zygote: " << errno;
536 } else if (len == 0) {
537 LOG(WARNING) << "Socket closed prematurely.";
538 } else {
539 Pickle read_pickle(buf, len);
540 int tmp_status, tmp_exit_code;
541 PickleIterator iter(read_pickle);
542 if (!read_pickle.ReadInt(&iter, &tmp_status) ||
543 !read_pickle.ReadInt(&iter, &tmp_exit_code)) {
544 LOG(WARNING)
545 << "Error parsing GetTerminationStatus response from zygote.";
546 } else {
547 if (exit_code)
548 *exit_code = tmp_exit_code;
549 status = tmp_status;
553 if (status != base::TERMINATION_STATUS_STILL_RUNNING) {
554 ZygoteChildDied(handle);
556 return static_cast<base::TerminationStatus>(status);
559 pid_t ZygoteHostImpl::GetPid() const {
560 return pid_;
563 int ZygoteHostImpl::GetSandboxStatus() const {
564 if (have_read_sandbox_status_word_)
565 return sandbox_status_;
566 return 0;
569 } // namespace content