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/command_line.h"
9 #include "base/message_loop.h"
10 #include "base/process.h"
11 #include "base/process_util.h"
12 #include "base/strings/string_util.h"
13 #include "base/tracked_objects.h"
14 #include "components/tracing/child_trace_message_filter.h"
15 #include "content/child/child_histogram_message_filter.h"
16 #include "content/child/child_process.h"
17 #include "content/child/child_resource_message_filter.h"
18 #include "content/child/fileapi/file_system_dispatcher.h"
19 #include "content/child/quota_dispatcher.h"
20 #include "content/child/resource_dispatcher.h"
21 #include "content/child/socket_stream_dispatcher.h"
22 #include "content/child/thread_safe_sender.h"
23 #include "content/common/child_process_messages.h"
24 #include "content/public/common/content_switches.h"
25 #include "ipc/ipc_logging.h"
26 #include "ipc/ipc_switches.h"
27 #include "ipc/ipc_sync_channel.h"
28 #include "ipc/ipc_sync_message_filter.h"
29 #include "webkit/glue/webkit_glue.h"
32 #include "content/common/handle_enumerator_win.h"
35 using tracked_objects::ThreadData
;
40 // How long to wait for a connection to the browser process before giving up.
41 const int kConnectionTimeoutS
= 15;
43 // This isn't needed on Windows because there the sandbox's job object
44 // terminates child processes automatically. For unsandboxed processes (i.e.
45 // plugins), PluginThread has EnsureTerminateMessageFilter.
48 class SuicideOnChannelErrorFilter
: public IPC::ChannelProxy::MessageFilter
{
50 // IPC::ChannelProxy::MessageFilter
51 virtual void OnChannelError() OVERRIDE
{
52 // For renderer/worker processes:
53 // On POSIX, at least, one can install an unload handler which loops
54 // forever and leave behind a renderer process which eats 100% CPU forever.
56 // This is because the terminate signals (ViewMsg_ShouldClose and the error
57 // from the IPC channel) are routed to the main message loop but never
58 // processed (because that message loop is stuck in V8).
60 // One could make the browser SIGKILL the renderers, but that leaves open a
61 // large window where a browser failure (or a user, manually terminating
62 // the browser because "it's stuck") will leave behind a process eating all
65 // So, we install a filter on the channel so that we can process this event
66 // here and kill the process.
68 // We want to kill this process after giving it 30 seconds to run the exit
69 // handlers. SIGALRM has a default disposition of terminating the
71 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kChildCleanExit
))
78 virtual ~SuicideOnChannelErrorFilter() {}
85 ChildThread::ChildThread()
86 : channel_connected_factory_(this) {
87 channel_name_
= CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
88 switches::kProcessChannelID
);
92 ChildThread::ChildThread(const std::string
& channel_name
)
93 : channel_name_(channel_name
),
94 channel_connected_factory_(this) {
98 void ChildThread::Init() {
99 on_channel_error_called_
= false;
100 message_loop_
= base::MessageLoop::current();
102 new IPC::SyncChannel(channel_name_
,
103 IPC::Channel::MODE_CLIENT
,
105 ChildProcess::current()->io_message_loop_proxy(),
107 ChildProcess::current()->GetShutDownEvent()));
108 #ifdef IPC_MESSAGE_LOG_ENABLED
109 IPC::Logging::GetInstance()->SetIPCSender(this);
112 resource_dispatcher_
.reset(new ResourceDispatcher(this));
113 socket_stream_dispatcher_
.reset(new SocketStreamDispatcher());
114 file_system_dispatcher_
.reset(new FileSystemDispatcher());
115 quota_dispatcher_
.reset(new QuotaDispatcher());
117 sync_message_filter_
=
118 new IPC::SyncMessageFilter(ChildProcess::current()->GetShutDownEvent());
119 thread_safe_sender_
= new ThreadSafeSender(
120 base::MessageLoopProxy::current().get(), sync_message_filter_
.get());
121 histogram_message_filter_
= new ChildHistogramMessageFilter();
122 resource_message_filter_
=
123 new ChildResourceMessageFilter(resource_dispatcher());
125 channel_
->AddFilter(histogram_message_filter_
.get());
126 channel_
->AddFilter(sync_message_filter_
.get());
127 channel_
->AddFilter(new tracing::ChildTraceMessageFilter(
128 ChildProcess::current()->io_message_loop_proxy()));
129 channel_
->AddFilter(resource_message_filter_
.get());
131 #if defined(OS_POSIX)
132 // Check that --process-type is specified so we don't do this in unit tests
133 // and single-process mode.
134 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kProcessType
))
135 channel_
->AddFilter(new SuicideOnChannelErrorFilter());
138 base::MessageLoop::current()->PostDelayedTask(
140 base::Bind(&ChildThread::EnsureConnected
,
141 channel_connected_factory_
.GetWeakPtr()),
142 base::TimeDelta::FromSeconds(kConnectionTimeoutS
));
145 ChildThread::~ChildThread() {
146 #ifdef IPC_MESSAGE_LOG_ENABLED
147 IPC::Logging::GetInstance()->SetIPCSender(NULL
);
150 channel_
->RemoveFilter(histogram_message_filter_
.get());
151 channel_
->RemoveFilter(sync_message_filter_
.get());
153 // The ChannelProxy object caches a pointer to the IPC thread, so need to
154 // reset it as it's not guaranteed to outlive this object.
155 // NOTE: this also has the side-effect of not closing the main IPC channel to
156 // the browser process. This is needed because this is the signal that the
157 // browser uses to know that this process has died, so we need it to be alive
158 // until this process is shut down, and the OS closes the handle
159 // automatically. We used to watch the object handle on Windows to do this,
160 // but it wasn't possible to do so on POSIX.
161 channel_
->ClearIPCTaskRunner();
164 void ChildThread::OnChannelConnected(int32 peer_pid
) {
165 channel_connected_factory_
.InvalidateWeakPtrs();
168 void ChildThread::OnChannelError() {
169 set_on_channel_error_called(true);
170 base::MessageLoop::current()->Quit();
173 bool ChildThread::Send(IPC::Message
* msg
) {
174 DCHECK(base::MessageLoop::current() == message_loop());
180 return channel_
->Send(msg
);
183 void ChildThread::AddRoute(int32 routing_id
, IPC::Listener
* listener
) {
184 DCHECK(base::MessageLoop::current() == message_loop());
186 router_
.AddRoute(routing_id
, listener
);
189 void ChildThread::RemoveRoute(int32 routing_id
) {
190 DCHECK(base::MessageLoop::current() == message_loop());
192 router_
.RemoveRoute(routing_id
);
195 webkit_glue::ResourceLoaderBridge
* ChildThread::CreateBridge(
196 const webkit_glue::ResourceLoaderBridge::RequestInfo
& request_info
) {
197 return resource_dispatcher()->CreateBridge(request_info
);
200 base::SharedMemory
* ChildThread::AllocateSharedMemory(size_t buf_size
) {
201 return AllocateSharedMemory(buf_size
, this);
205 base::SharedMemory
* ChildThread::AllocateSharedMemory(
207 IPC::Sender
* sender
) {
208 scoped_ptr
<base::SharedMemory
> shared_buf
;
210 shared_buf
.reset(new base::SharedMemory
);
211 if (!shared_buf
->CreateAndMapAnonymous(buf_size
)) {
216 // On POSIX, we need to ask the browser to create the shared memory for us,
217 // since this is blocked by the sandbox.
218 base::SharedMemoryHandle shared_mem_handle
;
219 if (sender
->Send(new ChildProcessHostMsg_SyncAllocateSharedMemory(
220 buf_size
, &shared_mem_handle
))) {
221 if (base::SharedMemory::IsHandleValid(shared_mem_handle
)) {
222 shared_buf
.reset(new base::SharedMemory(shared_mem_handle
, false));
223 if (!shared_buf
->Map(buf_size
)) {
224 NOTREACHED() << "Map failed";
228 NOTREACHED() << "Browser failed to allocate shared memory";
232 NOTREACHED() << "Browser allocation request message failed";
236 return shared_buf
.release();
239 bool ChildThread::OnMessageReceived(const IPC::Message
& msg
) {
240 // Resource responses are sent to the resource dispatcher.
241 if (resource_dispatcher_
->OnMessageReceived(msg
))
243 if (socket_stream_dispatcher_
->OnMessageReceived(msg
))
245 if (file_system_dispatcher_
->OnMessageReceived(msg
))
247 if (quota_dispatcher_
->OnMessageReceived(msg
))
251 IPC_BEGIN_MESSAGE_MAP(ChildThread
, msg
)
252 IPC_MESSAGE_HANDLER(ChildProcessMsg_Shutdown
, OnShutdown
)
253 #if defined(IPC_MESSAGE_LOG_ENABLED)
254 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetIPCLoggingEnabled
,
255 OnSetIPCLoggingEnabled
)
257 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetProfilerStatus
,
259 IPC_MESSAGE_HANDLER(ChildProcessMsg_GetChildProfilerData
,
260 OnGetChildProfilerData
)
261 IPC_MESSAGE_HANDLER(ChildProcessMsg_DumpHandles
, OnDumpHandles
)
262 #if defined(USE_TCMALLOC)
263 IPC_MESSAGE_HANDLER(ChildProcessMsg_GetTcmallocStats
, OnGetTcmallocStats
)
265 IPC_MESSAGE_UNHANDLED(handled
= false)
266 IPC_END_MESSAGE_MAP()
271 if (msg
.routing_id() == MSG_ROUTING_CONTROL
)
272 return OnControlMessageReceived(msg
);
274 return router_
.OnMessageReceived(msg
);
277 bool ChildThread::OnControlMessageReceived(const IPC::Message
& msg
) {
281 void ChildThread::OnShutdown() {
282 base::MessageLoop::current()->Quit();
285 #if defined(IPC_MESSAGE_LOG_ENABLED)
286 void ChildThread::OnSetIPCLoggingEnabled(bool enable
) {
288 IPC::Logging::GetInstance()->Enable();
290 IPC::Logging::GetInstance()->Disable();
292 #endif // IPC_MESSAGE_LOG_ENABLED
294 void ChildThread::OnSetProfilerStatus(ThreadData::Status status
) {
295 ThreadData::InitializeAndSetTrackingStatus(status
);
298 void ChildThread::OnGetChildProfilerData(int sequence_number
) {
299 tracked_objects::ProcessDataSnapshot process_data
;
300 ThreadData::Snapshot(false, &process_data
);
302 Send(new ChildProcessHostMsg_ChildProfilerData(sequence_number
,
306 void ChildThread::OnDumpHandles() {
308 scoped_refptr
<HandleEnumerator
> handle_enum(
309 new HandleEnumerator(
310 CommandLine::ForCurrentProcess()->HasSwitch(
311 switches::kAuditAllHandles
)));
312 handle_enum
->EnumerateHandles();
313 Send(new ChildProcessHostMsg_DumpHandlesDone
);
320 #if defined(USE_TCMALLOC)
321 void ChildThread::OnGetTcmallocStats() {
323 char buffer
[1024 * 32];
324 base::allocator::GetStats(buffer
, sizeof(buffer
));
325 result
.append(buffer
);
326 Send(new ChildProcessHostMsg_TcmallocStats(result
));
330 ChildThread
* ChildThread::current() {
331 return ChildProcess::current() ?
332 ChildProcess::current()->main_thread() : NULL
;
335 bool ChildThread::IsWebFrameValid(WebKit::WebFrame
* frame
) {
336 // Return false so that it is overridden in any process in which it is used.
340 void ChildThread::OnProcessFinalRelease() {
341 if (on_channel_error_called_
) {
342 base::MessageLoop::current()->Quit();
346 // The child process shutdown sequence is a request response based mechanism,
347 // where we send out an initial feeler request to the child process host
348 // instance in the browser to verify if it's ok to shutdown the child process.
349 // The browser then sends back a response if it's ok to shutdown. This avoids
350 // race conditions if the process refcount is 0 but there's an IPC message
351 // inflight that would addref it.
352 Send(new ChildProcessHostMsg_ShutdownRequest
);
355 void ChildThread::EnsureConnected() {
356 LOG(INFO
) << "ChildThread::EnsureConnected()";
357 base::KillProcess(base::GetCurrentProcessHandle(), 0, false);
360 } // namespace content