1 /*
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 
29 #include <android/api-level.h>
30 #include <elf.h>
31 #include <errno.h>
32 #include <stddef.h>
33 #include <stdint.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <sys/auxv.h>
37 #include <sys/mman.h>
38 
39 #include "libc_init_common.h"
40 #include "pthread_internal.h"
41 
42 #include "platform/bionic/macros.h"
43 #include "platform/bionic/mte.h"
44 #include "platform/bionic/page.h"
45 #include "private/KernelArgumentBlock.h"
46 #include "private/bionic_asm.h"
47 #include "private/bionic_asm_note.h"
48 #include "private/bionic_call_ifunc_resolver.h"
49 #include "private/bionic_elf_tls.h"
50 #include "private/bionic_globals.h"
51 #include "private/bionic_tls.h"
52 #include "sys/system_properties.h"
53 
54 #if __has_feature(hwaddress_sanitizer)
55 #include <sanitizer/hwasan_interface.h>
56 #endif
57 
58 // Leave the variable uninitialized for the sake of the dynamic loader, which
59 // links in this file. The loader will initialize this variable before
60 // relocating itself.
61 #if defined(__i386__)
62 __LIBC_HIDDEN__ void* __libc_sysinfo;
63 #endif
64 
65 extern "C" int __cxa_atexit(void (*)(void *), void *, void *);
66 extern "C" const char* __gnu_basename(const char* path);
67 
call_array(init_func_t ** list,int argc,char * argv[],char * envp[])68 static void call_array(init_func_t** list, int argc, char* argv[], char* envp[]) {
69   // First element is -1, list is null-terminated
70   while (*++list) {
71     (*list)(argc, argv, envp);
72   }
73 }
74 
75 #if defined(__aarch64__) || defined(__x86_64__)
76 extern __LIBC_HIDDEN__ __attribute__((weak)) ElfW(Rela) __rela_iplt_start[], __rela_iplt_end[];
77 
call_ifunc_resolvers()78 static void call_ifunc_resolvers() {
79   if (__rela_iplt_start == nullptr || __rela_iplt_end == nullptr) {
80     // These symbols are not emitted by gold. Gold has code to do so, but for
81     // whatever reason it is not being run. In these cases ifuncs cannot be
82     // resolved, so we do not support using ifuncs in static executables linked
83     // with gold.
84     //
85     // Since they are weak, they will be non-null when linked with bfd/lld and
86     // null when linked with gold.
87     return;
88   }
89 
90   for (ElfW(Rela) *r = __rela_iplt_start; r != __rela_iplt_end; ++r) {
91     ElfW(Addr)* offset = reinterpret_cast<ElfW(Addr)*>(r->r_offset);
92     ElfW(Addr) resolver = r->r_addend;
93     *offset = __bionic_call_ifunc_resolver(resolver);
94   }
95 }
96 #else
97 extern __LIBC_HIDDEN__ __attribute__((weak)) ElfW(Rel) __rel_iplt_start[], __rel_iplt_end[];
98 
call_ifunc_resolvers()99 static void call_ifunc_resolvers() {
100   if (__rel_iplt_start == nullptr || __rel_iplt_end == nullptr) {
101     // These symbols are not emitted by gold. Gold has code to do so, but for
102     // whatever reason it is not being run. In these cases ifuncs cannot be
103     // resolved, so we do not support using ifuncs in static executables linked
104     // with gold.
105     //
106     // Since they are weak, they will be non-null when linked with bfd/lld and
107     // null when linked with gold.
108     return;
109   }
110 
111   for (ElfW(Rel) *r = __rel_iplt_start; r != __rel_iplt_end; ++r) {
112     ElfW(Addr)* offset = reinterpret_cast<ElfW(Addr)*>(r->r_offset);
113     ElfW(Addr) resolver = *offset;
114     *offset = __bionic_call_ifunc_resolver(resolver);
115   }
116 }
117 #endif
118 
apply_gnu_relro()119 static void apply_gnu_relro() {
120   ElfW(Phdr)* phdr_start = reinterpret_cast<ElfW(Phdr)*>(getauxval(AT_PHDR));
121   unsigned long int phdr_ct = getauxval(AT_PHNUM);
122 
123   for (ElfW(Phdr)* phdr = phdr_start; phdr < (phdr_start + phdr_ct); phdr++) {
124     if (phdr->p_type != PT_GNU_RELRO) {
125       continue;
126     }
127 
128     ElfW(Addr) seg_page_start = PAGE_START(phdr->p_vaddr);
129     ElfW(Addr) seg_page_end = PAGE_END(phdr->p_vaddr + phdr->p_memsz);
130 
131     // Check return value here? What do we do if we fail?
132     mprotect(reinterpret_cast<void*>(seg_page_start), seg_page_end - seg_page_start, PROT_READ);
133   }
134 }
135 
layout_static_tls(KernelArgumentBlock & args)136 static void layout_static_tls(KernelArgumentBlock& args) {
137   StaticTlsLayout& layout = __libc_shared_globals()->static_tls_layout;
138   layout.reserve_bionic_tls();
139 
140   const char* progname = args.argv[0];
141   ElfW(Phdr)* phdr_start = reinterpret_cast<ElfW(Phdr)*>(getauxval(AT_PHDR));
142   size_t phdr_ct = getauxval(AT_PHNUM);
143 
144   static TlsModule mod;
145   TlsModules& modules = __libc_shared_globals()->tls_modules;
146   if (__bionic_get_tls_segment(phdr_start, phdr_ct, 0, &mod.segment)) {
147     if (!__bionic_check_tls_alignment(&mod.segment.alignment)) {
148       async_safe_fatal("error: TLS segment alignment in \"%s\" is not a power of 2: %zu\n",
149                        progname, mod.segment.alignment);
150     }
151     mod.static_offset = layout.reserve_exe_segment_and_tcb(&mod.segment, progname);
152     mod.first_generation = kTlsGenerationFirst;
153 
154     modules.module_count = 1;
155     modules.static_module_count = 1;
156     modules.module_table = &mod;
157   } else {
158     layout.reserve_exe_segment_and_tcb(nullptr, progname);
159   }
160   // Enable the fast path in __tls_get_addr.
161   __libc_tls_generation_copy = modules.generation;
162 
163   layout.finish_layout();
164 }
165 
166 // Get the presiding config string, in the following order of priority:
167 //   1. Environment variables.
168 //   2. System properties, in the order they're specified in sys_prop_names.
169 // If neither of these options are specified, this function returns false.
170 // Otherwise, it returns true, and the presiding options string is written to
171 // the `options` buffer of size `size`. If this function returns true, `options`
172 // is guaranteed to be null-terminated. `options_size` should be at least
173 // PROP_VALUE_MAX.
get_config_from_env_or_sysprops(const char * env_var_name,const char * const * sys_prop_names,size_t sys_prop_names_size,char * options,size_t options_size)174 bool get_config_from_env_or_sysprops(const char* env_var_name, const char* const* sys_prop_names,
175                                      size_t sys_prop_names_size, char* options,
176                                      size_t options_size) {
177   const char* env = getenv(env_var_name);
178   if (env && *env != '\0') {
179     strncpy(options, env, options_size);
180     options[options_size - 1] = '\0'; // Ensure null-termination.
181     return true;
182   }
183 
184   for (size_t i = 0; i < sys_prop_names_size; ++i) {
185     if (__system_property_get(sys_prop_names[i], options) && *options != '\0') return true;
186   }
187   return false;
188 }
189 
190 #ifdef __aarch64__
__read_memtag_note(const ElfW (Nhdr)* note,const char * name,const char * desc,unsigned * result)191 static bool __read_memtag_note(const ElfW(Nhdr)* note, const char* name, const char* desc,
192                                unsigned* result) {
193   if (note->n_namesz != 8 || strncmp(name, "Android", 8) != 0) {
194     return false;
195   }
196   if (note->n_type != NT_TYPE_MEMTAG) {
197     return false;
198   }
199   if (note->n_descsz != 4) {
200     async_safe_fatal("unrecognized android.memtag note: n_descsz = %d, expected 4", note->n_descsz);
201   }
202   *result = *reinterpret_cast<const ElfW(Word)*>(desc);
203   return true;
204 }
205 
__get_memtag_note(const ElfW (Phdr)* phdr_start,size_t phdr_ct,const ElfW (Addr)load_bias)206 static unsigned __get_memtag_note(const ElfW(Phdr)* phdr_start, size_t phdr_ct,
207                                   const ElfW(Addr) load_bias) {
208   for (size_t i = 0; i < phdr_ct; ++i) {
209     const ElfW(Phdr)* phdr = &phdr_start[i];
210     if (phdr->p_type != PT_NOTE) {
211       continue;
212     }
213     ElfW(Addr) p = load_bias + phdr->p_vaddr;
214     ElfW(Addr) note_end = load_bias + phdr->p_vaddr + phdr->p_memsz;
215     while (p + sizeof(ElfW(Nhdr)) <= note_end) {
216       const ElfW(Nhdr)* note = reinterpret_cast<const ElfW(Nhdr)*>(p);
217       p += sizeof(ElfW(Nhdr));
218       const char* name = reinterpret_cast<const char*>(p);
219       p += align_up(note->n_namesz, 4);
220       const char* desc = reinterpret_cast<const char*>(p);
221       p += align_up(note->n_descsz, 4);
222       if (p > note_end) {
223         break;
224       }
225       unsigned ret;
226       if (__read_memtag_note(note, name, desc, &ret)) {
227         return ret;
228       }
229     }
230   }
231   return 0;
232 }
233 
234 // Returns true if there's an environment setting (either sysprop or env var)
235 // that should overwrite the ELF note, and places the equivalent heap tagging
236 // level into *level.
get_environment_memtag_setting(HeapTaggingLevel * level)237 static bool get_environment_memtag_setting(HeapTaggingLevel* level) {
238   static const char kMemtagPrognameSyspropPrefix[] = "arm64.memtag.process.";
239 
240   const char* progname = __libc_shared_globals()->init_progname;
241   if (progname == nullptr) return false;
242 
243   const char* basename = __gnu_basename(progname);
244 
245   static constexpr size_t kOptionsSize = PROP_VALUE_MAX;
246   char options_str[kOptionsSize];
247   size_t sysprop_size = strlen(basename) + strlen(kMemtagPrognameSyspropPrefix) + 1;
248   char* sysprop_name = static_cast<char*>(alloca(sysprop_size));
249 
250   async_safe_format_buffer(sysprop_name, sysprop_size, "%s%s", kMemtagPrognameSyspropPrefix,
251                            basename);
252 
253   if (!get_config_from_env_or_sysprops("MEMTAG_OPTIONS", &sysprop_name,
254                                        /* sys_prop_names_size */ 1, options_str, kOptionsSize)) {
255     return false;
256   }
257 
258   if (strcmp("sync", options_str) == 0) {
259     *level = M_HEAP_TAGGING_LEVEL_SYNC;
260   } else if (strcmp("async", options_str) == 0) {
261     *level = M_HEAP_TAGGING_LEVEL_ASYNC;
262   } else if (strcmp("off", options_str) == 0) {
263     *level = M_HEAP_TAGGING_LEVEL_TBI;
264   } else {
265     async_safe_format_log(
266         ANDROID_LOG_ERROR, "libc",
267         "unrecognized memtag level: \"%s\" (options are \"sync\", \"async\", or \"off\").",
268         options_str);
269     return false;
270   }
271 
272   return true;
273 }
274 
275 // Returns the initial heap tagging level. Note: This function will never return
276 // M_HEAP_TAGGING_LEVEL_NONE, if MTE isn't enabled for this process we enable
277 // M_HEAP_TAGGING_LEVEL_TBI.
__get_heap_tagging_level(const void * phdr_start,size_t phdr_ct,uintptr_t load_bias)278 static HeapTaggingLevel __get_heap_tagging_level(const void* phdr_start, size_t phdr_ct,
279                                                  uintptr_t load_bias) {
280   HeapTaggingLevel level;
281   if (get_environment_memtag_setting(&level)) return level;
282 
283   unsigned note_val =
284       __get_memtag_note(reinterpret_cast<const ElfW(Phdr)*>(phdr_start), phdr_ct, load_bias);
285   if (note_val & ~(NT_MEMTAG_LEVEL_MASK | NT_MEMTAG_HEAP)) {
286     async_safe_fatal("unrecognized android.memtag note: desc = %d", note_val);
287   }
288 
289   if (!(note_val & NT_MEMTAG_HEAP)) return M_HEAP_TAGGING_LEVEL_TBI;
290 
291   unsigned memtag_level = note_val & NT_MEMTAG_LEVEL_MASK;
292   switch (memtag_level) {
293     case NT_MEMTAG_LEVEL_ASYNC:
294       return M_HEAP_TAGGING_LEVEL_ASYNC;
295     case NT_MEMTAG_LEVEL_DEFAULT:
296     case NT_MEMTAG_LEVEL_SYNC:
297       return M_HEAP_TAGGING_LEVEL_SYNC;
298     default:
299       async_safe_fatal("unrecognized android.memtag note: level = %d", memtag_level);
300   }
301 }
302 
303 // Figure out the desired memory tagging mode (sync/async, heap/globals/stack) for this executable.
304 // This function is called from the linker before the main executable is relocated.
__libc_init_mte(const void * phdr_start,size_t phdr_ct,uintptr_t load_bias)305 __attribute__((no_sanitize("hwaddress", "memtag"))) void __libc_init_mte(const void* phdr_start,
306                                                                          size_t phdr_ct,
307                                                                          uintptr_t load_bias) {
308   HeapTaggingLevel level = __get_heap_tagging_level(phdr_start, phdr_ct, load_bias);
309 
310   if (level == M_HEAP_TAGGING_LEVEL_SYNC || level == M_HEAP_TAGGING_LEVEL_ASYNC) {
311     unsigned long prctl_arg = PR_TAGGED_ADDR_ENABLE | PR_MTE_TAG_SET_NONZERO;
312     prctl_arg |= (level == M_HEAP_TAGGING_LEVEL_SYNC) ? PR_MTE_TCF_SYNC : PR_MTE_TCF_ASYNC;
313 
314     // When entering ASYNC mode, specify that we want to allow upgrading to SYNC by OR'ing in the
315     // SYNC flag. But if the kernel doesn't support specifying multiple TCF modes, fall back to
316     // specifying a single mode.
317     if (prctl(PR_SET_TAGGED_ADDR_CTRL, prctl_arg | PR_MTE_TCF_SYNC, 0, 0, 0) == 0 ||
318         prctl(PR_SET_TAGGED_ADDR_CTRL, prctl_arg, 0, 0, 0) == 0) {
319       __libc_shared_globals()->initial_heap_tagging_level = level;
320       return;
321     }
322   }
323 
324   // MTE was either not enabled, or wasn't supported on this device. Try and use
325   // TBI.
326   if (prctl(PR_SET_TAGGED_ADDR_CTRL, PR_TAGGED_ADDR_ENABLE, 0, 0, 0) == 0) {
327     __libc_shared_globals()->initial_heap_tagging_level = M_HEAP_TAGGING_LEVEL_TBI;
328   }
329 }
330 #else   // __aarch64__
__libc_init_mte(const void *,size_t,uintptr_t)331 void __libc_init_mte(const void*, size_t, uintptr_t) {}
332 #endif  // __aarch64__
333 
__real_libc_init(void * raw_args,void (* onexit)(void)__unused,int (* slingshot)(int,char **,char **),structors_array_t const * const structors,bionic_tcb * temp_tcb)334 __noreturn static void __real_libc_init(void *raw_args,
335                                         void (*onexit)(void) __unused,
336                                         int (*slingshot)(int, char**, char**),
337                                         structors_array_t const * const structors,
338                                         bionic_tcb* temp_tcb) {
339   BIONIC_STOP_UNWIND;
340 
341   // Initialize TLS early so system calls and errno work.
342   KernelArgumentBlock args(raw_args);
343   __libc_init_main_thread_early(args, temp_tcb);
344   __libc_init_main_thread_late();
345   __libc_init_globals();
346   __libc_shared_globals()->init_progname = args.argv[0];
347   __libc_init_AT_SECURE(args.envp);
348   layout_static_tls(args);
349   __libc_init_main_thread_final();
350   __libc_init_common();
351   __libc_init_mte(reinterpret_cast<ElfW(Phdr)*>(getauxval(AT_PHDR)), getauxval(AT_PHNUM),
352                   /*load_bias = */ 0);
353   __libc_init_scudo();
354   __libc_init_fork_handler();
355 
356   call_ifunc_resolvers();
357   apply_gnu_relro();
358 
359   // Several Linux ABIs don't pass the onexit pointer, and the ones that
360   // do never use it.  Therefore, we ignore it.
361 
362   call_array(structors->preinit_array, args.argc, args.argv, args.envp);
363   call_array(structors->init_array, args.argc, args.argv, args.envp);
364 
365   // The executable may have its own destructors listed in its .fini_array
366   // so we need to ensure that these are called when the program exits
367   // normally.
368   if (structors->fini_array != nullptr) {
369     __cxa_atexit(__libc_fini,structors->fini_array,nullptr);
370   }
371 
372   exit(slingshot(args.argc, args.argv, args.envp));
373 }
374 
375 extern "C" void __hwasan_init_static();
376 
377 // This __libc_init() is only used for static executables, and is called from crtbegin.c.
378 //
379 // The 'structors' parameter contains pointers to various initializer
380 // arrays that must be run before the program's 'main' routine is launched.
381 __attribute__((no_sanitize("hwaddress")))
__libc_init(void * raw_args,void (* onexit)(void)__unused,int (* slingshot)(int,char **,char **),structors_array_t const * const structors)382 __noreturn void __libc_init(void* raw_args,
383                             void (*onexit)(void) __unused,
384                             int (*slingshot)(int, char**, char**),
385                             structors_array_t const * const structors) {
386   bionic_tcb temp_tcb = {};
387 #if __has_feature(hwaddress_sanitizer)
388   // Install main thread TLS early. It will be initialized later in __libc_init_main_thread. For now
389   // all we need is access to TLS_SLOT_SANITIZER.
390   __set_tls(&temp_tcb.tls_slot(0));
391   // Initialize HWASan enough to run instrumented code. This sets up TLS_SLOT_SANITIZER, among other
392   // things.
393   __hwasan_init_static();
394   // We are ready to run HWASan-instrumented code, proceed with libc initialization...
395 #endif
396   __real_libc_init(raw_args, onexit, slingshot, structors, &temp_tcb);
397 }
398 
399 static int g_target_sdk_version{__ANDROID_API__};
400 
android_get_application_target_sdk_version()401 extern "C" int android_get_application_target_sdk_version() {
402   return g_target_sdk_version;
403 }
404 
android_set_application_target_sdk_version(int target)405 extern "C" void android_set_application_target_sdk_version(int target) {
406   g_target_sdk_version = target;
407   __libc_set_target_sdk_version(target);
408 }
409 
410 // This function is called in the dynamic linker before ifunc resolvers have run, so this file is
411 // compiled with -ffreestanding to avoid implicit string.h function calls. (It shouldn't strictly
412 // be necessary, though.)
__libc_shared_globals()413 __LIBC_HIDDEN__ libc_shared_globals* __libc_shared_globals() {
414   static libc_shared_globals globals;
415   return &globals;
416 }
417