service_resolver_64: Correctly check all the bytes of the service code.
[chromium-blink-merge.git] / content / child / child_thread_impl.cc
blobbb3cd6d79179a22543958a498ebf77b4e0e59176
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_impl.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/debug/profiler.h"
17 #include "base/lazy_instance.h"
18 #include "base/location.h"
19 #include "base/logging.h"
20 #include "base/message_loop/timer_slack.h"
21 #include "base/metrics/field_trial.h"
22 #include "base/process/process.h"
23 #include "base/process/process_handle.h"
24 #include "base/single_thread_task_runner.h"
25 #include "base/strings/string_number_conversions.h"
26 #include "base/strings/string_util.h"
27 #include "base/synchronization/condition_variable.h"
28 #include "base/synchronization/lock.h"
29 #include "base/thread_task_runner_handle.h"
30 #include "base/threading/thread_local.h"
31 #include "base/trace_event/memory_dump_manager.h"
32 #include "base/tracked_objects.h"
33 #include "components/tracing/child_trace_message_filter.h"
34 #include "content/child/bluetooth/bluetooth_message_filter.h"
35 #include "content/child/child_discardable_shared_memory_manager.h"
36 #include "content/child/child_gpu_memory_buffer_manager.h"
37 #include "content/child/child_histogram_message_filter.h"
38 #include "content/child/child_process.h"
39 #include "content/child/child_resource_message_filter.h"
40 #include "content/child/child_shared_bitmap_manager.h"
41 #include "content/child/fileapi/file_system_dispatcher.h"
42 #include "content/child/fileapi/webfilesystem_impl.h"
43 #include "content/child/geofencing/geofencing_message_filter.h"
44 #include "content/child/mojo/mojo_application.h"
45 #include "content/child/notifications/notification_dispatcher.h"
46 #include "content/child/power_monitor_broadcast_source.h"
47 #include "content/child/push_messaging/push_dispatcher.h"
48 #include "content/child/quota_dispatcher.h"
49 #include "content/child/quota_message_filter.h"
50 #include "content/child/resource_dispatcher.h"
51 #include "content/child/service_worker/service_worker_message_filter.h"
52 #include "content/child/thread_safe_sender.h"
53 #include "content/child/websocket_dispatcher.h"
54 #include "content/common/child_process_messages.h"
55 #include "content/common/in_process_child_thread_params.h"
56 #include "content/public/common/content_switches.h"
57 #include "ipc/attachment_broker.h"
58 #include "ipc/ipc_logging.h"
59 #include "ipc/ipc_switches.h"
60 #include "ipc/ipc_sync_channel.h"
61 #include "ipc/ipc_sync_message_filter.h"
62 #include "ipc/mojo/ipc_channel_mojo.h"
64 #if defined(OS_ANDROID)
65 #include "base/thread_task_runner_handle.h"
66 #endif
68 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
69 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
70 #endif
72 #if defined(OS_MACOSX)
73 #include "content/child/child_io_surface_manager_mac.h"
74 #endif
76 #if defined(OS_WIN)
77 #include "ipc/attachment_broker_win.h"
78 #endif
80 using tracked_objects::ThreadData;
82 namespace content {
83 namespace {
85 // How long to wait for a connection to the browser process before giving up.
86 const int kConnectionTimeoutS = 15;
88 base::LazyInstance<base::ThreadLocalPointer<ChildThreadImpl> > g_lazy_tls =
89 LAZY_INSTANCE_INITIALIZER;
91 // This isn't needed on Windows because there the sandbox's job object
92 // terminates child processes automatically. For unsandboxed processes (i.e.
93 // plugins), PluginThread has EnsureTerminateMessageFilter.
94 #if defined(OS_POSIX)
96 #if defined(ADDRESS_SANITIZER) || defined(LEAK_SANITIZER) || \
97 defined(MEMORY_SANITIZER) || defined(THREAD_SANITIZER) || \
98 defined(UNDEFINED_SANITIZER)
99 // A thread delegate that waits for |duration| and then exits the process with
100 // _exit(0).
101 class WaitAndExitDelegate : public base::PlatformThread::Delegate {
102 public:
103 explicit WaitAndExitDelegate(base::TimeDelta duration)
104 : duration_(duration) {}
106 void ThreadMain() override {
107 base::PlatformThread::Sleep(duration_);
108 _exit(0);
111 private:
112 const base::TimeDelta duration_;
113 DISALLOW_COPY_AND_ASSIGN(WaitAndExitDelegate);
116 bool CreateWaitAndExitThread(base::TimeDelta duration) {
117 scoped_ptr<WaitAndExitDelegate> delegate(new WaitAndExitDelegate(duration));
119 const bool thread_created =
120 base::PlatformThread::CreateNonJoinable(0, delegate.get());
121 if (!thread_created)
122 return false;
124 // A non joinable thread has been created. The thread will either terminate
125 // the process or will be terminated by the process. Therefore, keep the
126 // delegate object alive for the lifetime of the process.
127 WaitAndExitDelegate* leaking_delegate = delegate.release();
128 ANNOTATE_LEAKING_OBJECT_PTR(leaking_delegate);
129 ignore_result(leaking_delegate);
130 return true;
132 #endif
134 class SuicideOnChannelErrorFilter : public IPC::MessageFilter {
135 public:
136 // IPC::MessageFilter
137 void OnChannelError() override {
138 // For renderer/worker processes:
139 // On POSIX, at least, one can install an unload handler which loops
140 // forever and leave behind a renderer process which eats 100% CPU forever.
142 // This is because the terminate signals (ViewMsg_ShouldClose and the error
143 // from the IPC sender) are routed to the main message loop but never
144 // processed (because that message loop is stuck in V8).
146 // One could make the browser SIGKILL the renderers, but that leaves open a
147 // large window where a browser failure (or a user, manually terminating
148 // the browser because "it's stuck") will leave behind a process eating all
149 // the CPU.
151 // So, we install a filter on the sender so that we can process this event
152 // here and kill the process.
153 base::debug::StopProfiling();
154 #if defined(ADDRESS_SANITIZER) || defined(LEAK_SANITIZER) || \
155 defined(MEMORY_SANITIZER) || defined(THREAD_SANITIZER) || \
156 defined(UNDEFINED_SANITIZER)
157 // Some sanitizer tools rely on exit handlers (e.g. to run leak detection,
158 // or dump code coverage data to disk). Instead of exiting the process
159 // immediately, we give it 60 seconds to run exit handlers.
160 CHECK(CreateWaitAndExitThread(base::TimeDelta::FromSeconds(60)));
161 #if defined(LEAK_SANITIZER)
162 // Invoke LeakSanitizer early to avoid detecting shutdown-only leaks. If
163 // leaks are found, the process will exit here.
164 __lsan_do_leak_check();
165 #endif
166 #else
167 _exit(0);
168 #endif
171 protected:
172 ~SuicideOnChannelErrorFilter() override {}
175 #endif // OS(POSIX)
177 #if defined(OS_MACOSX)
178 class IOSurfaceManagerFilter : public IPC::MessageFilter {
179 public:
180 // Overridden from IPC::MessageFilter:
181 bool OnMessageReceived(const IPC::Message& message) override {
182 bool handled = true;
183 IPC_BEGIN_MESSAGE_MAP(IOSurfaceManagerFilter, message)
184 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetIOSurfaceManagerToken,
185 OnSetIOSurfaceManagerToken)
186 IPC_MESSAGE_UNHANDLED(handled = false)
187 IPC_END_MESSAGE_MAP()
188 return handled;
191 protected:
192 ~IOSurfaceManagerFilter() override {}
194 void OnSetIOSurfaceManagerToken(const IOSurfaceManagerToken& token) {
195 ChildIOSurfaceManager::GetInstance()->set_token(token);
198 #endif
200 #if defined(OS_ANDROID)
201 // A class that allows for triggering a clean shutdown from another
202 // thread through draining the main thread's msg loop.
203 class QuitClosure {
204 public:
205 QuitClosure();
206 ~QuitClosure();
208 void BindToMainThread();
209 void PostQuitFromNonMainThread();
211 private:
212 static void PostClosure(
213 const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
214 base::Closure closure);
216 base::Lock lock_;
217 base::ConditionVariable cond_var_;
218 base::Closure closure_;
221 QuitClosure::QuitClosure() : cond_var_(&lock_) {
224 QuitClosure::~QuitClosure() {
227 void QuitClosure::PostClosure(
228 const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
229 base::Closure closure) {
230 task_runner->PostTask(FROM_HERE, closure);
233 void QuitClosure::BindToMainThread() {
234 base::AutoLock lock(lock_);
235 scoped_refptr<base::SingleThreadTaskRunner> task_runner(
236 base::ThreadTaskRunnerHandle::Get());
237 base::Closure quit_closure =
238 base::MessageLoop::current()->QuitWhenIdleClosure();
239 closure_ = base::Bind(&QuitClosure::PostClosure, task_runner, quit_closure);
240 cond_var_.Signal();
243 void QuitClosure::PostQuitFromNonMainThread() {
244 base::AutoLock lock(lock_);
245 while (closure_.is_null())
246 cond_var_.Wait();
248 closure_.Run();
251 base::LazyInstance<QuitClosure> g_quit_closure = LAZY_INSTANCE_INITIALIZER;
252 #endif
254 } // namespace
256 ChildThread* ChildThread::Get() {
257 return ChildThreadImpl::current();
260 ChildThreadImpl::Options::Options()
261 : channel_name(base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
262 switches::kProcessChannelID)),
263 use_mojo_channel(false) {
266 ChildThreadImpl::Options::~Options() {
269 ChildThreadImpl::Options::Builder::Builder() {
272 ChildThreadImpl::Options::Builder&
273 ChildThreadImpl::Options::Builder::InBrowserProcess(
274 const InProcessChildThreadParams& params) {
275 options_.browser_process_io_runner = params.io_runner();
276 options_.channel_name = params.channel_name();
277 return *this;
280 ChildThreadImpl::Options::Builder&
281 ChildThreadImpl::Options::Builder::UseMojoChannel(bool use_mojo_channel) {
282 options_.use_mojo_channel = use_mojo_channel;
283 return *this;
286 ChildThreadImpl::Options::Builder&
287 ChildThreadImpl::Options::Builder::WithChannelName(
288 const std::string& channel_name) {
289 options_.channel_name = channel_name;
290 return *this;
293 ChildThreadImpl::Options::Builder&
294 ChildThreadImpl::Options::Builder::AddStartupFilter(
295 IPC::MessageFilter* filter) {
296 options_.startup_filters.push_back(filter);
297 return *this;
300 ChildThreadImpl::Options ChildThreadImpl::Options::Builder::Build() {
301 return options_;
304 ChildThreadImpl::ChildThreadMessageRouter::ChildThreadMessageRouter(
305 IPC::Sender* sender)
306 : sender_(sender) {}
308 bool ChildThreadImpl::ChildThreadMessageRouter::Send(IPC::Message* msg) {
309 return sender_->Send(msg);
312 ChildThreadImpl::ChildThreadImpl()
313 : router_(this),
314 channel_connected_factory_(this) {
315 Init(Options::Builder().Build());
318 ChildThreadImpl::ChildThreadImpl(const Options& options)
319 : router_(this),
320 browser_process_io_runner_(options.browser_process_io_runner),
321 channel_connected_factory_(this) {
322 Init(options);
325 scoped_refptr<base::SequencedTaskRunner> ChildThreadImpl::GetIOTaskRunner() {
326 if (IsInBrowserProcess())
327 return browser_process_io_runner_;
328 return ChildProcess::current()->io_task_runner();
331 void ChildThreadImpl::ConnectChannel(bool use_mojo_channel) {
332 bool create_pipe_now = true;
333 if (use_mojo_channel) {
334 VLOG(1) << "Mojo is enabled on child";
335 scoped_refptr<base::SequencedTaskRunner> io_task_runner = GetIOTaskRunner();
336 DCHECK(io_task_runner);
337 channel_->Init(IPC::ChannelMojo::CreateClientFactory(
338 io_task_runner, channel_name_, attachment_broker_.get()),
339 create_pipe_now);
340 return;
343 VLOG(1) << "Mojo is disabled on child";
344 channel_->Init(channel_name_, IPC::Channel::MODE_CLIENT, create_pipe_now,
345 attachment_broker_.get());
348 void ChildThreadImpl::Init(const Options& options) {
349 channel_name_ = options.channel_name;
351 g_lazy_tls.Pointer()->Set(this);
352 on_channel_error_called_ = false;
353 message_loop_ = base::MessageLoop::current();
354 #ifdef IPC_MESSAGE_LOG_ENABLED
355 // We must make sure to instantiate the IPC Logger *before* we create the
356 // channel, otherwise we can get a callback on the IO thread which creates
357 // the logger, and the logger does not like being created on the IO thread.
358 IPC::Logging::GetInstance();
359 #endif
360 channel_ =
361 IPC::SyncChannel::Create(this, ChildProcess::current()->io_task_runner(),
362 ChildProcess::current()->GetShutDownEvent());
363 #ifdef IPC_MESSAGE_LOG_ENABLED
364 if (!IsInBrowserProcess())
365 IPC::Logging::GetInstance()->SetIPCSender(this);
366 #endif
368 #if defined(OS_WIN)
369 attachment_broker_.reset(new IPC::AttachmentBrokerWin());
370 #endif
372 mojo_application_.reset(new MojoApplication(GetIOTaskRunner()));
374 sync_message_filter_ =
375 new IPC::SyncMessageFilter(ChildProcess::current()->GetShutDownEvent());
376 thread_safe_sender_ = new ThreadSafeSender(
377 message_loop_->task_runner(), sync_message_filter_.get());
379 resource_dispatcher_.reset(new ResourceDispatcher(
380 this, message_loop()->task_runner()));
381 websocket_dispatcher_.reset(new WebSocketDispatcher);
382 file_system_dispatcher_.reset(new FileSystemDispatcher());
384 histogram_message_filter_ = new ChildHistogramMessageFilter();
385 resource_message_filter_ =
386 new ChildResourceMessageFilter(resource_dispatcher());
388 service_worker_message_filter_ =
389 new ServiceWorkerMessageFilter(thread_safe_sender_.get());
391 quota_message_filter_ =
392 new QuotaMessageFilter(thread_safe_sender_.get());
393 quota_dispatcher_.reset(new QuotaDispatcher(thread_safe_sender_.get(),
394 quota_message_filter_.get()));
395 geofencing_message_filter_ =
396 new GeofencingMessageFilter(thread_safe_sender_.get());
397 bluetooth_message_filter_ =
398 new BluetoothMessageFilter(thread_safe_sender_.get());
399 notification_dispatcher_ =
400 new NotificationDispatcher(thread_safe_sender_.get());
401 push_dispatcher_ = new PushDispatcher(thread_safe_sender_.get());
403 channel_->AddFilter(histogram_message_filter_.get());
404 channel_->AddFilter(sync_message_filter_.get());
405 channel_->AddFilter(resource_message_filter_.get());
406 channel_->AddFilter(quota_message_filter_->GetFilter());
407 channel_->AddFilter(notification_dispatcher_->GetFilter());
408 channel_->AddFilter(push_dispatcher_->GetFilter());
409 channel_->AddFilter(service_worker_message_filter_->GetFilter());
410 channel_->AddFilter(geofencing_message_filter_->GetFilter());
411 channel_->AddFilter(bluetooth_message_filter_->GetFilter());
413 if (!IsInBrowserProcess()) {
414 // In single process mode, browser-side tracing will cover the whole
415 // process including renderers.
416 channel_->AddFilter(new tracing::ChildTraceMessageFilter(
417 ChildProcess::current()->io_task_runner()));
420 // In single process mode we may already have a power monitor
421 if (!base::PowerMonitor::Get()) {
422 scoped_ptr<PowerMonitorBroadcastSource> power_monitor_source(
423 new PowerMonitorBroadcastSource());
424 channel_->AddFilter(power_monitor_source->GetMessageFilter());
426 power_monitor_.reset(new base::PowerMonitor(
427 power_monitor_source.Pass()));
430 #if defined(OS_POSIX)
431 // Check that --process-type is specified so we don't do this in unit tests
432 // and single-process mode.
433 if (base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kProcessType))
434 channel_->AddFilter(new SuicideOnChannelErrorFilter());
435 #endif
437 #if defined(OS_MACOSX)
438 channel_->AddFilter(new IOSurfaceManagerFilter());
439 #endif
441 // Add filters passed here via options.
442 for (auto startup_filter : options.startup_filters) {
443 channel_->AddFilter(startup_filter);
446 ConnectChannel(options.use_mojo_channel);
448 int connection_timeout = kConnectionTimeoutS;
449 std::string connection_override =
450 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
451 switches::kIPCConnectionTimeout);
452 if (!connection_override.empty()) {
453 int temp;
454 if (base::StringToInt(connection_override, &temp))
455 connection_timeout = temp;
458 message_loop_->task_runner()->PostDelayedTask(
459 FROM_HERE, base::Bind(&ChildThreadImpl::EnsureConnected,
460 channel_connected_factory_.GetWeakPtr()),
461 base::TimeDelta::FromSeconds(connection_timeout));
463 #if defined(OS_ANDROID)
464 g_quit_closure.Get().BindToMainThread();
465 #endif
467 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
468 trace_memory_controller_.reset(new base::trace_event::TraceMemoryController(
469 message_loop_->task_runner(), ::HeapProfilerWithPseudoStackStart,
470 ::HeapProfilerStop, ::GetHeapProfile));
471 #endif
473 base::trace_event::MemoryDumpManager::GetInstance()->Initialize();
475 shared_bitmap_manager_.reset(
476 new ChildSharedBitmapManager(thread_safe_sender()));
478 gpu_memory_buffer_manager_.reset(
479 new ChildGpuMemoryBufferManager(thread_safe_sender()));
481 discardable_shared_memory_manager_.reset(
482 new ChildDiscardableSharedMemoryManager(thread_safe_sender()));
485 ChildThreadImpl::~ChildThreadImpl() {
486 // ChildDiscardableSharedMemoryManager has to be destroyed while
487 // |thread_safe_sender_| is still valid.
488 discardable_shared_memory_manager_.reset();
490 #ifdef IPC_MESSAGE_LOG_ENABLED
491 IPC::Logging::GetInstance()->SetIPCSender(NULL);
492 #endif
494 channel_->RemoveFilter(histogram_message_filter_.get());
495 channel_->RemoveFilter(sync_message_filter_.get());
497 // The ChannelProxy object caches a pointer to the IPC thread, so need to
498 // reset it as it's not guaranteed to outlive this object.
499 // NOTE: this also has the side-effect of not closing the main IPC channel to
500 // the browser process. This is needed because this is the signal that the
501 // browser uses to know that this process has died, so we need it to be alive
502 // until this process is shut down, and the OS closes the handle
503 // automatically. We used to watch the object handle on Windows to do this,
504 // but it wasn't possible to do so on POSIX.
505 channel_->ClearIPCTaskRunner();
506 g_lazy_tls.Pointer()->Set(NULL);
509 void ChildThreadImpl::Shutdown() {
510 // Delete objects that hold references to blink so derived classes can
511 // safely shutdown blink in their Shutdown implementation.
512 file_system_dispatcher_.reset();
513 quota_dispatcher_.reset();
514 WebFileSystemImpl::DeleteThreadSpecificInstance();
517 void ChildThreadImpl::OnChannelConnected(int32 peer_pid) {
518 channel_connected_factory_.InvalidateWeakPtrs();
521 void ChildThreadImpl::OnChannelError() {
522 set_on_channel_error_called(true);
523 base::MessageLoop::current()->Quit();
526 bool ChildThreadImpl::Send(IPC::Message* msg) {
527 DCHECK(base::MessageLoop::current() == message_loop());
528 if (!channel_) {
529 delete msg;
530 return false;
533 return channel_->Send(msg);
536 #if defined(OS_WIN)
537 void ChildThreadImpl::PreCacheFont(const LOGFONT& log_font) {
538 Send(new ChildProcessHostMsg_PreCacheFont(log_font));
541 void ChildThreadImpl::ReleaseCachedFonts() {
542 Send(new ChildProcessHostMsg_ReleaseCachedFonts());
544 #endif
546 IPC::AttachmentBroker* ChildThreadImpl::GetAttachmentBroker() {
547 return attachment_broker_.get();
550 MessageRouter* ChildThreadImpl::GetRouter() {
551 DCHECK(base::MessageLoop::current() == message_loop());
552 return &router_;
555 scoped_ptr<base::SharedMemory> ChildThreadImpl::AllocateSharedMemory(
556 size_t buf_size) {
557 DCHECK(base::MessageLoop::current() == message_loop());
558 return AllocateSharedMemory(buf_size, this);
561 // static
562 scoped_ptr<base::SharedMemory> ChildThreadImpl::AllocateSharedMemory(
563 size_t buf_size,
564 IPC::Sender* sender) {
565 scoped_ptr<base::SharedMemory> shared_buf;
566 #if defined(OS_WIN)
567 shared_buf.reset(new base::SharedMemory);
568 if (!shared_buf->CreateAnonymous(buf_size)) {
569 NOTREACHED();
570 return NULL;
572 #else
573 // On POSIX, we need to ask the browser to create the shared memory for us,
574 // since this is blocked by the sandbox.
575 base::SharedMemoryHandle shared_mem_handle;
576 if (sender->Send(new ChildProcessHostMsg_SyncAllocateSharedMemory(
577 buf_size, &shared_mem_handle))) {
578 if (base::SharedMemory::IsHandleValid(shared_mem_handle)) {
579 shared_buf.reset(new base::SharedMemory(shared_mem_handle, false));
580 } else {
581 NOTREACHED() << "Browser failed to allocate shared memory";
582 return NULL;
584 } else {
585 NOTREACHED() << "Browser allocation request message failed";
586 return NULL;
588 #endif
589 return shared_buf;
592 bool ChildThreadImpl::OnMessageReceived(const IPC::Message& msg) {
593 if (mojo_application_->OnMessageReceived(msg))
594 return true;
596 // Resource responses are sent to the resource dispatcher.
597 if (resource_dispatcher_->OnMessageReceived(msg))
598 return true;
599 if (websocket_dispatcher_->OnMessageReceived(msg))
600 return true;
601 if (file_system_dispatcher_->OnMessageReceived(msg))
602 return true;
604 bool handled = true;
605 IPC_BEGIN_MESSAGE_MAP(ChildThreadImpl, msg)
606 IPC_MESSAGE_HANDLER(ChildProcessMsg_Shutdown, OnShutdown)
607 #if defined(IPC_MESSAGE_LOG_ENABLED)
608 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetIPCLoggingEnabled,
609 OnSetIPCLoggingEnabled)
610 #endif
611 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetProfilerStatus,
612 OnSetProfilerStatus)
613 IPC_MESSAGE_HANDLER(ChildProcessMsg_GetChildProfilerData,
614 OnGetChildProfilerData)
615 IPC_MESSAGE_HANDLER(ChildProcessMsg_ProfilingPhaseCompleted,
616 OnProfilingPhaseCompleted)
617 IPC_MESSAGE_HANDLER(ChildProcessMsg_SetProcessBackgrounded,
618 OnProcessBackgrounded)
619 #if defined(USE_TCMALLOC)
620 IPC_MESSAGE_HANDLER(ChildProcessMsg_GetTcmallocStats, OnGetTcmallocStats)
621 #endif
622 IPC_MESSAGE_UNHANDLED(handled = false)
623 IPC_END_MESSAGE_MAP()
625 if (handled)
626 return true;
628 if (msg.routing_id() == MSG_ROUTING_CONTROL)
629 return OnControlMessageReceived(msg);
631 return router_.OnMessageReceived(msg);
634 bool ChildThreadImpl::OnControlMessageReceived(const IPC::Message& msg) {
635 return false;
638 void ChildThreadImpl::OnShutdown() {
639 base::MessageLoop::current()->Quit();
642 #if defined(IPC_MESSAGE_LOG_ENABLED)
643 void ChildThreadImpl::OnSetIPCLoggingEnabled(bool enable) {
644 if (enable)
645 IPC::Logging::GetInstance()->Enable();
646 else
647 IPC::Logging::GetInstance()->Disable();
649 #endif // IPC_MESSAGE_LOG_ENABLED
651 void ChildThreadImpl::OnSetProfilerStatus(ThreadData::Status status) {
652 ThreadData::InitializeAndSetTrackingStatus(status);
655 void ChildThreadImpl::OnGetChildProfilerData(int sequence_number,
656 int current_profiling_phase) {
657 tracked_objects::ProcessDataSnapshot process_data;
658 ThreadData::Snapshot(current_profiling_phase, &process_data);
660 Send(
661 new ChildProcessHostMsg_ChildProfilerData(sequence_number, process_data));
664 void ChildThreadImpl::OnProfilingPhaseCompleted(int profiling_phase) {
665 ThreadData::OnProfilingPhaseCompleted(profiling_phase);
668 #if defined(USE_TCMALLOC)
669 void ChildThreadImpl::OnGetTcmallocStats() {
670 std::string result;
671 char buffer[1024 * 32];
672 base::allocator::GetStats(buffer, sizeof(buffer));
673 result.append(buffer);
674 Send(new ChildProcessHostMsg_TcmallocStats(result));
676 #endif
678 ChildThreadImpl* ChildThreadImpl::current() {
679 return g_lazy_tls.Pointer()->Get();
682 #if defined(OS_ANDROID)
683 // The method must NOT be called on the child thread itself.
684 // It may block the child thread if so.
685 void ChildThreadImpl::ShutdownThread() {
686 DCHECK(!ChildThreadImpl::current()) <<
687 "this method should NOT be called from child thread itself";
688 g_quit_closure.Get().PostQuitFromNonMainThread();
690 #endif
692 void ChildThreadImpl::OnProcessFinalRelease() {
693 if (on_channel_error_called_) {
694 base::MessageLoop::current()->Quit();
695 return;
698 // The child process shutdown sequence is a request response based mechanism,
699 // where we send out an initial feeler request to the child process host
700 // instance in the browser to verify if it's ok to shutdown the child process.
701 // The browser then sends back a response if it's ok to shutdown. This avoids
702 // race conditions if the process refcount is 0 but there's an IPC message
703 // inflight that would addref it.
704 Send(new ChildProcessHostMsg_ShutdownRequest);
707 void ChildThreadImpl::EnsureConnected() {
708 VLOG(0) << "ChildThreadImpl::EnsureConnected()";
709 base::Process::Current().Terminate(0, false);
712 bool ChildThreadImpl::IsInBrowserProcess() const {
713 return browser_process_io_runner_;
716 void ChildThreadImpl::OnProcessBackgrounded(bool background) {
717 // Set timer slack to maximum on main thread when in background.
718 base::TimerSlack timer_slack = base::TIMER_SLACK_NONE;
719 if (background)
720 timer_slack = base::TIMER_SLACK_MAXIMUM;
721 base::MessageLoop::current()->SetTimerSlack(timer_slack);
724 } // namespace content