1 // Copyright 2014 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 "mojo/shell/child_process.h"
8 #include "base/callback_helpers.h"
9 #include "base/command_line.h"
10 #include "base/files/file_path.h"
11 #include "base/location.h"
12 #include "base/logging.h"
13 #include "base/macros.h"
14 #include "base/memory/ref_counted.h"
15 #include "base/memory/scoped_ptr.h"
16 #include "base/message_loop/message_loop.h"
17 #include "base/single_thread_task_runner.h"
18 #include "base/synchronization/waitable_event.h"
19 #include "base/threading/thread.h"
20 #include "base/threading/thread_checker.h"
21 #include "mojo/common/message_pump_mojo.h"
22 #include "mojo/edk/embedder/embedder.h"
23 #include "mojo/edk/embedder/platform_channel_pair.h"
24 #include "mojo/edk/embedder/process_delegate.h"
25 #include "mojo/edk/embedder/scoped_platform_handle.h"
26 #include "mojo/edk/embedder/simple_platform_support.h"
27 #include "mojo/public/cpp/system/core.h"
28 #include "mojo/shell/child_process.mojom.h"
29 #include "mojo/shell/native_application_support.h"
30 #include "mojo/shell/switches.h"
37 // Blocker ---------------------------------------------------------------------
39 // Blocks a thread until another thread unblocks it, at which point it unblocks
40 // and runs a closure provided by that thread.
45 explicit Unblocker(Blocker
* blocker
= nullptr) : blocker_(blocker
) {}
48 void Unblock(base::Closure run_after
) {
50 DCHECK(blocker_
->run_after_
.is_null());
51 blocker_
->run_after_
= run_after
;
52 blocker_
->event_
.Signal();
59 // Copy and assign allowed.
62 Blocker() : event_(true, false) {}
66 DCHECK(run_after_
.is_null());
71 Unblocker
GetUnblocker() { return Unblocker(this); }
74 base::WaitableEvent event_
;
75 base::Closure run_after_
;
77 DISALLOW_COPY_AND_ASSIGN(Blocker
);
80 // AppContext ------------------------------------------------------------------
82 class ChildControllerImpl
;
84 // Should be created and initialized on the main thread.
85 class AppContext
: public embedder::ProcessDelegate
{
88 : io_thread_("io_thread"), controller_thread_("controller_thread") {}
89 ~AppContext() override
{}
92 // Initialize Mojo before starting any threads.
93 embedder::Init(make_scoped_ptr(new embedder::SimplePlatformSupport()));
95 // Create and start our I/O thread.
96 base::Thread::Options
io_thread_options(base::MessageLoop::TYPE_IO
, 0);
97 CHECK(io_thread_
.StartWithOptions(io_thread_options
));
98 io_runner_
= io_thread_
.message_loop_proxy().get();
99 CHECK(io_runner_
.get());
101 // Create and start our controller thread.
102 base::Thread::Options controller_thread_options
;
103 controller_thread_options
.message_loop_type
=
104 base::MessageLoop::TYPE_CUSTOM
;
105 controller_thread_options
.message_pump_factory
=
106 base::Bind(&common::MessagePumpMojo::Create
);
107 CHECK(controller_thread_
.StartWithOptions(controller_thread_options
));
108 controller_runner_
= controller_thread_
.message_loop_proxy().get();
109 CHECK(controller_runner_
.get());
111 // TODO(vtl): This should be SLAVE, not NONE.
112 embedder::InitIPCSupport(embedder::ProcessType::NONE
, controller_runner_
,
114 embedder::ScopedPlatformHandle());
119 shutdown_unblocker_
= blocker
.GetUnblocker();
120 controller_runner_
->PostTask(
121 FROM_HERE
, base::Bind(&AppContext::ShutdownOnControllerThread
,
122 base::Unretained(this)));
126 base::SingleThreadTaskRunner
* io_runner() const { return io_runner_
.get(); }
128 base::SingleThreadTaskRunner
* controller_runner() const {
129 return controller_runner_
.get();
132 ChildControllerImpl
* controller() const { return controller_
.get(); }
134 void set_controller(scoped_ptr
<ChildControllerImpl
> controller
) {
135 controller_
= controller
.Pass();
139 void ShutdownOnControllerThread() {
140 // First, destroy the controller.
143 // Next shutdown IPC. We'll unblock the main thread in OnShutdownComplete().
144 embedder::ShutdownIPCSupport();
147 // ProcessDelegate implementation.
148 void OnShutdownComplete() override
{
149 shutdown_unblocker_
.Unblock(base::Closure());
152 base::Thread io_thread_
;
153 scoped_refptr
<base::SingleThreadTaskRunner
> io_runner_
;
155 base::Thread controller_thread_
;
156 scoped_refptr
<base::SingleThreadTaskRunner
> controller_runner_
;
158 // Accessed only on the controller thread.
159 scoped_ptr
<ChildControllerImpl
> controller_
;
161 // Used to unblock the main thread on shutdown.
162 Blocker::Unblocker shutdown_unblocker_
;
164 DISALLOW_COPY_AND_ASSIGN(AppContext
);
167 // ChildControllerImpl ------------------------------------------------------
169 class ChildControllerImpl
: public ChildController
, public ErrorHandler
{
171 ~ChildControllerImpl() override
{
172 DCHECK(thread_checker_
.CalledOnValidThread());
174 // TODO(vtl): Pass in the result from |MainMain()|.
175 on_app_complete_
.Run(MOJO_RESULT_UNIMPLEMENTED
);
178 // To be executed on the controller thread. Creates the |ChildController|,
180 static void Init(AppContext
* app_context
,
181 embedder::ScopedPlatformHandle platform_channel
,
182 const Blocker::Unblocker
& unblocker
) {
184 DCHECK(platform_channel
.is_valid());
186 DCHECK(!app_context
->controller());
188 scoped_ptr
<ChildControllerImpl
> impl(
189 new ChildControllerImpl(app_context
, unblocker
));
191 ScopedMessagePipeHandle
host_message_pipe(embedder::CreateChannel(
192 platform_channel
.Pass(), app_context
->io_runner(),
193 base::Bind(&ChildControllerImpl::DidCreateChannel
,
194 base::Unretained(impl
.get())),
195 base::MessageLoopProxy::current()));
197 impl
->Bind(host_message_pipe
.Pass());
199 app_context
->set_controller(impl
.Pass());
202 void Bind(ScopedMessagePipeHandle handle
) { binding_
.Bind(handle
.Pass()); }
204 // |ErrorHandler| methods:
205 void OnConnectionError() override
{
206 // A connection error means the connection to the shell is lost. This is not
208 LOG(ERROR
) << "Connection error to the shell.";
212 // |ChildController| methods:
213 void StartApp(const String
& app_path
,
215 InterfaceRequest
<Application
> application_request
,
216 const StartAppCallback
& on_app_complete
) override
{
217 DVLOG(2) << "ChildControllerImpl::StartApp(" << app_path
<< ", ...)";
218 DCHECK(thread_checker_
.CalledOnValidThread());
220 on_app_complete_
= on_app_complete
;
221 unblocker_
.Unblock(base::Bind(&ChildControllerImpl::StartAppOnMainThread
,
222 base::FilePath::FromUTF8Unsafe(app_path
),
224 ? NativeApplicationCleanup::DELETE
225 : NativeApplicationCleanup::DONT_DELETE
,
226 base::Passed(&application_request
)));
229 void ExitNow(int32_t exit_code
) override
{
230 DVLOG(2) << "ChildControllerImpl::ExitNow(" << exit_code
<< ")";
235 ChildControllerImpl(AppContext
* app_context
,
236 const Blocker::Unblocker
& unblocker
)
237 : app_context_(app_context
),
238 unblocker_(unblocker
),
239 channel_info_(nullptr),
241 binding_
.set_error_handler(this);
244 // Callback for |embedder::CreateChannel()|.
245 void DidCreateChannel(embedder::ChannelInfo
* channel_info
) {
246 DVLOG(2) << "ChildControllerImpl::DidCreateChannel()";
247 DCHECK(thread_checker_
.CalledOnValidThread());
248 channel_info_
= channel_info
;
251 static void StartAppOnMainThread(
252 const base::FilePath
& app_path
,
253 NativeApplicationCleanup cleanup
,
254 InterfaceRequest
<Application
> application_request
) {
255 // TODO(vtl): This is copied from in_process_native_runner.cc.
256 DVLOG(2) << "Loading/running Mojo app from " << app_path
.value()
257 << " out of process";
259 // We intentionally don't unload the native library as its lifetime is the
260 // same as that of the process.
261 base::NativeLibrary app_library
= LoadNativeApplication(app_path
, cleanup
);
262 RunNativeApplication(app_library
, application_request
.Pass());
265 base::ThreadChecker thread_checker_
;
266 AppContext
* const app_context_
;
267 Blocker::Unblocker unblocker_
;
268 StartAppCallback on_app_complete_
;
270 embedder::ChannelInfo
* channel_info_
;
271 Binding
<ChildController
> binding_
;
273 DISALLOW_COPY_AND_ASSIGN(ChildControllerImpl
);
278 int ChildProcessMain() {
279 DVLOG(2) << "ChildProcessMain()";
280 const base::CommandLine
& command_line
=
281 *base::CommandLine::ForCurrentProcess();
282 embedder::ScopedPlatformHandle platform_channel
=
283 embedder::PlatformChannelPair::PassClientHandleFromParentProcess(
285 CHECK(platform_channel
.is_valid());
287 DCHECK(!base::MessageLoop::current());
289 AppContext app_context
;
293 app_context
.controller_runner()->PostTask(
295 base::Bind(&ChildControllerImpl::Init
, base::Unretained(&app_context
),
296 base::Passed(&platform_channel
), blocker
.GetUnblocker()));
297 // This will block, then run whatever the controller wants.
300 app_context
.Shutdown();