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/files/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_browser_delegate.h"
31 #include "components/nacl/browser/nacl_host_message_filter.h"
32 #include "components/nacl/common/nacl_cmd_line.h"
33 #include "components/nacl/common/nacl_host_messages.h"
34 #include "components/nacl/common/nacl_messages.h"
35 #include "components/nacl/common/nacl_process_type.h"
36 #include "components/nacl/common/nacl_switches.h"
37 #include "content/public/browser/browser_child_process_host.h"
38 #include "content/public/browser/browser_ppapi_host.h"
39 #include "content/public/browser/child_process_data.h"
40 #include "content/public/browser/plugin_service.h"
41 #include "content/public/browser/render_process_host.h"
42 #include "content/public/browser/web_contents.h"
43 #include "content/public/common/child_process_host.h"
44 #include "content/public/common/content_switches.h"
45 #include "content/public/common/process_type.h"
46 #include "content/public/common/sandboxed_process_launcher_delegate.h"
47 #include "ipc/ipc_channel.h"
48 #include "ipc/ipc_switches.h"
49 #include "native_client/src/public/nacl_file_info.h"
50 #include "native_client/src/shared/imc/nacl_imc_c.h"
51 #include "net/base/net_util.h"
52 #include "net/socket/tcp_listen_socket.h"
53 #include "ppapi/host/host_factory.h"
54 #include "ppapi/host/ppapi_host.h"
55 #include "ppapi/proxy/ppapi_messages.h"
56 #include "ppapi/shared_impl/ppapi_constants.h"
57 #include "ppapi/shared_impl/ppapi_nacl_plugin_args.h"
63 #include "ipc/ipc_channel_posix.h"
67 #include "base/threading/thread.h"
68 #include "base/win/scoped_handle.h"
69 #include "components/nacl/browser/nacl_broker_service_win.h"
70 #include "components/nacl/common/nacl_debug_exception_handler_win.h"
71 #include "content/public/common/sandbox_init.h"
74 using content::BrowserThread
;
75 using content::ChildProcessData
;
76 using content::ChildProcessHost
;
77 using ppapi::proxy::SerializedHandle
;
84 // Looks for the largest contiguous unallocated region of address
85 // space and returns it via |*out_addr| and |*out_size|.
86 void FindAddressSpace(base::ProcessHandle process
,
87 char** out_addr
, size_t* out_size
) {
92 MEMORY_BASIC_INFORMATION info
;
93 size_t result
= VirtualQueryEx(process
, static_cast<void*>(addr
),
95 if (result
< sizeof(info
))
97 if (info
.State
== MEM_FREE
&& info
.RegionSize
> *out_size
) {
99 *out_size
= info
.RegionSize
;
101 addr
+= info
.RegionSize
;
107 bool IsInPath(const std::string
& path_env_var
, const std::string
& dir
) {
108 std::vector
<std::string
> split
;
109 base::SplitString(path_env_var
, ';', &split
);
110 for (std::vector
<std::string
>::const_iterator
i(split
.begin());
123 // Allocates |size| bytes of address space in the given process at a
124 // randomised address.
125 void* AllocateAddressSpaceASLR(base::ProcessHandle process
, size_t size
) {
128 FindAddressSpace(process
, &addr
, &avail_size
);
129 if (avail_size
< size
)
131 size_t offset
= base::RandGenerator(avail_size
- size
);
132 const int kPageSize
= 0x10000;
134 reinterpret_cast<void*>(reinterpret_cast<uint64
>(addr
+ offset
)
136 return VirtualAllocEx(process
, request_addr
, size
,
137 MEM_RESERVE
, PAGE_NOACCESS
);
142 bool RunningOnWOW64() {
143 return (base::win::OSInfo::GetInstance()->wow64_status() ==
144 base::win::OSInfo::WOW64_ENABLED
);
149 #endif // defined(OS_WIN)
153 // NOTE: changes to this class need to be reviewed by the security team.
154 class NaClSandboxedProcessLauncherDelegate
155 : public content::SandboxedProcessLauncherDelegate
{
157 NaClSandboxedProcessLauncherDelegate(ChildProcessHost
* host
)
158 #if defined(OS_POSIX)
159 : ipc_fd_(host
->TakeClientFileDescriptor())
163 ~NaClSandboxedProcessLauncherDelegate() override
{}
166 virtual void PostSpawnTarget(base::ProcessHandle process
) {
167 // For Native Client sel_ldr processes on 32-bit Windows, reserve 1 GB of
168 // address space to prevent later failure due to address space fragmentation
169 // from .dll loading. The NaCl process will attempt to locate this space by
170 // scanning the address space using VirtualQuery.
171 // TODO(bbudge) Handle the --no-sandbox case.
172 // http://code.google.com/p/nativeclient/issues/detail?id=2131
173 const SIZE_T kNaClSandboxSize
= 1 << 30;
174 if (!nacl::AllocateAddressSpaceASLR(process
, kNaClSandboxSize
)) {
175 DLOG(WARNING
) << "Failed to reserve address space for Native Client";
178 #elif defined(OS_POSIX)
179 bool ShouldUseZygote() override
{ return true; }
180 base::ScopedFD
TakeIpcFd() override
{ return ipc_fd_
.Pass(); }
184 #if defined(OS_POSIX)
185 base::ScopedFD ipc_fd_
;
189 void SetCloseOnExec(NaClHandle fd
) {
190 #if defined(OS_POSIX)
191 int flags
= fcntl(fd
, F_GETFD
);
193 int rc
= fcntl(fd
, F_SETFD
, flags
| FD_CLOEXEC
);
198 bool ShareHandleToSelLdr(
199 base::ProcessHandle processh
,
202 std::vector
<nacl::FileDescriptor
> *handles_for_sel_ldr
) {
205 int flags
= DUPLICATE_SAME_ACCESS
;
207 flags
|= DUPLICATE_CLOSE_SOURCE
;
208 if (!DuplicateHandle(GetCurrentProcess(),
209 reinterpret_cast<HANDLE
>(sourceh
),
212 0, // Unused given DUPLICATE_SAME_ACCESS.
215 LOG(ERROR
) << "DuplicateHandle() failed";
218 handles_for_sel_ldr
->push_back(
219 reinterpret_cast<nacl::FileDescriptor
>(channel
));
221 nacl::FileDescriptor channel
;
222 channel
.fd
= sourceh
;
223 channel
.auto_close
= close_source
;
224 handles_for_sel_ldr
->push_back(channel
);
229 void CloseFile(base::File file
) {
230 // The base::File destructor will close the file for us.
235 unsigned NaClProcessHost::keepalive_throttle_interval_milliseconds_
=
236 ppapi::kKeepaliveThrottleIntervalDefaultMilliseconds
;
238 NaClProcessHost::NaClProcessHost(const GURL
& manifest_url
,
239 base::File nexe_file
,
240 const NaClFileToken
& nexe_token
,
241 ppapi::PpapiPermissions permissions
,
243 uint32 permission_bits
,
244 bool uses_nonsfi_mode
,
246 NaClAppProcessType process_type
,
247 const base::FilePath
& profile_directory
)
248 : manifest_url_(manifest_url
),
249 nexe_file_(nexe_file
.Pass()),
250 nexe_token_(nexe_token
),
251 permissions_(permissions
),
253 process_launched_by_broker_(false),
257 debug_exception_handler_requested_(false),
259 uses_nonsfi_mode_(uses_nonsfi_mode
),
260 enable_debug_stub_(false),
261 enable_crash_throttling_(false),
262 off_the_record_(off_the_record
),
263 process_type_(process_type
),
264 profile_directory_(profile_directory
),
265 render_view_id_(render_view_id
),
266 weak_factory_(this) {
267 process_
.reset(content::BrowserChildProcessHost::Create(
268 PROCESS_TYPE_NACL_LOADER
, this));
270 // Set the display name so the user knows what plugin the process is running.
271 // We aren't on the UI thread so getting the pref locale for language
272 // formatting isn't possible, so IDN will be lost, but this is probably OK
273 // for this use case.
274 process_
->SetName(net::FormatUrl(manifest_url_
, std::string()));
276 enable_debug_stub_
= CommandLine::ForCurrentProcess()->HasSwitch(
277 switches::kEnableNaClDebug
);
278 DCHECK(process_type_
!= kUnknownNaClProcessType
);
279 enable_crash_throttling_
= process_type_
!= kNativeNaClProcessType
;
282 NaClProcessHost::~NaClProcessHost() {
283 // Report exit status only if the process was successfully started.
284 if (process_
->GetData().handle
!= base::kNullProcessHandle
) {
286 process_
->GetTerminationStatus(false /* known_dead */, &exit_code
);
287 std::string message
=
288 base::StringPrintf("NaCl process exited with status %i (0x%x)",
289 exit_code
, exit_code
);
290 if (exit_code
== 0) {
293 LOG(ERROR
) << message
;
295 NaClBrowser::GetInstance()->OnProcessEnd(process_
->GetData().id
);
299 // The process failed to launch for some reason.
300 // Don't keep the renderer hanging.
301 reply_msg_
->set_reply_error();
302 nacl_host_message_filter_
->Send(reply_msg_
);
305 if (process_launched_by_broker_
) {
306 NaClBrokerService::GetInstance()->OnLoaderDied();
311 void NaClProcessHost::OnProcessCrashed(int exit_status
) {
312 if (enable_crash_throttling_
&&
313 !CommandLine::ForCurrentProcess()->HasSwitch(
314 switches::kDisablePnaclCrashThrottling
)) {
315 NaClBrowser::GetInstance()->OnProcessCrashed();
319 // This is called at browser startup.
321 void NaClProcessHost::EarlyStartup() {
322 NaClBrowser::GetInstance()->EarlyStartup();
323 // Inform NaClBrowser that we exist and will have a debug port at some point.
324 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
325 // Open the IRT file early to make sure that it isn't replaced out from
326 // under us by autoupdate.
327 NaClBrowser::GetInstance()->EnsureIrtAvailable();
329 CommandLine
* cmd
= CommandLine::ForCurrentProcess();
330 UMA_HISTOGRAM_BOOLEAN(
332 !cmd
->GetSwitchValuePath(switches::kNaClGdb
).empty());
333 UMA_HISTOGRAM_BOOLEAN(
334 "NaCl.nacl-gdb-script",
335 !cmd
->GetSwitchValuePath(switches::kNaClGdbScript
).empty());
336 UMA_HISTOGRAM_BOOLEAN(
337 "NaCl.enable-nacl-debug",
338 cmd
->HasSwitch(switches::kEnableNaClDebug
));
339 std::string nacl_debug_mask
=
340 cmd
->GetSwitchValueASCII(switches::kNaClDebugMask
);
341 // By default, exclude debugging SSH and the PNaCl translator.
342 // about::flags only allows empty flags as the default, so replace
343 // the empty setting with the default. To debug all apps, use a wild-card.
344 if (nacl_debug_mask
.empty()) {
345 nacl_debug_mask
= "!*://*/*ssh_client.nmf,chrome://pnacl-translator/*";
347 NaClBrowser::GetDelegate()->SetDebugPatterns(nacl_debug_mask
);
351 void NaClProcessHost::SetPpapiKeepAliveThrottleForTesting(
352 unsigned milliseconds
) {
353 keepalive_throttle_interval_milliseconds_
= milliseconds
;
356 void NaClProcessHost::Launch(
357 NaClHostMessageFilter
* nacl_host_message_filter
,
358 IPC::Message
* reply_msg
,
359 const base::FilePath
& manifest_path
) {
360 nacl_host_message_filter_
= nacl_host_message_filter
;
361 reply_msg_
= reply_msg
;
362 manifest_path_
= manifest_path
;
364 // Do not launch the requested NaCl module if NaCl is marked "unstable" due
365 // to too many crashes within a given time period.
366 if (enable_crash_throttling_
&&
367 !CommandLine::ForCurrentProcess()->HasSwitch(
368 switches::kDisablePnaclCrashThrottling
) &&
369 NaClBrowser::GetInstance()->IsThrottled()) {
370 SendErrorToRenderer("Process creation was throttled due to excessive"
376 const CommandLine
* cmd
= CommandLine::ForCurrentProcess();
378 if (cmd
->HasSwitch(switches::kEnableNaClDebug
) &&
379 !cmd
->HasSwitch(switches::kNoSandbox
)) {
380 // We don't switch off sandbox automatically for security reasons.
381 SendErrorToRenderer("NaCl's GDB debug stub requires --no-sandbox flag"
382 " on Windows. See crbug.com/265624.");
387 if (cmd
->HasSwitch(switches::kNaClGdb
) &&
388 !cmd
->HasSwitch(switches::kEnableNaClDebug
)) {
389 LOG(WARNING
) << "--nacl-gdb flag requires --enable-nacl-debug flag";
392 // Start getting the IRT open asynchronously while we launch the NaCl process.
393 // We'll make sure this actually finished in StartWithLaunchedProcess, below.
394 NaClBrowser
* nacl_browser
= NaClBrowser::GetInstance();
395 nacl_browser
->EnsureAllResourcesAvailable();
396 if (!nacl_browser
->IsOk()) {
397 SendErrorToRenderer("could not find all the resources needed"
398 " to launch the process");
403 if (uses_nonsfi_mode_
) {
404 bool nonsfi_mode_forced_by_command_line
= false;
405 bool nonsfi_mode_allowed
= false;
406 #if defined(OS_LINUX)
407 nonsfi_mode_forced_by_command_line
=
408 cmd
->HasSwitch(switches::kEnableNaClNonSfiMode
);
409 #if defined(OS_CHROMEOS) && defined(ARCH_CPU_ARMEL)
410 nonsfi_mode_allowed
= NaClBrowser::GetDelegate()->IsNonSfiModeAllowed(
411 nacl_host_message_filter
->profile_directory(), manifest_url_
);
414 bool nonsfi_mode_enabled
=
415 nonsfi_mode_forced_by_command_line
|| nonsfi_mode_allowed
;
417 if (!nonsfi_mode_enabled
) {
419 "NaCl non-SFI mode is not available for this platform"
420 " and NaCl module.");
425 // Rather than creating a socket pair in the renderer, and passing
426 // one side through the browser to sel_ldr, socket pairs are created
427 // in the browser and then passed to the renderer and sel_ldr.
429 // This is mainly for the benefit of Windows, where sockets cannot
430 // be passed in messages, but are copied via DuplicateHandle().
431 // This means the sandboxed renderer cannot send handles to the
435 // Create a connected socket
436 if (NaClSocketPair(pair
) == -1) {
437 SendErrorToRenderer("NaClSocketPair() failed");
441 socket_for_renderer_
= base::File(pair
[0]);
442 socket_for_sel_ldr_
= base::File(pair
[1]);
443 SetCloseOnExec(pair
[0]);
444 SetCloseOnExec(pair
[1]);
447 // Create a shared memory region that the renderer and plugin share for
448 // reporting crash information.
449 crash_info_shmem_
.CreateAnonymous(kNaClCrashInfoShmemSize
);
451 // Launch the process
452 if (!LaunchSelLdr()) {
457 void NaClProcessHost::OnChannelConnected(int32 peer_pid
) {
458 if (!CommandLine::ForCurrentProcess()->GetSwitchValuePath(
459 switches::kNaClGdb
).empty()) {
465 void NaClProcessHost::OnProcessLaunchedByBroker(base::ProcessHandle handle
) {
466 process_launched_by_broker_
= true;
467 process_
->SetHandle(handle
);
468 SetDebugStubPort(nacl::kGdbDebugStubPortUnknown
);
469 if (!StartWithLaunchedProcess())
473 void NaClProcessHost::OnDebugExceptionHandlerLaunchedByBroker(bool success
) {
474 IPC::Message
* reply
= attach_debug_exception_handler_reply_msg_
.release();
475 NaClProcessMsg_AttachDebugExceptionHandler::WriteReplyParams(reply
, success
);
480 // Needed to handle sync messages in OnMessageReceived.
481 bool NaClProcessHost::Send(IPC::Message
* msg
) {
482 return process_
->Send(msg
);
485 bool NaClProcessHost::LaunchNaClGdb() {
487 base::FilePath nacl_gdb
=
488 CommandLine::ForCurrentProcess()->GetSwitchValuePath(switches::kNaClGdb
);
489 CommandLine
cmd_line(nacl_gdb
);
491 CommandLine::StringType nacl_gdb
=
492 CommandLine::ForCurrentProcess()->GetSwitchValueNative(
494 CommandLine::StringVector argv
;
495 // We don't support spaces inside arguments in --nacl-gdb switch.
496 base::SplitString(nacl_gdb
, static_cast<CommandLine::CharType
>(' '), &argv
);
497 CommandLine
cmd_line(argv
);
499 cmd_line
.AppendArg("--eval-command");
500 base::FilePath::StringType
irt_path(
501 NaClBrowser::GetInstance()->GetIrtFilePath().value());
502 // Avoid back slashes because nacl-gdb uses posix escaping rules on Windows.
503 // See issue https://code.google.com/p/nativeclient/issues/detail?id=3482.
504 std::replace(irt_path
.begin(), irt_path
.end(), '\\', '/');
505 cmd_line
.AppendArgNative(FILE_PATH_LITERAL("nacl-irt \"") + irt_path
+
506 FILE_PATH_LITERAL("\""));
507 if (!manifest_path_
.empty()) {
508 cmd_line
.AppendArg("--eval-command");
509 base::FilePath::StringType
manifest_path_value(manifest_path_
.value());
510 std::replace(manifest_path_value
.begin(), manifest_path_value
.end(),
512 cmd_line
.AppendArgNative(FILE_PATH_LITERAL("nacl-manifest \"") +
513 manifest_path_value
+ FILE_PATH_LITERAL("\""));
515 cmd_line
.AppendArg("--eval-command");
516 cmd_line
.AppendArg("target remote :4014");
517 base::FilePath script
= CommandLine::ForCurrentProcess()->GetSwitchValuePath(
518 switches::kNaClGdbScript
);
519 if (!script
.empty()) {
520 cmd_line
.AppendArg("--command");
521 cmd_line
.AppendArgNative(script
.value());
523 return base::LaunchProcess(cmd_line
, base::LaunchOptions(), NULL
);
526 bool NaClProcessHost::LaunchSelLdr() {
527 std::string channel_id
= process_
->GetHost()->CreateChannel();
528 if (channel_id
.empty()) {
529 SendErrorToRenderer("CreateChannel() failed");
533 // Build command line for nacl.
535 #if defined(OS_MACOSX)
536 // The Native Client process needs to be able to allocate a 1GB contiguous
537 // region to use as the client environment's virtual address space. ASLR
538 // (PIE) interferes with this by making it possible that no gap large enough
539 // to accomodate this request will exist in the child process' address
540 // space. Disable PIE for NaCl processes. See http://crbug.com/90221 and
541 // http://code.google.com/p/nativeclient/issues/detail?id=2043.
542 int flags
= ChildProcessHost::CHILD_NO_PIE
;
543 #elif defined(OS_LINUX)
544 int flags
= ChildProcessHost::CHILD_ALLOW_SELF
;
546 int flags
= ChildProcessHost::CHILD_NORMAL
;
549 base::FilePath exe_path
= ChildProcessHost::GetChildPath(flags
);
550 if (exe_path
.empty())
554 // On Windows 64-bit NaCl loader is called nacl64.exe instead of chrome.exe
555 if (RunningOnWOW64()) {
556 if (!NaClBrowser::GetInstance()->GetNaCl64ExePath(&exe_path
)) {
557 SendErrorToRenderer("could not get path to nacl64.exe");
562 // When using the DLL CRT on Windows, we need to amend the PATH to include
563 // the location of the x64 CRT DLLs. This is only the case when using a
564 // component=shared_library build (i.e. generally dev debug builds). The
565 // x86 CRT DLLs are in e.g. out\Debug for chrome.exe etc., so the x64 ones
566 // are put in out\Debug\x64 which we add to the PATH here so that loader
567 // can find them. See http://crbug.com/346034.
568 scoped_ptr
<base::Environment
> env(base::Environment::Create());
569 static const char kPath
[] = "PATH";
570 std::string old_path
;
571 base::FilePath module_path
;
572 if (!PathService::Get(base::FILE_MODULE
, &module_path
)) {
573 SendErrorToRenderer("could not get path to current module");
576 std::string x64_crt_path
=
577 base::WideToUTF8(module_path
.DirName().Append(L
"x64").value());
578 if (!env
->GetVar(kPath
, &old_path
)) {
579 env
->SetVar(kPath
, x64_crt_path
);
580 } else if (!IsInPath(old_path
, x64_crt_path
)) {
581 std::string
new_path(old_path
);
582 new_path
.append(";");
583 new_path
.append(x64_crt_path
);
584 env
->SetVar(kPath
, new_path
);
590 scoped_ptr
<CommandLine
> cmd_line(new CommandLine(exe_path
));
591 CopyNaClCommandLineArguments(cmd_line
.get());
593 cmd_line
->AppendSwitchASCII(switches::kProcessType
,
595 switches::kNaClLoaderNonSfiProcess
:
596 switches::kNaClLoaderProcess
));
597 cmd_line
->AppendSwitchASCII(switches::kProcessChannelID
, channel_id
);
598 if (NaClBrowser::GetDelegate()->DialogsAreSuppressed())
599 cmd_line
->AppendSwitch(switches::kNoErrorDialogs
);
601 // On Windows we might need to start the broker process to launch a new loader
603 if (RunningOnWOW64()) {
604 if (!NaClBrokerService::GetInstance()->LaunchLoader(
605 weak_factory_
.GetWeakPtr(), channel_id
)) {
606 SendErrorToRenderer("broker service did not launch process");
613 new NaClSandboxedProcessLauncherDelegate(process_
->GetHost()),
618 bool NaClProcessHost::OnMessageReceived(const IPC::Message
& msg
) {
620 if (uses_nonsfi_mode_
) {
621 // IPC messages relating to NaCl's validation cache must not be exposed
622 // in Non-SFI Mode, otherwise a Non-SFI nexe could use
623 // SetKnownToValidate to create a hole in the SFI sandbox.
624 IPC_BEGIN_MESSAGE_MAP(NaClProcessHost
, msg
)
625 IPC_MESSAGE_HANDLER(NaClProcessHostMsg_PpapiChannelsCreated
,
626 OnPpapiChannelsCreated
)
627 IPC_MESSAGE_UNHANDLED(handled
= false)
628 IPC_END_MESSAGE_MAP()
630 IPC_BEGIN_MESSAGE_MAP(NaClProcessHost
, msg
)
631 IPC_MESSAGE_HANDLER(NaClProcessMsg_QueryKnownToValidate
,
632 OnQueryKnownToValidate
)
633 IPC_MESSAGE_HANDLER(NaClProcessMsg_SetKnownToValidate
,
634 OnSetKnownToValidate
)
635 IPC_MESSAGE_HANDLER(NaClProcessMsg_ResolveFileToken
,
639 IPC_MESSAGE_HANDLER_DELAY_REPLY(
640 NaClProcessMsg_AttachDebugExceptionHandler
,
641 OnAttachDebugExceptionHandler
)
642 IPC_MESSAGE_HANDLER(NaClProcessHostMsg_DebugStubPortSelected
,
643 OnDebugStubPortSelected
)
645 IPC_MESSAGE_HANDLER(NaClProcessHostMsg_PpapiChannelsCreated
,
646 OnPpapiChannelsCreated
)
647 IPC_MESSAGE_UNHANDLED(handled
= false)
648 IPC_END_MESSAGE_MAP()
653 void NaClProcessHost::OnProcessLaunched() {
654 if (!StartWithLaunchedProcess())
658 // Called when the NaClBrowser singleton has been fully initialized.
659 void NaClProcessHost::OnResourcesReady() {
660 NaClBrowser
* nacl_browser
= NaClBrowser::GetInstance();
661 if (!nacl_browser
->IsReady()) {
662 SendErrorToRenderer("could not acquire shared resources needed by NaCl");
664 } else if (!StartNaClExecution()) {
669 bool NaClProcessHost::ReplyToRenderer(
670 const IPC::ChannelHandle
& ppapi_channel_handle
,
671 const IPC::ChannelHandle
& trusted_channel_handle
,
672 const IPC::ChannelHandle
& manifest_service_channel_handle
) {
674 // If we are on 64-bit Windows, the NaCl process's sandbox is
675 // managed by a different process from the renderer's sandbox. We
676 // need to inform the renderer's sandbox about the NaCl process so
677 // that the renderer can send handles to the NaCl process using
678 // BrokerDuplicateHandle().
679 if (RunningOnWOW64()) {
680 if (!content::BrokerAddTargetPeer(process_
->GetData().handle
)) {
681 SendErrorToRenderer("BrokerAddTargetPeer() failed");
687 FileDescriptor imc_handle_for_renderer
;
689 // Copy the handle into the renderer process.
690 HANDLE handle_in_renderer
;
691 if (!DuplicateHandle(base::GetCurrentProcessHandle(),
692 socket_for_renderer_
.TakePlatformFile(),
693 nacl_host_message_filter_
->PeerHandle(),
695 0, // Unused given DUPLICATE_SAME_ACCESS.
697 DUPLICATE_CLOSE_SOURCE
| DUPLICATE_SAME_ACCESS
)) {
698 SendErrorToRenderer("DuplicateHandle() failed");
701 imc_handle_for_renderer
= reinterpret_cast<FileDescriptor
>(
704 // No need to dup the imc_handle - we don't pass it anywhere else so
705 // it cannot be closed.
706 FileDescriptor imc_handle
;
707 imc_handle
.fd
= socket_for_renderer_
.TakePlatformFile();
708 imc_handle
.auto_close
= true;
709 imc_handle_for_renderer
= imc_handle
;
712 const ChildProcessData
& data
= process_
->GetData();
713 base::SharedMemoryHandle crash_info_shmem_renderer_handle
;
714 if (!crash_info_shmem_
.ShareToProcess(nacl_host_message_filter_
->PeerHandle(),
715 &crash_info_shmem_renderer_handle
)) {
716 SendErrorToRenderer("ShareToProcess() failed");
720 SendMessageToRenderer(
721 NaClLaunchResult(imc_handle_for_renderer
,
722 ppapi_channel_handle
,
723 trusted_channel_handle
,
724 manifest_service_channel_handle
,
725 base::GetProcId(data
.handle
),
727 crash_info_shmem_renderer_handle
),
728 std::string() /* error_message */);
730 // Now that the crash information shmem handles have been shared with the
731 // plugin and the renderer, the browser can close its handle.
732 crash_info_shmem_
.Close();
736 void NaClProcessHost::SendErrorToRenderer(const std::string
& error_message
) {
737 LOG(ERROR
) << "NaCl process launch failed: " << error_message
;
738 SendMessageToRenderer(NaClLaunchResult(), error_message
);
741 void NaClProcessHost::SendMessageToRenderer(
742 const NaClLaunchResult
& result
,
743 const std::string
& error_message
) {
744 DCHECK(nacl_host_message_filter_
.get());
746 if (nacl_host_message_filter_
.get() != NULL
&& reply_msg_
!= NULL
) {
747 NaClHostMsg_LaunchNaCl::WriteReplyParams(
748 reply_msg_
, result
, error_message
);
749 nacl_host_message_filter_
->Send(reply_msg_
);
750 nacl_host_message_filter_
= NULL
;
755 void NaClProcessHost::SetDebugStubPort(int port
) {
756 NaClBrowser
* nacl_browser
= NaClBrowser::GetInstance();
757 nacl_browser
->SetProcessGdbDebugStubPort(process_
->GetData().id
, port
);
760 #if defined(OS_POSIX)
761 // TCP port we chose for NaCl debug stub. It can be any other number.
762 static const uint16_t kInitialDebugStubPort
= 4014;
764 net::SocketDescriptor
NaClProcessHost::GetDebugStubSocketHandle() {
765 net::SocketDescriptor s
= net::kInvalidSocket
;
766 // We always try to allocate the default port first. If this fails, we then
767 // allocate any available port.
768 // On success, if the test system has register a handler
769 // (GdbDebugStubPortListener), we fire a notification.
770 uint16 port
= kInitialDebugStubPort
;
771 s
= net::TCPListenSocket::CreateAndBind("127.0.0.1", port
);
772 if (s
== net::kInvalidSocket
) {
773 s
= net::TCPListenSocket::CreateAndBindAnyPort("127.0.0.1", &port
);
775 if (s
!= net::kInvalidSocket
) {
776 SetDebugStubPort(port
);
778 if (s
== net::kInvalidSocket
) {
779 LOG(ERROR
) << "failed to open socket for debug stub";
780 return net::kInvalidSocket
;
782 LOG(WARNING
) << "debug stub on port " << port
;
785 LOG(ERROR
) << "listen() failed on debug stub socket";
786 if (IGNORE_EINTR(close(s
)) < 0)
787 PLOG(ERROR
) << "failed to close debug stub socket";
788 return net::kInvalidSocket
;
795 void NaClProcessHost::OnDebugStubPortSelected(uint16_t debug_stub_port
) {
796 CHECK(!uses_nonsfi_mode_
);
797 SetDebugStubPort(debug_stub_port
);
801 bool NaClProcessHost::StartNaClExecution() {
802 NaClBrowser
* nacl_browser
= NaClBrowser::GetInstance();
804 NaClStartParams params
;
806 // Enable PPAPI proxy channel creation only for renderer processes.
807 params
.enable_ipc_proxy
= enable_ppapi_proxy();
808 params
.process_type
= process_type_
;
809 if (uses_nonsfi_mode_
) {
810 // Currently, non-SFI mode is supported only on Linux.
811 #if defined(OS_LINUX)
812 // In non-SFI mode, we do not use SRPC. Make sure that the socketpair is
814 DCHECK(!socket_for_sel_ldr_
.IsValid());
817 params
.validation_cache_enabled
= nacl_browser
->ValidationCacheIsEnabled();
818 params
.validation_cache_key
= nacl_browser
->GetValidationCacheKey();
819 params
.version
= NaClBrowser::GetDelegate()->GetVersionString();
820 params
.enable_debug_stub
= enable_debug_stub_
&&
821 NaClBrowser::GetDelegate()->URLMatchesDebugPatterns(manifest_url_
);
823 const ChildProcessData
& data
= process_
->GetData();
824 if (!ShareHandleToSelLdr(data
.handle
,
825 socket_for_sel_ldr_
.TakePlatformFile(),
831 const base::File
& irt_file
= nacl_browser
->IrtFile();
832 CHECK(irt_file
.IsValid());
833 // Send over the IRT file handle. We don't close our own copy!
834 if (!ShareHandleToSelLdr(data
.handle
, irt_file
.GetPlatformFile(), false,
839 #if defined(OS_MACOSX)
840 // For dynamic loading support, NaCl requires a file descriptor that
841 // was created in /tmp, since those created with shm_open() are not
842 // mappable with PROT_EXEC. Rather than requiring an extra IPC
843 // round trip out of the sandbox, we create an FD here.
844 base::SharedMemory memory_buffer
;
845 base::SharedMemoryCreateOptions options
;
847 options
.executable
= true;
848 if (!memory_buffer
.Create(options
)) {
849 DLOG(ERROR
) << "Failed to allocate memory buffer";
852 FileDescriptor memory_fd
;
853 memory_fd
.fd
= dup(memory_buffer
.handle().fd
);
854 if (memory_fd
.fd
< 0) {
855 DLOG(ERROR
) << "Failed to dup() a file descriptor";
858 memory_fd
.auto_close
= true;
859 params
.handles
.push_back(memory_fd
);
862 #if defined(OS_POSIX)
863 if (params
.enable_debug_stub
) {
864 net::SocketDescriptor server_bound_socket
= GetDebugStubSocketHandle();
865 if (server_bound_socket
!= net::kInvalidSocket
) {
866 params
.debug_stub_server_bound_socket
=
867 FileDescriptor(server_bound_socket
, true);
873 if (!crash_info_shmem_
.ShareToProcess(process_
->GetData().handle
,
874 ¶ms
.crash_info_shmem_handle
)) {
875 DLOG(ERROR
) << "Failed to ShareToProcess() a shared memory buffer";
879 base::FilePath file_path
;
880 // Don't retrieve the file path when using nonsfi mode; there's no validation
881 // caching in that case, so it's unnecessary work, and would expose the file
882 // path to the plugin.
883 if (!uses_nonsfi_mode_
&&
884 NaClBrowser::GetInstance()->GetFilePath(nexe_token_
.lo
,
887 // We have to reopen the file in the browser process; we don't want a
888 // compromised renderer to pass an arbitrary fd that could get loaded
889 // into the plugin process.
890 if (base::PostTaskAndReplyWithResult(
891 content::BrowserThread::GetBlockingPool(),
893 base::Bind(OpenNaClReadExecImpl
,
895 true /* is_executable */),
896 base::Bind(&NaClProcessHost::StartNaClFileResolved
,
897 weak_factory_
.GetWeakPtr(),
904 params
.nexe_file
= IPC::TakeFileHandleForProcess(nexe_file_
.Pass(),
905 process_
->GetData().handle
);
906 process_
->Send(new NaClProcessMsg_Start(params
));
910 void NaClProcessHost::StartNaClFileResolved(
911 NaClStartParams params
,
912 const base::FilePath
& file_path
,
913 base::File checked_nexe_file
) {
914 if (checked_nexe_file
.IsValid()) {
915 // Release the file received from the renderer. This has to be done on a
916 // thread where IO is permitted, though.
917 content::BrowserThread::GetBlockingPool()->PostTask(
919 base::Bind(&CloseFile
, base::Passed(nexe_file_
.Pass())));
920 params
.nexe_file_path_metadata
= file_path
;
921 params
.nexe_file
= IPC::TakeFileHandleForProcess(
922 checked_nexe_file
.Pass(), process_
->GetData().handle
);
924 params
.nexe_file
= IPC::TakeFileHandleForProcess(
925 nexe_file_
.Pass(), process_
->GetData().handle
);
927 process_
->Send(new NaClProcessMsg_Start(params
));
930 // This method is called when NaClProcessHostMsg_PpapiChannelCreated is
932 void NaClProcessHost::OnPpapiChannelsCreated(
933 const IPC::ChannelHandle
& browser_channel_handle
,
934 const IPC::ChannelHandle
& ppapi_renderer_channel_handle
,
935 const IPC::ChannelHandle
& trusted_renderer_channel_handle
,
936 const IPC::ChannelHandle
& manifest_service_channel_handle
) {
937 if (!enable_ppapi_proxy()) {
938 ReplyToRenderer(IPC::ChannelHandle(),
939 trusted_renderer_channel_handle
,
940 manifest_service_channel_handle
);
944 if (!ipc_proxy_channel_
.get()) {
945 DCHECK_EQ(PROCESS_TYPE_NACL_LOADER
, process_
->GetData().process_type
);
948 IPC::ChannelProxy::Create(browser_channel_handle
,
949 IPC::Channel::MODE_CLIENT
,
951 base::MessageLoopProxy::current().get());
952 // Create the browser ppapi host and enable PPAPI message dispatching to the
954 ppapi_host_
.reset(content::BrowserPpapiHost::CreateExternalPluginProcess(
955 ipc_proxy_channel_
.get(), // sender
957 process_
->GetData().handle
,
958 ipc_proxy_channel_
.get(),
959 nacl_host_message_filter_
->render_process_id(),
961 profile_directory_
));
962 ppapi_host_
->SetOnKeepaliveCallback(
963 NaClBrowser::GetDelegate()->GetOnKeepaliveCallback());
965 ppapi::PpapiNaClPluginArgs args
;
966 args
.off_the_record
= nacl_host_message_filter_
->off_the_record();
967 args
.permissions
= permissions_
;
968 args
.keepalive_throttle_interval_milliseconds
=
969 keepalive_throttle_interval_milliseconds_
;
970 CommandLine
* cmdline
= CommandLine::ForCurrentProcess();
972 std::string flag_whitelist
[] = {
976 for (size_t i
= 0; i
< arraysize(flag_whitelist
); ++i
) {
977 std::string value
= cmdline
->GetSwitchValueASCII(flag_whitelist
[i
]);
978 if (!value
.empty()) {
979 args
.switch_names
.push_back(flag_whitelist
[i
]);
980 args
.switch_values
.push_back(value
);
984 ppapi_host_
->GetPpapiHost()->AddHostFactoryFilter(
985 scoped_ptr
<ppapi::host::HostFactory
>(
986 NaClBrowser::GetDelegate()->CreatePpapiHostFactory(
987 ppapi_host_
.get())));
989 // Send a message to initialize the IPC dispatchers in the NaCl plugin.
990 ipc_proxy_channel_
->Send(new PpapiMsg_InitializeNaClDispatcher(args
));
992 // Let the renderer know that the IPC channels are established.
993 ReplyToRenderer(ppapi_renderer_channel_handle
,
994 trusted_renderer_channel_handle
,
995 manifest_service_channel_handle
);
997 // Attempt to open more than 1 browser channel is not supported.
998 // Shut down the NaCl process.
999 process_
->GetHost()->ForceShutdown();
1003 bool NaClProcessHost::StartWithLaunchedProcess() {
1004 NaClBrowser
* nacl_browser
= NaClBrowser::GetInstance();
1006 if (nacl_browser
->IsReady()) {
1007 return StartNaClExecution();
1008 } else if (nacl_browser
->IsOk()) {
1009 nacl_browser
->WaitForResources(
1010 base::Bind(&NaClProcessHost::OnResourcesReady
,
1011 weak_factory_
.GetWeakPtr()));
1014 SendErrorToRenderer("previously failed to acquire shared resources");
1019 void NaClProcessHost::OnQueryKnownToValidate(const std::string
& signature
,
1021 CHECK(!uses_nonsfi_mode_
);
1022 NaClBrowser
* nacl_browser
= NaClBrowser::GetInstance();
1023 *result
= nacl_browser
->QueryKnownToValidate(signature
, off_the_record_
);
1026 void NaClProcessHost::OnSetKnownToValidate(const std::string
& signature
) {
1027 CHECK(!uses_nonsfi_mode_
);
1028 NaClBrowser::GetInstance()->SetKnownToValidate(
1029 signature
, off_the_record_
);
1032 void NaClProcessHost::OnResolveFileToken(uint64 file_token_lo
,
1033 uint64 file_token_hi
) {
1034 // Was the file registered?
1036 // Note that the file path cache is of bounded size, and old entries can get
1037 // evicted. If a large number of NaCl modules are being launched at once,
1038 // resolving the file_token may fail because the path cache was thrashed
1039 // while the file_token was in flight. In this case the query fails, and we
1040 // need to fall back to the slower path.
1042 // However: each NaCl process will consume 2-3 entries as it starts up, this
1043 // means that eviction will not happen unless you start up 33+ NaCl processes
1044 // at the same time, and this still requires worst-case timing. As a
1045 // practical matter, no entries should be evicted prematurely.
1046 // The cache itself should take ~ (150 characters * 2 bytes/char + ~60 bytes
1047 // data structure overhead) * 100 = 35k when full, so making it bigger should
1048 // not be a problem, if needed.
1050 // Each NaCl process will consume 2-3 entries because the manifest and main
1051 // nexe are currently not resolved. Shared libraries will be resolved. They
1052 // will be loaded sequentially, so they will only consume a single entry
1053 // while the load is in flight.
1055 // TODO(ncbray): track behavior with UMA. If entries are getting evicted or
1056 // bogus keys are getting queried, this would be good to know.
1057 CHECK(!uses_nonsfi_mode_
);
1058 base::FilePath file_path
;
1059 if (!NaClBrowser::GetInstance()->GetFilePath(
1060 file_token_lo
, file_token_hi
, &file_path
)) {
1061 Send(new NaClProcessMsg_ResolveFileTokenReply(
1064 IPC::PlatformFileForTransit(),
1070 if (!base::PostTaskAndReplyWithResult(
1071 content::BrowserThread::GetBlockingPool(),
1073 base::Bind(OpenNaClReadExecImpl
, file_path
, true /* is_executable */),
1074 base::Bind(&NaClProcessHost::FileResolved
,
1075 weak_factory_
.GetWeakPtr(),
1079 Send(new NaClProcessMsg_ResolveFileTokenReply(
1082 IPC::PlatformFileForTransit(),
1087 void NaClProcessHost::FileResolved(
1088 uint64_t file_token_lo
,
1089 uint64_t file_token_hi
,
1090 const base::FilePath
& file_path
,
1092 base::FilePath out_file_path
;
1093 IPC::PlatformFileForTransit out_handle
;
1094 if (file
.IsValid()) {
1095 out_file_path
= file_path
;
1096 out_handle
= IPC::TakeFileHandleForProcess(
1098 process_
->GetData().handle
);
1100 out_handle
= IPC::InvalidPlatformFileForTransit();
1102 Send(new NaClProcessMsg_ResolveFileTokenReply(
1110 void NaClProcessHost::OnAttachDebugExceptionHandler(const std::string
& info
,
1111 IPC::Message
* reply_msg
) {
1112 CHECK(!uses_nonsfi_mode_
);
1113 if (!AttachDebugExceptionHandler(info
, reply_msg
)) {
1114 // Send failure message.
1115 NaClProcessMsg_AttachDebugExceptionHandler::WriteReplyParams(reply_msg
,
1121 bool NaClProcessHost::AttachDebugExceptionHandler(const std::string
& info
,
1122 IPC::Message
* reply_msg
) {
1123 bool enable_exception_handling
= process_type_
== kNativeNaClProcessType
;
1124 if (!enable_exception_handling
&& !enable_debug_stub_
) {
1126 "Debug exception handler requested by NaCl process when not enabled";
1129 if (debug_exception_handler_requested_
) {
1130 // The NaCl process should not request this multiple times.
1131 DLOG(ERROR
) << "Multiple AttachDebugExceptionHandler requests received";
1134 debug_exception_handler_requested_
= true;
1136 base::ProcessId nacl_pid
= base::GetProcId(process_
->GetData().handle
);
1137 base::ProcessHandle temp_handle
;
1138 // We cannot use process_->GetData().handle because it does not have
1139 // the necessary access rights. We open the new handle here rather
1140 // than in the NaCl broker process in case the NaCl loader process
1141 // dies before the NaCl broker process receives the message we send.
1142 // The debug exception handler uses DebugActiveProcess() to attach,
1143 // but this takes a PID. We need to prevent the NaCl loader's PID
1144 // from being reused before DebugActiveProcess() is called, and
1145 // holding a process handle open achieves this.
1146 if (!base::OpenProcessHandleWithAccess(
1148 base::kProcessAccessQueryInformation
|
1149 base::kProcessAccessSuspendResume
|
1150 base::kProcessAccessTerminate
|
1151 base::kProcessAccessVMOperation
|
1152 base::kProcessAccessVMRead
|
1153 base::kProcessAccessVMWrite
|
1154 base::kProcessAccessDuplicateHandle
|
1155 base::kProcessAccessWaitForTermination
,
1157 LOG(ERROR
) << "Failed to get process handle";
1160 base::win::ScopedHandle
process_handle(temp_handle
);
1162 attach_debug_exception_handler_reply_msg_
.reset(reply_msg
);
1163 // If the NaCl loader is 64-bit, the process running its debug
1164 // exception handler must be 64-bit too, so we use the 64-bit NaCl
1165 // broker process for this. Otherwise, on a 32-bit system, we use
1166 // the 32-bit browser process to run the debug exception handler.
1167 if (RunningOnWOW64()) {
1168 return NaClBrokerService::GetInstance()->LaunchDebugExceptionHandler(
1169 weak_factory_
.GetWeakPtr(), nacl_pid
, process_handle
.Get(),
1172 NaClStartDebugExceptionHandlerThread(
1173 process_handle
.Take(), info
,
1174 base::MessageLoopProxy::current(),
1175 base::Bind(&NaClProcessHost::OnDebugExceptionHandlerLaunchedByBroker
,
1176 weak_factory_
.GetWeakPtr()));