ozone: evdev: Sync caps lock LED state to evdev
[chromium-blink-merge.git] / content / child / child_thread_impl.cc
blob8acc37dfcf806a277fdd39804538e4615180a561
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/kill.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/mojo/channel_init.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"
59 #include "ipc/mojo/scoped_ipc_support.h"
61 #if defined(OS_WIN)
62 #include "content/common/handle_enumerator_win.h"
63 #endif
65 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
66 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
67 #endif
69 using tracked_objects::ThreadData;
71 namespace content {
72 namespace {
74 // How long to wait for a connection to the browser process before giving up.
75 const int kConnectionTimeoutS = 15;
77 base::LazyInstance<base::ThreadLocalPointer<ChildThreadImpl> > g_lazy_tls =
78 LAZY_INSTANCE_INITIALIZER;
80 // This isn't needed on Windows because there the sandbox's job object
81 // terminates child processes automatically. For unsandboxed processes (i.e.
82 // plugins), PluginThread has EnsureTerminateMessageFilter.
83 #if defined(OS_POSIX)
85 #if defined(ADDRESS_SANITIZER) || defined(LEAK_SANITIZER) || \
86 defined(MEMORY_SANITIZER) || defined(THREAD_SANITIZER) || \
87 defined(UNDEFINED_SANITIZER)
88 // A thread delegate that waits for |duration| and then exits the process with
89 // _exit(0).
90 class WaitAndExitDelegate : public base::PlatformThread::Delegate {
91 public:
92 explicit WaitAndExitDelegate(base::TimeDelta duration)
93 : duration_(duration) {}
95 void ThreadMain() override {
96 base::PlatformThread::Sleep(duration_);
97 _exit(0);
100 private:
101 const base::TimeDelta duration_;
102 DISALLOW_COPY_AND_ASSIGN(WaitAndExitDelegate);
105 bool CreateWaitAndExitThread(base::TimeDelta duration) {
106 scoped_ptr<WaitAndExitDelegate> delegate(new WaitAndExitDelegate(duration));
108 const bool thread_created =
109 base::PlatformThread::CreateNonJoinable(0, delegate.get());
110 if (!thread_created)
111 return false;
113 // A non joinable thread has been created. The thread will either terminate
114 // the process or will be terminated by the process. Therefore, keep the
115 // delegate object alive for the lifetime of the process.
116 WaitAndExitDelegate* leaking_delegate = delegate.release();
117 ANNOTATE_LEAKING_OBJECT_PTR(leaking_delegate);
118 ignore_result(leaking_delegate);
119 return true;
121 #endif
123 class SuicideOnChannelErrorFilter : public IPC::MessageFilter {
124 public:
125 // IPC::MessageFilter
126 void OnChannelError() override {
127 // For renderer/worker processes:
128 // On POSIX, at least, one can install an unload handler which loops
129 // forever and leave behind a renderer process which eats 100% CPU forever.
131 // This is because the terminate signals (ViewMsg_ShouldClose and the error
132 // from the IPC sender) are routed to the main message loop but never
133 // processed (because that message loop is stuck in V8).
135 // One could make the browser SIGKILL the renderers, but that leaves open a
136 // large window where a browser failure (or a user, manually terminating
137 // the browser because "it's stuck") will leave behind a process eating all
138 // the CPU.
140 // So, we install a filter on the sender so that we can process this event
141 // here and kill the process.
142 #if defined(ADDRESS_SANITIZER) || defined(LEAK_SANITIZER) || \
143 defined(MEMORY_SANITIZER) || defined(THREAD_SANITIZER) || \
144 defined(UNDEFINED_SANITIZER)
145 // Some sanitizer tools rely on exit handlers (e.g. to run leak detection,
146 // or dump code coverage data to disk). Instead of exiting the process
147 // immediately, we give it 60 seconds to run exit handlers.
148 CHECK(CreateWaitAndExitThread(base::TimeDelta::FromSeconds(60)));
149 #if defined(LEAK_SANITIZER)
150 // Invoke LeakSanitizer early to avoid detecting shutdown-only leaks. If
151 // leaks are found, the process will exit here.
152 __lsan_do_leak_check();
153 #endif
154 #else
155 _exit(0);
156 #endif
159 protected:
160 ~SuicideOnChannelErrorFilter() override {}
163 #endif // OS(POSIX)
165 #if defined(OS_ANDROID)
166 ChildThreadImpl* g_child_thread = NULL;
167 bool g_child_thread_initialized = false;
169 // A lock protects g_child_thread.
170 base::LazyInstance<base::Lock>::Leaky g_lazy_child_thread_lock =
171 LAZY_INSTANCE_INITIALIZER;
173 // base::ConditionVariable has an explicit constructor that takes
174 // a base::Lock pointer as parameter. The base::DefaultLazyInstanceTraits
175 // doesn't handle the case. Thus, we need our own class here.
176 struct CondVarLazyInstanceTraits {
177 static const bool kRegisterOnExit = false;
178 #ifndef NDEBUG
179 static const bool kAllowedToAccessOnNonjoinableThread = true;
180 #endif
182 static base::ConditionVariable* New(void* instance) {
183 return new (instance) base::ConditionVariable(
184 g_lazy_child_thread_lock.Pointer());
186 static void Delete(base::ConditionVariable* instance) {
187 instance->~ConditionVariable();
191 // A condition variable that synchronize threads initializing and waiting
192 // for g_child_thread.
193 base::LazyInstance<base::ConditionVariable, CondVarLazyInstanceTraits>
194 g_lazy_child_thread_cv = LAZY_INSTANCE_INITIALIZER;
196 void QuitMainThreadMessageLoop() {
197 base::MessageLoop::current()->Quit();
200 #endif
202 } // namespace
204 ChildThread* ChildThread::Get() {
205 return ChildThreadImpl::current();
208 // Mojo client channel delegate to be used in single process mode.
209 class ChildThreadImpl::SingleProcessChannelDelegate
210 : public IPC::ChannelMojo::Delegate {
211 public:
212 explicit SingleProcessChannelDelegate() : weak_factory_(this) {}
214 ~SingleProcessChannelDelegate() override {}
216 base::WeakPtr<IPC::ChannelMojo::Delegate> ToWeakPtr() override {
217 return weak_factory_.GetWeakPtr();
220 scoped_refptr<base::TaskRunner> GetIOTaskRunner() override {
221 return ChannelInit::GetSingleProcessIOTaskRunner();
224 void OnChannelCreated(base::WeakPtr<IPC::ChannelMojo> channel) override {}
226 void DeleteSoon() {
227 ChannelInit::GetSingleProcessIOTaskRunner()->PostTask(
228 FROM_HERE,
229 base::Bind(&base::DeletePointer<SingleProcessChannelDelegate>,
230 base::Unretained(this)));
233 private:
234 base::WeakPtrFactory<IPC::ChannelMojo::Delegate> weak_factory_;
236 DISALLOW_COPY_AND_ASSIGN(SingleProcessChannelDelegate);
239 void ChildThreadImpl::SingleProcessChannelDelegateDeleter::operator()(
240 SingleProcessChannelDelegate* delegate) const {
241 delegate->DeleteSoon();
244 ChildThreadImpl::Options::Options()
245 : channel_name(base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
246 switches::kProcessChannelID)),
247 use_mojo_channel(false),
248 in_browser_process(false) {
251 ChildThreadImpl::Options::Options(bool mojo)
252 : channel_name(base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
253 switches::kProcessChannelID)),
254 use_mojo_channel(mojo),
255 in_browser_process(true) {
258 ChildThreadImpl::Options::Options(std::string name, bool mojo)
259 : channel_name(name), use_mojo_channel(mojo), in_browser_process(true) {
262 ChildThreadImpl::Options::~Options() {
265 ChildThreadImpl::ChildThreadMessageRouter::ChildThreadMessageRouter(
266 IPC::Sender* sender)
267 : sender_(sender) {}
269 bool ChildThreadImpl::ChildThreadMessageRouter::Send(IPC::Message* msg) {
270 return sender_->Send(msg);
273 ChildThreadImpl::ChildThreadImpl()
274 : router_(this),
275 in_browser_process_(false),
276 channel_connected_factory_(this) {
277 Init(Options());
280 ChildThreadImpl::ChildThreadImpl(const Options& options)
281 : router_(this),
282 in_browser_process_(options.in_browser_process),
283 channel_connected_factory_(this) {
284 Init(options);
287 void ChildThreadImpl::ConnectChannel(bool use_mojo_channel) {
288 bool create_pipe_now = true;
289 if (use_mojo_channel) {
290 VLOG(1) << "Mojo is enabled on child";
291 scoped_refptr<base::TaskRunner> io_task_runner =
292 ChannelInit::GetSingleProcessIOTaskRunner();
293 if (io_task_runner) {
294 single_process_channel_delegate_.reset(new SingleProcessChannelDelegate);
295 } else {
296 io_task_runner = ChildProcess::current()->io_message_loop_proxy();
298 DCHECK(io_task_runner);
299 ipc_support_.reset(new IPC::ScopedIPCSupport(io_task_runner));
300 channel_->Init(
301 IPC::ChannelMojo::CreateClientFactory(
302 single_process_channel_delegate_.get(),
303 channel_name_),
304 create_pipe_now);
305 return;
308 VLOG(1) << "Mojo is disabled on child";
309 channel_->Init(channel_name_, IPC::Channel::MODE_CLIENT, create_pipe_now);
312 void ChildThreadImpl::Init(const Options& options) {
313 channel_name_ = options.channel_name;
315 g_lazy_tls.Pointer()->Set(this);
316 on_channel_error_called_ = false;
317 message_loop_ = base::MessageLoop::current();
318 #ifdef IPC_MESSAGE_LOG_ENABLED
319 // We must make sure to instantiate the IPC Logger *before* we create the
320 // channel, otherwise we can get a callback on the IO thread which creates
321 // the logger, and the logger does not like being created on the IO thread.
322 IPC::Logging::GetInstance();
323 #endif
324 channel_ = IPC::SyncChannel::Create(
325 this, ChildProcess::current()->io_message_loop_proxy(),
326 ChildProcess::current()->GetShutDownEvent());
327 #ifdef IPC_MESSAGE_LOG_ENABLED
328 if (!in_browser_process_)
329 IPC::Logging::GetInstance()->SetIPCSender(this);
330 #endif
332 mojo_application_.reset(new MojoApplication);
334 sync_message_filter_ =
335 new IPC::SyncMessageFilter(ChildProcess::current()->GetShutDownEvent());
336 thread_safe_sender_ = new ThreadSafeSender(
337 base::MessageLoopProxy::current().get(), sync_message_filter_.get());
339 resource_dispatcher_.reset(new ResourceDispatcher(
340 this, message_loop()->task_runner()));
341 websocket_dispatcher_.reset(new WebSocketDispatcher);
342 file_system_dispatcher_.reset(new FileSystemDispatcher());
344 histogram_message_filter_ = new ChildHistogramMessageFilter();
345 resource_message_filter_ =
346 new ChildResourceMessageFilter(resource_dispatcher());
348 service_worker_message_filter_ =
349 new ServiceWorkerMessageFilter(thread_safe_sender_.get());
351 quota_message_filter_ =
352 new QuotaMessageFilter(thread_safe_sender_.get());
353 quota_dispatcher_.reset(new QuotaDispatcher(thread_safe_sender_.get(),
354 quota_message_filter_.get()));
355 geofencing_message_filter_ =
356 new GeofencingMessageFilter(thread_safe_sender_.get());
357 bluetooth_message_filter_ =
358 new BluetoothMessageFilter(thread_safe_sender_.get());
359 notification_dispatcher_ =
360 new NotificationDispatcher(thread_safe_sender_.get());
361 push_dispatcher_ = new PushDispatcher(thread_safe_sender_.get());
362 navigator_connect_dispatcher_ =
363 new NavigatorConnectDispatcher(thread_safe_sender_.get());
365 channel_->AddFilter(histogram_message_filter_.get());
366 channel_->AddFilter(sync_message_filter_.get());
367 channel_->AddFilter(resource_message_filter_.get());
368 channel_->AddFilter(quota_message_filter_->GetFilter());
369 channel_->AddFilter(notification_dispatcher_->GetFilter());
370 channel_->AddFilter(push_dispatcher_->GetFilter());
371 channel_->AddFilter(service_worker_message_filter_->GetFilter());
372 channel_->AddFilter(geofencing_message_filter_->GetFilter());
373 channel_->AddFilter(bluetooth_message_filter_->GetFilter());
374 channel_->AddFilter(navigator_connect_dispatcher_->GetFilter());
376 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
377 switches::kSingleProcess)) {
378 // In single process mode, browser-side tracing will cover the whole
379 // process including renderers.
380 channel_->AddFilter(new tracing::ChildTraceMessageFilter(
381 ChildProcess::current()->io_message_loop_proxy()));
384 // In single process mode we may already have a power monitor
385 if (!base::PowerMonitor::Get()) {
386 scoped_ptr<PowerMonitorBroadcastSource> power_monitor_source(
387 new PowerMonitorBroadcastSource());
388 channel_->AddFilter(power_monitor_source->GetMessageFilter());
390 power_monitor_.reset(new base::PowerMonitor(
391 power_monitor_source.Pass()));
394 #if defined(OS_POSIX)
395 // Check that --process-type is specified so we don't do this in unit tests
396 // and single-process mode.
397 if (base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kProcessType))
398 channel_->AddFilter(new SuicideOnChannelErrorFilter());
399 #endif
401 // Add filters passed here via options.
402 for (auto startup_filter : options.startup_filters) {
403 channel_->AddFilter(startup_filter);
406 ConnectChannel(options.use_mojo_channel);
408 int connection_timeout = kConnectionTimeoutS;
409 std::string connection_override =
410 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
411 switches::kIPCConnectionTimeout);
412 if (!connection_override.empty()) {
413 int temp;
414 if (base::StringToInt(connection_override, &temp))
415 connection_timeout = temp;
418 base::MessageLoop::current()->PostDelayedTask(
419 FROM_HERE,
420 base::Bind(&ChildThreadImpl::EnsureConnected,
421 channel_connected_factory_.GetWeakPtr()),
422 base::TimeDelta::FromSeconds(connection_timeout));
424 #if defined(OS_ANDROID)
426 base::AutoLock lock(g_lazy_child_thread_lock.Get());
427 g_child_thread = this;
428 g_child_thread_initialized = true;
430 // Signalling without locking is fine here because only
431 // one thread can wait on the condition variable.
432 g_lazy_child_thread_cv.Get().Signal();
433 #endif
435 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
436 trace_memory_controller_.reset(new base::trace_event::TraceMemoryController(
437 message_loop_->message_loop_proxy(), ::HeapProfilerWithPseudoStackStart,
438 ::HeapProfilerStop, ::GetHeapProfile));
439 #endif
441 shared_bitmap_manager_.reset(
442 new ChildSharedBitmapManager(thread_safe_sender()));
444 gpu_memory_buffer_manager_.reset(
445 new ChildGpuMemoryBufferManager(thread_safe_sender()));
447 discardable_shared_memory_manager_.reset(
448 new ChildDiscardableSharedMemoryManager(thread_safe_sender()));
451 ChildThreadImpl::~ChildThreadImpl() {
452 #if defined(OS_ANDROID)
454 base::AutoLock lock(g_lazy_child_thread_lock.Get());
455 g_child_thread = nullptr;
457 #endif
459 #ifdef IPC_MESSAGE_LOG_ENABLED
460 IPC::Logging::GetInstance()->SetIPCSender(NULL);
461 #endif
463 channel_->RemoveFilter(histogram_message_filter_.get());
464 channel_->RemoveFilter(sync_message_filter_.get());
466 // The ChannelProxy object caches a pointer to the IPC thread, so need to
467 // reset it as it's not guaranteed to outlive this object.
468 // NOTE: this also has the side-effect of not closing the main IPC channel to
469 // the browser process. This is needed because this is the signal that the
470 // browser uses to know that this process has died, so we need it to be alive
471 // until this process is shut down, and the OS closes the handle
472 // automatically. We used to watch the object handle on Windows to do this,
473 // but it wasn't possible to do so on POSIX.
474 channel_->ClearIPCTaskRunner();
475 g_lazy_tls.Pointer()->Set(NULL);
478 void ChildThreadImpl::Shutdown() {
479 // Delete objects that hold references to blink so derived classes can
480 // safely shutdown blink in their Shutdown implementation.
481 file_system_dispatcher_.reset();
482 quota_dispatcher_.reset();
483 WebFileSystemImpl::DeleteThreadSpecificInstance();
486 void ChildThreadImpl::OnChannelConnected(int32 peer_pid) {
487 channel_connected_factory_.InvalidateWeakPtrs();
490 void ChildThreadImpl::OnChannelError() {
491 set_on_channel_error_called(true);
492 base::MessageLoop::current()->Quit();
495 bool ChildThreadImpl::Send(IPC::Message* msg) {
496 DCHECK(base::MessageLoop::current() == message_loop());
497 if (!channel_) {
498 delete msg;
499 return false;
502 return channel_->Send(msg);
505 #if defined(OS_WIN)
506 void ChildThreadImpl::PreCacheFont(const LOGFONT& log_font) {
507 Send(new ChildProcessHostMsg_PreCacheFont(log_font));
510 void ChildThreadImpl::ReleaseCachedFonts() {
511 Send(new ChildProcessHostMsg_ReleaseCachedFonts());
513 #endif
515 MessageRouter* ChildThreadImpl::GetRouter() {
516 DCHECK(base::MessageLoop::current() == message_loop());
517 return &router_;
520 scoped_ptr<base::SharedMemory> ChildThreadImpl::AllocateSharedMemory(
521 size_t buf_size) {
522 DCHECK(base::MessageLoop::current() == message_loop());
523 return AllocateSharedMemory(buf_size, this);
526 // static
527 scoped_ptr<base::SharedMemory> ChildThreadImpl::AllocateSharedMemory(
528 size_t buf_size,
529 IPC::Sender* sender) {
530 scoped_ptr<base::SharedMemory> shared_buf;
531 #if defined(OS_WIN)
532 shared_buf.reset(new base::SharedMemory);
533 if (!shared_buf->CreateAnonymous(buf_size)) {
534 NOTREACHED();
535 return NULL;
537 #else
538 // On POSIX, we need to ask the browser to create the shared memory for us,
539 // since this is blocked by the sandbox.
540 base::SharedMemoryHandle shared_mem_handle;
541 if (sender->Send(new ChildProcessHostMsg_SyncAllocateSharedMemory(
542 buf_size, &shared_mem_handle))) {
543 if (base::SharedMemory::IsHandleValid(shared_mem_handle)) {
544 shared_buf.reset(new base::SharedMemory(shared_mem_handle, false));
545 } else {
546 NOTREACHED() << "Browser failed to allocate shared memory";
547 return NULL;
549 } else {
550 NOTREACHED() << "Browser allocation request message failed";
551 return NULL;
553 #endif
554 return shared_buf;
557 bool ChildThreadImpl::OnMessageReceived(const IPC::Message& msg) {
558 if (mojo_application_->OnMessageReceived(msg))
559 return true;
561 // Resource responses are sent to the resource dispatcher.
562 if (resource_dispatcher_->OnMessageReceived(msg))
563 return true;
564 if (websocket_dispatcher_->OnMessageReceived(msg))
565 return true;
566 if (file_system_dispatcher_->OnMessageReceived(msg))
567 return true;
569 bool handled = true;
570 IPC_BEGIN_MESSAGE_MAP(ChildThreadImpl, msg)
571 IPC_MESSAGE_HANDLER(ChildProcessMsg_Shutdown, OnShutdown)
572 #if defined(IPC_MESSAGE_LOG_ENABLED)
573 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetIPCLoggingEnabled,
574 OnSetIPCLoggingEnabled)
575 #endif
576 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetProfilerStatus,
577 OnSetProfilerStatus)
578 IPC_MESSAGE_HANDLER(ChildProcessMsg_GetChildProfilerData,
579 OnGetChildProfilerData)
580 IPC_MESSAGE_HANDLER(ChildProcessMsg_DumpHandles, OnDumpHandles)
581 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetProcessBackgrounded,
582 OnProcessBackgrounded)
583 #if defined(USE_TCMALLOC)
584 IPC_MESSAGE_HANDLER(ChildProcessMsg_GetTcmallocStats, OnGetTcmallocStats)
585 #endif
586 IPC_MESSAGE_UNHANDLED(handled = false)
587 IPC_END_MESSAGE_MAP()
589 if (handled)
590 return true;
592 if (msg.routing_id() == MSG_ROUTING_CONTROL)
593 return OnControlMessageReceived(msg);
595 return router_.OnMessageReceived(msg);
598 bool ChildThreadImpl::OnControlMessageReceived(const IPC::Message& msg) {
599 return false;
602 void ChildThreadImpl::OnShutdown() {
603 base::MessageLoop::current()->Quit();
606 #if defined(IPC_MESSAGE_LOG_ENABLED)
607 void ChildThreadImpl::OnSetIPCLoggingEnabled(bool enable) {
608 if (enable)
609 IPC::Logging::GetInstance()->Enable();
610 else
611 IPC::Logging::GetInstance()->Disable();
613 #endif // IPC_MESSAGE_LOG_ENABLED
615 void ChildThreadImpl::OnSetProfilerStatus(ThreadData::Status status) {
616 ThreadData::InitializeAndSetTrackingStatus(status);
619 void ChildThreadImpl::OnGetChildProfilerData(int sequence_number) {
620 tracked_objects::ProcessDataSnapshot process_data;
621 ThreadData::Snapshot(false, &process_data);
623 Send(new ChildProcessHostMsg_ChildProfilerData(sequence_number,
624 process_data));
627 void ChildThreadImpl::OnDumpHandles() {
628 #if defined(OS_WIN)
629 scoped_refptr<HandleEnumerator> handle_enum(
630 new HandleEnumerator(
631 base::CommandLine::ForCurrentProcess()->HasSwitch(
632 switches::kAuditAllHandles)));
633 handle_enum->EnumerateHandles();
634 Send(new ChildProcessHostMsg_DumpHandlesDone);
635 #else
636 NOTIMPLEMENTED();
637 #endif
640 #if defined(USE_TCMALLOC)
641 void ChildThreadImpl::OnGetTcmallocStats() {
642 std::string result;
643 char buffer[1024 * 32];
644 base::allocator::GetStats(buffer, sizeof(buffer));
645 result.append(buffer);
646 Send(new ChildProcessHostMsg_TcmallocStats(result));
648 #endif
650 ChildThreadImpl* ChildThreadImpl::current() {
651 return g_lazy_tls.Pointer()->Get();
654 #if defined(OS_ANDROID)
655 // The method must NOT be called on the child thread itself.
656 // It may block the child thread if so.
657 void ChildThreadImpl::ShutdownThread() {
658 DCHECK(!ChildThreadImpl::current()) <<
659 "this method should NOT be called from child thread itself";
661 base::AutoLock lock(g_lazy_child_thread_lock.Get());
662 while (!g_child_thread_initialized)
663 g_lazy_child_thread_cv.Get().Wait();
665 // g_child_thread may already have been destructed while we didn't hold the
666 // lock.
667 if (!g_child_thread)
668 return;
670 DCHECK_NE(base::MessageLoop::current(), g_child_thread->message_loop());
671 g_child_thread->message_loop()->PostTask(
672 FROM_HERE, base::Bind(&QuitMainThreadMessageLoop));
675 #endif
677 void ChildThreadImpl::OnProcessFinalRelease() {
678 if (on_channel_error_called_) {
679 base::MessageLoop::current()->Quit();
680 return;
683 // The child process shutdown sequence is a request response based mechanism,
684 // where we send out an initial feeler request to the child process host
685 // instance in the browser to verify if it's ok to shutdown the child process.
686 // The browser then sends back a response if it's ok to shutdown. This avoids
687 // race conditions if the process refcount is 0 but there's an IPC message
688 // inflight that would addref it.
689 Send(new ChildProcessHostMsg_ShutdownRequest);
692 void ChildThreadImpl::EnsureConnected() {
693 VLOG(0) << "ChildThreadImpl::EnsureConnected()";
694 base::KillProcess(base::GetCurrentProcessHandle(), 0, false);
697 void ChildThreadImpl::OnProcessBackgrounded(bool background) {
698 // Set timer slack to maximum on main thread when in background.
699 base::TimerSlack timer_slack = base::TIMER_SLACK_NONE;
700 if (background)
701 timer_slack = base::TIMER_SLACK_MAXIMUM;
702 base::MessageLoop::current()->SetTimerSlack(timer_slack);
704 #ifdef OS_WIN
705 // Windows Vista+ has a fancy process backgrounding mode that can only be set
706 // from within the process. This used to be how chrome set its renderers into
707 // background mode on Windows but was removed due to http://crbug.com/398103.
708 // As we experiment with bringing back some other form of background mode for
709 // hidden renderers, add a bucket to allow us to trigger this undesired method
710 // of setting background state in order to confirm that the metrics which were
711 // added to prevent regressions on the aforementioned issue indeed catch such
712 // regressions and are thus a reliable way to confirm that our latest proposal
713 // doesn't cause such issues. TODO(gab): Remove this once the experiment is
714 // over (http://crbug.com/458594).
715 base::FieldTrial* trial =
716 base::FieldTrialList::Find("BackgroundRendererProcesses");
717 if (trial && trial->group_name() == "AllowBackgroundModeFromRenderer")
718 base::Process::Current().SetProcessBackgrounded(background);
719 #endif // OS_WIN
722 } // namespace content