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"
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"
32 #include "ipc/ipc_channel_posix.h"
34 #include "chrome/browser/nacl_host/nacl_broker_service_win.h"
37 using content::BrowserThread
;
38 using content::ChildProcessHost
;
42 void SetCloseOnExec(nacl::Handle fd
) {
44 int flags
= fcntl(fd
, F_GETFD
);
46 int rc
= fcntl(fd
, F_SETFD
, flags
| FD_CLOEXEC
);
51 // Represents shared state for all NaClProcessHost objects in the browser.
52 // Currently this just handles holding onto the file descriptor for the IRT.
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
);
75 base::PlatformFile irt_platform_file_
;
77 friend struct DefaultSingletonTraits
<NaClBrowser
>;
80 : irt_platform_file_(base::kInvalidPlatformFileValue
)
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
);
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() {
106 return (base::win::OSInfo::GetInstance()->wow64_status() ==
107 base::win::OSInfo::WOW64_ENABLED
);
113 NaClProcessHost::NaClProcessHost(const std::wstring
& url
)
114 : BrowserChildProcessHost(content::PROCESS_TYPE_NACL_LOADER
),
116 internal_(new NaClInternal()),
117 ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)) {
118 set_name(WideToUTF16Hack(url
));
121 NaClProcessHost::~NaClProcessHost() {
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
;
130 LOG(ERROR
) << message
;
134 NaClBrokerService::GetInstance()->OnLoaderDied();
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";
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_
);
156 NaClBrokerService::GetInstance()->OnLoaderDied();
160 // Attempt to ensure the IRT will be available when we need it, but don't wait.
161 bool NaClBrowser::EnsureIrtAvailable() {
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.
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();
188 bool NaClProcessHost::Launch(
189 ChromeRenderMessageFilter
* chrome_render_message_filter
,
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) {
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";
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
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)
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()) {
230 chrome_render_message_filter_
= chrome_render_message_filter
;
231 reply_msg_
= reply_msg
;
236 bool NaClProcessHost::LaunchSelLdr() {
237 std::string channel_id
= child_process_host()->CreateChannel();
238 if (channel_id
.empty())
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
;
261 int flags
= ChildProcessHost::CHILD_NORMAL
;
264 FilePath exe_path
= ChildProcessHost::GetChildPath(flags
);
265 if (exe_path
.empty())
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
282 if (RunningOnWOW64()) {
283 return NaClBrokerService::GetInstance()->LaunchLoader(
284 this, ASCIIToWide(channel_id
));
286 BrowserChildProcessHost::Launch(FilePath(), cmd_line
);
288 #elif defined(OS_POSIX)
289 BrowserChildProcessHost::Launch(nacl_loader_prefix
.empty(), // use_zygote
290 base::environment_vector(),
297 void NaClProcessHost::OnProcessLaunchedByBroker(base::ProcessHandle handle
) {
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
;
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)
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");
330 #error Add support for your architecture to NaCl IRT file selection
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.
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
);
357 if (!PathService::Get(chrome::DIR_INTERNAL_PLUGINS
, &plugin_dir
)) {
358 LOG(ERROR
) << "Failed to locate the plugins directory";
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
,
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());
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());
398 LOG(ERROR
) << "Cannot launch NaCl process after IRT file open failed";
403 static bool SendHandleToSelLdr(
404 base::ProcessHandle processh
,
405 nacl::Handle sourceh
, bool close_source
,
406 std::vector
<nacl::FileDescriptor
> *handles_for_sel_ldr
) {
409 int flags
= DUPLICATE_SAME_ACCESS
;
411 flags
|= DUPLICATE_CLOSE_SOURCE
;
412 if (!DuplicateHandle(GetCurrentProcess(),
413 reinterpret_cast<HANDLE
>(sourceh
),
416 0, // Unused given DUPLICATE_SAME_ACCESS.
419 LOG(ERROR
) << "DuplicateHandle() failed";
422 handles_for_sel_ldr
->push_back(
423 reinterpret_cast<nacl::FileDescriptor
>(channel
));
425 nacl::FileDescriptor channel
;
426 channel
.fd
= sourceh
;
427 channel
.auto_close
= close_source
;
428 handles_for_sel_ldr
->push_back(channel
);
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
++) {
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(),
448 0, // Unused given DUPLICATE_SAME_ACCESS.
450 DUPLICATE_CLOSE_SOURCE
| DUPLICATE_SAME_ACCESS
)) {
451 LOG(ERROR
) << "DuplicateHandle() failed";
455 handles_for_renderer
.push_back(
456 reinterpret_cast<nacl::FileDescriptor
>(handle_in_renderer
));
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
);
468 // Copy the process handle into the renderer process.
469 if (!DuplicateHandle(base::GetCurrentProcessHandle(),
471 chrome_render_message_filter_
->peer_handle(),
472 &nacl_process_handle
,
476 LOG(ERROR
) << "DuplicateHandle() failed";
481 // We use pid as process handle on Posix
482 nacl_process_handle
= handle();
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
;
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
)) {
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
)) {
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
;
519 options
.executable
= true;
520 if (!memory_buffer
.Create(options
)) {
521 LOG(ERROR
) << "Failed to allocate memory buffer";
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";
532 memory_fd
.auto_close
= true;
533 handles_for_sel_ldr
.push_back(memory_fd
);
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();