blob: c4c602e20ca82887b7609af906e1d38ba4c92494 [file] [log] [blame]
[email protected]b39c6d92012-01-31 16:38:411// Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]d032f492009-09-29 00:33:462// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
[email protected]e15a4fa2010-02-11 23:09:295#include "chrome/browser/nacl_host/nacl_process_host.h"
[email protected]d032f492009-09-29 00:33:466
[email protected]a82af392012-02-24 04:40:207#include <string>
8#include <vector>
[email protected]d032f492009-09-29 00:33:469
[email protected]30c1eea2011-10-17 18:40:3010#include "base/bind.h"
[email protected]103607e2010-02-01 18:57:0911#include "base/command_line.h"
[email protected]4a0141b2012-03-27 01:15:3012#include "base/memory/mru_cache.h"
[email protected]4734d0b2011-12-03 07:10:4413#include "base/memory/singleton.h"
[email protected]338466a82011-05-03 04:27:4314#include "base/path_service.h"
[email protected]8f42b4d2012-03-24 14:12:3315#include "base/string_util.h"
[email protected]a0a69bf2011-09-23 21:40:2816#include "base/stringprintf.h"
[email protected]be1ce6a72010-08-03 14:35:2217#include "base/utf_string_conversions.h"
[email protected]1e67c2b2011-03-04 01:17:3718#include "base/win/windows_version.h"
[email protected]a82af392012-02-24 04:40:2019#include "build/build_config.h"
[email protected]8f42b4d2012-03-24 14:12:3320#include "chrome/browser/extensions/extension_info_map.h"
21#include "chrome/browser/renderer_host/chrome_render_message_filter.h"
[email protected]31a665e72012-03-11 12:37:4622#include "chrome/common/chrome_constants.h"
[email protected]338466a82011-05-03 04:27:4323#include "chrome/common/chrome_paths.h"
[email protected]d032f492009-09-29 00:33:4624#include "chrome/common/chrome_switches.h"
25#include "chrome/common/logging_chrome.h"
[email protected]103607e2010-02-01 18:57:0926#include "chrome/common/nacl_cmd_line.h"
[email protected]d032f492009-09-29 00:33:4627#include "chrome/common/nacl_messages.h"
[email protected]fb1277e82009-11-21 20:32:3028#include "chrome/common/render_messages.h"
[email protected]8f42b4d2012-03-24 14:12:3329#include "chrome/common/url_constants.h"
[email protected]4967f792012-01-20 22:14:4030#include "content/public/browser/browser_child_process_host.h"
31#include "content/public/browser/child_process_data.h"
[email protected]4734d0b2011-12-03 07:10:4432#include "content/public/common/child_process_host.h"
[email protected]8f42b4d2012-03-24 14:12:3333#include "googleurl/src/gurl.h"
[email protected]d032f492009-09-29 00:33:4634#include "ipc/ipc_switches.h"
[email protected]1d8a3d1f2011-02-19 07:11:5235#include "native_client/src/shared/imc/nacl_imc.h"
[email protected]d032f492009-09-29 00:33:4636
[email protected]d032f492009-09-29 00:33:4637#if defined(OS_POSIX)
[email protected]a82af392012-02-24 04:40:2038#include <fcntl.h>
39
[email protected]d032f492009-09-29 00:33:4640#include "ipc/ipc_channel_posix.h"
[email protected]4bdde602010-06-16 03:17:3541#elif defined(OS_WIN)
[email protected]a82af392012-02-24 04:40:2042#include <windows.h>
43
[email protected]b39c6d92012-01-31 16:38:4144#include "base/threading/thread.h"
45#include "base/process_util.h"
[email protected]4bdde602010-06-16 03:17:3546#include "chrome/browser/nacl_host/nacl_broker_service_win.h"
[email protected]b39c6d92012-01-31 16:38:4147#include "native_client/src/trusted/service_runtime/win/debug_exception_handler.h"
[email protected]d032f492009-09-29 00:33:4648#endif
49
[email protected]631bb742011-11-02 11:29:3950using content::BrowserThread;
[email protected]4967f792012-01-20 22:14:4051using content::ChildProcessData;
[email protected]4734d0b2011-12-03 07:10:4452using content::ChildProcessHost;
[email protected]631bb742011-11-02 11:29:3953
[email protected]b39c6d92012-01-31 16:38:4154#if defined(OS_WIN)
55class NaClProcessHost::DebugContext
56 : public base::RefCountedThreadSafe<NaClProcessHost::DebugContext> {
57 public:
58 DebugContext()
59 : can_send_start_msg_(false),
60 child_process_host_(NULL) {
61 }
62
63 ~DebugContext() {
64 }
65
66 void AttachDebugger(int pid, base::ProcessHandle process);
67
68 // 6 methods below must be called on Browser::IO thread.
69 void SetStartMessage(IPC::Message* start_msg);
70 void SetChildProcessHost(content::ChildProcessHost* child_process_host);
71 void SetDebugThread(base::Thread* thread_);
72
73 // Start message is sent from 2 flows of execution. The first flow is
74 // NaClProcessHost::SendStart. The second flow is
75 // NaClProcessHost::OnChannelConnected and
76 // NaClProcessHost::DebugContext::AttachThread. The message itself is created
77 // by first flow. But the moment it can be sent is determined by second flow.
78 // So first flow executes SetStartMessage and SendStartMessage while second
79 // flow uses AllowAndSendStartMessage to either send potentially pending
80 // start message or set the flag that allows the first flow to do this.
81
82 // Clears the flag that prevents sending start message.
83 void AllowToSendStartMsg();
84 // Send start message to the NaCl process or do nothing if message is not
85 // set or not allowed to be send. If message is sent, it is cleared and
86 // repeated calls do nothing.
87 void SendStartMessage();
88 // Clear the flag that prevents further sending start message and send start
89 // message if it is set.
90 void AllowAndSendStartMessage();
91 private:
92 void StopThread();
93 // These 4 fields are accessed only from Browser::IO thread.
94 scoped_ptr<base::Thread> thread_;
95 scoped_ptr<IPC::Message> start_msg_;
96 // Debugger is attached or exception handling is not switched on.
97 // This means that start message can be sent to the NaCl process.
98 bool can_send_start_msg_;
99 content::ChildProcessHost* child_process_host_;
100};
101
102void NaClProcessHost::DebugContext::AttachDebugger(
103 int pid, base::ProcessHandle process) {
104 BOOL attached;
105 DWORD exit_code;
106 attached = DebugActiveProcess(pid);
107 if (!attached) {
108 LOG(ERROR) << "Failed to connect to the process";
109 }
110 BrowserThread::PostTask(
111 BrowserThread::IO, FROM_HERE,
112 base::Bind(
113 &NaClProcessHost::DebugContext::AllowAndSendStartMessage, this));
114 if (attached) {
115 // debug the process
116 NaClDebugLoop(process, &exit_code);
117 base::CloseProcessHandle(process);
118 }
119 BrowserThread::PostTask(
120 BrowserThread::IO, FROM_HERE,
121 base::Bind(&NaClProcessHost::DebugContext::StopThread, this));
122}
123
124void NaClProcessHost::DebugContext::SetStartMessage(IPC::Message* start_msg) {
125 start_msg_.reset(start_msg);
126}
127
128void NaClProcessHost::DebugContext::SetChildProcessHost(
129 content::ChildProcessHost* child_process_host) {
130 child_process_host_ = child_process_host;
131}
132
133void NaClProcessHost::DebugContext::SetDebugThread(base::Thread* thread) {
134 thread_.reset(thread);
135}
136
137void NaClProcessHost::DebugContext::AllowToSendStartMsg() {
138 can_send_start_msg_ = true;
139}
140
141void NaClProcessHost::DebugContext::SendStartMessage() {
142 if (start_msg_.get() && can_send_start_msg_) {
143 if (child_process_host_) {
144 if (!child_process_host_->Send(start_msg_.release())) {
145 LOG(ERROR) << "Failed to send start message";
146 }
147 }
148 }
149}
150
151void NaClProcessHost::DebugContext::AllowAndSendStartMessage() {
152 AllowToSendStartMsg();
153 SendStartMessage();
154}
155
156void NaClProcessHost::DebugContext::StopThread() {
157 thread_->Stop();
158 thread_.reset();
159}
160#endif
161
[email protected]c47ec402010-07-29 10:20:49162namespace {
163
164void SetCloseOnExec(nacl::Handle fd) {
165#if defined(OS_POSIX)
166 int flags = fcntl(fd, F_GETFD);
[email protected]773ebb92011-11-15 19:06:52167 CHECK_NE(flags, -1);
[email protected]c47ec402010-07-29 10:20:49168 int rc = fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
[email protected]773ebb92011-11-15 19:06:52169 CHECK_EQ(rc, 0);
[email protected]c47ec402010-07-29 10:20:49170#endif
171}
172
[email protected]773ebb92011-11-15 19:06:52173// Represents shared state for all NaClProcessHost objects in the browser.
174// Currently this just handles holding onto the file descriptor for the IRT.
175class NaClBrowser {
176 public:
177 static NaClBrowser* GetInstance() {
178 return Singleton<NaClBrowser>::get();
179 }
180
181 bool IrtAvailable() const {
182 return irt_platform_file_ != base::kInvalidPlatformFileValue;
183 }
184
185 base::PlatformFile IrtFile() const {
186 CHECK_NE(irt_platform_file_, base::kInvalidPlatformFileValue);
187 return irt_platform_file_;
188 }
189
190 // Asynchronously attempt to get the IRT open.
191 bool EnsureIrtAvailable();
192
193 // Make sure the IRT gets opened and follow up with the reply when it's ready.
194 bool MakeIrtAvailable(const base::Closure& reply);
195
[email protected]31a665e72012-03-11 12:37:46196 // Path to IRT. Available even before IRT is loaded.
197 const FilePath& GetIrtFilePath();
198
[email protected]4a0141b2012-03-27 01:15:30199 // Is the validation signature in the database?
200 bool QueryKnownToValidate(const std::string& signature);
201
202 // Put the validation signature in the database.
203 void SetKnownToValidate(const std::string& signature);
204
[email protected]773ebb92011-11-15 19:06:52205 private:
206 base::PlatformFile irt_platform_file_;
207
[email protected]31a665e72012-03-11 12:37:46208 FilePath irt_filepath_;
209
[email protected]4a0141b2012-03-27 01:15:30210 typedef base::HashingMRUCache<std::string, bool> ValidationCacheType;
211 ValidationCacheType validation_cache_;
212
[email protected]773ebb92011-11-15 19:06:52213 friend struct DefaultSingletonTraits<NaClBrowser>;
214
215 NaClBrowser()
[email protected]31a665e72012-03-11 12:37:46216 : irt_platform_file_(base::kInvalidPlatformFileValue),
[email protected]4a0141b2012-03-27 01:15:30217 irt_filepath_(),
218 // For the moment, choose an arbitrary cache size.
219 validation_cache_(200) {
[email protected]31a665e72012-03-11 12:37:46220 InitIrtFilePath();
221 }
[email protected]773ebb92011-11-15 19:06:52222
223 ~NaClBrowser() {
224 if (irt_platform_file_ != base::kInvalidPlatformFileValue)
225 base::ClosePlatformFile(irt_platform_file_);
226 }
227
[email protected]31a665e72012-03-11 12:37:46228 void InitIrtFilePath();
229
[email protected]773ebb92011-11-15 19:06:52230 void OpenIrtLibraryFile();
231
232 static void DoOpenIrtLibraryFile() {
233 GetInstance()->OpenIrtLibraryFile();
234 }
235
236 DISALLOW_COPY_AND_ASSIGN(NaClBrowser);
237};
238
[email protected]c47ec402010-07-29 10:20:49239} // namespace
240
[email protected]1d8a3d1f2011-02-19 07:11:52241struct NaClProcessHost::NaClInternal {
242 std::vector<nacl::Handle> sockets_for_renderer;
243 std::vector<nacl::Handle> sockets_for_sel_ldr;
244};
245
[email protected]773ebb92011-11-15 19:06:52246#if defined(OS_WIN)
[email protected]5804cb5d2011-12-19 21:55:35247static bool RunningOnWOW64() {
[email protected]773ebb92011-11-15 19:06:52248 return (base::win::OSInfo::GetInstance()->wow64_status() ==
249 base::win::OSInfo::WOW64_ENABLED);
[email protected]773ebb92011-11-15 19:06:52250}
[email protected]5804cb5d2011-12-19 21:55:35251#endif
[email protected]773ebb92011-11-15 19:06:52252
[email protected]1dbaaa702011-04-06 17:43:42253NaClProcessHost::NaClProcessHost(const std::wstring& url)
[email protected]a575da52012-03-22 13:08:36254 :
255#if defined(OS_WIN)
256 process_launched_by_broker_(false),
257#endif
258 reply_msg_(NULL),
[email protected]1d8a3d1f2011-02-19 07:11:52259 internal_(new NaClInternal()),
[email protected]5ca93be2012-03-21 20:04:06260 ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)),
261 enable_exception_handling_(false) {
[email protected]4967f792012-01-20 22:14:40262 process_.reset(content::BrowserChildProcessHost::Create(
263 content::PROCESS_TYPE_NACL_LOADER, this));
264 process_->SetName(WideToUTF16Hack(url));
[email protected]5ca93be2012-03-21 20:04:06265
266 // We allow untrusted hardware exception handling to be enabled via
267 // an env var for consistency with the standalone build of NaCl.
268 if (CommandLine::ForCurrentProcess()->HasSwitch(
269 switches::kEnableNaClExceptionHandling) ||
270 getenv("NACL_UNTRUSTED_EXCEPTION_HANDLING") != NULL) {
271 enable_exception_handling_ = true;
[email protected]b39c6d92012-01-31 16:38:41272#if defined(OS_WIN)
[email protected]fb335fe2012-03-24 18:11:38273 debug_context_ = new DebugContext();
[email protected]b39c6d92012-01-31 16:38:41274#endif
[email protected]5ca93be2012-03-21 20:04:06275 }
[email protected]d032f492009-09-29 00:33:46276}
277
[email protected]fb1277e82009-11-21 20:32:30278NaClProcessHost::~NaClProcessHost() {
[email protected]4cb43102011-12-02 20:24:49279 int exit_code;
[email protected]4967f792012-01-20 22:14:40280 process_->GetTerminationStatus(&exit_code);
[email protected]4cb43102011-12-02 20:24:49281 std::string message =
282 base::StringPrintf("NaCl process exited with status %i (0x%x)",
283 exit_code, exit_code);
284 if (exit_code == 0) {
285 LOG(INFO) << message;
286 } else {
287 LOG(ERROR) << message;
288 }
289
[email protected]1d8a3d1f2011-02-19 07:11:52290 for (size_t i = 0; i < internal_->sockets_for_renderer.size(); i++) {
[email protected]909c2402011-05-09 11:39:04291 if (nacl::Close(internal_->sockets_for_renderer[i]) != 0) {
292 LOG(ERROR) << "nacl::Close() failed";
293 }
[email protected]c47ec402010-07-29 10:20:49294 }
[email protected]1d8a3d1f2011-02-19 07:11:52295 for (size_t i = 0; i < internal_->sockets_for_sel_ldr.size(); i++) {
[email protected]909c2402011-05-09 11:39:04296 if (nacl::Close(internal_->sockets_for_sel_ldr[i]) != 0) {
297 LOG(ERROR) << "nacl::Close() failed";
298 }
[email protected]c47ec402010-07-29 10:20:49299 }
300
[email protected]909c2402011-05-09 11:39:04301 if (reply_msg_) {
302 // The process failed to launch for some reason.
303 // Don't keep the renderer hanging.
304 reply_msg_->set_reply_error();
305 chrome_render_message_filter_->Send(reply_msg_);
306 }
[email protected]b39c6d92012-01-31 16:38:41307#if defined(OS_WIN)
[email protected]a575da52012-03-22 13:08:36308 if (process_launched_by_broker_) {
309 NaClBrokerService::GetInstance()->OnLoaderDied();
[email protected]5ca93be2012-03-21 20:04:06310 }
311 if (debug_context_ != NULL) {
[email protected]b39c6d92012-01-31 16:38:41312 debug_context_->SetChildProcessHost(NULL);
313 }
314#endif
[email protected]fb1277e82009-11-21 20:32:30315}
316
[email protected]773ebb92011-11-15 19:06:52317// Attempt to ensure the IRT will be available when we need it, but don't wait.
318bool NaClBrowser::EnsureIrtAvailable() {
319 if (IrtAvailable())
320 return true;
321
322 return BrowserThread::PostTask(
323 BrowserThread::FILE, FROM_HERE,
324 base::Bind(&NaClBrowser::DoOpenIrtLibraryFile));
325}
326
327// We really need the IRT to be available now, so make sure that it is.
328// When it's ready, we'll run the reply closure.
329bool NaClBrowser::MakeIrtAvailable(const base::Closure& reply) {
330 return BrowserThread::PostTaskAndReply(
331 BrowserThread::FILE, FROM_HERE,
332 base::Bind(&NaClBrowser::DoOpenIrtLibraryFile), reply);
333}
334
335// This is called at browser startup.
336// static
337void NaClProcessHost::EarlyStartup() {
338#if defined(OS_LINUX) && !defined(OS_CHROMEOS)
339 // Open the IRT file early to make sure that it isn't replaced out from
340 // under us by autoupdate.
341 NaClBrowser::GetInstance()->EnsureIrtAvailable();
342#endif
343}
344
[email protected]a575da52012-03-22 13:08:36345void NaClProcessHost::Launch(
[email protected]92d56412011-03-24 20:53:52346 ChromeRenderMessageFilter* chrome_render_message_filter,
347 int socket_count,
[email protected]8f42b4d2012-03-24 14:12:33348 IPC::Message* reply_msg,
349 scoped_refptr<ExtensionInfoMap> extension_info_map) {
[email protected]a575da52012-03-22 13:08:36350 chrome_render_message_filter_ = chrome_render_message_filter;
351 reply_msg_ = reply_msg;
[email protected]8f42b4d2012-03-24 14:12:33352 extension_info_map_ = extension_info_map;
[email protected]a575da52012-03-22 13:08:36353
[email protected]c47ec402010-07-29 10:20:49354 // Place an arbitrary limit on the number of sockets to limit
355 // exposure in case the renderer is compromised. We can increase
356 // this if necessary.
357 if (socket_count > 8) {
[email protected]a575da52012-03-22 13:08:36358 delete this;
359 return;
[email protected]c47ec402010-07-29 10:20:49360 }
361
[email protected]773ebb92011-11-15 19:06:52362 // Start getting the IRT open asynchronously while we launch the NaCl process.
363 // We'll make sure this actually finished in OnProcessLaunched, below.
364 if (!NaClBrowser::GetInstance()->EnsureIrtAvailable()) {
365 LOG(ERROR) << "Cannot launch NaCl process after IRT file open failed";
[email protected]a575da52012-03-22 13:08:36366 delete this;
367 return;
[email protected]773ebb92011-11-15 19:06:52368 }
369
[email protected]c47ec402010-07-29 10:20:49370 // Rather than creating a socket pair in the renderer, and passing
371 // one side through the browser to sel_ldr, socket pairs are created
372 // in the browser and then passed to the renderer and sel_ldr.
373 //
374 // This is mainly for the benefit of Windows, where sockets cannot
375 // be passed in messages, but are copied via DuplicateHandle().
376 // This means the sandboxed renderer cannot send handles to the
377 // browser process.
378
379 for (int i = 0; i < socket_count; i++) {
380 nacl::Handle pair[2];
381 // Create a connected socket
[email protected]a575da52012-03-22 13:08:36382 if (nacl::SocketPair(pair) == -1) {
383 delete this;
384 return;
385 }
[email protected]1d8a3d1f2011-02-19 07:11:52386 internal_->sockets_for_renderer.push_back(pair[0]);
387 internal_->sockets_for_sel_ldr.push_back(pair[1]);
[email protected]c47ec402010-07-29 10:20:49388 SetCloseOnExec(pair[0]);
389 SetCloseOnExec(pair[1]);
390 }
[email protected]d032f492009-09-29 00:33:46391
392 // Launch the process
[email protected]fb1277e82009-11-21 20:32:30393 if (!LaunchSelLdr()) {
[email protected]a575da52012-03-22 13:08:36394 delete this;
[email protected]d032f492009-09-29 00:33:46395 }
[email protected]d032f492009-09-29 00:33:46396}
397
[email protected]8ae7bd6f2012-03-14 03:23:02398scoped_ptr<CommandLine> NaClProcessHost::LaunchWithNaClGdb(
[email protected]8f42b4d2012-03-24 14:12:33399 const FilePath& nacl_gdb,
400 CommandLine* line,
401 const FilePath& manifest_path) {
[email protected]31a665e72012-03-11 12:37:46402 CommandLine* cmd_line = new CommandLine(nacl_gdb);
403 // We can't use PrependWrapper because our parameters contain spaces.
404 cmd_line->AppendArg("--eval-command");
405 const FilePath::StringType& irt_path =
406 NaClBrowser::GetInstance()->GetIrtFilePath().value();
407 cmd_line->AppendArgNative(FILE_PATH_LITERAL("nacl-irt ") + irt_path);
[email protected]8f42b4d2012-03-24 14:12:33408 if (!manifest_path.empty()) {
409 cmd_line->AppendArg("--eval-command");
410 cmd_line->AppendArgNative(FILE_PATH_LITERAL("nacl-manifest ") +
411 manifest_path.value());
412 }
[email protected]31a665e72012-03-11 12:37:46413 cmd_line->AppendArg("--args");
414 const CommandLine::StringVector& argv = line->argv();
415 for (size_t i = 0; i < argv.size(); i++) {
416 cmd_line->AppendArgNative(argv[i]);
417 }
418 return scoped_ptr<CommandLine>(cmd_line);
419}
420
[email protected]fb1277e82009-11-21 20:32:30421bool NaClProcessHost::LaunchSelLdr() {
[email protected]4967f792012-01-20 22:14:40422 std::string channel_id = process_->GetHost()->CreateChannel();
[email protected]4734d0b2011-12-03 07:10:44423 if (channel_id.empty())
[email protected]d032f492009-09-29 00:33:46424 return false;
425
[email protected]e3fc75a2011-05-05 08:20:42426 CommandLine::StringType nacl_loader_prefix;
427#if defined(OS_POSIX)
428 nacl_loader_prefix = CommandLine::ForCurrentProcess()->GetSwitchValueNative(
429 switches::kNaClLoaderCmdPrefix);
430#endif // defined(OS_POSIX)
431
[email protected]d032f492009-09-29 00:33:46432 // Build command line for nacl.
[email protected]8c40f322011-08-24 03:33:36433
434#if defined(OS_MACOSX)
435 // The Native Client process needs to be able to allocate a 1GB contiguous
436 // region to use as the client environment's virtual address space. ASLR
437 // (PIE) interferes with this by making it possible that no gap large enough
438 // to accomodate this request will exist in the child process' address
439 // space. Disable PIE for NaCl processes. See http://crbug.com/90221 and
440 // http://code.google.com/p/nativeclient/issues/detail?id=2043.
[email protected]4cb43102011-12-02 20:24:49441 int flags = ChildProcessHost::CHILD_NO_PIE;
[email protected]8c40f322011-08-24 03:33:36442#elif defined(OS_LINUX)
[email protected]4cb43102011-12-02 20:24:49443 int flags = nacl_loader_prefix.empty() ? ChildProcessHost::CHILD_ALLOW_SELF :
444 ChildProcessHost::CHILD_NORMAL;
[email protected]8c40f322011-08-24 03:33:36445#else
[email protected]4cb43102011-12-02 20:24:49446 int flags = ChildProcessHost::CHILD_NORMAL;
[email protected]8c40f322011-08-24 03:33:36447#endif
448
[email protected]4cb43102011-12-02 20:24:49449 FilePath exe_path = ChildProcessHost::GetChildPath(flags);
[email protected]fb1277e82009-11-21 20:32:30450 if (exe_path.empty())
[email protected]d032f492009-09-29 00:33:46451 return false;
452
[email protected]31a665e72012-03-11 12:37:46453#if defined(OS_WIN)
454 // On Windows 64-bit NaCl loader is called nacl64.exe instead of chrome.exe
455 if (RunningOnWOW64()) {
456 FilePath module_path;
457 if (!PathService::Get(base::FILE_MODULE, &module_path))
458 return false;
459 exe_path = module_path.DirName().Append(chrome::kNaClAppName);
460 }
461#endif
462
[email protected]33a05af2012-03-02 18:15:51463 scoped_ptr<CommandLine> cmd_line(new CommandLine(exe_path));
464 nacl::CopyNaClCommandLineArguments(cmd_line.get());
[email protected]599e6642010-01-27 18:52:13465
[email protected]05076ba22010-07-30 05:59:57466 cmd_line->AppendSwitchASCII(switches::kProcessType,
467 switches::kNaClLoaderProcess);
[email protected]4734d0b2011-12-03 07:10:44468 cmd_line->AppendSwitchASCII(switches::kProcessChannelID, channel_id);
[email protected]93156cec2011-09-12 21:14:44469 if (logging::DialogsAreSuppressed())
470 cmd_line->AppendSwitch(switches::kNoErrorDialogs);
[email protected]d032f492009-09-29 00:33:46471
[email protected]e3fc75a2011-05-05 08:20:42472 if (!nacl_loader_prefix.empty())
473 cmd_line->PrependWrapper(nacl_loader_prefix);
474
[email protected]31a665e72012-03-11 12:37:46475 FilePath nacl_gdb = CommandLine::ForCurrentProcess()->GetSwitchValuePath(
476 switches::kNaClGdb);
477 if (!nacl_gdb.empty()) {
[email protected]8f42b4d2012-03-24 14:12:33478 GURL manifest_url = GURL(process_->GetData().name);
479 FilePath manifest_path;
480 const Extension* extension = extension_info_map_->extensions().
481 GetExtensionOrAppByURL(ExtensionURLInfo(manifest_url));
482 if (extension != NULL && manifest_url.SchemeIs(chrome::kExtensionScheme)) {
483 std::string path = manifest_url.path();
484 TrimString(path, "/", &path); // Remove first slash
485 manifest_path = extension->path().AppendASCII(path);
486 }
[email protected]31a665e72012-03-11 12:37:46487 cmd_line->AppendSwitch(switches::kNoSandbox);
488 scoped_ptr<CommandLine> gdb_cmd_line(
[email protected]8f42b4d2012-03-24 14:12:33489 LaunchWithNaClGdb(nacl_gdb, cmd_line.get(), manifest_path));
[email protected]31a665e72012-03-11 12:37:46490 // We can't use process_->Launch() because OnProcessLaunched will be called
491 // with process_->GetData().handle filled by handle of gdb process. This
492 // handle will be used to duplicate handles for NaCl process and as
493 // a result NaCl process will not be able to use them.
494 //
495 // So we don't fill process_->GetData().handle and wait for
496 // OnChannelConnected to get handle of NaCl process from its pid. Then we
497 // call OnProcessLaunched.
498 return base::LaunchProcess(*gdb_cmd_line, base::LaunchOptions(), NULL);
499 }
500
[email protected]103607e2010-02-01 18:57:09501 // On Windows we might need to start the broker process to launch a new loader
[email protected]d032f492009-09-29 00:33:46502#if defined(OS_WIN)
[email protected]773ebb92011-11-15 19:06:52503 if (RunningOnWOW64()) {
[email protected]644b2e22012-03-25 01:41:07504 return NaClBrokerService::GetInstance()->LaunchLoader(this, channel_id);
[email protected]4bdde602010-06-16 03:17:35505 } else {
[email protected]33a05af2012-03-02 18:15:51506 process_->Launch(FilePath(), cmd_line.release());
[email protected]4bdde602010-06-16 03:17:35507 }
[email protected]103607e2010-02-01 18:57:09508#elif defined(OS_POSIX)
[email protected]4967f792012-01-20 22:14:40509 process_->Launch(nacl_loader_prefix.empty(), // use_zygote
[email protected]a82af392012-02-24 04:40:20510 base::EnvironmentVector(),
[email protected]33a05af2012-03-02 18:15:51511 cmd_line.release());
[email protected]103607e2010-02-01 18:57:09512#endif
[email protected]d032f492009-09-29 00:33:46513
[email protected]fb1277e82009-11-21 20:32:30514 return true;
[email protected]d032f492009-09-29 00:33:46515}
516
[email protected]a575da52012-03-22 13:08:36517#if defined(OS_WIN)
[email protected]fb335fe2012-03-24 18:11:38518void NaClProcessHost::OnProcessLaunchedByBroker(base::ProcessHandle handle) {
[email protected]a575da52012-03-22 13:08:36519 process_launched_by_broker_ = true;
[email protected]4967f792012-01-20 22:14:40520 process_->SetHandle(handle);
[email protected]103607e2010-02-01 18:57:09521 OnProcessLaunched();
522}
523
[email protected]fb335fe2012-03-24 18:11:38524void NaClProcessHost::OnDebugExceptionHandlerLaunchedByBroker() {
525 debug_context_->AllowAndSendStartMessage();
526}
527#endif
528
[email protected]463ea5f2011-12-03 06:57:47529void NaClProcessHost::OnProcessCrashed(int exit_code) {
530 std::string message = base::StringPrintf(
531 "NaCl process exited with status %i (0x%x)", exit_code, exit_code);
532 LOG(ERROR) << message;
[email protected]103607e2010-02-01 18:57:09533}
534
[email protected]75e0c502011-12-16 21:53:01535namespace {
536
537// Determine the name of the IRT file based on the architecture.
538
539#define NACL_IRT_FILE_NAME(arch_string) \
540 (FILE_PATH_LITERAL("nacl_irt_") \
541 FILE_PATH_LITERAL(arch_string) \
542 FILE_PATH_LITERAL(".nexe"))
543
544const FilePath::StringType NaClIrtName() {
545#if defined(ARCH_CPU_X86_FAMILY)
[email protected]75e0c502011-12-16 21:53:01546#if defined(ARCH_CPU_X86_64)
[email protected]5804cb5d2011-12-19 21:55:35547 bool is64 = true;
548#elif defined(OS_WIN)
549 bool is64 = RunningOnWOW64();
550#else
551 bool is64 = false;
[email protected]75e0c502011-12-16 21:53:01552#endif
553 return is64 ? NACL_IRT_FILE_NAME("x86_64") : NACL_IRT_FILE_NAME("x86_32");
554#elif defined(ARCH_CPU_ARMEL)
555 // TODO(mcgrathr): Eventually we'll need to distinguish arm32 vs thumb2.
556 // That may need to be based on the actual nexe rather than a static
557 // choice, which would require substantial refactoring.
558 return NACL_IRT_FILE_NAME("arm");
559#else
560#error Add support for your architecture to NaCl IRT file selection
561#endif
562}
563
564} // namespace
565
[email protected]31a665e72012-03-11 12:37:46566void NaClBrowser::InitIrtFilePath() {
[email protected]88e15832011-07-19 01:18:24567 // Allow the IRT library to be overridden via an environment
568 // variable. This allows the NaCl/Chromium integration bot to
569 // specify a newly-built IRT rather than using a prebuilt one
570 // downloaded via Chromium's DEPS file. We use the same environment
571 // variable that the standalone NaCl PPAPI plugin accepts.
572 const char* irt_path_var = getenv("NACL_IRT_LIBRARY");
573 if (irt_path_var != NULL) {
[email protected]773ebb92011-11-15 19:06:52574 FilePath::StringType path_string(
575 irt_path_var, const_cast<const char*>(strchr(irt_path_var, '\0')));
[email protected]31a665e72012-03-11 12:37:46576 irt_filepath_ = FilePath(path_string);
[email protected]88e15832011-07-19 01:18:24577 } else {
578 FilePath plugin_dir;
579 if (!PathService::Get(chrome::DIR_INTERNAL_PLUGINS, &plugin_dir)) {
580 LOG(ERROR) << "Failed to locate the plugins directory";
[email protected]88e15832011-07-19 01:18:24581 return;
582 }
[email protected]773ebb92011-11-15 19:06:52583
[email protected]31a665e72012-03-11 12:37:46584 irt_filepath_ = plugin_dir.Append(NaClIrtName());
[email protected]338466a82011-05-03 04:27:43585 }
[email protected]31a665e72012-03-11 12:37:46586}
587
588const FilePath& NaClBrowser::GetIrtFilePath() {
589 return irt_filepath_;
590}
591
592// This only ever runs on the BrowserThread::FILE thread.
593// If multiple tasks are posted, the later ones are no-ops.
594void NaClBrowser::OpenIrtLibraryFile() {
595 if (irt_platform_file_ != base::kInvalidPlatformFileValue)
596 // We've already run.
597 return;
[email protected]88e15832011-07-19 01:18:24598
[email protected]773ebb92011-11-15 19:06:52599 base::PlatformFileError error_code;
[email protected]31a665e72012-03-11 12:37:46600 irt_platform_file_ = base::CreatePlatformFile(irt_filepath_,
[email protected]773ebb92011-11-15 19:06:52601 base::PLATFORM_FILE_OPEN |
602 base::PLATFORM_FILE_READ,
603 NULL,
604 &error_code);
605 if (error_code != base::PLATFORM_FILE_OK) {
606 LOG(ERROR) << "Failed to open NaCl IRT file \""
[email protected]31a665e72012-03-11 12:37:46607 << irt_filepath_.LossyDisplayName()
[email protected]773ebb92011-11-15 19:06:52608 << "\": " << error_code;
609 }
610}
611
612void NaClProcessHost::OnProcessLaunched() {
613 NaClBrowser* nacl_browser = NaClBrowser::GetInstance();
614
615 if (nacl_browser->IrtAvailable()) {
616 // The IRT is already open. Away we go.
617 SendStart(nacl_browser->IrtFile());
618 } else {
619 // We're waiting for the IRT to be open.
[email protected]98999e802011-12-21 21:54:43620 if (!nacl_browser->MakeIrtAvailable(
621 base::Bind(&NaClProcessHost::IrtReady,
622 weak_factory_.GetWeakPtr())))
623 delete this;
[email protected]773ebb92011-11-15 19:06:52624 }
625}
626
627// The asynchronous attempt to get the IRT file open has completed.
628void NaClProcessHost::IrtReady() {
629 NaClBrowser* nacl_browser = NaClBrowser::GetInstance();
630
631 if (nacl_browser->IrtAvailable()) {
632 SendStart(nacl_browser->IrtFile());
633 } else {
634 LOG(ERROR) << "Cannot launch NaCl process after IRT file open failed";
[email protected]338466a82011-05-03 04:27:43635 delete this;
636 }
637}
638
[email protected]b39c6d92012-01-31 16:38:41639#if defined(OS_WIN)
[email protected]b39c6d92012-01-31 16:38:41640void NaClProcessHost::OnChannelConnected(int32 peer_pid) {
[email protected]31a665e72012-03-11 12:37:46641 // Set process handle, if it was not set previously.
642 // This is needed when NaCl process is launched with nacl-gdb.
643 if (process_->GetData().handle == base::kNullProcessHandle) {
644 base::ProcessHandle process;
645 DCHECK(!CommandLine::ForCurrentProcess()->GetSwitchValuePath(
646 switches::kNaClGdb).empty());
647 if (base::OpenProcessHandleWithAccess(
648 peer_pid,
649 base::kProcessAccessDuplicateHandle |
[email protected]59261242012-03-19 13:08:59650 base::kProcessAccessQueryInformation |
[email protected]31a665e72012-03-11 12:37:46651 base::kProcessAccessWaitForTermination,
652 &process)) {
653 process_->SetHandle(process);
654 OnProcessLaunched();
655 } else {
656 LOG(ERROR) << "Failed to get process handle";
657 }
658 }
[email protected]5ca93be2012-03-21 20:04:06659 if (debug_context_ == NULL) {
[email protected]b39c6d92012-01-31 16:38:41660 return;
661 }
[email protected]b39c6d92012-01-31 16:38:41662 debug_context_->SetChildProcessHost(process_->GetHost());
[email protected]fb335fe2012-03-24 18:11:38663 if (RunningOnWOW64()) {
664 if (!NaClBrokerService::GetInstance()->LaunchDebugExceptionHandler(
665 this, peer_pid)) {
666 debug_context_->AllowAndSendStartMessage();
667 }
668 } else {
669 // Start new thread for debug loop
670 // We can't use process_->GetData().handle because it doesn't have necessary
671 // access rights.
672 base::ProcessHandle process;
673 if (!base::OpenProcessHandleWithAccess(
674 peer_pid,
675 base::kProcessAccessQueryInformation |
676 base::kProcessAccessSuspendResume |
677 base::kProcessAccessTerminate |
678 base::kProcessAccessVMOperation |
679 base::kProcessAccessVMRead |
680 base::kProcessAccessVMWrite |
681 base::kProcessAccessWaitForTermination,
682 &process)) {
683 LOG(ERROR) << "Failed to open the process";
684 debug_context_->AllowAndSendStartMessage();
685 return;
686 }
687 base::Thread* dbg_thread = new base::Thread("Debug thread");
688 if (!dbg_thread->Start()) {
689 LOG(ERROR) << "Debug thread not started";
690 debug_context_->AllowAndSendStartMessage();
691 base::CloseProcessHandle(process);
692 return;
693 }
694 debug_context_->SetDebugThread(dbg_thread);
695 // System can not reallocate pid until we close process handle. So using
696 // pid in different thread is fine.
697 dbg_thread->message_loop()->PostTask(FROM_HERE,
698 base::Bind(&NaClProcessHost::DebugContext::AttachDebugger,
699 debug_context_, peer_pid, process));
[email protected]b39c6d92012-01-31 16:38:41700 }
[email protected]b39c6d92012-01-31 16:38:41701}
702#else
703void NaClProcessHost::OnChannelConnected(int32 peer_pid) {
704}
705#endif
706
707
[email protected]773ebb92011-11-15 19:06:52708static bool SendHandleToSelLdr(
709 base::ProcessHandle processh,
710 nacl::Handle sourceh, bool close_source,
711 std::vector<nacl::FileDescriptor> *handles_for_sel_ldr) {
712#if defined(OS_WIN)
713 HANDLE channel;
714 int flags = DUPLICATE_SAME_ACCESS;
715 if (close_source)
716 flags |= DUPLICATE_CLOSE_SOURCE;
717 if (!DuplicateHandle(GetCurrentProcess(),
718 reinterpret_cast<HANDLE>(sourceh),
719 processh,
720 &channel,
721 0, // Unused given DUPLICATE_SAME_ACCESS.
722 FALSE,
723 flags)) {
724 LOG(ERROR) << "DuplicateHandle() failed";
725 return false;
726 }
727 handles_for_sel_ldr->push_back(
728 reinterpret_cast<nacl::FileDescriptor>(channel));
729#else
730 nacl::FileDescriptor channel;
731 channel.fd = sourceh;
732 channel.auto_close = close_source;
733 handles_for_sel_ldr->push_back(channel);
734#endif
735 return true;
736}
737
738void NaClProcessHost::SendStart(base::PlatformFile irt_file) {
739 CHECK_NE(irt_file, base::kInvalidPlatformFileValue);
740
[email protected]c47ec402010-07-29 10:20:49741 std::vector<nacl::FileDescriptor> handles_for_renderer;
[email protected]fb1277e82009-11-21 20:32:30742 base::ProcessHandle nacl_process_handle;
[email protected]fb1277e82009-11-21 20:32:30743
[email protected]1d8a3d1f2011-02-19 07:11:52744 for (size_t i = 0; i < internal_->sockets_for_renderer.size(); i++) {
[email protected]c47ec402010-07-29 10:20:49745#if defined(OS_WIN)
746 // Copy the handle into the renderer process.
747 HANDLE handle_in_renderer;
[email protected]909c2402011-05-09 11:39:04748 if (!DuplicateHandle(base::GetCurrentProcessHandle(),
749 reinterpret_cast<HANDLE>(
750 internal_->sockets_for_renderer[i]),
751 chrome_render_message_filter_->peer_handle(),
752 &handle_in_renderer,
753 0, // Unused given DUPLICATE_SAME_ACCESS.
754 FALSE,
755 DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS)) {
756 LOG(ERROR) << "DuplicateHandle() failed";
757 delete this;
758 return;
759 }
[email protected]c47ec402010-07-29 10:20:49760 handles_for_renderer.push_back(
761 reinterpret_cast<nacl::FileDescriptor>(handle_in_renderer));
762#else
763 // No need to dup the imc_handle - we don't pass it anywhere else so
764 // it cannot be closed.
765 nacl::FileDescriptor imc_handle;
[email protected]1d8a3d1f2011-02-19 07:11:52766 imc_handle.fd = internal_->sockets_for_renderer[i];
[email protected]c47ec402010-07-29 10:20:49767 imc_handle.auto_close = true;
768 handles_for_renderer.push_back(imc_handle);
769#endif
770 }
771
[email protected]4967f792012-01-20 22:14:40772 const ChildProcessData& data = process_->GetData();
[email protected]c47ec402010-07-29 10:20:49773#if defined(OS_WIN)
774 // Copy the process handle into the renderer process.
[email protected]909c2402011-05-09 11:39:04775 if (!DuplicateHandle(base::GetCurrentProcessHandle(),
[email protected]4967f792012-01-20 22:14:40776 data.handle,
[email protected]909c2402011-05-09 11:39:04777 chrome_render_message_filter_->peer_handle(),
778 &nacl_process_handle,
779 PROCESS_DUP_HANDLE,
780 FALSE,
781 0)) {
782 LOG(ERROR) << "DuplicateHandle() failed";
783 delete this;
784 return;
785 }
[email protected]fb1277e82009-11-21 20:32:30786#else
[email protected]fb1277e82009-11-21 20:32:30787 // We use pid as process handle on Posix
[email protected]4967f792012-01-20 22:14:40788 nacl_process_handle = data.handle;
[email protected]fb1277e82009-11-21 20:32:30789#endif
790
791 // Get the pid of the NaCl process
[email protected]4967f792012-01-20 22:14:40792 base::ProcessId nacl_process_id = base::GetProcId(data.handle);
[email protected]fb1277e82009-11-21 20:32:30793
[email protected]2ccf45c2011-08-19 23:35:50794 ChromeViewHostMsg_LaunchNaCl::WriteReplyParams(
[email protected]c47ec402010-07-29 10:20:49795 reply_msg_, handles_for_renderer, nacl_process_handle, nacl_process_id);
[email protected]92d56412011-03-24 20:53:52796 chrome_render_message_filter_->Send(reply_msg_);
797 chrome_render_message_filter_ = NULL;
[email protected]fb1277e82009-11-21 20:32:30798 reply_msg_ = NULL;
[email protected]1d8a3d1f2011-02-19 07:11:52799 internal_->sockets_for_renderer.clear();
[email protected]fb1277e82009-11-21 20:32:30800
[email protected]c47ec402010-07-29 10:20:49801 std::vector<nacl::FileDescriptor> handles_for_sel_ldr;
[email protected]1d8a3d1f2011-02-19 07:11:52802 for (size_t i = 0; i < internal_->sockets_for_sel_ldr.size(); i++) {
[email protected]4967f792012-01-20 22:14:40803 if (!SendHandleToSelLdr(data.handle,
[email protected]773ebb92011-11-15 19:06:52804 internal_->sockets_for_sel_ldr[i], true,
805 &handles_for_sel_ldr)) {
[email protected]909c2402011-05-09 11:39:04806 delete this;
[email protected]c47ec402010-07-29 10:20:49807 return;
808 }
[email protected]773ebb92011-11-15 19:06:52809 }
810
811 // Send over the IRT file handle. We don't close our own copy!
[email protected]4967f792012-01-20 22:14:40812 if (!SendHandleToSelLdr(data.handle, irt_file, false, &handles_for_sel_ldr)) {
[email protected]773ebb92011-11-15 19:06:52813 delete this;
814 return;
[email protected]c47ec402010-07-29 10:20:49815 }
816
[email protected]ab88d1542011-11-18 22:52:00817#if defined(OS_MACOSX)
818 // For dynamic loading support, NaCl requires a file descriptor that
819 // was created in /tmp, since those created with shm_open() are not
820 // mappable with PROT_EXEC. Rather than requiring an extra IPC
821 // round trip out of the sandbox, we create an FD here.
[email protected]cbbe7842011-11-17 22:01:25822 base::SharedMemory memory_buffer;
[email protected]b05df6b2011-12-01 23:19:31823 base::SharedMemoryCreateOptions options;
824 options.size = 1;
825 options.executable = true;
826 if (!memory_buffer.Create(options)) {
[email protected]2c68bf032010-11-11 23:16:30827 LOG(ERROR) << "Failed to allocate memory buffer";
[email protected]909c2402011-05-09 11:39:04828 delete this;
[email protected]2c68bf032010-11-11 23:16:30829 return;
830 }
[email protected]cbbe7842011-11-17 22:01:25831 nacl::FileDescriptor memory_fd;
832 memory_fd.fd = dup(memory_buffer.handle().fd);
833 if (memory_fd.fd < 0) {
834 LOG(ERROR) << "Failed to dup() a file descriptor";
835 delete this;
836 return;
837 }
838 memory_fd.auto_close = true;
[email protected]2c68bf032010-11-11 23:16:30839 handles_for_sel_ldr.push_back(memory_fd);
840#endif
841
[email protected]5ca93be2012-03-21 20:04:06842 IPC::Message* start_message =
843 new NaClProcessMsg_Start(handles_for_sel_ldr, enable_exception_handling_);
[email protected]b39c6d92012-01-31 16:38:41844#if defined(OS_WIN)
[email protected]5ca93be2012-03-21 20:04:06845 if (debug_context_ != NULL) {
846 debug_context_->SetStartMessage(start_message);
[email protected]b39c6d92012-01-31 16:38:41847 debug_context_->SendStartMessage();
848 } else {
[email protected]5ca93be2012-03-21 20:04:06849 process_->Send(start_message);
[email protected]b39c6d92012-01-31 16:38:41850 }
851#else
[email protected]5ca93be2012-03-21 20:04:06852 process_->Send(start_message);
[email protected]b39c6d92012-01-31 16:38:41853#endif
854
[email protected]1d8a3d1f2011-02-19 07:11:52855 internal_->sockets_for_sel_ldr.clear();
[email protected]d032f492009-09-29 00:33:46856}
857
[email protected]4a0141b2012-03-27 01:15:30858bool NaClBrowser::QueryKnownToValidate(const std::string& signature) {
859 ValidationCacheType::iterator iter = validation_cache_.Get(signature);
860 if (iter == validation_cache_.end()) {
861 // Not found.
862 return false;
863 } else {
864 return iter->second;
865 }
866}
867
868void NaClBrowser::SetKnownToValidate(const std::string& signature) {
869 validation_cache_.Put(signature, true);
870}
871
872void NaClProcessHost::OnQueryKnownToValidate(const std::string& signature,
873 bool* result) {
874 *result = NaClBrowser::GetInstance()->QueryKnownToValidate(signature);
875}
876
877void NaClProcessHost::OnSetKnownToValidate(const std::string& signature) {
878 NaClBrowser::GetInstance()->SetKnownToValidate(signature);
879}
880
881// Needed to handle sync messages in OnMessageRecieved.
882bool NaClProcessHost::Send(IPC::Message* msg) {
883 return process_->Send(msg);
884}
885
[email protected]a95986a82010-12-24 06:19:28886bool NaClProcessHost::OnMessageReceived(const IPC::Message& msg) {
[email protected]4a0141b2012-03-27 01:15:30887 bool handled = true;
888 IPC_BEGIN_MESSAGE_MAP(NaClProcessHost, msg)
889 IPC_MESSAGE_HANDLER(NaClProcessMsg_QueryKnownToValidate,
890 OnQueryKnownToValidate)
891 IPC_MESSAGE_HANDLER(NaClProcessMsg_SetKnownToValidate,
892 OnSetKnownToValidate)
893 IPC_MESSAGE_UNHANDLED(handled = false)
894 IPC_END_MESSAGE_MAP()
895 return handled;
[email protected]d032f492009-09-29 00:33:46896}