Support Promise<T> syntax in the IDL parser.
[chromium-blink-merge.git] / components / nacl / browser / nacl_process_host.cc
blob3b6ddcf7050d0caa0f59588b5e4854146e7b4984
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"
7 #include <algorithm>
8 #include <string>
9 #include <vector>
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"
59 #if defined(OS_POSIX)
61 #include <fcntl.h>
63 #include "ipc/ipc_channel_posix.h"
64 #elif defined(OS_WIN)
65 #include <windows.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"
72 #endif
74 using content::BrowserThread;
75 using content::ChildProcessData;
76 using content::ChildProcessHost;
77 using ppapi::proxy::SerializedHandle;
79 namespace nacl {
81 #if defined(OS_WIN)
82 namespace {
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) {
88 *out_addr = NULL;
89 *out_size = 0;
90 char* addr = 0;
91 while (true) {
92 MEMORY_BASIC_INFORMATION info;
93 size_t result = VirtualQueryEx(process, static_cast<void*>(addr),
94 &info, sizeof(info));
95 if (result < sizeof(info))
96 break;
97 if (info.State == MEM_FREE && info.RegionSize > *out_size) {
98 *out_addr = addr;
99 *out_size = info.RegionSize;
101 addr += info.RegionSize;
105 #ifdef _DLL
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());
111 i != split.end();
112 ++i) {
113 if (*i == dir)
114 return true;
116 return false;
119 #endif // _DLL
121 } // namespace
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) {
126 char* addr;
127 size_t avail_size;
128 FindAddressSpace(process, &addr, &avail_size);
129 if (avail_size < size)
130 return NULL;
131 size_t offset = base::RandGenerator(avail_size - size);
132 const int kPageSize = 0x10000;
133 void* request_addr =
134 reinterpret_cast<void*>(reinterpret_cast<uint64>(addr + offset)
135 & ~(kPageSize - 1));
136 return VirtualAllocEx(process, request_addr, size,
137 MEM_RESERVE, PAGE_NOACCESS);
140 namespace {
142 bool RunningOnWOW64() {
143 return (base::win::OSInfo::GetInstance()->wow64_status() ==
144 base::win::OSInfo::WOW64_ENABLED);
147 } // namespace
149 #endif // defined(OS_WIN)
151 namespace {
153 // NOTE: changes to this class need to be reviewed by the security team.
154 class NaClSandboxedProcessLauncherDelegate
155 : public content::SandboxedProcessLauncherDelegate {
156 public:
157 NaClSandboxedProcessLauncherDelegate(ChildProcessHost* host)
158 #if defined(OS_POSIX)
159 : ipc_fd_(host->TakeClientFileDescriptor())
160 #endif
163 virtual ~NaClSandboxedProcessLauncherDelegate() {}
165 #if defined(OS_WIN)
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 virtual bool ShouldUseZygote() override {
180 return true;
182 virtual int GetIpcFd() override {
183 return ipc_fd_;
185 #endif // OS_WIN
187 private:
188 #if defined(OS_POSIX)
189 int ipc_fd_;
190 #endif // OS_POSIX
193 void SetCloseOnExec(NaClHandle fd) {
194 #if defined(OS_POSIX)
195 int flags = fcntl(fd, F_GETFD);
196 CHECK_NE(flags, -1);
197 int rc = fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
198 CHECK_EQ(rc, 0);
199 #endif
202 bool ShareHandleToSelLdr(
203 base::ProcessHandle processh,
204 NaClHandle sourceh,
205 bool close_source,
206 std::vector<nacl::FileDescriptor> *handles_for_sel_ldr) {
207 #if defined(OS_WIN)
208 HANDLE channel;
209 int flags = DUPLICATE_SAME_ACCESS;
210 if (close_source)
211 flags |= DUPLICATE_CLOSE_SOURCE;
212 if (!DuplicateHandle(GetCurrentProcess(),
213 reinterpret_cast<HANDLE>(sourceh),
214 processh,
215 &channel,
216 0, // Unused given DUPLICATE_SAME_ACCESS.
217 FALSE,
218 flags)) {
219 LOG(ERROR) << "DuplicateHandle() failed";
220 return false;
222 handles_for_sel_ldr->push_back(
223 reinterpret_cast<nacl::FileDescriptor>(channel));
224 #else
225 nacl::FileDescriptor channel;
226 channel.fd = sourceh;
227 channel.auto_close = close_source;
228 handles_for_sel_ldr->push_back(channel);
229 #endif
230 return true;
233 } // namespace
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,
242 int render_view_id,
243 uint32 permission_bits,
244 bool uses_nonsfi_mode,
245 bool off_the_record,
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),
252 #if defined(OS_WIN)
253 process_launched_by_broker_(false),
254 #endif
255 reply_msg_(NULL),
256 #if defined(OS_WIN)
257 debug_exception_handler_requested_(false),
258 #endif
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) {
285 int exit_code = 0;
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) {
291 VLOG(1) << message;
292 } else {
293 LOG(ERROR) << message;
295 NaClBrowser::GetInstance()->OnProcessEnd(process_->GetData().id);
298 if (reply_msg_) {
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_);
304 #if defined(OS_WIN)
305 if (process_launched_by_broker_) {
306 NaClBrokerService::GetInstance()->OnLoaderDied();
308 #endif
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.
320 // static
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();
328 #endif
329 CommandLine* cmd = CommandLine::ForCurrentProcess();
330 UMA_HISTOGRAM_BOOLEAN(
331 "NaCl.nacl-gdb",
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);
350 // static
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"
371 " crashes");
372 delete this;
373 return;
376 const CommandLine* cmd = CommandLine::ForCurrentProcess();
377 #if defined(OS_WIN)
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.");
383 delete this;
384 return;
386 #endif
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");
399 delete this;
400 return;
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_);
412 #endif
413 #endif
414 bool nonsfi_mode_enabled =
415 nonsfi_mode_forced_by_command_line || nonsfi_mode_allowed;
417 if (!nonsfi_mode_enabled) {
418 SendErrorToRenderer(
419 "NaCl non-SFI mode is not available for this platform"
420 " and NaCl module.");
421 delete this;
422 return;
424 } else {
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
432 // browser process.
434 NaClHandle pair[2];
435 // Create a connected socket
436 if (NaClSocketPair(pair) == -1) {
437 SendErrorToRenderer("NaClSocketPair() failed");
438 delete this;
439 return;
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()) {
453 delete this;
457 void NaClProcessHost::OnChannelConnected(int32 peer_pid) {
458 if (!CommandLine::ForCurrentProcess()->GetSwitchValuePath(
459 switches::kNaClGdb).empty()) {
460 LaunchNaClGdb();
464 #if defined(OS_WIN)
465 void NaClProcessHost::OnProcessLaunchedByBroker(base::ProcessHandle handle) {
466 process_launched_by_broker_ = true;
467 process_->SetHandle(handle);
468 SetDebugStubPort(nacl::kGdbDebugStubPortUnknown);
469 if (!StartWithLaunchedProcess())
470 delete this;
473 void NaClProcessHost::OnDebugExceptionHandlerLaunchedByBroker(bool success) {
474 IPC::Message* reply = attach_debug_exception_handler_reply_msg_.release();
475 NaClProcessMsg_AttachDebugExceptionHandler::WriteReplyParams(reply, success);
476 Send(reply);
478 #endif
480 // Needed to handle sync messages in OnMessageReceived.
481 bool NaClProcessHost::Send(IPC::Message* msg) {
482 return process_->Send(msg);
485 bool NaClProcessHost::LaunchNaClGdb() {
486 #if defined(OS_WIN)
487 base::FilePath nacl_gdb =
488 CommandLine::ForCurrentProcess()->GetSwitchValuePath(switches::kNaClGdb);
489 CommandLine cmd_line(nacl_gdb);
490 #else
491 CommandLine::StringType nacl_gdb =
492 CommandLine::ForCurrentProcess()->GetSwitchValueNative(
493 switches::kNaClGdb);
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);
498 #endif
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(),
511 '\\', '/');
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");
530 return false;
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;
545 #else
546 int flags = ChildProcessHost::CHILD_NORMAL;
547 #endif
549 base::FilePath exe_path = ChildProcessHost::GetChildPath(flags);
550 if (exe_path.empty())
551 return false;
553 #if defined(OS_WIN)
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");
558 return false;
561 #ifdef _DLL
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");
574 return false;
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);
586 #endif // _DLL
588 #endif
590 scoped_ptr<CommandLine> cmd_line(new CommandLine(exe_path));
591 CopyNaClCommandLineArguments(cmd_line.get());
593 cmd_line->AppendSwitchASCII(switches::kProcessType,
594 (uses_nonsfi_mode_ ?
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
602 #if defined(OS_WIN)
603 if (RunningOnWOW64()) {
604 if (!NaClBrokerService::GetInstance()->LaunchLoader(
605 weak_factory_.GetWeakPtr(), channel_id)) {
606 SendErrorToRenderer("broker service did not launch process");
607 return false;
609 return true;
611 #endif
612 process_->Launch(
613 new NaClSandboxedProcessLauncherDelegate(process_->GetHost()),
614 cmd_line.release());
615 return true;
618 bool NaClProcessHost::OnMessageReceived(const IPC::Message& msg) {
619 bool handled = true;
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()
629 } else {
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_DELAY_REPLY(NaClProcessMsg_ResolveFileToken,
636 OnResolveFileToken)
637 IPC_MESSAGE_HANDLER(NaClProcessMsg_ResolveFileTokenAsync,
638 OnResolveFileTokenAsync)
640 #if defined(OS_WIN)
641 IPC_MESSAGE_HANDLER_DELAY_REPLY(
642 NaClProcessMsg_AttachDebugExceptionHandler,
643 OnAttachDebugExceptionHandler)
644 IPC_MESSAGE_HANDLER(NaClProcessHostMsg_DebugStubPortSelected,
645 OnDebugStubPortSelected)
646 #endif
647 IPC_MESSAGE_HANDLER(NaClProcessHostMsg_PpapiChannelsCreated,
648 OnPpapiChannelsCreated)
649 IPC_MESSAGE_UNHANDLED(handled = false)
650 IPC_END_MESSAGE_MAP()
652 return handled;
655 void NaClProcessHost::OnProcessLaunched() {
656 if (!StartWithLaunchedProcess())
657 delete this;
660 // Called when the NaClBrowser singleton has been fully initialized.
661 void NaClProcessHost::OnResourcesReady() {
662 NaClBrowser* nacl_browser = NaClBrowser::GetInstance();
663 if (!nacl_browser->IsReady()) {
664 SendErrorToRenderer("could not acquire shared resources needed by NaCl");
665 delete this;
666 } else if (!StartNaClExecution()) {
667 delete this;
671 bool NaClProcessHost::ReplyToRenderer(
672 const IPC::ChannelHandle& ppapi_channel_handle,
673 const IPC::ChannelHandle& trusted_channel_handle,
674 const IPC::ChannelHandle& manifest_service_channel_handle) {
675 #if defined(OS_WIN)
676 // If we are on 64-bit Windows, the NaCl process's sandbox is
677 // managed by a different process from the renderer's sandbox. We
678 // need to inform the renderer's sandbox about the NaCl process so
679 // that the renderer can send handles to the NaCl process using
680 // BrokerDuplicateHandle().
681 if (RunningOnWOW64()) {
682 if (!content::BrokerAddTargetPeer(process_->GetData().handle)) {
683 SendErrorToRenderer("BrokerAddTargetPeer() failed");
684 return false;
687 #endif
689 FileDescriptor imc_handle_for_renderer;
690 #if defined(OS_WIN)
691 // Copy the handle into the renderer process.
692 HANDLE handle_in_renderer;
693 if (!DuplicateHandle(base::GetCurrentProcessHandle(),
694 socket_for_renderer_.TakePlatformFile(),
695 nacl_host_message_filter_->PeerHandle(),
696 &handle_in_renderer,
697 0, // Unused given DUPLICATE_SAME_ACCESS.
698 FALSE,
699 DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS)) {
700 SendErrorToRenderer("DuplicateHandle() failed");
701 return false;
703 imc_handle_for_renderer = reinterpret_cast<FileDescriptor>(
704 handle_in_renderer);
705 #else
706 // No need to dup the imc_handle - we don't pass it anywhere else so
707 // it cannot be closed.
708 FileDescriptor imc_handle;
709 imc_handle.fd = socket_for_renderer_.TakePlatformFile();
710 imc_handle.auto_close = true;
711 imc_handle_for_renderer = imc_handle;
712 #endif
714 const ChildProcessData& data = process_->GetData();
715 base::SharedMemoryHandle crash_info_shmem_renderer_handle;
716 if (!crash_info_shmem_.ShareToProcess(nacl_host_message_filter_->PeerHandle(),
717 &crash_info_shmem_renderer_handle)) {
718 SendErrorToRenderer("ShareToProcess() failed");
719 return false;
722 SendMessageToRenderer(
723 NaClLaunchResult(imc_handle_for_renderer,
724 ppapi_channel_handle,
725 trusted_channel_handle,
726 manifest_service_channel_handle,
727 base::GetProcId(data.handle),
728 data.id,
729 crash_info_shmem_renderer_handle),
730 std::string() /* error_message */);
732 // Now that the crash information shmem handles have been shared with the
733 // plugin and the renderer, the browser can close its handle.
734 crash_info_shmem_.Close();
735 return true;
738 void NaClProcessHost::SendErrorToRenderer(const std::string& error_message) {
739 LOG(ERROR) << "NaCl process launch failed: " << error_message;
740 SendMessageToRenderer(NaClLaunchResult(), error_message);
743 void NaClProcessHost::SendMessageToRenderer(
744 const NaClLaunchResult& result,
745 const std::string& error_message) {
746 DCHECK(nacl_host_message_filter_.get());
747 DCHECK(reply_msg_);
748 if (nacl_host_message_filter_.get() != NULL && reply_msg_ != NULL) {
749 NaClHostMsg_LaunchNaCl::WriteReplyParams(
750 reply_msg_, result, error_message);
751 nacl_host_message_filter_->Send(reply_msg_);
752 nacl_host_message_filter_ = NULL;
753 reply_msg_ = NULL;
757 void NaClProcessHost::SetDebugStubPort(int port) {
758 NaClBrowser* nacl_browser = NaClBrowser::GetInstance();
759 nacl_browser->SetProcessGdbDebugStubPort(process_->GetData().id, port);
762 #if defined(OS_POSIX)
763 // TCP port we chose for NaCl debug stub. It can be any other number.
764 static const int kInitialDebugStubPort = 4014;
766 net::SocketDescriptor NaClProcessHost::GetDebugStubSocketHandle() {
767 net::SocketDescriptor s = net::kInvalidSocket;
768 // We always try to allocate the default port first. If this fails, we then
769 // allocate any available port.
770 // On success, if the test system has register a handler
771 // (GdbDebugStubPortListener), we fire a notification.
772 int port = kInitialDebugStubPort;
773 s = net::TCPListenSocket::CreateAndBind("127.0.0.1", port);
774 if (s == net::kInvalidSocket) {
775 s = net::TCPListenSocket::CreateAndBindAnyPort("127.0.0.1", &port);
777 if (s != net::kInvalidSocket) {
778 SetDebugStubPort(port);
780 if (s == net::kInvalidSocket) {
781 LOG(ERROR) << "failed to open socket for debug stub";
782 return net::kInvalidSocket;
783 } else {
784 LOG(WARNING) << "debug stub on port " << port;
786 if (listen(s, 1)) {
787 LOG(ERROR) << "listen() failed on debug stub socket";
788 if (IGNORE_EINTR(close(s)) < 0)
789 PLOG(ERROR) << "failed to close debug stub socket";
790 return net::kInvalidSocket;
792 return s;
794 #endif
796 #if defined(OS_WIN)
797 void NaClProcessHost::OnDebugStubPortSelected(uint16_t debug_stub_port) {
798 CHECK(!uses_nonsfi_mode_);
799 SetDebugStubPort(debug_stub_port);
801 #endif
803 bool NaClProcessHost::StartNaClExecution() {
804 NaClBrowser* nacl_browser = NaClBrowser::GetInstance();
806 NaClStartParams params;
808 // Enable PPAPI proxy channel creation only for renderer processes.
809 params.enable_ipc_proxy = enable_ppapi_proxy();
810 params.process_type = process_type_;
811 if (uses_nonsfi_mode_) {
812 // Currently, non-SFI mode is supported only on Linux.
813 #if defined(OS_LINUX)
814 // In non-SFI mode, we do not use SRPC. Make sure that the socketpair is
815 // not created.
816 DCHECK(!socket_for_sel_ldr_.IsValid());
817 #endif
818 } else {
819 params.validation_cache_enabled = nacl_browser->ValidationCacheIsEnabled();
820 params.validation_cache_key = nacl_browser->GetValidationCacheKey();
821 params.version = NaClBrowser::GetDelegate()->GetVersionString();
822 params.enable_debug_stub = enable_debug_stub_ &&
823 NaClBrowser::GetDelegate()->URLMatchesDebugPatterns(manifest_url_);
825 // TODO(teravest): Resolve the file tokens right now instead of making the
826 // loader send IPC to resolve them later.
827 params.nexe_token_lo = nexe_token_.lo;
828 params.nexe_token_hi = nexe_token_.hi;
830 const ChildProcessData& data = process_->GetData();
831 if (!ShareHandleToSelLdr(data.handle,
832 socket_for_sel_ldr_.TakePlatformFile(),
833 true,
834 &params.handles)) {
835 return false;
838 // Currently, everything uses the IRT except for the PNaCl Translators.
839 bool uses_irt = process_type_ != kPNaClTranslatorProcessType;
840 if (uses_irt) {
841 const base::File& irt_file = nacl_browser->IrtFile();
842 CHECK(irt_file.IsValid());
843 // Send over the IRT file handle. We don't close our own copy!
844 if (!ShareHandleToSelLdr(data.handle, irt_file.GetPlatformFile(), false,
845 &params.handles)) {
846 return false;
850 #if defined(OS_MACOSX)
851 // For dynamic loading support, NaCl requires a file descriptor that
852 // was created in /tmp, since those created with shm_open() are not
853 // mappable with PROT_EXEC. Rather than requiring an extra IPC
854 // round trip out of the sandbox, we create an FD here.
855 base::SharedMemory memory_buffer;
856 base::SharedMemoryCreateOptions options;
857 options.size = 1;
858 options.executable = true;
859 if (!memory_buffer.Create(options)) {
860 DLOG(ERROR) << "Failed to allocate memory buffer";
861 return false;
863 FileDescriptor memory_fd;
864 memory_fd.fd = dup(memory_buffer.handle().fd);
865 if (memory_fd.fd < 0) {
866 DLOG(ERROR) << "Failed to dup() a file descriptor";
867 return false;
869 memory_fd.auto_close = true;
870 params.handles.push_back(memory_fd);
871 #endif
873 #if defined(OS_POSIX)
874 if (params.enable_debug_stub) {
875 net::SocketDescriptor server_bound_socket = GetDebugStubSocketHandle();
876 if (server_bound_socket != net::kInvalidSocket) {
877 params.debug_stub_server_bound_socket =
878 FileDescriptor(server_bound_socket, true);
881 #endif
884 params.nexe_file = IPC::TakeFileHandleForProcess(nexe_file_.Pass(),
885 process_->GetData().handle);
886 if (!crash_info_shmem_.ShareToProcess(process_->GetData().handle,
887 &params.crash_info_shmem_handle)) {
888 DLOG(ERROR) << "Failed to ShareToProcess() a shared memory buffer";
889 return false;
892 process_->Send(new NaClProcessMsg_Start(params));
893 return true;
896 // This method is called when NaClProcessHostMsg_PpapiChannelCreated is
897 // received.
898 void NaClProcessHost::OnPpapiChannelsCreated(
899 const IPC::ChannelHandle& browser_channel_handle,
900 const IPC::ChannelHandle& ppapi_renderer_channel_handle,
901 const IPC::ChannelHandle& trusted_renderer_channel_handle,
902 const IPC::ChannelHandle& manifest_service_channel_handle) {
903 if (!enable_ppapi_proxy()) {
904 ReplyToRenderer(IPC::ChannelHandle(),
905 trusted_renderer_channel_handle,
906 manifest_service_channel_handle);
907 return;
910 if (!ipc_proxy_channel_.get()) {
911 DCHECK_EQ(PROCESS_TYPE_NACL_LOADER, process_->GetData().process_type);
913 ipc_proxy_channel_ =
914 IPC::ChannelProxy::Create(browser_channel_handle,
915 IPC::Channel::MODE_CLIENT,
916 NULL,
917 base::MessageLoopProxy::current().get());
918 // Create the browser ppapi host and enable PPAPI message dispatching to the
919 // browser process.
920 ppapi_host_.reset(content::BrowserPpapiHost::CreateExternalPluginProcess(
921 ipc_proxy_channel_.get(), // sender
922 permissions_,
923 process_->GetData().handle,
924 ipc_proxy_channel_.get(),
925 nacl_host_message_filter_->render_process_id(),
926 render_view_id_,
927 profile_directory_));
928 ppapi_host_->SetOnKeepaliveCallback(
929 NaClBrowser::GetDelegate()->GetOnKeepaliveCallback());
931 ppapi::PpapiNaClPluginArgs args;
932 args.off_the_record = nacl_host_message_filter_->off_the_record();
933 args.permissions = permissions_;
934 args.keepalive_throttle_interval_milliseconds =
935 keepalive_throttle_interval_milliseconds_;
936 CommandLine* cmdline = CommandLine::ForCurrentProcess();
937 DCHECK(cmdline);
938 std::string flag_whitelist[] = {
939 switches::kV,
940 switches::kVModule,
942 for (size_t i = 0; i < arraysize(flag_whitelist); ++i) {
943 std::string value = cmdline->GetSwitchValueASCII(flag_whitelist[i]);
944 if (!value.empty()) {
945 args.switch_names.push_back(flag_whitelist[i]);
946 args.switch_values.push_back(value);
950 ppapi_host_->GetPpapiHost()->AddHostFactoryFilter(
951 scoped_ptr<ppapi::host::HostFactory>(
952 NaClBrowser::GetDelegate()->CreatePpapiHostFactory(
953 ppapi_host_.get())));
955 // Send a message to initialize the IPC dispatchers in the NaCl plugin.
956 ipc_proxy_channel_->Send(new PpapiMsg_InitializeNaClDispatcher(args));
958 // Let the renderer know that the IPC channels are established.
959 ReplyToRenderer(ppapi_renderer_channel_handle,
960 trusted_renderer_channel_handle,
961 manifest_service_channel_handle);
962 } else {
963 // Attempt to open more than 1 browser channel is not supported.
964 // Shut down the NaCl process.
965 process_->GetHost()->ForceShutdown();
969 bool NaClProcessHost::StartWithLaunchedProcess() {
970 NaClBrowser* nacl_browser = NaClBrowser::GetInstance();
972 if (nacl_browser->IsReady()) {
973 return StartNaClExecution();
974 } else if (nacl_browser->IsOk()) {
975 nacl_browser->WaitForResources(
976 base::Bind(&NaClProcessHost::OnResourcesReady,
977 weak_factory_.GetWeakPtr()));
978 return true;
979 } else {
980 SendErrorToRenderer("previously failed to acquire shared resources");
981 return false;
985 void NaClProcessHost::OnQueryKnownToValidate(const std::string& signature,
986 bool* result) {
987 CHECK(!uses_nonsfi_mode_);
988 NaClBrowser* nacl_browser = NaClBrowser::GetInstance();
989 *result = nacl_browser->QueryKnownToValidate(signature, off_the_record_);
992 void NaClProcessHost::OnSetKnownToValidate(const std::string& signature) {
993 CHECK(!uses_nonsfi_mode_);
994 NaClBrowser::GetInstance()->SetKnownToValidate(
995 signature, off_the_record_);
998 void NaClProcessHost::OnResolveFileToken(uint64 file_token_lo,
999 uint64 file_token_hi,
1000 IPC::Message* reply_msg) {
1001 // Was the file registered?
1003 // Note that the file path cache is of bounded size, and old entries can get
1004 // evicted. If a large number of NaCl modules are being launched at once,
1005 // resolving the file_token may fail because the path cache was thrashed
1006 // while the file_token was in flight. In this case the query fails, and we
1007 // need to fall back to the slower path.
1009 // However: each NaCl process will consume 2-3 entries as it starts up, this
1010 // means that eviction will not happen unless you start up 33+ NaCl processes
1011 // at the same time, and this still requires worst-case timing. As a
1012 // practical matter, no entries should be evicted prematurely.
1013 // The cache itself should take ~ (150 characters * 2 bytes/char + ~60 bytes
1014 // data structure overhead) * 100 = 35k when full, so making it bigger should
1015 // not be a problem, if needed.
1017 // Each NaCl process will consume 2-3 entries because the manifest and main
1018 // nexe are currently not resolved. Shared libraries will be resolved. They
1019 // will be loaded sequentially, so they will only consume a single entry
1020 // while the load is in flight.
1022 // TODO(ncbray): track behavior with UMA. If entries are getting evicted or
1023 // bogus keys are getting queried, this would be good to know.
1024 CHECK(!uses_nonsfi_mode_);
1025 base::FilePath file_path;
1026 if (!NaClBrowser::GetInstance()->GetFilePath(
1027 file_token_lo, file_token_hi, &file_path)) {
1028 NaClProcessMsg_ResolveFileToken::WriteReplyParams(
1029 reply_msg,
1030 IPC::InvalidPlatformFileForTransit(),
1031 base::FilePath());
1032 Send(reply_msg);
1033 return;
1036 // Open the file.
1037 if (!base::PostTaskAndReplyWithResult(
1038 content::BrowserThread::GetBlockingPool(),
1039 FROM_HERE,
1040 base::Bind(OpenNaClReadExecImpl, file_path, true /* is_executable */),
1041 base::Bind(&NaClProcessHost::FileResolved,
1042 weak_factory_.GetWeakPtr(),
1043 file_path,
1044 reply_msg))) {
1045 NaClProcessMsg_ResolveFileToken::WriteReplyParams(
1046 reply_msg,
1047 IPC::InvalidPlatformFileForTransit(),
1048 base::FilePath());
1049 Send(reply_msg);
1053 void NaClProcessHost::OnResolveFileTokenAsync(uint64 file_token_lo,
1054 uint64 file_token_hi) {
1055 // See the comment at OnResolveFileToken() for details of the file path cache
1056 // behavior.
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_ResolveFileTokenAsyncReply(
1062 file_token_lo,
1063 file_token_hi,
1064 IPC::PlatformFileForTransit(),
1065 base::FilePath()));
1066 return;
1069 // Open the file.
1070 if (!base::PostTaskAndReplyWithResult(
1071 content::BrowserThread::GetBlockingPool(),
1072 FROM_HERE,
1073 base::Bind(OpenNaClReadExecImpl, file_path, true /* is_executable */),
1074 base::Bind(&NaClProcessHost::FileResolvedAsync,
1075 weak_factory_.GetWeakPtr(),
1076 file_token_lo,
1077 file_token_hi,
1078 file_path))) {
1079 Send(new NaClProcessMsg_ResolveFileTokenAsyncReply(
1080 file_token_lo,
1081 file_token_hi,
1082 IPC::PlatformFileForTransit(),
1083 base::FilePath()));
1087 void NaClProcessHost::FileResolved(
1088 const base::FilePath& file_path,
1089 IPC::Message* reply_msg,
1090 base::File file) {
1091 if (file.IsValid()) {
1092 IPC::PlatformFileForTransit handle = IPC::TakeFileHandleForProcess(
1093 file.Pass(),
1094 process_->GetData().handle);
1095 NaClProcessMsg_ResolveFileToken::WriteReplyParams(
1096 reply_msg,
1097 handle,
1098 file_path);
1099 } else {
1100 NaClProcessMsg_ResolveFileToken::WriteReplyParams(
1101 reply_msg,
1102 IPC::InvalidPlatformFileForTransit(),
1103 base::FilePath());
1105 Send(reply_msg);
1108 void NaClProcessHost::FileResolvedAsync(
1109 uint64_t file_token_lo,
1110 uint64_t file_token_hi,
1111 const base::FilePath& file_path,
1112 base::File file) {
1113 base::FilePath out_file_path;
1114 IPC::PlatformFileForTransit out_handle;
1115 if (file.IsValid()) {
1116 out_file_path = file_path;
1117 out_handle = IPC::TakeFileHandleForProcess(
1118 file.Pass(),
1119 process_->GetData().handle);
1120 } else {
1121 out_handle = IPC::InvalidPlatformFileForTransit();
1123 Send(new NaClProcessMsg_ResolveFileTokenAsyncReply(
1124 file_token_lo,
1125 file_token_hi,
1126 out_handle,
1127 out_file_path));
1130 #if defined(OS_WIN)
1131 void NaClProcessHost::OnAttachDebugExceptionHandler(const std::string& info,
1132 IPC::Message* reply_msg) {
1133 CHECK(!uses_nonsfi_mode_);
1134 if (!AttachDebugExceptionHandler(info, reply_msg)) {
1135 // Send failure message.
1136 NaClProcessMsg_AttachDebugExceptionHandler::WriteReplyParams(reply_msg,
1137 false);
1138 Send(reply_msg);
1142 bool NaClProcessHost::AttachDebugExceptionHandler(const std::string& info,
1143 IPC::Message* reply_msg) {
1144 bool enable_exception_handling = process_type_ == kNativeNaClProcessType;
1145 if (!enable_exception_handling && !enable_debug_stub_) {
1146 DLOG(ERROR) <<
1147 "Debug exception handler requested by NaCl process when not enabled";
1148 return false;
1150 if (debug_exception_handler_requested_) {
1151 // The NaCl process should not request this multiple times.
1152 DLOG(ERROR) << "Multiple AttachDebugExceptionHandler requests received";
1153 return false;
1155 debug_exception_handler_requested_ = true;
1157 base::ProcessId nacl_pid = base::GetProcId(process_->GetData().handle);
1158 base::ProcessHandle temp_handle;
1159 // We cannot use process_->GetData().handle because it does not have
1160 // the necessary access rights. We open the new handle here rather
1161 // than in the NaCl broker process in case the NaCl loader process
1162 // dies before the NaCl broker process receives the message we send.
1163 // The debug exception handler uses DebugActiveProcess() to attach,
1164 // but this takes a PID. We need to prevent the NaCl loader's PID
1165 // from being reused before DebugActiveProcess() is called, and
1166 // holding a process handle open achieves this.
1167 if (!base::OpenProcessHandleWithAccess(
1168 nacl_pid,
1169 base::kProcessAccessQueryInformation |
1170 base::kProcessAccessSuspendResume |
1171 base::kProcessAccessTerminate |
1172 base::kProcessAccessVMOperation |
1173 base::kProcessAccessVMRead |
1174 base::kProcessAccessVMWrite |
1175 base::kProcessAccessDuplicateHandle |
1176 base::kProcessAccessWaitForTermination,
1177 &temp_handle)) {
1178 LOG(ERROR) << "Failed to get process handle";
1179 return false;
1181 base::win::ScopedHandle process_handle(temp_handle);
1183 attach_debug_exception_handler_reply_msg_.reset(reply_msg);
1184 // If the NaCl loader is 64-bit, the process running its debug
1185 // exception handler must be 64-bit too, so we use the 64-bit NaCl
1186 // broker process for this. Otherwise, on a 32-bit system, we use
1187 // the 32-bit browser process to run the debug exception handler.
1188 if (RunningOnWOW64()) {
1189 return NaClBrokerService::GetInstance()->LaunchDebugExceptionHandler(
1190 weak_factory_.GetWeakPtr(), nacl_pid, process_handle.Get(),
1191 info);
1192 } else {
1193 NaClStartDebugExceptionHandlerThread(
1194 process_handle.Take(), info,
1195 base::MessageLoopProxy::current(),
1196 base::Bind(&NaClProcessHost::OnDebugExceptionHandlerLaunchedByBroker,
1197 weak_factory_.GetWeakPtr()));
1198 return true;
1201 #endif
1203 } // namespace nacl