blob: 9b23ece5a33bb9fa2f7d8801c53ff6266531489e [file] [log] [blame]
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in
12 * the documentation and/or other materials provided with the
13 * distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080029#include "libc_init_common.h"
30
Elliott Hughes642331b2013-03-06 15:03:53 -080031#include <elf.h>
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080032#include <errno.h>
Elliott Hughes1801db32015-06-08 18:04:00 -070033#include <fcntl.h>
Elliott Hughes642331b2013-03-06 15:03:53 -080034#include <stddef.h>
35#include <stdint.h>
36#include <stdio.h>
37#include <stdlib.h>
Elliott Hughes1801db32015-06-08 18:04:00 -070038#include <string.h>
Elliott Hughes642331b2013-03-06 15:03:53 -080039#include <sys/auxv.h>
Brian Carlstrom322e7bc2013-09-12 21:47:20 -070040#include <sys/time.h>
Elliott Hughes642331b2013-03-06 15:03:53 -080041#include <unistd.h>
42
Elliott Hughes642331b2013-03-06 15:03:53 -080043#include "private/bionic_auxv.h"
44#include "private/bionic_ssp.h"
Elliott Hugheseb847bc2013-10-09 15:50:50 -070045#include "private/bionic_tls.h"
Elliott Hughes642331b2013-03-06 15:03:53 -080046#include "private/KernelArgumentBlock.h"
47#include "pthread_internal.h"
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080048
Elliott Hughes0d787c12013-04-04 13:46:46 -070049extern "C" abort_msg_t** __abort_message_ptr;
Elliott Hughes42b2c6a2013-02-07 10:14:39 -080050extern "C" int __system_properties_init(void);
Elliott Hughes70b24b12013-11-15 11:51:07 -080051extern "C" int __set_tls(void* ptr);
Elliott Hughes877ec6d2013-11-15 17:40:18 -080052extern "C" int __set_tid_address(int* tid_address);
David 'Digit' Turner3a654b12009-06-03 19:32:37 +020053
Dan Albertb3aaf392014-08-13 13:11:58 -070054__LIBC_HIDDEN__ void __libc_init_vdso();
Elliott Hughes625993d2014-07-15 16:53:13 -070055
Elliott Hughes42b2c6a2013-02-07 10:14:39 -080056// Not public, but well-known in the BSDs.
Elliott Hughese4ccf5a2013-02-07 12:06:44 -080057const char* __progname;
Elliott Hughes42b2c6a2013-02-07 10:14:39 -080058
Elliott Hughesd3920b32013-02-07 18:39:34 -080059// Declared in <unistd.h>.
Elliott Hughes4f251be2012-11-01 16:33:29 -070060char** environ;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080061
Elliott Hugheseb847bc2013-10-09 15:50:50 -070062// Declared in "private/bionic_ssp.h".
Elliott Hughes642331b2013-03-06 15:03:53 -080063uintptr_t __stack_chk_guard = 0;
64
Evgeniy Stepanov1a78fbb2012-03-22 18:01:53 +040065/* Init TLS for the initial thread. Called by the linker _before_ libc is mapped
66 * in memory. Beware: all writes to libc globals from this function will
67 * apply to linker-private copies and will not be visible from libc later on.
68 *
69 * Note: this function creates a pthread_internal_t for the initial thread and
Elliott Hughes1728b232014-05-14 10:02:03 -070070 * stores the pointer in TLS, but does not add it to pthread's thread list. This
Evgeniy Stepanov1a78fbb2012-03-22 18:01:53 +040071 * has to be done later from libc itself (see __libc_init_common).
72 *
Elliott Hughes42b2c6a2013-02-07 10:14:39 -080073 * This function also stores a pointer to the kernel argument block in a TLS slot to be
Evgeniy Stepanov1a78fbb2012-03-22 18:01:53 +040074 * picked up by the libc constructor.
75 */
Elliott Hughesd3920b32013-02-07 18:39:34 -080076void __libc_init_tls(KernelArgumentBlock& args) {
77 __libc_auxv = args.auxv;
78
Elliott Hughes877ec6d2013-11-15 17:40:18 -080079 static pthread_internal_t main_thread;
Elliott Hughes877ec6d2013-11-15 17:40:18 -080080
81 // Tell the kernel to clear our tid field when we exit, so we're like any other pthread.
Elliott Hughes7086ad62014-06-19 16:39:01 -070082 // As a side-effect, this tells us our pid (which is the same as the main thread's tid).
Elliott Hughes877ec6d2013-11-15 17:40:18 -080083 main_thread.tid = __set_tid_address(&main_thread.tid);
Elliott Hughes7086ad62014-06-19 16:39:01 -070084 main_thread.set_cached_pid(main_thread.tid);
Elliott Hughes877ec6d2013-11-15 17:40:18 -080085
Elliott Hughes7086ad62014-06-19 16:39:01 -070086 // We don't want to free the main thread's stack even when the main thread exits
87 // because things like environment variables with global scope live on it.
Elliott Hughes57b7a612014-08-25 17:26:50 -070088 // We also can't free the pthread_internal_t itself, since that lives on the main
89 // thread's stack rather than on the heap.
Yabin Cuiba8dfc22015-01-06 09:31:00 -080090 // The main thread has no mmap allocated space for stack or pthread_internal_t.
91 main_thread.mmap_size = 0;
Elliott Hughes877ec6d2013-11-15 17:40:18 -080092 pthread_attr_init(&main_thread.attr);
Elliott Hughes57b7a612014-08-25 17:26:50 -070093 main_thread.attr.guard_size = 0; // The main thread has no guard page.
94 main_thread.attr.stack_size = 0; // User code should never see this; we'll compute it when asked.
95 // TODO: the main thread's sched_policy and sched_priority need to be queried.
Elliott Hughes877ec6d2013-11-15 17:40:18 -080096
Yabin Cui673b15e2015-03-19 14:19:19 -070097 __init_thread(&main_thread);
Elliott Hughes877ec6d2013-11-15 17:40:18 -080098 __init_tls(&main_thread);
99 __set_tls(main_thread.tls);
Yabin Cui8cf1b302014-12-03 21:36:24 -0800100 main_thread.tls[TLS_SLOT_BIONIC_PREINIT] = &args;
Elliott Hughes70b24b12013-11-15 11:51:07 -0800101
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800102 __init_alternate_signal_stack(&main_thread);
Evgeniy Stepanov1a78fbb2012-03-22 18:01:53 +0400103}
104
Elliott Hughes42b2c6a2013-02-07 10:14:39 -0800105void __libc_init_common(KernelArgumentBlock& args) {
106 // Initialize various globals.
107 environ = args.envp;
108 errno = 0;
109 __libc_auxv = args.auxv;
Elliott Hughese4ccf5a2013-02-07 12:06:44 -0800110 __progname = args.argv[0] ? args.argv[0] : "<unknown>";
Elliott Hughes0d787c12013-04-04 13:46:46 -0700111 __abort_message_ptr = args.abort_message_ptr;
Evgeniy Stepanov1a78fbb2012-03-22 18:01:53 +0400112
Elliott Hughes642331b2013-03-06 15:03:53 -0800113 // AT_RANDOM is a pointer to 16 bytes of randomness on the stack.
114 __stack_chk_guard = *reinterpret_cast<uintptr_t*>(getauxval(AT_RANDOM));
115
Elliott Hughes4f251be2012-11-01 16:33:29 -0700116 // Get the main thread from TLS and add it to the thread list.
117 pthread_internal_t* main_thread = __get_thread();
Yabin Cui673b15e2015-03-19 14:19:19 -0700118 __pthread_internal_add(main_thread);
Evgeniy Stepanov1a78fbb2012-03-22 18:01:53 +0400119
Elliott Hughes4f251be2012-11-01 16:33:29 -0700120 __system_properties_init(); // Requires 'environ'.
Elliott Hughes625993d2014-07-15 16:53:13 -0700121
122 __libc_init_vdso();
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800123}
David 'Digit' Turner1df986c2010-10-21 04:16:50 +0200124
Elliott Hughes1801db32015-06-08 18:04:00 -0700125__noreturn static void __early_abort(int line) {
126 // We can't write to stdout or stderr because we're aborting before we've checked that
127 // it's safe for us to use those file descriptors. We probably can't strace either, so
128 // we rely on the fact that if we dereference a low address, either debuggerd or the
129 // kernel's crash dump will show the fault address.
130 *reinterpret_cast<int*>(line) = 0;
131 _exit(EXIT_FAILURE);
132}
133
134// Force any of the closed stdin, stdout and stderr to be associated with /dev/null.
135static void __nullify_closed_stdio() {
136 int dev_null = TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR));
137 if (dev_null == -1) {
138 // init won't have /dev/null available, but SELinux provides an equivalent.
139 dev_null = TEMP_FAILURE_RETRY(open("/sys/fs/selinux/null", O_RDWR));
140 }
141 if (dev_null == -1) {
142 __early_abort(__LINE__);
143 }
144
145 // If any of the stdio file descriptors is valid and not associated
146 // with /dev/null, dup /dev/null to it.
147 for (int i = 0; i < 3; i++) {
148 // If it is /dev/null already, we are done.
149 if (i == dev_null) {
150 continue;
151 }
152
153 // Is this fd already open?
154 int status = TEMP_FAILURE_RETRY(fcntl(i, F_GETFL));
155 if (status != -1) {
156 continue;
157 }
158
159 // The only error we allow is that the file descriptor does not
160 // exist, in which case we dup /dev/null to it.
161 if (errno == EBADF) {
162 // Try dupping /dev/null to this stdio file descriptor and
163 // repeat if there is a signal. Note that any errors in closing
164 // the stdio descriptor are lost.
165 status = TEMP_FAILURE_RETRY(dup2(dev_null, i));
166 if (status == -1) {
167 __early_abort(__LINE__);
168 }
169 } else {
170 __early_abort(__LINE__);
171 }
172 }
173
174 // If /dev/null is not one of the stdio file descriptors, close it.
175 if (dev_null > 2) {
176 if (close(dev_null) == -1) {
177 __early_abort(__LINE__);
178 }
179 }
180}
181
182// Check if the environment variable definition at 'envstr'
183// starts with '<name>=', and if so return the address of the
184// first character after the equal sign. Otherwise return null.
185static const char* env_match(const char* envstr, const char* name) {
186 size_t i = 0;
187
188 while (envstr[i] == name[i] && name[i] != '\0') {
189 ++i;
190 }
191
192 if (name[i] == '\0' && envstr[i] == '=') {
193 return envstr + i + 1;
194 }
195
196 return nullptr;
197}
198
199static bool __is_valid_environment_variable(const char* name) {
200 // According to the kernel source, by default the kernel uses 32*PAGE_SIZE
201 // as the maximum size for an environment variable definition.
202 const int MAX_ENV_LEN = 32*4096;
203
204 if (name == nullptr) {
205 return false;
206 }
207
208 // Parse the string, looking for the first '=' there, and its size.
209 int pos = 0;
210 int first_equal_pos = -1;
211 while (pos < MAX_ENV_LEN) {
212 if (name[pos] == '\0') {
213 break;
214 }
215 if (name[pos] == '=' && first_equal_pos < 0) {
216 first_equal_pos = pos;
217 }
218 pos++;
219 }
220
221 // Check that it's smaller than MAX_ENV_LEN (to detect non-zero terminated strings).
222 if (pos >= MAX_ENV_LEN) {
223 return false;
224 }
225
226 // Check that it contains at least one equal sign that is not the first character
227 if (first_equal_pos < 1) {
228 return false;
229 }
230
231 return true;
232}
233
234static bool __is_unsafe_environment_variable(const char* name) {
235 // None of these should be allowed in setuid programs.
236 static const char* const UNSAFE_VARIABLE_NAMES[] = {
237 "GCONV_PATH",
238 "GETCONF_DIR",
239 "HOSTALIASES",
240 "JE_MALLOC_CONF",
241 "LD_AOUT_LIBRARY_PATH",
242 "LD_AOUT_PRELOAD",
243 "LD_AUDIT",
244 "LD_DEBUG",
245 "LD_DEBUG_OUTPUT",
246 "LD_DYNAMIC_WEAK",
247 "LD_LIBRARY_PATH",
248 "LD_ORIGIN_PATH",
249 "LD_PRELOAD",
250 "LD_PROFILE",
251 "LD_SHOW_AUXV",
252 "LD_USE_LOAD_BIAS",
253 "LOCALDOMAIN",
254 "LOCPATH",
255 "MALLOC_CHECK_",
256 "MALLOC_CONF",
257 "MALLOC_TRACE",
258 "NIS_PATH",
259 "NLSPATH",
260 "RESOLV_HOST_CONF",
261 "RES_OPTIONS",
262 "TMPDIR",
263 "TZDIR",
264 nullptr
265 };
266 for (size_t i = 0; UNSAFE_VARIABLE_NAMES[i] != nullptr; ++i) {
267 if (env_match(name, UNSAFE_VARIABLE_NAMES[i]) != nullptr) {
268 return true;
269 }
270 }
271 return false;
272}
273
274static void __sanitize_environment_variables(char** env) {
275 bool is_AT_SECURE = getauxval(AT_SECURE);
276 char** src = env;
277 char** dst = env;
278 for (; src[0] != nullptr; ++src) {
279 if (!__is_valid_environment_variable(src[0])) {
280 continue;
281 }
282 // Remove various unsafe environment variables if we're loading a setuid program.
283 if (is_AT_SECURE && __is_unsafe_environment_variable(src[0])) {
284 continue;
285 }
286 dst[0] = src[0];
287 ++dst;
288 }
289 dst[0] = nullptr;
290}
291
292void __libc_init_AT_SECURE(KernelArgumentBlock& args) {
293 __libc_auxv = args.auxv;
294
295 // Check that the kernel provided a value for AT_SECURE.
296 bool found_AT_SECURE = false;
297 for (ElfW(auxv_t)* v = __libc_auxv; v->a_type != AT_NULL; ++v) {
298 if (v->a_type == AT_SECURE) {
299 found_AT_SECURE = true;
300 break;
301 }
302 }
303 if (!found_AT_SECURE) __early_abort(__LINE__);
304
305 if (getauxval(AT_SECURE)) {
306 // If this is a setuid/setgid program, close the security hole described in
307 // ftp://ftp.freebsd.org/pub/FreeBSD/CERT/advisories/FreeBSD-SA-02:23.stdio.asc
308 __nullify_closed_stdio();
309
310 __sanitize_environment_variables(args.envp);
311 }
312
313 // Now the environment has been sanitized, make it available.
314 environ = args.envp;
315}
316
David 'Digit' Turner1df986c2010-10-21 04:16:50 +0200317/* This function will be called during normal program termination
318 * to run the destructors that are listed in the .fini_array section
319 * of the executable, if any.
320 *
321 * 'fini_array' points to a list of function addresses. The first
322 * entry in the list has value -1, the last one has value 0.
323 */
Elliott Hughes4f251be2012-11-01 16:33:29 -0700324void __libc_fini(void* array) {
Elliott Hughes8b5df392015-01-21 16:19:07 -0800325 typedef void (*Dtor)();
326 Dtor* fini_array = reinterpret_cast<Dtor*>(array);
327 const Dtor minus1 = reinterpret_cast<Dtor>(static_cast<uintptr_t>(-1));
David 'Digit' Turner1df986c2010-10-21 04:16:50 +0200328
Elliott Hughes8b5df392015-01-21 16:19:07 -0800329 // Sanity check - first entry must be -1.
330 if (array == NULL || fini_array[0] != minus1) {
Elliott Hughes4f251be2012-11-01 16:33:29 -0700331 return;
332 }
333
Elliott Hughes8b5df392015-01-21 16:19:07 -0800334 // Skip over it.
Elliott Hughes4f251be2012-11-01 16:33:29 -0700335 fini_array += 1;
336
Elliott Hughes8b5df392015-01-21 16:19:07 -0800337 // Count the number of destructors.
Elliott Hughes4f251be2012-11-01 16:33:29 -0700338 int count = 0;
339 while (fini_array[count] != NULL) {
340 ++count;
341 }
342
Elliott Hughes8b5df392015-01-21 16:19:07 -0800343 // Now call each destructor in reverse order.
Elliott Hughes4f251be2012-11-01 16:33:29 -0700344 while (count > 0) {
Elliott Hughes8b5df392015-01-21 16:19:07 -0800345 Dtor dtor = fini_array[--count];
Elliott Hughes4f251be2012-11-01 16:33:29 -0700346
Elliott Hughes8b5df392015-01-21 16:19:07 -0800347 // Sanity check, any -1 in the list is ignored.
348 if (dtor == minus1) {
Elliott Hughes4f251be2012-11-01 16:33:29 -0700349 continue;
David 'Digit' Turner1df986c2010-10-21 04:16:50 +0200350 }
351
Elliott Hughes8b5df392015-01-21 16:19:07 -0800352 dtor();
Elliott Hughes4f251be2012-11-01 16:33:29 -0700353 }
Iliyan Malcheve1dd3c22012-05-29 14:22:42 -0700354
355#ifndef LIBC_STATIC
Elliott Hughes4f251be2012-11-01 16:33:29 -0700356 {
357 extern void __libc_postfini(void) __attribute__((weak));
358 if (__libc_postfini) {
359 __libc_postfini();
Iliyan Malcheve1dd3c22012-05-29 14:22:42 -0700360 }
Elliott Hughes4f251be2012-11-01 16:33:29 -0700361 }
Iliyan Malcheve1dd3c22012-05-29 14:22:42 -0700362#endif
David 'Digit' Turner1df986c2010-10-21 04:16:50 +0200363}