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