Don't preload rarely seen large images
[chromium-blink-merge.git] / components / nacl / loader / nacl_helper_linux.cc
blob8d003c9b4d6d87a311b622f3d7ff9286c659ac27
1 // Copyright 2013 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 // A mini-zygote specifically for Native Client.
7 #include "components/nacl/loader/nacl_helper_linux.h"
9 #include <errno.h>
10 #include <fcntl.h>
11 #include <signal.h>
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <sys/socket.h>
15 #include <sys/stat.h>
16 #include <sys/types.h>
18 #include <string>
19 #include <vector>
21 #include "base/at_exit.h"
22 #include "base/command_line.h"
23 #include "base/files/scoped_file.h"
24 #include "base/logging.h"
25 #include "base/memory/scoped_ptr.h"
26 #include "base/memory/scoped_vector.h"
27 #include "base/message_loop/message_loop.h"
28 #include "base/posix/eintr_wrapper.h"
29 #include "base/posix/global_descriptors.h"
30 #include "base/posix/unix_domain_socket_linux.h"
31 #include "base/process/kill.h"
32 #include "base/process/process_handle.h"
33 #include "base/rand_util.h"
34 #include "components/nacl/common/nacl_switches.h"
35 #include "components/nacl/loader/nacl_listener.h"
36 #include "components/nacl/loader/nonsfi/nonsfi_listener.h"
37 #include "components/nacl/loader/sandbox_linux/nacl_sandbox_linux.h"
38 #include "content/public/common/content_descriptors.h"
39 #include "content/public/common/send_zygote_child_ping_linux.h"
40 #include "content/public/common/zygote_fork_delegate_linux.h"
41 #include "crypto/nss_util.h"
42 #include "ipc/ipc_descriptors.h"
43 #include "ipc/ipc_switches.h"
44 #include "sandbox/linux/services/credentials.h"
45 #include "sandbox/linux/services/libc_urandom_override.h"
46 #include "sandbox/linux/services/namespace_sandbox.h"
48 #if defined(OS_NACL_NONSFI)
49 #include "native_client/src/public/nonsfi/irt_exception_handling.h"
50 #else
51 #include <link.h>
52 #include "components/nacl/loader/nonsfi/irt_exception_handling.h"
53 #endif
55 namespace {
57 struct NaClLoaderSystemInfo {
58 size_t prereserved_sandbox_size;
59 long number_of_cores;
62 // Replace |file_descriptor| with the reading end of a closed pipe.
63 void ReplaceFDWithDummy(int file_descriptor) {
64 // Make sure that file_descriptor is an open descriptor.
65 PCHECK(-1 != fcntl(file_descriptor, F_GETFD, 0));
66 int pipefd[2];
67 PCHECK(0 == pipe(pipefd));
68 PCHECK(-1 != dup2(pipefd[0], file_descriptor));
69 PCHECK(0 == IGNORE_EINTR(close(pipefd[0])));
70 PCHECK(0 == IGNORE_EINTR(close(pipefd[1])));
73 // The child must mimic the behavior of zygote_main_linux.cc on the child
74 // side of the fork. See zygote_main_linux.cc:HandleForkRequest from
75 // if (!child) {
76 void BecomeNaClLoader(base::ScopedFD browser_fd,
77 const NaClLoaderSystemInfo& system_info,
78 bool uses_nonsfi_mode,
79 nacl::NaClSandbox* nacl_sandbox) {
80 DCHECK(nacl_sandbox);
81 VLOG(1) << "NaCl loader: setting up IPC descriptor";
82 // Close or shutdown IPC channels that we don't need anymore.
83 PCHECK(0 == IGNORE_EINTR(close(kNaClZygoteDescriptor)));
84 // In Non-SFI mode, it's important to close any non-expected IPC channels.
85 if (uses_nonsfi_mode) {
86 // The low-level kSandboxIPCChannel is used by renderers and NaCl for
87 // various operations. See the LinuxSandbox::METHOD_* methods. NaCl uses
88 // LinuxSandbox::METHOD_MAKE_SHARED_MEMORY_SEGMENT in SFI mode, so this
89 // should only be closed in Non-SFI mode.
90 // This file descriptor is insidiously used by a number of APIs. Closing it
91 // could lead to difficult to debug issues. Instead of closing it, replace
92 // it with a dummy.
93 const int sandbox_ipc_channel =
94 base::GlobalDescriptors::kBaseDescriptor + kSandboxIPCChannel;
96 ReplaceFDWithDummy(sandbox_ipc_channel);
98 // Install crash signal handlers before disallowing system calls.
99 #if defined(OS_NACL_NONSFI)
100 nonsfi_initialize_signal_handler();
101 #else
102 nacl::nonsfi::InitializeSignalHandler();
103 #endif
106 // Always ignore SIGPIPE, for consistency with other Chrome processes and
107 // because some IPC code, such as sync_socket_posix.cc, requires this.
108 // We do this before seccomp-bpf is initialized.
109 PCHECK(signal(SIGPIPE, SIG_IGN) != SIG_ERR);
111 // Finish layer-1 sandbox initialization and initialize the layer-2 sandbox.
112 CHECK(!nacl_sandbox->HasOpenDirectory());
113 nacl_sandbox->InitializeLayerTwoSandbox(uses_nonsfi_mode);
114 nacl_sandbox->SealLayerOneSandbox();
115 nacl_sandbox->CheckSandboxingStateWithPolicy();
117 base::GlobalDescriptors::GetInstance()->Set(kPrimaryIPCChannel,
118 browser_fd.release());
120 base::MessageLoopForIO main_message_loop;
121 #if defined(OS_NACL_NONSFI)
122 CHECK(uses_nonsfi_mode);
123 nacl::nonsfi::NonSfiListener listener;
124 listener.Listen();
125 #else
126 // TODO(hidehiko): Drop Non-SFI supporting from nacl_helper after the
127 // nacl_helper_nonsfi switching is done.
128 if (uses_nonsfi_mode) {
129 nacl::nonsfi::NonSfiListener listener;
130 listener.Listen();
131 } else {
132 NaClListener listener;
133 listener.set_prereserved_sandbox_size(system_info.prereserved_sandbox_size);
134 listener.set_number_of_cores(system_info.number_of_cores);
135 listener.Listen();
137 #endif
138 _exit(0);
141 // Start the NaCl loader in a child created by the NaCl loader Zygote.
142 void ChildNaClLoaderInit(ScopedVector<base::ScopedFD> child_fds,
143 const NaClLoaderSystemInfo& system_info,
144 bool uses_nonsfi_mode,
145 nacl::NaClSandbox* nacl_sandbox,
146 const std::string& channel_id) {
147 DCHECK(child_fds.size() >
148 std::max(content::ZygoteForkDelegate::kPIDOracleFDIndex,
149 content::ZygoteForkDelegate::kBrowserFDIndex));
151 // Ping the PID oracle socket.
152 CHECK(content::SendZygoteChildPing(
153 child_fds[content::ZygoteForkDelegate::kPIDOracleFDIndex]->get()));
155 base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
156 switches::kProcessChannelID, channel_id);
158 // Save the browser socket and close the rest.
159 base::ScopedFD browser_fd(
160 child_fds[content::ZygoteForkDelegate::kBrowserFDIndex]->Pass());
161 child_fds.clear();
163 BecomeNaClLoader(
164 browser_fd.Pass(), system_info, uses_nonsfi_mode, nacl_sandbox);
165 _exit(1);
168 // Handle a fork request from the Zygote.
169 // Some of this code was lifted from
170 // content/browser/zygote_main_linux.cc:ForkWithRealPid()
171 bool HandleForkRequest(ScopedVector<base::ScopedFD> child_fds,
172 const NaClLoaderSystemInfo& system_info,
173 nacl::NaClSandbox* nacl_sandbox,
174 base::PickleIterator* input_iter,
175 base::Pickle* output_pickle) {
176 bool uses_nonsfi_mode;
177 if (!input_iter->ReadBool(&uses_nonsfi_mode)) {
178 LOG(ERROR) << "Could not read uses_nonsfi_mode status";
179 return false;
182 std::string channel_id;
183 if (!input_iter->ReadString(&channel_id)) {
184 LOG(ERROR) << "Could not read channel_id string";
185 return false;
188 if (content::ZygoteForkDelegate::kNumPassedFDs != child_fds.size()) {
189 LOG(ERROR) << "nacl_helper: unexpected number of fds, got "
190 << child_fds.size();
191 return false;
194 VLOG(1) << "nacl_helper: forking";
195 pid_t child_pid;
196 if (sandbox::NamespaceSandbox::InNewUserNamespace()) {
197 child_pid = sandbox::NamespaceSandbox::ForkInNewPidNamespace(
198 /*drop_capabilities_in_child=*/true);
199 } else {
200 child_pid = sandbox::Credentials::ForkAndDropCapabilitiesInChild();
203 if (child_pid < 0) {
204 PLOG(ERROR) << "*** fork() failed.";
207 if (child_pid == 0) {
208 // Install termiantion signal handlers for nonsfi NaCl. The SFI NaCl runtime
209 // will install signal handlers for SIGINT, SIGTERM, etc. so we do not need
210 // to install termination signal handlers ourselves (in fact, it will crash
211 // if signal handlers for these are present).
212 if (uses_nonsfi_mode && getpid() == 1) {
213 // Note that nonsfi NaCl may override some of these signal handlers, which
214 // is fine.
215 sandbox::NamespaceSandbox::InstallDefaultTerminationSignalHandlers();
217 ChildNaClLoaderInit(child_fds.Pass(),
218 system_info,
219 uses_nonsfi_mode,
220 nacl_sandbox,
221 channel_id);
222 NOTREACHED();
225 // I am the parent.
226 // First, close the dummy_fd so the sandbox won't find me when
227 // looking for the child's pid in /proc. Also close other fds.
228 child_fds.clear();
229 VLOG(1) << "nacl_helper: child_pid is " << child_pid;
231 // Now send child_pid (eventually -1 if fork failed) to the Chrome Zygote.
232 output_pickle->WriteInt(child_pid);
233 return true;
236 bool HandleGetTerminationStatusRequest(base::PickleIterator* input_iter,
237 base::Pickle* output_pickle) {
238 pid_t child_to_wait;
239 if (!input_iter->ReadInt(&child_to_wait)) {
240 LOG(ERROR) << "Could not read pid to wait for";
241 return false;
244 bool known_dead;
245 if (!input_iter->ReadBool(&known_dead)) {
246 LOG(ERROR) << "Could not read known_dead status";
247 return false;
249 // TODO(jln): With NaCl, known_dead seems to never be set to true (unless
250 // called from the Zygote's kZygoteCommandReap command). This means that we
251 // will sometimes detect the process as still running when it's not. Fix
252 // this!
254 int exit_code;
255 base::TerminationStatus status;
256 if (known_dead)
257 status = base::GetKnownDeadTerminationStatus(child_to_wait, &exit_code);
258 else
259 status = base::GetTerminationStatus(child_to_wait, &exit_code);
260 output_pickle->WriteInt(static_cast<int>(status));
261 output_pickle->WriteInt(exit_code);
262 return true;
265 // Honor a command |command_type|. Eventual command parameters are
266 // available in |input_iter| and eventual file descriptors attached to
267 // the command are in |attached_fds|.
268 // Reply to the command on |reply_fds|.
269 bool HonorRequestAndReply(int reply_fd,
270 int command_type,
271 ScopedVector<base::ScopedFD> attached_fds,
272 const NaClLoaderSystemInfo& system_info,
273 nacl::NaClSandbox* nacl_sandbox,
274 base::PickleIterator* input_iter) {
275 base::Pickle write_pickle;
276 bool have_to_reply = false;
277 // Commands must write anything to send back to |write_pickle|.
278 switch (command_type) {
279 case nacl::kNaClForkRequest:
280 have_to_reply = HandleForkRequest(attached_fds.Pass(),
281 system_info,
282 nacl_sandbox,
283 input_iter,
284 &write_pickle);
285 break;
286 case nacl::kNaClGetTerminationStatusRequest:
287 have_to_reply =
288 HandleGetTerminationStatusRequest(input_iter, &write_pickle);
289 break;
290 default:
291 LOG(ERROR) << "Unsupported command from Zygote";
292 return false;
294 if (!have_to_reply)
295 return false;
296 const std::vector<int> empty; // We never send file descriptors back.
297 if (!base::UnixDomainSocket::SendMsg(reply_fd, write_pickle.data(),
298 write_pickle.size(), empty)) {
299 LOG(ERROR) << "*** send() to zygote failed";
300 return false;
302 return true;
305 // Read a request from the Zygote from |zygote_ipc_fd| and handle it.
306 // Die on EOF from |zygote_ipc_fd|.
307 bool HandleZygoteRequest(int zygote_ipc_fd,
308 const NaClLoaderSystemInfo& system_info,
309 nacl::NaClSandbox* nacl_sandbox) {
310 ScopedVector<base::ScopedFD> fds;
311 char buf[kNaClMaxIPCMessageLength];
312 const ssize_t msglen = base::UnixDomainSocket::RecvMsg(zygote_ipc_fd,
313 &buf, sizeof(buf), &fds);
314 // If the Zygote has started handling requests, we should be sandboxed via
315 // the setuid sandbox.
316 if (!nacl_sandbox->layer_one_enabled()) {
317 LOG(ERROR) << "NaCl helper process running without a sandbox!\n"
318 << "Most likely you need to configure your SUID sandbox "
319 << "correctly";
321 if (msglen == 0 || (msglen == -1 && errno == ECONNRESET)) {
322 // EOF from the browser. Goodbye!
323 _exit(0);
325 if (msglen < 0) {
326 PLOG(ERROR) << "nacl_helper: receive from zygote failed";
327 return false;
330 base::Pickle read_pickle(buf, msglen);
331 base::PickleIterator read_iter(read_pickle);
332 int command_type;
333 if (!read_iter.ReadInt(&command_type)) {
334 LOG(ERROR) << "Unable to read command from Zygote";
335 return false;
337 return HonorRequestAndReply(zygote_ipc_fd,
338 command_type,
339 fds.Pass(),
340 system_info,
341 nacl_sandbox,
342 &read_iter);
345 #if !defined(OS_NACL_NONSFI)
346 static const char kNaClHelperReservedAtZero[] = "reserved_at_zero";
347 static const char kNaClHelperRDebug[] = "r_debug";
349 // Since we were started by nacl_helper_bootstrap rather than in the
350 // usual way, the debugger cannot figure out where our executable
351 // or the dynamic linker or the shared libraries are in memory,
352 // so it won't find any symbols. But we can fake it out to find us.
354 // The zygote passes --r_debug=0xXXXXXXXXXXXXXXXX.
355 // nacl_helper_bootstrap replaces the Xs with the address of its _r_debug
356 // structure. The debugger will look for that symbol by name to
357 // discover the addresses of key dynamic linker data structures.
358 // Since all it knows about is the original main executable, which
359 // is the bootstrap program, it finds the symbol defined there. The
360 // dynamic linker's structure is somewhere else, but it is filled in
361 // after initialization. The parts that really matter to the
362 // debugger never change. So we just copy the contents of the
363 // dynamic linker's structure into the address provided by the option.
364 // Hereafter, if someone attaches a debugger (or examines a core dump),
365 // the debugger will find all the symbols in the normal way.
367 // Non-SFI mode does not use nacl_helper_bootstrap, so it doesn't need to
368 // process the --r_debug option.
369 static void CheckRDebug(char* argv0) {
370 std::string r_debug_switch_value =
371 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
372 kNaClHelperRDebug);
373 if (!r_debug_switch_value.empty()) {
374 char* endp;
375 uintptr_t r_debug_addr = strtoul(r_debug_switch_value.c_str(), &endp, 0);
376 if (r_debug_addr != 0 && *endp == '\0') {
377 r_debug* bootstrap_r_debug = reinterpret_cast<r_debug*>(r_debug_addr);
378 *bootstrap_r_debug = _r_debug;
380 // Since the main executable (the bootstrap program) does not
381 // have a dynamic section, the debugger will not skip the
382 // first element of the link_map list as it usually would for
383 // an executable or PIE that was loaded normally. But the
384 // dynamic linker has set l_name for the PIE to "" as is
385 // normal for the main executable. So the debugger doesn't
386 // know which file it is. Fill in the actual file name, which
387 // came in as our argv[0].
388 link_map* l = _r_debug.r_map;
389 if (l->l_name[0] == '\0')
390 l->l_name = argv0;
395 // The zygote passes --reserved_at_zero=0xXXXXXXXXXXXXXXXX.
396 // nacl_helper_bootstrap replaces the Xs with the amount of prereserved
397 // sandbox memory.
399 // CheckReservedAtZero parses the value of the argument reserved_at_zero
400 // and returns the amount of prereserved sandbox memory.
401 static size_t CheckReservedAtZero() {
402 size_t prereserved_sandbox_size = 0;
403 std::string reserved_at_zero_switch_value =
404 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
405 kNaClHelperReservedAtZero);
406 if (!reserved_at_zero_switch_value.empty()) {
407 char* endp;
408 prereserved_sandbox_size =
409 strtoul(reserved_at_zero_switch_value.c_str(), &endp, 0);
410 if (*endp != '\0')
411 LOG(ERROR) << "Could not parse reserved_at_zero argument value of "
412 << reserved_at_zero_switch_value;
414 return prereserved_sandbox_size;
416 #endif
418 } // namespace
420 #if defined(ADDRESS_SANITIZER)
421 // Do not install the SIGSEGV handler in ASan. This should make the NaCl
422 // platform qualification test pass.
423 // detect_odr_violation=0: http://crbug.com/376306
424 static const char kAsanDefaultOptionsNaCl[] =
425 "handle_segv=0:detect_odr_violation=0";
427 // Override the default ASan options for the NaCl helper.
428 // __asan_default_options should not be instrumented, because it is called
429 // before ASan is initialized.
430 extern "C"
431 __attribute__((no_sanitize_address))
432 // The function isn't referenced from the executable itself. Make sure it isn't
433 // stripped by the linker.
434 __attribute__((used))
435 __attribute__((visibility("default")))
436 const char* __asan_default_options() {
437 return kAsanDefaultOptionsNaCl;
439 #endif
441 int main(int argc, char* argv[]) {
442 base::CommandLine::Init(argc, argv);
443 base::AtExitManager exit_manager;
444 base::RandUint64(); // acquire /dev/urandom fd before sandbox is raised
446 #if !defined(OS_NACL_NONSFI)
447 // NSS is only needed for SFI NaCl.
448 // Allows NSS to fopen() /dev/urandom.
449 sandbox::InitLibcUrandomOverrides();
450 #if !defined(USE_OPENSSL)
451 // Configure NSS for use inside the NaCl process.
452 // The fork check has not caused problems for NaCl, but this appears to be
453 // best practice (see other places LoadNSSLibraries is called.)
454 crypto::DisableNSSForkCheck();
455 // Without this line on Linux, HMAC::Init will instantiate a singleton that
456 // in turn attempts to open a file. Disabling this behavior avoids a ~70 ms
457 // stall the first time HMAC is used.
458 crypto::ForceNSSNoDBInit();
459 // Load shared libraries before sandbox is raised.
460 // NSS is needed to perform hashing for validation caching.
461 crypto::LoadNSSLibraries();
462 #endif // !defined(USE_OPENSSL)
463 #endif // defined(OS_NACL_NONSFI)
464 const NaClLoaderSystemInfo system_info = {
465 #if !defined(OS_NACL_NONSFI)
466 // These are not used by nacl_helper_nonsfi.
467 CheckReservedAtZero(),
468 sysconf(_SC_NPROCESSORS_ONLN)
469 #endif
472 #if !defined(OS_NACL_NONSFI)
473 CheckRDebug(argv[0]);
474 #endif
476 scoped_ptr<nacl::NaClSandbox> nacl_sandbox(new nacl::NaClSandbox);
477 // Make sure that the early initialization did not start any spurious
478 // threads.
479 #if !defined(THREAD_SANITIZER)
480 CHECK(nacl_sandbox->IsSingleThreaded());
481 #endif
483 const bool is_init_process = 1 == getpid();
484 nacl_sandbox->InitializeLayerOneSandbox();
485 CHECK_EQ(is_init_process, nacl_sandbox->layer_one_enabled());
487 const std::vector<int> empty;
488 // Send the zygote a message to let it know we are ready to help
489 if (!base::UnixDomainSocket::SendMsg(kNaClZygoteDescriptor,
490 kNaClHelperStartupAck,
491 sizeof(kNaClHelperStartupAck), empty)) {
492 LOG(ERROR) << "*** send() to zygote failed";
495 // Now handle requests from the Zygote.
496 while (true) {
497 bool request_handled = HandleZygoteRequest(
498 kNaClZygoteDescriptor, system_info, nacl_sandbox.get());
499 // Do not turn this into a CHECK() without thinking about robustness
500 // against malicious IPC requests.
501 DCHECK(request_handled);
503 NOTREACHED();