Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / content / child / child_thread_impl.cc
blob03a94244aca5c2805f2f0f24001542fe526590cf
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.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(OS_WIN)
72 #include "ipc/attachment_broker_win.h"
73 #endif
75 using tracked_objects::ThreadData;
77 namespace content {
78 namespace {
80 // How long to wait for a connection to the browser process before giving up.
81 const int kConnectionTimeoutS = 15;
83 base::LazyInstance<base::ThreadLocalPointer<ChildThreadImpl> > g_lazy_tls =
84 LAZY_INSTANCE_INITIALIZER;
86 // This isn't needed on Windows because there the sandbox's job object
87 // terminates child processes automatically. For unsandboxed processes (i.e.
88 // plugins), PluginThread has EnsureTerminateMessageFilter.
89 #if defined(OS_POSIX)
91 #if defined(ADDRESS_SANITIZER) || defined(LEAK_SANITIZER) || \
92 defined(MEMORY_SANITIZER) || defined(THREAD_SANITIZER) || \
93 defined(UNDEFINED_SANITIZER)
94 // A thread delegate that waits for |duration| and then exits the process with
95 // _exit(0).
96 class WaitAndExitDelegate : public base::PlatformThread::Delegate {
97 public:
98 explicit WaitAndExitDelegate(base::TimeDelta duration)
99 : duration_(duration) {}
101 void ThreadMain() override {
102 base::PlatformThread::Sleep(duration_);
103 _exit(0);
106 private:
107 const base::TimeDelta duration_;
108 DISALLOW_COPY_AND_ASSIGN(WaitAndExitDelegate);
111 bool CreateWaitAndExitThread(base::TimeDelta duration) {
112 scoped_ptr<WaitAndExitDelegate> delegate(new WaitAndExitDelegate(duration));
114 const bool thread_created =
115 base::PlatformThread::CreateNonJoinable(0, delegate.get());
116 if (!thread_created)
117 return false;
119 // A non joinable thread has been created. The thread will either terminate
120 // the process or will be terminated by the process. Therefore, keep the
121 // delegate object alive for the lifetime of the process.
122 WaitAndExitDelegate* leaking_delegate = delegate.release();
123 ANNOTATE_LEAKING_OBJECT_PTR(leaking_delegate);
124 ignore_result(leaking_delegate);
125 return true;
127 #endif
129 class SuicideOnChannelErrorFilter : public IPC::MessageFilter {
130 public:
131 // IPC::MessageFilter
132 void OnChannelError() override {
133 // For renderer/worker processes:
134 // On POSIX, at least, one can install an unload handler which loops
135 // forever and leave behind a renderer process which eats 100% CPU forever.
137 // This is because the terminate signals (FrameMsg_BeforeUnload and the
138 // error from the IPC sender) are routed to the main message loop but never
139 // processed (because that message loop is stuck in V8).
141 // One could make the browser SIGKILL the renderers, but that leaves open a
142 // large window where a browser failure (or a user, manually terminating
143 // the browser because "it's stuck") will leave behind a process eating all
144 // the CPU.
146 // So, we install a filter on the sender so that we can process this event
147 // here and kill the process.
148 base::debug::StopProfiling();
149 #if defined(ADDRESS_SANITIZER) || defined(LEAK_SANITIZER) || \
150 defined(MEMORY_SANITIZER) || defined(THREAD_SANITIZER) || \
151 defined(UNDEFINED_SANITIZER)
152 // Some sanitizer tools rely on exit handlers (e.g. to run leak detection,
153 // or dump code coverage data to disk). Instead of exiting the process
154 // immediately, we give it 60 seconds to run exit handlers.
155 CHECK(CreateWaitAndExitThread(base::TimeDelta::FromSeconds(60)));
156 #if defined(LEAK_SANITIZER)
157 // Invoke LeakSanitizer early to avoid detecting shutdown-only leaks. If
158 // leaks are found, the process will exit here.
159 __lsan_do_leak_check();
160 #endif
161 #else
162 _exit(0);
163 #endif
166 protected:
167 ~SuicideOnChannelErrorFilter() override {}
170 #endif // OS(POSIX)
172 #if defined(OS_MACOSX)
173 class IOSurfaceManagerFilter : public IPC::MessageFilter {
174 public:
175 // Overridden from IPC::MessageFilter:
176 bool OnMessageReceived(const IPC::Message& message) override {
177 bool handled = true;
178 IPC_BEGIN_MESSAGE_MAP(IOSurfaceManagerFilter, message)
179 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetIOSurfaceManagerToken,
180 OnSetIOSurfaceManagerToken)
181 IPC_MESSAGE_UNHANDLED(handled = false)
182 IPC_END_MESSAGE_MAP()
183 return handled;
186 protected:
187 ~IOSurfaceManagerFilter() override {}
189 void OnSetIOSurfaceManagerToken(const IOSurfaceManagerToken& token) {
190 ChildIOSurfaceManager::GetInstance()->set_token(token);
193 #endif
195 #if defined(OS_ANDROID)
196 // A class that allows for triggering a clean shutdown from another
197 // thread through draining the main thread's msg loop.
198 class QuitClosure {
199 public:
200 QuitClosure();
201 ~QuitClosure();
203 void BindToMainThread();
204 void PostQuitFromNonMainThread();
206 private:
207 static void PostClosure(
208 const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
209 base::Closure closure);
211 base::Lock lock_;
212 base::ConditionVariable cond_var_;
213 base::Closure closure_;
216 QuitClosure::QuitClosure() : cond_var_(&lock_) {
219 QuitClosure::~QuitClosure() {
222 void QuitClosure::PostClosure(
223 const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
224 base::Closure closure) {
225 task_runner->PostTask(FROM_HERE, closure);
228 void QuitClosure::BindToMainThread() {
229 base::AutoLock lock(lock_);
230 scoped_refptr<base::SingleThreadTaskRunner> task_runner(
231 base::ThreadTaskRunnerHandle::Get());
232 base::Closure quit_closure =
233 base::MessageLoop::current()->QuitWhenIdleClosure();
234 closure_ = base::Bind(&QuitClosure::PostClosure, task_runner, quit_closure);
235 cond_var_.Signal();
238 void QuitClosure::PostQuitFromNonMainThread() {
239 base::AutoLock lock(lock_);
240 while (closure_.is_null())
241 cond_var_.Wait();
243 closure_.Run();
246 base::LazyInstance<QuitClosure> g_quit_closure = LAZY_INSTANCE_INITIALIZER;
247 #endif
249 } // namespace
251 ChildThread* ChildThread::Get() {
252 return ChildThreadImpl::current();
255 ChildThreadImpl::Options::Options()
256 : channel_name(base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
257 switches::kProcessChannelID)),
258 use_mojo_channel(false) {
261 ChildThreadImpl::Options::~Options() {
264 ChildThreadImpl::Options::Builder::Builder() {
267 ChildThreadImpl::Options::Builder&
268 ChildThreadImpl::Options::Builder::InBrowserProcess(
269 const InProcessChildThreadParams& params) {
270 options_.browser_process_io_runner = params.io_runner();
271 options_.channel_name = params.channel_name();
272 return *this;
275 ChildThreadImpl::Options::Builder&
276 ChildThreadImpl::Options::Builder::UseMojoChannel(bool use_mojo_channel) {
277 options_.use_mojo_channel = use_mojo_channel;
278 return *this;
281 ChildThreadImpl::Options::Builder&
282 ChildThreadImpl::Options::Builder::WithChannelName(
283 const std::string& channel_name) {
284 options_.channel_name = channel_name;
285 return *this;
288 ChildThreadImpl::Options::Builder&
289 ChildThreadImpl::Options::Builder::AddStartupFilter(
290 IPC::MessageFilter* filter) {
291 options_.startup_filters.push_back(filter);
292 return *this;
295 ChildThreadImpl::Options ChildThreadImpl::Options::Builder::Build() {
296 return options_;
299 ChildThreadImpl::ChildThreadMessageRouter::ChildThreadMessageRouter(
300 IPC::Sender* sender)
301 : sender_(sender) {}
303 bool ChildThreadImpl::ChildThreadMessageRouter::Send(IPC::Message* msg) {
304 return sender_->Send(msg);
307 ChildThreadImpl::ChildThreadImpl()
308 : router_(this),
309 channel_connected_factory_(this) {
310 Init(Options::Builder().Build());
313 ChildThreadImpl::ChildThreadImpl(const Options& options)
314 : router_(this),
315 browser_process_io_runner_(options.browser_process_io_runner),
316 channel_connected_factory_(this) {
317 Init(options);
320 scoped_refptr<base::SequencedTaskRunner> ChildThreadImpl::GetIOTaskRunner() {
321 if (IsInBrowserProcess())
322 return browser_process_io_runner_;
323 return ChildProcess::current()->io_task_runner();
326 void ChildThreadImpl::ConnectChannel(bool use_mojo_channel) {
327 bool create_pipe_now = true;
328 if (use_mojo_channel) {
329 VLOG(1) << "Mojo is enabled on child";
330 scoped_refptr<base::SequencedTaskRunner> io_task_runner = GetIOTaskRunner();
331 DCHECK(io_task_runner);
332 channel_->Init(IPC::ChannelMojo::CreateClientFactory(
333 io_task_runner, channel_name_, attachment_broker_.get()),
334 create_pipe_now);
335 return;
338 VLOG(1) << "Mojo is disabled on child";
339 channel_->Init(channel_name_, IPC::Channel::MODE_CLIENT, create_pipe_now,
340 attachment_broker_.get());
343 void ChildThreadImpl::Init(const Options& options) {
344 channel_name_ = options.channel_name;
346 g_lazy_tls.Pointer()->Set(this);
347 on_channel_error_called_ = false;
348 message_loop_ = base::MessageLoop::current();
349 #ifdef IPC_MESSAGE_LOG_ENABLED
350 // We must make sure to instantiate the IPC Logger *before* we create the
351 // channel, otherwise we can get a callback on the IO thread which creates
352 // the logger, and the logger does not like being created on the IO thread.
353 IPC::Logging::GetInstance();
354 #endif
355 channel_ =
356 IPC::SyncChannel::Create(this, ChildProcess::current()->io_task_runner(),
357 ChildProcess::current()->GetShutDownEvent());
358 #ifdef IPC_MESSAGE_LOG_ENABLED
359 if (!IsInBrowserProcess())
360 IPC::Logging::GetInstance()->SetIPCSender(this);
361 #endif
363 #if defined(OS_WIN)
364 attachment_broker_.reset(new IPC::AttachmentBrokerWin());
365 #endif
367 mojo_application_.reset(new MojoApplication(GetIOTaskRunner()));
369 sync_message_filter_ =
370 new IPC::SyncMessageFilter(ChildProcess::current()->GetShutDownEvent());
371 thread_safe_sender_ = new ThreadSafeSender(
372 message_loop_->task_runner(), sync_message_filter_.get());
374 resource_dispatcher_.reset(new ResourceDispatcher(
375 this, message_loop()->task_runner()));
376 websocket_dispatcher_.reset(new WebSocketDispatcher);
377 file_system_dispatcher_.reset(new FileSystemDispatcher());
379 histogram_message_filter_ = new ChildHistogramMessageFilter();
380 resource_message_filter_ =
381 new ChildResourceMessageFilter(resource_dispatcher());
383 service_worker_message_filter_ =
384 new ServiceWorkerMessageFilter(thread_safe_sender_.get());
386 quota_message_filter_ =
387 new QuotaMessageFilter(thread_safe_sender_.get());
388 quota_dispatcher_.reset(new QuotaDispatcher(thread_safe_sender_.get(),
389 quota_message_filter_.get()));
390 geofencing_message_filter_ =
391 new GeofencingMessageFilter(thread_safe_sender_.get());
392 notification_dispatcher_ =
393 new NotificationDispatcher(thread_safe_sender_.get());
394 push_dispatcher_ = new PushDispatcher(thread_safe_sender_.get());
396 channel_->AddFilter(histogram_message_filter_.get());
397 channel_->AddFilter(sync_message_filter_.get());
398 channel_->AddFilter(resource_message_filter_.get());
399 channel_->AddFilter(quota_message_filter_->GetFilter());
400 channel_->AddFilter(notification_dispatcher_->GetFilter());
401 channel_->AddFilter(push_dispatcher_->GetFilter());
402 channel_->AddFilter(service_worker_message_filter_->GetFilter());
403 channel_->AddFilter(geofencing_message_filter_->GetFilter());
405 if (!IsInBrowserProcess()) {
406 // In single process mode, browser-side tracing will cover the whole
407 // process including renderers.
408 channel_->AddFilter(new tracing::ChildTraceMessageFilter(
409 ChildProcess::current()->io_task_runner()));
412 // In single process mode we may already have a power monitor
413 if (!base::PowerMonitor::Get()) {
414 scoped_ptr<PowerMonitorBroadcastSource> power_monitor_source(
415 new PowerMonitorBroadcastSource());
416 channel_->AddFilter(power_monitor_source->GetMessageFilter());
418 power_monitor_.reset(new base::PowerMonitor(
419 power_monitor_source.Pass()));
422 #if defined(OS_POSIX)
423 // Check that --process-type is specified so we don't do this in unit tests
424 // and single-process mode.
425 if (base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kProcessType))
426 channel_->AddFilter(new SuicideOnChannelErrorFilter());
427 #endif
429 #if defined(OS_MACOSX)
430 channel_->AddFilter(new IOSurfaceManagerFilter());
431 #endif
433 // Add filters passed here via options.
434 for (auto startup_filter : options.startup_filters) {
435 channel_->AddFilter(startup_filter);
438 ConnectChannel(options.use_mojo_channel);
440 int connection_timeout = kConnectionTimeoutS;
441 std::string connection_override =
442 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
443 switches::kIPCConnectionTimeout);
444 if (!connection_override.empty()) {
445 int temp;
446 if (base::StringToInt(connection_override, &temp))
447 connection_timeout = temp;
450 message_loop_->task_runner()->PostDelayedTask(
451 FROM_HERE, base::Bind(&ChildThreadImpl::EnsureConnected,
452 channel_connected_factory_.GetWeakPtr()),
453 base::TimeDelta::FromSeconds(connection_timeout));
455 #if defined(OS_ANDROID)
456 g_quit_closure.Get().BindToMainThread();
457 #endif
459 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
460 trace_memory_controller_.reset(new base::trace_event::TraceMemoryController(
461 message_loop_->task_runner(), ::HeapProfilerWithPseudoStackStart,
462 ::HeapProfilerStop, ::GetHeapProfile));
463 #endif
465 base::trace_event::MemoryDumpManager::GetInstance()->Initialize();
467 shared_bitmap_manager_.reset(
468 new ChildSharedBitmapManager(thread_safe_sender()));
470 gpu_memory_buffer_manager_.reset(
471 new ChildGpuMemoryBufferManager(thread_safe_sender()));
473 discardable_shared_memory_manager_.reset(
474 new ChildDiscardableSharedMemoryManager(thread_safe_sender()));
477 ChildThreadImpl::~ChildThreadImpl() {
478 // ChildDiscardableSharedMemoryManager has to be destroyed while
479 // |thread_safe_sender_| is still valid.
480 discardable_shared_memory_manager_.reset();
482 #ifdef IPC_MESSAGE_LOG_ENABLED
483 IPC::Logging::GetInstance()->SetIPCSender(NULL);
484 #endif
486 channel_->RemoveFilter(histogram_message_filter_.get());
487 channel_->RemoveFilter(sync_message_filter_.get());
489 // The ChannelProxy object caches a pointer to the IPC thread, so need to
490 // reset it as it's not guaranteed to outlive this object.
491 // NOTE: this also has the side-effect of not closing the main IPC channel to
492 // the browser process. This is needed because this is the signal that the
493 // browser uses to know that this process has died, so we need it to be alive
494 // until this process is shut down, and the OS closes the handle
495 // automatically. We used to watch the object handle on Windows to do this,
496 // but it wasn't possible to do so on POSIX.
497 channel_->ClearIPCTaskRunner();
498 g_lazy_tls.Pointer()->Set(NULL);
501 void ChildThreadImpl::Shutdown() {
502 // Delete objects that hold references to blink so derived classes can
503 // safely shutdown blink in their Shutdown implementation.
504 file_system_dispatcher_.reset();
505 quota_dispatcher_.reset();
506 WebFileSystemImpl::DeleteThreadSpecificInstance();
509 void ChildThreadImpl::OnChannelConnected(int32 peer_pid) {
510 channel_connected_factory_.InvalidateWeakPtrs();
513 void ChildThreadImpl::OnChannelError() {
514 set_on_channel_error_called(true);
515 base::MessageLoop::current()->Quit();
518 bool ChildThreadImpl::Send(IPC::Message* msg) {
519 DCHECK(base::MessageLoop::current() == message_loop());
520 if (!channel_) {
521 delete msg;
522 return false;
525 return channel_->Send(msg);
528 #if defined(OS_WIN)
529 void ChildThreadImpl::PreCacheFont(const LOGFONT& log_font) {
530 Send(new ChildProcessHostMsg_PreCacheFont(log_font));
533 void ChildThreadImpl::ReleaseCachedFonts() {
534 Send(new ChildProcessHostMsg_ReleaseCachedFonts());
536 #endif
538 IPC::AttachmentBroker* ChildThreadImpl::GetAttachmentBroker() {
539 return attachment_broker_.get();
542 MessageRouter* ChildThreadImpl::GetRouter() {
543 DCHECK(base::MessageLoop::current() == message_loop());
544 return &router_;
547 scoped_ptr<base::SharedMemory> ChildThreadImpl::AllocateSharedMemory(
548 size_t buf_size) {
549 DCHECK(base::MessageLoop::current() == message_loop());
550 return AllocateSharedMemory(buf_size, this);
553 // static
554 scoped_ptr<base::SharedMemory> ChildThreadImpl::AllocateSharedMemory(
555 size_t buf_size,
556 IPC::Sender* sender) {
557 scoped_ptr<base::SharedMemory> shared_buf;
558 #if defined(OS_WIN)
559 shared_buf.reset(new base::SharedMemory);
560 if (!shared_buf->CreateAnonymous(buf_size)) {
561 NOTREACHED();
562 return NULL;
564 #else
565 // On POSIX, we need to ask the browser to create the shared memory for us,
566 // since this is blocked by the sandbox.
567 base::SharedMemoryHandle shared_mem_handle;
568 if (sender->Send(new ChildProcessHostMsg_SyncAllocateSharedMemory(
569 buf_size, &shared_mem_handle))) {
570 if (base::SharedMemory::IsHandleValid(shared_mem_handle)) {
571 shared_buf.reset(new base::SharedMemory(shared_mem_handle, false));
572 } else {
573 NOTREACHED() << "Browser failed to allocate shared memory";
574 return NULL;
576 } else {
577 NOTREACHED() << "Browser allocation request message failed";
578 return NULL;
580 #endif
581 return shared_buf;
584 bool ChildThreadImpl::OnMessageReceived(const IPC::Message& msg) {
585 if (mojo_application_->OnMessageReceived(msg))
586 return true;
588 // Resource responses are sent to the resource dispatcher.
589 if (resource_dispatcher_->OnMessageReceived(msg))
590 return true;
591 if (websocket_dispatcher_->OnMessageReceived(msg))
592 return true;
593 if (file_system_dispatcher_->OnMessageReceived(msg))
594 return true;
595 if (attachment_broker_ && attachment_broker_->OnMessageReceived(msg))
596 return true;
598 bool handled = true;
599 IPC_BEGIN_MESSAGE_MAP(ChildThreadImpl, msg)
600 IPC_MESSAGE_HANDLER(ChildProcessMsg_Shutdown, OnShutdown)
601 #if defined(IPC_MESSAGE_LOG_ENABLED)
602 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetIPCLoggingEnabled,
603 OnSetIPCLoggingEnabled)
604 #endif
605 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetProfilerStatus,
606 OnSetProfilerStatus)
607 IPC_MESSAGE_HANDLER(ChildProcessMsg_GetChildProfilerData,
608 OnGetChildProfilerData)
609 IPC_MESSAGE_HANDLER(ChildProcessMsg_ProfilingPhaseCompleted,
610 OnProfilingPhaseCompleted)
611 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetProcessBackgrounded,
612 OnProcessBackgrounded)
613 #if defined(USE_TCMALLOC)
614 IPC_MESSAGE_HANDLER(ChildProcessMsg_GetTcmallocStats, OnGetTcmallocStats)
615 #endif
616 IPC_MESSAGE_UNHANDLED(handled = false)
617 IPC_END_MESSAGE_MAP()
619 if (handled)
620 return true;
622 if (msg.routing_id() == MSG_ROUTING_CONTROL)
623 return OnControlMessageReceived(msg);
625 return router_.OnMessageReceived(msg);
628 bool ChildThreadImpl::OnControlMessageReceived(const IPC::Message& msg) {
629 return false;
632 void ChildThreadImpl::OnShutdown() {
633 base::MessageLoop::current()->Quit();
636 #if defined(IPC_MESSAGE_LOG_ENABLED)
637 void ChildThreadImpl::OnSetIPCLoggingEnabled(bool enable) {
638 if (enable)
639 IPC::Logging::GetInstance()->Enable();
640 else
641 IPC::Logging::GetInstance()->Disable();
643 #endif // IPC_MESSAGE_LOG_ENABLED
645 void ChildThreadImpl::OnSetProfilerStatus(ThreadData::Status status) {
646 ThreadData::InitializeAndSetTrackingStatus(status);
649 void ChildThreadImpl::OnGetChildProfilerData(int sequence_number,
650 int current_profiling_phase) {
651 tracked_objects::ProcessDataSnapshot process_data;
652 ThreadData::Snapshot(current_profiling_phase, &process_data);
654 Send(
655 new ChildProcessHostMsg_ChildProfilerData(sequence_number, process_data));
658 void ChildThreadImpl::OnProfilingPhaseCompleted(int profiling_phase) {
659 ThreadData::OnProfilingPhaseCompleted(profiling_phase);
662 #if defined(USE_TCMALLOC)
663 void ChildThreadImpl::OnGetTcmallocStats() {
664 std::string result;
665 char buffer[1024 * 32];
666 base::allocator::GetStats(buffer, sizeof(buffer));
667 result.append(buffer);
668 Send(new ChildProcessHostMsg_TcmallocStats(result));
670 #endif
672 ChildThreadImpl* ChildThreadImpl::current() {
673 return g_lazy_tls.Pointer()->Get();
676 #if defined(OS_ANDROID)
677 // The method must NOT be called on the child thread itself.
678 // It may block the child thread if so.
679 void ChildThreadImpl::ShutdownThread() {
680 DCHECK(!ChildThreadImpl::current()) <<
681 "this method should NOT be called from child thread itself";
682 g_quit_closure.Get().PostQuitFromNonMainThread();
684 #endif
686 void ChildThreadImpl::OnProcessFinalRelease() {
687 if (on_channel_error_called_) {
688 base::MessageLoop::current()->Quit();
689 return;
692 // The child process shutdown sequence is a request response based mechanism,
693 // where we send out an initial feeler request to the child process host
694 // instance in the browser to verify if it's ok to shutdown the child process.
695 // The browser then sends back a response if it's ok to shutdown. This avoids
696 // race conditions if the process refcount is 0 but there's an IPC message
697 // inflight that would addref it.
698 Send(new ChildProcessHostMsg_ShutdownRequest);
701 void ChildThreadImpl::EnsureConnected() {
702 VLOG(0) << "ChildThreadImpl::EnsureConnected()";
703 base::Process::Current().Terminate(0, false);
706 bool ChildThreadImpl::IsInBrowserProcess() const {
707 return browser_process_io_runner_;
710 void ChildThreadImpl::OnProcessBackgrounded(bool background) {
711 // Set timer slack to maximum on main thread when in background.
712 base::TimerSlack timer_slack = base::TIMER_SLACK_NONE;
713 if (background)
714 timer_slack = base::TIMER_SLACK_MAXIMUM;
715 base::MessageLoop::current()->SetTimerSlack(timer_slack);
718 } // namespace content