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/child_shared_bitmap_manager.h"
31 #include "content/child/fileapi/file_system_dispatcher.h"
32 #include "content/child/mojo/mojo_application.h"
33 #include "content/child/power_monitor_broadcast_source.h"
34 #include "content/child/quota_dispatcher.h"
35 #include "content/child/quota_message_filter.h"
36 #include "content/child/resource_dispatcher.h"
37 #include "content/child/service_worker/service_worker_dispatcher.h"
38 #include "content/child/service_worker/service_worker_message_filter.h"
39 #include "content/child/socket_stream_dispatcher.h"
40 #include "content/child/thread_safe_sender.h"
41 #include "content/child/websocket_dispatcher.h"
42 #include "content/common/child_process_messages.h"
43 #include "content/public/common/content_switches.h"
44 #include "ipc/ipc_logging.h"
45 #include "ipc/ipc_switches.h"
46 #include "ipc/ipc_sync_channel.h"
47 #include "ipc/ipc_sync_message_filter.h"
48 #include "webkit/child/resource_loader_bridge.h"
51 #include "content/common/handle_enumerator_win.h"
54 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
55 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
58 using tracked_objects::ThreadData
;
63 // How long to wait for a connection to the browser process before giving up.
64 const int kConnectionTimeoutS
= 15;
66 base::LazyInstance
<base::ThreadLocalPointer
<ChildThread
> > g_lazy_tls
=
67 LAZY_INSTANCE_INITIALIZER
;
69 // This isn't needed on Windows because there the sandbox's job object
70 // terminates child processes automatically. For unsandboxed processes (i.e.
71 // plugins), PluginThread has EnsureTerminateMessageFilter.
74 // TODO(earthdok): Re-enable on CrOS http://crbug.com/360622
75 #if (defined(ADDRESS_SANITIZER) || defined(LEAK_SANITIZER) || \
76 defined(THREAD_SANITIZER)) && !defined(OS_CHROMEOS)
77 // A thread delegate that waits for |duration| and then exits the process with
79 class WaitAndExitDelegate
: public base::PlatformThread::Delegate
{
81 explicit WaitAndExitDelegate(base::TimeDelta duration
)
82 : duration_(duration
) {}
83 virtual ~WaitAndExitDelegate() OVERRIDE
{}
85 virtual void ThreadMain() OVERRIDE
{
86 base::PlatformThread::Sleep(duration_
);
91 const base::TimeDelta duration_
;
92 DISALLOW_COPY_AND_ASSIGN(WaitAndExitDelegate
);
95 bool CreateWaitAndExitThread(base::TimeDelta duration
) {
96 scoped_ptr
<WaitAndExitDelegate
> delegate(new WaitAndExitDelegate(duration
));
98 const bool thread_created
=
99 base::PlatformThread::CreateNonJoinable(0, delegate
.get());
103 // A non joinable thread has been created. The thread will either terminate
104 // the process or will be terminated by the process. Therefore, keep the
105 // delegate object alive for the lifetime of the process.
106 WaitAndExitDelegate
* leaking_delegate
= delegate
.release();
107 ANNOTATE_LEAKING_OBJECT_PTR(leaking_delegate
);
108 ignore_result(leaking_delegate
);
113 class SuicideOnChannelErrorFilter
: public IPC::MessageFilter
{
115 // IPC::MessageFilter
116 virtual void OnChannelError() OVERRIDE
{
117 // For renderer/worker processes:
118 // On POSIX, at least, one can install an unload handler which loops
119 // forever and leave behind a renderer process which eats 100% CPU forever.
121 // This is because the terminate signals (ViewMsg_ShouldClose and the error
122 // from the IPC channel) are routed to the main message loop but never
123 // processed (because that message loop is stuck in V8).
125 // One could make the browser SIGKILL the renderers, but that leaves open a
126 // large window where a browser failure (or a user, manually terminating
127 // the browser because "it's stuck") will leave behind a process eating all
130 // So, we install a filter on the channel so that we can process this event
131 // here and kill the process.
132 // TODO(earthdok): Re-enable on CrOS http://crbug.com/360622
133 #if (defined(ADDRESS_SANITIZER) || defined(LEAK_SANITIZER) || \
134 defined(THREAD_SANITIZER)) && !defined(OS_CHROMEOS)
135 // Some sanitizer tools rely on exit handlers (e.g. to run leak detection,
136 // or dump code coverage data to disk). Instead of exiting the process
137 // immediately, we give it 60 seconds to run exit handlers.
138 CHECK(CreateWaitAndExitThread(base::TimeDelta::FromSeconds(60)));
139 #if defined(LEAK_SANITIZER)
140 // Invoke LeakSanitizer early to avoid detecting shutdown-only leaks. If
141 // leaks are found, the process will exit here.
142 __lsan_do_leak_check();
150 virtual ~SuicideOnChannelErrorFilter() {}
155 #if defined(OS_ANDROID)
156 ChildThread
* g_child_thread
= NULL
;
158 // A lock protects g_child_thread.
159 base::LazyInstance
<base::Lock
> g_lazy_child_thread_lock
=
160 LAZY_INSTANCE_INITIALIZER
;
162 // base::ConditionVariable has an explicit constructor that takes
163 // a base::Lock pointer as parameter. The base::DefaultLazyInstanceTraits
164 // doesn't handle the case. Thus, we need our own class here.
165 struct CondVarLazyInstanceTraits
{
166 static const bool kRegisterOnExit
= true;
168 static const bool kAllowedToAccessOnNonjoinableThread
= false;
171 static base::ConditionVariable
* New(void* instance
) {
172 return new (instance
) base::ConditionVariable(
173 g_lazy_child_thread_lock
.Pointer());
175 static void Delete(base::ConditionVariable
* instance
) {
176 instance
->~ConditionVariable();
180 // A condition variable that synchronize threads initializing and waiting
181 // for g_child_thread.
182 base::LazyInstance
<base::ConditionVariable
, CondVarLazyInstanceTraits
>
183 g_lazy_child_thread_cv
= LAZY_INSTANCE_INITIALIZER
;
185 void QuitMainThreadMessageLoop() {
186 base::MessageLoop::current()->Quit();
193 ChildThread::ChildThreadMessageRouter::ChildThreadMessageRouter(
197 bool ChildThread::ChildThreadMessageRouter::Send(IPC::Message
* msg
) {
198 return sender_
->Send(msg
);
201 ChildThread::ChildThread()
203 channel_connected_factory_(this),
204 in_browser_process_(false) {
205 channel_name_
= CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
206 switches::kProcessChannelID
);
210 ChildThread::ChildThread(const std::string
& channel_name
)
211 : channel_name_(channel_name
),
213 channel_connected_factory_(this),
214 in_browser_process_(true) {
218 void ChildThread::Init() {
219 g_lazy_tls
.Pointer()->Set(this);
220 on_channel_error_called_
= false;
221 message_loop_
= base::MessageLoop::current();
222 #ifdef IPC_MESSAGE_LOG_ENABLED
223 // We must make sure to instantiate the IPC Logger *before* we create the
224 // channel, otherwise we can get a callback on the IO thread which creates
225 // the logger, and the logger does not like being created on the IO thread.
226 IPC::Logging::GetInstance();
229 new IPC::SyncChannel(channel_name_
,
230 IPC::Channel::MODE_CLIENT
,
232 ChildProcess::current()->io_message_loop_proxy(),
234 ChildProcess::current()->GetShutDownEvent()));
235 #ifdef IPC_MESSAGE_LOG_ENABLED
236 if (!in_browser_process_
)
237 IPC::Logging::GetInstance()->SetIPCSender(this);
240 mojo_application_
.reset(new MojoApplication(this));
242 sync_message_filter_
=
243 new IPC::SyncMessageFilter(ChildProcess::current()->GetShutDownEvent());
244 thread_safe_sender_
= new ThreadSafeSender(
245 base::MessageLoopProxy::current().get(), sync_message_filter_
.get());
247 resource_dispatcher_
.reset(new ResourceDispatcher(this));
248 socket_stream_dispatcher_
.reset(new SocketStreamDispatcher());
249 websocket_dispatcher_
.reset(new WebSocketDispatcher
);
250 file_system_dispatcher_
.reset(new FileSystemDispatcher());
252 histogram_message_filter_
= new ChildHistogramMessageFilter();
253 resource_message_filter_
=
254 new ChildResourceMessageFilter(resource_dispatcher());
256 service_worker_message_filter_
=
257 new ServiceWorkerMessageFilter(thread_safe_sender_
.get());
258 service_worker_dispatcher_
.reset(
259 new ServiceWorkerDispatcher(thread_safe_sender_
.get()));
261 quota_message_filter_
=
262 new QuotaMessageFilter(thread_safe_sender_
.get());
263 quota_dispatcher_
.reset(new QuotaDispatcher(thread_safe_sender_
.get(),
264 quota_message_filter_
.get()));
266 channel_
->AddFilter(histogram_message_filter_
.get());
267 channel_
->AddFilter(sync_message_filter_
.get());
268 channel_
->AddFilter(new tracing::ChildTraceMessageFilter(
269 ChildProcess::current()->io_message_loop_proxy()));
270 channel_
->AddFilter(resource_message_filter_
.get());
271 channel_
->AddFilter(quota_message_filter_
->GetFilter());
272 channel_
->AddFilter(service_worker_message_filter_
->GetFilter());
274 // In single process mode we may already have a power monitor
275 if (!base::PowerMonitor::Get()) {
276 scoped_ptr
<PowerMonitorBroadcastSource
> power_monitor_source(
277 new PowerMonitorBroadcastSource());
278 channel_
->AddFilter(power_monitor_source
->GetMessageFilter());
280 power_monitor_
.reset(new base::PowerMonitor(
281 power_monitor_source
.PassAs
<base::PowerMonitorSource
>()));
284 #if defined(OS_POSIX)
285 // Check that --process-type is specified so we don't do this in unit tests
286 // and single-process mode.
287 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kProcessType
))
288 channel_
->AddFilter(new SuicideOnChannelErrorFilter());
291 base::MessageLoop::current()->PostDelayedTask(
293 base::Bind(&ChildThread::EnsureConnected
,
294 channel_connected_factory_
.GetWeakPtr()),
295 base::TimeDelta::FromSeconds(kConnectionTimeoutS
));
297 #if defined(OS_ANDROID)
299 base::AutoLock
lock(g_lazy_child_thread_lock
.Get());
300 g_child_thread
= this;
302 // Signalling without locking is fine here because only
303 // one thread can wait on the condition variable.
304 g_lazy_child_thread_cv
.Get().Signal();
307 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
308 trace_memory_controller_
.reset(new base::debug::TraceMemoryController(
309 message_loop_
->message_loop_proxy(),
310 ::HeapProfilerWithPseudoStackStart
,
315 shared_bitmap_manager_
.reset(
316 new ChildSharedBitmapManager(thread_safe_sender()));
319 ChildThread::~ChildThread() {
320 #ifdef IPC_MESSAGE_LOG_ENABLED
321 IPC::Logging::GetInstance()->SetIPCSender(NULL
);
324 channel_
->RemoveFilter(histogram_message_filter_
.get());
325 channel_
->RemoveFilter(sync_message_filter_
.get());
327 // The ChannelProxy object caches a pointer to the IPC thread, so need to
328 // reset it as it's not guaranteed to outlive this object.
329 // NOTE: this also has the side-effect of not closing the main IPC channel to
330 // the browser process. This is needed because this is the signal that the
331 // browser uses to know that this process has died, so we need it to be alive
332 // until this process is shut down, and the OS closes the handle
333 // automatically. We used to watch the object handle on Windows to do this,
334 // but it wasn't possible to do so on POSIX.
335 channel_
->ClearIPCTaskRunner();
336 g_lazy_tls
.Pointer()->Set(NULL
);
339 void ChildThread::Shutdown() {
340 // Delete objects that hold references to blink so derived classes can
341 // safely shutdown blink in their Shutdown implementation.
342 file_system_dispatcher_
.reset();
343 quota_dispatcher_
.reset();
346 void ChildThread::OnChannelConnected(int32 peer_pid
) {
347 channel_connected_factory_
.InvalidateWeakPtrs();
350 void ChildThread::OnChannelError() {
351 set_on_channel_error_called(true);
352 base::MessageLoop::current()->Quit();
355 void ChildThread::AcceptConnection(
356 const mojo::String
& service_name
,
357 mojo::ScopedMessagePipeHandle message_pipe
) {
358 // By default, we don't expect incoming connections.
362 bool ChildThread::Send(IPC::Message
* msg
) {
363 DCHECK(base::MessageLoop::current() == message_loop());
369 return channel_
->Send(msg
);
372 MessageRouter
* ChildThread::GetRouter() {
373 DCHECK(base::MessageLoop::current() == message_loop());
377 webkit_glue::ResourceLoaderBridge
* ChildThread::CreateBridge(
378 const RequestInfo
& request_info
) {
379 return resource_dispatcher()->CreateBridge(request_info
);
382 base::SharedMemory
* ChildThread::AllocateSharedMemory(size_t buf_size
) {
383 return AllocateSharedMemory(buf_size
, this);
387 base::SharedMemory
* ChildThread::AllocateSharedMemory(
389 IPC::Sender
* sender
) {
390 scoped_ptr
<base::SharedMemory
> shared_buf
;
392 shared_buf
.reset(new base::SharedMemory
);
393 if (!shared_buf
->CreateAndMapAnonymous(buf_size
)) {
398 // On POSIX, we need to ask the browser to create the shared memory for us,
399 // since this is blocked by the sandbox.
400 base::SharedMemoryHandle shared_mem_handle
;
401 if (sender
->Send(new ChildProcessHostMsg_SyncAllocateSharedMemory(
402 buf_size
, &shared_mem_handle
))) {
403 if (base::SharedMemory::IsHandleValid(shared_mem_handle
)) {
404 shared_buf
.reset(new base::SharedMemory(shared_mem_handle
, false));
405 if (!shared_buf
->Map(buf_size
)) {
406 NOTREACHED() << "Map failed";
410 NOTREACHED() << "Browser failed to allocate shared memory";
414 NOTREACHED() << "Browser allocation request message failed";
418 return shared_buf
.release();
421 bool ChildThread::OnMessageReceived(const IPC::Message
& msg
) {
422 if (mojo_application_
->OnMessageReceived(msg
))
425 // Resource responses are sent to the resource dispatcher.
426 if (resource_dispatcher_
->OnMessageReceived(msg
))
428 if (socket_stream_dispatcher_
->OnMessageReceived(msg
))
430 if (websocket_dispatcher_
->OnMessageReceived(msg
))
432 if (file_system_dispatcher_
->OnMessageReceived(msg
))
436 IPC_BEGIN_MESSAGE_MAP(ChildThread
, msg
)
437 IPC_MESSAGE_HANDLER(ChildProcessMsg_Shutdown
, OnShutdown
)
438 #if defined(IPC_MESSAGE_LOG_ENABLED)
439 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetIPCLoggingEnabled
,
440 OnSetIPCLoggingEnabled
)
442 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetProfilerStatus
,
444 IPC_MESSAGE_HANDLER(ChildProcessMsg_GetChildProfilerData
,
445 OnGetChildProfilerData
)
446 IPC_MESSAGE_HANDLER(ChildProcessMsg_DumpHandles
, OnDumpHandles
)
447 #if defined(USE_TCMALLOC)
448 IPC_MESSAGE_HANDLER(ChildProcessMsg_GetTcmallocStats
, OnGetTcmallocStats
)
450 IPC_MESSAGE_UNHANDLED(handled
= false)
451 IPC_END_MESSAGE_MAP()
456 if (msg
.routing_id() == MSG_ROUTING_CONTROL
)
457 return OnControlMessageReceived(msg
);
459 return router_
.OnMessageReceived(msg
);
462 bool ChildThread::OnControlMessageReceived(const IPC::Message
& msg
) {
466 void ChildThread::OnShutdown() {
467 base::MessageLoop::current()->Quit();
470 #if defined(IPC_MESSAGE_LOG_ENABLED)
471 void ChildThread::OnSetIPCLoggingEnabled(bool enable
) {
473 IPC::Logging::GetInstance()->Enable();
475 IPC::Logging::GetInstance()->Disable();
477 #endif // IPC_MESSAGE_LOG_ENABLED
479 void ChildThread::OnSetProfilerStatus(ThreadData::Status status
) {
480 ThreadData::InitializeAndSetTrackingStatus(status
);
483 void ChildThread::OnGetChildProfilerData(int sequence_number
) {
484 tracked_objects::ProcessDataSnapshot process_data
;
485 ThreadData::Snapshot(false, &process_data
);
487 Send(new ChildProcessHostMsg_ChildProfilerData(sequence_number
,
491 void ChildThread::OnDumpHandles() {
493 scoped_refptr
<HandleEnumerator
> handle_enum(
494 new HandleEnumerator(
495 CommandLine::ForCurrentProcess()->HasSwitch(
496 switches::kAuditAllHandles
)));
497 handle_enum
->EnumerateHandles();
498 Send(new ChildProcessHostMsg_DumpHandlesDone
);
504 #if defined(USE_TCMALLOC)
505 void ChildThread::OnGetTcmallocStats() {
507 char buffer
[1024 * 32];
508 base::allocator::GetStats(buffer
, sizeof(buffer
));
509 result
.append(buffer
);
510 Send(new ChildProcessHostMsg_TcmallocStats(result
));
514 ChildThread
* ChildThread::current() {
515 return g_lazy_tls
.Pointer()->Get();
518 #if defined(OS_ANDROID)
519 // The method must NOT be called on the child thread itself.
520 // It may block the child thread if so.
521 void ChildThread::ShutdownThread() {
522 DCHECK(!ChildThread::current()) <<
523 "this method should NOT be called from child thread itself";
525 base::AutoLock
lock(g_lazy_child_thread_lock
.Get());
526 while (!g_child_thread
)
527 g_lazy_child_thread_cv
.Get().Wait();
529 DCHECK_NE(base::MessageLoop::current(), g_child_thread
->message_loop());
530 g_child_thread
->message_loop()->PostTask(
531 FROM_HERE
, base::Bind(&QuitMainThreadMessageLoop
));
535 void ChildThread::OnProcessFinalRelease() {
536 if (on_channel_error_called_
) {
537 base::MessageLoop::current()->Quit();
541 // The child process shutdown sequence is a request response based mechanism,
542 // where we send out an initial feeler request to the child process host
543 // instance in the browser to verify if it's ok to shutdown the child process.
544 // The browser then sends back a response if it's ok to shutdown. This avoids
545 // race conditions if the process refcount is 0 but there's an IPC message
546 // inflight that would addref it.
547 Send(new ChildProcessHostMsg_ShutdownRequest
);
550 void ChildThread::EnsureConnected() {
551 VLOG(0) << "ChildThread::EnsureConnected()";
552 base::KillProcess(base::GetCurrentProcessHandle(), 0, false);
555 } // namespace content