Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / content / child / child_thread_impl.cc
blobbfb1f3a21bf3d4fe20fd40242e37debfd6673457
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/debug/profiler.h"
17 #include "base/lazy_instance.h"
18 #include "base/location.h"
19 #include "base/logging.h"
20 #include "base/message_loop/timer_slack.h"
21 #include "base/metrics/field_trial.h"
22 #include "base/process/process.h"
23 #include "base/process/process_handle.h"
24 #include "base/single_thread_task_runner.h"
25 #include "base/strings/string_number_conversions.h"
26 #include "base/strings/string_util.h"
27 #include "base/synchronization/condition_variable.h"
28 #include "base/synchronization/lock.h"
29 #include "base/thread_task_runner_handle.h"
30 #include "base/threading/thread_local.h"
31 #include "base/tracked_objects.h"
32 #include "components/tracing/child_trace_message_filter.h"
33 #include "content/child/child_discardable_shared_memory_manager.h"
34 #include "content/child/child_gpu_memory_buffer_manager.h"
35 #include "content/child/child_histogram_message_filter.h"
36 #include "content/child/child_process.h"
37 #include "content/child/child_resource_message_filter.h"
38 #include "content/child/child_shared_bitmap_manager.h"
39 #include "content/child/fileapi/file_system_dispatcher.h"
40 #include "content/child/fileapi/webfilesystem_impl.h"
41 #include "content/child/geofencing/geofencing_message_filter.h"
42 #include "content/child/mojo/mojo_application.h"
43 #include "content/child/notifications/notification_dispatcher.h"
44 #include "content/child/power_monitor_broadcast_source.h"
45 #include "content/child/push_messaging/push_dispatcher.h"
46 #include "content/child/quota_dispatcher.h"
47 #include "content/child/quota_message_filter.h"
48 #include "content/child/resource_dispatcher.h"
49 #include "content/child/service_worker/service_worker_message_filter.h"
50 #include "content/child/thread_safe_sender.h"
51 #include "content/child/websocket_dispatcher.h"
52 #include "content/common/child_process_messages.h"
53 #include "content/common/in_process_child_thread_params.h"
54 #include "content/public/common/content_switches.h"
55 #include "ipc/attachment_broker_unprivileged.h"
56 #include "ipc/ipc_logging.h"
57 #include "ipc/ipc_switches.h"
58 #include "ipc/ipc_sync_channel.h"
59 #include "ipc/ipc_sync_message_filter.h"
60 #include "ipc/mojo/ipc_channel_mojo.h"
62 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
63 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
64 #endif
66 #if defined(OS_MACOSX)
67 #include "content/child/child_io_surface_manager_mac.h"
68 #endif
70 #if defined(USE_OZONE)
71 #include "ui/ozone/public/client_native_pixmap_factory.h"
72 #endif
74 #if defined(OS_WIN)
75 #include "ipc/attachment_broker_unprivileged_win.h"
76 #endif
78 using tracked_objects::ThreadData;
80 namespace content {
81 namespace {
83 // How long to wait for a connection to the browser process before giving up.
84 const int kConnectionTimeoutS = 15;
86 base::LazyInstance<base::ThreadLocalPointer<ChildThreadImpl> > g_lazy_tls =
87 LAZY_INSTANCE_INITIALIZER;
89 // This isn't needed on Windows because there the sandbox's job object
90 // terminates child processes automatically. For unsandboxed processes (i.e.
91 // plugins), PluginThread has EnsureTerminateMessageFilter.
92 #if defined(OS_POSIX)
94 #if defined(ADDRESS_SANITIZER) || defined(LEAK_SANITIZER) || \
95 defined(MEMORY_SANITIZER) || defined(THREAD_SANITIZER) || \
96 defined(UNDEFINED_SANITIZER)
97 // A thread delegate that waits for |duration| and then exits the process with
98 // _exit(0).
99 class WaitAndExitDelegate : public base::PlatformThread::Delegate {
100 public:
101 explicit WaitAndExitDelegate(base::TimeDelta duration)
102 : duration_(duration) {}
104 void ThreadMain() override {
105 base::PlatformThread::Sleep(duration_);
106 _exit(0);
109 private:
110 const base::TimeDelta duration_;
111 DISALLOW_COPY_AND_ASSIGN(WaitAndExitDelegate);
114 bool CreateWaitAndExitThread(base::TimeDelta duration) {
115 scoped_ptr<WaitAndExitDelegate> delegate(new WaitAndExitDelegate(duration));
117 const bool thread_created =
118 base::PlatformThread::CreateNonJoinable(0, delegate.get());
119 if (!thread_created)
120 return false;
122 // A non joinable thread has been created. The thread will either terminate
123 // the process or will be terminated by the process. Therefore, keep the
124 // delegate object alive for the lifetime of the process.
125 WaitAndExitDelegate* leaking_delegate = delegate.release();
126 ANNOTATE_LEAKING_OBJECT_PTR(leaking_delegate);
127 ignore_result(leaking_delegate);
128 return true;
130 #endif
132 class SuicideOnChannelErrorFilter : public IPC::MessageFilter {
133 public:
134 // IPC::MessageFilter
135 void OnChannelError() override {
136 // For renderer/worker processes:
137 // On POSIX, at least, one can install an unload handler which loops
138 // forever and leave behind a renderer process which eats 100% CPU forever.
140 // This is because the terminate signals (FrameMsg_BeforeUnload and the
141 // error from the IPC sender) are routed to the main message loop but never
142 // processed (because that message loop is stuck in V8).
144 // One could make the browser SIGKILL the renderers, but that leaves open a
145 // large window where a browser failure (or a user, manually terminating
146 // the browser because "it's stuck") will leave behind a process eating all
147 // the CPU.
149 // So, we install a filter on the sender so that we can process this event
150 // here and kill the process.
151 base::debug::StopProfiling();
152 #if defined(ADDRESS_SANITIZER) || defined(LEAK_SANITIZER) || \
153 defined(MEMORY_SANITIZER) || defined(THREAD_SANITIZER) || \
154 defined(UNDEFINED_SANITIZER)
155 // Some sanitizer tools rely on exit handlers (e.g. to run leak detection,
156 // or dump code coverage data to disk). Instead of exiting the process
157 // immediately, we give it 60 seconds to run exit handlers.
158 CHECK(CreateWaitAndExitThread(base::TimeDelta::FromSeconds(60)));
159 #if defined(LEAK_SANITIZER)
160 // Invoke LeakSanitizer early to avoid detecting shutdown-only leaks. If
161 // leaks are found, the process will exit here.
162 __lsan_do_leak_check();
163 #endif
164 #else
165 _exit(0);
166 #endif
169 protected:
170 ~SuicideOnChannelErrorFilter() override {}
173 #endif // OS(POSIX)
175 #if defined(OS_MACOSX)
176 class IOSurfaceManagerFilter : public IPC::MessageFilter {
177 public:
178 // Overridden from IPC::MessageFilter:
179 bool OnMessageReceived(const IPC::Message& message) override {
180 bool handled = true;
181 IPC_BEGIN_MESSAGE_MAP(IOSurfaceManagerFilter, message)
182 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetIOSurfaceManagerToken,
183 OnSetIOSurfaceManagerToken)
184 IPC_MESSAGE_UNHANDLED(handled = false)
185 IPC_END_MESSAGE_MAP()
186 return handled;
189 protected:
190 ~IOSurfaceManagerFilter() override {}
192 void OnSetIOSurfaceManagerToken(const IOSurfaceManagerToken& token) {
193 ChildIOSurfaceManager::GetInstance()->set_token(token);
196 #endif
198 #if defined(USE_OZONE)
199 class ClientNativePixmapFactoryFilter : public IPC::MessageFilter {
200 public:
201 // Overridden from IPC::MessageFilter:
202 bool OnMessageReceived(const IPC::Message& message) override {
203 bool handled = true;
204 IPC_BEGIN_MESSAGE_MAP(ClientNativePixmapFactoryFilter, message)
205 IPC_MESSAGE_HANDLER(ChildProcessMsg_InitializeClientNativePixmapFactory,
206 OnInitializeClientNativePixmapFactory)
207 IPC_MESSAGE_UNHANDLED(handled = false)
208 IPC_END_MESSAGE_MAP()
209 return handled;
212 protected:
213 ~ClientNativePixmapFactoryFilter() override {}
215 void OnInitializeClientNativePixmapFactory(
216 const base::FileDescriptor& device_fd) {
217 ui::ClientNativePixmapFactory::GetInstance()->Initialize(
218 base::ScopedFD(device_fd.fd));
221 #endif
223 #if defined(OS_ANDROID)
224 // A class that allows for triggering a clean shutdown from another
225 // thread through draining the main thread's msg loop.
226 class QuitClosure {
227 public:
228 QuitClosure();
229 ~QuitClosure();
231 void BindToMainThread();
232 void PostQuitFromNonMainThread();
234 private:
235 static void PostClosure(
236 const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
237 base::Closure closure);
239 base::Lock lock_;
240 base::ConditionVariable cond_var_;
241 base::Closure closure_;
244 QuitClosure::QuitClosure() : cond_var_(&lock_) {
247 QuitClosure::~QuitClosure() {
250 void QuitClosure::PostClosure(
251 const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
252 base::Closure closure) {
253 task_runner->PostTask(FROM_HERE, closure);
256 void QuitClosure::BindToMainThread() {
257 base::AutoLock lock(lock_);
258 scoped_refptr<base::SingleThreadTaskRunner> task_runner(
259 base::ThreadTaskRunnerHandle::Get());
260 base::Closure quit_closure =
261 base::MessageLoop::current()->QuitWhenIdleClosure();
262 closure_ = base::Bind(&QuitClosure::PostClosure, task_runner, quit_closure);
263 cond_var_.Signal();
266 void QuitClosure::PostQuitFromNonMainThread() {
267 base::AutoLock lock(lock_);
268 while (closure_.is_null())
269 cond_var_.Wait();
271 closure_.Run();
274 base::LazyInstance<QuitClosure> g_quit_closure = LAZY_INSTANCE_INITIALIZER;
275 #endif
277 } // namespace
279 ChildThread* ChildThread::Get() {
280 return ChildThreadImpl::current();
283 ChildThreadImpl::Options::Options()
284 : channel_name(base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
285 switches::kProcessChannelID)),
286 use_mojo_channel(false) {
289 ChildThreadImpl::Options::~Options() {
292 ChildThreadImpl::Options::Builder::Builder() {
295 ChildThreadImpl::Options::Builder&
296 ChildThreadImpl::Options::Builder::InBrowserProcess(
297 const InProcessChildThreadParams& params) {
298 options_.browser_process_io_runner = params.io_runner();
299 options_.channel_name = params.channel_name();
300 return *this;
303 ChildThreadImpl::Options::Builder&
304 ChildThreadImpl::Options::Builder::UseMojoChannel(bool use_mojo_channel) {
305 options_.use_mojo_channel = use_mojo_channel;
306 return *this;
309 ChildThreadImpl::Options::Builder&
310 ChildThreadImpl::Options::Builder::WithChannelName(
311 const std::string& channel_name) {
312 options_.channel_name = channel_name;
313 return *this;
316 ChildThreadImpl::Options::Builder&
317 ChildThreadImpl::Options::Builder::AddStartupFilter(
318 IPC::MessageFilter* filter) {
319 options_.startup_filters.push_back(filter);
320 return *this;
323 ChildThreadImpl::Options ChildThreadImpl::Options::Builder::Build() {
324 return options_;
327 ChildThreadImpl::ChildThreadMessageRouter::ChildThreadMessageRouter(
328 IPC::Sender* sender)
329 : sender_(sender) {}
331 bool ChildThreadImpl::ChildThreadMessageRouter::Send(IPC::Message* msg) {
332 return sender_->Send(msg);
335 ChildThreadImpl::ChildThreadImpl()
336 : router_(this),
337 channel_connected_factory_(this) {
338 Init(Options::Builder().Build());
341 ChildThreadImpl::ChildThreadImpl(const Options& options)
342 : router_(this),
343 browser_process_io_runner_(options.browser_process_io_runner),
344 channel_connected_factory_(this) {
345 Init(options);
348 scoped_refptr<base::SequencedTaskRunner> ChildThreadImpl::GetIOTaskRunner() {
349 if (IsInBrowserProcess())
350 return browser_process_io_runner_;
351 return ChildProcess::current()->io_task_runner();
354 void ChildThreadImpl::ConnectChannel(bool use_mojo_channel) {
355 bool create_pipe_now = true;
356 if (use_mojo_channel) {
357 VLOG(1) << "Mojo is enabled on child";
358 scoped_refptr<base::SequencedTaskRunner> io_task_runner = GetIOTaskRunner();
359 DCHECK(io_task_runner);
360 channel_->Init(
361 IPC::ChannelMojo::CreateClientFactory(io_task_runner, channel_name_),
362 create_pipe_now);
363 return;
366 VLOG(1) << "Mojo is disabled on child";
367 channel_->Init(channel_name_, IPC::Channel::MODE_CLIENT, create_pipe_now);
370 void ChildThreadImpl::Init(const Options& options) {
371 channel_name_ = options.channel_name;
373 g_lazy_tls.Pointer()->Set(this);
374 on_channel_error_called_ = false;
375 message_loop_ = base::MessageLoop::current();
376 #ifdef IPC_MESSAGE_LOG_ENABLED
377 // We must make sure to instantiate the IPC Logger *before* we create the
378 // channel, otherwise we can get a callback on the IO thread which creates
379 // the logger, and the logger does not like being created on the IO thread.
380 IPC::Logging::GetInstance();
381 #endif
383 #if defined(OS_WIN)
384 // The only reason a global would already exist is if the thread is being run
385 // in the browser process because of a command line switch.
386 if (!IPC::AttachmentBroker::GetGlobal()) {
387 attachment_broker_.reset(new IPC::AttachmentBrokerUnprivilegedWin());
388 IPC::AttachmentBroker::SetGlobal(attachment_broker_.get());
390 #endif
392 channel_ =
393 IPC::SyncChannel::Create(this, ChildProcess::current()->io_task_runner(),
394 ChildProcess::current()->GetShutDownEvent());
395 #ifdef IPC_MESSAGE_LOG_ENABLED
396 if (!IsInBrowserProcess())
397 IPC::Logging::GetInstance()->SetIPCSender(this);
398 #endif
400 mojo_application_.reset(new MojoApplication(GetIOTaskRunner()));
402 sync_message_filter_ = channel_->CreateSyncMessageFilter();
403 thread_safe_sender_ = new ThreadSafeSender(
404 message_loop_->task_runner(), sync_message_filter_.get());
406 resource_dispatcher_.reset(new ResourceDispatcher(
407 this, message_loop()->task_runner()));
408 websocket_dispatcher_.reset(new WebSocketDispatcher);
409 file_system_dispatcher_.reset(new FileSystemDispatcher());
411 histogram_message_filter_ = new ChildHistogramMessageFilter();
412 resource_message_filter_ =
413 new ChildResourceMessageFilter(resource_dispatcher());
415 service_worker_message_filter_ =
416 new ServiceWorkerMessageFilter(thread_safe_sender_.get());
418 quota_message_filter_ =
419 new QuotaMessageFilter(thread_safe_sender_.get());
420 quota_dispatcher_.reset(new QuotaDispatcher(thread_safe_sender_.get(),
421 quota_message_filter_.get()));
422 geofencing_message_filter_ =
423 new GeofencingMessageFilter(thread_safe_sender_.get());
424 notification_dispatcher_ =
425 new NotificationDispatcher(thread_safe_sender_.get());
426 push_dispatcher_ = new PushDispatcher(thread_safe_sender_.get());
428 channel_->AddFilter(histogram_message_filter_.get());
429 channel_->AddFilter(resource_message_filter_.get());
430 channel_->AddFilter(quota_message_filter_->GetFilter());
431 channel_->AddFilter(notification_dispatcher_->GetFilter());
432 channel_->AddFilter(push_dispatcher_->GetFilter());
433 channel_->AddFilter(service_worker_message_filter_->GetFilter());
434 channel_->AddFilter(geofencing_message_filter_->GetFilter());
436 if (!IsInBrowserProcess()) {
437 // In single process mode, browser-side tracing will cover the whole
438 // process including renderers.
439 channel_->AddFilter(new tracing::ChildTraceMessageFilter(
440 ChildProcess::current()->io_task_runner()));
443 // In single process mode we may already have a power monitor
444 if (!base::PowerMonitor::Get()) {
445 scoped_ptr<PowerMonitorBroadcastSource> power_monitor_source(
446 new PowerMonitorBroadcastSource());
447 channel_->AddFilter(power_monitor_source->GetMessageFilter());
449 power_monitor_.reset(new base::PowerMonitor(
450 power_monitor_source.Pass()));
453 #if defined(OS_POSIX)
454 // Check that --process-type is specified so we don't do this in unit tests
455 // and single-process mode.
456 if (base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kProcessType))
457 channel_->AddFilter(new SuicideOnChannelErrorFilter());
458 #endif
460 #if defined(OS_MACOSX)
461 channel_->AddFilter(new IOSurfaceManagerFilter());
462 #endif
464 #if defined(USE_OZONE)
465 channel_->AddFilter(new ClientNativePixmapFactoryFilter());
466 #endif
468 // Add filters passed here via options.
469 for (auto startup_filter : options.startup_filters) {
470 channel_->AddFilter(startup_filter);
473 ConnectChannel(options.use_mojo_channel);
474 if (attachment_broker_)
475 attachment_broker_->DesignateBrokerCommunicationChannel(channel_.get());
477 int connection_timeout = kConnectionTimeoutS;
478 std::string connection_override =
479 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
480 switches::kIPCConnectionTimeout);
481 if (!connection_override.empty()) {
482 int temp;
483 if (base::StringToInt(connection_override, &temp))
484 connection_timeout = temp;
487 message_loop_->task_runner()->PostDelayedTask(
488 FROM_HERE, base::Bind(&ChildThreadImpl::EnsureConnected,
489 channel_connected_factory_.GetWeakPtr()),
490 base::TimeDelta::FromSeconds(connection_timeout));
492 #if defined(OS_ANDROID)
493 g_quit_closure.Get().BindToMainThread();
494 #endif
496 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
497 trace_memory_controller_.reset(new base::trace_event::TraceMemoryController(
498 message_loop_->task_runner(), ::HeapProfilerWithPseudoStackStart,
499 ::HeapProfilerStop, ::GetHeapProfile));
500 #endif
502 shared_bitmap_manager_.reset(
503 new ChildSharedBitmapManager(thread_safe_sender()));
505 gpu_memory_buffer_manager_.reset(
506 new ChildGpuMemoryBufferManager(thread_safe_sender()));
508 discardable_shared_memory_manager_.reset(
509 new ChildDiscardableSharedMemoryManager(thread_safe_sender()));
512 ChildThreadImpl::~ChildThreadImpl() {
513 // ChildDiscardableSharedMemoryManager has to be destroyed while
514 // |thread_safe_sender_| is still valid.
515 discardable_shared_memory_manager_.reset();
517 #ifdef IPC_MESSAGE_LOG_ENABLED
518 IPC::Logging::GetInstance()->SetIPCSender(NULL);
519 #endif
521 channel_->RemoveFilter(histogram_message_filter_.get());
522 channel_->RemoveFilter(sync_message_filter_.get());
524 // The ChannelProxy object caches a pointer to the IPC thread, so need to
525 // reset it as it's not guaranteed to outlive this object.
526 // NOTE: this also has the side-effect of not closing the main IPC channel to
527 // the browser process. This is needed because this is the signal that the
528 // browser uses to know that this process has died, so we need it to be alive
529 // until this process is shut down, and the OS closes the handle
530 // automatically. We used to watch the object handle on Windows to do this,
531 // but it wasn't possible to do so on POSIX.
532 channel_->ClearIPCTaskRunner();
533 g_lazy_tls.Pointer()->Set(NULL);
536 void ChildThreadImpl::Shutdown() {
537 // Delete objects that hold references to blink so derived classes can
538 // safely shutdown blink in their Shutdown implementation.
539 file_system_dispatcher_.reset();
540 quota_dispatcher_.reset();
541 WebFileSystemImpl::DeleteThreadSpecificInstance();
544 void ChildThreadImpl::OnChannelConnected(int32 peer_pid) {
545 channel_connected_factory_.InvalidateWeakPtrs();
548 void ChildThreadImpl::OnChannelError() {
549 set_on_channel_error_called(true);
550 base::MessageLoop::current()->Quit();
553 bool ChildThreadImpl::Send(IPC::Message* msg) {
554 DCHECK(base::MessageLoop::current() == message_loop());
555 if (!channel_) {
556 delete msg;
557 return false;
560 return channel_->Send(msg);
563 #if defined(OS_WIN)
564 void ChildThreadImpl::PreCacheFont(const LOGFONT& log_font) {
565 Send(new ChildProcessHostMsg_PreCacheFont(log_font));
568 void ChildThreadImpl::ReleaseCachedFonts() {
569 Send(new ChildProcessHostMsg_ReleaseCachedFonts());
571 #endif
573 MessageRouter* ChildThreadImpl::GetRouter() {
574 DCHECK(base::MessageLoop::current() == message_loop());
575 return &router_;
578 scoped_ptr<base::SharedMemory> ChildThreadImpl::AllocateSharedMemory(
579 size_t buf_size) {
580 DCHECK(base::MessageLoop::current() == message_loop());
581 return AllocateSharedMemory(buf_size, this);
584 // static
585 scoped_ptr<base::SharedMemory> ChildThreadImpl::AllocateSharedMemory(
586 size_t buf_size,
587 IPC::Sender* sender) {
588 scoped_ptr<base::SharedMemory> shared_buf;
589 #if defined(OS_WIN)
590 shared_buf.reset(new base::SharedMemory);
591 if (!shared_buf->CreateAnonymous(buf_size)) {
592 NOTREACHED();
593 return NULL;
595 #else
596 // On POSIX, we need to ask the browser to create the shared memory for us,
597 // since this is blocked by the sandbox.
598 base::SharedMemoryHandle shared_mem_handle;
599 if (sender->Send(new ChildProcessHostMsg_SyncAllocateSharedMemory(
600 buf_size, &shared_mem_handle))) {
601 if (base::SharedMemory::IsHandleValid(shared_mem_handle)) {
602 shared_buf.reset(new base::SharedMemory(shared_mem_handle, false));
603 } else {
604 NOTREACHED() << "Browser failed to allocate shared memory";
605 return NULL;
607 } else {
608 NOTREACHED() << "Browser allocation request message failed";
609 return NULL;
611 #endif
612 return shared_buf;
615 bool ChildThreadImpl::OnMessageReceived(const IPC::Message& msg) {
616 if (mojo_application_->OnMessageReceived(msg))
617 return true;
619 // Resource responses are sent to the resource dispatcher.
620 if (resource_dispatcher_->OnMessageReceived(msg))
621 return true;
622 if (websocket_dispatcher_->OnMessageReceived(msg))
623 return true;
624 if (file_system_dispatcher_->OnMessageReceived(msg))
625 return true;
627 bool handled = true;
628 IPC_BEGIN_MESSAGE_MAP(ChildThreadImpl, msg)
629 IPC_MESSAGE_HANDLER(ChildProcessMsg_Shutdown, OnShutdown)
630 #if defined(IPC_MESSAGE_LOG_ENABLED)
631 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetIPCLoggingEnabled,
632 OnSetIPCLoggingEnabled)
633 #endif
634 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetProfilerStatus,
635 OnSetProfilerStatus)
636 IPC_MESSAGE_HANDLER(ChildProcessMsg_GetChildProfilerData,
637 OnGetChildProfilerData)
638 IPC_MESSAGE_HANDLER(ChildProcessMsg_ProfilingPhaseCompleted,
639 OnProfilingPhaseCompleted)
640 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetProcessBackgrounded,
641 OnProcessBackgrounded)
642 #if defined(USE_TCMALLOC)
643 IPC_MESSAGE_HANDLER(ChildProcessMsg_GetTcmallocStats, OnGetTcmallocStats)
644 #endif
645 IPC_MESSAGE_UNHANDLED(handled = false)
646 IPC_END_MESSAGE_MAP()
648 if (handled)
649 return true;
651 if (msg.routing_id() == MSG_ROUTING_CONTROL)
652 return OnControlMessageReceived(msg);
654 return router_.OnMessageReceived(msg);
657 bool ChildThreadImpl::OnControlMessageReceived(const IPC::Message& msg) {
658 return false;
661 void ChildThreadImpl::OnProcessBackgrounded(bool backgrounded) {
662 // Set timer slack to maximum on main thread when in background.
663 base::TimerSlack timer_slack = base::TIMER_SLACK_NONE;
664 if (backgrounded)
665 timer_slack = base::TIMER_SLACK_MAXIMUM;
666 base::MessageLoop::current()->SetTimerSlack(timer_slack);
669 void ChildThreadImpl::OnShutdown() {
670 base::MessageLoop::current()->Quit();
673 #if defined(IPC_MESSAGE_LOG_ENABLED)
674 void ChildThreadImpl::OnSetIPCLoggingEnabled(bool enable) {
675 if (enable)
676 IPC::Logging::GetInstance()->Enable();
677 else
678 IPC::Logging::GetInstance()->Disable();
680 #endif // IPC_MESSAGE_LOG_ENABLED
682 void ChildThreadImpl::OnSetProfilerStatus(ThreadData::Status status) {
683 ThreadData::InitializeAndSetTrackingStatus(status);
686 void ChildThreadImpl::OnGetChildProfilerData(int sequence_number,
687 int current_profiling_phase) {
688 tracked_objects::ProcessDataSnapshot process_data;
689 ThreadData::Snapshot(current_profiling_phase, &process_data);
691 Send(
692 new ChildProcessHostMsg_ChildProfilerData(sequence_number, process_data));
695 void ChildThreadImpl::OnProfilingPhaseCompleted(int profiling_phase) {
696 ThreadData::OnProfilingPhaseCompleted(profiling_phase);
699 #if defined(USE_TCMALLOC)
700 void ChildThreadImpl::OnGetTcmallocStats() {
701 std::string result;
702 char buffer[1024 * 32];
703 base::allocator::GetStats(buffer, sizeof(buffer));
704 result.append(buffer);
705 Send(new ChildProcessHostMsg_TcmallocStats(result));
707 #endif
709 ChildThreadImpl* ChildThreadImpl::current() {
710 return g_lazy_tls.Pointer()->Get();
713 #if defined(OS_ANDROID)
714 // The method must NOT be called on the child thread itself.
715 // It may block the child thread if so.
716 void ChildThreadImpl::ShutdownThread() {
717 DCHECK(!ChildThreadImpl::current()) <<
718 "this method should NOT be called from child thread itself";
719 g_quit_closure.Get().PostQuitFromNonMainThread();
721 #endif
723 void ChildThreadImpl::OnProcessFinalRelease() {
724 if (on_channel_error_called_) {
725 base::MessageLoop::current()->Quit();
726 return;
729 // The child process shutdown sequence is a request response based mechanism,
730 // where we send out an initial feeler request to the child process host
731 // instance in the browser to verify if it's ok to shutdown the child process.
732 // The browser then sends back a response if it's ok to shutdown. This avoids
733 // race conditions if the process refcount is 0 but there's an IPC message
734 // inflight that would addref it.
735 Send(new ChildProcessHostMsg_ShutdownRequest);
738 void ChildThreadImpl::EnsureConnected() {
739 VLOG(0) << "ChildThreadImpl::EnsureConnected()";
740 base::Process::Current().Terminate(0, false);
743 bool ChildThreadImpl::IsInBrowserProcess() const {
744 return browser_process_io_runner_;
747 } // namespace content