1 // Copyright 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/child_process_launcher.h"
8 #include "base/command_line.h"
9 #include "base/files/file_util.h"
10 #include "base/i18n/icu_util.h"
11 #include "base/logging.h"
12 #include "base/memory/scoped_ptr.h"
13 #include "base/metrics/histogram.h"
14 #include "base/process/process.h"
15 #include "base/profiler/scoped_tracker.h"
16 #include "base/synchronization/lock.h"
17 #include "base/threading/thread.h"
18 #include "content/public/browser/content_browser_client.h"
19 #include "content/public/common/content_descriptors.h"
20 #include "content/public/common/content_switches.h"
21 #include "content/public/common/result_codes.h"
22 #include "content/public/common/sandboxed_process_launcher_delegate.h"
25 #include "base/files/file_path.h"
26 #include "content/common/sandbox_win.h"
27 #include "content/public/common/sandbox_init.h"
28 #elif defined(OS_MACOSX)
29 #include "content/browser/bootstrap_sandbox_mac.h"
30 #include "content/browser/browser_io_surface_manager_mac.h"
31 #include "content/browser/mach_broker_mac.h"
32 #include "sandbox/mac/bootstrap_sandbox.h"
33 #elif defined(OS_ANDROID)
34 #include "base/android/jni_android.h"
35 #include "content/browser/android/child_process_launcher_android.h"
36 #elif defined(OS_POSIX)
37 #include "base/memory/shared_memory.h"
38 #include "base/memory/singleton.h"
39 #include "content/browser/renderer_host/render_sandbox_host_linux.h"
40 #include "content/browser/zygote_host/zygote_host_impl_linux.h"
41 #include "content/common/child_process_sandbox_support_impl_linux.h"
45 #include "base/posix/global_descriptors.h"
46 #include "content/browser/file_descriptor_info_impl.h"
47 #include "gin/v8_initializer.h"
54 typedef base::Callback
<void(bool,
55 #if defined(OS_ANDROID)
58 base::Process
)> NotifyCallback
;
60 void RecordHistogramsOnLauncherThread(base::TimeDelta launch_time
) {
61 DCHECK_CURRENTLY_ON(BrowserThread::PROCESS_LAUNCHER
);
62 // Log the launch time, separating out the first one (which will likely be
63 // slower due to the rest of the browser initializing at the same time).
64 static bool done_first_launch
= false;
65 if (done_first_launch
) {
66 UMA_HISTOGRAM_TIMES("MPArch.ChildProcessLaunchSubsequent", launch_time
);
68 UMA_HISTOGRAM_TIMES("MPArch.ChildProcessLaunchFirst", launch_time
);
69 done_first_launch
= true;
73 #if defined(OS_ANDROID)
74 // TODO(sievers): Remove this by defining better what happens on what
75 // thread in the corresponding Java code.
76 void OnChildProcessStartedAndroid(const NotifyCallback
& callback
,
77 BrowserThread::ID client_thread_id
,
78 const base::TimeTicks begin_launch_time
,
80 base::ProcessHandle handle
) {
81 // This can be called on the launcher thread or UI thread.
82 base::TimeDelta launch_time
= base::TimeTicks::Now() - begin_launch_time
;
83 BrowserThread::PostTask(
84 BrowserThread::PROCESS_LAUNCHER
, FROM_HERE
,
85 base::Bind(&RecordHistogramsOnLauncherThread
, launch_time
));
87 base::Closure
callback_on_client_thread(
88 base::Bind(callback
, false, base::Passed(&ipcfd
),
89 base::Passed(base::Process(handle
))));
90 if (BrowserThread::CurrentlyOn(client_thread_id
)) {
91 callback_on_client_thread
.Run();
93 BrowserThread::PostTask(
94 client_thread_id
, FROM_HERE
, callback_on_client_thread
);
99 void LaunchOnLauncherThread(const NotifyCallback
& callback
,
100 BrowserThread::ID client_thread_id
,
101 int child_process_id
,
102 SandboxedProcessLauncherDelegate
* delegate
,
103 #if defined(OS_ANDROID)
104 base::ScopedFD ipcfd
,
106 base::CommandLine
* cmd_line
) {
107 DCHECK_CURRENTLY_ON(BrowserThread::PROCESS_LAUNCHER
);
108 scoped_ptr
<SandboxedProcessLauncherDelegate
> delegate_deleter(delegate
);
110 bool use_zygote
= false;
111 bool launch_elevated
= delegate
->ShouldLaunchElevated();
112 #elif defined(OS_MACOSX)
113 bool use_zygote
= false;
114 base::EnvironmentMap env
= delegate
->GetEnvironment();
115 base::ScopedFD ipcfd
= delegate
->TakeIpcFd();
116 #elif defined(OS_POSIX) && !defined(OS_ANDROID)
117 bool use_zygote
= delegate
->ShouldUseZygote();
118 base::EnvironmentMap env
= delegate
->GetEnvironment();
119 base::ScopedFD ipcfd
= delegate
->TakeIpcFd();
121 scoped_ptr
<base::CommandLine
> cmd_line_deleter(cmd_line
);
122 base::TimeTicks begin_launch_time
= base::TimeTicks::Now();
124 base::Process process
;
126 if (launch_elevated
) {
127 base::LaunchOptions options
;
128 options
.start_hidden
= true;
129 process
= base::LaunchElevatedProcess(*cmd_line
, options
);
131 process
= StartSandboxedProcess(delegate
, cmd_line
);
133 #elif defined(OS_POSIX)
134 std::string process_type
=
135 cmd_line
->GetSwitchValueASCII(switches::kProcessType
);
136 scoped_ptr
<FileDescriptorInfo
> files_to_register(
137 FileDescriptorInfoImpl::Create());
139 #if defined(OS_ANDROID)
140 files_to_register
->Share(kPrimaryIPCChannel
, ipcfd
.get());
142 files_to_register
->Transfer(kPrimaryIPCChannel
, ipcfd
.Pass());
146 #if defined(OS_POSIX) && !defined(OS_MACOSX)
147 std::map
<int, base::MemoryMappedFile::Region
> regions
;
148 GetContentClient()->browser()->GetAdditionalMappedFilesForChildProcess(
149 *cmd_line
, child_process_id
, files_to_register
.get());
150 #if defined(V8_USE_EXTERNAL_STARTUP_DATA)
151 base::PlatformFile natives_pf
=
152 gin::V8Initializer::GetOpenNativesFileForChildProcesses(
153 ®ions
[kV8NativesDataDescriptor
]);
154 DCHECK_GE(natives_pf
, 0);
155 files_to_register
->Share(kV8NativesDataDescriptor
, natives_pf
);
157 base::MemoryMappedFile::Region snapshot_region
;
158 base::PlatformFile snapshot_pf
=
159 gin::V8Initializer::GetOpenSnapshotFileForChildProcesses(
161 // Failure to load the V8 snapshot is not necessarily an error. V8 can start
162 // up (slower) without the snapshot.
163 if (snapshot_pf
!= -1) {
164 files_to_register
->Share(kV8SnapshotDataDescriptor
, snapshot_pf
);
165 regions
.insert(std::make_pair(kV8SnapshotDataDescriptor
, snapshot_region
));
168 if (process_type
!= switches::kZygoteProcess
) {
169 cmd_line
->AppendSwitch(::switches::kV8NativesPassedByFD
);
170 if (snapshot_pf
!= -1) {
171 cmd_line
->AppendSwitch(::switches::kV8SnapshotPassedByFD
);
174 #endif // defined(V8_USE_EXTERNAL_STARTUP_DATA)
175 #endif // defined(OS_POSIX) && !defined(OS_MACOSX)
177 #if defined(OS_ANDROID)
178 files_to_register
->Share(
179 kAndroidICUDataDescriptor
,
180 base::i18n::GetIcuDataFileHandle(®ions
[kAndroidICUDataDescriptor
]));
182 // Android WebView runs in single process, ensure that we never get here
183 // when running in single process mode.
184 CHECK(!cmd_line
->HasSwitch(switches::kSingleProcess
));
187 cmd_line
->argv(), child_process_id
, files_to_register
.Pass(), regions
,
188 base::Bind(&OnChildProcessStartedAndroid
, callback
, client_thread_id
,
189 begin_launch_time
, base::Passed(&ipcfd
)));
191 #elif defined(OS_POSIX)
192 // We need to close the client end of the IPC channel to reliably detect
193 // child termination.
195 #if !defined(OS_MACOSX)
197 base::ProcessHandle handle
= ZygoteHostImpl::GetInstance()->ForkRequest(
198 cmd_line
->argv(), files_to_register
.Pass(), process_type
);
199 process
= base::Process(handle
);
201 // Fall through to the normal posix case below when we're not zygoting.
202 #endif // !defined(OS_MACOSX)
204 // Convert FD mapping to FileHandleMappingVector
205 base::FileHandleMappingVector fds_to_map
=
206 files_to_register
->GetMappingWithIDAdjustment(
207 base::GlobalDescriptors::kBaseDescriptor
);
209 #if !defined(OS_MACOSX)
210 if (process_type
== switches::kRendererProcess
) {
211 const int sandbox_fd
=
212 RenderSandboxHostLinux::GetInstance()->GetRendererSocket();
213 fds_to_map
.push_back(std::make_pair(
217 #endif // defined(OS_MACOSX)
219 // Actually launch the app.
220 base::LaunchOptions options
;
221 options
.environ
= env
;
222 options
.fds_to_remap
= &fds_to_map
;
224 #if defined(OS_MACOSX)
225 // Hold the MachBroker lock for the duration of LaunchProcess. The child
226 // will send its task port to the parent almost immediately after startup.
227 // The Mach message will be delivered to the parent, but updating the
228 // record of the launch will wait until after the placeholder PID is
229 // inserted below. This ensures that while the child process may send its
230 // port to the parent prior to the parent leaving LaunchProcess, the
231 // order in which the record in MachBroker is updated is correct.
232 MachBroker
* broker
= MachBroker::GetInstance();
233 broker
->GetLock().Acquire();
235 // Make sure the MachBroker is running, and inform it to expect a
236 // check-in from the new process.
237 broker
->EnsureRunning();
239 // Make sure the IOSurfaceManager service is running.
240 BrowserIOSurfaceManager::GetInstance()->EnsureRunning();
242 const int bootstrap_sandbox_policy
= delegate
->GetSandboxType();
243 if (ShouldEnableBootstrapSandbox() &&
244 bootstrap_sandbox_policy
!= SANDBOX_TYPE_INVALID
) {
245 options
.replacement_bootstrap_name
=
246 GetBootstrapSandbox()->server_bootstrap_name();
247 GetBootstrapSandbox()->PrepareToForkWithPolicy(
248 bootstrap_sandbox_policy
);
250 #endif // defined(OS_MACOSX)
252 process
= base::LaunchProcess(*cmd_line
, options
);
254 #if defined(OS_MACOSX)
255 if (ShouldEnableBootstrapSandbox() &&
256 bootstrap_sandbox_policy
!= SANDBOX_TYPE_INVALID
) {
257 GetBootstrapSandbox()->FinishedFork(process
.Handle());
260 if (process
.IsValid())
261 broker
->AddPlaceholderForPid(process
.Pid(), child_process_id
);
263 // After updating the broker, release the lock and let the child's
264 // messasge be processed on the broker's thread.
265 broker
->GetLock().Release();
266 #endif // defined(OS_MACOSX)
268 #endif // else defined(OS_POSIX)
269 #if !defined(OS_ANDROID)
270 if (process
.IsValid()) {
271 RecordHistogramsOnLauncherThread(base::TimeTicks::Now() -
274 BrowserThread::PostTask(client_thread_id
, FROM_HERE
,
277 base::Passed(&process
)));
278 #endif // !defined(OS_ANDROID)
281 void TerminateOnLauncherThread(bool zygote
, base::Process process
) {
282 DCHECK_CURRENTLY_ON(BrowserThread::PROCESS_LAUNCHER
);
283 #if defined(OS_ANDROID)
284 VLOG(1) << "ChromeProcess: Stopping process with handle "
286 StopChildProcess(process
.Handle());
288 // Client has gone away, so just kill the process. Using exit code 0
289 // means that UMA won't treat this as a crash.
290 process
.Terminate(RESULT_CODE_NORMAL_EXIT
, false);
291 // On POSIX, we must additionally reap the child.
292 #if defined(OS_POSIX)
293 #if !defined(OS_MACOSX)
295 // If the renderer was created via a zygote, we have to proxy the reaping
296 // through the zygote process.
297 ZygoteHostImpl::GetInstance()->EnsureProcessTerminated(process
.Handle());
300 base::EnsureProcessTerminated(process
.Pass());
302 #endif // defined(OS_ANDROID)
305 void SetProcessBackgroundedOnLauncherThread(base::Process process
,
307 DCHECK_CURRENTLY_ON(BrowserThread::PROCESS_LAUNCHER
);
308 #if defined(OS_MACOSX)
309 MachBroker
* broker
= MachBroker::GetInstance();
310 mach_port_t task_port
= broker
->TaskForPid(process
.Pid());
311 if (task_port
!= TASK_NULL
) {
312 process
.SetProcessBackgrounded(task_port
, background
);
315 process
.SetProcessBackgrounded(background
);
316 #endif // defined(OS_MACOSX)
317 #if defined(OS_ANDROID)
318 SetChildProcessInForeground(process
.Handle(), !background
);
322 } // anonymous namespace
324 ChildProcessLauncher::ChildProcessLauncher(
325 SandboxedProcessLauncherDelegate
* delegate
,
326 base::CommandLine
* cmd_line
,
327 int child_process_id
,
329 bool terminate_on_shutdown
)
331 termination_status_(base::TERMINATION_STATUS_NORMAL_TERMINATION
),
332 exit_code_(RESULT_CODE_NORMAL_EXIT
),
335 #if defined(ADDRESS_SANITIZER) || defined(LEAK_SANITIZER) || \
336 defined(MEMORY_SANITIZER) || defined(THREAD_SANITIZER) || \
337 defined(UNDEFINED_SANITIZER)
338 terminate_child_on_shutdown_(false),
340 terminate_child_on_shutdown_(terminate_on_shutdown
),
342 weak_factory_(this) {
343 DCHECK(CalledOnValidThread());
344 CHECK(BrowserThread::GetCurrentThreadIdentifier(&client_thread_id_
));
345 Launch(delegate
, cmd_line
, child_process_id
);
348 ChildProcessLauncher::~ChildProcessLauncher() {
349 DCHECK(CalledOnValidThread());
350 if (process_
.IsValid() && terminate_child_on_shutdown_
) {
351 // On Posix, EnsureProcessTerminated can lead to 2 seconds of sleep! So
352 // don't this on the UI/IO threads.
353 BrowserThread::PostTask(BrowserThread::PROCESS_LAUNCHER
, FROM_HERE
,
354 base::Bind(&TerminateOnLauncherThread
, zygote_
,
355 base::Passed(&process_
)));
359 void ChildProcessLauncher::Launch(
360 SandboxedProcessLauncherDelegate
* delegate
,
361 base::CommandLine
* cmd_line
,
362 int child_process_id
) {
363 DCHECK(CalledOnValidThread());
365 #if defined(OS_ANDROID)
366 // Android only supports renderer, sandboxed utility and gpu.
367 std::string process_type
=
368 cmd_line
->GetSwitchValueASCII(switches::kProcessType
);
369 CHECK(process_type
== switches::kGpuProcess
||
370 process_type
== switches::kRendererProcess
||
371 process_type
== switches::kUtilityProcess
)
372 << "Unsupported process type: " << process_type
;
374 // Non-sandboxed utility or renderer process are currently not supported.
375 DCHECK(process_type
== switches::kGpuProcess
||
376 !cmd_line
->HasSwitch(switches::kNoSandbox
));
378 // We need to close the client end of the IPC channel to reliably detect
379 // child termination. We will close this fd after we create the child
380 // process which is asynchronous on Android.
381 base::ScopedFD
ipcfd(delegate
->TakeIpcFd().release());
383 NotifyCallback
reply_callback(base::Bind(&ChildProcessLauncher::DidLaunch
,
384 weak_factory_
.GetWeakPtr(),
385 terminate_child_on_shutdown_
));
386 BrowserThread::PostTask(
387 BrowserThread::PROCESS_LAUNCHER
, FROM_HERE
,
388 base::Bind(&LaunchOnLauncherThread
, reply_callback
, client_thread_id_
,
389 child_process_id
, delegate
,
390 #if defined(OS_ANDROID)
391 base::Passed(&ipcfd
),
396 void ChildProcessLauncher::UpdateTerminationStatus(bool known_dead
) {
397 DCHECK(CalledOnValidThread());
398 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
400 termination_status_
= ZygoteHostImpl::GetInstance()->
401 GetTerminationStatus(process_
.Handle(), known_dead
, &exit_code_
);
402 } else if (known_dead
) {
403 termination_status_
=
404 base::GetKnownDeadTerminationStatus(process_
.Handle(), &exit_code_
);
406 #elif defined(OS_MACOSX)
408 termination_status_
=
409 base::GetKnownDeadTerminationStatus(process_
.Handle(), &exit_code_
);
411 #elif defined(OS_ANDROID)
412 if (IsChildProcessOomProtected(process_
.Handle())) {
413 termination_status_
= base::TERMINATION_STATUS_OOM_PROTECTED
;
418 termination_status_
=
419 base::GetTerminationStatus(process_
.Handle(), &exit_code_
);
423 void ChildProcessLauncher::SetProcessBackgrounded(bool background
) {
424 DCHECK(CalledOnValidThread());
425 base::Process to_pass
= process_
.Duplicate();
426 BrowserThread::PostTask(BrowserThread::PROCESS_LAUNCHER
, FROM_HERE
,
427 base::Bind(&SetProcessBackgroundedOnLauncherThread
,
428 base::Passed(&to_pass
), background
));
431 void ChildProcessLauncher::DidLaunch(
432 base::WeakPtr
<ChildProcessLauncher
> instance
,
433 bool terminate_on_shutdown
,
435 #if defined(OS_ANDROID)
436 base::ScopedFD ipcfd
,
438 base::Process process
) {
439 if (!process
.IsValid())
440 LOG(ERROR
) << "Failed to launch child process";
442 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
444 tracked_objects::ScopedTracker
tracking_profile1(
445 FROM_HERE_WITH_EXPLICIT_FUNCTION(
446 "465841 ChildProcessLauncher::Context::Notify::Start"));
448 if (instance
.get()) {
449 instance
->Notify(zygote
,
450 #if defined(OS_ANDROID)
455 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
457 tracked_objects::ScopedTracker
tracking_profile4(
458 FROM_HERE_WITH_EXPLICIT_FUNCTION(
459 "465841 ChildProcessLauncher::Context::Notify::ProcessTerminate"));
460 if (process
.IsValid() && terminate_on_shutdown
) {
461 // On Posix, EnsureProcessTerminated can lead to 2 seconds of sleep! So
462 // don't this on the UI/IO threads.
463 BrowserThread::PostTask(BrowserThread::PROCESS_LAUNCHER
, FROM_HERE
,
464 base::Bind(&TerminateOnLauncherThread
, zygote
,
465 base::Passed(&process
)));
470 void ChildProcessLauncher::Notify(
472 #if defined(OS_ANDROID)
473 base::ScopedFD ipcfd
,
475 base::Process process
) {
476 DCHECK(CalledOnValidThread());
478 process_
= process
.Pass();
480 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
483 if (process_
.IsValid()) {
484 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
486 tracked_objects::ScopedTracker
tracking_profile2(
487 FROM_HERE_WITH_EXPLICIT_FUNCTION(
488 "465841 ChildProcessLauncher::Context::Notify::ProcessLaunched"));
489 client_
->OnProcessLaunched();
491 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
493 tracked_objects::ScopedTracker
tracking_profile3(
494 FROM_HERE_WITH_EXPLICIT_FUNCTION(
495 "465841 ChildProcessLauncher::Context::Notify::ProcessFailed"));
496 client_
->OnProcessLaunchFailed();
500 bool ChildProcessLauncher::IsStarting() {
501 // TODO(crbug.com/469248): This fails in some tests.
502 // DCHECK(CalledOnValidThread());
506 const base::Process
& ChildProcessLauncher::GetProcess() const {
507 // TODO(crbug.com/469248): This fails in some tests.
508 // DCHECK(CalledOnValidThread());
512 base::TerminationStatus
ChildProcessLauncher::GetChildTerminationStatus(
515 DCHECK(CalledOnValidThread());
516 if (!process_
.IsValid()) {
517 // Process is already gone, so return the cached termination status.
519 *exit_code
= exit_code_
;
520 return termination_status_
;
523 UpdateTerminationStatus(known_dead
);
525 *exit_code
= exit_code_
;
527 // POSIX: If the process crashed, then the kernel closed the socket
528 // for it and so the child has already died by the time we get
529 // here. Since GetTerminationStatus called waitpid with WNOHANG,
530 // it'll reap the process. However, if GetTerminationStatus didn't
531 // reap the child (because it was still running), we'll need to
532 // Terminate via ProcessWatcher. So we can't close the handle here.
533 if (termination_status_
!= base::TERMINATION_STATUS_STILL_RUNNING
)
536 return termination_status_
;
539 ChildProcessLauncher::Client
* ChildProcessLauncher::ReplaceClientForTest(
541 Client
* ret
= client_
;
546 } // namespace content