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