Roll src/third_party/WebKit a452221:9ff6d11 (svn 202117:202119)
[chromium-blink-merge.git] / content / child / child_thread_impl.cc
blob08c2075f7faef7542f94dc26911e6a202ab93eda
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(IPC::ChannelMojo::CreateClientFactory(
361 io_task_runner, channel_name_, attachment_broker_.get()),
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,
368 attachment_broker_.get());
371 void ChildThreadImpl::Init(const Options& options) {
372 channel_name_ = options.channel_name;
374 g_lazy_tls.Pointer()->Set(this);
375 on_channel_error_called_ = false;
376 message_loop_ = base::MessageLoop::current();
377 #ifdef IPC_MESSAGE_LOG_ENABLED
378 // We must make sure to instantiate the IPC Logger *before* we create the
379 // channel, otherwise we can get a callback on the IO thread which creates
380 // the logger, and the logger does not like being created on the IO thread.
381 IPC::Logging::GetInstance();
382 #endif
383 channel_ =
384 IPC::SyncChannel::Create(this, ChildProcess::current()->io_task_runner(),
385 ChildProcess::current()->GetShutDownEvent());
386 #ifdef IPC_MESSAGE_LOG_ENABLED
387 if (!IsInBrowserProcess())
388 IPC::Logging::GetInstance()->SetIPCSender(this);
389 #endif
391 #if defined(OS_WIN)
392 attachment_broker_.reset(new IPC::AttachmentBrokerUnprivilegedWin());
393 #endif
395 mojo_application_.reset(new MojoApplication(GetIOTaskRunner()));
397 sync_message_filter_ = channel_->CreateSyncMessageFilter();
398 thread_safe_sender_ = new ThreadSafeSender(
399 message_loop_->task_runner(), sync_message_filter_.get());
401 resource_dispatcher_.reset(new ResourceDispatcher(
402 this, message_loop()->task_runner()));
403 websocket_dispatcher_.reset(new WebSocketDispatcher);
404 file_system_dispatcher_.reset(new FileSystemDispatcher());
406 histogram_message_filter_ = new ChildHistogramMessageFilter();
407 resource_message_filter_ =
408 new ChildResourceMessageFilter(resource_dispatcher());
410 service_worker_message_filter_ =
411 new ServiceWorkerMessageFilter(thread_safe_sender_.get());
413 quota_message_filter_ =
414 new QuotaMessageFilter(thread_safe_sender_.get());
415 quota_dispatcher_.reset(new QuotaDispatcher(thread_safe_sender_.get(),
416 quota_message_filter_.get()));
417 geofencing_message_filter_ =
418 new GeofencingMessageFilter(thread_safe_sender_.get());
419 notification_dispatcher_ =
420 new NotificationDispatcher(thread_safe_sender_.get());
421 push_dispatcher_ = new PushDispatcher(thread_safe_sender_.get());
423 channel_->AddFilter(histogram_message_filter_.get());
424 channel_->AddFilter(resource_message_filter_.get());
425 channel_->AddFilter(quota_message_filter_->GetFilter());
426 channel_->AddFilter(notification_dispatcher_->GetFilter());
427 channel_->AddFilter(push_dispatcher_->GetFilter());
428 channel_->AddFilter(service_worker_message_filter_->GetFilter());
429 channel_->AddFilter(geofencing_message_filter_->GetFilter());
431 if (!IsInBrowserProcess()) {
432 // In single process mode, browser-side tracing will cover the whole
433 // process including renderers.
434 channel_->AddFilter(new tracing::ChildTraceMessageFilter(
435 ChildProcess::current()->io_task_runner()));
438 // In single process mode we may already have a power monitor
439 if (!base::PowerMonitor::Get()) {
440 scoped_ptr<PowerMonitorBroadcastSource> power_monitor_source(
441 new PowerMonitorBroadcastSource());
442 channel_->AddFilter(power_monitor_source->GetMessageFilter());
444 power_monitor_.reset(new base::PowerMonitor(
445 power_monitor_source.Pass()));
448 #if defined(OS_POSIX)
449 // Check that --process-type is specified so we don't do this in unit tests
450 // and single-process mode.
451 if (base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kProcessType))
452 channel_->AddFilter(new SuicideOnChannelErrorFilter());
453 #endif
455 #if defined(OS_MACOSX)
456 channel_->AddFilter(new IOSurfaceManagerFilter());
457 #endif
459 #if defined(USE_OZONE)
460 channel_->AddFilter(new ClientNativePixmapFactoryFilter());
461 #endif
463 // Add filters passed here via options.
464 for (auto startup_filter : options.startup_filters) {
465 channel_->AddFilter(startup_filter);
468 ConnectChannel(options.use_mojo_channel);
469 if (attachment_broker_)
470 attachment_broker_->DesignateBrokerCommunicationChannel(channel_.get());
472 int connection_timeout = kConnectionTimeoutS;
473 std::string connection_override =
474 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
475 switches::kIPCConnectionTimeout);
476 if (!connection_override.empty()) {
477 int temp;
478 if (base::StringToInt(connection_override, &temp))
479 connection_timeout = temp;
482 message_loop_->task_runner()->PostDelayedTask(
483 FROM_HERE, base::Bind(&ChildThreadImpl::EnsureConnected,
484 channel_connected_factory_.GetWeakPtr()),
485 base::TimeDelta::FromSeconds(connection_timeout));
487 #if defined(OS_ANDROID)
488 g_quit_closure.Get().BindToMainThread();
489 #endif
491 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
492 trace_memory_controller_.reset(new base::trace_event::TraceMemoryController(
493 message_loop_->task_runner(), ::HeapProfilerWithPseudoStackStart,
494 ::HeapProfilerStop, ::GetHeapProfile));
495 #endif
497 shared_bitmap_manager_.reset(
498 new ChildSharedBitmapManager(thread_safe_sender()));
500 gpu_memory_buffer_manager_.reset(
501 new ChildGpuMemoryBufferManager(thread_safe_sender()));
503 discardable_shared_memory_manager_.reset(
504 new ChildDiscardableSharedMemoryManager(thread_safe_sender()));
507 ChildThreadImpl::~ChildThreadImpl() {
508 // ChildDiscardableSharedMemoryManager has to be destroyed while
509 // |thread_safe_sender_| is still valid.
510 discardable_shared_memory_manager_.reset();
512 #ifdef IPC_MESSAGE_LOG_ENABLED
513 IPC::Logging::GetInstance()->SetIPCSender(NULL);
514 #endif
516 channel_->RemoveFilter(histogram_message_filter_.get());
517 channel_->RemoveFilter(sync_message_filter_.get());
519 // The ChannelProxy object caches a pointer to the IPC thread, so need to
520 // reset it as it's not guaranteed to outlive this object.
521 // NOTE: this also has the side-effect of not closing the main IPC channel to
522 // the browser process. This is needed because this is the signal that the
523 // browser uses to know that this process has died, so we need it to be alive
524 // until this process is shut down, and the OS closes the handle
525 // automatically. We used to watch the object handle on Windows to do this,
526 // but it wasn't possible to do so on POSIX.
527 channel_->ClearIPCTaskRunner();
528 g_lazy_tls.Pointer()->Set(NULL);
531 void ChildThreadImpl::Shutdown() {
532 // Delete objects that hold references to blink so derived classes can
533 // safely shutdown blink in their Shutdown implementation.
534 file_system_dispatcher_.reset();
535 quota_dispatcher_.reset();
536 WebFileSystemImpl::DeleteThreadSpecificInstance();
539 void ChildThreadImpl::OnChannelConnected(int32 peer_pid) {
540 channel_connected_factory_.InvalidateWeakPtrs();
543 void ChildThreadImpl::OnChannelError() {
544 set_on_channel_error_called(true);
545 base::MessageLoop::current()->Quit();
548 bool ChildThreadImpl::Send(IPC::Message* msg) {
549 DCHECK(base::MessageLoop::current() == message_loop());
550 if (!channel_) {
551 delete msg;
552 return false;
555 return channel_->Send(msg);
558 #if defined(OS_WIN)
559 void ChildThreadImpl::PreCacheFont(const LOGFONT& log_font) {
560 Send(new ChildProcessHostMsg_PreCacheFont(log_font));
563 void ChildThreadImpl::ReleaseCachedFonts() {
564 Send(new ChildProcessHostMsg_ReleaseCachedFonts());
566 #endif
568 IPC::AttachmentBroker* ChildThreadImpl::GetAttachmentBroker() {
569 return attachment_broker_.get();
572 MessageRouter* ChildThreadImpl::GetRouter() {
573 DCHECK(base::MessageLoop::current() == message_loop());
574 return &router_;
577 scoped_ptr<base::SharedMemory> ChildThreadImpl::AllocateSharedMemory(
578 size_t buf_size) {
579 DCHECK(base::MessageLoop::current() == message_loop());
580 return AllocateSharedMemory(buf_size, this);
583 // static
584 scoped_ptr<base::SharedMemory> ChildThreadImpl::AllocateSharedMemory(
585 size_t buf_size,
586 IPC::Sender* sender) {
587 scoped_ptr<base::SharedMemory> shared_buf;
588 #if defined(OS_WIN)
589 shared_buf.reset(new base::SharedMemory);
590 if (!shared_buf->CreateAnonymous(buf_size)) {
591 NOTREACHED();
592 return NULL;
594 #else
595 // On POSIX, we need to ask the browser to create the shared memory for us,
596 // since this is blocked by the sandbox.
597 base::SharedMemoryHandle shared_mem_handle;
598 if (sender->Send(new ChildProcessHostMsg_SyncAllocateSharedMemory(
599 buf_size, &shared_mem_handle))) {
600 if (base::SharedMemory::IsHandleValid(shared_mem_handle)) {
601 shared_buf.reset(new base::SharedMemory(shared_mem_handle, false));
602 } else {
603 NOTREACHED() << "Browser failed to allocate shared memory";
604 return NULL;
606 } else {
607 NOTREACHED() << "Browser allocation request message failed";
608 return NULL;
610 #endif
611 return shared_buf;
614 bool ChildThreadImpl::OnMessageReceived(const IPC::Message& msg) {
615 if (mojo_application_->OnMessageReceived(msg))
616 return true;
618 // Resource responses are sent to the resource dispatcher.
619 if (resource_dispatcher_->OnMessageReceived(msg))
620 return true;
621 if (websocket_dispatcher_->OnMessageReceived(msg))
622 return true;
623 if (file_system_dispatcher_->OnMessageReceived(msg))
624 return true;
626 bool handled = true;
627 IPC_BEGIN_MESSAGE_MAP(ChildThreadImpl, msg)
628 IPC_MESSAGE_HANDLER(ChildProcessMsg_Shutdown, OnShutdown)
629 #if defined(IPC_MESSAGE_LOG_ENABLED)
630 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetIPCLoggingEnabled,
631 OnSetIPCLoggingEnabled)
632 #endif
633 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetProfilerStatus,
634 OnSetProfilerStatus)
635 IPC_MESSAGE_HANDLER(ChildProcessMsg_GetChildProfilerData,
636 OnGetChildProfilerData)
637 IPC_MESSAGE_HANDLER(ChildProcessMsg_ProfilingPhaseCompleted,
638 OnProfilingPhaseCompleted)
639 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetProcessBackgrounded,
640 OnProcessBackgrounded)
641 #if defined(USE_TCMALLOC)
642 IPC_MESSAGE_HANDLER(ChildProcessMsg_GetTcmallocStats, OnGetTcmallocStats)
643 #endif
644 IPC_MESSAGE_UNHANDLED(handled = false)
645 IPC_END_MESSAGE_MAP()
647 if (handled)
648 return true;
650 if (msg.routing_id() == MSG_ROUTING_CONTROL)
651 return OnControlMessageReceived(msg);
653 return router_.OnMessageReceived(msg);
656 bool ChildThreadImpl::OnControlMessageReceived(const IPC::Message& msg) {
657 return false;
660 void ChildThreadImpl::OnProcessBackgrounded(bool backgrounded) {
661 // Set timer slack to maximum on main thread when in background.
662 base::TimerSlack timer_slack = base::TIMER_SLACK_NONE;
663 if (backgrounded)
664 timer_slack = base::TIMER_SLACK_MAXIMUM;
665 base::MessageLoop::current()->SetTimerSlack(timer_slack);
668 void ChildThreadImpl::OnShutdown() {
669 base::MessageLoop::current()->Quit();
672 #if defined(IPC_MESSAGE_LOG_ENABLED)
673 void ChildThreadImpl::OnSetIPCLoggingEnabled(bool enable) {
674 if (enable)
675 IPC::Logging::GetInstance()->Enable();
676 else
677 IPC::Logging::GetInstance()->Disable();
679 #endif // IPC_MESSAGE_LOG_ENABLED
681 void ChildThreadImpl::OnSetProfilerStatus(ThreadData::Status status) {
682 ThreadData::InitializeAndSetTrackingStatus(status);
685 void ChildThreadImpl::OnGetChildProfilerData(int sequence_number,
686 int current_profiling_phase) {
687 tracked_objects::ProcessDataSnapshot process_data;
688 ThreadData::Snapshot(current_profiling_phase, &process_data);
690 Send(
691 new ChildProcessHostMsg_ChildProfilerData(sequence_number, process_data));
694 void ChildThreadImpl::OnProfilingPhaseCompleted(int profiling_phase) {
695 ThreadData::OnProfilingPhaseCompleted(profiling_phase);
698 #if defined(USE_TCMALLOC)
699 void ChildThreadImpl::OnGetTcmallocStats() {
700 std::string result;
701 char buffer[1024 * 32];
702 base::allocator::GetStats(buffer, sizeof(buffer));
703 result.append(buffer);
704 Send(new ChildProcessHostMsg_TcmallocStats(result));
706 #endif
708 ChildThreadImpl* ChildThreadImpl::current() {
709 return g_lazy_tls.Pointer()->Get();
712 #if defined(OS_ANDROID)
713 // The method must NOT be called on the child thread itself.
714 // It may block the child thread if so.
715 void ChildThreadImpl::ShutdownThread() {
716 DCHECK(!ChildThreadImpl::current()) <<
717 "this method should NOT be called from child thread itself";
718 g_quit_closure.Get().PostQuitFromNonMainThread();
720 #endif
722 void ChildThreadImpl::OnProcessFinalRelease() {
723 if (on_channel_error_called_) {
724 base::MessageLoop::current()->Quit();
725 return;
728 // The child process shutdown sequence is a request response based mechanism,
729 // where we send out an initial feeler request to the child process host
730 // instance in the browser to verify if it's ok to shutdown the child process.
731 // The browser then sends back a response if it's ok to shutdown. This avoids
732 // race conditions if the process refcount is 0 but there's an IPC message
733 // inflight that would addref it.
734 Send(new ChildProcessHostMsg_ShutdownRequest);
737 void ChildThreadImpl::EnsureConnected() {
738 VLOG(0) << "ChildThreadImpl::EnsureConnected()";
739 base::Process::Current().Terminate(0, false);
742 bool ChildThreadImpl::IsInBrowserProcess() const {
743 return browser_process_io_runner_;
746 } // namespace content