Reland debugging for ipc related crash.
[chromium-blink-merge.git] / content / child / child_thread_impl.cc
blob890b30a7712e4a7bfb95964314b9722d56ba8441
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/common/resource_messages.h"
55 #include "content/public/common/content_switches.h"
56 #include "ipc/attachment_broker_unprivileged.h"
57 #include "ipc/ipc_channel.h"
58 #include "ipc/ipc_logging.h"
59 #include "ipc/ipc_switches.h"
60 #include "ipc/ipc_sync_channel.h"
61 #include "ipc/ipc_sync_message_filter.h"
62 #include "ipc/mojo/ipc_channel_mojo.h"
64 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
65 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
66 #endif
68 #if defined(OS_MACOSX)
69 #include "content/child/child_io_surface_manager_mac.h"
70 #endif
72 #if defined(USE_OZONE)
73 #include "ui/ozone/public/client_native_pixmap_factory.h"
74 #endif
76 #if defined(OS_WIN)
77 #include "ipc/attachment_broker_unprivileged_win.h"
78 #endif
80 using tracked_objects::ThreadData;
82 namespace content {
83 namespace {
85 // How long to wait for a connection to the browser process before giving up.
86 const int kConnectionTimeoutS = 15;
88 base::LazyInstance<base::ThreadLocalPointer<ChildThreadImpl> > g_lazy_tls =
89 LAZY_INSTANCE_INITIALIZER;
91 // This isn't needed on Windows because there the sandbox's job object
92 // terminates child processes automatically. For unsandboxed processes (i.e.
93 // plugins), PluginThread has EnsureTerminateMessageFilter.
94 #if defined(OS_POSIX)
96 #if defined(ADDRESS_SANITIZER) || defined(LEAK_SANITIZER) || \
97 defined(MEMORY_SANITIZER) || defined(THREAD_SANITIZER) || \
98 defined(UNDEFINED_SANITIZER)
99 // A thread delegate that waits for |duration| and then exits the process with
100 // _exit(0).
101 class WaitAndExitDelegate : public base::PlatformThread::Delegate {
102 public:
103 explicit WaitAndExitDelegate(base::TimeDelta duration)
104 : duration_(duration) {}
106 void ThreadMain() override {
107 base::PlatformThread::Sleep(duration_);
108 _exit(0);
111 private:
112 const base::TimeDelta duration_;
113 DISALLOW_COPY_AND_ASSIGN(WaitAndExitDelegate);
116 bool CreateWaitAndExitThread(base::TimeDelta duration) {
117 scoped_ptr<WaitAndExitDelegate> delegate(new WaitAndExitDelegate(duration));
119 const bool thread_created =
120 base::PlatformThread::CreateNonJoinable(0, delegate.get());
121 if (!thread_created)
122 return false;
124 // A non joinable thread has been created. The thread will either terminate
125 // the process or will be terminated by the process. Therefore, keep the
126 // delegate object alive for the lifetime of the process.
127 WaitAndExitDelegate* leaking_delegate = delegate.release();
128 ANNOTATE_LEAKING_OBJECT_PTR(leaking_delegate);
129 ignore_result(leaking_delegate);
130 return true;
132 #endif
134 class SuicideOnChannelErrorFilter : public IPC::MessageFilter {
135 public:
136 // IPC::MessageFilter
137 void OnChannelError() override {
138 // For renderer/worker processes:
139 // On POSIX, at least, one can install an unload handler which loops
140 // forever and leave behind a renderer process which eats 100% CPU forever.
142 // This is because the terminate signals (FrameMsg_BeforeUnload and the
143 // error from the IPC sender) are routed to the main message loop but never
144 // processed (because that message loop is stuck in V8).
146 // One could make the browser SIGKILL the renderers, but that leaves open a
147 // large window where a browser failure (or a user, manually terminating
148 // the browser because "it's stuck") will leave behind a process eating all
149 // the CPU.
151 // So, we install a filter on the sender so that we can process this event
152 // here and kill the process.
153 base::debug::StopProfiling();
154 #if defined(ADDRESS_SANITIZER) || defined(LEAK_SANITIZER) || \
155 defined(MEMORY_SANITIZER) || defined(THREAD_SANITIZER) || \
156 defined(UNDEFINED_SANITIZER)
157 // Some sanitizer tools rely on exit handlers (e.g. to run leak detection,
158 // or dump code coverage data to disk). Instead of exiting the process
159 // immediately, we give it 60 seconds to run exit handlers.
160 CHECK(CreateWaitAndExitThread(base::TimeDelta::FromSeconds(60)));
161 #if defined(LEAK_SANITIZER)
162 // Invoke LeakSanitizer early to avoid detecting shutdown-only leaks. If
163 // leaks are found, the process will exit here.
164 __lsan_do_leak_check();
165 #endif
166 #else
167 _exit(0);
168 #endif
171 protected:
172 ~SuicideOnChannelErrorFilter() override {}
175 #endif // OS(POSIX)
177 #if defined(OS_MACOSX)
178 class IOSurfaceManagerFilter : public IPC::MessageFilter {
179 public:
180 // Overridden from IPC::MessageFilter:
181 bool OnMessageReceived(const IPC::Message& message) override {
182 bool handled = true;
183 IPC_BEGIN_MESSAGE_MAP(IOSurfaceManagerFilter, message)
184 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetIOSurfaceManagerToken,
185 OnSetIOSurfaceManagerToken)
186 IPC_MESSAGE_UNHANDLED(handled = false)
187 IPC_END_MESSAGE_MAP()
188 return handled;
191 protected:
192 ~IOSurfaceManagerFilter() override {}
194 void OnSetIOSurfaceManagerToken(const IOSurfaceManagerToken& token) {
195 ChildIOSurfaceManager::GetInstance()->set_token(token);
198 #endif
200 #if defined(USE_OZONE)
201 class ClientNativePixmapFactoryFilter : public IPC::MessageFilter {
202 public:
203 // Overridden from IPC::MessageFilter:
204 bool OnMessageReceived(const IPC::Message& message) override {
205 bool handled = true;
206 IPC_BEGIN_MESSAGE_MAP(ClientNativePixmapFactoryFilter, message)
207 IPC_MESSAGE_HANDLER(ChildProcessMsg_InitializeClientNativePixmapFactory,
208 OnInitializeClientNativePixmapFactory)
209 IPC_MESSAGE_UNHANDLED(handled = false)
210 IPC_END_MESSAGE_MAP()
211 return handled;
214 protected:
215 ~ClientNativePixmapFactoryFilter() override {}
217 void OnInitializeClientNativePixmapFactory(
218 const base::FileDescriptor& device_fd) {
219 ui::ClientNativePixmapFactory::GetInstance()->Initialize(
220 base::ScopedFD(device_fd.fd));
223 #endif
225 #if defined(OS_ANDROID)
226 // A class that allows for triggering a clean shutdown from another
227 // thread through draining the main thread's msg loop.
228 class QuitClosure {
229 public:
230 QuitClosure();
231 ~QuitClosure();
233 void BindToMainThread();
234 void PostQuitFromNonMainThread();
236 private:
237 static void PostClosure(
238 const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
239 base::Closure closure);
241 base::Lock lock_;
242 base::ConditionVariable cond_var_;
243 base::Closure closure_;
246 QuitClosure::QuitClosure() : cond_var_(&lock_) {
249 QuitClosure::~QuitClosure() {
252 void QuitClosure::PostClosure(
253 const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
254 base::Closure closure) {
255 task_runner->PostTask(FROM_HERE, closure);
258 void QuitClosure::BindToMainThread() {
259 base::AutoLock lock(lock_);
260 scoped_refptr<base::SingleThreadTaskRunner> task_runner(
261 base::ThreadTaskRunnerHandle::Get());
262 base::Closure quit_closure =
263 base::MessageLoop::current()->QuitWhenIdleClosure();
264 closure_ = base::Bind(&QuitClosure::PostClosure, task_runner, quit_closure);
265 cond_var_.Signal();
268 void QuitClosure::PostQuitFromNonMainThread() {
269 base::AutoLock lock(lock_);
270 while (closure_.is_null())
271 cond_var_.Wait();
273 closure_.Run();
276 base::LazyInstance<QuitClosure> g_quit_closure = LAZY_INSTANCE_INITIALIZER;
277 #endif
279 } // namespace
281 ChildThread* ChildThread::Get() {
282 return ChildThreadImpl::current();
285 ChildThreadImpl::Options::Options()
286 : channel_name(base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
287 switches::kProcessChannelID)),
288 use_mojo_channel(false) {
291 ChildThreadImpl::Options::~Options() {
294 ChildThreadImpl::Options::Builder::Builder() {
297 ChildThreadImpl::Options::Builder&
298 ChildThreadImpl::Options::Builder::InBrowserProcess(
299 const InProcessChildThreadParams& params) {
300 options_.browser_process_io_runner = params.io_runner();
301 options_.channel_name = params.channel_name();
302 return *this;
305 ChildThreadImpl::Options::Builder&
306 ChildThreadImpl::Options::Builder::UseMojoChannel(bool use_mojo_channel) {
307 options_.use_mojo_channel = use_mojo_channel;
308 return *this;
311 ChildThreadImpl::Options::Builder&
312 ChildThreadImpl::Options::Builder::WithChannelName(
313 const std::string& channel_name) {
314 options_.channel_name = channel_name;
315 return *this;
318 ChildThreadImpl::Options::Builder&
319 ChildThreadImpl::Options::Builder::AddStartupFilter(
320 IPC::MessageFilter* filter) {
321 options_.startup_filters.push_back(filter);
322 return *this;
325 ChildThreadImpl::Options ChildThreadImpl::Options::Builder::Build() {
326 return options_;
329 ChildThreadImpl::ChildThreadMessageRouter::ChildThreadMessageRouter(
330 IPC::Sender* sender)
331 : sender_(sender) {}
333 bool ChildThreadImpl::ChildThreadMessageRouter::Send(IPC::Message* msg) {
334 return sender_->Send(msg);
337 ChildThreadImpl::ChildThreadImpl()
338 : router_(this),
339 channel_connected_factory_(this) {
340 Init(Options::Builder().Build());
343 ChildThreadImpl::ChildThreadImpl(const Options& options)
344 : router_(this),
345 browser_process_io_runner_(options.browser_process_io_runner),
346 channel_connected_factory_(this) {
347 Init(options);
350 scoped_refptr<base::SequencedTaskRunner> ChildThreadImpl::GetIOTaskRunner() {
351 if (IsInBrowserProcess())
352 return browser_process_io_runner_;
353 return ChildProcess::current()->io_task_runner();
356 void ChildThreadImpl::ConnectChannel(bool use_mojo_channel) {
357 bool create_pipe_now = true;
358 if (use_mojo_channel) {
359 VLOG(1) << "Mojo is enabled on child";
360 scoped_refptr<base::SequencedTaskRunner> io_task_runner = GetIOTaskRunner();
361 DCHECK(io_task_runner);
362 channel_->Init(
363 IPC::ChannelMojo::CreateClientFactory(io_task_runner, channel_name_),
364 create_pipe_now);
365 return;
368 VLOG(1) << "Mojo is disabled on child";
369 channel_->Init(channel_name_, IPC::Channel::MODE_CLIENT, create_pipe_now);
372 void ChildThreadImpl::Init(const Options& options) {
373 channel_name_ = options.channel_name;
375 g_lazy_tls.Pointer()->Set(this);
376 on_channel_error_called_ = false;
377 message_loop_ = base::MessageLoop::current();
378 #ifdef IPC_MESSAGE_LOG_ENABLED
379 // We must make sure to instantiate the IPC Logger *before* we create the
380 // channel, otherwise we can get a callback on the IO thread which creates
381 // the logger, and the logger does not like being created on the IO thread.
382 IPC::Logging::GetInstance();
383 #endif
385 #if defined(OS_WIN)
386 // The only reason a global would already exist is if the thread is being run
387 // in the browser process because of a command line switch.
388 if (!IPC::AttachmentBroker::GetGlobal()) {
389 attachment_broker_.reset(new IPC::AttachmentBrokerUnprivilegedWin());
390 IPC::AttachmentBroker::SetGlobal(attachment_broker_.get());
392 #endif
394 channel_ =
395 IPC::SyncChannel::Create(this, ChildProcess::current()->io_task_runner(),
396 ChildProcess::current()->GetShutDownEvent());
397 #ifdef IPC_MESSAGE_LOG_ENABLED
398 if (!IsInBrowserProcess())
399 IPC::Logging::GetInstance()->SetIPCSender(this);
400 #endif
401 // TODO(erikchen): Temporary code to help track http://crbug.com/527588.
402 IPC::Channel::SetMessageVerifier(
403 &content::CheckContentsOfDataReceivedMessage);
405 mojo_application_.reset(new MojoApplication(GetIOTaskRunner()));
407 sync_message_filter_ = channel_->CreateSyncMessageFilter();
408 thread_safe_sender_ = new ThreadSafeSender(
409 message_loop_->task_runner(), sync_message_filter_.get());
411 resource_dispatcher_.reset(new ResourceDispatcher(
412 this, message_loop()->task_runner()));
413 websocket_dispatcher_.reset(new WebSocketDispatcher);
414 file_system_dispatcher_.reset(new FileSystemDispatcher());
416 histogram_message_filter_ = new ChildHistogramMessageFilter();
417 resource_message_filter_ =
418 new ChildResourceMessageFilter(resource_dispatcher());
420 service_worker_message_filter_ =
421 new ServiceWorkerMessageFilter(thread_safe_sender_.get());
423 quota_message_filter_ =
424 new QuotaMessageFilter(thread_safe_sender_.get());
425 quota_dispatcher_.reset(new QuotaDispatcher(thread_safe_sender_.get(),
426 quota_message_filter_.get()));
427 geofencing_message_filter_ =
428 new GeofencingMessageFilter(thread_safe_sender_.get());
429 notification_dispatcher_ =
430 new NotificationDispatcher(thread_safe_sender_.get());
431 push_dispatcher_ = new PushDispatcher(thread_safe_sender_.get());
433 channel_->AddFilter(histogram_message_filter_.get());
434 channel_->AddFilter(resource_message_filter_.get());
435 channel_->AddFilter(quota_message_filter_->GetFilter());
436 channel_->AddFilter(notification_dispatcher_->GetFilter());
437 channel_->AddFilter(push_dispatcher_->GetFilter());
438 channel_->AddFilter(service_worker_message_filter_->GetFilter());
439 channel_->AddFilter(geofencing_message_filter_->GetFilter());
441 if (!IsInBrowserProcess()) {
442 // In single process mode, browser-side tracing will cover the whole
443 // process including renderers.
444 channel_->AddFilter(new tracing::ChildTraceMessageFilter(
445 ChildProcess::current()->io_task_runner()));
448 // In single process mode we may already have a power monitor
449 if (!base::PowerMonitor::Get()) {
450 scoped_ptr<PowerMonitorBroadcastSource> power_monitor_source(
451 new PowerMonitorBroadcastSource());
452 channel_->AddFilter(power_monitor_source->GetMessageFilter());
454 power_monitor_.reset(new base::PowerMonitor(
455 power_monitor_source.Pass()));
458 #if defined(OS_POSIX)
459 // Check that --process-type is specified so we don't do this in unit tests
460 // and single-process mode.
461 if (base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kProcessType))
462 channel_->AddFilter(new SuicideOnChannelErrorFilter());
463 #endif
465 #if defined(OS_MACOSX)
466 channel_->AddFilter(new IOSurfaceManagerFilter());
467 #endif
469 #if defined(USE_OZONE)
470 channel_->AddFilter(new ClientNativePixmapFactoryFilter());
471 #endif
473 // Add filters passed here via options.
474 for (auto startup_filter : options.startup_filters) {
475 channel_->AddFilter(startup_filter);
478 ConnectChannel(options.use_mojo_channel);
479 if (attachment_broker_)
480 attachment_broker_->DesignateBrokerCommunicationChannel(channel_.get());
482 int connection_timeout = kConnectionTimeoutS;
483 std::string connection_override =
484 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
485 switches::kIPCConnectionTimeout);
486 if (!connection_override.empty()) {
487 int temp;
488 if (base::StringToInt(connection_override, &temp))
489 connection_timeout = temp;
492 message_loop_->task_runner()->PostDelayedTask(
493 FROM_HERE, base::Bind(&ChildThreadImpl::EnsureConnected,
494 channel_connected_factory_.GetWeakPtr()),
495 base::TimeDelta::FromSeconds(connection_timeout));
497 #if defined(OS_ANDROID)
498 g_quit_closure.Get().BindToMainThread();
499 #endif
501 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
502 trace_memory_controller_.reset(new base::trace_event::TraceMemoryController(
503 message_loop_->task_runner(), ::HeapProfilerWithPseudoStackStart,
504 ::HeapProfilerStop, ::GetHeapProfile));
505 #endif
507 shared_bitmap_manager_.reset(
508 new ChildSharedBitmapManager(thread_safe_sender()));
510 gpu_memory_buffer_manager_.reset(
511 new ChildGpuMemoryBufferManager(thread_safe_sender()));
513 discardable_shared_memory_manager_.reset(
514 new ChildDiscardableSharedMemoryManager(thread_safe_sender()));
517 ChildThreadImpl::~ChildThreadImpl() {
518 // ChildDiscardableSharedMemoryManager has to be destroyed while
519 // |thread_safe_sender_| is still valid.
520 discardable_shared_memory_manager_.reset();
522 #ifdef IPC_MESSAGE_LOG_ENABLED
523 IPC::Logging::GetInstance()->SetIPCSender(NULL);
524 #endif
526 channel_->RemoveFilter(histogram_message_filter_.get());
527 channel_->RemoveFilter(sync_message_filter_.get());
529 // The ChannelProxy object caches a pointer to the IPC thread, so need to
530 // reset it as it's not guaranteed to outlive this object.
531 // NOTE: this also has the side-effect of not closing the main IPC channel to
532 // the browser process. This is needed because this is the signal that the
533 // browser uses to know that this process has died, so we need it to be alive
534 // until this process is shut down, and the OS closes the handle
535 // automatically. We used to watch the object handle on Windows to do this,
536 // but it wasn't possible to do so on POSIX.
537 channel_->ClearIPCTaskRunner();
538 g_lazy_tls.Pointer()->Set(NULL);
541 void ChildThreadImpl::Shutdown() {
542 // Delete objects that hold references to blink so derived classes can
543 // safely shutdown blink in their Shutdown implementation.
544 file_system_dispatcher_.reset();
545 quota_dispatcher_.reset();
546 WebFileSystemImpl::DeleteThreadSpecificInstance();
549 void ChildThreadImpl::OnChannelConnected(int32 peer_pid) {
550 channel_connected_factory_.InvalidateWeakPtrs();
553 void ChildThreadImpl::OnChannelError() {
554 set_on_channel_error_called(true);
555 base::MessageLoop::current()->Quit();
558 bool ChildThreadImpl::Send(IPC::Message* msg) {
559 DCHECK(base::MessageLoop::current() == message_loop());
560 if (!channel_) {
561 delete msg;
562 return false;
565 return channel_->Send(msg);
568 #if defined(OS_WIN)
569 void ChildThreadImpl::PreCacheFont(const LOGFONT& log_font) {
570 Send(new ChildProcessHostMsg_PreCacheFont(log_font));
573 void ChildThreadImpl::ReleaseCachedFonts() {
574 Send(new ChildProcessHostMsg_ReleaseCachedFonts());
576 #endif
578 MessageRouter* ChildThreadImpl::GetRouter() {
579 DCHECK(base::MessageLoop::current() == message_loop());
580 return &router_;
583 scoped_ptr<base::SharedMemory> ChildThreadImpl::AllocateSharedMemory(
584 size_t buf_size) {
585 DCHECK(base::MessageLoop::current() == message_loop());
586 return AllocateSharedMemory(buf_size, this);
589 // static
590 scoped_ptr<base::SharedMemory> ChildThreadImpl::AllocateSharedMemory(
591 size_t buf_size,
592 IPC::Sender* sender) {
593 scoped_ptr<base::SharedMemory> shared_buf;
594 #if defined(OS_WIN)
595 shared_buf.reset(new base::SharedMemory);
596 if (!shared_buf->CreateAnonymous(buf_size)) {
597 NOTREACHED();
598 return NULL;
600 #else
601 // On POSIX, we need to ask the browser to create the shared memory for us,
602 // since this is blocked by the sandbox.
603 base::SharedMemoryHandle shared_mem_handle;
604 if (sender->Send(new ChildProcessHostMsg_SyncAllocateSharedMemory(
605 buf_size, &shared_mem_handle))) {
606 if (base::SharedMemory::IsHandleValid(shared_mem_handle)) {
607 shared_buf.reset(new base::SharedMemory(shared_mem_handle, false));
608 } else {
609 NOTREACHED() << "Browser failed to allocate shared memory";
610 return NULL;
612 } else {
613 NOTREACHED() << "Browser allocation request message failed";
614 return NULL;
616 #endif
617 return shared_buf;
620 bool ChildThreadImpl::OnMessageReceived(const IPC::Message& msg) {
621 if (mojo_application_->OnMessageReceived(msg))
622 return true;
624 // Resource responses are sent to the resource dispatcher.
625 if (resource_dispatcher_->OnMessageReceived(msg))
626 return true;
627 if (websocket_dispatcher_->OnMessageReceived(msg))
628 return true;
629 if (file_system_dispatcher_->OnMessageReceived(msg))
630 return true;
632 bool handled = true;
633 IPC_BEGIN_MESSAGE_MAP(ChildThreadImpl, msg)
634 IPC_MESSAGE_HANDLER(ChildProcessMsg_Shutdown, OnShutdown)
635 #if defined(IPC_MESSAGE_LOG_ENABLED)
636 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetIPCLoggingEnabled,
637 OnSetIPCLoggingEnabled)
638 #endif
639 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetProfilerStatus,
640 OnSetProfilerStatus)
641 IPC_MESSAGE_HANDLER(ChildProcessMsg_GetChildProfilerData,
642 OnGetChildProfilerData)
643 IPC_MESSAGE_HANDLER(ChildProcessMsg_ProfilingPhaseCompleted,
644 OnProfilingPhaseCompleted)
645 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetProcessBackgrounded,
646 OnProcessBackgrounded)
647 #if defined(USE_TCMALLOC)
648 IPC_MESSAGE_HANDLER(ChildProcessMsg_GetTcmallocStats, OnGetTcmallocStats)
649 #endif
650 IPC_MESSAGE_UNHANDLED(handled = false)
651 IPC_END_MESSAGE_MAP()
653 if (handled)
654 return true;
656 if (msg.routing_id() == MSG_ROUTING_CONTROL)
657 return OnControlMessageReceived(msg);
659 return router_.OnMessageReceived(msg);
662 bool ChildThreadImpl::OnControlMessageReceived(const IPC::Message& msg) {
663 return false;
666 void ChildThreadImpl::OnProcessBackgrounded(bool backgrounded) {
667 // Set timer slack to maximum on main thread when in background.
668 base::TimerSlack timer_slack = base::TIMER_SLACK_NONE;
669 if (backgrounded)
670 timer_slack = base::TIMER_SLACK_MAXIMUM;
671 base::MessageLoop::current()->SetTimerSlack(timer_slack);
674 void ChildThreadImpl::OnShutdown() {
675 base::MessageLoop::current()->Quit();
678 #if defined(IPC_MESSAGE_LOG_ENABLED)
679 void ChildThreadImpl::OnSetIPCLoggingEnabled(bool enable) {
680 if (enable)
681 IPC::Logging::GetInstance()->Enable();
682 else
683 IPC::Logging::GetInstance()->Disable();
685 #endif // IPC_MESSAGE_LOG_ENABLED
687 void ChildThreadImpl::OnSetProfilerStatus(ThreadData::Status status) {
688 ThreadData::InitializeAndSetTrackingStatus(status);
691 void ChildThreadImpl::OnGetChildProfilerData(int sequence_number,
692 int current_profiling_phase) {
693 tracked_objects::ProcessDataSnapshot process_data;
694 ThreadData::Snapshot(current_profiling_phase, &process_data);
696 Send(
697 new ChildProcessHostMsg_ChildProfilerData(sequence_number, process_data));
700 void ChildThreadImpl::OnProfilingPhaseCompleted(int profiling_phase) {
701 ThreadData::OnProfilingPhaseCompleted(profiling_phase);
704 #if defined(USE_TCMALLOC)
705 void ChildThreadImpl::OnGetTcmallocStats() {
706 std::string result;
707 char buffer[1024 * 32];
708 base::allocator::GetStats(buffer, sizeof(buffer));
709 result.append(buffer);
710 Send(new ChildProcessHostMsg_TcmallocStats(result));
712 #endif
714 ChildThreadImpl* ChildThreadImpl::current() {
715 return g_lazy_tls.Pointer()->Get();
718 #if defined(OS_ANDROID)
719 // The method must NOT be called on the child thread itself.
720 // It may block the child thread if so.
721 void ChildThreadImpl::ShutdownThread() {
722 DCHECK(!ChildThreadImpl::current()) <<
723 "this method should NOT be called from child thread itself";
724 g_quit_closure.Get().PostQuitFromNonMainThread();
726 #endif
728 void ChildThreadImpl::OnProcessFinalRelease() {
729 if (on_channel_error_called_) {
730 base::MessageLoop::current()->Quit();
731 return;
734 // The child process shutdown sequence is a request response based mechanism,
735 // where we send out an initial feeler request to the child process host
736 // instance in the browser to verify if it's ok to shutdown the child process.
737 // The browser then sends back a response if it's ok to shutdown. This avoids
738 // race conditions if the process refcount is 0 but there's an IPC message
739 // inflight that would addref it.
740 Send(new ChildProcessHostMsg_ShutdownRequest);
743 void ChildThreadImpl::EnsureConnected() {
744 VLOG(0) << "ChildThreadImpl::EnsureConnected()";
745 base::Process::Current().Terminate(0, false);
748 bool ChildThreadImpl::IsInBrowserProcess() const {
749 return browser_process_io_runner_;
752 } // namespace content