Fix link in German terms of service.
[chromium-blink-merge.git] / content / child / child_thread_impl.cc
blobca970ec4b94f45f4f3c8869647da0f937c632487
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/bluetooth/bluetooth_message_filter.h"
35 #include "content/child/child_discardable_shared_memory_manager.h"
36 #include "content/child/child_gpu_memory_buffer_manager.h"
37 #include "content/child/child_histogram_message_filter.h"
38 #include "content/child/child_process.h"
39 #include "content/child/child_resource_message_filter.h"
40 #include "content/child/child_shared_bitmap_manager.h"
41 #include "content/child/fileapi/file_system_dispatcher.h"
42 #include "content/child/fileapi/webfilesystem_impl.h"
43 #include "content/child/geofencing/geofencing_message_filter.h"
44 #include "content/child/mojo/mojo_application.h"
45 #include "content/child/navigator_connect/navigator_connect_dispatcher.h"
46 #include "content/child/notifications/notification_dispatcher.h"
47 #include "content/child/power_monitor_broadcast_source.h"
48 #include "content/child/push_messaging/push_dispatcher.h"
49 #include "content/child/quota_dispatcher.h"
50 #include "content/child/quota_message_filter.h"
51 #include "content/child/resource_dispatcher.h"
52 #include "content/child/service_worker/service_worker_message_filter.h"
53 #include "content/child/thread_safe_sender.h"
54 #include "content/child/websocket_dispatcher.h"
55 #include "content/common/child_process_messages.h"
56 #include "content/common/in_process_child_thread_params.h"
57 #include "content/public/common/content_switches.h"
58 #include "ipc/ipc_logging.h"
59 #include "ipc/ipc_switches.h"
60 #include "ipc/ipc_sync_channel.h"
61 #include "ipc/ipc_sync_message_filter.h"
62 #include "ipc/mojo/ipc_channel_mojo.h"
64 #if defined(OS_ANDROID)
65 #include "base/thread_task_runner_handle.h"
66 #endif
68 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
69 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
70 #endif
72 using tracked_objects::ThreadData;
74 namespace content {
75 namespace {
77 // How long to wait for a connection to the browser process before giving up.
78 const int kConnectionTimeoutS = 15;
80 base::LazyInstance<base::ThreadLocalPointer<ChildThreadImpl> > g_lazy_tls =
81 LAZY_INSTANCE_INITIALIZER;
83 // This isn't needed on Windows because there the sandbox's job object
84 // terminates child processes automatically. For unsandboxed processes (i.e.
85 // plugins), PluginThread has EnsureTerminateMessageFilter.
86 #if defined(OS_POSIX)
88 #if defined(ADDRESS_SANITIZER) || defined(LEAK_SANITIZER) || \
89 defined(MEMORY_SANITIZER) || defined(THREAD_SANITIZER) || \
90 defined(UNDEFINED_SANITIZER)
91 // A thread delegate that waits for |duration| and then exits the process with
92 // _exit(0).
93 class WaitAndExitDelegate : public base::PlatformThread::Delegate {
94 public:
95 explicit WaitAndExitDelegate(base::TimeDelta duration)
96 : duration_(duration) {}
98 void ThreadMain() override {
99 base::PlatformThread::Sleep(duration_);
100 _exit(0);
103 private:
104 const base::TimeDelta duration_;
105 DISALLOW_COPY_AND_ASSIGN(WaitAndExitDelegate);
108 bool CreateWaitAndExitThread(base::TimeDelta duration) {
109 scoped_ptr<WaitAndExitDelegate> delegate(new WaitAndExitDelegate(duration));
111 const bool thread_created =
112 base::PlatformThread::CreateNonJoinable(0, delegate.get());
113 if (!thread_created)
114 return false;
116 // A non joinable thread has been created. The thread will either terminate
117 // the process or will be terminated by the process. Therefore, keep the
118 // delegate object alive for the lifetime of the process.
119 WaitAndExitDelegate* leaking_delegate = delegate.release();
120 ANNOTATE_LEAKING_OBJECT_PTR(leaking_delegate);
121 ignore_result(leaking_delegate);
122 return true;
124 #endif
126 class SuicideOnChannelErrorFilter : public IPC::MessageFilter {
127 public:
128 // IPC::MessageFilter
129 void OnChannelError() override {
130 // For renderer/worker processes:
131 // On POSIX, at least, one can install an unload handler which loops
132 // forever and leave behind a renderer process which eats 100% CPU forever.
134 // This is because the terminate signals (ViewMsg_ShouldClose and the error
135 // from the IPC sender) are routed to the main message loop but never
136 // processed (because that message loop is stuck in V8).
138 // One could make the browser SIGKILL the renderers, but that leaves open a
139 // large window where a browser failure (or a user, manually terminating
140 // the browser because "it's stuck") will leave behind a process eating all
141 // the CPU.
143 // So, we install a filter on the sender so that we can process this event
144 // here and kill the process.
145 base::debug::StopProfiling();
146 #if defined(ADDRESS_SANITIZER) || defined(LEAK_SANITIZER) || \
147 defined(MEMORY_SANITIZER) || defined(THREAD_SANITIZER) || \
148 defined(UNDEFINED_SANITIZER)
149 // Some sanitizer tools rely on exit handlers (e.g. to run leak detection,
150 // or dump code coverage data to disk). Instead of exiting the process
151 // immediately, we give it 60 seconds to run exit handlers.
152 CHECK(CreateWaitAndExitThread(base::TimeDelta::FromSeconds(60)));
153 #if defined(LEAK_SANITIZER)
154 // Invoke LeakSanitizer early to avoid detecting shutdown-only leaks. If
155 // leaks are found, the process will exit here.
156 __lsan_do_leak_check();
157 #endif
158 #else
159 _exit(0);
160 #endif
163 protected:
164 ~SuicideOnChannelErrorFilter() override {}
167 #endif // OS(POSIX)
169 #if defined(OS_ANDROID)
170 // A class that allows for triggering a clean shutdown from another
171 // thread through draining the main thread's msg loop.
172 class QuitClosure {
173 public:
174 QuitClosure();
175 ~QuitClosure();
177 void BindToMainThread();
178 void PostQuitFromNonMainThread();
180 private:
181 static void PostClosure(
182 const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
183 base::Closure closure);
185 base::Lock lock_;
186 base::ConditionVariable cond_var_;
187 base::Closure closure_;
190 QuitClosure::QuitClosure() : cond_var_(&lock_) {
193 QuitClosure::~QuitClosure() {
196 void QuitClosure::PostClosure(
197 const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
198 base::Closure closure) {
199 task_runner->PostTask(FROM_HERE, closure);
202 void QuitClosure::BindToMainThread() {
203 base::AutoLock lock(lock_);
204 scoped_refptr<base::SingleThreadTaskRunner> task_runner(
205 base::ThreadTaskRunnerHandle::Get());
206 base::Closure quit_closure =
207 base::MessageLoop::current()->QuitWhenIdleClosure();
208 closure_ = base::Bind(&QuitClosure::PostClosure, task_runner, quit_closure);
209 cond_var_.Signal();
212 void QuitClosure::PostQuitFromNonMainThread() {
213 base::AutoLock lock(lock_);
214 while (closure_.is_null())
215 cond_var_.Wait();
217 closure_.Run();
220 base::LazyInstance<QuitClosure> g_quit_closure = LAZY_INSTANCE_INITIALIZER;
221 #endif
223 } // namespace
225 ChildThread* ChildThread::Get() {
226 return ChildThreadImpl::current();
229 ChildThreadImpl::Options::Options()
230 : channel_name(base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
231 switches::kProcessChannelID)),
232 use_mojo_channel(false) {
235 ChildThreadImpl::Options::~Options() {
238 ChildThreadImpl::Options::Builder::Builder() {
241 ChildThreadImpl::Options::Builder&
242 ChildThreadImpl::Options::Builder::InBrowserProcess(
243 const InProcessChildThreadParams& params) {
244 options_.browser_process_io_runner = params.io_runner();
245 options_.channel_name = params.channel_name();
246 return *this;
249 ChildThreadImpl::Options::Builder&
250 ChildThreadImpl::Options::Builder::UseMojoChannel(bool use_mojo_channel) {
251 options_.use_mojo_channel = use_mojo_channel;
252 return *this;
255 ChildThreadImpl::Options::Builder&
256 ChildThreadImpl::Options::Builder::WithChannelName(
257 const std::string& channel_name) {
258 options_.channel_name = channel_name;
259 return *this;
262 ChildThreadImpl::Options::Builder&
263 ChildThreadImpl::Options::Builder::AddStartupFilter(
264 IPC::MessageFilter* filter) {
265 options_.startup_filters.push_back(filter);
266 return *this;
269 ChildThreadImpl::Options ChildThreadImpl::Options::Builder::Build() {
270 return options_;
273 ChildThreadImpl::ChildThreadMessageRouter::ChildThreadMessageRouter(
274 IPC::Sender* sender)
275 : sender_(sender) {}
277 bool ChildThreadImpl::ChildThreadMessageRouter::Send(IPC::Message* msg) {
278 return sender_->Send(msg);
281 ChildThreadImpl::ChildThreadImpl()
282 : router_(this),
283 channel_connected_factory_(this) {
284 Init(Options::Builder().Build());
287 ChildThreadImpl::ChildThreadImpl(const Options& options)
288 : router_(this),
289 browser_process_io_runner_(options.browser_process_io_runner),
290 channel_connected_factory_(this) {
291 Init(options);
294 scoped_refptr<base::SequencedTaskRunner> ChildThreadImpl::GetIOTaskRunner() {
295 if (IsInBrowserProcess())
296 return browser_process_io_runner_;
297 return ChildProcess::current()->io_task_runner();
300 void ChildThreadImpl::ConnectChannel(bool use_mojo_channel) {
301 bool create_pipe_now = true;
302 if (use_mojo_channel) {
303 VLOG(1) << "Mojo is enabled on child";
304 scoped_refptr<base::SequencedTaskRunner> io_task_runner = GetIOTaskRunner();
305 DCHECK(io_task_runner);
306 channel_->Init(IPC::ChannelMojo::CreateClientFactory(
307 nullptr, io_task_runner, channel_name_),
308 create_pipe_now);
309 return;
312 VLOG(1) << "Mojo is disabled on child";
313 channel_->Init(channel_name_, IPC::Channel::MODE_CLIENT, create_pipe_now);
316 void ChildThreadImpl::Init(const Options& options) {
317 channel_name_ = options.channel_name;
319 g_lazy_tls.Pointer()->Set(this);
320 on_channel_error_called_ = false;
321 message_loop_ = base::MessageLoop::current();
322 #ifdef IPC_MESSAGE_LOG_ENABLED
323 // We must make sure to instantiate the IPC Logger *before* we create the
324 // channel, otherwise we can get a callback on the IO thread which creates
325 // the logger, and the logger does not like being created on the IO thread.
326 IPC::Logging::GetInstance();
327 #endif
328 channel_ =
329 IPC::SyncChannel::Create(this, ChildProcess::current()->io_task_runner(),
330 ChildProcess::current()->GetShutDownEvent());
331 #ifdef IPC_MESSAGE_LOG_ENABLED
332 if (!IsInBrowserProcess())
333 IPC::Logging::GetInstance()->SetIPCSender(this);
334 #endif
336 mojo_application_.reset(new MojoApplication(GetIOTaskRunner()));
338 sync_message_filter_ =
339 new IPC::SyncMessageFilter(ChildProcess::current()->GetShutDownEvent());
340 thread_safe_sender_ = new ThreadSafeSender(
341 message_loop_->task_runner(), sync_message_filter_.get());
343 resource_dispatcher_.reset(new ResourceDispatcher(
344 this, message_loop()->task_runner()));
345 websocket_dispatcher_.reset(new WebSocketDispatcher);
346 file_system_dispatcher_.reset(new FileSystemDispatcher());
348 histogram_message_filter_ = new ChildHistogramMessageFilter();
349 resource_message_filter_ =
350 new ChildResourceMessageFilter(resource_dispatcher());
352 service_worker_message_filter_ =
353 new ServiceWorkerMessageFilter(thread_safe_sender_.get());
355 quota_message_filter_ =
356 new QuotaMessageFilter(thread_safe_sender_.get());
357 quota_dispatcher_.reset(new QuotaDispatcher(thread_safe_sender_.get(),
358 quota_message_filter_.get()));
359 geofencing_message_filter_ =
360 new GeofencingMessageFilter(thread_safe_sender_.get());
361 bluetooth_message_filter_ =
362 new BluetoothMessageFilter(thread_safe_sender_.get());
363 notification_dispatcher_ =
364 new NotificationDispatcher(thread_safe_sender_.get());
365 push_dispatcher_ = new PushDispatcher(thread_safe_sender_.get());
366 navigator_connect_dispatcher_ =
367 new NavigatorConnectDispatcher(thread_safe_sender_.get());
369 channel_->AddFilter(histogram_message_filter_.get());
370 channel_->AddFilter(sync_message_filter_.get());
371 channel_->AddFilter(resource_message_filter_.get());
372 channel_->AddFilter(quota_message_filter_->GetFilter());
373 channel_->AddFilter(notification_dispatcher_->GetFilter());
374 channel_->AddFilter(push_dispatcher_->GetFilter());
375 channel_->AddFilter(service_worker_message_filter_->GetFilter());
376 channel_->AddFilter(geofencing_message_filter_->GetFilter());
377 channel_->AddFilter(bluetooth_message_filter_->GetFilter());
378 channel_->AddFilter(navigator_connect_dispatcher_->GetFilter());
380 if (!IsInBrowserProcess()) {
381 // In single process mode, browser-side tracing will cover the whole
382 // process including renderers.
383 channel_->AddFilter(new tracing::ChildTraceMessageFilter(
384 ChildProcess::current()->io_task_runner()));
387 // In single process mode we may already have a power monitor
388 if (!base::PowerMonitor::Get()) {
389 scoped_ptr<PowerMonitorBroadcastSource> power_monitor_source(
390 new PowerMonitorBroadcastSource());
391 channel_->AddFilter(power_monitor_source->GetMessageFilter());
393 power_monitor_.reset(new base::PowerMonitor(
394 power_monitor_source.Pass()));
397 #if defined(OS_POSIX)
398 // Check that --process-type is specified so we don't do this in unit tests
399 // and single-process mode.
400 if (base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kProcessType))
401 channel_->AddFilter(new SuicideOnChannelErrorFilter());
402 #endif
404 // Add filters passed here via options.
405 for (auto startup_filter : options.startup_filters) {
406 channel_->AddFilter(startup_filter);
409 ConnectChannel(options.use_mojo_channel);
411 int connection_timeout = kConnectionTimeoutS;
412 std::string connection_override =
413 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
414 switches::kIPCConnectionTimeout);
415 if (!connection_override.empty()) {
416 int temp;
417 if (base::StringToInt(connection_override, &temp))
418 connection_timeout = temp;
421 message_loop_->task_runner()->PostDelayedTask(
422 FROM_HERE, base::Bind(&ChildThreadImpl::EnsureConnected,
423 channel_connected_factory_.GetWeakPtr()),
424 base::TimeDelta::FromSeconds(connection_timeout));
426 #if defined(OS_ANDROID)
427 g_quit_closure.Get().BindToMainThread();
428 #endif
430 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
431 trace_memory_controller_.reset(new base::trace_event::TraceMemoryController(
432 message_loop_->task_runner(), ::HeapProfilerWithPseudoStackStart,
433 ::HeapProfilerStop, ::GetHeapProfile));
434 #endif
436 base::trace_event::MemoryDumpManager::GetInstance()->Initialize();
438 shared_bitmap_manager_.reset(
439 new ChildSharedBitmapManager(thread_safe_sender()));
441 gpu_memory_buffer_manager_.reset(
442 new ChildGpuMemoryBufferManager(thread_safe_sender()));
444 discardable_shared_memory_manager_.reset(
445 new ChildDiscardableSharedMemoryManager(thread_safe_sender()));
448 ChildThreadImpl::~ChildThreadImpl() {
449 // ChildDiscardableSharedMemoryManager has to be destroyed while
450 // |thread_safe_sender_| is still valid.
451 discardable_shared_memory_manager_.reset();
453 #ifdef IPC_MESSAGE_LOG_ENABLED
454 IPC::Logging::GetInstance()->SetIPCSender(NULL);
455 #endif
457 channel_->RemoveFilter(histogram_message_filter_.get());
458 channel_->RemoveFilter(sync_message_filter_.get());
460 // The ChannelProxy object caches a pointer to the IPC thread, so need to
461 // reset it as it's not guaranteed to outlive this object.
462 // NOTE: this also has the side-effect of not closing the main IPC channel to
463 // the browser process. This is needed because this is the signal that the
464 // browser uses to know that this process has died, so we need it to be alive
465 // until this process is shut down, and the OS closes the handle
466 // automatically. We used to watch the object handle on Windows to do this,
467 // but it wasn't possible to do so on POSIX.
468 channel_->ClearIPCTaskRunner();
469 g_lazy_tls.Pointer()->Set(NULL);
472 void ChildThreadImpl::Shutdown() {
473 // Delete objects that hold references to blink so derived classes can
474 // safely shutdown blink in their Shutdown implementation.
475 file_system_dispatcher_.reset();
476 quota_dispatcher_.reset();
477 WebFileSystemImpl::DeleteThreadSpecificInstance();
480 void ChildThreadImpl::OnChannelConnected(int32 peer_pid) {
481 channel_connected_factory_.InvalidateWeakPtrs();
484 void ChildThreadImpl::OnChannelError() {
485 set_on_channel_error_called(true);
486 base::MessageLoop::current()->Quit();
489 bool ChildThreadImpl::Send(IPC::Message* msg) {
490 DCHECK(base::MessageLoop::current() == message_loop());
491 if (!channel_) {
492 delete msg;
493 return false;
496 return channel_->Send(msg);
499 #if defined(OS_WIN)
500 void ChildThreadImpl::PreCacheFont(const LOGFONT& log_font) {
501 Send(new ChildProcessHostMsg_PreCacheFont(log_font));
504 void ChildThreadImpl::ReleaseCachedFonts() {
505 Send(new ChildProcessHostMsg_ReleaseCachedFonts());
507 #endif
509 MessageRouter* ChildThreadImpl::GetRouter() {
510 DCHECK(base::MessageLoop::current() == message_loop());
511 return &router_;
514 scoped_ptr<base::SharedMemory> ChildThreadImpl::AllocateSharedMemory(
515 size_t buf_size) {
516 DCHECK(base::MessageLoop::current() == message_loop());
517 return AllocateSharedMemory(buf_size, this);
520 // static
521 scoped_ptr<base::SharedMemory> ChildThreadImpl::AllocateSharedMemory(
522 size_t buf_size,
523 IPC::Sender* sender) {
524 scoped_ptr<base::SharedMemory> shared_buf;
525 #if defined(OS_WIN)
526 shared_buf.reset(new base::SharedMemory);
527 if (!shared_buf->CreateAnonymous(buf_size)) {
528 NOTREACHED();
529 return NULL;
531 #else
532 // On POSIX, we need to ask the browser to create the shared memory for us,
533 // since this is blocked by the sandbox.
534 base::SharedMemoryHandle shared_mem_handle;
535 if (sender->Send(new ChildProcessHostMsg_SyncAllocateSharedMemory(
536 buf_size, &shared_mem_handle))) {
537 if (base::SharedMemory::IsHandleValid(shared_mem_handle)) {
538 shared_buf.reset(new base::SharedMemory(shared_mem_handle, false));
539 } else {
540 NOTREACHED() << "Browser failed to allocate shared memory";
541 return NULL;
543 } else {
544 NOTREACHED() << "Browser allocation request message failed";
545 return NULL;
547 #endif
548 return shared_buf;
551 bool ChildThreadImpl::OnMessageReceived(const IPC::Message& msg) {
552 if (mojo_application_->OnMessageReceived(msg))
553 return true;
555 // Resource responses are sent to the resource dispatcher.
556 if (resource_dispatcher_->OnMessageReceived(msg))
557 return true;
558 if (websocket_dispatcher_->OnMessageReceived(msg))
559 return true;
560 if (file_system_dispatcher_->OnMessageReceived(msg))
561 return true;
563 bool handled = true;
564 IPC_BEGIN_MESSAGE_MAP(ChildThreadImpl, msg)
565 IPC_MESSAGE_HANDLER(ChildProcessMsg_Shutdown, OnShutdown)
566 #if defined(IPC_MESSAGE_LOG_ENABLED)
567 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetIPCLoggingEnabled,
568 OnSetIPCLoggingEnabled)
569 #endif
570 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetProfilerStatus,
571 OnSetProfilerStatus)
572 IPC_MESSAGE_HANDLER(ChildProcessMsg_GetChildProfilerData,
573 OnGetChildProfilerData)
574 IPC_MESSAGE_HANDLER(ChildProcessMsg_ProfilingPhaseCompleted,
575 OnProfilingPhaseCompleted)
576 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetProcessBackgrounded,
577 OnProcessBackgrounded)
578 #if defined(USE_TCMALLOC)
579 IPC_MESSAGE_HANDLER(ChildProcessMsg_GetTcmallocStats, OnGetTcmallocStats)
580 #endif
581 IPC_MESSAGE_UNHANDLED(handled = false)
582 IPC_END_MESSAGE_MAP()
584 if (handled)
585 return true;
587 if (msg.routing_id() == MSG_ROUTING_CONTROL)
588 return OnControlMessageReceived(msg);
590 return router_.OnMessageReceived(msg);
593 bool ChildThreadImpl::OnControlMessageReceived(const IPC::Message& msg) {
594 return false;
597 void ChildThreadImpl::OnShutdown() {
598 base::MessageLoop::current()->Quit();
601 #if defined(IPC_MESSAGE_LOG_ENABLED)
602 void ChildThreadImpl::OnSetIPCLoggingEnabled(bool enable) {
603 if (enable)
604 IPC::Logging::GetInstance()->Enable();
605 else
606 IPC::Logging::GetInstance()->Disable();
608 #endif // IPC_MESSAGE_LOG_ENABLED
610 void ChildThreadImpl::OnSetProfilerStatus(ThreadData::Status status) {
611 ThreadData::InitializeAndSetTrackingStatus(status);
614 void ChildThreadImpl::OnGetChildProfilerData(int sequence_number,
615 int current_profiling_phase) {
616 tracked_objects::ProcessDataSnapshot process_data;
617 ThreadData::Snapshot(current_profiling_phase, &process_data);
619 Send(
620 new ChildProcessHostMsg_ChildProfilerData(sequence_number, process_data));
623 void ChildThreadImpl::OnProfilingPhaseCompleted(int profiling_phase) {
624 ThreadData::OnProfilingPhaseCompleted(profiling_phase);
627 #if defined(USE_TCMALLOC)
628 void ChildThreadImpl::OnGetTcmallocStats() {
629 std::string result;
630 char buffer[1024 * 32];
631 base::allocator::GetStats(buffer, sizeof(buffer));
632 result.append(buffer);
633 Send(new ChildProcessHostMsg_TcmallocStats(result));
635 #endif
637 ChildThreadImpl* ChildThreadImpl::current() {
638 return g_lazy_tls.Pointer()->Get();
641 #if defined(OS_ANDROID)
642 // The method must NOT be called on the child thread itself.
643 // It may block the child thread if so.
644 void ChildThreadImpl::ShutdownThread() {
645 DCHECK(!ChildThreadImpl::current()) <<
646 "this method should NOT be called from child thread itself";
647 g_quit_closure.Get().PostQuitFromNonMainThread();
649 #endif
651 void ChildThreadImpl::OnProcessFinalRelease() {
652 if (on_channel_error_called_) {
653 base::MessageLoop::current()->Quit();
654 return;
657 // The child process shutdown sequence is a request response based mechanism,
658 // where we send out an initial feeler request to the child process host
659 // instance in the browser to verify if it's ok to shutdown the child process.
660 // The browser then sends back a response if it's ok to shutdown. This avoids
661 // race conditions if the process refcount is 0 but there's an IPC message
662 // inflight that would addref it.
663 Send(new ChildProcessHostMsg_ShutdownRequest);
666 void ChildThreadImpl::EnsureConnected() {
667 VLOG(0) << "ChildThreadImpl::EnsureConnected()";
668 base::Process::Current().Terminate(0, false);
671 bool ChildThreadImpl::IsInBrowserProcess() const {
672 return browser_process_io_runner_;
675 void ChildThreadImpl::OnProcessBackgrounded(bool background) {
676 // Set timer slack to maximum on main thread when in background.
677 base::TimerSlack timer_slack = base::TIMER_SLACK_NONE;
678 if (background)
679 timer_slack = base::TIMER_SLACK_MAXIMUM;
680 base::MessageLoop::current()->SetTimerSlack(timer_slack);
683 } // namespace content