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