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/process/process_info.h"
18 #include "base/run_loop.h"
19 #include "base/strings/string_number_conversions.h"
20 #include "base/strings/string_split.h"
21 #include "base/strings/string_util.h"
22 #include "base/trace_event/trace_event.h"
23 #include "build/build_config.h"
24 #include "components/devtools_service/public/cpp/switches.h"
25 #include "components/devtools_service/public/interfaces/devtools_service.mojom.h"
26 #include "mojo/application/public/cpp/application_connection.h"
27 #include "mojo/application/public/cpp/application_delegate.h"
28 #include "mojo/application/public/cpp/application_impl.h"
29 #include "mojo/common/trace_controller_impl.h"
30 #include "mojo/common/tracing_impl.h"
31 #include "mojo/edk/embedder/embedder.h"
32 #include "mojo/edk/embedder/simple_platform_support.h"
33 #include "mojo/runner/about_fetcher.h"
34 #include "mojo/runner/in_process_native_runner.h"
35 #include "mojo/runner/out_of_process_native_runner.h"
36 #include "mojo/runner/switches.h"
37 #include "mojo/services/tracing/public/cpp/switches.h"
38 #include "mojo/services/tracing/public/interfaces/tracing.mojom.h"
39 #include "mojo/shell/application_loader.h"
40 #include "mojo/shell/application_manager.h"
41 #include "mojo/shell/switches.h"
42 #include "mojo/util/filename_util.h"
49 // Used to ensure we only init once.
53 embedder::Init(make_scoped_ptr(new embedder::SimplePlatformSupport()));
59 DISALLOW_COPY_AND_ASSIGN(Setup
);
62 bool ConfigureURLMappings(const base::CommandLine
& command_line
,
64 URLResolver
* resolver
= context
->url_resolver();
66 // Configure the resolution of unknown mojo: URLs.
68 if (!command_line
.HasSwitch(switches::kUseUpdater
)) {
69 // Use the shell's file root if the base was not specified.
70 base_url
= context
->ResolveShellFileURL(std::string());
73 if (base_url
.is_valid())
74 resolver
->SetMojoBaseURL(base_url
);
76 // The network service and updater must be loaded from the filesystem.
77 // This mapping is done before the command line URL mapping are processed, so
78 // that it can be overridden.
79 resolver
->AddURLMapping(GURL("mojo:network_service"),
80 context
->ResolveShellFileURL(
81 "file:network_service/network_service.mojo"));
82 resolver
->AddURLMapping(
84 context
->ResolveShellFileURL("file:updater/updater.mojo"));
86 // Command line URL mapping.
87 std::vector
<URLResolver::OriginMapping
> origin_mappings
=
88 URLResolver::GetOriginMappings(command_line
.argv());
89 for (const auto& origin_mapping
: origin_mappings
)
90 resolver
->AddOriginMapping(GURL(origin_mapping
.origin
),
91 GURL(origin_mapping
.base_url
));
93 if (command_line
.HasSwitch(switches::kURLMappings
)) {
94 const std::string mappings
=
95 command_line
.GetSwitchValueASCII(switches::kURLMappings
);
97 base::StringPairs pairs
;
98 if (!base::SplitStringIntoKeyValuePairs(mappings
, '=', ',', &pairs
))
100 using StringPair
= std::pair
<std::string
, std::string
>;
101 for (const StringPair
& pair
: pairs
) {
102 const GURL
from(pair
.first
);
103 const GURL to
= context
->ResolveCommandLineURL(pair
.second
);
104 if (!from
.is_valid() || !to
.is_valid())
106 resolver
->AddURLMapping(from
, to
);
113 void InitContentHandlers(shell::ApplicationManager
* manager
,
114 const base::CommandLine
& command_line
) {
115 // Default content handlers.
116 manager
->RegisterContentHandler("application/pdf", GURL("mojo:pdf_viewer"));
117 manager
->RegisterContentHandler("image/png", GURL("mojo:png_viewer"));
118 manager
->RegisterContentHandler("text/html", GURL("mojo:html_viewer"));
120 // Command-line-specified content handlers.
121 std::string handlers_spec
=
122 command_line
.GetSwitchValueASCII(switches::kContentHandlers
);
123 if (handlers_spec
.empty())
126 #if defined(OS_ANDROID)
127 // TODO(eseidel): On Android we pass command line arguments is via the
128 // 'parameters' key on the intent, which we specify during 'am shell start'
129 // via --esa, however that expects comma-separated values and says:
131 // [--esa <EXTRA_KEY> <EXTRA_STRING_VALUE>[,<EXTRA_STRING_VALUE...]]
132 // (to embed a comma into a string escape it using "\,")
133 // Whatever takes 'parameters' and constructs a CommandLine is failing to
134 // un-escape the commas, we need to move this fix to that file.
135 base::ReplaceSubstringsAfterOffset(&handlers_spec
, 0, "\\,", ",");
138 std::vector
<std::string
> parts
= base::SplitString(
139 handlers_spec
, ",", base::TRIM_WHITESPACE
, base::SPLIT_WANT_ALL
);
140 if (parts
.size() % 2 != 0) {
141 LOG(ERROR
) << "Invalid value for switch " << switches::kContentHandlers
142 << ": must be a comma-separated list of mimetype/url pairs."
147 for (size_t i
= 0; i
< parts
.size(); i
+= 2) {
148 GURL
url(parts
[i
+ 1]);
149 if (!url
.is_valid()) {
150 LOG(ERROR
) << "Invalid value for switch " << switches::kContentHandlers
151 << ": '" << parts
[i
+ 1] << "' is not a valid URL.";
154 // TODO(eseidel): We should also validate that the mimetype is valid
155 // net/base/mime_util.h could do this, but we don't want to depend on net.
156 manager
->RegisterContentHandler(parts
[i
], url
);
160 void InitNativeOptions(shell::ApplicationManager
* manager
,
161 const base::CommandLine
& command_line
) {
162 std::vector
<std::string
> force_in_process_url_list
= base::SplitString(
163 command_line
.GetSwitchValueASCII(switches::kForceInProcess
), ",",
164 base::TRIM_WHITESPACE
, base::SPLIT_WANT_ALL
);
165 for (const auto& force_in_process_url
: force_in_process_url_list
) {
166 GURL
gurl(force_in_process_url
);
167 if (!gurl
.is_valid()) {
168 LOG(ERROR
) << "Invalid value for switch " << switches::kForceInProcess
169 << ": '" << force_in_process_url
<< "'is not a valid URL.";
173 shell::NativeRunnerFactory::Options options
;
174 options
.force_in_process
= true;
175 manager
->SetNativeOptionsForURL(options
, gurl
);
179 void InitDevToolsServiceIfNeeded(shell::ApplicationManager
* manager
,
180 const base::CommandLine
& command_line
) {
181 if (!command_line
.HasSwitch(devtools_service::kRemoteDebuggingPort
))
184 std::string port_str
=
185 command_line
.GetSwitchValueASCII(devtools_service::kRemoteDebuggingPort
);
187 if (!base::StringToUint(port_str
, &port
) || port
> 65535) {
188 LOG(ERROR
) << "Invalid value for switch "
189 << devtools_service::kRemoteDebuggingPort
<< ": '" << port_str
190 << "' is not a valid port number.";
194 ServiceProviderPtr devtools_service_provider
;
195 URLRequestPtr
request(URLRequest::New());
196 request
->url
= "mojo:devtools_service";
197 manager
->ConnectToApplication(
198 nullptr, request
.Pass(), std::string(), GURL("mojo:shell"),
199 GetProxy(&devtools_service_provider
), nullptr,
200 shell::GetPermissiveCapabilityFilter(), base::Closure());
202 devtools_service::DevToolsCoordinatorPtr devtools_coordinator
;
203 devtools_service_provider
->ConnectToService(
204 devtools_service::DevToolsCoordinator::Name_
,
205 GetProxy(&devtools_coordinator
).PassMessagePipe());
206 devtools_coordinator
->Initialize(static_cast<uint16_t>(port
));
209 class TracingServiceProvider
: public ServiceProvider
{
211 explicit TracingServiceProvider(InterfaceRequest
<ServiceProvider
> request
)
212 : binding_(this, request
.Pass()) {}
213 ~TracingServiceProvider() override
{}
215 void ConnectToService(const String
& service_name
,
216 ScopedMessagePipeHandle client_handle
) override
{
217 if (service_name
== tracing::TraceController::Name_
) {
218 new TraceControllerImpl(
219 MakeRequest
<tracing::TraceController
>(client_handle
.Pass()));
224 StrongBinding
<ServiceProvider
> binding_
;
226 DISALLOW_COPY_AND_ASSIGN(TracingServiceProvider
);
231 Context::Context() : application_manager_(this) {
232 DCHECK(!base::MessageLoop::current());
234 // By default assume that the local apps reside alongside the shell.
235 // TODO(ncbray): really, this should be passed in rather than defaulting.
236 // This default makes sense for desktop but not Android.
237 base::FilePath shell_dir
;
238 PathService::Get(base::DIR_MODULE
, &shell_dir
);
239 SetShellFileRoot(shell_dir
);
242 PathService::Get(base::DIR_CURRENT
, &cwd
);
243 SetCommandLineCWD(cwd
);
246 Context::~Context() {
247 DCHECK(!base::MessageLoop::current());
251 void Context::EnsureEmbedderIsInitialized() {
252 static base::LazyInstance
<Setup
>::Leaky setup
= LAZY_INSTANCE_INITIALIZER
;
256 void Context::SetShellFileRoot(const base::FilePath
& path
) {
258 util::AddTrailingSlashIfNeeded(util::FilePathToFileURL(path
));
261 GURL
Context::ResolveShellFileURL(const std::string
& path
) {
262 return shell_file_root_
.Resolve(path
);
265 void Context::SetCommandLineCWD(const base::FilePath
& path
) {
267 util::AddTrailingSlashIfNeeded(util::FilePathToFileURL(path
));
270 GURL
Context::ResolveCommandLineURL(const std::string
& path
) {
271 return command_line_cwd_
.Resolve(path
);
274 bool Context::Init() {
275 TRACE_EVENT0("mojo_shell", "Context::Init");
276 const base::CommandLine
& command_line
=
277 *base::CommandLine::ForCurrentProcess();
279 EnsureEmbedderIsInitialized();
281 new TaskRunners(base::MessageLoop::current()->task_runner()));
283 // TODO(vtl): Probably these failures should be checked before |Init()|, and
284 // this function simply shouldn't fail.
285 if (!shell_file_root_
.is_valid())
287 if (!ConfigureURLMappings(command_line
, this))
290 // TODO(vtl): This should be MASTER, not NONE.
291 embedder::InitIPCSupport(
292 embedder::ProcessType::NONE
, task_runners_
->shell_runner(), this,
293 task_runners_
->io_runner(), embedder::ScopedPlatformHandle());
295 scoped_ptr
<shell::NativeRunnerFactory
> runner_factory
;
296 if (command_line
.HasSwitch(switches::kEnableMultiprocess
))
297 runner_factory
.reset(new OutOfProcessNativeRunnerFactory(this));
299 runner_factory
.reset(new InProcessNativeRunnerFactory(this));
300 application_manager_
.set_blocking_pool(task_runners_
->blocking_pool());
301 application_manager_
.set_native_runner_factory(runner_factory
.Pass());
302 application_manager_
.set_disable_cache(
303 base::CommandLine::ForCurrentProcess()->HasSwitch(
304 switches::kDisableCache
));
306 InitContentHandlers(&application_manager_
, command_line
);
307 InitNativeOptions(&application_manager_
, command_line
);
309 ServiceProviderPtr service_provider_ptr
;
310 ServiceProviderPtr tracing_service_provider_ptr
;
311 new TracingServiceProvider(GetProxy(&tracing_service_provider_ptr
));
312 mojo::URLRequestPtr
request(mojo::URLRequest::New());
313 request
->url
= mojo::String::From("mojo:tracing");
314 application_manager_
.ConnectToApplication(
315 nullptr, request
.Pass(), std::string(), GURL(),
316 GetProxy(&service_provider_ptr
), tracing_service_provider_ptr
.Pass(),
317 shell::GetPermissiveCapabilityFilter(), base::Closure());
319 // CurrentProcessInfo::CreationTime() is missing on some platforms.
320 #if defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
321 // Record the shell process creation time for performance testing.
322 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
323 tracing::kEnableStatsCollectionBindings
)) {
324 tracing::StartupPerformanceDataCollectorPtr collector
;
325 service_provider_ptr
->ConnectToService(
326 tracing::StartupPerformanceDataCollector::Name_
,
327 GetProxy(&collector
).PassMessagePipe());
328 const base::Time creation_time
= base::CurrentProcessInfo::CreationTime();
329 collector
->SetShellProcessCreationTime(creation_time
.ToInternalValue());
333 InitDevToolsServiceIfNeeded(&application_manager_
, command_line
);
338 void Context::Shutdown() {
339 TRACE_EVENT0("mojo_shell", "Context::Shutdown");
340 DCHECK_EQ(base::MessageLoop::current()->task_runner(),
341 task_runners_
->shell_runner());
342 embedder::ShutdownIPCSupport();
343 // We'll quit when we get OnShutdownComplete().
344 base::MessageLoop::current()->Run();
347 GURL
Context::ResolveMappings(const GURL
& url
) {
348 return url_resolver_
.ApplyMappings(url
);
351 GURL
Context::ResolveMojoURL(const GURL
& url
) {
352 return url_resolver_
.ResolveMojoURL(url
);
355 bool Context::CreateFetcher(
357 const shell::Fetcher::FetchCallback
& loader_callback
) {
358 if (url
.SchemeIs(AboutFetcher::kAboutScheme
)) {
359 AboutFetcher::Start(url
, loader_callback
);
366 void Context::OnShutdownComplete() {
367 DCHECK_EQ(base::MessageLoop::current()->task_runner(),
368 task_runners_
->shell_runner());
369 base::MessageLoop::current()->Quit();
372 void Context::Run(const GURL
& url
) {
373 DCHECK(app_complete_callback_
.is_null());
374 ServiceProviderPtr services
;
375 ServiceProviderPtr exposed_services
;
377 app_urls_
.insert(url
);
378 mojo::URLRequestPtr
request(mojo::URLRequest::New());
379 request
->url
= mojo::String::From(url
.spec());
380 application_manager_
.ConnectToApplication(
381 nullptr, request
.Pass(), std::string(), GURL(), GetProxy(&services
),
382 exposed_services
.Pass(), shell::GetPermissiveCapabilityFilter(),
383 base::Bind(&Context::OnApplicationEnd
, base::Unretained(this), url
));
386 void Context::RunCommandLineApplication(const base::Closure
& callback
) {
387 DCHECK(app_urls_
.empty());
388 DCHECK(app_complete_callback_
.is_null());
389 base::CommandLine
* command_line
= base::CommandLine::ForCurrentProcess();
390 base::CommandLine::StringVector args
= command_line
->GetArgs();
391 for (size_t i
= 0; i
< args
.size(); ++i
) {
392 GURL
possible_app(args
[i
]);
393 if (possible_app
.SchemeIs("mojo")) {
395 app_complete_callback_
= callback
;
401 void Context::OnApplicationEnd(const GURL
& url
) {
402 if (app_urls_
.find(url
) != app_urls_
.end()) {
403 app_urls_
.erase(url
);
404 if (app_urls_
.empty() && base::MessageLoop::current()->is_running()) {
405 DCHECK_EQ(base::MessageLoop::current()->task_runner(),
406 task_runners_
->shell_runner());
407 if (app_complete_callback_
.is_null()) {
408 base::MessageLoop::current()->Quit();
410 app_complete_callback_
.Run();
416 } // namespace runner