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