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 <string.h>
8 #include <algorithm>
9 #include <memory>
10 #include <string>
11 #include <utility>
12 #include <vector>
13 
14 #include "base/base_switches.h"
15 #include "base/bind.h"
16 #include "base/command_line.h"
17 #include "base/feature_list.h"
18 #include "base/files/file_util.h"
19 #include "base/location.h"
20 #include "base/metrics/histogram_macros.h"
21 #include "base/path_service.h"
22 #include "base/process/launch.h"
23 #include "base/process/process_iterator.h"
24 #include "base/rand_util.h"
25 #include "base/single_thread_task_runner.h"
26 #include "base/stl_util.h"
27 #include "base/strings/string_number_conversions.h"
28 #include "base/strings/string_split.h"
29 #include "base/strings/string_util.h"
30 #include "base/strings/stringprintf.h"
31 #include "base/strings/utf_string_conversions.h"
32 #include "base/sys_byteorder.h"
33 #include "base/task/post_task.h"
34 #include "base/task/thread_pool.h"
35 #include "base/threading/thread_task_runner_handle.h"
36 #include "build/build_config.h"
37 #include "components/nacl/browser/nacl_browser.h"
38 #include "components/nacl/browser/nacl_browser_delegate.h"
39 #include "components/nacl/browser/nacl_host_message_filter.h"
40 #include "components/nacl/common/nacl_cmd_line.h"
41 #include "components/nacl/common/nacl_constants.h"
42 #include "components/nacl/common/nacl_host_messages.h"
43 #include "components/nacl/common/nacl_messages.h"
44 #include "components/nacl/common/nacl_process_type.h"
45 #include "components/nacl/common/nacl_switches.h"
46 #include "components/url_formatter/url_formatter.h"
47 #include "content/public/browser/browser_child_process_host.h"
48 #include "content/public/browser/browser_ppapi_host.h"
49 #include "content/public/browser/child_process_data.h"
50 #include "content/public/browser/plugin_service.h"
51 #include "content/public/browser/render_process_host.h"
52 #include "content/public/browser/web_contents.h"
53 #include "content/public/common/child_process_host.h"
54 #include "content/public/common/content_switches.h"
55 #include "content/public/common/process_type.h"
56 #include "content/public/common/sandboxed_process_launcher_delegate.h"
57 #include "content/public/common/zygote/zygote_buildflags.h"
58 #include "ipc/ipc_channel.h"
59 #include "mojo/public/cpp/system/invitation.h"
60 #include "net/socket/socket_descriptor.h"
61 #include "ppapi/host/host_factory.h"
62 #include "ppapi/host/ppapi_host.h"
63 #include "ppapi/proxy/ppapi_messages.h"
64 #include "ppapi/shared_impl/ppapi_constants.h"
65 #include "ppapi/shared_impl/ppapi_nacl_plugin_args.h"
66 #include "sandbox/policy/switches.h"
67 
68 #if BUILDFLAG(USE_ZYGOTE_HANDLE)
69 #include "content/public/common/zygote/zygote_handle.h"  // nogncheck
70 #endif  // BUILDFLAG(USE_ZYGOTE_HANDLE)
71 
72 #if defined(OS_POSIX)
73 
74 #include <arpa/inet.h>
75 #include <fcntl.h>
76 #include <netinet/in.h>
77 #include <sys/socket.h>
78 
79 #elif defined(OS_WIN)
80 #include <windows.h>
81 #include <winsock2.h>
82 
83 #include "base/threading/thread.h"
84 #include "base/win/scoped_handle.h"
85 #include "base/win/windows_version.h"
86 #include "components/nacl/browser/nacl_broker_service_win.h"
87 #include "components/nacl/common/nacl_debug_exception_handler_win.h"
88 #include "content/public/common/sandbox_init.h"
89 #endif
90 
91 using content::BrowserThread;
92 using content::ChildProcessData;
93 using content::ChildProcessHost;
94 using ppapi::proxy::SerializedHandle;
95 
96 namespace nacl {
97 
98 #if defined(OS_WIN)
99 namespace {
100 
101 // Looks for the largest contiguous unallocated region of address
102 // space and returns it via |*out_addr| and |*out_size|.
FindAddressSpace(base::ProcessHandle process,char ** out_addr,size_t * out_size)103 void FindAddressSpace(base::ProcessHandle process,
104                       char** out_addr, size_t* out_size) {
105   *out_addr = nullptr;
106   *out_size = 0;
107   char* addr = 0;
108   while (true) {
109     MEMORY_BASIC_INFORMATION info;
110     size_t result = VirtualQueryEx(process, static_cast<void*>(addr),
111                                    &info, sizeof(info));
112     if (result < sizeof(info))
113       break;
114     if (info.State == MEM_FREE && info.RegionSize > *out_size) {
115       *out_addr = addr;
116       *out_size = info.RegionSize;
117     }
118     addr += info.RegionSize;
119   }
120 }
121 
122 #ifdef _DLL
123 
IsInPath(const std::string & path_env_var,const std::string & dir)124 bool IsInPath(const std::string& path_env_var, const std::string& dir) {
125   for (const base::StringPiece& cur : base::SplitStringPiece(
126            path_env_var, ";", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL)) {
127     if (cur == dir)
128       return true;
129   }
130   return false;
131 }
132 
133 #endif  // _DLL
134 
135 }  // namespace
136 
137 // Allocates |size| bytes of address space in the given process at a
138 // randomised address.
AllocateAddressSpaceASLR(base::ProcessHandle process,size_t size)139 void* AllocateAddressSpaceASLR(base::ProcessHandle process, size_t size) {
140   char* addr;
141   size_t avail_size;
142   FindAddressSpace(process, &addr, &avail_size);
143   if (avail_size < size)
144     return nullptr;
145   size_t offset = base::RandGenerator(avail_size - size);
146   const int kPageSize = 0x10000;
147   void* request_addr = reinterpret_cast<void*>(
148       reinterpret_cast<uint64_t>(addr + offset) & ~(kPageSize - 1));
149   return VirtualAllocEx(process, request_addr, size,
150                         MEM_RESERVE, PAGE_NOACCESS);
151 }
152 
153 namespace {
154 
RunningOnWOW64()155 bool RunningOnWOW64() {
156   return (base::win::OSInfo::GetInstance()->wow64_status() ==
157           base::win::OSInfo::WOW64_ENABLED);
158 }
159 
160 }  // namespace
161 
162 #endif  // defined(OS_WIN)
163 
164 namespace {
165 
166 // NOTE: changes to this class need to be reviewed by the security team.
167 class NaClSandboxedProcessLauncherDelegate
168     : public content::SandboxedProcessLauncherDelegate {
169  public:
NaClSandboxedProcessLauncherDelegate()170   NaClSandboxedProcessLauncherDelegate() {}
171 
172 #if defined(OS_WIN)
PostSpawnTarget(base::ProcessHandle process)173   void PostSpawnTarget(base::ProcessHandle process) override {
174     // For Native Client sel_ldr processes on 32-bit Windows, reserve 1 GB of
175     // address space to prevent later failure due to address space fragmentation
176     // from .dll loading. The NaCl process will attempt to locate this space by
177     // scanning the address space using VirtualQuery.
178     // TODO(bbudge) Handle the --no-sandbox case.
179     // http://code.google.com/p/nativeclient/issues/detail?id=2131
180     const SIZE_T kNaClSandboxSize = 1 << 30;
181     if (!nacl::AllocateAddressSpaceASLR(process, kNaClSandboxSize)) {
182       DLOG(WARNING) << "Failed to reserve address space for Native Client";
183     }
184   }
185 #endif  // OS_WIN
186 
187 #if BUILDFLAG(USE_ZYGOTE_HANDLE)
GetZygote()188   content::ZygoteHandle GetZygote() override {
189     return content::GetGenericZygote();
190   }
191 #endif  // BUILDFLAG(USE_ZYGOTE_HANDLE)
192 
GetSandboxType()193   sandbox::policy::SandboxType GetSandboxType() override {
194     return sandbox::policy::SandboxType::kPpapi;
195   }
196 };
197 
CloseFile(base::File file)198 void CloseFile(base::File file) {
199   // The base::File destructor will close the file for us.
200 }
201 
202 }  // namespace
203 
NaClProcessHost(const GURL & manifest_url,base::File nexe_file,const NaClFileToken & nexe_token,const std::vector<NaClResourcePrefetchResult> & prefetched_resource_files,ppapi::PpapiPermissions permissions,int render_view_id,uint32_t permission_bits,bool uses_nonsfi_mode,bool nonsfi_mode_allowed,bool off_the_record,NaClAppProcessType process_type,const base::FilePath & profile_directory)204 NaClProcessHost::NaClProcessHost(
205     const GURL& manifest_url,
206     base::File nexe_file,
207     const NaClFileToken& nexe_token,
208     const std::vector<NaClResourcePrefetchResult>& prefetched_resource_files,
209     ppapi::PpapiPermissions permissions,
210     int render_view_id,
211     uint32_t permission_bits,
212     bool uses_nonsfi_mode,
213     bool nonsfi_mode_allowed,
214     bool off_the_record,
215     NaClAppProcessType process_type,
216     const base::FilePath& profile_directory)
217     : manifest_url_(manifest_url),
218       nexe_file_(std::move(nexe_file)),
219       nexe_token_(nexe_token),
220       prefetched_resource_files_(prefetched_resource_files),
221       permissions_(permissions),
222 #if defined(OS_WIN)
223       process_launched_by_broker_(false),
224 #endif
225       reply_msg_(nullptr),
226 #if defined(OS_WIN)
227       debug_exception_handler_requested_(false),
228 #endif
229       uses_nonsfi_mode_(uses_nonsfi_mode),
230       nonsfi_mode_allowed_(nonsfi_mode_allowed),
231       enable_debug_stub_(false),
232       enable_crash_throttling_(false),
233       off_the_record_(off_the_record),
234       process_type_(process_type),
235       profile_directory_(profile_directory),
236       render_view_id_(render_view_id) {
237   process_ = content::BrowserChildProcessHost::Create(
238       static_cast<content::ProcessType>(PROCESS_TYPE_NACL_LOADER), this,
239       content::ChildProcessHost::IpcMode::kLegacy);
240   process_->SetMetricsName("NaCl Loader");
241 
242   // Set the display name so the user knows what plugin the process is running.
243   // We aren't on the UI thread so getting the pref locale for language
244   // formatting isn't possible, so IDN will be lost, but this is probably OK
245   // for this use case.
246   process_->SetName(url_formatter::FormatUrl(manifest_url_));
247 
248   enable_debug_stub_ = base::CommandLine::ForCurrentProcess()->HasSwitch(
249       switches::kEnableNaClDebug);
250   DCHECK(process_type_ != kUnknownNaClProcessType);
251   enable_crash_throttling_ = process_type_ != kNativeNaClProcessType;
252 }
253 
~NaClProcessHost()254 NaClProcessHost::~NaClProcessHost() {
255   // Report exit status only if the process was successfully started.
256   if (process_->GetData().GetProcess().IsValid()) {
257     content::ChildProcessTerminationInfo info =
258         process_->GetTerminationInfo(false /* known_dead */);
259     std::string message =
260         base::StringPrintf("NaCl process exited with status %i (0x%x)",
261                            info.exit_code, info.exit_code);
262     if (info.exit_code == 0) {
263       VLOG(1) << message;
264     } else {
265       LOG(ERROR) << message;
266     }
267     NaClBrowser::GetInstance()->OnProcessEnd(process_->GetData().id);
268   }
269 
270   // Note: this does not work on Windows, though we currently support this
271   // prefetching feature only on POSIX platforms, so it should be ok.
272 #if defined(OS_WIN)
273   DCHECK(prefetched_resource_files_.empty());
274 #else
275   for (size_t i = 0; i < prefetched_resource_files_.size(); ++i) {
276     // The process failed to launch for some reason. Close resource file
277     // handles.
278     base::File file(IPC::PlatformFileForTransitToFile(
279         prefetched_resource_files_[i].file));
280     base::ThreadPool::PostTask(
281         FROM_HERE, {base::TaskPriority::BEST_EFFORT, base::MayBlock()},
282         base::BindOnce(&CloseFile, std::move(file)));
283   }
284 #endif
285   // Open files need to be closed on the blocking pool.
286   if (nexe_file_.IsValid()) {
287     base::ThreadPool::PostTask(
288         FROM_HERE, {base::TaskPriority::BEST_EFFORT, base::MayBlock()},
289         base::BindOnce(&CloseFile, std::move(nexe_file_)));
290   }
291 
292   if (reply_msg_) {
293     // The process failed to launch for some reason.
294     // Don't keep the renderer hanging.
295     reply_msg_->set_reply_error();
296     nacl_host_message_filter_->Send(reply_msg_);
297   }
298 #if defined(OS_WIN)
299   if (process_launched_by_broker_) {
300     NaClBrokerService::GetInstance()->OnLoaderDied();
301   }
302 #endif
303 }
304 
OnProcessCrashed(int exit_status)305 void NaClProcessHost::OnProcessCrashed(int exit_status) {
306   if (enable_crash_throttling_ &&
307       !base::CommandLine::ForCurrentProcess()->HasSwitch(
308           switches::kDisablePnaclCrashThrottling)) {
309     NaClBrowser::GetInstance()->OnProcessCrashed();
310   }
311 }
312 
313 // This is called at browser startup.
314 // static
EarlyStartup()315 void NaClProcessHost::EarlyStartup() {
316   NaClBrowser::GetInstance()->EarlyStartup();
317   // Inform NaClBrowser that we exist and will have a debug port at some point.
318 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
319   // Open the IRT file early to make sure that it isn't replaced out from
320   // under us by autoupdate.
321   NaClBrowser::GetInstance()->EnsureIrtAvailable();
322 #endif
323   base::CommandLine* cmd = base::CommandLine::ForCurrentProcess();
324   std::string nacl_debug_mask =
325       cmd->GetSwitchValueASCII(switches::kNaClDebugMask);
326   // By default, exclude debugging SSH and the PNaCl translator.
327   // about::flags only allows empty flags as the default, so replace
328   // the empty setting with the default. To debug all apps, use a wild-card.
329   if (nacl_debug_mask.empty()) {
330     nacl_debug_mask = "!*://*/*ssh_client.nmf,chrome://pnacl-translator/*";
331   }
332   NaClBrowser::GetDelegate()->SetDebugPatterns(nacl_debug_mask);
333 }
334 
Launch(NaClHostMessageFilter * nacl_host_message_filter,IPC::Message * reply_msg,const base::FilePath & manifest_path)335 void NaClProcessHost::Launch(
336     NaClHostMessageFilter* nacl_host_message_filter,
337     IPC::Message* reply_msg,
338     const base::FilePath& manifest_path) {
339   nacl_host_message_filter_ = nacl_host_message_filter;
340   reply_msg_ = reply_msg;
341   manifest_path_ = manifest_path;
342 
343   // Do not launch the requested NaCl module if NaCl is marked "unstable" due
344   // to too many crashes within a given time period.
345   if (enable_crash_throttling_ &&
346       !base::CommandLine::ForCurrentProcess()->HasSwitch(
347           switches::kDisablePnaclCrashThrottling) &&
348       NaClBrowser::GetInstance()->IsThrottled()) {
349     SendErrorToRenderer("Process creation was throttled due to excessive"
350                         " crashes");
351     delete this;
352     return;
353   }
354 
355   const base::CommandLine* cmd = base::CommandLine::ForCurrentProcess();
356 #if defined(OS_WIN)
357   if (cmd->HasSwitch(switches::kEnableNaClDebug) &&
358       !cmd->HasSwitch(sandbox::policy::switches::kNoSandbox)) {
359     // We don't switch off sandbox automatically for security reasons.
360     SendErrorToRenderer("NaCl's GDB debug stub requires --no-sandbox flag"
361                         " on Windows. See crbug.com/265624.");
362     delete this;
363     return;
364   }
365 #endif
366   if (cmd->HasSwitch(switches::kNaClGdb) &&
367       !cmd->HasSwitch(switches::kEnableNaClDebug)) {
368     LOG(WARNING) << "--nacl-gdb flag requires --enable-nacl-debug flag";
369   }
370 
371   // Start getting the IRT open asynchronously while we launch the NaCl process.
372   // We'll make sure this actually finished in StartWithLaunchedProcess, below.
373   NaClBrowser* nacl_browser = NaClBrowser::GetInstance();
374   nacl_browser->EnsureAllResourcesAvailable();
375   if (!nacl_browser->IsOk()) {
376     SendErrorToRenderer("could not find all the resources needed"
377                         " to launch the process");
378     delete this;
379     return;
380   }
381 
382   if (uses_nonsfi_mode_) {
383     bool nonsfi_mode_forced_by_command_line = false;
384 #if defined(OS_LINUX) || defined(OS_CHROMEOS)
385     nonsfi_mode_forced_by_command_line =
386         cmd->HasSwitch(switches::kEnableNaClNonSfiMode);
387 #endif
388     bool nonsfi_mode_enabled =
389         nonsfi_mode_forced_by_command_line || nonsfi_mode_allowed_;
390 
391     if (!nonsfi_mode_enabled) {
392       SendErrorToRenderer(
393           "NaCl non-SFI mode is not available for this platform"
394           " and NaCl module.");
395       delete this;
396       return;
397     }
398   }
399 
400   // Launch the process
401   if (!LaunchSelLdr()) {
402     delete this;
403   }
404 }
405 
OnChannelConnected(int32_t peer_pid)406 void NaClProcessHost::OnChannelConnected(int32_t peer_pid) {
407   if (!base::CommandLine::ForCurrentProcess()->GetSwitchValuePath(
408           switches::kNaClGdb).empty()) {
409     LaunchNaClGdb();
410   }
411 }
412 
413 #if defined(OS_WIN)
OnProcessLaunchedByBroker(base::Process process)414 void NaClProcessHost::OnProcessLaunchedByBroker(base::Process process) {
415   process_launched_by_broker_ = true;
416   process_->SetProcess(std::move(process));
417   SetDebugStubPort(nacl::kGdbDebugStubPortUnknown);
418   if (!StartWithLaunchedProcess())
419     delete this;
420 }
421 
OnDebugExceptionHandlerLaunchedByBroker(bool success)422 void NaClProcessHost::OnDebugExceptionHandlerLaunchedByBroker(bool success) {
423   IPC::Message* reply = attach_debug_exception_handler_reply_msg_.release();
424   NaClProcessMsg_AttachDebugExceptionHandler::WriteReplyParams(reply, success);
425   Send(reply);
426 }
427 #endif
428 
429 // Needed to handle sync messages in OnMessageReceived.
Send(IPC::Message * msg)430 bool NaClProcessHost::Send(IPC::Message* msg) {
431   return process_->Send(msg);
432 }
433 
LaunchNaClGdb()434 void NaClProcessHost::LaunchNaClGdb() {
435   const base::CommandLine& command_line =
436       *base::CommandLine::ForCurrentProcess();
437 #if defined(OS_WIN)
438   base::FilePath nacl_gdb =
439       command_line.GetSwitchValuePath(switches::kNaClGdb);
440   base::CommandLine cmd_line(nacl_gdb);
441 #else
442   base::CommandLine::StringType nacl_gdb =
443       command_line.GetSwitchValueNative(switches::kNaClGdb);
444   // We don't support spaces inside arguments in --nacl-gdb switch.
445   base::CommandLine cmd_line(base::SplitString(
446       nacl_gdb, base::CommandLine::StringType(1, ' '),
447       base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL));
448 #endif
449   cmd_line.AppendArg("--eval-command");
450   base::FilePath::StringType irt_path(
451       NaClBrowser::GetInstance()->GetIrtFilePath().value());
452   // Avoid back slashes because nacl-gdb uses posix escaping rules on Windows.
453   // See issue https://code.google.com/p/nativeclient/issues/detail?id=3482.
454   std::replace(irt_path.begin(), irt_path.end(), '\\', '/');
455   cmd_line.AppendArgNative(FILE_PATH_LITERAL("nacl-irt \"") + irt_path +
456                            FILE_PATH_LITERAL("\""));
457   if (!manifest_path_.empty()) {
458     cmd_line.AppendArg("--eval-command");
459     base::FilePath::StringType manifest_path_value(manifest_path_.value());
460     std::replace(manifest_path_value.begin(), manifest_path_value.end(),
461                  '\\', '/');
462     cmd_line.AppendArgNative(FILE_PATH_LITERAL("nacl-manifest \"") +
463                              manifest_path_value + FILE_PATH_LITERAL("\""));
464   }
465   cmd_line.AppendArg("--eval-command");
466   cmd_line.AppendArg("target remote :4014");
467   base::FilePath script =
468       command_line.GetSwitchValuePath(switches::kNaClGdbScript);
469   if (!script.empty()) {
470     cmd_line.AppendArg("--command");
471     cmd_line.AppendArgNative(script.value());
472   }
473   base::LaunchProcess(cmd_line, base::LaunchOptions());
474 }
475 
LaunchSelLdr()476 bool NaClProcessHost::LaunchSelLdr() {
477   process_->GetHost()->CreateChannelMojo();
478 
479   // Build command line for nacl.
480 
481 #if defined(OS_LINUX) || defined(OS_CHROMEOS)
482   int flags = ChildProcessHost::CHILD_ALLOW_SELF;
483 #elif defined(OS_APPLE)
484   int flags = ChildProcessHost::CHILD_PLUGIN;
485 #else
486   int flags = ChildProcessHost::CHILD_NORMAL;
487 #endif
488 
489   base::FilePath exe_path = ChildProcessHost::GetChildPath(flags);
490   if (exe_path.empty())
491     return false;
492 
493 #if defined(OS_WIN)
494   // On Windows 64-bit NaCl loader is called nacl64.exe instead of chrome.exe
495   if (RunningOnWOW64()) {
496     if (!NaClBrowser::GetInstance()->GetNaCl64ExePath(&exe_path)) {
497       SendErrorToRenderer("could not get path to nacl64.exe");
498       return false;
499     }
500 
501 #ifdef _DLL
502     // When using the DLL CRT on Windows, we need to amend the PATH to include
503     // the location of the x64 CRT DLLs. This is only the case when using a
504     // component=shared_library build (i.e. generally dev debug builds). The
505     // x86 CRT DLLs are in e.g. out\Debug for chrome.exe etc., so the x64 ones
506     // are put in out\Debug\x64 which we add to the PATH here so that loader
507     // can find them. See http://crbug.com/346034.
508     std::unique_ptr<base::Environment> env(base::Environment::Create());
509     static const char kPath[] = "PATH";
510     std::string old_path;
511     base::FilePath module_path;
512     if (!base::PathService::Get(base::FILE_MODULE, &module_path)) {
513       SendErrorToRenderer("could not get path to current module");
514       return false;
515     }
516     std::string x64_crt_path =
517         base::WideToUTF8(module_path.DirName().Append(L"x64").value());
518     if (!env->GetVar(kPath, &old_path)) {
519       env->SetVar(kPath, x64_crt_path);
520     } else if (!IsInPath(old_path, x64_crt_path)) {
521       std::string new_path(old_path);
522       new_path.append(";");
523       new_path.append(x64_crt_path);
524       env->SetVar(kPath, new_path);
525     }
526 #endif  // _DLL
527   }
528 #endif
529 
530   std::unique_ptr<base::CommandLine> cmd_line(new base::CommandLine(exe_path));
531   CopyNaClCommandLineArguments(cmd_line.get());
532 
533   cmd_line->AppendSwitchASCII(switches::kProcessType,
534                               (uses_nonsfi_mode_ ?
535                                switches::kNaClLoaderNonSfiProcess :
536                                switches::kNaClLoaderProcess));
537   if (NaClBrowser::GetDelegate()->DialogsAreSuppressed())
538     cmd_line->AppendSwitch(switches::kNoErrorDialogs);
539 
540 #if defined(OS_WIN)
541   cmd_line->AppendArg(switches::kPrefetchArgumentOther);
542 #endif  // defined(OS_WIN)
543 
544 // On Windows we might need to start the broker process to launch a new loader
545 #if defined(OS_WIN)
546   if (RunningOnWOW64()) {
547     if (!NaClBrokerService::GetInstance()->LaunchLoader(
548             weak_factory_.GetWeakPtr(),
549             process_->GetHost()->GetMojoInvitation()->ExtractMessagePipe(0))) {
550       SendErrorToRenderer("broker service did not launch process");
551       return false;
552     }
553     return true;
554   }
555 #endif
556   process_->Launch(std::make_unique<NaClSandboxedProcessLauncherDelegate>(),
557                    std::move(cmd_line), true);
558   return true;
559 }
560 
OnMessageReceived(const IPC::Message & msg)561 bool NaClProcessHost::OnMessageReceived(const IPC::Message& msg) {
562   if (uses_nonsfi_mode_) {
563     // IPC messages relating to NaCl's validation cache must not be exposed
564     // in Non-SFI Mode, otherwise a Non-SFI nexe could use SetKnownToValidate
565     // to create a hole in the SFI sandbox.
566     // In Non-SFI mode, no message is expected.
567     return false;
568   }
569 
570   bool handled = true;
571   IPC_BEGIN_MESSAGE_MAP(NaClProcessHost, msg)
572     IPC_MESSAGE_HANDLER(NaClProcessMsg_QueryKnownToValidate,
573                         OnQueryKnownToValidate)
574     IPC_MESSAGE_HANDLER(NaClProcessMsg_SetKnownToValidate,
575                         OnSetKnownToValidate)
576     IPC_MESSAGE_HANDLER(NaClProcessMsg_ResolveFileToken,
577                         OnResolveFileToken)
578 
579 #if defined(OS_WIN)
580     IPC_MESSAGE_HANDLER_DELAY_REPLY(
581         NaClProcessMsg_AttachDebugExceptionHandler,
582         OnAttachDebugExceptionHandler)
583     IPC_MESSAGE_HANDLER(NaClProcessHostMsg_DebugStubPortSelected,
584                         OnDebugStubPortSelected)
585 #endif
586     IPC_MESSAGE_HANDLER(NaClProcessHostMsg_PpapiChannelsCreated,
587                         OnPpapiChannelsCreated)
588     IPC_MESSAGE_UNHANDLED(handled = false)
589   IPC_END_MESSAGE_MAP()
590   return handled;
591 }
592 
OnProcessLaunched()593 void NaClProcessHost::OnProcessLaunched() {
594   if (!StartWithLaunchedProcess())
595     delete this;
596 }
597 
598 // Called when the NaClBrowser singleton has been fully initialized.
OnResourcesReady()599 void NaClProcessHost::OnResourcesReady() {
600   NaClBrowser* nacl_browser = NaClBrowser::GetInstance();
601   if (!nacl_browser->IsReady()) {
602     SendErrorToRenderer("could not acquire shared resources needed by NaCl");
603     delete this;
604   } else if (!StartNaClExecution()) {
605     delete this;
606   }
607 }
608 
ReplyToRenderer(mojo::ScopedMessagePipeHandle ppapi_channel_handle,mojo::ScopedMessagePipeHandle trusted_channel_handle,mojo::ScopedMessagePipeHandle manifest_service_channel_handle,base::ReadOnlySharedMemoryRegion crash_info_shmem_region)609 void NaClProcessHost::ReplyToRenderer(
610     mojo::ScopedMessagePipeHandle ppapi_channel_handle,
611     mojo::ScopedMessagePipeHandle trusted_channel_handle,
612     mojo::ScopedMessagePipeHandle manifest_service_channel_handle,
613     base::ReadOnlySharedMemoryRegion crash_info_shmem_region) {
614   // Hereafter, we always send an IPC message with handles created above
615   // which, on Windows, are not closable in this process.
616   std::string error_message;
617   if (!uses_nonsfi_mode_ && !crash_info_shmem_region.IsValid()) {
618     // On error, we do not send "IPC::ChannelHandle"s to the renderer process.
619     // Note that some other FDs/handles still get sent to the renderer, but
620     // will be closed there.
621     ppapi_channel_handle.reset();
622     trusted_channel_handle.reset();
623     manifest_service_channel_handle.reset();
624     error_message = "shared memory region not valid";
625   }
626 
627   const ChildProcessData& data = process_->GetData();
628   SendMessageToRenderer(
629       NaClLaunchResult(
630           ppapi_channel_handle.release(), trusted_channel_handle.release(),
631           manifest_service_channel_handle.release(), data.GetProcess().Pid(),
632           data.id, std::move(crash_info_shmem_region)),
633       error_message);
634 }
635 
SendErrorToRenderer(const std::string & error_message)636 void NaClProcessHost::SendErrorToRenderer(const std::string& error_message) {
637   LOG(ERROR) << "NaCl process launch failed: " << error_message;
638   SendMessageToRenderer(NaClLaunchResult(), error_message);
639 }
640 
SendMessageToRenderer(const NaClLaunchResult & result,const std::string & error_message)641 void NaClProcessHost::SendMessageToRenderer(
642     const NaClLaunchResult& result,
643     const std::string& error_message) {
644   DCHECK(nacl_host_message_filter_.get());
645   DCHECK(reply_msg_);
646   if (!nacl_host_message_filter_.get() || !reply_msg_) {
647     // As DCHECKed above, this case should not happen in general.
648     // Though, in this case, unfortunately there is no proper way to release
649     // resources which are already created in |result|. We just give up on
650     // releasing them, and leak them.
651     return;
652   }
653 
654   NaClHostMsg_LaunchNaCl::WriteReplyParams(reply_msg_, result, error_message);
655   nacl_host_message_filter_->Send(reply_msg_);
656   nacl_host_message_filter_.reset();
657   reply_msg_ = nullptr;
658 }
659 
SetDebugStubPort(int port)660 void NaClProcessHost::SetDebugStubPort(int port) {
661   NaClBrowser* nacl_browser = NaClBrowser::GetInstance();
662   nacl_browser->SetProcessGdbDebugStubPort(process_->GetData().id, port);
663 }
664 
665 #if defined(OS_POSIX)
666 // TCP port we chose for NaCl debug stub. It can be any other number.
667 static const uint16_t kInitialDebugStubPort = 4014;
668 
GetDebugStubSocketHandle()669 net::SocketDescriptor NaClProcessHost::GetDebugStubSocketHandle() {
670   // We always try to allocate the default port first. If this fails, we then
671   // allocate any available port.
672   // On success, if the test system has register a handler
673   // (GdbDebugStubPortListener), we fire a notification.
674   uint16_t port = kInitialDebugStubPort;
675   net::SocketDescriptor s =
676       net::CreatePlatformSocket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
677   if (s != net::kInvalidSocket) {
678     // Allow rapid reuse.
679     static const int kOn = 1;
680     setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &kOn, sizeof(kOn));
681 
682     sockaddr_in addr;
683     memset(&addr, 0, sizeof(addr));
684     addr.sin_family = AF_INET;
685     addr.sin_addr.s_addr = inet_addr("127.0.0.1");
686     addr.sin_port = base::HostToNet16(port);
687     if (bind(s, reinterpret_cast<sockaddr*>(&addr), sizeof(addr))) {
688       // Try allocate any available port.
689       addr.sin_port = base::HostToNet16(0);
690       if (bind(s, reinterpret_cast<sockaddr*>(&addr), sizeof(addr))) {
691         close(s);
692         LOG(ERROR) << "Could not bind socket to port" << port;
693         s = net::kInvalidSocket;
694       } else {
695         sockaddr_in sock_addr;
696         socklen_t sock_addr_size = sizeof(sock_addr);
697         if (getsockname(s, reinterpret_cast<struct sockaddr*>(&sock_addr),
698                         &sock_addr_size) != 0 ||
699             sock_addr_size != sizeof(sock_addr)) {
700           LOG(ERROR) << "Could not determine bound port, getsockname() failed";
701           close(s);
702           s = net::kInvalidSocket;
703         } else {
704           port = base::NetToHost16(sock_addr.sin_port);
705         }
706       }
707     }
708   }
709 
710   if (s != net::kInvalidSocket) {
711     SetDebugStubPort(port);
712   }
713   if (s == net::kInvalidSocket) {
714     LOG(ERROR) << "failed to open socket for debug stub";
715     return net::kInvalidSocket;
716   }
717   LOG(WARNING) << "debug stub on port " << port;
718   if (listen(s, 1)) {
719     LOG(ERROR) << "listen() failed on debug stub socket";
720     if (IGNORE_EINTR(close(s)) < 0)
721       PLOG(ERROR) << "failed to close debug stub socket";
722     return net::kInvalidSocket;
723   }
724   return s;
725 }
726 #endif
727 
728 #if defined(OS_WIN)
OnDebugStubPortSelected(uint16_t debug_stub_port)729 void NaClProcessHost::OnDebugStubPortSelected(uint16_t debug_stub_port) {
730   CHECK(!uses_nonsfi_mode_);
731   SetDebugStubPort(debug_stub_port);
732 }
733 #endif
734 
StartNaClExecution()735 bool NaClProcessHost::StartNaClExecution() {
736   NaClBrowser* nacl_browser = NaClBrowser::GetInstance();
737 
738   NaClStartParams params;
739 
740   params.process_type = process_type_;
741   bool enable_nacl_debug = enable_debug_stub_ &&
742       NaClBrowser::GetDelegate()->URLMatchesDebugPatterns(manifest_url_);
743   if (uses_nonsfi_mode_) {
744     // Currently, non-SFI mode is supported only on Linux.
745     if (enable_nacl_debug) {
746       LOG(WARNING) << "nonsfi nacl plugin running in "
747                    << process_->GetData().GetProcess().Pid();
748     }
749   } else {
750     params.validation_cache_enabled = nacl_browser->ValidationCacheIsEnabled();
751     params.validation_cache_key = nacl_browser->GetValidationCacheKey();
752     params.version = NaClBrowser::GetDelegate()->GetVersionString();
753     params.enable_debug_stub = enable_nacl_debug;
754 
755     const base::File& irt_file = nacl_browser->IrtFile();
756     CHECK(irt_file.IsValid());
757     // Send over the IRT file handle.  We don't close our own copy!
758     params.irt_handle = IPC::GetPlatformFileForTransit(
759         irt_file.GetPlatformFile(), false);
760     if (params.irt_handle == IPC::InvalidPlatformFileForTransit()) {
761       return false;
762     }
763 
764 #if defined(OS_POSIX)
765     if (params.enable_debug_stub) {
766       net::SocketDescriptor server_bound_socket = GetDebugStubSocketHandle();
767       if (server_bound_socket != net::kInvalidSocket) {
768         params.debug_stub_server_bound_socket = IPC::GetPlatformFileForTransit(
769             server_bound_socket, true);
770       }
771     }
772 #endif
773   }
774 
775   // Create a shared memory region that the renderer and the plugin share to
776   // report crash information.
777   params.crash_info_shmem_region =
778       base::WritableSharedMemoryRegion::Create(kNaClCrashInfoShmemSize);
779   if (!params.crash_info_shmem_region.IsValid()) {
780     DLOG(ERROR) << "Failed to create a shared memory buffer";
781     return false;
782   }
783 
784   // Pass the pre-opened resource files to the loader. We do not have to reopen
785   // resource files here even for SFI mode because the descriptors are not from
786   // a renderer.
787   for (size_t i = 0; i < prefetched_resource_files_.size(); ++i) {
788     process_->Send(new NaClProcessMsg_AddPrefetchedResource(
789         NaClResourcePrefetchResult(
790             prefetched_resource_files_[i].file,
791             // For the same reason as the comment below, always use an empty
792             // base::FilePath for non-SFI mode.
793             (uses_nonsfi_mode_ ? base::FilePath() :
794              prefetched_resource_files_[i].file_path_metadata),
795             prefetched_resource_files_[i].file_key)));
796   }
797   prefetched_resource_files_.clear();
798 
799   base::FilePath file_path;
800   if (uses_nonsfi_mode_) {
801     // Don't retrieve the file path when using nonsfi mode; there's no
802     // validation caching in that case, so it's unnecessary work, and would
803     // expose the file path to the plugin.
804   } else {
805     if (NaClBrowser::GetInstance()->GetFilePath(nexe_token_.lo,
806                                                 nexe_token_.hi,
807                                                 &file_path)) {
808       // We have to reopen the file in the browser process; we don't want a
809       // compromised renderer to pass an arbitrary fd that could get loaded
810       // into the plugin process.
811       base::ThreadPool::PostTaskAndReplyWithResult(
812           FROM_HERE,
813           // USER_BLOCKING because it is on the critical path of displaying the
814           // official virtual keyboard on Chrome OS. https://crbug.com/976542
815           {base::MayBlock(), base::TaskPriority::USER_BLOCKING},
816           base::BindOnce(OpenNaClReadExecImpl, file_path,
817                          true /* is_executable */),
818           base::BindOnce(&NaClProcessHost::StartNaClFileResolved,
819                          weak_factory_.GetWeakPtr(), std::move(params),
820                          file_path));
821       return true;
822     }
823   }
824 
825   StartNaClFileResolved(std::move(params), base::FilePath(), base::File());
826   return true;
827 }
828 
StartNaClFileResolved(NaClStartParams params,const base::FilePath & file_path,base::File checked_nexe_file)829 void NaClProcessHost::StartNaClFileResolved(
830     NaClStartParams params,
831     const base::FilePath& file_path,
832     base::File checked_nexe_file) {
833   if (checked_nexe_file.IsValid()) {
834     // Release the file received from the renderer. This has to be done on a
835     // thread where IO is permitted, though.
836     base::ThreadPool::PostTask(
837         FROM_HERE, {base::TaskPriority::BEST_EFFORT, base::MayBlock()},
838         base::BindOnce(&CloseFile, std::move(nexe_file_)));
839     params.nexe_file_path_metadata = file_path;
840     params.nexe_file =
841         IPC::TakePlatformFileForTransit(std::move(checked_nexe_file));
842   } else {
843     params.nexe_file = IPC::TakePlatformFileForTransit(std::move(nexe_file_));
844   }
845 
846 #if defined(OS_LINUX) || defined(OS_CHROMEOS)
847   // In Non-SFI mode, create socket pairs for IPC channels here, unlike in
848   // SFI-mode, in which those channels are created in nacl_listener.cc.
849   // This is for security hardening. We can then prohibit the socketpair()
850   // system call in nacl_helper and nacl_helper_nonsfi.
851   if (uses_nonsfi_mode_) {
852     mojo::MessagePipe ppapi_browser_channel;
853     mojo::MessagePipe ppapi_renderer_channel;
854     mojo::MessagePipe trusted_service_channel;
855     mojo::MessagePipe manifest_service_channel;
856 
857     if (!StartPPAPIProxy(std::move(ppapi_browser_channel.handle1))) {
858       SendErrorToRenderer("Failed to start browser PPAPI proxy.");
859       return;
860     }
861 
862     // On success, send back a success message to the renderer process,
863     // and transfer the channel handles for the NaCl loader process to
864     // |params|. Also send an invalid shared memory region as nonsfi_mode
865     // does not use the region.
866     ReplyToRenderer(std::move(ppapi_renderer_channel.handle1),
867                     std::move(trusted_service_channel.handle1),
868                     std::move(manifest_service_channel.handle1),
869                     base::ReadOnlySharedMemoryRegion());
870     params.ppapi_browser_channel_handle =
871         ppapi_browser_channel.handle0.release();
872     params.ppapi_renderer_channel_handle =
873         ppapi_renderer_channel.handle0.release();
874     params.trusted_service_channel_handle =
875         trusted_service_channel.handle0.release();
876     params.manifest_service_channel_handle =
877         manifest_service_channel.handle0.release();
878   }
879 #endif
880 
881   process_->Send(new NaClProcessMsg_Start(std::move(params)));
882 }
883 
StartPPAPIProxy(mojo::ScopedMessagePipeHandle channel_handle)884 bool NaClProcessHost::StartPPAPIProxy(
885     mojo::ScopedMessagePipeHandle channel_handle) {
886   if (ipc_proxy_channel_.get()) {
887     // Attempt to open more than 1 browser channel is not supported.
888     // Shut down the NaCl process.
889     process_->GetHost()->ForceShutdown();
890     return false;
891   }
892 
893   DCHECK_EQ(PROCESS_TYPE_NACL_LOADER, process_->GetData().process_type);
894 
895   ipc_proxy_channel_ = IPC::ChannelProxy::Create(
896       channel_handle.release(), IPC::Channel::MODE_CLIENT, nullptr,
897       base::ThreadTaskRunnerHandle::Get().get(),
898       base::ThreadTaskRunnerHandle::Get().get());
899   // Create the browser ppapi host and enable PPAPI message dispatching to the
900   // browser process.
901   ppapi_host_.reset(content::BrowserPpapiHost::CreateExternalPluginProcess(
902       ipc_proxy_channel_.get(),  // sender
903       permissions_, process_->GetData().GetProcess().Handle(),
904       ipc_proxy_channel_.get(), nacl_host_message_filter_->render_process_id(),
905       render_view_id_, profile_directory_));
906 
907   ppapi::PpapiNaClPluginArgs args;
908   args.off_the_record = nacl_host_message_filter_->off_the_record();
909   args.permissions = permissions_;
910   base::CommandLine* cmdline = base::CommandLine::ForCurrentProcess();
911   DCHECK(cmdline);
912   std::string flag_whitelist[] = {
913     switches::kV,
914     switches::kVModule,
915   };
916   for (size_t i = 0; i < base::size(flag_whitelist); ++i) {
917     std::string value = cmdline->GetSwitchValueASCII(flag_whitelist[i]);
918     if (!value.empty()) {
919       args.switch_names.push_back(flag_whitelist[i]);
920       args.switch_values.push_back(value);
921     }
922   }
923 
924   std::string enabled_features;
925   std::string disabled_features;
926   base::FeatureList::GetInstance()->GetFeatureOverrides(&enabled_features,
927                                                         &disabled_features);
928   if (!enabled_features.empty()) {
929     args.switch_names.push_back(switches::kEnableFeatures);
930     args.switch_values.push_back(enabled_features);
931   }
932   if (!disabled_features.empty()) {
933     args.switch_names.push_back(switches::kDisableFeatures);
934     args.switch_values.push_back(disabled_features);
935   }
936 
937   ppapi_host_->GetPpapiHost()->AddHostFactoryFilter(
938       std::unique_ptr<ppapi::host::HostFactory>(
939           NaClBrowser::GetDelegate()->CreatePpapiHostFactory(
940               ppapi_host_.get())));
941 
942   // Send a message to initialize the IPC dispatchers in the NaCl plugin.
943   ipc_proxy_channel_->Send(new PpapiMsg_InitializeNaClDispatcher(args));
944   return true;
945 }
946 
947 // This method is called when NaClProcessHostMsg_PpapiChannelCreated is
948 // received.
OnPpapiChannelsCreated(const IPC::ChannelHandle & raw_ppapi_browser_channel_handle,const IPC::ChannelHandle & raw_ppapi_renderer_channel_handle,const IPC::ChannelHandle & raw_trusted_renderer_channel_handle,const IPC::ChannelHandle & raw_manifest_service_channel_handle,base::ReadOnlySharedMemoryRegion crash_info_shmem_region)949 void NaClProcessHost::OnPpapiChannelsCreated(
950     const IPC::ChannelHandle& raw_ppapi_browser_channel_handle,
951     const IPC::ChannelHandle& raw_ppapi_renderer_channel_handle,
952     const IPC::ChannelHandle& raw_trusted_renderer_channel_handle,
953     const IPC::ChannelHandle& raw_manifest_service_channel_handle,
954     base::ReadOnlySharedMemoryRegion crash_info_shmem_region) {
955   DCHECK(raw_ppapi_browser_channel_handle.is_mojo_channel_handle());
956   DCHECK(raw_ppapi_renderer_channel_handle.is_mojo_channel_handle());
957   DCHECK(raw_trusted_renderer_channel_handle.is_mojo_channel_handle());
958   DCHECK(raw_manifest_service_channel_handle.is_mojo_channel_handle());
959 
960   mojo::ScopedMessagePipeHandle ppapi_browser_channel_handle(
961       raw_ppapi_browser_channel_handle.mojo_handle);
962   mojo::ScopedMessagePipeHandle ppapi_renderer_channel_handle(
963       raw_ppapi_renderer_channel_handle.mojo_handle);
964   mojo::ScopedMessagePipeHandle trusted_renderer_channel_handle(
965       raw_trusted_renderer_channel_handle.mojo_handle);
966   mojo::ScopedMessagePipeHandle manifest_service_channel_handle(
967       raw_manifest_service_channel_handle.mojo_handle);
968 
969   if (!StartPPAPIProxy(std::move(ppapi_browser_channel_handle))) {
970     SendErrorToRenderer("Browser PPAPI proxy could not start.");
971     return;
972   }
973 
974   // Let the renderer know that the IPC channels are established.
975   ReplyToRenderer(std::move(ppapi_renderer_channel_handle),
976                   std::move(trusted_renderer_channel_handle),
977                   std::move(manifest_service_channel_handle),
978                   std::move(crash_info_shmem_region));
979 }
980 
StartWithLaunchedProcess()981 bool NaClProcessHost::StartWithLaunchedProcess() {
982   NaClBrowser* nacl_browser = NaClBrowser::GetInstance();
983 
984   if (nacl_browser->IsReady())
985     return StartNaClExecution();
986   if (nacl_browser->IsOk()) {
987     nacl_browser->WaitForResources(base::BindOnce(
988         &NaClProcessHost::OnResourcesReady, weak_factory_.GetWeakPtr()));
989     return true;
990   }
991   SendErrorToRenderer("previously failed to acquire shared resources");
992   return false;
993 }
994 
OnQueryKnownToValidate(const std::string & signature,bool * result)995 void NaClProcessHost::OnQueryKnownToValidate(const std::string& signature,
996                                              bool* result) {
997   CHECK(!uses_nonsfi_mode_);
998   NaClBrowser* nacl_browser = NaClBrowser::GetInstance();
999   *result = nacl_browser->QueryKnownToValidate(signature, off_the_record_);
1000 }
1001 
OnSetKnownToValidate(const std::string & signature)1002 void NaClProcessHost::OnSetKnownToValidate(const std::string& signature) {
1003   CHECK(!uses_nonsfi_mode_);
1004   NaClBrowser::GetInstance()->SetKnownToValidate(
1005       signature, off_the_record_);
1006 }
1007 
OnResolveFileToken(uint64_t file_token_lo,uint64_t file_token_hi)1008 void NaClProcessHost::OnResolveFileToken(uint64_t file_token_lo,
1009                                          uint64_t file_token_hi) {
1010   // Was the file registered?
1011   //
1012   // Note that the file path cache is of bounded size, and old entries can get
1013   // evicted.  If a large number of NaCl modules are being launched at once,
1014   // resolving the file_token may fail because the path cache was thrashed
1015   // while the file_token was in flight.  In this case the query fails, and we
1016   // need to fall back to the slower path.
1017   //
1018   // However: each NaCl process will consume 2-3 entries as it starts up, this
1019   // means that eviction will not happen unless you start up 33+ NaCl processes
1020   // at the same time, and this still requires worst-case timing.  As a
1021   // practical matter, no entries should be evicted prematurely.
1022   // The cache itself should take ~ (150 characters * 2 bytes/char + ~60 bytes
1023   // data structure overhead) * 100 = 35k when full, so making it bigger should
1024   // not be a problem, if needed.
1025   //
1026   // Each NaCl process will consume 2-3 entries because the manifest and main
1027   // nexe are currently not resolved.  Shared libraries will be resolved.  They
1028   // will be loaded sequentially, so they will only consume a single entry
1029   // while the load is in flight.
1030   //
1031   // TODO(ncbray): track behavior with UMA. If entries are getting evicted or
1032   // bogus keys are getting queried, this would be good to know.
1033   CHECK(!uses_nonsfi_mode_);
1034   base::FilePath file_path;
1035   if (!NaClBrowser::GetInstance()->GetFilePath(
1036         file_token_lo, file_token_hi, &file_path)) {
1037     Send(new NaClProcessMsg_ResolveFileTokenReply(
1038              file_token_lo,
1039              file_token_hi,
1040              IPC::PlatformFileForTransit(),
1041              base::FilePath()));
1042     return;
1043   }
1044 
1045   // Open the file.
1046   base::ThreadPool::PostTaskAndReplyWithResult(
1047       FROM_HERE,
1048       // USER_BLOCKING because it is on the critical path of displaying the
1049       // official virtual keyboard on Chrome OS. https://crbug.com/976542
1050       {base::MayBlock(), base::TaskPriority::USER_BLOCKING},
1051       base::BindOnce(OpenNaClReadExecImpl, file_path, true /* is_executable */),
1052       base::BindOnce(&NaClProcessHost::FileResolved, weak_factory_.GetWeakPtr(),
1053                      file_token_lo, file_token_hi, file_path));
1054 }
1055 
FileResolved(uint64_t file_token_lo,uint64_t file_token_hi,const base::FilePath & file_path,base::File file)1056 void NaClProcessHost::FileResolved(
1057     uint64_t file_token_lo,
1058     uint64_t file_token_hi,
1059     const base::FilePath& file_path,
1060     base::File file) {
1061   base::FilePath out_file_path;
1062   IPC::PlatformFileForTransit out_handle;
1063   if (file.IsValid()) {
1064     out_file_path = file_path;
1065     out_handle = IPC::TakePlatformFileForTransit(std::move(file));
1066   } else {
1067     out_handle = IPC::InvalidPlatformFileForTransit();
1068   }
1069   Send(new NaClProcessMsg_ResolveFileTokenReply(
1070            file_token_lo,
1071            file_token_hi,
1072            out_handle,
1073            out_file_path));
1074 }
1075 
1076 #if defined(OS_WIN)
OnAttachDebugExceptionHandler(const std::string & info,IPC::Message * reply_msg)1077 void NaClProcessHost::OnAttachDebugExceptionHandler(const std::string& info,
1078                                                     IPC::Message* reply_msg) {
1079   CHECK(!uses_nonsfi_mode_);
1080   if (!AttachDebugExceptionHandler(info, reply_msg)) {
1081     // Send failure message.
1082     NaClProcessMsg_AttachDebugExceptionHandler::WriteReplyParams(reply_msg,
1083                                                                  false);
1084     Send(reply_msg);
1085   }
1086 }
1087 
AttachDebugExceptionHandler(const std::string & info,IPC::Message * reply_msg)1088 bool NaClProcessHost::AttachDebugExceptionHandler(const std::string& info,
1089                                                   IPC::Message* reply_msg) {
1090   bool enable_exception_handling = process_type_ == kNativeNaClProcessType;
1091   if (!enable_exception_handling && !enable_debug_stub_) {
1092     DLOG(ERROR) <<
1093         "Debug exception handler requested by NaCl process when not enabled";
1094     return false;
1095   }
1096   if (debug_exception_handler_requested_) {
1097     // The NaCl process should not request this multiple times.
1098     DLOG(ERROR) << "Multiple AttachDebugExceptionHandler requests received";
1099     return false;
1100   }
1101   debug_exception_handler_requested_ = true;
1102 
1103   base::ProcessId nacl_pid = process_->GetData().GetProcess().Pid();
1104   // We cannot use process_->GetData().handle because it does not have
1105   // the necessary access rights.  We open the new handle here rather
1106   // than in the NaCl broker process in case the NaCl loader process
1107   // dies before the NaCl broker process receives the message we send.
1108   // The debug exception handler uses DebugActiveProcess() to attach,
1109   // but this takes a PID.  We need to prevent the NaCl loader's PID
1110   // from being reused before DebugActiveProcess() is called, and
1111   // holding a process handle open achieves this.
1112   base::Process process =
1113       base::Process::OpenWithAccess(nacl_pid,
1114                                     PROCESS_QUERY_INFORMATION |
1115                                     PROCESS_SUSPEND_RESUME |
1116                                     PROCESS_TERMINATE |
1117                                     PROCESS_VM_OPERATION |
1118                                     PROCESS_VM_READ |
1119                                     PROCESS_VM_WRITE |
1120                                     PROCESS_DUP_HANDLE |
1121                                     SYNCHRONIZE);
1122   if (!process.IsValid()) {
1123     LOG(ERROR) << "Failed to get process handle";
1124     return false;
1125   }
1126 
1127   attach_debug_exception_handler_reply_msg_.reset(reply_msg);
1128   // If the NaCl loader is 64-bit, the process running its debug
1129   // exception handler must be 64-bit too, so we use the 64-bit NaCl
1130   // broker process for this.  Otherwise, on a 32-bit system, we use
1131   // the 32-bit browser process to run the debug exception handler.
1132   if (RunningOnWOW64()) {
1133     return NaClBrokerService::GetInstance()->LaunchDebugExceptionHandler(
1134                weak_factory_.GetWeakPtr(), nacl_pid, process.Handle(),
1135                info);
1136   }
1137   NaClStartDebugExceptionHandlerThread(
1138       std::move(process), info, base::ThreadTaskRunnerHandle::Get(),
1139       base::BindRepeating(
1140           &NaClProcessHost::OnDebugExceptionHandlerLaunchedByBroker,
1141           weak_factory_.GetWeakPtr()));
1142   return true;
1143 }
1144 #endif
1145 
1146 }  // namespace nacl
1147