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/shared/imc/nacl_imc_c.h"
50 #include "net/base/net_util.h"
51 #include "net/socket/tcp_listen_socket.h"
52 #include "ppapi/host/host_factory.h"
53 #include "ppapi/host/ppapi_host.h"
54 #include "ppapi/proxy/ppapi_messages.h"
55 #include "ppapi/shared_impl/ppapi_constants.h"
56 #include "ppapi/shared_impl/ppapi_nacl_plugin_args.h"
62 #include "ipc/ipc_channel_posix.h"
66 #include "base/threading/thread.h"
67 #include "base/win/scoped_handle.h"
68 #include "components/nacl/browser/nacl_broker_service_win.h"
69 #include "components/nacl/common/nacl_debug_exception_handler_win.h"
70 #include "content/public/common/sandbox_init.h"
73 using content::BrowserThread
;
74 using content::ChildProcessData
;
75 using content::ChildProcessHost
;
76 using ppapi::proxy::SerializedHandle
;
83 // Looks for the largest contiguous unallocated region of address
84 // space and returns it via |*out_addr| and |*out_size|.
85 void FindAddressSpace(base::ProcessHandle process
,
86 char** out_addr
, size_t* out_size
) {
91 MEMORY_BASIC_INFORMATION info
;
92 size_t result
= VirtualQueryEx(process
, static_cast<void*>(addr
),
94 if (result
< sizeof(info
))
96 if (info
.State
== MEM_FREE
&& info
.RegionSize
> *out_size
) {
98 *out_size
= info
.RegionSize
;
100 addr
+= info
.RegionSize
;
106 bool IsInPath(const std::string
& path_env_var
, const std::string
& dir
) {
107 std::vector
<std::string
> split
;
108 base::SplitString(path_env_var
, ';', &split
);
109 for (std::vector
<std::string
>::const_iterator
i(split
.begin());
122 // Allocates |size| bytes of address space in the given process at a
123 // randomised address.
124 void* AllocateAddressSpaceASLR(base::ProcessHandle process
, size_t size
) {
127 FindAddressSpace(process
, &addr
, &avail_size
);
128 if (avail_size
< size
)
130 size_t offset
= base::RandGenerator(avail_size
- size
);
131 const int kPageSize
= 0x10000;
133 reinterpret_cast<void*>(reinterpret_cast<uint64
>(addr
+ offset
)
135 return VirtualAllocEx(process
, request_addr
, size
,
136 MEM_RESERVE
, PAGE_NOACCESS
);
141 bool RunningOnWOW64() {
142 return (base::win::OSInfo::GetInstance()->wow64_status() ==
143 base::win::OSInfo::WOW64_ENABLED
);
148 #endif // defined(OS_WIN)
152 // NOTE: changes to this class need to be reviewed by the security team.
153 class NaClSandboxedProcessLauncherDelegate
154 : public content::SandboxedProcessLauncherDelegate
{
156 NaClSandboxedProcessLauncherDelegate(ChildProcessHost
* host
)
157 #if defined(OS_POSIX)
158 : ipc_fd_(host
->TakeClientFileDescriptor())
162 ~NaClSandboxedProcessLauncherDelegate() override
{}
165 virtual void PostSpawnTarget(base::ProcessHandle process
) {
166 // For Native Client sel_ldr processes on 32-bit Windows, reserve 1 GB of
167 // address space to prevent later failure due to address space fragmentation
168 // from .dll loading. The NaCl process will attempt to locate this space by
169 // scanning the address space using VirtualQuery.
170 // TODO(bbudge) Handle the --no-sandbox case.
171 // http://code.google.com/p/nativeclient/issues/detail?id=2131
172 const SIZE_T kNaClSandboxSize
= 1 << 30;
173 if (!nacl::AllocateAddressSpaceASLR(process
, kNaClSandboxSize
)) {
174 DLOG(WARNING
) << "Failed to reserve address space for Native Client";
177 #elif defined(OS_POSIX)
178 bool ShouldUseZygote() override
{ return true; }
179 base::ScopedFD
TakeIpcFd() override
{ return ipc_fd_
.Pass(); }
183 #if defined(OS_POSIX)
184 base::ScopedFD ipc_fd_
;
188 void SetCloseOnExec(NaClHandle fd
) {
189 #if defined(OS_POSIX)
190 int flags
= fcntl(fd
, F_GETFD
);
192 int rc
= fcntl(fd
, F_SETFD
, flags
| FD_CLOEXEC
);
197 bool ShareHandleToSelLdr(
198 base::ProcessHandle processh
,
201 std::vector
<nacl::FileDescriptor
> *handles_for_sel_ldr
) {
204 int flags
= DUPLICATE_SAME_ACCESS
;
206 flags
|= DUPLICATE_CLOSE_SOURCE
;
207 if (!DuplicateHandle(GetCurrentProcess(),
208 reinterpret_cast<HANDLE
>(sourceh
),
211 0, // Unused given DUPLICATE_SAME_ACCESS.
214 LOG(ERROR
) << "DuplicateHandle() failed";
217 handles_for_sel_ldr
->push_back(
218 reinterpret_cast<nacl::FileDescriptor
>(channel
));
220 nacl::FileDescriptor channel
;
221 channel
.fd
= sourceh
;
222 channel
.auto_close
= close_source
;
223 handles_for_sel_ldr
->push_back(channel
);
228 void CloseFile(base::File file
) {
229 // The base::File destructor will close the file for us.
234 unsigned NaClProcessHost::keepalive_throttle_interval_milliseconds_
=
235 ppapi::kKeepaliveThrottleIntervalDefaultMilliseconds
;
237 NaClProcessHost::NaClProcessHost(
238 const GURL
& manifest_url
,
239 base::File nexe_file
,
240 const NaClFileToken
& nexe_token
,
242 nacl::NaClResourceFileInfo
>& prefetched_resource_files_info
,
243 ppapi::PpapiPermissions permissions
,
245 uint32 permission_bits
,
246 bool uses_nonsfi_mode
,
248 NaClAppProcessType process_type
,
249 const base::FilePath
& profile_directory
)
250 : manifest_url_(manifest_url
),
251 nexe_file_(nexe_file
.Pass()),
252 nexe_token_(nexe_token
),
253 prefetched_resource_files_info_(prefetched_resource_files_info
),
254 permissions_(permissions
),
256 process_launched_by_broker_(false),
260 debug_exception_handler_requested_(false),
262 uses_nonsfi_mode_(uses_nonsfi_mode
),
263 enable_debug_stub_(false),
264 enable_crash_throttling_(false),
265 off_the_record_(off_the_record
),
266 process_type_(process_type
),
267 profile_directory_(profile_directory
),
268 render_view_id_(render_view_id
),
269 weak_factory_(this) {
270 process_
.reset(content::BrowserChildProcessHost::Create(
271 static_cast<content::ProcessType
>(PROCESS_TYPE_NACL_LOADER
), this));
273 // Set the display name so the user knows what plugin the process is running.
274 // We aren't on the UI thread so getting the pref locale for language
275 // formatting isn't possible, so IDN will be lost, but this is probably OK
276 // for this use case.
277 process_
->SetName(net::FormatUrl(manifest_url_
, std::string()));
279 enable_debug_stub_
= base::CommandLine::ForCurrentProcess()->HasSwitch(
280 switches::kEnableNaClDebug
);
281 DCHECK(process_type_
!= kUnknownNaClProcessType
);
282 enable_crash_throttling_
= process_type_
!= kNativeNaClProcessType
;
285 NaClProcessHost::~NaClProcessHost() {
286 // Report exit status only if the process was successfully started.
287 if (process_
->GetData().handle
!= base::kNullProcessHandle
) {
289 process_
->GetTerminationStatus(false /* known_dead */, &exit_code
);
290 std::string message
=
291 base::StringPrintf("NaCl process exited with status %i (0x%x)",
292 exit_code
, exit_code
);
293 if (exit_code
== 0) {
296 LOG(ERROR
) << message
;
298 NaClBrowser::GetInstance()->OnProcessEnd(process_
->GetData().id
);
301 for (size_t i
= 0; i
< prefetched_resource_files_info_
.size(); ++i
) {
302 // The process failed to launch for some reason. Close resource file
304 base::File
file(IPC::PlatformFileForTransitToFile(
305 prefetched_resource_files_info_
[i
].file
));
306 content::BrowserThread::GetBlockingPool()->PostTask(
308 base::Bind(&CloseFile
, base::Passed(file
.Pass())));
312 // The process failed to launch for some reason.
313 // Don't keep the renderer hanging.
314 reply_msg_
->set_reply_error();
315 nacl_host_message_filter_
->Send(reply_msg_
);
318 if (process_launched_by_broker_
) {
319 NaClBrokerService::GetInstance()->OnLoaderDied();
324 void NaClProcessHost::OnProcessCrashed(int exit_status
) {
325 if (enable_crash_throttling_
&&
326 !base::CommandLine::ForCurrentProcess()->HasSwitch(
327 switches::kDisablePnaclCrashThrottling
)) {
328 NaClBrowser::GetInstance()->OnProcessCrashed();
332 // This is called at browser startup.
334 void NaClProcessHost::EarlyStartup() {
335 NaClBrowser::GetInstance()->EarlyStartup();
336 // Inform NaClBrowser that we exist and will have a debug port at some point.
337 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
338 // Open the IRT file early to make sure that it isn't replaced out from
339 // under us by autoupdate.
340 NaClBrowser::GetInstance()->EnsureIrtAvailable();
342 base::CommandLine
* cmd
= base::CommandLine::ForCurrentProcess();
343 UMA_HISTOGRAM_BOOLEAN(
345 !cmd
->GetSwitchValuePath(switches::kNaClGdb
).empty());
346 UMA_HISTOGRAM_BOOLEAN(
347 "NaCl.nacl-gdb-script",
348 !cmd
->GetSwitchValuePath(switches::kNaClGdbScript
).empty());
349 UMA_HISTOGRAM_BOOLEAN(
350 "NaCl.enable-nacl-debug",
351 cmd
->HasSwitch(switches::kEnableNaClDebug
));
352 std::string nacl_debug_mask
=
353 cmd
->GetSwitchValueASCII(switches::kNaClDebugMask
);
354 // By default, exclude debugging SSH and the PNaCl translator.
355 // about::flags only allows empty flags as the default, so replace
356 // the empty setting with the default. To debug all apps, use a wild-card.
357 if (nacl_debug_mask
.empty()) {
358 nacl_debug_mask
= "!*://*/*ssh_client.nmf,chrome://pnacl-translator/*";
360 NaClBrowser::GetDelegate()->SetDebugPatterns(nacl_debug_mask
);
364 void NaClProcessHost::SetPpapiKeepAliveThrottleForTesting(
365 unsigned milliseconds
) {
366 keepalive_throttle_interval_milliseconds_
= milliseconds
;
369 void NaClProcessHost::Launch(
370 NaClHostMessageFilter
* nacl_host_message_filter
,
371 IPC::Message
* reply_msg
,
372 const base::FilePath
& manifest_path
) {
373 nacl_host_message_filter_
= nacl_host_message_filter
;
374 reply_msg_
= reply_msg
;
375 manifest_path_
= manifest_path
;
377 // Do not launch the requested NaCl module if NaCl is marked "unstable" due
378 // to too many crashes within a given time period.
379 if (enable_crash_throttling_
&&
380 !base::CommandLine::ForCurrentProcess()->HasSwitch(
381 switches::kDisablePnaclCrashThrottling
) &&
382 NaClBrowser::GetInstance()->IsThrottled()) {
383 SendErrorToRenderer("Process creation was throttled due to excessive"
389 const base::CommandLine
* cmd
= base::CommandLine::ForCurrentProcess();
391 if (cmd
->HasSwitch(switches::kEnableNaClDebug
) &&
392 !cmd
->HasSwitch(switches::kNoSandbox
)) {
393 // We don't switch off sandbox automatically for security reasons.
394 SendErrorToRenderer("NaCl's GDB debug stub requires --no-sandbox flag"
395 " on Windows. See crbug.com/265624.");
400 if (cmd
->HasSwitch(switches::kNaClGdb
) &&
401 !cmd
->HasSwitch(switches::kEnableNaClDebug
)) {
402 LOG(WARNING
) << "--nacl-gdb flag requires --enable-nacl-debug flag";
405 // Start getting the IRT open asynchronously while we launch the NaCl process.
406 // We'll make sure this actually finished in StartWithLaunchedProcess, below.
407 NaClBrowser
* nacl_browser
= NaClBrowser::GetInstance();
408 nacl_browser
->EnsureAllResourcesAvailable();
409 if (!nacl_browser
->IsOk()) {
410 SendErrorToRenderer("could not find all the resources needed"
411 " to launch the process");
416 if (uses_nonsfi_mode_
) {
417 bool nonsfi_mode_forced_by_command_line
= false;
418 bool nonsfi_mode_allowed
= false;
419 #if defined(OS_LINUX)
420 nonsfi_mode_forced_by_command_line
=
421 cmd
->HasSwitch(switches::kEnableNaClNonSfiMode
);
422 #if defined(OS_CHROMEOS) && defined(ARCH_CPU_ARMEL)
423 nonsfi_mode_allowed
= NaClBrowser::GetDelegate()->IsNonSfiModeAllowed(
424 nacl_host_message_filter
->profile_directory(), manifest_url_
);
427 bool nonsfi_mode_enabled
=
428 nonsfi_mode_forced_by_command_line
|| nonsfi_mode_allowed
;
430 if (!nonsfi_mode_enabled
) {
432 "NaCl non-SFI mode is not available for this platform"
433 " and NaCl module.");
438 // Rather than creating a socket pair in the renderer, and passing
439 // one side through the browser to sel_ldr, socket pairs are created
440 // in the browser and then passed to the renderer and sel_ldr.
442 // This is mainly for the benefit of Windows, where sockets cannot
443 // be passed in messages, but are copied via DuplicateHandle().
444 // This means the sandboxed renderer cannot send handles to the
448 // Create a connected socket
449 if (NaClSocketPair(pair
) == -1) {
450 SendErrorToRenderer("NaClSocketPair() failed");
454 socket_for_renderer_
= base::File(pair
[0]);
455 socket_for_sel_ldr_
= base::File(pair
[1]);
456 SetCloseOnExec(pair
[0]);
457 SetCloseOnExec(pair
[1]);
460 // Create a shared memory region that the renderer and plugin share for
461 // reporting crash information.
462 crash_info_shmem_
.CreateAnonymous(kNaClCrashInfoShmemSize
);
464 // Launch the process
465 if (!LaunchSelLdr()) {
470 void NaClProcessHost::OnChannelConnected(int32 peer_pid
) {
471 if (!base::CommandLine::ForCurrentProcess()->GetSwitchValuePath(
472 switches::kNaClGdb
).empty()) {
478 void NaClProcessHost::OnProcessLaunchedByBroker(base::ProcessHandle handle
) {
479 process_launched_by_broker_
= true;
480 process_
->SetHandle(handle
);
481 SetDebugStubPort(nacl::kGdbDebugStubPortUnknown
);
482 if (!StartWithLaunchedProcess())
486 void NaClProcessHost::OnDebugExceptionHandlerLaunchedByBroker(bool success
) {
487 IPC::Message
* reply
= attach_debug_exception_handler_reply_msg_
.release();
488 NaClProcessMsg_AttachDebugExceptionHandler::WriteReplyParams(reply
, success
);
493 // Needed to handle sync messages in OnMessageReceived.
494 bool NaClProcessHost::Send(IPC::Message
* msg
) {
495 return process_
->Send(msg
);
498 void NaClProcessHost::LaunchNaClGdb() {
499 const base::CommandLine
& command_line
=
500 *base::CommandLine::ForCurrentProcess();
502 base::FilePath nacl_gdb
=
503 command_line
.GetSwitchValuePath(switches::kNaClGdb
);
504 base::CommandLine
cmd_line(nacl_gdb
);
506 base::CommandLine::StringType nacl_gdb
=
507 command_line
.GetSwitchValueNative(switches::kNaClGdb
);
508 base::CommandLine::StringVector argv
;
509 // We don't support spaces inside arguments in --nacl-gdb switch.
510 base::SplitString(nacl_gdb
, static_cast<base::CommandLine::CharType
>(' '),
512 base::CommandLine
cmd_line(argv
);
514 cmd_line
.AppendArg("--eval-command");
515 base::FilePath::StringType
irt_path(
516 NaClBrowser::GetInstance()->GetIrtFilePath().value());
517 // Avoid back slashes because nacl-gdb uses posix escaping rules on Windows.
518 // See issue https://code.google.com/p/nativeclient/issues/detail?id=3482.
519 std::replace(irt_path
.begin(), irt_path
.end(), '\\', '/');
520 cmd_line
.AppendArgNative(FILE_PATH_LITERAL("nacl-irt \"") + irt_path
+
521 FILE_PATH_LITERAL("\""));
522 if (!manifest_path_
.empty()) {
523 cmd_line
.AppendArg("--eval-command");
524 base::FilePath::StringType
manifest_path_value(manifest_path_
.value());
525 std::replace(manifest_path_value
.begin(), manifest_path_value
.end(),
527 cmd_line
.AppendArgNative(FILE_PATH_LITERAL("nacl-manifest \"") +
528 manifest_path_value
+ FILE_PATH_LITERAL("\""));
530 cmd_line
.AppendArg("--eval-command");
531 cmd_line
.AppendArg("target remote :4014");
532 base::FilePath script
=
533 command_line
.GetSwitchValuePath(switches::kNaClGdbScript
);
534 if (!script
.empty()) {
535 cmd_line
.AppendArg("--command");
536 cmd_line
.AppendArgNative(script
.value());
538 base::LaunchProcess(cmd_line
, base::LaunchOptions());
541 bool NaClProcessHost::LaunchSelLdr() {
542 std::string channel_id
= process_
->GetHost()->CreateChannel();
543 if (channel_id
.empty()) {
544 SendErrorToRenderer("CreateChannel() failed");
548 // Build command line for nacl.
550 #if defined(OS_MACOSX)
551 // The Native Client process needs to be able to allocate a 1GB contiguous
552 // region to use as the client environment's virtual address space. ASLR
553 // (PIE) interferes with this by making it possible that no gap large enough
554 // to accomodate this request will exist in the child process' address
555 // space. Disable PIE for NaCl processes. See http://crbug.com/90221 and
556 // http://code.google.com/p/nativeclient/issues/detail?id=2043.
557 int flags
= ChildProcessHost::CHILD_NO_PIE
;
558 #elif defined(OS_LINUX)
559 int flags
= ChildProcessHost::CHILD_ALLOW_SELF
;
561 int flags
= ChildProcessHost::CHILD_NORMAL
;
564 base::FilePath exe_path
= ChildProcessHost::GetChildPath(flags
);
565 if (exe_path
.empty())
569 // On Windows 64-bit NaCl loader is called nacl64.exe instead of chrome.exe
570 if (RunningOnWOW64()) {
571 if (!NaClBrowser::GetInstance()->GetNaCl64ExePath(&exe_path
)) {
572 SendErrorToRenderer("could not get path to nacl64.exe");
577 // When using the DLL CRT on Windows, we need to amend the PATH to include
578 // the location of the x64 CRT DLLs. This is only the case when using a
579 // component=shared_library build (i.e. generally dev debug builds). The
580 // x86 CRT DLLs are in e.g. out\Debug for chrome.exe etc., so the x64 ones
581 // are put in out\Debug\x64 which we add to the PATH here so that loader
582 // can find them. See http://crbug.com/346034.
583 scoped_ptr
<base::Environment
> env(base::Environment::Create());
584 static const char kPath
[] = "PATH";
585 std::string old_path
;
586 base::FilePath module_path
;
587 if (!PathService::Get(base::FILE_MODULE
, &module_path
)) {
588 SendErrorToRenderer("could not get path to current module");
591 std::string x64_crt_path
=
592 base::WideToUTF8(module_path
.DirName().Append(L
"x64").value());
593 if (!env
->GetVar(kPath
, &old_path
)) {
594 env
->SetVar(kPath
, x64_crt_path
);
595 } else if (!IsInPath(old_path
, x64_crt_path
)) {
596 std::string
new_path(old_path
);
597 new_path
.append(";");
598 new_path
.append(x64_crt_path
);
599 env
->SetVar(kPath
, new_path
);
605 scoped_ptr
<base::CommandLine
> cmd_line(new base::CommandLine(exe_path
));
606 CopyNaClCommandLineArguments(cmd_line
.get());
608 cmd_line
->AppendSwitchASCII(switches::kProcessType
,
610 switches::kNaClLoaderNonSfiProcess
:
611 switches::kNaClLoaderProcess
));
612 cmd_line
->AppendSwitchASCII(switches::kProcessChannelID
, channel_id
);
613 if (NaClBrowser::GetDelegate()->DialogsAreSuppressed())
614 cmd_line
->AppendSwitch(switches::kNoErrorDialogs
);
616 // On Windows we might need to start the broker process to launch a new loader
618 if (RunningOnWOW64()) {
619 if (!NaClBrokerService::GetInstance()->LaunchLoader(
620 weak_factory_
.GetWeakPtr(), channel_id
)) {
621 SendErrorToRenderer("broker service did not launch process");
628 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(NaClProcessMsg_ResolveFileToken
,
655 IPC_MESSAGE_HANDLER_DELAY_REPLY(
656 NaClProcessMsg_AttachDebugExceptionHandler
,
657 OnAttachDebugExceptionHandler
)
658 IPC_MESSAGE_HANDLER(NaClProcessHostMsg_DebugStubPortSelected
,
659 OnDebugStubPortSelected
)
661 IPC_MESSAGE_HANDLER(NaClProcessHostMsg_PpapiChannelsCreated
,
662 OnPpapiChannelsCreated
)
663 IPC_MESSAGE_UNHANDLED(handled
= false)
664 IPC_END_MESSAGE_MAP()
669 void NaClProcessHost::OnProcessLaunched() {
670 if (!StartWithLaunchedProcess())
674 // Called when the NaClBrowser singleton has been fully initialized.
675 void NaClProcessHost::OnResourcesReady() {
676 NaClBrowser
* nacl_browser
= NaClBrowser::GetInstance();
677 if (!nacl_browser
->IsReady()) {
678 SendErrorToRenderer("could not acquire shared resources needed by NaCl");
680 } else if (!StartNaClExecution()) {
685 bool NaClProcessHost::ReplyToRenderer(
686 const IPC::ChannelHandle
& ppapi_channel_handle
,
687 const IPC::ChannelHandle
& trusted_channel_handle
,
688 const IPC::ChannelHandle
& manifest_service_channel_handle
) {
690 // If we are on 64-bit Windows, the NaCl process's sandbox is
691 // managed by a different process from the renderer's sandbox. We
692 // need to inform the renderer's sandbox about the NaCl process so
693 // that the renderer can send handles to the NaCl process using
694 // BrokerDuplicateHandle().
695 if (RunningOnWOW64()) {
696 if (!content::BrokerAddTargetPeer(process_
->GetData().handle
)) {
697 SendErrorToRenderer("BrokerAddTargetPeer() failed");
703 FileDescriptor imc_handle_for_renderer
;
705 // Copy the handle into the renderer process.
706 HANDLE handle_in_renderer
;
707 if (!DuplicateHandle(base::GetCurrentProcessHandle(),
708 socket_for_renderer_
.TakePlatformFile(),
709 nacl_host_message_filter_
->PeerHandle(),
711 0, // Unused given DUPLICATE_SAME_ACCESS.
713 DUPLICATE_CLOSE_SOURCE
| DUPLICATE_SAME_ACCESS
)) {
714 SendErrorToRenderer("DuplicateHandle() failed");
717 imc_handle_for_renderer
= reinterpret_cast<FileDescriptor
>(
720 // No need to dup the imc_handle - we don't pass it anywhere else so
721 // it cannot be closed.
722 FileDescriptor imc_handle
;
723 imc_handle
.fd
= socket_for_renderer_
.TakePlatformFile();
724 imc_handle
.auto_close
= true;
725 imc_handle_for_renderer
= imc_handle
;
728 const ChildProcessData
& data
= process_
->GetData();
729 base::SharedMemoryHandle crash_info_shmem_renderer_handle
;
730 if (!crash_info_shmem_
.ShareToProcess(nacl_host_message_filter_
->PeerHandle(),
731 &crash_info_shmem_renderer_handle
)) {
732 SendErrorToRenderer("ShareToProcess() failed");
736 SendMessageToRenderer(
737 NaClLaunchResult(imc_handle_for_renderer
,
738 ppapi_channel_handle
,
739 trusted_channel_handle
,
740 manifest_service_channel_handle
,
741 base::GetProcId(data
.handle
),
743 crash_info_shmem_renderer_handle
),
744 std::string() /* error_message */);
746 // Now that the crash information shmem handles have been shared with the
747 // plugin and the renderer, the browser can close its handle.
748 crash_info_shmem_
.Close();
752 void NaClProcessHost::SendErrorToRenderer(const std::string
& error_message
) {
753 LOG(ERROR
) << "NaCl process launch failed: " << error_message
;
754 SendMessageToRenderer(NaClLaunchResult(), error_message
);
757 void NaClProcessHost::SendMessageToRenderer(
758 const NaClLaunchResult
& result
,
759 const std::string
& error_message
) {
760 DCHECK(nacl_host_message_filter_
.get());
762 if (nacl_host_message_filter_
.get() != NULL
&& reply_msg_
!= NULL
) {
763 NaClHostMsg_LaunchNaCl::WriteReplyParams(
764 reply_msg_
, result
, error_message
);
765 nacl_host_message_filter_
->Send(reply_msg_
);
766 nacl_host_message_filter_
= NULL
;
771 void NaClProcessHost::SetDebugStubPort(int port
) {
772 NaClBrowser
* nacl_browser
= NaClBrowser::GetInstance();
773 nacl_browser
->SetProcessGdbDebugStubPort(process_
->GetData().id
, port
);
776 #if defined(OS_POSIX)
777 // TCP port we chose for NaCl debug stub. It can be any other number.
778 static const uint16_t kInitialDebugStubPort
= 4014;
780 net::SocketDescriptor
NaClProcessHost::GetDebugStubSocketHandle() {
781 net::SocketDescriptor s
= net::kInvalidSocket
;
782 // We always try to allocate the default port first. If this fails, we then
783 // allocate any available port.
784 // On success, if the test system has register a handler
785 // (GdbDebugStubPortListener), we fire a notification.
786 uint16 port
= kInitialDebugStubPort
;
787 s
= net::TCPListenSocket::CreateAndBind("127.0.0.1", port
);
788 if (s
== net::kInvalidSocket
) {
789 s
= net::TCPListenSocket::CreateAndBindAnyPort("127.0.0.1", &port
);
791 if (s
!= net::kInvalidSocket
) {
792 SetDebugStubPort(port
);
794 if (s
== net::kInvalidSocket
) {
795 LOG(ERROR
) << "failed to open socket for debug stub";
796 return net::kInvalidSocket
;
798 LOG(WARNING
) << "debug stub on port " << port
;
801 LOG(ERROR
) << "listen() failed on debug stub socket";
802 if (IGNORE_EINTR(close(s
)) < 0)
803 PLOG(ERROR
) << "failed to close debug stub socket";
804 return net::kInvalidSocket
;
811 void NaClProcessHost::OnDebugStubPortSelected(uint16_t debug_stub_port
) {
812 CHECK(!uses_nonsfi_mode_
);
813 SetDebugStubPort(debug_stub_port
);
817 bool NaClProcessHost::StartNaClExecution() {
818 NaClBrowser
* nacl_browser
= NaClBrowser::GetInstance();
820 NaClStartParams params
;
822 // Enable PPAPI proxy channel creation only for renderer processes.
823 params
.enable_ipc_proxy
= enable_ppapi_proxy();
824 params
.process_type
= process_type_
;
825 bool enable_nacl_debug
= enable_debug_stub_
&&
826 NaClBrowser::GetDelegate()->URLMatchesDebugPatterns(manifest_url_
);
827 if (uses_nonsfi_mode_
) {
828 // Currently, non-SFI mode is supported only on Linux.
829 #if defined(OS_LINUX)
830 // In non-SFI mode, we do not use SRPC. Make sure that the socketpair is
832 DCHECK(!socket_for_sel_ldr_
.IsValid());
834 if (enable_nacl_debug
) {
835 base::ProcessId pid
= base::GetProcId(process_
->GetData().handle
);
836 LOG(WARNING
) << "nonsfi nacl plugin running in " << pid
;
839 params
.validation_cache_enabled
= nacl_browser
->ValidationCacheIsEnabled();
840 params
.validation_cache_key
= nacl_browser
->GetValidationCacheKey();
841 params
.version
= NaClBrowser::GetDelegate()->GetVersionString();
842 params
.enable_debug_stub
= enable_nacl_debug
;
843 params
.enable_mojo
= base::CommandLine::ForCurrentProcess()->HasSwitch(
844 switches::kEnableNaClMojo
);
846 const ChildProcessData
& data
= process_
->GetData();
847 if (!ShareHandleToSelLdr(data
.handle
,
848 socket_for_sel_ldr_
.TakePlatformFile(),
854 const base::File
& irt_file
= nacl_browser
->IrtFile();
855 CHECK(irt_file
.IsValid());
856 // Send over the IRT file handle. We don't close our own copy!
857 if (!ShareHandleToSelLdr(data
.handle
, irt_file
.GetPlatformFile(), false,
862 #if defined(OS_MACOSX)
863 // For dynamic loading support, NaCl requires a file descriptor that
864 // was created in /tmp, since those created with shm_open() are not
865 // mappable with PROT_EXEC. Rather than requiring an extra IPC
866 // round trip out of the sandbox, we create an FD here.
867 base::SharedMemory memory_buffer
;
868 base::SharedMemoryCreateOptions options
;
870 options
.executable
= true;
871 if (!memory_buffer
.Create(options
)) {
872 DLOG(ERROR
) << "Failed to allocate memory buffer";
875 FileDescriptor memory_fd
;
876 memory_fd
.fd
= dup(memory_buffer
.handle().fd
);
877 if (memory_fd
.fd
< 0) {
878 DLOG(ERROR
) << "Failed to dup() a file descriptor";
881 memory_fd
.auto_close
= true;
882 params
.handles
.push_back(memory_fd
);
885 #if defined(OS_POSIX)
886 if (params
.enable_debug_stub
) {
887 net::SocketDescriptor server_bound_socket
= GetDebugStubSocketHandle();
888 if (server_bound_socket
!= net::kInvalidSocket
) {
889 params
.debug_stub_server_bound_socket
=
890 FileDescriptor(server_bound_socket
, true);
896 if (!crash_info_shmem_
.ShareToProcess(process_
->GetData().handle
,
897 ¶ms
.crash_info_shmem_handle
)) {
898 DLOG(ERROR
) << "Failed to ShareToProcess() a shared memory buffer";
902 base::FilePath file_path
;
903 if (uses_nonsfi_mode_
) {
904 // Don't retrieve the file path when using nonsfi mode; there's no
905 // validation caching in that case, so it's unnecessary work, and would
906 // expose the file path to the plugin.
908 // Pass the pre-opened resource files to the loader. For the same reason
909 // as above, use an empty base::FilePath.
910 for (size_t i
= 0; i
< prefetched_resource_files_info_
.size(); ++i
) {
911 params
.prefetched_resource_files
.push_back(
912 NaClResourceFileInfo(prefetched_resource_files_info_
[i
].file
,
914 prefetched_resource_files_info_
[i
].file_key
));
916 prefetched_resource_files_info_
.clear();
918 if (NaClBrowser::GetInstance()->GetFilePath(nexe_token_
.lo
,
921 // We have to reopen the file in the browser process; we don't want a
922 // compromised renderer to pass an arbitrary fd that could get loaded
923 // into the plugin process.
924 if (base::PostTaskAndReplyWithResult(
925 content::BrowserThread::GetBlockingPool(),
927 base::Bind(OpenNaClReadExecImpl
,
929 true /* is_executable */),
930 base::Bind(&NaClProcessHost::StartNaClFileResolved
,
931 weak_factory_
.GetWeakPtr(),
937 // TODO(yusukes): Handle |prefetched_resource_files_info_| for SFI-NaCl.
938 DCHECK(prefetched_resource_files_info_
.empty());
941 params
.nexe_file
= IPC::TakeFileHandleForProcess(nexe_file_
.Pass(),
942 process_
->GetData().handle
);
943 process_
->Send(new NaClProcessMsg_Start(params
));
947 void NaClProcessHost::StartNaClFileResolved(
948 NaClStartParams params
,
949 const base::FilePath
& file_path
,
950 base::File checked_nexe_file
) {
951 if (checked_nexe_file
.IsValid()) {
952 // Release the file received from the renderer. This has to be done on a
953 // thread where IO is permitted, though.
954 content::BrowserThread::GetBlockingPool()->PostTask(
956 base::Bind(&CloseFile
, base::Passed(nexe_file_
.Pass())));
957 params
.nexe_file_path_metadata
= file_path
;
958 params
.nexe_file
= IPC::TakeFileHandleForProcess(
959 checked_nexe_file
.Pass(), process_
->GetData().handle
);
961 params
.nexe_file
= IPC::TakeFileHandleForProcess(
962 nexe_file_
.Pass(), process_
->GetData().handle
);
964 process_
->Send(new NaClProcessMsg_Start(params
));
967 // This method is called when NaClProcessHostMsg_PpapiChannelCreated is
969 void NaClProcessHost::OnPpapiChannelsCreated(
970 const IPC::ChannelHandle
& browser_channel_handle
,
971 const IPC::ChannelHandle
& ppapi_renderer_channel_handle
,
972 const IPC::ChannelHandle
& trusted_renderer_channel_handle
,
973 const IPC::ChannelHandle
& manifest_service_channel_handle
) {
974 if (!enable_ppapi_proxy()) {
975 ReplyToRenderer(IPC::ChannelHandle(),
976 trusted_renderer_channel_handle
,
977 manifest_service_channel_handle
);
981 if (!ipc_proxy_channel_
.get()) {
982 DCHECK_EQ(PROCESS_TYPE_NACL_LOADER
, process_
->GetData().process_type
);
985 IPC::ChannelProxy::Create(browser_channel_handle
,
986 IPC::Channel::MODE_CLIENT
,
988 base::MessageLoopProxy::current().get());
989 // Create the browser ppapi host and enable PPAPI message dispatching to the
991 ppapi_host_
.reset(content::BrowserPpapiHost::CreateExternalPluginProcess(
992 ipc_proxy_channel_
.get(), // sender
994 process_
->GetData().handle
,
995 ipc_proxy_channel_
.get(),
996 nacl_host_message_filter_
->render_process_id(),
998 profile_directory_
));
999 ppapi_host_
->SetOnKeepaliveCallback(
1000 NaClBrowser::GetDelegate()->GetOnKeepaliveCallback());
1002 ppapi::PpapiNaClPluginArgs args
;
1003 args
.off_the_record
= nacl_host_message_filter_
->off_the_record();
1004 args
.permissions
= permissions_
;
1005 args
.keepalive_throttle_interval_milliseconds
=
1006 keepalive_throttle_interval_milliseconds_
;
1007 base::CommandLine
* cmdline
= base::CommandLine::ForCurrentProcess();
1009 std::string flag_whitelist
[] = {
1013 for (size_t i
= 0; i
< arraysize(flag_whitelist
); ++i
) {
1014 std::string value
= cmdline
->GetSwitchValueASCII(flag_whitelist
[i
]);
1015 if (!value
.empty()) {
1016 args
.switch_names
.push_back(flag_whitelist
[i
]);
1017 args
.switch_values
.push_back(value
);
1021 ppapi_host_
->GetPpapiHost()->AddHostFactoryFilter(
1022 scoped_ptr
<ppapi::host::HostFactory
>(
1023 NaClBrowser::GetDelegate()->CreatePpapiHostFactory(
1024 ppapi_host_
.get())));
1026 // Send a message to initialize the IPC dispatchers in the NaCl plugin.
1027 ipc_proxy_channel_
->Send(new PpapiMsg_InitializeNaClDispatcher(args
));
1029 // Let the renderer know that the IPC channels are established.
1030 ReplyToRenderer(ppapi_renderer_channel_handle
,
1031 trusted_renderer_channel_handle
,
1032 manifest_service_channel_handle
);
1034 // Attempt to open more than 1 browser channel is not supported.
1035 // Shut down the NaCl process.
1036 process_
->GetHost()->ForceShutdown();
1040 bool NaClProcessHost::StartWithLaunchedProcess() {
1041 NaClBrowser
* nacl_browser
= NaClBrowser::GetInstance();
1043 if (nacl_browser
->IsReady()) {
1044 return StartNaClExecution();
1045 } else if (nacl_browser
->IsOk()) {
1046 nacl_browser
->WaitForResources(
1047 base::Bind(&NaClProcessHost::OnResourcesReady
,
1048 weak_factory_
.GetWeakPtr()));
1051 SendErrorToRenderer("previously failed to acquire shared resources");
1056 void NaClProcessHost::OnQueryKnownToValidate(const std::string
& signature
,
1058 CHECK(!uses_nonsfi_mode_
);
1059 NaClBrowser
* nacl_browser
= NaClBrowser::GetInstance();
1060 *result
= nacl_browser
->QueryKnownToValidate(signature
, off_the_record_
);
1063 void NaClProcessHost::OnSetKnownToValidate(const std::string
& signature
) {
1064 CHECK(!uses_nonsfi_mode_
);
1065 NaClBrowser::GetInstance()->SetKnownToValidate(
1066 signature
, off_the_record_
);
1069 void NaClProcessHost::OnResolveFileToken(uint64 file_token_lo
,
1070 uint64 file_token_hi
) {
1071 // Was the file registered?
1073 // Note that the file path cache is of bounded size, and old entries can get
1074 // evicted. If a large number of NaCl modules are being launched at once,
1075 // resolving the file_token may fail because the path cache was thrashed
1076 // while the file_token was in flight. In this case the query fails, and we
1077 // need to fall back to the slower path.
1079 // However: each NaCl process will consume 2-3 entries as it starts up, this
1080 // means that eviction will not happen unless you start up 33+ NaCl processes
1081 // at the same time, and this still requires worst-case timing. As a
1082 // practical matter, no entries should be evicted prematurely.
1083 // The cache itself should take ~ (150 characters * 2 bytes/char + ~60 bytes
1084 // data structure overhead) * 100 = 35k when full, so making it bigger should
1085 // not be a problem, if needed.
1087 // Each NaCl process will consume 2-3 entries because the manifest and main
1088 // nexe are currently not resolved. Shared libraries will be resolved. They
1089 // will be loaded sequentially, so they will only consume a single entry
1090 // while the load is in flight.
1092 // TODO(ncbray): track behavior with UMA. If entries are getting evicted or
1093 // bogus keys are getting queried, this would be good to know.
1094 CHECK(!uses_nonsfi_mode_
);
1095 base::FilePath file_path
;
1096 if (!NaClBrowser::GetInstance()->GetFilePath(
1097 file_token_lo
, file_token_hi
, &file_path
)) {
1098 Send(new NaClProcessMsg_ResolveFileTokenReply(
1101 IPC::PlatformFileForTransit(),
1107 if (!base::PostTaskAndReplyWithResult(
1108 content::BrowserThread::GetBlockingPool(),
1110 base::Bind(OpenNaClReadExecImpl
, file_path
, true /* is_executable */),
1111 base::Bind(&NaClProcessHost::FileResolved
,
1112 weak_factory_
.GetWeakPtr(),
1116 Send(new NaClProcessMsg_ResolveFileTokenReply(
1119 IPC::PlatformFileForTransit(),
1124 void NaClProcessHost::FileResolved(
1125 uint64_t file_token_lo
,
1126 uint64_t file_token_hi
,
1127 const base::FilePath
& file_path
,
1129 base::FilePath out_file_path
;
1130 IPC::PlatformFileForTransit out_handle
;
1131 if (file
.IsValid()) {
1132 out_file_path
= file_path
;
1133 out_handle
= IPC::TakeFileHandleForProcess(
1135 process_
->GetData().handle
);
1137 out_handle
= IPC::InvalidPlatformFileForTransit();
1139 Send(new NaClProcessMsg_ResolveFileTokenReply(
1147 void NaClProcessHost::OnAttachDebugExceptionHandler(const std::string
& info
,
1148 IPC::Message
* reply_msg
) {
1149 CHECK(!uses_nonsfi_mode_
);
1150 if (!AttachDebugExceptionHandler(info
, reply_msg
)) {
1151 // Send failure message.
1152 NaClProcessMsg_AttachDebugExceptionHandler::WriteReplyParams(reply_msg
,
1158 bool NaClProcessHost::AttachDebugExceptionHandler(const std::string
& info
,
1159 IPC::Message
* reply_msg
) {
1160 bool enable_exception_handling
= process_type_
== kNativeNaClProcessType
;
1161 if (!enable_exception_handling
&& !enable_debug_stub_
) {
1163 "Debug exception handler requested by NaCl process when not enabled";
1166 if (debug_exception_handler_requested_
) {
1167 // The NaCl process should not request this multiple times.
1168 DLOG(ERROR
) << "Multiple AttachDebugExceptionHandler requests received";
1171 debug_exception_handler_requested_
= true;
1173 base::ProcessId nacl_pid
= base::GetProcId(process_
->GetData().handle
);
1174 // We cannot use process_->GetData().handle because it does not have
1175 // the necessary access rights. We open the new handle here rather
1176 // than in the NaCl broker process in case the NaCl loader process
1177 // dies before the NaCl broker process receives the message we send.
1178 // The debug exception handler uses DebugActiveProcess() to attach,
1179 // but this takes a PID. We need to prevent the NaCl loader's PID
1180 // from being reused before DebugActiveProcess() is called, and
1181 // holding a process handle open achieves this.
1182 base::Process process
=
1183 base::Process::OpenWithAccess(nacl_pid
,
1184 PROCESS_QUERY_INFORMATION
|
1185 PROCESS_SUSPEND_RESUME
|
1187 PROCESS_VM_OPERATION
|
1190 PROCESS_DUP_HANDLE
|
1192 if (!process
.IsValid()) {
1193 LOG(ERROR
) << "Failed to get process handle";
1197 attach_debug_exception_handler_reply_msg_
.reset(reply_msg
);
1198 // If the NaCl loader is 64-bit, the process running its debug
1199 // exception handler must be 64-bit too, so we use the 64-bit NaCl
1200 // broker process for this. Otherwise, on a 32-bit system, we use
1201 // the 32-bit browser process to run the debug exception handler.
1202 if (RunningOnWOW64()) {
1203 return NaClBrokerService::GetInstance()->LaunchDebugExceptionHandler(
1204 weak_factory_
.GetWeakPtr(), nacl_pid
, process
.Handle(),
1207 NaClStartDebugExceptionHandlerThread(
1208 process
.Pass(), info
,
1209 base::MessageLoopProxy::current(),
1210 base::Bind(&NaClProcessHost::OnDebugExceptionHandlerLaunchedByBroker
,
1211 weak_factory_
.GetWeakPtr()));