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/child/child_thread.h"
11 #include "base/allocator/allocator_extension.h"
12 #include "base/base_switches.h"
13 #include "base/basictypes.h"
14 #include "base/command_line.h"
15 #include "base/debug/leak_annotations.h"
16 #include "base/lazy_instance.h"
17 #include "base/logging.h"
18 #include "base/message_loop/message_loop.h"
19 #include "base/process/kill.h"
20 #include "base/process/process_handle.h"
21 #include "base/strings/string_util.h"
22 #include "base/synchronization/condition_variable.h"
23 #include "base/synchronization/lock.h"
24 #include "base/threading/thread_local.h"
25 #include "base/tracked_objects.h"
26 #include "components/tracing/child_trace_message_filter.h"
27 #include "content/child/child_histogram_message_filter.h"
28 #include "content/child/child_process.h"
29 #include "content/child/child_resource_message_filter.h"
30 #include "content/child/fileapi/file_system_dispatcher.h"
31 #include "content/child/power_monitor_broadcast_source.h"
32 #include "content/child/quota_dispatcher.h"
33 #include "content/child/quota_message_filter.h"
34 #include "content/child/resource_dispatcher.h"
35 #include "content/child/service_worker/service_worker_dispatcher.h"
36 #include "content/child/service_worker/service_worker_message_filter.h"
37 #include "content/child/socket_stream_dispatcher.h"
38 #include "content/child/thread_safe_sender.h"
39 #include "content/child/websocket_dispatcher.h"
40 #include "content/common/child_process_messages.h"
41 #include "content/public/common/content_switches.h"
42 #include "ipc/ipc_logging.h"
43 #include "ipc/ipc_switches.h"
44 #include "ipc/ipc_sync_channel.h"
45 #include "ipc/ipc_sync_message_filter.h"
48 #include "content/common/handle_enumerator_win.h"
51 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
52 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
55 using tracked_objects::ThreadData;
60 // How long to wait for a connection to the browser process before giving up.
61 const int kConnectionTimeoutS = 15;
63 base::LazyInstance<base::ThreadLocalPointer<ChildThread> > g_lazy_tls =
64 LAZY_INSTANCE_INITIALIZER;
66 // This isn't needed on Windows because there the sandbox's job object
67 // terminates child processes automatically. For unsandboxed processes (i.e.
68 // plugins), PluginThread has EnsureTerminateMessageFilter.
71 // A thread delegate that waits for |duration| and then signals the process
73 class WaitAndExitDelegate : public base::PlatformThread::Delegate {
75 explicit WaitAndExitDelegate(base::TimeDelta duration)
76 : duration_(duration) {}
77 virtual ~WaitAndExitDelegate() OVERRIDE {}
79 virtual void ThreadMain() OVERRIDE {
80 base::PlatformThread::Sleep(duration_);
81 // This used to be implemented with alarm(2). Make sure to not break
82 // anything that requires the process being signaled.
83 CHECK_EQ(0, raise(SIGALRM));
85 base::PlatformThread::Sleep((base::TimeDelta::FromSeconds(10)));
86 // If something erroneously blocked SIGALRM, this will trigger.
92 const base::TimeDelta duration_;
93 DISALLOW_COPY_AND_ASSIGN(WaitAndExitDelegate);
96 // This is similar to using alarm(2), except it will spawn a thread
97 // which will sleep for |duration| before raising SIGALRM.
98 bool CreateAlarmThread(base::TimeDelta duration) {
99 scoped_ptr<WaitAndExitDelegate> delegate(new WaitAndExitDelegate(duration));
101 const bool thread_created = base::PlatformThread::CreateNonJoinable(
102 0 /* stack_size */, delegate.get());
106 // A non joinable thread has been created. The thread will either terminate
107 // the process or will be terminated by the process. Therefore, keep the
108 // delegate object alive for the lifetime of the process.
109 WaitAndExitDelegate* leaking_delegate = delegate.release();
110 ANNOTATE_LEAKING_OBJECT_PTR(leaking_delegate);
111 ignore_result(leaking_delegate);
115 class SuicideOnChannelErrorFilter : public IPC::ChannelProxy::MessageFilter {
117 // IPC::ChannelProxy::MessageFilter
118 virtual void OnChannelError() OVERRIDE {
119 // For renderer/worker processes:
120 // On POSIX, at least, one can install an unload handler which loops
121 // forever and leave behind a renderer process which eats 100% CPU forever.
123 // This is because the terminate signals (ViewMsg_ShouldClose and the error
124 // from the IPC channel) are routed to the main message loop but never
125 // processed (because that message loop is stuck in V8).
127 // One could make the browser SIGKILL the renderers, but that leaves open a
128 // large window where a browser failure (or a user, manually terminating
129 // the browser because "it's stuck") will leave behind a process eating all
132 // So, we install a filter on the channel so that we can process this event
133 // here and kill the process.
134 if (CommandLine::ForCurrentProcess()->
135 HasSwitch(switches::kChildCleanExit)) {
136 // If clean exit is requested, we want to kill this process after giving
137 // it 60 seconds to run exit handlers. Exit handlers may including ones
138 // that write profile data to disk (which happens under profile collection
140 CHECK(CreateAlarmThread(base::TimeDelta::FromSeconds(60)));
141 #if defined(LEAK_SANITIZER)
142 // Invoke LeakSanitizer early to avoid detecting shutdown-only leaks. If
143 // leaks are found, the process will exit here.
144 __lsan_do_leak_check();
152 virtual ~SuicideOnChannelErrorFilter() {}
157 #if defined(OS_ANDROID)
158 ChildThread* g_child_thread = NULL;
160 // A lock protects g_child_thread.
161 base::LazyInstance<base::Lock> g_lazy_child_thread_lock =
162 LAZY_INSTANCE_INITIALIZER;
164 // base::ConditionVariable has an explicit constructor that takes
165 // a base::Lock pointer as parameter. The base::DefaultLazyInstanceTraits
166 // doesn't handle the case. Thus, we need our own class here.
167 struct CondVarLazyInstanceTraits {
168 static const bool kRegisterOnExit = true;
169 static const bool kAllowedToAccessOnNonjoinableThread ALLOW_UNUSED = false;
170 static base::ConditionVariable* New(void* instance) {
171 return new (instance) base::ConditionVariable(
172 g_lazy_child_thread_lock.Pointer());
174 static void Delete(base::ConditionVariable* instance) {
175 instance->~ConditionVariable();
179 // A condition variable that synchronize threads initializing and waiting
180 // for g_child_thread.
181 base::LazyInstance<base::ConditionVariable, CondVarLazyInstanceTraits>
182 g_lazy_child_thread_cv = LAZY_INSTANCE_INITIALIZER;
184 void QuitMainThreadMessageLoop() {
185 base::MessageLoop::current()->Quit();
192 ChildThread::ChildThread()
193 : channel_connected_factory_(this),
194 in_browser_process_(false) {
195 channel_name_ = CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
196 switches::kProcessChannelID);
200 ChildThread::ChildThread(const std::string& channel_name)
201 : channel_name_(channel_name),
202 channel_connected_factory_(this),
203 in_browser_process_(true) {
207 void ChildThread::Init() {
208 g_lazy_tls.Pointer()->Set(this);
209 on_channel_error_called_ = false;
210 message_loop_ = base::MessageLoop::current();
211 #ifdef IPC_MESSAGE_LOG_ENABLED
212 // We must make sure to instantiate the IPC Logger *before* we create the
213 // channel, otherwise we can get a callback on the IO thread which creates
214 // the logger, and the logger does not like being created on the IO thread.
215 IPC::Logging::GetInstance();
218 new IPC::SyncChannel(channel_name_,
219 IPC::Channel::MODE_CLIENT,
221 ChildProcess::current()->io_message_loop_proxy(),
223 ChildProcess::current()->GetShutDownEvent()));
224 #ifdef IPC_MESSAGE_LOG_ENABLED
225 if (!in_browser_process_)
226 IPC::Logging::GetInstance()->SetIPCSender(this);
229 sync_message_filter_ =
230 new IPC::SyncMessageFilter(ChildProcess::current()->GetShutDownEvent());
231 thread_safe_sender_ = new ThreadSafeSender(
232 base::MessageLoopProxy::current().get(), sync_message_filter_.get());
234 resource_dispatcher_.reset(new ResourceDispatcher(this));
235 socket_stream_dispatcher_.reset(new SocketStreamDispatcher());
236 websocket_dispatcher_.reset(new WebSocketDispatcher);
237 file_system_dispatcher_.reset(new FileSystemDispatcher());
239 histogram_message_filter_ = new ChildHistogramMessageFilter();
240 resource_message_filter_ =
241 new ChildResourceMessageFilter(resource_dispatcher());
243 service_worker_message_filter_ =
244 new ServiceWorkerMessageFilter(thread_safe_sender_.get());
245 service_worker_dispatcher_.reset(
246 new ServiceWorkerDispatcher(thread_safe_sender_.get()));
248 quota_message_filter_ =
249 new QuotaMessageFilter(thread_safe_sender_.get());
250 quota_dispatcher_.reset(new QuotaDispatcher(thread_safe_sender_.get(),
251 quota_message_filter_.get()));
253 channel_->AddFilter(histogram_message_filter_.get());
254 channel_->AddFilter(sync_message_filter_.get());
255 channel_->AddFilter(new tracing::ChildTraceMessageFilter(
256 ChildProcess::current()->io_message_loop_proxy()));
257 channel_->AddFilter(resource_message_filter_.get());
258 channel_->AddFilter(quota_message_filter_->GetFilter());
259 channel_->AddFilter(service_worker_message_filter_->GetFilter());
261 // In single process mode we may already have a power monitor
262 if (!base::PowerMonitor::Get()) {
263 scoped_ptr<PowerMonitorBroadcastSource> power_monitor_source(
264 new PowerMonitorBroadcastSource());
265 channel_->AddFilter(power_monitor_source->GetMessageFilter());
267 power_monitor_.reset(new base::PowerMonitor(
268 power_monitor_source.PassAs<base::PowerMonitorSource>()));
271 #if defined(OS_POSIX)
272 // Check that --process-type is specified so we don't do this in unit tests
273 // and single-process mode.
274 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kProcessType))
275 channel_->AddFilter(new SuicideOnChannelErrorFilter());
278 base::MessageLoop::current()->PostDelayedTask(
280 base::Bind(&ChildThread::EnsureConnected,
281 channel_connected_factory_.GetWeakPtr()),
282 base::TimeDelta::FromSeconds(kConnectionTimeoutS));
284 #if defined(OS_ANDROID)
286 base::AutoLock lock(g_lazy_child_thread_lock.Get());
287 g_child_thread = this;
289 // Signalling without locking is fine here because only
290 // one thread can wait on the condition variable.
291 g_lazy_child_thread_cv.Get().Signal();
294 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
295 trace_memory_controller_.reset(new base::debug::TraceMemoryController(
296 message_loop_->message_loop_proxy(),
297 ::HeapProfilerWithPseudoStackStart,
303 ChildThread::~ChildThread() {
304 #ifdef IPC_MESSAGE_LOG_ENABLED
305 IPC::Logging::GetInstance()->SetIPCSender(NULL);
308 channel_->RemoveFilter(histogram_message_filter_.get());
309 channel_->RemoveFilter(sync_message_filter_.get());
311 // The ChannelProxy object caches a pointer to the IPC thread, so need to
312 // reset it as it's not guaranteed to outlive this object.
313 // NOTE: this also has the side-effect of not closing the main IPC channel to
314 // the browser process. This is needed because this is the signal that the
315 // browser uses to know that this process has died, so we need it to be alive
316 // until this process is shut down, and the OS closes the handle
317 // automatically. We used to watch the object handle on Windows to do this,
318 // but it wasn't possible to do so on POSIX.
319 channel_->ClearIPCTaskRunner();
320 g_lazy_tls.Pointer()->Set(NULL);
323 void ChildThread::Shutdown() {
324 // Delete objects that hold references to blink so derived classes can
325 // safely shutdown blink in their Shutdown implementation.
326 file_system_dispatcher_.reset();
327 quota_dispatcher_.reset();
330 void ChildThread::OnChannelConnected(int32 peer_pid) {
331 channel_connected_factory_.InvalidateWeakPtrs();
334 void ChildThread::OnChannelError() {
335 set_on_channel_error_called(true);
336 base::MessageLoop::current()->Quit();
339 bool ChildThread::Send(IPC::Message* msg) {
340 DCHECK(base::MessageLoop::current() == message_loop());
346 return channel_->Send(msg);
349 void ChildThread::AddRoute(int32 routing_id, IPC::Listener* listener) {
350 DCHECK(base::MessageLoop::current() == message_loop());
352 router_.AddRoute(routing_id, listener);
355 void ChildThread::RemoveRoute(int32 routing_id) {
356 DCHECK(base::MessageLoop::current() == message_loop());
358 router_.RemoveRoute(routing_id);
361 webkit_glue::ResourceLoaderBridge* ChildThread::CreateBridge(
362 const webkit_glue::ResourceLoaderBridge::RequestInfo& request_info) {
363 return resource_dispatcher()->CreateBridge(request_info);
366 base::SharedMemory* ChildThread::AllocateSharedMemory(size_t buf_size) {
367 return AllocateSharedMemory(buf_size, this);
371 base::SharedMemory* ChildThread::AllocateSharedMemory(
373 IPC::Sender* sender) {
374 scoped_ptr<base::SharedMemory> shared_buf;
376 shared_buf.reset(new base::SharedMemory);
377 if (!shared_buf->CreateAndMapAnonymous(buf_size)) {
382 // On POSIX, we need to ask the browser to create the shared memory for us,
383 // since this is blocked by the sandbox.
384 base::SharedMemoryHandle shared_mem_handle;
385 if (sender->Send(new ChildProcessHostMsg_SyncAllocateSharedMemory(
386 buf_size, &shared_mem_handle))) {
387 if (base::SharedMemory::IsHandleValid(shared_mem_handle)) {
388 shared_buf.reset(new base::SharedMemory(shared_mem_handle, false));
389 if (!shared_buf->Map(buf_size)) {
390 NOTREACHED() << "Map failed";
394 NOTREACHED() << "Browser failed to allocate shared memory";
398 NOTREACHED() << "Browser allocation request message failed";
402 return shared_buf.release();
405 bool ChildThread::OnMessageReceived(const IPC::Message& msg) {
406 // Resource responses are sent to the resource dispatcher.
407 if (resource_dispatcher_->OnMessageReceived(msg))
409 if (socket_stream_dispatcher_->OnMessageReceived(msg))
411 if (websocket_dispatcher_->OnMessageReceived(msg))
413 if (file_system_dispatcher_->OnMessageReceived(msg))
417 IPC_BEGIN_MESSAGE_MAP(ChildThread, msg)
418 IPC_MESSAGE_HANDLER(ChildProcessMsg_Shutdown, OnShutdown)
419 #if defined(IPC_MESSAGE_LOG_ENABLED)
420 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetIPCLoggingEnabled,
421 OnSetIPCLoggingEnabled)
423 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetProfilerStatus,
425 IPC_MESSAGE_HANDLER(ChildProcessMsg_GetChildProfilerData,
426 OnGetChildProfilerData)
427 IPC_MESSAGE_HANDLER(ChildProcessMsg_DumpHandles, OnDumpHandles)
428 #if defined(USE_TCMALLOC)
429 IPC_MESSAGE_HANDLER(ChildProcessMsg_GetTcmallocStats, OnGetTcmallocStats)
431 IPC_MESSAGE_UNHANDLED(handled = false)
432 IPC_END_MESSAGE_MAP()
437 if (msg.routing_id() == MSG_ROUTING_CONTROL)
438 return OnControlMessageReceived(msg);
440 return router_.OnMessageReceived(msg);
443 bool ChildThread::OnControlMessageReceived(const IPC::Message& msg) {
447 void ChildThread::OnShutdown() {
448 base::MessageLoop::current()->Quit();
451 #if defined(IPC_MESSAGE_LOG_ENABLED)
452 void ChildThread::OnSetIPCLoggingEnabled(bool enable) {
454 IPC::Logging::GetInstance()->Enable();
456 IPC::Logging::GetInstance()->Disable();
458 #endif // IPC_MESSAGE_LOG_ENABLED
460 void ChildThread::OnSetProfilerStatus(ThreadData::Status status) {
461 ThreadData::InitializeAndSetTrackingStatus(status);
464 void ChildThread::OnGetChildProfilerData(int sequence_number) {
465 tracked_objects::ProcessDataSnapshot process_data;
466 ThreadData::Snapshot(false, &process_data);
468 Send(new ChildProcessHostMsg_ChildProfilerData(sequence_number,
472 void ChildThread::OnDumpHandles() {
474 scoped_refptr<HandleEnumerator> handle_enum(
475 new HandleEnumerator(
476 CommandLine::ForCurrentProcess()->HasSwitch(
477 switches::kAuditAllHandles)));
478 handle_enum->EnumerateHandles();
479 Send(new ChildProcessHostMsg_DumpHandlesDone);
486 #if defined(USE_TCMALLOC)
487 void ChildThread::OnGetTcmallocStats() {
489 char buffer[1024 * 32];
490 base::allocator::GetStats(buffer, sizeof(buffer));
491 result.append(buffer);
492 Send(new ChildProcessHostMsg_TcmallocStats(result));
496 ChildThread* ChildThread::current() {
497 return g_lazy_tls.Pointer()->Get();
500 #if defined(OS_ANDROID)
501 // The method must NOT be called on the child thread itself.
502 // It may block the child thread if so.
503 void ChildThread::ShutdownThread() {
504 DCHECK(!ChildThread::current()) <<
505 "this method should NOT be called from child thread itself";
507 base::AutoLock lock(g_lazy_child_thread_lock.Get());
508 while (!g_child_thread)
509 g_lazy_child_thread_cv.Get().Wait();
511 DCHECK_NE(base::MessageLoop::current(), g_child_thread->message_loop());
512 g_child_thread->message_loop()->PostTask(
513 FROM_HERE, base::Bind(&QuitMainThreadMessageLoop));
518 void ChildThread::OnProcessFinalRelease() {
519 if (on_channel_error_called_) {
520 base::MessageLoop::current()->Quit();
524 // The child process shutdown sequence is a request response based mechanism,
525 // where we send out an initial feeler request to the child process host
526 // instance in the browser to verify if it's ok to shutdown the child process.
527 // The browser then sends back a response if it's ok to shutdown. This avoids
528 // race conditions if the process refcount is 0 but there's an IPC message
529 // inflight that would addref it.
530 Send(new ChildProcessHostMsg_ShutdownRequest);
533 void ChildThread::EnsureConnected() {
534 VLOG(0) << "ChildThread::EnsureConnected()";
535 base::KillProcess(base::GetCurrentProcessHandle(), 0, false);
538 } // namespace content