blob: dc1fa75503424a8065847f2ab90d5242d24164dd [file] [log] [blame]
Dimitry Ivanov3f660572016-09-09 10:00:39 -07001/*
2 * Copyright (C) 2016 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 "linker_main.h"
30
31#include "linker_debug.h"
Evgenii Stepanov0a3637d2016-07-06 13:20:59 -070032#include "linker_cfi.h"
Dimitry Ivanov3f660572016-09-09 10:00:39 -070033#include "linker_gdb_support.h"
34#include "linker_globals.h"
35#include "linker_phdr.h"
36#include "linker_utils.h"
37
38#include "private/bionic_globals.h"
39#include "private/bionic_tls.h"
40#include "private/KernelArgumentBlock.h"
41
42#include "android-base/strings.h"
43#include "android-base/stringprintf.h"
Dan Willemsen7ec52b12016-11-28 17:02:25 -080044#ifdef __ANDROID__
Josh Gao2a3b4fa2016-10-26 17:55:49 -070045#include "debuggerd/handler.h"
Dan Willemsen7ec52b12016-11-28 17:02:25 -080046#endif
Dimitry Ivanov3f660572016-09-09 10:00:39 -070047
Christopher Ferris7a3681e2017-04-24 17:48:32 -070048#include <async_safe/log.h>
49
Dimitry Ivanov3f660572016-09-09 10:00:39 -070050#include <vector>
51
52extern void __libc_init_globals(KernelArgumentBlock&);
53extern void __libc_init_AT_SECURE(KernelArgumentBlock&);
54
55extern "C" void _start();
56
57static ElfW(Addr) get_elf_exec_load_bias(const ElfW(Ehdr)* elf);
58
59// These should be preserved static to avoid emitting
60// RELATIVE relocations for the part of the code running
61// before linker links itself.
62
63// TODO (dimtiry): remove somain, rename solist to solist_head
64static soinfo* solist;
65static soinfo* sonext;
66static soinfo* somain; // main process, always the one after libdl_info
67
68void solist_add_soinfo(soinfo* si) {
69 sonext->next = si;
70 sonext = si;
71}
72
73bool solist_remove_soinfo(soinfo* si) {
74 soinfo *prev = nullptr, *trav;
75 for (trav = solist; trav != nullptr; trav = trav->next) {
76 if (trav == si) {
77 break;
78 }
79 prev = trav;
80 }
81
82 if (trav == nullptr) {
83 // si was not in solist
84 PRINT("name \"%s\"@%p is not in solist!", si->get_realpath(), si);
85 return false;
86 }
87
88 // prev will never be null, because the first entry in solist is
89 // always the static libdl_info.
George Burgess IV70591002017-06-27 16:23:45 -070090 CHECK(prev != nullptr);
Dimitry Ivanov3f660572016-09-09 10:00:39 -070091 prev->next = si->next;
92 if (si == sonext) {
93 sonext = prev;
94 }
95
96 return true;
97}
98
99soinfo* solist_get_head() {
100 return solist;
101}
102
103soinfo* solist_get_somain() {
104 return somain;
105}
106
107int g_ld_debug_verbosity;
108abort_msg_t* g_abort_message = nullptr; // For debuggerd.
109
110static std::vector<std::string> g_ld_preload_names;
111
112static std::vector<soinfo*> g_ld_preloads;
113
114static void parse_path(const char* path, const char* delimiters,
115 std::vector<std::string>* resolved_paths) {
116 std::vector<std::string> paths;
117 split_path(path, delimiters, &paths);
118 resolve_paths(paths, resolved_paths);
119}
120
121static void parse_LD_LIBRARY_PATH(const char* path) {
122 std::vector<std::string> ld_libary_paths;
123 parse_path(path, ":", &ld_libary_paths);
124 g_default_namespace.set_ld_library_paths(std::move(ld_libary_paths));
125}
126
127static void parse_LD_PRELOAD(const char* path) {
128 g_ld_preload_names.clear();
129 if (path != nullptr) {
130 // We have historically supported ':' as well as ' ' in LD_PRELOAD.
131 g_ld_preload_names = android::base::Split(path, " :");
Josh Gao44f6e182017-10-18 17:25:24 -0700132 g_ld_preload_names.erase(std::remove_if(g_ld_preload_names.begin(), g_ld_preload_names.end(),
Josh Gao27242c62017-10-20 17:45:13 -0700133 [](const std::string& s) { return s.empty(); }),
134 g_ld_preload_names.end());
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700135 }
136}
137
138// An empty list of soinfos
139static soinfo_list_t g_empty_list;
140
dimitryf9abbf62017-07-06 12:17:14 +0200141static void add_vdso(KernelArgumentBlock& args) {
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700142 ElfW(Ehdr)* ehdr_vdso = reinterpret_cast<ElfW(Ehdr)*>(args.getauxval(AT_SYSINFO_EHDR));
143 if (ehdr_vdso == nullptr) {
144 return;
145 }
146
147 soinfo* si = soinfo_alloc(&g_default_namespace, "[vdso]", nullptr, 0, 0);
148
149 si->phdr = reinterpret_cast<ElfW(Phdr)*>(reinterpret_cast<char*>(ehdr_vdso) + ehdr_vdso->e_phoff);
150 si->phnum = ehdr_vdso->e_phnum;
151 si->base = reinterpret_cast<ElfW(Addr)>(ehdr_vdso);
152 si->size = phdr_table_get_load_size(si->phdr, si->phnum);
153 si->load_bias = get_elf_exec_load_bias(ehdr_vdso);
154
155 si->prelink_image();
156 si->link_image(g_empty_list, soinfo_list_t::make_list(si), nullptr);
dimitryc18de1b2017-09-26 14:31:35 +0200157 // prevents accidental unloads...
158 si->set_dt_flags_1(si->get_dt_flags_1() | DF_1_NODELETE);
159 si->set_linked();
160 si->call_constructors();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700161}
162
163/* gdb expects the linker to be in the debug shared object list.
164 * Without this, gdb has trouble locating the linker's ".text"
165 * and ".plt" sections. Gdb could also potentially use this to
166 * relocate the offset of our exported 'rtld_db_dlactivity' symbol.
167 * Note that the linker shouldn't be on the soinfo list.
168 */
Dimitry Ivanovcd510cb2017-05-31 15:07:41 -0700169static link_map linker_link_map;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700170
Dimitry Ivanovcd510cb2017-05-31 15:07:41 -0700171static void init_linker_info_for_gdb(ElfW(Addr) linker_base, char* linker_path) {
172 linker_link_map.l_addr = linker_base;
173 linker_link_map.l_name = linker_path;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700174
175 /*
176 * Set the dynamic field in the link map otherwise gdb will complain with
177 * the following:
178 * warning: .dynamic section for "/system/bin/linker" is not at the
179 * expected address (wrong library or version mismatch?)
180 */
181 ElfW(Ehdr)* elf_hdr = reinterpret_cast<ElfW(Ehdr)*>(linker_base);
182 ElfW(Phdr)* phdr = reinterpret_cast<ElfW(Phdr)*>(linker_base + elf_hdr->e_phoff);
183 phdr_table_get_dynamic_section(phdr, elf_hdr->e_phnum, linker_base,
Dimitry Ivanovcd510cb2017-05-31 15:07:41 -0700184 &linker_link_map.l_ld, nullptr);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700185
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700186}
187
188extern "C" int __system_properties_init(void);
189
190static const char* get_executable_path() {
191 static std::string executable_path;
192 if (executable_path.empty()) {
193 char path[PATH_MAX];
194 ssize_t path_len = readlink("/proc/self/exe", path, sizeof(path));
195 if (path_len == -1 || path_len >= static_cast<ssize_t>(sizeof(path))) {
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700196 async_safe_fatal("readlink('/proc/self/exe') failed: %s", strerror(errno));
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700197 }
198 executable_path = std::string(path, path_len);
199 }
200
201 return executable_path.c_str();
202}
203
Dimitry Ivanovd9e427c2016-11-22 16:55:25 -0800204#if defined(__LP64__)
205static char kLinkerPath[] = "/system/bin/linker64";
206#else
207static char kLinkerPath[] = "/system/bin/linker";
208#endif
209
Elliott Hughesad2d0382017-07-31 11:43:34 -0700210static void __linker_cannot_link(const char* argv0) {
dimitry04f7a792017-09-29 11:52:17 +0200211 async_safe_format_fd(STDERR_FILENO,
212 "CANNOT LINK EXECUTABLE \"%s\": %s\n",
213 argv0,
214 linker_get_error_buffer());
215
216 async_safe_format_log(ANDROID_LOG_FATAL,
217 "linker",
218 "CANNOT LINK EXECUTABLE \"%s\": %s",
219 argv0,
220 linker_get_error_buffer());
221 _exit(EXIT_FAILURE);
Elliott Hughesad2d0382017-07-31 11:43:34 -0700222}
223
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700224/*
225 * This code is called after the linker has linked itself and
226 * fixed it's own GOT. It is safe to make references to externs
227 * and other non-local data at this point.
228 */
Dimitry Ivanovcd510cb2017-05-31 15:07:41 -0700229static ElfW(Addr) __linker_init_post_relocation(KernelArgumentBlock& args) {
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -0800230 ProtectedDataGuard guard;
231
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700232#if TIMING
233 struct timeval t0, t1;
234 gettimeofday(&t0, 0);
235#endif
236
237 // Sanitize the environment.
238 __libc_init_AT_SECURE(args);
239
240 // Initialize system properties
241 __system_properties_init(); // may use 'environ'
242
243 // Register the debuggerd signal handler.
Dan Willemsen7ec52b12016-11-28 17:02:25 -0800244#ifdef __ANDROID__
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700245 debuggerd_callbacks_t callbacks = {
246 .get_abort_message = []() {
247 return g_abort_message;
248 },
249 .post_dump = &notify_gdb_of_libraries,
250 };
251 debuggerd_init(&callbacks);
Dan Willemsen7ec52b12016-11-28 17:02:25 -0800252#endif
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700253
254 g_linker_logger.ResetState();
255
256 // Get a few environment variables.
257 const char* LD_DEBUG = getenv("LD_DEBUG");
258 if (LD_DEBUG != nullptr) {
259 g_ld_debug_verbosity = atoi(LD_DEBUG);
260 }
261
262#if defined(__LP64__)
263 INFO("[ Android dynamic linker (64-bit) ]");
264#else
265 INFO("[ Android dynamic linker (32-bit) ]");
266#endif
267
268 // These should have been sanitized by __libc_init_AT_SECURE, but the test
269 // doesn't cost us anything.
270 const char* ldpath_env = nullptr;
271 const char* ldpreload_env = nullptr;
272 if (!getauxval(AT_SECURE)) {
273 ldpath_env = getenv("LD_LIBRARY_PATH");
274 if (ldpath_env != nullptr) {
275 INFO("[ LD_LIBRARY_PATH set to \"%s\" ]", ldpath_env);
276 }
277 ldpreload_env = getenv("LD_PRELOAD");
278 if (ldpreload_env != nullptr) {
279 INFO("[ LD_PRELOAD set to \"%s\" ]", ldpreload_env);
280 }
281 }
282
283 struct stat file_stat;
284 // Stat "/proc/self/exe" instead of executable_path because
285 // the executable could be unlinked by this point and it should
286 // not cause a crash (see http://b/31084669)
287 if (TEMP_FAILURE_RETRY(stat("/proc/self/exe", &file_stat)) != 0) {
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700288 async_safe_fatal("unable to stat \"/proc/self/exe\": %s", strerror(errno));
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700289 }
290
291 const char* executable_path = get_executable_path();
292 soinfo* si = soinfo_alloc(&g_default_namespace, executable_path, &file_stat, 0, RTLD_GLOBAL);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700293
Elliott Hughes7b0af7a2017-09-15 16:09:22 -0700294 // Bootstrap the link map, the main exe always needs to be first.
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700295 si->set_main_executable();
296 link_map* map = &(si->link_map_head);
297
298 // Register the main executable and the linker upfront to have
299 // gdb aware of them before loading the rest of the dependency
300 // tree.
301 map->l_addr = 0;
302 map->l_name = const_cast<char*>(executable_path);
303 insert_link_map_into_debug_map(map);
Dimitry Ivanovcd510cb2017-05-31 15:07:41 -0700304 insert_link_map_into_debug_map(&linker_link_map);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700305
306 // Extract information passed from the kernel.
307 si->phdr = reinterpret_cast<ElfW(Phdr)*>(args.getauxval(AT_PHDR));
308 si->phnum = args.getauxval(AT_PHNUM);
309
310 /* Compute the value of si->base. We can't rely on the fact that
311 * the first entry is the PHDR because this will not be true
312 * for certain executables (e.g. some in the NDK unit test suite)
313 */
314 si->base = 0;
315 si->size = phdr_table_get_load_size(si->phdr, si->phnum);
316 si->load_bias = 0;
317 for (size_t i = 0; i < si->phnum; ++i) {
318 if (si->phdr[i].p_type == PT_PHDR) {
319 si->load_bias = reinterpret_cast<ElfW(Addr)>(si->phdr) - si->phdr[i].p_vaddr;
320 si->base = reinterpret_cast<ElfW(Addr)>(si->phdr) - si->phdr[i].p_offset;
321 break;
322 }
323 }
George Burgess IV70591002017-06-27 16:23:45 -0700324
325 if (si->base == 0) {
326 async_safe_fatal("Could not find a PHDR: broken executable?");
327 }
328
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700329 si->dynamic = nullptr;
330
331 ElfW(Ehdr)* elf_hdr = reinterpret_cast<ElfW(Ehdr)*>(si->base);
Elliott Hughes3bdb31b2017-01-07 10:38:20 -0800332
333 // We haven't supported non-PIE since Lollipop for security reasons.
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700334 if (elf_hdr->e_type != ET_DYN) {
Elliott Hughesad2d0382017-07-31 11:43:34 -0700335 // We don't use async_safe_fatal here because we don't want a tombstone:
336 // even after several years we still find ourselves on app compatibility
Elliott Hughes3bdb31b2017-01-07 10:38:20 -0800337 // investigations because some app's trying to launch an executable that
338 // hasn't worked in at least three years, and we've "helpfully" dropped a
339 // tombstone for them. The tombstone never provided any detail relevant to
340 // fixing the problem anyway, and the utility of drawing extra attention
341 // to the problem is non-existent at this late date.
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700342 async_safe_format_fd(STDERR_FILENO,
Elliott Hughesad2d0382017-07-31 11:43:34 -0700343 "\"%s\": error: Android 5.0 and later only support "
344 "position-independent executables (-fPIE).\n",
345 g_argv[0]);
Dan Albert95e2e6f2017-01-31 16:02:43 -0800346 exit(EXIT_FAILURE);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700347 }
348
349 // Use LD_LIBRARY_PATH and LD_PRELOAD (but only if we aren't setuid/setgid).
350 parse_LD_LIBRARY_PATH(ldpath_env);
351 parse_LD_PRELOAD(ldpreload_env);
352
353 somain = si;
354
Jiyong Park02586a22017-05-20 01:01:24 +0900355 std::vector<android_namespace_t*> namespaces = init_default_namespaces(executable_path);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700356
Elliott Hughesad2d0382017-07-31 11:43:34 -0700357 if (!si->prelink_image()) __linker_cannot_link(g_argv[0]);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700358
359 // add somain to global group
360 si->set_dt_flags_1(si->get_dt_flags_1() | DF_1_GLOBAL);
Jiyong Park02586a22017-05-20 01:01:24 +0900361 // ... and add it to all other linked namespaces
362 for (auto linked_ns : namespaces) {
363 if (linked_ns != &g_default_namespace) {
364 linked_ns->add_soinfo(somain);
365 somain->add_secondary_namespace(linked_ns);
366 }
367 }
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700368
dimitryc18de1b2017-09-26 14:31:35 +0200369 add_vdso(args);
370
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700371 // Load ld_preloads and dependencies.
372 std::vector<const char*> needed_library_name_list;
373 size_t ld_preloads_count = 0;
374
375 for (const auto& ld_preload_name : g_ld_preload_names) {
376 needed_library_name_list.push_back(ld_preload_name.c_str());
377 ++ld_preloads_count;
378 }
379
380 for_each_dt_needed(si, [&](const char* name) {
381 needed_library_name_list.push_back(name);
382 });
383
384 const char** needed_library_names = &needed_library_name_list[0];
385 size_t needed_libraries_count = needed_library_name_list.size();
386
387 if (needed_libraries_count > 0 &&
Dimitry Ivanov7d429d32017-02-01 15:28:52 -0800388 !find_libraries(&g_default_namespace,
389 si,
390 needed_library_names,
391 needed_libraries_count,
392 nullptr,
393 &g_ld_preloads,
394 ld_preloads_count,
395 RTLD_GLOBAL,
396 nullptr,
397 true /* add_as_children */,
Jiyong Park02586a22017-05-20 01:01:24 +0900398 true /* search_linked_namespaces */,
Jiyong Park02586a22017-05-20 01:01:24 +0900399 &namespaces)) {
Elliott Hughesad2d0382017-07-31 11:43:34 -0700400 __linker_cannot_link(g_argv[0]);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700401 } else if (needed_libraries_count == 0) {
402 if (!si->link_image(g_empty_list, soinfo_list_t::make_list(si), nullptr)) {
Elliott Hughesad2d0382017-07-31 11:43:34 -0700403 __linker_cannot_link(g_argv[0]);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700404 }
405 si->increment_ref_count();
406 }
407
Elliott Hughesad2d0382017-07-31 11:43:34 -0700408 if (!get_cfi_shadow()->InitialLinkDone(solist)) __linker_cannot_link(g_argv[0]);
Evgenii Stepanov0a3637d2016-07-06 13:20:59 -0700409
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -0800410 si->call_pre_init_constructors();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700411
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -0800412 /* After the prelink_image, the si->load_bias is initialized.
413 * For so lib, the map->l_addr will be updated in notify_gdb_of_load.
414 * We need to update this value for so exe here. So Unwind_Backtrace
415 * for some arch like x86 could work correctly within so exe.
416 */
417 map->l_addr = si->load_bias;
418 si->call_constructors();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700419
420#if TIMING
421 gettimeofday(&t1, nullptr);
422 PRINT("LINKER TIME: %s: %d microseconds", g_argv[0], (int) (
423 (((long long)t1.tv_sec * 1000000LL) + (long long)t1.tv_usec) -
424 (((long long)t0.tv_sec * 1000000LL) + (long long)t0.tv_usec)));
425#endif
426#if STATS
427 PRINT("RELO STATS: %s: %d abs, %d rel, %d copy, %d symbol", g_argv[0],
428 linker_stats.count[kRelocAbsolute],
429 linker_stats.count[kRelocRelative],
430 linker_stats.count[kRelocCopy],
431 linker_stats.count[kRelocSymbol]);
432#endif
433#if COUNT_PAGES
434 {
435 unsigned n;
436 unsigned i;
437 unsigned count = 0;
438 for (n = 0; n < 4096; n++) {
439 if (bitmask[n]) {
440 unsigned x = bitmask[n];
441#if defined(__LP64__)
442 for (i = 0; i < 32; i++) {
443#else
444 for (i = 0; i < 8; i++) {
445#endif
446 if (x & 1) {
447 count++;
448 }
449 x >>= 1;
450 }
451 }
452 }
453 PRINT("PAGES MODIFIED: %s: %d (%dKB)", g_argv[0], count, count * 4);
454 }
455#endif
456
457#if TIMING || STATS || COUNT_PAGES
458 fflush(stdout);
459#endif
460
461 ElfW(Addr) entry = args.getauxval(AT_ENTRY);
462 TRACE("[ Ready to execute \"%s\" @ %p ]", si->get_realpath(), reinterpret_cast<void*>(entry));
463 return entry;
464}
465
466/* Compute the load-bias of an existing executable. This shall only
467 * be used to compute the load bias of an executable or shared library
468 * that was loaded by the kernel itself.
469 *
470 * Input:
471 * elf -> address of ELF header, assumed to be at the start of the file.
472 * Return:
473 * load bias, i.e. add the value of any p_vaddr in the file to get
474 * the corresponding address in memory.
475 */
476static ElfW(Addr) get_elf_exec_load_bias(const ElfW(Ehdr)* elf) {
477 ElfW(Addr) offset = elf->e_phoff;
478 const ElfW(Phdr)* phdr_table =
479 reinterpret_cast<const ElfW(Phdr)*>(reinterpret_cast<uintptr_t>(elf) + offset);
480 const ElfW(Phdr)* phdr_end = phdr_table + elf->e_phnum;
481
482 for (const ElfW(Phdr)* phdr = phdr_table; phdr < phdr_end; phdr++) {
483 if (phdr->p_type == PT_LOAD) {
484 return reinterpret_cast<ElfW(Addr)>(elf) + phdr->p_offset - phdr->p_vaddr;
485 }
486 }
487 return 0;
488}
489
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700490/*
491 * This is the entry point for the linker, called from begin.S. This
492 * method is responsible for fixing the linker's own relocations, and
493 * then calling __linker_init_post_relocation().
494 *
495 * Because this method is called before the linker has fixed it's own
496 * relocations, any attempt to reference an extern variable, extern
497 * function, or other GOT reference will generate a segfault.
498 */
499extern "C" ElfW(Addr) __linker_init(void* raw_args) {
500 KernelArgumentBlock args(raw_args);
501
Dimitry Ivanov9b1cc4b2017-03-23 16:17:15 -0700502 // AT_BASE is set to 0 in the case when linker is run by iself
503 // so in order to link the linker it needs to calcuate AT_BASE
504 // using information at hand. The trick below takes advantage
505 // of the fact that the value of linktime_addr before relocations
506 // are run is an offset and this can be used to calculate AT_BASE.
507 static uintptr_t linktime_addr = reinterpret_cast<uintptr_t>(&linktime_addr);
508 ElfW(Addr) linker_addr = reinterpret_cast<uintptr_t>(&linktime_addr) - linktime_addr;
509
George Burgess IV70591002017-06-27 16:23:45 -0700510#if defined(__clang_analyzer__)
511 // The analyzer assumes that linker_addr will always be null. Make it an
512 // unknown value so we don't have to mark N places with NOLINTs.
513 //
514 // (`+=`, rather than `=`, allows us to sidestep a potential "unused store"
515 // complaint)
516 linker_addr += reinterpret_cast<uintptr_t>(raw_args);
517#endif
518
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700519 ElfW(Addr) entry_point = args.getauxval(AT_ENTRY);
520 ElfW(Ehdr)* elf_hdr = reinterpret_cast<ElfW(Ehdr)*>(linker_addr);
521 ElfW(Phdr)* phdr = reinterpret_cast<ElfW(Phdr)*>(linker_addr + elf_hdr->e_phoff);
522
523 soinfo linker_so(nullptr, nullptr, nullptr, 0, 0);
524
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700525 linker_so.base = linker_addr;
526 linker_so.size = phdr_table_get_load_size(phdr, elf_hdr->e_phnum);
527 linker_so.load_bias = get_elf_exec_load_bias(elf_hdr);
528 linker_so.dynamic = nullptr;
529 linker_so.phdr = phdr;
530 linker_so.phnum = elf_hdr->e_phnum;
531 linker_so.set_linker_flag();
532
533 // Prelink the linker so we can access linker globals.
534 if (!linker_so.prelink_image()) __linker_cannot_link(args.argv[0]);
535
536 // This might not be obvious... The reasons why we pass g_empty_list
537 // in place of local_group here are (1) we do not really need it, because
538 // linker is built with DT_SYMBOLIC and therefore relocates its symbols against
539 // itself without having to look into local_group and (2) allocators
540 // are not yet initialized, and therefore we cannot use linked_list.push_*
541 // functions at this point.
542 if (!linker_so.link_image(g_empty_list, g_empty_list, nullptr)) __linker_cannot_link(args.argv[0]);
543
544#if defined(__i386__)
545 // On x86, we can't make system calls before this point.
546 // We can't move this up because this needs to assign to a global.
547 // Note that until we call __libc_init_main_thread below we have
548 // no TLS, so you shouldn't make a system call that can fail, because
549 // it will SEGV when it tries to set errno.
550 __libc_init_sysinfo(args);
551#endif
552
553 // Initialize the main thread (including TLS, so system calls really work).
554 __libc_init_main_thread(args);
555
556 // We didn't protect the linker's RELRO pages in link_image because we
557 // couldn't make system calls on x86 at that point, but we can now...
558 if (!linker_so.protect_relro()) __linker_cannot_link(args.argv[0]);
559
560 // Initialize the linker's static libc's globals
561 __libc_init_globals(args);
562
563 // store argc/argv/envp to use them for calling constructors
564 g_argc = args.argc;
565 g_argv = args.argv;
566 g_envp = args.envp;
567
568 // Initialize the linker's own global variables
569 linker_so.call_constructors();
570
Dimitry Ivanov9b1cc4b2017-03-23 16:17:15 -0700571 // If the linker is not acting as PT_INTERP entry_point is equal to
572 // _start. Which means that the linker is running as an executable and
573 // already linked by PT_INTERP.
574 //
575 // This happens when user tries to run 'adb shell /system/bin/linker'
576 // see also https://code.google.com/p/android/issues/detail?id=63174
577 if (reinterpret_cast<ElfW(Addr)>(&_start) == entry_point) {
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700578 async_safe_format_fd(STDOUT_FILENO,
Dimitry Ivanov9b1cc4b2017-03-23 16:17:15 -0700579 "This is %s, the helper program for dynamic executables.\n",
580 args.argv[0]);
581 exit(0);
582 }
583
Dimitry Ivanovcd510cb2017-05-31 15:07:41 -0700584 init_linker_info_for_gdb(linker_addr, kLinkerPath);
585
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700586 // Initialize static variables. Note that in order to
587 // get correct libdl_info we need to call constructors
588 // before get_libdl_info().
dimitry7abea572017-08-29 18:14:49 +0200589 sonext = solist = get_libdl_info(kLinkerPath, linker_so, linker_link_map);
Dimitry Ivanovd9e427c2016-11-22 16:55:25 -0800590 g_default_namespace.add_soinfo(solist);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700591
592 // We have successfully fixed our own relocations. It's safe to run
593 // the main part of the linker now.
594 args.abort_message_ptr = &g_abort_message;
Dimitry Ivanovcd510cb2017-05-31 15:07:41 -0700595 ElfW(Addr) start_address = __linker_init_post_relocation(args);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700596
597 INFO("[ Jumping to _start (%p)... ]", reinterpret_cast<void*>(start_address));
598
599 // Return the address that the calling assembly stub should jump to.
600 return start_address;
601}