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