Remove const WebMediaPlayer::didLoadingProgress() implementations.
[chromium-blink-merge.git] / content / zygote / zygote_main_linux.cc
blobe506820a9529e809b1fc8b6617c833e27e8940fa
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 #include "content/zygote/zygote_main.h"
7 #include <dlfcn.h>
8 #include <errno.h>
9 #include <fcntl.h>
10 #include <pthread.h>
11 #include <stdio.h>
12 #include <sys/socket.h>
13 #include <sys/stat.h>
14 #include <sys/types.h>
15 #include <sys/wait.h>
16 #include <unistd.h>
18 #include "base/basictypes.h"
19 #include "base/bind.h"
20 #include "base/callback.h"
21 #include "base/command_line.h"
22 #include "base/compiler_specific.h"
23 #include "base/linux_util.h"
24 #include "base/memory/scoped_vector.h"
25 #include "base/native_library.h"
26 #include "base/pickle.h"
27 #include "base/posix/eintr_wrapper.h"
28 #include "base/posix/unix_domain_socket_linux.h"
29 #include "base/rand_util.h"
30 #include "base/sys_info.h"
31 #include "build/build_config.h"
32 #include "content/common/child_process_sandbox_support_impl_linux.h"
33 #include "content/common/font_config_ipc_linux.h"
34 #include "content/common/pepper_plugin_list.h"
35 #include "content/common/sandbox_linux/sandbox_linux.h"
36 #include "content/common/zygote_commands_linux.h"
37 #include "content/public/common/content_switches.h"
38 #include "content/public/common/main_function_params.h"
39 #include "content/public/common/pepper_plugin_info.h"
40 #include "content/public/common/sandbox_linux.h"
41 #include "content/public/common/zygote_fork_delegate_linux.h"
42 #include "content/zygote/zygote_linux.h"
43 #include "crypto/nss_util.h"
44 #include "sandbox/linux/services/init_process_reaper.h"
45 #include "sandbox/linux/services/libc_urandom_override.h"
46 #include "sandbox/linux/suid/client/setuid_sandbox_client.h"
47 #include "third_party/icu/source/i18n/unicode/timezone.h"
48 #include "third_party/skia/include/ports/SkFontConfigInterface.h"
50 #if defined(OS_LINUX)
51 #include <sys/epoll.h>
52 #include <sys/prctl.h>
53 #include <sys/signal.h>
54 #else
55 #include <signal.h>
56 #endif
58 #if defined(ENABLE_WEBRTC)
59 #include "third_party/libjingle/overrides/init_webrtc.h"
60 #endif
62 namespace content {
64 // See http://code.google.com/p/chromium/wiki/LinuxZygote
66 static void ProxyLocaltimeCallToBrowser(time_t input, struct tm* output,
67 char* timezone_out,
68 size_t timezone_out_len) {
69 Pickle request;
70 request.WriteInt(LinuxSandbox::METHOD_LOCALTIME);
71 request.WriteString(
72 std::string(reinterpret_cast<char*>(&input), sizeof(input)));
74 uint8_t reply_buf[512];
75 const ssize_t r = UnixDomainSocket::SendRecvMsg(
76 GetSandboxFD(), reply_buf, sizeof(reply_buf), NULL,
77 request);
78 if (r == -1) {
79 memset(output, 0, sizeof(struct tm));
80 return;
83 Pickle reply(reinterpret_cast<char*>(reply_buf), r);
84 PickleIterator iter(reply);
85 std::string result, timezone;
86 if (!reply.ReadString(&iter, &result) ||
87 !reply.ReadString(&iter, &timezone) ||
88 result.size() != sizeof(struct tm)) {
89 memset(output, 0, sizeof(struct tm));
90 return;
93 memcpy(output, result.data(), sizeof(struct tm));
94 if (timezone_out_len) {
95 const size_t copy_len = std::min(timezone_out_len - 1, timezone.size());
96 memcpy(timezone_out, timezone.data(), copy_len);
97 timezone_out[copy_len] = 0;
98 output->tm_zone = timezone_out;
99 } else {
100 output->tm_zone = NULL;
104 static bool g_am_zygote_or_renderer = false;
106 // Sandbox interception of libc calls.
108 // Because we are running in a sandbox certain libc calls will fail (localtime
109 // being the motivating example - it needs to read /etc/localtime). We need to
110 // intercept these calls and proxy them to the browser. However, these calls
111 // may come from us or from our libraries. In some cases we can't just change
112 // our code.
114 // It's for these cases that we have the following setup:
116 // We define global functions for those functions which we wish to override.
117 // Since we will be first in the dynamic resolution order, the dynamic linker
118 // will point callers to our versions of these functions. However, we have the
119 // same binary for both the browser and the renderers, which means that our
120 // overrides will apply in the browser too.
122 // The global |g_am_zygote_or_renderer| is true iff we are in a zygote or
123 // renderer process. It's set in ZygoteMain and inherited by the renderers when
124 // they fork. (This means that it'll be incorrect for global constructor
125 // functions and before ZygoteMain is called - beware).
127 // Our replacement functions can check this global and either proxy
128 // the call to the browser over the sandbox IPC
129 // (http://code.google.com/p/chromium/wiki/LinuxSandboxIPC) or they can use
130 // dlsym with RTLD_NEXT to resolve the symbol, ignoring any symbols in the
131 // current module.
133 // Other avenues:
135 // Our first attempt involved some assembly to patch the GOT of the current
136 // module. This worked, but was platform specific and doesn't catch the case
137 // where a library makes a call rather than current module.
139 // We also considered patching the function in place, but this would again by
140 // platform specific and the above technique seems to work well enough.
142 typedef struct tm* (*LocaltimeFunction)(const time_t* timep);
143 typedef struct tm* (*LocaltimeRFunction)(const time_t* timep,
144 struct tm* result);
146 static pthread_once_t g_libc_localtime_funcs_guard = PTHREAD_ONCE_INIT;
147 static LocaltimeFunction g_libc_localtime;
148 static LocaltimeFunction g_libc_localtime64;
149 static LocaltimeRFunction g_libc_localtime_r;
150 static LocaltimeRFunction g_libc_localtime64_r;
152 static void InitLibcLocaltimeFunctions() {
153 g_libc_localtime = reinterpret_cast<LocaltimeFunction>(
154 dlsym(RTLD_NEXT, "localtime"));
155 g_libc_localtime64 = reinterpret_cast<LocaltimeFunction>(
156 dlsym(RTLD_NEXT, "localtime64"));
157 g_libc_localtime_r = reinterpret_cast<LocaltimeRFunction>(
158 dlsym(RTLD_NEXT, "localtime_r"));
159 g_libc_localtime64_r = reinterpret_cast<LocaltimeRFunction>(
160 dlsym(RTLD_NEXT, "localtime64_r"));
162 if (!g_libc_localtime || !g_libc_localtime_r) {
163 // http://code.google.com/p/chromium/issues/detail?id=16800
165 // Nvidia's libGL.so overrides dlsym for an unknown reason and replaces
166 // it with a version which doesn't work. In this case we'll get a NULL
167 // result. There's not a lot we can do at this point, so we just bodge it!
168 LOG(ERROR) << "Your system is broken: dlsym doesn't work! This has been "
169 "reported to be caused by Nvidia's libGL. You should expect"
170 " time related functions to misbehave. "
171 "http://code.google.com/p/chromium/issues/detail?id=16800";
174 if (!g_libc_localtime)
175 g_libc_localtime = gmtime;
176 if (!g_libc_localtime64)
177 g_libc_localtime64 = g_libc_localtime;
178 if (!g_libc_localtime_r)
179 g_libc_localtime_r = gmtime_r;
180 if (!g_libc_localtime64_r)
181 g_libc_localtime64_r = g_libc_localtime_r;
184 // Define localtime_override() function with asm name "localtime", so that all
185 // references to localtime() will resolve to this function. Notice that we need
186 // to set visibility attribute to "default" to export the symbol, as it is set
187 // to "hidden" by default in chrome per build/common.gypi.
188 __attribute__ ((__visibility__("default")))
189 struct tm* localtime_override(const time_t* timep) __asm__ ("localtime");
191 __attribute__ ((__visibility__("default")))
192 struct tm* localtime_override(const time_t* timep) {
193 if (g_am_zygote_or_renderer) {
194 static struct tm time_struct;
195 static char timezone_string[64];
196 ProxyLocaltimeCallToBrowser(*timep, &time_struct, timezone_string,
197 sizeof(timezone_string));
198 return &time_struct;
199 } else {
200 CHECK_EQ(0, pthread_once(&g_libc_localtime_funcs_guard,
201 InitLibcLocaltimeFunctions));
202 struct tm* res = g_libc_localtime(timep);
203 #if defined(MEMORY_SANITIZER)
204 if (res) __msan_unpoison(res, sizeof(*res));
205 if (res->tm_zone) __msan_unpoison_string(res->tm_zone);
206 #endif
207 return res;
211 // Use same trick to override localtime64(), localtime_r() and localtime64_r().
212 __attribute__ ((__visibility__("default")))
213 struct tm* localtime64_override(const time_t* timep) __asm__ ("localtime64");
215 __attribute__ ((__visibility__("default")))
216 struct tm* localtime64_override(const time_t* timep) {
217 if (g_am_zygote_or_renderer) {
218 static struct tm time_struct;
219 static char timezone_string[64];
220 ProxyLocaltimeCallToBrowser(*timep, &time_struct, timezone_string,
221 sizeof(timezone_string));
222 return &time_struct;
223 } else {
224 CHECK_EQ(0, pthread_once(&g_libc_localtime_funcs_guard,
225 InitLibcLocaltimeFunctions));
226 struct tm* res = g_libc_localtime64(timep);
227 #if defined(MEMORY_SANITIZER)
228 if (res) __msan_unpoison(res, sizeof(*res));
229 if (res->tm_zone) __msan_unpoison_string(res->tm_zone);
230 #endif
231 return res;
235 __attribute__ ((__visibility__("default")))
236 struct tm* localtime_r_override(const time_t* timep,
237 struct tm* result) __asm__ ("localtime_r");
239 __attribute__ ((__visibility__("default")))
240 struct tm* localtime_r_override(const time_t* timep, struct tm* result) {
241 if (g_am_zygote_or_renderer) {
242 ProxyLocaltimeCallToBrowser(*timep, result, NULL, 0);
243 return result;
244 } else {
245 CHECK_EQ(0, pthread_once(&g_libc_localtime_funcs_guard,
246 InitLibcLocaltimeFunctions));
247 struct tm* res = g_libc_localtime_r(timep, result);
248 #if defined(MEMORY_SANITIZER)
249 if (res) __msan_unpoison(res, sizeof(*res));
250 if (res->tm_zone) __msan_unpoison_string(res->tm_zone);
251 #endif
252 return res;
256 __attribute__ ((__visibility__("default")))
257 struct tm* localtime64_r_override(const time_t* timep,
258 struct tm* result) __asm__ ("localtime64_r");
260 __attribute__ ((__visibility__("default")))
261 struct tm* localtime64_r_override(const time_t* timep, struct tm* result) {
262 if (g_am_zygote_or_renderer) {
263 ProxyLocaltimeCallToBrowser(*timep, result, NULL, 0);
264 return result;
265 } else {
266 CHECK_EQ(0, pthread_once(&g_libc_localtime_funcs_guard,
267 InitLibcLocaltimeFunctions));
268 struct tm* res = g_libc_localtime64_r(timep, result);
269 #if defined(MEMORY_SANITIZER)
270 if (res) __msan_unpoison(res, sizeof(*res));
271 if (res->tm_zone) __msan_unpoison_string(res->tm_zone);
272 #endif
273 return res;
277 #if defined(ENABLE_PLUGINS)
278 // Loads the (native) libraries but does not initialize them (i.e., does not
279 // call PPP_InitializeModule). This is needed by the zygote on Linux to get
280 // access to the plugins before entering the sandbox.
281 void PreloadPepperPlugins() {
282 std::vector<PepperPluginInfo> plugins;
283 ComputePepperPluginList(&plugins);
284 for (size_t i = 0; i < plugins.size(); ++i) {
285 if (!plugins[i].is_internal && plugins[i].is_sandboxed) {
286 base::NativeLibraryLoadError error;
287 base::NativeLibrary library = base::LoadNativeLibrary(plugins[i].path,
288 &error);
289 VLOG_IF(1, !library) << "Unable to load plugin "
290 << plugins[i].path.value() << " "
291 << error.ToString();
293 (void)library; // Prevent release-mode warning.
297 #endif
299 // This function triggers the static and lazy construction of objects that need
300 // to be created before imposing the sandbox.
301 static void ZygotePreSandboxInit() {
302 base::RandUint64();
304 base::SysInfo::AmountOfPhysicalMemory();
305 base::SysInfo::MaxSharedMemorySize();
306 base::SysInfo::NumberOfProcessors();
308 // ICU DateFormat class (used in base/time_format.cc) needs to get the
309 // Olson timezone ID by accessing the zoneinfo files on disk. After
310 // TimeZone::createDefault is called once here, the timezone ID is
311 // cached and there's no more need to access the file system.
312 scoped_ptr<icu::TimeZone> zone(icu::TimeZone::createDefault());
314 #if defined(USE_NSS)
315 // NSS libraries are loaded before sandbox is activated. This is to allow
316 // successful initialization of NSS which tries to load extra library files.
317 crypto::LoadNSSLibraries();
318 #elif defined(USE_OPENSSL)
319 // OpenSSL is intentionally not supported in the sandboxed processes, see
320 // http://crbug.com/99163. If that ever changes we'll likely need to init
321 // OpenSSL here (at least, load the library and error strings).
322 #else
323 // It's possible that another hypothetical crypto stack would not require
324 // pre-sandbox init, but more likely this is just a build configuration error.
325 #error Which SSL library are you using?
326 #endif
327 #if defined(ENABLE_PLUGINS)
328 // Ensure access to the Pepper plugins before the sandbox is turned on.
329 PreloadPepperPlugins();
330 #endif
331 #if defined(ENABLE_WEBRTC)
332 InitializeWebRtcModule();
333 #endif
334 SkFontConfigInterface::SetGlobal(
335 new FontConfigIPC(GetSandboxFD()))->unref();
338 static bool CreateInitProcessReaper() {
339 // The current process becomes init(1), this function returns from a
340 // newly created process.
341 const bool init_created = sandbox::CreateInitProcessReaper(NULL);
342 if (!init_created) {
343 LOG(ERROR) << "Error creating an init process to reap zombies";
344 return false;
346 return true;
349 // Enter the setuid sandbox. This requires the current process to have been
350 // created through the setuid sandbox.
351 static bool EnterSuidSandbox(sandbox::SetuidSandboxClient* setuid_sandbox) {
352 DCHECK(setuid_sandbox);
353 DCHECK(setuid_sandbox->IsSuidSandboxChild());
355 // Use the SUID sandbox. This still allows the seccomp sandbox to
356 // be enabled by the process later.
358 if (!setuid_sandbox->IsSuidSandboxUpToDate()) {
359 LOG(WARNING) <<
360 "You are using a wrong version of the setuid binary!\n"
361 "Please read "
362 "https://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment."
363 "\n\n";
366 if (!setuid_sandbox->ChrootMe())
367 return false;
369 if (setuid_sandbox->IsInNewPIDNamespace()) {
370 CHECK_EQ(1, getpid())
371 << "The SUID sandbox created a new PID namespace but Zygote "
372 "is not the init process. Please, make sure the SUID "
373 "binary is up to date.";
376 if (getpid() == 1) {
377 // The setuid sandbox has created a new PID namespace and we need
378 // to assume the role of init.
379 CHECK(CreateInitProcessReaper());
382 #if !defined(OS_OPENBSD)
383 // Previously, we required that the binary be non-readable. This causes the
384 // kernel to mark the process as non-dumpable at startup. The thinking was
385 // that, although we were putting the renderers into a PID namespace (with
386 // the SUID sandbox), they would nonetheless be in the /same/ PID
387 // namespace. So they could ptrace each other unless they were non-dumpable.
389 // If the binary was readable, then there would be a window between process
390 // startup and the point where we set the non-dumpable flag in which a
391 // compromised renderer could ptrace attach.
393 // However, now that we have a zygote model, only the (trusted) zygote
394 // exists at this point and we can set the non-dumpable flag which is
395 // inherited by all our renderer children.
397 // Note: a non-dumpable process can't be debugged. To debug sandbox-related
398 // issues, one can specify --allow-sandbox-debugging to let the process be
399 // dumpable.
400 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
401 if (!command_line.HasSwitch(switches::kAllowSandboxDebugging)) {
402 prctl(PR_SET_DUMPABLE, 0, 0, 0, 0);
403 if (prctl(PR_GET_DUMPABLE, 0, 0, 0, 0)) {
404 LOG(ERROR) << "Failed to set non-dumpable flag";
405 return false;
408 #endif
410 return true;
413 // If |is_suid_sandbox_child|, then make sure that the setuid sandbox is
414 // engaged.
415 static void EnterLayerOneSandbox(LinuxSandbox* linux_sandbox,
416 bool is_suid_sandbox_child) {
417 DCHECK(linux_sandbox);
419 ZygotePreSandboxInit();
421 // Check that the pre-sandbox initialization didn't spawn threads.
422 #if !defined(THREAD_SANITIZER)
423 DCHECK(linux_sandbox->IsSingleThreaded());
424 #endif
426 sandbox::SetuidSandboxClient* setuid_sandbox =
427 linux_sandbox->setuid_sandbox_client();
429 if (is_suid_sandbox_child) {
430 CHECK(EnterSuidSandbox(setuid_sandbox)) << "Failed to enter setuid sandbox";
434 bool ZygoteMain(const MainFunctionParams& params,
435 ScopedVector<ZygoteForkDelegate> fork_delegates) {
436 g_am_zygote_or_renderer = true;
437 sandbox::InitLibcUrandomOverrides();
439 LinuxSandbox* linux_sandbox = LinuxSandbox::GetInstance();
440 // This will pre-initialize the various sandboxes that need it.
441 linux_sandbox->PreinitializeSandbox();
443 const bool must_enable_setuid_sandbox =
444 linux_sandbox->setuid_sandbox_client()->IsSuidSandboxChild();
445 if (must_enable_setuid_sandbox) {
446 linux_sandbox->setuid_sandbox_client()->CloseDummyFile();
448 // Let the ZygoteHost know we're booting up.
449 CHECK(UnixDomainSocket::SendMsg(kZygoteSocketPairFd,
450 kZygoteBootMessage,
451 sizeof(kZygoteBootMessage),
452 std::vector<int>()));
455 VLOG(1) << "ZygoteMain: initializing " << fork_delegates.size()
456 << " fork delegates";
457 for (ScopedVector<ZygoteForkDelegate>::iterator i = fork_delegates.begin();
458 i != fork_delegates.end();
459 ++i) {
460 (*i)->Init(GetSandboxFD(), must_enable_setuid_sandbox);
463 // Turn on the first layer of the sandbox if the configuration warrants it.
464 EnterLayerOneSandbox(linux_sandbox, must_enable_setuid_sandbox);
466 int sandbox_flags = linux_sandbox->GetStatus();
467 bool setuid_sandbox_engaged = sandbox_flags & kSandboxLinuxSUID;
468 CHECK_EQ(must_enable_setuid_sandbox, setuid_sandbox_engaged);
470 Zygote zygote(sandbox_flags, fork_delegates.Pass());
471 // This function call can return multiple times, once per fork().
472 return zygote.ProcessRequests();
475 } // namespace content