Added unit test for DevTools' ephemeral port support.
[chromium-blink-merge.git] / content / child / child_thread.cc
blob5e77c4046bec7deb5396eacb3671da1bc0b50dc4
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_util.h"
23 #include "base/synchronization/condition_variable.h"
24 #include "base/synchronization/lock.h"
25 #include "base/threading/thread_local.h"
26 #include "base/tracked_objects.h"
27 #include "components/tracing/child_trace_message_filter.h"
28 #include "content/child/child_histogram_message_filter.h"
29 #include "content/child/child_process.h"
30 #include "content/child/child_resource_message_filter.h"
31 #include "content/child/child_shared_bitmap_manager.h"
32 #include "content/child/fileapi/file_system_dispatcher.h"
33 #include "content/child/fileapi/webfilesystem_impl.h"
34 #include "content/child/mojo/mojo_application.h"
35 #include "content/child/power_monitor_broadcast_source.h"
36 #include "content/child/quota_dispatcher.h"
37 #include "content/child/quota_message_filter.h"
38 #include "content/child/resource_dispatcher.h"
39 #include "content/child/service_worker/service_worker_dispatcher.h"
40 #include "content/child/service_worker/service_worker_message_filter.h"
41 #include "content/child/socket_stream_dispatcher.h"
42 #include "content/child/thread_safe_sender.h"
43 #include "content/child/websocket_dispatcher.h"
44 #include "content/common/child_process_messages.h"
45 #include "content/public/common/content_switches.h"
46 #include "ipc/ipc_logging.h"
47 #include "ipc/ipc_switches.h"
48 #include "ipc/ipc_sync_channel.h"
49 #include "ipc/ipc_sync_message_filter.h"
51 #if defined(OS_WIN)
52 #include "content/common/handle_enumerator_win.h"
53 #endif
55 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
56 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
57 #endif
59 using tracked_objects::ThreadData;
61 namespace content {
62 namespace {
64 // How long to wait for a connection to the browser process before giving up.
65 const int kConnectionTimeoutS = 15;
67 base::LazyInstance<base::ThreadLocalPointer<ChildThread> > g_lazy_tls =
68 LAZY_INSTANCE_INITIALIZER;
70 // This isn't needed on Windows because there the sandbox's job object
71 // terminates child processes automatically. For unsandboxed processes (i.e.
72 // plugins), PluginThread has EnsureTerminateMessageFilter.
73 #if defined(OS_POSIX)
75 // TODO(earthdok): Re-enable on CrOS http://crbug.com/360622
76 #if (defined(ADDRESS_SANITIZER) || defined(LEAK_SANITIZER) || \
77 defined(THREAD_SANITIZER)) && !defined(OS_CHROMEOS)
78 // A thread delegate that waits for |duration| and then exits the process with
79 // _exit(0).
80 class WaitAndExitDelegate : public base::PlatformThread::Delegate {
81 public:
82 explicit WaitAndExitDelegate(base::TimeDelta duration)
83 : duration_(duration) {}
84 virtual ~WaitAndExitDelegate() OVERRIDE {}
86 virtual void ThreadMain() OVERRIDE {
87 base::PlatformThread::Sleep(duration_);
88 _exit(0);
91 private:
92 const base::TimeDelta duration_;
93 DISALLOW_COPY_AND_ASSIGN(WaitAndExitDelegate);
96 bool CreateWaitAndExitThread(base::TimeDelta duration) {
97 scoped_ptr<WaitAndExitDelegate> delegate(new WaitAndExitDelegate(duration));
99 const bool thread_created =
100 base::PlatformThread::CreateNonJoinable(0, delegate.get());
101 if (!thread_created)
102 return false;
104 // A non joinable thread has been created. The thread will either terminate
105 // the process or will be terminated by the process. Therefore, keep the
106 // delegate object alive for the lifetime of the process.
107 WaitAndExitDelegate* leaking_delegate = delegate.release();
108 ANNOTATE_LEAKING_OBJECT_PTR(leaking_delegate);
109 ignore_result(leaking_delegate);
110 return true;
112 #endif
114 class SuicideOnChannelErrorFilter : public IPC::MessageFilter {
115 public:
116 // IPC::MessageFilter
117 virtual void OnChannelError() OVERRIDE {
118 // For renderer/worker processes:
119 // On POSIX, at least, one can install an unload handler which loops
120 // forever and leave behind a renderer process which eats 100% CPU forever.
122 // This is because the terminate signals (ViewMsg_ShouldClose and the error
123 // from the IPC channel) are routed to the main message loop but never
124 // processed (because that message loop is stuck in V8).
126 // One could make the browser SIGKILL the renderers, but that leaves open a
127 // large window where a browser failure (or a user, manually terminating
128 // the browser because "it's stuck") will leave behind a process eating all
129 // the CPU.
131 // So, we install a filter on the channel so that we can process this event
132 // here and kill the process.
133 // TODO(earthdok): Re-enable on CrOS http://crbug.com/360622
134 #if (defined(ADDRESS_SANITIZER) || defined(LEAK_SANITIZER) || \
135 defined(THREAD_SANITIZER)) && !defined(OS_CHROMEOS)
136 // Some sanitizer tools rely on exit handlers (e.g. to run leak detection,
137 // or dump code coverage data to disk). Instead of exiting the process
138 // immediately, we give it 60 seconds to run exit handlers.
139 CHECK(CreateWaitAndExitThread(base::TimeDelta::FromSeconds(60)));
140 #if defined(LEAK_SANITIZER)
141 // Invoke LeakSanitizer early to avoid detecting shutdown-only leaks. If
142 // leaks are found, the process will exit here.
143 __lsan_do_leak_check();
144 #endif
145 #else
146 _exit(0);
147 #endif
150 protected:
151 virtual ~SuicideOnChannelErrorFilter() {}
154 #endif // OS(POSIX)
156 #if defined(OS_ANDROID)
157 ChildThread* g_child_thread = NULL;
159 // A lock protects g_child_thread.
160 base::LazyInstance<base::Lock> g_lazy_child_thread_lock =
161 LAZY_INSTANCE_INITIALIZER;
163 // base::ConditionVariable has an explicit constructor that takes
164 // a base::Lock pointer as parameter. The base::DefaultLazyInstanceTraits
165 // doesn't handle the case. Thus, we need our own class here.
166 struct CondVarLazyInstanceTraits {
167 static const bool kRegisterOnExit = true;
168 #ifndef NDEBUG
169 static const bool kAllowedToAccessOnNonjoinableThread = false;
170 #endif
172 static base::ConditionVariable* New(void* instance) {
173 return new (instance) base::ConditionVariable(
174 g_lazy_child_thread_lock.Pointer());
176 static void Delete(base::ConditionVariable* instance) {
177 instance->~ConditionVariable();
181 // A condition variable that synchronize threads initializing and waiting
182 // for g_child_thread.
183 base::LazyInstance<base::ConditionVariable, CondVarLazyInstanceTraits>
184 g_lazy_child_thread_cv = LAZY_INSTANCE_INITIALIZER;
186 void QuitMainThreadMessageLoop() {
187 base::MessageLoop::current()->Quit();
190 #endif
192 } // namespace
194 ChildThread::ChildThreadMessageRouter::ChildThreadMessageRouter(
195 IPC::Sender* sender)
196 : sender_(sender) {}
198 bool ChildThread::ChildThreadMessageRouter::Send(IPC::Message* msg) {
199 return sender_->Send(msg);
202 ChildThread::ChildThread()
203 : router_(this),
204 channel_connected_factory_(this),
205 in_browser_process_(false) {
206 channel_name_ = CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
207 switches::kProcessChannelID);
208 Init();
211 ChildThread::ChildThread(const std::string& channel_name)
212 : channel_name_(channel_name),
213 router_(this),
214 channel_connected_factory_(this),
215 in_browser_process_(true) {
216 Init();
219 void ChildThread::Init() {
220 g_lazy_tls.Pointer()->Set(this);
221 on_channel_error_called_ = false;
222 message_loop_ = base::MessageLoop::current();
223 #ifdef IPC_MESSAGE_LOG_ENABLED
224 // We must make sure to instantiate the IPC Logger *before* we create the
225 // channel, otherwise we can get a callback on the IO thread which creates
226 // the logger, and the logger does not like being created on the IO thread.
227 IPC::Logging::GetInstance();
228 #endif
229 channel_ =
230 IPC::SyncChannel::Create(channel_name_,
231 IPC::Channel::MODE_CLIENT,
232 this,
233 ChildProcess::current()->io_message_loop_proxy(),
234 true,
235 ChildProcess::current()->GetShutDownEvent());
236 #ifdef IPC_MESSAGE_LOG_ENABLED
237 if (!in_browser_process_)
238 IPC::Logging::GetInstance()->SetIPCSender(this);
239 #endif
241 mojo_application_.reset(new MojoApplication(this));
243 sync_message_filter_ =
244 new IPC::SyncMessageFilter(ChildProcess::current()->GetShutDownEvent());
245 thread_safe_sender_ = new ThreadSafeSender(
246 base::MessageLoopProxy::current().get(), sync_message_filter_.get());
248 resource_dispatcher_.reset(new ResourceDispatcher(this));
249 socket_stream_dispatcher_.reset(new SocketStreamDispatcher());
250 websocket_dispatcher_.reset(new WebSocketDispatcher);
251 file_system_dispatcher_.reset(new FileSystemDispatcher());
253 histogram_message_filter_ = new ChildHistogramMessageFilter();
254 resource_message_filter_ =
255 new ChildResourceMessageFilter(resource_dispatcher());
257 service_worker_message_filter_ =
258 new ServiceWorkerMessageFilter(thread_safe_sender_.get());
259 service_worker_dispatcher_.reset(
260 new ServiceWorkerDispatcher(thread_safe_sender_.get()));
262 quota_message_filter_ =
263 new QuotaMessageFilter(thread_safe_sender_.get());
264 quota_dispatcher_.reset(new QuotaDispatcher(thread_safe_sender_.get(),
265 quota_message_filter_.get()));
267 channel_->AddFilter(histogram_message_filter_.get());
268 channel_->AddFilter(sync_message_filter_.get());
269 channel_->AddFilter(new tracing::ChildTraceMessageFilter(
270 ChildProcess::current()->io_message_loop_proxy()));
271 channel_->AddFilter(resource_message_filter_.get());
272 channel_->AddFilter(quota_message_filter_->GetFilter());
273 channel_->AddFilter(service_worker_message_filter_->GetFilter());
275 // In single process mode we may already have a power monitor
276 if (!base::PowerMonitor::Get()) {
277 scoped_ptr<PowerMonitorBroadcastSource> power_monitor_source(
278 new PowerMonitorBroadcastSource());
279 channel_->AddFilter(power_monitor_source->GetMessageFilter());
281 power_monitor_.reset(new base::PowerMonitor(
282 power_monitor_source.PassAs<base::PowerMonitorSource>()));
285 #if defined(OS_POSIX)
286 // Check that --process-type is specified so we don't do this in unit tests
287 // and single-process mode.
288 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kProcessType))
289 channel_->AddFilter(new SuicideOnChannelErrorFilter());
290 #endif
292 base::MessageLoop::current()->PostDelayedTask(
293 FROM_HERE,
294 base::Bind(&ChildThread::EnsureConnected,
295 channel_connected_factory_.GetWeakPtr()),
296 base::TimeDelta::FromSeconds(kConnectionTimeoutS));
298 #if defined(OS_ANDROID)
300 base::AutoLock lock(g_lazy_child_thread_lock.Get());
301 g_child_thread = this;
303 // Signalling without locking is fine here because only
304 // one thread can wait on the condition variable.
305 g_lazy_child_thread_cv.Get().Signal();
306 #endif
308 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
309 trace_memory_controller_.reset(new base::debug::TraceMemoryController(
310 message_loop_->message_loop_proxy(),
311 ::HeapProfilerWithPseudoStackStart,
312 ::HeapProfilerStop,
313 ::GetHeapProfile));
314 #endif
316 shared_bitmap_manager_.reset(
317 new ChildSharedBitmapManager(thread_safe_sender()));
320 ChildThread::~ChildThread() {
321 #ifdef IPC_MESSAGE_LOG_ENABLED
322 IPC::Logging::GetInstance()->SetIPCSender(NULL);
323 #endif
325 channel_->RemoveFilter(histogram_message_filter_.get());
326 channel_->RemoveFilter(sync_message_filter_.get());
328 // The ChannelProxy object caches a pointer to the IPC thread, so need to
329 // reset it as it's not guaranteed to outlive this object.
330 // NOTE: this also has the side-effect of not closing the main IPC channel to
331 // the browser process. This is needed because this is the signal that the
332 // browser uses to know that this process has died, so we need it to be alive
333 // until this process is shut down, and the OS closes the handle
334 // automatically. We used to watch the object handle on Windows to do this,
335 // but it wasn't possible to do so on POSIX.
336 channel_->ClearIPCTaskRunner();
337 g_lazy_tls.Pointer()->Set(NULL);
340 void ChildThread::Shutdown() {
341 // Delete objects that hold references to blink so derived classes can
342 // safely shutdown blink in their Shutdown implementation.
343 file_system_dispatcher_.reset();
344 quota_dispatcher_.reset();
345 WebFileSystemImpl::DeleteThreadSpecificInstance();
348 void ChildThread::OnChannelConnected(int32 peer_pid) {
349 channel_connected_factory_.InvalidateWeakPtrs();
352 void ChildThread::OnChannelError() {
353 set_on_channel_error_called(true);
354 base::MessageLoop::current()->Quit();
357 void ChildThread::ConnectToService(
358 const mojo::String& service_url,
359 const mojo::String& service_name,
360 mojo::ScopedMessagePipeHandle message_pipe,
361 const mojo::String& requestor_url) {
362 // By default, we don't expect incoming connections.
363 NOTREACHED();
366 bool ChildThread::Send(IPC::Message* msg) {
367 DCHECK(base::MessageLoop::current() == message_loop());
368 if (!channel_) {
369 delete msg;
370 return false;
373 return channel_->Send(msg);
376 MessageRouter* ChildThread::GetRouter() {
377 DCHECK(base::MessageLoop::current() == message_loop());
378 return &router_;
381 base::SharedMemory* ChildThread::AllocateSharedMemory(size_t buf_size) {
382 return AllocateSharedMemory(buf_size, this);
385 // static
386 base::SharedMemory* ChildThread::AllocateSharedMemory(
387 size_t buf_size,
388 IPC::Sender* sender) {
389 scoped_ptr<base::SharedMemory> shared_buf;
390 #if defined(OS_WIN)
391 shared_buf.reset(new base::SharedMemory);
392 if (!shared_buf->CreateAndMapAnonymous(buf_size)) {
393 NOTREACHED();
394 return NULL;
396 #else
397 // On POSIX, we need to ask the browser to create the shared memory for us,
398 // since this is blocked by the sandbox.
399 base::SharedMemoryHandle shared_mem_handle;
400 if (sender->Send(new ChildProcessHostMsg_SyncAllocateSharedMemory(
401 buf_size, &shared_mem_handle))) {
402 if (base::SharedMemory::IsHandleValid(shared_mem_handle)) {
403 shared_buf.reset(new base::SharedMemory(shared_mem_handle, false));
404 if (!shared_buf->Map(buf_size)) {
405 NOTREACHED() << "Map failed";
406 return NULL;
408 } else {
409 NOTREACHED() << "Browser failed to allocate shared memory";
410 return NULL;
412 } else {
413 NOTREACHED() << "Browser allocation request message failed";
414 return NULL;
416 #endif
417 return shared_buf.release();
420 bool ChildThread::OnMessageReceived(const IPC::Message& msg) {
421 if (mojo_application_->OnMessageReceived(msg))
422 return true;
424 // Resource responses are sent to the resource dispatcher.
425 if (resource_dispatcher_->OnMessageReceived(msg))
426 return true;
427 if (socket_stream_dispatcher_->OnMessageReceived(msg))
428 return true;
429 if (websocket_dispatcher_->OnMessageReceived(msg))
430 return true;
431 if (file_system_dispatcher_->OnMessageReceived(msg))
432 return true;
434 bool handled = true;
435 IPC_BEGIN_MESSAGE_MAP(ChildThread, msg)
436 IPC_MESSAGE_HANDLER(ChildProcessMsg_Shutdown, OnShutdown)
437 #if defined(IPC_MESSAGE_LOG_ENABLED)
438 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetIPCLoggingEnabled,
439 OnSetIPCLoggingEnabled)
440 #endif
441 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetProfilerStatus,
442 OnSetProfilerStatus)
443 IPC_MESSAGE_HANDLER(ChildProcessMsg_GetChildProfilerData,
444 OnGetChildProfilerData)
445 IPC_MESSAGE_HANDLER(ChildProcessMsg_DumpHandles, OnDumpHandles)
446 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetProcessBackgrounded,
447 OnProcessBackgrounded)
448 #if defined(USE_TCMALLOC)
449 IPC_MESSAGE_HANDLER(ChildProcessMsg_GetTcmallocStats, OnGetTcmallocStats)
450 #endif
451 IPC_MESSAGE_UNHANDLED(handled = false)
452 IPC_END_MESSAGE_MAP()
454 if (handled)
455 return true;
457 if (msg.routing_id() == MSG_ROUTING_CONTROL)
458 return OnControlMessageReceived(msg);
460 return router_.OnMessageReceived(msg);
463 bool ChildThread::OnControlMessageReceived(const IPC::Message& msg) {
464 return false;
467 void ChildThread::OnShutdown() {
468 base::MessageLoop::current()->Quit();
471 #if defined(IPC_MESSAGE_LOG_ENABLED)
472 void ChildThread::OnSetIPCLoggingEnabled(bool enable) {
473 if (enable)
474 IPC::Logging::GetInstance()->Enable();
475 else
476 IPC::Logging::GetInstance()->Disable();
478 #endif // IPC_MESSAGE_LOG_ENABLED
480 void ChildThread::OnSetProfilerStatus(ThreadData::Status status) {
481 ThreadData::InitializeAndSetTrackingStatus(status);
484 void ChildThread::OnGetChildProfilerData(int sequence_number) {
485 tracked_objects::ProcessDataSnapshot process_data;
486 ThreadData::Snapshot(false, &process_data);
488 Send(new ChildProcessHostMsg_ChildProfilerData(sequence_number,
489 process_data));
492 void ChildThread::OnDumpHandles() {
493 #if defined(OS_WIN)
494 scoped_refptr<HandleEnumerator> handle_enum(
495 new HandleEnumerator(
496 CommandLine::ForCurrentProcess()->HasSwitch(
497 switches::kAuditAllHandles)));
498 handle_enum->EnumerateHandles();
499 Send(new ChildProcessHostMsg_DumpHandlesDone);
500 #else
501 NOTIMPLEMENTED();
502 #endif
505 #if defined(USE_TCMALLOC)
506 void ChildThread::OnGetTcmallocStats() {
507 std::string result;
508 char buffer[1024 * 32];
509 base::allocator::GetStats(buffer, sizeof(buffer));
510 result.append(buffer);
511 Send(new ChildProcessHostMsg_TcmallocStats(result));
513 #endif
515 ChildThread* ChildThread::current() {
516 return g_lazy_tls.Pointer()->Get();
519 #if defined(OS_ANDROID)
520 // The method must NOT be called on the child thread itself.
521 // It may block the child thread if so.
522 void ChildThread::ShutdownThread() {
523 DCHECK(!ChildThread::current()) <<
524 "this method should NOT be called from child thread itself";
526 base::AutoLock lock(g_lazy_child_thread_lock.Get());
527 while (!g_child_thread)
528 g_lazy_child_thread_cv.Get().Wait();
530 DCHECK_NE(base::MessageLoop::current(), g_child_thread->message_loop());
531 g_child_thread->message_loop()->PostTask(
532 FROM_HERE, base::Bind(&QuitMainThreadMessageLoop));
534 #endif
536 void ChildThread::OnProcessFinalRelease() {
537 if (on_channel_error_called_) {
538 base::MessageLoop::current()->Quit();
539 return;
542 // The child process shutdown sequence is a request response based mechanism,
543 // where we send out an initial feeler request to the child process host
544 // instance in the browser to verify if it's ok to shutdown the child process.
545 // The browser then sends back a response if it's ok to shutdown. This avoids
546 // race conditions if the process refcount is 0 but there's an IPC message
547 // inflight that would addref it.
548 Send(new ChildProcessHostMsg_ShutdownRequest);
551 void ChildThread::EnsureConnected() {
552 VLOG(0) << "ChildThread::EnsureConnected()";
553 base::KillProcess(base::GetCurrentProcessHandle(), 0, false);
556 void ChildThread::OnProcessBackgrounded(bool background) {
557 // Set timer slack to maximum on main thread when in background.
558 base::TimerSlack timer_slack = base::TIMER_SLACK_NONE;
559 if (background)
560 timer_slack = base::TIMER_SLACK_MAXIMUM;
561 base::MessageLoop::current()->SetTimerSlack(timer_slack);
563 #ifdef OS_WIN
564 // Windows Vista+ has a fancy process backgrounding mode that can only be set
565 // from within the process.
566 base::Process::Current().SetProcessBackgrounded(background);
567 #endif // OS_WIN
570 } // namespace content