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