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"
7 #include "base/allocator/allocator_extension.h"
8 #include "base/base_switches.h"
9 #include "base/command_line.h"
10 #include "base/lazy_instance.h"
11 #include "base/message_loop/message_loop.h"
12 #include "base/process/kill.h"
13 #include "base/process/process_handle.h"
14 #include "base/strings/string_util.h"
15 #include "base/threading/thread_local.h"
16 #include "base/tracked_objects.h"
17 #include "components/tracing/child_trace_message_filter.h"
18 #include "content/child/child_histogram_message_filter.h"
19 #include "content/child/child_process.h"
20 #include "content/child/child_resource_message_filter.h"
21 #include "content/child/fileapi/file_system_dispatcher.h"
22 #include "content/child/power_monitor_broadcast_source.h"
23 #include "content/child/quota_dispatcher.h"
24 #include "content/child/quota_message_filter.h"
25 #include "content/child/resource_dispatcher.h"
26 #include "content/child/socket_stream_dispatcher.h"
27 #include "content/child/thread_safe_sender.h"
28 #include "content/common/child_process_messages.h"
29 #include "content/public/common/content_switches.h"
30 #include "ipc/ipc_logging.h"
31 #include "ipc/ipc_switches.h"
32 #include "ipc/ipc_sync_channel.h"
33 #include "ipc/ipc_sync_message_filter.h"
34 #include "webkit/glue/webkit_glue.h"
37 #include "content/common/handle_enumerator_win.h"
40 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
41 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
44 using tracked_objects::ThreadData
;
49 // How long to wait for a connection to the browser process before giving up.
50 const int kConnectionTimeoutS
= 15;
52 base::LazyInstance
<base::ThreadLocalPointer
<ChildThread
> > g_lazy_tls
=
53 LAZY_INSTANCE_INITIALIZER
;
55 // This isn't needed on Windows because there the sandbox's job object
56 // terminates child processes automatically. For unsandboxed processes (i.e.
57 // plugins), PluginThread has EnsureTerminateMessageFilter.
60 class SuicideOnChannelErrorFilter
: public IPC::ChannelProxy::MessageFilter
{
62 // IPC::ChannelProxy::MessageFilter
63 virtual void OnChannelError() OVERRIDE
{
64 // For renderer/worker processes:
65 // On POSIX, at least, one can install an unload handler which loops
66 // forever and leave behind a renderer process which eats 100% CPU forever.
68 // This is because the terminate signals (ViewMsg_ShouldClose and the error
69 // from the IPC channel) are routed to the main message loop but never
70 // processed (because that message loop is stuck in V8).
72 // One could make the browser SIGKILL the renderers, but that leaves open a
73 // large window where a browser failure (or a user, manually terminating
74 // the browser because "it's stuck") will leave behind a process eating all
77 // So, we install a filter on the channel so that we can process this event
78 // here and kill the process.
79 if (CommandLine::ForCurrentProcess()->
80 HasSwitch(switches::kChildCleanExit
)) {
81 // If clean exit is requested, we want to kill this process after giving
82 // it 60 seconds to run exit handlers. Exit handlers may including ones
83 // that write profile data to disk (which happens under profile collection
92 virtual ~SuicideOnChannelErrorFilter() {}
97 #if defined(OS_ANDROID)
98 ChildThread
* g_child_thread
;
100 void QuitMainThreadMessageLoop() {
101 base::MessageLoop::current()->Quit();
108 ChildThread::ChildThread()
109 : channel_connected_factory_(this) {
110 channel_name_
= CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
111 switches::kProcessChannelID
);
115 ChildThread::ChildThread(const std::string
& channel_name
)
116 : channel_name_(channel_name
),
117 channel_connected_factory_(this) {
121 void ChildThread::Init() {
122 g_lazy_tls
.Pointer()->Set(this);
123 on_channel_error_called_
= false;
124 message_loop_
= base::MessageLoop::current();
125 #ifdef IPC_MESSAGE_LOG_ENABLED
126 // We must make sure to instantiate the IPC Logger *before* we create the
127 // channel, otherwise we can get a callback on the IO thread which creates
128 // the logger, and the logger does not like being created on the IO thread.
129 IPC::Logging::GetInstance();
132 new IPC::SyncChannel(channel_name_
,
133 IPC::Channel::MODE_CLIENT
,
135 ChildProcess::current()->io_message_loop_proxy(),
137 ChildProcess::current()->GetShutDownEvent()));
138 #ifdef IPC_MESSAGE_LOG_ENABLED
139 IPC::Logging::GetInstance()->SetIPCSender(this);
142 sync_message_filter_
=
143 new IPC::SyncMessageFilter(ChildProcess::current()->GetShutDownEvent());
144 thread_safe_sender_
= new ThreadSafeSender(
145 base::MessageLoopProxy::current().get(), sync_message_filter_
.get());
147 resource_dispatcher_
.reset(new ResourceDispatcher(this));
148 socket_stream_dispatcher_
.reset(new SocketStreamDispatcher());
149 file_system_dispatcher_
.reset(new FileSystemDispatcher());
151 histogram_message_filter_
= new ChildHistogramMessageFilter();
152 resource_message_filter_
=
153 new ChildResourceMessageFilter(resource_dispatcher());
155 quota_message_filter_
=
156 new QuotaMessageFilter(thread_safe_sender_
.get());
157 quota_dispatcher_
.reset(new QuotaDispatcher(thread_safe_sender_
.get(),
158 quota_message_filter_
.get()));
160 channel_
->AddFilter(histogram_message_filter_
.get());
161 channel_
->AddFilter(sync_message_filter_
.get());
162 channel_
->AddFilter(new tracing::ChildTraceMessageFilter(
163 ChildProcess::current()->io_message_loop_proxy()));
164 channel_
->AddFilter(resource_message_filter_
.get());
165 channel_
->AddFilter(quota_message_filter_
.get());
167 // In single process mode we may already have a power monitor
168 if (!base::PowerMonitor::Get()) {
169 scoped_ptr
<PowerMonitorBroadcastSource
> power_monitor_source(
170 new PowerMonitorBroadcastSource());
171 channel_
->AddFilter(power_monitor_source
->GetMessageFilter());
173 power_monitor_
.reset(new base::PowerMonitor(
174 power_monitor_source
.PassAs
<base::PowerMonitorSource
>()));
177 #if defined(OS_POSIX)
178 // Check that --process-type is specified so we don't do this in unit tests
179 // and single-process mode.
180 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kProcessType
))
181 channel_
->AddFilter(new SuicideOnChannelErrorFilter());
184 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kTraceToConsole
)) {
185 std::string category_string
=
186 CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
187 switches::kTraceToConsole
);
189 if (!category_string
.size())
190 category_string
= "*";
192 base::debug::TraceLog::GetInstance()->SetEnabled(
193 base::debug::CategoryFilter(category_string
),
194 base::debug::TraceLog::ECHO_TO_CONSOLE
);
197 base::MessageLoop::current()->PostDelayedTask(
199 base::Bind(&ChildThread::EnsureConnected
,
200 channel_connected_factory_
.GetWeakPtr()),
201 base::TimeDelta::FromSeconds(kConnectionTimeoutS
));
203 #if defined(OS_ANDROID)
204 g_child_thread
= this;
207 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
208 trace_memory_controller_
.reset(new base::debug::TraceMemoryController(
209 message_loop_
->message_loop_proxy(),
210 ::HeapProfilerWithPseudoStackStart
,
216 ChildThread::~ChildThread() {
217 #ifdef IPC_MESSAGE_LOG_ENABLED
218 IPC::Logging::GetInstance()->SetIPCSender(NULL
);
221 channel_
->RemoveFilter(quota_message_filter_
.get());
222 channel_
->RemoveFilter(histogram_message_filter_
.get());
223 channel_
->RemoveFilter(sync_message_filter_
.get());
225 // The ChannelProxy object caches a pointer to the IPC thread, so need to
226 // reset it as it's not guaranteed to outlive this object.
227 // NOTE: this also has the side-effect of not closing the main IPC channel to
228 // the browser process. This is needed because this is the signal that the
229 // browser uses to know that this process has died, so we need it to be alive
230 // until this process is shut down, and the OS closes the handle
231 // automatically. We used to watch the object handle on Windows to do this,
232 // but it wasn't possible to do so on POSIX.
233 channel_
->ClearIPCTaskRunner();
234 g_lazy_tls
.Pointer()->Set(NULL
);
237 void ChildThread::Shutdown() {
238 // Delete objects that hold references to blink so derived classes can
239 // safely shutdown blink in their Shutdown implementation.
240 file_system_dispatcher_
.reset();
243 void ChildThread::OnChannelConnected(int32 peer_pid
) {
244 channel_connected_factory_
.InvalidateWeakPtrs();
247 void ChildThread::OnChannelError() {
248 set_on_channel_error_called(true);
249 base::MessageLoop::current()->Quit();
252 bool ChildThread::Send(IPC::Message
* msg
) {
253 DCHECK(base::MessageLoop::current() == message_loop());
259 return channel_
->Send(msg
);
262 void ChildThread::AddRoute(int32 routing_id
, IPC::Listener
* listener
) {
263 DCHECK(base::MessageLoop::current() == message_loop());
265 router_
.AddRoute(routing_id
, listener
);
268 void ChildThread::RemoveRoute(int32 routing_id
) {
269 DCHECK(base::MessageLoop::current() == message_loop());
271 router_
.RemoveRoute(routing_id
);
274 webkit_glue::ResourceLoaderBridge
* ChildThread::CreateBridge(
275 const webkit_glue::ResourceLoaderBridge::RequestInfo
& request_info
) {
276 return resource_dispatcher()->CreateBridge(request_info
);
279 base::SharedMemory
* ChildThread::AllocateSharedMemory(size_t buf_size
) {
280 return AllocateSharedMemory(buf_size
, this);
284 base::SharedMemory
* ChildThread::AllocateSharedMemory(
286 IPC::Sender
* sender
) {
287 scoped_ptr
<base::SharedMemory
> shared_buf
;
289 shared_buf
.reset(new base::SharedMemory
);
290 if (!shared_buf
->CreateAndMapAnonymous(buf_size
)) {
295 // On POSIX, we need to ask the browser to create the shared memory for us,
296 // since this is blocked by the sandbox.
297 base::SharedMemoryHandle shared_mem_handle
;
298 if (sender
->Send(new ChildProcessHostMsg_SyncAllocateSharedMemory(
299 buf_size
, &shared_mem_handle
))) {
300 if (base::SharedMemory::IsHandleValid(shared_mem_handle
)) {
301 shared_buf
.reset(new base::SharedMemory(shared_mem_handle
, false));
302 if (!shared_buf
->Map(buf_size
)) {
303 NOTREACHED() << "Map failed";
307 NOTREACHED() << "Browser failed to allocate shared memory";
311 NOTREACHED() << "Browser allocation request message failed";
315 return shared_buf
.release();
318 bool ChildThread::OnMessageReceived(const IPC::Message
& msg
) {
319 // Resource responses are sent to the resource dispatcher.
320 if (resource_dispatcher_
->OnMessageReceived(msg
))
322 if (socket_stream_dispatcher_
->OnMessageReceived(msg
))
324 if (file_system_dispatcher_
->OnMessageReceived(msg
))
328 IPC_BEGIN_MESSAGE_MAP(ChildThread
, msg
)
329 IPC_MESSAGE_HANDLER(ChildProcessMsg_Shutdown
, OnShutdown
)
330 #if defined(IPC_MESSAGE_LOG_ENABLED)
331 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetIPCLoggingEnabled
,
332 OnSetIPCLoggingEnabled
)
334 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetProfilerStatus
,
336 IPC_MESSAGE_HANDLER(ChildProcessMsg_GetChildProfilerData
,
337 OnGetChildProfilerData
)
338 IPC_MESSAGE_HANDLER(ChildProcessMsg_DumpHandles
, OnDumpHandles
)
339 #if defined(USE_TCMALLOC)
340 IPC_MESSAGE_HANDLER(ChildProcessMsg_GetTcmallocStats
, OnGetTcmallocStats
)
342 IPC_MESSAGE_UNHANDLED(handled
= false)
343 IPC_END_MESSAGE_MAP()
348 if (msg
.routing_id() == MSG_ROUTING_CONTROL
)
349 return OnControlMessageReceived(msg
);
351 return router_
.OnMessageReceived(msg
);
354 bool ChildThread::OnControlMessageReceived(const IPC::Message
& msg
) {
358 void ChildThread::OnShutdown() {
359 base::MessageLoop::current()->Quit();
362 #if defined(IPC_MESSAGE_LOG_ENABLED)
363 void ChildThread::OnSetIPCLoggingEnabled(bool enable
) {
365 IPC::Logging::GetInstance()->Enable();
367 IPC::Logging::GetInstance()->Disable();
369 #endif // IPC_MESSAGE_LOG_ENABLED
371 void ChildThread::OnSetProfilerStatus(ThreadData::Status status
) {
372 ThreadData::InitializeAndSetTrackingStatus(status
);
375 void ChildThread::OnGetChildProfilerData(int sequence_number
) {
376 tracked_objects::ProcessDataSnapshot process_data
;
377 ThreadData::Snapshot(false, &process_data
);
379 Send(new ChildProcessHostMsg_ChildProfilerData(sequence_number
,
383 void ChildThread::OnDumpHandles() {
385 scoped_refptr
<HandleEnumerator
> handle_enum(
386 new HandleEnumerator(
387 CommandLine::ForCurrentProcess()->HasSwitch(
388 switches::kAuditAllHandles
)));
389 handle_enum
->EnumerateHandles();
390 Send(new ChildProcessHostMsg_DumpHandlesDone
);
397 #if defined(USE_TCMALLOC)
398 void ChildThread::OnGetTcmallocStats() {
400 char buffer
[1024 * 32];
401 base::allocator::GetStats(buffer
, sizeof(buffer
));
402 result
.append(buffer
);
403 Send(new ChildProcessHostMsg_TcmallocStats(result
));
407 ChildThread
* ChildThread::current() {
408 return g_lazy_tls
.Pointer()->Get();
411 #if defined(OS_ANDROID)
412 void ChildThread::ShutdownThread() {
413 DCHECK_NE(base::MessageLoop::current(), g_child_thread
->message_loop());
414 g_child_thread
->message_loop()->PostTask(
415 FROM_HERE
, base::Bind(&QuitMainThreadMessageLoop
));
420 void ChildThread::OnProcessFinalRelease() {
421 if (on_channel_error_called_
) {
422 base::MessageLoop::current()->Quit();
426 // The child process shutdown sequence is a request response based mechanism,
427 // where we send out an initial feeler request to the child process host
428 // instance in the browser to verify if it's ok to shutdown the child process.
429 // The browser then sends back a response if it's ok to shutdown. This avoids
430 // race conditions if the process refcount is 0 but there's an IPC message
431 // inflight that would addref it.
432 Send(new ChildProcessHostMsg_ShutdownRequest
);
435 void ChildThread::EnsureConnected() {
436 LOG(INFO
) << "ChildThread::EnsureConnected()";
437 base::KillProcess(base::GetCurrentProcessHandle(), 0, false);
440 } // namespace content