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.
4 
5 #include "content/child/child_thread_impl.h"
6 
7 #include <signal.h>
8 #include <string>
9 #include <utility>
10 
11 #include "base/base_switches.h"
12 #include "base/bind.h"
13 #include "base/clang_profiling_buildflags.h"
14 #include "base/command_line.h"
15 #include "base/compiler_specific.h"
16 #include "base/debug/alias.h"
17 #include "base/debug/leak_annotations.h"
18 #include "base/debug/profiler.h"
19 #include "base/files/file.h"
20 #include "base/lazy_instance.h"
21 #include "base/location.h"
22 #include "base/logging.h"
23 #include "base/macros.h"
24 #include "base/memory/memory_pressure_listener.h"
25 #include "base/message_loop/timer_slack.h"
26 #include "base/metrics/field_trial.h"
27 #include "base/metrics/histogram_macros.h"
28 #include "base/no_destructor.h"
29 #include "base/power_monitor/power_monitor.h"
30 #include "base/process/process.h"
31 #include "base/process/process_handle.h"
32 #include "base/run_loop.h"
33 #include "base/single_thread_task_runner.h"
34 #include "base/strings/string_number_conversions.h"
35 #include "base/strings/string_util.h"
36 #include "base/synchronization/condition_variable.h"
37 #include "base/synchronization/lock.h"
38 #include "base/threading/thread_local.h"
39 #include "base/threading/thread_task_runner_handle.h"
40 #include "base/timer/elapsed_timer.h"
41 #include "base/trace_event/memory_dump_manager.h"
42 #include "base/trace_event/trace_event.h"
43 #include "build/build_config.h"
44 #include "content/child/browser_exposed_child_interfaces.h"
45 #include "content/child/child_process.h"
46 #include "content/child/thread_safe_sender.h"
47 #include "content/common/child_process.mojom.h"
48 #include "content/common/field_trial_recorder.mojom.h"
49 #include "content/common/in_process_child_thread_params.h"
50 #include "content/public/common/content_client.h"
51 #include "content/public/common/content_features.h"
52 #include "content/public/common/content_switches.h"
53 #include "ipc/ipc_channel_mojo.h"
54 #include "ipc/ipc_logging.h"
55 #include "ipc/ipc_platform_file.h"
56 #include "ipc/ipc_sync_channel.h"
57 #include "ipc/ipc_sync_message_filter.h"
58 #include "mojo/core/embedder/scoped_ipc_support.h"
59 #include "mojo/public/cpp/bindings/pending_receiver.h"
60 #include "mojo/public/cpp/bindings/pending_remote.h"
61 #include "mojo/public/cpp/bindings/remote.h"
62 #include "mojo/public/cpp/bindings/self_owned_receiver.h"
63 #include "mojo/public/cpp/platform/named_platform_channel.h"
64 #include "mojo/public/cpp/platform/platform_channel.h"
65 #include "mojo/public/cpp/platform/platform_channel_endpoint.h"
66 #include "mojo/public/cpp/platform/platform_handle.h"
67 #include "mojo/public/cpp/system/buffer.h"
68 #include "mojo/public/cpp/system/invitation.h"
69 #include "mojo/public/cpp/system/platform_handle.h"
70 #include "services/device/public/cpp/power_monitor/power_monitor_broadcast_source.h"
71 #include "services/resource_coordinator/public/cpp/memory_instrumentation/client_process_impl.h"
72 #include "services/resource_coordinator/public/mojom/memory_instrumentation/memory_instrumentation.mojom.h"
73 #include "services/service_manager/embedder/switches.h"
74 #include "services/service_manager/sandbox/sandbox_type.h"
75 #include "services/tracing/public/cpp/background_tracing/background_tracing_agent_impl.h"
76 #include "services/tracing/public/cpp/background_tracing/background_tracing_agent_provider_impl.h"
77 
78 #if defined(OS_POSIX)
79 #include "base/posix/global_descriptors.h"
80 #include "content/public/common/content_descriptors.h"
81 #endif
82 
83 #if defined(OS_MACOSX)
84 #include "base/mac/mach_port_rendezvous.h"
85 #endif
86 
87 #if BUILDFLAG(CLANG_PROFILING_INSIDE_SANDBOX)
88 #include <stdio.h>
89 #if defined(OS_WIN)
90 #include <io.h>
91 #endif
92 // Function provided by libclang_rt.profile-*.a, declared and documented at:
93 // https://github.com/llvm/llvm-project/blob/master/compiler-rt/lib/profile/InstrProfiling.h
94 extern "C" void __llvm_profile_set_file_object(FILE* File, int EnableMerge);
95 #endif
96 
97 namespace content {
98 namespace {
99 
100 // How long to wait for a connection to the browser process before giving up.
101 const int kConnectionTimeoutS = 15;
102 
103 base::LazyInstance<base::ThreadLocalPointer<ChildThreadImpl>>::DestructorAtExit
104     g_lazy_child_thread_impl_tls = LAZY_INSTANCE_INITIALIZER;
105 
106 // This isn't needed on Windows because there the sandbox's job object
107 // terminates child processes automatically. For unsandboxed processes (i.e.
108 // plugins), PluginThread has EnsureTerminateMessageFilter.
109 #if defined(OS_POSIX)
110 
111 #if defined(ADDRESS_SANITIZER) || defined(LEAK_SANITIZER) || \
112     defined(MEMORY_SANITIZER) || defined(THREAD_SANITIZER) || \
113     defined(UNDEFINED_SANITIZER)
114 // A thread delegate that waits for |duration| and then exits the process
115 // immediately, without executing finalizers.
116 class WaitAndExitDelegate : public base::PlatformThread::Delegate {
117  public:
WaitAndExitDelegate(base::TimeDelta duration)118   explicit WaitAndExitDelegate(base::TimeDelta duration)
119       : duration_(duration) {}
120 
ThreadMain()121   void ThreadMain() override {
122     base::PlatformThread::Sleep(duration_);
123     base::Process::TerminateCurrentProcessImmediately(0);
124   }
125 
126  private:
127   const base::TimeDelta duration_;
128   DISALLOW_COPY_AND_ASSIGN(WaitAndExitDelegate);
129 };
130 
CreateWaitAndExitThread(base::TimeDelta duration)131 bool CreateWaitAndExitThread(base::TimeDelta duration) {
132   std::unique_ptr<WaitAndExitDelegate> delegate(
133       new WaitAndExitDelegate(duration));
134 
135   const bool thread_created =
136       base::PlatformThread::CreateNonJoinable(0, delegate.get());
137   if (!thread_created)
138     return false;
139 
140   // A non joinable thread has been created. The thread will either terminate
141   // the process or will be terminated by the process. Therefore, keep the
142   // delegate object alive for the lifetime of the process.
143   WaitAndExitDelegate* leaking_delegate = delegate.release();
144   ANNOTATE_LEAKING_OBJECT_PTR(leaking_delegate);
145   ignore_result(leaking_delegate);
146   return true;
147 }
148 #endif
149 
150 class SuicideOnChannelErrorFilter : public IPC::MessageFilter {
151  public:
152   // IPC::MessageFilter
OnChannelError()153   void OnChannelError() override {
154     // For renderer/worker processes:
155     // On POSIX, at least, one can install an unload handler which loops
156     // forever and leave behind a renderer process which eats 100% CPU forever.
157     //
158     // This is because the terminate signals (FrameMsg_BeforeUnload and the
159     // error from the IPC sender) are routed to the main message loop but never
160     // processed (because that message loop is stuck in V8).
161     //
162     // One could make the browser SIGKILL the renderers, but that leaves open a
163     // large window where a browser failure (or a user, manually terminating
164     // the browser because "it's stuck") will leave behind a process eating all
165     // the CPU.
166     //
167     // So, we install a filter on the sender so that we can process this event
168     // here and kill the process.
169     base::debug::StopProfiling();
170 #if defined(ADDRESS_SANITIZER) || defined(LEAK_SANITIZER) || \
171     defined(MEMORY_SANITIZER) || defined(THREAD_SANITIZER) || \
172     defined(UNDEFINED_SANITIZER)
173     // Some sanitizer tools rely on exit handlers (e.g. to run leak detection,
174     // or dump code coverage data to disk). Instead of exiting the process
175     // immediately, we give it 60 seconds to run exit handlers.
176     CHECK(CreateWaitAndExitThread(base::TimeDelta::FromSeconds(60)));
177 #if defined(LEAK_SANITIZER)
178     // Invoke LeakSanitizer early to avoid detecting shutdown-only leaks. If
179     // leaks are found, the process will exit here.
180     __lsan_do_leak_check();
181 #endif
182 #else
183     base::Process::TerminateCurrentProcessImmediately(0);
184 #endif
185   }
186 
187  protected:
~SuicideOnChannelErrorFilter()188   ~SuicideOnChannelErrorFilter() override {}
189 };
190 
191 #endif  // OS(POSIX)
192 
InitializeMojoIPCChannel()193 mojo::IncomingInvitation InitializeMojoIPCChannel() {
194   TRACE_EVENT0("startup", "InitializeMojoIPCChannel");
195   mojo::PlatformChannelEndpoint endpoint;
196 #if defined(OS_WIN)
197   if (base::CommandLine::ForCurrentProcess()->HasSwitch(
198           mojo::PlatformChannel::kHandleSwitch)) {
199     endpoint = mojo::PlatformChannel::RecoverPassedEndpointFromCommandLine(
200         *base::CommandLine::ForCurrentProcess());
201   } else {
202     // If this process is elevated, it will have a pipe path passed on the
203     // command line.
204     endpoint = mojo::NamedPlatformChannel::ConnectToServer(
205         *base::CommandLine::ForCurrentProcess());
206   }
207 #elif defined(OS_FUCHSIA)
208   endpoint = mojo::PlatformChannel::RecoverPassedEndpointFromCommandLine(
209       *base::CommandLine::ForCurrentProcess());
210 #elif defined(OS_MACOSX)
211   auto* client = base::MachPortRendezvousClient::GetInstance();
212   if (!client) {
213     LOG(ERROR) << "Mach rendezvous failed, terminating process (parent died?)";
214     base::Process::TerminateCurrentProcessImmediately(0);
215     return {};
216   }
217   auto receive = client->TakeReceiveRight('mojo');
218   if (!receive.is_valid()) {
219     LOG(ERROR) << "Invalid PlatformChannel receive right";
220     return {};
221   }
222   endpoint =
223       mojo::PlatformChannelEndpoint(mojo::PlatformHandle(std::move(receive)));
224 #elif defined(OS_POSIX)
225   endpoint = mojo::PlatformChannelEndpoint(mojo::PlatformHandle(
226       base::ScopedFD(base::GlobalDescriptors::GetInstance()->Get(
227           service_manager::kMojoIPCChannel))));
228 #endif
229 
230   return mojo::IncomingInvitation::Accept(
231       std::move(endpoint), MOJO_ACCEPT_INVITATION_FLAG_LEAK_TRANSPORT_ENDPOINT);
232 }
233 
234 }  // namespace
235 
236 // Implements the mojom ChildProcess interface and lives on the IO thread.
237 class ChildThreadImpl::IOThreadState
238     : public base::RefCountedThreadSafe<IOThreadState>,
239       public mojom::ChildProcess {
240  public:
IOThreadState(scoped_refptr<base::SequencedTaskRunner> main_thread_task_runner,base::WeakPtr<ChildThreadImpl> weak_main_thread,base::RepeatingClosure quit_closure,ChildThreadImpl::Options::ServiceBinder service_binder,mojo::PendingReceiver<mojom::ChildProcessHost> host_receiver)241   IOThreadState(
242       scoped_refptr<base::SequencedTaskRunner> main_thread_task_runner,
243       base::WeakPtr<ChildThreadImpl> weak_main_thread,
244       base::RepeatingClosure quit_closure,
245       ChildThreadImpl::Options::ServiceBinder service_binder,
246       mojo::PendingReceiver<mojom::ChildProcessHost> host_receiver)
247       : main_thread_task_runner_(std::move(main_thread_task_runner)),
248         weak_main_thread_(std::move(weak_main_thread)),
249         quit_closure_(std::move(quit_closure)),
250         service_binder_(std::move(service_binder)),
251         host_receiver_(std::move(host_receiver)) {}
252 
253   // Used only in the deprecated Service Manager IPC mode.
BindChildProcessReceiver(mojo::PendingReceiver<mojom::ChildProcess> receiver)254   void BindChildProcessReceiver(
255       mojo::PendingReceiver<mojom::ChildProcess> receiver) {
256     receiver_.Bind(std::move(receiver));
257   }
258 
259   // Used in non-Service Manager IPC mode.
BindChildProcessReceiverAndLegacyIpc(mojo::PendingReceiver<mojom::ChildProcess> receiver,mojo::PendingRemote<IPC::mojom::ChannelBootstrap> legacy_ipc_bootstrap)260   void BindChildProcessReceiverAndLegacyIpc(
261       mojo::PendingReceiver<mojom::ChildProcess> receiver,
262       mojo::PendingRemote<IPC::mojom::ChannelBootstrap> legacy_ipc_bootstrap) {
263     legacy_ipc_bootstrap_ = std::move(legacy_ipc_bootstrap);
264     receiver_.Bind(std::move(receiver));
265   }
266 
ExposeInterfacesToBrowser(mojo::BinderMap binders)267   void ExposeInterfacesToBrowser(mojo::BinderMap binders) {
268     DCHECK(wait_for_interface_binders_);
269     wait_for_interface_binders_ = false;
270     interface_binders_ = std::move(binders);
271     std::vector<mojo::GenericPendingReceiver> pending_requests;
272     std::swap(pending_requests, pending_binding_requests_);
273     for (auto& receiver : pending_requests)
274       BindReceiver(std::move(receiver));
275   }
276 
277  private:
278   friend class base::RefCountedThreadSafe<IOThreadState>;
279 
280   ~IOThreadState() override = default;
281 
282   // mojom::ChildProcess:
Initialize(mojo::PendingRemote<mojom::ChildProcessHostBootstrap> bootstrap)283   void Initialize(mojo::PendingRemote<mojom::ChildProcessHostBootstrap>
284                       bootstrap) override {
285     // The browser only calls this method once.
286     DCHECK(host_receiver_);
287     mojo::Remote<mojom::ChildProcessHostBootstrap>(std::move(bootstrap))
288         ->BindProcessHost(std::move(host_receiver_));
289   }
290 
ProcessShutdown()291   void ProcessShutdown() override {
292     main_thread_task_runner_->PostTask(FROM_HERE,
293                                        base::BindOnce(quit_closure_));
294   }
295 
296 #if defined(OS_MACOSX)
GetTaskPort(GetTaskPortCallback callback)297   void GetTaskPort(GetTaskPortCallback callback) override {
298     mojo::PlatformHandle task_port(
299         (base::mac::ScopedMachSendRight(task_self_trap())));
300     std::move(callback).Run(std::move(task_port));
301   }
302 #endif
303 
304 #if BUILDFLAG(IPC_MESSAGE_LOG_ENABLED)
SetIPCLoggingEnabled(bool enable)305   void SetIPCLoggingEnabled(bool enable) override {
306     main_thread_task_runner_->PostTask(
307         FROM_HERE, base::BindOnce(
308                        [](bool enable) {
309                          if (enable)
310                            IPC::Logging::GetInstance()->Enable();
311                          else
312                            IPC::Logging::GetInstance()->Disable();
313                        },
314                        enable));
315   }
316 #endif
317 
GetBackgroundTracingAgentProvider(mojo::PendingReceiver<tracing::mojom::BackgroundTracingAgentProvider> receiver)318   void GetBackgroundTracingAgentProvider(
319       mojo::PendingReceiver<tracing::mojom::BackgroundTracingAgentProvider>
320           receiver) override {
321     main_thread_task_runner_->PostTask(
322         FROM_HERE,
323         base::BindOnce(&ChildThreadImpl::GetBackgroundTracingAgentProvider,
324                        weak_main_thread_, std::move(receiver)));
325   }
326 
327   // Make sure this isn't inlined so it shows up in stack traces, and also make
328   // the function body unique by adding a log line, so it doesn't get merged
329   // with other functions by link time optimizations (ICF).
CrashHungProcess()330   NOINLINE void CrashHungProcess() override {
331     LOG(ERROR) << "Crashing because hung";
332     IMMEDIATE_CRASH();
333   }
334 
BootstrapLegacyIpc(mojo::PendingReceiver<IPC::mojom::ChannelBootstrap> receiver)335   void BootstrapLegacyIpc(
336       mojo::PendingReceiver<IPC::mojom::ChannelBootstrap> receiver) override {
337     DCHECK(legacy_ipc_bootstrap_);
338     mojo::FusePipes(std::move(receiver), std::move(legacy_ipc_bootstrap_));
339   }
340 
RunService(const std::string & service_name,mojo::PendingReceiver<service_manager::mojom::Service> receiver)341   void RunService(const std::string& service_name,
342                   mojo::PendingReceiver<service_manager::mojom::Service>
343                       receiver) override {
344     main_thread_task_runner_->PostTask(
345         FROM_HERE,
346         base::BindOnce(&ChildThreadImpl::RunService, weak_main_thread_,
347                        service_name, std::move(receiver)));
348   }
349 
BindServiceInterface(mojo::GenericPendingReceiver receiver)350   void BindServiceInterface(mojo::GenericPendingReceiver receiver) override {
351     if (service_binder_)
352       service_binder_.Run(&receiver);
353 
354     if (receiver) {
355       main_thread_task_runner_->PostTask(
356           FROM_HERE, base::BindOnce(&ChildThreadImpl::BindServiceInterface,
357                                     weak_main_thread_, std::move(receiver)));
358     }
359   }
360 
BindReceiver(mojo::GenericPendingReceiver receiver)361   void BindReceiver(mojo::GenericPendingReceiver receiver) override {
362     if (wait_for_interface_binders_) {
363       pending_binding_requests_.push_back(std::move(receiver));
364       return;
365     }
366 
367     if (interface_binders_.Bind(&receiver))
368       return;
369 
370     main_thread_task_runner_->PostTask(
371         FROM_HERE, base::BindOnce(&ChildThreadImpl::OnBindReceiver,
372                                   weak_main_thread_, std::move(receiver)));
373   }
374 
375 #if BUILDFLAG(CLANG_PROFILING_INSIDE_SANDBOX)
SetProfilingFile(base::File file)376   void SetProfilingFile(base::File file) override {
377     // TODO(crbug.com/985574) Remove Android check when possible.
378 #if defined(OS_POSIX) && !defined(OS_ANDROID)
379     // Take the file descriptor so that |file| does not close it.
380     int fd = file.TakePlatformFile();
381     FILE* f = fdopen(fd, "r+b");
382     __llvm_profile_set_file_object(f, 1);
383 #elif defined(OS_WIN)
384     HANDLE handle = file.TakePlatformFile();
385     int fd = _open_osfhandle((intptr_t)handle, 0);
386     FILE* f = _fdopen(fd, "r+b");
387     __llvm_profile_set_file_object(f, 1);
388 #endif
389   }
390 #endif
391 
392   const scoped_refptr<base::SequencedTaskRunner> main_thread_task_runner_;
393   const base::WeakPtr<ChildThreadImpl> weak_main_thread_;
394   const base::RepeatingClosure quit_closure_;
395 
396   ChildThreadImpl::Options::ServiceBinder service_binder_;
397   mojo::BinderMap interface_binders_;
398   bool wait_for_interface_binders_ = true;
399   mojo::Receiver<mojom::ChildProcess> receiver_{this};
400   mojo::PendingReceiver<mojom::ChildProcessHost> host_receiver_;
401 
402   // The pending legacy IPC channel endpoint to fuse with one we will eventually
403   // receiver on the ChildProcess interface. Only used when not in the
404   // deprecated Service Manager IPC mode.
405   mojo::PendingRemote<IPC::mojom::ChannelBootstrap> legacy_ipc_bootstrap_;
406 
407   // Binding requests which should be handled by |interface_binders|, but which
408   // have been queued because |allow_interface_binders_| is still |false|.
409   std::vector<mojo::GenericPendingReceiver> pending_binding_requests_;
410 
411   DISALLOW_COPY_AND_ASSIGN(IOThreadState);
412 };
413 
Get()414 ChildThread* ChildThread::Get() {
415   return ChildThreadImpl::current();
416 }
417 
Options()418 ChildThreadImpl::Options::Options() : connect_to_browser(false) {}
419 
420 ChildThreadImpl::Options::Options(const Options& other) = default;
421 
~Options()422 ChildThreadImpl::Options::~Options() {
423 }
424 
Builder()425 ChildThreadImpl::Options::Builder::Builder() {
426 }
427 
428 ChildThreadImpl::Options::Builder&
InBrowserProcess(const InProcessChildThreadParams & params)429 ChildThreadImpl::Options::Builder::InBrowserProcess(
430     const InProcessChildThreadParams& params) {
431   options_.browser_process_io_runner = params.io_runner();
432   options_.mojo_invitation = params.mojo_invitation();
433   return *this;
434 }
435 
436 ChildThreadImpl::Options::Builder&
ConnectToBrowser(bool connect_to_browser_parms)437 ChildThreadImpl::Options::Builder::ConnectToBrowser(
438     bool connect_to_browser_parms) {
439   options_.connect_to_browser = connect_to_browser_parms;
440   return *this;
441 }
442 
443 ChildThreadImpl::Options::Builder&
AddStartupFilter(IPC::MessageFilter * filter)444 ChildThreadImpl::Options::Builder::AddStartupFilter(
445     IPC::MessageFilter* filter) {
446   options_.startup_filters.push_back(filter);
447   return *this;
448 }
449 
450 ChildThreadImpl::Options::Builder&
IPCTaskRunner(scoped_refptr<base::SingleThreadTaskRunner> ipc_task_runner_parms)451 ChildThreadImpl::Options::Builder::IPCTaskRunner(
452     scoped_refptr<base::SingleThreadTaskRunner> ipc_task_runner_parms) {
453   options_.ipc_task_runner = ipc_task_runner_parms;
454   return *this;
455 }
456 
457 ChildThreadImpl::Options::Builder&
ServiceBinder(ChildThreadImpl::Options::ServiceBinder binder)458 ChildThreadImpl::Options::Builder::ServiceBinder(
459     ChildThreadImpl::Options::ServiceBinder binder) {
460   options_.service_binder = std::move(binder);
461   return *this;
462 }
463 
464 ChildThreadImpl::Options::Builder&
ExposesInterfacesToBrowser()465 ChildThreadImpl::Options::Builder::ExposesInterfacesToBrowser() {
466   options_.exposes_interfaces_to_browser = true;
467   return *this;
468 }
469 
Build()470 ChildThreadImpl::Options ChildThreadImpl::Options::Builder::Build() {
471   return options_;
472 }
473 
ChildThreadMessageRouter(IPC::Sender * sender)474 ChildThreadImpl::ChildThreadMessageRouter::ChildThreadMessageRouter(
475     IPC::Sender* sender)
476     : sender_(sender) {}
477 
Send(IPC::Message * msg)478 bool ChildThreadImpl::ChildThreadMessageRouter::Send(IPC::Message* msg) {
479   return sender_->Send(msg);
480 }
481 
RouteMessage(const IPC::Message & msg)482 bool ChildThreadImpl::ChildThreadMessageRouter::RouteMessage(
483     const IPC::Message& msg) {
484   bool handled = IPC::MessageRouter::RouteMessage(msg);
485 #if defined(OS_ANDROID)
486   if (!handled && msg.is_sync()) {
487     IPC::Message* reply = IPC::SyncMessage::GenerateReply(&msg);
488     reply->set_reply_error();
489     Send(reply);
490   }
491 #endif
492   return handled;
493 }
494 
ChildThreadImpl(base::RepeatingClosure quit_closure)495 ChildThreadImpl::ChildThreadImpl(base::RepeatingClosure quit_closure)
496     : ChildThreadImpl(std::move(quit_closure), Options::Builder().Build()) {}
497 
ChildThreadImpl(base::RepeatingClosure quit_closure,const Options & options)498 ChildThreadImpl::ChildThreadImpl(base::RepeatingClosure quit_closure,
499                                  const Options& options)
500     : router_(this),
501       quit_closure_(std::move(quit_closure)),
502       browser_process_io_runner_(options.browser_process_io_runner),
503       channel_connected_factory_(
504           new base::WeakPtrFactory<ChildThreadImpl>(this)),
505       ipc_task_runner_(options.ipc_task_runner) {
506   mojo::PendingRemote<mojom::ChildProcessHost> remote_host;
507   auto host_receiver = remote_host.InitWithNewPipeAndPassReceiver();
508   child_process_host_ = mojo::SharedRemote<mojom::ChildProcessHost>(
509       std::move(remote_host), GetIOTaskRunner());
510   io_thread_state_ = base::MakeRefCounted<IOThreadState>(
511       base::ThreadTaskRunnerHandle::Get(), weak_factory_.GetWeakPtr(),
512       quit_closure_, std::move(options.service_binder),
513       std::move(host_receiver));
514 
515   // |ExposeInterfacesToBrowser()| must be called exactly once. Subclasses which
516   // set |exposes_interfaces_to_browser| in Options signify that they take
517   // responsibility for calling it.
518   //
519   // For other process types, we call it to expose only the basic set of
520   // interfaces common to all child process types.
521   if (!options.exposes_interfaces_to_browser)
522     ExposeInterfacesToBrowser(mojo::BinderMap());
523 
524   Init(options);
525 }
526 
GetIOTaskRunner()527 scoped_refptr<base::SingleThreadTaskRunner> ChildThreadImpl::GetIOTaskRunner() {
528   if (IsInBrowserProcess())
529     return browser_process_io_runner_;
530   return ChildProcess::current()->io_task_runner();
531 }
532 
SetFieldTrialGroup(const std::string & trial_name,const std::string & group_name)533 void ChildThreadImpl::SetFieldTrialGroup(const std::string& trial_name,
534                                          const std::string& group_name) {
535   if (field_trial_syncer_)
536     field_trial_syncer_->OnSetFieldTrialGroup(trial_name, group_name);
537 }
538 
OnFieldTrialGroupFinalized(const std::string & trial_name,const std::string & group_name)539 void ChildThreadImpl::OnFieldTrialGroupFinalized(
540     const std::string& trial_name,
541     const std::string& group_name) {
542   mojo::Remote<mojom::FieldTrialRecorder> field_trial_recorder;
543   BindHostReceiver(field_trial_recorder.BindNewPipeAndPassReceiver());
544   field_trial_recorder->FieldTrialActivated(trial_name);
545 }
546 
Init(const Options & options)547 void ChildThreadImpl::Init(const Options& options) {
548   TRACE_EVENT0("startup", "ChildThreadImpl::Init");
549   g_lazy_child_thread_impl_tls.Pointer()->Set(this);
550   on_channel_error_called_ = false;
551   main_thread_runner_ = base::ThreadTaskRunnerHandle::Get();
552 #if BUILDFLAG(IPC_MESSAGE_LOG_ENABLED)
553   // We must make sure to instantiate the IPC Logger *before* we create the
554   // channel, otherwise we can get a callback on the IO thread which creates
555   // the logger, and the logger does not like being created on the IO thread.
556   IPC::Logging::GetInstance();
557 #endif
558 
559   channel_ = IPC::SyncChannel::Create(
560       this, ChildProcess::current()->io_task_runner(),
561       ipc_task_runner_ ? ipc_task_runner_ : base::ThreadTaskRunnerHandle::Get(),
562       ChildProcess::current()->GetShutDownEvent());
563 #if BUILDFLAG(IPC_MESSAGE_LOG_ENABLED)
564   if (!IsInBrowserProcess())
565     IPC::Logging::GetInstance()->SetIPCSender(this);
566 #endif
567 
568   // Only one of these will be made valid by the block below. This determines
569   // whether we were launched in normal IPC mode or deprecated Service Manager
570   // IPC mode.
571   mojo::ScopedMessagePipeHandle child_process_pipe;
572   if (!IsInBrowserProcess()) {
573     mojo_ipc_support_.reset(new mojo::core::ScopedIPCSupport(
574         GetIOTaskRunner(), mojo::core::ScopedIPCSupport::ShutdownPolicy::FAST));
575     mojo::IncomingInvitation invitation = InitializeMojoIPCChannel();
576     child_process_pipe = invitation.ExtractMessagePipe(0);
577   } else {
578     child_process_pipe = options.mojo_invitation->ExtractMessagePipe(0);
579   }
580 
581   sync_message_filter_ = channel_->CreateSyncMessageFilter();
582   thread_safe_sender_ =
583       new ThreadSafeSender(main_thread_runner_, sync_message_filter_.get());
584 
585   // In single process mode, browser-side tracing and memory will cover the
586   // whole process including renderers.
587   if (!IsInBrowserProcess()) {
588     mojo::PendingRemote<memory_instrumentation::mojom::Coordinator> coordinator;
589     mojo::PendingRemote<memory_instrumentation::mojom::ClientProcess> process;
590     auto process_receiver = process.InitWithNewPipeAndPassReceiver();
591     mojo::Remote<memory_instrumentation::mojom::CoordinatorConnector> connector;
592     BindHostReceiver(connector.BindNewPipeAndPassReceiver());
593     connector->RegisterCoordinatorClient(
594         coordinator.InitWithNewPipeAndPassReceiver(), std::move(process));
595     memory_instrumentation::ClientProcessImpl::CreateInstance(
596         std::move(process_receiver), std::move(coordinator));
597   }
598 
599   // In single process mode we may already have initialized the power monitor,
600   if (!base::PowerMonitor::IsInitialized()) {
601     auto power_monitor_source =
602         std::make_unique<device::PowerMonitorBroadcastSource>(
603             GetIOTaskRunner());
604     auto* source_ptr = power_monitor_source.get();
605     base::PowerMonitor::Initialize(std::move(power_monitor_source));
606     // The two-phase init is necessary to ensure that the process-wide
607     // PowerMonitor is set before the power monitor source receives incoming
608     // communication from the browser process (see https://crbug.com/821790 for
609     // details)
610     mojo::PendingRemote<device::mojom::PowerMonitor> remote_power_monitor;
611     BindHostReceiver(remote_power_monitor.InitWithNewPipeAndPassReceiver());
612     source_ptr->Init(std::move(remote_power_monitor));
613   }
614 
615 #if defined(OS_POSIX)
616   // Check that --process-type is specified so we don't do this in unit tests
617   // and single-process mode.
618   if (base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kProcessType))
619     channel_->AddFilter(new SuicideOnChannelErrorFilter());
620 #endif
621 
622   // Add filters passed here via options.
623   for (auto* startup_filter : options.startup_filters) {
624     channel_->AddFilter(startup_filter);
625   }
626 
627   DCHECK(child_process_pipe.is_valid());
628   mojo::PendingRemote<IPC::mojom::ChannelBootstrap> legacy_ipc_bootstrap;
629   mojo::ScopedMessagePipeHandle legacy_ipc_channel_handle =
630       legacy_ipc_bootstrap.InitWithNewPipeAndPassReceiver().PassPipe();
631   channel_->Init(IPC::ChannelMojo::CreateClientFactory(
632                      std::move(legacy_ipc_channel_handle),
633                      ChildProcess::current()->io_task_runner(),
634                      ipc_task_runner_ ? ipc_task_runner_
635                                       : base::ThreadTaskRunnerHandle::Get()),
636                  /*create_pipe_now=*/true);
637 
638   ChildThreadImpl::GetIOTaskRunner()->PostTask(
639       FROM_HERE,
640       base::BindOnce(&IOThreadState::BindChildProcessReceiverAndLegacyIpc,
641                      io_thread_state_,
642                      mojo::PendingReceiver<mojom::ChildProcess>(
643                          std::move(child_process_pipe)),
644                      std::move(legacy_ipc_bootstrap)));
645 
646   int connection_timeout = kConnectionTimeoutS;
647   std::string connection_override =
648       base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
649           switches::kIPCConnectionTimeout);
650   if (!connection_override.empty()) {
651     int temp;
652     if (base::StringToInt(connection_override, &temp))
653       connection_timeout = temp;
654   }
655 
656   main_thread_runner_->PostDelayedTask(
657       FROM_HERE,
658       base::BindOnce(&ChildThreadImpl::EnsureConnected,
659                      channel_connected_factory_->GetWeakPtr()),
660       base::TimeDelta::FromSeconds(connection_timeout));
661 
662   // In single-process mode, there is no need to synchronize trials to the
663   // browser process (because it's the same process).
664   if (!IsInBrowserProcess()) {
665     field_trial_syncer_.reset(
666         new variations::ChildProcessFieldTrialSyncer(this));
667     field_trial_syncer_->InitFieldTrialObserving(
668         *base::CommandLine::ForCurrentProcess());
669   }
670 }
671 
~ChildThreadImpl()672 ChildThreadImpl::~ChildThreadImpl() {
673 #if BUILDFLAG(IPC_MESSAGE_LOG_ENABLED)
674   IPC::Logging::GetInstance()->SetIPCSender(NULL);
675 #endif
676 
677   channel_->RemoveFilter(sync_message_filter_.get());
678 
679   // The ChannelProxy object caches a pointer to the IPC thread, so need to
680   // reset it as it's not guaranteed to outlive this object.
681   // NOTE: this also has the side-effect of not closing the main IPC channel to
682   // the browser process.  This is needed because this is the signal that the
683   // browser uses to know that this process has died, so we need it to be alive
684   // until this process is shut down, and the OS closes the handle
685   // automatically.  We used to watch the object handle on Windows to do this,
686   // but it wasn't possible to do so on POSIX.
687   channel_->ClearIPCTaskRunner();
688   g_lazy_child_thread_impl_tls.Pointer()->Set(nullptr);
689 }
690 
Shutdown()691 void ChildThreadImpl::Shutdown() {
692   // Ensure that our IOThreadState's last ref goes away on the IO thread.
693   ChildThreadImpl::GetIOTaskRunner()->PostTask(
694       FROM_HERE, base::BindOnce([](scoped_refptr<IOThreadState>) {},
695                                 std::move(io_thread_state_)));
696 }
697 
ShouldBeDestroyed()698 bool ChildThreadImpl::ShouldBeDestroyed() {
699   return true;
700 }
701 
OnChannelConnected(int32_t peer_pid)702 void ChildThreadImpl::OnChannelConnected(int32_t peer_pid) {
703   channel_connected_factory_.reset();
704 }
705 
OnChannelError()706 void ChildThreadImpl::OnChannelError() {
707   on_channel_error_called_ = true;
708   // If this thread runs in the browser process, only Thread::Stop should
709   // stop its message loop. Otherwise, QuitWhenIdle could race Thread::Stop.
710   if (!IsInBrowserProcess())
711     quit_closure_.Run();
712 }
713 
Send(IPC::Message * msg)714 bool ChildThreadImpl::Send(IPC::Message* msg) {
715   DCHECK(main_thread_runner_->BelongsToCurrentThread());
716   if (!channel_) {
717     delete msg;
718     return false;
719   }
720 
721   return channel_->Send(msg);
722 }
723 
724 #if defined(OS_WIN)
PreCacheFont(const LOGFONT & log_font)725 void ChildThreadImpl::PreCacheFont(const LOGFONT& log_font) {
726   GetFontCacheWin()->PreCacheFont(log_font);
727 }
728 
ReleaseCachedFonts()729 void ChildThreadImpl::ReleaseCachedFonts() {
730   GetFontCacheWin()->ReleaseCachedFonts();
731 }
732 
GetFontCacheWin()733 const mojo::Remote<mojom::FontCacheWin>& ChildThreadImpl::GetFontCacheWin() {
734   if (!font_cache_win_)
735     BindHostReceiver(font_cache_win_.BindNewPipeAndPassReceiver());
736   return font_cache_win_;
737 }
738 #endif
739 
RecordAction(const base::UserMetricsAction & action)740 void ChildThreadImpl::RecordAction(const base::UserMetricsAction& action) {
741     NOTREACHED();
742 }
743 
RecordComputedAction(const std::string & action)744 void ChildThreadImpl::RecordComputedAction(const std::string& action) {
745     NOTREACHED();
746 }
747 
BindHostReceiver(mojo::GenericPendingReceiver receiver)748 void ChildThreadImpl::BindHostReceiver(mojo::GenericPendingReceiver receiver) {
749   child_process_host_->BindHostReceiver(std::move(receiver));
750 }
751 
GetRouter()752 IPC::MessageRouter* ChildThreadImpl::GetRouter() {
753   DCHECK(main_thread_runner_->BelongsToCurrentThread());
754   return &router_;
755 }
756 
GetRemoteRouteProvider()757 mojom::RouteProvider* ChildThreadImpl::GetRemoteRouteProvider() {
758   if (!remote_route_provider_) {
759     DCHECK(channel_);
760     channel_->GetRemoteAssociatedInterface(&remote_route_provider_);
761   }
762   return remote_route_provider_.get();
763 }
764 
OnMessageReceived(const IPC::Message & msg)765 bool ChildThreadImpl::OnMessageReceived(const IPC::Message& msg) {
766   if (msg.routing_id() == MSG_ROUTING_CONTROL)
767     return OnControlMessageReceived(msg);
768 
769   return router_.OnMessageReceived(msg);
770 }
771 
OnAssociatedInterfaceRequest(const std::string & interface_name,mojo::ScopedInterfaceEndpointHandle handle)772 void ChildThreadImpl::OnAssociatedInterfaceRequest(
773     const std::string& interface_name,
774     mojo::ScopedInterfaceEndpointHandle handle) {
775   if (interface_name == mojom::RouteProvider::Name_) {
776     DCHECK(!route_provider_receiver_.is_bound());
777     route_provider_receiver_.Bind(
778         mojo::PendingAssociatedReceiver<mojom::RouteProvider>(
779             std::move(handle)),
780         ipc_task_runner_ ? ipc_task_runner_
781                          : base::ThreadTaskRunnerHandle::Get());
782   } else {
783     LOG(ERROR) << "Receiver for unknown Channel-associated interface: "
784                << interface_name;
785   }
786 }
787 
ExposeInterfacesToBrowser(mojo::BinderMap binders)788 void ChildThreadImpl::ExposeInterfacesToBrowser(mojo::BinderMap binders) {
789   // NOTE: Do not add new binders directly within this method. Instead, modify
790   // the definition of |ExposeChildInterfacesToBrowser()|, ensuring security
791   // review coverage.
792   ExposeChildInterfacesToBrowser(GetIOTaskRunner(), &binders);
793 
794   ChildThreadImpl::GetIOTaskRunner()->PostTask(
795       FROM_HERE, base::BindOnce(&IOThreadState::ExposeInterfacesToBrowser,
796                                 io_thread_state_, std::move(binders)));
797 }
798 
OnControlMessageReceived(const IPC::Message & msg)799 bool ChildThreadImpl::OnControlMessageReceived(const IPC::Message& msg) {
800   return false;
801 }
802 
GetBackgroundTracingAgentProvider(mojo::PendingReceiver<tracing::mojom::BackgroundTracingAgentProvider> receiver)803 void ChildThreadImpl::GetBackgroundTracingAgentProvider(
804     mojo::PendingReceiver<tracing::mojom::BackgroundTracingAgentProvider>
805         receiver) {
806   if (!background_tracing_agent_provider_) {
807     background_tracing_agent_provider_ =
808         std::make_unique<tracing::BackgroundTracingAgentProviderImpl>();
809   }
810   background_tracing_agent_provider_->AddBinding(std::move(receiver));
811 }
812 
RunService(const std::string & service_name,mojo::PendingReceiver<service_manager::mojom::Service> receiver)813 void ChildThreadImpl::RunService(
814     const std::string& service_name,
815     mojo::PendingReceiver<service_manager::mojom::Service> receiver) {
816   DLOG(ERROR) << "Ignoring unhandled request to run service: " << service_name;
817 }
818 
BindServiceInterface(mojo::GenericPendingReceiver receiver)819 void ChildThreadImpl::BindServiceInterface(
820     mojo::GenericPendingReceiver receiver) {
821   DLOG(ERROR) << "Ignoring unhandled request to bind service interface: "
822               << *receiver.interface_name();
823 }
824 
OnBindReceiver(mojo::GenericPendingReceiver receiver)825 void ChildThreadImpl::OnBindReceiver(mojo::GenericPendingReceiver receiver) {}
826 
current()827 ChildThreadImpl* ChildThreadImpl::current() {
828   return g_lazy_child_thread_impl_tls.Pointer()->Get();
829 }
830 
OnProcessFinalRelease()831 void ChildThreadImpl::OnProcessFinalRelease() {
832   if (on_channel_error_called_)
833     return;
834 
835   quit_closure_.Run();
836 }
837 
EnsureConnected()838 void ChildThreadImpl::EnsureConnected() {
839   VLOG(0) << "ChildThreadImpl::EnsureConnected()";
840   base::Process::TerminateCurrentProcessImmediately(0);
841 }
842 
GetRoute(int32_t routing_id,mojo::PendingAssociatedReceiver<blink::mojom::AssociatedInterfaceProvider> receiver)843 void ChildThreadImpl::GetRoute(
844     int32_t routing_id,
845     mojo::PendingAssociatedReceiver<blink::mojom::AssociatedInterfaceProvider>
846         receiver) {
847   associated_interface_provider_receivers_.Add(this, std::move(receiver),
848                                                routing_id);
849 }
850 
GetAssociatedInterface(const std::string & name,mojo::PendingAssociatedReceiver<blink::mojom::AssociatedInterface> receiver)851 void ChildThreadImpl::GetAssociatedInterface(
852     const std::string& name,
853     mojo::PendingAssociatedReceiver<blink::mojom::AssociatedInterface>
854         receiver) {
855   int32_t routing_id =
856       associated_interface_provider_receivers_.current_context();
857   Listener* route = router_.GetRoute(routing_id);
858   if (route)
859     route->OnAssociatedInterfaceRequest(name, receiver.PassHandle());
860 }
861 
IsInBrowserProcess() const862 bool ChildThreadImpl::IsInBrowserProcess() const {
863   return static_cast<bool>(browser_process_io_runner_);
864 }
865 
866 }  // namespace content
867