1852dc902e961d9a602ff5f7d88fb7551ee46eea
[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/process/kill.h"
20 #include "base/process/process_handle.h"
21 #include "base/strings/string_util.h"
22 #include "base/synchronization/condition_variable.h"
23 #include "base/synchronization/lock.h"
24 #include "base/threading/thread_local.h"
25 #include "base/tracked_objects.h"
26 #include "components/tracing/child_trace_message_filter.h"
27 #include "content/child/child_histogram_message_filter.h"
28 #include "content/child/child_process.h"
29 #include "content/child/child_resource_message_filter.h"
30 #include "content/child/child_shared_bitmap_manager.h"
31 #include "content/child/fileapi/file_system_dispatcher.h"
32 #include "content/child/power_monitor_broadcast_source.h"
33 #include "content/child/quota_dispatcher.h"
34 #include "content/child/quota_message_filter.h"
35 #include "content/child/resource_dispatcher.h"
36 #include "content/child/service_worker/service_worker_dispatcher.h"
37 #include "content/child/service_worker/service_worker_message_filter.h"
38 #include "content/child/socket_stream_dispatcher.h"
39 #include "content/child/thread_safe_sender.h"
40 #include "content/child/websocket_dispatcher.h"
41 #include "content/common/child_process_messages.h"
42 #include "content/public/common/content_switches.h"
43 #include "ipc/ipc_logging.h"
44 #include "ipc/ipc_switches.h"
45 #include "ipc/ipc_sync_channel.h"
46 #include "ipc/ipc_sync_message_filter.h"
47 #include "webkit/child/resource_loader_bridge.h"
48
49 #if defined(OS_WIN)
50 #include "content/common/handle_enumerator_win.h"
51 #endif
52
53 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
54 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
55 #endif
56
57 using tracked_objects::ThreadData;
58
59 namespace content {
60 namespace {
61
62 // How long to wait for a connection to the browser process before giving up.
63 const int kConnectionTimeoutS = 15;
64
65 base::LazyInstance<base::ThreadLocalPointer<ChildThread> > g_lazy_tls =
66     LAZY_INSTANCE_INITIALIZER;
67
68 // This isn't needed on Windows because there the sandbox's job object
69 // terminates child processes automatically. For unsandboxed processes (i.e.
70 // plugins), PluginThread has EnsureTerminateMessageFilter.
71 #if defined(OS_POSIX)
72
73 // A thread delegate that waits for |duration| and then signals the process
74 // with SIGALRM.
75 class WaitAndExitDelegate : public base::PlatformThread::Delegate {
76  public:
77   explicit WaitAndExitDelegate(base::TimeDelta duration)
78       : duration_(duration) {}
79   virtual ~WaitAndExitDelegate() OVERRIDE {}
80
81   virtual void ThreadMain() OVERRIDE {
82     base::PlatformThread::Sleep(duration_);
83     // This used to be implemented with alarm(2). Make sure to not break
84     // anything that requires the process being signaled.
85     CHECK_EQ(0, raise(SIGALRM));
86
87     base::PlatformThread::Sleep((base::TimeDelta::FromSeconds(10)));
88     // If something erroneously blocked SIGALRM, this will trigger.
89     NOTREACHED();
90     _exit(0);
91   }
92
93  private:
94   const base::TimeDelta duration_;
95   DISALLOW_COPY_AND_ASSIGN(WaitAndExitDelegate);
96 };
97
98 // This is similar to using alarm(2), except it will spawn a thread
99 // which will sleep for |duration| before raising SIGALRM.
100 bool CreateAlarmThread(base::TimeDelta duration) {
101   scoped_ptr<WaitAndExitDelegate> delegate(new WaitAndExitDelegate(duration));
102
103   const bool thread_created = base::PlatformThread::CreateNonJoinable(
104       0 /* stack_size */, delegate.get());
105   if (!thread_created)
106     return false;
107
108   // A non joinable thread has been created. The thread will either terminate
109   // the process or will be terminated by the process. Therefore, keep the
110   // delegate object alive for the lifetime of the process.
111   WaitAndExitDelegate* leaking_delegate = delegate.release();
112   ANNOTATE_LEAKING_OBJECT_PTR(leaking_delegate);
113   ignore_result(leaking_delegate);
114   return true;
115 }
116
117 class SuicideOnChannelErrorFilter : public IPC::ChannelProxy::MessageFilter {
118  public:
119   // IPC::ChannelProxy::MessageFilter
120   virtual 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.
124     //
125     // This is because the terminate signals (ViewMsg_ShouldClose and the error
126     // from the IPC channel) are routed to the main message loop but never
127     // processed (because that message loop is stuck in V8).
128     //
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.
133     //
134     // So, we install a filter on the channel so that we can process this event
135     // here and kill the process.
136     if (CommandLine::ForCurrentProcess()->
137         HasSwitch(switches::kChildCleanExit)) {
138       // If clean exit is requested, we want to kill this process after giving
139       // it 60 seconds to run exit handlers. Exit handlers may including ones
140       // that write profile data to disk (which happens under profile collection
141       // mode).
142       CHECK(CreateAlarmThread(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     }
151   }
152
153  protected:
154   virtual ~SuicideOnChannelErrorFilter() {}
155 };
156
157 #endif  // OS(POSIX)
158
159 #if defined(OS_ANDROID)
160 ChildThread* g_child_thread = NULL;
161
162 // A lock protects g_child_thread.
163 base::LazyInstance<base::Lock> g_lazy_child_thread_lock =
164     LAZY_INSTANCE_INITIALIZER;
165
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
174
175   static base::ConditionVariable* New(void* instance) {
176     return new (instance) base::ConditionVariable(
177         g_lazy_child_thread_lock.Pointer());
178   }
179   static void Delete(base::ConditionVariable* instance) {
180     instance->~ConditionVariable();
181   }
182 };
183
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;
188
189 void QuitMainThreadMessageLoop() {
190   base::MessageLoop::current()->Quit();
191 }
192
193 #endif
194
195 }  // namespace
196
197 ChildThread::ChildThreadMessageRouter::ChildThreadMessageRouter(
198     IPC::Sender* sender)
199     : sender_(sender) {}
200
201 bool ChildThread::ChildThreadMessageRouter::Send(IPC::Message* msg) {
202   return sender_->Send(msg);
203 }
204
205 ChildThread::ChildThread()
206     : router_(this),
207       channel_connected_factory_(this),
208       in_browser_process_(false) {
209   channel_name_ = CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
210       switches::kProcessChannelID);
211   Init();
212 }
213
214 ChildThread::ChildThread(const std::string& channel_name)
215     : channel_name_(channel_name),
216       router_(this),
217       channel_connected_factory_(this),
218       in_browser_process_(true) {
219   Init();
220 }
221
222 void ChildThread::Init() {
223   g_lazy_tls.Pointer()->Set(this);
224   on_channel_error_called_ = false;
225   message_loop_ = base::MessageLoop::current();
226 #ifdef IPC_MESSAGE_LOG_ENABLED
227   // We must make sure to instantiate the IPC Logger *before* we create the
228   // channel, otherwise we can get a callback on the IO thread which creates
229   // the logger, and the logger does not like being created on the IO thread.
230   IPC::Logging::GetInstance();
231 #endif
232   channel_.reset(
233       new IPC::SyncChannel(channel_name_,
234                            IPC::Channel::MODE_CLIENT,
235                            this,
236                            ChildProcess::current()->io_message_loop_proxy(),
237                            true,
238                            ChildProcess::current()->GetShutDownEvent()));
239 #ifdef IPC_MESSAGE_LOG_ENABLED
240   if (!in_browser_process_)
241     IPC::Logging::GetInstance()->SetIPCSender(this);
242 #endif
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(new tracing::ChildTraceMessageFilter(
271       ChildProcess::current()->io_message_loop_proxy()));
272   channel_->AddFilter(resource_message_filter_.get());
273   channel_->AddFilter(quota_message_filter_->GetFilter());
274   channel_->AddFilter(service_worker_message_filter_->GetFilter());
275
276   // In single process mode we may already have a power monitor
277   if (!base::PowerMonitor::Get()) {
278     scoped_ptr<PowerMonitorBroadcastSource> power_monitor_source(
279       new PowerMonitorBroadcastSource());
280     channel_->AddFilter(power_monitor_source->GetMessageFilter());
281
282     power_monitor_.reset(new base::PowerMonitor(
283         power_monitor_source.PassAs<base::PowerMonitorSource>()));
284   }
285
286 #if defined(OS_POSIX)
287   // Check that --process-type is specified so we don't do this in unit tests
288   // and single-process mode.
289   if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kProcessType))
290     channel_->AddFilter(new SuicideOnChannelErrorFilter());
291 #endif
292
293   base::MessageLoop::current()->PostDelayedTask(
294       FROM_HERE,
295       base::Bind(&ChildThread::EnsureConnected,
296                  channel_connected_factory_.GetWeakPtr()),
297       base::TimeDelta::FromSeconds(kConnectionTimeoutS));
298
299 #if defined(OS_ANDROID)
300   {
301     base::AutoLock lock(g_lazy_child_thread_lock.Get());
302     g_child_thread = this;
303   }
304   // Signalling without locking is fine here because only
305   // one thread can wait on the condition variable.
306   g_lazy_child_thread_cv.Get().Signal();
307 #endif
308
309 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
310   trace_memory_controller_.reset(new base::debug::TraceMemoryController(
311       message_loop_->message_loop_proxy(),
312       ::HeapProfilerWithPseudoStackStart,
313       ::HeapProfilerStop,
314       ::GetHeapProfile));
315 #endif
316
317   shared_bitmap_manager_.reset(
318       new ChildSharedBitmapManager(thread_safe_sender()));
319 }
320
321 ChildThread::~ChildThread() {
322 #ifdef IPC_MESSAGE_LOG_ENABLED
323   IPC::Logging::GetInstance()->SetIPCSender(NULL);
324 #endif
325
326   channel_->RemoveFilter(histogram_message_filter_.get());
327   channel_->RemoveFilter(sync_message_filter_.get());
328
329   // The ChannelProxy object caches a pointer to the IPC thread, so need to
330   // reset it as it's not guaranteed to outlive this object.
331   // NOTE: this also has the side-effect of not closing the main IPC channel to
332   // the browser process.  This is needed because this is the signal that the
333   // browser uses to know that this process has died, so we need it to be alive
334   // until this process is shut down, and the OS closes the handle
335   // automatically.  We used to watch the object handle on Windows to do this,
336   // but it wasn't possible to do so on POSIX.
337   channel_->ClearIPCTaskRunner();
338   g_lazy_tls.Pointer()->Set(NULL);
339 }
340
341 void ChildThread::Shutdown() {
342   // Delete objects that hold references to blink so derived classes can
343   // safely shutdown blink in their Shutdown implementation.
344   file_system_dispatcher_.reset();
345   quota_dispatcher_.reset();
346 }
347
348 void ChildThread::OnChannelConnected(int32 peer_pid) {
349   channel_connected_factory_.InvalidateWeakPtrs();
350 }
351
352 void ChildThread::OnChannelError() {
353   set_on_channel_error_called(true);
354   base::MessageLoop::current()->Quit();
355 }
356
357 bool ChildThread::Send(IPC::Message* msg) {
358   DCHECK(base::MessageLoop::current() == message_loop());
359   if (!channel_) {
360     delete msg;
361     return false;
362   }
363
364   return channel_->Send(msg);
365 }
366
367 MessageRouter* ChildThread::GetRouter() {
368   DCHECK(base::MessageLoop::current() == message_loop());
369   return &router_;
370 }
371
372 webkit_glue::ResourceLoaderBridge* ChildThread::CreateBridge(
373     const RequestInfo& request_info) {
374   return resource_dispatcher()->CreateBridge(request_info);
375 }
376
377 base::SharedMemory* ChildThread::AllocateSharedMemory(size_t buf_size) {
378   return AllocateSharedMemory(buf_size, this);
379 }
380
381 // static
382 base::SharedMemory* ChildThread::AllocateSharedMemory(
383     size_t buf_size,
384     IPC::Sender* sender) {
385   scoped_ptr<base::SharedMemory> shared_buf;
386 #if defined(OS_WIN)
387   shared_buf.reset(new base::SharedMemory);
388   if (!shared_buf->CreateAndMapAnonymous(buf_size)) {
389     NOTREACHED();
390     return NULL;
391   }
392 #else
393   // On POSIX, we need to ask the browser to create the shared memory for us,
394   // since this is blocked by the sandbox.
395   base::SharedMemoryHandle shared_mem_handle;
396   if (sender->Send(new ChildProcessHostMsg_SyncAllocateSharedMemory(
397                            buf_size, &shared_mem_handle))) {
398     if (base::SharedMemory::IsHandleValid(shared_mem_handle)) {
399       shared_buf.reset(new base::SharedMemory(shared_mem_handle, false));
400       if (!shared_buf->Map(buf_size)) {
401         NOTREACHED() << "Map failed";
402         return NULL;
403       }
404     } else {
405       NOTREACHED() << "Browser failed to allocate shared memory";
406       return NULL;
407     }
408   } else {
409     NOTREACHED() << "Browser allocation request message failed";
410     return NULL;
411   }
412 #endif
413   return shared_buf.release();
414 }
415
416 bool ChildThread::OnMessageReceived(const IPC::Message& msg) {
417   // Resource responses are sent to the resource dispatcher.
418   if (resource_dispatcher_->OnMessageReceived(msg))
419     return true;
420   if (socket_stream_dispatcher_->OnMessageReceived(msg))
421     return true;
422   if (websocket_dispatcher_->OnMessageReceived(msg))
423     return true;
424   if (file_system_dispatcher_->OnMessageReceived(msg))
425     return true;
426
427   bool handled = true;
428   IPC_BEGIN_MESSAGE_MAP(ChildThread, msg)
429     IPC_MESSAGE_HANDLER(ChildProcessMsg_Shutdown, OnShutdown)
430 #if defined(IPC_MESSAGE_LOG_ENABLED)
431     IPC_MESSAGE_HANDLER(ChildProcessMsg_SetIPCLoggingEnabled,
432                         OnSetIPCLoggingEnabled)
433 #endif
434     IPC_MESSAGE_HANDLER(ChildProcessMsg_SetProfilerStatus,
435                         OnSetProfilerStatus)
436     IPC_MESSAGE_HANDLER(ChildProcessMsg_GetChildProfilerData,
437                         OnGetChildProfilerData)
438     IPC_MESSAGE_HANDLER(ChildProcessMsg_DumpHandles, OnDumpHandles)
439 #if defined(USE_TCMALLOC)
440     IPC_MESSAGE_HANDLER(ChildProcessMsg_GetTcmallocStats, OnGetTcmallocStats)
441 #endif
442     IPC_MESSAGE_UNHANDLED(handled = false)
443   IPC_END_MESSAGE_MAP()
444
445   if (handled)
446     return true;
447
448   if (msg.routing_id() == MSG_ROUTING_CONTROL)
449     return OnControlMessageReceived(msg);
450
451   return router_.OnMessageReceived(msg);
452 }
453
454 bool ChildThread::OnControlMessageReceived(const IPC::Message& msg) {
455   return false;
456 }
457
458 void ChildThread::OnShutdown() {
459   base::MessageLoop::current()->Quit();
460 }
461
462 #if defined(IPC_MESSAGE_LOG_ENABLED)
463 void ChildThread::OnSetIPCLoggingEnabled(bool enable) {
464   if (enable)
465     IPC::Logging::GetInstance()->Enable();
466   else
467     IPC::Logging::GetInstance()->Disable();
468 }
469 #endif  //  IPC_MESSAGE_LOG_ENABLED
470
471 void ChildThread::OnSetProfilerStatus(ThreadData::Status status) {
472   ThreadData::InitializeAndSetTrackingStatus(status);
473 }
474
475 void ChildThread::OnGetChildProfilerData(int sequence_number) {
476   tracked_objects::ProcessDataSnapshot process_data;
477   ThreadData::Snapshot(false, &process_data);
478
479   Send(new ChildProcessHostMsg_ChildProfilerData(sequence_number,
480                                                  process_data));
481 }
482
483 void ChildThread::OnDumpHandles() {
484 #if defined(OS_WIN)
485   scoped_refptr<HandleEnumerator> handle_enum(
486       new HandleEnumerator(
487           CommandLine::ForCurrentProcess()->HasSwitch(
488               switches::kAuditAllHandles)));
489   handle_enum->EnumerateHandles();
490   Send(new ChildProcessHostMsg_DumpHandlesDone);
491 #else
492   NOTIMPLEMENTED();
493 #endif
494 }
495
496 #if defined(USE_TCMALLOC)
497 void ChildThread::OnGetTcmallocStats() {
498   std::string result;
499   char buffer[1024 * 32];
500   base::allocator::GetStats(buffer, sizeof(buffer));
501   result.append(buffer);
502   Send(new ChildProcessHostMsg_TcmallocStats(result));
503 }
504 #endif
505
506 ChildThread* ChildThread::current() {
507   return g_lazy_tls.Pointer()->Get();
508 }
509
510 #if defined(OS_ANDROID)
511 // The method must NOT be called on the child thread itself.
512 // It may block the child thread if so.
513 void ChildThread::ShutdownThread() {
514   DCHECK(!ChildThread::current()) <<
515       "this method should NOT be called from child thread itself";
516   {
517     base::AutoLock lock(g_lazy_child_thread_lock.Get());
518     while (!g_child_thread)
519       g_lazy_child_thread_cv.Get().Wait();
520   }
521   DCHECK_NE(base::MessageLoop::current(), g_child_thread->message_loop());
522   g_child_thread->message_loop()->PostTask(
523       FROM_HERE, base::Bind(&QuitMainThreadMessageLoop));
524 }
525 #endif
526
527 void ChildThread::OnProcessFinalRelease() {
528   if (on_channel_error_called_) {
529     base::MessageLoop::current()->Quit();
530     return;
531   }
532
533   // The child process shutdown sequence is a request response based mechanism,
534   // where we send out an initial feeler request to the child process host
535   // instance in the browser to verify if it's ok to shutdown the child process.
536   // The browser then sends back a response if it's ok to shutdown. This avoids
537   // race conditions if the process refcount is 0 but there's an IPC message
538   // inflight that would addref it.
539   Send(new ChildProcessHostMsg_ShutdownRequest);
540 }
541
542 void ChildThread::EnsureConnected() {
543   VLOG(0) << "ChildThread::EnsureConnected()";
544   base::KillProcess(base::GetCurrentProcessHandle(), 0, false);
545 }
546
547 }  // namespace content