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