nacl_process_host.cc revision 03b57e008b61dfcb1fbad3aea950ae0e001748b0
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. 4 5#include "components/nacl/browser/nacl_process_host.h" 6 7#include <algorithm> 8#include <string> 9#include <vector> 10 11#include "base/base_switches.h" 12#include "base/bind.h" 13#include "base/command_line.h" 14#include "base/file_util.h" 15#include "base/message_loop/message_loop.h" 16#include "base/metrics/histogram.h" 17#include "base/path_service.h" 18#include "base/process/launch.h" 19#include "base/process/process_iterator.h" 20#include "base/rand_util.h" 21#include "base/strings/string_number_conversions.h" 22#include "base/strings/string_split.h" 23#include "base/strings/string_util.h" 24#include "base/strings/stringprintf.h" 25#include "base/strings/utf_string_conversions.h" 26#include "base/threading/sequenced_worker_pool.h" 27#include "base/win/windows_version.h" 28#include "build/build_config.h" 29#include "components/nacl/browser/nacl_browser.h" 30#include "components/nacl/browser/nacl_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" 58 59#if defined(OS_POSIX) 60 61#include <fcntl.h> 62 63#include "ipc/ipc_channel_posix.h" 64#elif defined(OS_WIN) 65#include <windows.h> 66 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 73 74using content::BrowserThread; 75using content::ChildProcessData; 76using content::ChildProcessHost; 77using ppapi::proxy::SerializedHandle; 78 79#if defined(OS_WIN) 80 81namespace { 82 83// Looks for the largest contiguous unallocated region of address 84// space and returns it via |*out_addr| and |*out_size|. 85void FindAddressSpace(base::ProcessHandle process, 86 char** out_addr, size_t* out_size) { 87 *out_addr = NULL; 88 *out_size = 0; 89 char* addr = 0; 90 while (true) { 91 MEMORY_BASIC_INFORMATION info; 92 size_t result = VirtualQueryEx(process, static_cast<void*>(addr), 93 &info, sizeof(info)); 94 if (result < sizeof(info)) 95 break; 96 if (info.State == MEM_FREE && info.RegionSize > *out_size) { 97 *out_addr = addr; 98 *out_size = info.RegionSize; 99 } 100 addr += info.RegionSize; 101 } 102} 103 104#ifdef _DLL 105 106bool 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()); 110 i != split.end(); 111 ++i) { 112 if (*i == dir) 113 return true; 114 } 115 return false; 116} 117 118#endif // _DLL 119 120} // namespace 121 122namespace nacl { 123 124// Allocates |size| bytes of address space in the given process at a 125// randomised address. 126void* AllocateAddressSpaceASLR(base::ProcessHandle process, size_t size) { 127 char* addr; 128 size_t avail_size; 129 FindAddressSpace(process, &addr, &avail_size); 130 if (avail_size < size) 131 return NULL; 132 size_t offset = base::RandGenerator(avail_size - size); 133 const int kPageSize = 0x10000; 134 void* request_addr = 135 reinterpret_cast<void*>(reinterpret_cast<uint64>(addr + offset) 136 & ~(kPageSize - 1)); 137 return VirtualAllocEx(process, request_addr, size, 138 MEM_RESERVE, PAGE_NOACCESS); 139} 140 141} // namespace nacl 142 143#endif // defined(OS_WIN) 144 145namespace { 146 147#if defined(OS_WIN) 148bool RunningOnWOW64() { 149 return (base::win::OSInfo::GetInstance()->wow64_status() == 150 base::win::OSInfo::WOW64_ENABLED); 151} 152#endif 153 154// NOTE: changes to this class need to be reviewed by the security team. 155class NaClSandboxedProcessLauncherDelegate 156 : public content::SandboxedProcessLauncherDelegate { 157 public: 158 NaClSandboxedProcessLauncherDelegate(ChildProcessHost* host) 159#if defined(OS_POSIX) 160 : ipc_fd_(host->TakeClientFileDescriptor()) 161#endif 162 {} 163 164 virtual ~NaClSandboxedProcessLauncherDelegate() {} 165 166#if defined(OS_WIN) 167 virtual void PostSpawnTarget(base::ProcessHandle process) { 168 // For Native Client sel_ldr processes on 32-bit Windows, reserve 1 GB of 169 // address space to prevent later failure due to address space fragmentation 170 // from .dll loading. The NaCl process will attempt to locate this space by 171 // scanning the address space using VirtualQuery. 172 // TODO(bbudge) Handle the --no-sandbox case. 173 // http://code.google.com/p/nativeclient/issues/detail?id=2131 174 const SIZE_T kNaClSandboxSize = 1 << 30; 175 if (!nacl::AllocateAddressSpaceASLR(process, kNaClSandboxSize)) { 176 DLOG(WARNING) << "Failed to reserve address space for Native Client"; 177 } 178 } 179#elif defined(OS_POSIX) 180 virtual bool ShouldUseZygote() OVERRIDE { 181 return true; 182 } 183 virtual int GetIpcFd() OVERRIDE { 184 return ipc_fd_; 185 } 186#endif // OS_WIN 187 188 private: 189#if defined(OS_POSIX) 190 int ipc_fd_; 191#endif // OS_POSIX 192}; 193 194void SetCloseOnExec(NaClHandle fd) { 195#if defined(OS_POSIX) 196 int flags = fcntl(fd, F_GETFD); 197 CHECK_NE(flags, -1); 198 int rc = fcntl(fd, F_SETFD, flags | FD_CLOEXEC); 199 CHECK_EQ(rc, 0); 200#endif 201} 202 203bool ShareHandleToSelLdr( 204 base::ProcessHandle processh, 205 NaClHandle sourceh, 206 bool close_source, 207 std::vector<nacl::FileDescriptor> *handles_for_sel_ldr) { 208#if defined(OS_WIN) 209 HANDLE channel; 210 int flags = DUPLICATE_SAME_ACCESS; 211 if (close_source) 212 flags |= DUPLICATE_CLOSE_SOURCE; 213 if (!DuplicateHandle(GetCurrentProcess(), 214 reinterpret_cast<HANDLE>(sourceh), 215 processh, 216 &channel, 217 0, // Unused given DUPLICATE_SAME_ACCESS. 218 FALSE, 219 flags)) { 220 LOG(ERROR) << "DuplicateHandle() failed"; 221 return false; 222 } 223 handles_for_sel_ldr->push_back( 224 reinterpret_cast<nacl::FileDescriptor>(channel)); 225#else 226 nacl::FileDescriptor channel; 227 channel.fd = sourceh; 228 channel.auto_close = close_source; 229 handles_for_sel_ldr->push_back(channel); 230#endif 231 return true; 232} 233 234} // namespace 235 236namespace nacl { 237 238struct NaClProcessHost::NaClInternal { 239 NaClHandle socket_for_renderer; 240 NaClHandle socket_for_sel_ldr; 241 242 NaClInternal() 243 : socket_for_renderer(NACL_INVALID_HANDLE), 244 socket_for_sel_ldr(NACL_INVALID_HANDLE) { } 245}; 246 247// ----------------------------------------------------------------------------- 248 249unsigned NaClProcessHost::keepalive_throttle_interval_milliseconds_ = 250 ppapi::kKeepaliveThrottleIntervalDefaultMilliseconds; 251 252NaClProcessHost::NaClProcessHost(const GURL& manifest_url, 253 base::File nexe_file, 254 const NaClFileToken& nexe_token, 255 ppapi::PpapiPermissions permissions, 256 int render_view_id, 257 uint32 permission_bits, 258 bool uses_irt, 259 bool uses_nonsfi_mode, 260 bool enable_dyncode_syscalls, 261 bool enable_exception_handling, 262 bool enable_crash_throttling, 263 bool off_the_record, 264 const base::FilePath& profile_directory) 265 : manifest_url_(manifest_url), 266 nexe_file_(nexe_file.Pass()), 267 nexe_token_(nexe_token), 268 permissions_(permissions), 269#if defined(OS_WIN) 270 process_launched_by_broker_(false), 271#endif 272 reply_msg_(NULL), 273#if defined(OS_WIN) 274 debug_exception_handler_requested_(false), 275#endif 276 internal_(new NaClInternal()), 277 weak_factory_(this), 278 uses_irt_(uses_irt), 279 uses_nonsfi_mode_(uses_nonsfi_mode), 280 enable_debug_stub_(false), 281 enable_dyncode_syscalls_(enable_dyncode_syscalls), 282 enable_exception_handling_(enable_exception_handling), 283 enable_crash_throttling_(enable_crash_throttling), 284 off_the_record_(off_the_record), 285 profile_directory_(profile_directory), 286 render_view_id_(render_view_id) { 287 process_.reset(content::BrowserChildProcessHost::Create( 288 PROCESS_TYPE_NACL_LOADER, this)); 289 290 // Set the display name so the user knows what plugin the process is running. 291 // We aren't on the UI thread so getting the pref locale for language 292 // formatting isn't possible, so IDN will be lost, but this is probably OK 293 // for this use case. 294 process_->SetName(net::FormatUrl(manifest_url_, std::string())); 295 296 enable_debug_stub_ = CommandLine::ForCurrentProcess()->HasSwitch( 297 switches::kEnableNaClDebug); 298} 299 300NaClProcessHost::~NaClProcessHost() { 301 // Report exit status only if the process was successfully started. 302 if (process_->GetData().handle != base::kNullProcessHandle) { 303 int exit_code = 0; 304 process_->GetTerminationStatus(false /* known_dead */, &exit_code); 305 std::string message = 306 base::StringPrintf("NaCl process exited with status %i (0x%x)", 307 exit_code, exit_code); 308 if (exit_code == 0) { 309 VLOG(1) << message; 310 } else { 311 LOG(ERROR) << message; 312 } 313 NaClBrowser::GetInstance()->OnProcessEnd(process_->GetData().id); 314 } 315 316 if (internal_->socket_for_renderer != NACL_INVALID_HANDLE) { 317 if (NaClClose(internal_->socket_for_renderer) != 0) { 318 NOTREACHED() << "NaClClose() failed"; 319 } 320 } 321 322 if (internal_->socket_for_sel_ldr != NACL_INVALID_HANDLE) { 323 if (NaClClose(internal_->socket_for_sel_ldr) != 0) { 324 NOTREACHED() << "NaClClose() failed"; 325 } 326 } 327 328 if (reply_msg_) { 329 // The process failed to launch for some reason. 330 // Don't keep the renderer hanging. 331 reply_msg_->set_reply_error(); 332 nacl_host_message_filter_->Send(reply_msg_); 333 } 334#if defined(OS_WIN) 335 if (process_launched_by_broker_) { 336 NaClBrokerService::GetInstance()->OnLoaderDied(); 337 } 338#endif 339} 340 341void NaClProcessHost::OnProcessCrashed(int exit_status) { 342 if (enable_crash_throttling_ && 343 !CommandLine::ForCurrentProcess()->HasSwitch( 344 switches::kDisablePnaclCrashThrottling)) { 345 NaClBrowser::GetInstance()->OnProcessCrashed(); 346 } 347} 348 349// This is called at browser startup. 350// static 351void NaClProcessHost::EarlyStartup() { 352 NaClBrowser::GetInstance()->EarlyStartup(); 353 // Inform NaClBrowser that we exist and will have a debug port at some point. 354#if defined(OS_LINUX) && !defined(OS_CHROMEOS) 355 // Open the IRT file early to make sure that it isn't replaced out from 356 // under us by autoupdate. 357 NaClBrowser::GetInstance()->EnsureIrtAvailable(); 358#endif 359 CommandLine* cmd = CommandLine::ForCurrentProcess(); 360 UMA_HISTOGRAM_BOOLEAN( 361 "NaCl.nacl-gdb", 362 !cmd->GetSwitchValuePath(switches::kNaClGdb).empty()); 363 UMA_HISTOGRAM_BOOLEAN( 364 "NaCl.nacl-gdb-script", 365 !cmd->GetSwitchValuePath(switches::kNaClGdbScript).empty()); 366 UMA_HISTOGRAM_BOOLEAN( 367 "NaCl.enable-nacl-debug", 368 cmd->HasSwitch(switches::kEnableNaClDebug)); 369 std::string nacl_debug_mask = 370 cmd->GetSwitchValueASCII(switches::kNaClDebugMask); 371 // By default, exclude debugging SSH and the PNaCl translator. 372 // about::flags only allows empty flags as the default, so replace 373 // the empty setting with the default. To debug all apps, use a wild-card. 374 if (nacl_debug_mask.empty()) { 375 nacl_debug_mask = "!*://*/*ssh_client.nmf,chrome://pnacl-translator/*"; 376 } 377 NaClBrowser::GetDelegate()->SetDebugPatterns(nacl_debug_mask); 378} 379 380// static 381void NaClProcessHost::SetPpapiKeepAliveThrottleForTesting( 382 unsigned milliseconds) { 383 keepalive_throttle_interval_milliseconds_ = milliseconds; 384} 385 386void NaClProcessHost::Launch( 387 NaClHostMessageFilter* nacl_host_message_filter, 388 IPC::Message* reply_msg, 389 const base::FilePath& manifest_path) { 390 nacl_host_message_filter_ = nacl_host_message_filter; 391 reply_msg_ = reply_msg; 392 manifest_path_ = manifest_path; 393 394 // Do not launch the requested NaCl module if NaCl is marked "unstable" due 395 // to too many crashes within a given time period. 396 if (enable_crash_throttling_ && 397 !CommandLine::ForCurrentProcess()->HasSwitch( 398 switches::kDisablePnaclCrashThrottling) && 399 NaClBrowser::GetInstance()->IsThrottled()) { 400 SendErrorToRenderer("Process creation was throttled due to excessive" 401 " crashes"); 402 delete this; 403 return; 404 } 405 406 const CommandLine* cmd = CommandLine::ForCurrentProcess(); 407#if defined(OS_WIN) 408 if (cmd->HasSwitch(switches::kEnableNaClDebug) && 409 !cmd->HasSwitch(switches::kNoSandbox)) { 410 // We don't switch off sandbox automatically for security reasons. 411 SendErrorToRenderer("NaCl's GDB debug stub requires --no-sandbox flag" 412 " on Windows. See crbug.com/265624."); 413 delete this; 414 return; 415 } 416#endif 417 if (cmd->HasSwitch(switches::kNaClGdb) && 418 !cmd->HasSwitch(switches::kEnableNaClDebug)) { 419 LOG(WARNING) << "--nacl-gdb flag requires --enable-nacl-debug flag"; 420 } 421 422 // Start getting the IRT open asynchronously while we launch the NaCl process. 423 // We'll make sure this actually finished in StartWithLaunchedProcess, below. 424 NaClBrowser* nacl_browser = NaClBrowser::GetInstance(); 425 nacl_browser->EnsureAllResourcesAvailable(); 426 if (!nacl_browser->IsOk()) { 427 SendErrorToRenderer("could not find all the resources needed" 428 " to launch the process"); 429 delete this; 430 return; 431 } 432 433 if (uses_nonsfi_mode_) { 434 bool nonsfi_mode_forced_by_command_line = false; 435 bool nonsfi_mode_allowed = false; 436#if defined(OS_LINUX) 437 nonsfi_mode_forced_by_command_line = 438 cmd->HasSwitch(switches::kEnableNaClNonSfiMode); 439#if defined(OS_CHROMEOS) && defined(ARCH_CPU_ARMEL) 440 nonsfi_mode_allowed = NaClBrowser::GetDelegate()->IsNonSfiModeAllowed( 441 nacl_host_message_filter->profile_directory(), manifest_url_); 442#endif 443#endif 444 bool nonsfi_mode_enabled = 445 nonsfi_mode_forced_by_command_line || nonsfi_mode_allowed; 446 447 if (!nonsfi_mode_enabled) { 448 SendErrorToRenderer( 449 "NaCl non-SFI mode is not available for this platform" 450 " and NaCl module."); 451 delete this; 452 return; 453 } 454 } else { 455 // Rather than creating a socket pair in the renderer, and passing 456 // one side through the browser to sel_ldr, socket pairs are created 457 // in the browser and then passed to the renderer and sel_ldr. 458 // 459 // This is mainly for the benefit of Windows, where sockets cannot 460 // be passed in messages, but are copied via DuplicateHandle(). 461 // This means the sandboxed renderer cannot send handles to the 462 // browser process. 463 464 NaClHandle pair[2]; 465 // Create a connected socket 466 if (NaClSocketPair(pair) == -1) { 467 SendErrorToRenderer("NaClSocketPair() failed"); 468 delete this; 469 return; 470 } 471 internal_->socket_for_renderer = pair[0]; 472 internal_->socket_for_sel_ldr = pair[1]; 473 SetCloseOnExec(pair[0]); 474 SetCloseOnExec(pair[1]); 475 } 476 477 // Create a shared memory region that the renderer and plugin share for 478 // reporting crash information. 479 crash_info_shmem_.CreateAnonymous(kNaClCrashInfoShmemSize); 480 481 // Launch the process 482 if (!LaunchSelLdr()) { 483 delete this; 484 } 485} 486 487void NaClProcessHost::OnChannelConnected(int32 peer_pid) { 488 if (!CommandLine::ForCurrentProcess()->GetSwitchValuePath( 489 switches::kNaClGdb).empty()) { 490 LaunchNaClGdb(); 491 } 492} 493 494#if defined(OS_WIN) 495void NaClProcessHost::OnProcessLaunchedByBroker(base::ProcessHandle handle) { 496 process_launched_by_broker_ = true; 497 process_->SetHandle(handle); 498 SetDebugStubPort(nacl::kGdbDebugStubPortUnknown); 499 if (!StartWithLaunchedProcess()) 500 delete this; 501} 502 503void NaClProcessHost::OnDebugExceptionHandlerLaunchedByBroker(bool success) { 504 IPC::Message* reply = attach_debug_exception_handler_reply_msg_.release(); 505 NaClProcessMsg_AttachDebugExceptionHandler::WriteReplyParams(reply, success); 506 Send(reply); 507} 508#endif 509 510// Needed to handle sync messages in OnMessageReceived. 511bool NaClProcessHost::Send(IPC::Message* msg) { 512 return process_->Send(msg); 513} 514 515bool NaClProcessHost::LaunchNaClGdb() { 516#if defined(OS_WIN) 517 base::FilePath nacl_gdb = 518 CommandLine::ForCurrentProcess()->GetSwitchValuePath(switches::kNaClGdb); 519 CommandLine cmd_line(nacl_gdb); 520#else 521 CommandLine::StringType nacl_gdb = 522 CommandLine::ForCurrentProcess()->GetSwitchValueNative( 523 switches::kNaClGdb); 524 CommandLine::StringVector argv; 525 // We don't support spaces inside arguments in --nacl-gdb switch. 526 base::SplitString(nacl_gdb, static_cast<CommandLine::CharType>(' '), &argv); 527 CommandLine cmd_line(argv); 528#endif 529 cmd_line.AppendArg("--eval-command"); 530 base::FilePath::StringType irt_path( 531 NaClBrowser::GetInstance()->GetIrtFilePath().value()); 532 // Avoid back slashes because nacl-gdb uses posix escaping rules on Windows. 533 // See issue https://code.google.com/p/nativeclient/issues/detail?id=3482. 534 std::replace(irt_path.begin(), irt_path.end(), '\\', '/'); 535 cmd_line.AppendArgNative(FILE_PATH_LITERAL("nacl-irt \"") + irt_path + 536 FILE_PATH_LITERAL("\"")); 537 if (!manifest_path_.empty()) { 538 cmd_line.AppendArg("--eval-command"); 539 base::FilePath::StringType manifest_path_value(manifest_path_.value()); 540 std::replace(manifest_path_value.begin(), manifest_path_value.end(), 541 '\\', '/'); 542 cmd_line.AppendArgNative(FILE_PATH_LITERAL("nacl-manifest \"") + 543 manifest_path_value + FILE_PATH_LITERAL("\"")); 544 } 545 cmd_line.AppendArg("--eval-command"); 546 cmd_line.AppendArg("target remote :4014"); 547 base::FilePath script = CommandLine::ForCurrentProcess()->GetSwitchValuePath( 548 switches::kNaClGdbScript); 549 if (!script.empty()) { 550 cmd_line.AppendArg("--command"); 551 cmd_line.AppendArgNative(script.value()); 552 } 553 return base::LaunchProcess(cmd_line, base::LaunchOptions(), NULL); 554} 555 556bool NaClProcessHost::LaunchSelLdr() { 557 std::string channel_id = process_->GetHost()->CreateChannel(); 558 if (channel_id.empty()) { 559 SendErrorToRenderer("CreateChannel() failed"); 560 return false; 561 } 562 563 // Build command line for nacl. 564 565#if defined(OS_MACOSX) 566 // The Native Client process needs to be able to allocate a 1GB contiguous 567 // region to use as the client environment's virtual address space. ASLR 568 // (PIE) interferes with this by making it possible that no gap large enough 569 // to accomodate this request will exist in the child process' address 570 // space. Disable PIE for NaCl processes. See http://crbug.com/90221 and 571 // http://code.google.com/p/nativeclient/issues/detail?id=2043. 572 int flags = ChildProcessHost::CHILD_NO_PIE; 573#elif defined(OS_LINUX) 574 int flags = ChildProcessHost::CHILD_ALLOW_SELF; 575#else 576 int flags = ChildProcessHost::CHILD_NORMAL; 577#endif 578 579 base::FilePath exe_path = ChildProcessHost::GetChildPath(flags); 580 if (exe_path.empty()) 581 return false; 582 583#if defined(OS_WIN) 584 // On Windows 64-bit NaCl loader is called nacl64.exe instead of chrome.exe 585 if (RunningOnWOW64()) { 586 if (!NaClBrowser::GetInstance()->GetNaCl64ExePath(&exe_path)) { 587 SendErrorToRenderer("could not get path to nacl64.exe"); 588 return false; 589 } 590 591#ifdef _DLL 592 // When using the DLL CRT on Windows, we need to amend the PATH to include 593 // the location of the x64 CRT DLLs. This is only the case when using a 594 // component=shared_library build (i.e. generally dev debug builds). The 595 // x86 CRT DLLs are in e.g. out\Debug for chrome.exe etc., so the x64 ones 596 // are put in out\Debug\x64 which we add to the PATH here so that loader 597 // can find them. See http://crbug.com/346034. 598 scoped_ptr<base::Environment> env(base::Environment::Create()); 599 static const char kPath[] = "PATH"; 600 std::string old_path; 601 base::FilePath module_path; 602 if (!PathService::Get(base::FILE_MODULE, &module_path)) { 603 SendErrorToRenderer("could not get path to current module"); 604 return false; 605 } 606 std::string x64_crt_path = 607 base::WideToUTF8(module_path.DirName().Append(L"x64").value()); 608 if (!env->GetVar(kPath, &old_path)) { 609 env->SetVar(kPath, x64_crt_path); 610 } else if (!IsInPath(old_path, x64_crt_path)) { 611 std::string new_path(old_path); 612 new_path.append(";"); 613 new_path.append(x64_crt_path); 614 env->SetVar(kPath, new_path); 615 } 616#endif // _DLL 617 } 618#endif 619 620 scoped_ptr<CommandLine> cmd_line(new CommandLine(exe_path)); 621 CopyNaClCommandLineArguments(cmd_line.get()); 622 623 cmd_line->AppendSwitchASCII(switches::kProcessType, 624 (uses_nonsfi_mode_ ? 625 switches::kNaClLoaderNonSfiProcess : 626 switches::kNaClLoaderProcess)); 627 cmd_line->AppendSwitchASCII(switches::kProcessChannelID, channel_id); 628 if (NaClBrowser::GetDelegate()->DialogsAreSuppressed()) 629 cmd_line->AppendSwitch(switches::kNoErrorDialogs); 630 631 // On Windows we might need to start the broker process to launch a new loader 632#if defined(OS_WIN) 633 if (RunningOnWOW64()) { 634 if (!NaClBrokerService::GetInstance()->LaunchLoader( 635 weak_factory_.GetWeakPtr(), channel_id)) { 636 SendErrorToRenderer("broker service did not launch process"); 637 return false; 638 } 639 return true; 640 } 641#endif 642 process_->Launch( 643 new NaClSandboxedProcessLauncherDelegate(process_->GetHost()), 644 cmd_line.release()); 645 return true; 646} 647 648bool NaClProcessHost::OnMessageReceived(const IPC::Message& msg) { 649 bool handled = true; 650 if (uses_nonsfi_mode_) { 651 // IPC messages relating to NaCl's validation cache must not be exposed 652 // in Non-SFI Mode, otherwise a Non-SFI nexe could use 653 // SetKnownToValidate to create a hole in the SFI sandbox. 654 IPC_BEGIN_MESSAGE_MAP(NaClProcessHost, msg) 655 IPC_MESSAGE_HANDLER(NaClProcessHostMsg_PpapiChannelsCreated, 656 OnPpapiChannelsCreated) 657 IPC_MESSAGE_UNHANDLED(handled = false) 658 IPC_END_MESSAGE_MAP() 659 } else { 660 IPC_BEGIN_MESSAGE_MAP(NaClProcessHost, msg) 661 IPC_MESSAGE_HANDLER(NaClProcessMsg_QueryKnownToValidate, 662 OnQueryKnownToValidate) 663 IPC_MESSAGE_HANDLER(NaClProcessMsg_SetKnownToValidate, 664 OnSetKnownToValidate) 665 IPC_MESSAGE_HANDLER_DELAY_REPLY(NaClProcessMsg_ResolveFileToken, 666 OnResolveFileToken) 667#if defined(OS_WIN) 668 IPC_MESSAGE_HANDLER_DELAY_REPLY( 669 NaClProcessMsg_AttachDebugExceptionHandler, 670 OnAttachDebugExceptionHandler) 671 IPC_MESSAGE_HANDLER(NaClProcessHostMsg_DebugStubPortSelected, 672 OnDebugStubPortSelected) 673#endif 674 IPC_MESSAGE_HANDLER(NaClProcessHostMsg_PpapiChannelsCreated, 675 OnPpapiChannelsCreated) 676 IPC_MESSAGE_UNHANDLED(handled = false) 677 IPC_END_MESSAGE_MAP() 678 } 679 return handled; 680} 681 682void NaClProcessHost::OnProcessLaunched() { 683 if (!StartWithLaunchedProcess()) 684 delete this; 685} 686 687// Called when the NaClBrowser singleton has been fully initialized. 688void NaClProcessHost::OnResourcesReady() { 689 NaClBrowser* nacl_browser = NaClBrowser::GetInstance(); 690 if (!nacl_browser->IsReady()) { 691 SendErrorToRenderer("could not acquire shared resources needed by NaCl"); 692 delete this; 693 } else if (!StartNaClExecution()) { 694 delete this; 695 } 696} 697 698bool NaClProcessHost::ReplyToRenderer( 699 const IPC::ChannelHandle& ppapi_channel_handle, 700 const IPC::ChannelHandle& trusted_channel_handle, 701 const IPC::ChannelHandle& manifest_service_channel_handle) { 702#if defined(OS_WIN) 703 // If we are on 64-bit Windows, the NaCl process's sandbox is 704 // managed by a different process from the renderer's sandbox. We 705 // need to inform the renderer's sandbox about the NaCl process so 706 // that the renderer can send handles to the NaCl process using 707 // BrokerDuplicateHandle(). 708 if (RunningOnWOW64()) { 709 if (!content::BrokerAddTargetPeer(process_->GetData().handle)) { 710 SendErrorToRenderer("BrokerAddTargetPeer() failed"); 711 return false; 712 } 713 } 714#endif 715 716 FileDescriptor imc_handle_for_renderer; 717#if defined(OS_WIN) 718 // Copy the handle into the renderer process. 719 HANDLE handle_in_renderer; 720 if (!DuplicateHandle(base::GetCurrentProcessHandle(), 721 reinterpret_cast<HANDLE>( 722 internal_->socket_for_renderer), 723 nacl_host_message_filter_->PeerHandle(), 724 &handle_in_renderer, 725 0, // Unused given DUPLICATE_SAME_ACCESS. 726 FALSE, 727 DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS)) { 728 SendErrorToRenderer("DuplicateHandle() failed"); 729 return false; 730 } 731 imc_handle_for_renderer = reinterpret_cast<FileDescriptor>( 732 handle_in_renderer); 733#else 734 // No need to dup the imc_handle - we don't pass it anywhere else so 735 // it cannot be closed. 736 FileDescriptor imc_handle; 737 imc_handle.fd = internal_->socket_for_renderer; 738 imc_handle.auto_close = true; 739 imc_handle_for_renderer = imc_handle; 740#endif 741 742 const ChildProcessData& data = process_->GetData(); 743 base::SharedMemoryHandle crash_info_shmem_renderer_handle; 744 if (!crash_info_shmem_.ShareToProcess(nacl_host_message_filter_->PeerHandle(), 745 &crash_info_shmem_renderer_handle)) { 746 SendErrorToRenderer("ShareToProcess() failed"); 747 return false; 748 } 749 750 SendMessageToRenderer( 751 NaClLaunchResult(imc_handle_for_renderer, 752 ppapi_channel_handle, 753 trusted_channel_handle, 754 manifest_service_channel_handle, 755 base::GetProcId(data.handle), 756 data.id, 757 crash_info_shmem_renderer_handle), 758 std::string() /* error_message */); 759 internal_->socket_for_renderer = NACL_INVALID_HANDLE; 760 761 // Now that the crash information shmem handles have been shared with the 762 // plugin and the renderer, the browser can close its handle. 763 crash_info_shmem_.Close(); 764 return true; 765} 766 767void NaClProcessHost::SendErrorToRenderer(const std::string& error_message) { 768 LOG(ERROR) << "NaCl process launch failed: " << error_message; 769 SendMessageToRenderer(NaClLaunchResult(), error_message); 770} 771 772void NaClProcessHost::SendMessageToRenderer( 773 const NaClLaunchResult& result, 774 const std::string& error_message) { 775 DCHECK(nacl_host_message_filter_); 776 DCHECK(reply_msg_); 777 if (nacl_host_message_filter_ != NULL && reply_msg_ != NULL) { 778 NaClHostMsg_LaunchNaCl::WriteReplyParams( 779 reply_msg_, result, error_message); 780 nacl_host_message_filter_->Send(reply_msg_); 781 nacl_host_message_filter_ = NULL; 782 reply_msg_ = NULL; 783 } 784} 785 786void NaClProcessHost::SetDebugStubPort(int port) { 787 NaClBrowser* nacl_browser = NaClBrowser::GetInstance(); 788 nacl_browser->SetProcessGdbDebugStubPort(process_->GetData().id, port); 789} 790 791#if defined(OS_POSIX) 792// TCP port we chose for NaCl debug stub. It can be any other number. 793static const int kInitialDebugStubPort = 4014; 794 795net::SocketDescriptor NaClProcessHost::GetDebugStubSocketHandle() { 796 net::SocketDescriptor s = net::kInvalidSocket; 797 // We always try to allocate the default port first. If this fails, we then 798 // allocate any available port. 799 // On success, if the test system has register a handler 800 // (GdbDebugStubPortListener), we fire a notification. 801 int port = kInitialDebugStubPort; 802 s = net::TCPListenSocket::CreateAndBind("127.0.0.1", port); 803 if (s == net::kInvalidSocket) { 804 s = net::TCPListenSocket::CreateAndBindAnyPort("127.0.0.1", &port); 805 } 806 if (s != net::kInvalidSocket) { 807 SetDebugStubPort(port); 808 } 809 if (s == net::kInvalidSocket) { 810 LOG(ERROR) << "failed to open socket for debug stub"; 811 return net::kInvalidSocket; 812 } else { 813 LOG(WARNING) << "debug stub on port " << port; 814 } 815 if (listen(s, 1)) { 816 LOG(ERROR) << "listen() failed on debug stub socket"; 817 if (IGNORE_EINTR(close(s)) < 0) 818 PLOG(ERROR) << "failed to close debug stub socket"; 819 return net::kInvalidSocket; 820 } 821 return s; 822} 823#endif 824 825#if defined(OS_WIN) 826void NaClProcessHost::OnDebugStubPortSelected(uint16_t debug_stub_port) { 827 CHECK(!uses_nonsfi_mode_); 828 SetDebugStubPort(debug_stub_port); 829} 830#endif 831 832bool NaClProcessHost::StartNaClExecution() { 833 NaClBrowser* nacl_browser = NaClBrowser::GetInstance(); 834 835 NaClStartParams params; 836 837 // Enable PPAPI proxy channel creation only for renderer processes. 838 params.enable_ipc_proxy = enable_ppapi_proxy(); 839 if (uses_nonsfi_mode_) { 840 // Currently, non-SFI mode is supported only on Linux. 841#if defined(OS_LINUX) 842 // In non-SFI mode, we do not use SRPC. Make sure that the socketpair is 843 // not created. 844 DCHECK_EQ(internal_->socket_for_sel_ldr, NACL_INVALID_HANDLE); 845#endif 846 } else { 847 params.validation_cache_enabled = nacl_browser->ValidationCacheIsEnabled(); 848 params.validation_cache_key = nacl_browser->GetValidationCacheKey(); 849 params.version = NaClBrowser::GetDelegate()->GetVersionString(); 850 params.enable_exception_handling = enable_exception_handling_; 851 params.enable_debug_stub = enable_debug_stub_ && 852 NaClBrowser::GetDelegate()->URLMatchesDebugPatterns(manifest_url_); 853 params.uses_irt = uses_irt_; 854 params.enable_dyncode_syscalls = enable_dyncode_syscalls_; 855 856 // TODO(teravest): Resolve the file tokens right now instead of making the 857 // loader send IPC to resolve them later. 858 params.nexe_token_lo = nexe_token_.lo; 859 params.nexe_token_hi = nexe_token_.hi; 860 861 const ChildProcessData& data = process_->GetData(); 862 if (!ShareHandleToSelLdr(data.handle, 863 internal_->socket_for_sel_ldr, true, 864 ¶ms.handles)) { 865 return false; 866 } 867 868 if (params.uses_irt) { 869 const base::File& irt_file = nacl_browser->IrtFile(); 870 CHECK(irt_file.IsValid()); 871 // Send over the IRT file handle. We don't close our own copy! 872 if (!ShareHandleToSelLdr(data.handle, irt_file.GetPlatformFile(), false, 873 ¶ms.handles)) { 874 return false; 875 } 876 } 877 878#if defined(OS_MACOSX) 879 // For dynamic loading support, NaCl requires a file descriptor that 880 // was created in /tmp, since those created with shm_open() are not 881 // mappable with PROT_EXEC. Rather than requiring an extra IPC 882 // round trip out of the sandbox, we create an FD here. 883 base::SharedMemory memory_buffer; 884 base::SharedMemoryCreateOptions options; 885 options.size = 1; 886 options.executable = true; 887 if (!memory_buffer.Create(options)) { 888 DLOG(ERROR) << "Failed to allocate memory buffer"; 889 return false; 890 } 891 FileDescriptor memory_fd; 892 memory_fd.fd = dup(memory_buffer.handle().fd); 893 if (memory_fd.fd < 0) { 894 DLOG(ERROR) << "Failed to dup() a file descriptor"; 895 return false; 896 } 897 memory_fd.auto_close = true; 898 params.handles.push_back(memory_fd); 899#endif 900 901#if defined(OS_POSIX) 902 if (params.enable_debug_stub) { 903 net::SocketDescriptor server_bound_socket = GetDebugStubSocketHandle(); 904 if (server_bound_socket != net::kInvalidSocket) { 905 params.debug_stub_server_bound_socket = 906 FileDescriptor(server_bound_socket, true); 907 } 908 } 909#endif 910 } 911 912 if (!uses_nonsfi_mode_) { 913 internal_->socket_for_sel_ldr = NACL_INVALID_HANDLE; 914 } 915 916 params.nexe_file = IPC::TakeFileHandleForProcess(nexe_file_.Pass(), 917 process_->GetData().handle); 918 if (!crash_info_shmem_.ShareToProcess(process_->GetData().handle, 919 ¶ms.crash_info_shmem_handle)) { 920 DLOG(ERROR) << "Failed to ShareToProcess() a shared memory buffer"; 921 return false; 922 } 923 924 process_->Send(new NaClProcessMsg_Start(params)); 925 return true; 926} 927 928// This method is called when NaClProcessHostMsg_PpapiChannelCreated is 929// received. 930void NaClProcessHost::OnPpapiChannelsCreated( 931 const IPC::ChannelHandle& browser_channel_handle, 932 const IPC::ChannelHandle& ppapi_renderer_channel_handle, 933 const IPC::ChannelHandle& trusted_renderer_channel_handle, 934 const IPC::ChannelHandle& manifest_service_channel_handle) { 935 if (!enable_ppapi_proxy()) { 936 ReplyToRenderer(IPC::ChannelHandle(), 937 trusted_renderer_channel_handle, 938 manifest_service_channel_handle); 939 return; 940 } 941 942 if (!ipc_proxy_channel_.get()) { 943 DCHECK_EQ(PROCESS_TYPE_NACL_LOADER, process_->GetData().process_type); 944 945 ipc_proxy_channel_ = 946 IPC::ChannelProxy::Create(browser_channel_handle, 947 IPC::Channel::MODE_CLIENT, 948 NULL, 949 base::MessageLoopProxy::current().get()); 950 // Create the browser ppapi host and enable PPAPI message dispatching to the 951 // browser process. 952 ppapi_host_.reset(content::BrowserPpapiHost::CreateExternalPluginProcess( 953 ipc_proxy_channel_.get(), // sender 954 permissions_, 955 process_->GetData().handle, 956 ipc_proxy_channel_.get(), 957 nacl_host_message_filter_->render_process_id(), 958 render_view_id_, 959 profile_directory_)); 960 ppapi_host_->SetOnKeepaliveCallback( 961 NaClBrowser::GetDelegate()->GetOnKeepaliveCallback()); 962 963 ppapi::PpapiNaClPluginArgs args; 964 args.off_the_record = nacl_host_message_filter_->off_the_record(); 965 args.permissions = permissions_; 966 args.keepalive_throttle_interval_milliseconds = 967 keepalive_throttle_interval_milliseconds_; 968 CommandLine* cmdline = CommandLine::ForCurrentProcess(); 969 DCHECK(cmdline); 970 std::string flag_whitelist[] = { 971 switches::kV, 972 switches::kVModule, 973 }; 974 for (size_t i = 0; i < arraysize(flag_whitelist); ++i) { 975 std::string value = cmdline->GetSwitchValueASCII(flag_whitelist[i]); 976 if (!value.empty()) { 977 args.switch_names.push_back(flag_whitelist[i]); 978 args.switch_values.push_back(value); 979 } 980 } 981 982 ppapi_host_->GetPpapiHost()->AddHostFactoryFilter( 983 scoped_ptr<ppapi::host::HostFactory>( 984 NaClBrowser::GetDelegate()->CreatePpapiHostFactory( 985 ppapi_host_.get()))); 986 987 // Send a message to initialize the IPC dispatchers in the NaCl plugin. 988 ipc_proxy_channel_->Send(new PpapiMsg_InitializeNaClDispatcher(args)); 989 990 // Let the renderer know that the IPC channels are established. 991 ReplyToRenderer(ppapi_renderer_channel_handle, 992 trusted_renderer_channel_handle, 993 manifest_service_channel_handle); 994 } else { 995 // Attempt to open more than 1 browser channel is not supported. 996 // Shut down the NaCl process. 997 process_->GetHost()->ForceShutdown(); 998 } 999} 1000 1001bool NaClProcessHost::StartWithLaunchedProcess() { 1002 NaClBrowser* nacl_browser = NaClBrowser::GetInstance(); 1003 1004 if (nacl_browser->IsReady()) { 1005 return StartNaClExecution(); 1006 } else if (nacl_browser->IsOk()) { 1007 nacl_browser->WaitForResources( 1008 base::Bind(&NaClProcessHost::OnResourcesReady, 1009 weak_factory_.GetWeakPtr())); 1010 return true; 1011 } else { 1012 SendErrorToRenderer("previously failed to acquire shared resources"); 1013 return false; 1014 } 1015} 1016 1017void NaClProcessHost::OnQueryKnownToValidate(const std::string& signature, 1018 bool* result) { 1019 CHECK(!uses_nonsfi_mode_); 1020 NaClBrowser* nacl_browser = NaClBrowser::GetInstance(); 1021 *result = nacl_browser->QueryKnownToValidate(signature, off_the_record_); 1022} 1023 1024void NaClProcessHost::OnSetKnownToValidate(const std::string& signature) { 1025 CHECK(!uses_nonsfi_mode_); 1026 NaClBrowser::GetInstance()->SetKnownToValidate( 1027 signature, off_the_record_); 1028} 1029 1030void NaClProcessHost::FileResolved( 1031 const base::FilePath& file_path, 1032 IPC::Message* reply_msg, 1033 base::File file) { 1034 if (file.IsValid()) { 1035 IPC::PlatformFileForTransit handle = IPC::TakeFileHandleForProcess( 1036 file.Pass(), 1037 process_->GetData().handle); 1038 NaClProcessMsg_ResolveFileToken::WriteReplyParams( 1039 reply_msg, 1040 handle, 1041 file_path); 1042 } else { 1043 NaClProcessMsg_ResolveFileToken::WriteReplyParams( 1044 reply_msg, 1045 IPC::InvalidPlatformFileForTransit(), 1046 base::FilePath()); 1047 } 1048 Send(reply_msg); 1049} 1050 1051void NaClProcessHost::OnResolveFileToken(uint64 file_token_lo, 1052 uint64 file_token_hi, 1053 IPC::Message* reply_msg) { 1054 // Was the file registered? 1055 // 1056 // Note that the file path cache is of bounded size, and old entries can get 1057 // evicted. If a large number of NaCl modules are being launched at once, 1058 // resolving the file_token may fail because the path cache was thrashed 1059 // while the file_token was in flight. In this case the query fails, and we 1060 // need to fall back to the slower path. 1061 // 1062 // However: each NaCl process will consume 2-3 entries as it starts up, this 1063 // means that eviction will not happen unless you start up 33+ NaCl processes 1064 // at the same time, and this still requires worst-case timing. As a 1065 // practical matter, no entries should be evicted prematurely. 1066 // The cache itself should take ~ (150 characters * 2 bytes/char + ~60 bytes 1067 // data structure overhead) * 100 = 35k when full, so making it bigger should 1068 // not be a problem, if needed. 1069 // 1070 // Each NaCl process will consume 2-3 entries because the manifest and main 1071 // nexe are currently not resolved. Shared libraries will be resolved. They 1072 // will be loaded sequentially, so they will only consume a single entry 1073 // while the load is in flight. 1074 // 1075 // TODO(ncbray): track behavior with UMA. If entries are getting evicted or 1076 // bogus keys are getting queried, this would be good to know. 1077 CHECK(!uses_nonsfi_mode_); 1078 base::FilePath file_path; 1079 if (!NaClBrowser::GetInstance()->GetFilePath( 1080 file_token_lo, file_token_hi, &file_path)) { 1081 NaClProcessMsg_ResolveFileToken::WriteReplyParams( 1082 reply_msg, 1083 IPC::InvalidPlatformFileForTransit(), 1084 base::FilePath()); 1085 Send(reply_msg); 1086 return; 1087 } 1088 1089 // Open the file. 1090 if (!base::PostTaskAndReplyWithResult( 1091 content::BrowserThread::GetBlockingPool(), 1092 FROM_HERE, 1093 base::Bind(OpenNaClReadExecImpl, file_path, true /* is_executable */), 1094 base::Bind(&NaClProcessHost::FileResolved, 1095 weak_factory_.GetWeakPtr(), 1096 file_path, 1097 reply_msg))) { 1098 NaClProcessMsg_ResolveFileToken::WriteReplyParams( 1099 reply_msg, 1100 IPC::InvalidPlatformFileForTransit(), 1101 base::FilePath()); 1102 Send(reply_msg); 1103 } 1104} 1105 1106#if defined(OS_WIN) 1107void NaClProcessHost::OnAttachDebugExceptionHandler(const std::string& info, 1108 IPC::Message* reply_msg) { 1109 CHECK(!uses_nonsfi_mode_); 1110 if (!AttachDebugExceptionHandler(info, reply_msg)) { 1111 // Send failure message. 1112 NaClProcessMsg_AttachDebugExceptionHandler::WriteReplyParams(reply_msg, 1113 false); 1114 Send(reply_msg); 1115 } 1116} 1117 1118bool NaClProcessHost::AttachDebugExceptionHandler(const std::string& info, 1119 IPC::Message* reply_msg) { 1120 if (!enable_exception_handling_ && !enable_debug_stub_) { 1121 DLOG(ERROR) << 1122 "Debug exception handler requested by NaCl process when not enabled"; 1123 return false; 1124 } 1125 if (debug_exception_handler_requested_) { 1126 // The NaCl process should not request this multiple times. 1127 DLOG(ERROR) << "Multiple AttachDebugExceptionHandler requests received"; 1128 return false; 1129 } 1130 debug_exception_handler_requested_ = true; 1131 1132 base::ProcessId nacl_pid = base::GetProcId(process_->GetData().handle); 1133 base::ProcessHandle temp_handle; 1134 // We cannot use process_->GetData().handle because it does not have 1135 // the necessary access rights. We open the new handle here rather 1136 // than in the NaCl broker process in case the NaCl loader process 1137 // dies before the NaCl broker process receives the message we send. 1138 // The debug exception handler uses DebugActiveProcess() to attach, 1139 // but this takes a PID. We need to prevent the NaCl loader's PID 1140 // from being reused before DebugActiveProcess() is called, and 1141 // holding a process handle open achieves this. 1142 if (!base::OpenProcessHandleWithAccess( 1143 nacl_pid, 1144 base::kProcessAccessQueryInformation | 1145 base::kProcessAccessSuspendResume | 1146 base::kProcessAccessTerminate | 1147 base::kProcessAccessVMOperation | 1148 base::kProcessAccessVMRead | 1149 base::kProcessAccessVMWrite | 1150 base::kProcessAccessDuplicateHandle | 1151 base::kProcessAccessWaitForTermination, 1152 &temp_handle)) { 1153 LOG(ERROR) << "Failed to get process handle"; 1154 return false; 1155 } 1156 base::win::ScopedHandle process_handle(temp_handle); 1157 1158 attach_debug_exception_handler_reply_msg_.reset(reply_msg); 1159 // If the NaCl loader is 64-bit, the process running its debug 1160 // exception handler must be 64-bit too, so we use the 64-bit NaCl 1161 // broker process for this. Otherwise, on a 32-bit system, we use 1162 // the 32-bit browser process to run the debug exception handler. 1163 if (RunningOnWOW64()) { 1164 return NaClBrokerService::GetInstance()->LaunchDebugExceptionHandler( 1165 weak_factory_.GetWeakPtr(), nacl_pid, process_handle, info); 1166 } else { 1167 NaClStartDebugExceptionHandlerThread( 1168 process_handle.Take(), info, 1169 base::MessageLoopProxy::current(), 1170 base::Bind(&NaClProcessHost::OnDebugExceptionHandlerLaunchedByBroker, 1171 weak_factory_.GetWeakPtr())); 1172 return true; 1173 } 1174} 1175#endif 1176 1177} // namespace nacl 1178