Cast: Stop logging kVideoFrameSentToEncoder and rename a couple events.
[chromium-blink-merge.git] / content / browser / zygote_host / zygote_host_impl_linux.cc
blob8a28f466cf1bbaf6da65e06b1539717a8c08eabf
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 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 CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();
115 if (browser_command_line.HasSwitch(switches::kZygoteCmdPrefix)) {
116 cmd_line.PrependWrapper(
117 browser_command_line.GetSwitchValueNative(switches::kZygoteCmdPrefix));
119 // Append any switches from the browser process that need to be forwarded on
120 // to the zygote/renderers.
121 // Should this list be obtained from browser_render_process_host.cc?
122 static const char* kForwardSwitches[] = {
123 switches::kAllowSandboxDebugging,
124 switches::kLoggingLevel,
125 switches::kEnableLogging, // Support, e.g., --enable-logging=stderr.
126 switches::kV,
127 switches::kVModule,
128 switches::kRegisterPepperPlugins,
129 switches::kDisableSeccompFilterSandbox,
131 // Zygote process needs to know what resources to have loaded when it
132 // becomes a renderer process.
133 switches::kForceDeviceScaleFactor,
135 switches::kNoSandbox,
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(
291 const std::vector<std::string>& argv,
292 const std::vector<FileDescriptorInfo>& mapping,
293 const std::string& process_type) {
294 DCHECK(init_);
295 Pickle pickle;
297 pickle.WriteInt(kZygoteCommandFork);
298 pickle.WriteString(process_type);
299 pickle.WriteInt(argv.size());
300 for (std::vector<std::string>::const_iterator
301 i = argv.begin(); i != argv.end(); ++i)
302 pickle.WriteString(*i);
304 pickle.WriteInt(mapping.size());
306 std::vector<int> fds;
307 // Scoped pointers cannot be stored in containers, so we have to use a
308 // linked_ptr.
309 std::vector<linked_ptr<base::ScopedFD> > autodelete_fds;
310 for (std::vector<FileDescriptorInfo>::const_iterator
311 i = mapping.begin(); i != mapping.end(); ++i) {
312 pickle.WriteUInt32(i->id);
313 fds.push_back(i->fd.fd);
314 if (i->fd.auto_close) {
315 // Auto-close means we need to close the FDs after they have been passed
316 // to the other process.
317 linked_ptr<base::ScopedFD> ptr(new base::ScopedFD(fds.back()));
318 autodelete_fds.push_back(ptr);
322 pid_t pid;
324 base::AutoLock lock(control_lock_);
325 if (!SendMessage(pickle, &fds))
326 return base::kNullProcessHandle;
328 // Read the reply, which pickles the PID and an optional UMA enumeration.
329 static const unsigned kMaxReplyLength = 2048;
330 char buf[kMaxReplyLength];
331 const ssize_t len = ReadReply(buf, sizeof(buf));
333 Pickle reply_pickle(buf, len);
334 PickleIterator iter(reply_pickle);
335 if (len <= 0 || !reply_pickle.ReadInt(&iter, &pid))
336 return base::kNullProcessHandle;
338 // If there is a nonempty UMA name string, then there is a UMA
339 // enumeration to record.
340 std::string uma_name;
341 int uma_sample;
342 int uma_boundary_value;
343 if (reply_pickle.ReadString(&iter, &uma_name) &&
344 !uma_name.empty() &&
345 reply_pickle.ReadInt(&iter, &uma_sample) &&
346 reply_pickle.ReadInt(&iter, &uma_boundary_value)) {
347 // We cannot use the UMA_HISTOGRAM_ENUMERATION macro here,
348 // because that's only for when the name is the same every time.
349 // Here we're using whatever name we got from the other side.
350 // But since it's likely that the same one will be used repeatedly
351 // (even though it's not guaranteed), we cache it here.
352 static base::HistogramBase* uma_histogram;
353 if (!uma_histogram || uma_histogram->histogram_name() != uma_name) {
354 uma_histogram = base::LinearHistogram::FactoryGet(
355 uma_name, 1,
356 uma_boundary_value,
357 uma_boundary_value + 1,
358 base::HistogramBase::kUmaTargetedHistogramFlag);
360 uma_histogram->Add(uma_sample);
363 if (pid <= 0)
364 return base::kNullProcessHandle;
367 #if !defined(OS_OPENBSD)
368 // This is just a starting score for a renderer or extension (the
369 // only types of processes that will be started this way). It will
370 // get adjusted as time goes on. (This is the same value as
371 // chrome::kLowestRendererOomScore in chrome/chrome_constants.h, but
372 // that's not something we can include here.)
373 const int kLowestRendererOomScore = 300;
374 AdjustRendererOOMScore(pid, kLowestRendererOomScore);
375 #endif
377 ZygoteChildBorn(pid);
378 return pid;
381 #if !defined(OS_OPENBSD)
382 void ZygoteHostImpl::AdjustRendererOOMScore(base::ProcessHandle pid,
383 int score) {
384 // 1) You can't change the oom_score_adj of a non-dumpable process
385 // (EPERM) unless you're root. Because of this, we can't set the
386 // oom_adj from the browser process.
388 // 2) We can't set the oom_score_adj before entering the sandbox
389 // because the zygote is in the sandbox and the zygote is as
390 // critical as the browser process. Its oom_adj value shouldn't
391 // be changed.
393 // 3) A non-dumpable process can't even change its own oom_score_adj
394 // because it's root owned 0644. The sandboxed processes don't
395 // even have /proc, but one could imagine passing in a descriptor
396 // from outside.
398 // So, in the normal case, we use the SUID binary to change it for us.
399 // However, Fedora (and other SELinux systems) don't like us touching other
400 // process's oom_score_adj (or oom_adj) values
401 // (https://bugzilla.redhat.com/show_bug.cgi?id=581256).
403 // The offical way to get the SELinux mode is selinux_getenforcemode, but I
404 // don't want to add another library to the build as it's sure to cause
405 // problems with other, non-SELinux distros.
407 // So we just check for files in /selinux. This isn't foolproof, but it's not
408 // bad and it's easy.
410 static bool selinux;
411 static bool selinux_valid = false;
413 if (!selinux_valid) {
414 const base::FilePath kSelinuxPath("/selinux");
415 base::FileEnumerator en(kSelinuxPath, false, base::FileEnumerator::FILES);
416 bool has_selinux_files = !en.Next().empty();
418 selinux = access(kSelinuxPath.value().c_str(), X_OK) == 0 &&
419 has_selinux_files;
420 selinux_valid = true;
423 if (using_suid_sandbox_ && !selinux) {
424 #if defined(USE_TCMALLOC)
425 // If heap profiling is running, these processes are not exiting, at least
426 // on ChromeOS. The easiest thing to do is not launch them when profiling.
427 // TODO(stevenjb): Investigate further and fix.
428 if (IsHeapProfilerRunning())
429 return;
430 #endif
431 std::vector<std::string> adj_oom_score_cmdline;
432 adj_oom_score_cmdline.push_back(sandbox_binary_);
433 adj_oom_score_cmdline.push_back(sandbox::kAdjustOOMScoreSwitch);
434 adj_oom_score_cmdline.push_back(base::Int64ToString(pid));
435 adj_oom_score_cmdline.push_back(base::IntToString(score));
437 base::ProcessHandle sandbox_helper_process;
438 base::LaunchOptions options;
440 // sandbox_helper_process is a setuid binary.
441 options.allow_new_privs = true;
443 if (base::LaunchProcess(adj_oom_score_cmdline, options,
444 &sandbox_helper_process)) {
445 base::EnsureProcessGetsReaped(sandbox_helper_process);
447 } else if (!using_suid_sandbox_) {
448 if (!base::AdjustOOMScore(pid, score))
449 PLOG(ERROR) << "Failed to adjust OOM score of renderer with pid " << pid;
452 #endif
454 void ZygoteHostImpl::EnsureProcessTerminated(pid_t process) {
455 DCHECK(init_);
456 Pickle pickle;
458 pickle.WriteInt(kZygoteCommandReap);
459 pickle.WriteInt(process);
460 if (!SendMessage(pickle, NULL))
461 LOG(ERROR) << "Failed to send Reap message to zygote";
462 ZygoteChildDied(process);
465 base::TerminationStatus ZygoteHostImpl::GetTerminationStatus(
466 base::ProcessHandle handle,
467 bool known_dead,
468 int* exit_code) {
469 DCHECK(init_);
470 Pickle pickle;
471 pickle.WriteInt(kZygoteCommandGetTerminationStatus);
472 pickle.WriteBool(known_dead);
473 pickle.WriteInt(handle);
475 static const unsigned kMaxMessageLength = 128;
476 char buf[kMaxMessageLength];
477 ssize_t len;
479 base::AutoLock lock(control_lock_);
480 if (!SendMessage(pickle, NULL))
481 LOG(ERROR) << "Failed to send GetTerminationStatus message to zygote";
482 len = ReadReply(buf, sizeof(buf));
485 // Set this now to handle the error cases.
486 if (exit_code)
487 *exit_code = RESULT_CODE_NORMAL_EXIT;
488 int status = base::TERMINATION_STATUS_NORMAL_TERMINATION;
490 if (len == -1) {
491 LOG(WARNING) << "Error reading message from zygote: " << errno;
492 } else if (len == 0) {
493 LOG(WARNING) << "Socket closed prematurely.";
494 } else {
495 Pickle read_pickle(buf, len);
496 int tmp_status, tmp_exit_code;
497 PickleIterator iter(read_pickle);
498 if (!read_pickle.ReadInt(&iter, &tmp_status) ||
499 !read_pickle.ReadInt(&iter, &tmp_exit_code)) {
500 LOG(WARNING)
501 << "Error parsing GetTerminationStatus response from zygote.";
502 } else {
503 if (exit_code)
504 *exit_code = tmp_exit_code;
505 status = tmp_status;
509 if (status != base::TERMINATION_STATUS_STILL_RUNNING) {
510 ZygoteChildDied(handle);
512 return static_cast<base::TerminationStatus>(status);
515 pid_t ZygoteHostImpl::GetPid() const {
516 return pid_;
519 pid_t ZygoteHostImpl::GetSandboxHelperPid() const {
520 return RenderSandboxHostLinux::GetInstance()->pid();
523 int ZygoteHostImpl::GetSandboxStatus() const {
524 if (have_read_sandbox_status_word_)
525 return sandbox_status_;
526 return 0;
529 } // namespace content