Fix platform conditionalization of NaCl IRT file name
[chromium-blink-merge.git] / chrome / browser / nacl_host / nacl_process_host.cc
blobba2fa93178102683f26eee6a3db1bf02a84619b0
1 // Copyright (c) 2011 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.
5 #include "build/build_config.h"
7 #include "chrome/browser/nacl_host/nacl_process_host.h"
9 #if defined(OS_POSIX)
10 #include <fcntl.h>
11 #endif
13 #include "base/bind.h"
14 #include "base/command_line.h"
15 #include "base/memory/singleton.h"
16 #include "base/path_service.h"
17 #include "base/stringprintf.h"
18 #include "base/utf_string_conversions.h"
19 #include "base/win/windows_version.h"
20 #include "chrome/common/chrome_paths.h"
21 #include "chrome/common/chrome_switches.h"
22 #include "chrome/common/logging_chrome.h"
23 #include "chrome/common/nacl_cmd_line.h"
24 #include "chrome/common/nacl_messages.h"
25 #include "chrome/common/render_messages.h"
26 #include "chrome/browser/renderer_host/chrome_render_message_filter.h"
27 #include "content/public/common/child_process_host.h"
28 #include "ipc/ipc_switches.h"
29 #include "native_client/src/shared/imc/nacl_imc.h"
31 #if defined(OS_POSIX)
32 #include "ipc/ipc_channel_posix.h"
33 #elif defined(OS_WIN)
34 #include "chrome/browser/nacl_host/nacl_broker_service_win.h"
35 #endif
37 using content::BrowserThread;
38 using content::ChildProcessHost;
40 namespace {
42 void SetCloseOnExec(nacl::Handle fd) {
43 #if defined(OS_POSIX)
44 int flags = fcntl(fd, F_GETFD);
45 CHECK_NE(flags, -1);
46 int rc = fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
47 CHECK_EQ(rc, 0);
48 #endif
51 // Represents shared state for all NaClProcessHost objects in the browser.
52 // Currently this just handles holding onto the file descriptor for the IRT.
53 class NaClBrowser {
54 public:
55 static NaClBrowser* GetInstance() {
56 return Singleton<NaClBrowser>::get();
59 bool IrtAvailable() const {
60 return irt_platform_file_ != base::kInvalidPlatformFileValue;
63 base::PlatformFile IrtFile() const {
64 CHECK_NE(irt_platform_file_, base::kInvalidPlatformFileValue);
65 return irt_platform_file_;
68 // Asynchronously attempt to get the IRT open.
69 bool EnsureIrtAvailable();
71 // Make sure the IRT gets opened and follow up with the reply when it's ready.
72 bool MakeIrtAvailable(const base::Closure& reply);
74 private:
75 base::PlatformFile irt_platform_file_;
77 friend struct DefaultSingletonTraits<NaClBrowser>;
79 NaClBrowser()
80 : irt_platform_file_(base::kInvalidPlatformFileValue)
83 ~NaClBrowser() {
84 if (irt_platform_file_ != base::kInvalidPlatformFileValue)
85 base::ClosePlatformFile(irt_platform_file_);
88 void OpenIrtLibraryFile();
90 static void DoOpenIrtLibraryFile() {
91 GetInstance()->OpenIrtLibraryFile();
94 DISALLOW_COPY_AND_ASSIGN(NaClBrowser);
97 } // namespace
99 struct NaClProcessHost::NaClInternal {
100 std::vector<nacl::Handle> sockets_for_renderer;
101 std::vector<nacl::Handle> sockets_for_sel_ldr;
104 static bool RunningOnWOW64() {
105 #if defined(OS_WIN)
106 return (base::win::OSInfo::GetInstance()->wow64_status() ==
107 base::win::OSInfo::WOW64_ENABLED);
108 #else
109 return false;
110 #endif
113 NaClProcessHost::NaClProcessHost(const std::wstring& url)
114 : BrowserChildProcessHost(content::PROCESS_TYPE_NACL_LOADER),
115 reply_msg_(NULL),
116 internal_(new NaClInternal()),
117 ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)) {
118 set_name(WideToUTF16Hack(url));
121 NaClProcessHost::~NaClProcessHost() {
122 int exit_code;
123 GetChildTerminationStatus(&exit_code);
124 std::string message =
125 base::StringPrintf("NaCl process exited with status %i (0x%x)",
126 exit_code, exit_code);
127 if (exit_code == 0) {
128 LOG(INFO) << message;
129 } else {
130 LOG(ERROR) << message;
133 #if defined(OS_WIN)
134 NaClBrokerService::GetInstance()->OnLoaderDied();
135 #endif
137 for (size_t i = 0; i < internal_->sockets_for_renderer.size(); i++) {
138 if (nacl::Close(internal_->sockets_for_renderer[i]) != 0) {
139 LOG(ERROR) << "nacl::Close() failed";
142 for (size_t i = 0; i < internal_->sockets_for_sel_ldr.size(); i++) {
143 if (nacl::Close(internal_->sockets_for_sel_ldr[i]) != 0) {
144 LOG(ERROR) << "nacl::Close() failed";
148 if (reply_msg_) {
149 // The process failed to launch for some reason.
150 // Don't keep the renderer hanging.
151 reply_msg_->set_reply_error();
152 chrome_render_message_filter_->Send(reply_msg_);
155 #if defined(OS_WIN)
156 NaClBrokerService::GetInstance()->OnLoaderDied();
157 #endif
160 // Attempt to ensure the IRT will be available when we need it, but don't wait.
161 bool NaClBrowser::EnsureIrtAvailable() {
162 if (IrtAvailable())
163 return true;
165 return BrowserThread::PostTask(
166 BrowserThread::FILE, FROM_HERE,
167 base::Bind(&NaClBrowser::DoOpenIrtLibraryFile));
170 // We really need the IRT to be available now, so make sure that it is.
171 // When it's ready, we'll run the reply closure.
172 bool NaClBrowser::MakeIrtAvailable(const base::Closure& reply) {
173 return BrowserThread::PostTaskAndReply(
174 BrowserThread::FILE, FROM_HERE,
175 base::Bind(&NaClBrowser::DoOpenIrtLibraryFile), reply);
178 // This is called at browser startup.
179 // static
180 void NaClProcessHost::EarlyStartup() {
181 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
182 // Open the IRT file early to make sure that it isn't replaced out from
183 // under us by autoupdate.
184 NaClBrowser::GetInstance()->EnsureIrtAvailable();
185 #endif
188 bool NaClProcessHost::Launch(
189 ChromeRenderMessageFilter* chrome_render_message_filter,
190 int socket_count,
191 IPC::Message* reply_msg) {
192 // Place an arbitrary limit on the number of sockets to limit
193 // exposure in case the renderer is compromised. We can increase
194 // this if necessary.
195 if (socket_count > 8) {
196 return false;
199 // Start getting the IRT open asynchronously while we launch the NaCl process.
200 // We'll make sure this actually finished in OnProcessLaunched, below.
201 if (!NaClBrowser::GetInstance()->EnsureIrtAvailable()) {
202 LOG(ERROR) << "Cannot launch NaCl process after IRT file open failed";
203 return false;
206 // Rather than creating a socket pair in the renderer, and passing
207 // one side through the browser to sel_ldr, socket pairs are created
208 // in the browser and then passed to the renderer and sel_ldr.
210 // This is mainly for the benefit of Windows, where sockets cannot
211 // be passed in messages, but are copied via DuplicateHandle().
212 // This means the sandboxed renderer cannot send handles to the
213 // browser process.
215 for (int i = 0; i < socket_count; i++) {
216 nacl::Handle pair[2];
217 // Create a connected socket
218 if (nacl::SocketPair(pair) == -1)
219 return false;
220 internal_->sockets_for_renderer.push_back(pair[0]);
221 internal_->sockets_for_sel_ldr.push_back(pair[1]);
222 SetCloseOnExec(pair[0]);
223 SetCloseOnExec(pair[1]);
226 // Launch the process
227 if (!LaunchSelLdr()) {
228 return false;
230 chrome_render_message_filter_ = chrome_render_message_filter;
231 reply_msg_ = reply_msg;
233 return true;
236 bool NaClProcessHost::LaunchSelLdr() {
237 std::string channel_id = child_process_host()->CreateChannel();
238 if (channel_id.empty())
239 return false;
241 CommandLine::StringType nacl_loader_prefix;
242 #if defined(OS_POSIX)
243 nacl_loader_prefix = CommandLine::ForCurrentProcess()->GetSwitchValueNative(
244 switches::kNaClLoaderCmdPrefix);
245 #endif // defined(OS_POSIX)
247 // Build command line for nacl.
249 #if defined(OS_MACOSX)
250 // The Native Client process needs to be able to allocate a 1GB contiguous
251 // region to use as the client environment's virtual address space. ASLR
252 // (PIE) interferes with this by making it possible that no gap large enough
253 // to accomodate this request will exist in the child process' address
254 // space. Disable PIE for NaCl processes. See http://crbug.com/90221 and
255 // http://code.google.com/p/nativeclient/issues/detail?id=2043.
256 int flags = ChildProcessHost::CHILD_NO_PIE;
257 #elif defined(OS_LINUX)
258 int flags = nacl_loader_prefix.empty() ? ChildProcessHost::CHILD_ALLOW_SELF :
259 ChildProcessHost::CHILD_NORMAL;
260 #else
261 int flags = ChildProcessHost::CHILD_NORMAL;
262 #endif
264 FilePath exe_path = ChildProcessHost::GetChildPath(flags);
265 if (exe_path.empty())
266 return false;
268 CommandLine* cmd_line = new CommandLine(exe_path);
269 nacl::CopyNaClCommandLineArguments(cmd_line);
271 cmd_line->AppendSwitchASCII(switches::kProcessType,
272 switches::kNaClLoaderProcess);
273 cmd_line->AppendSwitchASCII(switches::kProcessChannelID, channel_id);
274 if (logging::DialogsAreSuppressed())
275 cmd_line->AppendSwitch(switches::kNoErrorDialogs);
277 if (!nacl_loader_prefix.empty())
278 cmd_line->PrependWrapper(nacl_loader_prefix);
280 // On Windows we might need to start the broker process to launch a new loader
281 #if defined(OS_WIN)
282 if (RunningOnWOW64()) {
283 return NaClBrokerService::GetInstance()->LaunchLoader(
284 this, ASCIIToWide(channel_id));
285 } else {
286 BrowserChildProcessHost::Launch(FilePath(), cmd_line);
288 #elif defined(OS_POSIX)
289 BrowserChildProcessHost::Launch(nacl_loader_prefix.empty(), // use_zygote
290 base::environment_vector(),
291 cmd_line);
292 #endif
294 return true;
297 void NaClProcessHost::OnProcessLaunchedByBroker(base::ProcessHandle handle) {
298 set_handle(handle);
299 OnProcessLaunched();
302 void NaClProcessHost::OnProcessCrashed(int exit_code) {
303 std::string message = base::StringPrintf(
304 "NaCl process exited with status %i (0x%x)", exit_code, exit_code);
305 LOG(ERROR) << message;
308 namespace {
310 // Determine the name of the IRT file based on the architecture.
312 #define NACL_IRT_FILE_NAME(arch_string) \
313 (FILE_PATH_LITERAL("nacl_irt_") \
314 FILE_PATH_LITERAL(arch_string) \
315 FILE_PATH_LITERAL(".nexe"))
317 const FilePath::StringType NaClIrtName() {
318 #if defined(ARCH_CPU_X86_FAMILY)
319 bool is64 = RunningOnWOW64();
320 #if defined(ARCH_CPU_X86_64)
321 is64 = true;
322 #endif
323 return is64 ? NACL_IRT_FILE_NAME("x86_64") : NACL_IRT_FILE_NAME("x86_32");
324 #elif defined(ARCH_CPU_ARMEL)
325 // TODO(mcgrathr): Eventually we'll need to distinguish arm32 vs thumb2.
326 // That may need to be based on the actual nexe rather than a static
327 // choice, which would require substantial refactoring.
328 return NACL_IRT_FILE_NAME("arm");
329 #else
330 #error Add support for your architecture to NaCl IRT file selection
331 #endif
334 } // namespace
336 // This only ever runs on the BrowserThread::FILE thread.
337 // If multiple tasks are posted, the later ones are no-ops.
338 void NaClBrowser::OpenIrtLibraryFile() {
339 if (irt_platform_file_ != base::kInvalidPlatformFileValue)
340 // We've already run.
341 return;
343 FilePath irt_filepath;
345 // Allow the IRT library to be overridden via an environment
346 // variable. This allows the NaCl/Chromium integration bot to
347 // specify a newly-built IRT rather than using a prebuilt one
348 // downloaded via Chromium's DEPS file. We use the same environment
349 // variable that the standalone NaCl PPAPI plugin accepts.
350 const char* irt_path_var = getenv("NACL_IRT_LIBRARY");
351 if (irt_path_var != NULL) {
352 FilePath::StringType path_string(
353 irt_path_var, const_cast<const char*>(strchr(irt_path_var, '\0')));
354 irt_filepath = FilePath(path_string);
355 } else {
356 FilePath plugin_dir;
357 if (!PathService::Get(chrome::DIR_INTERNAL_PLUGINS, &plugin_dir)) {
358 LOG(ERROR) << "Failed to locate the plugins directory";
359 return;
362 irt_filepath = plugin_dir.Append(NaClIrtName());
365 base::PlatformFileError error_code;
366 irt_platform_file_ = base::CreatePlatformFile(irt_filepath,
367 base::PLATFORM_FILE_OPEN |
368 base::PLATFORM_FILE_READ,
369 NULL,
370 &error_code);
371 if (error_code != base::PLATFORM_FILE_OK) {
372 LOG(ERROR) << "Failed to open NaCl IRT file \""
373 << irt_filepath.LossyDisplayName()
374 << "\": " << error_code;
378 void NaClProcessHost::OnProcessLaunched() {
379 NaClBrowser* nacl_browser = NaClBrowser::GetInstance();
381 if (nacl_browser->IrtAvailable()) {
382 // The IRT is already open. Away we go.
383 SendStart(nacl_browser->IrtFile());
384 } else {
385 // We're waiting for the IRT to be open.
386 nacl_browser->MakeIrtAvailable(base::Bind(&NaClProcessHost::IrtReady,
387 weak_factory_.GetWeakPtr()));
391 // The asynchronous attempt to get the IRT file open has completed.
392 void NaClProcessHost::IrtReady() {
393 NaClBrowser* nacl_browser = NaClBrowser::GetInstance();
395 if (nacl_browser->IrtAvailable()) {
396 SendStart(nacl_browser->IrtFile());
397 } else {
398 LOG(ERROR) << "Cannot launch NaCl process after IRT file open failed";
399 delete this;
403 static bool SendHandleToSelLdr(
404 base::ProcessHandle processh,
405 nacl::Handle sourceh, bool close_source,
406 std::vector<nacl::FileDescriptor> *handles_for_sel_ldr) {
407 #if defined(OS_WIN)
408 HANDLE channel;
409 int flags = DUPLICATE_SAME_ACCESS;
410 if (close_source)
411 flags |= DUPLICATE_CLOSE_SOURCE;
412 if (!DuplicateHandle(GetCurrentProcess(),
413 reinterpret_cast<HANDLE>(sourceh),
414 processh,
415 &channel,
416 0, // Unused given DUPLICATE_SAME_ACCESS.
417 FALSE,
418 flags)) {
419 LOG(ERROR) << "DuplicateHandle() failed";
420 return false;
422 handles_for_sel_ldr->push_back(
423 reinterpret_cast<nacl::FileDescriptor>(channel));
424 #else
425 nacl::FileDescriptor channel;
426 channel.fd = sourceh;
427 channel.auto_close = close_source;
428 handles_for_sel_ldr->push_back(channel);
429 #endif
430 return true;
433 void NaClProcessHost::SendStart(base::PlatformFile irt_file) {
434 CHECK_NE(irt_file, base::kInvalidPlatformFileValue);
436 std::vector<nacl::FileDescriptor> handles_for_renderer;
437 base::ProcessHandle nacl_process_handle;
439 for (size_t i = 0; i < internal_->sockets_for_renderer.size(); i++) {
440 #if defined(OS_WIN)
441 // Copy the handle into the renderer process.
442 HANDLE handle_in_renderer;
443 if (!DuplicateHandle(base::GetCurrentProcessHandle(),
444 reinterpret_cast<HANDLE>(
445 internal_->sockets_for_renderer[i]),
446 chrome_render_message_filter_->peer_handle(),
447 &handle_in_renderer,
448 0, // Unused given DUPLICATE_SAME_ACCESS.
449 FALSE,
450 DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS)) {
451 LOG(ERROR) << "DuplicateHandle() failed";
452 delete this;
453 return;
455 handles_for_renderer.push_back(
456 reinterpret_cast<nacl::FileDescriptor>(handle_in_renderer));
457 #else
458 // No need to dup the imc_handle - we don't pass it anywhere else so
459 // it cannot be closed.
460 nacl::FileDescriptor imc_handle;
461 imc_handle.fd = internal_->sockets_for_renderer[i];
462 imc_handle.auto_close = true;
463 handles_for_renderer.push_back(imc_handle);
464 #endif
467 #if defined(OS_WIN)
468 // Copy the process handle into the renderer process.
469 if (!DuplicateHandle(base::GetCurrentProcessHandle(),
470 handle(),
471 chrome_render_message_filter_->peer_handle(),
472 &nacl_process_handle,
473 PROCESS_DUP_HANDLE,
474 FALSE,
475 0)) {
476 LOG(ERROR) << "DuplicateHandle() failed";
477 delete this;
478 return;
480 #else
481 // We use pid as process handle on Posix
482 nacl_process_handle = handle();
483 #endif
485 // Get the pid of the NaCl process
486 base::ProcessId nacl_process_id = base::GetProcId(handle());
488 ChromeViewHostMsg_LaunchNaCl::WriteReplyParams(
489 reply_msg_, handles_for_renderer, nacl_process_handle, nacl_process_id);
490 chrome_render_message_filter_->Send(reply_msg_);
491 chrome_render_message_filter_ = NULL;
492 reply_msg_ = NULL;
493 internal_->sockets_for_renderer.clear();
495 std::vector<nacl::FileDescriptor> handles_for_sel_ldr;
496 for (size_t i = 0; i < internal_->sockets_for_sel_ldr.size(); i++) {
497 if (!SendHandleToSelLdr(handle(),
498 internal_->sockets_for_sel_ldr[i], true,
499 &handles_for_sel_ldr)) {
500 delete this;
501 return;
505 // Send over the IRT file handle. We don't close our own copy!
506 if (!SendHandleToSelLdr(handle(), irt_file, false, &handles_for_sel_ldr)) {
507 delete this;
508 return;
511 #if defined(OS_MACOSX)
512 // For dynamic loading support, NaCl requires a file descriptor that
513 // was created in /tmp, since those created with shm_open() are not
514 // mappable with PROT_EXEC. Rather than requiring an extra IPC
515 // round trip out of the sandbox, we create an FD here.
516 base::SharedMemory memory_buffer;
517 base::SharedMemoryCreateOptions options;
518 options.size = 1;
519 options.executable = true;
520 if (!memory_buffer.Create(options)) {
521 LOG(ERROR) << "Failed to allocate memory buffer";
522 delete this;
523 return;
525 nacl::FileDescriptor memory_fd;
526 memory_fd.fd = dup(memory_buffer.handle().fd);
527 if (memory_fd.fd < 0) {
528 LOG(ERROR) << "Failed to dup() a file descriptor";
529 delete this;
530 return;
532 memory_fd.auto_close = true;
533 handles_for_sel_ldr.push_back(memory_fd);
534 #endif
536 Send(new NaClProcessMsg_Start(handles_for_sel_ldr));
537 internal_->sockets_for_sel_ldr.clear();
540 bool NaClProcessHost::OnMessageReceived(const IPC::Message& msg) {
541 NOTREACHED() << "Invalid message with type = " << msg.type();
542 return false;