chrome/browser/extensions: Remove use of MessageLoopProxy and deprecated MessageLoop...
[chromium-blink-merge.git] / content / browser / utility_process_host_impl.cc
blob8b87f75a6e2ff149a1fd987a58fd9b5b873d0f82
1 // Copyright (c) 2012 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 "content/browser/utility_process_host_impl.h"
7 #include "base/base_switches.h"
8 #include "base/bind.h"
9 #include "base/bind_helpers.h"
10 #include "base/command_line.h"
11 #include "base/lazy_instance.h"
12 #include "base/message_loop/message_loop.h"
13 #include "base/process/process_handle.h"
14 #include "base/run_loop.h"
15 #include "base/sequenced_task_runner.h"
16 #include "base/strings/utf_string_conversions.h"
17 #include "base/synchronization/lock.h"
18 #include "base/synchronization/waitable_event.h"
19 #include "content/browser/browser_child_process_host_impl.h"
20 #include "content/browser/mojo/mojo_application_host.h"
21 #include "content/browser/renderer_host/render_process_host_impl.h"
22 #include "content/common/child_process_host_impl.h"
23 #include "content/common/in_process_child_thread_params.h"
24 #include "content/common/utility_messages.h"
25 #include "content/public/browser/browser_thread.h"
26 #include "content/public/browser/content_browser_client.h"
27 #include "content/public/browser/utility_process_host_client.h"
28 #include "content/public/common/content_switches.h"
29 #include "content/public/common/process_type.h"
30 #include "content/public/common/sandboxed_process_launcher_delegate.h"
31 #include "ipc/ipc_switches.h"
32 #include "ui/base/ui_base_switches.h"
34 namespace content {
36 // NOTE: changes to this class need to be reviewed by the security team.
37 class UtilitySandboxedProcessLauncherDelegate
38 : public SandboxedProcessLauncherDelegate {
39 public:
40 UtilitySandboxedProcessLauncherDelegate(const base::FilePath& exposed_dir,
41 bool launch_elevated,
42 bool no_sandbox,
43 const base::EnvironmentMap& env,
44 ChildProcessHost* host)
45 : exposed_dir_(exposed_dir),
46 #if defined(OS_WIN)
47 launch_elevated_(launch_elevated)
48 #elif defined(OS_POSIX)
49 env_(env),
50 no_sandbox_(no_sandbox),
51 ipc_fd_(host->TakeClientFileDescriptor())
52 #endif // OS_WIN
55 ~UtilitySandboxedProcessLauncherDelegate() override {}
57 #if defined(OS_WIN)
58 bool ShouldLaunchElevated() override { return launch_elevated_; }
59 void PreSandbox(bool* disable_default_policy,
60 base::FilePath* exposed_dir) override {
61 *exposed_dir = exposed_dir_;
63 #elif defined(OS_POSIX)
65 bool ShouldUseZygote() override {
66 return !no_sandbox_ && exposed_dir_.empty();
68 base::EnvironmentMap GetEnvironment() override { return env_; }
69 base::ScopedFD TakeIpcFd() override { return ipc_fd_.Pass(); }
70 #endif // OS_WIN
72 private:
73 base::FilePath exposed_dir_;
75 #if defined(OS_WIN)
76 bool launch_elevated_;
77 #elif defined(OS_POSIX)
78 base::EnvironmentMap env_;
79 bool no_sandbox_;
80 base::ScopedFD ipc_fd_;
81 #endif // OS_WIN
84 UtilityMainThreadFactoryFunction g_utility_main_thread_factory = NULL;
86 UtilityProcessHost* UtilityProcessHost::Create(
87 const scoped_refptr<UtilityProcessHostClient>& client,
88 const scoped_refptr<base::SequencedTaskRunner>& client_task_runner) {
89 return new UtilityProcessHostImpl(client, client_task_runner);
92 void UtilityProcessHostImpl::RegisterUtilityMainThreadFactory(
93 UtilityMainThreadFactoryFunction create) {
94 g_utility_main_thread_factory = create;
97 UtilityProcessHostImpl::UtilityProcessHostImpl(
98 const scoped_refptr<UtilityProcessHostClient>& client,
99 const scoped_refptr<base::SequencedTaskRunner>& client_task_runner)
100 : client_(client),
101 client_task_runner_(client_task_runner),
102 is_batch_mode_(false),
103 is_mdns_enabled_(false),
104 no_sandbox_(false),
105 run_elevated_(false),
106 #if defined(OS_LINUX)
107 child_flags_(ChildProcessHost::CHILD_ALLOW_SELF),
108 #else
109 child_flags_(ChildProcessHost::CHILD_NORMAL),
110 #endif
111 started_(false),
112 name_(base::ASCIIToUTF16("utility process")) {
115 UtilityProcessHostImpl::~UtilityProcessHostImpl() {
116 DCHECK_CURRENTLY_ON(BrowserThread::IO);
117 if (is_batch_mode_)
118 EndBatchMode();
120 // We could be destroyed as a result of Chrome shutdown. When that happens,
121 // the Mojo channel doesn't get the opportunity to shut down cleanly because
122 // it posts to the IO thread (the current thread) which is being destroyed.
123 // To guarantee proper shutdown of the Mojo channel, do it explicitly here.
124 if (mojo_application_host_)
125 mojo_application_host_->ShutdownOnIOThread();
128 bool UtilityProcessHostImpl::Send(IPC::Message* message) {
129 if (!StartProcess())
130 return false;
132 return process_->Send(message);
135 bool UtilityProcessHostImpl::StartBatchMode() {
136 CHECK(!is_batch_mode_);
137 is_batch_mode_ = StartProcess();
138 Send(new UtilityMsg_BatchMode_Started());
139 return is_batch_mode_;
142 void UtilityProcessHostImpl::EndBatchMode() {
143 CHECK(is_batch_mode_);
144 is_batch_mode_ = false;
145 Send(new UtilityMsg_BatchMode_Finished());
148 void UtilityProcessHostImpl::SetExposedDir(const base::FilePath& dir) {
149 exposed_dir_ = dir;
152 void UtilityProcessHostImpl::EnableMDns() {
153 is_mdns_enabled_ = true;
156 void UtilityProcessHostImpl::DisableSandbox() {
157 no_sandbox_ = true;
160 #if defined(OS_WIN)
161 void UtilityProcessHostImpl::ElevatePrivileges() {
162 no_sandbox_ = true;
163 run_elevated_ = true;
165 #endif
167 const ChildProcessData& UtilityProcessHostImpl::GetData() {
168 return process_->GetData();
171 #if defined(OS_POSIX)
173 void UtilityProcessHostImpl::SetEnv(const base::EnvironmentMap& env) {
174 env_ = env;
177 #endif // OS_POSIX
179 bool UtilityProcessHostImpl::StartMojoMode() {
180 CHECK(!mojo_application_host_);
181 mojo_application_host_.reset(new MojoApplicationHost);
183 bool mojo_result = mojo_application_host_->Init();
184 if (!mojo_result)
185 return false;
187 return StartProcess();
190 ServiceRegistry* UtilityProcessHostImpl::GetServiceRegistry() {
191 if (mojo_application_host_)
192 return mojo_application_host_->service_registry();
193 return nullptr;
196 void UtilityProcessHostImpl::SetName(const base::string16& name) {
197 name_ = name;
200 bool UtilityProcessHostImpl::StartProcess() {
201 if (started_)
202 return true;
203 started_ = true;
205 if (is_batch_mode_)
206 return true;
208 // Name must be set or metrics_service will crash in any test which
209 // launches a UtilityProcessHost.
210 process_.reset(new BrowserChildProcessHostImpl(PROCESS_TYPE_UTILITY, this));
211 process_->SetName(name_);
213 std::string channel_id = process_->GetHost()->CreateChannel();
214 if (channel_id.empty())
215 return false;
217 if (RenderProcessHost::run_renderer_in_process()) {
218 DCHECK(g_utility_main_thread_factory);
219 // See comment in RenderProcessHostImpl::Init() for the background on why we
220 // support single process mode this way.
221 in_process_thread_.reset(
222 g_utility_main_thread_factory(InProcessChildThreadParams(
223 channel_id, BrowserThread::UnsafeGetMessageLoopForThread(
224 BrowserThread::IO)->task_runner())));
225 in_process_thread_->Start();
226 OnProcessLaunched();
227 } else {
228 const base::CommandLine& browser_command_line =
229 *base::CommandLine::ForCurrentProcess();
230 int child_flags = child_flags_;
232 bool has_cmd_prefix = browser_command_line.HasSwitch(
233 switches::kUtilityCmdPrefix);
235 // When running under gdb, forking /proc/self/exe ends up forking the gdb
236 // executable instead of Chromium. It is almost safe to assume that no
237 // updates will happen while a developer is running with
238 // |switches::kUtilityCmdPrefix|. See ChildProcessHost::GetChildPath() for
239 // a similar case with Valgrind.
240 if (has_cmd_prefix)
241 child_flags = ChildProcessHost::CHILD_NORMAL;
243 base::FilePath exe_path = ChildProcessHost::GetChildPath(child_flags);
244 if (exe_path.empty()) {
245 NOTREACHED() << "Unable to get utility process binary name.";
246 return false;
249 base::CommandLine* cmd_line = new base::CommandLine(exe_path);
250 cmd_line->AppendSwitchASCII(switches::kProcessType,
251 switches::kUtilityProcess);
252 cmd_line->AppendSwitchASCII(switches::kProcessChannelID, channel_id);
253 std::string locale = GetContentClient()->browser()->GetApplicationLocale();
254 cmd_line->AppendSwitchASCII(switches::kLang, locale);
256 if (no_sandbox_)
257 cmd_line->AppendSwitch(switches::kNoSandbox);
259 // Browser command-line switches to propagate to the utility process.
260 static const char* const kSwitchNames[] = {
261 switches::kDebugPluginLoading,
262 switches::kNoSandbox,
263 switches::kProfilerTiming,
264 #if defined(OS_MACOSX)
265 switches::kEnableSandboxLogging,
266 #endif
268 cmd_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
269 arraysize(kSwitchNames));
271 if (has_cmd_prefix) {
272 // Launch the utility child process with some prefix
273 // (usually "xterm -e gdb --args").
274 cmd_line->PrependWrapper(browser_command_line.GetSwitchValueNative(
275 switches::kUtilityCmdPrefix));
278 if (!exposed_dir_.empty()) {
279 cmd_line->AppendSwitchPath(switches::kUtilityProcessAllowedDir,
280 exposed_dir_);
283 if (is_mdns_enabled_)
284 cmd_line->AppendSwitch(switches::kUtilityProcessEnableMDns);
286 #if defined(OS_WIN)
287 // Let the utility process know if it is intended to be elevated.
288 if (run_elevated_)
289 cmd_line->AppendSwitch(switches::kUtilityProcessRunningElevated);
290 #endif
292 process_->Launch(
293 new UtilitySandboxedProcessLauncherDelegate(exposed_dir_,
294 run_elevated_,
295 no_sandbox_, env_,
296 process_->GetHost()),
297 cmd_line,
298 true);
301 return true;
304 bool UtilityProcessHostImpl::OnMessageReceived(const IPC::Message& message) {
305 if (!client_.get())
306 return true;
308 client_task_runner_->PostTask(
309 FROM_HERE,
310 base::Bind(
311 base::IgnoreResult(&UtilityProcessHostClient::OnMessageReceived),
312 client_.get(),
313 message));
315 return true;
318 void UtilityProcessHostImpl::OnProcessLaunchFailed() {
319 if (!client_.get())
320 return;
322 client_task_runner_->PostTask(
323 FROM_HERE,
324 base::Bind(&UtilityProcessHostClient::OnProcessLaunchFailed,
325 client_.get()));
328 void UtilityProcessHostImpl::OnProcessCrashed(int exit_code) {
329 if (!client_.get())
330 return;
332 client_task_runner_->PostTask(
333 FROM_HERE,
334 base::Bind(&UtilityProcessHostClient::OnProcessCrashed, client_.get(),
335 exit_code));
338 void UtilityProcessHostImpl::OnProcessLaunched() {
339 if (mojo_application_host_) {
340 base::ProcessHandle handle;
341 if (RenderProcessHost::run_renderer_in_process())
342 handle = base::GetCurrentProcessHandle();
343 else
344 handle = process_->GetData().handle;
346 mojo_application_host_->Activate(this, handle);
350 } // namespace content