Remove PlatformFile from profile_browsertest
[chromium-blink-merge.git] / content / browser / zygote_host / zygote_host_impl_linux.cc
blobaaf4d3b686e916a53f217bad0a33bc043a191f23
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>
8 #include <sys/stat.h>
9 #include <sys/types.h>
10 #include <unistd.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"
45 #endif
47 namespace content {
49 // static
50 ZygoteHost* ZygoteHost::GetInstance() {
51 return ZygoteHostImpl::GetInstance();
54 ZygoteHostImpl::ZygoteHostImpl()
55 : control_fd_(-1),
56 control_lock_(),
57 pid_(-1),
58 init_(false),
59 using_suid_sandbox_(false),
60 sandbox_binary_(),
61 have_read_sandbox_status_word_(false),
62 sandbox_status_(0),
63 child_tracking_lock_(),
64 list_of_running_zygote_children_(),
65 should_teardown_after_last_child_exits_(false) {}
67 ZygoteHostImpl::~ZygoteHostImpl() { TearDown(); }
69 // static
70 ZygoteHostImpl* ZygoteHostImpl::GetInstance() {
71 return Singleton<ZygoteHostImpl>::get();
74 void ZygoteHostImpl::Init(const std::string& sandbox_cmd) {
75 DCHECK(!init_);
76 init_ = true;
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);
84 int fds[2];
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);
90 #else
91 CHECK(socketpair(PF_UNIX, SOCK_SEQPACKET, 0, fds) == 0);
92 #endif
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.
108 switches::kV,
109 switches::kVModule,
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_) {
131 struct stat st;
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 &&
138 (st.st_uid == 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();
146 } else {
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()));
159 int dummy_fd = -1;
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),
181 &fds_vec);
182 CHECK(len == kExpectedLength) << "Incorrect zygote magic length";
183 CHECK(0 == strcmp(buf, kZygoteHelloMessage))
184 << "Incorrect zygote hello";
186 std::string inode_output;
187 ino_t inode = 0;
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)) {
191 close(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_) {
205 // Reap the sandbox.
206 base::EnsureProcessGetsReaped(process);
208 } else {
209 // Not using the SUID sandbox.
210 pid_ = process;
213 close(fds[1]);
214 control_fd_ = fds[0];
216 Pickle pickle;
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();
230 if (do_teardown) {
231 TearDown();
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
240 // to the Zygote.
241 if (IGNORE_EINTR(close(control_fd_))) {
242 PLOG(ERROR) << "Could not close Zygote control channel.";
243 NOTREACHED();
245 control_fd_ = -1;
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();
265 if (do_teardown) {
266 TearDown();
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_)) {
295 return -1;
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) {
307 DCHECK(init_);
308 Pickle pickle;
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
321 // linked_ptr.
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);
335 pid_t pid;
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;
354 int uma_sample;
355 int uma_boundary_value;
356 if (reply_pickle.ReadString(&iter, &uma_name) &&
357 !uma_name.empty() &&
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(
368 uma_name, 1,
369 uma_boundary_value,
370 uma_boundary_value + 1,
371 base::HistogramBase::kUmaTargetedHistogramFlag);
373 uma_histogram->Add(uma_sample);
376 if (pid <= 0)
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);
388 #endif
390 ZygoteChildBorn(pid);
391 return pid;
394 #if !defined(OS_OPENBSD)
395 void ZygoteHostImpl::AdjustRendererOOMScore(base::ProcessHandle pid,
396 int score) {
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
404 // be changed.
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
409 // from outside.
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.
423 static bool selinux;
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 &&
432 has_selinux_files;
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())
442 return;
443 #endif
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;
460 #endif
462 void ZygoteHostImpl::EnsureProcessTerminated(pid_t process) {
463 DCHECK(init_);
464 Pickle pickle;
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,
475 bool known_dead,
476 int* exit_code) {
477 DCHECK(init_);
478 Pickle pickle;
479 pickle.WriteInt(kZygoteCommandGetTerminationStatus);
480 pickle.WriteBool(known_dead);
481 pickle.WriteInt(handle);
483 static const unsigned kMaxMessageLength = 128;
484 char buf[kMaxMessageLength];
485 ssize_t len;
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.
494 if (exit_code)
495 *exit_code = RESULT_CODE_NORMAL_EXIT;
496 int status = base::TERMINATION_STATUS_NORMAL_TERMINATION;
498 if (len == -1) {
499 LOG(WARNING) << "Error reading message from zygote: " << errno;
500 } else if (len == 0) {
501 LOG(WARNING) << "Socket closed prematurely.";
502 } else {
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)) {
508 LOG(WARNING)
509 << "Error parsing GetTerminationStatus response from zygote.";
510 } else {
511 if (exit_code)
512 *exit_code = tmp_exit_code;
513 status = tmp_status;
517 if (status != base::TERMINATION_STATUS_STILL_RUNNING) {
518 ZygoteChildDied(handle);
520 return static_cast<base::TerminationStatus>(status);
523 pid_t ZygoteHostImpl::GetPid() const {
524 return pid_;
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_;
534 return 0;
537 } // namespace content