1 // Copyright 2013 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/runner/context.h"
10 #include "base/command_line.h"
11 #include "base/files/file_path.h"
12 #include "base/lazy_instance.h"
13 #include "base/macros.h"
14 #include "base/memory/scoped_ptr.h"
15 #include "base/memory/scoped_vector.h"
16 #include "base/path_service.h"
17 #include "base/run_loop.h"
18 #include "base/strings/string_number_conversions.h"
19 #include "base/strings/string_split.h"
20 #include "base/strings/string_util.h"
21 #include "base/trace_event/trace_event.h"
22 #include "build/build_config.h"
23 #include "components/devtools_service/public/interfaces/devtools_service.mojom.h"
24 #include "mojo/application/public/cpp/application_connection.h"
25 #include "mojo/application/public/cpp/application_delegate.h"
26 #include "mojo/application/public/cpp/application_impl.h"
27 #include "mojo/common/trace_controller_impl.h"
28 #include "mojo/common/tracing_impl.h"
29 #include "mojo/edk/embedder/embedder.h"
30 #include "mojo/edk/embedder/simple_platform_support.h"
31 #include "mojo/runner/in_process_native_runner.h"
32 #include "mojo/runner/out_of_process_native_runner.h"
33 #include "mojo/runner/switches.h"
34 #include "mojo/services/tracing/tracing.mojom.h"
35 #include "mojo/shell/application_loader.h"
36 #include "mojo/shell/application_manager.h"
37 #include "mojo/shell/switches.h"
38 #include "mojo/util/filename_util.h"
45 // Used to ensure we only init once.
49 embedder::Init(make_scoped_ptr(new embedder::SimplePlatformSupport()));
55 DISALLOW_COPY_AND_ASSIGN(Setup
);
58 bool ConfigureURLMappings(const base::CommandLine
& command_line
,
60 URLResolver
* resolver
= context
->url_resolver();
62 // Configure the resolution of unknown mojo: URLs.
64 if (command_line
.HasSwitch(switches::kOrigin
))
65 base_url
= GURL(command_line
.GetSwitchValueASCII(switches::kOrigin
));
67 // Use the shell's file root if the base was not specified.
68 base_url
= context
->ResolveShellFileURL("");
70 if (!base_url
.is_valid())
73 resolver
->SetMojoBaseURL(base_url
);
75 // The network service must be loaded from the filesystem.
76 // This mapping is done before the command line URL mapping are processed, so
77 // that it can be overridden.
78 resolver
->AddURLMapping(
79 GURL("mojo:network_service"),
80 context
->ResolveShellFileURL("file:network_service.mojo"));
82 // Command line URL mapping.
83 std::vector
<URLResolver::OriginMapping
> origin_mappings
=
84 URLResolver::GetOriginMappings(command_line
.argv());
85 for (const auto& origin_mapping
: origin_mappings
)
86 resolver
->AddOriginMapping(GURL(origin_mapping
.origin
),
87 GURL(origin_mapping
.base_url
));
89 if (command_line
.HasSwitch(switches::kURLMappings
)) {
90 const std::string mappings
=
91 command_line
.GetSwitchValueASCII(switches::kURLMappings
);
93 base::StringPairs pairs
;
94 if (!base::SplitStringIntoKeyValuePairs(mappings
, '=', ',', &pairs
))
96 using StringPair
= std::pair
<std::string
, std::string
>;
97 for (const StringPair
& pair
: pairs
) {
98 const GURL
from(pair
.first
);
99 const GURL to
= context
->ResolveCommandLineURL(pair
.second
);
100 if (!from
.is_valid() || !to
.is_valid())
102 resolver
->AddURLMapping(from
, to
);
109 void InitContentHandlers(shell::ApplicationManager
* manager
,
110 const base::CommandLine
& command_line
) {
111 // Default content handlers.
112 manager
->RegisterContentHandler("application/pdf", GURL("mojo:pdf_viewer"));
113 manager
->RegisterContentHandler("image/png", GURL("mojo:png_viewer"));
114 manager
->RegisterContentHandler("text/html", GURL("mojo:html_viewer"));
116 // Command-line-specified content handlers.
117 std::string handlers_spec
=
118 command_line
.GetSwitchValueASCII(switches::kContentHandlers
);
119 if (handlers_spec
.empty())
122 #if defined(OS_ANDROID)
123 // TODO(eseidel): On Android we pass command line arguments is via the
124 // 'parameters' key on the intent, which we specify during 'am shell start'
125 // via --esa, however that expects comma-separated values and says:
127 // [--esa <EXTRA_KEY> <EXTRA_STRING_VALUE>[,<EXTRA_STRING_VALUE...]]
128 // (to embed a comma into a string escape it using "\,")
129 // Whatever takes 'parameters' and constructs a CommandLine is failing to
130 // un-escape the commas, we need to move this fix to that file.
131 ReplaceSubstringsAfterOffset(&handlers_spec
, 0, "\\,", ",");
134 std::vector
<std::string
> parts
;
135 base::SplitString(handlers_spec
, ',', &parts
);
136 if (parts
.size() % 2 != 0) {
137 LOG(ERROR
) << "Invalid value for switch " << switches::kContentHandlers
138 << ": must be a comma-separated list of mimetype/url pairs."
143 for (size_t i
= 0; i
< parts
.size(); i
+= 2) {
144 GURL
url(parts
[i
+ 1]);
145 if (!url
.is_valid()) {
146 LOG(ERROR
) << "Invalid value for switch " << switches::kContentHandlers
147 << ": '" << parts
[i
+ 1] << "' is not a valid URL.";
150 // TODO(eseidel): We should also validate that the mimetype is valid
151 // net/base/mime_util.h could do this, but we don't want to depend on net.
152 manager
->RegisterContentHandler(parts
[i
], url
);
156 void InitNativeOptions(shell::ApplicationManager
* manager
,
157 const base::CommandLine
& command_line
) {
158 std::vector
<std::string
> force_in_process_url_list
;
159 base::SplitString(command_line
.GetSwitchValueASCII(switches::kForceInProcess
),
160 ',', &force_in_process_url_list
);
161 for (const auto& force_in_process_url
: force_in_process_url_list
) {
162 GURL
gurl(force_in_process_url
);
163 if (!gurl
.is_valid()) {
164 LOG(ERROR
) << "Invalid value for switch " << switches::kForceInProcess
165 << ": '" << force_in_process_url
<< "'is not a valid URL.";
169 shell::NativeRunnerFactory::Options options
;
170 options
.force_in_process
= true;
171 manager
->SetNativeOptionsForURL(options
, gurl
);
175 void InitDevToolsServiceIfNeeded(shell::ApplicationManager
* manager
,
176 const base::CommandLine
& command_line
) {
177 if (!command_line
.HasSwitch(switches::kRemoteDebuggingPort
))
180 std::string port_str
=
181 command_line
.GetSwitchValueASCII(switches::kRemoteDebuggingPort
);
183 if (!base::StringToUint(port_str
, &port
) || port
> 65535) {
184 LOG(ERROR
) << "Invalid value for switch " << switches::kRemoteDebuggingPort
185 << ": '" << port_str
<< "' is not a valid port number.";
189 ServiceProviderPtr devtools_service_provider
;
190 URLRequestPtr
request(URLRequest::New());
191 request
->url
= "mojo:devtools_service";
192 manager
->ConnectToApplication(request
.Pass(), GURL("mojo:shell"),
193 GetProxy(&devtools_service_provider
), nullptr,
196 devtools_service::DevToolsCoordinatorPtr devtools_coordinator
;
197 devtools_service_provider
->ConnectToService(
198 devtools_service::DevToolsCoordinator::Name_
,
199 GetProxy(&devtools_coordinator
).PassMessagePipe());
200 devtools_coordinator
->Initialize(static_cast<uint16_t>(port
));
203 class TracingServiceProvider
: public ServiceProvider
{
205 explicit TracingServiceProvider(InterfaceRequest
<ServiceProvider
> request
)
206 : binding_(this, request
.Pass()) {}
207 ~TracingServiceProvider() override
{}
209 void ConnectToService(const String
& service_name
,
210 ScopedMessagePipeHandle client_handle
) override
{
211 if (service_name
== tracing::TraceController::Name_
) {
212 new TraceControllerImpl(
213 MakeRequest
<tracing::TraceController
>(client_handle
.Pass()));
218 StrongBinding
<ServiceProvider
> binding_
;
220 DISALLOW_COPY_AND_ASSIGN(TracingServiceProvider
);
225 Context::Context() : application_manager_(this) {
226 DCHECK(!base::MessageLoop::current());
228 // By default assume that the local apps reside alongside the shell.
229 // TODO(ncbray): really, this should be passed in rather than defaulting.
230 // This default makes sense for desktop but not Android.
231 base::FilePath shell_dir
;
232 PathService::Get(base::DIR_MODULE
, &shell_dir
);
233 SetShellFileRoot(shell_dir
);
236 PathService::Get(base::DIR_CURRENT
, &cwd
);
237 SetCommandLineCWD(cwd
);
240 Context::~Context() {
241 DCHECK(!base::MessageLoop::current());
245 void Context::EnsureEmbedderIsInitialized() {
246 static base::LazyInstance
<Setup
>::Leaky setup
= LAZY_INSTANCE_INITIALIZER
;
250 void Context::SetShellFileRoot(const base::FilePath
& path
) {
252 util::AddTrailingSlashIfNeeded(util::FilePathToFileURL(path
));
255 GURL
Context::ResolveShellFileURL(const std::string
& path
) {
256 return shell_file_root_
.Resolve(path
);
259 void Context::SetCommandLineCWD(const base::FilePath
& path
) {
261 util::AddTrailingSlashIfNeeded(util::FilePathToFileURL(path
));
264 GURL
Context::ResolveCommandLineURL(const std::string
& path
) {
265 return command_line_cwd_
.Resolve(path
);
268 bool Context::Init() {
269 TRACE_EVENT0("mojo_shell", "Context::Init");
270 const base::CommandLine
& command_line
=
271 *base::CommandLine::ForCurrentProcess();
273 EnsureEmbedderIsInitialized();
275 new TaskRunners(base::MessageLoop::current()->message_loop_proxy()));
277 // TODO(vtl): Probably these failures should be checked before |Init()|, and
278 // this function simply shouldn't fail.
279 if (!shell_file_root_
.is_valid())
281 if (!ConfigureURLMappings(command_line
, this))
284 // TODO(vtl): This should be MASTER, not NONE.
285 embedder::InitIPCSupport(
286 embedder::ProcessType::NONE
, task_runners_
->shell_runner(), this,
287 task_runners_
->io_runner(), embedder::ScopedPlatformHandle());
289 scoped_ptr
<shell::NativeRunnerFactory
> runner_factory
;
290 if (command_line
.HasSwitch(switches::kEnableMultiprocess
))
291 runner_factory
.reset(new OutOfProcessNativeRunnerFactory(this));
293 runner_factory
.reset(new InProcessNativeRunnerFactory(this));
294 application_manager_
.set_blocking_pool(task_runners_
->blocking_pool());
295 application_manager_
.set_native_runner_factory(runner_factory
.Pass());
296 application_manager_
.set_disable_cache(
297 base::CommandLine::ForCurrentProcess()->HasSwitch(
298 switches::kDisableCache
));
300 InitContentHandlers(&application_manager_
, command_line
);
301 InitNativeOptions(&application_manager_
, command_line
);
303 ServiceProviderPtr tracing_service_provider_ptr
;
304 new TracingServiceProvider(GetProxy(&tracing_service_provider_ptr
));
305 mojo::URLRequestPtr
request(mojo::URLRequest::New());
306 request
->url
= mojo::String::From("mojo:tracing");
307 application_manager_
.ConnectToApplication(request
.Pass(), GURL(""), nullptr,
308 tracing_service_provider_ptr
.Pass(),
311 InitDevToolsServiceIfNeeded(&application_manager_
, command_line
);
316 void Context::Shutdown() {
317 TRACE_EVENT0("mojo_shell", "Context::Shutdown");
318 DCHECK_EQ(base::MessageLoop::current()->task_runner(),
319 task_runners_
->shell_runner());
320 embedder::ShutdownIPCSupport();
321 // We'll quit when we get OnShutdownComplete().
322 base::MessageLoop::current()->Run();
325 GURL
Context::ResolveMappings(const GURL
& url
) {
326 return url_resolver_
.ApplyMappings(url
);
329 GURL
Context::ResolveMojoURL(const GURL
& url
) {
330 return url_resolver_
.ResolveMojoURL(url
);
333 bool Context::CreateFetcher(
335 const shell::Fetcher::FetchCallback
& loader_callback
) {
339 void Context::OnShutdownComplete() {
340 DCHECK_EQ(base::MessageLoop::current()->task_runner(),
341 task_runners_
->shell_runner());
342 base::MessageLoop::current()->Quit();
345 void Context::Run(const GURL
& url
) {
346 ServiceProviderPtr services
;
347 ServiceProviderPtr exposed_services
;
349 app_urls_
.insert(url
);
350 mojo::URLRequestPtr
request(mojo::URLRequest::New());
351 request
->url
= mojo::String::From(url
.spec());
352 application_manager_
.ConnectToApplication(
353 request
.Pass(), GURL(), GetProxy(&services
), exposed_services
.Pass(),
354 base::Bind(&Context::OnApplicationEnd
, base::Unretained(this), url
));
357 void Context::RunCommandLineApplication() {
358 base::CommandLine
* command_line
= base::CommandLine::ForCurrentProcess();
359 base::CommandLine::StringVector args
= command_line
->GetArgs();
360 for (size_t i
= 0; i
< args
.size(); ++i
) {
361 GURL
possible_app(args
[i
]);
362 if (possible_app
.SchemeIs("mojo")) {
369 void Context::OnApplicationEnd(const GURL
& url
) {
370 if (app_urls_
.find(url
) != app_urls_
.end()) {
371 app_urls_
.erase(url
);
372 if (app_urls_
.empty() && base::MessageLoop::current()->is_running()) {
373 DCHECK_EQ(base::MessageLoop::current()->task_runner(),
374 task_runners_
->shell_runner());
375 base::MessageLoop::current()->Quit();
380 } // namespace runner