Add long running gmail memory benchmark for background tab.
[chromium-blink-merge.git] / mojo / runner / context.cc
blob7a6a6adf19b303f6139289676ddd933b3be7b087
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"
7 #include <vector>
9 #include "base/bind.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/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/in_process_native_runner.h"
33 #include "mojo/runner/out_of_process_native_runner.h"
34 #include "mojo/runner/switches.h"
35 #include "mojo/services/tracing/tracing.mojom.h"
36 #include "mojo/shell/application_loader.h"
37 #include "mojo/shell/application_manager.h"
38 #include "mojo/shell/switches.h"
39 #include "mojo/util/filename_util.h"
40 #include "url/gurl.h"
42 namespace mojo {
43 namespace runner {
44 namespace {
46 // Used to ensure we only init once.
47 class Setup {
48 public:
49 Setup() {
50 embedder::Init(make_scoped_ptr(new embedder::SimplePlatformSupport()));
53 ~Setup() {}
55 private:
56 DISALLOW_COPY_AND_ASSIGN(Setup);
59 bool ConfigureURLMappings(const base::CommandLine& command_line,
60 Context* context) {
61 URLResolver* resolver = context->url_resolver();
63 // Configure the resolution of unknown mojo: URLs.
64 GURL base_url;
65 if (!command_line.HasSwitch(switches::kUseUpdater)) {
66 // Use the shell's file root if the base was not specified.
67 base_url = context->ResolveShellFileURL(std::string());
70 if (base_url.is_valid())
71 resolver->SetMojoBaseURL(base_url);
73 // The network service and updater must be loaded from the filesystem.
74 // This mapping is done before the command line URL mapping are processed, so
75 // that it can be overridden.
76 resolver->AddURLMapping(GURL("mojo:network_service"),
77 context->ResolveShellFileURL(
78 "file:network_service/network_service.mojo"));
79 resolver->AddURLMapping(
80 GURL("mojo:updater"),
81 context->ResolveShellFileURL("file:updater/updater.mojo"));
83 // Command line URL mapping.
84 std::vector<URLResolver::OriginMapping> origin_mappings =
85 URLResolver::GetOriginMappings(command_line.argv());
86 for (const auto& origin_mapping : origin_mappings)
87 resolver->AddOriginMapping(GURL(origin_mapping.origin),
88 GURL(origin_mapping.base_url));
90 if (command_line.HasSwitch(switches::kURLMappings)) {
91 const std::string mappings =
92 command_line.GetSwitchValueASCII(switches::kURLMappings);
94 base::StringPairs pairs;
95 if (!base::SplitStringIntoKeyValuePairs(mappings, '=', ',', &pairs))
96 return false;
97 using StringPair = std::pair<std::string, std::string>;
98 for (const StringPair& pair : pairs) {
99 const GURL from(pair.first);
100 const GURL to = context->ResolveCommandLineURL(pair.second);
101 if (!from.is_valid() || !to.is_valid())
102 return false;
103 resolver->AddURLMapping(from, to);
107 return true;
110 void InitContentHandlers(shell::ApplicationManager* manager,
111 const base::CommandLine& command_line) {
112 // Default content handlers.
113 manager->RegisterContentHandler("application/pdf", GURL("mojo:pdf_viewer"));
114 manager->RegisterContentHandler("image/png", GURL("mojo:png_viewer"));
115 manager->RegisterContentHandler("text/html", GURL("mojo:html_viewer"));
117 // Command-line-specified content handlers.
118 std::string handlers_spec =
119 command_line.GetSwitchValueASCII(switches::kContentHandlers);
120 if (handlers_spec.empty())
121 return;
123 #if defined(OS_ANDROID)
124 // TODO(eseidel): On Android we pass command line arguments is via the
125 // 'parameters' key on the intent, which we specify during 'am shell start'
126 // via --esa, however that expects comma-separated values and says:
127 // am shell --help:
128 // [--esa <EXTRA_KEY> <EXTRA_STRING_VALUE>[,<EXTRA_STRING_VALUE...]]
129 // (to embed a comma into a string escape it using "\,")
130 // Whatever takes 'parameters' and constructs a CommandLine is failing to
131 // un-escape the commas, we need to move this fix to that file.
132 base::ReplaceSubstringsAfterOffset(&handlers_spec, 0, "\\,", ",");
133 #endif
135 std::vector<std::string> parts;
136 base::SplitString(handlers_spec, ',', &parts);
137 if (parts.size() % 2 != 0) {
138 LOG(ERROR) << "Invalid value for switch " << switches::kContentHandlers
139 << ": must be a comma-separated list of mimetype/url pairs."
140 << handlers_spec;
141 return;
144 for (size_t i = 0; i < parts.size(); i += 2) {
145 GURL url(parts[i + 1]);
146 if (!url.is_valid()) {
147 LOG(ERROR) << "Invalid value for switch " << switches::kContentHandlers
148 << ": '" << parts[i + 1] << "' is not a valid URL.";
149 return;
151 // TODO(eseidel): We should also validate that the mimetype is valid
152 // net/base/mime_util.h could do this, but we don't want to depend on net.
153 manager->RegisterContentHandler(parts[i], url);
157 void InitNativeOptions(shell::ApplicationManager* manager,
158 const base::CommandLine& command_line) {
159 std::vector<std::string> force_in_process_url_list;
160 base::SplitString(command_line.GetSwitchValueASCII(switches::kForceInProcess),
161 ',', &force_in_process_url_list);
162 for (const auto& force_in_process_url : force_in_process_url_list) {
163 GURL gurl(force_in_process_url);
164 if (!gurl.is_valid()) {
165 LOG(ERROR) << "Invalid value for switch " << switches::kForceInProcess
166 << ": '" << force_in_process_url << "'is not a valid URL.";
167 return;
170 shell::NativeRunnerFactory::Options options;
171 options.force_in_process = true;
172 manager->SetNativeOptionsForURL(options, gurl);
176 void InitDevToolsServiceIfNeeded(shell::ApplicationManager* manager,
177 const base::CommandLine& command_line) {
178 if (!command_line.HasSwitch(devtools_service::kRemoteDebuggingPort))
179 return;
181 std::string port_str =
182 command_line.GetSwitchValueASCII(devtools_service::kRemoteDebuggingPort);
183 unsigned port;
184 if (!base::StringToUint(port_str, &port) || port > 65535) {
185 LOG(ERROR) << "Invalid value for switch "
186 << devtools_service::kRemoteDebuggingPort << ": '" << port_str
187 << "' is not a valid port number.";
188 return;
191 ServiceProviderPtr devtools_service_provider;
192 URLRequestPtr request(URLRequest::New());
193 request->url = "mojo:devtools_service";
194 manager->ConnectToApplication(
195 nullptr, request.Pass(), std::string(), GURL("mojo:shell"),
196 GetProxy(&devtools_service_provider), nullptr,
197 shell::GetPermissiveCapabilityFilter(), base::Closure());
199 devtools_service::DevToolsCoordinatorPtr devtools_coordinator;
200 devtools_service_provider->ConnectToService(
201 devtools_service::DevToolsCoordinator::Name_,
202 GetProxy(&devtools_coordinator).PassMessagePipe());
203 devtools_coordinator->Initialize(static_cast<uint16_t>(port));
206 class TracingServiceProvider : public ServiceProvider {
207 public:
208 explicit TracingServiceProvider(InterfaceRequest<ServiceProvider> request)
209 : binding_(this, request.Pass()) {}
210 ~TracingServiceProvider() override {}
212 void ConnectToService(const String& service_name,
213 ScopedMessagePipeHandle client_handle) override {
214 if (service_name == tracing::TraceController::Name_) {
215 new TraceControllerImpl(
216 MakeRequest<tracing::TraceController>(client_handle.Pass()));
220 private:
221 StrongBinding<ServiceProvider> binding_;
223 DISALLOW_COPY_AND_ASSIGN(TracingServiceProvider);
226 } // namespace
228 Context::Context() : application_manager_(this) {
229 DCHECK(!base::MessageLoop::current());
231 // By default assume that the local apps reside alongside the shell.
232 // TODO(ncbray): really, this should be passed in rather than defaulting.
233 // This default makes sense for desktop but not Android.
234 base::FilePath shell_dir;
235 PathService::Get(base::DIR_MODULE, &shell_dir);
236 SetShellFileRoot(shell_dir);
238 base::FilePath cwd;
239 PathService::Get(base::DIR_CURRENT, &cwd);
240 SetCommandLineCWD(cwd);
243 Context::~Context() {
244 DCHECK(!base::MessageLoop::current());
247 // static
248 void Context::EnsureEmbedderIsInitialized() {
249 static base::LazyInstance<Setup>::Leaky setup = LAZY_INSTANCE_INITIALIZER;
250 setup.Get();
253 void Context::SetShellFileRoot(const base::FilePath& path) {
254 shell_file_root_ =
255 util::AddTrailingSlashIfNeeded(util::FilePathToFileURL(path));
258 GURL Context::ResolveShellFileURL(const std::string& path) {
259 return shell_file_root_.Resolve(path);
262 void Context::SetCommandLineCWD(const base::FilePath& path) {
263 command_line_cwd_ =
264 util::AddTrailingSlashIfNeeded(util::FilePathToFileURL(path));
267 GURL Context::ResolveCommandLineURL(const std::string& path) {
268 return command_line_cwd_.Resolve(path);
271 bool Context::Init() {
272 TRACE_EVENT0("mojo_shell", "Context::Init");
273 const base::CommandLine& command_line =
274 *base::CommandLine::ForCurrentProcess();
276 EnsureEmbedderIsInitialized();
277 task_runners_.reset(
278 new TaskRunners(base::MessageLoop::current()->task_runner()));
280 // TODO(vtl): Probably these failures should be checked before |Init()|, and
281 // this function simply shouldn't fail.
282 if (!shell_file_root_.is_valid())
283 return false;
284 if (!ConfigureURLMappings(command_line, this))
285 return false;
287 // TODO(vtl): This should be MASTER, not NONE.
288 embedder::InitIPCSupport(
289 embedder::ProcessType::NONE, task_runners_->shell_runner(), this,
290 task_runners_->io_runner(), embedder::ScopedPlatformHandle());
292 scoped_ptr<shell::NativeRunnerFactory> runner_factory;
293 if (command_line.HasSwitch(switches::kEnableMultiprocess))
294 runner_factory.reset(new OutOfProcessNativeRunnerFactory(this));
295 else
296 runner_factory.reset(new InProcessNativeRunnerFactory(this));
297 application_manager_.set_blocking_pool(task_runners_->blocking_pool());
298 application_manager_.set_native_runner_factory(runner_factory.Pass());
299 application_manager_.set_disable_cache(
300 base::CommandLine::ForCurrentProcess()->HasSwitch(
301 switches::kDisableCache));
303 InitContentHandlers(&application_manager_, command_line);
304 InitNativeOptions(&application_manager_, command_line);
306 ServiceProviderPtr tracing_service_provider_ptr;
307 new TracingServiceProvider(GetProxy(&tracing_service_provider_ptr));
308 mojo::URLRequestPtr request(mojo::URLRequest::New());
309 request->url = mojo::String::From("mojo:tracing");
310 application_manager_.ConnectToApplication(
311 nullptr, request.Pass(), std::string(), GURL(""), nullptr,
312 tracing_service_provider_ptr.Pass(),
313 shell::GetPermissiveCapabilityFilter(), base::Closure());
315 InitDevToolsServiceIfNeeded(&application_manager_, command_line);
317 return true;
320 void Context::Shutdown() {
321 TRACE_EVENT0("mojo_shell", "Context::Shutdown");
322 DCHECK_EQ(base::MessageLoop::current()->task_runner(),
323 task_runners_->shell_runner());
324 embedder::ShutdownIPCSupport();
325 // We'll quit when we get OnShutdownComplete().
326 base::MessageLoop::current()->Run();
329 GURL Context::ResolveMappings(const GURL& url) {
330 return url_resolver_.ApplyMappings(url);
333 GURL Context::ResolveMojoURL(const GURL& url) {
334 return url_resolver_.ResolveMojoURL(url);
337 bool Context::CreateFetcher(
338 const GURL& url,
339 const shell::Fetcher::FetchCallback& loader_callback) {
340 return false;
343 void Context::OnShutdownComplete() {
344 DCHECK_EQ(base::MessageLoop::current()->task_runner(),
345 task_runners_->shell_runner());
346 base::MessageLoop::current()->Quit();
349 void Context::Run(const GURL& url) {
350 DCHECK(app_complete_callback_.is_null());
351 ServiceProviderPtr services;
352 ServiceProviderPtr exposed_services;
354 app_urls_.insert(url);
355 mojo::URLRequestPtr request(mojo::URLRequest::New());
356 request->url = mojo::String::From(url.spec());
357 application_manager_.ConnectToApplication(
358 nullptr, request.Pass(), std::string(), GURL(), GetProxy(&services),
359 exposed_services.Pass(), shell::GetPermissiveCapabilityFilter(),
360 base::Bind(&Context::OnApplicationEnd, base::Unretained(this), url));
363 void Context::RunCommandLineApplication(const base::Closure& callback) {
364 DCHECK(app_urls_.empty());
365 DCHECK(app_complete_callback_.is_null());
366 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
367 base::CommandLine::StringVector args = command_line->GetArgs();
368 for (size_t i = 0; i < args.size(); ++i) {
369 GURL possible_app(args[i]);
370 if (possible_app.SchemeIs("mojo")) {
371 Run(possible_app);
372 app_complete_callback_ = callback;
373 break;
378 void Context::OnApplicationEnd(const GURL& url) {
379 if (app_urls_.find(url) != app_urls_.end()) {
380 app_urls_.erase(url);
381 if (app_urls_.empty() && base::MessageLoop::current()->is_running()) {
382 DCHECK_EQ(base::MessageLoop::current()->task_runner(),
383 task_runners_->shell_runner());
384 if (app_complete_callback_.is_null()) {
385 base::MessageLoop::current()->Quit();
386 } else {
387 app_complete_callback_.Run();
393 } // namespace runner
394 } // namespace mojo