blob: e5450c7b99cb4fd8b7101f554c76515aad4a0c9d [file] [log] [blame]
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001/*
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07002 * Copyright (C) 2008 The Android Open Source Project
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08003 * 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
Dmitriy Ivanov19133522015-06-02 17:36:54 -070029#include <android/api-level.h>
Elliott Hughes46882792012-08-03 16:49:39 -070030#include <errno.h>
31#include <fcntl.h>
Elliott Hughes0266ae52014-02-10 17:46:57 -080032#include <inttypes.h>
Elliott Hughes46882792012-08-03 16:49:39 -070033#include <pthread.h>
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080034#include <stdio.h>
35#include <stdlib.h>
36#include <string.h>
Elliott Hughes46882792012-08-03 16:49:39 -070037#include <sys/mman.h>
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -080038#include <sys/param.h>
Dimitry Ivanovbf34ba32017-04-21 13:12:05 -070039#include <sys/vfs.h>
Elliott Hughes46882792012-08-03 16:49:39 -070040#include <unistd.h>
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080041
Dmitriy Ivanov0d150942014-08-22 12:25:04 -070042#include <new>
Dmitriy Ivanovd165f562015-03-23 18:43:02 -070043#include <string>
Dmitriy Ivanovb4827502015-09-28 16:38:31 -070044#include <unordered_map>
Dmitriy Ivanovd165f562015-03-23 18:43:02 -070045#include <vector>
Dmitriy Ivanov0d150942014-08-22 12:25:04 -070046
Logan Chienbcfe3cf2018-05-08 20:17:26 +080047#include <android-base/properties.h>
Tom Cherryb8ab6182017-04-05 16:20:29 -070048#include <android-base/scopeguard.h>
Christopher Ferris7a3681e2017-04-24 17:48:32 -070049#include <async_safe/log.h>
Ryan Pricharda2e83ab2019-08-16 17:25:43 -070050#include <bionic/pthread_internal.h>
Christopher Ferris7a3681e2017-04-24 17:48:32 -070051
Elliott Hughes46882792012-08-03 16:49:39 -070052// Private C library headers.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080053
54#include "linker.h"
Dmitriy Ivanovc9ce70d2015-03-10 15:30:26 -070055#include "linker_block_allocator.h"
Evgenii Stepanov0a3637d2016-07-06 13:20:59 -070056#include "linker_cfi.h"
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -080057#include "linker_config.h"
Dimitry Ivanov6b788ee2016-02-17 16:08:03 -080058#include "linker_gdb_support.h"
Dimitry Ivanov48ec2882016-08-04 11:50:36 -070059#include "linker_globals.h"
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080060#include "linker_debug.h"
Dimitry Ivanov769b33f2016-07-21 11:33:40 -070061#include "linker_dlwarning.h"
Dimitry Ivanov3f660572016-09-09 10:00:39 -070062#include "linker_main.h"
Dimitry Ivanovb943f302016-08-03 16:00:10 -070063#include "linker_namespaces.h"
Dmitriy Ivanov18870d32015-04-22 13:10:04 -070064#include "linker_sleb128.h"
David 'Digit' Turner23363ed2012-06-18 18:13:49 +020065#include "linker_phdr.h"
Ryan Prichard339ecef2020-01-02 16:36:06 -080066#include "linker_relocate.h"
Ryan Pricharde5e69e02019-01-01 18:53:48 -080067#include "linker_tls.h"
Victor Khimenko01790fd2020-05-12 22:59:04 +020068#include "linker_translate_path.h"
Dmitriy Ivanova1feb112015-10-01 18:41:57 -070069#include "linker_utils.h"
tony.ys_liub4474402015-07-29 18:00:22 +080070
Peter Collingbournee9491952019-10-28 10:57:26 -070071#include "private/bionic_call_ifunc_resolver.h"
Ryan Pricharde5e69e02019-01-01 18:53:48 -080072#include "private/bionic_globals.h"
dimitryfe1b27c2017-08-11 14:43:21 +020073#include "android-base/macros.h"
Elliott Hughes939a7e02015-12-04 15:27:46 -080074#include "android-base/strings.h"
Dimitry Ivanovb996d602016-07-11 18:11:39 -070075#include "android-base/stringprintf.h"
Simon Baldwinaef71952015-01-16 13:22:54 +000076#include "ziparchive/zip_archive.h"
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080077
dimitry06016f22018-01-05 11:39:28 +010078static std::unordered_map<void*, size_t> g_dso_handle_counters;
79
Jiyong Park25bedfd2019-05-16 21:00:39 +090080static bool g_anonymous_namespace_set = false;
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -070081static android_namespace_t* g_anonymous_namespace = &g_default_namespace;
Jiyong Park01de74e2017-04-03 23:10:37 +090082static std::unordered_map<std::string, android_namespace_t*> g_exported_namespaces;
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -070083
Dmitriy Ivanov600bc3c2015-03-10 15:43:50 -070084static LinkerTypeAllocator<soinfo> g_soinfo_allocator;
85static LinkerTypeAllocator<LinkedListEntry<soinfo>> g_soinfo_links_allocator;
Magnus Malmbornba98d922012-09-12 13:00:55 +020086
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -070087static LinkerTypeAllocator<android_namespace_t> g_namespace_allocator;
Dimitry Ivanovaca299a2016-04-11 12:42:58 -070088static LinkerTypeAllocator<LinkedListEntry<android_namespace_t>> g_namespace_list_allocator;
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -070089
Ryan Pricharda2e83ab2019-08-16 17:25:43 -070090static uint64_t g_module_load_counter = 0;
91static uint64_t g_module_unload_counter = 0;
92
dimitryfe1b27c2017-08-11 14:43:21 +020093static const char* const kLdConfigArchFilePath = "/system/etc/ld.config." ABI_STRING ".txt";
94
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -080095static const char* const kLdConfigFilePath = "/system/etc/ld.config.txt";
Roland Levillain09bde952019-10-29 19:17:49 +000096static const char* const kLdConfigVndkLiteFilePath = "/system/etc/ld.config.vndk_lite.txt";
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -080097
Kiyoung Kim1a2460d2019-11-22 14:38:25 +090098static const char* const kLdGeneratedConfigFilePath = "/linkerconfig/ld.config.txt";
Kiyoung Kim35e3b4b2019-08-07 19:24:13 +090099
Elliott Hughes4eeb1f12013-10-25 17:38:02 -0700100#if defined(__LP64__)
Victor Chang6cb719f2019-02-06 17:19:10 +0000101static const char* const kSystemLibDir = "/system/lib64";
102static const char* const kOdmLibDir = "/odm/lib64";
103static const char* const kVendorLibDir = "/vendor/lib64";
104static const char* const kAsanSystemLibDir = "/data/asan/system/lib64";
105static const char* const kAsanOdmLibDir = "/data/asan/odm/lib64";
106static const char* const kAsanVendorLibDir = "/data/asan/vendor/lib64";
Elliott Hughes011bc0b2013-10-08 14:27:10 -0700107#else
Victor Chang6cb719f2019-02-06 17:19:10 +0000108static const char* const kSystemLibDir = "/system/lib";
109static const char* const kOdmLibDir = "/odm/lib";
110static const char* const kVendorLibDir = "/vendor/lib";
111static const char* const kAsanSystemLibDir = "/data/asan/system/lib";
112static const char* const kAsanOdmLibDir = "/data/asan/odm/lib";
113static const char* const kAsanVendorLibDir = "/data/asan/vendor/lib";
Elliott Hughes011bc0b2013-10-08 14:27:10 -0700114#endif
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700115
Vishwath Mohan4113def2017-03-29 15:31:34 -0700116static const char* const kAsanLibDirPrefix = "/data/asan";
117
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700118static const char* const kDefaultLdPaths[] = {
119 kSystemLibDir,
Alin Jerpelea074a9fd2017-09-25 17:47:49 +0200120 kOdmLibDir,
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700121 kVendorLibDir,
Dmitriy Ivanov851135b2014-08-29 12:02:36 -0700122 nullptr
Elliott Hughes124fae92012-10-31 14:20:03 -0700123};
David Bartleybc3a5c22009-06-02 18:27:28 -0700124
Evgenii Stepanovd640b222015-07-10 17:54:01 -0700125static const char* const kAsanDefaultLdPaths[] = {
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700126 kAsanSystemLibDir,
127 kSystemLibDir,
Alin Jerpelea074a9fd2017-09-25 17:47:49 +0200128 kAsanOdmLibDir,
129 kOdmLibDir,
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700130 kAsanVendorLibDir,
131 kVendorLibDir,
Evgenii Stepanovd640b222015-07-10 17:54:01 -0700132 nullptr
133};
134
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700135// Is ASAN enabled?
136static bool g_is_asan = false;
137
Evgenii Stepanov0a3637d2016-07-06 13:20:59 -0700138static CFIShadowWriter g_cfi_shadow;
139
140CFIShadowWriter* get_cfi_shadow() {
141 return &g_cfi_shadow;
142}
143
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700144static bool is_system_library(const std::string& realpath) {
145 for (const auto& dir : g_default_namespace.get_default_library_paths()) {
146 if (file_is_in_dir(realpath, dir)) {
147 return true;
148 }
149 }
150 return false;
151}
152
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700153// Checks if the file exists and not a directory.
154static bool file_exists(const char* path) {
Dimitry Ivanov4cf70242016-08-11 11:11:52 -0700155 struct stat s;
156
157 if (stat(path, &s) != 0) {
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700158 return false;
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700159 }
Dimitry Ivanov4cf70242016-08-11 11:11:52 -0700160
161 return S_ISREG(s.st_mode);
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700162}
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700163
Dimitry Ivanov35c8e3b2017-02-27 12:17:47 -0800164static std::string resolve_soname(const std::string& name) {
165 // We assume that soname equals to basename here
166
167 // TODO(dimitry): consider having honest absolute-path -> soname resolution
168 // note that since we might end up refusing to load this library because
169 // it is not in shared libs list we need to get the soname without actually loading
170 // the library.
171 //
172 // On the other hand there are several places where we already assume that
173 // soname == basename in particular for any not-loaded library mentioned
174 // in DT_NEEDED list.
175 return basename(name.c_str());
176}
177
178static bool maybe_accessible_via_namespace_links(android_namespace_t* ns, const char* name) {
179 std::string soname = resolve_soname(name);
180 for (auto& ns_link : ns->linked_namespaces()) {
181 if (ns_link.is_accessible(soname.c_str())) {
182 return true;
183 }
184 }
185
186 return false;
187}
188
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700189// TODO(dimitry): The grey-list is a workaround for http://b/26394120 ---
190// gradually remove libraries from this list until it is gone.
Dimitry Ivanov35c8e3b2017-02-27 12:17:47 -0800191static bool is_greylisted(android_namespace_t* ns, const char* name, const soinfo* needed_by) {
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700192 static const char* const kLibraryGreyList[] = {
193 "libandroid_runtime.so",
194 "libbinder.so",
195 "libcrypto.so",
196 "libcutils.so",
197 "libexpat.so",
198 "libgui.so",
199 "libmedia.so",
200 "libnativehelper.so",
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700201 "libssl.so",
202 "libstagefright.so",
203 "libsqlite.so",
204 "libui.so",
205 "libutils.so",
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700206 nullptr
207 };
208
Elliott Hughes5bc78c82016-11-16 11:35:43 -0800209 // If you're targeting N, you don't get the greylist.
Elliott Hughes95c6cd72019-12-20 13:26:14 -0800210 if (g_greylist_disabled || get_application_target_sdk_version() >= 24) {
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700211 return false;
212 }
213
214 // if the library needed by a system library - implicitly assume it
Dimitry Ivanov35c8e3b2017-02-27 12:17:47 -0800215 // is greylisted unless it is in the list of shared libraries for one or
216 // more linked namespaces
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700217 if (needed_by != nullptr && is_system_library(needed_by->get_realpath())) {
Dimitry Ivanov35c8e3b2017-02-27 12:17:47 -0800218 return !maybe_accessible_via_namespace_links(ns, name);
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700219 }
220
221 // if this is an absolute path - make sure it points to /system/lib(64)
222 if (name[0] == '/' && dirname(name) == kSystemLibDir) {
223 // and reduce the path to basename
224 name = basename(name);
225 }
226
227 for (size_t i = 0; kLibraryGreyList[i] != nullptr; ++i) {
228 if (strcmp(name, kLibraryGreyList[i]) == 0) {
229 return true;
230 }
231 }
232
233 return false;
234}
235// END OF WORKAROUND
236
Dmitriy Ivanovd165f562015-03-23 18:43:02 -0700237static std::vector<std::string> g_ld_preload_names;
Elliott Hughesa4aafd12014-01-13 16:37:47 -0800238
Elliott Hughesbedfe382012-08-14 14:07:59 -0700239static void notify_gdb_of_load(soinfo* info) {
Dimitry Ivanove97d8ed2016-03-01 15:55:56 -0800240 if (info->is_linker() || info->is_main_executable()) {
241 // gdb already knows about the linker and the main executable.
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700242 return;
243 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800244
Dimitry Ivanov6b788ee2016-02-17 16:08:03 -0800245 link_map* map = &(info->link_map_head);
Nicolas Geoffray0fa54102016-02-18 09:31:24 +0000246
Dimitry Ivanov6b788ee2016-02-17 16:08:03 -0800247 map->l_addr = info->load_bias;
248 // link_map l_name field is not const.
249 map->l_name = const_cast<char*>(info->get_realpath());
250 map->l_ld = info->dynamic;
Nicolas Geoffray0fa54102016-02-18 09:31:24 +0000251
Dimitry Ivanove97d8ed2016-03-01 15:55:56 -0800252 CHECK(map->l_name != nullptr);
253 CHECK(map->l_name[0] != '\0');
254
Dimitry Ivanov6b788ee2016-02-17 16:08:03 -0800255 notify_gdb_of_load(map);
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -0700256}
257
Elliott Hughesbedfe382012-08-14 14:07:59 -0700258static void notify_gdb_of_unload(soinfo* info) {
Dimitry Ivanov6b788ee2016-02-17 16:08:03 -0800259 notify_gdb_of_unload(&(info->link_map_head));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800260}
261
Dmitriy Ivanovd59e5002014-05-09 09:10:14 -0700262LinkedListEntry<soinfo>* SoinfoListAllocator::alloc() {
263 return g_soinfo_links_allocator.alloc();
264}
265
266void SoinfoListAllocator::free(LinkedListEntry<soinfo>* entry) {
267 g_soinfo_links_allocator.free(entry);
268}
269
Dimitry Ivanovaca299a2016-04-11 12:42:58 -0700270LinkedListEntry<android_namespace_t>* NamespaceListAllocator::alloc() {
271 return g_namespace_list_allocator.alloc();
272}
273
274void NamespaceListAllocator::free(LinkedListEntry<android_namespace_t>* entry) {
275 g_namespace_list_allocator.free(entry);
276}
277
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700278soinfo* soinfo_alloc(android_namespace_t* ns, const char* name,
Ryan Prichard8f639a42018-10-01 23:10:05 -0700279 const struct stat* file_stat, off64_t file_offset,
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700280 uint32_t rtld_flags) {
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -0700281 if (strlen(name) >= PATH_MAX) {
Elliott Hughes7b0af7a2017-09-15 16:09:22 -0700282 async_safe_fatal("library name \"%s\" too long", name);
Magnus Malmbornba98d922012-09-12 13:00:55 +0200283 }
284
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700285 TRACE("name %s: allocating soinfo for ns=%p", name, ns);
286
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -0700287 soinfo* si = new (g_soinfo_allocator.alloc()) soinfo(ns, name, file_stat,
288 file_offset, rtld_flags);
Dmitriy Ivanovd59e5002014-05-09 09:10:14 -0700289
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700290 solist_add_soinfo(si);
Magnus Malmbornba98d922012-09-12 13:00:55 +0200291
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -0700292 si->generate_handle();
293 ns->add_soinfo(si);
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -0700294
Elliott Hughesca0c11b2013-03-12 10:40:45 -0700295 TRACE("name %s: allocated soinfo @ %p", name, si);
Magnus Malmbornba98d922012-09-12 13:00:55 +0200296 return si;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800297}
298
Elliott Hughesfaf05ba2014-02-11 16:59:37 -0800299static void soinfo_free(soinfo* si) {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700300 if (si == nullptr) {
301 return;
302 }
303
Evgenii Stepanova8cf3fe2020-06-08 16:21:35 -0700304 void* start = reinterpret_cast<void*>(si->has_min_version(6) ? si->get_map_start() : si->base);
305 size_t size = si->has_min_version(6) ? si->get_map_size() : si->size;
306 if (start != nullptr && size != 0) {
Dimitry Ivanovf45b0e92016-01-15 11:13:35 -0800307 if (!si->is_mapped_by_caller()) {
Evgenii Stepanova8cf3fe2020-06-08 16:21:35 -0700308 munmap(start, size);
Dimitry Ivanovf45b0e92016-01-15 11:13:35 -0800309 } else {
310 // remap the region as PROT_NONE, MAP_ANONYMOUS | MAP_NORESERVE
Evgenii Stepanova8cf3fe2020-06-08 16:21:35 -0700311 mmap(start, size, PROT_NONE, MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
Dimitry Ivanovf45b0e92016-01-15 11:13:35 -0800312 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700313 }
314
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -0700315 TRACE("name %s: freeing soinfo @ %p", si->get_realpath(), si);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700316
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700317 if (!solist_remove_soinfo(si)) {
dimitry965d06d2017-11-28 16:03:07 +0100318 async_safe_fatal("soinfo=%p is not in soinfo_list (double unload?)", si);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700319 }
Elliott Hughes46882792012-08-03 16:49:39 -0700320
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700321 // clear links to/from si
322 si->remove_all_links();
Dmitriy Ivanovd59e5002014-05-09 09:10:14 -0700323
Dmitriy Ivanov609f11b2015-07-08 15:26:46 -0700324 si->~soinfo();
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700325 g_soinfo_allocator.free(si);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800326}
327
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -0700328static void parse_path(const char* path, const char* delimiters,
329 std::vector<std::string>* resolved_paths) {
330 std::vector<std::string> paths;
331 split_path(path, delimiters, &paths);
332 resolve_paths(paths, resolved_paths);
333}
334
Elliott Hughescade4c32012-12-20 14:42:14 -0800335static void parse_LD_LIBRARY_PATH(const char* path) {
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -0700336 std::vector<std::string> ld_libary_paths;
337 parse_path(path, ":", &ld_libary_paths);
338 g_default_namespace.set_ld_library_paths(std::move(ld_libary_paths));
Elliott Hughescade4c32012-12-20 14:42:14 -0800339}
340
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -0700341static bool realpath_fd(int fd, std::string* realpath) {
Vic Yangd8bef672019-05-15 21:10:22 -0700342 // proc_self_fd needs to be large enough to hold "/proc/self/fd/" plus an
343 // integer, plus the NULL terminator.
344 char proc_self_fd[32];
345 // We want to statically allocate this large buffer so that we don't grow
346 // the stack by too much.
347 static char buf[PATH_MAX];
348
349 async_safe_format_buffer(proc_self_fd, sizeof(proc_self_fd), "/proc/self/fd/%d", fd);
350 auto length = readlink(proc_self_fd, buf, sizeof(buf));
351 if (length == -1) {
Tom Cherry66bc4282018-11-08 13:40:52 -0800352 if (!is_first_stage_init()) {
Vic Yangd8bef672019-05-15 21:10:22 -0700353 PRINT("readlink(\"%s\") failed: %s [fd=%d]", proc_self_fd, strerror(errno), fd);
Tom Cherry66bc4282018-11-08 13:40:52 -0800354 }
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -0700355 return false;
356 }
357
Vic Yangd8bef672019-05-15 21:10:22 -0700358 realpath->assign(buf, length);
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -0700359 return true;
360}
361
Ryan Pricharda2e83ab2019-08-16 17:25:43 -0700362// Returns the address of the current thread's copy of a TLS module. If the current thread doesn't
363// have a copy yet, allocate one on-demand if should_alloc is true, and return nullptr otherwise.
364static inline void* get_tls_block_for_this_thread(const soinfo_tls* si_tls, bool should_alloc) {
365 const TlsModule& tls_mod = get_tls_module(si_tls->module_id);
366 if (tls_mod.static_offset != SIZE_MAX) {
367 const StaticTlsLayout& layout = __libc_shared_globals()->static_tls_layout;
368 char* static_tls = reinterpret_cast<char*>(__get_bionic_tcb()) - layout.offset_bionic_tcb();
369 return static_tls + tls_mod.static_offset;
370 } else if (should_alloc) {
371 const TlsIndex ti { si_tls->module_id, 0 };
372 return TLS_GET_ADDR(&ti);
373 } else {
374 TlsDtv* dtv = __get_tcb_dtv(__get_bionic_tcb());
375 if (dtv->generation < tls_mod.first_generation) return nullptr;
376 return dtv->modules[__tls_module_id_to_idx(si_tls->module_id)];
377 }
378}
379
Elliott Hughes4eeb1f12013-10-25 17:38:02 -0700380#if defined(__arm__)
Elliott Hughes46882792012-08-03 16:49:39 -0700381
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700382// For a given PC, find the .so that it belongs to.
383// Returns the base address of the .ARM.exidx section
384// for that .so, and the number of 8-byte entries
385// in that section (via *pcount).
386//
387// Intended to be called by libc's __gnu_Unwind_Find_exidx().
Dimitry Ivanovd9e427c2016-11-22 16:55:25 -0800388_Unwind_Ptr do_dl_unwind_find_exidx(_Unwind_Ptr pc, int* pcount) {
Peter Collingbourneb39cb3c2019-03-01 13:12:49 -0800389 if (soinfo* si = find_containing_library(reinterpret_cast<void*>(pc))) {
390 *pcount = si->ARM_exidx_count;
391 return reinterpret_cast<_Unwind_Ptr>(si->ARM_exidx);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700392 }
393 *pcount = 0;
Elliott Hughesf2c6ad62017-04-21 10:25:56 -0700394 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800395}
Elliott Hughes46882792012-08-03 16:49:39 -0700396
Christopher Ferris24053a42013-08-19 17:45:09 -0700397#endif
Elliott Hughes46882792012-08-03 16:49:39 -0700398
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700399// Here, we only have to provide a callback to iterate across all the
400// loaded libraries. gcc_eh does the rest.
Dmitriy Ivanov7271caf2015-06-29 14:48:25 -0700401int do_dl_iterate_phdr(int (*cb)(dl_phdr_info* info, size_t size, void* data), void* data) {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700402 int rv = 0;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700403 for (soinfo* si = solist_get_head(); si != nullptr; si = si->next) {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700404 dl_phdr_info dl_info;
405 dl_info.dlpi_addr = si->link_map_head.l_addr;
406 dl_info.dlpi_name = si->link_map_head.l_name;
407 dl_info.dlpi_phdr = si->phdr;
408 dl_info.dlpi_phnum = si->phnum;
Ryan Pricharda2e83ab2019-08-16 17:25:43 -0700409 dl_info.dlpi_adds = g_module_load_counter;
410 dl_info.dlpi_subs = g_module_unload_counter;
411 if (soinfo_tls* tls_module = si->get_tls()) {
412 dl_info.dlpi_tls_modid = tls_module->module_id;
413 dl_info.dlpi_tls_data = get_tls_block_for_this_thread(tls_module, /*should_alloc=*/false);
414 } else {
415 dl_info.dlpi_tls_modid = 0;
416 dl_info.dlpi_tls_data = nullptr;
417 }
418
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700419 rv = cb(&dl_info, sizeof(dl_phdr_info), data);
420 if (rv != 0) {
421 break;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800422 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700423 }
424 return rv;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800425}
Elliott Hughes46882792012-08-03 16:49:39 -0700426
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700427ProtectedDataGuard::ProtectedDataGuard() {
428 if (ref_count_++ == 0) {
429 protect_data(PROT_READ | PROT_WRITE);
430 }
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700431
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700432 if (ref_count_ == 0) { // overflow
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700433 async_safe_fatal("Too many nested calls to dlopen()");
Dmitriy Ivanov279a22f2015-01-23 12:03:53 -0800434 }
Dimitry Ivanov68e6c032017-02-01 12:55:11 -0800435}
Dmitriy Ivanov279a22f2015-01-23 12:03:53 -0800436
Dimitry Ivanov68e6c032017-02-01 12:55:11 -0800437ProtectedDataGuard::~ProtectedDataGuard() {
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700438 if (--ref_count_ == 0) {
439 protect_data(PROT_READ);
Dmitriy Ivanov279a22f2015-01-23 12:03:53 -0800440 }
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700441}
Dmitriy Ivanov279a22f2015-01-23 12:03:53 -0800442
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700443void ProtectedDataGuard::protect_data(int protection) {
444 g_soinfo_allocator.protect_all(protection);
445 g_soinfo_links_allocator.protect_all(protection);
446 g_namespace_allocator.protect_all(protection);
447 g_namespace_list_allocator.protect_all(protection);
448}
Dmitriy Ivanov279a22f2015-01-23 12:03:53 -0800449
450size_t ProtectedDataGuard::ref_count_ = 0;
451
Dmitriy Ivanov0cd83eb2014-09-01 16:15:52 -0700452// Each size has it's own allocator.
453template<size_t size>
454class SizeBasedAllocator {
455 public:
456 static void* alloc() {
457 return allocator_.alloc();
458 }
Dmitriy Ivanov4bea4982014-08-29 14:01:48 -0700459
Dmitriy Ivanov0cd83eb2014-09-01 16:15:52 -0700460 static void free(void* ptr) {
461 allocator_.free(ptr);
462 }
Dmitriy Ivanov4bea4982014-08-29 14:01:48 -0700463
Vic Yangbb7e1232019-01-29 20:23:16 -0800464 static void purge() {
465 allocator_.purge();
466 }
467
Dmitriy Ivanov0cd83eb2014-09-01 16:15:52 -0700468 private:
469 static LinkerBlockAllocator allocator_;
470};
471
472template<size_t size>
473LinkerBlockAllocator SizeBasedAllocator<size>::allocator_(size);
474
475template<typename T>
476class TypeBasedAllocator {
477 public:
478 static T* alloc() {
479 return reinterpret_cast<T*>(SizeBasedAllocator<sizeof(T)>::alloc());
480 }
481
482 static void free(T* ptr) {
483 SizeBasedAllocator<sizeof(T)>::free(ptr);
484 }
Vic Yangbb7e1232019-01-29 20:23:16 -0800485
486 static void purge() {
487 SizeBasedAllocator<sizeof(T)>::purge();
488 }
Dmitriy Ivanov0cd83eb2014-09-01 16:15:52 -0700489};
490
Dmitriy Ivanov14669a92014-09-05 16:42:53 -0700491class LoadTask {
492 public:
493 struct deleter_t {
494 void operator()(LoadTask* t) {
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700495 t->~LoadTask();
Dmitriy Ivanov14669a92014-09-05 16:42:53 -0700496 TypeBasedAllocator<LoadTask>::free(t);
497 }
498 };
499
Dmitriy Ivanov14669a92014-09-05 16:42:53 -0700500 static deleter_t deleter;
501
Ryan Prichardaa2db962020-03-24 20:25:53 -0700502 // needed_by is NULL iff dlopen is called from memory that isn't part of any known soinfo.
503 static LoadTask* create(const char* _Nonnull name, soinfo* _Nullable needed_by,
504 android_namespace_t* _Nonnull start_from,
505 std::unordered_map<const soinfo*, ElfReader>* _Nonnull readers_map) {
Dmitriy Ivanov14669a92014-09-05 16:42:53 -0700506 LoadTask* ptr = TypeBasedAllocator<LoadTask>::alloc();
Jiyong Park02586a22017-05-20 01:01:24 +0900507 return new (ptr) LoadTask(name, needed_by, start_from, readers_map);
Dmitriy Ivanov14669a92014-09-05 16:42:53 -0700508 }
509
510 const char* get_name() const {
511 return name_;
512 }
513
514 soinfo* get_needed_by() const {
515 return needed_by_;
516 }
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700517
518 soinfo* get_soinfo() const {
519 return si_;
520 }
521
522 void set_soinfo(soinfo* si) {
523 si_ = si;
524 }
525
526 off64_t get_file_offset() const {
527 return file_offset_;
528 }
529
530 void set_file_offset(off64_t offset) {
531 file_offset_ = offset;
532 }
533
534 int get_fd() const {
535 return fd_;
536 }
537
538 void set_fd(int fd, bool assume_ownership) {
Martin Stjernholmde853ff2019-01-17 00:18:44 +0000539 if (fd_ != -1 && close_fd_) {
540 close(fd_);
541 }
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700542 fd_ = fd;
543 close_fd_ = assume_ownership;
544 }
545
546 const android_dlextinfo* get_extinfo() const {
547 return extinfo_;
548 }
549
550 void set_extinfo(const android_dlextinfo* extinfo) {
551 extinfo_ = extinfo;
552 }
553
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700554 bool is_dt_needed() const {
555 return is_dt_needed_;
556 }
557
558 void set_dt_needed(bool is_dt_needed) {
559 is_dt_needed_ = is_dt_needed;
560 }
561
Jiyong Park02586a22017-05-20 01:01:24 +0900562 // returns the namespace from where we need to start loading this.
563 const android_namespace_t* get_start_from() const {
564 return start_from_;
565 }
566
Ryan Prichard4fa6d992020-03-26 21:31:43 -0700567 void remove_cached_elf_reader() {
568 CHECK(si_ != nullptr);
569 (*elf_readers_map_).erase(si_);
570 }
571
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700572 const ElfReader& get_elf_reader() const {
573 CHECK(si_ != nullptr);
574 return (*elf_readers_map_)[si_];
575 }
576
577 ElfReader& get_elf_reader() {
578 CHECK(si_ != nullptr);
579 return (*elf_readers_map_)[si_];
580 }
581
582 std::unordered_map<const soinfo*, ElfReader>* get_readers_map() {
583 return elf_readers_map_;
584 }
585
586 bool read(const char* realpath, off64_t file_size) {
587 ElfReader& elf_reader = get_elf_reader();
588 return elf_reader.Read(realpath, fd_, file_offset_, file_size);
589 }
590
Torne (Richard Coles)efbe9a52018-10-17 15:59:38 -0400591 bool load(address_space_params* address_space) {
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700592 ElfReader& elf_reader = get_elf_reader();
Torne (Richard Coles)efbe9a52018-10-17 15:59:38 -0400593 if (!elf_reader.Load(address_space)) {
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700594 return false;
595 }
596
597 si_->base = elf_reader.load_start();
598 si_->size = elf_reader.load_size();
Dimitry Ivanovf45b0e92016-01-15 11:13:35 -0800599 si_->set_mapped_by_caller(elf_reader.is_mapped_by_caller());
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700600 si_->load_bias = elf_reader.load_bias();
601 si_->phnum = elf_reader.phdr_count();
602 si_->phdr = elf_reader.loaded_phdr();
Evgenii Stepanova8cf3fe2020-06-08 16:21:35 -0700603 si_->set_map_start(elf_reader.map_start());
604 si_->set_map_size(elf_reader.map_size());
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700605
606 return true;
607 }
608
Dmitriy Ivanov14669a92014-09-05 16:42:53 -0700609 private:
Dimitry Ivanov7d429d32017-02-01 15:28:52 -0800610 LoadTask(const char* name,
611 soinfo* needed_by,
Jiyong Park02586a22017-05-20 01:01:24 +0900612 android_namespace_t* start_from,
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700613 std::unordered_map<const soinfo*, ElfReader>* readers_map)
614 : name_(name), needed_by_(needed_by), si_(nullptr),
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700615 fd_(-1), close_fd_(false), file_offset_(0), elf_readers_map_(readers_map),
Jiyong Park02586a22017-05-20 01:01:24 +0900616 is_dt_needed_(false), start_from_(start_from) {}
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700617
618 ~LoadTask() {
619 if (fd_ != -1 && close_fd_) {
620 close(fd_);
621 }
622 }
Dmitriy Ivanov14669a92014-09-05 16:42:53 -0700623
624 const char* name_;
625 soinfo* needed_by_;
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700626 soinfo* si_;
627 const android_dlextinfo* extinfo_;
628 int fd_;
629 bool close_fd_;
630 off64_t file_offset_;
631 std::unordered_map<const soinfo*, ElfReader>* elf_readers_map_;
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700632 // TODO(dimitry): needed by workaround for http://b/26394120 (the grey-list)
633 bool is_dt_needed_;
634 // END OF WORKAROUND
Jiyong Park02586a22017-05-20 01:01:24 +0900635 const android_namespace_t* const start_from_;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -0700636
637 DISALLOW_IMPLICIT_CONSTRUCTORS(LoadTask);
638};
639
Ningsheng Jiane93be992014-09-16 15:22:10 +0800640LoadTask::deleter_t LoadTask::deleter;
641
Dmitriy Ivanov0cd83eb2014-09-01 16:15:52 -0700642template <typename T>
643using linked_list_t = LinkedList<T, TypeBasedAllocator<LinkedListEntry<T>>>;
644
645typedef linked_list_t<soinfo> SoinfoLinkedList;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -0700646typedef linked_list_t<const char> StringLinkedList;
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700647typedef std::vector<LoadTask*> LoadTaskList;
Dmitriy Ivanov0cd83eb2014-09-01 16:15:52 -0700648
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800649enum walk_action_result_t : uint32_t {
650 kWalkStop = 0,
651 kWalkContinue = 1,
652 kWalkSkip = 2
653};
Dmitriy Ivanovaa0f2bd2014-07-28 17:32:20 -0700654
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700655// This function walks down the tree of soinfo dependencies
656// in breadth-first order and
657// * calls action(soinfo* si) for each node, and
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800658// * terminates walk if action returns kWalkStop
659// * skips children of the node if action
660// return kWalkSkip
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700661//
662// walk_dependencies_tree returns false if walk was terminated
663// by the action and true otherwise.
664template<typename F>
dimitry965d06d2017-11-28 16:03:07 +0100665static bool walk_dependencies_tree(soinfo* root_soinfo, F action) {
Dmitriy Ivanov0cd83eb2014-09-01 16:15:52 -0700666 SoinfoLinkedList visit_list;
667 SoinfoLinkedList visited;
668
dimitry965d06d2017-11-28 16:03:07 +0100669 visit_list.push_back(root_soinfo);
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700670
671 soinfo* si;
672 while ((si = visit_list.pop_front()) != nullptr) {
673 if (visited.contains(si)) {
Dmitriy Ivanov042426b2014-08-12 21:02:13 -0700674 continue;
675 }
676
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800677 walk_action_result_t result = action(si);
678
679 if (result == kWalkStop) {
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700680 return false;
Dmitriy Ivanovaa0f2bd2014-07-28 17:32:20 -0700681 }
682
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700683 visited.push_back(si);
684
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800685 if (result != kWalkSkip) {
686 si->get_children().for_each([&](soinfo* child) {
687 visit_list.push_back(child);
688 });
689 }
Dmitriy Ivanovaa0f2bd2014-07-28 17:32:20 -0700690 }
691
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700692 return true;
693}
694
695
Ryan Prichard272458e2020-01-23 16:07:27 -0800696static const ElfW(Sym)* dlsym_handle_lookup_impl(android_namespace_t* ns,
697 soinfo* root,
698 soinfo* skip_until,
699 soinfo** found,
700 SymbolName& symbol_name,
701 const version_info* vi) {
Dmitriy Ivanov2a815362015-04-09 13:42:33 -0700702 const ElfW(Sym)* result = nullptr;
Dmitriy Ivanov697bd9f2015-05-12 11:12:27 -0700703 bool skip_lookup = skip_until != nullptr;
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700704
dimitry965d06d2017-11-28 16:03:07 +0100705 walk_dependencies_tree(root, [&](soinfo* current_soinfo) {
Dmitriy Ivanov697bd9f2015-05-12 11:12:27 -0700706 if (skip_lookup) {
707 skip_lookup = current_soinfo != skip_until;
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800708 return kWalkContinue;
709 }
710
711 if (!ns->is_accessible(current_soinfo)) {
712 return kWalkSkip;
Dmitriy Ivanov697bd9f2015-05-12 11:12:27 -0700713 }
714
Ryan Prichard0e12cce2020-01-02 14:59:11 -0800715 result = current_soinfo->find_symbol_by_name(symbol_name, vi);
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700716 if (result != nullptr) {
717 *found = current_soinfo;
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800718 return kWalkStop;
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700719 }
720
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800721 return kWalkContinue;
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700722 });
723
724 return result;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800725}
726
Brian Carlstromd4ee82d2013-02-28 15:58:45 -0800727/* This is used by dlsym(3) to performs a global symbol lookup. If the
728 start value is null (for RTLD_DEFAULT), the search starts at the
729 beginning of the global solist. Otherwise the search starts at the
730 specified soinfo (for RTLD_NEXT).
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700731 */
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -0800732static const ElfW(Sym)* dlsym_linear_lookup(android_namespace_t* ns,
733 const char* name,
734 const version_info* vi,
735 soinfo** found,
736 soinfo* caller,
737 void* handle) {
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -0800738 SymbolName symbol_name(name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800739
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -0700740 auto& soinfo_list = ns->soinfo_list();
741 auto start = soinfo_list.begin();
Dmitriy Ivanov76ac1ac2015-04-01 14:45:10 -0700742
743 if (handle == RTLD_NEXT) {
Dmitriy Ivanovb96ac412015-05-22 12:34:42 -0700744 if (caller == nullptr) {
Dmitriy Ivanov76ac1ac2015-04-01 14:45:10 -0700745 return nullptr;
746 } else {
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -0700747 auto it = soinfo_list.find(caller);
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -0700748 CHECK (it != soinfo_list.end());
749 start = ++it;
Dmitriy Ivanov76ac1ac2015-04-01 14:45:10 -0700750 }
Elliott Hughescade4c32012-12-20 14:42:14 -0800751 }
752
Dmitriy Ivanov2a815362015-04-09 13:42:33 -0700753 const ElfW(Sym)* s = nullptr;
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -0700754 for (auto it = start, end = soinfo_list.end(); it != end; ++it) {
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -0700755 soinfo* si = *it;
Dmitriy Ivanov19133522015-06-02 17:36:54 -0700756 // Do not skip RTLD_LOCAL libraries in dlsym(RTLD_DEFAULT, ...)
Elliott Hughes5bc78c82016-11-16 11:35:43 -0800757 // if the library is opened by application with target api level < M.
Dmitriy Ivanov19133522015-06-02 17:36:54 -0700758 // See http://b/21565766
Elliott Hughes95c6cd72019-12-20 13:26:14 -0800759 if ((si->get_rtld_flags() & RTLD_GLOBAL) == 0 && si->get_target_sdk_version() >= 23) {
Dmitriy Ivanove8ba50f2014-09-15 17:00:10 -0700760 continue;
761 }
762
Ryan Prichard0e12cce2020-01-02 14:59:11 -0800763 s = si->find_symbol_by_name(symbol_name, vi);
Dmitriy Ivanov851135b2014-08-29 12:02:36 -0700764 if (s != nullptr) {
Elliott Hughescade4c32012-12-20 14:42:14 -0800765 *found = si;
766 break;
Matt Fischer1698d9e2009-12-31 12:17:56 -0600767 }
Elliott Hughescade4c32012-12-20 14:42:14 -0800768 }
Matt Fischer1698d9e2009-12-31 12:17:56 -0600769
Ryan Prichard272458e2020-01-23 16:07:27 -0800770 // If not found - use dlsym_handle_lookup_impl for caller's local_group
dimitry153168c2018-02-20 16:51:41 +0100771 if (s == nullptr && caller != nullptr) {
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800772 soinfo* local_group_root = caller->get_local_group_root();
773
Ryan Prichard272458e2020-01-23 16:07:27 -0800774 return dlsym_handle_lookup_impl(local_group_root->get_primary_namespace(),
775 local_group_root,
776 (handle == RTLD_NEXT) ? caller : nullptr,
777 found,
778 symbol_name,
779 vi);
Dmitriy Ivanov76ac1ac2015-04-01 14:45:10 -0700780 }
781
Dmitriy Ivanov851135b2014-08-29 12:02:36 -0700782 if (s != nullptr) {
Elliott Hughesc00f2cb2013-10-04 17:01:33 -0700783 TRACE_TYPE(LOOKUP, "%s s->st_value = %p, found->base = %p",
784 name, reinterpret_cast<void*>(s->st_value), reinterpret_cast<void*>((*found)->base));
Elliott Hughescade4c32012-12-20 14:42:14 -0800785 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800786
Elliott Hughescade4c32012-12-20 14:42:14 -0800787 return s;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800788}
789
Ryan Prichard272458e2020-01-23 16:07:27 -0800790// This is used by dlsym(3). It performs symbol lookup only within the
791// specified soinfo object and its dependencies in breadth first order.
792static const ElfW(Sym)* dlsym_handle_lookup(soinfo* si,
793 soinfo** found,
794 const char* name,
795 const version_info* vi) {
796 // According to man dlopen(3) and posix docs in the case when si is handle
797 // of the main executable we need to search not only in the executable and its
798 // dependencies but also in all libraries loaded with RTLD_GLOBAL.
799 //
800 // Since RTLD_GLOBAL is always set for the main executable and all dt_needed shared
801 // libraries and they are loaded in breath-first (correct) order we can just execute
802 // dlsym(RTLD_DEFAULT, ...); instead of doing two stage lookup.
803 if (si == solist_get_somain()) {
804 return dlsym_linear_lookup(&g_default_namespace, name, vi, found, nullptr, RTLD_DEFAULT);
805 }
806
807 SymbolName symbol_name(name);
808 // note that the namespace is not the namespace associated with caller_addr
809 // we use ns associated with root si intentionally here. Using caller_ns
810 // causes problems when user uses dlopen_ext to open a library in the separate
811 // namespace and then calls dlsym() on the handle.
812 return dlsym_handle_lookup_impl(si->get_primary_namespace(), si, nullptr, found, symbol_name, vi);
813}
814
Kito Chengfa8c05d2013-03-12 14:58:06 +0800815soinfo* find_containing_library(const void* p) {
Peter Collingbourne191ecdc2019-08-07 19:06:00 -0700816 // Addresses within a library may be tagged if they point to globals. Untag
817 // them so that the bounds check succeeds.
818 ElfW(Addr) address = reinterpret_cast<ElfW(Addr)>(untag_address(p));
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700819 for (soinfo* si = solist_get_head(); si != nullptr; si = si->next) {
Peter Collingbourneb39cb3c2019-03-01 13:12:49 -0800820 if (address < si->base || address - si->base >= si->size) {
821 continue;
822 }
823 ElfW(Addr) vaddr = address - si->load_bias;
824 for (size_t i = 0; i != si->phnum; ++i) {
825 const ElfW(Phdr)* phdr = &si->phdr[i];
826 if (phdr->p_type != PT_LOAD) {
827 continue;
828 }
829 if (vaddr >= phdr->p_vaddr && vaddr < phdr->p_vaddr + phdr->p_memsz) {
830 return si;
831 }
Matt Fischere2a8b1f2009-12-31 12:17:40 -0600832 }
Kito Chengfa8c05d2013-03-12 14:58:06 +0800833 }
Dmitriy Ivanov851135b2014-08-29 12:02:36 -0700834 return nullptr;
Matt Fischere2a8b1f2009-12-31 12:17:40 -0600835}
836
Dmitriy Ivanovb4827502015-09-28 16:38:31 -0700837class ZipArchiveCache {
838 public:
839 ZipArchiveCache() {}
840 ~ZipArchiveCache();
841
842 bool get_or_open(const char* zip_path, ZipArchiveHandle* handle);
843 private:
844 DISALLOW_COPY_AND_ASSIGN(ZipArchiveCache);
845
846 std::unordered_map<std::string, ZipArchiveHandle> cache_;
847};
848
849bool ZipArchiveCache::get_or_open(const char* zip_path, ZipArchiveHandle* handle) {
850 std::string key(zip_path);
851
852 auto it = cache_.find(key);
853 if (it != cache_.end()) {
854 *handle = it->second;
855 return true;
856 }
857
858 int fd = TEMP_FAILURE_RETRY(open(zip_path, O_RDONLY | O_CLOEXEC));
859 if (fd == -1) {
860 return false;
861 }
862
863 if (OpenArchiveFd(fd, "", handle) != 0) {
864 // invalid zip-file (?)
Ryan Prichard0adf09b2018-10-01 18:35:46 -0700865 CloseArchive(*handle);
Dmitriy Ivanovb4827502015-09-28 16:38:31 -0700866 return false;
867 }
868
869 cache_[key] = *handle;
870 return true;
871}
872
873ZipArchiveCache::~ZipArchiveCache() {
Dmitriy Ivanov5dce8942015-10-13 12:14:16 -0700874 for (const auto& it : cache_) {
Dmitriy Ivanovb4827502015-09-28 16:38:31 -0700875 CloseArchive(it.second);
876 }
877}
878
879static int open_library_in_zipfile(ZipArchiveCache* zip_archive_cache,
Dmitriy Ivanova1feb112015-10-01 18:41:57 -0700880 const char* const input_path,
881 off64_t* file_offset, std::string* realpath) {
882 std::string normalized_path;
883 if (!normalize_path(input_path, &normalized_path)) {
884 return -1;
885 }
886
887 const char* const path = normalized_path.c_str();
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700888 TRACE("Trying zip file open from path \"%s\" -> normalized \"%s\"", input_path, path);
Simon Baldwinaef71952015-01-16 13:22:54 +0000889
Dmitriy Ivanov402a7502015-06-09 13:46:51 -0700890 // Treat an '!/' separator inside a path as the separator between the name
Simon Baldwinaef71952015-01-16 13:22:54 +0000891 // of the zip file on disk and the subdirectory to search within it.
Dmitriy Ivanov402a7502015-06-09 13:46:51 -0700892 // For example, if path is "foo.zip!/bar/bas/x.so", then we search for
Simon Baldwinaef71952015-01-16 13:22:54 +0000893 // "bar/bas/x.so" within "foo.zip".
Dmitriy Ivanova1feb112015-10-01 18:41:57 -0700894 const char* const separator = strstr(path, kZipFileSeparator);
Simon Baldwinaef71952015-01-16 13:22:54 +0000895 if (separator == nullptr) {
896 return -1;
Elliott Hughes124fae92012-10-31 14:20:03 -0700897 }
Simon Baldwinaef71952015-01-16 13:22:54 +0000898
899 char buf[512];
900 if (strlcpy(buf, path, sizeof(buf)) >= sizeof(buf)) {
901 PRINT("Warning: ignoring very long library path: %s", path);
902 return -1;
903 }
904
905 buf[separator - path] = '\0';
906
907 const char* zip_path = buf;
Dmitriy Ivanov402a7502015-06-09 13:46:51 -0700908 const char* file_path = &buf[separator - path + 2];
Simon Baldwinaef71952015-01-16 13:22:54 +0000909 int fd = TEMP_FAILURE_RETRY(open(zip_path, O_RDONLY | O_CLOEXEC));
910 if (fd == -1) {
911 return -1;
912 }
913
914 ZipArchiveHandle handle;
Dmitriy Ivanovb4827502015-09-28 16:38:31 -0700915 if (!zip_archive_cache->get_or_open(zip_path, &handle)) {
Simon Baldwinaef71952015-01-16 13:22:54 +0000916 // invalid zip-file (?)
917 close(fd);
918 return -1;
919 }
920
Simon Baldwinaef71952015-01-16 13:22:54 +0000921 ZipEntry entry;
922
Elliott Hughesb51bb502019-05-03 22:45:41 -0700923 if (FindEntry(handle, file_path, &entry) != 0) {
Simon Baldwinaef71952015-01-16 13:22:54 +0000924 // Entry was not found.
925 close(fd);
926 return -1;
927 }
928
929 // Check if it is properly stored
930 if (entry.method != kCompressStored || (entry.offset % PAGE_SIZE) != 0) {
931 close(fd);
932 return -1;
933 }
934
935 *file_offset = entry.offset;
Dmitriy Ivanova1feb112015-10-01 18:41:57 -0700936
937 if (realpath_fd(fd, realpath)) {
938 *realpath += separator;
939 } else {
Tom Cherry66bc4282018-11-08 13:40:52 -0800940 if (!is_first_stage_init()) {
941 PRINT("warning: unable to get realpath for the library \"%s\". Will use given path.",
942 normalized_path.c_str());
943 }
Dmitriy Ivanova1feb112015-10-01 18:41:57 -0700944 *realpath = normalized_path;
945 }
946
Simon Baldwinaef71952015-01-16 13:22:54 +0000947 return fd;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800948}
949
Dmitriy Ivanovd165f562015-03-23 18:43:02 -0700950static bool format_path(char* buf, size_t buf_size, const char* path, const char* name) {
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700951 int n = async_safe_format_buffer(buf, buf_size, "%s/%s", path, name);
Dmitriy Ivanovd165f562015-03-23 18:43:02 -0700952 if (n < 0 || n >= static_cast<int>(buf_size)) {
953 PRINT("Warning: ignoring very long library path: %s/%s", path, name);
954 return false;
955 }
Simon Baldwinaef71952015-01-16 13:22:54 +0000956
Dmitriy Ivanovd165f562015-03-23 18:43:02 -0700957 return true;
958}
959
Ryan Prichard8f639a42018-10-01 23:10:05 -0700960static int open_library_at_path(ZipArchiveCache* zip_archive_cache,
961 const char* path, off64_t* file_offset,
962 std::string* realpath) {
963 int fd = -1;
964 if (strstr(path, kZipFileSeparator) != nullptr) {
965 fd = open_library_in_zipfile(zip_archive_cache, path, file_offset, realpath);
966 }
967
968 if (fd == -1) {
969 fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC));
970 if (fd != -1) {
971 *file_offset = 0;
972 if (!realpath_fd(fd, realpath)) {
Tom Cherry66bc4282018-11-08 13:40:52 -0800973 if (!is_first_stage_init()) {
974 PRINT("warning: unable to get realpath for the library \"%s\". Will use given path.",
975 path);
976 }
Ryan Prichard8f639a42018-10-01 23:10:05 -0700977 *realpath = path;
978 }
979 }
980 }
981
982 return fd;
983}
984
Dmitriy Ivanovb4827502015-09-28 16:38:31 -0700985static int open_library_on_paths(ZipArchiveCache* zip_archive_cache,
986 const char* name, off64_t* file_offset,
Dmitriy Ivanova1feb112015-10-01 18:41:57 -0700987 const std::vector<std::string>& paths,
988 std::string* realpath) {
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -0700989 for (const auto& path : paths) {
Dmitriy Ivanovd165f562015-03-23 18:43:02 -0700990 char buf[512];
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -0700991 if (!format_path(buf, sizeof(buf), path.c_str(), name)) {
Dmitriy Ivanovd165f562015-03-23 18:43:02 -0700992 continue;
993 }
994
Ryan Prichard8f639a42018-10-01 23:10:05 -0700995 int fd = open_library_at_path(zip_archive_cache, buf, file_offset, realpath);
Dmitriy Ivanovd165f562015-03-23 18:43:02 -0700996 if (fd != -1) {
997 return fd;
998 }
Simon Baldwinaef71952015-01-16 13:22:54 +0000999 }
1000
Dmitriy Ivanovd165f562015-03-23 18:43:02 -07001001 return -1;
Simon Baldwinaef71952015-01-16 13:22:54 +00001002}
1003
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001004static int open_library(android_namespace_t* ns,
1005 ZipArchiveCache* zip_archive_cache,
Dmitriy Ivanovb4827502015-09-28 16:38:31 -07001006 const char* name, soinfo *needed_by,
Dmitriy Ivanova1feb112015-10-01 18:41:57 -07001007 off64_t* file_offset, std::string* realpath) {
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001008 TRACE("[ opening %s from namespace %s ]", name, ns->get_name());
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001009
Elliott Hughes124fae92012-10-31 14:20:03 -07001010 // If the name contains a slash, we should attempt to open it directly and not search the paths.
Dmitriy Ivanov851135b2014-08-29 12:02:36 -07001011 if (strchr(name, '/') != nullptr) {
Ryan Prichardaa2db962020-03-24 20:25:53 -07001012 return open_library_at_path(zip_archive_cache, name, file_offset, realpath);
Elliott Hughes124fae92012-10-31 14:20:03 -07001013 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001014
Ryan Prichardaa2db962020-03-24 20:25:53 -07001015 // LD_LIBRARY_PATH has the highest priority. We don't have to check accessibility when searching
1016 // the namespace's path lists, because anything found on a namespace path list should always be
1017 // accessible.
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001018 int fd = open_library_on_paths(zip_archive_cache, name, file_offset, ns->get_ld_library_paths(), realpath);
Ryan Prichardaa2db962020-03-24 20:25:53 -07001019
1020 // Try the DT_RUNPATH, and verify that the library is accessible.
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001021 if (fd == -1 && needed_by != nullptr) {
Dmitriy Ivanova1feb112015-10-01 18:41:57 -07001022 fd = open_library_on_paths(zip_archive_cache, name, file_offset, needed_by->get_dt_runpath(), realpath);
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001023 if (fd != -1 && !ns->is_accessible(*realpath)) {
Vic Yang48b69112018-10-24 14:14:26 -07001024 close(fd);
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001025 fd = -1;
1026 }
Evgenii Stepanov68650822015-06-10 13:38:39 -07001027 }
Dmitriy Ivanovb4827502015-09-28 16:38:31 -07001028
Ryan Prichardaa2db962020-03-24 20:25:53 -07001029 // Finally search the namespace's main search path list.
Elliott Hughes124fae92012-10-31 14:20:03 -07001030 if (fd == -1) {
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001031 fd = open_library_on_paths(zip_archive_cache, name, file_offset, ns->get_default_library_paths(), realpath);
Elliott Hughes124fae92012-10-31 14:20:03 -07001032 }
Dmitriy Ivanovb4827502015-09-28 16:38:31 -07001033
Elliott Hughes124fae92012-10-31 14:20:03 -07001034 return fd;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001035}
1036
Ryan Prichard8f639a42018-10-01 23:10:05 -07001037int open_executable(const char* path, off64_t* file_offset, std::string* realpath) {
1038 ZipArchiveCache zip_archive_cache;
1039 return open_library_at_path(&zip_archive_cache, path, file_offset, realpath);
1040}
1041
Dimitry Ivanov3f660572016-09-09 10:00:39 -07001042const char* fix_dt_needed(const char* dt_needed, const char* sopath __unused) {
Dmitriy Ivanovd974e882015-05-27 18:29:41 -07001043#if !defined(__LP64__)
1044 // Work around incorrect DT_NEEDED entries for old apps: http://b/21364029
Elliott Hughes9076b0c2018-02-28 11:29:45 -08001045 int app_target_api_level = get_application_target_sdk_version();
Elliott Hughes95c6cd72019-12-20 13:26:14 -08001046 if (app_target_api_level < 23) {
Dmitriy Ivanovd974e882015-05-27 18:29:41 -07001047 const char* bname = basename(dt_needed);
1048 if (bname != dt_needed) {
Elliott Hughes95c6cd72019-12-20 13:26:14 -08001049 DL_WARN_documented_change(23,
Elliott Hughes9076b0c2018-02-28 11:29:45 -08001050 "invalid-dt_needed-entries-enforced-for-api-level-23",
1051 "library \"%s\" has invalid DT_NEEDED entry \"%s\"",
1052 sopath, dt_needed, app_target_api_level);
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07001053 add_dlwarning(sopath, "invalid DT_NEEDED entry", dt_needed);
Dmitriy Ivanovd974e882015-05-27 18:29:41 -07001054 }
1055
1056 return bname;
1057 }
1058#endif
1059 return dt_needed;
1060}
1061
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001062template<typename F>
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001063static void for_each_dt_needed(const ElfReader& elf_reader, F action) {
1064 for (const ElfW(Dyn)* d = elf_reader.dynamic(); d->d_tag != DT_NULL; ++d) {
1065 if (d->d_tag == DT_NEEDED) {
1066 action(fix_dt_needed(elf_reader.get_string(d->d_un.d_val), elf_reader.name()));
1067 }
1068 }
1069}
1070
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001071static bool find_loaded_library_by_inode(android_namespace_t* ns,
1072 const struct stat& file_stat,
1073 off64_t file_offset,
1074 bool search_linked_namespaces,
1075 soinfo** candidate) {
Vic Yang3ec16be2019-06-02 21:10:53 -07001076 if (file_stat.st_dev == 0 || file_stat.st_ino == 0) {
1077 *candidate = nullptr;
1078 return false;
1079 }
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001080
1081 auto predicate = [&](soinfo* si) {
Vic Yang3ec16be2019-06-02 21:10:53 -07001082 return si->get_st_ino() == file_stat.st_ino &&
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001083 si->get_st_dev() == file_stat.st_dev &&
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001084 si->get_file_offset() == file_offset;
1085 };
1086
1087 *candidate = ns->soinfo_list().find_if(predicate);
1088
1089 if (*candidate == nullptr && search_linked_namespaces) {
1090 for (auto& link : ns->linked_namespaces()) {
1091 android_namespace_t* linked_ns = link.linked_namespace();
1092 soinfo* si = linked_ns->soinfo_list().find_if(predicate);
1093
1094 if (si != nullptr && link.is_accessible(si->get_soname())) {
1095 *candidate = si;
1096 return true;
1097 }
1098 }
1099 }
1100
1101 return *candidate != nullptr;
1102}
1103
Evgenii Stepanov9e77a642017-07-27 14:55:44 -07001104static bool find_loaded_library_by_realpath(android_namespace_t* ns, const char* realpath,
1105 bool search_linked_namespaces, soinfo** candidate) {
1106 auto predicate = [&](soinfo* si) { return strcmp(realpath, si->get_realpath()) == 0; };
1107
1108 *candidate = ns->soinfo_list().find_if(predicate);
1109
1110 if (*candidate == nullptr && search_linked_namespaces) {
1111 for (auto& link : ns->linked_namespaces()) {
1112 android_namespace_t* linked_ns = link.linked_namespace();
1113 soinfo* si = linked_ns->soinfo_list().find_if(predicate);
1114
1115 if (si != nullptr && link.is_accessible(si->get_soname())) {
1116 *candidate = si;
1117 return true;
1118 }
1119 }
1120 }
1121
1122 return *candidate != nullptr;
1123}
1124
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001125static bool load_library(android_namespace_t* ns,
1126 LoadTask* task,
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001127 LoadTaskList* load_tasks,
1128 int rtld_flags,
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001129 const std::string& realpath,
1130 bool search_linked_namespaces) {
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001131 off64_t file_offset = task->get_file_offset();
1132 const char* name = task->get_name();
1133 const android_dlextinfo* extinfo = task->get_extinfo();
1134
Martin Stjernholm9fe38262019-08-27 17:08:45 +01001135 LD_LOG(kLogDlopen,
1136 "load_library(ns=%s, task=%s, flags=0x%x, realpath=%s, search_linked_namespaces=%d)",
1137 ns->get_name(), name, rtld_flags, realpath.c_str(), search_linked_namespaces);
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001138
Dmitriy Ivanov07e5bc12014-10-03 17:52:44 -07001139 if ((file_offset % PAGE_SIZE) != 0) {
Martin Stjernholm9fe38262019-08-27 17:08:45 +01001140 DL_OPEN_ERR("file offset for the library \"%s\" is not page-aligned: %" PRId64, name, file_offset);
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001141 return false;
Dmitriy Ivanov07e5bc12014-10-03 17:52:44 -07001142 }
Yabin Cui16f7f8d2014-11-04 11:08:05 -08001143 if (file_offset < 0) {
Martin Stjernholm9fe38262019-08-27 17:08:45 +01001144 DL_OPEN_ERR("file offset for the library \"%s\" is negative: %" PRId64, name, file_offset);
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001145 return false;
Yabin Cui16f7f8d2014-11-04 11:08:05 -08001146 }
Dmitriy Ivanov07e5bc12014-10-03 17:52:44 -07001147
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001148 struct stat file_stat;
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001149 if (TEMP_FAILURE_RETRY(fstat(task->get_fd(), &file_stat)) != 0) {
Martin Stjernholm9fe38262019-08-27 17:08:45 +01001150 DL_OPEN_ERR("unable to stat file for the library \"%s\": %s", name, strerror(errno));
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001151 return false;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001152 }
Yabin Cui16f7f8d2014-11-04 11:08:05 -08001153 if (file_offset >= file_stat.st_size) {
Martin Stjernholm9fe38262019-08-27 17:08:45 +01001154 DL_OPEN_ERR("file offset for the library \"%s\" >= file size: %" PRId64 " >= %" PRId64,
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07001155 name, file_offset, file_stat.st_size);
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001156 return false;
Yabin Cui16f7f8d2014-11-04 11:08:05 -08001157 }
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001158
1159 // Check for symlink and other situations where
Dmitriy Ivanov9b821362015-04-02 16:03:56 -07001160 // file can have different names, unless ANDROID_DLEXT_FORCE_LOAD is set
1161 if (extinfo == nullptr || (extinfo->flags & ANDROID_DLEXT_FORCE_LOAD) == 0) {
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001162 soinfo* si = nullptr;
1163 if (find_loaded_library_by_inode(ns, file_stat, file_offset, search_linked_namespaces, &si)) {
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001164 LD_LOG(kLogDlopen,
1165 "load_library(ns=%s, task=%s): Already loaded under different name/path \"%s\" - "
1166 "will return existing soinfo",
1167 ns->get_name(), name, si->get_realpath());
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001168 task->set_soinfo(si);
1169 return true;
1170 }
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001171 }
Dmitriy Ivanovd59e5002014-05-09 09:10:14 -07001172
Dmitriy Ivanove8ba50f2014-09-15 17:00:10 -07001173 if ((rtld_flags & RTLD_NOLOAD) != 0) {
Martin Stjernholm9fe38262019-08-27 17:08:45 +01001174 DL_OPEN_ERR("library \"%s\" wasn't loaded and RTLD_NOLOAD prevented it", name);
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001175 return false;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001176 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001177
Dimitry Ivanovbf34ba32017-04-21 13:12:05 -07001178 struct statfs fs_stat;
1179 if (TEMP_FAILURE_RETRY(fstatfs(task->get_fd(), &fs_stat)) != 0) {
Martin Stjernholm9fe38262019-08-27 17:08:45 +01001180 DL_OPEN_ERR("unable to fstatfs file for the library \"%s\": %s", name, strerror(errno));
Dimitry Ivanovbf34ba32017-04-21 13:12:05 -07001181 return false;
1182 }
1183
1184 // do not check accessibility using realpath if fd is located on tmpfs
1185 // this enables use of memfd_create() for apps
1186 if ((fs_stat.f_type != TMPFS_MAGIC) && (!ns->is_accessible(realpath))) {
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07001187 // TODO(dimitry): workaround for http://b/26394120 - the grey-list
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001188
1189 // TODO(dimitry) before O release: add a namespace attribute to have this enabled
1190 // only for classloader-namespaces
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07001191 const soinfo* needed_by = task->is_dt_needed() ? task->get_needed_by() : nullptr;
Dimitry Ivanov35c8e3b2017-02-27 12:17:47 -08001192 if (is_greylisted(ns, name, needed_by)) {
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07001193 // print warning only if needed by non-system library
1194 if (needed_by == nullptr || !is_system_library(needed_by->get_realpath())) {
1195 const soinfo* needed_or_dlopened_by = task->get_needed_by();
1196 const char* sopath = needed_or_dlopened_by == nullptr ? "(unknown)" :
1197 needed_or_dlopened_by->get_realpath();
Elliott Hughes95c6cd72019-12-20 13:26:14 -08001198 DL_WARN_documented_change(24,
Elliott Hughes9076b0c2018-02-28 11:29:45 -08001199 "private-api-enforced-for-api-level-24",
1200 "library \"%s\" (\"%s\") needed or dlopened by \"%s\" "
1201 "is not accessible by namespace \"%s\"",
1202 name, realpath.c_str(), sopath, ns->get_name());
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07001203 add_dlwarning(sopath, "unauthorized access to", name);
1204 }
1205 } else {
1206 // do not load libraries if they are not accessible for the specified namespace.
1207 const char* needed_or_dlopened_by = task->get_needed_by() == nullptr ?
1208 "(unknown)" :
1209 task->get_needed_by()->get_realpath();
Dimitry Ivanovd17a3772016-03-01 13:11:28 -08001210
Martin Stjernholm9fe38262019-08-27 17:08:45 +01001211 DL_OPEN_ERR("library \"%s\" needed or dlopened by \"%s\" is not accessible for the namespace \"%s\"",
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07001212 name, needed_or_dlopened_by, ns->get_name());
Dimitry Ivanovd17a3772016-03-01 13:11:28 -08001213
Dimitry Ivanov35c8e3b2017-02-27 12:17:47 -08001214 // do not print this if a library is in the list of shared libraries for linked namespaces
1215 if (!maybe_accessible_via_namespace_links(ns, name)) {
1216 PRINT("library \"%s\" (\"%s\") needed or dlopened by \"%s\" is not accessible for the"
1217 " namespace: [name=\"%s\", ld_library_paths=\"%s\", default_library_paths=\"%s\","
1218 " permitted_paths=\"%s\"]",
1219 name, realpath.c_str(),
1220 needed_or_dlopened_by,
1221 ns->get_name(),
1222 android::base::Join(ns->get_ld_library_paths(), ':').c_str(),
1223 android::base::Join(ns->get_default_library_paths(), ':').c_str(),
1224 android::base::Join(ns->get_permitted_paths(), ':').c_str());
1225 }
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07001226 return false;
1227 }
Dimitry Ivanov22840aa2015-12-04 18:28:49 -08001228 }
1229
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001230 soinfo* si = soinfo_alloc(ns, realpath.c_str(), &file_stat, file_offset, rtld_flags);
Dmitriy Ivanovd59e5002014-05-09 09:10:14 -07001231
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001232 task->set_soinfo(si);
1233
1234 // Read the ELF header and some of the segments.
1235 if (!task->read(realpath.c_str(), file_stat.st_size)) {
Ryan Prichard4fa6d992020-03-26 21:31:43 -07001236 task->remove_cached_elf_reader();
Dmitriy Ivanovfd7a91e2015-11-06 10:44:37 -08001237 task->set_soinfo(nullptr);
Ryan Prichard4fa6d992020-03-26 21:31:43 -07001238 soinfo_free(si);
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001239 return false;
1240 }
1241
1242 // find and set DT_RUNPATH and dt_soname
1243 // Note that these field values are temporary and are
1244 // going to be overwritten on soinfo::prelink_image
1245 // with values from PT_LOAD segments.
1246 const ElfReader& elf_reader = task->get_elf_reader();
1247 for (const ElfW(Dyn)* d = elf_reader.dynamic(); d->d_tag != DT_NULL; ++d) {
1248 if (d->d_tag == DT_RUNPATH) {
1249 si->set_dt_runpath(elf_reader.get_string(d->d_un.d_val));
1250 }
1251 if (d->d_tag == DT_SONAME) {
1252 si->set_soname(elf_reader.get_string(d->d_un.d_val));
1253 }
1254 }
1255
Dan Willemsen5038ef62018-10-21 17:45:04 -07001256#if !defined(__ANDROID__)
1257 // Bionic on the host currently uses some Android prebuilts, which don't set
1258 // DT_RUNPATH with any relative paths, so they can't find their dependencies.
1259 // b/118058804
1260 if (si->get_dt_runpath().empty()) {
1261 si->set_dt_runpath("$ORIGIN/../lib64:$ORIGIN/lib64");
1262 }
1263#endif
1264
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001265 for_each_dt_needed(task->get_elf_reader(), [&](const char* name) {
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001266 LD_LOG(kLogDlopen, "load_library(ns=%s, task=%s): Adding DT_NEEDED task: %s",
1267 ns->get_name(), task->get_name(), name);
Jiyong Park02586a22017-05-20 01:01:24 +09001268 load_tasks->push_back(LoadTask::create(name, si, ns, task->get_readers_map()));
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001269 });
Dmitriy Ivanovd59e5002014-05-09 09:10:14 -07001270
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001271 return true;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001272}
1273
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001274static bool load_library(android_namespace_t* ns,
1275 LoadTask* task,
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001276 ZipArchiveCache* zip_archive_cache,
1277 LoadTaskList* load_tasks,
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001278 int rtld_flags,
1279 bool search_linked_namespaces) {
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001280 const char* name = task->get_name();
1281 soinfo* needed_by = task->get_needed_by();
1282 const android_dlextinfo* extinfo = task->get_extinfo();
1283
Spencer Low0346ad72015-04-22 18:06:51 -07001284 if (extinfo != nullptr && (extinfo->flags & ANDROID_DLEXT_USE_LIBRARY_FD) != 0) {
Ryan Prichardaa2db962020-03-24 20:25:53 -07001285 off64_t file_offset = 0;
Spencer Low0346ad72015-04-22 18:06:51 -07001286 if ((extinfo->flags & ANDROID_DLEXT_USE_LIBRARY_FD_OFFSET) != 0) {
1287 file_offset = extinfo->library_fd_offset;
1288 }
Dmitriy Ivanova1feb112015-10-01 18:41:57 -07001289
Ryan Prichardaa2db962020-03-24 20:25:53 -07001290 std::string realpath;
Dmitriy Ivanova1feb112015-10-01 18:41:57 -07001291 if (!realpath_fd(extinfo->library_fd, &realpath)) {
Tom Cherry66bc4282018-11-08 13:40:52 -08001292 if (!is_first_stage_init()) {
1293 PRINT(
1294 "warning: unable to get realpath for the library \"%s\" by extinfo->library_fd. "
1295 "Will use given name.",
1296 name);
1297 }
Dmitriy Ivanova1feb112015-10-01 18:41:57 -07001298 realpath = name;
1299 }
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001300
1301 task->set_fd(extinfo->library_fd, false);
1302 task->set_file_offset(file_offset);
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001303 return load_library(ns, task, load_tasks, rtld_flags, realpath, search_linked_namespaces);
Spencer Low0346ad72015-04-22 18:06:51 -07001304 }
1305
Martin Stjernholm9fe38262019-08-27 17:08:45 +01001306 LD_LOG(kLogDlopen,
1307 "load_library(ns=%s, task=%s, flags=0x%x, search_linked_namespaces=%d): calling "
Ryan Prichardaa2db962020-03-24 20:25:53 -07001308 "open_library",
1309 ns->get_name(), name, rtld_flags, search_linked_namespaces);
Martin Stjernholm9fe38262019-08-27 17:08:45 +01001310
Spencer Low0346ad72015-04-22 18:06:51 -07001311 // Open the file.
Ryan Prichardaa2db962020-03-24 20:25:53 -07001312 off64_t file_offset;
1313 std::string realpath;
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001314 int fd = open_library(ns, zip_archive_cache, name, needed_by, &file_offset, &realpath);
Spencer Low0346ad72015-04-22 18:06:51 -07001315 if (fd == -1) {
Josh Gao16269572019-10-29 13:41:00 -07001316 if (task->is_dt_needed()) {
1317 if (needed_by->is_main_executable()) {
1318 DL_OPEN_ERR("library \"%s\" not found: needed by main executable", name);
1319 } else {
1320 DL_OPEN_ERR("library \"%s\" not found: needed by %s in namespace %s", name,
1321 needed_by->get_realpath(), task->get_start_from()->get_name());
1322 }
1323 } else {
1324 DL_OPEN_ERR("library \"%s\" not found", name);
1325 }
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001326 return false;
Spencer Low0346ad72015-04-22 18:06:51 -07001327 }
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001328
1329 task->set_fd(fd, true);
1330 task->set_file_offset(file_offset);
1331
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001332 return load_library(ns, task, load_tasks, rtld_flags, realpath, search_linked_namespaces);
Spencer Low0346ad72015-04-22 18:06:51 -07001333}
1334
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001335static bool find_loaded_library_by_soname(android_namespace_t* ns,
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001336 const char* name,
1337 soinfo** candidate) {
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001338 return !ns->soinfo_list().visit([&](soinfo* si) {
Dmitriy Ivanov618f1a32015-03-17 20:06:36 -07001339 const char* soname = si->get_soname();
1340 if (soname != nullptr && (strcmp(name, soname) == 0)) {
Dimitry Ivanov3bd90612017-02-01 08:54:43 -08001341 *candidate = si;
1342 return false;
Ard Biesheuvel12c78bb2012-08-14 12:30:09 +02001343 }
Dmitriy Ivanova9703332015-06-16 15:38:21 -07001344
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001345 return true;
1346 });
Ard Biesheuvel12c78bb2012-08-14 12:30:09 +02001347}
1348
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001349// Returns true if library was found and false otherwise
1350static bool find_loaded_library_by_soname(android_namespace_t* ns,
1351 const char* name,
1352 bool search_linked_namespaces,
1353 soinfo** candidate) {
1354 *candidate = nullptr;
1355
1356 // Ignore filename with path.
1357 if (strchr(name, '/') != nullptr) {
1358 return false;
1359 }
1360
1361 bool found = find_loaded_library_by_soname(ns, name, candidate);
1362
1363 if (!found && search_linked_namespaces) {
1364 // if a library was not found - look into linked namespaces
1365 for (auto& link : ns->linked_namespaces()) {
1366 if (!link.is_accessible(name)) {
1367 continue;
1368 }
1369
1370 android_namespace_t* linked_ns = link.linked_namespace();
1371
1372 if (find_loaded_library_by_soname(linked_ns, name, candidate)) {
1373 return true;
1374 }
1375 }
1376 }
1377
1378 return found;
1379}
1380
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001381static bool find_library_in_linked_namespace(const android_namespace_link_t& namespace_link,
Jiyong Park02586a22017-05-20 01:01:24 +09001382 LoadTask* task) {
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001383 android_namespace_t* ns = namespace_link.linked_namespace();
1384
1385 soinfo* candidate;
1386 bool loaded = false;
1387
1388 std::string soname;
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001389 if (find_loaded_library_by_soname(ns, task->get_name(), false, &candidate)) {
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001390 loaded = true;
1391 soname = candidate->get_soname();
1392 } else {
1393 soname = resolve_soname(task->get_name());
1394 }
1395
1396 if (!namespace_link.is_accessible(soname.c_str())) {
1397 // the library is not accessible via namespace_link
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001398 LD_LOG(kLogDlopen,
1399 "find_library_in_linked_namespace(ns=%s, task=%s): Not accessible (soname=%s)",
1400 ns->get_name(), task->get_name(), soname.c_str());
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001401 return false;
1402 }
1403
1404 // if library is already loaded - return it
1405 if (loaded) {
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001406 LD_LOG(kLogDlopen, "find_library_in_linked_namespace(ns=%s, task=%s): Already loaded",
1407 ns->get_name(), task->get_name());
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001408 task->set_soinfo(candidate);
1409 return true;
1410 }
1411
Jiyong Park02586a22017-05-20 01:01:24 +09001412 // returning true with empty soinfo means that the library is okay to be
Logan Chien9ee45912018-01-18 12:05:09 +08001413 // loaded in the namespace but has not yet been loaded there before.
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001414 LD_LOG(kLogDlopen, "find_library_in_linked_namespace(ns=%s, task=%s): Ok to load", ns->get_name(),
1415 task->get_name());
Jiyong Park02586a22017-05-20 01:01:24 +09001416 task->set_soinfo(nullptr);
1417 return true;
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001418}
1419
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001420static bool find_library_internal(android_namespace_t* ns,
1421 LoadTask* task,
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001422 ZipArchiveCache* zip_archive_cache,
1423 LoadTaskList* load_tasks,
Ryan Prichard323d7df2020-03-24 21:19:06 -07001424 int rtld_flags) {
Dmitriy Ivanova9703332015-06-16 15:38:21 -07001425 soinfo* candidate;
1426
Ryan Prichard323d7df2020-03-24 21:19:06 -07001427 if (find_loaded_library_by_soname(ns, task->get_name(), true /* search_linked_namespaces */,
1428 &candidate)) {
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001429 LD_LOG(kLogDlopen,
1430 "find_library_internal(ns=%s, task=%s): Already loaded (by soname): %s",
1431 ns->get_name(), task->get_name(), candidate->get_realpath());
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001432 task->set_soinfo(candidate);
1433 return true;
Dmitriy Ivanova9703332015-06-16 15:38:21 -07001434 }
Dmitriy Ivanovb648a8a2014-05-19 15:06:58 -07001435
1436 // Library might still be loaded, the accurate detection
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001437 // of this fact is done by load_library.
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001438 TRACE("[ \"%s\" find_loaded_library_by_soname failed (*candidate=%s@%p). Trying harder... ]",
1439 task->get_name(), candidate == nullptr ? "n/a" : candidate->get_realpath(), candidate);
Dmitriy Ivanova9703332015-06-16 15:38:21 -07001440
Ryan Prichard323d7df2020-03-24 21:19:06 -07001441 if (load_library(ns, task, zip_archive_cache, load_tasks, rtld_flags,
1442 true /* search_linked_namespaces */)) {
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001443 return true;
1444 }
1445
Jiyong Parkefc503d2019-02-12 01:08:57 +09001446 // TODO(dimitry): workaround for http://b/26394120 (the grey-list)
1447 if (ns->is_greylist_enabled() && is_greylisted(ns, task->get_name(), task->get_needed_by())) {
1448 // For the libs in the greylist, switch to the default namespace and then
1449 // try the load again from there. The library could be loaded from the
1450 // default namespace or from another namespace (e.g. runtime) that is linked
1451 // from the default namespace.
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001452 LD_LOG(kLogDlopen,
1453 "find_library_internal(ns=%s, task=%s): Greylisted library - trying namespace %s",
1454 ns->get_name(), task->get_name(), g_default_namespace.get_name());
Jiyong Parkefc503d2019-02-12 01:08:57 +09001455 ns = &g_default_namespace;
1456 if (load_library(ns, task, zip_archive_cache, load_tasks, rtld_flags,
Ryan Prichard323d7df2020-03-24 21:19:06 -07001457 true /* search_linked_namespaces */)) {
Jiyong Parkefc503d2019-02-12 01:08:57 +09001458 return true;
1459 }
1460 }
1461 // END OF WORKAROUND
1462
Ryan Prichard323d7df2020-03-24 21:19:06 -07001463 // if a library was not found - look into linked namespaces
1464 // preserve current dlerror in the case it fails.
1465 DlErrorRestorer dlerror_restorer;
1466 LD_LOG(kLogDlopen, "find_library_internal(ns=%s, task=%s): Trying %zu linked namespaces",
1467 ns->get_name(), task->get_name(), ns->linked_namespaces().size());
1468 for (auto& linked_namespace : ns->linked_namespaces()) {
1469 if (find_library_in_linked_namespace(linked_namespace, task)) {
1470 // Library is already loaded.
1471 if (task->get_soinfo() != nullptr) {
1472 // n.b. This code path runs when find_library_in_linked_namespace found an already-loaded
1473 // library by soname. That should only be possible with a greylist lookup, where we switch
1474 // the namespace, because otherwise, find_library_in_linked_namespace is duplicating the
1475 // soname scan done in this function's first call to find_loaded_library_by_soname.
1476 return true;
1477 }
1478
1479 if (load_library(linked_namespace.linked_namespace(), task, zip_archive_cache, load_tasks,
1480 rtld_flags, false /* search_linked_namespaces */)) {
1481 LD_LOG(kLogDlopen, "find_library_internal(ns=%s, task=%s): Found in linked namespace %s",
1482 ns->get_name(), task->get_name(), linked_namespace.linked_namespace()->get_name());
1483 return true;
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001484 }
1485 }
1486 }
1487
1488 return false;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001489}
1490
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001491static void soinfo_unload(soinfo* si);
1492
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001493static void shuffle(std::vector<LoadTask*>* v) {
Tom Cherry66bc4282018-11-08 13:40:52 -08001494 if (is_first_stage_init()) {
1495 // arc4random* is not available in first stage init because /dev/random
1496 // hasn't yet been created.
Jiyong Park31cd08f2018-06-01 19:18:56 +09001497 return;
1498 }
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001499 for (size_t i = 0, size = v->size(); i < size; ++i) {
1500 size_t n = size - i;
1501 size_t r = arc4random_uniform(n);
1502 std::swap((*v)[n-1], (*v)[r]);
1503 }
1504}
1505
Evgenii Stepanov0cdef7e2015-07-06 17:56:31 -07001506// add_as_children - add first-level loaded libraries (i.e. library_names[], but
1507// not their transitive dependencies) as children of the start_with library.
1508// This is false when find_libraries is called for dlopen(), when newly loaded
1509// libraries must form a disjoint tree.
Dimitry Ivanov3f660572016-09-09 10:00:39 -07001510bool find_libraries(android_namespace_t* ns,
1511 soinfo* start_with,
1512 const char* const library_names[],
1513 size_t library_names_count,
1514 soinfo* soinfos[],
1515 std::vector<soinfo*>* ld_preloads,
1516 size_t ld_preloads_count,
1517 int rtld_flags,
1518 const android_dlextinfo* extinfo,
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001519 bool add_as_children,
Jiyong Park02586a22017-05-20 01:01:24 +09001520 std::vector<android_namespace_t*>* namespaces) {
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001521 // Step 0: prepare.
dimitry965d06d2017-11-28 16:03:07 +01001522 std::unordered_map<const soinfo*, ElfReader> readers_map;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001523 LoadTaskList load_tasks;
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001524
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -07001525 for (size_t i = 0; i < library_names_count; ++i) {
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001526 const char* name = library_names[i];
Jiyong Park02586a22017-05-20 01:01:24 +09001527 load_tasks.push_back(LoadTask::create(name, start_with, ns, &readers_map));
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001528 }
1529
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -07001530 // If soinfos array is null allocate one on stack.
1531 // The array is needed in case of failure; for example
1532 // when library_names[] = {libone.so, libtwo.so} and libone.so
1533 // is loaded correctly but libtwo.so failed for some reason.
1534 // In this case libone.so should be unloaded on return.
1535 // See also implementation of failure_guard below.
1536
1537 if (soinfos == nullptr) {
1538 size_t soinfos_size = sizeof(soinfo*)*library_names_count;
1539 soinfos = reinterpret_cast<soinfo**>(alloca(soinfos_size));
1540 memset(soinfos, 0, soinfos_size);
1541 }
1542
1543 // list of libraries to link - see step 2.
1544 size_t soinfos_count = 0;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001545
Tom Cherryb8ab6182017-04-05 16:20:29 -07001546 auto scope_guard = android::base::make_scope_guard([&]() {
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001547 for (LoadTask* t : load_tasks) {
1548 LoadTask::deleter(t);
1549 }
1550 });
1551
Dmitriy Ivanovb4827502015-09-28 16:38:31 -07001552 ZipArchiveCache zip_archive_cache;
1553
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001554 // Step 1: expand the list of load_tasks to include
1555 // all DT_NEEDED libraries (do not load them just yet)
1556 for (size_t i = 0; i<load_tasks.size(); ++i) {
1557 LoadTask* task = load_tasks[i];
Evgenii Stepanov68650822015-06-10 13:38:39 -07001558 soinfo* needed_by = task->get_needed_by();
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001559
Dmitriy Ivanovedfc9f62015-09-02 16:32:02 -07001560 bool is_dt_needed = needed_by != nullptr && (needed_by != start_with || add_as_children);
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001561 task->set_extinfo(is_dt_needed ? nullptr : extinfo);
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07001562 task->set_dt_needed(is_dt_needed);
Dmitriy Ivanovedfc9f62015-09-02 16:32:02 -07001563
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001564 LD_LOG(kLogDlopen, "find_libraries(ns=%s): task=%s, is_dt_needed=%d", ns->get_name(),
1565 task->get_name(), is_dt_needed);
1566
Jiyong Park02586a22017-05-20 01:01:24 +09001567 // Note: start from the namespace that is stored in the LoadTask. This namespace
1568 // is different from the current namespace when the LoadTask is for a transitive
1569 // dependency and the lib that created the LoadTask is not found in the
1570 // current namespace but in one of the linked namespace.
1571 if (!find_library_internal(const_cast<android_namespace_t*>(task->get_start_from()),
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001572 task,
1573 &zip_archive_cache,
1574 &load_tasks,
Ryan Prichard323d7df2020-03-24 21:19:06 -07001575 rtld_flags)) {
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001576 return false;
1577 }
1578
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001579 soinfo* si = task->get_soinfo();
1580
Dmitriy Ivanovedfc9f62015-09-02 16:32:02 -07001581 if (is_dt_needed) {
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001582 needed_by->add_child(si);
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08001583 }
1584
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -07001585 // When ld_preloads is not null, the first
1586 // ld_preloads_count libs are in fact ld_preloads.
1587 if (ld_preloads != nullptr && soinfos_count < ld_preloads_count) {
Dmitriy Ivanovd165f562015-03-23 18:43:02 -07001588 ld_preloads->push_back(si);
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001589 }
1590
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -07001591 if (soinfos_count < library_names_count) {
1592 soinfos[soinfos_count++] = si;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001593 }
1594 }
1595
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001596 // Step 2: Load libraries in random order (see b/24047022)
1597 LoadTaskList load_list;
1598 for (auto&& task : load_tasks) {
1599 soinfo* si = task->get_soinfo();
1600 auto pred = [&](const LoadTask* t) {
1601 return t->get_soinfo() == si;
1602 };
1603
1604 if (!si->is_linked() &&
1605 std::find_if(load_list.begin(), load_list.end(), pred) == load_list.end() ) {
1606 load_list.push_back(task);
1607 }
1608 }
Torne (Richard Coles)efbe9a52018-10-17 15:59:38 -04001609 bool reserved_address_recursive = false;
1610 if (extinfo) {
1611 reserved_address_recursive = extinfo->flags & ANDROID_DLEXT_RESERVED_ADDRESS_RECURSIVE;
1612 }
1613 if (!reserved_address_recursive) {
1614 // Shuffle the load order in the normal case, but not if we are loading all
1615 // the libraries to a reserved address range.
1616 shuffle(&load_list);
1617 }
1618
1619 // Set up address space parameters.
1620 address_space_params extinfo_params, default_params;
1621 size_t relro_fd_offset = 0;
1622 if (extinfo) {
1623 if (extinfo->flags & ANDROID_DLEXT_RESERVED_ADDRESS) {
1624 extinfo_params.start_addr = extinfo->reserved_addr;
1625 extinfo_params.reserved_size = extinfo->reserved_size;
1626 extinfo_params.must_use_address = true;
1627 } else if (extinfo->flags & ANDROID_DLEXT_RESERVED_ADDRESS_HINT) {
1628 extinfo_params.start_addr = extinfo->reserved_addr;
1629 extinfo_params.reserved_size = extinfo->reserved_size;
1630 }
1631 }
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001632
1633 for (auto&& task : load_list) {
Torne (Richard Coles)efbe9a52018-10-17 15:59:38 -04001634 address_space_params* address_space =
1635 (reserved_address_recursive || !task->is_dt_needed()) ? &extinfo_params : &default_params;
1636 if (!task->load(address_space)) {
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001637 return false;
1638 }
1639 }
1640
1641 // Step 3: pre-link all DT_NEEDED libraries in breadth first order.
1642 for (auto&& task : load_tasks) {
1643 soinfo* si = task->get_soinfo();
1644 if (!si->is_linked() && !si->prelink_image()) {
1645 return false;
1646 }
Ryan Pricharde5e69e02019-01-01 18:53:48 -08001647 register_soinfo_tls(si);
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001648 }
1649
Jiyong Park02586a22017-05-20 01:01:24 +09001650 // Step 4: Construct the global group. Note: DF_1_GLOBAL bit of a library is
1651 // determined at step 3.
1652
1653 // Step 4-1: DF_1_GLOBAL bit is force set for LD_PRELOADed libs because they
1654 // must be added to the global group
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001655 if (ld_preloads != nullptr) {
1656 for (auto&& si : *ld_preloads) {
1657 si->set_dt_flags_1(si->get_dt_flags_1() | DF_1_GLOBAL);
1658 }
1659 }
1660
Jiyong Park02586a22017-05-20 01:01:24 +09001661 // Step 4-2: Gather all DF_1_GLOBAL libs which were newly loaded during this
1662 // run. These will be the new member of the global group
1663 soinfo_list_t new_global_group_members;
1664 for (auto&& task : load_tasks) {
1665 soinfo* si = task->get_soinfo();
1666 if (!si->is_linked() && (si->get_dt_flags_1() & DF_1_GLOBAL) != 0) {
1667 new_global_group_members.push_back(si);
1668 }
1669 }
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001670
Jiyong Park02586a22017-05-20 01:01:24 +09001671 // Step 4-3: Add the new global group members to all the linked namespaces
Jiyong Park01162f22017-10-16 15:31:09 +09001672 if (namespaces != nullptr) {
Jiyong Park02586a22017-05-20 01:01:24 +09001673 for (auto linked_ns : *namespaces) {
Jiyong Park01162f22017-10-16 15:31:09 +09001674 for (auto si : new_global_group_members) {
1675 if (si->get_primary_namespace() != linked_ns) {
1676 linked_ns->add_soinfo(si);
1677 si->add_secondary_namespace(linked_ns);
1678 }
Jiyong Park02586a22017-05-20 01:01:24 +09001679 }
1680 }
1681 }
1682
dimitry965d06d2017-11-28 16:03:07 +01001683 // Step 5: Collect roots of local_groups.
1684 // Whenever needed_by->si link crosses a namespace boundary it forms its own local_group.
1685 // Here we collect new roots to link them separately later on. Note that we need to avoid
1686 // collecting duplicates. Also the order is important. They need to be linked in the same
1687 // BFS order we link individual libraries.
1688 std::vector<soinfo*> local_group_roots;
1689 if (start_with != nullptr && add_as_children) {
1690 local_group_roots.push_back(start_with);
1691 } else {
1692 CHECK(soinfos_count == 1);
1693 local_group_roots.push_back(soinfos[0]);
1694 }
1695
Jiyong Park02586a22017-05-20 01:01:24 +09001696 for (auto&& task : load_tasks) {
1697 soinfo* si = task->get_soinfo();
dimitry965d06d2017-11-28 16:03:07 +01001698 soinfo* needed_by = task->get_needed_by();
1699 bool is_dt_needed = needed_by != nullptr && (needed_by != start_with || add_as_children);
1700 android_namespace_t* needed_by_ns =
1701 is_dt_needed ? needed_by->get_primary_namespace() : ns;
1702
1703 if (!si->is_linked() && si->get_primary_namespace() != needed_by_ns) {
1704 auto it = std::find(local_group_roots.begin(), local_group_roots.end(), si);
1705 LD_LOG(kLogDlopen,
1706 "Crossing namespace boundary (si=%s@%p, si_ns=%s@%p, needed_by=%s@%p, ns=%s@%p, needed_by_ns=%s@%p) adding to local_group_roots: %s",
1707 si->get_realpath(),
1708 si,
1709 si->get_primary_namespace()->get_name(),
1710 si->get_primary_namespace(),
1711 needed_by == nullptr ? "(nullptr)" : needed_by->get_realpath(),
1712 needed_by,
1713 ns->get_name(),
1714 ns,
1715 needed_by_ns->get_name(),
1716 needed_by_ns,
1717 it == local_group_roots.end() ? "yes" : "no");
1718
1719 if (it == local_group_roots.end()) {
1720 local_group_roots.push_back(si);
Jiyong Park02586a22017-05-20 01:01:24 +09001721 }
1722 }
1723 }
1724
dimitry965d06d2017-11-28 16:03:07 +01001725 // Step 6: Link all local groups
1726 for (auto root : local_group_roots) {
1727 soinfo_list_t local_group;
1728 android_namespace_t* local_group_ns = root->get_primary_namespace();
1729
1730 walk_dependencies_tree(root,
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -07001731 [&] (soinfo* si) {
dimitry965d06d2017-11-28 16:03:07 +01001732 if (local_group_ns->is_accessible(si)) {
1733 local_group.push_back(si);
1734 return kWalkContinue;
1735 } else {
1736 return kWalkSkip;
1737 }
1738 });
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -07001739
dimitry965d06d2017-11-28 16:03:07 +01001740 soinfo_list_t global_group = local_group_ns->get_global_group();
Ryan Prichard339ecef2020-01-02 16:36:06 -08001741 SymbolLookupList lookup_list(global_group, local_group);
1742 soinfo* local_group_root = local_group.front();
1743
dimitry965d06d2017-11-28 16:03:07 +01001744 bool linked = local_group.visit([&](soinfo* si) {
Torne (Richard Coles)5d103742019-04-11 12:25:06 -04001745 // Even though local group may contain accessible soinfos from other namespaces
dimitry965d06d2017-11-28 16:03:07 +01001746 // we should avoid linking them (because if they are not linked -> they
1747 // are in the local_group_roots and will be linked later).
1748 if (!si->is_linked() && si->get_primary_namespace() == local_group_ns) {
Torne (Richard Coles)5d103742019-04-11 12:25:06 -04001749 const android_dlextinfo* link_extinfo = nullptr;
1750 if (si == soinfos[0] || reserved_address_recursive) {
1751 // Only forward extinfo for the first library unless the recursive
1752 // flag is set.
1753 link_extinfo = extinfo;
1754 }
Peter Collingbourne191ecdc2019-08-07 19:06:00 -07001755 if (__libc_shared_globals()->load_hook) {
1756 __libc_shared_globals()->load_hook(si->load_bias, si->phdr, si->phnum);
1757 }
Ryan Prichard339ecef2020-01-02 16:36:06 -08001758 lookup_list.set_dt_symbolic_lib(si->has_DT_SYMBOLIC ? si : nullptr);
1759 if (!si->link_image(lookup_list, local_group_root, link_extinfo, &relro_fd_offset) ||
dimitry965d06d2017-11-28 16:03:07 +01001760 !get_cfi_shadow()->AfterLoad(si, solist_get_head())) {
1761 return false;
1762 }
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001763 }
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -07001764
dimitry965d06d2017-11-28 16:03:07 +01001765 return true;
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001766 });
Elliott Hughes27f18062017-11-29 18:47:42 +00001767
dimitry965d06d2017-11-28 16:03:07 +01001768 if (!linked) {
1769 return false;
1770 }
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001771 }
1772
dimitry965d06d2017-11-28 16:03:07 +01001773 // Step 7: Mark all load_tasks as linked and increment refcounts
1774 // for references between load_groups (at this point it does not matter if
1775 // referenced load_groups were loaded by previous dlopen or as part of this
1776 // one on step 6)
1777 if (start_with != nullptr && add_as_children) {
1778 start_with->set_linked();
1779 }
1780
1781 for (auto&& task : load_tasks) {
1782 soinfo* si = task->get_soinfo();
1783 si->set_linked();
1784 }
1785
1786 for (auto&& task : load_tasks) {
1787 soinfo* si = task->get_soinfo();
1788 soinfo* needed_by = task->get_needed_by();
1789 if (needed_by != nullptr &&
1790 needed_by != start_with &&
1791 needed_by->get_local_group_root() != si->get_local_group_root()) {
1792 si->increment_ref_count();
1793 }
1794 }
1795
1796
1797 return true;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001798}
1799
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001800static soinfo* find_library(android_namespace_t* ns,
1801 const char* name, int rtld_flags,
Evgenii Stepanov0cdef7e2015-07-06 17:56:31 -07001802 const android_dlextinfo* extinfo,
1803 soinfo* needed_by) {
dimitry965d06d2017-11-28 16:03:07 +01001804 soinfo* si = nullptr;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001805
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08001806 if (name == nullptr) {
Dimitry Ivanov3f660572016-09-09 10:00:39 -07001807 si = solist_get_somain();
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001808 } else if (!find_libraries(ns,
1809 needed_by,
1810 &name,
1811 1,
1812 &si,
1813 nullptr,
1814 0,
1815 rtld_flags,
1816 extinfo,
Ryan Prichard323d7df2020-03-24 21:19:06 -07001817 false /* add_as_children */)) {
dimitry965d06d2017-11-28 16:03:07 +01001818 if (si != nullptr) {
1819 soinfo_unload(si);
1820 }
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001821 return nullptr;
1822 }
1823
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001824 si->increment_ref_count();
1825
Elliott Hughesd23736e2012-11-01 15:16:56 -07001826 return si;
1827}
Elliott Hughesbedfe382012-08-14 14:07:59 -07001828
dimitry06016f22018-01-05 11:39:28 +01001829static void soinfo_unload_impl(soinfo* root) {
Dimitry Ivanov6705e8c2017-03-21 10:29:06 -07001830 ScopedTrace trace((std::string("unload ") + root->get_realpath()).c_str());
dimitry06016f22018-01-05 11:39:28 +01001831 bool is_linked = root->is_linked();
Dimitry Ivanov6705e8c2017-03-21 10:29:06 -07001832
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08001833 if (!root->can_unload()) {
dimitryc92ce712017-10-27 14:12:53 +02001834 LD_LOG(kLogDlopen,
1835 "... dlclose(root=\"%s\"@%p) ... not unloading - the load group is flagged with NODELETE",
1836 root->get_realpath(),
1837 root);
Dmitriy Ivanov1b20daf2014-05-19 15:06:58 -07001838 return;
1839 }
1840
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08001841
Dimitry Ivanovb943f302016-08-03 16:00:10 -07001842 soinfo_list_t unload_list;
dimitry965d06d2017-11-28 16:03:07 +01001843 unload_list.push_back(root);
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001844
Dimitry Ivanovb943f302016-08-03 16:00:10 -07001845 soinfo_list_t local_unload_list;
1846 soinfo_list_t external_unload_list;
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001847 soinfo* si = nullptr;
1848
1849 while ((si = unload_list.pop_front()) != nullptr) {
1850 if (local_unload_list.contains(si)) {
1851 continue;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001852 }
Elliott Hughesd23736e2012-11-01 15:16:56 -07001853
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001854 local_unload_list.push_back(si);
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08001855
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001856 if (si->has_min_version(0)) {
1857 soinfo* child = nullptr;
1858 while ((child = si->get_children().pop_front()) != nullptr) {
1859 TRACE("%s@%p needs to unload %s@%p", si->get_realpath(), si,
1860 child->get_realpath(), child);
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08001861
Dimitry Ivanovec90e242017-02-10 11:04:20 -08001862 child->get_parents().remove(si);
1863
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001864 if (local_unload_list.contains(child)) {
1865 continue;
1866 } else if (child->is_linked() && child->get_local_group_root() != root) {
1867 external_unload_list.push_back(child);
Dimitry Ivanovec90e242017-02-10 11:04:20 -08001868 } else if (child->get_parents().empty()) {
1869 unload_list.push_back(child);
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001870 }
1871 }
1872 } else {
Christopher Ferris7a3681e2017-04-24 17:48:32 -07001873 async_safe_fatal("soinfo for \"%s\"@%p has no version", si->get_realpath(), si);
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08001874 }
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001875 }
1876
1877 local_unload_list.for_each([](soinfo* si) {
dimitryc92ce712017-10-27 14:12:53 +02001878 LD_LOG(kLogDlopen,
1879 "... dlclose: calling destructors for \"%s\"@%p ... ",
1880 si->get_realpath(),
1881 si);
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001882 si->call_destructors();
dimitryc92ce712017-10-27 14:12:53 +02001883 LD_LOG(kLogDlopen,
1884 "... dlclose: calling destructors for \"%s\"@%p ... done",
1885 si->get_realpath(),
1886 si);
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001887 });
1888
1889 while ((si = local_unload_list.pop_front()) != nullptr) {
dimitryc92ce712017-10-27 14:12:53 +02001890 LD_LOG(kLogDlopen,
1891 "... dlclose: unloading \"%s\"@%p ...",
1892 si->get_realpath(),
1893 si);
Ryan Pricharda2e83ab2019-08-16 17:25:43 -07001894 ++g_module_unload_counter;
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001895 notify_gdb_of_unload(si);
Ryan Pricharde5e69e02019-01-01 18:53:48 -08001896 unregister_soinfo_tls(si);
Peter Collingbourne65332082019-08-05 16:16:14 -07001897 if (__libc_shared_globals()->unload_hook) {
1898 __libc_shared_globals()->unload_hook(si->load_bias, si->phdr, si->phnum);
1899 }
Evgenii Stepanov0a3637d2016-07-06 13:20:59 -07001900 get_cfi_shadow()->BeforeUnload(si);
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001901 soinfo_free(si);
1902 }
1903
dimitry965d06d2017-11-28 16:03:07 +01001904 if (is_linked) {
1905 while ((si = external_unload_list.pop_front()) != nullptr) {
1906 LD_LOG(kLogDlopen,
1907 "... dlclose: unloading external reference \"%s\"@%p ...",
1908 si->get_realpath(),
1909 si);
1910 soinfo_unload(si);
1911 }
1912 } else {
1913 LD_LOG(kLogDlopen,
1914 "... dlclose: unload_si was not linked - not unloading external references ...");
Dmitriy Ivanova2547052014-11-18 12:03:09 -08001915 }
1916}
1917
dimitry06016f22018-01-05 11:39:28 +01001918static void soinfo_unload(soinfo* unload_si) {
1919 // Note that the library can be loaded but not linked;
1920 // in which case there is no root but we still need
1921 // to walk the tree and unload soinfos involved.
1922 //
1923 // This happens on unsuccessful dlopen, when one of
1924 // the DT_NEEDED libraries could not be linked/found.
1925 bool is_linked = unload_si->is_linked();
1926 soinfo* root = is_linked ? unload_si->get_local_group_root() : unload_si;
1927
1928 LD_LOG(kLogDlopen,
1929 "... dlclose(realpath=\"%s\"@%p) ... load group root is \"%s\"@%p",
1930 unload_si->get_realpath(),
1931 unload_si,
1932 root->get_realpath(),
1933 root);
1934
1935
1936 size_t ref_count = is_linked ? root->decrement_ref_count() : 0;
1937 if (ref_count > 0) {
1938 LD_LOG(kLogDlopen,
1939 "... dlclose(root=\"%s\"@%p) ... not unloading - decrementing ref_count to %zd",
1940 root->get_realpath(),
1941 root,
1942 ref_count);
1943 return;
1944 }
1945
1946 soinfo_unload_impl(root);
1947}
1948
1949void increment_dso_handle_reference_counter(void* dso_handle) {
1950 if (dso_handle == nullptr) {
1951 return;
1952 }
1953
1954 auto it = g_dso_handle_counters.find(dso_handle);
1955 if (it != g_dso_handle_counters.end()) {
1956 CHECK(++it->second != 0);
1957 } else {
1958 soinfo* si = find_containing_library(dso_handle);
1959 if (si != nullptr) {
1960 ProtectedDataGuard guard;
dimitry55547db2018-05-25 14:17:37 +02001961 si->increment_ref_count();
dimitry06016f22018-01-05 11:39:28 +01001962 } else {
1963 async_safe_fatal(
1964 "increment_dso_handle_reference_counter: Couldn't find soinfo by dso_handle=%p",
1965 dso_handle);
1966 }
1967 g_dso_handle_counters[dso_handle] = 1U;
1968 }
1969}
1970
1971void decrement_dso_handle_reference_counter(void* dso_handle) {
1972 if (dso_handle == nullptr) {
1973 return;
1974 }
1975
1976 auto it = g_dso_handle_counters.find(dso_handle);
1977 CHECK(it != g_dso_handle_counters.end());
1978 CHECK(it->second != 0);
1979
1980 if (--it->second == 0) {
1981 soinfo* si = find_containing_library(dso_handle);
1982 if (si != nullptr) {
1983 ProtectedDataGuard guard;
dimitry55547db2018-05-25 14:17:37 +02001984 soinfo_unload(si);
dimitry06016f22018-01-05 11:39:28 +01001985 } else {
1986 async_safe_fatal(
1987 "decrement_dso_handle_reference_counter: Couldn't find soinfo by dso_handle=%p",
1988 dso_handle);
1989 }
1990 g_dso_handle_counters.erase(it);
1991 }
1992}
1993
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08001994static std::string symbol_display_name(const char* sym_name, const char* sym_ver) {
1995 if (sym_ver == nullptr) {
1996 return sym_name;
1997 }
1998
Dimitry Ivanov9cf99cb2015-12-11 14:22:24 -08001999 return std::string(sym_name) + ", version " + sym_ver;
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002000}
2001
Dimitry Ivanovaca299a2016-04-11 12:42:58 -07002002static android_namespace_t* get_caller_namespace(soinfo* caller) {
2003 return caller != nullptr ? caller->get_primary_namespace() : g_anonymous_namespace;
2004}
2005
Elliott Hughesa4aafd12014-01-13 16:37:47 -08002006void do_android_get_LD_LIBRARY_PATH(char* buffer, size_t buffer_size) {
Christopher Ferris052fa3a2014-08-26 20:48:11 -07002007 // Use basic string manipulation calls to avoid snprintf.
2008 // snprintf indirectly calls pthread_getspecific to get the size of a buffer.
2009 // When debug malloc is enabled, this call returns 0. This in turn causes
2010 // snprintf to do nothing, which causes libraries to fail to load.
2011 // See b/17302493 for further details.
2012 // Once the above bug is fixed, this code can be modified to use
2013 // snprintf again.
Dimitry Ivanov77ad6422017-03-06 13:02:29 -08002014 const auto& default_ld_paths = g_default_namespace.get_default_library_paths();
2015
2016 size_t required_size = 0;
2017 for (const auto& path : default_ld_paths) {
2018 required_size += path.size() + 1;
Evgenii Stepanovd640b222015-07-10 17:54:01 -07002019 }
Dimitry Ivanov77ad6422017-03-06 13:02:29 -08002020
2021 if (buffer_size < required_size) {
Christopher Ferris7a3681e2017-04-24 17:48:32 -07002022 async_safe_fatal("android_get_LD_LIBRARY_PATH failed, buffer too small: "
2023 "buffer len %zu, required len %zu", buffer_size, required_size);
Christopher Ferris052fa3a2014-08-26 20:48:11 -07002024 }
Dimitry Ivanov77ad6422017-03-06 13:02:29 -08002025
Evgenii Stepanovd640b222015-07-10 17:54:01 -07002026 char* end = buffer;
Dimitry Ivanov77ad6422017-03-06 13:02:29 -08002027 for (size_t i = 0; i < default_ld_paths.size(); ++i) {
Evgenii Stepanovd640b222015-07-10 17:54:01 -07002028 if (i > 0) *end++ = ':';
Dimitry Ivanov77ad6422017-03-06 13:02:29 -08002029 end = stpcpy(end, default_ld_paths[i].c_str());
Evgenii Stepanovd640b222015-07-10 17:54:01 -07002030 }
Elliott Hughesa4aafd12014-01-13 16:37:47 -08002031}
2032
Elliott Hughescade4c32012-12-20 14:42:14 -08002033void do_android_update_LD_LIBRARY_PATH(const char* ld_library_path) {
Nick Kralevich6bb01b62015-03-07 13:37:05 -08002034 parse_LD_LIBRARY_PATH(ld_library_path);
Elliott Hughescade4c32012-12-20 14:42:14 -08002035}
2036
Dimitry Ivanovb996d602016-07-11 18:11:39 -07002037static std::string android_dlextinfo_to_string(const android_dlextinfo* info) {
2038 if (info == nullptr) {
2039 return "(null)";
2040 }
2041
2042 return android::base::StringPrintf("[flags=0x%" PRIx64 ","
2043 " reserved_addr=%p,"
2044 " reserved_size=0x%zx,"
2045 " relro_fd=%d,"
2046 " library_fd=%d,"
2047 " library_fd_offset=0x%" PRIx64 ","
2048 " library_namespace=%s@%p]",
2049 info->flags,
2050 info->reserved_addr,
2051 info->reserved_size,
2052 info->relro_fd,
2053 info->library_fd,
2054 info->library_fd_offset,
2055 (info->flags & ANDROID_DLEXT_USE_NAMESPACE) != 0 ?
2056 (info->library_namespace != nullptr ?
2057 info->library_namespace->get_name() : "(null)") : "(n/a)",
2058 (info->flags & ANDROID_DLEXT_USE_NAMESPACE) != 0 ?
2059 info->library_namespace : nullptr);
2060}
2061
Dimitry Ivanovd9e427c2016-11-22 16:55:25 -08002062void* do_dlopen(const char* name, int flags,
2063 const android_dlextinfo* extinfo,
2064 const void* caller_addr) {
Dimitry Ivanov5c4a5802017-03-17 16:41:34 -07002065 std::string trace_prefix = std::string("dlopen: ") + (name == nullptr ? "(nullptr)" : name);
2066 ScopedTrace trace(trace_prefix.c_str());
2067 ScopedTrace loading_trace((trace_prefix + " - loading and linking").c_str());
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002068 soinfo* const caller = find_containing_library(caller_addr);
Dimitry Ivanovb996d602016-07-11 18:11:39 -07002069 android_namespace_t* ns = get_caller_namespace(caller);
2070
2071 LD_LOG(kLogDlopen,
Victor Chang6cb719f2019-02-06 17:19:10 +00002072 "dlopen(name=\"%s\", flags=0x%x, extinfo=%s, caller=\"%s\", caller_ns=%s@%p, targetSdkVersion=%i) ...",
Dimitry Ivanovb996d602016-07-11 18:11:39 -07002073 name,
2074 flags,
2075 android_dlextinfo_to_string(extinfo).c_str(),
2076 caller == nullptr ? "(null)" : caller->get_realpath(),
2077 ns == nullptr ? "(null)" : ns->get_name(),
Victor Chang6cb719f2019-02-06 17:19:10 +00002078 ns,
2079 get_application_target_sdk_version());
Dimitry Ivanovb996d602016-07-11 18:11:39 -07002080
Vic Yangbb7e1232019-01-29 20:23:16 -08002081 auto purge_guard = android::base::make_scope_guard([&]() { purge_unused_memory(); });
2082
Tom Cherryb8ab6182017-04-05 16:20:29 -07002083 auto failure_guard = android::base::make_scope_guard(
2084 [&]() { LD_LOG(kLogDlopen, "... dlopen failed: %s", linker_get_error_buffer()); });
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002085
Dmitriy Ivanov1b20daf2014-05-19 15:06:58 -07002086 if ((flags & ~(RTLD_NOW|RTLD_LAZY|RTLD_LOCAL|RTLD_GLOBAL|RTLD_NODELETE|RTLD_NOLOAD)) != 0) {
Martin Stjernholm9fe38262019-08-27 17:08:45 +01002087 DL_OPEN_ERR("invalid flags to dlopen: %x", flags);
Dmitriy Ivanov851135b2014-08-29 12:02:36 -07002088 return nullptr;
Elliott Hughese66190d2012-12-18 15:57:55 -08002089 }
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002090
Dmitriy Ivanov07e5bc12014-10-03 17:52:44 -07002091 if (extinfo != nullptr) {
2092 if ((extinfo->flags & ~(ANDROID_DLEXT_VALID_FLAG_BITS)) != 0) {
Martin Stjernholm9fe38262019-08-27 17:08:45 +01002093 DL_OPEN_ERR("invalid extended flags to android_dlopen_ext: 0x%" PRIx64, extinfo->flags);
Dmitriy Ivanov07e5bc12014-10-03 17:52:44 -07002094 return nullptr;
2095 }
Dmitriy Ivanov126af752015-10-07 16:34:20 -07002096
Dmitriy Ivanov07e5bc12014-10-03 17:52:44 -07002097 if ((extinfo->flags & ANDROID_DLEXT_USE_LIBRARY_FD) == 0 &&
Dmitriy Ivanova6c12792014-10-21 12:09:18 -07002098 (extinfo->flags & ANDROID_DLEXT_USE_LIBRARY_FD_OFFSET) != 0) {
Martin Stjernholm9fe38262019-08-27 17:08:45 +01002099 DL_OPEN_ERR("invalid extended flag combination (ANDROID_DLEXT_USE_LIBRARY_FD_OFFSET without "
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07002100 "ANDROID_DLEXT_USE_LIBRARY_FD): 0x%" PRIx64, extinfo->flags);
Dmitriy Ivanov07e5bc12014-10-03 17:52:44 -07002101 return nullptr;
2102 }
Dmitriy Ivanov126af752015-10-07 16:34:20 -07002103
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002104 if ((extinfo->flags & ANDROID_DLEXT_USE_NAMESPACE) != 0) {
2105 if (extinfo->library_namespace == nullptr) {
Martin Stjernholm9fe38262019-08-27 17:08:45 +01002106 DL_OPEN_ERR("ANDROID_DLEXT_USE_NAMESPACE is set but extinfo->library_namespace is null");
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002107 return nullptr;
2108 }
2109 ns = extinfo->library_namespace;
2110 }
Torne (Richard Coles)012cb452014-02-06 14:34:21 +00002111 }
Dmitriy Ivanov279a22f2015-01-23 12:03:53 -08002112
Victor Chang6cb719f2019-02-06 17:19:10 +00002113 // Workaround for dlopen(/system/lib/<soname>) when .so is in /apex. http://b/121248172
2114 // The workaround works only when targetSdkVersion < Q.
2115 std::string name_to_apex;
2116 if (translateSystemPathToApexPath(name, &name_to_apex)) {
2117 const char* new_name = name_to_apex.c_str();
2118 LD_LOG(kLogDlopen, "dlopen considering translation from %s to APEX path %s",
2119 name,
2120 new_name);
2121 // Some APEXs could be optionally disabled. Only translate the path
2122 // when the old file is absent and the new file exists.
Victor Changaf12c942019-02-11 19:35:24 +00002123 // TODO(b/124218500): Re-enable it once app compat issue is resolved
2124 /*
Victor Chang6cb719f2019-02-06 17:19:10 +00002125 if (file_exists(name)) {
2126 LD_LOG(kLogDlopen, "dlopen %s exists, not translating", name);
Victor Changaf12c942019-02-11 19:35:24 +00002127 } else
2128 */
2129 if (!file_exists(new_name)) {
Victor Chang6cb719f2019-02-06 17:19:10 +00002130 LD_LOG(kLogDlopen, "dlopen %s does not exist, not translating",
2131 new_name);
2132 } else {
2133 LD_LOG(kLogDlopen, "dlopen translation accepted: using %s", new_name);
2134 name = new_name;
2135 }
2136 }
2137 // End Workaround for dlopen(/system/lib/<soname>) when .so is in /apex.
2138
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -07002139 std::string asan_name_holder;
2140
2141 const char* translated_name = name;
Dimitry Ivanov6c14f862016-12-05 13:35:47 -08002142 if (g_is_asan && translated_name != nullptr && translated_name[0] == '/') {
Evgenii Stepanov9e77a642017-07-27 14:55:44 -07002143 char original_path[PATH_MAX];
2144 if (realpath(name, original_path) != nullptr) {
2145 asan_name_holder = std::string(kAsanLibDirPrefix) + original_path;
Vishwath Mohan4113def2017-03-29 15:31:34 -07002146 if (file_exists(asan_name_holder.c_str())) {
Evgenii Stepanov9e77a642017-07-27 14:55:44 -07002147 soinfo* si = nullptr;
2148 if (find_loaded_library_by_realpath(ns, original_path, true, &si)) {
2149 PRINT("linker_asan dlopen NOT translating \"%s\" -> \"%s\": library already loaded", name,
2150 asan_name_holder.c_str());
2151 } else {
2152 PRINT("linker_asan dlopen translating \"%s\" -> \"%s\"", name, translated_name);
2153 translated_name = asan_name_holder.c_str();
2154 }
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -07002155 }
2156 }
2157 }
2158
Dmitriy Ivanov279a22f2015-01-23 12:03:53 -08002159 ProtectedDataGuard guard;
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -07002160 soinfo* si = find_library(ns, translated_name, flags, extinfo, caller);
Dimitry Ivanov5c4a5802017-03-17 16:41:34 -07002161 loading_trace.End();
2162
Dmitriy Ivanov851135b2014-08-29 12:02:36 -07002163 if (si != nullptr) {
Dimitry Ivanovb996d602016-07-11 18:11:39 -07002164 void* handle = si->to_handle();
2165 LD_LOG(kLogDlopen,
Dimitry Ivanovae4a0c12016-11-21 10:44:35 -08002166 "... dlopen calling constructors: realpath=\"%s\", soname=\"%s\", handle=%p",
2167 si->get_realpath(), si->get_soname(), handle);
2168 si->call_constructors();
Tom Cherryb8ab6182017-04-05 16:20:29 -07002169 failure_guard.Disable();
Dimitry Ivanovae4a0c12016-11-21 10:44:35 -08002170 LD_LOG(kLogDlopen,
Dimitry Ivanovb996d602016-07-11 18:11:39 -07002171 "... dlopen successful: realpath=\"%s\", soname=\"%s\", handle=%p",
2172 si->get_realpath(), si->get_soname(), handle);
2173 return handle;
Elliott Hughesd23736e2012-11-01 15:16:56 -07002174 }
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002175
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -07002176 return nullptr;
Elliott Hughesd23736e2012-11-01 15:16:56 -07002177}
2178
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002179int do_dladdr(const void* addr, Dl_info* info) {
2180 // Determine if this address can be found in any library currently mapped.
2181 soinfo* si = find_containing_library(addr);
2182 if (si == nullptr) {
2183 return 0;
2184 }
2185
2186 memset(info, 0, sizeof(Dl_info));
2187
2188 info->dli_fname = si->get_realpath();
2189 // Address at which the shared object is loaded.
2190 info->dli_fbase = reinterpret_cast<void*>(si->base);
2191
2192 // Determine if any symbol in the library contains the specified address.
2193 ElfW(Sym)* sym = si->find_symbol_by_address(addr);
2194 if (sym != nullptr) {
2195 info->dli_sname = si->get_string(sym->st_name);
2196 info->dli_saddr = reinterpret_cast<void*>(si->resolve_symbol_address(sym));
2197 }
2198
2199 return 1;
2200}
2201
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -07002202static soinfo* soinfo_from_handle(void* handle) {
2203 if ((reinterpret_cast<uintptr_t>(handle) & 1) != 0) {
2204 auto it = g_soinfo_handles_map.find(reinterpret_cast<uintptr_t>(handle));
2205 if (it == g_soinfo_handles_map.end()) {
2206 return nullptr;
2207 } else {
2208 return it->second;
2209 }
2210 }
2211
2212 return static_cast<soinfo*>(handle);
2213}
2214
Dimitry Ivanovd9e427c2016-11-22 16:55:25 -08002215bool do_dlsym(void* handle,
2216 const char* sym_name,
2217 const char* sym_ver,
2218 const void* caller_addr,
2219 void** symbol) {
Dimitry Ivanov6705e8c2017-03-21 10:29:06 -07002220 ScopedTrace trace("dlsym");
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002221#if !defined(__LP64__)
2222 if (handle == nullptr) {
Martin Stjernholm9fe38262019-08-27 17:08:45 +01002223 DL_SYM_ERR("dlsym failed: library handle is null");
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002224 return false;
2225 }
2226#endif
2227
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002228 soinfo* found = nullptr;
2229 const ElfW(Sym)* sym = nullptr;
2230 soinfo* caller = find_containing_library(caller_addr);
Dimitry Ivanovaca299a2016-04-11 12:42:58 -07002231 android_namespace_t* ns = get_caller_namespace(caller);
Dimitry Ivanov4742abd2016-12-12 16:30:15 -08002232 soinfo* si = nullptr;
2233 if (handle != RTLD_DEFAULT && handle != RTLD_NEXT) {
2234 si = soinfo_from_handle(handle);
2235 }
2236
2237 LD_LOG(kLogDlsym,
2238 "dlsym(handle=%p(\"%s\"), sym_name=\"%s\", sym_ver=\"%s\", caller=\"%s\", caller_ns=%s@%p) ...",
2239 handle,
2240 si != nullptr ? si->get_realpath() : "n/a",
2241 sym_name,
2242 sym_ver,
2243 caller == nullptr ? "(null)" : caller->get_realpath(),
2244 ns == nullptr ? "(null)" : ns->get_name(),
2245 ns);
2246
Tom Cherryb8ab6182017-04-05 16:20:29 -07002247 auto failure_guard = android::base::make_scope_guard(
2248 [&]() { LD_LOG(kLogDlsym, "... dlsym failed: %s", linker_get_error_buffer()); });
Dimitry Ivanov4742abd2016-12-12 16:30:15 -08002249
2250 if (sym_name == nullptr) {
Martin Stjernholm9fe38262019-08-27 17:08:45 +01002251 DL_SYM_ERR("dlsym failed: symbol name is null");
Dimitry Ivanov4742abd2016-12-12 16:30:15 -08002252 return false;
2253 }
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002254
2255 version_info vi_instance;
2256 version_info* vi = nullptr;
2257
2258 if (sym_ver != nullptr) {
Dimitry Ivanov9cf99cb2015-12-11 14:22:24 -08002259 vi_instance.name = sym_ver;
2260 vi_instance.elf_hash = calculate_elf_hash(sym_ver);
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002261 vi = &vi_instance;
2262 }
2263
2264 if (handle == RTLD_DEFAULT || handle == RTLD_NEXT) {
2265 sym = dlsym_linear_lookup(ns, sym_name, vi, &found, caller, handle);
2266 } else {
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -07002267 if (si == nullptr) {
Martin Stjernholm9fe38262019-08-27 17:08:45 +01002268 DL_SYM_ERR("dlsym failed: invalid handle: %p", handle);
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -07002269 return false;
2270 }
2271 sym = dlsym_handle_lookup(si, &found, sym_name, vi);
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002272 }
2273
2274 if (sym != nullptr) {
2275 uint32_t bind = ELF_ST_BIND(sym->st_info);
Ryan Pricharde4d620b2019-04-01 17:42:14 -07002276 uint32_t type = ELF_ST_TYPE(sym->st_info);
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002277
2278 if ((bind == STB_GLOBAL || bind == STB_WEAK) && sym->st_shndx != 0) {
Ryan Pricharde4d620b2019-04-01 17:42:14 -07002279 if (type == STT_TLS) {
2280 // For a TLS symbol, dlsym returns the address of the current thread's
Ryan Pricharda2e83ab2019-08-16 17:25:43 -07002281 // copy of the symbol.
2282 const soinfo_tls* tls_module = found->get_tls();
Ryan Pricharde4d620b2019-04-01 17:42:14 -07002283 if (tls_module == nullptr) {
Martin Stjernholm9fe38262019-08-27 17:08:45 +01002284 DL_SYM_ERR("TLS symbol \"%s\" in solib \"%s\" with no TLS segment",
2285 sym_name, found->get_realpath());
Ryan Pricharde4d620b2019-04-01 17:42:14 -07002286 return false;
2287 }
Ryan Pricharda2e83ab2019-08-16 17:25:43 -07002288 void* tls_block = get_tls_block_for_this_thread(tls_module, /*should_alloc=*/true);
2289 *symbol = static_cast<char*>(tls_block) + sym->st_value;
Ryan Pricharde4d620b2019-04-01 17:42:14 -07002290 } else {
2291 *symbol = reinterpret_cast<void*>(found->resolve_symbol_address(sym));
2292 }
Tom Cherryb8ab6182017-04-05 16:20:29 -07002293 failure_guard.Disable();
Dimitry Ivanov4742abd2016-12-12 16:30:15 -08002294 LD_LOG(kLogDlsym,
2295 "... dlsym successful: sym_name=\"%s\", sym_ver=\"%s\", found in=\"%s\", address=%p",
2296 sym_name, sym_ver, found->get_soname(), *symbol);
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002297 return true;
2298 }
2299
Martin Stjernholm9fe38262019-08-27 17:08:45 +01002300 DL_SYM_ERR("symbol \"%s\" found but not global", symbol_display_name(sym_name, sym_ver).c_str());
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002301 return false;
2302 }
2303
Martin Stjernholm9fe38262019-08-27 17:08:45 +01002304 DL_SYM_ERR("undefined symbol: %s", symbol_display_name(sym_name, sym_ver).c_str());
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002305 return false;
2306}
2307
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -07002308int do_dlclose(void* handle) {
Dimitry Ivanov6705e8c2017-03-21 10:29:06 -07002309 ScopedTrace trace("dlclose");
Dmitriy Ivanov279a22f2015-01-23 12:03:53 -08002310 ProtectedDataGuard guard;
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -07002311 soinfo* si = soinfo_from_handle(handle);
2312 if (si == nullptr) {
Martin Stjernholm9fe38262019-08-27 17:08:45 +01002313 DL_OPEN_ERR("invalid handle: %p", handle);
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -07002314 return -1;
2315 }
2316
dimitryc92ce712017-10-27 14:12:53 +02002317 LD_LOG(kLogDlopen,
2318 "dlclose(handle=%p, realpath=\"%s\"@%p) ...",
2319 handle,
2320 si->get_realpath(),
2321 si);
Dmitriy Ivanovb648a8a2014-05-19 15:06:58 -07002322 soinfo_unload(si);
dimitryc92ce712017-10-27 14:12:53 +02002323 LD_LOG(kLogDlopen,
2324 "dlclose(handle=%p) ... done",
2325 handle);
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -07002326 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002327}
2328
Jiyong Park25bedfd2019-05-16 21:00:39 +09002329// Make ns as the anonymous namespace that is a namespace used when
2330// we fail to determine the caller address (e.g., call from mono-jited code)
2331// Since there can be multiple anonymous namespace in a process, subsequent
2332// call to this function causes an error.
2333static bool set_anonymous_namespace(android_namespace_t* ns) {
2334 if (!g_anonymous_namespace_set && ns != nullptr) {
2335 CHECK(ns->is_also_used_as_anonymous());
2336 g_anonymous_namespace = ns;
2337 g_anonymous_namespace_set = true;
2338 return true;
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002339 }
Jiyong Park25bedfd2019-05-16 21:00:39 +09002340 return false;
2341}
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002342
Jiyong Park25bedfd2019-05-16 21:00:39 +09002343// TODO(b/130388701) remove this. Currently, this is used only for testing
2344// where we don't have classloader namespace.
2345bool init_anonymous_namespace(const char* shared_lib_sonames, const char* library_search_path) {
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002346 ProtectedDataGuard guard;
2347
Jiyong Park25bedfd2019-05-16 21:00:39 +09002348 // Test-only feature: we need to change the anonymous namespace multiple times
2349 // while the test is running.
2350 g_anonymous_namespace_set = false;
2351
Dmitriy Ivanov1ffec1c2015-11-23 11:26:35 -08002352 // create anonymous namespace
Dimitry Ivanov7331fe12015-12-14 14:11:17 -08002353 // When the caller is nullptr - create_namespace will take global group
2354 // from the anonymous namespace, which is fine because anonymous namespace
2355 // is still pointing to the default one.
Dmitriy Ivanov1ffec1c2015-11-23 11:26:35 -08002356 android_namespace_t* anon_ns =
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -08002357 create_namespace(nullptr,
2358 "(anonymous)",
2359 nullptr,
2360 library_search_path,
Jiyong Park25bedfd2019-05-16 21:00:39 +09002361 ANDROID_NAMESPACE_TYPE_ISOLATED |
2362 ANDROID_NAMESPACE_TYPE_ALSO_USED_AS_ANONYMOUS,
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -08002363 nullptr,
2364 &g_default_namespace);
Dmitriy Ivanov1ffec1c2015-11-23 11:26:35 -08002365
Jiyong Park25bedfd2019-05-16 21:00:39 +09002366 CHECK(anon_ns != nullptr);
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -08002367
2368 if (!link_namespaces(anon_ns, &g_default_namespace, shared_lib_sonames)) {
Jiyong Park25bedfd2019-05-16 21:00:39 +09002369 // TODO: delete anon_ns
Dmitriy Ivanov1ffec1c2015-11-23 11:26:35 -08002370 return false;
2371 }
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08002372
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002373 return true;
2374}
2375
Dimitry Ivanovb943f302016-08-03 16:00:10 -07002376static void add_soinfos_to_namespace(const soinfo_list_t& soinfos, android_namespace_t* ns) {
2377 ns->add_soinfos(soinfos);
2378 for (auto si : soinfos) {
2379 si->add_secondary_namespace(ns);
2380 }
2381}
2382
Ryan Prichard40494402020-03-24 22:37:50 -07002383std::vector<std::string> fix_lib_paths(std::vector<std::string> paths) {
2384 // For the bootstrap linker, insert /system/${LIB}/bootstrap in front of /system/${LIB} in any
2385 // namespace search path. The bootstrap linker should prefer to use the bootstrap bionic libraries
2386 // (e.g. libc.so).
2387#if !defined(__ANDROID_APEX__)
2388 for (size_t i = 0; i < paths.size(); ++i) {
2389 if (paths[i] == kSystemLibDir) {
2390 paths.insert(paths.begin() + i, std::string(kSystemLibDir) + "/bootstrap");
2391 ++i;
2392 }
2393 }
2394#endif
2395 return paths;
2396}
2397
Dimitry Ivanov7331fe12015-12-14 14:11:17 -08002398android_namespace_t* create_namespace(const void* caller_addr,
2399 const char* name,
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002400 const char* ld_library_path,
2401 const char* default_library_path,
Dimitry Ivanov7331fe12015-12-14 14:11:17 -08002402 uint64_t type,
Dimitry Ivanovfc2da532016-05-12 15:20:21 -07002403 const char* permitted_when_isolated_path,
2404 android_namespace_t* parent_namespace) {
Dimitry Ivanovfc2da532016-05-12 15:20:21 -07002405 if (parent_namespace == nullptr) {
Dimitry Ivanov52408632016-05-23 10:31:11 -07002406 // if parent_namespace is nullptr -> set it to the caller namespace
2407 soinfo* caller_soinfo = find_containing_library(caller_addr);
2408
2409 parent_namespace = caller_soinfo != nullptr ?
2410 caller_soinfo->get_primary_namespace() :
2411 g_anonymous_namespace;
Dimitry Ivanovfc2da532016-05-12 15:20:21 -07002412 }
2413
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002414 ProtectedDataGuard guard;
2415 std::vector<std::string> ld_library_paths;
2416 std::vector<std::string> default_library_paths;
Dimitry Ivanov284ae352015-12-08 10:47:13 -08002417 std::vector<std::string> permitted_paths;
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002418
2419 parse_path(ld_library_path, ":", &ld_library_paths);
2420 parse_path(default_library_path, ":", &default_library_paths);
Dimitry Ivanov284ae352015-12-08 10:47:13 -08002421 parse_path(permitted_when_isolated_path, ":", &permitted_paths);
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002422
2423 android_namespace_t* ns = new (g_namespace_allocator.alloc()) android_namespace_t();
2424 ns->set_name(name);
Dimitry Ivanov7331fe12015-12-14 14:11:17 -08002425 ns->set_isolated((type & ANDROID_NAMESPACE_TYPE_ISOLATED) != 0);
Jiyong Park37b91af2017-05-05 22:07:05 +09002426 ns->set_greylist_enabled((type & ANDROID_NAMESPACE_TYPE_GREYLIST_ENABLED) != 0);
Jiyong Park25bedfd2019-05-16 21:00:39 +09002427 ns->set_also_used_as_anonymous((type & ANDROID_NAMESPACE_TYPE_ALSO_USED_AS_ANONYMOUS) != 0);
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002428
Dimitry Ivanov7331fe12015-12-14 14:11:17 -08002429 if ((type & ANDROID_NAMESPACE_TYPE_SHARED) != 0) {
Dimitry Ivanovf1cb6692017-05-01 17:45:38 -07002430 // append parent namespace paths.
2431 std::copy(parent_namespace->get_ld_library_paths().begin(),
2432 parent_namespace->get_ld_library_paths().end(),
2433 back_inserter(ld_library_paths));
2434
2435 std::copy(parent_namespace->get_default_library_paths().begin(),
2436 parent_namespace->get_default_library_paths().end(),
2437 back_inserter(default_library_paths));
2438
2439 std::copy(parent_namespace->get_permitted_paths().begin(),
2440 parent_namespace->get_permitted_paths().end(),
2441 back_inserter(permitted_paths));
2442
Dimitry Ivanovfc2da532016-05-12 15:20:21 -07002443 // If shared - clone the parent namespace
Dimitry Ivanovb943f302016-08-03 16:00:10 -07002444 add_soinfos_to_namespace(parent_namespace->soinfo_list(), ns);
Dimitry Ivanovf1cb6692017-05-01 17:45:38 -07002445 // and copy parent namespace links
2446 for (auto& link : parent_namespace->linked_namespaces()) {
Logan Chien9ee45912018-01-18 12:05:09 +08002447 ns->add_linked_namespace(link.linked_namespace(), link.shared_lib_sonames(),
2448 link.allow_all_shared_libs());
Dimitry Ivanovf1cb6692017-05-01 17:45:38 -07002449 }
Dimitry Ivanov7331fe12015-12-14 14:11:17 -08002450 } else {
Dimitry Ivanovfc2da532016-05-12 15:20:21 -07002451 // If not shared - copy only the shared group
Jiyong Park02586a22017-05-20 01:01:24 +09002452 add_soinfos_to_namespace(parent_namespace->get_shared_group(), ns);
Dimitry Ivanov7331fe12015-12-14 14:11:17 -08002453 }
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002454
Dimitry Ivanovf1cb6692017-05-01 17:45:38 -07002455 ns->set_ld_library_paths(std::move(ld_library_paths));
2456 ns->set_default_library_paths(std::move(default_library_paths));
2457 ns->set_permitted_paths(std::move(permitted_paths));
2458
Jiyong Park25bedfd2019-05-16 21:00:39 +09002459 if (ns->is_also_used_as_anonymous() && !set_anonymous_namespace(ns)) {
2460 DL_ERR("failed to set namespace: [name=\"%s\", ld_library_path=\"%s\", default_library_paths=\"%s\""
2461 " permitted_paths=\"%s\"] as the anonymous namespace",
2462 ns->get_name(),
2463 android::base::Join(ns->get_ld_library_paths(), ':').c_str(),
2464 android::base::Join(ns->get_default_library_paths(), ':').c_str(),
2465 android::base::Join(ns->get_permitted_paths(), ':').c_str());
2466 return nullptr;
2467 }
2468
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002469 return ns;
2470}
2471
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -08002472bool link_namespaces(android_namespace_t* namespace_from,
2473 android_namespace_t* namespace_to,
2474 const char* shared_lib_sonames) {
2475 if (namespace_to == nullptr) {
2476 namespace_to = &g_default_namespace;
2477 }
2478
2479 if (namespace_from == nullptr) {
2480 DL_ERR("error linking namespaces: namespace_from is null.");
2481 return false;
2482 }
2483
2484 if (shared_lib_sonames == nullptr || shared_lib_sonames[0] == '\0') {
2485 DL_ERR("error linking namespaces \"%s\"->\"%s\": the list of shared libraries is empty.",
2486 namespace_from->get_name(), namespace_to->get_name());
2487 return false;
2488 }
2489
2490 auto sonames = android::base::Split(shared_lib_sonames, ":");
2491 std::unordered_set<std::string> sonames_set(sonames.begin(), sonames.end());
2492
2493 ProtectedDataGuard guard;
Logan Chien9ee45912018-01-18 12:05:09 +08002494 namespace_from->add_linked_namespace(namespace_to, sonames_set, false);
2495
2496 return true;
2497}
2498
2499bool link_namespaces_all_libs(android_namespace_t* namespace_from,
2500 android_namespace_t* namespace_to) {
2501 if (namespace_from == nullptr) {
2502 DL_ERR("error linking namespaces: namespace_from is null.");
2503 return false;
2504 }
2505
2506 if (namespace_to == nullptr) {
2507 DL_ERR("error linking namespaces: namespace_to is null.");
2508 return false;
2509 }
2510
2511 ProtectedDataGuard guard;
2512 namespace_from->add_linked_namespace(namespace_to, std::unordered_set<std::string>(), true);
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -08002513
2514 return true;
2515}
2516
Dimitry Ivanov48ec2882016-08-04 11:50:36 -07002517ElfW(Addr) call_ifunc_resolver(ElfW(Addr) resolver_addr) {
Elliott Hughes90f96b92019-05-09 15:56:39 -07002518 if (g_is_ldd) return 0;
2519
Peter Collingbournee9491952019-10-28 10:57:26 -07002520 ElfW(Addr) ifunc_addr = __bionic_call_ifunc_resolver(resolver_addr);
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07002521 TRACE_TYPE(RELO, "Called ifunc_resolver@%p. The result is %p",
Peter Collingbournee9491952019-10-28 10:57:26 -07002522 reinterpret_cast<void *>(resolver_addr), reinterpret_cast<void*>(ifunc_addr));
Brigid Smithc5a13ef2014-07-23 11:22:25 -07002523
Dmitriy Ivanov9aea1642014-09-11 15:16:03 -07002524 return ifunc_addr;
Brigid Smithc5a13ef2014-07-23 11:22:25 -07002525}
Brigid Smithc5a13ef2014-07-23 11:22:25 -07002526
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07002527const version_info* VersionTracker::get_version_info(ElfW(Versym) source_symver) const {
2528 if (source_symver < 2 ||
2529 source_symver >= version_infos.size() ||
2530 version_infos[source_symver].name == nullptr) {
2531 return nullptr;
2532 }
2533
2534 return &version_infos[source_symver];
2535}
2536
2537void VersionTracker::add_version_info(size_t source_index,
2538 ElfW(Word) elf_hash,
2539 const char* ver_name,
2540 const soinfo* target_si) {
2541 if (source_index >= version_infos.size()) {
2542 version_infos.resize(source_index+1);
2543 }
2544
2545 version_infos[source_index].elf_hash = elf_hash;
2546 version_infos[source_index].name = ver_name;
2547 version_infos[source_index].target_si = target_si;
2548}
2549
2550bool VersionTracker::init_verneed(const soinfo* si_from) {
2551 uintptr_t verneed_ptr = si_from->get_verneed_ptr();
2552
2553 if (verneed_ptr == 0) {
2554 return true;
2555 }
2556
2557 size_t verneed_cnt = si_from->get_verneed_cnt();
2558
2559 for (size_t i = 0, offset = 0; i<verneed_cnt; ++i) {
2560 const ElfW(Verneed)* verneed = reinterpret_cast<ElfW(Verneed)*>(verneed_ptr + offset);
2561 size_t vernaux_offset = offset + verneed->vn_aux;
2562 offset += verneed->vn_next;
2563
2564 if (verneed->vn_version != 1) {
2565 DL_ERR("unsupported verneed[%zd] vn_version: %d (expected 1)", i, verneed->vn_version);
2566 return false;
2567 }
2568
2569 const char* target_soname = si_from->get_string(verneed->vn_file);
2570 // find it in dependencies
2571 soinfo* target_si = si_from->get_children().find_if([&](const soinfo* si) {
Dmitriy Ivanov406d9962015-05-06 11:05:27 -07002572 return si->get_soname() != nullptr && strcmp(si->get_soname(), target_soname) == 0;
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07002573 });
2574
2575 if (target_si == nullptr) {
2576 DL_ERR("cannot find \"%s\" from verneed[%zd] in DT_NEEDED list for \"%s\"",
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07002577 target_soname, i, si_from->get_realpath());
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07002578 return false;
2579 }
2580
2581 for (size_t j = 0; j<verneed->vn_cnt; ++j) {
2582 const ElfW(Vernaux)* vernaux = reinterpret_cast<ElfW(Vernaux)*>(verneed_ptr + vernaux_offset);
2583 vernaux_offset += vernaux->vna_next;
2584
2585 const ElfW(Word) elf_hash = vernaux->vna_hash;
2586 const char* ver_name = si_from->get_string(vernaux->vna_name);
2587 ElfW(Half) source_index = vernaux->vna_other;
2588
2589 add_version_info(source_index, elf_hash, ver_name, target_si);
2590 }
2591 }
2592
2593 return true;
2594}
2595
Dimitry Ivanov48ec2882016-08-04 11:50:36 -07002596template <typename F>
2597static bool for_each_verdef(const soinfo* si, F functor) {
2598 if (!si->has_min_version(2)) {
2599 return true;
2600 }
2601
2602 uintptr_t verdef_ptr = si->get_verdef_ptr();
2603 if (verdef_ptr == 0) {
2604 return true;
2605 }
2606
2607 size_t offset = 0;
2608
2609 size_t verdef_cnt = si->get_verdef_cnt();
2610 for (size_t i = 0; i<verdef_cnt; ++i) {
2611 const ElfW(Verdef)* verdef = reinterpret_cast<ElfW(Verdef)*>(verdef_ptr + offset);
2612 size_t verdaux_offset = offset + verdef->vd_aux;
2613 offset += verdef->vd_next;
2614
2615 if (verdef->vd_version != 1) {
2616 DL_ERR("unsupported verdef[%zd] vd_version: %d (expected 1) library: %s",
2617 i, verdef->vd_version, si->get_realpath());
2618 return false;
2619 }
2620
2621 if ((verdef->vd_flags & VER_FLG_BASE) != 0) {
2622 // "this is the version of the file itself. It must not be used for
2623 // matching a symbol. It can be used to match references."
2624 //
2625 // http://www.akkadia.org/drepper/symbol-versioning
2626 continue;
2627 }
2628
2629 if (verdef->vd_cnt == 0) {
2630 DL_ERR("invalid verdef[%zd] vd_cnt == 0 (version without a name)", i);
2631 return false;
2632 }
2633
2634 const ElfW(Verdaux)* verdaux = reinterpret_cast<ElfW(Verdaux)*>(verdef_ptr + verdaux_offset);
2635
2636 if (functor(i, verdef, verdaux) == true) {
2637 break;
2638 }
2639 }
2640
2641 return true;
2642}
2643
Ryan Prichard0e12cce2020-01-02 14:59:11 -08002644ElfW(Versym) find_verdef_version_index(const soinfo* si, const version_info* vi) {
Dimitry Ivanov48ec2882016-08-04 11:50:36 -07002645 if (vi == nullptr) {
Ryan Prichard0e12cce2020-01-02 14:59:11 -08002646 return kVersymNotNeeded;
Dimitry Ivanov48ec2882016-08-04 11:50:36 -07002647 }
2648
Ryan Prichard0e12cce2020-01-02 14:59:11 -08002649 ElfW(Versym) result = kVersymGlobal;
Dimitry Ivanov48ec2882016-08-04 11:50:36 -07002650
Ryan Prichard0e12cce2020-01-02 14:59:11 -08002651 if (!for_each_verdef(si,
Dimitry Ivanov48ec2882016-08-04 11:50:36 -07002652 [&](size_t, const ElfW(Verdef)* verdef, const ElfW(Verdaux)* verdaux) {
2653 if (verdef->vd_hash == vi->elf_hash &&
2654 strcmp(vi->name, si->get_string(verdaux->vda_name)) == 0) {
Ryan Prichard0e12cce2020-01-02 14:59:11 -08002655 result = verdef->vd_ndx;
Dimitry Ivanov48ec2882016-08-04 11:50:36 -07002656 return true;
2657 }
2658
2659 return false;
2660 }
Ryan Prichard0e12cce2020-01-02 14:59:11 -08002661 )) {
2662 // verdef should have already been validated in prelink_image.
2663 async_safe_fatal("invalid verdef after prelinking: %s, %s",
2664 si->get_realpath(), linker_get_error_buffer());
2665 }
2666
2667 return result;
2668}
2669
2670// Validate the library's verdef section. On error, returns false and invokes DL_ERR.
2671bool validate_verdef_section(const soinfo* si) {
2672 return for_each_verdef(si,
2673 [&](size_t, const ElfW(Verdef)*, const ElfW(Verdaux)*) {
2674 return false;
2675 });
Dimitry Ivanov48ec2882016-08-04 11:50:36 -07002676}
2677
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07002678bool VersionTracker::init_verdef(const soinfo* si_from) {
2679 return for_each_verdef(si_from,
2680 [&](size_t, const ElfW(Verdef)* verdef, const ElfW(Verdaux)* verdaux) {
2681 add_version_info(verdef->vd_ndx, verdef->vd_hash,
2682 si_from->get_string(verdaux->vda_name), si_from);
2683 return false;
2684 }
2685 );
2686}
2687
2688bool VersionTracker::init(const soinfo* si_from) {
2689 if (!si_from->has_min_version(2)) {
2690 return true;
2691 }
2692
2693 return init_verneed(si_from) && init_verdef(si_from);
2694}
2695
Dimitry Ivanov48ec2882016-08-04 11:50:36 -07002696// TODO (dimitry): Methods below need to be moved out of soinfo
2697// and in more isolated file in order minimize dependencies on
2698// unnecessary object in the linker binary. Consider making them
2699// independent from soinfo (?).
Dmitriy Ivanov31b408d2015-04-30 16:11:48 -07002700bool soinfo::lookup_version_info(const VersionTracker& version_tracker, ElfW(Word) sym,
2701 const char* sym_name, const version_info** vi) {
2702 const ElfW(Versym)* sym_ver_ptr = get_versym(sym);
2703 ElfW(Versym) sym_ver = sym_ver_ptr == nullptr ? 0 : *sym_ver_ptr;
2704
2705 if (sym_ver != VER_NDX_LOCAL && sym_ver != VER_NDX_GLOBAL) {
2706 *vi = version_tracker.get_version_info(sym_ver);
2707
2708 if (*vi == nullptr) {
2709 DL_ERR("cannot find verneed/verdef for version index=%d "
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07002710 "referenced by symbol \"%s\" at \"%s\"", sym_ver, sym_name, get_realpath());
Dmitriy Ivanov31b408d2015-04-30 16:11:48 -07002711 return false;
2712 }
2713 } else {
2714 // there is no version info
2715 *vi = nullptr;
2716 }
2717
2718 return true;
2719}
2720
Rahul Chaudhryf16b6592018-01-25 15:34:15 -08002721void soinfo::apply_relr_reloc(ElfW(Addr) offset) {
2722 ElfW(Addr) address = offset + load_bias;
2723 *reinterpret_cast<ElfW(Addr)*>(address) += load_bias;
2724}
2725
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08002726// Process relocations in SHT_RELR section (experimental).
Rahul Chaudhryf16b6592018-01-25 15:34:15 -08002727// Details of the encoding are described in this post:
2728// https://groups.google.com/d/msg/generic-abi/bX460iggiKg/Pi9aSwwABgAJ
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08002729bool soinfo::relocate_relr() {
2730 ElfW(Relr)* begin = relr_;
2731 ElfW(Relr)* end = relr_ + relr_count_;
Rahul Chaudhryf16b6592018-01-25 15:34:15 -08002732 constexpr size_t wordsize = sizeof(ElfW(Addr));
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08002733
Rahul Chaudhryf16b6592018-01-25 15:34:15 -08002734 ElfW(Addr) base = 0;
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08002735 for (ElfW(Relr)* current = begin; current < end; ++current) {
Rahul Chaudhryf16b6592018-01-25 15:34:15 -08002736 ElfW(Relr) entry = *current;
2737 ElfW(Addr) offset;
2738
2739 if ((entry&1) == 0) {
2740 // Even entry: encodes the offset for next relocation.
2741 offset = static_cast<ElfW(Addr)>(entry);
2742 apply_relr_reloc(offset);
2743 // Set base offset for subsequent bitmap entries.
2744 base = offset + wordsize;
2745 continue;
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08002746 }
Rahul Chaudhryf16b6592018-01-25 15:34:15 -08002747
2748 // Odd entry: encodes bitmap for relocations starting at base.
2749 offset = base;
2750 while (entry != 0) {
2751 entry >>= 1;
2752 if ((entry&1) != 0) {
2753 apply_relr_reloc(offset);
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08002754 }
Rahul Chaudhryf16b6592018-01-25 15:34:15 -08002755 offset += wordsize;
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08002756 }
Rahul Chaudhryf16b6592018-01-25 15:34:15 -08002757
2758 // Advance base offset by 63 words for 64-bit platforms,
2759 // or 31 words for 32-bit platforms.
2760 base += (8*wordsize - 1) * wordsize;
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08002761 }
2762 return true;
2763}
2764
Dimitry Ivanov48ec2882016-08-04 11:50:36 -07002765// An empty list of soinfos
Dimitry Ivanovb943f302016-08-03 16:00:10 -07002766static soinfo_list_t g_empty_list;
Dmitriy Ivanovd59e5002014-05-09 09:10:14 -07002767
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002768bool soinfo::prelink_image() {
Ryan Prichardae320cd2019-12-10 12:39:05 -08002769 if (flags_ & FLAG_PRELINKED) return true;
Ningsheng Jiane93be992014-09-16 15:22:10 +08002770 /* Extract dynamic section */
2771 ElfW(Word) dynamic_flags = 0;
2772 phdr_table_get_dynamic_section(phdr, phnum, load_bias, &dynamic, &dynamic_flags);
Dmitriy Ivanov498eb182014-09-05 14:57:59 -07002773
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002774 /* We can't log anything until the linker is relocated */
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08002775 bool relocating_linker = (flags_ & FLAG_LINKER) != 0;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002776 if (!relocating_linker) {
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07002777 INFO("[ Linking \"%s\" ]", get_realpath());
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08002778 DEBUG("si->base = %p si->flags = 0x%08x", reinterpret_cast<void*>(base), flags_);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002779 }
2780
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002781 if (dynamic == nullptr) {
David 'Digit' Turnerb52e4382012-06-19 01:24:17 +02002782 if (!relocating_linker) {
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07002783 DL_ERR("missing PT_DYNAMIC in \"%s\"", get_realpath());
David 'Digit' Turnerb52e4382012-06-19 01:24:17 +02002784 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002785 return false;
2786 } else {
2787 if (!relocating_linker) {
2788 DEBUG("dynamic = %p", dynamic);
David 'Digit' Turner63f99f42012-06-19 00:08:39 +02002789 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002790 }
David 'Digit' Turner63f99f42012-06-19 00:08:39 +02002791
Elliott Hughes4eeb1f12013-10-25 17:38:02 -07002792#if defined(__arm__)
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002793 (void) phdr_table_get_arm_exidx(phdr, phnum, load_bias,
2794 &ARM_exidx, &ARM_exidx_count);
David 'Digit' Turner63f99f42012-06-19 00:08:39 +02002795#endif
2796
Ryan Pricharde5e69e02019-01-01 18:53:48 -08002797 TlsSegment tls_segment;
Ryan Prichard19883502019-01-16 23:13:38 -08002798 if (__bionic_get_tls_segment(phdr, phnum, load_bias, &tls_segment)) {
2799 if (!__bionic_check_tls_alignment(&tls_segment.alignment)) {
2800 if (!relocating_linker) {
2801 DL_ERR("TLS segment alignment in \"%s\" is not a power of 2: %zu",
2802 get_realpath(), tls_segment.alignment);
2803 }
2804 return false;
2805 }
Ryan Pricharde5e69e02019-01-01 18:53:48 -08002806 tls_ = std::make_unique<soinfo_tls>();
2807 tls_->segment = tls_segment;
2808 }
2809
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002810 // Extract useful information from dynamic section.
Dmitriy Ivanov618f1a32015-03-17 20:06:36 -07002811 // Note that: "Except for the DT_NULL element at the end of the array,
2812 // and the relative order of DT_NEEDED elements, entries may appear in any order."
2813 //
2814 // source: http://www.sco.com/developers/gabi/1998-04-29/ch5.dynamic.html
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002815 uint32_t needed_count = 0;
2816 for (ElfW(Dyn)* d = dynamic; d->d_tag != DT_NULL; ++d) {
2817 DEBUG("d = %p, d[0](tag) = %p d[1](val) = %p",
2818 d, reinterpret_cast<void*>(d->d_tag), reinterpret_cast<void*>(d->d_un.d_val));
2819 switch (d->d_tag) {
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07002820 case DT_SONAME:
Dmitriy Ivanov618f1a32015-03-17 20:06:36 -07002821 // this is parsed after we have strtab initialized (see below).
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07002822 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002823
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002824 case DT_HASH:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002825 nbucket_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[0];
2826 nchain_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[1];
2827 bucket_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr + 8);
2828 chain_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr + 8 + nbucket_ * 4);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002829 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002830
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -08002831 case DT_GNU_HASH:
Dmitriy Ivanov3597b802015-03-09 12:02:02 -07002832 gnu_nbucket_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[0];
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -08002833 // skip symndx
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002834 gnu_maskwords_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[2];
2835 gnu_shift2_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[3];
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -08002836
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002837 gnu_bloom_filter_ = reinterpret_cast<ElfW(Addr)*>(load_bias + d->d_un.d_ptr + 16);
Dmitriy Ivanov3597b802015-03-09 12:02:02 -07002838 gnu_bucket_ = reinterpret_cast<uint32_t*>(gnu_bloom_filter_ + gnu_maskwords_);
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -08002839 // amend chain for symndx = header[1]
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07002840 gnu_chain_ = gnu_bucket_ + gnu_nbucket_ -
2841 reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[1];
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -08002842
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002843 if (!powerof2(gnu_maskwords_)) {
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07002844 DL_ERR("invalid maskwords for gnu_hash = 0x%x, in \"%s\" expecting power to two",
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07002845 gnu_maskwords_, get_realpath());
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -08002846 return false;
2847 }
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002848 --gnu_maskwords_;
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -08002849
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08002850 flags_ |= FLAG_GNU_HASH;
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -08002851 break;
2852
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002853 case DT_STRTAB:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002854 strtab_ = reinterpret_cast<const char*>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002855 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002856
Dmitriy Ivanov6cdeb522014-09-29 19:14:45 -07002857 case DT_STRSZ:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002858 strtab_size_ = d->d_un.d_val;
Dmitriy Ivanov6cdeb522014-09-29 19:14:45 -07002859 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002860
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002861 case DT_SYMTAB:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002862 symtab_ = reinterpret_cast<ElfW(Sym)*>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002863 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002864
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07002865 case DT_SYMENT:
2866 if (d->d_un.d_val != sizeof(ElfW(Sym))) {
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07002867 DL_ERR("invalid DT_SYMENT: %zd in \"%s\"",
2868 static_cast<size_t>(d->d_un.d_val), get_realpath());
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07002869 return false;
2870 }
2871 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002872
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002873 case DT_PLTREL:
Dmitriy Ivanov513e29e2014-10-06 11:30:43 -07002874#if defined(USE_RELA)
2875 if (d->d_un.d_val != DT_RELA) {
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07002876 DL_ERR("unsupported DT_PLTREL in \"%s\"; expected DT_RELA", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002877 return false;
2878 }
Dmitriy Ivanov513e29e2014-10-06 11:30:43 -07002879#else
2880 if (d->d_un.d_val != DT_REL) {
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07002881 DL_ERR("unsupported DT_PLTREL in \"%s\"; expected DT_REL", get_realpath());
Dmitriy Ivanov513e29e2014-10-06 11:30:43 -07002882 return false;
2883 }
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07002884#endif
Dmitriy Ivanov513e29e2014-10-06 11:30:43 -07002885 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002886
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002887 case DT_JMPREL:
Elliott Hughes4eeb1f12013-10-25 17:38:02 -07002888#if defined(USE_RELA)
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002889 plt_rela_ = reinterpret_cast<ElfW(Rela)*>(load_bias + d->d_un.d_ptr);
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07002890#else
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002891 plt_rel_ = reinterpret_cast<ElfW(Rel)*>(load_bias + d->d_un.d_ptr);
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07002892#endif
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002893 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002894
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002895 case DT_PLTRELSZ:
Elliott Hughes4eeb1f12013-10-25 17:38:02 -07002896#if defined(USE_RELA)
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002897 plt_rela_count_ = d->d_un.d_val / sizeof(ElfW(Rela));
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07002898#else
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002899 plt_rel_count_ = d->d_un.d_val / sizeof(ElfW(Rel));
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07002900#endif
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002901 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002902
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002903 case DT_PLTGOT:
Elliott Hughes14798932020-02-13 15:40:07 -08002904 // Ignored (because RTLD_LAZY is not supported).
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07002905 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002906
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002907 case DT_DEBUG:
2908 // Set the DT_DEBUG entry to the address of _r_debug for GDB
2909 // if the dynamic table is writable
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002910 if ((dynamic_flags & PF_W) != 0) {
2911 d->d_un.d_val = reinterpret_cast<uintptr_t>(&_r_debug);
2912 }
Dmitriy Ivanovc6292ea2015-02-13 16:29:50 -08002913 break;
Elliott Hughes4eeb1f12013-10-25 17:38:02 -07002914#if defined(USE_RELA)
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002915 case DT_RELA:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002916 rela_ = reinterpret_cast<ElfW(Rela)*>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002917 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002918
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002919 case DT_RELASZ:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002920 rela_count_ = d->d_un.d_val / sizeof(ElfW(Rela));
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002921 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002922
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08002923 case DT_ANDROID_RELA:
2924 android_relocs_ = reinterpret_cast<uint8_t*>(load_bias + d->d_un.d_ptr);
2925 break;
2926
2927 case DT_ANDROID_RELASZ:
2928 android_relocs_size_ = d->d_un.d_val;
2929 break;
2930
2931 case DT_ANDROID_REL:
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07002932 DL_ERR("unsupported DT_ANDROID_REL in \"%s\"", get_realpath());
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08002933 return false;
2934
2935 case DT_ANDROID_RELSZ:
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07002936 DL_ERR("unsupported DT_ANDROID_RELSZ in \"%s\"", get_realpath());
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08002937 return false;
2938
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07002939 case DT_RELAENT:
2940 if (d->d_un.d_val != sizeof(ElfW(Rela))) {
Dmitriy Ivanovf240aa82014-09-16 23:34:20 -07002941 DL_ERR("invalid DT_RELAENT: %zd", static_cast<size_t>(d->d_un.d_val));
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07002942 return false;
2943 }
2944 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002945
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08002946 // Ignored (see DT_RELCOUNT comments for details).
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07002947 case DT_RELACOUNT:
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07002948 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002949
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002950 case DT_REL:
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07002951 DL_ERR("unsupported DT_REL in \"%s\"", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002952 return false;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002953
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002954 case DT_RELSZ:
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07002955 DL_ERR("unsupported DT_RELSZ in \"%s\"", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002956 return false;
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08002957
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07002958#else
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002959 case DT_REL:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002960 rel_ = reinterpret_cast<ElfW(Rel)*>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002961 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002962
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002963 case DT_RELSZ:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002964 rel_count_ = d->d_un.d_val / sizeof(ElfW(Rel));
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002965 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002966
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07002967 case DT_RELENT:
2968 if (d->d_un.d_val != sizeof(ElfW(Rel))) {
Dmitriy Ivanovf240aa82014-09-16 23:34:20 -07002969 DL_ERR("invalid DT_RELENT: %zd", static_cast<size_t>(d->d_un.d_val));
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07002970 return false;
2971 }
2972 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002973
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08002974 case DT_ANDROID_REL:
2975 android_relocs_ = reinterpret_cast<uint8_t*>(load_bias + d->d_un.d_ptr);
2976 break;
2977
2978 case DT_ANDROID_RELSZ:
2979 android_relocs_size_ = d->d_un.d_val;
2980 break;
2981
2982 case DT_ANDROID_RELA:
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07002983 DL_ERR("unsupported DT_ANDROID_RELA in \"%s\"", get_realpath());
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08002984 return false;
2985
2986 case DT_ANDROID_RELASZ:
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07002987 DL_ERR("unsupported DT_ANDROID_RELASZ in \"%s\"", get_realpath());
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08002988 return false;
2989
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002990 // "Indicates that all RELATIVE relocations have been concatenated together,
2991 // and specifies the RELATIVE relocation count."
2992 //
2993 // TODO: Spec also mentions that this can be used to optimize relocation process;
2994 // Not currently used by bionic linker - ignored.
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07002995 case DT_RELCOUNT:
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07002996 break;
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08002997
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002998 case DT_RELA:
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07002999 DL_ERR("unsupported DT_RELA in \"%s\"", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003000 return false;
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08003001
3002 case DT_RELASZ:
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003003 DL_ERR("unsupported DT_RELASZ in \"%s\"", get_realpath());
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08003004 return false;
3005
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07003006#endif
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08003007 case DT_RELR:
Elliott Hughes6663f552020-01-24 14:36:10 -08003008 case DT_ANDROID_RELR:
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08003009 relr_ = reinterpret_cast<ElfW(Relr)*>(load_bias + d->d_un.d_ptr);
3010 break;
3011
3012 case DT_RELRSZ:
Elliott Hughes6663f552020-01-24 14:36:10 -08003013 case DT_ANDROID_RELRSZ:
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08003014 relr_count_ = d->d_un.d_val / sizeof(ElfW(Relr));
3015 break;
3016
3017 case DT_RELRENT:
Elliott Hughes6663f552020-01-24 14:36:10 -08003018 case DT_ANDROID_RELRENT:
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08003019 if (d->d_un.d_val != sizeof(ElfW(Relr))) {
3020 DL_ERR("invalid DT_RELRENT: %zd", static_cast<size_t>(d->d_un.d_val));
3021 return false;
3022 }
3023 break;
3024
3025 // Ignored (see DT_RELCOUNT comments for details).
Elliott Hughes6663f552020-01-24 14:36:10 -08003026 // There is no DT_RELRCOUNT specifically because it would only be ignored.
3027 case DT_ANDROID_RELRCOUNT:
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08003028 break;
3029
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003030 case DT_INIT:
Dimitry Ivanov55437462016-07-20 15:33:07 -07003031 init_func_ = reinterpret_cast<linker_ctor_function_t>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003032 DEBUG("%s constructors (DT_INIT) found at %p", get_realpath(), init_func_);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003033 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003034
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003035 case DT_FINI:
Dimitry Ivanov55437462016-07-20 15:33:07 -07003036 fini_func_ = reinterpret_cast<linker_dtor_function_t>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003037 DEBUG("%s destructors (DT_FINI) found at %p", get_realpath(), fini_func_);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003038 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003039
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003040 case DT_INIT_ARRAY:
Dimitry Ivanov55437462016-07-20 15:33:07 -07003041 init_array_ = reinterpret_cast<linker_ctor_function_t*>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003042 DEBUG("%s constructors (DT_INIT_ARRAY) found at %p", get_realpath(), init_array_);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003043 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003044
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003045 case DT_INIT_ARRAYSZ:
Dmitriy Ivanov1649e7e2015-01-22 16:04:25 -08003046 init_array_count_ = static_cast<uint32_t>(d->d_un.d_val) / sizeof(ElfW(Addr));
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003047 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003048
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003049 case DT_FINI_ARRAY:
Dimitry Ivanov55437462016-07-20 15:33:07 -07003050 fini_array_ = reinterpret_cast<linker_dtor_function_t*>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003051 DEBUG("%s destructors (DT_FINI_ARRAY) found at %p", get_realpath(), fini_array_);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003052 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003053
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003054 case DT_FINI_ARRAYSZ:
Dmitriy Ivanov1649e7e2015-01-22 16:04:25 -08003055 fini_array_count_ = static_cast<uint32_t>(d->d_un.d_val) / sizeof(ElfW(Addr));
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003056 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003057
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003058 case DT_PREINIT_ARRAY:
Dimitry Ivanov55437462016-07-20 15:33:07 -07003059 preinit_array_ = reinterpret_cast<linker_ctor_function_t*>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003060 DEBUG("%s constructors (DT_PREINIT_ARRAY) found at %p", get_realpath(), preinit_array_);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003061 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003062
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003063 case DT_PREINIT_ARRAYSZ:
Dmitriy Ivanov1649e7e2015-01-22 16:04:25 -08003064 preinit_array_count_ = static_cast<uint32_t>(d->d_un.d_val) / sizeof(ElfW(Addr));
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003065 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003066
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003067 case DT_TEXTREL:
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003068#if defined(__LP64__)
Dimitry Ivanov816676e2016-10-19 11:00:28 -07003069 DL_ERR("\"%s\" has text relocations", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003070 return false;
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003071#else
3072 has_text_relocations = true;
3073 break;
3074#endif
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003075
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003076 case DT_SYMBOLIC:
Dmitriy Ivanov96bc37f2014-09-29 12:10:36 -07003077 has_DT_SYMBOLIC = true;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003078 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003079
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003080 case DT_NEEDED:
3081 ++needed_count;
3082 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003083
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003084 case DT_FLAGS:
3085 if (d->d_un.d_val & DF_TEXTREL) {
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003086#if defined(__LP64__)
Dimitry Ivanov816676e2016-10-19 11:00:28 -07003087 DL_ERR("\"%s\" has text relocations", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003088 return false;
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003089#else
3090 has_text_relocations = true;
3091#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08003092 }
Dmitriy Ivanov96bc37f2014-09-29 12:10:36 -07003093 if (d->d_un.d_val & DF_SYMBOLIC) {
3094 has_DT_SYMBOLIC = true;
3095 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003096 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003097
Dmitriy Ivanov6cdeb522014-09-29 19:14:45 -07003098 case DT_FLAGS_1:
Dmitriy Ivanovd225a5e2014-08-28 14:12:12 -07003099 set_dt_flags_1(d->d_un.d_val);
Dmitriy Ivanov1b20daf2014-05-19 15:06:58 -07003100
Dmitriy Ivanovd225a5e2014-08-28 14:12:12 -07003101 if ((d->d_un.d_val & ~SUPPORTED_DT_FLAGS_1) != 0) {
Elliott Hughes9076b0c2018-02-28 11:29:45 -08003102 DL_WARN("Warning: \"%s\" has unsupported flags DT_FLAGS_1=%p "
3103 "(ignoring unsupported flags)",
3104 get_realpath(), reinterpret_cast<void*>(d->d_un.d_val));
Dmitriy Ivanov6cdeb522014-09-29 19:14:45 -07003105 }
3106 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003107
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003108 // Ignored: "Its use has been superseded by the DF_BIND_NOW flag"
3109 case DT_BIND_NOW:
3110 break;
3111
Dmitriy Ivanov513e29e2014-10-06 11:30:43 -07003112 case DT_VERSYM:
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07003113 versym_ = reinterpret_cast<ElfW(Versym)*>(load_bias + d->d_un.d_ptr);
3114 break;
3115
Dmitriy Ivanov513e29e2014-10-06 11:30:43 -07003116 case DT_VERDEF:
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07003117 verdef_ptr_ = load_bias + d->d_un.d_ptr;
3118 break;
Dmitriy Ivanov513e29e2014-10-06 11:30:43 -07003119 case DT_VERDEFNUM:
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07003120 verdef_cnt_ = d->d_un.d_val;
3121 break;
3122
Alexander Ivchenkoe8314332014-12-02 15:32:25 +03003123 case DT_VERNEED:
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07003124 verneed_ptr_ = load_bias + d->d_un.d_ptr;
3125 break;
3126
Alexander Ivchenkoe8314332014-12-02 15:32:25 +03003127 case DT_VERNEEDNUM:
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07003128 verneed_cnt_ = d->d_un.d_val;
Dmitriy Ivanov513e29e2014-10-06 11:30:43 -07003129 break;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003130
Evgenii Stepanov68650822015-06-10 13:38:39 -07003131 case DT_RUNPATH:
3132 // this is parsed after we have strtab initialized (see below).
3133 break;
3134
Ryan Prichardea41ab02019-01-23 16:33:03 -08003135 case DT_TLSDESC_GOT:
3136 case DT_TLSDESC_PLT:
3137 // These DT entries are used for lazy TLSDESC relocations. Bionic
3138 // resolves everything eagerly, so these can be ignored.
3139 break;
3140
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003141 default:
Dmitriy Ivanov8f61d992014-09-16 14:31:06 -07003142 if (!relocating_linker) {
Elliott Hughes6eae4cc2017-08-30 09:02:33 -07003143 const char* tag_name;
3144 if (d->d_tag == DT_RPATH) {
3145 tag_name = "DT_RPATH";
3146 } else if (d->d_tag == DT_ENCODING) {
3147 tag_name = "DT_ENCODING";
3148 } else if (d->d_tag >= DT_LOOS && d->d_tag <= DT_HIOS) {
3149 tag_name = "unknown OS-specific";
3150 } else if (d->d_tag >= DT_LOPROC && d->d_tag <= DT_HIPROC) {
3151 tag_name = "unknown processor-specific";
3152 } else {
3153 tag_name = "unknown";
3154 }
Elliott Hughes9076b0c2018-02-28 11:29:45 -08003155 DL_WARN("Warning: \"%s\" unused DT entry: %s (type %p arg %p) (ignoring)",
Elliott Hughes6eae4cc2017-08-30 09:02:33 -07003156 get_realpath(),
3157 tag_name,
3158 reinterpret_cast<void*>(d->d_tag),
3159 reinterpret_cast<void*>(d->d_un.d_val));
Dmitriy Ivanov8f61d992014-09-16 14:31:06 -07003160 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003161 break;
Brian Carlstromd4ee82d2013-02-28 15:58:45 -08003162 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003163 }
3164
3165 DEBUG("si->base = %p, si->strtab = %p, si->symtab = %p",
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003166 reinterpret_cast<void*>(base), strtab_, symtab_);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003167
3168 // Sanity checks.
3169 if (relocating_linker && needed_count != 0) {
3170 DL_ERR("linker cannot have DT_NEEDED dependencies on other libraries");
3171 return false;
3172 }
Dmitriy Ivanov3597b802015-03-09 12:02:02 -07003173 if (nbucket_ == 0 && gnu_nbucket_ == 0) {
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003174 DL_ERR("empty/missing DT_HASH/DT_GNU_HASH in \"%s\" "
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07003175 "(new hash type from the future?)", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003176 return false;
3177 }
Yi Kong32bc0fc2018-08-02 17:31:13 -07003178 if (strtab_ == nullptr) {
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07003179 DL_ERR("empty/missing DT_STRTAB in \"%s\"", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003180 return false;
3181 }
Yi Kong32bc0fc2018-08-02 17:31:13 -07003182 if (symtab_ == nullptr) {
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07003183 DL_ERR("empty/missing DT_SYMTAB in \"%s\"", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003184 return false;
3185 }
Dmitriy Ivanov75108f42015-06-02 13:28:06 -07003186
Dmitriy Ivanov624b8f12015-06-08 10:41:33 -07003187 // second pass - parse entries relying on strtab
3188 for (ElfW(Dyn)* d = dynamic; d->d_tag != DT_NULL; ++d) {
Evgenii Stepanov68650822015-06-10 13:38:39 -07003189 switch (d->d_tag) {
3190 case DT_SONAME:
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07003191 set_soname(get_string(d->d_un.d_val));
Evgenii Stepanov68650822015-06-10 13:38:39 -07003192 break;
3193 case DT_RUNPATH:
Evgenii Stepanov68650822015-06-10 13:38:39 -07003194 set_dt_runpath(get_string(d->d_un.d_val));
3195 break;
Dmitriy Ivanov624b8f12015-06-08 10:41:33 -07003196 }
3197 }
3198
Dmitriy Ivanov75108f42015-06-02 13:28:06 -07003199 // Before M release linker was using basename in place of soname.
Dmitriy Ivanov19133522015-06-02 17:36:54 -07003200 // In the case when dt_soname is absent some apps stop working
Dmitriy Ivanov75108f42015-06-02 13:28:06 -07003201 // because they can't find dt_needed library by soname.
Elliott Hughes9076b0c2018-02-28 11:29:45 -08003202 // This workaround should keep them working. (Applies only
3203 // for apps targeting sdk version < M.) Make an exception for
3204 // the main executable and linker; they do not need to have dt_soname.
3205 // TODO: >= O the linker doesn't need this workaround.
Dimitry Ivanov3f660572016-09-09 10:00:39 -07003206 if (soname_ == nullptr &&
3207 this != solist_get_somain() &&
3208 (flags_ & FLAG_LINKER) == 0 &&
Elliott Hughes95c6cd72019-12-20 13:26:14 -08003209 get_application_target_sdk_version() < 23) {
Dmitriy Ivanov75108f42015-06-02 13:28:06 -07003210 soname_ = basename(realpath_.c_str());
Elliott Hughes95c6cd72019-12-20 13:26:14 -08003211 DL_WARN_documented_change(23,
Elliott Hughes9076b0c2018-02-28 11:29:45 -08003212 "missing-soname-enforced-for-api-level-23",
3213 "\"%s\" has no DT_SONAME (will use %s instead)",
3214 get_realpath(), soname_);
3215
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07003216 // Don't call add_dlwarning because a missing DT_SONAME isn't important enough to show in the UI
Dmitriy Ivanov75108f42015-06-02 13:28:06 -07003217 }
Ryan Prichardae320cd2019-12-10 12:39:05 -08003218
Ryan Prichard0e12cce2020-01-02 14:59:11 -08003219 // Validate each library's verdef section once, so we don't have to validate
3220 // it each time we look up a symbol with a version.
3221 if (!validate_verdef_section(this)) return false;
3222
Ryan Prichardae320cd2019-12-10 12:39:05 -08003223 flags_ |= FLAG_PRELINKED;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003224 return true;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07003225}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08003226
Ryan Prichard339ecef2020-01-02 16:36:06 -08003227bool soinfo::link_image(const SymbolLookupList& lookup_list, soinfo* local_group_root,
Torne (Richard Coles)efbe9a52018-10-17 15:59:38 -04003228 const android_dlextinfo* extinfo, size_t* relro_fd_offset) {
dimitry965d06d2017-11-28 16:03:07 +01003229 if (is_image_linked()) {
3230 // already linked.
3231 return true;
3232 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08003233
Elliott Hughes90f96b92019-05-09 15:56:39 -07003234 if (g_is_ldd && !is_main_executable()) {
3235 async_safe_format_fd(STDOUT_FILENO, "\t%s => %s (%p)\n", get_soname(),
3236 get_realpath(), reinterpret_cast<void*>(base));
3237 }
3238
Ryan Prichard339ecef2020-01-02 16:36:06 -08003239 local_group_root_ = local_group_root;
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08003240 if (local_group_root_ == nullptr) {
3241 local_group_root_ = this;
3242 }
3243
Dmitriy Ivanov19133522015-06-02 17:36:54 -07003244 if ((flags_ & FLAG_LINKER) == 0 && local_group_root_ == this) {
3245 target_sdk_version_ = get_application_target_sdk_version();
3246 }
3247
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003248#if !defined(__LP64__)
3249 if (has_text_relocations) {
Elliott Hughes5bc78c82016-11-16 11:35:43 -08003250 // Fail if app is targeting M or above.
Elliott Hughes9076b0c2018-02-28 11:29:45 -08003251 int app_target_api_level = get_application_target_sdk_version();
Elliott Hughes95c6cd72019-12-20 13:26:14 -08003252 if (app_target_api_level >= 23) {
Ryan Prichard146620b2020-03-26 19:55:05 -07003253 DL_ERR_AND_LOG("\"%s\" has text relocations (%s#Text-Relocations-Enforced-for-API-level-23)",
3254 get_realpath(), kBionicChangesUrl);
Dmitriy Ivanove4ad91f2015-06-12 15:00:31 -07003255 return false;
3256 }
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003257 // Make segments writable to allow text relocations to work properly. We will later call
Dmitriy Ivanov7e039932015-10-01 14:02:19 -07003258 // phdr_table_protect_segments() after all of them are applied.
Elliott Hughes95c6cd72019-12-20 13:26:14 -08003259 DL_WARN_documented_change(23,
Elliott Hughes9076b0c2018-02-28 11:29:45 -08003260 "Text-Relocations-Enforced-for-API-level-23",
3261 "\"%s\" has text relocations",
3262 get_realpath());
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07003263 add_dlwarning(get_realpath(), "text relocations");
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003264 if (phdr_table_unprotect_segments(phdr, phnum, load_bias) < 0) {
Elliott Hughes9076b0c2018-02-28 11:29:45 -08003265 DL_ERR("can't unprotect loadable segments for \"%s\": %s", get_realpath(), strerror(errno));
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003266 return false;
3267 }
3268 }
3269#endif
3270
Ryan Prichard339ecef2020-01-02 16:36:06 -08003271 if (!relocate(lookup_list)) {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003272 return false;
3273 }
Raghu Gandhamd7daacb2012-07-31 12:07:22 -07003274
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07003275 DEBUG("[ finished linking %s ]", get_realpath());
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08003276
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003277#if !defined(__LP64__)
3278 if (has_text_relocations) {
3279 // All relocations are done, we can protect our segments back to read-only.
3280 if (phdr_table_protect_segments(phdr, phnum, load_bias) < 0) {
3281 DL_ERR("can't protect segments for \"%s\": %s",
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07003282 get_realpath(), strerror(errno));
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003283 return false;
3284 }
3285 }
3286#endif
3287
Mingwei Shibe910522015-11-12 07:02:14 +00003288 // We can also turn on GNU RELRO protection if we're not linking the dynamic linker
3289 // itself --- it can't make system calls yet, and will have to call protect_relro later.
3290 if (!is_linker() && !protect_relro()) {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003291 return false;
3292 }
Nick Kralevich9ec0f032012-02-28 10:40:00 -08003293
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003294 /* Handle serializing/sharing the RELRO segment */
3295 if (extinfo && (extinfo->flags & ANDROID_DLEXT_WRITE_RELRO)) {
3296 if (phdr_table_serialize_gnu_relro(phdr, phnum, load_bias,
Torne (Richard Coles)fa9f7f22019-04-02 17:04:42 -04003297 extinfo->relro_fd, relro_fd_offset) < 0) {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003298 DL_ERR("failed serializing GNU RELRO section for \"%s\": %s",
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07003299 get_realpath(), strerror(errno));
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003300 return false;
Torne (Richard Coles)183ad9d2014-02-27 13:18:00 +00003301 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003302 } else if (extinfo && (extinfo->flags & ANDROID_DLEXT_USE_RELRO)) {
3303 if (phdr_table_map_gnu_relro(phdr, phnum, load_bias,
Torne (Richard Coles)efbe9a52018-10-17 15:59:38 -04003304 extinfo->relro_fd, relro_fd_offset) < 0) {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003305 DL_ERR("failed mapping GNU RELRO section for \"%s\": %s",
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07003306 get_realpath(), strerror(errno));
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003307 return false;
3308 }
3309 }
Torne (Richard Coles)183ad9d2014-02-27 13:18:00 +00003310
Ryan Pricharda2e83ab2019-08-16 17:25:43 -07003311 ++g_module_load_counter;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003312 notify_gdb_of_load(this);
dimitry965d06d2017-11-28 16:03:07 +01003313 set_image_linked();
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003314 return true;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08003315}
3316
Mingwei Shibe910522015-11-12 07:02:14 +00003317bool soinfo::protect_relro() {
3318 if (phdr_table_protect_gnu_relro(phdr, phnum, load_bias) < 0) {
3319 DL_ERR("can't enable GNU RELRO protection for \"%s\": %s",
3320 get_realpath(), strerror(errno));
3321 return false;
3322 }
3323 return true;
3324}
3325
Jiyong Park02586a22017-05-20 01:01:24 +09003326static std::vector<android_namespace_t*> init_default_namespace_no_config(bool is_asan) {
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07003327 g_default_namespace.set_isolated(false);
Dimitry Ivanov77ad6422017-03-06 13:02:29 -08003328 auto default_ld_paths = is_asan ? kAsanDefaultLdPaths : kDefaultLdPaths;
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07003329
neo.chae2589f9d2016-10-04 11:00:27 +09003330 char real_path[PATH_MAX];
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07003331 std::vector<std::string> ld_default_paths;
Dimitry Ivanov77ad6422017-03-06 13:02:29 -08003332 for (size_t i = 0; default_ld_paths[i] != nullptr; ++i) {
3333 if (realpath(default_ld_paths[i], real_path) != nullptr) {
neo.chae2589f9d2016-10-04 11:00:27 +09003334 ld_default_paths.push_back(real_path);
3335 } else {
Dimitry Ivanov77ad6422017-03-06 13:02:29 -08003336 ld_default_paths.push_back(default_ld_paths[i]);
neo.chae2589f9d2016-10-04 11:00:27 +09003337 }
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07003338 }
3339
3340 g_default_namespace.set_default_library_paths(std::move(ld_default_paths));
Jiyong Park02586a22017-05-20 01:01:24 +09003341
3342 std::vector<android_namespace_t*> namespaces;
3343 namespaces.push_back(&g_default_namespace);
3344 return namespaces;
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08003345}
3346
Roland Levillain57e6b862020-02-12 17:34:20 +00003347// Given an `executable_path` starting with "/apex/<name>/bin/, return
3348// "/linkerconfig/<name>/ld.config.txt" (or "/apex/<name>/etc/ld.config.txt", if
3349// the former does not exist).
Jiyong Park35833412018-10-26 14:45:21 +09003350static std::string get_ld_config_file_apex_path(const char* executable_path) {
3351 std::vector<std::string> paths = android::base::Split(executable_path, "/");
Roland Levillaindc25f6c2019-07-02 16:40:19 +01003352 if (paths.size() >= 5 && paths[1] == "apex" && paths[3] == "bin") {
Kiyoung Kimfb587442020-01-29 16:31:54 +09003353 // Check auto-generated ld.config.txt first
3354 std::string generated_apex_config = "/linkerconfig/" + paths[2] + "/ld.config.txt";
3355 if (file_exists(generated_apex_config.c_str())) {
3356 return generated_apex_config;
3357 }
3358
Jiyong Park35833412018-10-26 14:45:21 +09003359 return std::string("/apex/") + paths[2] + "/etc/ld.config.txt";
3360 }
3361 return "";
3362}
3363
Logan Chien886b96e2018-05-08 17:52:18 +08003364static std::string get_ld_config_file_vndk_path() {
Roland Levillain09bde952019-10-29 19:17:49 +00003365 if (android::base::GetBoolProperty("ro.vndk.lite", false)) {
3366 return kLdConfigVndkLiteFilePath;
Logan Chienbcfe3cf2018-05-08 20:17:26 +08003367 }
3368
Roland Levillain09bde952019-10-29 19:17:49 +00003369 std::string ld_config_file_vndk = kLdConfigFilePath;
3370 size_t insert_pos = ld_config_file_vndk.find_last_of('.');
3371 if (insert_pos == std::string::npos) {
3372 insert_pos = ld_config_file_vndk.length();
3373 }
3374 ld_config_file_vndk.insert(insert_pos, Config::get_vndk_version_string('.'));
3375 return ld_config_file_vndk;
Logan Chien886b96e2018-05-08 17:52:18 +08003376}
3377
Kiyoung Kim46e731c2020-06-26 16:54:50 +09003378bool is_linker_config_expected(const char* executable_path) {
3379 // Do not raise message from a host environment which is expected to miss generated linker
3380 // configuration.
3381#if !defined(__ANDROID__)
3382 return false;
3383#endif
3384
3385 if (strcmp(executable_path, "/system/bin/init") == 0) {
3386 // Generated linker configuration can be missed from processes executed
3387 // with init binary
3388 return false;
3389 }
3390
3391 return true;
3392}
3393
Jiyong Park35833412018-10-26 14:45:21 +09003394static std::string get_ld_config_file_path(const char* executable_path) {
Logan Chien886b96e2018-05-08 17:52:18 +08003395#ifdef USE_LD_CONFIG_FILE
3396 // This is a debugging/testing only feature. Must not be available on
3397 // production builds.
3398 const char* ld_config_file_env = getenv("LD_CONFIG_FILE");
3399 if (ld_config_file_env != nullptr && file_exists(ld_config_file_env)) {
3400 return ld_config_file_env;
3401 }
3402#endif
3403
Jiyong Park35833412018-10-26 14:45:21 +09003404 std::string path = get_ld_config_file_apex_path(executable_path);
3405 if (!path.empty()) {
3406 if (file_exists(path.c_str())) {
3407 return path;
3408 }
3409 DL_WARN("Warning: couldn't read config file \"%s\" for \"%s\"",
3410 path.c_str(), executable_path);
Logan Chien886b96e2018-05-08 17:52:18 +08003411 }
3412
Evgeny Eltsinff43ec02019-12-16 19:22:07 +01003413 path = kLdConfigArchFilePath;
3414 if (file_exists(path.c_str())) {
3415 return path;
3416 }
3417
Kiyoung Kim18786902020-02-12 07:47:37 +09003418 if (file_exists(kLdGeneratedConfigFilePath)) {
3419 return kLdGeneratedConfigFilePath;
Kiyoung Kimef04c802019-12-13 12:19:56 +09003420 }
3421
Kiyoung Kim46e731c2020-06-26 16:54:50 +09003422 if (is_linker_config_expected(executable_path)) {
3423 DL_WARN("Warning: failed to find generated linker configuration from \"%s\"",
3424 kLdGeneratedConfigFilePath);
3425 }
Kiyoung Kim8bc03532020-03-16 13:22:27 +09003426
Jiyong Park35833412018-10-26 14:45:21 +09003427 path = get_ld_config_file_vndk_path();
Roland Levillain09bde952019-10-29 19:17:49 +00003428 if (file_exists(path.c_str())) {
Jiyong Park35833412018-10-26 14:45:21 +09003429 return path;
Logan Chien886b96e2018-05-08 17:52:18 +08003430 }
3431
3432 return kLdConfigFilePath;
3433}
3434
Jiyong Park02586a22017-05-20 01:01:24 +09003435std::vector<android_namespace_t*> init_default_namespaces(const char* executable_path) {
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08003436 g_default_namespace.set_name("(default)");
3437
3438 soinfo* somain = solist_get_somain();
3439
3440 const char *interp = phdr_table_get_interpreter_name(somain->phdr, somain->phnum,
3441 somain->load_bias);
Dan Willemsen7ccc50d2017-09-18 21:28:14 -07003442 const char* bname = (interp != nullptr) ? basename(interp) : nullptr;
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08003443
3444 g_is_asan = bname != nullptr &&
3445 (strcmp(bname, "linker_asan") == 0 ||
3446 strcmp(bname, "linker_asan64") == 0);
3447
3448 const Config* config = nullptr;
3449
3450 std::string error_msg;
3451
Jiyong Park35833412018-10-26 14:45:21 +09003452 std::string ld_config_file_path = get_ld_config_file_path(executable_path);
Jiyong Park02586a22017-05-20 01:01:24 +09003453
Martin Stjernholm95252ee2019-02-22 22:48:59 +00003454 INFO("[ Reading linker config \"%s\" ]", ld_config_file_path.c_str());
Logan Chien886b96e2018-05-08 17:52:18 +08003455 if (!Config::read_binary_config(ld_config_file_path.c_str(),
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08003456 executable_path,
3457 g_is_asan,
3458 &config,
3459 &error_msg)) {
3460 if (!error_msg.empty()) {
Elliott Hughes9076b0c2018-02-28 11:29:45 -08003461 DL_WARN("Warning: couldn't read \"%s\" for \"%s\" (using default configuration instead): %s",
Logan Chien886b96e2018-05-08 17:52:18 +08003462 ld_config_file_path.c_str(),
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08003463 executable_path,
3464 error_msg.c_str());
3465 }
3466 config = nullptr;
3467 }
3468
3469 if (config == nullptr) {
Jiyong Park02586a22017-05-20 01:01:24 +09003470 return init_default_namespace_no_config(g_is_asan);
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08003471 }
3472
3473 const auto& namespace_configs = config->namespace_configs();
3474 std::unordered_map<std::string, android_namespace_t*> namespaces;
3475
3476 // 1. Initialize default namespace
3477 const NamespaceConfig* default_ns_config = config->default_namespace_config();
3478
3479 g_default_namespace.set_isolated(default_ns_config->isolated());
3480 g_default_namespace.set_default_library_paths(default_ns_config->search_paths());
3481 g_default_namespace.set_permitted_paths(default_ns_config->permitted_paths());
3482
3483 namespaces[default_ns_config->name()] = &g_default_namespace;
Justin Yun90de9f02017-07-07 16:21:53 +09003484 if (default_ns_config->visible()) {
3485 g_exported_namespaces[default_ns_config->name()] = &g_default_namespace;
3486 }
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08003487
3488 // 2. Initialize other namespaces
3489
3490 for (auto& ns_config : namespace_configs) {
3491 if (namespaces.find(ns_config->name()) != namespaces.end()) {
3492 continue;
3493 }
3494
3495 android_namespace_t* ns = new (g_namespace_allocator.alloc()) android_namespace_t();
3496 ns->set_name(ns_config->name());
3497 ns->set_isolated(ns_config->isolated());
3498 ns->set_default_library_paths(ns_config->search_paths());
3499 ns->set_permitted_paths(ns_config->permitted_paths());
Vic Yang2d020e42019-01-12 21:03:25 -08003500 ns->set_whitelisted_libs(ns_config->whitelisted_libs());
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08003501
3502 namespaces[ns_config->name()] = ns;
Jiyong Park01de74e2017-04-03 23:10:37 +09003503 if (ns_config->visible()) {
3504 g_exported_namespaces[ns_config->name()] = ns;
3505 }
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08003506 }
3507
3508 // 3. Establish links between namespaces
3509 for (auto& ns_config : namespace_configs) {
3510 auto it_from = namespaces.find(ns_config->name());
3511 CHECK(it_from != namespaces.end());
3512 android_namespace_t* namespace_from = it_from->second;
3513 for (const NamespaceLinkConfig& ns_link : ns_config->links()) {
3514 auto it_to = namespaces.find(ns_link.ns_name());
3515 CHECK(it_to != namespaces.end());
3516 android_namespace_t* namespace_to = it_to->second;
Logan Chien9ee45912018-01-18 12:05:09 +08003517 if (ns_link.allow_all_shared_libs()) {
3518 link_namespaces_all_libs(namespace_from, namespace_to);
3519 } else {
3520 link_namespaces(namespace_from, namespace_to, ns_link.shared_libs().c_str());
3521 }
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08003522 }
3523 }
3524 // we can no longer rely on the fact that libdl.so is part of default namespace
3525 // this is why we want to add ld-android.so to all namespaces from ld.config.txt
3526 soinfo* ld_android_so = solist_get_head();
dimitry8b142562018-05-09 15:22:38 +02003527
3528 // we also need vdso to be available for all namespaces (if present)
3529 soinfo* vdso = solist_get_vdso();
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08003530 for (auto it : namespaces) {
NIEJuhue2871bd2019-12-20 18:51:21 +08003531 if (it.second != &g_default_namespace) {
3532 it.second->add_soinfo(ld_android_so);
3533 if (vdso != nullptr) {
3534 it.second->add_soinfo(vdso);
3535 }
3536 // somain and ld_preloads are added to these namespaces after LD_PRELOAD libs are linked
dimitry8b142562018-05-09 15:22:38 +02003537 }
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08003538 }
3539
3540 set_application_target_sdk_version(config->target_sdk_version());
Jiyong Park02586a22017-05-20 01:01:24 +09003541
3542 std::vector<android_namespace_t*> created_namespaces;
3543 created_namespaces.reserve(namespaces.size());
Chih-Hung Hsieh0218e922018-12-11 10:22:11 -08003544 for (const auto& kv : namespaces) {
Jiyong Park02586a22017-05-20 01:01:24 +09003545 created_namespaces.push_back(kv.second);
3546 }
3547 return created_namespaces;
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08003548}
Jiyong Park01de74e2017-04-03 23:10:37 +09003549
3550// This function finds a namespace exported in ld.config.txt by its name.
3551// A namespace can be exported by setting .visible property to true.
3552android_namespace_t* get_exported_namespace(const char* name) {
3553 if (name == nullptr) {
3554 return nullptr;
3555 }
3556 auto it = g_exported_namespaces.find(std::string(name));
3557 if (it == g_exported_namespaces.end()) {
3558 return nullptr;
3559 }
3560 return it->second;
3561}
Vic Yangbb7e1232019-01-29 20:23:16 -08003562
3563void purge_unused_memory() {
3564 // For now, we only purge the memory used by LoadTask because we know those
3565 // are temporary objects.
3566 //
3567 // Purging other LinkerBlockAllocator hardly yields much because they hold
3568 // information about namespaces and opened libraries, which are not freed
3569 // when the control leaves the linker.
3570 //
3571 // Purging BionicAllocator may give us a few dirty pages back, but those pages
3572 // would be already zeroed out, so they compress easily in ZRAM. Therefore,
3573 // it is not worth munmap()'ing those pages.
3574 TypeBasedAllocator<LoadTask>::purge();
3575}