Save errno for logging before potentially overwriting it.
[chromium-blink-merge.git] / content / browser / browser_child_process_host_impl.cc
blob3748f6f2d8c7a5b4e4f631fe5bfcf43fec01720b
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"
8 #include "base/bind.h"
9 #include "base/command_line.h"
10 #include "base/files/file_path.h"
11 #include "base/lazy_instance.h"
12 #include "base/logging.h"
13 #include "base/metrics/histogram.h"
14 #include "base/path_service.h"
15 #include "base/process_util.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"
35 #endif
37 namespace content {
38 namespace {
40 static base::LazyInstance<BrowserChildProcessHostImpl::BrowserChildProcessList>
41 g_child_process_list = LAZY_INSTANCE_INITIALIZER;
43 base::LazyInstance<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) {
57 FOR_EACH_OBSERVER(BrowserChildProcessObserver, g_observers.Get(),
58 BrowserChildProcessCrashed(data));
61 } // namespace
63 BrowserChildProcessHost* BrowserChildProcessHost::Create(
64 int process_type,
65 BrowserChildProcessHostDelegate* delegate) {
66 return new BrowserChildProcessHostImpl(process_type, delegate);
69 #if defined(OS_MACOSX)
70 base::ProcessMetrics::PortProvider* BrowserChildProcessHost::GetPortProvider() {
71 return MachBroker::GetInstance();
73 #endif
75 // static
76 BrowserChildProcessHostImpl::BrowserChildProcessList*
77 BrowserChildProcessHostImpl::GetIterator() {
78 return g_child_process_list.Pointer();
81 // static
82 void BrowserChildProcessHostImpl::AddObserver(
83 BrowserChildProcessObserver* observer) {
84 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
85 g_observers.Get().AddObserver(observer);
88 // static
89 void BrowserChildProcessHostImpl::RemoveObserver(
90 BrowserChildProcessObserver* observer) {
91 // TODO(phajdan.jr): Check thread after fixing http://crbug.com/167126.
92 g_observers.Get().RemoveObserver(observer);
95 BrowserChildProcessHostImpl::BrowserChildProcessHostImpl(
96 int process_type,
97 BrowserChildProcessHostDelegate* delegate)
98 : data_(process_type),
99 delegate_(delegate) {
100 data_.id = ChildProcessHostImpl::GenerateChildProcessUniqueId();
102 child_process_host_.reset(ChildProcessHost::Create(this));
103 child_process_host_->AddFilter(new TraceMessageFilter);
104 child_process_host_->AddFilter(new ProfilerMessageFilter(process_type));
105 child_process_host_->AddFilter(new HistogramMessageFilter());
107 g_child_process_list.Get().push_back(this);
108 GetContentClient()->browser()->BrowserChildProcessHostCreated(this);
111 BrowserChildProcessHostImpl::~BrowserChildProcessHostImpl() {
112 g_child_process_list.Get().remove(this);
114 #if defined(OS_WIN)
115 DeleteProcessWaitableEvent(early_exit_watcher_.GetWatchedEvent());
116 #endif
119 // static
120 void BrowserChildProcessHostImpl::TerminateAll() {
121 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
122 // Make a copy since the BrowserChildProcessHost dtor mutates the original
123 // list.
124 BrowserChildProcessList copy = g_child_process_list.Get();
125 for (BrowserChildProcessList::iterator it = copy.begin();
126 it != copy.end(); ++it) {
127 delete (*it)->delegate(); // ~*HostDelegate deletes *HostImpl.
131 void BrowserChildProcessHostImpl::Launch(
132 #if defined(OS_WIN)
133 SandboxedProcessLauncherDelegate* delegate,
134 #elif defined(OS_POSIX)
135 bool use_zygote,
136 const base::EnvironmentVector& environ,
137 #endif
138 CommandLine* cmd_line) {
139 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
141 GetContentClient()->browser()->AppendExtraCommandLineSwitches(
142 cmd_line, data_.id);
144 const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();
145 static const char* kForwardSwitches[] = {
146 switches::kDisableLogging,
147 switches::kEnableDCHECK,
148 switches::kEnableLogging,
149 switches::kLoggingLevel,
150 switches::kV,
151 switches::kVModule,
152 #if defined(OS_POSIX)
153 switches::kChildCleanExit,
154 #endif
156 cmd_line->CopySwitchesFrom(browser_command_line, kForwardSwitches,
157 arraysize(kForwardSwitches));
159 child_process_.reset(new ChildProcessLauncher(
160 #if defined(OS_WIN)
161 delegate,
162 #elif defined(OS_POSIX)
163 use_zygote,
164 environ,
165 child_process_host_->TakeClientFileDescriptor(),
166 #endif
167 cmd_line,
168 data_.id,
169 this));
172 const ChildProcessData& BrowserChildProcessHostImpl::GetData() const {
173 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
174 return data_;
177 ChildProcessHost* BrowserChildProcessHostImpl::GetHost() const {
178 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
179 return child_process_host_.get();
182 base::ProcessHandle BrowserChildProcessHostImpl::GetHandle() const {
183 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
184 DCHECK(child_process_.get())
185 << "Requesting a child process handle before launching.";
186 DCHECK(child_process_->GetHandle())
187 << "Requesting a child process handle before launch has completed OK.";
188 return child_process_->GetHandle();
191 void BrowserChildProcessHostImpl::SetName(const string16& name) {
192 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
193 data_.name = name;
196 void BrowserChildProcessHostImpl::SetHandle(base::ProcessHandle handle) {
197 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
198 data_.handle = handle;
201 void BrowserChildProcessHostImpl::ForceShutdown() {
202 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
203 g_child_process_list.Get().remove(this);
204 child_process_host_->ForceShutdown();
207 void BrowserChildProcessHostImpl::SetBackgrounded(bool backgrounded) {
208 child_process_->SetProcessBackgrounded(backgrounded);
211 void BrowserChildProcessHostImpl::SetTerminateChildOnShutdown(
212 bool terminate_on_shutdown) {
213 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
214 child_process_->SetTerminateChildOnShutdown(terminate_on_shutdown);
217 void BrowserChildProcessHostImpl::NotifyProcessInstanceCreated(
218 const ChildProcessData& data) {
219 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
220 FOR_EACH_OBSERVER(BrowserChildProcessObserver, g_observers.Get(),
221 BrowserChildProcessInstanceCreated(data));
224 base::TerminationStatus BrowserChildProcessHostImpl::GetTerminationStatus(
225 int* exit_code) {
226 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
227 if (!child_process_) // If the delegate doesn't use Launch() helper.
228 return base::GetTerminationStatus(data_.handle, exit_code);
229 return child_process_->GetChildTerminationStatus(false /* known_dead */,
230 exit_code);
233 bool BrowserChildProcessHostImpl::OnMessageReceived(
234 const IPC::Message& message) {
235 return delegate_->OnMessageReceived(message);
238 void BrowserChildProcessHostImpl::OnChannelConnected(int32 peer_pid) {
239 #if defined(OS_WIN)
240 // From this point onward, the exit of the child process is detected by an
241 // error on the IPC channel.
242 DeleteProcessWaitableEvent(early_exit_watcher_.GetWatchedEvent());
243 early_exit_watcher_.StopWatching();
244 #endif
246 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
247 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
248 base::Bind(&NotifyProcessHostConnected, data_));
250 delegate_->OnChannelConnected(peer_pid);
253 void BrowserChildProcessHostImpl::OnChannelError() {
254 delegate_->OnChannelError();
257 bool BrowserChildProcessHostImpl::CanShutdown() {
258 return delegate_->CanShutdown();
261 void BrowserChildProcessHostImpl::OnChildDisconnected() {
262 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
263 DCHECK(data_.handle != base::kNullProcessHandle);
264 int exit_code;
265 base::TerminationStatus status = GetTerminationStatus(&exit_code);
266 switch (status) {
267 case base::TERMINATION_STATUS_PROCESS_CRASHED:
268 case base::TERMINATION_STATUS_ABNORMAL_TERMINATION: {
269 delegate_->OnProcessCrashed(exit_code);
270 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
271 base::Bind(&NotifyProcessCrashed, data_));
272 UMA_HISTOGRAM_ENUMERATION("ChildProcess.Crashed2",
273 data_.process_type,
274 PROCESS_TYPE_MAX);
275 break;
277 case base::TERMINATION_STATUS_PROCESS_WAS_KILLED: {
278 delegate_->OnProcessCrashed(exit_code);
279 // Report that this child process was killed.
280 UMA_HISTOGRAM_ENUMERATION("ChildProcess.Killed2",
281 data_.process_type,
282 PROCESS_TYPE_MAX);
283 break;
285 case base::TERMINATION_STATUS_STILL_RUNNING: {
286 UMA_HISTOGRAM_ENUMERATION("ChildProcess.DisconnectedAlive2",
287 data_.process_type,
288 PROCESS_TYPE_MAX);
290 default:
291 break;
293 UMA_HISTOGRAM_ENUMERATION("ChildProcess.Disconnected2",
294 data_.process_type,
295 PROCESS_TYPE_MAX);
296 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
297 base::Bind(&NotifyProcessHostDisconnected, data_));
298 delete delegate_; // Will delete us
301 bool BrowserChildProcessHostImpl::Send(IPC::Message* message) {
302 return child_process_host_->Send(message);
305 void BrowserChildProcessHostImpl::OnProcessLaunched() {
306 base::ProcessHandle handle = child_process_->GetHandle();
307 if (!handle) {
308 delete delegate_; // Will delete us
309 return;
312 #if defined(OS_WIN)
313 // Start a WaitableEventWatcher that will invoke OnProcessExitedEarly if the
314 // child process exits. This watcher is stopped once the IPC channel is
315 // connected and the exit of the child process is detecter by an error on the
316 // IPC channel thereafter.
317 DCHECK(!early_exit_watcher_.GetWatchedEvent());
318 early_exit_watcher_.StartWatching(
319 new base::WaitableEvent(handle),
320 base::Bind(&BrowserChildProcessHostImpl::OnProcessExitedEarly,
321 base::Unretained(this)));
322 #endif
324 data_.handle = handle;
325 delegate_->OnProcessLaunched();
328 #if defined(OS_WIN)
330 void BrowserChildProcessHostImpl::DeleteProcessWaitableEvent(
331 base::WaitableEvent* event) {
332 if (!event)
333 return;
335 // The WaitableEvent does not own the process handle so ensure it does not
336 // close it.
337 event->Release();
339 delete event;
342 void BrowserChildProcessHostImpl::OnProcessExitedEarly(
343 base::WaitableEvent* event) {
344 DeleteProcessWaitableEvent(event);
345 OnChildDisconnected();
348 #endif
350 } // namespace content