[safe_browsing] Remove unused ContainsBrowseUrl() parameter.
[chromium-blink-merge.git] / content / child / child_thread.cc
blob2c9c59ee461faed6a7581ee5cb0ebbbde9566976
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 <signal.h>
9 #include <string>
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/child_shared_bitmap_manager.h"
31 #include "content/child/fileapi/file_system_dispatcher.h"
32 #include "content/child/mojo/mojo_application.h"
33 #include "content/child/power_monitor_broadcast_source.h"
34 #include "content/child/quota_dispatcher.h"
35 #include "content/child/quota_message_filter.h"
36 #include "content/child/resource_dispatcher.h"
37 #include "content/child/service_worker/service_worker_dispatcher.h"
38 #include "content/child/service_worker/service_worker_message_filter.h"
39 #include "content/child/socket_stream_dispatcher.h"
40 #include "content/child/thread_safe_sender.h"
41 #include "content/child/websocket_dispatcher.h"
42 #include "content/common/child_process_messages.h"
43 #include "content/public/common/content_switches.h"
44 #include "ipc/ipc_logging.h"
45 #include "ipc/ipc_switches.h"
46 #include "ipc/ipc_sync_channel.h"
47 #include "ipc/ipc_sync_message_filter.h"
48 #include "webkit/child/resource_loader_bridge.h"
50 #if defined(OS_WIN)
51 #include "content/common/handle_enumerator_win.h"
52 #endif
54 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
55 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
56 #endif
58 using tracked_objects::ThreadData;
60 namespace content {
61 namespace {
63 // How long to wait for a connection to the browser process before giving up.
64 const int kConnectionTimeoutS = 15;
66 base::LazyInstance<base::ThreadLocalPointer<ChildThread> > g_lazy_tls =
67 LAZY_INSTANCE_INITIALIZER;
69 // This isn't needed on Windows because there the sandbox's job object
70 // terminates child processes automatically. For unsandboxed processes (i.e.
71 // plugins), PluginThread has EnsureTerminateMessageFilter.
72 #if defined(OS_POSIX)
74 // TODO(earthdok): Re-enable on CrOS http://crbug.com/360622
75 #if (defined(ADDRESS_SANITIZER) || defined(LEAK_SANITIZER) || \
76 defined(THREAD_SANITIZER)) && !defined(OS_CHROMEOS)
77 // A thread delegate that waits for |duration| and then exits the process with
78 // _exit(0).
79 class WaitAndExitDelegate : public base::PlatformThread::Delegate {
80 public:
81 explicit WaitAndExitDelegate(base::TimeDelta duration)
82 : duration_(duration) {}
83 virtual ~WaitAndExitDelegate() OVERRIDE {}
85 virtual void ThreadMain() OVERRIDE {
86 base::PlatformThread::Sleep(duration_);
87 _exit(0);
90 private:
91 const base::TimeDelta duration_;
92 DISALLOW_COPY_AND_ASSIGN(WaitAndExitDelegate);
95 bool CreateWaitAndExitThread(base::TimeDelta duration) {
96 scoped_ptr<WaitAndExitDelegate> delegate(new WaitAndExitDelegate(duration));
98 const bool thread_created =
99 base::PlatformThread::CreateNonJoinable(0, delegate.get());
100 if (!thread_created)
101 return false;
103 // A non joinable thread has been created. The thread will either terminate
104 // the process or will be terminated by the process. Therefore, keep the
105 // delegate object alive for the lifetime of the process.
106 WaitAndExitDelegate* leaking_delegate = delegate.release();
107 ANNOTATE_LEAKING_OBJECT_PTR(leaking_delegate);
108 ignore_result(leaking_delegate);
109 return true;
111 #endif
113 class SuicideOnChannelErrorFilter : public IPC::MessageFilter {
114 public:
115 // IPC::MessageFilter
116 virtual void OnChannelError() OVERRIDE {
117 // For renderer/worker processes:
118 // On POSIX, at least, one can install an unload handler which loops
119 // forever and leave behind a renderer process which eats 100% CPU forever.
121 // This is because the terminate signals (ViewMsg_ShouldClose and the error
122 // from the IPC channel) are routed to the main message loop but never
123 // processed (because that message loop is stuck in V8).
125 // One could make the browser SIGKILL the renderers, but that leaves open a
126 // large window where a browser failure (or a user, manually terminating
127 // the browser because "it's stuck") will leave behind a process eating all
128 // the CPU.
130 // So, we install a filter on the channel so that we can process this event
131 // here and kill the process.
132 // TODO(earthdok): Re-enable on CrOS http://crbug.com/360622
133 #if (defined(ADDRESS_SANITIZER) || defined(LEAK_SANITIZER) || \
134 defined(THREAD_SANITIZER)) && !defined(OS_CHROMEOS)
135 // Some sanitizer tools rely on exit handlers (e.g. to run leak detection,
136 // or dump code coverage data to disk). Instead of exiting the process
137 // immediately, we give it 60 seconds to run exit handlers.
138 CHECK(CreateWaitAndExitThread(base::TimeDelta::FromSeconds(60)));
139 #if defined(LEAK_SANITIZER)
140 // Invoke LeakSanitizer early to avoid detecting shutdown-only leaks. If
141 // leaks are found, the process will exit here.
142 __lsan_do_leak_check();
143 #endif
144 #else
145 _exit(0);
146 #endif
149 protected:
150 virtual ~SuicideOnChannelErrorFilter() {}
153 #endif // OS(POSIX)
155 #if defined(OS_ANDROID)
156 ChildThread* g_child_thread = NULL;
158 // A lock protects g_child_thread.
159 base::LazyInstance<base::Lock> g_lazy_child_thread_lock =
160 LAZY_INSTANCE_INITIALIZER;
162 // base::ConditionVariable has an explicit constructor that takes
163 // a base::Lock pointer as parameter. The base::DefaultLazyInstanceTraits
164 // doesn't handle the case. Thus, we need our own class here.
165 struct CondVarLazyInstanceTraits {
166 static const bool kRegisterOnExit = true;
167 #ifndef NDEBUG
168 static const bool kAllowedToAccessOnNonjoinableThread = false;
169 #endif
171 static base::ConditionVariable* New(void* instance) {
172 return new (instance) base::ConditionVariable(
173 g_lazy_child_thread_lock.Pointer());
175 static void Delete(base::ConditionVariable* instance) {
176 instance->~ConditionVariable();
180 // A condition variable that synchronize threads initializing and waiting
181 // for g_child_thread.
182 base::LazyInstance<base::ConditionVariable, CondVarLazyInstanceTraits>
183 g_lazy_child_thread_cv = LAZY_INSTANCE_INITIALIZER;
185 void QuitMainThreadMessageLoop() {
186 base::MessageLoop::current()->Quit();
189 #endif
191 } // namespace
193 ChildThread::ChildThreadMessageRouter::ChildThreadMessageRouter(
194 IPC::Sender* sender)
195 : sender_(sender) {}
197 bool ChildThread::ChildThreadMessageRouter::Send(IPC::Message* msg) {
198 return sender_->Send(msg);
201 ChildThread::ChildThread()
202 : router_(this),
203 channel_connected_factory_(this),
204 in_browser_process_(false) {
205 channel_name_ = CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
206 switches::kProcessChannelID);
207 Init();
210 ChildThread::ChildThread(const std::string& channel_name)
211 : channel_name_(channel_name),
212 router_(this),
213 channel_connected_factory_(this),
214 in_browser_process_(true) {
215 Init();
218 void ChildThread::Init() {
219 g_lazy_tls.Pointer()->Set(this);
220 on_channel_error_called_ = false;
221 message_loop_ = base::MessageLoop::current();
222 #ifdef IPC_MESSAGE_LOG_ENABLED
223 // We must make sure to instantiate the IPC Logger *before* we create the
224 // channel, otherwise we can get a callback on the IO thread which creates
225 // the logger, and the logger does not like being created on the IO thread.
226 IPC::Logging::GetInstance();
227 #endif
228 channel_.reset(
229 new IPC::SyncChannel(channel_name_,
230 IPC::Channel::MODE_CLIENT,
231 this,
232 ChildProcess::current()->io_message_loop_proxy(),
233 true,
234 ChildProcess::current()->GetShutDownEvent()));
235 #ifdef IPC_MESSAGE_LOG_ENABLED
236 if (!in_browser_process_)
237 IPC::Logging::GetInstance()->SetIPCSender(this);
238 #endif
240 mojo_application_.reset(new MojoApplication(this));
242 sync_message_filter_ =
243 new IPC::SyncMessageFilter(ChildProcess::current()->GetShutDownEvent());
244 thread_safe_sender_ = new ThreadSafeSender(
245 base::MessageLoopProxy::current().get(), sync_message_filter_.get());
247 resource_dispatcher_.reset(new ResourceDispatcher(this));
248 socket_stream_dispatcher_.reset(new SocketStreamDispatcher());
249 websocket_dispatcher_.reset(new WebSocketDispatcher);
250 file_system_dispatcher_.reset(new FileSystemDispatcher());
252 histogram_message_filter_ = new ChildHistogramMessageFilter();
253 resource_message_filter_ =
254 new ChildResourceMessageFilter(resource_dispatcher());
256 service_worker_message_filter_ =
257 new ServiceWorkerMessageFilter(thread_safe_sender_.get());
258 service_worker_dispatcher_.reset(
259 new ServiceWorkerDispatcher(thread_safe_sender_.get()));
261 quota_message_filter_ =
262 new QuotaMessageFilter(thread_safe_sender_.get());
263 quota_dispatcher_.reset(new QuotaDispatcher(thread_safe_sender_.get(),
264 quota_message_filter_.get()));
266 channel_->AddFilter(histogram_message_filter_.get());
267 channel_->AddFilter(sync_message_filter_.get());
268 channel_->AddFilter(new tracing::ChildTraceMessageFilter(
269 ChildProcess::current()->io_message_loop_proxy()));
270 channel_->AddFilter(resource_message_filter_.get());
271 channel_->AddFilter(quota_message_filter_->GetFilter());
272 channel_->AddFilter(service_worker_message_filter_->GetFilter());
274 // In single process mode we may already have a power monitor
275 if (!base::PowerMonitor::Get()) {
276 scoped_ptr<PowerMonitorBroadcastSource> power_monitor_source(
277 new PowerMonitorBroadcastSource());
278 channel_->AddFilter(power_monitor_source->GetMessageFilter());
280 power_monitor_.reset(new base::PowerMonitor(
281 power_monitor_source.PassAs<base::PowerMonitorSource>()));
284 #if defined(OS_POSIX)
285 // Check that --process-type is specified so we don't do this in unit tests
286 // and single-process mode.
287 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kProcessType))
288 channel_->AddFilter(new SuicideOnChannelErrorFilter());
289 #endif
291 base::MessageLoop::current()->PostDelayedTask(
292 FROM_HERE,
293 base::Bind(&ChildThread::EnsureConnected,
294 channel_connected_factory_.GetWeakPtr()),
295 base::TimeDelta::FromSeconds(kConnectionTimeoutS));
297 #if defined(OS_ANDROID)
299 base::AutoLock lock(g_lazy_child_thread_lock.Get());
300 g_child_thread = this;
302 // Signalling without locking is fine here because only
303 // one thread can wait on the condition variable.
304 g_lazy_child_thread_cv.Get().Signal();
305 #endif
307 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
308 trace_memory_controller_.reset(new base::debug::TraceMemoryController(
309 message_loop_->message_loop_proxy(),
310 ::HeapProfilerWithPseudoStackStart,
311 ::HeapProfilerStop,
312 ::GetHeapProfile));
313 #endif
315 shared_bitmap_manager_.reset(
316 new ChildSharedBitmapManager(thread_safe_sender()));
319 ChildThread::~ChildThread() {
320 #ifdef IPC_MESSAGE_LOG_ENABLED
321 IPC::Logging::GetInstance()->SetIPCSender(NULL);
322 #endif
324 channel_->RemoveFilter(histogram_message_filter_.get());
325 channel_->RemoveFilter(sync_message_filter_.get());
327 // The ChannelProxy object caches a pointer to the IPC thread, so need to
328 // reset it as it's not guaranteed to outlive this object.
329 // NOTE: this also has the side-effect of not closing the main IPC channel to
330 // the browser process. This is needed because this is the signal that the
331 // browser uses to know that this process has died, so we need it to be alive
332 // until this process is shut down, and the OS closes the handle
333 // automatically. We used to watch the object handle on Windows to do this,
334 // but it wasn't possible to do so on POSIX.
335 channel_->ClearIPCTaskRunner();
336 g_lazy_tls.Pointer()->Set(NULL);
339 void ChildThread::Shutdown() {
340 // Delete objects that hold references to blink so derived classes can
341 // safely shutdown blink in their Shutdown implementation.
342 file_system_dispatcher_.reset();
343 quota_dispatcher_.reset();
346 void ChildThread::OnChannelConnected(int32 peer_pid) {
347 channel_connected_factory_.InvalidateWeakPtrs();
350 void ChildThread::OnChannelError() {
351 set_on_channel_error_called(true);
352 base::MessageLoop::current()->Quit();
355 void ChildThread::AcceptConnection(
356 const mojo::String& service_name,
357 mojo::ScopedMessagePipeHandle message_pipe) {
358 // By default, we don't expect incoming connections.
359 NOTREACHED();
362 bool ChildThread::Send(IPC::Message* msg) {
363 DCHECK(base::MessageLoop::current() == message_loop());
364 if (!channel_) {
365 delete msg;
366 return false;
369 return channel_->Send(msg);
372 MessageRouter* ChildThread::GetRouter() {
373 DCHECK(base::MessageLoop::current() == message_loop());
374 return &router_;
377 webkit_glue::ResourceLoaderBridge* ChildThread::CreateBridge(
378 const RequestInfo& request_info) {
379 return resource_dispatcher()->CreateBridge(request_info);
382 base::SharedMemory* ChildThread::AllocateSharedMemory(size_t buf_size) {
383 return AllocateSharedMemory(buf_size, this);
386 // static
387 base::SharedMemory* ChildThread::AllocateSharedMemory(
388 size_t buf_size,
389 IPC::Sender* sender) {
390 scoped_ptr<base::SharedMemory> shared_buf;
391 #if defined(OS_WIN)
392 shared_buf.reset(new base::SharedMemory);
393 if (!shared_buf->CreateAndMapAnonymous(buf_size)) {
394 NOTREACHED();
395 return NULL;
397 #else
398 // On POSIX, we need to ask the browser to create the shared memory for us,
399 // since this is blocked by the sandbox.
400 base::SharedMemoryHandle shared_mem_handle;
401 if (sender->Send(new ChildProcessHostMsg_SyncAllocateSharedMemory(
402 buf_size, &shared_mem_handle))) {
403 if (base::SharedMemory::IsHandleValid(shared_mem_handle)) {
404 shared_buf.reset(new base::SharedMemory(shared_mem_handle, false));
405 if (!shared_buf->Map(buf_size)) {
406 NOTREACHED() << "Map failed";
407 return NULL;
409 } else {
410 NOTREACHED() << "Browser failed to allocate shared memory";
411 return NULL;
413 } else {
414 NOTREACHED() << "Browser allocation request message failed";
415 return NULL;
417 #endif
418 return shared_buf.release();
421 bool ChildThread::OnMessageReceived(const IPC::Message& msg) {
422 if (mojo_application_->OnMessageReceived(msg))
423 return true;
425 // Resource responses are sent to the resource dispatcher.
426 if (resource_dispatcher_->OnMessageReceived(msg))
427 return true;
428 if (socket_stream_dispatcher_->OnMessageReceived(msg))
429 return true;
430 if (websocket_dispatcher_->OnMessageReceived(msg))
431 return true;
432 if (file_system_dispatcher_->OnMessageReceived(msg))
433 return true;
435 bool handled = true;
436 IPC_BEGIN_MESSAGE_MAP(ChildThread, msg)
437 IPC_MESSAGE_HANDLER(ChildProcessMsg_Shutdown, OnShutdown)
438 #if defined(IPC_MESSAGE_LOG_ENABLED)
439 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetIPCLoggingEnabled,
440 OnSetIPCLoggingEnabled)
441 #endif
442 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetProfilerStatus,
443 OnSetProfilerStatus)
444 IPC_MESSAGE_HANDLER(ChildProcessMsg_GetChildProfilerData,
445 OnGetChildProfilerData)
446 IPC_MESSAGE_HANDLER(ChildProcessMsg_DumpHandles, OnDumpHandles)
447 #if defined(USE_TCMALLOC)
448 IPC_MESSAGE_HANDLER(ChildProcessMsg_GetTcmallocStats, OnGetTcmallocStats)
449 #endif
450 IPC_MESSAGE_UNHANDLED(handled = false)
451 IPC_END_MESSAGE_MAP()
453 if (handled)
454 return true;
456 if (msg.routing_id() == MSG_ROUTING_CONTROL)
457 return OnControlMessageReceived(msg);
459 return router_.OnMessageReceived(msg);
462 bool ChildThread::OnControlMessageReceived(const IPC::Message& msg) {
463 return false;
466 void ChildThread::OnShutdown() {
467 base::MessageLoop::current()->Quit();
470 #if defined(IPC_MESSAGE_LOG_ENABLED)
471 void ChildThread::OnSetIPCLoggingEnabled(bool enable) {
472 if (enable)
473 IPC::Logging::GetInstance()->Enable();
474 else
475 IPC::Logging::GetInstance()->Disable();
477 #endif // IPC_MESSAGE_LOG_ENABLED
479 void ChildThread::OnSetProfilerStatus(ThreadData::Status status) {
480 ThreadData::InitializeAndSetTrackingStatus(status);
483 void ChildThread::OnGetChildProfilerData(int sequence_number) {
484 tracked_objects::ProcessDataSnapshot process_data;
485 ThreadData::Snapshot(false, &process_data);
487 Send(new ChildProcessHostMsg_ChildProfilerData(sequence_number,
488 process_data));
491 void ChildThread::OnDumpHandles() {
492 #if defined(OS_WIN)
493 scoped_refptr<HandleEnumerator> handle_enum(
494 new HandleEnumerator(
495 CommandLine::ForCurrentProcess()->HasSwitch(
496 switches::kAuditAllHandles)));
497 handle_enum->EnumerateHandles();
498 Send(new ChildProcessHostMsg_DumpHandlesDone);
499 #else
500 NOTIMPLEMENTED();
501 #endif
504 #if defined(USE_TCMALLOC)
505 void ChildThread::OnGetTcmallocStats() {
506 std::string result;
507 char buffer[1024 * 32];
508 base::allocator::GetStats(buffer, sizeof(buffer));
509 result.append(buffer);
510 Send(new ChildProcessHostMsg_TcmallocStats(result));
512 #endif
514 ChildThread* ChildThread::current() {
515 return g_lazy_tls.Pointer()->Get();
518 #if defined(OS_ANDROID)
519 // The method must NOT be called on the child thread itself.
520 // It may block the child thread if so.
521 void ChildThread::ShutdownThread() {
522 DCHECK(!ChildThread::current()) <<
523 "this method should NOT be called from child thread itself";
525 base::AutoLock lock(g_lazy_child_thread_lock.Get());
526 while (!g_child_thread)
527 g_lazy_child_thread_cv.Get().Wait();
529 DCHECK_NE(base::MessageLoop::current(), g_child_thread->message_loop());
530 g_child_thread->message_loop()->PostTask(
531 FROM_HERE, base::Bind(&QuitMainThreadMessageLoop));
533 #endif
535 void ChildThread::OnProcessFinalRelease() {
536 if (on_channel_error_called_) {
537 base::MessageLoop::current()->Quit();
538 return;
541 // The child process shutdown sequence is a request response based mechanism,
542 // where we send out an initial feeler request to the child process host
543 // instance in the browser to verify if it's ok to shutdown the child process.
544 // The browser then sends back a response if it's ok to shutdown. This avoids
545 // race conditions if the process refcount is 0 but there's an IPC message
546 // inflight that would addref it.
547 Send(new ChildProcessHostMsg_ShutdownRequest);
550 void ChildThread::EnsureConnected() {
551 VLOG(0) << "ChildThread::EnsureConnected()";
552 base::KillProcess(base::GetCurrentProcessHandle(), 0, false);
555 } // namespace content