Don't add extra app list launcher page webviews.
[chromium-blink-merge.git] / content / child / child_thread_impl.cc
blobeddd157c340cd583109bff0c9746512832f73232
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/lazy_instance.h"
17 #include "base/logging.h"
18 #include "base/message_loop/message_loop.h"
19 #include "base/message_loop/timer_slack.h"
20 #include "base/metrics/field_trial.h"
21 #include "base/process/process.h"
22 #include "base/process/process_handle.h"
23 #include "base/strings/string_number_conversions.h"
24 #include "base/strings/string_util.h"
25 #include "base/synchronization/condition_variable.h"
26 #include "base/synchronization/lock.h"
27 #include "base/threading/thread_local.h"
28 #include "base/tracked_objects.h"
29 #include "components/tracing/child_trace_message_filter.h"
30 #include "content/child/bluetooth/bluetooth_message_filter.h"
31 #include "content/child/child_discardable_shared_memory_manager.h"
32 #include "content/child/child_gpu_memory_buffer_manager.h"
33 #include "content/child/child_histogram_message_filter.h"
34 #include "content/child/child_process.h"
35 #include "content/child/child_resource_message_filter.h"
36 #include "content/child/child_shared_bitmap_manager.h"
37 #include "content/child/fileapi/file_system_dispatcher.h"
38 #include "content/child/fileapi/webfilesystem_impl.h"
39 #include "content/child/geofencing/geofencing_message_filter.h"
40 #include "content/child/mojo/mojo_application.h"
41 #include "content/child/navigator_connect/navigator_connect_dispatcher.h"
42 #include "content/child/notifications/notification_dispatcher.h"
43 #include "content/child/power_monitor_broadcast_source.h"
44 #include "content/child/push_messaging/push_dispatcher.h"
45 #include "content/child/quota_dispatcher.h"
46 #include "content/child/quota_message_filter.h"
47 #include "content/child/resource_dispatcher.h"
48 #include "content/child/service_worker/service_worker_message_filter.h"
49 #include "content/child/thread_safe_sender.h"
50 #include "content/child/websocket_dispatcher.h"
51 #include "content/common/child_process_messages.h"
52 #include "content/common/in_process_child_thread_params.h"
53 #include "content/public/common/content_switches.h"
54 #include "ipc/ipc_logging.h"
55 #include "ipc/ipc_switches.h"
56 #include "ipc/ipc_sync_channel.h"
57 #include "ipc/ipc_sync_message_filter.h"
58 #include "ipc/mojo/ipc_channel_mojo.h"
60 #if defined(OS_WIN)
61 #include "content/common/handle_enumerator_win.h"
62 #endif
64 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
65 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
66 #endif
68 using tracked_objects::ThreadData;
70 namespace content {
71 namespace {
73 // How long to wait for a connection to the browser process before giving up.
74 const int kConnectionTimeoutS = 15;
76 base::LazyInstance<base::ThreadLocalPointer<ChildThreadImpl> > g_lazy_tls =
77 LAZY_INSTANCE_INITIALIZER;
79 // This isn't needed on Windows because there the sandbox's job object
80 // terminates child processes automatically. For unsandboxed processes (i.e.
81 // plugins), PluginThread has EnsureTerminateMessageFilter.
82 #if defined(OS_POSIX)
84 #if defined(ADDRESS_SANITIZER) || defined(LEAK_SANITIZER) || \
85 defined(MEMORY_SANITIZER) || defined(THREAD_SANITIZER) || \
86 defined(UNDEFINED_SANITIZER)
87 // A thread delegate that waits for |duration| and then exits the process with
88 // _exit(0).
89 class WaitAndExitDelegate : public base::PlatformThread::Delegate {
90 public:
91 explicit WaitAndExitDelegate(base::TimeDelta duration)
92 : duration_(duration) {}
94 void ThreadMain() override {
95 base::PlatformThread::Sleep(duration_);
96 _exit(0);
99 private:
100 const base::TimeDelta duration_;
101 DISALLOW_COPY_AND_ASSIGN(WaitAndExitDelegate);
104 bool CreateWaitAndExitThread(base::TimeDelta duration) {
105 scoped_ptr<WaitAndExitDelegate> delegate(new WaitAndExitDelegate(duration));
107 const bool thread_created =
108 base::PlatformThread::CreateNonJoinable(0, delegate.get());
109 if (!thread_created)
110 return false;
112 // A non joinable thread has been created. The thread will either terminate
113 // the process or will be terminated by the process. Therefore, keep the
114 // delegate object alive for the lifetime of the process.
115 WaitAndExitDelegate* leaking_delegate = delegate.release();
116 ANNOTATE_LEAKING_OBJECT_PTR(leaking_delegate);
117 ignore_result(leaking_delegate);
118 return true;
120 #endif
122 class SuicideOnChannelErrorFilter : public IPC::MessageFilter {
123 public:
124 // IPC::MessageFilter
125 void OnChannelError() override {
126 // For renderer/worker processes:
127 // On POSIX, at least, one can install an unload handler which loops
128 // forever and leave behind a renderer process which eats 100% CPU forever.
130 // This is because the terminate signals (ViewMsg_ShouldClose and the error
131 // from the IPC sender) are routed to the main message loop but never
132 // processed (because that message loop is stuck in V8).
134 // One could make the browser SIGKILL the renderers, but that leaves open a
135 // large window where a browser failure (or a user, manually terminating
136 // the browser because "it's stuck") will leave behind a process eating all
137 // the CPU.
139 // So, we install a filter on the sender so that we can process this event
140 // here and kill the process.
141 #if defined(ADDRESS_SANITIZER) || defined(LEAK_SANITIZER) || \
142 defined(MEMORY_SANITIZER) || defined(THREAD_SANITIZER) || \
143 defined(UNDEFINED_SANITIZER)
144 // Some sanitizer tools rely on exit handlers (e.g. to run leak detection,
145 // or dump code coverage data to disk). Instead of exiting the process
146 // immediately, we give it 60 seconds to run exit handlers.
147 CHECK(CreateWaitAndExitThread(base::TimeDelta::FromSeconds(60)));
148 #if defined(LEAK_SANITIZER)
149 // Invoke LeakSanitizer early to avoid detecting shutdown-only leaks. If
150 // leaks are found, the process will exit here.
151 __lsan_do_leak_check();
152 #endif
153 #else
154 _exit(0);
155 #endif
158 protected:
159 ~SuicideOnChannelErrorFilter() override {}
162 #endif // OS(POSIX)
164 #if defined(OS_ANDROID)
165 ChildThreadImpl* g_child_thread = NULL;
166 bool g_child_thread_initialized = false;
168 // A lock protects g_child_thread.
169 base::LazyInstance<base::Lock>::Leaky g_lazy_child_thread_lock =
170 LAZY_INSTANCE_INITIALIZER;
172 // base::ConditionVariable has an explicit constructor that takes
173 // a base::Lock pointer as parameter. The base::DefaultLazyInstanceTraits
174 // doesn't handle the case. Thus, we need our own class here.
175 struct CondVarLazyInstanceTraits {
176 static const bool kRegisterOnExit = false;
177 #ifndef NDEBUG
178 static const bool kAllowedToAccessOnNonjoinableThread = true;
179 #endif
181 static base::ConditionVariable* New(void* instance) {
182 return new (instance) base::ConditionVariable(
183 g_lazy_child_thread_lock.Pointer());
185 static void Delete(base::ConditionVariable* instance) {
186 instance->~ConditionVariable();
190 // A condition variable that synchronize threads initializing and waiting
191 // for g_child_thread.
192 base::LazyInstance<base::ConditionVariable, CondVarLazyInstanceTraits>
193 g_lazy_child_thread_cv = LAZY_INSTANCE_INITIALIZER;
195 void QuitMainThreadMessageLoop() {
196 base::MessageLoop::current()->Quit();
199 #endif
201 } // namespace
203 ChildThread* ChildThread::Get() {
204 return ChildThreadImpl::current();
207 ChildThreadImpl::Options::Options()
208 : channel_name(base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
209 switches::kProcessChannelID)),
210 use_mojo_channel(false) {
213 ChildThreadImpl::Options::~Options() {
216 ChildThreadImpl::Options::Builder::Builder() {
219 ChildThreadImpl::Options::Builder&
220 ChildThreadImpl::Options::Builder::InBrowserProcess(
221 const InProcessChildThreadParams& params) {
222 options_.browser_process_io_runner = params.io_runner();
223 options_.channel_name = params.channel_name();
224 return *this;
227 ChildThreadImpl::Options::Builder&
228 ChildThreadImpl::Options::Builder::UseMojoChannel(bool use_mojo_channel) {
229 options_.use_mojo_channel = use_mojo_channel;
230 return *this;
233 ChildThreadImpl::Options::Builder&
234 ChildThreadImpl::Options::Builder::WithChannelName(
235 const std::string& channel_name) {
236 options_.channel_name = channel_name;
237 return *this;
240 ChildThreadImpl::Options::Builder&
241 ChildThreadImpl::Options::Builder::AddStartupFilter(
242 IPC::MessageFilter* filter) {
243 options_.startup_filters.push_back(filter);
244 return *this;
247 ChildThreadImpl::Options ChildThreadImpl::Options::Builder::Build() {
248 return options_;
251 ChildThreadImpl::ChildThreadMessageRouter::ChildThreadMessageRouter(
252 IPC::Sender* sender)
253 : sender_(sender) {}
255 bool ChildThreadImpl::ChildThreadMessageRouter::Send(IPC::Message* msg) {
256 return sender_->Send(msg);
259 ChildThreadImpl::ChildThreadImpl()
260 : router_(this),
261 channel_connected_factory_(this) {
262 Init(Options::Builder().Build());
265 ChildThreadImpl::ChildThreadImpl(const Options& options)
266 : router_(this),
267 browser_process_io_runner_(options.browser_process_io_runner),
268 channel_connected_factory_(this) {
269 Init(options);
272 scoped_refptr<base::SequencedTaskRunner> ChildThreadImpl::GetIOTaskRunner() {
273 if (IsInBrowserProcess())
274 return browser_process_io_runner_;
275 return ChildProcess::current()->io_message_loop_proxy();
278 void ChildThreadImpl::ConnectChannel(bool use_mojo_channel) {
279 bool create_pipe_now = true;
280 if (use_mojo_channel) {
281 VLOG(1) << "Mojo is enabled on child";
282 scoped_refptr<base::SequencedTaskRunner> io_task_runner = GetIOTaskRunner();
283 DCHECK(io_task_runner);
284 channel_->Init(IPC::ChannelMojo::CreateClientFactory(
285 nullptr, io_task_runner, channel_name_),
286 create_pipe_now);
287 return;
290 VLOG(1) << "Mojo is disabled on child";
291 channel_->Init(channel_name_, IPC::Channel::MODE_CLIENT, create_pipe_now);
294 void ChildThreadImpl::Init(const Options& options) {
295 channel_name_ = options.channel_name;
297 g_lazy_tls.Pointer()->Set(this);
298 on_channel_error_called_ = false;
299 message_loop_ = base::MessageLoop::current();
300 #ifdef IPC_MESSAGE_LOG_ENABLED
301 // We must make sure to instantiate the IPC Logger *before* we create the
302 // channel, otherwise we can get a callback on the IO thread which creates
303 // the logger, and the logger does not like being created on the IO thread.
304 IPC::Logging::GetInstance();
305 #endif
306 channel_ = IPC::SyncChannel::Create(
307 this, ChildProcess::current()->io_message_loop_proxy(),
308 ChildProcess::current()->GetShutDownEvent());
309 #ifdef IPC_MESSAGE_LOG_ENABLED
310 if (!IsInBrowserProcess())
311 IPC::Logging::GetInstance()->SetIPCSender(this);
312 #endif
314 mojo_application_.reset(new MojoApplication(GetIOTaskRunner()));
316 sync_message_filter_ =
317 new IPC::SyncMessageFilter(ChildProcess::current()->GetShutDownEvent());
318 thread_safe_sender_ = new ThreadSafeSender(
319 base::MessageLoopProxy::current().get(), sync_message_filter_.get());
321 resource_dispatcher_.reset(new ResourceDispatcher(
322 this, message_loop()->task_runner()));
323 websocket_dispatcher_.reset(new WebSocketDispatcher);
324 file_system_dispatcher_.reset(new FileSystemDispatcher());
326 histogram_message_filter_ = new ChildHistogramMessageFilter();
327 resource_message_filter_ =
328 new ChildResourceMessageFilter(resource_dispatcher());
330 service_worker_message_filter_ =
331 new ServiceWorkerMessageFilter(thread_safe_sender_.get());
333 quota_message_filter_ =
334 new QuotaMessageFilter(thread_safe_sender_.get());
335 quota_dispatcher_.reset(new QuotaDispatcher(thread_safe_sender_.get(),
336 quota_message_filter_.get()));
337 geofencing_message_filter_ =
338 new GeofencingMessageFilter(thread_safe_sender_.get());
339 bluetooth_message_filter_ =
340 new BluetoothMessageFilter(thread_safe_sender_.get());
341 notification_dispatcher_ =
342 new NotificationDispatcher(thread_safe_sender_.get());
343 push_dispatcher_ = new PushDispatcher(thread_safe_sender_.get());
344 navigator_connect_dispatcher_ =
345 new NavigatorConnectDispatcher(thread_safe_sender_.get());
347 channel_->AddFilter(histogram_message_filter_.get());
348 channel_->AddFilter(sync_message_filter_.get());
349 channel_->AddFilter(resource_message_filter_.get());
350 channel_->AddFilter(quota_message_filter_->GetFilter());
351 channel_->AddFilter(notification_dispatcher_->GetFilter());
352 channel_->AddFilter(push_dispatcher_->GetFilter());
353 channel_->AddFilter(service_worker_message_filter_->GetFilter());
354 channel_->AddFilter(geofencing_message_filter_->GetFilter());
355 channel_->AddFilter(bluetooth_message_filter_->GetFilter());
356 channel_->AddFilter(navigator_connect_dispatcher_->GetFilter());
358 if (!IsInBrowserProcess()) {
359 // In single process mode, browser-side tracing will cover the whole
360 // process including renderers.
361 channel_->AddFilter(new tracing::ChildTraceMessageFilter(
362 ChildProcess::current()->io_message_loop_proxy()));
365 // In single process mode we may already have a power monitor
366 if (!base::PowerMonitor::Get()) {
367 scoped_ptr<PowerMonitorBroadcastSource> power_monitor_source(
368 new PowerMonitorBroadcastSource());
369 channel_->AddFilter(power_monitor_source->GetMessageFilter());
371 power_monitor_.reset(new base::PowerMonitor(
372 power_monitor_source.Pass()));
375 #if defined(OS_POSIX)
376 // Check that --process-type is specified so we don't do this in unit tests
377 // and single-process mode.
378 if (base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kProcessType))
379 channel_->AddFilter(new SuicideOnChannelErrorFilter());
380 #endif
382 // Add filters passed here via options.
383 for (auto startup_filter : options.startup_filters) {
384 channel_->AddFilter(startup_filter);
387 ConnectChannel(options.use_mojo_channel);
389 int connection_timeout = kConnectionTimeoutS;
390 std::string connection_override =
391 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
392 switches::kIPCConnectionTimeout);
393 if (!connection_override.empty()) {
394 int temp;
395 if (base::StringToInt(connection_override, &temp))
396 connection_timeout = temp;
399 base::MessageLoop::current()->PostDelayedTask(
400 FROM_HERE,
401 base::Bind(&ChildThreadImpl::EnsureConnected,
402 channel_connected_factory_.GetWeakPtr()),
403 base::TimeDelta::FromSeconds(connection_timeout));
405 #if defined(OS_ANDROID)
407 base::AutoLock lock(g_lazy_child_thread_lock.Get());
408 g_child_thread = this;
409 g_child_thread_initialized = true;
411 // Signalling without locking is fine here because only
412 // one thread can wait on the condition variable.
413 g_lazy_child_thread_cv.Get().Signal();
414 #endif
416 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
417 trace_memory_controller_.reset(new base::trace_event::TraceMemoryController(
418 message_loop_->message_loop_proxy(), ::HeapProfilerWithPseudoStackStart,
419 ::HeapProfilerStop, ::GetHeapProfile));
420 #endif
422 shared_bitmap_manager_.reset(
423 new ChildSharedBitmapManager(thread_safe_sender()));
425 gpu_memory_buffer_manager_.reset(
426 new ChildGpuMemoryBufferManager(thread_safe_sender()));
428 discardable_shared_memory_manager_.reset(
429 new ChildDiscardableSharedMemoryManager(thread_safe_sender()));
432 ChildThreadImpl::~ChildThreadImpl() {
433 // ChildDiscardableSharedMemoryManager has to be destroyed while
434 // |thread_safe_sender_| is still valid.
435 discardable_shared_memory_manager_.reset();
437 #if defined(OS_ANDROID)
439 base::AutoLock lock(g_lazy_child_thread_lock.Get());
440 g_child_thread = nullptr;
442 #endif
444 #ifdef IPC_MESSAGE_LOG_ENABLED
445 IPC::Logging::GetInstance()->SetIPCSender(NULL);
446 #endif
448 channel_->RemoveFilter(histogram_message_filter_.get());
449 channel_->RemoveFilter(sync_message_filter_.get());
451 // The ChannelProxy object caches a pointer to the IPC thread, so need to
452 // reset it as it's not guaranteed to outlive this object.
453 // NOTE: this also has the side-effect of not closing the main IPC channel to
454 // the browser process. This is needed because this is the signal that the
455 // browser uses to know that this process has died, so we need it to be alive
456 // until this process is shut down, and the OS closes the handle
457 // automatically. We used to watch the object handle on Windows to do this,
458 // but it wasn't possible to do so on POSIX.
459 channel_->ClearIPCTaskRunner();
460 g_lazy_tls.Pointer()->Set(NULL);
463 void ChildThreadImpl::Shutdown() {
464 // Delete objects that hold references to blink so derived classes can
465 // safely shutdown blink in their Shutdown implementation.
466 file_system_dispatcher_.reset();
467 quota_dispatcher_.reset();
468 WebFileSystemImpl::DeleteThreadSpecificInstance();
471 void ChildThreadImpl::OnChannelConnected(int32 peer_pid) {
472 channel_connected_factory_.InvalidateWeakPtrs();
475 void ChildThreadImpl::OnChannelError() {
476 set_on_channel_error_called(true);
477 base::MessageLoop::current()->Quit();
480 bool ChildThreadImpl::Send(IPC::Message* msg) {
481 DCHECK(base::MessageLoop::current() == message_loop());
482 if (!channel_) {
483 delete msg;
484 return false;
487 return channel_->Send(msg);
490 #if defined(OS_WIN)
491 void ChildThreadImpl::PreCacheFont(const LOGFONT& log_font) {
492 Send(new ChildProcessHostMsg_PreCacheFont(log_font));
495 void ChildThreadImpl::ReleaseCachedFonts() {
496 Send(new ChildProcessHostMsg_ReleaseCachedFonts());
498 #endif
500 MessageRouter* ChildThreadImpl::GetRouter() {
501 DCHECK(base::MessageLoop::current() == message_loop());
502 return &router_;
505 scoped_ptr<base::SharedMemory> ChildThreadImpl::AllocateSharedMemory(
506 size_t buf_size) {
507 DCHECK(base::MessageLoop::current() == message_loop());
508 return AllocateSharedMemory(buf_size, this);
511 // static
512 scoped_ptr<base::SharedMemory> ChildThreadImpl::AllocateSharedMemory(
513 size_t buf_size,
514 IPC::Sender* sender) {
515 scoped_ptr<base::SharedMemory> shared_buf;
516 #if defined(OS_WIN)
517 shared_buf.reset(new base::SharedMemory);
518 if (!shared_buf->CreateAnonymous(buf_size)) {
519 NOTREACHED();
520 return NULL;
522 #else
523 // On POSIX, we need to ask the browser to create the shared memory for us,
524 // since this is blocked by the sandbox.
525 base::SharedMemoryHandle shared_mem_handle;
526 if (sender->Send(new ChildProcessHostMsg_SyncAllocateSharedMemory(
527 buf_size, &shared_mem_handle))) {
528 if (base::SharedMemory::IsHandleValid(shared_mem_handle)) {
529 shared_buf.reset(new base::SharedMemory(shared_mem_handle, false));
530 } else {
531 NOTREACHED() << "Browser failed to allocate shared memory";
532 return NULL;
534 } else {
535 NOTREACHED() << "Browser allocation request message failed";
536 return NULL;
538 #endif
539 return shared_buf;
542 bool ChildThreadImpl::OnMessageReceived(const IPC::Message& msg) {
543 if (mojo_application_->OnMessageReceived(msg))
544 return true;
546 // Resource responses are sent to the resource dispatcher.
547 if (resource_dispatcher_->OnMessageReceived(msg))
548 return true;
549 if (websocket_dispatcher_->OnMessageReceived(msg))
550 return true;
551 if (file_system_dispatcher_->OnMessageReceived(msg))
552 return true;
554 bool handled = true;
555 IPC_BEGIN_MESSAGE_MAP(ChildThreadImpl, msg)
556 IPC_MESSAGE_HANDLER(ChildProcessMsg_Shutdown, OnShutdown)
557 #if defined(IPC_MESSAGE_LOG_ENABLED)
558 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetIPCLoggingEnabled,
559 OnSetIPCLoggingEnabled)
560 #endif
561 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetProfilerStatus,
562 OnSetProfilerStatus)
563 IPC_MESSAGE_HANDLER(ChildProcessMsg_GetChildProfilerData,
564 OnGetChildProfilerData)
565 IPC_MESSAGE_HANDLER(ChildProcessMsg_DumpHandles, OnDumpHandles)
566 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetProcessBackgrounded,
567 OnProcessBackgrounded)
568 #if defined(USE_TCMALLOC)
569 IPC_MESSAGE_HANDLER(ChildProcessMsg_GetTcmallocStats, OnGetTcmallocStats)
570 #endif
571 IPC_MESSAGE_UNHANDLED(handled = false)
572 IPC_END_MESSAGE_MAP()
574 if (handled)
575 return true;
577 if (msg.routing_id() == MSG_ROUTING_CONTROL)
578 return OnControlMessageReceived(msg);
580 return router_.OnMessageReceived(msg);
583 bool ChildThreadImpl::OnControlMessageReceived(const IPC::Message& msg) {
584 return false;
587 void ChildThreadImpl::OnShutdown() {
588 base::MessageLoop::current()->Quit();
591 #if defined(IPC_MESSAGE_LOG_ENABLED)
592 void ChildThreadImpl::OnSetIPCLoggingEnabled(bool enable) {
593 if (enable)
594 IPC::Logging::GetInstance()->Enable();
595 else
596 IPC::Logging::GetInstance()->Disable();
598 #endif // IPC_MESSAGE_LOG_ENABLED
600 void ChildThreadImpl::OnSetProfilerStatus(ThreadData::Status status) {
601 ThreadData::InitializeAndSetTrackingStatus(status);
604 void ChildThreadImpl::OnGetChildProfilerData(int sequence_number) {
605 tracked_objects::ProcessDataSnapshot process_data;
606 ThreadData::Snapshot(&process_data);
608 Send(
609 new ChildProcessHostMsg_ChildProfilerData(sequence_number, process_data));
612 void ChildThreadImpl::OnDumpHandles() {
613 #if defined(OS_WIN)
614 scoped_refptr<HandleEnumerator> handle_enum(
615 new HandleEnumerator(
616 base::CommandLine::ForCurrentProcess()->HasSwitch(
617 switches::kAuditAllHandles)));
618 handle_enum->EnumerateHandles();
619 Send(new ChildProcessHostMsg_DumpHandlesDone);
620 #else
621 NOTIMPLEMENTED();
622 #endif
625 #if defined(USE_TCMALLOC)
626 void ChildThreadImpl::OnGetTcmallocStats() {
627 std::string result;
628 char buffer[1024 * 32];
629 base::allocator::GetStats(buffer, sizeof(buffer));
630 result.append(buffer);
631 Send(new ChildProcessHostMsg_TcmallocStats(result));
633 #endif
635 ChildThreadImpl* ChildThreadImpl::current() {
636 return g_lazy_tls.Pointer()->Get();
639 #if defined(OS_ANDROID)
640 // The method must NOT be called on the child thread itself.
641 // It may block the child thread if so.
642 void ChildThreadImpl::ShutdownThread() {
643 DCHECK(!ChildThreadImpl::current()) <<
644 "this method should NOT be called from child thread itself";
646 base::AutoLock lock(g_lazy_child_thread_lock.Get());
647 while (!g_child_thread_initialized)
648 g_lazy_child_thread_cv.Get().Wait();
650 // g_child_thread may already have been destructed while we didn't hold the
651 // lock.
652 if (!g_child_thread)
653 return;
655 DCHECK_NE(base::MessageLoop::current(), g_child_thread->message_loop());
656 g_child_thread->message_loop()->PostTask(
657 FROM_HERE, base::Bind(&QuitMainThreadMessageLoop));
660 #endif
662 void ChildThreadImpl::OnProcessFinalRelease() {
663 if (on_channel_error_called_) {
664 base::MessageLoop::current()->Quit();
665 return;
668 // The child process shutdown sequence is a request response based mechanism,
669 // where we send out an initial feeler request to the child process host
670 // instance in the browser to verify if it's ok to shutdown the child process.
671 // The browser then sends back a response if it's ok to shutdown. This avoids
672 // race conditions if the process refcount is 0 but there's an IPC message
673 // inflight that would addref it.
674 Send(new ChildProcessHostMsg_ShutdownRequest);
677 void ChildThreadImpl::EnsureConnected() {
678 VLOG(0) << "ChildThreadImpl::EnsureConnected()";
679 base::Process::Current().Terminate(0, false);
682 bool ChildThreadImpl::IsInBrowserProcess() const {
683 return browser_process_io_runner_;
686 void ChildThreadImpl::OnProcessBackgrounded(bool background) {
687 // Set timer slack to maximum on main thread when in background.
688 base::TimerSlack timer_slack = base::TIMER_SLACK_NONE;
689 if (background)
690 timer_slack = base::TIMER_SLACK_MAXIMUM;
691 base::MessageLoop::current()->SetTimerSlack(timer_slack);
693 #ifdef OS_WIN
694 // Windows Vista+ has a fancy process backgrounding mode that can only be set
695 // from within the process. This used to be how chrome set its renderers into
696 // background mode on Windows but was removed due to http://crbug.com/398103.
697 // As we experiment with bringing back some other form of background mode for
698 // hidden renderers, add a bucket to allow us to trigger this undesired method
699 // of setting background state in order to confirm that the metrics which were
700 // added to prevent regressions on the aforementioned issue indeed catch such
701 // regressions and are thus a reliable way to confirm that our latest proposal
702 // doesn't cause such issues. TODO(gab): Remove this once the experiment is
703 // over (http://crbug.com/458594).
704 base::FieldTrial* trial =
705 base::FieldTrialList::Find("BackgroundRendererProcesses");
706 if (trial && trial->group_name() == "AllowBackgroundModeFromRenderer")
707 base::Process::Current().SetProcessBackgrounded(background);
708 #endif // OS_WIN
711 } // namespace content