[Do not revert] Roll-back V8 to version 4.4.63.
[chromium-blink-merge.git] / content / child / child_thread_impl.cc
blobcc13a5bf0a566b683a331b7e35d361f45cf18fe7
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(TCMALLOC_TRACE_MEMORY_SUPPORTED)
63 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
64 #endif
66 using tracked_objects::ThreadData;
68 namespace content {
69 namespace {
71 // How long to wait for a connection to the browser process before giving up.
72 const int kConnectionTimeoutS = 15;
74 base::LazyInstance<base::ThreadLocalPointer<ChildThreadImpl> > g_lazy_tls =
75 LAZY_INSTANCE_INITIALIZER;
77 // This isn't needed on Windows because there the sandbox's job object
78 // terminates child processes automatically. For unsandboxed processes (i.e.
79 // plugins), PluginThread has EnsureTerminateMessageFilter.
80 #if defined(OS_POSIX)
82 #if defined(ADDRESS_SANITIZER) || defined(LEAK_SANITIZER) || \
83 defined(MEMORY_SANITIZER) || defined(THREAD_SANITIZER) || \
84 defined(UNDEFINED_SANITIZER)
85 // A thread delegate that waits for |duration| and then exits the process with
86 // _exit(0).
87 class WaitAndExitDelegate : public base::PlatformThread::Delegate {
88 public:
89 explicit WaitAndExitDelegate(base::TimeDelta duration)
90 : duration_(duration) {}
92 void ThreadMain() override {
93 base::PlatformThread::Sleep(duration_);
94 _exit(0);
97 private:
98 const base::TimeDelta duration_;
99 DISALLOW_COPY_AND_ASSIGN(WaitAndExitDelegate);
102 bool CreateWaitAndExitThread(base::TimeDelta duration) {
103 scoped_ptr<WaitAndExitDelegate> delegate(new WaitAndExitDelegate(duration));
105 const bool thread_created =
106 base::PlatformThread::CreateNonJoinable(0, delegate.get());
107 if (!thread_created)
108 return false;
110 // A non joinable thread has been created. The thread will either terminate
111 // the process or will be terminated by the process. Therefore, keep the
112 // delegate object alive for the lifetime of the process.
113 WaitAndExitDelegate* leaking_delegate = delegate.release();
114 ANNOTATE_LEAKING_OBJECT_PTR(leaking_delegate);
115 ignore_result(leaking_delegate);
116 return true;
118 #endif
120 class SuicideOnChannelErrorFilter : public IPC::MessageFilter {
121 public:
122 // IPC::MessageFilter
123 void OnChannelError() override {
124 // For renderer/worker processes:
125 // On POSIX, at least, one can install an unload handler which loops
126 // forever and leave behind a renderer process which eats 100% CPU forever.
128 // This is because the terminate signals (ViewMsg_ShouldClose and the error
129 // from the IPC sender) are routed to the main message loop but never
130 // processed (because that message loop is stuck in V8).
132 // One could make the browser SIGKILL the renderers, but that leaves open a
133 // large window where a browser failure (or a user, manually terminating
134 // the browser because "it's stuck") will leave behind a process eating all
135 // the CPU.
137 // So, we install a filter on the sender so that we can process this event
138 // here and kill the process.
139 base::debug::StopProfiling();
140 #if defined(ADDRESS_SANITIZER) || defined(LEAK_SANITIZER) || \
141 defined(MEMORY_SANITIZER) || defined(THREAD_SANITIZER) || \
142 defined(UNDEFINED_SANITIZER)
143 // Some sanitizer tools rely on exit handlers (e.g. to run leak detection,
144 // or dump code coverage data to disk). Instead of exiting the process
145 // immediately, we give it 60 seconds to run exit handlers.
146 CHECK(CreateWaitAndExitThread(base::TimeDelta::FromSeconds(60)));
147 #if defined(LEAK_SANITIZER)
148 // Invoke LeakSanitizer early to avoid detecting shutdown-only leaks. If
149 // leaks are found, the process will exit here.
150 __lsan_do_leak_check();
151 #endif
152 #else
153 _exit(0);
154 #endif
157 protected:
158 ~SuicideOnChannelErrorFilter() override {}
161 #endif // OS(POSIX)
163 #if defined(OS_ANDROID)
164 ChildThreadImpl* g_child_thread = NULL;
165 bool g_child_thread_initialized = false;
167 // A lock protects g_child_thread.
168 base::LazyInstance<base::Lock>::Leaky g_lazy_child_thread_lock =
169 LAZY_INSTANCE_INITIALIZER;
171 // base::ConditionVariable has an explicit constructor that takes
172 // a base::Lock pointer as parameter. The base::DefaultLazyInstanceTraits
173 // doesn't handle the case. Thus, we need our own class here.
174 struct CondVarLazyInstanceTraits {
175 static const bool kRegisterOnExit = false;
176 #ifndef NDEBUG
177 static const bool kAllowedToAccessOnNonjoinableThread = true;
178 #endif
180 static base::ConditionVariable* New(void* instance) {
181 return new (instance) base::ConditionVariable(
182 g_lazy_child_thread_lock.Pointer());
184 static void Delete(base::ConditionVariable* instance) {
185 instance->~ConditionVariable();
189 // A condition variable that synchronize threads initializing and waiting
190 // for g_child_thread.
191 base::LazyInstance<base::ConditionVariable, CondVarLazyInstanceTraits>
192 g_lazy_child_thread_cv = LAZY_INSTANCE_INITIALIZER;
194 void QuitMainThreadMessageLoop() {
195 base::MessageLoop::current()->Quit();
198 #endif
200 } // namespace
202 ChildThread* ChildThread::Get() {
203 return ChildThreadImpl::current();
206 ChildThreadImpl::Options::Options()
207 : channel_name(base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
208 switches::kProcessChannelID)),
209 use_mojo_channel(false) {
212 ChildThreadImpl::Options::~Options() {
215 ChildThreadImpl::Options::Builder::Builder() {
218 ChildThreadImpl::Options::Builder&
219 ChildThreadImpl::Options::Builder::InBrowserProcess(
220 const InProcessChildThreadParams& params) {
221 options_.browser_process_io_runner = params.io_runner();
222 options_.channel_name = params.channel_name();
223 return *this;
226 ChildThreadImpl::Options::Builder&
227 ChildThreadImpl::Options::Builder::UseMojoChannel(bool use_mojo_channel) {
228 options_.use_mojo_channel = use_mojo_channel;
229 return *this;
232 ChildThreadImpl::Options::Builder&
233 ChildThreadImpl::Options::Builder::WithChannelName(
234 const std::string& channel_name) {
235 options_.channel_name = channel_name;
236 return *this;
239 ChildThreadImpl::Options::Builder&
240 ChildThreadImpl::Options::Builder::AddStartupFilter(
241 IPC::MessageFilter* filter) {
242 options_.startup_filters.push_back(filter);
243 return *this;
246 ChildThreadImpl::Options ChildThreadImpl::Options::Builder::Build() {
247 return options_;
250 ChildThreadImpl::ChildThreadMessageRouter::ChildThreadMessageRouter(
251 IPC::Sender* sender)
252 : sender_(sender) {}
254 bool ChildThreadImpl::ChildThreadMessageRouter::Send(IPC::Message* msg) {
255 return sender_->Send(msg);
258 ChildThreadImpl::ChildThreadImpl()
259 : router_(this),
260 channel_connected_factory_(this) {
261 Init(Options::Builder().Build());
264 ChildThreadImpl::ChildThreadImpl(const Options& options)
265 : router_(this),
266 browser_process_io_runner_(options.browser_process_io_runner),
267 channel_connected_factory_(this) {
268 Init(options);
271 scoped_refptr<base::SequencedTaskRunner> ChildThreadImpl::GetIOTaskRunner() {
272 if (IsInBrowserProcess())
273 return browser_process_io_runner_;
274 return ChildProcess::current()->io_message_loop_proxy();
277 void ChildThreadImpl::ConnectChannel(bool use_mojo_channel) {
278 bool create_pipe_now = true;
279 if (use_mojo_channel) {
280 VLOG(1) << "Mojo is enabled on child";
281 scoped_refptr<base::SequencedTaskRunner> io_task_runner = GetIOTaskRunner();
282 DCHECK(io_task_runner);
283 channel_->Init(IPC::ChannelMojo::CreateClientFactory(
284 nullptr, io_task_runner, channel_name_),
285 create_pipe_now);
286 return;
289 VLOG(1) << "Mojo is disabled on child";
290 channel_->Init(channel_name_, IPC::Channel::MODE_CLIENT, create_pipe_now);
293 void ChildThreadImpl::Init(const Options& options) {
294 channel_name_ = options.channel_name;
296 g_lazy_tls.Pointer()->Set(this);
297 on_channel_error_called_ = false;
298 message_loop_ = base::MessageLoop::current();
299 #ifdef IPC_MESSAGE_LOG_ENABLED
300 // We must make sure to instantiate the IPC Logger *before* we create the
301 // channel, otherwise we can get a callback on the IO thread which creates
302 // the logger, and the logger does not like being created on the IO thread.
303 IPC::Logging::GetInstance();
304 #endif
305 channel_ = IPC::SyncChannel::Create(
306 this, ChildProcess::current()->io_message_loop_proxy(),
307 ChildProcess::current()->GetShutDownEvent());
308 #ifdef IPC_MESSAGE_LOG_ENABLED
309 if (!IsInBrowserProcess())
310 IPC::Logging::GetInstance()->SetIPCSender(this);
311 #endif
313 mojo_application_.reset(new MojoApplication(GetIOTaskRunner()));
315 sync_message_filter_ =
316 new IPC::SyncMessageFilter(ChildProcess::current()->GetShutDownEvent());
317 thread_safe_sender_ = new ThreadSafeSender(
318 base::MessageLoopProxy::current().get(), sync_message_filter_.get());
320 resource_dispatcher_.reset(new ResourceDispatcher(
321 this, message_loop()->task_runner()));
322 websocket_dispatcher_.reset(new WebSocketDispatcher);
323 file_system_dispatcher_.reset(new FileSystemDispatcher());
325 histogram_message_filter_ = new ChildHistogramMessageFilter();
326 resource_message_filter_ =
327 new ChildResourceMessageFilter(resource_dispatcher());
329 service_worker_message_filter_ =
330 new ServiceWorkerMessageFilter(thread_safe_sender_.get());
332 quota_message_filter_ =
333 new QuotaMessageFilter(thread_safe_sender_.get());
334 quota_dispatcher_.reset(new QuotaDispatcher(thread_safe_sender_.get(),
335 quota_message_filter_.get()));
336 geofencing_message_filter_ =
337 new GeofencingMessageFilter(thread_safe_sender_.get());
338 bluetooth_message_filter_ =
339 new BluetoothMessageFilter(thread_safe_sender_.get());
340 notification_dispatcher_ =
341 new NotificationDispatcher(thread_safe_sender_.get());
342 push_dispatcher_ = new PushDispatcher(thread_safe_sender_.get());
343 navigator_connect_dispatcher_ =
344 new NavigatorConnectDispatcher(thread_safe_sender_.get());
346 channel_->AddFilter(histogram_message_filter_.get());
347 channel_->AddFilter(sync_message_filter_.get());
348 channel_->AddFilter(resource_message_filter_.get());
349 channel_->AddFilter(quota_message_filter_->GetFilter());
350 channel_->AddFilter(notification_dispatcher_->GetFilter());
351 channel_->AddFilter(push_dispatcher_->GetFilter());
352 channel_->AddFilter(service_worker_message_filter_->GetFilter());
353 channel_->AddFilter(geofencing_message_filter_->GetFilter());
354 channel_->AddFilter(bluetooth_message_filter_->GetFilter());
355 channel_->AddFilter(navigator_connect_dispatcher_->GetFilter());
357 if (!IsInBrowserProcess()) {
358 // In single process mode, browser-side tracing will cover the whole
359 // process including renderers.
360 channel_->AddFilter(new tracing::ChildTraceMessageFilter(
361 ChildProcess::current()->io_message_loop_proxy()));
364 // In single process mode we may already have a power monitor
365 if (!base::PowerMonitor::Get()) {
366 scoped_ptr<PowerMonitorBroadcastSource> power_monitor_source(
367 new PowerMonitorBroadcastSource());
368 channel_->AddFilter(power_monitor_source->GetMessageFilter());
370 power_monitor_.reset(new base::PowerMonitor(
371 power_monitor_source.Pass()));
374 #if defined(OS_POSIX)
375 // Check that --process-type is specified so we don't do this in unit tests
376 // and single-process mode.
377 if (base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kProcessType))
378 channel_->AddFilter(new SuicideOnChannelErrorFilter());
379 #endif
381 // Add filters passed here via options.
382 for (auto startup_filter : options.startup_filters) {
383 channel_->AddFilter(startup_filter);
386 ConnectChannel(options.use_mojo_channel);
388 int connection_timeout = kConnectionTimeoutS;
389 std::string connection_override =
390 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
391 switches::kIPCConnectionTimeout);
392 if (!connection_override.empty()) {
393 int temp;
394 if (base::StringToInt(connection_override, &temp))
395 connection_timeout = temp;
398 base::MessageLoop::current()->PostDelayedTask(
399 FROM_HERE,
400 base::Bind(&ChildThreadImpl::EnsureConnected,
401 channel_connected_factory_.GetWeakPtr()),
402 base::TimeDelta::FromSeconds(connection_timeout));
404 #if defined(OS_ANDROID)
406 base::AutoLock lock(g_lazy_child_thread_lock.Get());
407 g_child_thread = this;
408 g_child_thread_initialized = true;
410 // Signalling without locking is fine here because only
411 // one thread can wait on the condition variable.
412 g_lazy_child_thread_cv.Get().Signal();
413 #endif
415 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
416 trace_memory_controller_.reset(new base::trace_event::TraceMemoryController(
417 message_loop_->message_loop_proxy(), ::HeapProfilerWithPseudoStackStart,
418 ::HeapProfilerStop, ::GetHeapProfile));
419 #endif
421 base::trace_event::MemoryDumpManager::GetInstance()->Initialize();
423 shared_bitmap_manager_.reset(
424 new ChildSharedBitmapManager(thread_safe_sender()));
426 gpu_memory_buffer_manager_.reset(
427 new ChildGpuMemoryBufferManager(thread_safe_sender()));
429 discardable_shared_memory_manager_.reset(
430 new ChildDiscardableSharedMemoryManager(thread_safe_sender()));
433 ChildThreadImpl::~ChildThreadImpl() {
434 // ChildDiscardableSharedMemoryManager has to be destroyed while
435 // |thread_safe_sender_| is still valid.
436 discardable_shared_memory_manager_.reset();
438 #if defined(OS_ANDROID)
440 base::AutoLock lock(g_lazy_child_thread_lock.Get());
441 g_child_thread = nullptr;
443 #endif
445 #ifdef IPC_MESSAGE_LOG_ENABLED
446 IPC::Logging::GetInstance()->SetIPCSender(NULL);
447 #endif
449 channel_->RemoveFilter(histogram_message_filter_.get());
450 channel_->RemoveFilter(sync_message_filter_.get());
452 // The ChannelProxy object caches a pointer to the IPC thread, so need to
453 // reset it as it's not guaranteed to outlive this object.
454 // NOTE: this also has the side-effect of not closing the main IPC channel to
455 // the browser process. This is needed because this is the signal that the
456 // browser uses to know that this process has died, so we need it to be alive
457 // until this process is shut down, and the OS closes the handle
458 // automatically. We used to watch the object handle on Windows to do this,
459 // but it wasn't possible to do so on POSIX.
460 channel_->ClearIPCTaskRunner();
461 g_lazy_tls.Pointer()->Set(NULL);
464 void ChildThreadImpl::Shutdown() {
465 // Delete objects that hold references to blink so derived classes can
466 // safely shutdown blink in their Shutdown implementation.
467 file_system_dispatcher_.reset();
468 quota_dispatcher_.reset();
469 WebFileSystemImpl::DeleteThreadSpecificInstance();
472 void ChildThreadImpl::OnChannelConnected(int32 peer_pid) {
473 channel_connected_factory_.InvalidateWeakPtrs();
476 void ChildThreadImpl::OnChannelError() {
477 set_on_channel_error_called(true);
478 base::MessageLoop::current()->Quit();
481 bool ChildThreadImpl::Send(IPC::Message* msg) {
482 DCHECK(base::MessageLoop::current() == message_loop());
483 if (!channel_) {
484 delete msg;
485 return false;
488 return channel_->Send(msg);
491 #if defined(OS_WIN)
492 void ChildThreadImpl::PreCacheFont(const LOGFONT& log_font) {
493 Send(new ChildProcessHostMsg_PreCacheFont(log_font));
496 void ChildThreadImpl::ReleaseCachedFonts() {
497 Send(new ChildProcessHostMsg_ReleaseCachedFonts());
499 #endif
501 MessageRouter* ChildThreadImpl::GetRouter() {
502 DCHECK(base::MessageLoop::current() == message_loop());
503 return &router_;
506 scoped_ptr<base::SharedMemory> ChildThreadImpl::AllocateSharedMemory(
507 size_t buf_size) {
508 DCHECK(base::MessageLoop::current() == message_loop());
509 return AllocateSharedMemory(buf_size, this);
512 // static
513 scoped_ptr<base::SharedMemory> ChildThreadImpl::AllocateSharedMemory(
514 size_t buf_size,
515 IPC::Sender* sender) {
516 scoped_ptr<base::SharedMemory> shared_buf;
517 #if defined(OS_WIN)
518 shared_buf.reset(new base::SharedMemory);
519 if (!shared_buf->CreateAnonymous(buf_size)) {
520 NOTREACHED();
521 return NULL;
523 #else
524 // On POSIX, we need to ask the browser to create the shared memory for us,
525 // since this is blocked by the sandbox.
526 base::SharedMemoryHandle shared_mem_handle;
527 if (sender->Send(new ChildProcessHostMsg_SyncAllocateSharedMemory(
528 buf_size, &shared_mem_handle))) {
529 if (base::SharedMemory::IsHandleValid(shared_mem_handle)) {
530 shared_buf.reset(new base::SharedMemory(shared_mem_handle, false));
531 } else {
532 NOTREACHED() << "Browser failed to allocate shared memory";
533 return NULL;
535 } else {
536 NOTREACHED() << "Browser allocation request message failed";
537 return NULL;
539 #endif
540 return shared_buf;
543 bool ChildThreadImpl::OnMessageReceived(const IPC::Message& msg) {
544 if (mojo_application_->OnMessageReceived(msg))
545 return true;
547 // Resource responses are sent to the resource dispatcher.
548 if (resource_dispatcher_->OnMessageReceived(msg))
549 return true;
550 if (websocket_dispatcher_->OnMessageReceived(msg))
551 return true;
552 if (file_system_dispatcher_->OnMessageReceived(msg))
553 return true;
555 bool handled = true;
556 IPC_BEGIN_MESSAGE_MAP(ChildThreadImpl, msg)
557 IPC_MESSAGE_HANDLER(ChildProcessMsg_Shutdown, OnShutdown)
558 #if defined(IPC_MESSAGE_LOG_ENABLED)
559 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetIPCLoggingEnabled,
560 OnSetIPCLoggingEnabled)
561 #endif
562 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetProfilerStatus,
563 OnSetProfilerStatus)
564 IPC_MESSAGE_HANDLER(ChildProcessMsg_GetChildProfilerData,
565 OnGetChildProfilerData)
566 IPC_MESSAGE_HANDLER(ChildProcessMsg_ProfilingPhaseCompleted,
567 OnProfilingPhaseCompleted)
568 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetProcessBackgrounded,
569 OnProcessBackgrounded)
570 #if defined(USE_TCMALLOC)
571 IPC_MESSAGE_HANDLER(ChildProcessMsg_GetTcmallocStats, OnGetTcmallocStats)
572 #endif
573 IPC_MESSAGE_UNHANDLED(handled = false)
574 IPC_END_MESSAGE_MAP()
576 if (handled)
577 return true;
579 if (msg.routing_id() == MSG_ROUTING_CONTROL)
580 return OnControlMessageReceived(msg);
582 return router_.OnMessageReceived(msg);
585 bool ChildThreadImpl::OnControlMessageReceived(const IPC::Message& msg) {
586 return false;
589 void ChildThreadImpl::OnShutdown() {
590 base::MessageLoop::current()->Quit();
593 #if defined(IPC_MESSAGE_LOG_ENABLED)
594 void ChildThreadImpl::OnSetIPCLoggingEnabled(bool enable) {
595 if (enable)
596 IPC::Logging::GetInstance()->Enable();
597 else
598 IPC::Logging::GetInstance()->Disable();
600 #endif // IPC_MESSAGE_LOG_ENABLED
602 void ChildThreadImpl::OnSetProfilerStatus(ThreadData::Status status) {
603 ThreadData::InitializeAndSetTrackingStatus(status);
606 void ChildThreadImpl::OnGetChildProfilerData(int sequence_number,
607 int current_profiling_phase) {
608 tracked_objects::ProcessDataSnapshot process_data;
609 ThreadData::Snapshot(current_profiling_phase, &process_data);
611 Send(
612 new ChildProcessHostMsg_ChildProfilerData(sequence_number, process_data));
615 void ChildThreadImpl::OnProfilingPhaseCompleted(int profiling_phase) {
616 ThreadData::OnProfilingPhaseCompleted(profiling_phase);
619 #if defined(USE_TCMALLOC)
620 void ChildThreadImpl::OnGetTcmallocStats() {
621 std::string result;
622 char buffer[1024 * 32];
623 base::allocator::GetStats(buffer, sizeof(buffer));
624 result.append(buffer);
625 Send(new ChildProcessHostMsg_TcmallocStats(result));
627 #endif
629 ChildThreadImpl* ChildThreadImpl::current() {
630 return g_lazy_tls.Pointer()->Get();
633 #if defined(OS_ANDROID)
634 // The method must NOT be called on the child thread itself.
635 // It may block the child thread if so.
636 void ChildThreadImpl::ShutdownThread() {
637 DCHECK(!ChildThreadImpl::current()) <<
638 "this method should NOT be called from child thread itself";
640 base::AutoLock lock(g_lazy_child_thread_lock.Get());
641 while (!g_child_thread_initialized)
642 g_lazy_child_thread_cv.Get().Wait();
644 // g_child_thread may already have been destructed while we didn't hold the
645 // lock.
646 if (!g_child_thread)
647 return;
649 DCHECK_NE(base::MessageLoop::current(), g_child_thread->message_loop());
650 g_child_thread->message_loop()->PostTask(
651 FROM_HERE, base::Bind(&QuitMainThreadMessageLoop));
654 #endif
656 void ChildThreadImpl::OnProcessFinalRelease() {
657 if (on_channel_error_called_) {
658 base::MessageLoop::current()->Quit();
659 return;
662 // The child process shutdown sequence is a request response based mechanism,
663 // where we send out an initial feeler request to the child process host
664 // instance in the browser to verify if it's ok to shutdown the child process.
665 // The browser then sends back a response if it's ok to shutdown. This avoids
666 // race conditions if the process refcount is 0 but there's an IPC message
667 // inflight that would addref it.
668 Send(new ChildProcessHostMsg_ShutdownRequest);
671 void ChildThreadImpl::EnsureConnected() {
672 VLOG(0) << "ChildThreadImpl::EnsureConnected()";
673 base::Process::Current().Terminate(0, false);
676 bool ChildThreadImpl::IsInBrowserProcess() const {
677 return browser_process_io_runner_;
680 void ChildThreadImpl::OnProcessBackgrounded(bool background) {
681 // Set timer slack to maximum on main thread when in background.
682 base::TimerSlack timer_slack = base::TIMER_SLACK_NONE;
683 if (background)
684 timer_slack = base::TIMER_SLACK_MAXIMUM;
685 base::MessageLoop::current()->SetTimerSlack(timer_slack);
688 } // namespace content