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/child_histogram_message_filter.h"
30 #include "content/child/child_process.h"
31 #include "content/child/child_resource_message_filter.h"
32 #include "content/child/child_shared_bitmap_manager.h"
33 #include "content/child/fileapi/file_system_dispatcher.h"
34 #include "content/child/fileapi/webfilesystem_impl.h"
35 #include "content/child/mojo/mojo_application.h"
36 #include "content/child/power_monitor_broadcast_source.h"
37 #include "content/child/quota_dispatcher.h"
38 #include "content/child/quota_message_filter.h"
39 #include "content/child/resource_dispatcher.h"
40 #include "content/child/service_worker/service_worker_message_filter.h"
41 #include "content/child/socket_stream_dispatcher.h"
42 #include "content/child/thread_safe_sender.h"
43 #include "content/child/websocket_dispatcher.h"
44 #include "content/common/child_process_messages.h"
45 #include "content/public/common/content_switches.h"
46 #include "ipc/ipc_logging.h"
47 #include "ipc/ipc_switches.h"
48 #include "ipc/ipc_sync_channel.h"
49 #include "ipc/ipc_sync_message_filter.h"
50 #include "ipc/mojo/ipc_channel_mojo.h"
53 #include "content/common/handle_enumerator_win.h"
56 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
57 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
60 using tracked_objects::ThreadData
;
65 // How long to wait for a connection to the browser process before giving up.
66 const int kConnectionTimeoutS
= 15;
68 base::LazyInstance
<base::ThreadLocalPointer
<ChildThread
> > g_lazy_tls
=
69 LAZY_INSTANCE_INITIALIZER
;
71 // This isn't needed on Windows because there the sandbox's job object
72 // terminates child processes automatically. For unsandboxed processes (i.e.
73 // plugins), PluginThread has EnsureTerminateMessageFilter.
76 // TODO(earthdok): Re-enable on CrOS http://crbug.com/360622
77 #if (defined(ADDRESS_SANITIZER) || defined(LEAK_SANITIZER) || \
78 defined(THREAD_SANITIZER)) && !defined(OS_CHROMEOS)
79 // A thread delegate that waits for |duration| and then exits the process with
81 class WaitAndExitDelegate
: public base::PlatformThread::Delegate
{
83 explicit WaitAndExitDelegate(base::TimeDelta duration
)
84 : duration_(duration
) {}
85 virtual ~WaitAndExitDelegate() OVERRIDE
{}
87 virtual void ThreadMain() OVERRIDE
{
88 base::PlatformThread::Sleep(duration_
);
93 const base::TimeDelta duration_
;
94 DISALLOW_COPY_AND_ASSIGN(WaitAndExitDelegate
);
97 bool CreateWaitAndExitThread(base::TimeDelta duration
) {
98 scoped_ptr
<WaitAndExitDelegate
> delegate(new WaitAndExitDelegate(duration
));
100 const bool thread_created
=
101 base::PlatformThread::CreateNonJoinable(0, delegate
.get());
105 // A non joinable thread has been created. The thread will either terminate
106 // the process or will be terminated by the process. Therefore, keep the
107 // delegate object alive for the lifetime of the process.
108 WaitAndExitDelegate
* leaking_delegate
= delegate
.release();
109 ANNOTATE_LEAKING_OBJECT_PTR(leaking_delegate
);
110 ignore_result(leaking_delegate
);
115 class SuicideOnChannelErrorFilter
: public IPC::MessageFilter
{
117 // IPC::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 sender) 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 sender so that we can process this event
133 // here and kill the process.
134 // TODO(earthdok): Re-enable on CrOS http://crbug.com/360622
135 #if (defined(ADDRESS_SANITIZER) || defined(LEAK_SANITIZER) || \
136 defined(THREAD_SANITIZER)) && !defined(OS_CHROMEOS)
137 // Some sanitizer tools rely on exit handlers (e.g. to run leak detection,
138 // or dump code coverage data to disk). Instead of exiting the process
139 // immediately, we give it 60 seconds to run exit handlers.
140 CHECK(CreateWaitAndExitThread(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;
170 static const bool kAllowedToAccessOnNonjoinableThread
= false;
173 static base::ConditionVariable
* New(void* instance
) {
174 return new (instance
) base::ConditionVariable(
175 g_lazy_child_thread_lock
.Pointer());
177 static void Delete(base::ConditionVariable
* instance
) {
178 instance
->~ConditionVariable();
182 // A condition variable that synchronize threads initializing and waiting
183 // for g_child_thread.
184 base::LazyInstance
<base::ConditionVariable
, CondVarLazyInstanceTraits
>
185 g_lazy_child_thread_cv
= LAZY_INSTANCE_INITIALIZER
;
187 void QuitMainThreadMessageLoop() {
188 base::MessageLoop::current()->Quit();
195 ChildThread::Options::Options()
196 : channel_name(CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
197 switches::kProcessChannelID
)),
198 use_mojo_channel(false) {}
200 ChildThread::Options::Options(bool mojo
)
201 : channel_name(CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
202 switches::kProcessChannelID
)),
203 use_mojo_channel(mojo
) {}
206 ChildThread::ChildThreadMessageRouter::ChildThreadMessageRouter(
210 bool ChildThread::ChildThreadMessageRouter::Send(IPC::Message
* msg
) {
211 return sender_
->Send(msg
);
214 ChildThread::ChildThread()
216 channel_connected_factory_(this),
217 in_browser_process_(false) {
221 ChildThread::ChildThread(const Options
& options
)
223 channel_connected_factory_(this),
224 in_browser_process_(true) {
228 scoped_ptr
<IPC::SyncChannel
> ChildThread::CreateChannel(bool use_mojo_channel
) {
229 if (use_mojo_channel
) {
230 VLOG(1) << "Mojo is enabled on child";
231 return IPC::SyncChannel::Create(
232 IPC::ChannelMojo::CreateFactory(
234 IPC::Channel::MODE_CLIENT
,
235 ChildProcess::current()->io_message_loop_proxy()),
237 ChildProcess::current()->io_message_loop_proxy(),
239 ChildProcess::current()->GetShutDownEvent());
242 VLOG(1) << "Mojo is disabled on child";
243 return IPC::SyncChannel::Create(
245 IPC::Channel::MODE_CLIENT
,
247 ChildProcess::current()->io_message_loop_proxy(),
249 ChildProcess::current()->GetShutDownEvent());
252 void ChildThread::Init(const Options
& options
) {
253 channel_name_
= options
.channel_name
;
255 g_lazy_tls
.Pointer()->Set(this);
256 on_channel_error_called_
= false;
257 message_loop_
= base::MessageLoop::current();
258 #ifdef IPC_MESSAGE_LOG_ENABLED
259 // We must make sure to instantiate the IPC Logger *before* we create the
260 // channel, otherwise we can get a callback on the IO thread which creates
261 // the logger, and the logger does not like being created on the IO thread.
262 IPC::Logging::GetInstance();
264 channel_
= CreateChannel(options
.use_mojo_channel
);
265 #ifdef IPC_MESSAGE_LOG_ENABLED
266 if (!in_browser_process_
)
267 IPC::Logging::GetInstance()->SetIPCSender(this);
270 mojo_application_
.reset(new MojoApplication
);
272 sync_message_filter_
=
273 new IPC::SyncMessageFilter(ChildProcess::current()->GetShutDownEvent());
274 thread_safe_sender_
= new ThreadSafeSender(
275 base::MessageLoopProxy::current().get(), sync_message_filter_
.get());
277 resource_dispatcher_
.reset(new ResourceDispatcher(this));
278 socket_stream_dispatcher_
.reset(new SocketStreamDispatcher());
279 websocket_dispatcher_
.reset(new WebSocketDispatcher
);
280 file_system_dispatcher_
.reset(new FileSystemDispatcher());
282 histogram_message_filter_
= new ChildHistogramMessageFilter();
283 resource_message_filter_
=
284 new ChildResourceMessageFilter(resource_dispatcher());
286 service_worker_message_filter_
=
287 new ServiceWorkerMessageFilter(thread_safe_sender_
.get());
289 quota_message_filter_
=
290 new QuotaMessageFilter(thread_safe_sender_
.get());
291 quota_dispatcher_
.reset(new QuotaDispatcher(thread_safe_sender_
.get(),
292 quota_message_filter_
.get()));
294 channel_
->AddFilter(histogram_message_filter_
.get());
295 channel_
->AddFilter(sync_message_filter_
.get());
296 channel_
->AddFilter(resource_message_filter_
.get());
297 channel_
->AddFilter(quota_message_filter_
->GetFilter());
298 channel_
->AddFilter(service_worker_message_filter_
->GetFilter());
300 if (!CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess
)) {
301 // In single process mode, browser-side tracing will cover the whole
302 // process including renderers.
303 channel_
->AddFilter(new tracing::ChildTraceMessageFilter(
304 ChildProcess::current()->io_message_loop_proxy()));
307 // In single process mode we may already have a power monitor
308 if (!base::PowerMonitor::Get()) {
309 scoped_ptr
<PowerMonitorBroadcastSource
> power_monitor_source(
310 new PowerMonitorBroadcastSource());
311 channel_
->AddFilter(power_monitor_source
->GetMessageFilter());
313 power_monitor_
.reset(new base::PowerMonitor(
314 power_monitor_source
.PassAs
<base::PowerMonitorSource
>()));
317 #if defined(OS_POSIX)
318 // Check that --process-type is specified so we don't do this in unit tests
319 // and single-process mode.
320 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kProcessType
))
321 channel_
->AddFilter(new SuicideOnChannelErrorFilter());
324 int connection_timeout
= kConnectionTimeoutS
;
325 std::string connection_override
=
326 CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
327 switches::kIPCConnectionTimeout
);
328 if (!connection_override
.empty()) {
330 if (base::StringToInt(connection_override
, &temp
))
331 connection_timeout
= temp
;
334 base::MessageLoop::current()->PostDelayedTask(
336 base::Bind(&ChildThread::EnsureConnected
,
337 channel_connected_factory_
.GetWeakPtr()),
338 base::TimeDelta::FromSeconds(connection_timeout
));
340 #if defined(OS_ANDROID)
342 base::AutoLock
lock(g_lazy_child_thread_lock
.Get());
343 g_child_thread
= this;
345 // Signalling without locking is fine here because only
346 // one thread can wait on the condition variable.
347 g_lazy_child_thread_cv
.Get().Signal();
350 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
351 trace_memory_controller_
.reset(new base::debug::TraceMemoryController(
352 message_loop_
->message_loop_proxy(),
353 ::HeapProfilerWithPseudoStackStart
,
358 shared_bitmap_manager_
.reset(
359 new ChildSharedBitmapManager(thread_safe_sender()));
362 ChildThread::~ChildThread() {
363 #ifdef IPC_MESSAGE_LOG_ENABLED
364 IPC::Logging::GetInstance()->SetIPCSender(NULL
);
367 channel_
->RemoveFilter(histogram_message_filter_
.get());
368 channel_
->RemoveFilter(sync_message_filter_
.get());
370 // The ChannelProxy object caches a pointer to the IPC thread, so need to
371 // reset it as it's not guaranteed to outlive this object.
372 // NOTE: this also has the side-effect of not closing the main IPC channel to
373 // the browser process. This is needed because this is the signal that the
374 // browser uses to know that this process has died, so we need it to be alive
375 // until this process is shut down, and the OS closes the handle
376 // automatically. We used to watch the object handle on Windows to do this,
377 // but it wasn't possible to do so on POSIX.
378 channel_
->ClearIPCTaskRunner();
379 g_lazy_tls
.Pointer()->Set(NULL
);
382 void ChildThread::Shutdown() {
383 // Delete objects that hold references to blink so derived classes can
384 // safely shutdown blink in their Shutdown implementation.
385 file_system_dispatcher_
.reset();
386 quota_dispatcher_
.reset();
387 WebFileSystemImpl::DeleteThreadSpecificInstance();
390 void ChildThread::OnChannelConnected(int32 peer_pid
) {
391 channel_connected_factory_
.InvalidateWeakPtrs();
394 void ChildThread::OnChannelError() {
395 set_on_channel_error_called(true);
396 base::MessageLoop::current()->Quit();
399 bool ChildThread::Send(IPC::Message
* msg
) {
400 DCHECK(base::MessageLoop::current() == message_loop());
406 return channel_
->Send(msg
);
409 MessageRouter
* ChildThread::GetRouter() {
410 DCHECK(base::MessageLoop::current() == message_loop());
414 base::SharedMemory
* ChildThread::AllocateSharedMemory(size_t buf_size
) {
415 return AllocateSharedMemory(buf_size
, this);
419 base::SharedMemory
* ChildThread::AllocateSharedMemory(
421 IPC::Sender
* sender
) {
422 scoped_ptr
<base::SharedMemory
> shared_buf
;
424 shared_buf
.reset(new base::SharedMemory
);
425 if (!shared_buf
->CreateAndMapAnonymous(buf_size
)) {
430 // On POSIX, we need to ask the browser to create the shared memory for us,
431 // since this is blocked by the sandbox.
432 base::SharedMemoryHandle shared_mem_handle
;
433 if (sender
->Send(new ChildProcessHostMsg_SyncAllocateSharedMemory(
434 buf_size
, &shared_mem_handle
))) {
435 if (base::SharedMemory::IsHandleValid(shared_mem_handle
)) {
436 shared_buf
.reset(new base::SharedMemory(shared_mem_handle
, false));
437 if (!shared_buf
->Map(buf_size
)) {
438 NOTREACHED() << "Map failed";
442 NOTREACHED() << "Browser failed to allocate shared memory";
446 NOTREACHED() << "Browser allocation request message failed";
450 return shared_buf
.release();
453 bool ChildThread::OnMessageReceived(const IPC::Message
& msg
) {
454 if (mojo_application_
->OnMessageReceived(msg
))
457 // Resource responses are sent to the resource dispatcher.
458 if (resource_dispatcher_
->OnMessageReceived(msg
))
460 if (socket_stream_dispatcher_
->OnMessageReceived(msg
))
462 if (websocket_dispatcher_
->OnMessageReceived(msg
))
464 if (file_system_dispatcher_
->OnMessageReceived(msg
))
468 IPC_BEGIN_MESSAGE_MAP(ChildThread
, msg
)
469 IPC_MESSAGE_HANDLER(ChildProcessMsg_Shutdown
, OnShutdown
)
470 #if defined(IPC_MESSAGE_LOG_ENABLED)
471 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetIPCLoggingEnabled
,
472 OnSetIPCLoggingEnabled
)
474 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetProfilerStatus
,
476 IPC_MESSAGE_HANDLER(ChildProcessMsg_GetChildProfilerData
,
477 OnGetChildProfilerData
)
478 IPC_MESSAGE_HANDLER(ChildProcessMsg_DumpHandles
, OnDumpHandles
)
479 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetProcessBackgrounded
,
480 OnProcessBackgrounded
)
481 #if defined(USE_TCMALLOC)
482 IPC_MESSAGE_HANDLER(ChildProcessMsg_GetTcmallocStats
, OnGetTcmallocStats
)
484 IPC_MESSAGE_UNHANDLED(handled
= false)
485 IPC_END_MESSAGE_MAP()
490 if (msg
.routing_id() == MSG_ROUTING_CONTROL
)
491 return OnControlMessageReceived(msg
);
493 return router_
.OnMessageReceived(msg
);
496 bool ChildThread::OnControlMessageReceived(const IPC::Message
& msg
) {
500 void ChildThread::OnShutdown() {
501 base::MessageLoop::current()->Quit();
504 #if defined(IPC_MESSAGE_LOG_ENABLED)
505 void ChildThread::OnSetIPCLoggingEnabled(bool enable
) {
507 IPC::Logging::GetInstance()->Enable();
509 IPC::Logging::GetInstance()->Disable();
511 #endif // IPC_MESSAGE_LOG_ENABLED
513 void ChildThread::OnSetProfilerStatus(ThreadData::Status status
) {
514 ThreadData::InitializeAndSetTrackingStatus(status
);
517 void ChildThread::OnGetChildProfilerData(int sequence_number
) {
518 tracked_objects::ProcessDataSnapshot process_data
;
519 ThreadData::Snapshot(false, &process_data
);
521 Send(new ChildProcessHostMsg_ChildProfilerData(sequence_number
,
525 void ChildThread::OnDumpHandles() {
527 scoped_refptr
<HandleEnumerator
> handle_enum(
528 new HandleEnumerator(
529 CommandLine::ForCurrentProcess()->HasSwitch(
530 switches::kAuditAllHandles
)));
531 handle_enum
->EnumerateHandles();
532 Send(new ChildProcessHostMsg_DumpHandlesDone
);
538 #if defined(USE_TCMALLOC)
539 void ChildThread::OnGetTcmallocStats() {
541 char buffer
[1024 * 32];
542 base::allocator::GetStats(buffer
, sizeof(buffer
));
543 result
.append(buffer
);
544 Send(new ChildProcessHostMsg_TcmallocStats(result
));
548 ChildThread
* ChildThread::current() {
549 return g_lazy_tls
.Pointer()->Get();
552 #if defined(OS_ANDROID)
553 // The method must NOT be called on the child thread itself.
554 // It may block the child thread if so.
555 void ChildThread::ShutdownThread() {
556 DCHECK(!ChildThread::current()) <<
557 "this method should NOT be called from child thread itself";
559 base::AutoLock
lock(g_lazy_child_thread_lock
.Get());
560 while (!g_child_thread
)
561 g_lazy_child_thread_cv
.Get().Wait();
563 DCHECK_NE(base::MessageLoop::current(), g_child_thread
->message_loop());
564 g_child_thread
->message_loop()->PostTask(
565 FROM_HERE
, base::Bind(&QuitMainThreadMessageLoop
));
569 void ChildThread::OnProcessFinalRelease() {
570 if (on_channel_error_called_
) {
571 base::MessageLoop::current()->Quit();
575 // The child process shutdown sequence is a request response based mechanism,
576 // where we send out an initial feeler request to the child process host
577 // instance in the browser to verify if it's ok to shutdown the child process.
578 // The browser then sends back a response if it's ok to shutdown. This avoids
579 // race conditions if the process refcount is 0 but there's an IPC message
580 // inflight that would addref it.
581 Send(new ChildProcessHostMsg_ShutdownRequest
);
584 void ChildThread::EnsureConnected() {
585 VLOG(0) << "ChildThread::EnsureConnected()";
586 base::KillProcess(base::GetCurrentProcessHandle(), 0, false);
589 void ChildThread::OnProcessBackgrounded(bool background
) {
590 // Set timer slack to maximum on main thread when in background.
591 base::TimerSlack timer_slack
= base::TIMER_SLACK_NONE
;
593 timer_slack
= base::TIMER_SLACK_MAXIMUM
;
594 base::MessageLoop::current()->SetTimerSlack(timer_slack
);
597 } // namespace content