xref: /aosp_15_r20/bionic/libc/bionic/libc_init_dynamic.cpp (revision 8d67ca893c1523eb926b9080dbe4e2ffd2a27ba1)
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 /*
30  * This source files provides two important functions for dynamic
31  * executables:
32  *
33  * - a C runtime initializer (__libc_preinit), which is called by
34  *   the dynamic linker when libc.so is loaded. This happens before
35  *   any other initializer (e.g. static C++ constructors in other
36  *   shared libraries the program depends on).
37  *
38  * - a program launch function (__libc_init), which is called after
39  *   all dynamic linking has been performed.
40  */
41 
42 #include <elf.h>
43 #include <stddef.h>
44 #include <stdint.h>
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include "bionic/pthread_internal.h"
48 #include "libc_init_common.h"
49 
50 #include "private/bionic_defs.h"
51 #include "private/bionic_elf_tls.h"
52 #include "private/bionic_globals.h"
53 #include "platform/bionic/macros.h"
54 #include "private/bionic_ssp.h"
55 #include "private/bionic_tls.h"
56 #include "private/KernelArgumentBlock.h"
57 
58 extern "C" {
59   extern void netdClientInit(void);
60   extern int __cxa_atexit(void (*)(void *), void *, void *);
61 };
62 
memtag_stack_dlopen_callback()63 void memtag_stack_dlopen_callback() {
64   if (__pthread_internal_remap_stack_with_mte()) {
65     async_safe_format_log(ANDROID_LOG_DEBUG, "libc", "remapped stacks as PROT_MTE");
66   }
67 }
68 
69 // Use an initializer so __libc_sysinfo will have a fallback implementation
70 // while .preinit_array constructors run.
71 #if defined(__i386__)
72 __LIBC_HIDDEN__ void* __libc_sysinfo = reinterpret_cast<void*>(__libc_int0x80);
73 #endif
74 
75 extern "C" __attribute__((weak)) void __hwasan_library_loaded(ElfW(Addr) base,
76                                                               const ElfW(Phdr)* phdr,
77                                                               ElfW(Half) phnum);
78 extern "C" __attribute__((weak)) void __hwasan_library_unloaded(ElfW(Addr) base,
79                                                                 const ElfW(Phdr)* phdr,
80                                                                 ElfW(Half) phnum);
81 
82 // We need a helper function for __libc_preinit because compiling with LTO may
83 // inline functions requiring a stack protector check, but __stack_chk_guard is
84 // not initialized at the start of __libc_preinit. __libc_preinit_impl will run
85 // after __stack_chk_guard is initialized and therefore can safely have a stack
86 // protector.
87 __attribute__((noinline))
__libc_preinit_impl()88 static void __libc_preinit_impl() {
89 #if defined(__i386__)
90   __libc_init_sysinfo();
91 #endif
92 
93   // Register libc.so's copy of the TLS generation variable so the linker can
94   // update it when it loads or unloads a shared object.
95   TlsModules& tls_modules = __libc_shared_globals()->tls_modules;
96   tls_modules.generation_libc_so = &__libc_tls_generation_copy;
97   __libc_tls_generation_copy = tls_modules.generation;
98 
99   __libc_init_globals();
100   __libc_init_common();
101   __libc_init_scudo();
102 
103 #if __has_feature(hwaddress_sanitizer)
104   // Notify the HWASan runtime library whenever a library is loaded or unloaded
105   // so that it can update its shadow memory.
106   // This has to happen before _libc_init_malloc which might dlopen to load
107   // profiler libraries.
108   __libc_shared_globals()->load_hook = __hwasan_library_loaded;
109   __libc_shared_globals()->unload_hook = __hwasan_library_unloaded;
110 #endif
111 
112   // Hooks for various libraries to let them know that we're starting up.
113   __libc_globals.mutate(__libc_init_malloc);
114 
115   // Install reserved signal handlers for assisting the platform's profilers.
116   __libc_init_profiling_handlers();
117 
118   __libc_init_fork_handler();
119 
120   __libc_shared_globals()->set_target_sdk_version_hook = __libc_set_target_sdk_version;
121 
122   netdClientInit();
123 }
124 
125 // We flag the __libc_preinit function as a constructor to ensure that
126 // its address is listed in libc.so's .init_array section.
127 // This ensures that the function is called by the dynamic linker as
128 // soon as the shared library is loaded.
129 // We give this constructor priority 1 because we want libc's constructor
130 // to run before any others (such as the jemalloc constructor), and lower
131 // is better (http://b/68046352).
__libc_preinit()132 __attribute__((constructor(1))) static void __libc_preinit() {
133   // The linker has initialized its copy of the global stack_chk_guard, and filled in the main
134   // thread's TLS slot with that value. Initialize the local global stack guard with its value.
135   __stack_chk_guard = reinterpret_cast<uintptr_t>(__get_tls()[TLS_SLOT_STACK_GUARD]);
136 
137   __libc_preinit_impl();
138 }
139 
140 // This function is called from the executable's _start entry point
141 // (see arch-$ARCH/bionic/crtbegin.c), which is itself called by the dynamic
142 // linker after it has loaded all shared libraries the executable depends on.
143 //
144 // Note that the dynamic linker has also run all constructors in the
145 // executable at this point.
__libc_init(void * raw_args,void (* onexit)(void)__unused,int (* slingshot)(int,char **,char **),structors_array_t const * const structors)146 __noreturn void __libc_init(void* raw_args,
147                             void (*onexit)(void) __unused,
148                             int (*slingshot)(int, char**, char**),
149                             structors_array_t const * const structors) {
150   BIONIC_STOP_UNWIND;
151 
152   KernelArgumentBlock args(raw_args);
153 
154   // Several Linux ABIs don't pass the onexit pointer, and the ones that
155   // do never use it.  Therefore, we ignore it.
156 
157   // The executable may have its own destructors listed in its .fini_array
158   // so we need to ensure that these are called when the program exits
159   // normally.
160   if (structors->fini_array) {
161     __cxa_atexit(__libc_fini,structors->fini_array,nullptr);
162   }
163 
164   __libc_init_mte_late();
165 
166   // This roundabout way is needed so we don't use the static libc linked into the linker, which
167   // will not affect the process.
168   __libc_shared_globals()->memtag_stack_dlopen_callback = memtag_stack_dlopen_callback;
169 
170   exit(slingshot(args.argc - __libc_shared_globals()->initial_linker_arg_count,
171                  args.argv + __libc_shared_globals()->initial_linker_arg_count,
172                  args.envp));
173 }
174 
175 extern "C" libc_shared_globals* __loader_shared_globals();
176 
__libc_shared_globals()177 __LIBC_HIDDEN__ libc_shared_globals* __libc_shared_globals() {
178   return __loader_shared_globals();
179 }
180