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