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