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/power_monitor_broadcast_source.h"
33 #include "content/child/quota_dispatcher.h"
34 #include "content/child/quota_message_filter.h"
35 #include "content/child/resource_dispatcher.h"
36 #include "content/child/service_worker/service_worker_dispatcher.h"
37 #include "content/child/service_worker/service_worker_message_filter.h"
38 #include "content/child/socket_stream_dispatcher.h"
39 #include "content/child/thread_safe_sender.h"
40 #include "content/child/websocket_dispatcher.h"
41 #include "content/common/child_process_messages.h"
42 #include "content/public/common/content_switches.h"
43 #include "ipc/ipc_logging.h"
44 #include "ipc/ipc_switches.h"
45 #include "ipc/ipc_sync_channel.h"
46 #include "ipc/ipc_sync_message_filter.h"
49 #include "content/common/handle_enumerator_win.h"
52 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
53 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
56 using tracked_objects::ThreadData
;
61 // How long to wait for a connection to the browser process before giving up.
62 const int kConnectionTimeoutS
= 15;
64 base::LazyInstance
<base::ThreadLocalPointer
<ChildThread
> > g_lazy_tls
=
65 LAZY_INSTANCE_INITIALIZER
;
67 // This isn't needed on Windows because there the sandbox's job object
68 // terminates child processes automatically. For unsandboxed processes (i.e.
69 // plugins), PluginThread has EnsureTerminateMessageFilter.
72 // A thread delegate that waits for |duration| and then signals the process
74 class WaitAndExitDelegate
: public base::PlatformThread::Delegate
{
76 explicit WaitAndExitDelegate(base::TimeDelta duration
)
77 : duration_(duration
) {}
78 virtual ~WaitAndExitDelegate() OVERRIDE
{}
80 virtual void ThreadMain() OVERRIDE
{
81 base::PlatformThread::Sleep(duration_
);
82 // This used to be implemented with alarm(2). Make sure to not break
83 // anything that requires the process being signaled.
84 CHECK_EQ(0, raise(SIGALRM
));
86 base::PlatformThread::Sleep((base::TimeDelta::FromSeconds(10)));
87 // If something erroneously blocked SIGALRM, this will trigger.
93 const base::TimeDelta duration_
;
94 DISALLOW_COPY_AND_ASSIGN(WaitAndExitDelegate
);
97 // This is similar to using alarm(2), except it will spawn a thread
98 // which will sleep for |duration| before raising SIGALRM.
99 bool CreateAlarmThread(base::TimeDelta duration
) {
100 scoped_ptr
<WaitAndExitDelegate
> delegate(new WaitAndExitDelegate(duration
));
102 const bool thread_created
= base::PlatformThread::CreateNonJoinable(
103 0 /* stack_size */, delegate
.get());
107 // A non joinable thread has been created. The thread will either terminate
108 // the process or will be terminated by the process. Therefore, keep the
109 // delegate object alive for the lifetime of the process.
110 WaitAndExitDelegate
* leaking_delegate
= delegate
.release();
111 ANNOTATE_LEAKING_OBJECT_PTR(leaking_delegate
);
112 ignore_result(leaking_delegate
);
116 class SuicideOnChannelErrorFilter
: public IPC::ChannelProxy::MessageFilter
{
118 // IPC::ChannelProxy::MessageFilter
119 virtual void OnChannelError() OVERRIDE
{
120 // For renderer/worker processes:
121 // On POSIX, at least, one can install an unload handler which loops
122 // forever and leave behind a renderer process which eats 100% CPU forever.
124 // This is because the terminate signals (ViewMsg_ShouldClose and the error
125 // from the IPC channel) are routed to the main message loop but never
126 // processed (because that message loop is stuck in V8).
128 // One could make the browser SIGKILL the renderers, but that leaves open a
129 // large window where a browser failure (or a user, manually terminating
130 // the browser because "it's stuck") will leave behind a process eating all
133 // So, we install a filter on the channel so that we can process this event
134 // here and kill the process.
135 if (CommandLine::ForCurrentProcess()->
136 HasSwitch(switches::kChildCleanExit
)) {
137 // If clean exit is requested, we want to kill this process after giving
138 // it 60 seconds to run exit handlers. Exit handlers may including ones
139 // that write profile data to disk (which happens under profile collection
141 CHECK(CreateAlarmThread(base::TimeDelta::FromSeconds(60)));
142 #if defined(LEAK_SANITIZER)
143 // Invoke LeakSanitizer early to avoid detecting shutdown-only leaks. If
144 // leaks are found, the process will exit here.
145 __lsan_do_leak_check();
153 virtual ~SuicideOnChannelErrorFilter() {}
158 #if defined(OS_ANDROID)
159 ChildThread
* g_child_thread
= NULL
;
161 // A lock protects g_child_thread.
162 base::LazyInstance
<base::Lock
> g_lazy_child_thread_lock
=
163 LAZY_INSTANCE_INITIALIZER
;
165 // base::ConditionVariable has an explicit constructor that takes
166 // a base::Lock pointer as parameter. The base::DefaultLazyInstanceTraits
167 // doesn't handle the case. Thus, we need our own class here.
168 struct CondVarLazyInstanceTraits
{
169 static const bool kRegisterOnExit
= true;
171 static const bool kAllowedToAccessOnNonjoinableThread
= false;
174 static base::ConditionVariable
* New(void* instance
) {
175 return new (instance
) base::ConditionVariable(
176 g_lazy_child_thread_lock
.Pointer());
178 static void Delete(base::ConditionVariable
* instance
) {
179 instance
->~ConditionVariable();
183 // A condition variable that synchronize threads initializing and waiting
184 // for g_child_thread.
185 base::LazyInstance
<base::ConditionVariable
, CondVarLazyInstanceTraits
>
186 g_lazy_child_thread_cv
= LAZY_INSTANCE_INITIALIZER
;
188 void QuitMainThreadMessageLoop() {
189 base::MessageLoop::current()->Quit();
196 ChildThread::ChildThreadMessageRouter::ChildThreadMessageRouter(
200 bool ChildThread::ChildThreadMessageRouter::Send(IPC::Message
* msg
) {
201 return sender_
->Send(msg
);
204 ChildThread::ChildThread()
206 channel_connected_factory_(this),
207 in_browser_process_(false) {
208 channel_name_
= CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
209 switches::kProcessChannelID
);
213 ChildThread::ChildThread(const std::string
& channel_name
)
214 : channel_name_(channel_name
),
216 channel_connected_factory_(this),
217 in_browser_process_(true) {
221 void ChildThread::Init() {
222 g_lazy_tls
.Pointer()->Set(this);
223 on_channel_error_called_
= false;
224 message_loop_
= base::MessageLoop::current();
225 #ifdef IPC_MESSAGE_LOG_ENABLED
226 // We must make sure to instantiate the IPC Logger *before* we create the
227 // channel, otherwise we can get a callback on the IO thread which creates
228 // the logger, and the logger does not like being created on the IO thread.
229 IPC::Logging::GetInstance();
232 new IPC::SyncChannel(channel_name_
,
233 IPC::Channel::MODE_CLIENT
,
235 ChildProcess::current()->io_message_loop_proxy(),
237 ChildProcess::current()->GetShutDownEvent()));
238 #ifdef IPC_MESSAGE_LOG_ENABLED
239 if (!in_browser_process_
)
240 IPC::Logging::GetInstance()->SetIPCSender(this);
243 sync_message_filter_
=
244 new IPC::SyncMessageFilter(ChildProcess::current()->GetShutDownEvent());
245 thread_safe_sender_
= new ThreadSafeSender(
246 base::MessageLoopProxy::current().get(), sync_message_filter_
.get());
248 resource_dispatcher_
.reset(new ResourceDispatcher(this));
249 socket_stream_dispatcher_
.reset(new SocketStreamDispatcher());
250 websocket_dispatcher_
.reset(new WebSocketDispatcher
);
251 file_system_dispatcher_
.reset(new FileSystemDispatcher());
253 histogram_message_filter_
= new ChildHistogramMessageFilter();
254 resource_message_filter_
=
255 new ChildResourceMessageFilter(resource_dispatcher());
257 service_worker_message_filter_
=
258 new ServiceWorkerMessageFilter(thread_safe_sender_
.get());
259 service_worker_dispatcher_
.reset(
260 new ServiceWorkerDispatcher(thread_safe_sender_
.get()));
262 quota_message_filter_
=
263 new QuotaMessageFilter(thread_safe_sender_
.get());
264 quota_dispatcher_
.reset(new QuotaDispatcher(thread_safe_sender_
.get(),
265 quota_message_filter_
.get()));
267 channel_
->AddFilter(histogram_message_filter_
.get());
268 channel_
->AddFilter(sync_message_filter_
.get());
269 channel_
->AddFilter(new tracing::ChildTraceMessageFilter(
270 ChildProcess::current()->io_message_loop_proxy()));
271 channel_
->AddFilter(resource_message_filter_
.get());
272 channel_
->AddFilter(quota_message_filter_
->GetFilter());
273 channel_
->AddFilter(service_worker_message_filter_
->GetFilter());
275 // In single process mode we may already have a power monitor
276 if (!base::PowerMonitor::Get()) {
277 scoped_ptr
<PowerMonitorBroadcastSource
> power_monitor_source(
278 new PowerMonitorBroadcastSource());
279 channel_
->AddFilter(power_monitor_source
->GetMessageFilter());
281 power_monitor_
.reset(new base::PowerMonitor(
282 power_monitor_source
.PassAs
<base::PowerMonitorSource
>()));
285 #if defined(OS_POSIX)
286 // Check that --process-type is specified so we don't do this in unit tests
287 // and single-process mode.
288 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kProcessType
))
289 channel_
->AddFilter(new SuicideOnChannelErrorFilter());
292 base::MessageLoop::current()->PostDelayedTask(
294 base::Bind(&ChildThread::EnsureConnected
,
295 channel_connected_factory_
.GetWeakPtr()),
296 base::TimeDelta::FromSeconds(kConnectionTimeoutS
));
298 #if defined(OS_ANDROID)
300 base::AutoLock
lock(g_lazy_child_thread_lock
.Get());
301 g_child_thread
= this;
303 // Signalling without locking is fine here because only
304 // one thread can wait on the condition variable.
305 g_lazy_child_thread_cv
.Get().Signal();
308 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
309 trace_memory_controller_
.reset(new base::debug::TraceMemoryController(
310 message_loop_
->message_loop_proxy(),
311 ::HeapProfilerWithPseudoStackStart
,
316 shared_bitmap_manager_
.reset(
317 new ChildSharedBitmapManager(thread_safe_sender()));
320 ChildThread::~ChildThread() {
321 #ifdef IPC_MESSAGE_LOG_ENABLED
322 IPC::Logging::GetInstance()->SetIPCSender(NULL
);
325 channel_
->RemoveFilter(histogram_message_filter_
.get());
326 channel_
->RemoveFilter(sync_message_filter_
.get());
328 // The ChannelProxy object caches a pointer to the IPC thread, so need to
329 // reset it as it's not guaranteed to outlive this object.
330 // NOTE: this also has the side-effect of not closing the main IPC channel to
331 // the browser process. This is needed because this is the signal that the
332 // browser uses to know that this process has died, so we need it to be alive
333 // until this process is shut down, and the OS closes the handle
334 // automatically. We used to watch the object handle on Windows to do this,
335 // but it wasn't possible to do so on POSIX.
336 channel_
->ClearIPCTaskRunner();
337 g_lazy_tls
.Pointer()->Set(NULL
);
340 void ChildThread::Shutdown() {
341 // Delete objects that hold references to blink so derived classes can
342 // safely shutdown blink in their Shutdown implementation.
343 file_system_dispatcher_
.reset();
344 quota_dispatcher_
.reset();
347 void ChildThread::OnChannelConnected(int32 peer_pid
) {
348 channel_connected_factory_
.InvalidateWeakPtrs();
351 void ChildThread::OnChannelError() {
352 set_on_channel_error_called(true);
353 base::MessageLoop::current()->Quit();
356 bool ChildThread::Send(IPC::Message
* msg
) {
357 DCHECK(base::MessageLoop::current() == message_loop());
363 return channel_
->Send(msg
);
366 MessageRouter
* ChildThread::GetRouter() {
367 DCHECK(base::MessageLoop::current() == message_loop());
371 webkit_glue::ResourceLoaderBridge
* ChildThread::CreateBridge(
372 const webkit_glue::ResourceLoaderBridge::RequestInfo
& request_info
) {
373 return resource_dispatcher()->CreateBridge(request_info
);
376 base::SharedMemory
* ChildThread::AllocateSharedMemory(size_t buf_size
) {
377 return AllocateSharedMemory(buf_size
, this);
381 base::SharedMemory
* ChildThread::AllocateSharedMemory(
383 IPC::Sender
* sender
) {
384 scoped_ptr
<base::SharedMemory
> shared_buf
;
386 shared_buf
.reset(new base::SharedMemory
);
387 if (!shared_buf
->CreateAndMapAnonymous(buf_size
)) {
392 // On POSIX, we need to ask the browser to create the shared memory for us,
393 // since this is blocked by the sandbox.
394 base::SharedMemoryHandle shared_mem_handle
;
395 if (sender
->Send(new ChildProcessHostMsg_SyncAllocateSharedMemory(
396 buf_size
, &shared_mem_handle
))) {
397 if (base::SharedMemory::IsHandleValid(shared_mem_handle
)) {
398 shared_buf
.reset(new base::SharedMemory(shared_mem_handle
, false));
399 if (!shared_buf
->Map(buf_size
)) {
400 NOTREACHED() << "Map failed";
404 NOTREACHED() << "Browser failed to allocate shared memory";
408 NOTREACHED() << "Browser allocation request message failed";
412 return shared_buf
.release();
415 bool ChildThread::OnMessageReceived(const IPC::Message
& msg
) {
416 // Resource responses are sent to the resource dispatcher.
417 if (resource_dispatcher_
->OnMessageReceived(msg
))
419 if (socket_stream_dispatcher_
->OnMessageReceived(msg
))
421 if (websocket_dispatcher_
->OnMessageReceived(msg
))
423 if (file_system_dispatcher_
->OnMessageReceived(msg
))
427 IPC_BEGIN_MESSAGE_MAP(ChildThread
, msg
)
428 IPC_MESSAGE_HANDLER(ChildProcessMsg_Shutdown
, OnShutdown
)
429 #if defined(IPC_MESSAGE_LOG_ENABLED)
430 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetIPCLoggingEnabled
,
431 OnSetIPCLoggingEnabled
)
433 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetProfilerStatus
,
435 IPC_MESSAGE_HANDLER(ChildProcessMsg_GetChildProfilerData
,
436 OnGetChildProfilerData
)
437 IPC_MESSAGE_HANDLER(ChildProcessMsg_DumpHandles
, OnDumpHandles
)
438 #if defined(USE_TCMALLOC)
439 IPC_MESSAGE_HANDLER(ChildProcessMsg_GetTcmallocStats
, OnGetTcmallocStats
)
441 IPC_MESSAGE_UNHANDLED(handled
= false)
442 IPC_END_MESSAGE_MAP()
447 if (msg
.routing_id() == MSG_ROUTING_CONTROL
)
448 return OnControlMessageReceived(msg
);
450 return router_
.OnMessageReceived(msg
);
453 bool ChildThread::OnControlMessageReceived(const IPC::Message
& msg
) {
457 void ChildThread::OnShutdown() {
458 base::MessageLoop::current()->Quit();
461 #if defined(IPC_MESSAGE_LOG_ENABLED)
462 void ChildThread::OnSetIPCLoggingEnabled(bool enable
) {
464 IPC::Logging::GetInstance()->Enable();
466 IPC::Logging::GetInstance()->Disable();
468 #endif // IPC_MESSAGE_LOG_ENABLED
470 void ChildThread::OnSetProfilerStatus(ThreadData::Status status
) {
471 ThreadData::InitializeAndSetTrackingStatus(status
);
474 void ChildThread::OnGetChildProfilerData(int sequence_number
) {
475 tracked_objects::ProcessDataSnapshot process_data
;
476 ThreadData::Snapshot(false, &process_data
);
478 Send(new ChildProcessHostMsg_ChildProfilerData(sequence_number
,
482 void ChildThread::OnDumpHandles() {
484 scoped_refptr
<HandleEnumerator
> handle_enum(
485 new HandleEnumerator(
486 CommandLine::ForCurrentProcess()->HasSwitch(
487 switches::kAuditAllHandles
)));
488 handle_enum
->EnumerateHandles();
489 Send(new ChildProcessHostMsg_DumpHandlesDone
);
495 #if defined(USE_TCMALLOC)
496 void ChildThread::OnGetTcmallocStats() {
498 char buffer
[1024 * 32];
499 base::allocator::GetStats(buffer
, sizeof(buffer
));
500 result
.append(buffer
);
501 Send(new ChildProcessHostMsg_TcmallocStats(result
));
505 ChildThread
* ChildThread::current() {
506 return g_lazy_tls
.Pointer()->Get();
509 #if defined(OS_ANDROID)
510 // The method must NOT be called on the child thread itself.
511 // It may block the child thread if so.
512 void ChildThread::ShutdownThread() {
513 DCHECK(!ChildThread::current()) <<
514 "this method should NOT be called from child thread itself";
516 base::AutoLock
lock(g_lazy_child_thread_lock
.Get());
517 while (!g_child_thread
)
518 g_lazy_child_thread_cv
.Get().Wait();
520 DCHECK_NE(base::MessageLoop::current(), g_child_thread
->message_loop());
521 g_child_thread
->message_loop()->PostTask(
522 FROM_HERE
, base::Bind(&QuitMainThreadMessageLoop
));
526 void ChildThread::OnProcessFinalRelease() {
527 if (on_channel_error_called_
) {
528 base::MessageLoop::current()->Quit();
532 // The child process shutdown sequence is a request response based mechanism,
533 // where we send out an initial feeler request to the child process host
534 // instance in the browser to verify if it's ok to shutdown the child process.
535 // The browser then sends back a response if it's ok to shutdown. This avoids
536 // race conditions if the process refcount is 0 but there's an IPC message
537 // inflight that would addref it.
538 Send(new ChildProcessHostMsg_ShutdownRequest
);
541 void ChildThread::EnsureConnected() {
542 VLOG(0) << "ChildThread::EnsureConnected()";
543 base::KillProcess(base::GetCurrentProcessHandle(), 0, false);
546 } // namespace content