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