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 "components/nacl/browser/nacl_process_host.h"
11 #include "base/base_switches.h"
12 #include "base/bind.h"
13 #include "base/command_line.h"
14 #include "base/file_util.h"
15 #include "base/message_loop/message_loop.h"
16 #include "base/metrics/histogram.h"
17 #include "base/path_service.h"
18 #include "base/process/launch.h"
19 #include "base/process/process_iterator.h"
20 #include "base/rand_util.h"
21 #include "base/strings/string_number_conversions.h"
22 #include "base/strings/string_split.h"
23 #include "base/strings/string_util.h"
24 #include "base/strings/stringprintf.h"
25 #include "base/strings/utf_string_conversions.h"
26 #include "base/threading/sequenced_worker_pool.h"
27 #include "base/win/windows_version.h"
28 #include "build/build_config.h"
29 #include "components/nacl/browser/nacl_browser.h"
30 #include "components/nacl/browser/nacl_host_message_filter.h"
31 #include "components/nacl/common/nacl_cmd_line.h"
32 #include "components/nacl/common/nacl_host_messages.h"
33 #include "components/nacl/common/nacl_messages.h"
34 #include "components/nacl/common/nacl_process_type.h"
35 #include "components/nacl/common/nacl_switches.h"
36 #include "content/public/browser/browser_child_process_host.h"
37 #include "content/public/browser/browser_ppapi_host.h"
38 #include "content/public/browser/child_process_data.h"
39 #include "content/public/browser/plugin_service.h"
40 #include "content/public/common/child_process_host.h"
41 #include "content/public/common/content_switches.h"
42 #include "content/public/common/process_type.h"
43 #include "ipc/ipc_channel.h"
44 #include "ipc/ipc_switches.h"
45 #include "native_client/src/shared/imc/nacl_imc_c.h"
46 #include "net/base/net_util.h"
47 #include "net/socket/tcp_listen_socket.h"
48 #include "ppapi/host/host_factory.h"
49 #include "ppapi/host/ppapi_host.h"
50 #include "ppapi/proxy/ppapi_messages.h"
51 #include "ppapi/shared_impl/ppapi_nacl_plugin_args.h"
52 #include "ppapi/shared_impl/ppapi_switches.h"
57 #include "ipc/ipc_channel_posix.h"
61 #include "base/threading/thread.h"
62 #include "base/win/scoped_handle.h"
63 #include "components/nacl/browser/nacl_broker_service_win.h"
64 #include "components/nacl/common/nacl_debug_exception_handler_win.h"
65 #include "content/public/common/sandbox_init.h"
66 #include "content/public/common/sandboxed_process_launcher_delegate.h"
69 using content::BrowserThread;
70 using content::ChildProcessData;
71 using content::ChildProcessHost;
72 using ppapi::proxy::SerializedHandle;
78 // Looks for the largest contiguous unallocated region of address
79 // space and returns it via |*out_addr| and |*out_size|.
80 void FindAddressSpace(base::ProcessHandle process,
81 char** out_addr, size_t* out_size) {
86 MEMORY_BASIC_INFORMATION info;
87 size_t result = VirtualQueryEx(process, static_cast<void*>(addr),
89 if (result < sizeof(info))
91 if (info.State == MEM_FREE && info.RegionSize > *out_size) {
93 *out_size = info.RegionSize;
95 addr += info.RegionSize;
103 // Allocates |size| bytes of address space in the given process at a
104 // randomised address.
105 void* AllocateAddressSpaceASLR(base::ProcessHandle process, size_t size) {
108 FindAddressSpace(process, &addr, &avail_size);
109 if (avail_size < size)
111 size_t offset = base::RandGenerator(avail_size - size);
112 const int kPageSize = 0x10000;
114 reinterpret_cast<void*>(reinterpret_cast<uint64>(addr + offset)
116 return VirtualAllocEx(process, request_addr, size,
117 MEM_RESERVE, PAGE_NOACCESS);
122 #endif // defined(OS_WIN)
127 bool RunningOnWOW64() {
128 return (base::win::OSInfo::GetInstance()->wow64_status() ==
129 base::win::OSInfo::WOW64_ENABLED);
132 // NOTE: changes to this class need to be reviewed by the security team.
133 class NaClSandboxedProcessLauncherDelegate
134 : public content::SandboxedProcessLauncherDelegate {
136 NaClSandboxedProcessLauncherDelegate() {}
137 virtual ~NaClSandboxedProcessLauncherDelegate() {}
139 virtual void PostSpawnTarget(base::ProcessHandle process) {
140 // For Native Client sel_ldr processes on 32-bit Windows, reserve 1 GB of
141 // address space to prevent later failure due to address space fragmentation
142 // from .dll loading. The NaCl process will attempt to locate this space by
143 // scanning the address space using VirtualQuery.
144 // TODO(bbudge) Handle the --no-sandbox case.
145 // http://code.google.com/p/nativeclient/issues/detail?id=2131
146 const SIZE_T kNaClSandboxSize = 1 << 30;
147 if (!nacl::AllocateAddressSpaceASLR(process, kNaClSandboxSize)) {
148 DLOG(WARNING) << "Failed to reserve address space for Native Client";
155 void SetCloseOnExec(NaClHandle fd) {
156 #if defined(OS_POSIX)
157 int flags = fcntl(fd, F_GETFD);
159 int rc = fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
164 bool ShareHandleToSelLdr(
165 base::ProcessHandle processh,
168 std::vector<nacl::FileDescriptor> *handles_for_sel_ldr) {
171 int flags = DUPLICATE_SAME_ACCESS;
173 flags |= DUPLICATE_CLOSE_SOURCE;
174 if (!DuplicateHandle(GetCurrentProcess(),
175 reinterpret_cast<HANDLE>(sourceh),
178 0, // Unused given DUPLICATE_SAME_ACCESS.
181 LOG(ERROR) << "DuplicateHandle() failed";
184 handles_for_sel_ldr->push_back(
185 reinterpret_cast<nacl::FileDescriptor>(channel));
187 nacl::FileDescriptor channel;
188 channel.fd = sourceh;
189 channel.auto_close = close_source;
190 handles_for_sel_ldr->push_back(channel);
195 ppapi::PpapiPermissions GetNaClPermissions(uint32 permission_bits) {
196 // Only allow NaCl plugins to request certain permissions. We don't want
197 // a compromised renderer to be able to start a nacl plugin with e.g. Flash
198 // permissions which may expand the surface area of the sandbox.
199 uint32 masked_bits = permission_bits & ppapi::PERMISSION_DEV;
200 if (content::PluginService::GetInstance()->PpapiDevChannelSupported())
201 masked_bits |= ppapi::PERMISSION_DEV_CHANNEL;
202 return ppapi::PpapiPermissions::GetForCommandLine(masked_bits);
209 struct NaClProcessHost::NaClInternal {
210 NaClHandle socket_for_renderer;
211 NaClHandle socket_for_sel_ldr;
214 : socket_for_renderer(NACL_INVALID_HANDLE),
215 socket_for_sel_ldr(NACL_INVALID_HANDLE) { }
218 // -----------------------------------------------------------------------------
220 NaClProcessHost::NaClProcessHost(const GURL& manifest_url,
222 uint32 permission_bits,
224 bool enable_dyncode_syscalls,
225 bool enable_exception_handling,
226 bool enable_crash_throttling,
228 const base::FilePath& profile_directory)
229 : manifest_url_(manifest_url),
230 permissions_(GetNaClPermissions(permission_bits)),
232 process_launched_by_broker_(false),
236 debug_exception_handler_requested_(false),
238 internal_(new NaClInternal()),
241 enable_debug_stub_(false),
242 enable_dyncode_syscalls_(enable_dyncode_syscalls),
243 enable_exception_handling_(enable_exception_handling),
244 enable_crash_throttling_(enable_crash_throttling),
245 off_the_record_(off_the_record),
246 profile_directory_(profile_directory),
247 render_view_id_(render_view_id) {
248 process_.reset(content::BrowserChildProcessHost::Create(
249 PROCESS_TYPE_NACL_LOADER, this));
251 // Set the display name so the user knows what plugin the process is running.
252 // We aren't on the UI thread so getting the pref locale for language
253 // formatting isn't possible, so IDN will be lost, but this is probably OK
254 // for this use case.
255 process_->SetName(net::FormatUrl(manifest_url_, std::string()));
257 enable_debug_stub_ = CommandLine::ForCurrentProcess()->HasSwitch(
258 switches::kEnableNaClDebug);
261 NaClProcessHost::~NaClProcessHost() {
262 // Report exit status only if the process was successfully started.
263 if (process_->GetData().handle != base::kNullProcessHandle) {
265 process_->GetTerminationStatus(false /* known_dead */, &exit_code);
266 std::string message =
267 base::StringPrintf("NaCl process exited with status %i (0x%x)",
268 exit_code, exit_code);
269 if (exit_code == 0) {
272 LOG(ERROR) << message;
276 if (internal_->socket_for_renderer != NACL_INVALID_HANDLE) {
277 if (NaClClose(internal_->socket_for_renderer) != 0) {
278 NOTREACHED() << "NaClClose() failed";
282 if (internal_->socket_for_sel_ldr != NACL_INVALID_HANDLE) {
283 if (NaClClose(internal_->socket_for_sel_ldr) != 0) {
284 NOTREACHED() << "NaClClose() failed";
289 // The process failed to launch for some reason.
290 // Don't keep the renderer hanging.
291 reply_msg_->set_reply_error();
292 nacl_host_message_filter_->Send(reply_msg_);
295 if (process_launched_by_broker_) {
296 NaClBrokerService::GetInstance()->OnLoaderDied();
301 void NaClProcessHost::OnProcessCrashed(int exit_status) {
302 if (enable_crash_throttling_ &&
303 !CommandLine::ForCurrentProcess()->HasSwitch(
304 switches::kDisablePnaclCrashThrottling)) {
305 NaClBrowser::GetInstance()->OnProcessCrashed();
309 // This is called at browser startup.
311 void NaClProcessHost::EarlyStartup() {
312 NaClBrowser::GetInstance()->EarlyStartup();
313 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
314 // Open the IRT file early to make sure that it isn't replaced out from
315 // under us by autoupdate.
316 NaClBrowser::GetInstance()->EnsureIrtAvailable();
318 CommandLine* cmd = CommandLine::ForCurrentProcess();
319 UMA_HISTOGRAM_BOOLEAN(
321 !cmd->GetSwitchValuePath(switches::kNaClGdb).empty());
322 UMA_HISTOGRAM_BOOLEAN(
323 "NaCl.nacl-gdb-script",
324 !cmd->GetSwitchValuePath(switches::kNaClGdbScript).empty());
325 UMA_HISTOGRAM_BOOLEAN(
326 "NaCl.enable-nacl-debug",
327 cmd->HasSwitch(switches::kEnableNaClDebug));
328 NaClBrowser::GetDelegate()->SetDebugPatterns(
329 cmd->GetSwitchValueASCII(switches::kNaClDebugMask));
332 void NaClProcessHost::Launch(
333 NaClHostMessageFilter* nacl_host_message_filter,
334 IPC::Message* reply_msg,
335 const base::FilePath& manifest_path) {
336 nacl_host_message_filter_ = nacl_host_message_filter;
337 reply_msg_ = reply_msg;
338 manifest_path_ = manifest_path;
340 // Do not launch the requested NaCl module if NaCl is marked "unstable" due
341 // to too many crashes within a given time period.
342 if (enable_crash_throttling_ &&
343 !CommandLine::ForCurrentProcess()->HasSwitch(
344 switches::kDisablePnaclCrashThrottling) &&
345 NaClBrowser::GetInstance()->IsThrottled()) {
346 SendErrorToRenderer("Process creation was throttled due to excessive"
352 const CommandLine* cmd = CommandLine::ForCurrentProcess();
354 if (cmd->HasSwitch(switches::kEnableNaClDebug) &&
355 !cmd->HasSwitch(switches::kNoSandbox)) {
356 // We don't switch off sandbox automatically for security reasons.
357 SendErrorToRenderer("NaCl's GDB debug stub requires --no-sandbox flag"
358 " on Windows. See crbug.com/265624.");
363 if (cmd->HasSwitch(switches::kNaClGdb) &&
364 !cmd->HasSwitch(switches::kEnableNaClDebug)) {
365 LOG(WARNING) << "--nacl-gdb flag requires --enable-nacl-debug flag";
368 // Start getting the IRT open asynchronously while we launch the NaCl process.
369 // We'll make sure this actually finished in StartWithLaunchedProcess, below.
370 NaClBrowser* nacl_browser = NaClBrowser::GetInstance();
371 nacl_browser->EnsureAllResourcesAvailable();
372 if (!nacl_browser->IsOk()) {
373 SendErrorToRenderer("could not find all the resources needed"
374 " to launch the process");
379 // Rather than creating a socket pair in the renderer, and passing
380 // one side through the browser to sel_ldr, socket pairs are created
381 // in the browser and then passed to the renderer and sel_ldr.
383 // This is mainly for the benefit of Windows, where sockets cannot
384 // be passed in messages, but are copied via DuplicateHandle().
385 // This means the sandboxed renderer cannot send handles to the
389 // Create a connected socket
390 if (NaClSocketPair(pair) == -1) {
391 SendErrorToRenderer("NaClSocketPair() failed");
395 internal_->socket_for_renderer = pair[0];
396 internal_->socket_for_sel_ldr = pair[1];
397 SetCloseOnExec(pair[0]);
398 SetCloseOnExec(pair[1]);
400 // Launch the process
401 if (!LaunchSelLdr()) {
406 void NaClProcessHost::OnChannelConnected(int32 peer_pid) {
407 if (!CommandLine::ForCurrentProcess()->GetSwitchValuePath(
408 switches::kNaClGdb).empty()) {
414 void NaClProcessHost::OnProcessLaunchedByBroker(base::ProcessHandle handle) {
415 process_launched_by_broker_ = true;
416 process_->SetHandle(handle);
417 if (!StartWithLaunchedProcess())
421 void NaClProcessHost::OnDebugExceptionHandlerLaunchedByBroker(bool success) {
422 IPC::Message* reply = attach_debug_exception_handler_reply_msg_.release();
423 NaClProcessMsg_AttachDebugExceptionHandler::WriteReplyParams(reply, success);
428 // Needed to handle sync messages in OnMessageRecieved.
429 bool NaClProcessHost::Send(IPC::Message* msg) {
430 return process_->Send(msg);
433 bool NaClProcessHost::LaunchNaClGdb() {
435 base::FilePath nacl_gdb =
436 CommandLine::ForCurrentProcess()->GetSwitchValuePath(switches::kNaClGdb);
437 CommandLine cmd_line(nacl_gdb);
439 CommandLine::StringType nacl_gdb =
440 CommandLine::ForCurrentProcess()->GetSwitchValueNative(
442 CommandLine::StringVector argv;
443 // We don't support spaces inside arguments in --nacl-gdb switch.
444 base::SplitString(nacl_gdb, static_cast<CommandLine::CharType>(' '), &argv);
445 CommandLine cmd_line(argv);
447 cmd_line.AppendArg("--eval-command");
448 base::FilePath::StringType irt_path(
449 NaClBrowser::GetInstance()->GetIrtFilePath().value());
450 // Avoid back slashes because nacl-gdb uses posix escaping rules on Windows.
451 // See issue https://code.google.com/p/nativeclient/issues/detail?id=3482.
452 std::replace(irt_path.begin(), irt_path.end(), '\\', '/');
453 cmd_line.AppendArgNative(FILE_PATH_LITERAL("nacl-irt \"") + irt_path +
454 FILE_PATH_LITERAL("\""));
455 if (!manifest_path_.empty()) {
456 cmd_line.AppendArg("--eval-command");
457 base::FilePath::StringType manifest_path_value(manifest_path_.value());
458 std::replace(manifest_path_value.begin(), manifest_path_value.end(),
460 cmd_line.AppendArgNative(FILE_PATH_LITERAL("nacl-manifest \"") +
461 manifest_path_value + FILE_PATH_LITERAL("\""));
463 cmd_line.AppendArg("--eval-command");
464 cmd_line.AppendArg("target remote :4014");
465 base::FilePath script = CommandLine::ForCurrentProcess()->GetSwitchValuePath(
466 switches::kNaClGdbScript);
467 if (!script.empty()) {
468 cmd_line.AppendArg("--command");
469 cmd_line.AppendArgNative(script.value());
471 return base::LaunchProcess(cmd_line, base::LaunchOptions(), NULL);
474 bool NaClProcessHost::LaunchSelLdr() {
475 std::string channel_id = process_->GetHost()->CreateChannel();
476 if (channel_id.empty()) {
477 SendErrorToRenderer("CreateChannel() failed");
481 CommandLine::StringType nacl_loader_prefix;
482 #if defined(OS_POSIX)
483 nacl_loader_prefix = CommandLine::ForCurrentProcess()->GetSwitchValueNative(
484 switches::kNaClLoaderCmdPrefix);
485 #endif // defined(OS_POSIX)
487 // Build command line for nacl.
489 #if defined(OS_MACOSX)
490 // The Native Client process needs to be able to allocate a 1GB contiguous
491 // region to use as the client environment's virtual address space. ASLR
492 // (PIE) interferes with this by making it possible that no gap large enough
493 // to accomodate this request will exist in the child process' address
494 // space. Disable PIE for NaCl processes. See http://crbug.com/90221 and
495 // http://code.google.com/p/nativeclient/issues/detail?id=2043.
496 int flags = ChildProcessHost::CHILD_NO_PIE;
497 #elif defined(OS_LINUX)
498 int flags = nacl_loader_prefix.empty() ? ChildProcessHost::CHILD_ALLOW_SELF :
499 ChildProcessHost::CHILD_NORMAL;
501 int flags = ChildProcessHost::CHILD_NORMAL;
504 base::FilePath exe_path = ChildProcessHost::GetChildPath(flags);
505 if (exe_path.empty())
509 // On Windows 64-bit NaCl loader is called nacl64.exe instead of chrome.exe
510 if (RunningOnWOW64()) {
511 if (!NaClBrowser::GetInstance()->GetNaCl64ExePath(&exe_path)) {
512 SendErrorToRenderer("could not get path to nacl64.exe");
518 scoped_ptr<CommandLine> cmd_line(new CommandLine(exe_path));
519 CopyNaClCommandLineArguments(cmd_line.get());
521 cmd_line->AppendSwitchASCII(switches::kProcessType,
522 switches::kNaClLoaderProcess);
523 cmd_line->AppendSwitchASCII(switches::kProcessChannelID, channel_id);
524 if (NaClBrowser::GetDelegate()->DialogsAreSuppressed())
525 cmd_line->AppendSwitch(switches::kNoErrorDialogs);
527 if (!nacl_loader_prefix.empty())
528 cmd_line->PrependWrapper(nacl_loader_prefix);
530 // On Windows we might need to start the broker process to launch a new loader
532 if (RunningOnWOW64()) {
533 if (!NaClBrokerService::GetInstance()->LaunchLoader(
534 weak_factory_.GetWeakPtr(), channel_id)) {
535 SendErrorToRenderer("broker service did not launch process");
539 process_->Launch(new NaClSandboxedProcessLauncherDelegate,
543 #elif defined(OS_POSIX)
544 process_->Launch(nacl_loader_prefix.empty(), // use_zygote
545 base::EnvironmentMap(),
552 bool NaClProcessHost::OnMessageReceived(const IPC::Message& msg) {
554 IPC_BEGIN_MESSAGE_MAP(NaClProcessHost, msg)
555 IPC_MESSAGE_HANDLER(NaClProcessMsg_QueryKnownToValidate,
556 OnQueryKnownToValidate)
557 IPC_MESSAGE_HANDLER(NaClProcessMsg_SetKnownToValidate,
558 OnSetKnownToValidate)
559 IPC_MESSAGE_HANDLER_DELAY_REPLY(NaClProcessMsg_ResolveFileToken,
562 IPC_MESSAGE_HANDLER_DELAY_REPLY(NaClProcessMsg_AttachDebugExceptionHandler,
563 OnAttachDebugExceptionHandler)
565 IPC_MESSAGE_HANDLER(NaClProcessHostMsg_PpapiChannelsCreated,
566 OnPpapiChannelsCreated)
567 IPC_MESSAGE_UNHANDLED(handled = false)
568 IPC_END_MESSAGE_MAP()
572 void NaClProcessHost::OnProcessLaunched() {
573 if (!StartWithLaunchedProcess())
577 // Called when the NaClBrowser singleton has been fully initialized.
578 void NaClProcessHost::OnResourcesReady() {
579 NaClBrowser* nacl_browser = NaClBrowser::GetInstance();
580 if (!nacl_browser->IsReady()) {
581 SendErrorToRenderer("could not acquire shared resources needed by NaCl");
583 } else if (!SendStart()) {
588 bool NaClProcessHost::ReplyToRenderer(
589 const IPC::ChannelHandle& channel_handle) {
591 // If we are on 64-bit Windows, the NaCl process's sandbox is
592 // managed by a different process from the renderer's sandbox. We
593 // need to inform the renderer's sandbox about the NaCl process so
594 // that the renderer can send handles to the NaCl process using
595 // BrokerDuplicateHandle().
596 if (RunningOnWOW64()) {
597 if (!content::BrokerAddTargetPeer(process_->GetData().handle)) {
598 SendErrorToRenderer("BrokerAddTargetPeer() failed");
604 FileDescriptor handle_for_renderer;
606 // Copy the handle into the renderer process.
607 HANDLE handle_in_renderer;
608 if (!DuplicateHandle(base::GetCurrentProcessHandle(),
609 reinterpret_cast<HANDLE>(
610 internal_->socket_for_renderer),
611 nacl_host_message_filter_->PeerHandle(),
613 0, // Unused given DUPLICATE_SAME_ACCESS.
615 DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS)) {
616 SendErrorToRenderer("DuplicateHandle() failed");
619 handle_for_renderer = reinterpret_cast<FileDescriptor>(
622 // No need to dup the imc_handle - we don't pass it anywhere else so
623 // it cannot be closed.
624 FileDescriptor imc_handle;
625 imc_handle.fd = internal_->socket_for_renderer;
626 imc_handle.auto_close = true;
627 handle_for_renderer = imc_handle;
630 const ChildProcessData& data = process_->GetData();
631 SendMessageToRenderer(
632 NaClLaunchResult(handle_for_renderer,
634 base::GetProcId(data.handle),
636 std::string() /* error_message */);
637 internal_->socket_for_renderer = NACL_INVALID_HANDLE;
641 void NaClProcessHost::SendErrorToRenderer(const std::string& error_message) {
642 LOG(ERROR) << "NaCl process launch failed: " << error_message;
643 SendMessageToRenderer(NaClLaunchResult(), error_message);
646 void NaClProcessHost::SendMessageToRenderer(
647 const NaClLaunchResult& result,
648 const std::string& error_message) {
649 DCHECK(nacl_host_message_filter_);
651 if (nacl_host_message_filter_ != NULL && reply_msg_ != NULL) {
652 NaClHostMsg_LaunchNaCl::WriteReplyParams(
653 reply_msg_, result, error_message);
654 nacl_host_message_filter_->Send(reply_msg_);
655 nacl_host_message_filter_ = NULL;
660 // TCP port we chose for NaCl debug stub. It can be any other number.
661 static const int kInitialDebugStubPort = 4014;
663 #if defined(OS_POSIX)
664 net::SocketDescriptor NaClProcessHost::GetDebugStubSocketHandle() {
665 NaClBrowser* nacl_browser = NaClBrowser::GetInstance();
666 net::SocketDescriptor s = net::kInvalidSocket;
667 // We always try to allocate the default port first. If this fails, we then
668 // allocate any available port.
669 // On success, if the test system has register a handler
670 // (GdbDebugStubPortListener), we fire a notification.
671 int port = kInitialDebugStubPort;
672 s = net::TCPListenSocket::CreateAndBind("127.0.0.1", port);
673 if (s == net::kInvalidSocket) {
674 s = net::TCPListenSocket::CreateAndBindAnyPort("127.0.0.1", &port);
676 if (s != net::kInvalidSocket) {
677 if (nacl_browser->HasGdbDebugStubPortListener()) {
678 nacl_browser->FireGdbDebugStubPortOpened(port);
681 // Set debug stub port on the process object.
682 process_->SetNaClDebugStubPort(port);
683 if (s == net::kInvalidSocket) {
684 LOG(ERROR) << "failed to open socket for debug stub";
685 return net::kInvalidSocket;
687 LOG(WARNING) << "debug stub on port " << port;
690 LOG(ERROR) << "listen() failed on debug stub socket";
691 if (IGNORE_EINTR(close(s)) < 0)
692 PLOG(ERROR) << "failed to close debug stub socket";
693 return net::kInvalidSocket;
699 bool NaClProcessHost::StartNaClExecution() {
700 NaClBrowser* nacl_browser = NaClBrowser::GetInstance();
702 NaClStartParams params;
703 params.validation_cache_enabled = nacl_browser->ValidationCacheIsEnabled();
704 params.validation_cache_key = nacl_browser->GetValidationCacheKey();
705 params.version = NaClBrowser::GetDelegate()->GetVersionString();
706 params.enable_exception_handling = enable_exception_handling_;
707 params.enable_debug_stub = enable_debug_stub_ &&
708 NaClBrowser::GetDelegate()->URLMatchesDebugPatterns(manifest_url_);
709 // Enable PPAPI proxy channel creation only for renderer processes.
710 params.enable_ipc_proxy = enable_ppapi_proxy();
711 params.uses_irt = uses_irt_;
712 params.enable_dyncode_syscalls = enable_dyncode_syscalls_;
713 params.enable_nonsfi_mode = CommandLine::ForCurrentProcess()->HasSwitch(
714 switches::kEnableNaClNonSfiMode);
716 const ChildProcessData& data = process_->GetData();
717 if (!ShareHandleToSelLdr(data.handle,
718 internal_->socket_for_sel_ldr, true,
723 if (params.uses_irt) {
724 base::PlatformFile irt_file = nacl_browser->IrtFile();
725 CHECK_NE(irt_file, base::kInvalidPlatformFileValue);
726 // Send over the IRT file handle. We don't close our own copy!
727 if (!ShareHandleToSelLdr(data.handle, irt_file, false, ¶ms.handles))
731 #if defined(OS_MACOSX)
732 // For dynamic loading support, NaCl requires a file descriptor that
733 // was created in /tmp, since those created with shm_open() are not
734 // mappable with PROT_EXEC. Rather than requiring an extra IPC
735 // round trip out of the sandbox, we create an FD here.
736 base::SharedMemory memory_buffer;
737 base::SharedMemoryCreateOptions options;
739 options.executable = true;
740 if (!memory_buffer.Create(options)) {
741 DLOG(ERROR) << "Failed to allocate memory buffer";
744 FileDescriptor memory_fd;
745 memory_fd.fd = dup(memory_buffer.handle().fd);
746 if (memory_fd.fd < 0) {
747 DLOG(ERROR) << "Failed to dup() a file descriptor";
750 memory_fd.auto_close = true;
751 params.handles.push_back(memory_fd);
754 #if defined(OS_POSIX)
755 if (params.enable_debug_stub) {
756 net::SocketDescriptor server_bound_socket = GetDebugStubSocketHandle();
757 if (server_bound_socket != net::kInvalidSocket) {
758 params.debug_stub_server_bound_socket =
759 FileDescriptor(server_bound_socket, true);
764 process_->Send(new NaClProcessMsg_Start(params));
766 internal_->socket_for_sel_ldr = NACL_INVALID_HANDLE;
770 bool NaClProcessHost::SendStart() {
771 if (!enable_ppapi_proxy()) {
772 if (!ReplyToRenderer(IPC::ChannelHandle()))
775 return StartNaClExecution();
778 // This method is called when NaClProcessHostMsg_PpapiChannelCreated is
780 void NaClProcessHost::OnPpapiChannelsCreated(
781 const IPC::ChannelHandle& browser_channel_handle,
782 const IPC::ChannelHandle& renderer_channel_handle) {
783 // Only renderer processes should create a channel.
784 DCHECK(enable_ppapi_proxy());
785 if (!ipc_proxy_channel_.get()) {
786 DCHECK_EQ(PROCESS_TYPE_NACL_LOADER, process_->GetData().process_type);
788 ipc_proxy_channel_.reset(
789 new IPC::ChannelProxy(browser_channel_handle,
790 IPC::Channel::MODE_CLIENT,
792 base::MessageLoopProxy::current().get()));
793 // Create the browser ppapi host and enable PPAPI message dispatching to the
795 ppapi_host_.reset(content::BrowserPpapiHost::CreateExternalPluginProcess(
796 ipc_proxy_channel_.get(), // sender
798 process_->GetData().handle,
799 ipc_proxy_channel_.get(),
800 nacl_host_message_filter_->render_process_id(),
802 profile_directory_));
803 ppapi_host_->SetOnKeepaliveCallback(
804 NaClBrowser::GetDelegate()->GetOnKeepaliveCallback());
806 ppapi::PpapiNaClPluginArgs args;
807 args.off_the_record = nacl_host_message_filter_->off_the_record();
808 args.permissions = permissions_;
809 CommandLine* cmdline = CommandLine::ForCurrentProcess();
811 std::string flag_whitelist[] = {
812 switches::kPpapiKeepAliveThrottle,
816 for (size_t i = 0; i < arraysize(flag_whitelist); ++i) {
817 std::string value = cmdline->GetSwitchValueASCII(flag_whitelist[i]);
818 if (!value.empty()) {
819 args.switch_names.push_back(flag_whitelist[i]);
820 args.switch_values.push_back(value);
824 ppapi_host_->GetPpapiHost()->AddHostFactoryFilter(
825 scoped_ptr<ppapi::host::HostFactory>(
826 NaClBrowser::GetDelegate()->CreatePpapiHostFactory(
827 ppapi_host_.get())));
829 // Send a message to initialize the IPC dispatchers in the NaCl plugin.
830 ipc_proxy_channel_->Send(new PpapiMsg_InitializeNaClDispatcher(args));
832 // Let the renderer know that the IPC channels are established.
833 ReplyToRenderer(renderer_channel_handle);
835 // Attempt to open more than 1 browser channel is not supported.
836 // Shut down the NaCl process.
837 process_->GetHost()->ForceShutdown();
841 bool NaClProcessHost::StartWithLaunchedProcess() {
842 NaClBrowser* nacl_browser = NaClBrowser::GetInstance();
844 if (nacl_browser->IsReady()) {
846 } else if (nacl_browser->IsOk()) {
847 nacl_browser->WaitForResources(
848 base::Bind(&NaClProcessHost::OnResourcesReady,
849 weak_factory_.GetWeakPtr()));
852 SendErrorToRenderer("previously failed to acquire shared resources");
857 void NaClProcessHost::OnQueryKnownToValidate(const std::string& signature,
859 NaClBrowser* nacl_browser = NaClBrowser::GetInstance();
860 *result = nacl_browser->QueryKnownToValidate(signature, off_the_record_);
863 void NaClProcessHost::OnSetKnownToValidate(const std::string& signature) {
864 NaClBrowser::GetInstance()->SetKnownToValidate(
865 signature, off_the_record_);
868 void NaClProcessHost::FileResolved(
869 const base::FilePath& file_path,
870 IPC::Message* reply_msg,
871 const base::PlatformFile& file) {
872 if (file != base::kInvalidPlatformFileValue) {
873 IPC::PlatformFileForTransit handle = IPC::GetFileHandleForProcess(
875 process_->GetData().handle,
876 true /* close_source */);
877 NaClProcessMsg_ResolveFileToken::WriteReplyParams(
882 NaClProcessMsg_ResolveFileToken::WriteReplyParams(
884 IPC::InvalidPlatformFileForTransit(),
890 void NaClProcessHost::OnResolveFileToken(uint64 file_token_lo,
891 uint64 file_token_hi,
892 IPC::Message* reply_msg) {
893 // Was the file registered?
895 // Note that the file path cache is of bounded size, and old entries can get
896 // evicted. If a large number of NaCl modules are being launched at once,
897 // resolving the file_token may fail because the path cache was thrashed
898 // while the file_token was in flight. In this case the query fails, and we
899 // need to fall back to the slower path.
901 // However: each NaCl process will consume 2-3 entries as it starts up, this
902 // means that eviction will not happen unless you start up 33+ NaCl processes
903 // at the same time, and this still requires worst-case timing. As a
904 // practical matter, no entries should be evicted prematurely.
905 // The cache itself should take ~ (150 characters * 2 bytes/char + ~60 bytes
906 // data structure overhead) * 100 = 35k when full, so making it bigger should
907 // not be a problem, if needed.
909 // Each NaCl process will consume 2-3 entries because the manifest and main
910 // nexe are currently not resolved. Shared libraries will be resolved. They
911 // will be loaded sequentially, so they will only consume a single entry
912 // while the load is in flight.
914 // TODO(ncbray): track behavior with UMA. If entries are getting evicted or
915 // bogus keys are getting queried, this would be good to know.
916 base::FilePath file_path;
917 if (!NaClBrowser::GetInstance()->GetFilePath(
918 file_token_lo, file_token_hi, &file_path)) {
919 NaClProcessMsg_ResolveFileToken::WriteReplyParams(
921 IPC::InvalidPlatformFileForTransit(),
928 if (!base::PostTaskAndReplyWithResult(
929 content::BrowserThread::GetBlockingPool(),
931 base::Bind(OpenNaClExecutableImpl, file_path),
932 base::Bind(&NaClProcessHost::FileResolved,
933 weak_factory_.GetWeakPtr(),
936 NaClProcessMsg_ResolveFileToken::WriteReplyParams(
938 IPC::InvalidPlatformFileForTransit(),
945 void NaClProcessHost::OnAttachDebugExceptionHandler(const std::string& info,
946 IPC::Message* reply_msg) {
947 if (!AttachDebugExceptionHandler(info, reply_msg)) {
948 // Send failure message.
949 NaClProcessMsg_AttachDebugExceptionHandler::WriteReplyParams(reply_msg,
955 bool NaClProcessHost::AttachDebugExceptionHandler(const std::string& info,
956 IPC::Message* reply_msg) {
957 if (!enable_exception_handling_ && !enable_debug_stub_) {
959 "Debug exception handler requested by NaCl process when not enabled";
962 if (debug_exception_handler_requested_) {
963 // The NaCl process should not request this multiple times.
964 DLOG(ERROR) << "Multiple AttachDebugExceptionHandler requests received";
967 debug_exception_handler_requested_ = true;
969 base::ProcessId nacl_pid = base::GetProcId(process_->GetData().handle);
970 base::ProcessHandle temp_handle;
971 // We cannot use process_->GetData().handle because it does not have
972 // the necessary access rights. We open the new handle here rather
973 // than in the NaCl broker process in case the NaCl loader process
974 // dies before the NaCl broker process receives the message we send.
975 // The debug exception handler uses DebugActiveProcess() to attach,
976 // but this takes a PID. We need to prevent the NaCl loader's PID
977 // from being reused before DebugActiveProcess() is called, and
978 // holding a process handle open achieves this.
979 if (!base::OpenProcessHandleWithAccess(
981 base::kProcessAccessQueryInformation |
982 base::kProcessAccessSuspendResume |
983 base::kProcessAccessTerminate |
984 base::kProcessAccessVMOperation |
985 base::kProcessAccessVMRead |
986 base::kProcessAccessVMWrite |
987 base::kProcessAccessDuplicateHandle |
988 base::kProcessAccessWaitForTermination,
990 LOG(ERROR) << "Failed to get process handle";
993 base::win::ScopedHandle process_handle(temp_handle);
995 attach_debug_exception_handler_reply_msg_.reset(reply_msg);
996 // If the NaCl loader is 64-bit, the process running its debug
997 // exception handler must be 64-bit too, so we use the 64-bit NaCl
998 // broker process for this. Otherwise, on a 32-bit system, we use
999 // the 32-bit browser process to run the debug exception handler.
1000 if (RunningOnWOW64()) {
1001 return NaClBrokerService::GetInstance()->LaunchDebugExceptionHandler(
1002 weak_factory_.GetWeakPtr(), nacl_pid, process_handle, info);
1004 NaClStartDebugExceptionHandlerThread(
1005 process_handle.Take(), info,
1006 base::MessageLoopProxy::current(),
1007 base::Bind(&NaClProcessHost::OnDebugExceptionHandlerLaunchedByBroker,
1008 weak_factory_.GetWeakPtr()));