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_dispatcher.h"
41 #include "content/child/service_worker/service_worker_message_filter.h"
42 #include "content/child/socket_stream_dispatcher.h"
43 #include "content/child/thread_safe_sender.h"
44 #include "content/child/websocket_dispatcher.h"
45 #include "content/common/child_process_messages.h"
46 #include "content/public/common/content_switches.h"
47 #include "ipc/ipc_logging.h"
48 #include "ipc/ipc_switches.h"
49 #include "ipc/ipc_sync_channel.h"
50 #include "ipc/ipc_sync_message_filter.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::ChildThreadMessageRouter::ChildThreadMessageRouter(
199 bool ChildThread::ChildThreadMessageRouter::Send(IPC::Message* msg) {
200 return sender_->Send(msg);
203 ChildThread::ChildThread()
205 channel_connected_factory_(this),
206 in_browser_process_(false) {
207 channel_name_ = CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
208 switches::kProcessChannelID);
212 ChildThread::ChildThread(const std::string& channel_name)
213 : channel_name_(channel_name),
215 channel_connected_factory_(this),
216 in_browser_process_(true) {
220 void ChildThread::Init() {
221 g_lazy_tls.Pointer()->Set(this);
222 on_channel_error_called_ = false;
223 message_loop_ = base::MessageLoop::current();
224 #ifdef IPC_MESSAGE_LOG_ENABLED
225 // We must make sure to instantiate the IPC Logger *before* we create the
226 // channel, otherwise we can get a callback on the IO thread which creates
227 // the logger, and the logger does not like being created on the IO thread.
228 IPC::Logging::GetInstance();
231 IPC::SyncChannel::Create(channel_name_,
232 IPC::Channel::MODE_CLIENT,
234 ChildProcess::current()->io_message_loop_proxy(),
236 ChildProcess::current()->GetShutDownEvent());
237 #ifdef IPC_MESSAGE_LOG_ENABLED
238 if (!in_browser_process_)
239 IPC::Logging::GetInstance()->SetIPCSender(this);
242 mojo_application_.reset(new MojoApplication(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(resource_message_filter_.get());
271 channel_->AddFilter(quota_message_filter_->GetFilter());
272 channel_->AddFilter(service_worker_message_filter_->GetFilter());
274 if (!CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess)) {
275 // In single process mode, browser-side tracing will cover the whole
276 // process including renderers.
277 channel_->AddFilter(new tracing::ChildTraceMessageFilter(
278 ChildProcess::current()->io_message_loop_proxy()));
281 // In single process mode we may already have a power monitor
282 if (!base::PowerMonitor::Get()) {
283 scoped_ptr<PowerMonitorBroadcastSource> power_monitor_source(
284 new PowerMonitorBroadcastSource());
285 channel_->AddFilter(power_monitor_source->GetMessageFilter());
287 power_monitor_.reset(new base::PowerMonitor(
288 power_monitor_source.PassAs<base::PowerMonitorSource>()));
291 #if defined(OS_POSIX)
292 // Check that --process-type is specified so we don't do this in unit tests
293 // and single-process mode.
294 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kProcessType))
295 channel_->AddFilter(new SuicideOnChannelErrorFilter());
298 int connection_timeout = kConnectionTimeoutS;
299 std::string connection_override =
300 CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
301 switches::kIPCConnectionTimeout);
302 if (!connection_override.empty()) {
304 if (base::StringToInt(connection_override, &temp))
305 connection_timeout = temp;
308 base::MessageLoop::current()->PostDelayedTask(
310 base::Bind(&ChildThread::EnsureConnected,
311 channel_connected_factory_.GetWeakPtr()),
312 base::TimeDelta::FromSeconds(connection_timeout));
314 #if defined(OS_ANDROID)
316 base::AutoLock lock(g_lazy_child_thread_lock.Get());
317 g_child_thread = this;
319 // Signalling without locking is fine here because only
320 // one thread can wait on the condition variable.
321 g_lazy_child_thread_cv.Get().Signal();
324 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
325 trace_memory_controller_.reset(new base::debug::TraceMemoryController(
326 message_loop_->message_loop_proxy(),
327 ::HeapProfilerWithPseudoStackStart,
332 shared_bitmap_manager_.reset(
333 new ChildSharedBitmapManager(thread_safe_sender()));
336 ChildThread::~ChildThread() {
337 #ifdef IPC_MESSAGE_LOG_ENABLED
338 IPC::Logging::GetInstance()->SetIPCSender(NULL);
341 channel_->RemoveFilter(histogram_message_filter_.get());
342 channel_->RemoveFilter(sync_message_filter_.get());
344 // The ChannelProxy object caches a pointer to the IPC thread, so need to
345 // reset it as it's not guaranteed to outlive this object.
346 // NOTE: this also has the side-effect of not closing the main IPC channel to
347 // the browser process. This is needed because this is the signal that the
348 // browser uses to know that this process has died, so we need it to be alive
349 // until this process is shut down, and the OS closes the handle
350 // automatically. We used to watch the object handle on Windows to do this,
351 // but it wasn't possible to do so on POSIX.
352 channel_->ClearIPCTaskRunner();
353 g_lazy_tls.Pointer()->Set(NULL);
356 void ChildThread::Shutdown() {
357 // Delete objects that hold references to blink so derived classes can
358 // safely shutdown blink in their Shutdown implementation.
359 file_system_dispatcher_.reset();
360 quota_dispatcher_.reset();
361 WebFileSystemImpl::DeleteThreadSpecificInstance();
364 void ChildThread::OnChannelConnected(int32 peer_pid) {
365 channel_connected_factory_.InvalidateWeakPtrs();
368 void ChildThread::OnChannelError() {
369 set_on_channel_error_called(true);
370 base::MessageLoop::current()->Quit();
373 void ChildThread::ConnectToService(
374 const mojo::String& service_url,
375 const mojo::String& service_name,
376 mojo::ScopedMessagePipeHandle message_pipe,
377 const mojo::String& requestor_url) {
378 // By default, we don't expect incoming connections.
382 bool ChildThread::Send(IPC::Message* msg) {
383 DCHECK(base::MessageLoop::current() == message_loop());
389 return channel_->Send(msg);
392 MessageRouter* ChildThread::GetRouter() {
393 DCHECK(base::MessageLoop::current() == message_loop());
397 base::SharedMemory* ChildThread::AllocateSharedMemory(size_t buf_size) {
398 return AllocateSharedMemory(buf_size, this);
402 base::SharedMemory* ChildThread::AllocateSharedMemory(
404 IPC::Sender* sender) {
405 scoped_ptr<base::SharedMemory> shared_buf;
407 shared_buf.reset(new base::SharedMemory);
408 if (!shared_buf->CreateAndMapAnonymous(buf_size)) {
413 // On POSIX, we need to ask the browser to create the shared memory for us,
414 // since this is blocked by the sandbox.
415 base::SharedMemoryHandle shared_mem_handle;
416 if (sender->Send(new ChildProcessHostMsg_SyncAllocateSharedMemory(
417 buf_size, &shared_mem_handle))) {
418 if (base::SharedMemory::IsHandleValid(shared_mem_handle)) {
419 shared_buf.reset(new base::SharedMemory(shared_mem_handle, false));
420 if (!shared_buf->Map(buf_size)) {
421 NOTREACHED() << "Map failed";
425 NOTREACHED() << "Browser failed to allocate shared memory";
429 NOTREACHED() << "Browser allocation request message failed";
433 return shared_buf.release();
436 bool ChildThread::OnMessageReceived(const IPC::Message& msg) {
437 if (mojo_application_->OnMessageReceived(msg))
440 // Resource responses are sent to the resource dispatcher.
441 if (resource_dispatcher_->OnMessageReceived(msg))
443 if (socket_stream_dispatcher_->OnMessageReceived(msg))
445 if (websocket_dispatcher_->OnMessageReceived(msg))
447 if (file_system_dispatcher_->OnMessageReceived(msg))
451 IPC_BEGIN_MESSAGE_MAP(ChildThread, msg)
452 IPC_MESSAGE_HANDLER(ChildProcessMsg_Shutdown, OnShutdown)
453 #if defined(IPC_MESSAGE_LOG_ENABLED)
454 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetIPCLoggingEnabled,
455 OnSetIPCLoggingEnabled)
457 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetProfilerStatus,
459 IPC_MESSAGE_HANDLER(ChildProcessMsg_GetChildProfilerData,
460 OnGetChildProfilerData)
461 IPC_MESSAGE_HANDLER(ChildProcessMsg_DumpHandles, OnDumpHandles)
462 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetProcessBackgrounded,
463 OnProcessBackgrounded)
464 #if defined(USE_TCMALLOC)
465 IPC_MESSAGE_HANDLER(ChildProcessMsg_GetTcmallocStats, OnGetTcmallocStats)
467 IPC_MESSAGE_UNHANDLED(handled = false)
468 IPC_END_MESSAGE_MAP()
473 if (msg.routing_id() == MSG_ROUTING_CONTROL)
474 return OnControlMessageReceived(msg);
476 return router_.OnMessageReceived(msg);
479 bool ChildThread::OnControlMessageReceived(const IPC::Message& msg) {
483 void ChildThread::OnShutdown() {
484 base::MessageLoop::current()->Quit();
487 #if defined(IPC_MESSAGE_LOG_ENABLED)
488 void ChildThread::OnSetIPCLoggingEnabled(bool enable) {
490 IPC::Logging::GetInstance()->Enable();
492 IPC::Logging::GetInstance()->Disable();
494 #endif // IPC_MESSAGE_LOG_ENABLED
496 void ChildThread::OnSetProfilerStatus(ThreadData::Status status) {
497 ThreadData::InitializeAndSetTrackingStatus(status);
500 void ChildThread::OnGetChildProfilerData(int sequence_number) {
501 tracked_objects::ProcessDataSnapshot process_data;
502 ThreadData::Snapshot(false, &process_data);
504 Send(new ChildProcessHostMsg_ChildProfilerData(sequence_number,
508 void ChildThread::OnDumpHandles() {
510 scoped_refptr<HandleEnumerator> handle_enum(
511 new HandleEnumerator(
512 CommandLine::ForCurrentProcess()->HasSwitch(
513 switches::kAuditAllHandles)));
514 handle_enum->EnumerateHandles();
515 Send(new ChildProcessHostMsg_DumpHandlesDone);
521 #if defined(USE_TCMALLOC)
522 void ChildThread::OnGetTcmallocStats() {
524 char buffer[1024 * 32];
525 base::allocator::GetStats(buffer, sizeof(buffer));
526 result.append(buffer);
527 Send(new ChildProcessHostMsg_TcmallocStats(result));
531 ChildThread* ChildThread::current() {
532 return g_lazy_tls.Pointer()->Get();
535 #if defined(OS_ANDROID)
536 // The method must NOT be called on the child thread itself.
537 // It may block the child thread if so.
538 void ChildThread::ShutdownThread() {
539 DCHECK(!ChildThread::current()) <<
540 "this method should NOT be called from child thread itself";
542 base::AutoLock lock(g_lazy_child_thread_lock.Get());
543 while (!g_child_thread)
544 g_lazy_child_thread_cv.Get().Wait();
546 DCHECK_NE(base::MessageLoop::current(), g_child_thread->message_loop());
547 g_child_thread->message_loop()->PostTask(
548 FROM_HERE, base::Bind(&QuitMainThreadMessageLoop));
552 void ChildThread::OnProcessFinalRelease() {
553 if (on_channel_error_called_) {
554 base::MessageLoop::current()->Quit();
558 // The child process shutdown sequence is a request response based mechanism,
559 // where we send out an initial feeler request to the child process host
560 // instance in the browser to verify if it's ok to shutdown the child process.
561 // The browser then sends back a response if it's ok to shutdown. This avoids
562 // race conditions if the process refcount is 0 but there's an IPC message
563 // inflight that would addref it.
564 Send(new ChildProcessHostMsg_ShutdownRequest);
567 void ChildThread::EnsureConnected() {
568 VLOG(0) << "ChildThread::EnsureConnected()";
569 base::KillProcess(base::GetCurrentProcessHandle(), 0, false);
572 void ChildThread::OnProcessBackgrounded(bool background) {
573 // Set timer slack to maximum on main thread when in background.
574 base::TimerSlack timer_slack = base::TIMER_SLACK_NONE;
576 timer_slack = base::TIMER_SLACK_MAXIMUM;
577 base::MessageLoop::current()->SetTimerSlack(timer_slack);
580 // Windows Vista+ has a fancy process backgrounding mode that can only be set
581 // from within the process.
582 base::Process::Current().SetProcessBackgrounded(background);
586 } // namespace content