blob: eb8b25c9accf4d46b018ccc51277f71485c6b581 [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]5b974952012-04-05 18:18:2314#include "base/message_loop.h"
[email protected]0ae52b42012-03-27 02:53:5915#include "base/metrics/histogram.h"
[email protected]338466a82011-05-03 04:27:4316#include "base/path_service.h"
[email protected]5b974952012-04-05 18:18:2317#include "base/string_number_conversions.h"
18#include "base/string_split.h"
[email protected]8f42b4d2012-03-24 14:12:3319#include "base/string_util.h"
[email protected]1657e6d2012-03-30 20:28:0020#include "base/rand_util.h"
[email protected]a0a69bf2011-09-23 21:40:2821#include "base/stringprintf.h"
[email protected]be1ce6a72010-08-03 14:35:2222#include "base/utf_string_conversions.h"
[email protected]1e67c2b2011-03-04 01:17:3723#include "base/win/windows_version.h"
[email protected]a82af392012-02-24 04:40:2024#include "build/build_config.h"
[email protected]8f42b4d2012-03-24 14:12:3325#include "chrome/browser/extensions/extension_info_map.h"
26#include "chrome/browser/renderer_host/chrome_render_message_filter.h"
[email protected]31a665e72012-03-11 12:37:4627#include "chrome/common/chrome_constants.h"
[email protected]338466a82011-05-03 04:27:4328#include "chrome/common/chrome_paths.h"
[email protected]d032f492009-09-29 00:33:4629#include "chrome/common/chrome_switches.h"
[email protected]1657e6d2012-03-30 20:28:0030#include "chrome/common/chrome_version_info.h"
[email protected]d032f492009-09-29 00:33:4631#include "chrome/common/logging_chrome.h"
[email protected]103607e2010-02-01 18:57:0932#include "chrome/common/nacl_cmd_line.h"
[email protected]d032f492009-09-29 00:33:4633#include "chrome/common/nacl_messages.h"
[email protected]fb1277e82009-11-21 20:32:3034#include "chrome/common/render_messages.h"
[email protected]8f42b4d2012-03-24 14:12:3335#include "chrome/common/url_constants.h"
[email protected]4967f792012-01-20 22:14:4036#include "content/public/browser/browser_child_process_host.h"
37#include "content/public/browser/child_process_data.h"
[email protected]4734d0b2011-12-03 07:10:4438#include "content/public/common/child_process_host.h"
[email protected]d032f492009-09-29 00:33:4639#include "ipc/ipc_switches.h"
[email protected]1d8a3d1f2011-02-19 07:11:5240#include "native_client/src/shared/imc/nacl_imc.h"
[email protected]87f35592012-04-08 00:49:1641#include "net/base/net_util.h"
[email protected]d032f492009-09-29 00:33:4642
[email protected]d032f492009-09-29 00:33:4643#if defined(OS_POSIX)
[email protected]a82af392012-02-24 04:40:2044#include <fcntl.h>
45
[email protected]d032f492009-09-29 00:33:4646#include "ipc/ipc_channel_posix.h"
[email protected]4bdde602010-06-16 03:17:3547#elif defined(OS_WIN)
[email protected]a82af392012-02-24 04:40:2048#include <windows.h>
49
[email protected]b39c6d92012-01-31 16:38:4150#include "base/threading/thread.h"
51#include "base/process_util.h"
[email protected]4bdde602010-06-16 03:17:3552#include "chrome/browser/nacl_host/nacl_broker_service_win.h"
[email protected]e4f6eb0232012-04-17 00:47:5053#include "content/public/common/sandbox_init.h"
[email protected]b39c6d92012-01-31 16:38:4154#include "native_client/src/trusted/service_runtime/win/debug_exception_handler.h"
[email protected]d032f492009-09-29 00:33:4655#endif
56
[email protected]631bb742011-11-02 11:29:3957using content::BrowserThread;
[email protected]4967f792012-01-20 22:14:4058using content::ChildProcessData;
[email protected]4734d0b2011-12-03 07:10:4459using content::ChildProcessHost;
[email protected]631bb742011-11-02 11:29:3960
[email protected]646e15552012-04-06 22:01:0461namespace {
62
63#if defined(OS_WIN)
64bool RunningOnWOW64() {
65 return (base::win::OSInfo::GetInstance()->wow64_status() ==
66 base::win::OSInfo::WOW64_ENABLED);
67}
68#endif
69
70// Determine the name of the IRT file based on the architecture.
71#define NACL_IRT_FILE_NAME(arch_string) \
72 (FILE_PATH_LITERAL("nacl_irt_") \
73 FILE_PATH_LITERAL(arch_string) \
74 FILE_PATH_LITERAL(".nexe"))
75
76const FilePath::StringType NaClIrtName() {
77#if defined(ARCH_CPU_X86_FAMILY)
78#if defined(ARCH_CPU_X86_64)
79 bool is64 = true;
80#elif defined(OS_WIN)
81 bool is64 = RunningOnWOW64();
82#else
83 bool is64 = false;
84#endif
85 return is64 ? NACL_IRT_FILE_NAME("x86_64") : NACL_IRT_FILE_NAME("x86_32");
86#elif defined(ARCH_CPU_ARMEL)
87 // TODO(mcgrathr): Eventually we'll need to distinguish arm32 vs thumb2.
88 // That may need to be based on the actual nexe rather than a static
89 // choice, which would require substantial refactoring.
90 return NACL_IRT_FILE_NAME("arm");
91#else
92#error Add support for your architecture to NaCl IRT file selection
93#endif
94}
95
96void SetCloseOnExec(nacl::Handle fd) {
97#if defined(OS_POSIX)
98 int flags = fcntl(fd, F_GETFD);
99 CHECK_NE(flags, -1);
100 int rc = fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
101 CHECK_EQ(rc, 0);
102#endif
103}
104
[email protected]00d99542012-04-17 22:48:02105bool ShareHandleToSelLdr(
[email protected]646e15552012-04-06 22:01:04106 base::ProcessHandle processh,
107 nacl::Handle sourceh,
108 bool close_source,
109 std::vector<nacl::FileDescriptor> *handles_for_sel_ldr) {
110#if defined(OS_WIN)
111 HANDLE channel;
112 int flags = DUPLICATE_SAME_ACCESS;
113 if (close_source)
114 flags |= DUPLICATE_CLOSE_SOURCE;
115 if (!DuplicateHandle(GetCurrentProcess(),
116 reinterpret_cast<HANDLE>(sourceh),
117 processh,
118 &channel,
119 0, // Unused given DUPLICATE_SAME_ACCESS.
120 FALSE,
121 flags)) {
[email protected]09afc2e2012-04-10 17:29:03122 DLOG(ERROR) << "DuplicateHandle() failed";
[email protected]646e15552012-04-06 22:01:04123 return false;
124 }
125 handles_for_sel_ldr->push_back(
126 reinterpret_cast<nacl::FileDescriptor>(channel));
127#else
128 nacl::FileDescriptor channel;
129 channel.fd = sourceh;
130 channel.auto_close = close_source;
131 handles_for_sel_ldr->push_back(channel);
132#endif
133 return true;
134}
135
136// NaClBrowser -----------------------------------------------------------------
137
138// Represents shared state for all NaClProcessHost objects in the browser.
139// Currently this just handles holding onto the file descriptor for the IRT.
140class NaClBrowser {
141 public:
142 static NaClBrowser* GetInstance() {
143 return Singleton<NaClBrowser>::get();
144 }
145
146 bool IrtAvailable() const {
147 return irt_platform_file_ != base::kInvalidPlatformFileValue;
148 }
149
150 base::PlatformFile IrtFile() const {
151 CHECK_NE(irt_platform_file_, base::kInvalidPlatformFileValue);
152 return irt_platform_file_;
153 }
154
155 // Asynchronously attempt to get the IRT open.
156 bool EnsureIrtAvailable();
157
158 // Make sure the IRT gets opened and follow up with the reply when it's ready.
159 bool MakeIrtAvailable(const base::Closure& reply);
160
161 // Path to IRT. Available even before IRT is loaded.
162 const FilePath& GetIrtFilePath();
163
164 // Get the key used for HMACing validation signatures. This should be a
165 // string of cryptographically secure random bytes.
166 const std::string& GetValidatorCacheKey() const {
167 return validator_cache_key_;
168 }
169
170 // Is the validation signature in the database?
171 bool QueryKnownToValidate(const std::string& signature);
172
173 // Put the validation signature in the database.
174 void SetKnownToValidate(const std::string& signature);
175
176 private:
177 friend struct DefaultSingletonTraits<NaClBrowser>;
178
179 NaClBrowser()
180 : irt_platform_file_(base::kInvalidPlatformFileValue),
181 irt_filepath_(),
182 // For the moment, choose an arbitrary cache size.
183 validation_cache_(200),
184 // TODO(ncbray) persist this key along with the cache.
185 // Key size is equal to the block size (not the digest size) of SHA256.
186 validator_cache_key_(base::RandBytesAsString(64)) {
187 InitIrtFilePath();
188 }
189
190 ~NaClBrowser() {
191 if (irt_platform_file_ != base::kInvalidPlatformFileValue)
192 base::ClosePlatformFile(irt_platform_file_);
193 }
194
195 void InitIrtFilePath();
196
197 void OpenIrtLibraryFile();
198
199 static void DoOpenIrtLibraryFile() {
200 GetInstance()->OpenIrtLibraryFile();
201 }
202
203 base::PlatformFile irt_platform_file_;
204
205 FilePath irt_filepath_;
206
207 typedef base::HashingMRUCache<std::string, bool> ValidationCacheType;
208 ValidationCacheType validation_cache_;
209
210 std::string validator_cache_key_;
211
212 DISALLOW_COPY_AND_ASSIGN(NaClBrowser);
213};
214
215// Attempt to ensure the IRT will be available when we need it, but don't wait.
216bool NaClBrowser::EnsureIrtAvailable() {
217 if (IrtAvailable())
218 return true;
219
220 return BrowserThread::PostTask(
221 BrowserThread::FILE, FROM_HERE,
222 base::Bind(&NaClBrowser::DoOpenIrtLibraryFile));
223}
224
225// We really need the IRT to be available now, so make sure that it is.
226// When it's ready, we'll run the reply closure.
227bool NaClBrowser::MakeIrtAvailable(const base::Closure& reply) {
228 return BrowserThread::PostTaskAndReply(
229 BrowserThread::FILE, FROM_HERE,
230 base::Bind(&NaClBrowser::DoOpenIrtLibraryFile), reply);
231}
232
233const FilePath& NaClBrowser::GetIrtFilePath() {
234 return irt_filepath_;
235}
236
237bool NaClBrowser::QueryKnownToValidate(const std::string& signature) {
238 bool result = false;
239 ValidationCacheType::iterator iter = validation_cache_.Get(signature);
240 if (iter != validation_cache_.end()) {
241 result = iter->second;
242 }
243 UMA_HISTOGRAM_ENUMERATION("NaCl.ValidationCache.Query",
244 result ? 1 : 0, 2);
245 return result;
246}
247
248void NaClBrowser::SetKnownToValidate(const std::string& signature) {
249 validation_cache_.Put(signature, true);
250 // The number of sets should be equal to the number of cache misses, minus
251 // validation failures and successful validations where stubout occurs.
252 // Bucket zero is reserved for future use.
253 UMA_HISTOGRAM_ENUMERATION("NaCl.ValidationCache.Set", 1, 2);
254}
255
256void NaClBrowser::InitIrtFilePath() {
257 // Allow the IRT library to be overridden via an environment
258 // variable. This allows the NaCl/Chromium integration bot to
259 // specify a newly-built IRT rather than using a prebuilt one
260 // downloaded via Chromium's DEPS file. We use the same environment
261 // variable that the standalone NaCl PPAPI plugin accepts.
262 const char* irt_path_var = getenv("NACL_IRT_LIBRARY");
263 if (irt_path_var != NULL) {
264 FilePath::StringType path_string(
265 irt_path_var, const_cast<const char*>(strchr(irt_path_var, '\0')));
266 irt_filepath_ = FilePath(path_string);
267 } else {
268 FilePath plugin_dir;
269 if (!PathService::Get(chrome::DIR_INTERNAL_PLUGINS, &plugin_dir)) {
[email protected]09afc2e2012-04-10 17:29:03270 DLOG(ERROR) << "Failed to locate the plugins directory";
[email protected]646e15552012-04-06 22:01:04271 return;
272 }
273
274 irt_filepath_ = plugin_dir.Append(NaClIrtName());
275 }
276}
277
278// This only ever runs on the BrowserThread::FILE thread.
279// If multiple tasks are posted, the later ones are no-ops.
280void NaClBrowser::OpenIrtLibraryFile() {
281 if (irt_platform_file_ != base::kInvalidPlatformFileValue)
282 // We've already run.
283 return;
284
285 base::PlatformFileError error_code;
286 irt_platform_file_ = base::CreatePlatformFile(irt_filepath_,
287 base::PLATFORM_FILE_OPEN |
288 base::PLATFORM_FILE_READ,
289 NULL,
290 &error_code);
291 if (error_code != base::PLATFORM_FILE_OK) {
292 LOG(ERROR) << "Failed to open NaCl IRT file \""
293 << irt_filepath_.LossyDisplayName()
294 << "\": " << error_code;
295 }
296}
297
298} // namespace
299
300// DebugContext ----------------------------------------------------------------
301
[email protected]b39c6d92012-01-31 16:38:41302#if defined(OS_WIN)
303class NaClProcessHost::DebugContext
304 : public base::RefCountedThreadSafe<NaClProcessHost::DebugContext> {
305 public:
306 DebugContext()
[email protected]8236f852012-04-05 10:24:31307 : can_send_start_msg_(false) {
[email protected]b39c6d92012-01-31 16:38:41308 }
309
310 ~DebugContext() {
311 }
312
313 void AttachDebugger(int pid, base::ProcessHandle process);
314
315 // 6 methods below must be called on Browser::IO thread.
316 void SetStartMessage(IPC::Message* start_msg);
[email protected]8236f852012-04-05 10:24:31317 void SetNaClProcessHost(base::WeakPtr<NaClProcessHost> nacl_process_host);
[email protected]b39c6d92012-01-31 16:38:41318 void SetDebugThread(base::Thread* thread_);
319
320 // Start message is sent from 2 flows of execution. The first flow is
321 // NaClProcessHost::SendStart. The second flow is
322 // NaClProcessHost::OnChannelConnected and
323 // NaClProcessHost::DebugContext::AttachThread. The message itself is created
324 // by first flow. But the moment it can be sent is determined by second flow.
325 // So first flow executes SetStartMessage and SendStartMessage while second
326 // flow uses AllowAndSendStartMessage to either send potentially pending
327 // start message or set the flag that allows the first flow to do this.
328
329 // Clears the flag that prevents sending start message.
330 void AllowToSendStartMsg();
331 // Send start message to the NaCl process or do nothing if message is not
332 // set or not allowed to be send. If message is sent, it is cleared and
333 // repeated calls do nothing.
334 void SendStartMessage();
335 // Clear the flag that prevents further sending start message and send start
336 // message if it is set.
337 void AllowAndSendStartMessage();
338 private:
339 void StopThread();
340 // These 4 fields are accessed only from Browser::IO thread.
341 scoped_ptr<base::Thread> thread_;
342 scoped_ptr<IPC::Message> start_msg_;
343 // Debugger is attached or exception handling is not switched on.
344 // This means that start message can be sent to the NaCl process.
345 bool can_send_start_msg_;
[email protected]8236f852012-04-05 10:24:31346 base::WeakPtr<NaClProcessHost> nacl_process_host_;
[email protected]b39c6d92012-01-31 16:38:41347};
348
349void NaClProcessHost::DebugContext::AttachDebugger(
350 int pid, base::ProcessHandle process) {
351 BOOL attached;
352 DWORD exit_code;
353 attached = DebugActiveProcess(pid);
354 if (!attached) {
[email protected]09afc2e2012-04-10 17:29:03355 DLOG(ERROR) << "Failed to connect to the process";
[email protected]b39c6d92012-01-31 16:38:41356 }
357 BrowserThread::PostTask(
358 BrowserThread::IO, FROM_HERE,
359 base::Bind(
360 &NaClProcessHost::DebugContext::AllowAndSendStartMessage, this));
361 if (attached) {
362 // debug the process
363 NaClDebugLoop(process, &exit_code);
364 base::CloseProcessHandle(process);
365 }
366 BrowserThread::PostTask(
367 BrowserThread::IO, FROM_HERE,
368 base::Bind(&NaClProcessHost::DebugContext::StopThread, this));
369}
370
371void NaClProcessHost::DebugContext::SetStartMessage(IPC::Message* start_msg) {
372 start_msg_.reset(start_msg);
373}
374
[email protected]8236f852012-04-05 10:24:31375void NaClProcessHost::DebugContext::SetNaClProcessHost(
376 base::WeakPtr<NaClProcessHost> nacl_process_host) {
377 nacl_process_host_ = nacl_process_host;
[email protected]b39c6d92012-01-31 16:38:41378}
379
380void NaClProcessHost::DebugContext::SetDebugThread(base::Thread* thread) {
381 thread_.reset(thread);
382}
383
384void NaClProcessHost::DebugContext::AllowToSendStartMsg() {
385 can_send_start_msg_ = true;
386}
387
388void NaClProcessHost::DebugContext::SendStartMessage() {
389 if (start_msg_.get() && can_send_start_msg_) {
[email protected]8236f852012-04-05 10:24:31390 if (nacl_process_host_) {
391 if (!nacl_process_host_->Send(start_msg_.release())) {
[email protected]09afc2e2012-04-10 17:29:03392 DLOG(ERROR) << "Failed to send start message";
[email protected]b39c6d92012-01-31 16:38:41393 }
394 }
395 }
396}
397
398void NaClProcessHost::DebugContext::AllowAndSendStartMessage() {
399 AllowToSendStartMsg();
400 SendStartMessage();
401}
402
403void NaClProcessHost::DebugContext::StopThread() {
404 thread_->Stop();
405 thread_.reset();
406}
407#endif
408
[email protected]1d8a3d1f2011-02-19 07:11:52409struct NaClProcessHost::NaClInternal {
410 std::vector<nacl::Handle> sockets_for_renderer;
411 std::vector<nacl::Handle> sockets_for_sel_ldr;
412};
413
[email protected]646e15552012-04-06 22:01:04414// -----------------------------------------------------------------------------
[email protected]773ebb92011-11-15 19:06:52415
[email protected]87f35592012-04-08 00:49:16416NaClProcessHost::NaClProcessHost(const GURL& manifest_url)
417 : manifest_url_(manifest_url),
[email protected]a575da52012-03-22 13:08:36418#if defined(OS_WIN)
419 process_launched_by_broker_(false),
[email protected]5b974952012-04-05 18:18:23420#elif defined(OS_LINUX)
421 wait_for_nacl_gdb_(false),
[email protected]a575da52012-03-22 13:08:36422#endif
423 reply_msg_(NULL),
[email protected]1d8a3d1f2011-02-19 07:11:52424 internal_(new NaClInternal()),
[email protected]5ca93be2012-03-21 20:04:06425 ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)),
426 enable_exception_handling_(false) {
[email protected]4967f792012-01-20 22:14:40427 process_.reset(content::BrowserChildProcessHost::Create(
428 content::PROCESS_TYPE_NACL_LOADER, this));
[email protected]87f35592012-04-08 00:49:16429
430 // Set the display name so the user knows what plugin the process is running.
431 // We aren't on the UI thread so getting the pref locale for language
432 // formatting isn't possible, so IDN will be lost, but this is probably OK
433 // for this use case.
434 process_->SetName(net::FormatUrl(manifest_url_, std::string()));
[email protected]5ca93be2012-03-21 20:04:06435
436 // We allow untrusted hardware exception handling to be enabled via
437 // an env var for consistency with the standalone build of NaCl.
438 if (CommandLine::ForCurrentProcess()->HasSwitch(
439 switches::kEnableNaClExceptionHandling) ||
440 getenv("NACL_UNTRUSTED_EXCEPTION_HANDLING") != NULL) {
441 enable_exception_handling_ = true;
[email protected]b39c6d92012-01-31 16:38:41442#if defined(OS_WIN)
[email protected]fb335fe2012-03-24 18:11:38443 debug_context_ = new DebugContext();
[email protected]b39c6d92012-01-31 16:38:41444#endif
[email protected]5ca93be2012-03-21 20:04:06445 }
[email protected]d032f492009-09-29 00:33:46446}
447
[email protected]fb1277e82009-11-21 20:32:30448NaClProcessHost::~NaClProcessHost() {
[email protected]4cb43102011-12-02 20:24:49449 int exit_code;
[email protected]4967f792012-01-20 22:14:40450 process_->GetTerminationStatus(&exit_code);
[email protected]4cb43102011-12-02 20:24:49451 std::string message =
452 base::StringPrintf("NaCl process exited with status %i (0x%x)",
453 exit_code, exit_code);
454 if (exit_code == 0) {
455 LOG(INFO) << message;
456 } else {
457 LOG(ERROR) << message;
458 }
459
[email protected]1d8a3d1f2011-02-19 07:11:52460 for (size_t i = 0; i < internal_->sockets_for_renderer.size(); i++) {
[email protected]909c2402011-05-09 11:39:04461 if (nacl::Close(internal_->sockets_for_renderer[i]) != 0) {
[email protected]09afc2e2012-04-10 17:29:03462 NOTREACHED() << "nacl::Close() failed";
[email protected]909c2402011-05-09 11:39:04463 }
[email protected]c47ec402010-07-29 10:20:49464 }
[email protected]1d8a3d1f2011-02-19 07:11:52465 for (size_t i = 0; i < internal_->sockets_for_sel_ldr.size(); i++) {
[email protected]909c2402011-05-09 11:39:04466 if (nacl::Close(internal_->sockets_for_sel_ldr[i]) != 0) {
[email protected]09afc2e2012-04-10 17:29:03467 NOTREACHED() << "nacl::Close() failed";
[email protected]909c2402011-05-09 11:39:04468 }
[email protected]c47ec402010-07-29 10:20:49469 }
470
[email protected]909c2402011-05-09 11:39:04471 if (reply_msg_) {
472 // The process failed to launch for some reason.
473 // Don't keep the renderer hanging.
474 reply_msg_->set_reply_error();
475 chrome_render_message_filter_->Send(reply_msg_);
476 }
[email protected]b39c6d92012-01-31 16:38:41477#if defined(OS_WIN)
[email protected]a575da52012-03-22 13:08:36478 if (process_launched_by_broker_) {
479 NaClBrokerService::GetInstance()->OnLoaderDied();
[email protected]5ca93be2012-03-21 20:04:06480 }
[email protected]b39c6d92012-01-31 16:38:41481#endif
[email protected]fb1277e82009-11-21 20:32:30482}
483
[email protected]773ebb92011-11-15 19:06:52484// This is called at browser startup.
485// static
486void NaClProcessHost::EarlyStartup() {
487#if defined(OS_LINUX) && !defined(OS_CHROMEOS)
488 // Open the IRT file early to make sure that it isn't replaced out from
489 // under us by autoupdate.
490 NaClBrowser::GetInstance()->EnsureIrtAvailable();
491#endif
492}
493
[email protected]a575da52012-03-22 13:08:36494void NaClProcessHost::Launch(
[email protected]92d56412011-03-24 20:53:52495 ChromeRenderMessageFilter* chrome_render_message_filter,
496 int socket_count,
[email protected]8f42b4d2012-03-24 14:12:33497 IPC::Message* reply_msg,
498 scoped_refptr<ExtensionInfoMap> extension_info_map) {
[email protected]a575da52012-03-22 13:08:36499 chrome_render_message_filter_ = chrome_render_message_filter;
500 reply_msg_ = reply_msg;
[email protected]8f42b4d2012-03-24 14:12:33501 extension_info_map_ = extension_info_map;
[email protected]a575da52012-03-22 13:08:36502
[email protected]c47ec402010-07-29 10:20:49503 // Place an arbitrary limit on the number of sockets to limit
504 // exposure in case the renderer is compromised. We can increase
505 // this if necessary.
506 if (socket_count > 8) {
[email protected]a575da52012-03-22 13:08:36507 delete this;
508 return;
[email protected]c47ec402010-07-29 10:20:49509 }
510
[email protected]773ebb92011-11-15 19:06:52511 // Start getting the IRT open asynchronously while we launch the NaCl process.
[email protected]09afc2e2012-04-10 17:29:03512 // We'll make sure this actually finished in StartWithLaunchedProcess, below.
[email protected]773ebb92011-11-15 19:06:52513 if (!NaClBrowser::GetInstance()->EnsureIrtAvailable()) {
[email protected]09afc2e2012-04-10 17:29:03514 DLOG(ERROR) << "Cannot launch NaCl process after IRT file open failed";
[email protected]a575da52012-03-22 13:08:36515 delete this;
516 return;
[email protected]773ebb92011-11-15 19:06:52517 }
518
[email protected]c47ec402010-07-29 10:20:49519 // Rather than creating a socket pair in the renderer, and passing
520 // one side through the browser to sel_ldr, socket pairs are created
521 // in the browser and then passed to the renderer and sel_ldr.
522 //
523 // This is mainly for the benefit of Windows, where sockets cannot
524 // be passed in messages, but are copied via DuplicateHandle().
525 // This means the sandboxed renderer cannot send handles to the
526 // browser process.
527
528 for (int i = 0; i < socket_count; i++) {
529 nacl::Handle pair[2];
530 // Create a connected socket
[email protected]a575da52012-03-22 13:08:36531 if (nacl::SocketPair(pair) == -1) {
532 delete this;
533 return;
534 }
[email protected]1d8a3d1f2011-02-19 07:11:52535 internal_->sockets_for_renderer.push_back(pair[0]);
536 internal_->sockets_for_sel_ldr.push_back(pair[1]);
[email protected]c47ec402010-07-29 10:20:49537 SetCloseOnExec(pair[0]);
538 SetCloseOnExec(pair[1]);
539 }
[email protected]d032f492009-09-29 00:33:46540
541 // Launch the process
[email protected]fb1277e82009-11-21 20:32:30542 if (!LaunchSelLdr()) {
[email protected]a575da52012-03-22 13:08:36543 delete this;
[email protected]d032f492009-09-29 00:33:46544 }
[email protected]d032f492009-09-29 00:33:46545}
[email protected]646e15552012-04-06 22:01:04546
[email protected]5b974952012-04-05 18:18:23547#if defined(OS_WIN)
[email protected]646e15552012-04-06 22:01:04548void NaClProcessHost::OnChannelConnected(int32 peer_pid) {
549 // Set process handle, if it was not set previously.
550 // This is needed when NaCl process is launched with nacl-gdb.
551 if (process_->GetData().handle == base::kNullProcessHandle) {
552 base::ProcessHandle process;
553 DCHECK(!CommandLine::ForCurrentProcess()->GetSwitchValuePath(
554 switches::kNaClGdb).empty());
555 if (base::OpenProcessHandleWithAccess(
556 peer_pid,
557 base::kProcessAccessDuplicateHandle |
558 base::kProcessAccessQueryInformation |
559 base::kProcessAccessWaitForTermination,
560 &process)) {
561 process_->SetHandle(process);
[email protected]09afc2e2012-04-10 17:29:03562 if (!StartWithLaunchedProcess()) {
563 delete this;
564 return;
565 }
[email protected]646e15552012-04-06 22:01:04566 } else {
[email protected]09afc2e2012-04-10 17:29:03567 DLOG(ERROR) << "Failed to get process handle";
[email protected]646e15552012-04-06 22:01:04568 }
569 }
570 if (debug_context_ == NULL) {
571 return;
572 }
573 debug_context_->SetNaClProcessHost(weak_factory_.GetWeakPtr());
574 if (RunningOnWOW64()) {
575 if (!NaClBrokerService::GetInstance()->LaunchDebugExceptionHandler(
576 this, peer_pid)) {
577 debug_context_->AllowAndSendStartMessage();
578 }
579 } else {
580 // Start new thread for debug loop
581 // We can't use process_->GetData().handle because it doesn't have necessary
582 // access rights.
583 base::ProcessHandle process;
584 if (!base::OpenProcessHandleWithAccess(
585 peer_pid,
586 base::kProcessAccessQueryInformation |
587 base::kProcessAccessSuspendResume |
588 base::kProcessAccessTerminate |
589 base::kProcessAccessVMOperation |
590 base::kProcessAccessVMRead |
591 base::kProcessAccessVMWrite |
592 base::kProcessAccessWaitForTermination,
593 &process)) {
[email protected]09afc2e2012-04-10 17:29:03594 DLOG(ERROR) << "Failed to open the process";
[email protected]646e15552012-04-06 22:01:04595 debug_context_->AllowAndSendStartMessage();
596 return;
597 }
598 base::Thread* dbg_thread = new base::Thread("Debug thread");
599 if (!dbg_thread->Start()) {
[email protected]09afc2e2012-04-10 17:29:03600 DLOG(ERROR) << "Debug thread not started";
[email protected]646e15552012-04-06 22:01:04601 debug_context_->AllowAndSendStartMessage();
602 base::CloseProcessHandle(process);
603 return;
604 }
605 debug_context_->SetDebugThread(dbg_thread);
606 // System can not reallocate pid until we close process handle. So using
607 // pid in different thread is fine.
608 dbg_thread->message_loop()->PostTask(FROM_HERE,
609 base::Bind(&NaClProcessHost::DebugContext::AttachDebugger,
610 debug_context_, peer_pid, process));
611 }
612}
613#else
614void NaClProcessHost::OnChannelConnected(int32 peer_pid) {
615}
616#endif
617
618#if defined(OS_WIN)
619void NaClProcessHost::OnProcessLaunchedByBroker(base::ProcessHandle handle) {
620 process_launched_by_broker_ = true;
621 process_->SetHandle(handle);
[email protected]09afc2e2012-04-10 17:29:03622 if (!StartWithLaunchedProcess())
623 delete this;
[email protected]646e15552012-04-06 22:01:04624}
625
626void NaClProcessHost::OnDebugExceptionHandlerLaunchedByBroker() {
627 debug_context_->AllowAndSendStartMessage();
628}
629#endif
630
631// Needed to handle sync messages in OnMessageRecieved.
632bool NaClProcessHost::Send(IPC::Message* msg) {
633 return process_->Send(msg);
634}
635
636#if defined(OS_WIN)
637scoped_ptr<CommandLine> NaClProcessHost::GetCommandForLaunchWithGdb(
[email protected]8f42b4d2012-03-24 14:12:33638 const FilePath& nacl_gdb,
[email protected]5b974952012-04-05 18:18:23639 CommandLine* line) {
[email protected]31a665e72012-03-11 12:37:46640 CommandLine* cmd_line = new CommandLine(nacl_gdb);
641 // We can't use PrependWrapper because our parameters contain spaces.
642 cmd_line->AppendArg("--eval-command");
643 const FilePath::StringType& irt_path =
644 NaClBrowser::GetInstance()->GetIrtFilePath().value();
645 cmd_line->AppendArgNative(FILE_PATH_LITERAL("nacl-irt ") + irt_path);
[email protected]5b974952012-04-05 18:18:23646 FilePath manifest_path = GetManifestPath();
[email protected]8f42b4d2012-03-24 14:12:33647 if (!manifest_path.empty()) {
648 cmd_line->AppendArg("--eval-command");
649 cmd_line->AppendArgNative(FILE_PATH_LITERAL("nacl-manifest ") +
650 manifest_path.value());
651 }
[email protected]31a665e72012-03-11 12:37:46652 cmd_line->AppendArg("--args");
653 const CommandLine::StringVector& argv = line->argv();
654 for (size_t i = 0; i < argv.size(); i++) {
655 cmd_line->AppendArgNative(argv[i]);
656 }
657 return scoped_ptr<CommandLine>(cmd_line);
658}
[email protected]5b974952012-04-05 18:18:23659#elif defined(OS_LINUX)
660namespace {
661class NaClGdbWatchDelegate : public MessageLoopForIO::Watcher {
662 public:
663 // fd_write_ is used by nacl-gdb via /proc/browser_PID/fd/fd_write_
664 NaClGdbWatchDelegate(int fd_read, int fd_write,
665 const base::Closure& reply)
666 : fd_read_(fd_read),
667 fd_write_(fd_write),
668 reply_(reply) {}
669
670 ~NaClGdbWatchDelegate() {
671 if (HANDLE_EINTR(close(fd_read_)) != 0)
672 DLOG(ERROR) << "close(fd_read_) failed";
673 if (HANDLE_EINTR(close(fd_write_)) != 0)
674 DLOG(ERROR) << "close(fd_write_) failed";
675 }
676
677 virtual void OnFileCanReadWithoutBlocking(int fd) OVERRIDE;
678 virtual void OnFileCanWriteWithoutBlocking(int fd) OVERRIDE {}
679
680 private:
681 int fd_read_;
682 int fd_write_;
683 base::Closure reply_;
684};
685
686void NaClGdbWatchDelegate::OnFileCanReadWithoutBlocking(int fd) {
687 char buf;
688 if (HANDLE_EINTR(read(fd_read_, &buf, 1)) != 1 || buf != '\0')
689 LOG(ERROR) << "Failed to sync with nacl-gdb";
690 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, reply_);
691}
692} // namespace
693
694bool NaClProcessHost::LaunchNaClGdb(base::ProcessId pid) {
695 CommandLine::StringType nacl_gdb =
696 CommandLine::ForCurrentProcess()->GetSwitchValueNative(
697 switches::kNaClGdb);
698 CommandLine::StringVector argv;
699 // We don't support spaces inside arguments in --nacl-gdb switch.
700 base::SplitString(nacl_gdb, static_cast<CommandLine::CharType>(' '), &argv);
701 CommandLine cmd_line(argv);
702 cmd_line.AppendArg("--eval-command");
703 const FilePath::StringType& irt_path =
704 NaClBrowser::GetInstance()->GetIrtFilePath().value();
705 cmd_line.AppendArgNative(FILE_PATH_LITERAL("nacl-irt ") + irt_path);
706 FilePath manifest_path = GetManifestPath();
707 if (!manifest_path.empty()) {
708 cmd_line.AppendArg("--eval-command");
709 cmd_line.AppendArgNative(FILE_PATH_LITERAL("nacl-manifest ") +
710 manifest_path.value());
711 }
712 cmd_line.AppendArg("--eval-command");
713 cmd_line.AppendArg("attach " + base::IntToString(pid));
714 int fds[2];
715 if (pipe(fds) != 0)
716 return false;
717 // Tell the debugger to send a byte to the writable end of the pipe.
718 // We use a file descriptor in our process because the debugger will be
719 // typically launched in a separate terminal, and a lot of terminals close all
720 // file descriptors before launching external programs.
721 cmd_line.AppendArg("--eval-command");
722 cmd_line.AppendArg("dump binary value /proc/" +
723 base::IntToString(base::GetCurrentProcId()) +
724 "/fd/" + base::IntToString(fds[1]) + " (char)0");
725 // wait on fds[0]
726 // If the debugger crashes before attaching to the NaCl process, the user can
727 // release resources by terminating the NaCl loader in Chrome Task Manager.
728 nacl_gdb_watcher_delegate_.reset(
729 new NaClGdbWatchDelegate(
730 fds[0], fds[1],
731 base::Bind(&NaClProcessHost::OnNaClGdbAttached,
732 weak_factory_.GetWeakPtr())));
733 MessageLoopForIO::current()->WatchFileDescriptor(
734 fds[0],
735 true,
736 MessageLoopForIO::WATCH_READ,
737 &nacl_gdb_watcher_,
738 nacl_gdb_watcher_delegate_.get());
739 return base::LaunchProcess(cmd_line, base::LaunchOptions(), NULL);
740}
741
742void NaClProcessHost::OnNaClGdbAttached() {
743 wait_for_nacl_gdb_ = false;
744 nacl_gdb_watcher_.StopWatchingFileDescriptor();
745 nacl_gdb_watcher_delegate_.reset();
746 OnProcessLaunched();
747}
748#endif
749
750FilePath NaClProcessHost::GetManifestPath() {
[email protected]5b974952012-04-05 18:18:23751 const Extension* extension = extension_info_map_->extensions()
[email protected]87f35592012-04-08 00:49:16752 .GetExtensionOrAppByURL(ExtensionURLInfo(manifest_url_));
753 if (extension != NULL && manifest_url_.SchemeIs(chrome::kExtensionScheme)) {
754 std::string path = manifest_url_.path();
[email protected]5b974952012-04-05 18:18:23755 TrimString(path, "/", &path); // Remove first slash
756 return extension->path().AppendASCII(path);
757 }
758 return FilePath();
759}
[email protected]31a665e72012-03-11 12:37:46760
[email protected]fb1277e82009-11-21 20:32:30761bool NaClProcessHost::LaunchSelLdr() {
[email protected]4967f792012-01-20 22:14:40762 std::string channel_id = process_->GetHost()->CreateChannel();
[email protected]4734d0b2011-12-03 07:10:44763 if (channel_id.empty())
[email protected]d032f492009-09-29 00:33:46764 return false;
765
[email protected]e3fc75a2011-05-05 08:20:42766 CommandLine::StringType nacl_loader_prefix;
767#if defined(OS_POSIX)
768 nacl_loader_prefix = CommandLine::ForCurrentProcess()->GetSwitchValueNative(
769 switches::kNaClLoaderCmdPrefix);
770#endif // defined(OS_POSIX)
771
[email protected]d032f492009-09-29 00:33:46772 // Build command line for nacl.
[email protected]8c40f322011-08-24 03:33:36773
774#if defined(OS_MACOSX)
775 // The Native Client process needs to be able to allocate a 1GB contiguous
776 // region to use as the client environment's virtual address space. ASLR
777 // (PIE) interferes with this by making it possible that no gap large enough
778 // to accomodate this request will exist in the child process' address
779 // space. Disable PIE for NaCl processes. See http://crbug.com/90221 and
780 // http://code.google.com/p/nativeclient/issues/detail?id=2043.
[email protected]4cb43102011-12-02 20:24:49781 int flags = ChildProcessHost::CHILD_NO_PIE;
[email protected]8c40f322011-08-24 03:33:36782#elif defined(OS_LINUX)
[email protected]4cb43102011-12-02 20:24:49783 int flags = nacl_loader_prefix.empty() ? ChildProcessHost::CHILD_ALLOW_SELF :
784 ChildProcessHost::CHILD_NORMAL;
[email protected]8c40f322011-08-24 03:33:36785#else
[email protected]4cb43102011-12-02 20:24:49786 int flags = ChildProcessHost::CHILD_NORMAL;
[email protected]8c40f322011-08-24 03:33:36787#endif
788
[email protected]4cb43102011-12-02 20:24:49789 FilePath exe_path = ChildProcessHost::GetChildPath(flags);
[email protected]fb1277e82009-11-21 20:32:30790 if (exe_path.empty())
[email protected]d032f492009-09-29 00:33:46791 return false;
792
[email protected]31a665e72012-03-11 12:37:46793#if defined(OS_WIN)
794 // On Windows 64-bit NaCl loader is called nacl64.exe instead of chrome.exe
795 if (RunningOnWOW64()) {
796 FilePath module_path;
797 if (!PathService::Get(base::FILE_MODULE, &module_path))
798 return false;
799 exe_path = module_path.DirName().Append(chrome::kNaClAppName);
800 }
801#endif
802
[email protected]33a05af2012-03-02 18:15:51803 scoped_ptr<CommandLine> cmd_line(new CommandLine(exe_path));
804 nacl::CopyNaClCommandLineArguments(cmd_line.get());
[email protected]599e6642010-01-27 18:52:13805
[email protected]05076ba22010-07-30 05:59:57806 cmd_line->AppendSwitchASCII(switches::kProcessType,
807 switches::kNaClLoaderProcess);
[email protected]4734d0b2011-12-03 07:10:44808 cmd_line->AppendSwitchASCII(switches::kProcessChannelID, channel_id);
[email protected]93156cec2011-09-12 21:14:44809 if (logging::DialogsAreSuppressed())
810 cmd_line->AppendSwitch(switches::kNoErrorDialogs);
[email protected]d032f492009-09-29 00:33:46811
[email protected]e3fc75a2011-05-05 08:20:42812 if (!nacl_loader_prefix.empty())
813 cmd_line->PrependWrapper(nacl_loader_prefix);
814
[email protected]31a665e72012-03-11 12:37:46815 FilePath nacl_gdb = CommandLine::ForCurrentProcess()->GetSwitchValuePath(
816 switches::kNaClGdb);
817 if (!nacl_gdb.empty()) {
[email protected]5b974952012-04-05 18:18:23818#if defined(OS_WIN)
[email protected]31a665e72012-03-11 12:37:46819 cmd_line->AppendSwitch(switches::kNoSandbox);
820 scoped_ptr<CommandLine> gdb_cmd_line(
[email protected]646e15552012-04-06 22:01:04821 GetCommandForLaunchWithGdb(nacl_gdb, cmd_line.get()));
[email protected]31a665e72012-03-11 12:37:46822 // We can't use process_->Launch() because OnProcessLaunched will be called
823 // with process_->GetData().handle filled by handle of gdb process. This
824 // handle will be used to duplicate handles for NaCl process and as
825 // a result NaCl process will not be able to use them.
826 //
827 // So we don't fill process_->GetData().handle and wait for
828 // OnChannelConnected to get handle of NaCl process from its pid. Then we
829 // call OnProcessLaunched.
830 return base::LaunchProcess(*gdb_cmd_line, base::LaunchOptions(), NULL);
[email protected]5b974952012-04-05 18:18:23831#elif defined(OS_LINUX)
832 wait_for_nacl_gdb_ = true;
833#endif
[email protected]31a665e72012-03-11 12:37:46834 }
835
[email protected]103607e2010-02-01 18:57:09836 // On Windows we might need to start the broker process to launch a new loader
[email protected]d032f492009-09-29 00:33:46837#if defined(OS_WIN)
[email protected]773ebb92011-11-15 19:06:52838 if (RunningOnWOW64()) {
[email protected]644b2e22012-03-25 01:41:07839 return NaClBrokerService::GetInstance()->LaunchLoader(this, channel_id);
[email protected]4bdde602010-06-16 03:17:35840 } else {
[email protected]33a05af2012-03-02 18:15:51841 process_->Launch(FilePath(), cmd_line.release());
[email protected]4bdde602010-06-16 03:17:35842 }
[email protected]103607e2010-02-01 18:57:09843#elif defined(OS_POSIX)
[email protected]4967f792012-01-20 22:14:40844 process_->Launch(nacl_loader_prefix.empty(), // use_zygote
[email protected]a82af392012-02-24 04:40:20845 base::EnvironmentVector(),
[email protected]33a05af2012-03-02 18:15:51846 cmd_line.release());
[email protected]103607e2010-02-01 18:57:09847#endif
[email protected]d032f492009-09-29 00:33:46848
[email protected]fb1277e82009-11-21 20:32:30849 return true;
[email protected]d032f492009-09-29 00:33:46850}
851
[email protected]646e15552012-04-06 22:01:04852bool NaClProcessHost::OnMessageReceived(const IPC::Message& msg) {
853 bool handled = true;
854 IPC_BEGIN_MESSAGE_MAP(NaClProcessHost, msg)
855 IPC_MESSAGE_HANDLER(NaClProcessMsg_QueryKnownToValidate,
856 OnQueryKnownToValidate)
857 IPC_MESSAGE_HANDLER(NaClProcessMsg_SetKnownToValidate,
858 OnSetKnownToValidate)
859 IPC_MESSAGE_UNHANDLED(handled = false)
860 IPC_END_MESSAGE_MAP()
861 return handled;
[email protected]103607e2010-02-01 18:57:09862}
863
[email protected]463ea5f2011-12-03 06:57:47864void NaClProcessHost::OnProcessCrashed(int exit_code) {
865 std::string message = base::StringPrintf(
866 "NaCl process exited with status %i (0x%x)", exit_code, exit_code);
867 LOG(ERROR) << message;
[email protected]103607e2010-02-01 18:57:09868}
869
[email protected]773ebb92011-11-15 19:06:52870void NaClProcessHost::OnProcessLaunched() {
[email protected]09afc2e2012-04-10 17:29:03871 if (!StartWithLaunchedProcess())
872 delete this;
[email protected]773ebb92011-11-15 19:06:52873}
874
875// The asynchronous attempt to get the IRT file open has completed.
876void NaClProcessHost::IrtReady() {
877 NaClBrowser* nacl_browser = NaClBrowser::GetInstance();
[email protected]09afc2e2012-04-10 17:29:03878 if (!nacl_browser->IrtAvailable() || !SendStart()) {
879 DLOG(ERROR) << "Cannot launch NaCl process";
[email protected]338466a82011-05-03 04:27:43880 delete this;
881 }
882}
883
[email protected]00d99542012-04-17 22:48:02884bool NaClProcessHost::ReplyToRenderer() {
[email protected]c47ec402010-07-29 10:20:49885 std::vector<nacl::FileDescriptor> handles_for_renderer;
[email protected]1d8a3d1f2011-02-19 07:11:52886 for (size_t i = 0; i < internal_->sockets_for_renderer.size(); i++) {
[email protected]c47ec402010-07-29 10:20:49887#if defined(OS_WIN)
888 // Copy the handle into the renderer process.
889 HANDLE handle_in_renderer;
[email protected]909c2402011-05-09 11:39:04890 if (!DuplicateHandle(base::GetCurrentProcessHandle(),
891 reinterpret_cast<HANDLE>(
892 internal_->sockets_for_renderer[i]),
893 chrome_render_message_filter_->peer_handle(),
894 &handle_in_renderer,
895 0, // Unused given DUPLICATE_SAME_ACCESS.
896 FALSE,
897 DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS)) {
[email protected]09afc2e2012-04-10 17:29:03898 DLOG(ERROR) << "DuplicateHandle() failed";
899 return false;
[email protected]909c2402011-05-09 11:39:04900 }
[email protected]c47ec402010-07-29 10:20:49901 handles_for_renderer.push_back(
902 reinterpret_cast<nacl::FileDescriptor>(handle_in_renderer));
903#else
904 // No need to dup the imc_handle - we don't pass it anywhere else so
905 // it cannot be closed.
906 nacl::FileDescriptor imc_handle;
[email protected]1d8a3d1f2011-02-19 07:11:52907 imc_handle.fd = internal_->sockets_for_renderer[i];
[email protected]c47ec402010-07-29 10:20:49908 imc_handle.auto_close = true;
909 handles_for_renderer.push_back(imc_handle);
910#endif
911 }
912
[email protected]4967f792012-01-20 22:14:40913 const ChildProcessData& data = process_->GetData();
[email protected]00d99542012-04-17 22:48:02914 base::ProcessHandle nacl_process_handle;
[email protected]c47ec402010-07-29 10:20:49915#if defined(OS_WIN)
916 // Copy the process handle into the renderer process.
[email protected]e4f6eb0232012-04-17 00:47:50917 // TODO(mseaborn): Remove this. The renderer process uses this
918 // handle with NaCl's handle_pass module, but we are replacing
919 // handle_pass with Chrome's BrokerDuplicateHandle() function.
[email protected]909c2402011-05-09 11:39:04920 if (!DuplicateHandle(base::GetCurrentProcessHandle(),
[email protected]4967f792012-01-20 22:14:40921 data.handle,
[email protected]909c2402011-05-09 11:39:04922 chrome_render_message_filter_->peer_handle(),
923 &nacl_process_handle,
924 PROCESS_DUP_HANDLE,
925 FALSE,
926 0)) {
[email protected]09afc2e2012-04-10 17:29:03927 DLOG(ERROR) << "DuplicateHandle() failed";
928 return false;
[email protected]909c2402011-05-09 11:39:04929 }
[email protected]e4f6eb0232012-04-17 00:47:50930 // If we are on 64-bit Windows, the NaCl process's sandbox is
931 // managed by a different process from the renderer's sandbox. We
932 // need to inform the renderer's sandbox about the NaCl process so
933 // that the renderer can send handles to the NaCl process using
934 // BrokerDuplicateHandle().
935 if (RunningOnWOW64()) {
936 if (!content::BrokerAddTargetPeer(data.handle)) {
937 DLOG(ERROR) << "Failed to add NaCl process PID";
938 return false;
939 }
940 }
[email protected]fb1277e82009-11-21 20:32:30941#else
[email protected]fb1277e82009-11-21 20:32:30942 // We use pid as process handle on Posix
[email protected]4967f792012-01-20 22:14:40943 nacl_process_handle = data.handle;
[email protected]fb1277e82009-11-21 20:32:30944#endif
945
946 // Get the pid of the NaCl process
[email protected]4967f792012-01-20 22:14:40947 base::ProcessId nacl_process_id = base::GetProcId(data.handle);
[email protected]fb1277e82009-11-21 20:32:30948
[email protected]2ccf45c2011-08-19 23:35:50949 ChromeViewHostMsg_LaunchNaCl::WriteReplyParams(
[email protected]c47ec402010-07-29 10:20:49950 reply_msg_, handles_for_renderer, nacl_process_handle, nacl_process_id);
[email protected]92d56412011-03-24 20:53:52951 chrome_render_message_filter_->Send(reply_msg_);
952 chrome_render_message_filter_ = NULL;
[email protected]fb1277e82009-11-21 20:32:30953 reply_msg_ = NULL;
[email protected]1d8a3d1f2011-02-19 07:11:52954 internal_->sockets_for_renderer.clear();
[email protected]00d99542012-04-17 22:48:02955 return true;
956}
[email protected]fb1277e82009-11-21 20:32:30957
[email protected]00d99542012-04-17 22:48:02958bool NaClProcessHost::StartNaClExecution() {
959 NaClBrowser* nacl_browser = NaClBrowser::GetInstance();
960
961 nacl::NaClStartParams params;
962 params.validation_cache_key = nacl_browser->GetValidatorCacheKey();
963 params.version = chrome::VersionInfo().CreateVersionString();
964 params.enable_exception_handling = enable_exception_handling_;
965
966 base::PlatformFile irt_file = nacl_browser->IrtFile();
967 CHECK_NE(irt_file, base::kInvalidPlatformFileValue);
968
969 const ChildProcessData& data = process_->GetData();
[email protected]1d8a3d1f2011-02-19 07:11:52970 for (size_t i = 0; i < internal_->sockets_for_sel_ldr.size(); i++) {
[email protected]00d99542012-04-17 22:48:02971 if (!ShareHandleToSelLdr(data.handle,
972 internal_->sockets_for_sel_ldr[i], true,
973 &params.handles)) {
[email protected]09afc2e2012-04-10 17:29:03974 return false;
[email protected]c47ec402010-07-29 10:20:49975 }
[email protected]773ebb92011-11-15 19:06:52976 }
977
978 // Send over the IRT file handle. We don't close our own copy!
[email protected]00d99542012-04-17 22:48:02979 if (!ShareHandleToSelLdr(data.handle, irt_file, false, &params.handles))
[email protected]09afc2e2012-04-10 17:29:03980 return false;
[email protected]c47ec402010-07-29 10:20:49981
[email protected]ab88d1542011-11-18 22:52:00982#if defined(OS_MACOSX)
983 // For dynamic loading support, NaCl requires a file descriptor that
984 // was created in /tmp, since those created with shm_open() are not
985 // mappable with PROT_EXEC. Rather than requiring an extra IPC
986 // round trip out of the sandbox, we create an FD here.
[email protected]cbbe7842011-11-17 22:01:25987 base::SharedMemory memory_buffer;
[email protected]b05df6b2011-12-01 23:19:31988 base::SharedMemoryCreateOptions options;
989 options.size = 1;
990 options.executable = true;
991 if (!memory_buffer.Create(options)) {
[email protected]09afc2e2012-04-10 17:29:03992 DLOG(ERROR) << "Failed to allocate memory buffer";
993 return false;
[email protected]2c68bf032010-11-11 23:16:30994 }
[email protected]cbbe7842011-11-17 22:01:25995 nacl::FileDescriptor memory_fd;
996 memory_fd.fd = dup(memory_buffer.handle().fd);
997 if (memory_fd.fd < 0) {
[email protected]09afc2e2012-04-10 17:29:03998 DLOG(ERROR) << "Failed to dup() a file descriptor";
999 return false;
[email protected]cbbe7842011-11-17 22:01:251000 }
1001 memory_fd.auto_close = true;
[email protected]00d99542012-04-17 22:48:021002 params.handles.push_back(memory_fd);
[email protected]2c68bf032010-11-11 23:16:301003#endif
1004
[email protected]00d99542012-04-17 22:48:021005 IPC::Message* start_message = new NaClProcessMsg_Start(params);
[email protected]b39c6d92012-01-31 16:38:411006#if defined(OS_WIN)
[email protected]5ca93be2012-03-21 20:04:061007 if (debug_context_ != NULL) {
1008 debug_context_->SetStartMessage(start_message);
[email protected]b39c6d92012-01-31 16:38:411009 debug_context_->SendStartMessage();
1010 } else {
[email protected]5ca93be2012-03-21 20:04:061011 process_->Send(start_message);
[email protected]b39c6d92012-01-31 16:38:411012 }
1013#else
[email protected]5ca93be2012-03-21 20:04:061014 process_->Send(start_message);
[email protected]b39c6d92012-01-31 16:38:411015#endif
1016
[email protected]1d8a3d1f2011-02-19 07:11:521017 internal_->sockets_for_sel_ldr.clear();
[email protected]09afc2e2012-04-10 17:29:031018 return true;
1019}
1020
[email protected]00d99542012-04-17 22:48:021021bool NaClProcessHost::SendStart() {
1022 return ReplyToRenderer() && StartNaClExecution();
1023}
1024
[email protected]09afc2e2012-04-10 17:29:031025bool NaClProcessHost::StartWithLaunchedProcess() {
1026#if defined(OS_LINUX)
1027 if (wait_for_nacl_gdb_) {
1028 if (LaunchNaClGdb(base::GetProcId(process_->GetData().handle))) {
1029 // We will be called with wait_for_nacl_gdb_ = false once debugger is
1030 // attached to the program.
1031 return true;
1032 }
1033 DLOG(ERROR) << "Failed to launch debugger";
1034 // Continue execution without debugger.
1035 }
1036#endif
1037
1038 NaClBrowser* nacl_browser = NaClBrowser::GetInstance();
1039 if (nacl_browser->IrtAvailable())
1040 return SendStart(); // The IRT is already open. Away we go.
1041
1042 // We're waiting for the IRT to be open.
1043 return nacl_browser->MakeIrtAvailable(
1044 base::Bind(&NaClProcessHost::IrtReady, weak_factory_.GetWeakPtr()));
[email protected]d032f492009-09-29 00:33:461045}
1046
[email protected]4a0141b2012-03-27 01:15:301047void NaClProcessHost::OnQueryKnownToValidate(const std::string& signature,
1048 bool* result) {
1049 *result = NaClBrowser::GetInstance()->QueryKnownToValidate(signature);
1050}
1051
1052void NaClProcessHost::OnSetKnownToValidate(const std::string& signature) {
1053 NaClBrowser::GetInstance()->SetKnownToValidate(signature);
1054}