Mac: Fix performance issues with remote CoreAnimation
[chromium-blink-merge.git] / content / child / child_thread.cc
blob5061b4cb2c0ff747ce9137ddb3cbf40351274361
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.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/process/kill.h"
21 #include "base/process/process_handle.h"
22 #include "base/strings/string_number_conversions.h"
23 #include "base/strings/string_util.h"
24 #include "base/synchronization/condition_variable.h"
25 #include "base/synchronization/lock.h"
26 #include "base/threading/thread_local.h"
27 #include "base/tracked_objects.h"
28 #include "components/tracing/child_trace_message_filter.h"
29 #include "content/child/bluetooth/bluetooth_message_filter.h"
30 #include "content/child/child_discardable_shared_memory_manager.h"
31 #include "content/child/child_gpu_memory_buffer_manager.h"
32 #include "content/child/child_histogram_message_filter.h"
33 #include "content/child/child_process.h"
34 #include "content/child/child_resource_message_filter.h"
35 #include "content/child/child_shared_bitmap_manager.h"
36 #include "content/child/fileapi/file_system_dispatcher.h"
37 #include "content/child/fileapi/webfilesystem_impl.h"
38 #include "content/child/geofencing/geofencing_message_filter.h"
39 #include "content/child/mojo/mojo_application.h"
40 #include "content/child/notifications/notification_dispatcher.h"
41 #include "content/child/power_monitor_broadcast_source.h"
42 #include "content/child/quota_dispatcher.h"
43 #include "content/child/quota_message_filter.h"
44 #include "content/child/resource_dispatcher.h"
45 #include "content/child/service_worker/service_worker_message_filter.h"
46 #include "content/child/thread_safe_sender.h"
47 #include "content/child/websocket_dispatcher.h"
48 #include "content/common/child_process_messages.h"
49 #include "content/public/common/content_switches.h"
50 #include "ipc/ipc_logging.h"
51 #include "ipc/ipc_switches.h"
52 #include "ipc/ipc_sync_channel.h"
53 #include "ipc/ipc_sync_message_filter.h"
54 #include "ipc/mojo/ipc_channel_mojo.h"
56 #if defined(OS_WIN)
57 #include "content/common/handle_enumerator_win.h"
58 #endif
60 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
61 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
62 #endif
64 using tracked_objects::ThreadData;
66 namespace content {
67 namespace {
69 // How long to wait for a connection to the browser process before giving up.
70 const int kConnectionTimeoutS = 15;
72 base::LazyInstance<base::ThreadLocalPointer<ChildThread> > g_lazy_tls =
73 LAZY_INSTANCE_INITIALIZER;
75 // This isn't needed on Windows because there the sandbox's job object
76 // terminates child processes automatically. For unsandboxed processes (i.e.
77 // plugins), PluginThread has EnsureTerminateMessageFilter.
78 #if defined(OS_POSIX)
80 // TODO(earthdok): Re-enable on CrOS http://crbug.com/360622
81 #if (defined(ADDRESS_SANITIZER) || defined(LEAK_SANITIZER) || \
82 defined(THREAD_SANITIZER)) && !defined(OS_CHROMEOS)
83 // A thread delegate that waits for |duration| and then exits the process with
84 // _exit(0).
85 class WaitAndExitDelegate : public base::PlatformThread::Delegate {
86 public:
87 explicit WaitAndExitDelegate(base::TimeDelta duration)
88 : duration_(duration) {}
89 virtual ~WaitAndExitDelegate() override {}
91 virtual void ThreadMain() override {
92 base::PlatformThread::Sleep(duration_);
93 _exit(0);
96 private:
97 const base::TimeDelta duration_;
98 DISALLOW_COPY_AND_ASSIGN(WaitAndExitDelegate);
101 bool CreateWaitAndExitThread(base::TimeDelta duration) {
102 scoped_ptr<WaitAndExitDelegate> delegate(new WaitAndExitDelegate(duration));
104 const bool thread_created =
105 base::PlatformThread::CreateNonJoinable(0, delegate.get());
106 if (!thread_created)
107 return false;
109 // A non joinable thread has been created. The thread will either terminate
110 // the process or will be terminated by the process. Therefore, keep the
111 // delegate object alive for the lifetime of the process.
112 WaitAndExitDelegate* leaking_delegate = delegate.release();
113 ANNOTATE_LEAKING_OBJECT_PTR(leaking_delegate);
114 ignore_result(leaking_delegate);
115 return true;
117 #endif
119 class SuicideOnChannelErrorFilter : public IPC::MessageFilter {
120 public:
121 // IPC::MessageFilter
122 void OnChannelError() override {
123 // For renderer/worker processes:
124 // On POSIX, at least, one can install an unload handler which loops
125 // forever and leave behind a renderer process which eats 100% CPU forever.
127 // This is because the terminate signals (ViewMsg_ShouldClose and the error
128 // from the IPC sender) are routed to the main message loop but never
129 // processed (because that message loop is stuck in V8).
131 // One could make the browser SIGKILL the renderers, but that leaves open a
132 // large window where a browser failure (or a user, manually terminating
133 // the browser because "it's stuck") will leave behind a process eating all
134 // the CPU.
136 // So, we install a filter on the sender so that we can process this event
137 // here and kill the process.
138 // TODO(earthdok): Re-enable on CrOS http://crbug.com/360622
139 #if (defined(ADDRESS_SANITIZER) || defined(LEAK_SANITIZER) || \
140 defined(THREAD_SANITIZER)) && !defined(OS_CHROMEOS)
141 // Some sanitizer tools rely on exit handlers (e.g. to run leak detection,
142 // or dump code coverage data to disk). Instead of exiting the process
143 // immediately, we give it 60 seconds to run exit handlers.
144 CHECK(CreateWaitAndExitThread(base::TimeDelta::FromSeconds(60)));
145 #if defined(LEAK_SANITIZER)
146 // Invoke LeakSanitizer early to avoid detecting shutdown-only leaks. If
147 // leaks are found, the process will exit here.
148 __lsan_do_leak_check();
149 #endif
150 #else
151 _exit(0);
152 #endif
155 protected:
156 ~SuicideOnChannelErrorFilter() override {}
159 #endif // OS(POSIX)
161 #if defined(OS_ANDROID)
162 ChildThread* g_child_thread = NULL;
164 // A lock protects g_child_thread.
165 base::LazyInstance<base::Lock> g_lazy_child_thread_lock =
166 LAZY_INSTANCE_INITIALIZER;
168 // base::ConditionVariable has an explicit constructor that takes
169 // a base::Lock pointer as parameter. The base::DefaultLazyInstanceTraits
170 // doesn't handle the case. Thus, we need our own class here.
171 struct CondVarLazyInstanceTraits {
172 static const bool kRegisterOnExit = true;
173 #ifndef NDEBUG
174 static const bool kAllowedToAccessOnNonjoinableThread = false;
175 #endif
177 static base::ConditionVariable* New(void* instance) {
178 return new (instance) base::ConditionVariable(
179 g_lazy_child_thread_lock.Pointer());
181 static void Delete(base::ConditionVariable* instance) {
182 instance->~ConditionVariable();
186 // A condition variable that synchronize threads initializing and waiting
187 // for g_child_thread.
188 base::LazyInstance<base::ConditionVariable, CondVarLazyInstanceTraits>
189 g_lazy_child_thread_cv = LAZY_INSTANCE_INITIALIZER;
191 void QuitMainThreadMessageLoop() {
192 base::MessageLoop::current()->Quit();
195 #endif
197 } // namespace
199 ChildThread::Options::Options()
200 : channel_name(base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
201 switches::kProcessChannelID)),
202 use_mojo_channel(false) {}
204 ChildThread::Options::Options(bool mojo)
205 : channel_name(base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
206 switches::kProcessChannelID)),
207 use_mojo_channel(mojo) {}
210 ChildThread::ChildThreadMessageRouter::ChildThreadMessageRouter(
211 IPC::Sender* sender)
212 : sender_(sender) {}
214 bool ChildThread::ChildThreadMessageRouter::Send(IPC::Message* msg) {
215 return sender_->Send(msg);
218 ChildThread::ChildThread()
219 : router_(this),
220 in_browser_process_(false),
221 channel_connected_factory_(this) {
222 Init(Options());
225 ChildThread::ChildThread(const Options& options)
226 : router_(this),
227 in_browser_process_(true),
228 channel_connected_factory_(this) {
229 Init(options);
232 scoped_ptr<IPC::SyncChannel> ChildThread::CreateChannel(bool use_mojo_channel) {
233 if (use_mojo_channel) {
234 VLOG(1) << "Mojo is enabled on child";
235 return IPC::SyncChannel::Create(
236 IPC::ChannelMojo::CreateClientFactory(channel_name_),
237 this,
238 ChildProcess::current()->io_message_loop_proxy(),
239 true,
240 ChildProcess::current()->GetShutDownEvent());
243 VLOG(1) << "Mojo is disabled on child";
244 return IPC::SyncChannel::Create(
245 channel_name_,
246 IPC::Channel::MODE_CLIENT,
247 this,
248 ChildProcess::current()->io_message_loop_proxy(),
249 true,
250 ChildProcess::current()->GetShutDownEvent());
253 void ChildThread::Init(const Options& options) {
254 channel_name_ = options.channel_name;
256 g_lazy_tls.Pointer()->Set(this);
257 on_channel_error_called_ = false;
258 message_loop_ = base::MessageLoop::current();
259 #ifdef IPC_MESSAGE_LOG_ENABLED
260 // We must make sure to instantiate the IPC Logger *before* we create the
261 // channel, otherwise we can get a callback on the IO thread which creates
262 // the logger, and the logger does not like being created on the IO thread.
263 IPC::Logging::GetInstance();
264 #endif
265 channel_ = CreateChannel(options.use_mojo_channel);
266 #ifdef IPC_MESSAGE_LOG_ENABLED
267 if (!in_browser_process_)
268 IPC::Logging::GetInstance()->SetIPCSender(this);
269 #endif
271 mojo_application_.reset(new MojoApplication);
273 sync_message_filter_ =
274 new IPC::SyncMessageFilter(ChildProcess::current()->GetShutDownEvent());
275 thread_safe_sender_ = new ThreadSafeSender(
276 base::MessageLoopProxy::current().get(), sync_message_filter_.get());
278 resource_dispatcher_.reset(new ResourceDispatcher(this));
279 websocket_dispatcher_.reset(new WebSocketDispatcher);
280 file_system_dispatcher_.reset(new FileSystemDispatcher());
282 histogram_message_filter_ = new ChildHistogramMessageFilter();
283 resource_message_filter_ =
284 new ChildResourceMessageFilter(resource_dispatcher());
286 service_worker_message_filter_ =
287 new ServiceWorkerMessageFilter(thread_safe_sender_.get());
289 quota_message_filter_ =
290 new QuotaMessageFilter(thread_safe_sender_.get());
291 quota_dispatcher_.reset(new QuotaDispatcher(thread_safe_sender_.get(),
292 quota_message_filter_.get()));
293 geofencing_message_filter_ =
294 new GeofencingMessageFilter(thread_safe_sender_.get());
295 bluetooth_message_filter_ =
296 new BluetoothMessageFilter(thread_safe_sender_.get());
297 notification_dispatcher_ =
298 new NotificationDispatcher(thread_safe_sender_.get());
299 channel_->AddFilter(histogram_message_filter_.get());
300 channel_->AddFilter(sync_message_filter_.get());
301 channel_->AddFilter(resource_message_filter_.get());
302 channel_->AddFilter(quota_message_filter_->GetFilter());
303 channel_->AddFilter(notification_dispatcher_->GetFilter());
304 channel_->AddFilter(service_worker_message_filter_->GetFilter());
305 channel_->AddFilter(geofencing_message_filter_->GetFilter());
306 channel_->AddFilter(bluetooth_message_filter_->GetFilter());
308 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
309 switches::kSingleProcess)) {
310 // In single process mode, browser-side tracing will cover the whole
311 // process including renderers.
312 channel_->AddFilter(new tracing::ChildTraceMessageFilter(
313 ChildProcess::current()->io_message_loop_proxy()));
316 // In single process mode we may already have a power monitor
317 if (!base::PowerMonitor::Get()) {
318 scoped_ptr<PowerMonitorBroadcastSource> power_monitor_source(
319 new PowerMonitorBroadcastSource());
320 channel_->AddFilter(power_monitor_source->GetMessageFilter());
322 power_monitor_.reset(new base::PowerMonitor(
323 power_monitor_source.Pass()));
326 #if defined(OS_POSIX)
327 // Check that --process-type is specified so we don't do this in unit tests
328 // and single-process mode.
329 if (base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kProcessType))
330 channel_->AddFilter(new SuicideOnChannelErrorFilter());
331 #endif
333 int connection_timeout = kConnectionTimeoutS;
334 std::string connection_override =
335 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
336 switches::kIPCConnectionTimeout);
337 if (!connection_override.empty()) {
338 int temp;
339 if (base::StringToInt(connection_override, &temp))
340 connection_timeout = temp;
343 base::MessageLoop::current()->PostDelayedTask(
344 FROM_HERE,
345 base::Bind(&ChildThread::EnsureConnected,
346 channel_connected_factory_.GetWeakPtr()),
347 base::TimeDelta::FromSeconds(connection_timeout));
349 #if defined(OS_ANDROID)
351 base::AutoLock lock(g_lazy_child_thread_lock.Get());
352 g_child_thread = this;
354 // Signalling without locking is fine here because only
355 // one thread can wait on the condition variable.
356 g_lazy_child_thread_cv.Get().Signal();
357 #endif
359 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
360 trace_memory_controller_.reset(new base::debug::TraceMemoryController(
361 message_loop_->message_loop_proxy(),
362 ::HeapProfilerWithPseudoStackStart,
363 ::HeapProfilerStop,
364 ::GetHeapProfile));
365 #endif
367 shared_bitmap_manager_.reset(
368 new ChildSharedBitmapManager(thread_safe_sender()));
370 gpu_memory_buffer_manager_.reset(
371 new ChildGpuMemoryBufferManager(thread_safe_sender()));
373 discardable_shared_memory_manager_.reset(
374 new ChildDiscardableSharedMemoryManager(thread_safe_sender()));
377 ChildThread::~ChildThread() {
378 #ifdef IPC_MESSAGE_LOG_ENABLED
379 IPC::Logging::GetInstance()->SetIPCSender(NULL);
380 #endif
382 channel_->RemoveFilter(histogram_message_filter_.get());
383 channel_->RemoveFilter(sync_message_filter_.get());
385 // The ChannelProxy object caches a pointer to the IPC thread, so need to
386 // reset it as it's not guaranteed to outlive this object.
387 // NOTE: this also has the side-effect of not closing the main IPC channel to
388 // the browser process. This is needed because this is the signal that the
389 // browser uses to know that this process has died, so we need it to be alive
390 // until this process is shut down, and the OS closes the handle
391 // automatically. We used to watch the object handle on Windows to do this,
392 // but it wasn't possible to do so on POSIX.
393 channel_->ClearIPCTaskRunner();
394 g_lazy_tls.Pointer()->Set(NULL);
397 void ChildThread::Shutdown() {
398 // Delete objects that hold references to blink so derived classes can
399 // safely shutdown blink in their Shutdown implementation.
400 file_system_dispatcher_.reset();
401 quota_dispatcher_.reset();
402 WebFileSystemImpl::DeleteThreadSpecificInstance();
405 void ChildThread::OnChannelConnected(int32 peer_pid) {
406 channel_connected_factory_.InvalidateWeakPtrs();
409 void ChildThread::OnChannelError() {
410 set_on_channel_error_called(true);
411 base::MessageLoop::current()->Quit();
414 bool ChildThread::Send(IPC::Message* msg) {
415 DCHECK(base::MessageLoop::current() == message_loop());
416 if (!channel_) {
417 delete msg;
418 return false;
421 return channel_->Send(msg);
424 MessageRouter* ChildThread::GetRouter() {
425 DCHECK(base::MessageLoop::current() == message_loop());
426 return &router_;
429 base::SharedMemory* ChildThread::AllocateSharedMemory(size_t buf_size) {
430 return AllocateSharedMemory(buf_size, this);
433 // static
434 base::SharedMemory* ChildThread::AllocateSharedMemory(
435 size_t buf_size,
436 IPC::Sender* sender) {
437 scoped_ptr<base::SharedMemory> shared_buf;
438 #if defined(OS_WIN)
439 shared_buf.reset(new base::SharedMemory);
440 if (!shared_buf->CreateAndMapAnonymous(buf_size)) {
441 NOTREACHED();
442 return NULL;
444 #else
445 // On POSIX, we need to ask the browser to create the shared memory for us,
446 // since this is blocked by the sandbox.
447 base::SharedMemoryHandle shared_mem_handle;
448 if (sender->Send(new ChildProcessHostMsg_SyncAllocateSharedMemory(
449 buf_size, &shared_mem_handle))) {
450 if (base::SharedMemory::IsHandleValid(shared_mem_handle)) {
451 shared_buf.reset(new base::SharedMemory(shared_mem_handle, false));
452 if (!shared_buf->Map(buf_size)) {
453 NOTREACHED() << "Map failed";
454 return NULL;
456 } else {
457 NOTREACHED() << "Browser failed to allocate shared memory";
458 return NULL;
460 } else {
461 NOTREACHED() << "Browser allocation request message failed";
462 return NULL;
464 #endif
465 return shared_buf.release();
468 bool ChildThread::OnMessageReceived(const IPC::Message& msg) {
469 if (mojo_application_->OnMessageReceived(msg))
470 return true;
472 // Resource responses are sent to the resource dispatcher.
473 if (resource_dispatcher_->OnMessageReceived(msg))
474 return true;
475 if (websocket_dispatcher_->OnMessageReceived(msg))
476 return true;
477 if (file_system_dispatcher_->OnMessageReceived(msg))
478 return true;
480 bool handled = true;
481 IPC_BEGIN_MESSAGE_MAP(ChildThread, msg)
482 IPC_MESSAGE_HANDLER(ChildProcessMsg_Shutdown, OnShutdown)
483 #if defined(IPC_MESSAGE_LOG_ENABLED)
484 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetIPCLoggingEnabled,
485 OnSetIPCLoggingEnabled)
486 #endif
487 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetProfilerStatus,
488 OnSetProfilerStatus)
489 IPC_MESSAGE_HANDLER(ChildProcessMsg_GetChildProfilerData,
490 OnGetChildProfilerData)
491 IPC_MESSAGE_HANDLER(ChildProcessMsg_DumpHandles, OnDumpHandles)
492 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetProcessBackgrounded,
493 OnProcessBackgrounded)
494 #if defined(USE_TCMALLOC)
495 IPC_MESSAGE_HANDLER(ChildProcessMsg_GetTcmallocStats, OnGetTcmallocStats)
496 #endif
497 IPC_MESSAGE_UNHANDLED(handled = false)
498 IPC_END_MESSAGE_MAP()
500 if (handled)
501 return true;
503 if (msg.routing_id() == MSG_ROUTING_CONTROL)
504 return OnControlMessageReceived(msg);
506 return router_.OnMessageReceived(msg);
509 bool ChildThread::OnControlMessageReceived(const IPC::Message& msg) {
510 return false;
513 void ChildThread::OnShutdown() {
514 base::MessageLoop::current()->Quit();
517 #if defined(IPC_MESSAGE_LOG_ENABLED)
518 void ChildThread::OnSetIPCLoggingEnabled(bool enable) {
519 if (enable)
520 IPC::Logging::GetInstance()->Enable();
521 else
522 IPC::Logging::GetInstance()->Disable();
524 #endif // IPC_MESSAGE_LOG_ENABLED
526 void ChildThread::OnSetProfilerStatus(ThreadData::Status status) {
527 ThreadData::InitializeAndSetTrackingStatus(status);
530 void ChildThread::OnGetChildProfilerData(int sequence_number) {
531 tracked_objects::ProcessDataSnapshot process_data;
532 ThreadData::Snapshot(false, &process_data);
534 Send(new ChildProcessHostMsg_ChildProfilerData(sequence_number,
535 process_data));
538 void ChildThread::OnDumpHandles() {
539 #if defined(OS_WIN)
540 scoped_refptr<HandleEnumerator> handle_enum(
541 new HandleEnumerator(
542 base::CommandLine::ForCurrentProcess()->HasSwitch(
543 switches::kAuditAllHandles)));
544 handle_enum->EnumerateHandles();
545 Send(new ChildProcessHostMsg_DumpHandlesDone);
546 #else
547 NOTIMPLEMENTED();
548 #endif
551 #if defined(USE_TCMALLOC)
552 void ChildThread::OnGetTcmallocStats() {
553 std::string result;
554 char buffer[1024 * 32];
555 base::allocator::GetStats(buffer, sizeof(buffer));
556 result.append(buffer);
557 Send(new ChildProcessHostMsg_TcmallocStats(result));
559 #endif
561 ChildThread* ChildThread::current() {
562 return g_lazy_tls.Pointer()->Get();
565 #if defined(OS_ANDROID)
566 // The method must NOT be called on the child thread itself.
567 // It may block the child thread if so.
568 void ChildThread::ShutdownThread() {
569 DCHECK(!ChildThread::current()) <<
570 "this method should NOT be called from child thread itself";
572 base::AutoLock lock(g_lazy_child_thread_lock.Get());
573 while (!g_child_thread)
574 g_lazy_child_thread_cv.Get().Wait();
576 DCHECK_NE(base::MessageLoop::current(), g_child_thread->message_loop());
577 g_child_thread->message_loop()->PostTask(
578 FROM_HERE, base::Bind(&QuitMainThreadMessageLoop));
580 #endif
582 void ChildThread::OnProcessFinalRelease() {
583 if (on_channel_error_called_) {
584 base::MessageLoop::current()->Quit();
585 return;
588 // The child process shutdown sequence is a request response based mechanism,
589 // where we send out an initial feeler request to the child process host
590 // instance in the browser to verify if it's ok to shutdown the child process.
591 // The browser then sends back a response if it's ok to shutdown. This avoids
592 // race conditions if the process refcount is 0 but there's an IPC message
593 // inflight that would addref it.
594 Send(new ChildProcessHostMsg_ShutdownRequest);
597 void ChildThread::EnsureConnected() {
598 VLOG(0) << "ChildThread::EnsureConnected()";
599 base::KillProcess(base::GetCurrentProcessHandle(), 0, false);
602 void ChildThread::OnProcessBackgrounded(bool background) {
603 // Set timer slack to maximum on main thread when in background.
604 base::TimerSlack timer_slack = base::TIMER_SLACK_NONE;
605 if (background)
606 timer_slack = base::TIMER_SLACK_MAXIMUM;
607 base::MessageLoop::current()->SetTimerSlack(timer_slack);
610 } // namespace content