Introducing phased profiling framework.
[chromium-blink-merge.git] / content / child / child_thread_impl.cc
blob013d1d51302d1920edcbe76ec7b463357789c8f5
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_impl.h"
7 #include <signal.h>
9 #include <string>
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/metrics/field_trial.h"
21 #include "base/process/process.h"
22 #include "base/process/process_handle.h"
23 #include "base/strings/string_number_conversions.h"
24 #include "base/strings/string_util.h"
25 #include "base/synchronization/condition_variable.h"
26 #include "base/synchronization/lock.h"
27 #include "base/threading/thread_local.h"
28 #include "base/tracked_objects.h"
29 #include "components/tracing/child_trace_message_filter.h"
30 #include "content/child/bluetooth/bluetooth_message_filter.h"
31 #include "content/child/child_discardable_shared_memory_manager.h"
32 #include "content/child/child_gpu_memory_buffer_manager.h"
33 #include "content/child/child_histogram_message_filter.h"
34 #include "content/child/child_process.h"
35 #include "content/child/child_resource_message_filter.h"
36 #include "content/child/child_shared_bitmap_manager.h"
37 #include "content/child/fileapi/file_system_dispatcher.h"
38 #include "content/child/fileapi/webfilesystem_impl.h"
39 #include "content/child/geofencing/geofencing_message_filter.h"
40 #include "content/child/mojo/mojo_application.h"
41 #include "content/child/navigator_connect/navigator_connect_dispatcher.h"
42 #include "content/child/notifications/notification_dispatcher.h"
43 #include "content/child/power_monitor_broadcast_source.h"
44 #include "content/child/push_messaging/push_dispatcher.h"
45 #include "content/child/quota_dispatcher.h"
46 #include "content/child/quota_message_filter.h"
47 #include "content/child/resource_dispatcher.h"
48 #include "content/child/service_worker/service_worker_message_filter.h"
49 #include "content/child/thread_safe_sender.h"
50 #include "content/child/websocket_dispatcher.h"
51 #include "content/common/child_process_messages.h"
52 #include "content/common/in_process_child_thread_params.h"
53 #include "content/public/common/content_switches.h"
54 #include "ipc/ipc_logging.h"
55 #include "ipc/ipc_switches.h"
56 #include "ipc/ipc_sync_channel.h"
57 #include "ipc/ipc_sync_message_filter.h"
58 #include "ipc/mojo/ipc_channel_mojo.h"
59 #include "ipc/mojo/scoped_ipc_support.h"
61 #if defined(OS_WIN)
62 #include "content/common/handle_enumerator_win.h"
63 #endif
65 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
66 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
67 #endif
69 using tracked_objects::ThreadData;
71 namespace content {
72 namespace {
74 // How long to wait for a connection to the browser process before giving up.
75 const int kConnectionTimeoutS = 15;
77 base::LazyInstance<base::ThreadLocalPointer<ChildThreadImpl> > g_lazy_tls =
78 LAZY_INSTANCE_INITIALIZER;
80 // This isn't needed on Windows because there the sandbox's job object
81 // terminates child processes automatically. For unsandboxed processes (i.e.
82 // plugins), PluginThread has EnsureTerminateMessageFilter.
83 #if defined(OS_POSIX)
85 #if defined(ADDRESS_SANITIZER) || defined(LEAK_SANITIZER) || \
86 defined(MEMORY_SANITIZER) || defined(THREAD_SANITIZER) || \
87 defined(UNDEFINED_SANITIZER)
88 // A thread delegate that waits for |duration| and then exits the process with
89 // _exit(0).
90 class WaitAndExitDelegate : public base::PlatformThread::Delegate {
91 public:
92 explicit WaitAndExitDelegate(base::TimeDelta duration)
93 : duration_(duration) {}
95 void ThreadMain() override {
96 base::PlatformThread::Sleep(duration_);
97 _exit(0);
100 private:
101 const base::TimeDelta duration_;
102 DISALLOW_COPY_AND_ASSIGN(WaitAndExitDelegate);
105 bool CreateWaitAndExitThread(base::TimeDelta duration) {
106 scoped_ptr<WaitAndExitDelegate> delegate(new WaitAndExitDelegate(duration));
108 const bool thread_created =
109 base::PlatformThread::CreateNonJoinable(0, delegate.get());
110 if (!thread_created)
111 return false;
113 // A non joinable thread has been created. The thread will either terminate
114 // the process or will be terminated by the process. Therefore, keep the
115 // delegate object alive for the lifetime of the process.
116 WaitAndExitDelegate* leaking_delegate = delegate.release();
117 ANNOTATE_LEAKING_OBJECT_PTR(leaking_delegate);
118 ignore_result(leaking_delegate);
119 return true;
121 #endif
123 class SuicideOnChannelErrorFilter : public IPC::MessageFilter {
124 public:
125 // IPC::MessageFilter
126 void OnChannelError() override {
127 // For renderer/worker processes:
128 // On POSIX, at least, one can install an unload handler which loops
129 // forever and leave behind a renderer process which eats 100% CPU forever.
131 // This is because the terminate signals (ViewMsg_ShouldClose and the error
132 // from the IPC sender) are routed to the main message loop but never
133 // processed (because that message loop is stuck in V8).
135 // One could make the browser SIGKILL the renderers, but that leaves open a
136 // large window where a browser failure (or a user, manually terminating
137 // the browser because "it's stuck") will leave behind a process eating all
138 // the CPU.
140 // So, we install a filter on the sender so that we can process this event
141 // here and kill the process.
142 #if defined(ADDRESS_SANITIZER) || defined(LEAK_SANITIZER) || \
143 defined(MEMORY_SANITIZER) || defined(THREAD_SANITIZER) || \
144 defined(UNDEFINED_SANITIZER)
145 // Some sanitizer tools rely on exit handlers (e.g. to run leak detection,
146 // or dump code coverage data to disk). Instead of exiting the process
147 // immediately, we give it 60 seconds to run exit handlers.
148 CHECK(CreateWaitAndExitThread(base::TimeDelta::FromSeconds(60)));
149 #if defined(LEAK_SANITIZER)
150 // Invoke LeakSanitizer early to avoid detecting shutdown-only leaks. If
151 // leaks are found, the process will exit here.
152 __lsan_do_leak_check();
153 #endif
154 #else
155 _exit(0);
156 #endif
159 protected:
160 ~SuicideOnChannelErrorFilter() override {}
163 #endif // OS(POSIX)
165 #if defined(OS_ANDROID)
166 ChildThreadImpl* g_child_thread = NULL;
167 bool g_child_thread_initialized = false;
169 // A lock protects g_child_thread.
170 base::LazyInstance<base::Lock>::Leaky g_lazy_child_thread_lock =
171 LAZY_INSTANCE_INITIALIZER;
173 // base::ConditionVariable has an explicit constructor that takes
174 // a base::Lock pointer as parameter. The base::DefaultLazyInstanceTraits
175 // doesn't handle the case. Thus, we need our own class here.
176 struct CondVarLazyInstanceTraits {
177 static const bool kRegisterOnExit = false;
178 #ifndef NDEBUG
179 static const bool kAllowedToAccessOnNonjoinableThread = true;
180 #endif
182 static base::ConditionVariable* New(void* instance) {
183 return new (instance) base::ConditionVariable(
184 g_lazy_child_thread_lock.Pointer());
186 static void Delete(base::ConditionVariable* instance) {
187 instance->~ConditionVariable();
191 // A condition variable that synchronize threads initializing and waiting
192 // for g_child_thread.
193 base::LazyInstance<base::ConditionVariable, CondVarLazyInstanceTraits>
194 g_lazy_child_thread_cv = LAZY_INSTANCE_INITIALIZER;
196 void QuitMainThreadMessageLoop() {
197 base::MessageLoop::current()->Quit();
200 #endif
202 } // namespace
204 ChildThread* ChildThread::Get() {
205 return ChildThreadImpl::current();
208 // Mojo client channel delegate to be used in single process mode.
209 class ChildThreadImpl::SingleProcessChannelDelegate
210 : public IPC::ChannelMojo::Delegate {
211 public:
212 explicit SingleProcessChannelDelegate(
213 scoped_refptr<base::SequencedTaskRunner> io_runner)
214 : io_runner_(io_runner), weak_factory_(this) {}
216 ~SingleProcessChannelDelegate() override {}
218 base::WeakPtr<IPC::ChannelMojo::Delegate> ToWeakPtr() override {
219 return weak_factory_.GetWeakPtr();
222 scoped_refptr<base::TaskRunner> GetIOTaskRunner() override {
223 return io_runner_;
226 void OnChannelCreated(base::WeakPtr<IPC::ChannelMojo> channel) override {}
228 void DeleteSoon() {
229 io_runner_->PostTask(
230 FROM_HERE,
231 base::Bind(&base::DeletePointer<SingleProcessChannelDelegate>,
232 base::Unretained(this)));
235 private:
236 scoped_refptr<base::SequencedTaskRunner> io_runner_;
237 base::WeakPtrFactory<IPC::ChannelMojo::Delegate> weak_factory_;
239 DISALLOW_COPY_AND_ASSIGN(SingleProcessChannelDelegate);
242 void ChildThreadImpl::SingleProcessChannelDelegateDeleter::operator()(
243 SingleProcessChannelDelegate* delegate) const {
244 delegate->DeleteSoon();
247 ChildThreadImpl::Options::Options()
248 : channel_name(base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
249 switches::kProcessChannelID)),
250 use_mojo_channel(false) {
253 ChildThreadImpl::Options::~Options() {
256 ChildThreadImpl::Options::Builder::Builder() {
259 ChildThreadImpl::Options::Builder&
260 ChildThreadImpl::Options::Builder::InBrowserProcess(
261 const InProcessChildThreadParams& params) {
262 options_.browser_process_io_runner = params.io_runner();
263 options_.channel_name = params.channel_name();
264 return *this;
267 ChildThreadImpl::Options::Builder&
268 ChildThreadImpl::Options::Builder::UseMojoChannel(bool use_mojo_channel) {
269 options_.use_mojo_channel = use_mojo_channel;
270 return *this;
273 ChildThreadImpl::Options::Builder&
274 ChildThreadImpl::Options::Builder::WithChannelName(
275 const std::string& channel_name) {
276 options_.channel_name = channel_name;
277 return *this;
280 ChildThreadImpl::Options::Builder&
281 ChildThreadImpl::Options::Builder::AddStartupFilter(
282 IPC::MessageFilter* filter) {
283 options_.startup_filters.push_back(filter);
284 return *this;
287 ChildThreadImpl::Options ChildThreadImpl::Options::Builder::Build() {
288 return options_;
291 ChildThreadImpl::ChildThreadMessageRouter::ChildThreadMessageRouter(
292 IPC::Sender* sender)
293 : sender_(sender) {}
295 bool ChildThreadImpl::ChildThreadMessageRouter::Send(IPC::Message* msg) {
296 return sender_->Send(msg);
299 ChildThreadImpl::ChildThreadImpl()
300 : router_(this),
301 channel_connected_factory_(this) {
302 Init(Options::Builder().Build());
305 ChildThreadImpl::ChildThreadImpl(const Options& options)
306 : router_(this),
307 browser_process_io_runner_(options.browser_process_io_runner),
308 channel_connected_factory_(this) {
309 Init(options);
312 scoped_refptr<base::SequencedTaskRunner> ChildThreadImpl::GetIOTaskRunner() {
313 if (IsInBrowserProcess())
314 return browser_process_io_runner_;
315 return ChildProcess::current()->io_message_loop_proxy();
318 void ChildThreadImpl::ConnectChannel(bool use_mojo_channel) {
319 bool create_pipe_now = true;
320 if (use_mojo_channel) {
321 VLOG(1) << "Mojo is enabled on child";
322 scoped_refptr<base::SequencedTaskRunner> io_task_runner = GetIOTaskRunner();
323 DCHECK(io_task_runner);
324 if (IsInBrowserProcess())
325 single_process_channel_delegate_.reset(
326 new SingleProcessChannelDelegate(io_task_runner));
327 ipc_support_.reset(new IPC::ScopedIPCSupport(io_task_runner));
328 channel_->Init(
329 IPC::ChannelMojo::CreateClientFactory(
330 single_process_channel_delegate_.get(),
331 channel_name_),
332 create_pipe_now);
333 return;
336 VLOG(1) << "Mojo is disabled on child";
337 channel_->Init(channel_name_, IPC::Channel::MODE_CLIENT, create_pipe_now);
340 void ChildThreadImpl::Init(const Options& options) {
341 channel_name_ = options.channel_name;
343 g_lazy_tls.Pointer()->Set(this);
344 on_channel_error_called_ = false;
345 message_loop_ = base::MessageLoop::current();
346 #ifdef IPC_MESSAGE_LOG_ENABLED
347 // We must make sure to instantiate the IPC Logger *before* we create the
348 // channel, otherwise we can get a callback on the IO thread which creates
349 // the logger, and the logger does not like being created on the IO thread.
350 IPC::Logging::GetInstance();
351 #endif
352 channel_ = IPC::SyncChannel::Create(
353 this, ChildProcess::current()->io_message_loop_proxy(),
354 ChildProcess::current()->GetShutDownEvent());
355 #ifdef IPC_MESSAGE_LOG_ENABLED
356 if (!IsInBrowserProcess())
357 IPC::Logging::GetInstance()->SetIPCSender(this);
358 #endif
360 mojo_application_.reset(new MojoApplication(GetIOTaskRunner()));
362 sync_message_filter_ =
363 new IPC::SyncMessageFilter(ChildProcess::current()->GetShutDownEvent());
364 thread_safe_sender_ = new ThreadSafeSender(
365 base::MessageLoopProxy::current().get(), sync_message_filter_.get());
367 resource_dispatcher_.reset(new ResourceDispatcher(
368 this, message_loop()->task_runner()));
369 websocket_dispatcher_.reset(new WebSocketDispatcher);
370 file_system_dispatcher_.reset(new FileSystemDispatcher());
372 histogram_message_filter_ = new ChildHistogramMessageFilter();
373 resource_message_filter_ =
374 new ChildResourceMessageFilter(resource_dispatcher());
376 service_worker_message_filter_ =
377 new ServiceWorkerMessageFilter(thread_safe_sender_.get());
379 quota_message_filter_ =
380 new QuotaMessageFilter(thread_safe_sender_.get());
381 quota_dispatcher_.reset(new QuotaDispatcher(thread_safe_sender_.get(),
382 quota_message_filter_.get()));
383 geofencing_message_filter_ =
384 new GeofencingMessageFilter(thread_safe_sender_.get());
385 bluetooth_message_filter_ =
386 new BluetoothMessageFilter(thread_safe_sender_.get());
387 notification_dispatcher_ =
388 new NotificationDispatcher(thread_safe_sender_.get());
389 push_dispatcher_ = new PushDispatcher(thread_safe_sender_.get());
390 navigator_connect_dispatcher_ =
391 new NavigatorConnectDispatcher(thread_safe_sender_.get());
393 channel_->AddFilter(histogram_message_filter_.get());
394 channel_->AddFilter(sync_message_filter_.get());
395 channel_->AddFilter(resource_message_filter_.get());
396 channel_->AddFilter(quota_message_filter_->GetFilter());
397 channel_->AddFilter(notification_dispatcher_->GetFilter());
398 channel_->AddFilter(push_dispatcher_->GetFilter());
399 channel_->AddFilter(service_worker_message_filter_->GetFilter());
400 channel_->AddFilter(geofencing_message_filter_->GetFilter());
401 channel_->AddFilter(bluetooth_message_filter_->GetFilter());
402 channel_->AddFilter(navigator_connect_dispatcher_->GetFilter());
404 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
405 switches::kSingleProcess)) {
406 // In single process mode, browser-side tracing will cover the whole
407 // process including renderers.
408 channel_->AddFilter(new tracing::ChildTraceMessageFilter(
409 ChildProcess::current()->io_message_loop_proxy()));
412 // In single process mode we may already have a power monitor
413 if (!base::PowerMonitor::Get()) {
414 scoped_ptr<PowerMonitorBroadcastSource> power_monitor_source(
415 new PowerMonitorBroadcastSource());
416 channel_->AddFilter(power_monitor_source->GetMessageFilter());
418 power_monitor_.reset(new base::PowerMonitor(
419 power_monitor_source.Pass()));
422 #if defined(OS_POSIX)
423 // Check that --process-type is specified so we don't do this in unit tests
424 // and single-process mode.
425 if (base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kProcessType))
426 channel_->AddFilter(new SuicideOnChannelErrorFilter());
427 #endif
429 // Add filters passed here via options.
430 for (auto startup_filter : options.startup_filters) {
431 channel_->AddFilter(startup_filter);
434 ConnectChannel(options.use_mojo_channel);
436 int connection_timeout = kConnectionTimeoutS;
437 std::string connection_override =
438 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
439 switches::kIPCConnectionTimeout);
440 if (!connection_override.empty()) {
441 int temp;
442 if (base::StringToInt(connection_override, &temp))
443 connection_timeout = temp;
446 base::MessageLoop::current()->PostDelayedTask(
447 FROM_HERE,
448 base::Bind(&ChildThreadImpl::EnsureConnected,
449 channel_connected_factory_.GetWeakPtr()),
450 base::TimeDelta::FromSeconds(connection_timeout));
452 #if defined(OS_ANDROID)
454 base::AutoLock lock(g_lazy_child_thread_lock.Get());
455 g_child_thread = this;
456 g_child_thread_initialized = true;
458 // Signalling without locking is fine here because only
459 // one thread can wait on the condition variable.
460 g_lazy_child_thread_cv.Get().Signal();
461 #endif
463 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
464 trace_memory_controller_.reset(new base::trace_event::TraceMemoryController(
465 message_loop_->message_loop_proxy(), ::HeapProfilerWithPseudoStackStart,
466 ::HeapProfilerStop, ::GetHeapProfile));
467 #endif
469 shared_bitmap_manager_.reset(
470 new ChildSharedBitmapManager(thread_safe_sender()));
472 gpu_memory_buffer_manager_.reset(
473 new ChildGpuMemoryBufferManager(thread_safe_sender()));
475 discardable_shared_memory_manager_.reset(
476 new ChildDiscardableSharedMemoryManager(thread_safe_sender()));
479 ChildThreadImpl::~ChildThreadImpl() {
480 // ChildDiscardableSharedMemoryManager has to be destroyed while
481 // |thread_safe_sender_| is still valid.
482 discardable_shared_memory_manager_.reset();
484 #if defined(OS_ANDROID)
486 base::AutoLock lock(g_lazy_child_thread_lock.Get());
487 g_child_thread = nullptr;
489 #endif
491 #ifdef IPC_MESSAGE_LOG_ENABLED
492 IPC::Logging::GetInstance()->SetIPCSender(NULL);
493 #endif
495 channel_->RemoveFilter(histogram_message_filter_.get());
496 channel_->RemoveFilter(sync_message_filter_.get());
498 // The ChannelProxy object caches a pointer to the IPC thread, so need to
499 // reset it as it's not guaranteed to outlive this object.
500 // NOTE: this also has the side-effect of not closing the main IPC channel to
501 // the browser process. This is needed because this is the signal that the
502 // browser uses to know that this process has died, so we need it to be alive
503 // until this process is shut down, and the OS closes the handle
504 // automatically. We used to watch the object handle on Windows to do this,
505 // but it wasn't possible to do so on POSIX.
506 channel_->ClearIPCTaskRunner();
507 g_lazy_tls.Pointer()->Set(NULL);
510 void ChildThreadImpl::Shutdown() {
511 // Delete objects that hold references to blink so derived classes can
512 // safely shutdown blink in their Shutdown implementation.
513 file_system_dispatcher_.reset();
514 quota_dispatcher_.reset();
515 WebFileSystemImpl::DeleteThreadSpecificInstance();
518 void ChildThreadImpl::OnChannelConnected(int32 peer_pid) {
519 channel_connected_factory_.InvalidateWeakPtrs();
522 void ChildThreadImpl::OnChannelError() {
523 set_on_channel_error_called(true);
524 base::MessageLoop::current()->Quit();
527 bool ChildThreadImpl::Send(IPC::Message* msg) {
528 DCHECK(base::MessageLoop::current() == message_loop());
529 if (!channel_) {
530 delete msg;
531 return false;
534 return channel_->Send(msg);
537 #if defined(OS_WIN)
538 void ChildThreadImpl::PreCacheFont(const LOGFONT& log_font) {
539 Send(new ChildProcessHostMsg_PreCacheFont(log_font));
542 void ChildThreadImpl::ReleaseCachedFonts() {
543 Send(new ChildProcessHostMsg_ReleaseCachedFonts());
545 #endif
547 MessageRouter* ChildThreadImpl::GetRouter() {
548 DCHECK(base::MessageLoop::current() == message_loop());
549 return &router_;
552 scoped_ptr<base::SharedMemory> ChildThreadImpl::AllocateSharedMemory(
553 size_t buf_size) {
554 DCHECK(base::MessageLoop::current() == message_loop());
555 return AllocateSharedMemory(buf_size, this);
558 // static
559 scoped_ptr<base::SharedMemory> ChildThreadImpl::AllocateSharedMemory(
560 size_t buf_size,
561 IPC::Sender* sender) {
562 scoped_ptr<base::SharedMemory> shared_buf;
563 #if defined(OS_WIN)
564 shared_buf.reset(new base::SharedMemory);
565 if (!shared_buf->CreateAnonymous(buf_size)) {
566 NOTREACHED();
567 return NULL;
569 #else
570 // On POSIX, we need to ask the browser to create the shared memory for us,
571 // since this is blocked by the sandbox.
572 base::SharedMemoryHandle shared_mem_handle;
573 if (sender->Send(new ChildProcessHostMsg_SyncAllocateSharedMemory(
574 buf_size, &shared_mem_handle))) {
575 if (base::SharedMemory::IsHandleValid(shared_mem_handle)) {
576 shared_buf.reset(new base::SharedMemory(shared_mem_handle, false));
577 } else {
578 NOTREACHED() << "Browser failed to allocate shared memory";
579 return NULL;
581 } else {
582 NOTREACHED() << "Browser allocation request message failed";
583 return NULL;
585 #endif
586 return shared_buf;
589 bool ChildThreadImpl::OnMessageReceived(const IPC::Message& msg) {
590 if (mojo_application_->OnMessageReceived(msg))
591 return true;
593 // Resource responses are sent to the resource dispatcher.
594 if (resource_dispatcher_->OnMessageReceived(msg))
595 return true;
596 if (websocket_dispatcher_->OnMessageReceived(msg))
597 return true;
598 if (file_system_dispatcher_->OnMessageReceived(msg))
599 return true;
601 bool handled = true;
602 IPC_BEGIN_MESSAGE_MAP(ChildThreadImpl, msg)
603 IPC_MESSAGE_HANDLER(ChildProcessMsg_Shutdown, OnShutdown)
604 #if defined(IPC_MESSAGE_LOG_ENABLED)
605 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetIPCLoggingEnabled,
606 OnSetIPCLoggingEnabled)
607 #endif
608 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetProfilerStatus,
609 OnSetProfilerStatus)
610 IPC_MESSAGE_HANDLER(ChildProcessMsg_GetChildProfilerData,
611 OnGetChildProfilerData)
612 IPC_MESSAGE_HANDLER(ChildProcessMsg_DumpHandles, OnDumpHandles)
613 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetProcessBackgrounded,
614 OnProcessBackgrounded)
615 #if defined(USE_TCMALLOC)
616 IPC_MESSAGE_HANDLER(ChildProcessMsg_GetTcmallocStats, OnGetTcmallocStats)
617 #endif
618 IPC_MESSAGE_UNHANDLED(handled = false)
619 IPC_END_MESSAGE_MAP()
621 if (handled)
622 return true;
624 if (msg.routing_id() == MSG_ROUTING_CONTROL)
625 return OnControlMessageReceived(msg);
627 return router_.OnMessageReceived(msg);
630 bool ChildThreadImpl::OnControlMessageReceived(const IPC::Message& msg) {
631 return false;
634 void ChildThreadImpl::OnShutdown() {
635 base::MessageLoop::current()->Quit();
638 #if defined(IPC_MESSAGE_LOG_ENABLED)
639 void ChildThreadImpl::OnSetIPCLoggingEnabled(bool enable) {
640 if (enable)
641 IPC::Logging::GetInstance()->Enable();
642 else
643 IPC::Logging::GetInstance()->Disable();
645 #endif // IPC_MESSAGE_LOG_ENABLED
647 void ChildThreadImpl::OnSetProfilerStatus(ThreadData::Status status) {
648 ThreadData::InitializeAndSetTrackingStatus(status);
651 void ChildThreadImpl::OnGetChildProfilerData(int sequence_number) {
652 tracked_objects::ProcessDataSnapshot process_data;
653 ThreadData::Snapshot(&process_data);
655 Send(
656 new ChildProcessHostMsg_ChildProfilerData(sequence_number, process_data));
659 void ChildThreadImpl::OnDumpHandles() {
660 #if defined(OS_WIN)
661 scoped_refptr<HandleEnumerator> handle_enum(
662 new HandleEnumerator(
663 base::CommandLine::ForCurrentProcess()->HasSwitch(
664 switches::kAuditAllHandles)));
665 handle_enum->EnumerateHandles();
666 Send(new ChildProcessHostMsg_DumpHandlesDone);
667 #else
668 NOTIMPLEMENTED();
669 #endif
672 #if defined(USE_TCMALLOC)
673 void ChildThreadImpl::OnGetTcmallocStats() {
674 std::string result;
675 char buffer[1024 * 32];
676 base::allocator::GetStats(buffer, sizeof(buffer));
677 result.append(buffer);
678 Send(new ChildProcessHostMsg_TcmallocStats(result));
680 #endif
682 ChildThreadImpl* ChildThreadImpl::current() {
683 return g_lazy_tls.Pointer()->Get();
686 #if defined(OS_ANDROID)
687 // The method must NOT be called on the child thread itself.
688 // It may block the child thread if so.
689 void ChildThreadImpl::ShutdownThread() {
690 DCHECK(!ChildThreadImpl::current()) <<
691 "this method should NOT be called from child thread itself";
693 base::AutoLock lock(g_lazy_child_thread_lock.Get());
694 while (!g_child_thread_initialized)
695 g_lazy_child_thread_cv.Get().Wait();
697 // g_child_thread may already have been destructed while we didn't hold the
698 // lock.
699 if (!g_child_thread)
700 return;
702 DCHECK_NE(base::MessageLoop::current(), g_child_thread->message_loop());
703 g_child_thread->message_loop()->PostTask(
704 FROM_HERE, base::Bind(&QuitMainThreadMessageLoop));
707 #endif
709 void ChildThreadImpl::OnProcessFinalRelease() {
710 if (on_channel_error_called_) {
711 base::MessageLoop::current()->Quit();
712 return;
715 // The child process shutdown sequence is a request response based mechanism,
716 // where we send out an initial feeler request to the child process host
717 // instance in the browser to verify if it's ok to shutdown the child process.
718 // The browser then sends back a response if it's ok to shutdown. This avoids
719 // race conditions if the process refcount is 0 but there's an IPC message
720 // inflight that would addref it.
721 Send(new ChildProcessHostMsg_ShutdownRequest);
724 void ChildThreadImpl::EnsureConnected() {
725 VLOG(0) << "ChildThreadImpl::EnsureConnected()";
726 base::Process::Current().Terminate(0, false);
729 bool ChildThreadImpl::IsInBrowserProcess() const {
730 return browser_process_io_runner_;
733 void ChildThreadImpl::OnProcessBackgrounded(bool background) {
734 // Set timer slack to maximum on main thread when in background.
735 base::TimerSlack timer_slack = base::TIMER_SLACK_NONE;
736 if (background)
737 timer_slack = base::TIMER_SLACK_MAXIMUM;
738 base::MessageLoop::current()->SetTimerSlack(timer_slack);
740 #ifdef OS_WIN
741 // Windows Vista+ has a fancy process backgrounding mode that can only be set
742 // from within the process. This used to be how chrome set its renderers into
743 // background mode on Windows but was removed due to http://crbug.com/398103.
744 // As we experiment with bringing back some other form of background mode for
745 // hidden renderers, add a bucket to allow us to trigger this undesired method
746 // of setting background state in order to confirm that the metrics which were
747 // added to prevent regressions on the aforementioned issue indeed catch such
748 // regressions and are thus a reliable way to confirm that our latest proposal
749 // doesn't cause such issues. TODO(gab): Remove this once the experiment is
750 // over (http://crbug.com/458594).
751 base::FieldTrial* trial =
752 base::FieldTrialList::Find("BackgroundRendererProcesses");
753 if (trial && trial->group_name() == "AllowBackgroundModeFromRenderer")
754 base::Process::Current().SetProcessBackgrounded(background);
755 #endif // OS_WIN
758 } // namespace content