Standardize usage of virtual/override/final in content/
[chromium-blink-merge.git] / content / child / child_thread.cc
blob6bbc4a46edd3653951e7d3df529ee5aea1a9e0ad
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/child_gpu_memory_buffer_manager.h"
30 #include "content/child/child_histogram_message_filter.h"
31 #include "content/child/child_process.h"
32 #include "content/child/child_resource_message_filter.h"
33 #include "content/child/child_shared_bitmap_manager.h"
34 #include "content/child/fileapi/file_system_dispatcher.h"
35 #include "content/child/fileapi/webfilesystem_impl.h"
36 #include "content/child/geofencing/geofencing_message_filter.h"
37 #include "content/child/mojo/mojo_application.h"
38 #include "content/child/power_monitor_broadcast_source.h"
39 #include "content/child/quota_dispatcher.h"
40 #include "content/child/quota_message_filter.h"
41 #include "content/child/resource_dispatcher.h"
42 #include "content/child/service_worker/service_worker_message_filter.h"
43 #include "content/child/socket_stream_dispatcher.h"
44 #include "content/child/thread_safe_sender.h"
45 #include "content/child/websocket_dispatcher.h"
46 #include "content/common/child_process_messages.h"
47 #include "content/public/common/content_switches.h"
48 #include "ipc/ipc_logging.h"
49 #include "ipc/ipc_switches.h"
50 #include "ipc/ipc_sync_channel.h"
51 #include "ipc/ipc_sync_message_filter.h"
52 #include "ipc/mojo/ipc_channel_mojo.h"
54 #if defined(OS_WIN)
55 #include "content/common/handle_enumerator_win.h"
56 #endif
58 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
59 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
60 #endif
62 using tracked_objects::ThreadData;
64 namespace content {
65 namespace {
67 // How long to wait for a connection to the browser process before giving up.
68 const int kConnectionTimeoutS = 15;
70 base::LazyInstance<base::ThreadLocalPointer<ChildThread> > g_lazy_tls =
71 LAZY_INSTANCE_INITIALIZER;
73 // This isn't needed on Windows because there the sandbox's job object
74 // terminates child processes automatically. For unsandboxed processes (i.e.
75 // plugins), PluginThread has EnsureTerminateMessageFilter.
76 #if defined(OS_POSIX)
78 // TODO(earthdok): Re-enable on CrOS http://crbug.com/360622
79 #if (defined(ADDRESS_SANITIZER) || defined(LEAK_SANITIZER) || \
80 defined(THREAD_SANITIZER)) && !defined(OS_CHROMEOS)
81 // A thread delegate that waits for |duration| and then exits the process with
82 // _exit(0).
83 class WaitAndExitDelegate : public base::PlatformThread::Delegate {
84 public:
85 explicit WaitAndExitDelegate(base::TimeDelta duration)
86 : duration_(duration) {}
87 virtual ~WaitAndExitDelegate() override {}
89 virtual void ThreadMain() override {
90 base::PlatformThread::Sleep(duration_);
91 _exit(0);
94 private:
95 const base::TimeDelta duration_;
96 DISALLOW_COPY_AND_ASSIGN(WaitAndExitDelegate);
99 bool CreateWaitAndExitThread(base::TimeDelta duration) {
100 scoped_ptr<WaitAndExitDelegate> delegate(new WaitAndExitDelegate(duration));
102 const bool thread_created =
103 base::PlatformThread::CreateNonJoinable(0, delegate.get());
104 if (!thread_created)
105 return false;
107 // A non joinable thread has been created. The thread will either terminate
108 // the process or will be terminated by the process. Therefore, keep the
109 // delegate object alive for the lifetime of the process.
110 WaitAndExitDelegate* leaking_delegate = delegate.release();
111 ANNOTATE_LEAKING_OBJECT_PTR(leaking_delegate);
112 ignore_result(leaking_delegate);
113 return true;
115 #endif
117 class SuicideOnChannelErrorFilter : public IPC::MessageFilter {
118 public:
119 // IPC::MessageFilter
120 void OnChannelError() override {
121 // For renderer/worker processes:
122 // On POSIX, at least, one can install an unload handler which loops
123 // forever and leave behind a renderer process which eats 100% CPU forever.
125 // This is because the terminate signals (ViewMsg_ShouldClose and the error
126 // from the IPC sender) are routed to the main message loop but never
127 // processed (because that message loop is stuck in V8).
129 // One could make the browser SIGKILL the renderers, but that leaves open a
130 // large window where a browser failure (or a user, manually terminating
131 // the browser because "it's stuck") will leave behind a process eating all
132 // the CPU.
134 // So, we install a filter on the sender so that we can process this event
135 // here and kill the process.
136 // TODO(earthdok): Re-enable on CrOS http://crbug.com/360622
137 #if (defined(ADDRESS_SANITIZER) || defined(LEAK_SANITIZER) || \
138 defined(THREAD_SANITIZER)) && !defined(OS_CHROMEOS)
139 // Some sanitizer tools rely on exit handlers (e.g. to run leak detection,
140 // or dump code coverage data to disk). Instead of exiting the process
141 // immediately, we give it 60 seconds to run exit handlers.
142 CHECK(CreateWaitAndExitThread(base::TimeDelta::FromSeconds(60)));
143 #if defined(LEAK_SANITIZER)
144 // Invoke LeakSanitizer early to avoid detecting shutdown-only leaks. If
145 // leaks are found, the process will exit here.
146 __lsan_do_leak_check();
147 #endif
148 #else
149 _exit(0);
150 #endif
153 protected:
154 ~SuicideOnChannelErrorFilter() override {}
157 #endif // OS(POSIX)
159 #if defined(OS_ANDROID)
160 ChildThread* g_child_thread = NULL;
162 // A lock protects g_child_thread.
163 base::LazyInstance<base::Lock> g_lazy_child_thread_lock =
164 LAZY_INSTANCE_INITIALIZER;
166 // base::ConditionVariable has an explicit constructor that takes
167 // a base::Lock pointer as parameter. The base::DefaultLazyInstanceTraits
168 // doesn't handle the case. Thus, we need our own class here.
169 struct CondVarLazyInstanceTraits {
170 static const bool kRegisterOnExit = true;
171 #ifndef NDEBUG
172 static const bool kAllowedToAccessOnNonjoinableThread = false;
173 #endif
175 static base::ConditionVariable* New(void* instance) {
176 return new (instance) base::ConditionVariable(
177 g_lazy_child_thread_lock.Pointer());
179 static void Delete(base::ConditionVariable* instance) {
180 instance->~ConditionVariable();
184 // A condition variable that synchronize threads initializing and waiting
185 // for g_child_thread.
186 base::LazyInstance<base::ConditionVariable, CondVarLazyInstanceTraits>
187 g_lazy_child_thread_cv = LAZY_INSTANCE_INITIALIZER;
189 void QuitMainThreadMessageLoop() {
190 base::MessageLoop::current()->Quit();
193 #endif
195 } // namespace
197 ChildThread::Options::Options()
198 : channel_name(base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
199 switches::kProcessChannelID)),
200 use_mojo_channel(false) {}
202 ChildThread::Options::Options(bool mojo)
203 : channel_name(base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
204 switches::kProcessChannelID)),
205 use_mojo_channel(mojo) {}
208 ChildThread::ChildThreadMessageRouter::ChildThreadMessageRouter(
209 IPC::Sender* sender)
210 : sender_(sender) {}
212 bool ChildThread::ChildThreadMessageRouter::Send(IPC::Message* msg) {
213 return sender_->Send(msg);
216 ChildThread::ChildThread()
217 : router_(this),
218 in_browser_process_(false),
219 channel_connected_factory_(this) {
220 Init(Options());
223 ChildThread::ChildThread(const Options& options)
224 : router_(this),
225 in_browser_process_(true),
226 channel_connected_factory_(this) {
227 Init(options);
230 scoped_ptr<IPC::SyncChannel> ChildThread::CreateChannel(bool use_mojo_channel) {
231 if (use_mojo_channel) {
232 VLOG(1) << "Mojo is enabled on child";
233 return IPC::SyncChannel::Create(
234 IPC::ChannelMojo::CreateClientFactory(channel_name_),
235 this,
236 ChildProcess::current()->io_message_loop_proxy(),
237 true,
238 ChildProcess::current()->GetShutDownEvent());
241 VLOG(1) << "Mojo is disabled on child";
242 return IPC::SyncChannel::Create(
243 channel_name_,
244 IPC::Channel::MODE_CLIENT,
245 this,
246 ChildProcess::current()->io_message_loop_proxy(),
247 true,
248 ChildProcess::current()->GetShutDownEvent());
251 void ChildThread::Init(const Options& options) {
252 channel_name_ = options.channel_name;
254 g_lazy_tls.Pointer()->Set(this);
255 on_channel_error_called_ = false;
256 message_loop_ = base::MessageLoop::current();
257 #ifdef IPC_MESSAGE_LOG_ENABLED
258 // We must make sure to instantiate the IPC Logger *before* we create the
259 // channel, otherwise we can get a callback on the IO thread which creates
260 // the logger, and the logger does not like being created on the IO thread.
261 IPC::Logging::GetInstance();
262 #endif
263 channel_ = CreateChannel(options.use_mojo_channel);
264 #ifdef IPC_MESSAGE_LOG_ENABLED
265 if (!in_browser_process_)
266 IPC::Logging::GetInstance()->SetIPCSender(this);
267 #endif
269 mojo_application_.reset(new MojoApplication);
271 sync_message_filter_ =
272 new IPC::SyncMessageFilter(ChildProcess::current()->GetShutDownEvent());
273 thread_safe_sender_ = new ThreadSafeSender(
274 base::MessageLoopProxy::current().get(), sync_message_filter_.get());
276 resource_dispatcher_.reset(new ResourceDispatcher(this));
277 socket_stream_dispatcher_.reset(new SocketStreamDispatcher());
278 websocket_dispatcher_.reset(new WebSocketDispatcher);
279 file_system_dispatcher_.reset(new FileSystemDispatcher());
281 histogram_message_filter_ = new ChildHistogramMessageFilter();
282 resource_message_filter_ =
283 new ChildResourceMessageFilter(resource_dispatcher());
285 service_worker_message_filter_ =
286 new ServiceWorkerMessageFilter(thread_safe_sender_.get());
288 quota_message_filter_ =
289 new QuotaMessageFilter(thread_safe_sender_.get());
290 quota_dispatcher_.reset(new QuotaDispatcher(thread_safe_sender_.get(),
291 quota_message_filter_.get()));
293 geofencing_message_filter_ =
294 new GeofencingMessageFilter(thread_safe_sender_.get());
296 channel_->AddFilter(histogram_message_filter_.get());
297 channel_->AddFilter(sync_message_filter_.get());
298 channel_->AddFilter(resource_message_filter_.get());
299 channel_->AddFilter(quota_message_filter_->GetFilter());
300 channel_->AddFilter(service_worker_message_filter_->GetFilter());
301 channel_->AddFilter(geofencing_message_filter_->GetFilter());
303 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
304 switches::kSingleProcess)) {
305 // In single process mode, browser-side tracing will cover the whole
306 // process including renderers.
307 channel_->AddFilter(new tracing::ChildTraceMessageFilter(
308 ChildProcess::current()->io_message_loop_proxy()));
311 // In single process mode we may already have a power monitor
312 if (!base::PowerMonitor::Get()) {
313 scoped_ptr<PowerMonitorBroadcastSource> power_monitor_source(
314 new PowerMonitorBroadcastSource());
315 channel_->AddFilter(power_monitor_source->GetMessageFilter());
317 power_monitor_.reset(new base::PowerMonitor(
318 power_monitor_source.Pass()));
321 #if defined(OS_POSIX)
322 // Check that --process-type is specified so we don't do this in unit tests
323 // and single-process mode.
324 if (base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kProcessType))
325 channel_->AddFilter(new SuicideOnChannelErrorFilter());
326 #endif
328 int connection_timeout = kConnectionTimeoutS;
329 std::string connection_override =
330 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
331 switches::kIPCConnectionTimeout);
332 if (!connection_override.empty()) {
333 int temp;
334 if (base::StringToInt(connection_override, &temp))
335 connection_timeout = temp;
338 base::MessageLoop::current()->PostDelayedTask(
339 FROM_HERE,
340 base::Bind(&ChildThread::EnsureConnected,
341 channel_connected_factory_.GetWeakPtr()),
342 base::TimeDelta::FromSeconds(connection_timeout));
344 #if defined(OS_ANDROID)
346 base::AutoLock lock(g_lazy_child_thread_lock.Get());
347 g_child_thread = this;
349 // Signalling without locking is fine here because only
350 // one thread can wait on the condition variable.
351 g_lazy_child_thread_cv.Get().Signal();
352 #endif
354 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
355 trace_memory_controller_.reset(new base::debug::TraceMemoryController(
356 message_loop_->message_loop_proxy(),
357 ::HeapProfilerWithPseudoStackStart,
358 ::HeapProfilerStop,
359 ::GetHeapProfile));
360 #endif
362 shared_bitmap_manager_.reset(
363 new ChildSharedBitmapManager(thread_safe_sender()));
365 gpu_memory_buffer_manager_.reset(
366 new ChildGpuMemoryBufferManager(thread_safe_sender()));
369 ChildThread::~ChildThread() {
370 #ifdef IPC_MESSAGE_LOG_ENABLED
371 IPC::Logging::GetInstance()->SetIPCSender(NULL);
372 #endif
374 channel_->RemoveFilter(histogram_message_filter_.get());
375 channel_->RemoveFilter(sync_message_filter_.get());
377 // The ChannelProxy object caches a pointer to the IPC thread, so need to
378 // reset it as it's not guaranteed to outlive this object.
379 // NOTE: this also has the side-effect of not closing the main IPC channel to
380 // the browser process. This is needed because this is the signal that the
381 // browser uses to know that this process has died, so we need it to be alive
382 // until this process is shut down, and the OS closes the handle
383 // automatically. We used to watch the object handle on Windows to do this,
384 // but it wasn't possible to do so on POSIX.
385 channel_->ClearIPCTaskRunner();
386 g_lazy_tls.Pointer()->Set(NULL);
389 void ChildThread::Shutdown() {
390 // Delete objects that hold references to blink so derived classes can
391 // safely shutdown blink in their Shutdown implementation.
392 file_system_dispatcher_.reset();
393 quota_dispatcher_.reset();
394 WebFileSystemImpl::DeleteThreadSpecificInstance();
397 void ChildThread::OnChannelConnected(int32 peer_pid) {
398 channel_connected_factory_.InvalidateWeakPtrs();
401 void ChildThread::OnChannelError() {
402 set_on_channel_error_called(true);
403 base::MessageLoop::current()->Quit();
406 bool ChildThread::Send(IPC::Message* msg) {
407 DCHECK(base::MessageLoop::current() == message_loop());
408 if (!channel_) {
409 delete msg;
410 return false;
413 return channel_->Send(msg);
416 MessageRouter* ChildThread::GetRouter() {
417 DCHECK(base::MessageLoop::current() == message_loop());
418 return &router_;
421 base::SharedMemory* ChildThread::AllocateSharedMemory(size_t buf_size) {
422 return AllocateSharedMemory(buf_size, this);
425 // static
426 base::SharedMemory* ChildThread::AllocateSharedMemory(
427 size_t buf_size,
428 IPC::Sender* sender) {
429 scoped_ptr<base::SharedMemory> shared_buf;
430 #if defined(OS_WIN)
431 shared_buf.reset(new base::SharedMemory);
432 if (!shared_buf->CreateAndMapAnonymous(buf_size)) {
433 NOTREACHED();
434 return NULL;
436 #else
437 // On POSIX, we need to ask the browser to create the shared memory for us,
438 // since this is blocked by the sandbox.
439 base::SharedMemoryHandle shared_mem_handle;
440 if (sender->Send(new ChildProcessHostMsg_SyncAllocateSharedMemory(
441 buf_size, &shared_mem_handle))) {
442 if (base::SharedMemory::IsHandleValid(shared_mem_handle)) {
443 shared_buf.reset(new base::SharedMemory(shared_mem_handle, false));
444 if (!shared_buf->Map(buf_size)) {
445 NOTREACHED() << "Map failed";
446 return NULL;
448 } else {
449 NOTREACHED() << "Browser failed to allocate shared memory";
450 return NULL;
452 } else {
453 NOTREACHED() << "Browser allocation request message failed";
454 return NULL;
456 #endif
457 return shared_buf.release();
460 bool ChildThread::OnMessageReceived(const IPC::Message& msg) {
461 if (mojo_application_->OnMessageReceived(msg))
462 return true;
464 // Resource responses are sent to the resource dispatcher.
465 if (resource_dispatcher_->OnMessageReceived(msg))
466 return true;
467 if (socket_stream_dispatcher_->OnMessageReceived(msg))
468 return true;
469 if (websocket_dispatcher_->OnMessageReceived(msg))
470 return true;
471 if (file_system_dispatcher_->OnMessageReceived(msg))
472 return true;
474 bool handled = true;
475 IPC_BEGIN_MESSAGE_MAP(ChildThread, msg)
476 IPC_MESSAGE_HANDLER(ChildProcessMsg_Shutdown, OnShutdown)
477 #if defined(IPC_MESSAGE_LOG_ENABLED)
478 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetIPCLoggingEnabled,
479 OnSetIPCLoggingEnabled)
480 #endif
481 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetProfilerStatus,
482 OnSetProfilerStatus)
483 IPC_MESSAGE_HANDLER(ChildProcessMsg_GetChildProfilerData,
484 OnGetChildProfilerData)
485 IPC_MESSAGE_HANDLER(ChildProcessMsg_DumpHandles, OnDumpHandles)
486 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetProcessBackgrounded,
487 OnProcessBackgrounded)
488 #if defined(USE_TCMALLOC)
489 IPC_MESSAGE_HANDLER(ChildProcessMsg_GetTcmallocStats, OnGetTcmallocStats)
490 #endif
491 IPC_MESSAGE_UNHANDLED(handled = false)
492 IPC_END_MESSAGE_MAP()
494 if (handled)
495 return true;
497 if (msg.routing_id() == MSG_ROUTING_CONTROL)
498 return OnControlMessageReceived(msg);
500 return router_.OnMessageReceived(msg);
503 bool ChildThread::OnControlMessageReceived(const IPC::Message& msg) {
504 return false;
507 void ChildThread::OnShutdown() {
508 base::MessageLoop::current()->Quit();
511 #if defined(IPC_MESSAGE_LOG_ENABLED)
512 void ChildThread::OnSetIPCLoggingEnabled(bool enable) {
513 if (enable)
514 IPC::Logging::GetInstance()->Enable();
515 else
516 IPC::Logging::GetInstance()->Disable();
518 #endif // IPC_MESSAGE_LOG_ENABLED
520 void ChildThread::OnSetProfilerStatus(ThreadData::Status status) {
521 ThreadData::InitializeAndSetTrackingStatus(status);
524 void ChildThread::OnGetChildProfilerData(int sequence_number) {
525 tracked_objects::ProcessDataSnapshot process_data;
526 ThreadData::Snapshot(false, &process_data);
528 Send(new ChildProcessHostMsg_ChildProfilerData(sequence_number,
529 process_data));
532 void ChildThread::OnDumpHandles() {
533 #if defined(OS_WIN)
534 scoped_refptr<HandleEnumerator> handle_enum(
535 new HandleEnumerator(
536 base::CommandLine::ForCurrentProcess()->HasSwitch(
537 switches::kAuditAllHandles)));
538 handle_enum->EnumerateHandles();
539 Send(new ChildProcessHostMsg_DumpHandlesDone);
540 #else
541 NOTIMPLEMENTED();
542 #endif
545 #if defined(USE_TCMALLOC)
546 void ChildThread::OnGetTcmallocStats() {
547 std::string result;
548 char buffer[1024 * 32];
549 base::allocator::GetStats(buffer, sizeof(buffer));
550 result.append(buffer);
551 Send(new ChildProcessHostMsg_TcmallocStats(result));
553 #endif
555 ChildThread* ChildThread::current() {
556 return g_lazy_tls.Pointer()->Get();
559 #if defined(OS_ANDROID)
560 // The method must NOT be called on the child thread itself.
561 // It may block the child thread if so.
562 void ChildThread::ShutdownThread() {
563 DCHECK(!ChildThread::current()) <<
564 "this method should NOT be called from child thread itself";
566 base::AutoLock lock(g_lazy_child_thread_lock.Get());
567 while (!g_child_thread)
568 g_lazy_child_thread_cv.Get().Wait();
570 DCHECK_NE(base::MessageLoop::current(), g_child_thread->message_loop());
571 g_child_thread->message_loop()->PostTask(
572 FROM_HERE, base::Bind(&QuitMainThreadMessageLoop));
574 #endif
576 void ChildThread::OnProcessFinalRelease() {
577 if (on_channel_error_called_) {
578 base::MessageLoop::current()->Quit();
579 return;
582 // The child process shutdown sequence is a request response based mechanism,
583 // where we send out an initial feeler request to the child process host
584 // instance in the browser to verify if it's ok to shutdown the child process.
585 // The browser then sends back a response if it's ok to shutdown. This avoids
586 // race conditions if the process refcount is 0 but there's an IPC message
587 // inflight that would addref it.
588 Send(new ChildProcessHostMsg_ShutdownRequest);
591 void ChildThread::EnsureConnected() {
592 VLOG(0) << "ChildThread::EnsureConnected()";
593 base::KillProcess(base::GetCurrentProcessHandle(), 0, false);
596 void ChildThread::OnProcessBackgrounded(bool background) {
597 // Set timer slack to maximum on main thread when in background.
598 base::TimerSlack timer_slack = base::TIMER_SLACK_NONE;
599 if (background)
600 timer_slack = base::TIMER_SLACK_MAXIMUM;
601 base::MessageLoop::current()->SetTimerSlack(timer_slack);
604 } // namespace content