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 "content/public/common/sandboxed_process_launcher_delegate.h"
44 #include "ipc/ipc_channel.h"
45 #include "ipc/ipc_switches.h"
46 #include "native_client/src/shared/imc/nacl_imc_c.h"
47 #include "net/base/net_util.h"
48 #include "net/socket/tcp_listen_socket.h"
49 #include "ppapi/host/host_factory.h"
50 #include "ppapi/host/ppapi_host.h"
51 #include "ppapi/proxy/ppapi_messages.h"
52 #include "ppapi/shared_impl/ppapi_constants.h"
53 #include "ppapi/shared_impl/ppapi_nacl_plugin_args.h"
59 #include "ipc/ipc_channel_posix.h"
63 #include "base/threading/thread.h"
64 #include "base/win/scoped_handle.h"
65 #include "components/nacl/browser/nacl_broker_service_win.h"
66 #include "components/nacl/common/nacl_debug_exception_handler_win.h"
67 #include "content/public/common/sandbox_init.h"
70 using content::BrowserThread;
71 using content::ChildProcessData;
72 using content::ChildProcessHost;
73 using ppapi::proxy::SerializedHandle;
79 // Looks for the largest contiguous unallocated region of address
80 // space and returns it via |*out_addr| and |*out_size|.
81 void FindAddressSpace(base::ProcessHandle process,
82 char** out_addr, size_t* out_size) {
87 MEMORY_BASIC_INFORMATION info;
88 size_t result = VirtualQueryEx(process, static_cast<void*>(addr),
90 if (result < sizeof(info))
92 if (info.State == MEM_FREE && info.RegionSize > *out_size) {
94 *out_size = info.RegionSize;
96 addr += info.RegionSize;
102 bool IsInPath(const std::string& path_env_var, const std::string& dir) {
103 std::vector<std::string> split;
104 base::SplitString(path_env_var, ';', &split);
105 for (std::vector<std::string>::const_iterator i(split.begin());
120 // Allocates |size| bytes of address space in the given process at a
121 // randomised address.
122 void* AllocateAddressSpaceASLR(base::ProcessHandle process, size_t size) {
125 FindAddressSpace(process, &addr, &avail_size);
126 if (avail_size < size)
128 size_t offset = base::RandGenerator(avail_size - size);
129 const int kPageSize = 0x10000;
131 reinterpret_cast<void*>(reinterpret_cast<uint64>(addr + offset)
133 return VirtualAllocEx(process, request_addr, size,
134 MEM_RESERVE, PAGE_NOACCESS);
139 #endif // defined(OS_WIN)
144 bool RunningOnWOW64() {
145 return (base::win::OSInfo::GetInstance()->wow64_status() ==
146 base::win::OSInfo::WOW64_ENABLED);
150 // NOTE: changes to this class need to be reviewed by the security team.
151 class NaClSandboxedProcessLauncherDelegate
152 : public content::SandboxedProcessLauncherDelegate {
154 NaClSandboxedProcessLauncherDelegate(ChildProcessHost* host)
155 #if defined(OS_POSIX)
156 : ipc_fd_(host->TakeClientFileDescriptor())
160 virtual ~NaClSandboxedProcessLauncherDelegate() {}
163 virtual void PostSpawnTarget(base::ProcessHandle process) {
164 // For Native Client sel_ldr processes on 32-bit Windows, reserve 1 GB of
165 // address space to prevent later failure due to address space fragmentation
166 // from .dll loading. The NaCl process will attempt to locate this space by
167 // scanning the address space using VirtualQuery.
168 // TODO(bbudge) Handle the --no-sandbox case.
169 // http://code.google.com/p/nativeclient/issues/detail?id=2131
170 const SIZE_T kNaClSandboxSize = 1 << 30;
171 if (!nacl::AllocateAddressSpaceASLR(process, kNaClSandboxSize)) {
172 DLOG(WARNING) << "Failed to reserve address space for Native Client";
175 #elif defined(OS_POSIX)
176 virtual bool ShouldUseZygote() OVERRIDE {
179 virtual int GetIpcFd() OVERRIDE {
185 #if defined(OS_POSIX)
190 void SetCloseOnExec(NaClHandle fd) {
191 #if defined(OS_POSIX)
192 int flags = fcntl(fd, F_GETFD);
194 int rc = fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
199 bool ShareHandleToSelLdr(
200 base::ProcessHandle processh,
203 std::vector<nacl::FileDescriptor> *handles_for_sel_ldr) {
206 int flags = DUPLICATE_SAME_ACCESS;
208 flags |= DUPLICATE_CLOSE_SOURCE;
209 if (!DuplicateHandle(GetCurrentProcess(),
210 reinterpret_cast<HANDLE>(sourceh),
213 0, // Unused given DUPLICATE_SAME_ACCESS.
216 LOG(ERROR) << "DuplicateHandle() failed";
219 handles_for_sel_ldr->push_back(
220 reinterpret_cast<nacl::FileDescriptor>(channel));
222 nacl::FileDescriptor channel;
223 channel.fd = sourceh;
224 channel.auto_close = close_source;
225 handles_for_sel_ldr->push_back(channel);
230 ppapi::PpapiPermissions GetNaClPermissions(uint32 permission_bits) {
231 // Only allow NaCl plugins to request certain permissions. We don't want
232 // a compromised renderer to be able to start a nacl plugin with e.g. Flash
233 // permissions which may expand the surface area of the sandbox.
234 uint32 masked_bits = permission_bits & ppapi::PERMISSION_DEV;
235 if (content::PluginService::GetInstance()->PpapiDevChannelSupported())
236 masked_bits |= ppapi::PERMISSION_DEV_CHANNEL;
237 return ppapi::PpapiPermissions::GetForCommandLine(masked_bits);
244 struct NaClProcessHost::NaClInternal {
245 NaClHandle socket_for_renderer;
246 NaClHandle socket_for_sel_ldr;
249 : socket_for_renderer(NACL_INVALID_HANDLE),
250 socket_for_sel_ldr(NACL_INVALID_HANDLE) { }
253 // -----------------------------------------------------------------------------
255 unsigned NaClProcessHost::keepalive_throttle_interval_milliseconds_ =
256 ppapi::kKeepaliveThrottleIntervalDefaultMilliseconds;
258 NaClProcessHost::NaClProcessHost(const GURL& manifest_url,
260 uint32 permission_bits,
262 bool uses_nonsfi_mode,
263 bool enable_dyncode_syscalls,
264 bool enable_exception_handling,
265 bool enable_crash_throttling,
267 const base::FilePath& profile_directory)
268 : manifest_url_(manifest_url),
269 permissions_(GetNaClPermissions(permission_bits)),
271 process_launched_by_broker_(false),
275 debug_exception_handler_requested_(false),
277 internal_(new NaClInternal()),
280 uses_nonsfi_mode_(uses_nonsfi_mode),
281 enable_debug_stub_(false),
282 enable_dyncode_syscalls_(enable_dyncode_syscalls),
283 enable_exception_handling_(enable_exception_handling),
284 enable_crash_throttling_(enable_crash_throttling),
285 off_the_record_(off_the_record),
286 profile_directory_(profile_directory),
287 render_view_id_(render_view_id) {
288 process_.reset(content::BrowserChildProcessHost::Create(
289 PROCESS_TYPE_NACL_LOADER, this));
291 // Set the display name so the user knows what plugin the process is running.
292 // We aren't on the UI thread so getting the pref locale for language
293 // formatting isn't possible, so IDN will be lost, but this is probably OK
294 // for this use case.
295 process_->SetName(net::FormatUrl(manifest_url_, std::string()));
297 enable_debug_stub_ = CommandLine::ForCurrentProcess()->HasSwitch(
298 switches::kEnableNaClDebug);
301 NaClProcessHost::~NaClProcessHost() {
302 // Report exit status only if the process was successfully started.
303 if (process_->GetData().handle != base::kNullProcessHandle) {
305 process_->GetTerminationStatus(false /* known_dead */, &exit_code);
306 std::string message =
307 base::StringPrintf("NaCl process exited with status %i (0x%x)",
308 exit_code, exit_code);
309 if (exit_code == 0) {
312 LOG(ERROR) << message;
316 if (internal_->socket_for_renderer != NACL_INVALID_HANDLE) {
317 if (NaClClose(internal_->socket_for_renderer) != 0) {
318 NOTREACHED() << "NaClClose() failed";
322 if (internal_->socket_for_sel_ldr != NACL_INVALID_HANDLE) {
323 if (NaClClose(internal_->socket_for_sel_ldr) != 0) {
324 NOTREACHED() << "NaClClose() failed";
329 // The process failed to launch for some reason.
330 // Don't keep the renderer hanging.
331 reply_msg_->set_reply_error();
332 nacl_host_message_filter_->Send(reply_msg_);
335 if (process_launched_by_broker_) {
336 NaClBrokerService::GetInstance()->OnLoaderDied();
341 void NaClProcessHost::OnProcessCrashed(int exit_status) {
342 if (enable_crash_throttling_ &&
343 !CommandLine::ForCurrentProcess()->HasSwitch(
344 switches::kDisablePnaclCrashThrottling)) {
345 NaClBrowser::GetInstance()->OnProcessCrashed();
349 // This is called at browser startup.
351 void NaClProcessHost::EarlyStartup() {
352 NaClBrowser::GetInstance()->EarlyStartup();
353 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
354 // Open the IRT file early to make sure that it isn't replaced out from
355 // under us by autoupdate.
356 NaClBrowser::GetInstance()->EnsureIrtAvailable();
358 CommandLine* cmd = CommandLine::ForCurrentProcess();
359 UMA_HISTOGRAM_BOOLEAN(
361 !cmd->GetSwitchValuePath(switches::kNaClGdb).empty());
362 UMA_HISTOGRAM_BOOLEAN(
363 "NaCl.nacl-gdb-script",
364 !cmd->GetSwitchValuePath(switches::kNaClGdbScript).empty());
365 UMA_HISTOGRAM_BOOLEAN(
366 "NaCl.enable-nacl-debug",
367 cmd->HasSwitch(switches::kEnableNaClDebug));
368 std::string nacl_debug_mask =
369 cmd->GetSwitchValueASCII(switches::kNaClDebugMask);
370 // By default, exclude debugging SSH and the PNaCl translator.
371 // about::flags only allows empty flags as the default, so replace
372 // the empty setting with the default. To debug all apps, use a wild-card.
373 if (nacl_debug_mask.empty()) {
374 nacl_debug_mask = "!*://*/*ssh_client.nmf,chrome://pnacl-translator/*";
376 NaClBrowser::GetDelegate()->SetDebugPatterns(nacl_debug_mask);
380 void NaClProcessHost::SetPpapiKeepAliveThrottleForTesting(
381 unsigned milliseconds) {
382 keepalive_throttle_interval_milliseconds_ = milliseconds;
385 void NaClProcessHost::Launch(
386 NaClHostMessageFilter* nacl_host_message_filter,
387 IPC::Message* reply_msg,
388 const base::FilePath& manifest_path) {
389 nacl_host_message_filter_ = nacl_host_message_filter;
390 reply_msg_ = reply_msg;
391 manifest_path_ = manifest_path;
393 // Do not launch the requested NaCl module if NaCl is marked "unstable" due
394 // to too many crashes within a given time period.
395 if (enable_crash_throttling_ &&
396 !CommandLine::ForCurrentProcess()->HasSwitch(
397 switches::kDisablePnaclCrashThrottling) &&
398 NaClBrowser::GetInstance()->IsThrottled()) {
399 SendErrorToRenderer("Process creation was throttled due to excessive"
405 const CommandLine* cmd = CommandLine::ForCurrentProcess();
407 if (cmd->HasSwitch(switches::kEnableNaClDebug) &&
408 !cmd->HasSwitch(switches::kNoSandbox)) {
409 // We don't switch off sandbox automatically for security reasons.
410 SendErrorToRenderer("NaCl's GDB debug stub requires --no-sandbox flag"
411 " on Windows. See crbug.com/265624.");
416 if (cmd->HasSwitch(switches::kNaClGdb) &&
417 !cmd->HasSwitch(switches::kEnableNaClDebug)) {
418 LOG(WARNING) << "--nacl-gdb flag requires --enable-nacl-debug flag";
421 // Start getting the IRT open asynchronously while we launch the NaCl process.
422 // We'll make sure this actually finished in StartWithLaunchedProcess, below.
423 NaClBrowser* nacl_browser = NaClBrowser::GetInstance();
424 nacl_browser->EnsureAllResourcesAvailable();
425 if (!nacl_browser->IsOk()) {
426 SendErrorToRenderer("could not find all the resources needed"
427 " to launch the process");
432 if (uses_nonsfi_mode_) {
433 #if defined(OS_LINUX)
434 const bool kNonSFIModeSupported = true;
436 const bool kNonSFIModeSupported = false;
438 if (!kNonSFIModeSupported ||
439 !cmd->HasSwitch(switches::kEnableNaClNonSfiMode)) {
440 SendErrorToRenderer("NaCl non-SFI mode works only on Linux with"
441 " --enable-nacl-nonsfi-mode specified");
447 // Rather than creating a socket pair in the renderer, and passing
448 // one side through the browser to sel_ldr, socket pairs are created
449 // in the browser and then passed to the renderer and sel_ldr.
451 // This is mainly for the benefit of Windows, where sockets cannot
452 // be passed in messages, but are copied via DuplicateHandle().
453 // This means the sandboxed renderer cannot send handles to the
457 // Create a connected socket
458 if (NaClSocketPair(pair) == -1) {
459 SendErrorToRenderer("NaClSocketPair() failed");
463 internal_->socket_for_renderer = pair[0];
464 internal_->socket_for_sel_ldr = pair[1];
465 SetCloseOnExec(pair[0]);
466 SetCloseOnExec(pair[1]);
468 // Launch the process
469 if (!LaunchSelLdr()) {
474 void NaClProcessHost::OnChannelConnected(int32 peer_pid) {
475 if (!CommandLine::ForCurrentProcess()->GetSwitchValuePath(
476 switches::kNaClGdb).empty()) {
482 void NaClProcessHost::OnProcessLaunchedByBroker(base::ProcessHandle handle) {
483 process_launched_by_broker_ = true;
484 process_->SetHandle(handle);
485 if (!StartWithLaunchedProcess())
489 void NaClProcessHost::OnDebugExceptionHandlerLaunchedByBroker(bool success) {
490 IPC::Message* reply = attach_debug_exception_handler_reply_msg_.release();
491 NaClProcessMsg_AttachDebugExceptionHandler::WriteReplyParams(reply, success);
496 // Needed to handle sync messages in OnMessageReceived.
497 bool NaClProcessHost::Send(IPC::Message* msg) {
498 return process_->Send(msg);
501 bool NaClProcessHost::LaunchNaClGdb() {
503 base::FilePath nacl_gdb =
504 CommandLine::ForCurrentProcess()->GetSwitchValuePath(switches::kNaClGdb);
505 CommandLine cmd_line(nacl_gdb);
507 CommandLine::StringType nacl_gdb =
508 CommandLine::ForCurrentProcess()->GetSwitchValueNative(
510 CommandLine::StringVector argv;
511 // We don't support spaces inside arguments in --nacl-gdb switch.
512 base::SplitString(nacl_gdb, static_cast<CommandLine::CharType>(' '), &argv);
513 CommandLine cmd_line(argv);
515 cmd_line.AppendArg("--eval-command");
516 base::FilePath::StringType irt_path(
517 NaClBrowser::GetInstance()->GetIrtFilePath().value());
518 // Avoid back slashes because nacl-gdb uses posix escaping rules on Windows.
519 // See issue https://code.google.com/p/nativeclient/issues/detail?id=3482.
520 std::replace(irt_path.begin(), irt_path.end(), '\\', '/');
521 cmd_line.AppendArgNative(FILE_PATH_LITERAL("nacl-irt \"") + irt_path +
522 FILE_PATH_LITERAL("\""));
523 if (!manifest_path_.empty()) {
524 cmd_line.AppendArg("--eval-command");
525 base::FilePath::StringType manifest_path_value(manifest_path_.value());
526 std::replace(manifest_path_value.begin(), manifest_path_value.end(),
528 cmd_line.AppendArgNative(FILE_PATH_LITERAL("nacl-manifest \"") +
529 manifest_path_value + FILE_PATH_LITERAL("\""));
531 cmd_line.AppendArg("--eval-command");
532 cmd_line.AppendArg("target remote :4014");
533 base::FilePath script = CommandLine::ForCurrentProcess()->GetSwitchValuePath(
534 switches::kNaClGdbScript);
535 if (!script.empty()) {
536 cmd_line.AppendArg("--command");
537 cmd_line.AppendArgNative(script.value());
539 return base::LaunchProcess(cmd_line, base::LaunchOptions(), NULL);
542 bool NaClProcessHost::LaunchSelLdr() {
543 std::string channel_id = process_->GetHost()->CreateChannel();
544 if (channel_id.empty()) {
545 SendErrorToRenderer("CreateChannel() failed");
549 // Build command line for nacl.
551 #if defined(OS_MACOSX)
552 // The Native Client process needs to be able to allocate a 1GB contiguous
553 // region to use as the client environment's virtual address space. ASLR
554 // (PIE) interferes with this by making it possible that no gap large enough
555 // to accomodate this request will exist in the child process' address
556 // space. Disable PIE for NaCl processes. See http://crbug.com/90221 and
557 // http://code.google.com/p/nativeclient/issues/detail?id=2043.
558 int flags = ChildProcessHost::CHILD_NO_PIE;
559 #elif defined(OS_LINUX)
560 int flags = ChildProcessHost::CHILD_ALLOW_SELF;
562 int flags = ChildProcessHost::CHILD_NORMAL;
565 base::FilePath exe_path = ChildProcessHost::GetChildPath(flags);
566 if (exe_path.empty())
570 // On Windows 64-bit NaCl loader is called nacl64.exe instead of chrome.exe
571 if (RunningOnWOW64()) {
572 if (!NaClBrowser::GetInstance()->GetNaCl64ExePath(&exe_path)) {
573 SendErrorToRenderer("could not get path to nacl64.exe");
578 // When using the DLL CRT on Windows, we need to amend the PATH to include
579 // the location of the x64 CRT DLLs. This is only the case when using a
580 // component=shared_library build (i.e. generally dev debug builds). The
581 // x86 CRT DLLs are in e.g. out\Debug for chrome.exe etc., so the x64 ones
582 // are put in out\Debug\x64 which we add to the PATH here so that loader
583 // can find them. See http://crbug.com/346034.
584 scoped_ptr<base::Environment> env(base::Environment::Create());
585 static const char kPath[] = "PATH";
586 std::string old_path;
587 base::FilePath module_path;
588 if (!PathService::Get(base::FILE_MODULE, &module_path)) {
589 SendErrorToRenderer("could not get path to current module");
592 std::string x64_crt_path =
593 base::WideToUTF8(module_path.DirName().Append(L"x64").value());
594 if (!env->GetVar(kPath, &old_path)) {
595 env->SetVar(kPath, x64_crt_path);
596 } else if (!IsInPath(old_path, x64_crt_path)) {
597 std::string new_path(old_path);
598 new_path.append(";");
599 new_path.append(x64_crt_path);
600 env->SetVar(kPath, new_path);
606 scoped_ptr<CommandLine> cmd_line(new CommandLine(exe_path));
607 CopyNaClCommandLineArguments(cmd_line.get());
609 cmd_line->AppendSwitchASCII(switches::kProcessType,
611 switches::kNaClLoaderNonSfiProcess :
612 switches::kNaClLoaderProcess));
613 cmd_line->AppendSwitchASCII(switches::kProcessChannelID, channel_id);
614 if (NaClBrowser::GetDelegate()->DialogsAreSuppressed())
615 cmd_line->AppendSwitch(switches::kNoErrorDialogs);
617 // On Windows we might need to start the broker process to launch a new loader
619 if (RunningOnWOW64()) {
620 if (!NaClBrokerService::GetInstance()->LaunchLoader(
621 weak_factory_.GetWeakPtr(), channel_id)) {
622 SendErrorToRenderer("broker service did not launch process");
629 new NaClSandboxedProcessLauncherDelegate(process_->GetHost()),
634 bool NaClProcessHost::OnMessageReceived(const IPC::Message& msg) {
636 if (uses_nonsfi_mode_) {
637 // IPC messages relating to NaCl's validation cache must not be exposed
638 // in Non-SFI Mode, otherwise a Non-SFI nexe could use
639 // SetKnownToValidate to create a hole in the SFI sandbox.
640 IPC_BEGIN_MESSAGE_MAP(NaClProcessHost, msg)
641 IPC_MESSAGE_HANDLER(NaClProcessHostMsg_PpapiChannelsCreated,
642 OnPpapiChannelsCreated)
643 IPC_MESSAGE_UNHANDLED(handled = false)
644 IPC_END_MESSAGE_MAP()
646 IPC_BEGIN_MESSAGE_MAP(NaClProcessHost, msg)
647 IPC_MESSAGE_HANDLER(NaClProcessMsg_QueryKnownToValidate,
648 OnQueryKnownToValidate)
649 IPC_MESSAGE_HANDLER(NaClProcessMsg_SetKnownToValidate,
650 OnSetKnownToValidate)
651 IPC_MESSAGE_HANDLER_DELAY_REPLY(NaClProcessMsg_ResolveFileToken,
654 IPC_MESSAGE_HANDLER_DELAY_REPLY(
655 NaClProcessMsg_AttachDebugExceptionHandler,
656 OnAttachDebugExceptionHandler)
658 IPC_MESSAGE_HANDLER(NaClProcessHostMsg_PpapiChannelsCreated,
659 OnPpapiChannelsCreated)
660 IPC_MESSAGE_UNHANDLED(handled = false)
661 IPC_END_MESSAGE_MAP()
666 void NaClProcessHost::OnProcessLaunched() {
667 if (!StartWithLaunchedProcess())
671 // Called when the NaClBrowser singleton has been fully initialized.
672 void NaClProcessHost::OnResourcesReady() {
673 NaClBrowser* nacl_browser = NaClBrowser::GetInstance();
674 if (!nacl_browser->IsReady()) {
675 SendErrorToRenderer("could not acquire shared resources needed by NaCl");
677 } else if (!StartNaClExecution()) {
682 bool NaClProcessHost::ReplyToRenderer(
683 const IPC::ChannelHandle& ppapi_channel_handle,
684 const IPC::ChannelHandle& trusted_channel_handle,
685 const IPC::ChannelHandle& manifest_service_channel_handle) {
687 // If we are on 64-bit Windows, the NaCl process's sandbox is
688 // managed by a different process from the renderer's sandbox. We
689 // need to inform the renderer's sandbox about the NaCl process so
690 // that the renderer can send handles to the NaCl process using
691 // BrokerDuplicateHandle().
692 if (RunningOnWOW64()) {
693 if (!content::BrokerAddTargetPeer(process_->GetData().handle)) {
694 SendErrorToRenderer("BrokerAddTargetPeer() failed");
700 FileDescriptor imc_handle_for_renderer;
702 // Copy the handle into the renderer process.
703 HANDLE handle_in_renderer;
704 if (!DuplicateHandle(base::GetCurrentProcessHandle(),
705 reinterpret_cast<HANDLE>(
706 internal_->socket_for_renderer),
707 nacl_host_message_filter_->PeerHandle(),
709 0, // Unused given DUPLICATE_SAME_ACCESS.
711 DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS)) {
712 SendErrorToRenderer("DuplicateHandle() failed");
715 imc_handle_for_renderer = reinterpret_cast<FileDescriptor>(
718 // No need to dup the imc_handle - we don't pass it anywhere else so
719 // it cannot be closed.
720 FileDescriptor imc_handle;
721 imc_handle.fd = internal_->socket_for_renderer;
722 imc_handle.auto_close = true;
723 imc_handle_for_renderer = imc_handle;
726 const ChildProcessData& data = process_->GetData();
727 SendMessageToRenderer(
728 NaClLaunchResult(imc_handle_for_renderer,
729 ppapi_channel_handle,
730 trusted_channel_handle,
731 manifest_service_channel_handle,
732 base::GetProcId(data.handle),
734 std::string() /* error_message */);
735 internal_->socket_for_renderer = NACL_INVALID_HANDLE;
739 void NaClProcessHost::SendErrorToRenderer(const std::string& error_message) {
740 LOG(ERROR) << "NaCl process launch failed: " << error_message;
741 SendMessageToRenderer(NaClLaunchResult(), error_message);
744 void NaClProcessHost::SendMessageToRenderer(
745 const NaClLaunchResult& result,
746 const std::string& error_message) {
747 DCHECK(nacl_host_message_filter_);
749 if (nacl_host_message_filter_ != NULL && reply_msg_ != NULL) {
750 NaClHostMsg_LaunchNaCl::WriteReplyParams(
751 reply_msg_, result, error_message);
752 nacl_host_message_filter_->Send(reply_msg_);
753 nacl_host_message_filter_ = NULL;
758 // TCP port we chose for NaCl debug stub. It can be any other number.
759 static const int kInitialDebugStubPort = 4014;
761 #if defined(OS_POSIX)
762 net::SocketDescriptor NaClProcessHost::GetDebugStubSocketHandle() {
763 NaClBrowser* nacl_browser = NaClBrowser::GetInstance();
764 net::SocketDescriptor s = net::kInvalidSocket;
765 // We always try to allocate the default port first. If this fails, we then
766 // allocate any available port.
767 // On success, if the test system has register a handler
768 // (GdbDebugStubPortListener), we fire a notification.
769 int port = kInitialDebugStubPort;
770 s = net::TCPListenSocket::CreateAndBind("127.0.0.1", port);
771 if (s == net::kInvalidSocket) {
772 s = net::TCPListenSocket::CreateAndBindAnyPort("127.0.0.1", &port);
774 if (s != net::kInvalidSocket) {
775 if (nacl_browser->HasGdbDebugStubPortListener()) {
776 nacl_browser->FireGdbDebugStubPortOpened(port);
779 // Set debug stub port on the process object.
780 process_->SetNaClDebugStubPort(port);
781 if (s == net::kInvalidSocket) {
782 LOG(ERROR) << "failed to open socket for debug stub";
783 return net::kInvalidSocket;
785 LOG(WARNING) << "debug stub on port " << port;
788 LOG(ERROR) << "listen() failed on debug stub socket";
789 if (IGNORE_EINTR(close(s)) < 0)
790 PLOG(ERROR) << "failed to close debug stub socket";
791 return net::kInvalidSocket;
797 bool NaClProcessHost::StartNaClExecution() {
798 NaClBrowser* nacl_browser = NaClBrowser::GetInstance();
800 NaClStartParams params;
801 // Enable PPAPI proxy channel creation only for renderer processes.
802 params.enable_ipc_proxy = enable_ppapi_proxy();
803 if (!uses_nonsfi_mode_) {
804 params.validation_cache_enabled = nacl_browser->ValidationCacheIsEnabled();
805 params.validation_cache_key = nacl_browser->GetValidationCacheKey();
806 params.version = NaClBrowser::GetDelegate()->GetVersionString();
807 params.enable_exception_handling = enable_exception_handling_;
808 params.enable_debug_stub = enable_debug_stub_ &&
809 NaClBrowser::GetDelegate()->URLMatchesDebugPatterns(manifest_url_);
810 params.uses_irt = uses_irt_;
811 params.enable_dyncode_syscalls = enable_dyncode_syscalls_;
814 const ChildProcessData& data = process_->GetData();
815 if (!ShareHandleToSelLdr(data.handle,
816 internal_->socket_for_sel_ldr, true,
821 if (params.uses_irt) {
822 const base::File& irt_file = nacl_browser->IrtFile();
823 CHECK(irt_file.IsValid());
824 // Send over the IRT file handle. We don't close our own copy!
825 if (!ShareHandleToSelLdr(data.handle, irt_file.GetPlatformFile(), false,
831 #if defined(OS_MACOSX)
832 // For dynamic loading support, NaCl requires a file descriptor that
833 // was created in /tmp, since those created with shm_open() are not
834 // mappable with PROT_EXEC. Rather than requiring an extra IPC
835 // round trip out of the sandbox, we create an FD here.
836 base::SharedMemory memory_buffer;
837 base::SharedMemoryCreateOptions options;
839 options.executable = true;
840 if (!memory_buffer.Create(options)) {
841 DLOG(ERROR) << "Failed to allocate memory buffer";
844 FileDescriptor memory_fd;
845 memory_fd.fd = dup(memory_buffer.handle().fd);
846 if (memory_fd.fd < 0) {
847 DLOG(ERROR) << "Failed to dup() a file descriptor";
850 memory_fd.auto_close = true;
851 params.handles.push_back(memory_fd);
854 #if defined(OS_POSIX)
855 if (params.enable_debug_stub) {
856 net::SocketDescriptor server_bound_socket = GetDebugStubSocketHandle();
857 if (server_bound_socket != net::kInvalidSocket) {
858 params.debug_stub_server_bound_socket =
859 FileDescriptor(server_bound_socket, true);
864 process_->Send(new NaClProcessMsg_Start(params));
866 internal_->socket_for_sel_ldr = NACL_INVALID_HANDLE;
870 // This method is called when NaClProcessHostMsg_PpapiChannelCreated is
872 void NaClProcessHost::OnPpapiChannelsCreated(
873 const IPC::ChannelHandle& browser_channel_handle,
874 const IPC::ChannelHandle& ppapi_renderer_channel_handle,
875 const IPC::ChannelHandle& trusted_renderer_channel_handle,
876 const IPC::ChannelHandle& manifest_service_channel_handle) {
877 if (!enable_ppapi_proxy()) {
878 ReplyToRenderer(IPC::ChannelHandle(),
879 trusted_renderer_channel_handle,
880 manifest_service_channel_handle);
884 if (!ipc_proxy_channel_.get()) {
885 DCHECK_EQ(PROCESS_TYPE_NACL_LOADER, process_->GetData().process_type);
887 ipc_proxy_channel_.reset(
888 new IPC::ChannelProxy(browser_channel_handle,
889 IPC::Channel::MODE_CLIENT,
891 base::MessageLoopProxy::current().get()));
892 // Create the browser ppapi host and enable PPAPI message dispatching to the
894 ppapi_host_.reset(content::BrowserPpapiHost::CreateExternalPluginProcess(
895 ipc_proxy_channel_.get(), // sender
897 process_->GetData().handle,
898 ipc_proxy_channel_.get(),
899 nacl_host_message_filter_->render_process_id(),
901 profile_directory_));
902 ppapi_host_->SetOnKeepaliveCallback(
903 NaClBrowser::GetDelegate()->GetOnKeepaliveCallback());
905 ppapi::PpapiNaClPluginArgs args;
906 args.off_the_record = nacl_host_message_filter_->off_the_record();
907 args.permissions = permissions_;
908 args.keepalive_throttle_interval_milliseconds =
909 keepalive_throttle_interval_milliseconds_;
910 CommandLine* cmdline = CommandLine::ForCurrentProcess();
912 std::string flag_whitelist[] = {
916 for (size_t i = 0; i < arraysize(flag_whitelist); ++i) {
917 std::string value = cmdline->GetSwitchValueASCII(flag_whitelist[i]);
918 if (!value.empty()) {
919 args.switch_names.push_back(flag_whitelist[i]);
920 args.switch_values.push_back(value);
924 ppapi_host_->GetPpapiHost()->AddHostFactoryFilter(
925 scoped_ptr<ppapi::host::HostFactory>(
926 NaClBrowser::GetDelegate()->CreatePpapiHostFactory(
927 ppapi_host_.get())));
929 // Send a message to initialize the IPC dispatchers in the NaCl plugin.
930 ipc_proxy_channel_->Send(new PpapiMsg_InitializeNaClDispatcher(args));
932 // Let the renderer know that the IPC channels are established.
933 ReplyToRenderer(ppapi_renderer_channel_handle,
934 trusted_renderer_channel_handle,
935 manifest_service_channel_handle);
937 // Attempt to open more than 1 browser channel is not supported.
938 // Shut down the NaCl process.
939 process_->GetHost()->ForceShutdown();
943 bool NaClProcessHost::StartWithLaunchedProcess() {
944 NaClBrowser* nacl_browser = NaClBrowser::GetInstance();
946 if (nacl_browser->IsReady()) {
947 return StartNaClExecution();
948 } else if (nacl_browser->IsOk()) {
949 nacl_browser->WaitForResources(
950 base::Bind(&NaClProcessHost::OnResourcesReady,
951 weak_factory_.GetWeakPtr()));
954 SendErrorToRenderer("previously failed to acquire shared resources");
959 void NaClProcessHost::OnQueryKnownToValidate(const std::string& signature,
961 CHECK(!uses_nonsfi_mode_);
962 NaClBrowser* nacl_browser = NaClBrowser::GetInstance();
963 *result = nacl_browser->QueryKnownToValidate(signature, off_the_record_);
966 void NaClProcessHost::OnSetKnownToValidate(const std::string& signature) {
967 CHECK(!uses_nonsfi_mode_);
968 NaClBrowser::GetInstance()->SetKnownToValidate(
969 signature, off_the_record_);
972 void NaClProcessHost::FileResolved(
973 const base::FilePath& file_path,
974 IPC::Message* reply_msg,
976 if (file.IsValid()) {
977 IPC::PlatformFileForTransit handle = IPC::TakeFileHandleForProcess(
979 process_->GetData().handle);
980 NaClProcessMsg_ResolveFileToken::WriteReplyParams(
985 NaClProcessMsg_ResolveFileToken::WriteReplyParams(
987 IPC::InvalidPlatformFileForTransit(),
993 void NaClProcessHost::OnResolveFileToken(uint64 file_token_lo,
994 uint64 file_token_hi,
995 IPC::Message* reply_msg) {
996 // Was the file registered?
998 // Note that the file path cache is of bounded size, and old entries can get
999 // evicted. If a large number of NaCl modules are being launched at once,
1000 // resolving the file_token may fail because the path cache was thrashed
1001 // while the file_token was in flight. In this case the query fails, and we
1002 // need to fall back to the slower path.
1004 // However: each NaCl process will consume 2-3 entries as it starts up, this
1005 // means that eviction will not happen unless you start up 33+ NaCl processes
1006 // at the same time, and this still requires worst-case timing. As a
1007 // practical matter, no entries should be evicted prematurely.
1008 // The cache itself should take ~ (150 characters * 2 bytes/char + ~60 bytes
1009 // data structure overhead) * 100 = 35k when full, so making it bigger should
1010 // not be a problem, if needed.
1012 // Each NaCl process will consume 2-3 entries because the manifest and main
1013 // nexe are currently not resolved. Shared libraries will be resolved. They
1014 // will be loaded sequentially, so they will only consume a single entry
1015 // while the load is in flight.
1017 // TODO(ncbray): track behavior with UMA. If entries are getting evicted or
1018 // bogus keys are getting queried, this would be good to know.
1019 CHECK(!uses_nonsfi_mode_);
1020 base::FilePath file_path;
1021 if (!NaClBrowser::GetInstance()->GetFilePath(
1022 file_token_lo, file_token_hi, &file_path)) {
1023 NaClProcessMsg_ResolveFileToken::WriteReplyParams(
1025 IPC::InvalidPlatformFileForTransit(),
1032 if (!base::PostTaskAndReplyWithResult(
1033 content::BrowserThread::GetBlockingPool(),
1035 base::Bind(OpenNaClExecutableImpl, file_path),
1036 base::Bind(&NaClProcessHost::FileResolved,
1037 weak_factory_.GetWeakPtr(),
1040 NaClProcessMsg_ResolveFileToken::WriteReplyParams(
1042 IPC::InvalidPlatformFileForTransit(),
1049 void NaClProcessHost::OnAttachDebugExceptionHandler(const std::string& info,
1050 IPC::Message* reply_msg) {
1051 CHECK(!uses_nonsfi_mode_);
1052 if (!AttachDebugExceptionHandler(info, reply_msg)) {
1053 // Send failure message.
1054 NaClProcessMsg_AttachDebugExceptionHandler::WriteReplyParams(reply_msg,
1060 bool NaClProcessHost::AttachDebugExceptionHandler(const std::string& info,
1061 IPC::Message* reply_msg) {
1062 if (!enable_exception_handling_ && !enable_debug_stub_) {
1064 "Debug exception handler requested by NaCl process when not enabled";
1067 if (debug_exception_handler_requested_) {
1068 // The NaCl process should not request this multiple times.
1069 DLOG(ERROR) << "Multiple AttachDebugExceptionHandler requests received";
1072 debug_exception_handler_requested_ = true;
1074 base::ProcessId nacl_pid = base::GetProcId(process_->GetData().handle);
1075 base::ProcessHandle temp_handle;
1076 // We cannot use process_->GetData().handle because it does not have
1077 // the necessary access rights. We open the new handle here rather
1078 // than in the NaCl broker process in case the NaCl loader process
1079 // dies before the NaCl broker process receives the message we send.
1080 // The debug exception handler uses DebugActiveProcess() to attach,
1081 // but this takes a PID. We need to prevent the NaCl loader's PID
1082 // from being reused before DebugActiveProcess() is called, and
1083 // holding a process handle open achieves this.
1084 if (!base::OpenProcessHandleWithAccess(
1086 base::kProcessAccessQueryInformation |
1087 base::kProcessAccessSuspendResume |
1088 base::kProcessAccessTerminate |
1089 base::kProcessAccessVMOperation |
1090 base::kProcessAccessVMRead |
1091 base::kProcessAccessVMWrite |
1092 base::kProcessAccessDuplicateHandle |
1093 base::kProcessAccessWaitForTermination,
1095 LOG(ERROR) << "Failed to get process handle";
1098 base::win::ScopedHandle process_handle(temp_handle);
1100 attach_debug_exception_handler_reply_msg_.reset(reply_msg);
1101 // If the NaCl loader is 64-bit, the process running its debug
1102 // exception handler must be 64-bit too, so we use the 64-bit NaCl
1103 // broker process for this. Otherwise, on a 32-bit system, we use
1104 // the 32-bit browser process to run the debug exception handler.
1105 if (RunningOnWOW64()) {
1106 return NaClBrokerService::GetInstance()->LaunchDebugExceptionHandler(
1107 weak_factory_.GetWeakPtr(), nacl_pid, process_handle, info);
1109 NaClStartDebugExceptionHandlerThread(
1110 process_handle.Take(), info,
1111 base::MessageLoopProxy::current(),
1112 base::Bind(&NaClProcessHost::OnDebugExceptionHandlerLaunchedByBroker,
1113 weak_factory_.GetWeakPtr()));