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