nacl_process_host.cc revision e5d81f57cb97b3b6b7fccc9c5610d21eb81db09d
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  if (uses_nonsfi_mode_) {
433#if defined(OS_LINUX)
434    const bool kNonSFIModeSupported = true;
435#else
436    const bool kNonSFIModeSupported = false;
437#endif
438    if (!kNonSFIModeSupported ||
439        !cmd->HasSwitch(switches::kEnableNaClNonSfiMode)) {
440      SendErrorToRenderer("NaCl non-SFI mode works only on Linux with"
441                          " --enable-nacl-nonsfi-mode specified");
442      delete this;
443      return;
444    }
445  }
446
447  // Rather than creating a socket pair in the renderer, and passing
448  // one side through the browser to sel_ldr, socket pairs are created
449  // in the browser and then passed to the renderer and sel_ldr.
450  //
451  // This is mainly for the benefit of Windows, where sockets cannot
452  // be passed in messages, but are copied via DuplicateHandle().
453  // This means the sandboxed renderer cannot send handles to the
454  // browser process.
455
456  NaClHandle pair[2];
457  // Create a connected socket
458  if (NaClSocketPair(pair) == -1) {
459    SendErrorToRenderer("NaClSocketPair() failed");
460    delete this;
461    return;
462  }
463  internal_->socket_for_renderer = pair[0];
464  internal_->socket_for_sel_ldr = pair[1];
465  SetCloseOnExec(pair[0]);
466  SetCloseOnExec(pair[1]);
467
468  // Launch the process
469  if (!LaunchSelLdr()) {
470    delete this;
471  }
472}
473
474void NaClProcessHost::OnChannelConnected(int32 peer_pid) {
475  if (!CommandLine::ForCurrentProcess()->GetSwitchValuePath(
476          switches::kNaClGdb).empty()) {
477    LaunchNaClGdb();
478  }
479}
480
481#if defined(OS_WIN)
482void NaClProcessHost::OnProcessLaunchedByBroker(base::ProcessHandle handle) {
483  process_launched_by_broker_ = true;
484  process_->SetHandle(handle);
485  if (!StartWithLaunchedProcess())
486    delete this;
487}
488
489void NaClProcessHost::OnDebugExceptionHandlerLaunchedByBroker(bool success) {
490  IPC::Message* reply = attach_debug_exception_handler_reply_msg_.release();
491  NaClProcessMsg_AttachDebugExceptionHandler::WriteReplyParams(reply, success);
492  Send(reply);
493}
494#endif
495
496// Needed to handle sync messages in OnMessageRecieved.
497bool NaClProcessHost::Send(IPC::Message* msg) {
498  return process_->Send(msg);
499}
500
501bool NaClProcessHost::LaunchNaClGdb() {
502#if defined(OS_WIN)
503  base::FilePath nacl_gdb =
504      CommandLine::ForCurrentProcess()->GetSwitchValuePath(switches::kNaClGdb);
505  CommandLine cmd_line(nacl_gdb);
506#else
507  CommandLine::StringType nacl_gdb =
508      CommandLine::ForCurrentProcess()->GetSwitchValueNative(
509          switches::kNaClGdb);
510  CommandLine::StringVector argv;
511  // We don't support spaces inside arguments in --nacl-gdb switch.
512  base::SplitString(nacl_gdb, static_cast<CommandLine::CharType>(' '), &argv);
513  CommandLine cmd_line(argv);
514#endif
515  cmd_line.AppendArg("--eval-command");
516  base::FilePath::StringType irt_path(
517      NaClBrowser::GetInstance()->GetIrtFilePath().value());
518  // Avoid back slashes because nacl-gdb uses posix escaping rules on Windows.
519  // See issue https://code.google.com/p/nativeclient/issues/detail?id=3482.
520  std::replace(irt_path.begin(), irt_path.end(), '\\', '/');
521  cmd_line.AppendArgNative(FILE_PATH_LITERAL("nacl-irt \"") + irt_path +
522                           FILE_PATH_LITERAL("\""));
523  if (!manifest_path_.empty()) {
524    cmd_line.AppendArg("--eval-command");
525    base::FilePath::StringType manifest_path_value(manifest_path_.value());
526    std::replace(manifest_path_value.begin(), manifest_path_value.end(),
527                 '\\', '/');
528    cmd_line.AppendArgNative(FILE_PATH_LITERAL("nacl-manifest \"") +
529                             manifest_path_value + FILE_PATH_LITERAL("\""));
530  }
531  cmd_line.AppendArg("--eval-command");
532  cmd_line.AppendArg("target remote :4014");
533  base::FilePath script = CommandLine::ForCurrentProcess()->GetSwitchValuePath(
534      switches::kNaClGdbScript);
535  if (!script.empty()) {
536    cmd_line.AppendArg("--command");
537    cmd_line.AppendArgNative(script.value());
538  }
539  return base::LaunchProcess(cmd_line, base::LaunchOptions(), NULL);
540}
541
542bool NaClProcessHost::LaunchSelLdr() {
543  std::string channel_id = process_->GetHost()->CreateChannel();
544  if (channel_id.empty()) {
545    SendErrorToRenderer("CreateChannel() failed");
546    return false;
547  }
548
549  // Build command line for nacl.
550
551#if defined(OS_MACOSX)
552  // The Native Client process needs to be able to allocate a 1GB contiguous
553  // region to use as the client environment's virtual address space. ASLR
554  // (PIE) interferes with this by making it possible that no gap large enough
555  // to accomodate this request will exist in the child process' address
556  // space. Disable PIE for NaCl processes. See http://crbug.com/90221 and
557  // http://code.google.com/p/nativeclient/issues/detail?id=2043.
558  int flags = ChildProcessHost::CHILD_NO_PIE;
559#elif defined(OS_LINUX)
560  int flags = ChildProcessHost::CHILD_ALLOW_SELF;
561#else
562  int flags = ChildProcessHost::CHILD_NORMAL;
563#endif
564
565  base::FilePath exe_path = ChildProcessHost::GetChildPath(flags);
566  if (exe_path.empty())
567    return false;
568
569#if defined(OS_WIN)
570  // On Windows 64-bit NaCl loader is called nacl64.exe instead of chrome.exe
571  if (RunningOnWOW64()) {
572    if (!NaClBrowser::GetInstance()->GetNaCl64ExePath(&exe_path)) {
573      SendErrorToRenderer("could not get path to nacl64.exe");
574      return false;
575    }
576
577#ifdef _DLL
578    // When using the DLL CRT on Windows, we need to amend the PATH to include
579    // the location of the x64 CRT DLLs. This is only the case when using a
580    // component=shared_library build (i.e. generally dev debug builds). The
581    // x86 CRT DLLs are in e.g. out\Debug for chrome.exe etc., so the x64 ones
582    // are put in out\Debug\x64 which we add to the PATH here so that loader
583    // can find them. See http://crbug.com/346034.
584    scoped_ptr<base::Environment> env(base::Environment::Create());
585    static const char kPath[] = "PATH";
586    std::string old_path;
587    base::FilePath module_path;
588    if (!PathService::Get(base::FILE_MODULE, &module_path)) {
589      SendErrorToRenderer("could not get path to current module");
590      return false;
591    }
592    std::string x64_crt_path =
593        base::WideToUTF8(module_path.DirName().Append(L"x64").value());
594    if (!env->GetVar(kPath, &old_path)) {
595      env->SetVar(kPath, x64_crt_path);
596    } else if (!IsInPath(old_path, x64_crt_path)) {
597      std::string new_path(old_path);
598      new_path.append(";");
599      new_path.append(x64_crt_path);
600      env->SetVar(kPath, new_path);
601    }
602#endif  // _DLL
603  }
604#endif
605
606  scoped_ptr<CommandLine> cmd_line(new CommandLine(exe_path));
607  CopyNaClCommandLineArguments(cmd_line.get());
608
609  cmd_line->AppendSwitchASCII(switches::kProcessType,
610                              (uses_nonsfi_mode_ ?
611                               switches::kNaClLoaderNonSfiProcess :
612                               switches::kNaClLoaderProcess));
613  cmd_line->AppendSwitchASCII(switches::kProcessChannelID, channel_id);
614  if (NaClBrowser::GetDelegate()->DialogsAreSuppressed())
615    cmd_line->AppendSwitch(switches::kNoErrorDialogs);
616
617  // On Windows we might need to start the broker process to launch a new loader
618#if defined(OS_WIN)
619  if (RunningOnWOW64()) {
620    if (!NaClBrokerService::GetInstance()->LaunchLoader(
621            weak_factory_.GetWeakPtr(), channel_id)) {
622      SendErrorToRenderer("broker service did not launch process");
623      return false;
624    }
625    return true;
626  }
627#endif
628  process_->Launch(
629      new NaClSandboxedProcessLauncherDelegate(process_->GetHost()),
630      cmd_line.release());
631  return true;
632}
633
634bool NaClProcessHost::OnMessageReceived(const IPC::Message& msg) {
635  bool handled = true;
636  IPC_BEGIN_MESSAGE_MAP(NaClProcessHost, msg)
637    IPC_MESSAGE_HANDLER(NaClProcessMsg_QueryKnownToValidate,
638                        OnQueryKnownToValidate)
639    IPC_MESSAGE_HANDLER(NaClProcessMsg_SetKnownToValidate,
640                        OnSetKnownToValidate)
641    IPC_MESSAGE_HANDLER_DELAY_REPLY(NaClProcessMsg_ResolveFileToken,
642                                    OnResolveFileToken)
643#if defined(OS_WIN)
644    IPC_MESSAGE_HANDLER_DELAY_REPLY(NaClProcessMsg_AttachDebugExceptionHandler,
645                                    OnAttachDebugExceptionHandler)
646#endif
647    IPC_MESSAGE_HANDLER(NaClProcessHostMsg_PpapiChannelsCreated,
648                        OnPpapiChannelsCreated)
649    IPC_MESSAGE_UNHANDLED(handled = false)
650  IPC_END_MESSAGE_MAP()
651  return handled;
652}
653
654void NaClProcessHost::OnProcessLaunched() {
655  if (!StartWithLaunchedProcess())
656    delete this;
657}
658
659// Called when the NaClBrowser singleton has been fully initialized.
660void 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;
667  }
668}
669
670bool NaClProcessHost::ReplyToRenderer(
671    const IPC::ChannelHandle& ppapi_channel_handle,
672    const IPC::ChannelHandle& trusted_channel_handle) {
673#if defined(OS_WIN)
674  // If we are on 64-bit Windows, the NaCl process's sandbox is
675  // managed by a different process from the renderer's sandbox.  We
676  // need to inform the renderer's sandbox about the NaCl process so
677  // that the renderer can send handles to the NaCl process using
678  // BrokerDuplicateHandle().
679  if (RunningOnWOW64()) {
680    if (!content::BrokerAddTargetPeer(process_->GetData().handle)) {
681      SendErrorToRenderer("BrokerAddTargetPeer() failed");
682      return false;
683    }
684  }
685#endif
686
687  FileDescriptor imc_handle_for_renderer;
688#if defined(OS_WIN)
689  // Copy the handle into the renderer process.
690  HANDLE handle_in_renderer;
691  if (!DuplicateHandle(base::GetCurrentProcessHandle(),
692                       reinterpret_cast<HANDLE>(
693                           internal_->socket_for_renderer),
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;
701  }
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 = internal_->socket_for_renderer;
709  imc_handle.auto_close = true;
710  imc_handle_for_renderer = imc_handle;
711#endif
712
713  const ChildProcessData& data = process_->GetData();
714  SendMessageToRenderer(
715      NaClLaunchResult(imc_handle_for_renderer,
716                       ppapi_channel_handle,
717                       trusted_channel_handle,
718                       base::GetProcId(data.handle),
719                       data.id),
720      std::string() /* error_message */);
721  internal_->socket_for_renderer = NACL_INVALID_HANDLE;
722  return true;
723}
724
725void NaClProcessHost::SendErrorToRenderer(const std::string& error_message) {
726  LOG(ERROR) << "NaCl process launch failed: " << error_message;
727  SendMessageToRenderer(NaClLaunchResult(), error_message);
728}
729
730void NaClProcessHost::SendMessageToRenderer(
731    const NaClLaunchResult& result,
732    const std::string& error_message) {
733  DCHECK(nacl_host_message_filter_);
734  DCHECK(reply_msg_);
735  if (nacl_host_message_filter_ != NULL && reply_msg_ != NULL) {
736    NaClHostMsg_LaunchNaCl::WriteReplyParams(
737        reply_msg_, result, error_message);
738    nacl_host_message_filter_->Send(reply_msg_);
739    nacl_host_message_filter_ = NULL;
740    reply_msg_ = NULL;
741  }
742}
743
744// TCP port we chose for NaCl debug stub. It can be any other number.
745static const int kInitialDebugStubPort = 4014;
746
747#if defined(OS_POSIX)
748net::SocketDescriptor NaClProcessHost::GetDebugStubSocketHandle() {
749  NaClBrowser* nacl_browser = NaClBrowser::GetInstance();
750  net::SocketDescriptor s = net::kInvalidSocket;
751  // We always try to allocate the default port first. If this fails, we then
752  // allocate any available port.
753  // On success, if the test system has register a handler
754  // (GdbDebugStubPortListener), we fire a notification.
755  int port = kInitialDebugStubPort;
756  s = net::TCPListenSocket::CreateAndBind("127.0.0.1", port);
757  if (s == net::kInvalidSocket) {
758    s = net::TCPListenSocket::CreateAndBindAnyPort("127.0.0.1", &port);
759  }
760  if (s != net::kInvalidSocket) {
761    if (nacl_browser->HasGdbDebugStubPortListener()) {
762      nacl_browser->FireGdbDebugStubPortOpened(port);
763    }
764  }
765  // Set debug stub port on the process object.
766  process_->SetNaClDebugStubPort(port);
767  if (s == net::kInvalidSocket) {
768    LOG(ERROR) << "failed to open socket for debug stub";
769    return net::kInvalidSocket;
770  } else {
771    LOG(WARNING) << "debug stub on port " << port;
772  }
773  if (listen(s, 1)) {
774    LOG(ERROR) << "listen() failed on debug stub socket";
775    if (IGNORE_EINTR(close(s)) < 0)
776      PLOG(ERROR) << "failed to close debug stub socket";
777    return net::kInvalidSocket;
778  }
779  return s;
780}
781#endif
782
783bool NaClProcessHost::StartNaClExecution() {
784  NaClBrowser* nacl_browser = NaClBrowser::GetInstance();
785
786  NaClStartParams params;
787  params.validation_cache_enabled = nacl_browser->ValidationCacheIsEnabled();
788  params.validation_cache_key = nacl_browser->GetValidationCacheKey();
789  params.version = NaClBrowser::GetDelegate()->GetVersionString();
790  params.enable_exception_handling = enable_exception_handling_;
791  params.enable_debug_stub = enable_debug_stub_ &&
792      NaClBrowser::GetDelegate()->URLMatchesDebugPatterns(manifest_url_);
793  // Enable PPAPI proxy channel creation only for renderer processes.
794  params.enable_ipc_proxy = enable_ppapi_proxy();
795  params.uses_irt = uses_irt_;
796  params.enable_dyncode_syscalls = enable_dyncode_syscalls_;
797
798  const ChildProcessData& data = process_->GetData();
799  if (!ShareHandleToSelLdr(data.handle,
800                           internal_->socket_for_sel_ldr, true,
801                           &params.handles)) {
802    return false;
803  }
804
805  if (params.uses_irt) {
806    base::PlatformFile irt_file = nacl_browser->IrtFile();
807    CHECK_NE(irt_file, base::kInvalidPlatformFileValue);
808    // Send over the IRT file handle.  We don't close our own copy!
809    if (!ShareHandleToSelLdr(data.handle, irt_file, false, &params.handles))
810      return false;
811  }
812
813#if defined(OS_MACOSX)
814  // For dynamic loading support, NaCl requires a file descriptor that
815  // was created in /tmp, since those created with shm_open() are not
816  // mappable with PROT_EXEC.  Rather than requiring an extra IPC
817  // round trip out of the sandbox, we create an FD here.
818  base::SharedMemory memory_buffer;
819  base::SharedMemoryCreateOptions options;
820  options.size = 1;
821  options.executable = true;
822  if (!memory_buffer.Create(options)) {
823    DLOG(ERROR) << "Failed to allocate memory buffer";
824    return false;
825  }
826  FileDescriptor memory_fd;
827  memory_fd.fd = dup(memory_buffer.handle().fd);
828  if (memory_fd.fd < 0) {
829    DLOG(ERROR) << "Failed to dup() a file descriptor";
830    return false;
831  }
832  memory_fd.auto_close = true;
833  params.handles.push_back(memory_fd);
834#endif
835
836#if defined(OS_POSIX)
837  if (params.enable_debug_stub) {
838    net::SocketDescriptor server_bound_socket = GetDebugStubSocketHandle();
839    if (server_bound_socket != net::kInvalidSocket) {
840      params.debug_stub_server_bound_socket =
841          FileDescriptor(server_bound_socket, true);
842    }
843  }
844#endif
845
846  process_->Send(new NaClProcessMsg_Start(params));
847
848  internal_->socket_for_sel_ldr = NACL_INVALID_HANDLE;
849  return true;
850}
851
852// This method is called when NaClProcessHostMsg_PpapiChannelCreated is
853// received.
854void NaClProcessHost::OnPpapiChannelsCreated(
855    const IPC::ChannelHandle& browser_channel_handle,
856    const IPC::ChannelHandle& ppapi_renderer_channel_handle,
857    const IPC::ChannelHandle& trusted_renderer_channel_handle) {
858  if (!enable_ppapi_proxy()) {
859    ReplyToRenderer(IPC::ChannelHandle(), trusted_renderer_channel_handle);
860    return;
861  }
862
863  if (!ipc_proxy_channel_.get()) {
864    DCHECK_EQ(PROCESS_TYPE_NACL_LOADER, process_->GetData().process_type);
865
866    ipc_proxy_channel_.reset(
867        new IPC::ChannelProxy(browser_channel_handle,
868                              IPC::Channel::MODE_CLIENT,
869                              NULL,
870                              base::MessageLoopProxy::current().get()));
871    // Create the browser ppapi host and enable PPAPI message dispatching to the
872    // browser process.
873    ppapi_host_.reset(content::BrowserPpapiHost::CreateExternalPluginProcess(
874        ipc_proxy_channel_.get(),  // sender
875        permissions_,
876        process_->GetData().handle,
877        ipc_proxy_channel_.get(),
878        nacl_host_message_filter_->render_process_id(),
879        render_view_id_,
880        profile_directory_));
881    ppapi_host_->SetOnKeepaliveCallback(
882        NaClBrowser::GetDelegate()->GetOnKeepaliveCallback());
883
884    ppapi::PpapiNaClPluginArgs args;
885    args.off_the_record = nacl_host_message_filter_->off_the_record();
886    args.permissions = permissions_;
887    args.keepalive_throttle_interval_milliseconds =
888        keepalive_throttle_interval_milliseconds_;
889    CommandLine* cmdline = CommandLine::ForCurrentProcess();
890    DCHECK(cmdline);
891    std::string flag_whitelist[] = {
892      switches::kV,
893      switches::kVModule,
894    };
895    for (size_t i = 0; i < arraysize(flag_whitelist); ++i) {
896      std::string value = cmdline->GetSwitchValueASCII(flag_whitelist[i]);
897      if (!value.empty()) {
898        args.switch_names.push_back(flag_whitelist[i]);
899        args.switch_values.push_back(value);
900      }
901    }
902
903    ppapi_host_->GetPpapiHost()->AddHostFactoryFilter(
904        scoped_ptr<ppapi::host::HostFactory>(
905            NaClBrowser::GetDelegate()->CreatePpapiHostFactory(
906                ppapi_host_.get())));
907
908    // Send a message to initialize the IPC dispatchers in the NaCl plugin.
909    ipc_proxy_channel_->Send(new PpapiMsg_InitializeNaClDispatcher(args));
910
911    // Let the renderer know that the IPC channels are established.
912    ReplyToRenderer(ppapi_renderer_channel_handle,
913                    trusted_renderer_channel_handle);
914  } else {
915    // Attempt to open more than 1 browser channel is not supported.
916    // Shut down the NaCl process.
917    process_->GetHost()->ForceShutdown();
918  }
919}
920
921bool NaClProcessHost::StartWithLaunchedProcess() {
922  NaClBrowser* nacl_browser = NaClBrowser::GetInstance();
923
924  if (nacl_browser->IsReady()) {
925    return StartNaClExecution();
926  } else if (nacl_browser->IsOk()) {
927    nacl_browser->WaitForResources(
928        base::Bind(&NaClProcessHost::OnResourcesReady,
929                   weak_factory_.GetWeakPtr()));
930    return true;
931  } else {
932    SendErrorToRenderer("previously failed to acquire shared resources");
933    return false;
934  }
935}
936
937void NaClProcessHost::OnQueryKnownToValidate(const std::string& signature,
938                                             bool* result) {
939  NaClBrowser* nacl_browser = NaClBrowser::GetInstance();
940  *result = nacl_browser->QueryKnownToValidate(signature, off_the_record_);
941}
942
943void NaClProcessHost::OnSetKnownToValidate(const std::string& signature) {
944  NaClBrowser::GetInstance()->SetKnownToValidate(
945      signature, off_the_record_);
946}
947
948void NaClProcessHost::FileResolved(
949    const base::FilePath& file_path,
950    IPC::Message* reply_msg,
951    base::File file) {
952  if (file.IsValid()) {
953    IPC::PlatformFileForTransit handle = IPC::TakeFileHandleForProcess(
954        file.Pass(),
955        process_->GetData().handle);
956    NaClProcessMsg_ResolveFileToken::WriteReplyParams(
957        reply_msg,
958        handle,
959        file_path);
960  } else {
961    NaClProcessMsg_ResolveFileToken::WriteReplyParams(
962        reply_msg,
963        IPC::InvalidPlatformFileForTransit(),
964        base::FilePath());
965  }
966  Send(reply_msg);
967}
968
969void NaClProcessHost::OnResolveFileToken(uint64 file_token_lo,
970                                         uint64 file_token_hi,
971                                         IPC::Message* reply_msg) {
972  // Was the file registered?
973  //
974  // Note that the file path cache is of bounded size, and old entries can get
975  // evicted.  If a large number of NaCl modules are being launched at once,
976  // resolving the file_token may fail because the path cache was thrashed
977  // while the file_token was in flight.  In this case the query fails, and we
978  // need to fall back to the slower path.
979  //
980  // However: each NaCl process will consume 2-3 entries as it starts up, this
981  // means that eviction will not happen unless you start up 33+ NaCl processes
982  // at the same time, and this still requires worst-case timing.  As a
983  // practical matter, no entries should be evicted prematurely.
984  // The cache itself should take ~ (150 characters * 2 bytes/char + ~60 bytes
985  // data structure overhead) * 100 = 35k when full, so making it bigger should
986  // not be a problem, if needed.
987  //
988  // Each NaCl process will consume 2-3 entries because the manifest and main
989  // nexe are currently not resolved.  Shared libraries will be resolved.  They
990  // will be loaded sequentially, so they will only consume a single entry
991  // while the load is in flight.
992  //
993  // TODO(ncbray): track behavior with UMA. If entries are getting evicted or
994  // bogus keys are getting queried, this would be good to know.
995  base::FilePath file_path;
996  if (!NaClBrowser::GetInstance()->GetFilePath(
997        file_token_lo, file_token_hi, &file_path)) {
998    NaClProcessMsg_ResolveFileToken::WriteReplyParams(
999        reply_msg,
1000        IPC::InvalidPlatformFileForTransit(),
1001        base::FilePath());
1002    Send(reply_msg);
1003    return;
1004  }
1005
1006  // Open the file.
1007  if (!base::PostTaskAndReplyWithResult(
1008          content::BrowserThread::GetBlockingPool(),
1009          FROM_HERE,
1010          base::Bind(OpenNaClExecutableImpl, file_path),
1011          base::Bind(&NaClProcessHost::FileResolved,
1012                     weak_factory_.GetWeakPtr(),
1013                     file_path,
1014                     reply_msg))) {
1015     NaClProcessMsg_ResolveFileToken::WriteReplyParams(
1016         reply_msg,
1017         IPC::InvalidPlatformFileForTransit(),
1018         base::FilePath());
1019     Send(reply_msg);
1020  }
1021}
1022
1023#if defined(OS_WIN)
1024void NaClProcessHost::OnAttachDebugExceptionHandler(const std::string& info,
1025                                                    IPC::Message* reply_msg) {
1026  if (!AttachDebugExceptionHandler(info, reply_msg)) {
1027    // Send failure message.
1028    NaClProcessMsg_AttachDebugExceptionHandler::WriteReplyParams(reply_msg,
1029                                                                 false);
1030    Send(reply_msg);
1031  }
1032}
1033
1034bool NaClProcessHost::AttachDebugExceptionHandler(const std::string& info,
1035                                                  IPC::Message* reply_msg) {
1036  if (!enable_exception_handling_ && !enable_debug_stub_) {
1037    DLOG(ERROR) <<
1038        "Debug exception handler requested by NaCl process when not enabled";
1039    return false;
1040  }
1041  if (debug_exception_handler_requested_) {
1042    // The NaCl process should not request this multiple times.
1043    DLOG(ERROR) << "Multiple AttachDebugExceptionHandler requests received";
1044    return false;
1045  }
1046  debug_exception_handler_requested_ = true;
1047
1048  base::ProcessId nacl_pid = base::GetProcId(process_->GetData().handle);
1049  base::ProcessHandle temp_handle;
1050  // We cannot use process_->GetData().handle because it does not have
1051  // the necessary access rights.  We open the new handle here rather
1052  // than in the NaCl broker process in case the NaCl loader process
1053  // dies before the NaCl broker process receives the message we send.
1054  // The debug exception handler uses DebugActiveProcess() to attach,
1055  // but this takes a PID.  We need to prevent the NaCl loader's PID
1056  // from being reused before DebugActiveProcess() is called, and
1057  // holding a process handle open achieves this.
1058  if (!base::OpenProcessHandleWithAccess(
1059           nacl_pid,
1060           base::kProcessAccessQueryInformation |
1061           base::kProcessAccessSuspendResume |
1062           base::kProcessAccessTerminate |
1063           base::kProcessAccessVMOperation |
1064           base::kProcessAccessVMRead |
1065           base::kProcessAccessVMWrite |
1066           base::kProcessAccessDuplicateHandle |
1067           base::kProcessAccessWaitForTermination,
1068           &temp_handle)) {
1069    LOG(ERROR) << "Failed to get process handle";
1070    return false;
1071  }
1072  base::win::ScopedHandle process_handle(temp_handle);
1073
1074  attach_debug_exception_handler_reply_msg_.reset(reply_msg);
1075  // If the NaCl loader is 64-bit, the process running its debug
1076  // exception handler must be 64-bit too, so we use the 64-bit NaCl
1077  // broker process for this.  Otherwise, on a 32-bit system, we use
1078  // the 32-bit browser process to run the debug exception handler.
1079  if (RunningOnWOW64()) {
1080    return NaClBrokerService::GetInstance()->LaunchDebugExceptionHandler(
1081               weak_factory_.GetWeakPtr(), nacl_pid, process_handle, info);
1082  } else {
1083    NaClStartDebugExceptionHandlerThread(
1084        process_handle.Take(), info,
1085        base::MessageLoopProxy::current(),
1086        base::Bind(&NaClProcessHost::OnDebugExceptionHandlerLaunchedByBroker,
1087                   weak_factory_.GetWeakPtr()));
1088    return true;
1089  }
1090}
1091#endif
1092
1093}  // namespace nacl
1094