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/path_service.h"
16 #include "base/process/process_info.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/cpp/switches.h"
24 #include "components/devtools_service/public/interfaces/devtools_service.mojom.h"
25 #include "mojo/application/public/cpp/application_connection.h"
26 #include "mojo/application/public/cpp/application_delegate.h"
27 #include "mojo/application/public/cpp/application_impl.h"
28 #include "mojo/common/trace_controller_impl.h"
29 #include "mojo/common/tracing_impl.h"
30 #include "mojo/edk/embedder/embedder.h"
31 #include "mojo/edk/embedder/simple_platform_support.h"
32 #include "mojo/runner/about_fetcher.h"
33 #include "mojo/runner/in_process_native_runner.h"
34 #include "mojo/runner/out_of_process_native_runner.h"
35 #include "mojo/runner/switches.h"
36 #include "mojo/services/tracing/public/cpp/switches.h"
37 #include "mojo/services/tracing/public/interfaces/tracing.mojom.h"
38 #include "mojo/shell/application_loader.h"
39 #include "mojo/shell/application_manager.h"
40 #include "mojo/shell/connect_to_application_params.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 scoped_ptr
<shell::ConnectToApplicationParams
> params(
196 new shell::ConnectToApplicationParams
);
197 params
->set_originator_identity(shell::Identity(GURL("mojo:shell")));
198 params
->set_originator_filter(shell::GetPermissiveCapabilityFilter());
199 params
->SetURLInfo(GURL("mojo:devtools_service"));
200 params
->set_services(GetProxy(&devtools_service_provider
));
201 params
->set_filter(shell::GetPermissiveCapabilityFilter());
202 manager
->ConnectToApplication(params
.Pass());
204 devtools_service::DevToolsCoordinatorPtr devtools_coordinator
;
205 devtools_service_provider
->ConnectToService(
206 devtools_service::DevToolsCoordinator::Name_
,
207 GetProxy(&devtools_coordinator
).PassMessagePipe());
208 devtools_coordinator
->Initialize(static_cast<uint16_t>(port
));
211 class TracingServiceProvider
: public ServiceProvider
{
213 explicit TracingServiceProvider(InterfaceRequest
<ServiceProvider
> request
)
214 : binding_(this, request
.Pass()) {}
215 ~TracingServiceProvider() override
{}
217 void ConnectToService(const String
& service_name
,
218 ScopedMessagePipeHandle client_handle
) override
{
219 if (service_name
== tracing::TraceController::Name_
) {
220 new TraceControllerImpl(
221 MakeRequest
<tracing::TraceController
>(client_handle
.Pass()));
226 StrongBinding
<ServiceProvider
> binding_
;
228 DISALLOW_COPY_AND_ASSIGN(TracingServiceProvider
);
234 : application_manager_(this), main_entry_time_(base::Time::Now()) {
235 DCHECK(!base::MessageLoop::current());
237 // By default assume that the local apps reside alongside the shell.
238 // TODO(ncbray): really, this should be passed in rather than defaulting.
239 // This default makes sense for desktop but not Android.
240 base::FilePath shell_dir
;
241 PathService::Get(base::DIR_MODULE
, &shell_dir
);
242 SetShellFileRoot(shell_dir
);
245 PathService::Get(base::DIR_CURRENT
, &cwd
);
246 SetCommandLineCWD(cwd
);
249 Context::~Context() {
250 DCHECK(!base::MessageLoop::current());
254 void Context::EnsureEmbedderIsInitialized() {
255 static base::LazyInstance
<Setup
>::Leaky setup
= LAZY_INSTANCE_INITIALIZER
;
259 void Context::SetShellFileRoot(const base::FilePath
& path
) {
261 util::AddTrailingSlashIfNeeded(util::FilePathToFileURL(path
));
264 GURL
Context::ResolveShellFileURL(const std::string
& path
) {
265 return shell_file_root_
.Resolve(path
);
268 void Context::SetCommandLineCWD(const base::FilePath
& path
) {
270 util::AddTrailingSlashIfNeeded(util::FilePathToFileURL(path
));
273 GURL
Context::ResolveCommandLineURL(const std::string
& path
) {
274 return command_line_cwd_
.Resolve(path
);
277 bool Context::Init() {
278 TRACE_EVENT0("mojo_shell", "Context::Init");
279 const base::CommandLine
& command_line
=
280 *base::CommandLine::ForCurrentProcess();
282 EnsureEmbedderIsInitialized();
284 new TaskRunners(base::MessageLoop::current()->task_runner()));
286 // TODO(vtl): Probably these failures should be checked before |Init()|, and
287 // this function simply shouldn't fail.
288 if (!shell_file_root_
.is_valid())
290 if (!ConfigureURLMappings(command_line
, this))
293 // TODO(vtl): This should be MASTER, not NONE.
294 embedder::InitIPCSupport(
295 embedder::ProcessType::NONE
, task_runners_
->shell_runner(), this,
296 task_runners_
->io_runner(), embedder::ScopedPlatformHandle());
298 scoped_ptr
<shell::NativeRunnerFactory
> runner_factory
;
299 if (command_line
.HasSwitch(switches::kEnableMultiprocess
))
300 runner_factory
.reset(new OutOfProcessNativeRunnerFactory(this));
302 runner_factory
.reset(new InProcessNativeRunnerFactory(this));
303 application_manager_
.set_blocking_pool(task_runners_
->blocking_pool());
304 application_manager_
.set_native_runner_factory(runner_factory
.Pass());
305 application_manager_
.set_disable_cache(
306 base::CommandLine::ForCurrentProcess()->HasSwitch(
307 switches::kDisableCache
));
309 InitContentHandlers(&application_manager_
, command_line
);
310 InitNativeOptions(&application_manager_
, command_line
);
312 ServiceProviderPtr service_provider_ptr
;
313 ServiceProviderPtr tracing_service_provider_ptr
;
314 new TracingServiceProvider(GetProxy(&tracing_service_provider_ptr
));
315 mojo::URLRequestPtr
request(mojo::URLRequest::New());
316 request
->url
= mojo::String::From("mojo:tracing");
317 application_manager_
.ConnectToApplication(
318 nullptr, request
.Pass(), std::string(), GetProxy(&service_provider_ptr
),
319 tracing_service_provider_ptr
.Pass(),
320 shell::GetPermissiveCapabilityFilter(), base::Closure(),
321 shell::EmptyConnectCallback());
323 // Record the shell startup metrics used for performance testing.
324 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
325 tracing::kEnableStatsCollectionBindings
)) {
326 tracing::StartupPerformanceDataCollectorPtr collector
;
327 service_provider_ptr
->ConnectToService(
328 tracing::StartupPerformanceDataCollector::Name_
,
329 GetProxy(&collector
).PassMessagePipe());
330 #if defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
331 // CurrentProcessInfo::CreationTime is only defined on some platforms.
332 const base::Time creation_time
= base::CurrentProcessInfo::CreationTime();
333 collector
->SetShellProcessCreationTime(creation_time
.ToInternalValue());
335 collector
->SetShellMainEntryPointTime(main_entry_time_
.ToInternalValue());
338 InitDevToolsServiceIfNeeded(&application_manager_
, command_line
);
343 void Context::Shutdown() {
344 TRACE_EVENT0("mojo_shell", "Context::Shutdown");
345 DCHECK_EQ(base::MessageLoop::current()->task_runner(),
346 task_runners_
->shell_runner());
347 embedder::ShutdownIPCSupport();
348 // We'll quit when we get OnShutdownComplete().
349 base::MessageLoop::current()->Run();
352 GURL
Context::ResolveMappings(const GURL
& url
) {
353 return url_resolver_
.ApplyMappings(url
);
356 GURL
Context::ResolveMojoURL(const GURL
& url
) {
357 return url_resolver_
.ResolveMojoURL(url
);
360 bool Context::CreateFetcher(
362 const shell::Fetcher::FetchCallback
& loader_callback
) {
363 if (url
.SchemeIs(AboutFetcher::kAboutScheme
)) {
364 AboutFetcher::Start(url
, loader_callback
);
371 void Context::OnShutdownComplete() {
372 DCHECK_EQ(base::MessageLoop::current()->task_runner(),
373 task_runners_
->shell_runner());
374 base::MessageLoop::current()->Quit();
377 void Context::Run(const GURL
& url
) {
378 DCHECK(app_complete_callback_
.is_null());
379 ServiceProviderPtr services
;
380 ServiceProviderPtr exposed_services
;
382 app_urls_
.insert(url
);
383 mojo::URLRequestPtr
request(mojo::URLRequest::New());
384 request
->url
= mojo::String::From(url
.spec());
385 application_manager_
.ConnectToApplication(
386 nullptr, request
.Pass(), std::string(), GetProxy(&services
),
387 exposed_services
.Pass(), shell::GetPermissiveCapabilityFilter(),
388 base::Bind(&Context::OnApplicationEnd
, base::Unretained(this), url
),
389 shell::EmptyConnectCallback());
392 void Context::RunCommandLineApplication(const base::Closure
& callback
) {
393 DCHECK(app_urls_
.empty());
394 DCHECK(app_complete_callback_
.is_null());
395 base::CommandLine
* command_line
= base::CommandLine::ForCurrentProcess();
396 base::CommandLine::StringVector args
= command_line
->GetArgs();
397 for (size_t i
= 0; i
< args
.size(); ++i
) {
398 GURL
possible_app(args
[i
]);
399 if (possible_app
.SchemeIs("mojo")) {
401 app_complete_callback_
= callback
;
407 void Context::OnApplicationEnd(const GURL
& url
) {
408 if (app_urls_
.find(url
) != app_urls_
.end()) {
409 app_urls_
.erase(url
);
410 if (app_urls_
.empty() && base::MessageLoop::current()->is_running()) {
411 DCHECK_EQ(base::MessageLoop::current()->task_runner(),
412 task_runners_
->shell_runner());
413 if (app_complete_callback_
.is_null()) {
414 base::MessageLoop::current()->Quit();
416 app_complete_callback_
.Run();
422 } // namespace runner