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/message_loop/timer_slack.h"
20 #include "base/process/kill.h"
21 #include "base/process/process_handle.h"
22 #include "base/strings/string_number_conversions.h"
23 #include "base/strings/string_util.h"
24 #include "base/synchronization/condition_variable.h"
25 #include "base/synchronization/lock.h"
26 #include "base/threading/thread_local.h"
27 #include "base/tracked_objects.h"
28 #include "components/tracing/child_trace_message_filter.h"
29 #include "content/child/bluetooth/bluetooth_message_filter.h"
30 #include "content/child/child_discardable_shared_memory_manager.h"
31 #include "content/child/child_gpu_memory_buffer_manager.h"
32 #include "content/child/child_histogram_message_filter.h"
33 #include "content/child/child_process.h"
34 #include "content/child/child_resource_message_filter.h"
35 #include "content/child/child_shared_bitmap_manager.h"
36 #include "content/child/fileapi/file_system_dispatcher.h"
37 #include "content/child/fileapi/webfilesystem_impl.h"
38 #include "content/child/geofencing/geofencing_message_filter.h"
39 #include "content/child/mojo/mojo_application.h"
40 #include "content/child/navigator_connect/navigator_connect_dispatcher.h"
41 #include "content/child/notifications/notification_dispatcher.h"
42 #include "content/child/power_monitor_broadcast_source.h"
43 #include "content/child/push_messaging/push_dispatcher.h"
44 #include "content/child/quota_dispatcher.h"
45 #include "content/child/quota_message_filter.h"
46 #include "content/child/resource_dispatcher.h"
47 #include "content/child/service_worker/service_worker_message_filter.h"
48 #include "content/child/thread_safe_sender.h"
49 #include "content/child/websocket_dispatcher.h"
50 #include "content/common/child_process_messages.h"
51 #include "content/public/common/content_switches.h"
52 #include "ipc/ipc_logging.h"
53 #include "ipc/ipc_switches.h"
54 #include "ipc/ipc_sync_channel.h"
55 #include "ipc/ipc_sync_message_filter.h"
56 #include "ipc/mojo/ipc_channel_mojo.h"
59 #include "content/common/handle_enumerator_win.h"
62 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
63 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
66 using tracked_objects::ThreadData
;
71 // How long to wait for a connection to the browser process before giving up.
72 const int kConnectionTimeoutS
= 15;
74 base::LazyInstance
<base::ThreadLocalPointer
<ChildThread
> > g_lazy_tls
=
75 LAZY_INSTANCE_INITIALIZER
;
77 // This isn't needed on Windows because there the sandbox's job object
78 // terminates child processes automatically. For unsandboxed processes (i.e.
79 // plugins), PluginThread has EnsureTerminateMessageFilter.
82 // TODO(earthdok): Re-enable on CrOS http://crbug.com/360622
83 #if (defined(ADDRESS_SANITIZER) || defined(LEAK_SANITIZER) || \
84 defined(THREAD_SANITIZER)) && !defined(OS_CHROMEOS)
85 // A thread delegate that waits for |duration| and then exits the process with
87 class WaitAndExitDelegate
: public base::PlatformThread::Delegate
{
89 explicit WaitAndExitDelegate(base::TimeDelta duration
)
90 : duration_(duration
) {}
92 void ThreadMain() override
{
93 base::PlatformThread::Sleep(duration_
);
98 const base::TimeDelta duration_
;
99 DISALLOW_COPY_AND_ASSIGN(WaitAndExitDelegate
);
102 bool CreateWaitAndExitThread(base::TimeDelta duration
) {
103 scoped_ptr
<WaitAndExitDelegate
> delegate(new WaitAndExitDelegate(duration
));
105 const bool thread_created
=
106 base::PlatformThread::CreateNonJoinable(0, delegate
.get());
110 // A non joinable thread has been created. The thread will either terminate
111 // the process or will be terminated by the process. Therefore, keep the
112 // delegate object alive for the lifetime of the process.
113 WaitAndExitDelegate
* leaking_delegate
= delegate
.release();
114 ANNOTATE_LEAKING_OBJECT_PTR(leaking_delegate
);
115 ignore_result(leaking_delegate
);
120 class SuicideOnChannelErrorFilter
: public IPC::MessageFilter
{
122 // IPC::MessageFilter
123 void OnChannelError() override
{
124 // For renderer/worker processes:
125 // On POSIX, at least, one can install an unload handler which loops
126 // forever and leave behind a renderer process which eats 100% CPU forever.
128 // This is because the terminate signals (ViewMsg_ShouldClose and the error
129 // from the IPC sender) are routed to the main message loop but never
130 // processed (because that message loop is stuck in V8).
132 // One could make the browser SIGKILL the renderers, but that leaves open a
133 // large window where a browser failure (or a user, manually terminating
134 // the browser because "it's stuck") will leave behind a process eating all
137 // So, we install a filter on the sender so that we can process this event
138 // here and kill the process.
139 // TODO(earthdok): Re-enable on CrOS http://crbug.com/360622
140 #if (defined(ADDRESS_SANITIZER) || defined(LEAK_SANITIZER) || \
141 defined(THREAD_SANITIZER)) && !defined(OS_CHROMEOS)
142 // Some sanitizer tools rely on exit handlers (e.g. to run leak detection,
143 // or dump code coverage data to disk). Instead of exiting the process
144 // immediately, we give it 60 seconds to run exit handlers.
145 CHECK(CreateWaitAndExitThread(base::TimeDelta::FromSeconds(60)));
146 #if defined(LEAK_SANITIZER)
147 // Invoke LeakSanitizer early to avoid detecting shutdown-only leaks. If
148 // leaks are found, the process will exit here.
149 __lsan_do_leak_check();
157 ~SuicideOnChannelErrorFilter() override
{}
162 #if defined(OS_ANDROID)
163 ChildThread
* g_child_thread
= NULL
;
165 // A lock protects g_child_thread.
166 base::LazyInstance
<base::Lock
> g_lazy_child_thread_lock
=
167 LAZY_INSTANCE_INITIALIZER
;
169 // base::ConditionVariable has an explicit constructor that takes
170 // a base::Lock pointer as parameter. The base::DefaultLazyInstanceTraits
171 // doesn't handle the case. Thus, we need our own class here.
172 struct CondVarLazyInstanceTraits
{
173 static const bool kRegisterOnExit
= true;
175 static const bool kAllowedToAccessOnNonjoinableThread
= false;
178 static base::ConditionVariable
* New(void* instance
) {
179 return new (instance
) base::ConditionVariable(
180 g_lazy_child_thread_lock
.Pointer());
182 static void Delete(base::ConditionVariable
* instance
) {
183 instance
->~ConditionVariable();
187 // A condition variable that synchronize threads initializing and waiting
188 // for g_child_thread.
189 base::LazyInstance
<base::ConditionVariable
, CondVarLazyInstanceTraits
>
190 g_lazy_child_thread_cv
= LAZY_INSTANCE_INITIALIZER
;
192 void QuitMainThreadMessageLoop() {
193 base::MessageLoop::current()->Quit();
200 ChildThread::Options::Options()
201 : channel_name(base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
202 switches::kProcessChannelID
)),
203 use_mojo_channel(false) {}
205 ChildThread::Options::Options(bool mojo
)
206 : channel_name(base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
207 switches::kProcessChannelID
)),
208 use_mojo_channel(mojo
) {}
211 ChildThread::ChildThreadMessageRouter::ChildThreadMessageRouter(
215 bool ChildThread::ChildThreadMessageRouter::Send(IPC::Message
* msg
) {
216 return sender_
->Send(msg
);
219 ChildThread::ChildThread()
221 in_browser_process_(false),
222 channel_connected_factory_(this) {
226 ChildThread::ChildThread(const Options
& options
)
228 in_browser_process_(true),
229 channel_connected_factory_(this) {
233 scoped_ptr
<IPC::SyncChannel
> ChildThread::CreateChannel(bool use_mojo_channel
) {
234 if (use_mojo_channel
) {
235 VLOG(1) << "Mojo is enabled on child";
236 return IPC::SyncChannel::Create(
237 IPC::ChannelMojo::CreateClientFactory(channel_name_
),
239 ChildProcess::current()->io_message_loop_proxy(),
241 ChildProcess::current()->GetShutDownEvent());
244 VLOG(1) << "Mojo is disabled on child";
245 return IPC::SyncChannel::Create(
247 IPC::Channel::MODE_CLIENT
,
249 ChildProcess::current()->io_message_loop_proxy(),
251 ChildProcess::current()->GetShutDownEvent());
254 void ChildThread::Init(const Options
& options
) {
255 channel_name_
= options
.channel_name
;
257 g_lazy_tls
.Pointer()->Set(this);
258 on_channel_error_called_
= false;
259 message_loop_
= base::MessageLoop::current();
260 #ifdef IPC_MESSAGE_LOG_ENABLED
261 // We must make sure to instantiate the IPC Logger *before* we create the
262 // channel, otherwise we can get a callback on the IO thread which creates
263 // the logger, and the logger does not like being created on the IO thread.
264 IPC::Logging::GetInstance();
266 channel_
= CreateChannel(options
.use_mojo_channel
);
267 #ifdef IPC_MESSAGE_LOG_ENABLED
268 if (!in_browser_process_
)
269 IPC::Logging::GetInstance()->SetIPCSender(this);
272 mojo_application_
.reset(new MojoApplication
);
274 sync_message_filter_
=
275 new IPC::SyncMessageFilter(ChildProcess::current()->GetShutDownEvent());
276 thread_safe_sender_
= new ThreadSafeSender(
277 base::MessageLoopProxy::current().get(), sync_message_filter_
.get());
279 resource_dispatcher_
.reset(new ResourceDispatcher(
280 this, message_loop()->task_runner()));
281 websocket_dispatcher_
.reset(new WebSocketDispatcher
);
282 file_system_dispatcher_
.reset(new FileSystemDispatcher());
284 histogram_message_filter_
= new ChildHistogramMessageFilter();
285 resource_message_filter_
=
286 new ChildResourceMessageFilter(resource_dispatcher());
288 service_worker_message_filter_
=
289 new ServiceWorkerMessageFilter(thread_safe_sender_
.get());
291 quota_message_filter_
=
292 new QuotaMessageFilter(thread_safe_sender_
.get());
293 quota_dispatcher_
.reset(new QuotaDispatcher(thread_safe_sender_
.get(),
294 quota_message_filter_
.get()));
295 geofencing_message_filter_
=
296 new GeofencingMessageFilter(thread_safe_sender_
.get());
297 bluetooth_message_filter_
=
298 new BluetoothMessageFilter(thread_safe_sender_
.get());
299 notification_dispatcher_
=
300 new NotificationDispatcher(thread_safe_sender_
.get());
301 push_dispatcher_
= new PushDispatcher(thread_safe_sender_
.get());
302 navigator_connect_dispatcher_
=
303 new NavigatorConnectDispatcher(thread_safe_sender_
.get());
305 channel_
->AddFilter(histogram_message_filter_
.get());
306 channel_
->AddFilter(sync_message_filter_
.get());
307 channel_
->AddFilter(resource_message_filter_
.get());
308 channel_
->AddFilter(quota_message_filter_
->GetFilter());
309 channel_
->AddFilter(notification_dispatcher_
->GetFilter());
310 channel_
->AddFilter(push_dispatcher_
->GetFilter());
311 channel_
->AddFilter(service_worker_message_filter_
->GetFilter());
312 channel_
->AddFilter(geofencing_message_filter_
->GetFilter());
313 channel_
->AddFilter(bluetooth_message_filter_
->GetFilter());
314 channel_
->AddFilter(navigator_connect_dispatcher_
->GetFilter());
316 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
317 switches::kSingleProcess
)) {
318 // In single process mode, browser-side tracing will cover the whole
319 // process including renderers.
320 channel_
->AddFilter(new tracing::ChildTraceMessageFilter(
321 ChildProcess::current()->io_message_loop_proxy()));
324 // In single process mode we may already have a power monitor
325 if (!base::PowerMonitor::Get()) {
326 scoped_ptr
<PowerMonitorBroadcastSource
> power_monitor_source(
327 new PowerMonitorBroadcastSource());
328 channel_
->AddFilter(power_monitor_source
->GetMessageFilter());
330 power_monitor_
.reset(new base::PowerMonitor(
331 power_monitor_source
.Pass()));
334 #if defined(OS_POSIX)
335 // Check that --process-type is specified so we don't do this in unit tests
336 // and single-process mode.
337 if (base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kProcessType
))
338 channel_
->AddFilter(new SuicideOnChannelErrorFilter());
341 int connection_timeout
= kConnectionTimeoutS
;
342 std::string connection_override
=
343 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
344 switches::kIPCConnectionTimeout
);
345 if (!connection_override
.empty()) {
347 if (base::StringToInt(connection_override
, &temp
))
348 connection_timeout
= temp
;
351 base::MessageLoop::current()->PostDelayedTask(
353 base::Bind(&ChildThread::EnsureConnected
,
354 channel_connected_factory_
.GetWeakPtr()),
355 base::TimeDelta::FromSeconds(connection_timeout
));
357 #if defined(OS_ANDROID)
359 base::AutoLock
lock(g_lazy_child_thread_lock
.Get());
360 g_child_thread
= this;
362 // Signalling without locking is fine here because only
363 // one thread can wait on the condition variable.
364 g_lazy_child_thread_cv
.Get().Signal();
367 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
368 trace_memory_controller_
.reset(new base::debug::TraceMemoryController(
369 message_loop_
->message_loop_proxy(),
370 ::HeapProfilerWithPseudoStackStart
,
375 shared_bitmap_manager_
.reset(
376 new ChildSharedBitmapManager(thread_safe_sender()));
378 gpu_memory_buffer_manager_
.reset(
379 new ChildGpuMemoryBufferManager(thread_safe_sender()));
381 discardable_shared_memory_manager_
.reset(
382 new ChildDiscardableSharedMemoryManager(thread_safe_sender()));
385 ChildThread::~ChildThread() {
386 #ifdef IPC_MESSAGE_LOG_ENABLED
387 IPC::Logging::GetInstance()->SetIPCSender(NULL
);
390 channel_
->RemoveFilter(histogram_message_filter_
.get());
391 channel_
->RemoveFilter(sync_message_filter_
.get());
393 // The ChannelProxy object caches a pointer to the IPC thread, so need to
394 // reset it as it's not guaranteed to outlive this object.
395 // NOTE: this also has the side-effect of not closing the main IPC channel to
396 // the browser process. This is needed because this is the signal that the
397 // browser uses to know that this process has died, so we need it to be alive
398 // until this process is shut down, and the OS closes the handle
399 // automatically. We used to watch the object handle on Windows to do this,
400 // but it wasn't possible to do so on POSIX.
401 channel_
->ClearIPCTaskRunner();
402 g_lazy_tls
.Pointer()->Set(NULL
);
405 void ChildThread::Shutdown() {
406 // Delete objects that hold references to blink so derived classes can
407 // safely shutdown blink in their Shutdown implementation.
408 file_system_dispatcher_
.reset();
409 quota_dispatcher_
.reset();
410 WebFileSystemImpl::DeleteThreadSpecificInstance();
413 void ChildThread::OnChannelConnected(int32 peer_pid
) {
414 channel_connected_factory_
.InvalidateWeakPtrs();
417 void ChildThread::OnChannelError() {
418 set_on_channel_error_called(true);
419 base::MessageLoop::current()->Quit();
422 bool ChildThread::Send(IPC::Message
* msg
) {
423 DCHECK(base::MessageLoop::current() == message_loop());
429 return channel_
->Send(msg
);
432 MessageRouter
* ChildThread::GetRouter() {
433 DCHECK(base::MessageLoop::current() == message_loop());
437 scoped_ptr
<base::SharedMemory
> ChildThread::AllocateSharedMemory(
439 DCHECK(base::MessageLoop::current() == message_loop());
440 return AllocateSharedMemory(buf_size
, this);
444 scoped_ptr
<base::SharedMemory
> ChildThread::AllocateSharedMemory(
446 IPC::Sender
* sender
) {
447 scoped_ptr
<base::SharedMemory
> shared_buf
;
449 shared_buf
.reset(new base::SharedMemory
);
450 if (!shared_buf
->CreateAnonymous(buf_size
)) {
455 // On POSIX, we need to ask the browser to create the shared memory for us,
456 // since this is blocked by the sandbox.
457 base::SharedMemoryHandle shared_mem_handle
;
458 if (sender
->Send(new ChildProcessHostMsg_SyncAllocateSharedMemory(
459 buf_size
, &shared_mem_handle
))) {
460 if (base::SharedMemory::IsHandleValid(shared_mem_handle
)) {
461 shared_buf
.reset(new base::SharedMemory(shared_mem_handle
, false));
463 NOTREACHED() << "Browser failed to allocate shared memory";
467 NOTREACHED() << "Browser allocation request message failed";
474 bool ChildThread::OnMessageReceived(const IPC::Message
& msg
) {
475 if (mojo_application_
->OnMessageReceived(msg
))
478 // Resource responses are sent to the resource dispatcher.
479 if (resource_dispatcher_
->OnMessageReceived(msg
))
481 if (websocket_dispatcher_
->OnMessageReceived(msg
))
483 if (file_system_dispatcher_
->OnMessageReceived(msg
))
487 IPC_BEGIN_MESSAGE_MAP(ChildThread
, msg
)
488 IPC_MESSAGE_HANDLER(ChildProcessMsg_Shutdown
, OnShutdown
)
489 #if defined(IPC_MESSAGE_LOG_ENABLED)
490 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetIPCLoggingEnabled
,
491 OnSetIPCLoggingEnabled
)
493 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetProfilerStatus
,
495 IPC_MESSAGE_HANDLER(ChildProcessMsg_GetChildProfilerData
,
496 OnGetChildProfilerData
)
497 IPC_MESSAGE_HANDLER(ChildProcessMsg_DumpHandles
, OnDumpHandles
)
498 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetProcessBackgrounded
,
499 OnProcessBackgrounded
)
500 #if defined(USE_TCMALLOC)
501 IPC_MESSAGE_HANDLER(ChildProcessMsg_GetTcmallocStats
, OnGetTcmallocStats
)
503 IPC_MESSAGE_UNHANDLED(handled
= false)
504 IPC_END_MESSAGE_MAP()
509 if (msg
.routing_id() == MSG_ROUTING_CONTROL
)
510 return OnControlMessageReceived(msg
);
512 return router_
.OnMessageReceived(msg
);
515 bool ChildThread::OnControlMessageReceived(const IPC::Message
& msg
) {
519 void ChildThread::OnShutdown() {
520 base::MessageLoop::current()->Quit();
523 #if defined(IPC_MESSAGE_LOG_ENABLED)
524 void ChildThread::OnSetIPCLoggingEnabled(bool enable
) {
526 IPC::Logging::GetInstance()->Enable();
528 IPC::Logging::GetInstance()->Disable();
530 #endif // IPC_MESSAGE_LOG_ENABLED
532 void ChildThread::OnSetProfilerStatus(ThreadData::Status status
) {
533 ThreadData::InitializeAndSetTrackingStatus(status
);
536 void ChildThread::OnGetChildProfilerData(int sequence_number
) {
537 tracked_objects::ProcessDataSnapshot process_data
;
538 ThreadData::Snapshot(false, &process_data
);
540 Send(new ChildProcessHostMsg_ChildProfilerData(sequence_number
,
544 void ChildThread::OnDumpHandles() {
546 scoped_refptr
<HandleEnumerator
> handle_enum(
547 new HandleEnumerator(
548 base::CommandLine::ForCurrentProcess()->HasSwitch(
549 switches::kAuditAllHandles
)));
550 handle_enum
->EnumerateHandles();
551 Send(new ChildProcessHostMsg_DumpHandlesDone
);
557 #if defined(USE_TCMALLOC)
558 void ChildThread::OnGetTcmallocStats() {
560 char buffer
[1024 * 32];
561 base::allocator::GetStats(buffer
, sizeof(buffer
));
562 result
.append(buffer
);
563 Send(new ChildProcessHostMsg_TcmallocStats(result
));
567 ChildThread
* ChildThread::current() {
568 return g_lazy_tls
.Pointer()->Get();
571 #if defined(OS_ANDROID)
572 // The method must NOT be called on the child thread itself.
573 // It may block the child thread if so.
574 void ChildThread::ShutdownThread() {
575 DCHECK(!ChildThread::current()) <<
576 "this method should NOT be called from child thread itself";
578 base::AutoLock
lock(g_lazy_child_thread_lock
.Get());
579 while (!g_child_thread
)
580 g_lazy_child_thread_cv
.Get().Wait();
582 DCHECK_NE(base::MessageLoop::current(), g_child_thread
->message_loop());
583 g_child_thread
->message_loop()->PostTask(
584 FROM_HERE
, base::Bind(&QuitMainThreadMessageLoop
));
588 void ChildThread::OnProcessFinalRelease() {
589 if (on_channel_error_called_
) {
590 base::MessageLoop::current()->Quit();
594 // The child process shutdown sequence is a request response based mechanism,
595 // where we send out an initial feeler request to the child process host
596 // instance in the browser to verify if it's ok to shutdown the child process.
597 // The browser then sends back a response if it's ok to shutdown. This avoids
598 // race conditions if the process refcount is 0 but there's an IPC message
599 // inflight that would addref it.
600 Send(new ChildProcessHostMsg_ShutdownRequest
);
603 void ChildThread::EnsureConnected() {
604 VLOG(0) << "ChildThread::EnsureConnected()";
605 base::KillProcess(base::GetCurrentProcessHandle(), 0, false);
608 void ChildThread::OnProcessBackgrounded(bool background
) {
609 // Set timer slack to maximum on main thread when in background.
610 base::TimerSlack timer_slack
= base::TIMER_SLACK_NONE
;
612 timer_slack
= base::TIMER_SLACK_MAXIMUM
;
613 base::MessageLoop::current()->SetTimerSlack(timer_slack
);
616 } // namespace content