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