- add sources.
[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 <string>
8
9 #include "base/allocator/allocator_extension.h"
10 #include "base/base_switches.h"
11 #include "base/command_line.h"
12 #include "base/lazy_instance.h"
13 #include "base/message_loop/message_loop.h"
14 #include "base/process/kill.h"
15 #include "base/process/process_handle.h"
16 #include "base/strings/string_util.h"
17 #include "base/synchronization/condition_variable.h"
18 #include "base/synchronization/lock.h"
19 #include "base/threading/thread_local.h"
20 #include "base/tracked_objects.h"
21 #include "components/tracing/child_trace_message_filter.h"
22 #include "content/child/child_histogram_message_filter.h"
23 #include "content/child/child_process.h"
24 #include "content/child/child_resource_message_filter.h"
25 #include "content/child/fileapi/file_system_dispatcher.h"
26 #include "content/child/power_monitor_broadcast_source.h"
27 #include "content/child/quota_dispatcher.h"
28 #include "content/child/quota_message_filter.h"
29 #include "content/child/resource_dispatcher.h"
30 #include "content/child/service_worker/service_worker_dispatcher.h"
31 #include "content/child/service_worker/service_worker_message_filter.h"
32 #include "content/child/socket_stream_dispatcher.h"
33 #include "content/child/thread_safe_sender.h"
34 #include "content/child/websocket_dispatcher.h"
35 #include "content/common/child_process_messages.h"
36 #include "content/public/common/content_switches.h"
37 #include "ipc/ipc_logging.h"
38 #include "ipc/ipc_switches.h"
39 #include "ipc/ipc_sync_channel.h"
40 #include "ipc/ipc_sync_message_filter.h"
41 #include "webkit/glue/webkit_glue.h"
42
43 #if defined(OS_WIN)
44 #include "content/common/handle_enumerator_win.h"
45 #endif
46
47 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
48 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
49 #endif
50
51 using tracked_objects::ThreadData;
52
53 namespace content {
54 namespace {
55
56 // How long to wait for a connection to the browser process before giving up.
57 const int kConnectionTimeoutS = 15;
58
59 base::LazyInstance<base::ThreadLocalPointer<ChildThread> > g_lazy_tls =
60     LAZY_INSTANCE_INITIALIZER;
61
62 // This isn't needed on Windows because there the sandbox's job object
63 // terminates child processes automatically. For unsandboxed processes (i.e.
64 // plugins), PluginThread has EnsureTerminateMessageFilter.
65 #if defined(OS_POSIX)
66
67 class SuicideOnChannelErrorFilter : public IPC::ChannelProxy::MessageFilter {
68  public:
69   // IPC::ChannelProxy::MessageFilter
70   virtual void OnChannelError() OVERRIDE {
71     // For renderer/worker processes:
72     // On POSIX, at least, one can install an unload handler which loops
73     // forever and leave behind a renderer process which eats 100% CPU forever.
74     //
75     // This is because the terminate signals (ViewMsg_ShouldClose and the error
76     // from the IPC channel) are routed to the main message loop but never
77     // processed (because that message loop is stuck in V8).
78     //
79     // One could make the browser SIGKILL the renderers, but that leaves open a
80     // large window where a browser failure (or a user, manually terminating
81     // the browser because "it's stuck") will leave behind a process eating all
82     // the CPU.
83     //
84     // So, we install a filter on the channel so that we can process this event
85     // here and kill the process.
86     if (CommandLine::ForCurrentProcess()->
87         HasSwitch(switches::kChildCleanExit)) {
88       // If clean exit is requested, we want to kill this process after giving
89       // it 60 seconds to run exit handlers. Exit handlers may including ones
90       // that write profile data to disk (which happens under profile collection
91       // mode).
92       alarm(60);
93     } else {
94       _exit(0);
95     }
96   }
97
98  protected:
99   virtual ~SuicideOnChannelErrorFilter() {}
100 };
101
102 #endif  // OS(POSIX)
103
104 #if defined(OS_ANDROID)
105 ChildThread* g_child_thread = NULL;
106
107 // A lock protects g_child_thread.
108 base::LazyInstance<base::Lock> g_lazy_child_thread_lock =
109     LAZY_INSTANCE_INITIALIZER;
110
111 // base::ConditionVariable has an explicit constructor that takes
112 // a base::Lock pointer as parameter. The base::DefaultLazyInstanceTraits
113 // doesn't handle the case. Thus, we need our own class here.
114 struct CondVarLazyInstanceTraits {
115   static const bool kRegisterOnExit = true;
116   static const bool kAllowedToAccessOnNonjoinableThread ALLOW_UNUSED = false;
117   static base::ConditionVariable* New(void* instance) {
118     return new (instance) base::ConditionVariable(
119         g_lazy_child_thread_lock.Pointer());
120   }
121   static void Delete(base::ConditionVariable* instance) {
122     instance->~ConditionVariable();
123   }
124 };
125
126 // A condition variable that synchronize threads initializing and waiting
127 // for g_child_thread.
128 base::LazyInstance<base::ConditionVariable, CondVarLazyInstanceTraits>
129     g_lazy_child_thread_cv = LAZY_INSTANCE_INITIALIZER;
130
131 void QuitMainThreadMessageLoop() {
132   base::MessageLoop::current()->Quit();
133 }
134
135 #endif
136
137 }  // namespace
138
139 ChildThread::ChildThread()
140     : channel_connected_factory_(this),
141       in_browser_process_(false) {
142   channel_name_ = CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
143       switches::kProcessChannelID);
144   Init();
145 }
146
147 ChildThread::ChildThread(const std::string& channel_name)
148     : channel_name_(channel_name),
149       channel_connected_factory_(this),
150       in_browser_process_(true) {
151   Init();
152 }
153
154 void ChildThread::Init() {
155   g_lazy_tls.Pointer()->Set(this);
156   on_channel_error_called_ = false;
157   message_loop_ = base::MessageLoop::current();
158 #ifdef IPC_MESSAGE_LOG_ENABLED
159   // We must make sure to instantiate the IPC Logger *before* we create the
160   // channel, otherwise we can get a callback on the IO thread which creates
161   // the logger, and the logger does not like being created on the IO thread.
162   IPC::Logging::GetInstance();
163 #endif
164   channel_.reset(
165       new IPC::SyncChannel(channel_name_,
166                            IPC::Channel::MODE_CLIENT,
167                            this,
168                            ChildProcess::current()->io_message_loop_proxy(),
169                            true,
170                            ChildProcess::current()->GetShutDownEvent()));
171 #ifdef IPC_MESSAGE_LOG_ENABLED
172   if (!in_browser_process_)
173     IPC::Logging::GetInstance()->SetIPCSender(this);
174 #endif
175
176   sync_message_filter_ =
177       new IPC::SyncMessageFilter(ChildProcess::current()->GetShutDownEvent());
178   thread_safe_sender_ = new ThreadSafeSender(
179       base::MessageLoopProxy::current().get(), sync_message_filter_.get());
180
181   resource_dispatcher_.reset(new ResourceDispatcher(this));
182   socket_stream_dispatcher_.reset(new SocketStreamDispatcher());
183   websocket_dispatcher_.reset(new WebSocketDispatcher);
184   file_system_dispatcher_.reset(new FileSystemDispatcher());
185
186   histogram_message_filter_ = new ChildHistogramMessageFilter();
187   resource_message_filter_ =
188       new ChildResourceMessageFilter(resource_dispatcher());
189
190   service_worker_message_filter_ =
191       new ServiceWorkerMessageFilter(thread_safe_sender_.get());
192   service_worker_dispatcher_.reset(
193       new ServiceWorkerDispatcher(thread_safe_sender_.get()));
194
195   quota_message_filter_ =
196       new QuotaMessageFilter(thread_safe_sender_.get());
197   quota_dispatcher_.reset(new QuotaDispatcher(thread_safe_sender_.get(),
198                                               quota_message_filter_.get()));
199
200   channel_->AddFilter(histogram_message_filter_.get());
201   channel_->AddFilter(sync_message_filter_.get());
202   channel_->AddFilter(new tracing::ChildTraceMessageFilter(
203       ChildProcess::current()->io_message_loop_proxy()));
204   channel_->AddFilter(resource_message_filter_.get());
205   channel_->AddFilter(quota_message_filter_.get());
206   channel_->AddFilter(service_worker_message_filter_.get());
207
208   // In single process mode we may already have a power monitor
209   if (!base::PowerMonitor::Get()) {
210     scoped_ptr<PowerMonitorBroadcastSource> power_monitor_source(
211       new PowerMonitorBroadcastSource());
212     channel_->AddFilter(power_monitor_source->GetMessageFilter());
213
214     power_monitor_.reset(new base::PowerMonitor(
215         power_monitor_source.PassAs<base::PowerMonitorSource>()));
216   }
217
218 #if defined(OS_POSIX)
219   // Check that --process-type is specified so we don't do this in unit tests
220   // and single-process mode.
221   if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kProcessType))
222     channel_->AddFilter(new SuicideOnChannelErrorFilter());
223 #endif
224
225   if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kTraceToConsole)) {
226     std::string category_string =
227         CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
228             switches::kTraceToConsole);
229
230     if (!category_string.size())
231       category_string = "*";
232
233     base::debug::TraceLog::GetInstance()->SetEnabled(
234         base::debug::CategoryFilter(category_string),
235         base::debug::TraceLog::ECHO_TO_CONSOLE);
236   }
237
238   base::MessageLoop::current()->PostDelayedTask(
239       FROM_HERE,
240       base::Bind(&ChildThread::EnsureConnected,
241                  channel_connected_factory_.GetWeakPtr()),
242       base::TimeDelta::FromSeconds(kConnectionTimeoutS));
243
244 #if defined(OS_ANDROID)
245   {
246     base::AutoLock lock(g_lazy_child_thread_lock.Get());
247     g_child_thread = this;
248   }
249   // Signalling without locking is fine here because only
250   // one thread can wait on the condition variable.
251   g_lazy_child_thread_cv.Get().Signal();
252 #endif
253
254 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
255   trace_memory_controller_.reset(new base::debug::TraceMemoryController(
256       message_loop_->message_loop_proxy(),
257       ::HeapProfilerWithPseudoStackStart,
258       ::HeapProfilerStop,
259       ::GetHeapProfile));
260 #endif
261 }
262
263 ChildThread::~ChildThread() {
264 #ifdef IPC_MESSAGE_LOG_ENABLED
265   IPC::Logging::GetInstance()->SetIPCSender(NULL);
266 #endif
267
268   channel_->RemoveFilter(service_worker_message_filter_.get());
269   channel_->RemoveFilter(quota_message_filter_.get());
270   channel_->RemoveFilter(histogram_message_filter_.get());
271   channel_->RemoveFilter(sync_message_filter_.get());
272
273   // The ChannelProxy object caches a pointer to the IPC thread, so need to
274   // reset it as it's not guaranteed to outlive this object.
275   // NOTE: this also has the side-effect of not closing the main IPC channel to
276   // the browser process.  This is needed because this is the signal that the
277   // browser uses to know that this process has died, so we need it to be alive
278   // until this process is shut down, and the OS closes the handle
279   // automatically.  We used to watch the object handle on Windows to do this,
280   // but it wasn't possible to do so on POSIX.
281   channel_->ClearIPCTaskRunner();
282   g_lazy_tls.Pointer()->Set(NULL);
283 }
284
285 void ChildThread::Shutdown() {
286   // Delete objects that hold references to blink so derived classes can
287   // safely shutdown blink in their Shutdown implementation.
288   file_system_dispatcher_.reset();
289 }
290
291 void ChildThread::OnChannelConnected(int32 peer_pid) {
292   channel_connected_factory_.InvalidateWeakPtrs();
293 }
294
295 void ChildThread::OnChannelError() {
296   set_on_channel_error_called(true);
297   base::MessageLoop::current()->Quit();
298 }
299
300 bool ChildThread::Send(IPC::Message* msg) {
301   DCHECK(base::MessageLoop::current() == message_loop());
302   if (!channel_) {
303     delete msg;
304     return false;
305   }
306
307   return channel_->Send(msg);
308 }
309
310 void ChildThread::AddRoute(int32 routing_id, IPC::Listener* listener) {
311   DCHECK(base::MessageLoop::current() == message_loop());
312
313   router_.AddRoute(routing_id, listener);
314 }
315
316 void ChildThread::RemoveRoute(int32 routing_id) {
317   DCHECK(base::MessageLoop::current() == message_loop());
318
319   router_.RemoveRoute(routing_id);
320 }
321
322 webkit_glue::ResourceLoaderBridge* ChildThread::CreateBridge(
323     const webkit_glue::ResourceLoaderBridge::RequestInfo& request_info) {
324   return resource_dispatcher()->CreateBridge(request_info);
325 }
326
327 base::SharedMemory* ChildThread::AllocateSharedMemory(size_t buf_size) {
328   return AllocateSharedMemory(buf_size, this);
329 }
330
331 // static
332 base::SharedMemory* ChildThread::AllocateSharedMemory(
333     size_t buf_size,
334     IPC::Sender* sender) {
335   scoped_ptr<base::SharedMemory> shared_buf;
336 #if defined(OS_WIN)
337   shared_buf.reset(new base::SharedMemory);
338   if (!shared_buf->CreateAndMapAnonymous(buf_size)) {
339     NOTREACHED();
340     return NULL;
341   }
342 #else
343   // On POSIX, we need to ask the browser to create the shared memory for us,
344   // since this is blocked by the sandbox.
345   base::SharedMemoryHandle shared_mem_handle;
346   if (sender->Send(new ChildProcessHostMsg_SyncAllocateSharedMemory(
347                            buf_size, &shared_mem_handle))) {
348     if (base::SharedMemory::IsHandleValid(shared_mem_handle)) {
349       shared_buf.reset(new base::SharedMemory(shared_mem_handle, false));
350       if (!shared_buf->Map(buf_size)) {
351         NOTREACHED() << "Map failed";
352         return NULL;
353       }
354     } else {
355       NOTREACHED() << "Browser failed to allocate shared memory";
356       return NULL;
357     }
358   } else {
359     NOTREACHED() << "Browser allocation request message failed";
360     return NULL;
361   }
362 #endif
363   return shared_buf.release();
364 }
365
366 bool ChildThread::OnMessageReceived(const IPC::Message& msg) {
367   // Resource responses are sent to the resource dispatcher.
368   if (resource_dispatcher_->OnMessageReceived(msg))
369     return true;
370   if (socket_stream_dispatcher_->OnMessageReceived(msg))
371     return true;
372   if (websocket_dispatcher_->OnMessageReceived(msg))
373     return true;
374   if (file_system_dispatcher_->OnMessageReceived(msg))
375     return true;
376
377   bool handled = true;
378   IPC_BEGIN_MESSAGE_MAP(ChildThread, msg)
379     IPC_MESSAGE_HANDLER(ChildProcessMsg_Shutdown, OnShutdown)
380 #if defined(IPC_MESSAGE_LOG_ENABLED)
381     IPC_MESSAGE_HANDLER(ChildProcessMsg_SetIPCLoggingEnabled,
382                         OnSetIPCLoggingEnabled)
383 #endif
384     IPC_MESSAGE_HANDLER(ChildProcessMsg_SetProfilerStatus,
385                         OnSetProfilerStatus)
386     IPC_MESSAGE_HANDLER(ChildProcessMsg_GetChildProfilerData,
387                         OnGetChildProfilerData)
388     IPC_MESSAGE_HANDLER(ChildProcessMsg_DumpHandles, OnDumpHandles)
389 #if defined(USE_TCMALLOC)
390     IPC_MESSAGE_HANDLER(ChildProcessMsg_GetTcmallocStats, OnGetTcmallocStats)
391 #endif
392     IPC_MESSAGE_UNHANDLED(handled = false)
393   IPC_END_MESSAGE_MAP()
394
395   if (handled)
396     return true;
397
398   if (msg.routing_id() == MSG_ROUTING_CONTROL)
399     return OnControlMessageReceived(msg);
400
401   return router_.OnMessageReceived(msg);
402 }
403
404 bool ChildThread::OnControlMessageReceived(const IPC::Message& msg) {
405   return false;
406 }
407
408 void ChildThread::OnShutdown() {
409   base::MessageLoop::current()->Quit();
410 }
411
412 #if defined(IPC_MESSAGE_LOG_ENABLED)
413 void ChildThread::OnSetIPCLoggingEnabled(bool enable) {
414   if (enable)
415     IPC::Logging::GetInstance()->Enable();
416   else
417     IPC::Logging::GetInstance()->Disable();
418 }
419 #endif  //  IPC_MESSAGE_LOG_ENABLED
420
421 void ChildThread::OnSetProfilerStatus(ThreadData::Status status) {
422   ThreadData::InitializeAndSetTrackingStatus(status);
423 }
424
425 void ChildThread::OnGetChildProfilerData(int sequence_number) {
426   tracked_objects::ProcessDataSnapshot process_data;
427   ThreadData::Snapshot(false, &process_data);
428
429   Send(new ChildProcessHostMsg_ChildProfilerData(sequence_number,
430                                                  process_data));
431 }
432
433 void ChildThread::OnDumpHandles() {
434 #if defined(OS_WIN)
435   scoped_refptr<HandleEnumerator> handle_enum(
436       new HandleEnumerator(
437           CommandLine::ForCurrentProcess()->HasSwitch(
438               switches::kAuditAllHandles)));
439   handle_enum->EnumerateHandles();
440   Send(new ChildProcessHostMsg_DumpHandlesDone);
441   return;
442 #endif
443
444   NOTIMPLEMENTED();
445 }
446
447 #if defined(USE_TCMALLOC)
448 void ChildThread::OnGetTcmallocStats() {
449   std::string result;
450   char buffer[1024 * 32];
451   base::allocator::GetStats(buffer, sizeof(buffer));
452   result.append(buffer);
453   Send(new ChildProcessHostMsg_TcmallocStats(result));
454 }
455 #endif
456
457 ChildThread* ChildThread::current() {
458   return g_lazy_tls.Pointer()->Get();
459 }
460
461 #if defined(OS_ANDROID)
462 // The method must NOT be called on the child thread itself.
463 // It may block the child thread if so.
464 void ChildThread::ShutdownThread() {
465   DCHECK(!ChildThread::current()) <<
466       "this method should NOT be called from child thread itself";
467   {
468     base::AutoLock lock(g_lazy_child_thread_lock.Get());
469     while (!g_child_thread)
470       g_lazy_child_thread_cv.Get().Wait();
471   }
472   DCHECK_NE(base::MessageLoop::current(), g_child_thread->message_loop());
473   g_child_thread->message_loop()->PostTask(
474       FROM_HERE, base::Bind(&QuitMainThreadMessageLoop));
475 }
476
477 #endif
478
479 void ChildThread::OnProcessFinalRelease() {
480   if (on_channel_error_called_) {
481     base::MessageLoop::current()->Quit();
482     return;
483   }
484
485   // The child process shutdown sequence is a request response based mechanism,
486   // where we send out an initial feeler request to the child process host
487   // instance in the browser to verify if it's ok to shutdown the child process.
488   // The browser then sends back a response if it's ok to shutdown. This avoids
489   // race conditions if the process refcount is 0 but there's an IPC message
490   // inflight that would addref it.
491   Send(new ChildProcessHostMsg_ShutdownRequest);
492 }
493
494 void ChildThread::EnsureConnected() {
495   LOG(INFO) << "ChildThread::EnsureConnected()";
496   base::KillProcess(base::GetCurrentProcessHandle(), 0, false);
497 }
498
499 }  // namespace content