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"
47 #include "webkit/child/resource_loader_bridge.h"
50 #include "content/common/handle_enumerator_win.h"
53 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
54 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
57 using tracked_objects::ThreadData;
62 // How long to wait for a connection to the browser process before giving up.
63 const int kConnectionTimeoutS = 15;
65 base::LazyInstance<base::ThreadLocalPointer<ChildThread> > g_lazy_tls =
66 LAZY_INSTANCE_INITIALIZER;
68 // This isn't needed on Windows because there the sandbox's job object
69 // terminates child processes automatically. For unsandboxed processes (i.e.
70 // plugins), PluginThread has EnsureTerminateMessageFilter.
73 // A thread delegate that waits for |duration| and then signals the process
75 class WaitAndExitDelegate : public base::PlatformThread::Delegate {
77 explicit WaitAndExitDelegate(base::TimeDelta duration)
78 : duration_(duration) {}
79 virtual ~WaitAndExitDelegate() OVERRIDE {}
81 virtual void ThreadMain() OVERRIDE {
82 base::PlatformThread::Sleep(duration_);
83 // This used to be implemented with alarm(2). Make sure to not break
84 // anything that requires the process being signaled.
85 CHECK_EQ(0, raise(SIGALRM));
87 base::PlatformThread::Sleep((base::TimeDelta::FromSeconds(10)));
88 // If something erroneously blocked SIGALRM, this will trigger.
94 const base::TimeDelta duration_;
95 DISALLOW_COPY_AND_ASSIGN(WaitAndExitDelegate);
98 // This is similar to using alarm(2), except it will spawn a thread
99 // which will sleep for |duration| before raising SIGALRM.
100 bool CreateAlarmThread(base::TimeDelta duration) {
101 scoped_ptr<WaitAndExitDelegate> delegate(new WaitAndExitDelegate(duration));
103 const bool thread_created = base::PlatformThread::CreateNonJoinable(
104 0 /* stack_size */, delegate.get());
108 // A non joinable thread has been created. The thread will either terminate
109 // the process or will be terminated by the process. Therefore, keep the
110 // delegate object alive for the lifetime of the process.
111 WaitAndExitDelegate* leaking_delegate = delegate.release();
112 ANNOTATE_LEAKING_OBJECT_PTR(leaking_delegate);
113 ignore_result(leaking_delegate);
117 class SuicideOnChannelErrorFilter : public IPC::ChannelProxy::MessageFilter {
119 // IPC::ChannelProxy::MessageFilter
120 virtual void OnChannelError() OVERRIDE {
121 // For renderer/worker processes:
122 // On POSIX, at least, one can install an unload handler which loops
123 // forever and leave behind a renderer process which eats 100% CPU forever.
125 // This is because the terminate signals (ViewMsg_ShouldClose and the error
126 // from the IPC channel) are routed to the main message loop but never
127 // processed (because that message loop is stuck in V8).
129 // One could make the browser SIGKILL the renderers, but that leaves open a
130 // large window where a browser failure (or a user, manually terminating
131 // the browser because "it's stuck") will leave behind a process eating all
134 // So, we install a filter on the channel so that we can process this event
135 // here and kill the process.
136 if (CommandLine::ForCurrentProcess()->
137 HasSwitch(switches::kChildCleanExit)) {
138 // If clean exit is requested, we want to kill this process after giving
139 // it 60 seconds to run exit handlers. Exit handlers may including ones
140 // that write profile data to disk (which happens under profile collection
142 CHECK(CreateAlarmThread(base::TimeDelta::FromSeconds(60)));
143 #if defined(LEAK_SANITIZER)
144 // Invoke LeakSanitizer early to avoid detecting shutdown-only leaks. If
145 // leaks are found, the process will exit here.
146 __lsan_do_leak_check();
154 virtual ~SuicideOnChannelErrorFilter() {}
159 #if defined(OS_ANDROID)
160 ChildThread* g_child_thread = NULL;
162 // A lock protects g_child_thread.
163 base::LazyInstance<base::Lock> g_lazy_child_thread_lock =
164 LAZY_INSTANCE_INITIALIZER;
166 // base::ConditionVariable has an explicit constructor that takes
167 // a base::Lock pointer as parameter. The base::DefaultLazyInstanceTraits
168 // doesn't handle the case. Thus, we need our own class here.
169 struct CondVarLazyInstanceTraits {
170 static const bool kRegisterOnExit = true;
172 static const bool kAllowedToAccessOnNonjoinableThread = false;
175 static base::ConditionVariable* New(void* instance) {
176 return new (instance) base::ConditionVariable(
177 g_lazy_child_thread_lock.Pointer());
179 static void Delete(base::ConditionVariable* instance) {
180 instance->~ConditionVariable();
184 // A condition variable that synchronize threads initializing and waiting
185 // for g_child_thread.
186 base::LazyInstance<base::ConditionVariable, CondVarLazyInstanceTraits>
187 g_lazy_child_thread_cv = LAZY_INSTANCE_INITIALIZER;
189 void QuitMainThreadMessageLoop() {
190 base::MessageLoop::current()->Quit();
197 ChildThread::ChildThreadMessageRouter::ChildThreadMessageRouter(
201 bool ChildThread::ChildThreadMessageRouter::Send(IPC::Message* msg) {
202 return sender_->Send(msg);
205 ChildThread::ChildThread()
207 channel_connected_factory_(this),
208 in_browser_process_(false) {
209 channel_name_ = CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
210 switches::kProcessChannelID);
214 ChildThread::ChildThread(const std::string& channel_name)
215 : channel_name_(channel_name),
217 channel_connected_factory_(this),
218 in_browser_process_(true) {
222 void ChildThread::Init() {
223 g_lazy_tls.Pointer()->Set(this);
224 on_channel_error_called_ = false;
225 message_loop_ = base::MessageLoop::current();
226 #ifdef IPC_MESSAGE_LOG_ENABLED
227 // We must make sure to instantiate the IPC Logger *before* we create the
228 // channel, otherwise we can get a callback on the IO thread which creates
229 // the logger, and the logger does not like being created on the IO thread.
230 IPC::Logging::GetInstance();
233 new IPC::SyncChannel(channel_name_,
234 IPC::Channel::MODE_CLIENT,
236 ChildProcess::current()->io_message_loop_proxy(),
238 ChildProcess::current()->GetShutDownEvent()));
239 #ifdef IPC_MESSAGE_LOG_ENABLED
240 if (!in_browser_process_)
241 IPC::Logging::GetInstance()->SetIPCSender(this);
244 sync_message_filter_ =
245 new IPC::SyncMessageFilter(ChildProcess::current()->GetShutDownEvent());
246 thread_safe_sender_ = new ThreadSafeSender(
247 base::MessageLoopProxy::current().get(), sync_message_filter_.get());
249 resource_dispatcher_.reset(new ResourceDispatcher(this));
250 socket_stream_dispatcher_.reset(new SocketStreamDispatcher());
251 websocket_dispatcher_.reset(new WebSocketDispatcher);
252 file_system_dispatcher_.reset(new FileSystemDispatcher());
254 histogram_message_filter_ = new ChildHistogramMessageFilter();
255 resource_message_filter_ =
256 new ChildResourceMessageFilter(resource_dispatcher());
258 service_worker_message_filter_ =
259 new ServiceWorkerMessageFilter(thread_safe_sender_.get());
260 service_worker_dispatcher_.reset(
261 new ServiceWorkerDispatcher(thread_safe_sender_.get()));
263 quota_message_filter_ =
264 new QuotaMessageFilter(thread_safe_sender_.get());
265 quota_dispatcher_.reset(new QuotaDispatcher(thread_safe_sender_.get(),
266 quota_message_filter_.get()));
268 channel_->AddFilter(histogram_message_filter_.get());
269 channel_->AddFilter(sync_message_filter_.get());
270 channel_->AddFilter(new tracing::ChildTraceMessageFilter(
271 ChildProcess::current()->io_message_loop_proxy()));
272 channel_->AddFilter(resource_message_filter_.get());
273 channel_->AddFilter(quota_message_filter_->GetFilter());
274 channel_->AddFilter(service_worker_message_filter_->GetFilter());
276 // In single process mode we may already have a power monitor
277 if (!base::PowerMonitor::Get()) {
278 scoped_ptr<PowerMonitorBroadcastSource> power_monitor_source(
279 new PowerMonitorBroadcastSource());
280 channel_->AddFilter(power_monitor_source->GetMessageFilter());
282 power_monitor_.reset(new base::PowerMonitor(
283 power_monitor_source.PassAs<base::PowerMonitorSource>()));
286 #if defined(OS_POSIX)
287 // Check that --process-type is specified so we don't do this in unit tests
288 // and single-process mode.
289 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kProcessType))
290 channel_->AddFilter(new SuicideOnChannelErrorFilter());
293 base::MessageLoop::current()->PostDelayedTask(
295 base::Bind(&ChildThread::EnsureConnected,
296 channel_connected_factory_.GetWeakPtr()),
297 base::TimeDelta::FromSeconds(kConnectionTimeoutS));
299 #if defined(OS_ANDROID)
301 base::AutoLock lock(g_lazy_child_thread_lock.Get());
302 g_child_thread = this;
304 // Signalling without locking is fine here because only
305 // one thread can wait on the condition variable.
306 g_lazy_child_thread_cv.Get().Signal();
309 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
310 trace_memory_controller_.reset(new base::debug::TraceMemoryController(
311 message_loop_->message_loop_proxy(),
312 ::HeapProfilerWithPseudoStackStart,
317 shared_bitmap_manager_.reset(
318 new ChildSharedBitmapManager(thread_safe_sender()));
321 ChildThread::~ChildThread() {
322 #ifdef IPC_MESSAGE_LOG_ENABLED
323 IPC::Logging::GetInstance()->SetIPCSender(NULL);
326 channel_->RemoveFilter(histogram_message_filter_.get());
327 channel_->RemoveFilter(sync_message_filter_.get());
329 // The ChannelProxy object caches a pointer to the IPC thread, so need to
330 // reset it as it's not guaranteed to outlive this object.
331 // NOTE: this also has the side-effect of not closing the main IPC channel to
332 // the browser process. This is needed because this is the signal that the
333 // browser uses to know that this process has died, so we need it to be alive
334 // until this process is shut down, and the OS closes the handle
335 // automatically. We used to watch the object handle on Windows to do this,
336 // but it wasn't possible to do so on POSIX.
337 channel_->ClearIPCTaskRunner();
338 g_lazy_tls.Pointer()->Set(NULL);
341 void ChildThread::Shutdown() {
342 // Delete objects that hold references to blink so derived classes can
343 // safely shutdown blink in their Shutdown implementation.
344 file_system_dispatcher_.reset();
345 quota_dispatcher_.reset();
348 void ChildThread::OnChannelConnected(int32 peer_pid) {
349 channel_connected_factory_.InvalidateWeakPtrs();
352 void ChildThread::OnChannelError() {
353 set_on_channel_error_called(true);
354 base::MessageLoop::current()->Quit();
357 bool ChildThread::Send(IPC::Message* msg) {
358 DCHECK(base::MessageLoop::current() == message_loop());
364 return channel_->Send(msg);
367 MessageRouter* ChildThread::GetRouter() {
368 DCHECK(base::MessageLoop::current() == message_loop());
372 webkit_glue::ResourceLoaderBridge* ChildThread::CreateBridge(
373 const RequestInfo& request_info) {
374 return resource_dispatcher()->CreateBridge(request_info);
377 base::SharedMemory* ChildThread::AllocateSharedMemory(size_t buf_size) {
378 return AllocateSharedMemory(buf_size, this);
382 base::SharedMemory* ChildThread::AllocateSharedMemory(
384 IPC::Sender* sender) {
385 scoped_ptr<base::SharedMemory> shared_buf;
387 shared_buf.reset(new base::SharedMemory);
388 if (!shared_buf->CreateAndMapAnonymous(buf_size)) {
393 // On POSIX, we need to ask the browser to create the shared memory for us,
394 // since this is blocked by the sandbox.
395 base::SharedMemoryHandle shared_mem_handle;
396 if (sender->Send(new ChildProcessHostMsg_SyncAllocateSharedMemory(
397 buf_size, &shared_mem_handle))) {
398 if (base::SharedMemory::IsHandleValid(shared_mem_handle)) {
399 shared_buf.reset(new base::SharedMemory(shared_mem_handle, false));
400 if (!shared_buf->Map(buf_size)) {
401 NOTREACHED() << "Map failed";
405 NOTREACHED() << "Browser failed to allocate shared memory";
409 NOTREACHED() << "Browser allocation request message failed";
413 return shared_buf.release();
416 bool ChildThread::OnMessageReceived(const IPC::Message& msg) {
417 // Resource responses are sent to the resource dispatcher.
418 if (resource_dispatcher_->OnMessageReceived(msg))
420 if (socket_stream_dispatcher_->OnMessageReceived(msg))
422 if (websocket_dispatcher_->OnMessageReceived(msg))
424 if (file_system_dispatcher_->OnMessageReceived(msg))
428 IPC_BEGIN_MESSAGE_MAP(ChildThread, msg)
429 IPC_MESSAGE_HANDLER(ChildProcessMsg_Shutdown, OnShutdown)
430 #if defined(IPC_MESSAGE_LOG_ENABLED)
431 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetIPCLoggingEnabled,
432 OnSetIPCLoggingEnabled)
434 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetProfilerStatus,
436 IPC_MESSAGE_HANDLER(ChildProcessMsg_GetChildProfilerData,
437 OnGetChildProfilerData)
438 IPC_MESSAGE_HANDLER(ChildProcessMsg_DumpHandles, OnDumpHandles)
439 #if defined(USE_TCMALLOC)
440 IPC_MESSAGE_HANDLER(ChildProcessMsg_GetTcmallocStats, OnGetTcmallocStats)
442 IPC_MESSAGE_UNHANDLED(handled = false)
443 IPC_END_MESSAGE_MAP()
448 if (msg.routing_id() == MSG_ROUTING_CONTROL)
449 return OnControlMessageReceived(msg);
451 return router_.OnMessageReceived(msg);
454 bool ChildThread::OnControlMessageReceived(const IPC::Message& msg) {
458 void ChildThread::OnShutdown() {
459 base::MessageLoop::current()->Quit();
462 #if defined(IPC_MESSAGE_LOG_ENABLED)
463 void ChildThread::OnSetIPCLoggingEnabled(bool enable) {
465 IPC::Logging::GetInstance()->Enable();
467 IPC::Logging::GetInstance()->Disable();
469 #endif // IPC_MESSAGE_LOG_ENABLED
471 void ChildThread::OnSetProfilerStatus(ThreadData::Status status) {
472 ThreadData::InitializeAndSetTrackingStatus(status);
475 void ChildThread::OnGetChildProfilerData(int sequence_number) {
476 tracked_objects::ProcessDataSnapshot process_data;
477 ThreadData::Snapshot(false, &process_data);
479 Send(new ChildProcessHostMsg_ChildProfilerData(sequence_number,
483 void ChildThread::OnDumpHandles() {
485 scoped_refptr<HandleEnumerator> handle_enum(
486 new HandleEnumerator(
487 CommandLine::ForCurrentProcess()->HasSwitch(
488 switches::kAuditAllHandles)));
489 handle_enum->EnumerateHandles();
490 Send(new ChildProcessHostMsg_DumpHandlesDone);
496 #if defined(USE_TCMALLOC)
497 void ChildThread::OnGetTcmallocStats() {
499 char buffer[1024 * 32];
500 base::allocator::GetStats(buffer, sizeof(buffer));
501 result.append(buffer);
502 Send(new ChildProcessHostMsg_TcmallocStats(result));
506 ChildThread* ChildThread::current() {
507 return g_lazy_tls.Pointer()->Get();
510 #if defined(OS_ANDROID)
511 // The method must NOT be called on the child thread itself.
512 // It may block the child thread if so.
513 void ChildThread::ShutdownThread() {
514 DCHECK(!ChildThread::current()) <<
515 "this method should NOT be called from child thread itself";
517 base::AutoLock lock(g_lazy_child_thread_lock.Get());
518 while (!g_child_thread)
519 g_lazy_child_thread_cv.Get().Wait();
521 DCHECK_NE(base::MessageLoop::current(), g_child_thread->message_loop());
522 g_child_thread->message_loop()->PostTask(
523 FROM_HERE, base::Bind(&QuitMainThreadMessageLoop));
527 void ChildThread::OnProcessFinalRelease() {
528 if (on_channel_error_called_) {
529 base::MessageLoop::current()->Quit();
533 // The child process shutdown sequence is a request response based mechanism,
534 // where we send out an initial feeler request to the child process host
535 // instance in the browser to verify if it's ok to shutdown the child process.
536 // The browser then sends back a response if it's ok to shutdown. This avoids
537 // race conditions if the process refcount is 0 but there's an IPC message
538 // inflight that would addref it.
539 Send(new ChildProcessHostMsg_ShutdownRequest);
542 void ChildThread::EnsureConnected() {
543 VLOG(0) << "ChildThread::EnsureConnected()";
544 base::KillProcess(base::GetCurrentProcessHandle(), 0, false);
547 } // namespace content