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/browser_child_process_host_impl.h"
7 #include "base/base_switches.h"
9 #include "base/command_line.h"
10 #include "base/debug/dump_without_crashing.h"
11 #include "base/files/file_path.h"
12 #include "base/lazy_instance.h"
13 #include "base/logging.h"
14 #include "base/metrics/histogram.h"
15 #include "base/profiler/scoped_tracker.h"
16 #include "base/stl_util.h"
17 #include "base/strings/string_util.h"
18 #include "base/synchronization/waitable_event.h"
19 #include "content/browser/histogram_message_filter.h"
20 #include "content/browser/loader/resource_message_filter.h"
21 #include "content/browser/profiler_message_filter.h"
22 #include "content/browser/tracing/trace_message_filter.h"
23 #include "content/common/child_process_host_impl.h"
24 #include "content/public/browser/browser_child_process_host_delegate.h"
25 #include "content/public/browser/browser_child_process_observer.h"
26 #include "content/public/browser/browser_thread.h"
27 #include "content/public/browser/child_process_data.h"
28 #include "content/public/browser/content_browser_client.h"
29 #include "content/public/common/content_switches.h"
30 #include "content/public/common/process_type.h"
31 #include "content/public/common/result_codes.h"
33 #if defined(OS_MACOSX)
34 #include "content/browser/mach_broker_mac.h"
40 static base::LazyInstance
<BrowserChildProcessHostImpl::BrowserChildProcessList
>
41 g_child_process_list
= LAZY_INSTANCE_INITIALIZER
;
43 base::LazyInstance
<base::ObserverList
<BrowserChildProcessObserver
>>
44 g_observers
= LAZY_INSTANCE_INITIALIZER
;
46 void NotifyProcessHostConnected(const ChildProcessData
& data
) {
47 FOR_EACH_OBSERVER(BrowserChildProcessObserver
, g_observers
.Get(),
48 BrowserChildProcessHostConnected(data
));
51 void NotifyProcessHostDisconnected(const ChildProcessData
& data
) {
52 FOR_EACH_OBSERVER(BrowserChildProcessObserver
, g_observers
.Get(),
53 BrowserChildProcessHostDisconnected(data
));
56 void NotifyProcessCrashed(const ChildProcessData
& data
, int exit_code
) {
57 FOR_EACH_OBSERVER(BrowserChildProcessObserver
, g_observers
.Get(),
58 BrowserChildProcessCrashed(data
, exit_code
));
63 BrowserChildProcessHost
* BrowserChildProcessHost::Create(
64 content::ProcessType process_type
,
65 BrowserChildProcessHostDelegate
* delegate
) {
66 return new BrowserChildProcessHostImpl(process_type
, delegate
);
69 BrowserChildProcessHost
* BrowserChildProcessHost::FromID(int child_process_id
) {
70 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
71 BrowserChildProcessHostImpl::BrowserChildProcessList
* process_list
=
72 g_child_process_list
.Pointer();
73 for (BrowserChildProcessHostImpl
* host
: *process_list
) {
74 if (host
->GetData().id
== child_process_id
)
80 #if defined(OS_MACOSX)
81 base::ProcessMetrics::PortProvider
* BrowserChildProcessHost::GetPortProvider() {
82 return MachBroker::GetInstance();
87 BrowserChildProcessHostImpl::BrowserChildProcessList
*
88 BrowserChildProcessHostImpl::GetIterator() {
89 return g_child_process_list
.Pointer();
93 void BrowserChildProcessHostImpl::AddObserver(
94 BrowserChildProcessObserver
* observer
) {
95 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
96 g_observers
.Get().AddObserver(observer
);
100 void BrowserChildProcessHostImpl::RemoveObserver(
101 BrowserChildProcessObserver
* observer
) {
102 // TODO(phajdan.jr): Check thread after fixing http://crbug.com/167126.
103 g_observers
.Get().RemoveObserver(observer
);
106 BrowserChildProcessHostImpl::BrowserChildProcessHostImpl(
107 content::ProcessType process_type
,
108 BrowserChildProcessHostDelegate
* delegate
)
109 : data_(process_type
),
111 power_monitor_message_broadcaster_(this) {
112 data_
.id
= ChildProcessHostImpl::GenerateChildProcessUniqueId();
114 child_process_host_
.reset(ChildProcessHost::Create(this));
115 AddFilter(new TraceMessageFilter(data_
.id
));
116 AddFilter(new ProfilerMessageFilter(process_type
));
117 AddFilter(new HistogramMessageFilter
);
119 g_child_process_list
.Get().push_back(this);
120 GetContentClient()->browser()->BrowserChildProcessHostCreated(this);
122 power_monitor_message_broadcaster_
.Init();
125 BrowserChildProcessHostImpl::~BrowserChildProcessHostImpl() {
126 g_child_process_list
.Get().remove(this);
130 void BrowserChildProcessHostImpl::TerminateAll() {
131 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
132 // Make a copy since the BrowserChildProcessHost dtor mutates the original
134 BrowserChildProcessList copy
= g_child_process_list
.Get();
135 for (BrowserChildProcessList::iterator it
= copy
.begin();
136 it
!= copy
.end(); ++it
) {
137 delete (*it
)->delegate(); // ~*HostDelegate deletes *HostImpl.
141 void BrowserChildProcessHostImpl::Launch(
142 SandboxedProcessLauncherDelegate
* delegate
,
143 base::CommandLine
* cmd_line
,
144 bool terminate_on_shutdown
) {
145 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
147 GetContentClient()->browser()->AppendExtraCommandLineSwitches(
150 const base::CommandLine
& browser_command_line
=
151 *base::CommandLine::ForCurrentProcess();
152 static const char* kForwardSwitches
[] = {
153 switches::kDisableLogging
,
154 switches::kEnableLogging
,
155 switches::kIPCConnectionTimeout
,
156 switches::kLoggingLevel
,
157 switches::kTraceToConsole
,
161 cmd_line
->CopySwitchesFrom(browser_command_line
, kForwardSwitches
,
162 arraysize(kForwardSwitches
));
164 child_process_
.reset(new ChildProcessLauncher(
169 terminate_on_shutdown
));
172 const ChildProcessData
& BrowserChildProcessHostImpl::GetData() const {
173 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
177 ChildProcessHost
* BrowserChildProcessHostImpl::GetHost() const {
178 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
179 return child_process_host_
.get();
182 const base::Process
& BrowserChildProcessHostImpl::GetProcess() const {
183 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
184 DCHECK(child_process_
.get())
185 << "Requesting a child process handle before launching.";
186 DCHECK(child_process_
->GetProcess().IsValid())
187 << "Requesting a child process handle before launch has completed OK.";
188 return child_process_
->GetProcess();
191 void BrowserChildProcessHostImpl::SetName(const base::string16
& name
) {
192 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
196 void BrowserChildProcessHostImpl::SetHandle(base::ProcessHandle handle
) {
197 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
198 data_
.handle
= handle
;
201 ServiceRegistry
* BrowserChildProcessHostImpl::GetServiceRegistry() {
202 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
203 return delegate_
->GetServiceRegistry();
206 void BrowserChildProcessHostImpl::ForceShutdown() {
207 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
208 g_child_process_list
.Get().remove(this);
209 child_process_host_
->ForceShutdown();
212 void BrowserChildProcessHostImpl::SetBackgrounded(bool backgrounded
) {
213 child_process_
->SetProcessBackgrounded(backgrounded
);
216 void BrowserChildProcessHostImpl::AddFilter(BrowserMessageFilter
* filter
) {
217 child_process_host_
->AddFilter(filter
->GetFilter());
220 void BrowserChildProcessHostImpl::NotifyProcessInstanceCreated(
221 const ChildProcessData
& data
) {
222 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
223 FOR_EACH_OBSERVER(BrowserChildProcessObserver
, g_observers
.Get(),
224 BrowserChildProcessInstanceCreated(data
));
227 void BrowserChildProcessHostImpl::HistogramBadMessageTerminated(
229 UMA_HISTOGRAM_ENUMERATION("ChildProcess.BadMessgeTerminated", process_type
,
233 base::TerminationStatus
BrowserChildProcessHostImpl::GetTerminationStatus(
234 bool known_dead
, int* exit_code
) {
235 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
236 if (!child_process_
) // If the delegate doesn't use Launch() helper.
237 return base::GetTerminationStatus(data_
.handle
, exit_code
);
238 return child_process_
->GetChildTerminationStatus(known_dead
,
242 bool BrowserChildProcessHostImpl::OnMessageReceived(
243 const IPC::Message
& message
) {
244 return delegate_
->OnMessageReceived(message
);
247 void BrowserChildProcessHostImpl::OnChannelConnected(int32 peer_pid
) {
249 // From this point onward, the exit of the child process is detected by an
250 // error on the IPC channel.
251 early_exit_watcher_
.StopWatching();
254 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
255 BrowserThread::PostTask(BrowserThread::UI
, FROM_HERE
,
256 base::Bind(&NotifyProcessHostConnected
, data_
));
258 delegate_
->OnChannelConnected(peer_pid
);
261 void BrowserChildProcessHostImpl::OnChannelError() {
262 delegate_
->OnChannelError();
265 void BrowserChildProcessHostImpl::OnBadMessageReceived(
266 const IPC::Message
& message
) {
267 HistogramBadMessageTerminated(data_
.process_type
);
268 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
269 switches::kDisableKillAfterBadIPC
)) {
272 LOG(ERROR
) << "Terminating child process for bad IPC message of type "
275 // Create a memory dump. This will contain enough stack frames to work out
276 // what the bad message was.
277 base::debug::DumpWithoutCrashing();
279 child_process_
->GetProcess().Terminate(RESULT_CODE_KILLED_BAD_MESSAGE
, false);
282 bool BrowserChildProcessHostImpl::CanShutdown() {
283 return delegate_
->CanShutdown();
286 void BrowserChildProcessHostImpl::OnChildDisconnected() {
287 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
289 // OnChildDisconnected may be called without OnChannelConnected, so stop the
290 // early exit watcher so GetTerminationStatus can close the process handle.
291 early_exit_watcher_
.StopWatching();
293 if (child_process_
.get() || data_
.handle
) {
295 base::TerminationStatus status
= GetTerminationStatus(
296 true /* known_dead */, &exit_code
);
298 case base::TERMINATION_STATUS_PROCESS_CRASHED
:
299 case base::TERMINATION_STATUS_ABNORMAL_TERMINATION
: {
300 delegate_
->OnProcessCrashed(exit_code
);
301 BrowserThread::PostTask(
302 BrowserThread::UI
, FROM_HERE
,
303 base::Bind(&NotifyProcessCrashed
, data_
, exit_code
));
304 UMA_HISTOGRAM_ENUMERATION("ChildProcess.Crashed2",
309 #if defined(OS_CHROMEOS)
310 case base::TERMINATION_STATUS_PROCESS_WAS_KILLED_BY_OOM
:
312 case base::TERMINATION_STATUS_PROCESS_WAS_KILLED
: {
313 delegate_
->OnProcessCrashed(exit_code
);
314 // Report that this child process was killed.
315 UMA_HISTOGRAM_ENUMERATION("ChildProcess.Killed2",
320 case base::TERMINATION_STATUS_STILL_RUNNING
: {
321 UMA_HISTOGRAM_ENUMERATION("ChildProcess.DisconnectedAlive2",
328 UMA_HISTOGRAM_ENUMERATION("ChildProcess.Disconnected2",
331 #if defined(OS_CHROMEOS)
332 if (status
== base::TERMINATION_STATUS_PROCESS_WAS_KILLED_BY_OOM
) {
333 UMA_HISTOGRAM_ENUMERATION("ChildProcess.Killed2.OOM",
339 BrowserThread::PostTask(BrowserThread::UI
, FROM_HERE
,
340 base::Bind(&NotifyProcessHostDisconnected
, data_
));
341 delete delegate_
; // Will delete us
344 bool BrowserChildProcessHostImpl::Send(IPC::Message
* message
) {
345 return child_process_host_
->Send(message
);
348 void BrowserChildProcessHostImpl::OnProcessLaunchFailed() {
349 delegate_
->OnProcessLaunchFailed();
350 delete delegate_
; // Will delete us
353 void BrowserChildProcessHostImpl::OnProcessLaunched() {
354 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
356 tracked_objects::ScopedTracker
tracking_profile(
357 FROM_HERE_WITH_EXPLICIT_FUNCTION(
358 "465841 BrowserChildProcessHostImpl::OnProcessLaunched"));
359 const base::Process
& process
= child_process_
->GetProcess();
360 DCHECK(process
.IsValid());
363 // Start a WaitableEventWatcher that will invoke OnProcessExitedEarly if the
364 // child process exits. This watcher is stopped once the IPC channel is
365 // connected and the exit of the child process is detecter by an error on the
366 // IPC channel thereafter.
367 DCHECK(!early_exit_watcher_
.GetWatchedObject());
368 early_exit_watcher_
.StartWatching(process
.Handle(), this);
371 // TODO(rvargas) crbug.com/417532: Don't store a handle.
372 data_
.handle
= process
.Handle();
373 delegate_
->OnProcessLaunched();
378 void BrowserChildProcessHostImpl::OnObjectSignaled(HANDLE object
) {
379 OnChildDisconnected();
384 } // namespace content