Remove unnecessary casts for WebContentsImpl::GetRenderViewHost.
[chromium-blink-merge.git] / content / child / child_thread_impl.cc
blobd2f1791baa9d884933b25a39ae9bb0a87c251a3a
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/logging.h"
19 #include "base/message_loop/message_loop.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/strings/string_number_conversions.h"
25 #include "base/strings/string_util.h"
26 #include "base/synchronization/condition_variable.h"
27 #include "base/synchronization/lock.h"
28 #include "base/threading/thread_local.h"
29 #include "base/trace_event/memory_dump_manager.h"
30 #include "base/tracked_objects.h"
31 #include "components/tracing/child_trace_message_filter.h"
32 #include "content/child/bluetooth/bluetooth_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/navigator_connect/navigator_connect_dispatcher.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/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(OS_WIN)
63 #include "content/common/handle_enumerator_win.h"
64 #endif
66 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
67 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
68 #endif
70 using tracked_objects::ThreadData;
72 namespace content {
73 namespace {
75 // How long to wait for a connection to the browser process before giving up.
76 const int kConnectionTimeoutS = 15;
78 base::LazyInstance<base::ThreadLocalPointer<ChildThreadImpl> > g_lazy_tls =
79 LAZY_INSTANCE_INITIALIZER;
81 // This isn't needed on Windows because there the sandbox's job object
82 // terminates child processes automatically. For unsandboxed processes (i.e.
83 // plugins), PluginThread has EnsureTerminateMessageFilter.
84 #if defined(OS_POSIX)
86 #if defined(ADDRESS_SANITIZER) || defined(LEAK_SANITIZER) || \
87 defined(MEMORY_SANITIZER) || defined(THREAD_SANITIZER) || \
88 defined(UNDEFINED_SANITIZER)
89 // A thread delegate that waits for |duration| and then exits the process with
90 // _exit(0).
91 class WaitAndExitDelegate : public base::PlatformThread::Delegate {
92 public:
93 explicit WaitAndExitDelegate(base::TimeDelta duration)
94 : duration_(duration) {}
96 void ThreadMain() override {
97 base::PlatformThread::Sleep(duration_);
98 _exit(0);
101 private:
102 const base::TimeDelta duration_;
103 DISALLOW_COPY_AND_ASSIGN(WaitAndExitDelegate);
106 bool CreateWaitAndExitThread(base::TimeDelta duration) {
107 scoped_ptr<WaitAndExitDelegate> delegate(new WaitAndExitDelegate(duration));
109 const bool thread_created =
110 base::PlatformThread::CreateNonJoinable(0, delegate.get());
111 if (!thread_created)
112 return false;
114 // A non joinable thread has been created. The thread will either terminate
115 // the process or will be terminated by the process. Therefore, keep the
116 // delegate object alive for the lifetime of the process.
117 WaitAndExitDelegate* leaking_delegate = delegate.release();
118 ANNOTATE_LEAKING_OBJECT_PTR(leaking_delegate);
119 ignore_result(leaking_delegate);
120 return true;
122 #endif
124 class SuicideOnChannelErrorFilter : public IPC::MessageFilter {
125 public:
126 // IPC::MessageFilter
127 void OnChannelError() override {
128 // For renderer/worker processes:
129 // On POSIX, at least, one can install an unload handler which loops
130 // forever and leave behind a renderer process which eats 100% CPU forever.
132 // This is because the terminate signals (ViewMsg_ShouldClose and the error
133 // from the IPC sender) are routed to the main message loop but never
134 // processed (because that message loop is stuck in V8).
136 // One could make the browser SIGKILL the renderers, but that leaves open a
137 // large window where a browser failure (or a user, manually terminating
138 // the browser because "it's stuck") will leave behind a process eating all
139 // the CPU.
141 // So, we install a filter on the sender so that we can process this event
142 // here and kill the process.
143 base::debug::StopProfiling();
144 #if defined(ADDRESS_SANITIZER) || defined(LEAK_SANITIZER) || \
145 defined(MEMORY_SANITIZER) || defined(THREAD_SANITIZER) || \
146 defined(UNDEFINED_SANITIZER)
147 // Some sanitizer tools rely on exit handlers (e.g. to run leak detection,
148 // or dump code coverage data to disk). Instead of exiting the process
149 // immediately, we give it 60 seconds to run exit handlers.
150 CHECK(CreateWaitAndExitThread(base::TimeDelta::FromSeconds(60)));
151 #if defined(LEAK_SANITIZER)
152 // Invoke LeakSanitizer early to avoid detecting shutdown-only leaks. If
153 // leaks are found, the process will exit here.
154 __lsan_do_leak_check();
155 #endif
156 #else
157 _exit(0);
158 #endif
161 protected:
162 ~SuicideOnChannelErrorFilter() override {}
165 #endif // OS(POSIX)
167 #if defined(OS_ANDROID)
168 ChildThreadImpl* g_child_thread = NULL;
169 bool g_child_thread_initialized = false;
171 // A lock protects g_child_thread.
172 base::LazyInstance<base::Lock>::Leaky g_lazy_child_thread_lock =
173 LAZY_INSTANCE_INITIALIZER;
175 // base::ConditionVariable has an explicit constructor that takes
176 // a base::Lock pointer as parameter. The base::DefaultLazyInstanceTraits
177 // doesn't handle the case. Thus, we need our own class here.
178 struct CondVarLazyInstanceTraits {
179 static const bool kRegisterOnExit = false;
180 #ifndef NDEBUG
181 static const bool kAllowedToAccessOnNonjoinableThread = true;
182 #endif
184 static base::ConditionVariable* New(void* instance) {
185 return new (instance) base::ConditionVariable(
186 g_lazy_child_thread_lock.Pointer());
188 static void Delete(base::ConditionVariable* instance) {
189 instance->~ConditionVariable();
193 // A condition variable that synchronize threads initializing and waiting
194 // for g_child_thread.
195 base::LazyInstance<base::ConditionVariable, CondVarLazyInstanceTraits>
196 g_lazy_child_thread_cv = LAZY_INSTANCE_INITIALIZER;
198 void QuitMainThreadMessageLoop() {
199 base::MessageLoop::current()->Quit();
202 #endif
204 } // namespace
206 ChildThread* ChildThread::Get() {
207 return ChildThreadImpl::current();
210 ChildThreadImpl::Options::Options()
211 : channel_name(base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
212 switches::kProcessChannelID)),
213 use_mojo_channel(false) {
216 ChildThreadImpl::Options::~Options() {
219 ChildThreadImpl::Options::Builder::Builder() {
222 ChildThreadImpl::Options::Builder&
223 ChildThreadImpl::Options::Builder::InBrowserProcess(
224 const InProcessChildThreadParams& params) {
225 options_.browser_process_io_runner = params.io_runner();
226 options_.channel_name = params.channel_name();
227 return *this;
230 ChildThreadImpl::Options::Builder&
231 ChildThreadImpl::Options::Builder::UseMojoChannel(bool use_mojo_channel) {
232 options_.use_mojo_channel = use_mojo_channel;
233 return *this;
236 ChildThreadImpl::Options::Builder&
237 ChildThreadImpl::Options::Builder::WithChannelName(
238 const std::string& channel_name) {
239 options_.channel_name = channel_name;
240 return *this;
243 ChildThreadImpl::Options::Builder&
244 ChildThreadImpl::Options::Builder::AddStartupFilter(
245 IPC::MessageFilter* filter) {
246 options_.startup_filters.push_back(filter);
247 return *this;
250 ChildThreadImpl::Options ChildThreadImpl::Options::Builder::Build() {
251 return options_;
254 ChildThreadImpl::ChildThreadMessageRouter::ChildThreadMessageRouter(
255 IPC::Sender* sender)
256 : sender_(sender) {}
258 bool ChildThreadImpl::ChildThreadMessageRouter::Send(IPC::Message* msg) {
259 return sender_->Send(msg);
262 ChildThreadImpl::ChildThreadImpl()
263 : router_(this),
264 channel_connected_factory_(this) {
265 Init(Options::Builder().Build());
268 ChildThreadImpl::ChildThreadImpl(const Options& options)
269 : router_(this),
270 browser_process_io_runner_(options.browser_process_io_runner),
271 channel_connected_factory_(this) {
272 Init(options);
275 scoped_refptr<base::SequencedTaskRunner> ChildThreadImpl::GetIOTaskRunner() {
276 if (IsInBrowserProcess())
277 return browser_process_io_runner_;
278 return ChildProcess::current()->io_message_loop_proxy();
281 void ChildThreadImpl::ConnectChannel(bool use_mojo_channel) {
282 bool create_pipe_now = true;
283 if (use_mojo_channel) {
284 VLOG(1) << "Mojo is enabled on child";
285 scoped_refptr<base::SequencedTaskRunner> io_task_runner = GetIOTaskRunner();
286 DCHECK(io_task_runner);
287 channel_->Init(IPC::ChannelMojo::CreateClientFactory(
288 nullptr, io_task_runner, channel_name_),
289 create_pipe_now);
290 return;
293 VLOG(1) << "Mojo is disabled on child";
294 channel_->Init(channel_name_, IPC::Channel::MODE_CLIENT, create_pipe_now);
297 void ChildThreadImpl::Init(const Options& options) {
298 channel_name_ = options.channel_name;
300 g_lazy_tls.Pointer()->Set(this);
301 on_channel_error_called_ = false;
302 message_loop_ = base::MessageLoop::current();
303 #ifdef IPC_MESSAGE_LOG_ENABLED
304 // We must make sure to instantiate the IPC Logger *before* we create the
305 // channel, otherwise we can get a callback on the IO thread which creates
306 // the logger, and the logger does not like being created on the IO thread.
307 IPC::Logging::GetInstance();
308 #endif
309 channel_ = IPC::SyncChannel::Create(
310 this, ChildProcess::current()->io_message_loop_proxy(),
311 ChildProcess::current()->GetShutDownEvent());
312 #ifdef IPC_MESSAGE_LOG_ENABLED
313 if (!IsInBrowserProcess())
314 IPC::Logging::GetInstance()->SetIPCSender(this);
315 #endif
317 mojo_application_.reset(new MojoApplication(GetIOTaskRunner()));
319 sync_message_filter_ =
320 new IPC::SyncMessageFilter(ChildProcess::current()->GetShutDownEvent());
321 thread_safe_sender_ = new ThreadSafeSender(
322 base::MessageLoopProxy::current().get(), sync_message_filter_.get());
324 resource_dispatcher_.reset(new ResourceDispatcher(
325 this, message_loop()->task_runner()));
326 websocket_dispatcher_.reset(new WebSocketDispatcher);
327 file_system_dispatcher_.reset(new FileSystemDispatcher());
329 histogram_message_filter_ = new ChildHistogramMessageFilter();
330 resource_message_filter_ =
331 new ChildResourceMessageFilter(resource_dispatcher());
333 service_worker_message_filter_ =
334 new ServiceWorkerMessageFilter(thread_safe_sender_.get());
336 quota_message_filter_ =
337 new QuotaMessageFilter(thread_safe_sender_.get());
338 quota_dispatcher_.reset(new QuotaDispatcher(thread_safe_sender_.get(),
339 quota_message_filter_.get()));
340 geofencing_message_filter_ =
341 new GeofencingMessageFilter(thread_safe_sender_.get());
342 bluetooth_message_filter_ =
343 new BluetoothMessageFilter(thread_safe_sender_.get());
344 notification_dispatcher_ =
345 new NotificationDispatcher(thread_safe_sender_.get());
346 push_dispatcher_ = new PushDispatcher(thread_safe_sender_.get());
347 navigator_connect_dispatcher_ =
348 new NavigatorConnectDispatcher(thread_safe_sender_.get());
350 channel_->AddFilter(histogram_message_filter_.get());
351 channel_->AddFilter(sync_message_filter_.get());
352 channel_->AddFilter(resource_message_filter_.get());
353 channel_->AddFilter(quota_message_filter_->GetFilter());
354 channel_->AddFilter(notification_dispatcher_->GetFilter());
355 channel_->AddFilter(push_dispatcher_->GetFilter());
356 channel_->AddFilter(service_worker_message_filter_->GetFilter());
357 channel_->AddFilter(geofencing_message_filter_->GetFilter());
358 channel_->AddFilter(bluetooth_message_filter_->GetFilter());
359 channel_->AddFilter(navigator_connect_dispatcher_->GetFilter());
361 if (!IsInBrowserProcess()) {
362 // In single process mode, browser-side tracing will cover the whole
363 // process including renderers.
364 channel_->AddFilter(new tracing::ChildTraceMessageFilter(
365 ChildProcess::current()->io_message_loop_proxy()));
368 // In single process mode we may already have a power monitor
369 if (!base::PowerMonitor::Get()) {
370 scoped_ptr<PowerMonitorBroadcastSource> power_monitor_source(
371 new PowerMonitorBroadcastSource());
372 channel_->AddFilter(power_monitor_source->GetMessageFilter());
374 power_monitor_.reset(new base::PowerMonitor(
375 power_monitor_source.Pass()));
378 #if defined(OS_POSIX)
379 // Check that --process-type is specified so we don't do this in unit tests
380 // and single-process mode.
381 if (base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kProcessType))
382 channel_->AddFilter(new SuicideOnChannelErrorFilter());
383 #endif
385 // Add filters passed here via options.
386 for (auto startup_filter : options.startup_filters) {
387 channel_->AddFilter(startup_filter);
390 ConnectChannel(options.use_mojo_channel);
392 int connection_timeout = kConnectionTimeoutS;
393 std::string connection_override =
394 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
395 switches::kIPCConnectionTimeout);
396 if (!connection_override.empty()) {
397 int temp;
398 if (base::StringToInt(connection_override, &temp))
399 connection_timeout = temp;
402 base::MessageLoop::current()->PostDelayedTask(
403 FROM_HERE,
404 base::Bind(&ChildThreadImpl::EnsureConnected,
405 channel_connected_factory_.GetWeakPtr()),
406 base::TimeDelta::FromSeconds(connection_timeout));
408 #if defined(OS_ANDROID)
410 base::AutoLock lock(g_lazy_child_thread_lock.Get());
411 g_child_thread = this;
412 g_child_thread_initialized = true;
414 // Signalling without locking is fine here because only
415 // one thread can wait on the condition variable.
416 g_lazy_child_thread_cv.Get().Signal();
417 #endif
419 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
420 trace_memory_controller_.reset(new base::trace_event::TraceMemoryController(
421 message_loop_->message_loop_proxy(), ::HeapProfilerWithPseudoStackStart,
422 ::HeapProfilerStop, ::GetHeapProfile));
423 #endif
425 base::trace_event::MemoryDumpManager::GetInstance()->Initialize();
427 shared_bitmap_manager_.reset(
428 new ChildSharedBitmapManager(thread_safe_sender()));
430 gpu_memory_buffer_manager_.reset(
431 new ChildGpuMemoryBufferManager(thread_safe_sender()));
433 discardable_shared_memory_manager_.reset(
434 new ChildDiscardableSharedMemoryManager(thread_safe_sender()));
437 ChildThreadImpl::~ChildThreadImpl() {
438 // ChildDiscardableSharedMemoryManager has to be destroyed while
439 // |thread_safe_sender_| is still valid.
440 discardable_shared_memory_manager_.reset();
442 #if defined(OS_ANDROID)
444 base::AutoLock lock(g_lazy_child_thread_lock.Get());
445 g_child_thread = nullptr;
447 #endif
449 #ifdef IPC_MESSAGE_LOG_ENABLED
450 IPC::Logging::GetInstance()->SetIPCSender(NULL);
451 #endif
453 channel_->RemoveFilter(histogram_message_filter_.get());
454 channel_->RemoveFilter(sync_message_filter_.get());
456 // The ChannelProxy object caches a pointer to the IPC thread, so need to
457 // reset it as it's not guaranteed to outlive this object.
458 // NOTE: this also has the side-effect of not closing the main IPC channel to
459 // the browser process. This is needed because this is the signal that the
460 // browser uses to know that this process has died, so we need it to be alive
461 // until this process is shut down, and the OS closes the handle
462 // automatically. We used to watch the object handle on Windows to do this,
463 // but it wasn't possible to do so on POSIX.
464 channel_->ClearIPCTaskRunner();
465 g_lazy_tls.Pointer()->Set(NULL);
468 void ChildThreadImpl::Shutdown() {
469 // Delete objects that hold references to blink so derived classes can
470 // safely shutdown blink in their Shutdown implementation.
471 file_system_dispatcher_.reset();
472 quota_dispatcher_.reset();
473 WebFileSystemImpl::DeleteThreadSpecificInstance();
476 void ChildThreadImpl::OnChannelConnected(int32 peer_pid) {
477 channel_connected_factory_.InvalidateWeakPtrs();
480 void ChildThreadImpl::OnChannelError() {
481 set_on_channel_error_called(true);
482 base::MessageLoop::current()->Quit();
485 bool ChildThreadImpl::Send(IPC::Message* msg) {
486 DCHECK(base::MessageLoop::current() == message_loop());
487 if (!channel_) {
488 delete msg;
489 return false;
492 return channel_->Send(msg);
495 #if defined(OS_WIN)
496 void ChildThreadImpl::PreCacheFont(const LOGFONT& log_font) {
497 Send(new ChildProcessHostMsg_PreCacheFont(log_font));
500 void ChildThreadImpl::ReleaseCachedFonts() {
501 Send(new ChildProcessHostMsg_ReleaseCachedFonts());
503 #endif
505 MessageRouter* ChildThreadImpl::GetRouter() {
506 DCHECK(base::MessageLoop::current() == message_loop());
507 return &router_;
510 scoped_ptr<base::SharedMemory> ChildThreadImpl::AllocateSharedMemory(
511 size_t buf_size) {
512 DCHECK(base::MessageLoop::current() == message_loop());
513 return AllocateSharedMemory(buf_size, this);
516 // static
517 scoped_ptr<base::SharedMemory> ChildThreadImpl::AllocateSharedMemory(
518 size_t buf_size,
519 IPC::Sender* sender) {
520 scoped_ptr<base::SharedMemory> shared_buf;
521 #if defined(OS_WIN)
522 shared_buf.reset(new base::SharedMemory);
523 if (!shared_buf->CreateAnonymous(buf_size)) {
524 NOTREACHED();
525 return NULL;
527 #else
528 // On POSIX, we need to ask the browser to create the shared memory for us,
529 // since this is blocked by the sandbox.
530 base::SharedMemoryHandle shared_mem_handle;
531 if (sender->Send(new ChildProcessHostMsg_SyncAllocateSharedMemory(
532 buf_size, &shared_mem_handle))) {
533 if (base::SharedMemory::IsHandleValid(shared_mem_handle)) {
534 shared_buf.reset(new base::SharedMemory(shared_mem_handle, false));
535 } else {
536 NOTREACHED() << "Browser failed to allocate shared memory";
537 return NULL;
539 } else {
540 NOTREACHED() << "Browser allocation request message failed";
541 return NULL;
543 #endif
544 return shared_buf;
547 bool ChildThreadImpl::OnMessageReceived(const IPC::Message& msg) {
548 if (mojo_application_->OnMessageReceived(msg))
549 return true;
551 // Resource responses are sent to the resource dispatcher.
552 if (resource_dispatcher_->OnMessageReceived(msg))
553 return true;
554 if (websocket_dispatcher_->OnMessageReceived(msg))
555 return true;
556 if (file_system_dispatcher_->OnMessageReceived(msg))
557 return true;
559 bool handled = true;
560 IPC_BEGIN_MESSAGE_MAP(ChildThreadImpl, msg)
561 IPC_MESSAGE_HANDLER(ChildProcessMsg_Shutdown, OnShutdown)
562 #if defined(IPC_MESSAGE_LOG_ENABLED)
563 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetIPCLoggingEnabled,
564 OnSetIPCLoggingEnabled)
565 #endif
566 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetProfilerStatus,
567 OnSetProfilerStatus)
568 IPC_MESSAGE_HANDLER(ChildProcessMsg_GetChildProfilerData,
569 OnGetChildProfilerData)
570 IPC_MESSAGE_HANDLER(ChildProcessMsg_DumpHandles, OnDumpHandles)
571 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetProcessBackgrounded,
572 OnProcessBackgrounded)
573 #if defined(USE_TCMALLOC)
574 IPC_MESSAGE_HANDLER(ChildProcessMsg_GetTcmallocStats, OnGetTcmallocStats)
575 #endif
576 IPC_MESSAGE_UNHANDLED(handled = false)
577 IPC_END_MESSAGE_MAP()
579 if (handled)
580 return true;
582 if (msg.routing_id() == MSG_ROUTING_CONTROL)
583 return OnControlMessageReceived(msg);
585 return router_.OnMessageReceived(msg);
588 bool ChildThreadImpl::OnControlMessageReceived(const IPC::Message& msg) {
589 return false;
592 void ChildThreadImpl::OnShutdown() {
593 base::MessageLoop::current()->Quit();
596 #if defined(IPC_MESSAGE_LOG_ENABLED)
597 void ChildThreadImpl::OnSetIPCLoggingEnabled(bool enable) {
598 if (enable)
599 IPC::Logging::GetInstance()->Enable();
600 else
601 IPC::Logging::GetInstance()->Disable();
603 #endif // IPC_MESSAGE_LOG_ENABLED
605 void ChildThreadImpl::OnSetProfilerStatus(ThreadData::Status status) {
606 ThreadData::InitializeAndSetTrackingStatus(status);
609 void ChildThreadImpl::OnGetChildProfilerData(int sequence_number) {
610 tracked_objects::ProcessDataSnapshot process_data;
611 ThreadData::Snapshot(&process_data);
613 Send(
614 new ChildProcessHostMsg_ChildProfilerData(sequence_number, process_data));
617 void ChildThreadImpl::OnDumpHandles() {
618 #if defined(OS_WIN)
619 scoped_refptr<HandleEnumerator> handle_enum(
620 new HandleEnumerator(
621 base::CommandLine::ForCurrentProcess()->HasSwitch(
622 switches::kAuditAllHandles)));
623 handle_enum->EnumerateHandles();
624 Send(new ChildProcessHostMsg_DumpHandlesDone);
625 #else
626 NOTIMPLEMENTED();
627 #endif
630 #if defined(USE_TCMALLOC)
631 void ChildThreadImpl::OnGetTcmallocStats() {
632 std::string result;
633 char buffer[1024 * 32];
634 base::allocator::GetStats(buffer, sizeof(buffer));
635 result.append(buffer);
636 Send(new ChildProcessHostMsg_TcmallocStats(result));
638 #endif
640 ChildThreadImpl* ChildThreadImpl::current() {
641 return g_lazy_tls.Pointer()->Get();
644 #if defined(OS_ANDROID)
645 // The method must NOT be called on the child thread itself.
646 // It may block the child thread if so.
647 void ChildThreadImpl::ShutdownThread() {
648 DCHECK(!ChildThreadImpl::current()) <<
649 "this method should NOT be called from child thread itself";
651 base::AutoLock lock(g_lazy_child_thread_lock.Get());
652 while (!g_child_thread_initialized)
653 g_lazy_child_thread_cv.Get().Wait();
655 // g_child_thread may already have been destructed while we didn't hold the
656 // lock.
657 if (!g_child_thread)
658 return;
660 DCHECK_NE(base::MessageLoop::current(), g_child_thread->message_loop());
661 g_child_thread->message_loop()->PostTask(
662 FROM_HERE, base::Bind(&QuitMainThreadMessageLoop));
665 #endif
667 void ChildThreadImpl::OnProcessFinalRelease() {
668 if (on_channel_error_called_) {
669 base::MessageLoop::current()->Quit();
670 return;
673 // The child process shutdown sequence is a request response based mechanism,
674 // where we send out an initial feeler request to the child process host
675 // instance in the browser to verify if it's ok to shutdown the child process.
676 // The browser then sends back a response if it's ok to shutdown. This avoids
677 // race conditions if the process refcount is 0 but there's an IPC message
678 // inflight that would addref it.
679 Send(new ChildProcessHostMsg_ShutdownRequest);
682 void ChildThreadImpl::EnsureConnected() {
683 VLOG(0) << "ChildThreadImpl::EnsureConnected()";
684 base::Process::Current().Terminate(0, false);
687 bool ChildThreadImpl::IsInBrowserProcess() const {
688 return browser_process_io_runner_;
691 void ChildThreadImpl::OnProcessBackgrounded(bool background) {
692 // Set timer slack to maximum on main thread when in background.
693 base::TimerSlack timer_slack = base::TIMER_SLACK_NONE;
694 if (background)
695 timer_slack = base::TIMER_SLACK_MAXIMUM;
696 base::MessageLoop::current()->SetTimerSlack(timer_slack);
699 } // namespace content