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