Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(120)

Side by Side Diff: mojo/runner/context.cc

Issue 1630823002: Move mojo/runner to mojo/shell/standalone (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: . Created 4 years, 10 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « mojo/runner/context.h ('k') | mojo/runner/desktop/launcher_process.h » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
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.
4
5 #include "mojo/runner/context.h"
6
7 #include <stddef.h>
8 #include <stdint.h>
9
10 #include <utility>
11 #include <vector>
12
13 #include "base/bind.h"
14 #include "base/command_line.h"
15 #include "base/files/file_path.h"
16 #include "base/i18n/icu_util.h"
17 #include "base/lazy_instance.h"
18 #include "base/macros.h"
19 #include "base/memory/scoped_ptr.h"
20 #include "base/path_service.h"
21 #include "base/process/process_info.h"
22 #include "base/run_loop.h"
23 #include "base/strings/string_number_conversions.h"
24 #include "base/strings/string_split.h"
25 #include "base/strings/string_util.h"
26 #include "base/trace_event/trace_event.h"
27 #include "build/build_config.h"
28 #include "components/devtools_service/public/cpp/switches.h"
29 #include "components/devtools_service/public/interfaces/devtools_service.mojom.h "
30 #include "components/tracing/tracing_switches.h"
31 #include "mojo/public/cpp/bindings/strong_binding.h"
32 #include "mojo/runner/register_local_aliases.h"
33 #include "mojo/runner/switches.h"
34 #include "mojo/runner/tracer.h"
35 #include "mojo/services/tracing/public/cpp/switches.h"
36 #include "mojo/services/tracing/public/cpp/trace_provider_impl.h"
37 #include "mojo/services/tracing/public/cpp/tracing_impl.h"
38 #include "mojo/services/tracing/public/interfaces/tracing.mojom.h"
39 #include "mojo/shell/application_loader.h"
40 #include "mojo/shell/connect_to_application_params.h"
41 #include "mojo/shell/package_manager/package_manager_impl.h"
42 #include "mojo/shell/public/cpp/application_connection.h"
43 #include "mojo/shell/public/cpp/application_delegate.h"
44 #include "mojo/shell/public/cpp/application_impl.h"
45 #include "mojo/shell/query_util.h"
46 #include "mojo/shell/runner/host/in_process_native_runner.h"
47 #include "mojo/shell/runner/host/out_of_process_native_runner.h"
48 #include "mojo/shell/switches.h"
49 #include "mojo/util/filename_util.h"
50 #include "third_party/mojo/src/mojo/edk/embedder/embedder.h"
51 #include "url/gurl.h"
52
53 namespace mojo {
54 namespace runner {
55 namespace {
56
57 // Used to ensure we only init once.
58 class Setup {
59 public:
60 Setup() {
61 embedder::PreInitializeParentProcess();
62 embedder::Init();
63 }
64
65 ~Setup() {}
66
67 private:
68 DISALLOW_COPY_AND_ASSIGN(Setup);
69 };
70
71 void InitContentHandlers(shell::PackageManagerImpl* manager,
72 const base::CommandLine& command_line) {
73 // Default content handlers.
74 manager->RegisterContentHandler("application/javascript",
75 GURL("mojo:html_viewer"));
76 manager->RegisterContentHandler("application/pdf", GURL("mojo:pdf_viewer"));
77 manager->RegisterContentHandler("image/gif", GURL("mojo:html_viewer"));
78 manager->RegisterContentHandler("image/jpeg", GURL("mojo:html_viewer"));
79 manager->RegisterContentHandler("image/png", GURL("mojo:html_viewer"));
80 manager->RegisterContentHandler("text/css", GURL("mojo:html_viewer"));
81 manager->RegisterContentHandler("text/html", GURL("mojo:html_viewer"));
82 manager->RegisterContentHandler("text/plain", GURL("mojo:html_viewer"));
83
84 // Command-line-specified content handlers.
85 std::string handlers_spec =
86 command_line.GetSwitchValueASCII(switches::kContentHandlers);
87 if (handlers_spec.empty())
88 return;
89
90 #if defined(OS_ANDROID)
91 // TODO(eseidel): On Android we pass command line arguments is via the
92 // 'parameters' key on the intent, which we specify during 'am shell start'
93 // via --esa, however that expects comma-separated values and says:
94 // am shell --help:
95 // [--esa <EXTRA_KEY> <EXTRA_STRING_VALUE>[,<EXTRA_STRING_VALUE...]]
96 // (to embed a comma into a string escape it using "\,")
97 // Whatever takes 'parameters' and constructs a CommandLine is failing to
98 // un-escape the commas, we need to move this fix to that file.
99 base::ReplaceSubstringsAfterOffset(&handlers_spec, 0, "\\,", ",");
100 #endif
101
102 std::vector<std::string> parts = base::SplitString(
103 handlers_spec, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
104 if (parts.size() % 2 != 0) {
105 LOG(ERROR) << "Invalid value for switch " << switches::kContentHandlers
106 << ": must be a comma-separated list of mimetype/url pairs."
107 << handlers_spec;
108 return;
109 }
110
111 for (size_t i = 0; i < parts.size(); i += 2) {
112 GURL url(parts[i + 1]);
113 if (!url.is_valid()) {
114 LOG(ERROR) << "Invalid value for switch " << switches::kContentHandlers
115 << ": '" << parts[i + 1] << "' is not a valid URL.";
116 return;
117 }
118 // TODO(eseidel): We should also validate that the mimetype is valid
119 // net/base/mime_util.h could do this, but we don't want to depend on net.
120 manager->RegisterContentHandler(parts[i], url);
121 }
122 }
123
124 void InitDevToolsServiceIfNeeded(shell::ApplicationManager* manager,
125 const base::CommandLine& command_line) {
126 if (!command_line.HasSwitch(devtools_service::kRemoteDebuggingPort))
127 return;
128
129 std::string port_str =
130 command_line.GetSwitchValueASCII(devtools_service::kRemoteDebuggingPort);
131 unsigned port;
132 if (!base::StringToUint(port_str, &port) || port > 65535) {
133 LOG(ERROR) << "Invalid value for switch "
134 << devtools_service::kRemoteDebuggingPort << ": '" << port_str
135 << "' is not a valid port number.";
136 return;
137 }
138
139 ServiceProviderPtr devtools_service_provider;
140 scoped_ptr<shell::ConnectToApplicationParams> params(
141 new shell::ConnectToApplicationParams);
142 params->set_source(shell::Identity(GURL("mojo:shell"), std::string(),
143 shell::GetPermissiveCapabilityFilter()));
144 params->SetTarget(shell::Identity(GURL("mojo:devtools_service"),
145 std::string(),
146 shell::GetPermissiveCapabilityFilter()));
147 params->set_services(GetProxy(&devtools_service_provider));
148 manager->ConnectToApplication(std::move(params));
149
150 devtools_service::DevToolsCoordinatorPtr devtools_coordinator;
151 devtools_service_provider->ConnectToService(
152 devtools_service::DevToolsCoordinator::Name_,
153 GetProxy(&devtools_coordinator).PassMessagePipe());
154 devtools_coordinator->Initialize(static_cast<uint16_t>(port));
155 }
156
157 class TracingServiceProvider : public ServiceProvider {
158 public:
159 TracingServiceProvider(Tracer* tracer,
160 InterfaceRequest<ServiceProvider> request)
161 : tracer_(tracer), binding_(this, std::move(request)) {}
162 ~TracingServiceProvider() override {}
163
164 void ConnectToService(const mojo::String& service_name,
165 ScopedMessagePipeHandle client_handle) override {
166 if (tracer_ && service_name == tracing::TraceProvider::Name_) {
167 tracer_->ConnectToProvider(
168 MakeRequest<tracing::TraceProvider>(std::move(client_handle)));
169 }
170 }
171
172 private:
173 Tracer* tracer_;
174 StrongBinding<ServiceProvider> binding_;
175
176 DISALLOW_COPY_AND_ASSIGN(TracingServiceProvider);
177 };
178
179 } // namespace
180
181 Context::Context()
182 : package_manager_(nullptr), main_entry_time_(base::Time::Now()) {}
183
184 Context::~Context() {
185 DCHECK(!base::MessageLoop::current());
186 }
187
188 // static
189 void Context::EnsureEmbedderIsInitialized() {
190 static base::LazyInstance<Setup>::Leaky setup = LAZY_INSTANCE_INITIALIZER;
191 setup.Get();
192 }
193
194 bool Context::Init(const base::FilePath& shell_file_root) {
195 TRACE_EVENT0("mojo_shell", "Context::Init");
196 const base::CommandLine& command_line =
197 *base::CommandLine::ForCurrentProcess();
198
199 bool trace_startup = command_line.HasSwitch(switches::kTraceStartup);
200 if (trace_startup) {
201 tracer_.Start(
202 command_line.GetSwitchValueASCII(switches::kTraceStartup),
203 command_line.GetSwitchValueASCII(switches::kTraceStartupDuration),
204 "mojo_runner.trace");
205 }
206
207 // ICU data is a thing every part of the system needs. This here warms
208 // up the copy of ICU in the mojo runner.
209 CHECK(base::i18n::InitializeICU());
210
211 EnsureEmbedderIsInitialized();
212 task_runners_.reset(
213 new TaskRunners(base::MessageLoop::current()->task_runner()));
214
215 // TODO(vtl): This should be MASTER, not NONE.
216 embedder::InitIPCSupport(embedder::ProcessType::NONE, this,
217 task_runners_->io_runner(),
218 embedder::ScopedPlatformHandle());
219
220 package_manager_ = new shell::PackageManagerImpl(
221 shell_file_root, task_runners_->blocking_pool());
222 InitContentHandlers(package_manager_, command_line);
223
224 RegisterLocalAliases(package_manager_);
225
226 scoped_ptr<shell::NativeRunnerFactory> runner_factory;
227 if (command_line.HasSwitch(switches::kMojoSingleProcess)) {
228 #if defined(COMPONENT_BUILD)
229 LOG(ERROR) << "Running Mojo in single process component build, which isn't "
230 << "supported because statics in apps interact. Use static build"
231 << " or don't pass --single-process.";
232 #endif
233 runner_factory.reset(new shell::InProcessNativeRunnerFactory(
234 task_runners_->blocking_pool()));
235 } else {
236 runner_factory.reset(new shell::OutOfProcessNativeRunnerFactory(
237 task_runners_->blocking_pool()));
238 }
239 application_manager_.reset(new shell::ApplicationManager(
240 make_scoped_ptr(package_manager_), std::move(runner_factory),
241 task_runners_->blocking_pool()));
242
243 ServiceProviderPtr tracing_services;
244 ServiceProviderPtr tracing_exposed_services;
245 new TracingServiceProvider(&tracer_, GetProxy(&tracing_exposed_services));
246
247 scoped_ptr<shell::ConnectToApplicationParams> params(
248 new shell::ConnectToApplicationParams);
249 params->set_source(shell::Identity(GURL("mojo:shell"), std::string(),
250 shell::GetPermissiveCapabilityFilter()));
251 params->SetTarget(shell::Identity(GURL("mojo:tracing"), std::string(),
252 shell::GetPermissiveCapabilityFilter()));
253 params->set_services(GetProxy(&tracing_services));
254 params->set_exposed_services(std::move(tracing_exposed_services));
255 application_manager_->ConnectToApplication(std::move(params));
256
257 if (command_line.HasSwitch(tracing::kTraceStartup)) {
258 tracing::TraceCollectorPtr coordinator;
259 auto coordinator_request = GetProxy(&coordinator);
260 tracing_services->ConnectToService(tracing::TraceCollector::Name_,
261 coordinator_request.PassMessagePipe());
262 tracer_.StartCollectingFromTracingService(std::move(coordinator));
263 }
264
265 // Record the shell startup metrics used for performance testing.
266 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
267 tracing::kEnableStatsCollectionBindings)) {
268 tracing::StartupPerformanceDataCollectorPtr collector;
269 tracing_services->ConnectToService(
270 tracing::StartupPerformanceDataCollector::Name_,
271 GetProxy(&collector).PassMessagePipe());
272 #if defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
273 // CurrentProcessInfo::CreationTime is only defined on some platforms.
274 const base::Time creation_time = base::CurrentProcessInfo::CreationTime();
275 collector->SetShellProcessCreationTime(creation_time.ToInternalValue());
276 #endif
277 collector->SetShellMainEntryPointTime(main_entry_time_.ToInternalValue());
278 }
279
280 InitDevToolsServiceIfNeeded(application_manager_.get(), command_line);
281
282 return true;
283 }
284
285 void Context::Shutdown() {
286 // Actions triggered by ApplicationManager's destructor may require a current
287 // message loop, so we should destruct it explicitly now as ~Context() occurs
288 // post message loop shutdown.
289 application_manager_.reset();
290
291 TRACE_EVENT0("mojo_shell", "Context::Shutdown");
292 DCHECK_EQ(base::MessageLoop::current()->task_runner(),
293 task_runners_->shell_runner());
294 // Post a task in case OnShutdownComplete is called synchronously.
295 base::MessageLoop::current()->PostTask(
296 FROM_HERE, base::Bind(embedder::ShutdownIPCSupport));
297 // We'll quit when we get OnShutdownComplete().
298 base::MessageLoop::current()->Run();
299 }
300
301 void Context::OnShutdownComplete() {
302 DCHECK_EQ(base::MessageLoop::current()->task_runner(),
303 task_runners_->shell_runner());
304 base::MessageLoop::current()->QuitWhenIdle();
305 }
306
307 void Context::Run(const GURL& url) {
308 DCHECK(app_complete_callback_.is_null());
309 ServiceProviderPtr services;
310 ServiceProviderPtr exposed_services;
311
312 app_urls_.insert(url);
313
314 scoped_ptr<shell::ConnectToApplicationParams> params(
315 new shell::ConnectToApplicationParams);
316 params->SetTarget(shell::Identity(url, std::string(),
317 shell::GetPermissiveCapabilityFilter()));
318 params->set_services(GetProxy(&services));
319 params->set_exposed_services(std::move(exposed_services));
320 params->set_on_application_end(
321 base::Bind(&Context::OnApplicationEnd, base::Unretained(this), url));
322 application_manager_->ConnectToApplication(std::move(params));
323 }
324
325 void Context::RunCommandLineApplication(const base::Closure& callback) {
326 DCHECK(app_urls_.empty());
327 DCHECK(app_complete_callback_.is_null());
328 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
329 base::CommandLine::StringVector args = command_line->GetArgs();
330 for (size_t i = 0; i < args.size(); ++i) {
331 GURL possible_app(args[i]);
332 if (possible_app.SchemeIs("mojo")) {
333 Run(possible_app);
334 app_complete_callback_ = callback;
335 break;
336 }
337 }
338 }
339
340 void Context::OnApplicationEnd(const GURL& url) {
341 if (app_urls_.find(url) != app_urls_.end()) {
342 app_urls_.erase(url);
343 if (app_urls_.empty() && base::MessageLoop::current()->is_running()) {
344 DCHECK_EQ(base::MessageLoop::current()->task_runner(),
345 task_runners_->shell_runner());
346 if (app_complete_callback_.is_null()) {
347 base::MessageLoop::current()->QuitWhenIdle();
348 } else {
349 app_complete_callback_.Run();
350 }
351 }
352 }
353 }
354
355 } // namespace runner
356 } // namespace mojo
OLDNEW
« no previous file with comments | « mojo/runner/context.h ('k') | mojo/runner/desktop/launcher_process.h » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698