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"
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"
44 #include "content/common/handle_enumerator_win.h"
47 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
48 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
51 using tracked_objects::ThreadData;
56 // How long to wait for a connection to the browser process before giving up.
57 const int kConnectionTimeoutS = 15;
59 base::LazyInstance<base::ThreadLocalPointer<ChildThread> > g_lazy_tls =
60 LAZY_INSTANCE_INITIALIZER;
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.
67 class SuicideOnChannelErrorFilter : public IPC::ChannelProxy::MessageFilter {
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.
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).
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
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
99 virtual ~SuicideOnChannelErrorFilter() {}
104 #if defined(OS_ANDROID)
105 ChildThread* g_child_thread = NULL;
107 // A lock protects g_child_thread.
108 base::LazyInstance<base::Lock> g_lazy_child_thread_lock =
109 LAZY_INSTANCE_INITIALIZER;
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());
121 static void Delete(base::ConditionVariable* instance) {
122 instance->~ConditionVariable();
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;
131 void QuitMainThreadMessageLoop() {
132 base::MessageLoop::current()->Quit();
139 ChildThread::ChildThread()
140 : channel_connected_factory_(this),
141 in_browser_process_(false) {
142 channel_name_ = CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
143 switches::kProcessChannelID);
147 ChildThread::ChildThread(const std::string& channel_name)
148 : channel_name_(channel_name),
149 channel_connected_factory_(this),
150 in_browser_process_(true) {
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();
165 new IPC::SyncChannel(channel_name_,
166 IPC::Channel::MODE_CLIENT,
168 ChildProcess::current()->io_message_loop_proxy(),
170 ChildProcess::current()->GetShutDownEvent()));
171 #ifdef IPC_MESSAGE_LOG_ENABLED
172 if (!in_browser_process_)
173 IPC::Logging::GetInstance()->SetIPCSender(this);
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());
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());
186 histogram_message_filter_ = new ChildHistogramMessageFilter();
187 resource_message_filter_ =
188 new ChildResourceMessageFilter(resource_dispatcher());
190 service_worker_message_filter_ =
191 new ServiceWorkerMessageFilter(thread_safe_sender_.get());
192 service_worker_dispatcher_.reset(
193 new ServiceWorkerDispatcher(thread_safe_sender_.get()));
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()));
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());
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());
214 power_monitor_.reset(new base::PowerMonitor(
215 power_monitor_source.PassAs<base::PowerMonitorSource>()));
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());
225 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kTraceToConsole)) {
226 std::string category_string =
227 CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
228 switches::kTraceToConsole);
230 if (!category_string.size())
231 category_string = "*";
233 base::debug::TraceLog::GetInstance()->SetEnabled(
234 base::debug::CategoryFilter(category_string),
235 base::debug::TraceLog::ECHO_TO_CONSOLE);
238 base::MessageLoop::current()->PostDelayedTask(
240 base::Bind(&ChildThread::EnsureConnected,
241 channel_connected_factory_.GetWeakPtr()),
242 base::TimeDelta::FromSeconds(kConnectionTimeoutS));
244 #if defined(OS_ANDROID)
246 base::AutoLock lock(g_lazy_child_thread_lock.Get());
247 g_child_thread = this;
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();
254 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
255 trace_memory_controller_.reset(new base::debug::TraceMemoryController(
256 message_loop_->message_loop_proxy(),
257 ::HeapProfilerWithPseudoStackStart,
263 ChildThread::~ChildThread() {
264 #ifdef IPC_MESSAGE_LOG_ENABLED
265 IPC::Logging::GetInstance()->SetIPCSender(NULL);
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());
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);
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();
291 void ChildThread::OnChannelConnected(int32 peer_pid) {
292 channel_connected_factory_.InvalidateWeakPtrs();
295 void ChildThread::OnChannelError() {
296 set_on_channel_error_called(true);
297 base::MessageLoop::current()->Quit();
300 bool ChildThread::Send(IPC::Message* msg) {
301 DCHECK(base::MessageLoop::current() == message_loop());
307 return channel_->Send(msg);
310 void ChildThread::AddRoute(int32 routing_id, IPC::Listener* listener) {
311 DCHECK(base::MessageLoop::current() == message_loop());
313 router_.AddRoute(routing_id, listener);
316 void ChildThread::RemoveRoute(int32 routing_id) {
317 DCHECK(base::MessageLoop::current() == message_loop());
319 router_.RemoveRoute(routing_id);
322 webkit_glue::ResourceLoaderBridge* ChildThread::CreateBridge(
323 const webkit_glue::ResourceLoaderBridge::RequestInfo& request_info) {
324 return resource_dispatcher()->CreateBridge(request_info);
327 base::SharedMemory* ChildThread::AllocateSharedMemory(size_t buf_size) {
328 return AllocateSharedMemory(buf_size, this);
332 base::SharedMemory* ChildThread::AllocateSharedMemory(
334 IPC::Sender* sender) {
335 scoped_ptr<base::SharedMemory> shared_buf;
337 shared_buf.reset(new base::SharedMemory);
338 if (!shared_buf->CreateAndMapAnonymous(buf_size)) {
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";
355 NOTREACHED() << "Browser failed to allocate shared memory";
359 NOTREACHED() << "Browser allocation request message failed";
363 return shared_buf.release();
366 bool ChildThread::OnMessageReceived(const IPC::Message& msg) {
367 // Resource responses are sent to the resource dispatcher.
368 if (resource_dispatcher_->OnMessageReceived(msg))
370 if (socket_stream_dispatcher_->OnMessageReceived(msg))
372 if (websocket_dispatcher_->OnMessageReceived(msg))
374 if (file_system_dispatcher_->OnMessageReceived(msg))
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)
384 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetProfilerStatus,
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)
392 IPC_MESSAGE_UNHANDLED(handled = false)
393 IPC_END_MESSAGE_MAP()
398 if (msg.routing_id() == MSG_ROUTING_CONTROL)
399 return OnControlMessageReceived(msg);
401 return router_.OnMessageReceived(msg);
404 bool ChildThread::OnControlMessageReceived(const IPC::Message& msg) {
408 void ChildThread::OnShutdown() {
409 base::MessageLoop::current()->Quit();
412 #if defined(IPC_MESSAGE_LOG_ENABLED)
413 void ChildThread::OnSetIPCLoggingEnabled(bool enable) {
415 IPC::Logging::GetInstance()->Enable();
417 IPC::Logging::GetInstance()->Disable();
419 #endif // IPC_MESSAGE_LOG_ENABLED
421 void ChildThread::OnSetProfilerStatus(ThreadData::Status status) {
422 ThreadData::InitializeAndSetTrackingStatus(status);
425 void ChildThread::OnGetChildProfilerData(int sequence_number) {
426 tracked_objects::ProcessDataSnapshot process_data;
427 ThreadData::Snapshot(false, &process_data);
429 Send(new ChildProcessHostMsg_ChildProfilerData(sequence_number,
433 void ChildThread::OnDumpHandles() {
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);
447 #if defined(USE_TCMALLOC)
448 void ChildThread::OnGetTcmallocStats() {
450 char buffer[1024 * 32];
451 base::allocator::GetStats(buffer, sizeof(buffer));
452 result.append(buffer);
453 Send(new ChildProcessHostMsg_TcmallocStats(result));
457 ChildThread* ChildThread::current() {
458 return g_lazy_tls.Pointer()->Get();
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";
468 base::AutoLock lock(g_lazy_child_thread_lock.Get());
469 while (!g_child_thread)
470 g_lazy_child_thread_cv.Get().Wait();
472 DCHECK_NE(base::MessageLoop::current(), g_child_thread->message_loop());
473 g_child_thread->message_loop()->PostTask(
474 FROM_HERE, base::Bind(&QuitMainThreadMessageLoop));
479 void ChildThread::OnProcessFinalRelease() {
480 if (on_channel_error_called_) {
481 base::MessageLoop::current()->Quit();
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);
494 void ChildThread::EnsureConnected() {
495 LOG(INFO) << "ChildThread::EnsureConnected()";
496 base::KillProcess(base::GetCurrentProcessHandle(), 0, false);
499 } // namespace content