app_list: Change touch drag start delay to 200ms.
[chromium-blink-merge.git] / chrome / nacl / nacl_helper_linux.cc
blobe102ed0b869abbf32e7c8a03a107cebc0e8e08cf
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.
5 // A mini-zygote specifically for Native Client.
7 #include "chrome/common/nacl_helper_linux.h"
9 #include <errno.h>
10 #include <link.h>
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <sys/socket.h>
14 #include <sys/types.h>
16 #include <string>
17 #include <vector>
19 #include "base/at_exit.h"
20 #include "base/command_line.h"
21 #include "base/eintr_wrapper.h"
22 #include "base/global_descriptors_posix.h"
23 #include "base/json/string_escape.h"
24 #include "base/logging.h"
25 #include "base/message_loop.h"
26 #include "base/posix/unix_domain_socket.h"
27 #include "base/rand_util.h"
28 #include "chrome/nacl/nacl_listener.h"
29 #include "crypto/nss_util.h"
30 #include "ipc/ipc_descriptors.h"
31 #include "ipc/ipc_switches.h"
32 #include "sandbox/linux/services/libc_urandom_override.h"
34 namespace {
36 // The child must mimic the behavior of zygote_main_linux.cc on the child
37 // side of the fork. See zygote_main_linux.cc:HandleForkRequest from
38 // if (!child) {
39 // Note: this code doesn't attempt to support SELINUX or the SECCOMP sandbox.
40 void BecomeNaClLoader(const std::vector<int>& child_fds,
41 size_t prereserved_sandbox_size) {
42 VLOG(1) << "NaCl loader: setting up IPC descriptor";
43 // don't need zygote FD any more
44 if (HANDLE_EINTR(close(kNaClZygoteDescriptor)) != 0)
45 LOG(ERROR) << "close(kNaClZygoteDescriptor) failed.";
46 // Set up browser descriptor on fd 3 and IPC as expected by Chrome.
47 base::GlobalDescriptors::GetInstance()->Set(kPrimaryIPCChannel,
48 kPrimaryIPCChannel + base::GlobalDescriptors::kBaseDescriptor);
49 int zfd = dup2(child_fds[kNaClBrowserFDIndex], kNaClBrowserDescriptor);
50 if (zfd != kNaClBrowserDescriptor) {
51 LOG(ERROR) << "Could not initialize kNaClBrowserDescriptor";
52 _exit(-1);
55 MessageLoopForIO main_message_loop;
56 NaClListener listener;
57 listener.set_prereserved_sandbox_size(prereserved_sandbox_size);
58 listener.Listen();
59 _exit(0);
62 // Some of this code was lifted from
63 // content/browser/zygote_main_linux.cc:ForkWithRealPid()
64 void HandleForkRequest(const std::vector<int>& child_fds,
65 size_t prereserved_sandbox_size) {
66 VLOG(1) << "nacl_helper: forking";
67 pid_t childpid = fork();
68 if (childpid < 0) {
69 perror("fork");
70 LOG(ERROR) << "*** HandleForkRequest failed\n";
71 // fall through to parent case below
72 } else if (childpid == 0) { // In the child process.
73 bool validack = false;
74 const size_t kMaxReadSize = 1024;
75 char buffer[kMaxReadSize];
76 // Wait until the parent process has discovered our PID. We
77 // should not fork any child processes (which the seccomp
78 // sandbox does) until then, because that can interfere with the
79 // parent's discovery of our PID.
80 const int nread = HANDLE_EINTR(read(child_fds[kNaClParentFDIndex], buffer,
81 kMaxReadSize));
82 const std::string switch_prefix = std::string("--") +
83 switches::kProcessChannelID + std::string("=");
84 const size_t len = switch_prefix.length();
86 if (nread < 0) {
87 perror("read");
88 LOG(ERROR) << "read returned " << nread;
89 } else if (nread > static_cast<int>(len)) {
90 if (switch_prefix.compare(0, len, buffer, 0, len) == 0) {
91 VLOG(1) << "NaCl loader is synchronised with Chrome zygote";
92 CommandLine::ForCurrentProcess()->AppendSwitchASCII(
93 switches::kProcessChannelID,
94 std::string(&buffer[len], nread - len));
95 validack = true;
98 if (HANDLE_EINTR(close(child_fds[kNaClDummyFDIndex])) != 0)
99 LOG(ERROR) << "close(child_fds[kNaClDummyFDIndex]) failed";
100 if (HANDLE_EINTR(close(child_fds[kNaClParentFDIndex])) != 0)
101 LOG(ERROR) << "close(child_fds[kNaClParentFDIndex]) failed";
102 if (validack) {
103 BecomeNaClLoader(child_fds, prereserved_sandbox_size);
104 } else {
105 LOG(ERROR) << "Failed to synch with zygote";
107 // NOTREACHED
108 return;
110 // I am the parent.
111 // First, close the dummy_fd so the sandbox won't find me when
112 // looking for the child's pid in /proc. Also close other fds.
113 for (size_t i = 0; i < child_fds.size(); i++) {
114 if (HANDLE_EINTR(close(child_fds[i])) != 0)
115 LOG(ERROR) << "close(child_fds[i]) failed";
117 VLOG(1) << "nacl_helper: childpid is " << childpid;
118 // Now tell childpid to the Chrome zygote.
119 if (HANDLE_EINTR(send(kNaClZygoteDescriptor,
120 &childpid, sizeof(childpid), MSG_EOR))
121 != sizeof(childpid)) {
122 LOG(ERROR) << "*** send() to zygote failed";
126 } // namespace
128 static const char kNaClHelperReservedAtZero[] = "reserved_at_zero";
129 static const char kNaClHelperRDebug[] = "r_debug";
132 * Since we were started by nacl_helper_bootstrap rather than in the
133 * usual way, the debugger cannot figure out where our executable
134 * or the dynamic linker or the shared libraries are in memory,
135 * so it won't find any symbols. But we can fake it out to find us.
137 * The zygote passes --r_debug=0xXXXXXXXXXXXXXXXX.
138 * nacl_helper_bootstrap replaces the Xs with the address of its _r_debug
139 * structure. The debugger will look for that symbol by name to
140 * discover the addresses of key dynamic linker data structures.
141 * Since all it knows about is the original main executable, which
142 * is the bootstrap program, it finds the symbol defined there. The
143 * dynamic linker's structure is somewhere else, but it is filled in
144 * after initialization. The parts that really matter to the
145 * debugger never change. So we just copy the contents of the
146 * dynamic linker's structure into the address provided by the option.
147 * Hereafter, if someone attaches a debugger (or examines a core dump),
148 * the debugger will find all the symbols in the normal way.
150 static void CheckRDebug(char *argv0) {
151 std::string r_debug_switch_value =
152 CommandLine::ForCurrentProcess()->GetSwitchValueASCII(kNaClHelperRDebug);
153 if (!r_debug_switch_value.empty()) {
154 char *endp;
155 uintptr_t r_debug_addr = strtoul(r_debug_switch_value.c_str(), &endp, 0);
156 if (r_debug_addr != 0 && *endp == '\0') {
157 struct r_debug *bootstrap_r_debug = (struct r_debug *) r_debug_addr;
158 *bootstrap_r_debug = _r_debug;
161 * Since the main executable (the bootstrap program) does not
162 * have a dynamic section, the debugger will not skip the
163 * first element of the link_map list as it usually would for
164 * an executable or PIE that was loaded normally. But the
165 * dynamic linker has set l_name for the PIE to "" as is
166 * normal for the main executable. So the debugger doesn't
167 * know which file it is. Fill in the actual file name, which
168 * came in as our argv[0].
170 struct link_map *l = _r_debug.r_map;
171 if (l->l_name[0] == '\0')
172 l->l_name = argv0;
178 * The zygote passes --reserved_at_zero=0xXXXXXXXXXXXXXXXX.
179 * nacl_helper_bootstrap replaces the Xs with the amount of prereserved
180 * sandbox memory.
182 * CheckReservedAtZero parses the value of the argument reserved_at_zero
183 * and returns the amount of prereserved sandbox memory.
185 static size_t CheckReservedAtZero() {
186 size_t prereserved_sandbox_size = 0;
187 std::string reserved_at_zero_switch_value =
188 CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
189 kNaClHelperReservedAtZero);
190 if (!reserved_at_zero_switch_value.empty()) {
191 char *endp;
192 prereserved_sandbox_size =
193 strtoul(reserved_at_zero_switch_value.c_str(), &endp, 0);
194 if (*endp != '\0')
195 LOG(ERROR) << "Could not parse reserved_at_zero argument value of "
196 << reserved_at_zero_switch_value;
198 return prereserved_sandbox_size;
201 #if defined(ADDRESS_SANITIZER)
202 // Do not install the SIGSEGV handler in ASan. This should make the NaCl
203 // platform qualification test pass.
204 static const char kAsanDefaultOptionsNaCl[] = "handle_segv=0";
206 // Override the default ASan options for the NaCl helper.
207 // __asan_default_options should not be instrumented, because it is called
208 // before ASan is initialized.
209 extern "C"
210 __attribute__((no_address_safety_analysis))
211 const char *__asan_default_options() {
212 return kAsanDefaultOptionsNaCl;
214 #endif
216 int main(int argc, char *argv[]) {
217 CommandLine::Init(argc, argv);
218 base::AtExitManager exit_manager;
219 base::RandUint64(); // acquire /dev/urandom fd before sandbox is raised
220 #if !defined(CHROMIUM_SELINUX)
221 // Allows NSS to fopen() /dev/urandom.
222 sandbox::InitLibcUrandomOverrides();
223 #endif
224 #if defined(USE_NSS)
225 // Configure NSS for use inside the NaCl process.
226 // The fork check has not caused problems for NaCl, but this appears to be
227 // best practice (see other places LoadNSSLibraries is called.)
228 crypto::DisableNSSForkCheck();
229 // Without this line on Linux, HMAC::Init will instantiate a singleton that
230 // in turn attempts to open a file. Disabling this behavior avoids a ~70 ms
231 // stall the first time HMAC is used.
232 crypto::ForceNSSNoDBInit();
233 // Load shared libraries before sandbox is raised.
234 // NSS is needed to perform hashing for validation caching.
235 crypto::LoadNSSLibraries();
236 #endif
237 std::vector<int> empty; // for SendMsg() calls
238 size_t prereserved_sandbox_size = CheckReservedAtZero();
240 CheckRDebug(argv[0]);
242 // Send the zygote a message to let it know we are ready to help
243 if (!UnixDomainSocket::SendMsg(kNaClZygoteDescriptor,
244 kNaClHelperStartupAck,
245 sizeof(kNaClHelperStartupAck), empty)) {
246 LOG(ERROR) << "*** send() to zygote failed";
249 while (true) {
250 int badpid = -1;
251 std::vector<int> fds;
252 static const unsigned kMaxMessageLength = 2048;
253 char buf[kMaxMessageLength];
254 const ssize_t msglen = UnixDomainSocket::RecvMsg(kNaClZygoteDescriptor,
255 &buf, sizeof(buf), &fds);
256 if (msglen == 0 || (msglen == -1 && errno == ECONNRESET)) {
257 // EOF from the browser. Goodbye!
258 _exit(0);
259 } else if (msglen < 0) {
260 LOG(ERROR) << "nacl_helper: receive from zygote failed, errno = "
261 << errno;
262 } else if (msglen == sizeof(kNaClForkRequest) - 1 &&
263 memcmp(buf, kNaClForkRequest, msglen) == 0) {
264 if (kNaClParentFDIndex + 1 == fds.size()) {
265 HandleForkRequest(fds, prereserved_sandbox_size);
266 continue; // fork succeeded. Note: child does not return
267 } else {
268 LOG(ERROR) << "nacl_helper: unexpected number of fds, got "
269 << fds.size();
271 } else {
272 LOG(ERROR) << "nacl_helper unrecognized request: "
273 << base::GetDoubleQuotedJson(std::string(buf, buf + msglen));
274 _exit(-1);
276 // if fork fails, send PID=-1 to zygote
277 if (!UnixDomainSocket::SendMsg(kNaClZygoteDescriptor, &badpid,
278 sizeof(badpid), empty)) {
279 LOG(ERROR) << "*** send() to zygote failed";
282 CHECK(false); // This routine must not return