cygprofile: increase timeouts to allow showing web contents
[chromium-blink-merge.git] / content / child / child_thread_impl.cc
blob8f0d93c67c36a9dbc2261ee635b734c0143e15ea
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/trace_event/memory_dump_manager.h"
32 #include "base/tracked_objects.h"
33 #include "components/tracing/child_trace_message_filter.h"
34 #include "content/child/child_discardable_shared_memory_manager.h"
35 #include "content/child/child_gpu_memory_buffer_manager.h"
36 #include "content/child/child_histogram_message_filter.h"
37 #include "content/child/child_process.h"
38 #include "content/child/child_resource_message_filter.h"
39 #include "content/child/child_shared_bitmap_manager.h"
40 #include "content/child/fileapi/file_system_dispatcher.h"
41 #include "content/child/fileapi/webfilesystem_impl.h"
42 #include "content/child/geofencing/geofencing_message_filter.h"
43 #include "content/child/mojo/mojo_application.h"
44 #include "content/child/notifications/notification_dispatcher.h"
45 #include "content/child/power_monitor_broadcast_source.h"
46 #include "content/child/push_messaging/push_dispatcher.h"
47 #include "content/child/quota_dispatcher.h"
48 #include "content/child/quota_message_filter.h"
49 #include "content/child/resource_dispatcher.h"
50 #include "content/child/service_worker/service_worker_message_filter.h"
51 #include "content/child/thread_safe_sender.h"
52 #include "content/child/websocket_dispatcher.h"
53 #include "content/common/child_process_messages.h"
54 #include "content/common/in_process_child_thread_params.h"
55 #include "content/public/common/content_switches.h"
56 #include "ipc/attachment_broker_unprivileged.h"
57 #include "ipc/ipc_logging.h"
58 #include "ipc/ipc_switches.h"
59 #include "ipc/ipc_sync_channel.h"
60 #include "ipc/ipc_sync_message_filter.h"
61 #include "ipc/mojo/ipc_channel_mojo.h"
63 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
64 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
65 #endif
67 #if defined(OS_MACOSX)
68 #include "content/child/child_io_surface_manager_mac.h"
69 #endif
71 #if defined(USE_OZONE)
72 #include "ui/ozone/public/client_native_pixmap_factory.h"
73 #endif
75 #if defined(OS_WIN)
76 #include "ipc/attachment_broker_unprivileged_win.h"
77 #endif
79 using tracked_objects::ThreadData;
81 namespace content {
82 namespace {
84 // How long to wait for a connection to the browser process before giving up.
85 const int kConnectionTimeoutS = 15;
87 base::LazyInstance<base::ThreadLocalPointer<ChildThreadImpl> > g_lazy_tls =
88 LAZY_INSTANCE_INITIALIZER;
90 // This isn't needed on Windows because there the sandbox's job object
91 // terminates child processes automatically. For unsandboxed processes (i.e.
92 // plugins), PluginThread has EnsureTerminateMessageFilter.
93 #if defined(OS_POSIX)
95 #if defined(ADDRESS_SANITIZER) || defined(LEAK_SANITIZER) || \
96 defined(MEMORY_SANITIZER) || defined(THREAD_SANITIZER) || \
97 defined(UNDEFINED_SANITIZER)
98 // A thread delegate that waits for |duration| and then exits the process with
99 // _exit(0).
100 class WaitAndExitDelegate : public base::PlatformThread::Delegate {
101 public:
102 explicit WaitAndExitDelegate(base::TimeDelta duration)
103 : duration_(duration) {}
105 void ThreadMain() override {
106 base::PlatformThread::Sleep(duration_);
107 _exit(0);
110 private:
111 const base::TimeDelta duration_;
112 DISALLOW_COPY_AND_ASSIGN(WaitAndExitDelegate);
115 bool CreateWaitAndExitThread(base::TimeDelta duration) {
116 scoped_ptr<WaitAndExitDelegate> delegate(new WaitAndExitDelegate(duration));
118 const bool thread_created =
119 base::PlatformThread::CreateNonJoinable(0, delegate.get());
120 if (!thread_created)
121 return false;
123 // A non joinable thread has been created. The thread will either terminate
124 // the process or will be terminated by the process. Therefore, keep the
125 // delegate object alive for the lifetime of the process.
126 WaitAndExitDelegate* leaking_delegate = delegate.release();
127 ANNOTATE_LEAKING_OBJECT_PTR(leaking_delegate);
128 ignore_result(leaking_delegate);
129 return true;
131 #endif
133 class SuicideOnChannelErrorFilter : public IPC::MessageFilter {
134 public:
135 // IPC::MessageFilter
136 void OnChannelError() override {
137 // For renderer/worker processes:
138 // On POSIX, at least, one can install an unload handler which loops
139 // forever and leave behind a renderer process which eats 100% CPU forever.
141 // This is because the terminate signals (FrameMsg_BeforeUnload and the
142 // error from the IPC sender) are routed to the main message loop but never
143 // processed (because that message loop is stuck in V8).
145 // One could make the browser SIGKILL the renderers, but that leaves open a
146 // large window where a browser failure (or a user, manually terminating
147 // the browser because "it's stuck") will leave behind a process eating all
148 // the CPU.
150 // So, we install a filter on the sender so that we can process this event
151 // here and kill the process.
152 base::debug::StopProfiling();
153 #if defined(ADDRESS_SANITIZER) || defined(LEAK_SANITIZER) || \
154 defined(MEMORY_SANITIZER) || defined(THREAD_SANITIZER) || \
155 defined(UNDEFINED_SANITIZER)
156 // Some sanitizer tools rely on exit handlers (e.g. to run leak detection,
157 // or dump code coverage data to disk). Instead of exiting the process
158 // immediately, we give it 60 seconds to run exit handlers.
159 CHECK(CreateWaitAndExitThread(base::TimeDelta::FromSeconds(60)));
160 #if defined(LEAK_SANITIZER)
161 // Invoke LeakSanitizer early to avoid detecting shutdown-only leaks. If
162 // leaks are found, the process will exit here.
163 __lsan_do_leak_check();
164 #endif
165 #else
166 _exit(0);
167 #endif
170 protected:
171 ~SuicideOnChannelErrorFilter() override {}
174 #endif // OS(POSIX)
176 #if defined(OS_MACOSX)
177 class IOSurfaceManagerFilter : public IPC::MessageFilter {
178 public:
179 // Overridden from IPC::MessageFilter:
180 bool OnMessageReceived(const IPC::Message& message) override {
181 bool handled = true;
182 IPC_BEGIN_MESSAGE_MAP(IOSurfaceManagerFilter, message)
183 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetIOSurfaceManagerToken,
184 OnSetIOSurfaceManagerToken)
185 IPC_MESSAGE_UNHANDLED(handled = false)
186 IPC_END_MESSAGE_MAP()
187 return handled;
190 protected:
191 ~IOSurfaceManagerFilter() override {}
193 void OnSetIOSurfaceManagerToken(const IOSurfaceManagerToken& token) {
194 ChildIOSurfaceManager::GetInstance()->set_token(token);
197 #endif
199 #if defined(USE_OZONE)
200 class ClientNativePixmapFactoryFilter : public IPC::MessageFilter {
201 public:
202 // Overridden from IPC::MessageFilter:
203 bool OnMessageReceived(const IPC::Message& message) override {
204 bool handled = true;
205 IPC_BEGIN_MESSAGE_MAP(ClientNativePixmapFactoryFilter, message)
206 IPC_MESSAGE_HANDLER(ChildProcessMsg_InitializeClientNativePixmapFactory,
207 OnInitializeClientNativePixmapFactory)
208 IPC_MESSAGE_UNHANDLED(handled = false)
209 IPC_END_MESSAGE_MAP()
210 return handled;
213 protected:
214 ~ClientNativePixmapFactoryFilter() override {}
216 void OnInitializeClientNativePixmapFactory(
217 const base::FileDescriptor& device_fd) {
218 ui::ClientNativePixmapFactory::GetInstance()->Initialize(
219 base::ScopedFD(device_fd.fd));
222 #endif
224 #if defined(OS_ANDROID)
225 // A class that allows for triggering a clean shutdown from another
226 // thread through draining the main thread's msg loop.
227 class QuitClosure {
228 public:
229 QuitClosure();
230 ~QuitClosure();
232 void BindToMainThread();
233 void PostQuitFromNonMainThread();
235 private:
236 static void PostClosure(
237 const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
238 base::Closure closure);
240 base::Lock lock_;
241 base::ConditionVariable cond_var_;
242 base::Closure closure_;
245 QuitClosure::QuitClosure() : cond_var_(&lock_) {
248 QuitClosure::~QuitClosure() {
251 void QuitClosure::PostClosure(
252 const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
253 base::Closure closure) {
254 task_runner->PostTask(FROM_HERE, closure);
257 void QuitClosure::BindToMainThread() {
258 base::AutoLock lock(lock_);
259 scoped_refptr<base::SingleThreadTaskRunner> task_runner(
260 base::ThreadTaskRunnerHandle::Get());
261 base::Closure quit_closure =
262 base::MessageLoop::current()->QuitWhenIdleClosure();
263 closure_ = base::Bind(&QuitClosure::PostClosure, task_runner, quit_closure);
264 cond_var_.Signal();
267 void QuitClosure::PostQuitFromNonMainThread() {
268 base::AutoLock lock(lock_);
269 while (closure_.is_null())
270 cond_var_.Wait();
272 closure_.Run();
275 base::LazyInstance<QuitClosure> g_quit_closure = LAZY_INSTANCE_INITIALIZER;
276 #endif
278 } // namespace
280 ChildThread* ChildThread::Get() {
281 return ChildThreadImpl::current();
284 ChildThreadImpl::Options::Options()
285 : channel_name(base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
286 switches::kProcessChannelID)),
287 use_mojo_channel(false) {
290 ChildThreadImpl::Options::~Options() {
293 ChildThreadImpl::Options::Builder::Builder() {
296 ChildThreadImpl::Options::Builder&
297 ChildThreadImpl::Options::Builder::InBrowserProcess(
298 const InProcessChildThreadParams& params) {
299 options_.browser_process_io_runner = params.io_runner();
300 options_.channel_name = params.channel_name();
301 return *this;
304 ChildThreadImpl::Options::Builder&
305 ChildThreadImpl::Options::Builder::UseMojoChannel(bool use_mojo_channel) {
306 options_.use_mojo_channel = use_mojo_channel;
307 return *this;
310 ChildThreadImpl::Options::Builder&
311 ChildThreadImpl::Options::Builder::WithChannelName(
312 const std::string& channel_name) {
313 options_.channel_name = channel_name;
314 return *this;
317 ChildThreadImpl::Options::Builder&
318 ChildThreadImpl::Options::Builder::AddStartupFilter(
319 IPC::MessageFilter* filter) {
320 options_.startup_filters.push_back(filter);
321 return *this;
324 ChildThreadImpl::Options ChildThreadImpl::Options::Builder::Build() {
325 return options_;
328 ChildThreadImpl::ChildThreadMessageRouter::ChildThreadMessageRouter(
329 IPC::Sender* sender)
330 : sender_(sender) {}
332 bool ChildThreadImpl::ChildThreadMessageRouter::Send(IPC::Message* msg) {
333 return sender_->Send(msg);
336 ChildThreadImpl::ChildThreadImpl()
337 : router_(this),
338 channel_connected_factory_(this) {
339 Init(Options::Builder().Build());
342 ChildThreadImpl::ChildThreadImpl(const Options& options)
343 : router_(this),
344 browser_process_io_runner_(options.browser_process_io_runner),
345 channel_connected_factory_(this) {
346 Init(options);
349 scoped_refptr<base::SequencedTaskRunner> ChildThreadImpl::GetIOTaskRunner() {
350 if (IsInBrowserProcess())
351 return browser_process_io_runner_;
352 return ChildProcess::current()->io_task_runner();
355 void ChildThreadImpl::ConnectChannel(bool use_mojo_channel) {
356 bool create_pipe_now = true;
357 if (use_mojo_channel) {
358 VLOG(1) << "Mojo is enabled on child";
359 scoped_refptr<base::SequencedTaskRunner> io_task_runner = GetIOTaskRunner();
360 DCHECK(io_task_runner);
361 channel_->Init(IPC::ChannelMojo::CreateClientFactory(
362 io_task_runner, channel_name_, attachment_broker_.get()),
363 create_pipe_now);
364 return;
367 VLOG(1) << "Mojo is disabled on child";
368 channel_->Init(channel_name_, IPC::Channel::MODE_CLIENT, create_pipe_now,
369 attachment_broker_.get());
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
384 channel_ =
385 IPC::SyncChannel::Create(this, ChildProcess::current()->io_task_runner(),
386 ChildProcess::current()->GetShutDownEvent());
387 #ifdef IPC_MESSAGE_LOG_ENABLED
388 if (!IsInBrowserProcess())
389 IPC::Logging::GetInstance()->SetIPCSender(this);
390 #endif
392 #if defined(OS_WIN)
393 attachment_broker_.reset(new IPC::AttachmentBrokerUnprivilegedWin());
394 #endif
396 mojo_application_.reset(new MojoApplication(GetIOTaskRunner()));
398 sync_message_filter_ = channel_->CreateSyncMessageFilter();
399 thread_safe_sender_ = new ThreadSafeSender(
400 message_loop_->task_runner(), sync_message_filter_.get());
402 resource_dispatcher_.reset(new ResourceDispatcher(
403 this, message_loop()->task_runner()));
404 websocket_dispatcher_.reset(new WebSocketDispatcher);
405 file_system_dispatcher_.reset(new FileSystemDispatcher());
407 histogram_message_filter_ = new ChildHistogramMessageFilter();
408 resource_message_filter_ =
409 new ChildResourceMessageFilter(resource_dispatcher());
411 service_worker_message_filter_ =
412 new ServiceWorkerMessageFilter(thread_safe_sender_.get());
414 quota_message_filter_ =
415 new QuotaMessageFilter(thread_safe_sender_.get());
416 quota_dispatcher_.reset(new QuotaDispatcher(thread_safe_sender_.get(),
417 quota_message_filter_.get()));
418 geofencing_message_filter_ =
419 new GeofencingMessageFilter(thread_safe_sender_.get());
420 notification_dispatcher_ =
421 new NotificationDispatcher(thread_safe_sender_.get());
422 push_dispatcher_ = new PushDispatcher(thread_safe_sender_.get());
424 channel_->AddFilter(histogram_message_filter_.get());
425 channel_->AddFilter(resource_message_filter_.get());
426 channel_->AddFilter(quota_message_filter_->GetFilter());
427 channel_->AddFilter(notification_dispatcher_->GetFilter());
428 channel_->AddFilter(push_dispatcher_->GetFilter());
429 channel_->AddFilter(service_worker_message_filter_->GetFilter());
430 channel_->AddFilter(geofencing_message_filter_->GetFilter());
432 if (!IsInBrowserProcess()) {
433 // In single process mode, browser-side tracing will cover the whole
434 // process including renderers.
435 channel_->AddFilter(new tracing::ChildTraceMessageFilter(
436 ChildProcess::current()->io_task_runner()));
439 // In single process mode we may already have a power monitor
440 if (!base::PowerMonitor::Get()) {
441 scoped_ptr<PowerMonitorBroadcastSource> power_monitor_source(
442 new PowerMonitorBroadcastSource());
443 channel_->AddFilter(power_monitor_source->GetMessageFilter());
445 power_monitor_.reset(new base::PowerMonitor(
446 power_monitor_source.Pass()));
449 #if defined(OS_POSIX)
450 // Check that --process-type is specified so we don't do this in unit tests
451 // and single-process mode.
452 if (base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kProcessType))
453 channel_->AddFilter(new SuicideOnChannelErrorFilter());
454 #endif
456 #if defined(OS_MACOSX)
457 channel_->AddFilter(new IOSurfaceManagerFilter());
458 #endif
460 #if defined(USE_OZONE)
461 channel_->AddFilter(new ClientNativePixmapFactoryFilter());
462 #endif
464 // Add filters passed here via options.
465 for (auto startup_filter : options.startup_filters) {
466 channel_->AddFilter(startup_filter);
469 ConnectChannel(options.use_mojo_channel);
470 if (attachment_broker_)
471 attachment_broker_->DesignateBrokerCommunicationChannel(channel_.get());
473 int connection_timeout = kConnectionTimeoutS;
474 std::string connection_override =
475 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
476 switches::kIPCConnectionTimeout);
477 if (!connection_override.empty()) {
478 int temp;
479 if (base::StringToInt(connection_override, &temp))
480 connection_timeout = temp;
483 message_loop_->task_runner()->PostDelayedTask(
484 FROM_HERE, base::Bind(&ChildThreadImpl::EnsureConnected,
485 channel_connected_factory_.GetWeakPtr()),
486 base::TimeDelta::FromSeconds(connection_timeout));
488 #if defined(OS_ANDROID)
489 g_quit_closure.Get().BindToMainThread();
490 #endif
492 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
493 trace_memory_controller_.reset(new base::trace_event::TraceMemoryController(
494 message_loop_->task_runner(), ::HeapProfilerWithPseudoStackStart,
495 ::HeapProfilerStop, ::GetHeapProfile));
496 #endif
498 base::trace_event::MemoryDumpManager::GetInstance()->Initialize();
500 shared_bitmap_manager_.reset(
501 new ChildSharedBitmapManager(thread_safe_sender()));
503 gpu_memory_buffer_manager_.reset(
504 new ChildGpuMemoryBufferManager(thread_safe_sender()));
506 discardable_shared_memory_manager_.reset(
507 new ChildDiscardableSharedMemoryManager(thread_safe_sender()));
510 ChildThreadImpl::~ChildThreadImpl() {
511 // ChildDiscardableSharedMemoryManager has to be destroyed while
512 // |thread_safe_sender_| is still valid.
513 discardable_shared_memory_manager_.reset();
515 #ifdef IPC_MESSAGE_LOG_ENABLED
516 IPC::Logging::GetInstance()->SetIPCSender(NULL);
517 #endif
519 channel_->RemoveFilter(histogram_message_filter_.get());
520 channel_->RemoveFilter(sync_message_filter_.get());
522 // The ChannelProxy object caches a pointer to the IPC thread, so need to
523 // reset it as it's not guaranteed to outlive this object.
524 // NOTE: this also has the side-effect of not closing the main IPC channel to
525 // the browser process. This is needed because this is the signal that the
526 // browser uses to know that this process has died, so we need it to be alive
527 // until this process is shut down, and the OS closes the handle
528 // automatically. We used to watch the object handle on Windows to do this,
529 // but it wasn't possible to do so on POSIX.
530 channel_->ClearIPCTaskRunner();
531 g_lazy_tls.Pointer()->Set(NULL);
534 void ChildThreadImpl::Shutdown() {
535 // Delete objects that hold references to blink so derived classes can
536 // safely shutdown blink in their Shutdown implementation.
537 file_system_dispatcher_.reset();
538 quota_dispatcher_.reset();
539 WebFileSystemImpl::DeleteThreadSpecificInstance();
542 void ChildThreadImpl::OnChannelConnected(int32 peer_pid) {
543 channel_connected_factory_.InvalidateWeakPtrs();
546 void ChildThreadImpl::OnChannelError() {
547 set_on_channel_error_called(true);
548 base::MessageLoop::current()->Quit();
551 bool ChildThreadImpl::Send(IPC::Message* msg) {
552 DCHECK(base::MessageLoop::current() == message_loop());
553 if (!channel_) {
554 delete msg;
555 return false;
558 return channel_->Send(msg);
561 #if defined(OS_WIN)
562 void ChildThreadImpl::PreCacheFont(const LOGFONT& log_font) {
563 Send(new ChildProcessHostMsg_PreCacheFont(log_font));
566 void ChildThreadImpl::ReleaseCachedFonts() {
567 Send(new ChildProcessHostMsg_ReleaseCachedFonts());
569 #endif
571 IPC::AttachmentBroker* ChildThreadImpl::GetAttachmentBroker() {
572 return attachment_broker_.get();
575 MessageRouter* ChildThreadImpl::GetRouter() {
576 DCHECK(base::MessageLoop::current() == message_loop());
577 return &router_;
580 scoped_ptr<base::SharedMemory> ChildThreadImpl::AllocateSharedMemory(
581 size_t buf_size) {
582 DCHECK(base::MessageLoop::current() == message_loop());
583 return AllocateSharedMemory(buf_size, this);
586 // static
587 scoped_ptr<base::SharedMemory> ChildThreadImpl::AllocateSharedMemory(
588 size_t buf_size,
589 IPC::Sender* sender) {
590 scoped_ptr<base::SharedMemory> shared_buf;
591 #if defined(OS_WIN)
592 shared_buf.reset(new base::SharedMemory);
593 if (!shared_buf->CreateAnonymous(buf_size)) {
594 NOTREACHED();
595 return NULL;
597 #else
598 // On POSIX, we need to ask the browser to create the shared memory for us,
599 // since this is blocked by the sandbox.
600 base::SharedMemoryHandle shared_mem_handle;
601 if (sender->Send(new ChildProcessHostMsg_SyncAllocateSharedMemory(
602 buf_size, &shared_mem_handle))) {
603 if (base::SharedMemory::IsHandleValid(shared_mem_handle)) {
604 shared_buf.reset(new base::SharedMemory(shared_mem_handle, false));
605 } else {
606 NOTREACHED() << "Browser failed to allocate shared memory";
607 return NULL;
609 } else {
610 NOTREACHED() << "Browser allocation request message failed";
611 return NULL;
613 #endif
614 return shared_buf;
617 bool ChildThreadImpl::OnMessageReceived(const IPC::Message& msg) {
618 if (mojo_application_->OnMessageReceived(msg))
619 return true;
621 // Resource responses are sent to the resource dispatcher.
622 if (resource_dispatcher_->OnMessageReceived(msg))
623 return true;
624 if (websocket_dispatcher_->OnMessageReceived(msg))
625 return true;
626 if (file_system_dispatcher_->OnMessageReceived(msg))
627 return true;
629 bool handled = true;
630 IPC_BEGIN_MESSAGE_MAP(ChildThreadImpl, msg)
631 IPC_MESSAGE_HANDLER(ChildProcessMsg_Shutdown, OnShutdown)
632 #if defined(IPC_MESSAGE_LOG_ENABLED)
633 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetIPCLoggingEnabled,
634 OnSetIPCLoggingEnabled)
635 #endif
636 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetProfilerStatus,
637 OnSetProfilerStatus)
638 IPC_MESSAGE_HANDLER(ChildProcessMsg_GetChildProfilerData,
639 OnGetChildProfilerData)
640 IPC_MESSAGE_HANDLER(ChildProcessMsg_ProfilingPhaseCompleted,
641 OnProfilingPhaseCompleted)
642 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetProcessBackgrounded,
643 OnProcessBackgrounded)
644 #if defined(USE_TCMALLOC)
645 IPC_MESSAGE_HANDLER(ChildProcessMsg_GetTcmallocStats, OnGetTcmallocStats)
646 #endif
647 IPC_MESSAGE_UNHANDLED(handled = false)
648 IPC_END_MESSAGE_MAP()
650 if (handled)
651 return true;
653 if (msg.routing_id() == MSG_ROUTING_CONTROL)
654 return OnControlMessageReceived(msg);
656 return router_.OnMessageReceived(msg);
659 bool ChildThreadImpl::OnControlMessageReceived(const IPC::Message& msg) {
660 return false;
663 void ChildThreadImpl::OnProcessBackgrounded(bool backgrounded) {
664 // Set timer slack to maximum on main thread when in background.
665 base::TimerSlack timer_slack = base::TIMER_SLACK_NONE;
666 if (backgrounded)
667 timer_slack = base::TIMER_SLACK_MAXIMUM;
668 base::MessageLoop::current()->SetTimerSlack(timer_slack);
671 void ChildThreadImpl::OnShutdown() {
672 base::MessageLoop::current()->Quit();
675 #if defined(IPC_MESSAGE_LOG_ENABLED)
676 void ChildThreadImpl::OnSetIPCLoggingEnabled(bool enable) {
677 if (enable)
678 IPC::Logging::GetInstance()->Enable();
679 else
680 IPC::Logging::GetInstance()->Disable();
682 #endif // IPC_MESSAGE_LOG_ENABLED
684 void ChildThreadImpl::OnSetProfilerStatus(ThreadData::Status status) {
685 ThreadData::InitializeAndSetTrackingStatus(status);
688 void ChildThreadImpl::OnGetChildProfilerData(int sequence_number,
689 int current_profiling_phase) {
690 tracked_objects::ProcessDataSnapshot process_data;
691 ThreadData::Snapshot(current_profiling_phase, &process_data);
693 Send(
694 new ChildProcessHostMsg_ChildProfilerData(sequence_number, process_data));
697 void ChildThreadImpl::OnProfilingPhaseCompleted(int profiling_phase) {
698 ThreadData::OnProfilingPhaseCompleted(profiling_phase);
701 #if defined(USE_TCMALLOC)
702 void ChildThreadImpl::OnGetTcmallocStats() {
703 std::string result;
704 char buffer[1024 * 32];
705 base::allocator::GetStats(buffer, sizeof(buffer));
706 result.append(buffer);
707 Send(new ChildProcessHostMsg_TcmallocStats(result));
709 #endif
711 ChildThreadImpl* ChildThreadImpl::current() {
712 return g_lazy_tls.Pointer()->Get();
715 #if defined(OS_ANDROID)
716 // The method must NOT be called on the child thread itself.
717 // It may block the child thread if so.
718 void ChildThreadImpl::ShutdownThread() {
719 DCHECK(!ChildThreadImpl::current()) <<
720 "this method should NOT be called from child thread itself";
721 g_quit_closure.Get().PostQuitFromNonMainThread();
723 #endif
725 void ChildThreadImpl::OnProcessFinalRelease() {
726 if (on_channel_error_called_) {
727 base::MessageLoop::current()->Quit();
728 return;
731 // The child process shutdown sequence is a request response based mechanism,
732 // where we send out an initial feeler request to the child process host
733 // instance in the browser to verify if it's ok to shutdown the child process.
734 // The browser then sends back a response if it's ok to shutdown. This avoids
735 // race conditions if the process refcount is 0 but there's an IPC message
736 // inflight that would addref it.
737 Send(new ChildProcessHostMsg_ShutdownRequest);
740 void ChildThreadImpl::EnsureConnected() {
741 VLOG(0) << "ChildThreadImpl::EnsureConnected()";
742 base::Process::Current().Terminate(0, false);
745 bool ChildThreadImpl::IsInBrowserProcess() const {
746 return browser_process_io_runner_;
749 } // namespace content