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