blob: 1553ba9db3234fcb74557c987a785eea25c03c49 [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>
Ryan Prichard3714f212023-07-20 15:54:14 -070030#include <assert.h>
Elliott Hughes46882792012-08-03 16:49:39 -070031#include <errno.h>
32#include <fcntl.h>
Elliott Hughes0266ae52014-02-10 17:46:57 -080033#include <inttypes.h>
Elliott Hughes46882792012-08-03 16:49:39 -070034#include <pthread.h>
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080035#include <stdio.h>
36#include <stdlib.h>
37#include <string.h>
Florian Mayerc10d0642023-03-22 16:12:49 -070038#include <sys/auxv.h>
Elliott Hughes46882792012-08-03 16:49:39 -070039#include <sys/mman.h>
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -080040#include <sys/param.h>
Dimitry Ivanovbf34ba32017-04-21 13:12:05 -070041#include <sys/vfs.h>
Elliott Hughes46882792012-08-03 16:49:39 -070042#include <unistd.h>
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080043
Jooyung Han57b03de2022-12-01 16:23:03 +090044#include <iterator>
Dmitriy Ivanov0d150942014-08-22 12:25:04 -070045#include <new>
Dmitriy Ivanovd165f562015-03-23 18:43:02 -070046#include <string>
Dmitriy Ivanovb4827502015-09-28 16:38:31 -070047#include <unordered_map>
Dmitriy Ivanovd165f562015-03-23 18:43:02 -070048#include <vector>
Dmitriy Ivanov0d150942014-08-22 12:25:04 -070049
Logan Chienbcfe3cf2018-05-08 20:17:26 +080050#include <android-base/properties.h>
Tom Cherryb8ab6182017-04-05 16:20:29 -070051#include <android-base/scopeguard.h>
Christopher Ferris7a3681e2017-04-24 17:48:32 -070052#include <async_safe/log.h>
Ryan Pricharda2e83ab2019-08-16 17:25:43 -070053#include <bionic/pthread_internal.h>
Christopher Ferris7a3681e2017-04-24 17:48:32 -070054
Elliott Hughes46882792012-08-03 16:49:39 -070055// Private C library headers.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080056
57#include "linker.h"
Dmitriy Ivanovc9ce70d2015-03-10 15:30:26 -070058#include "linker_block_allocator.h"
Evgenii Stepanov0a3637d2016-07-06 13:20:59 -070059#include "linker_cfi.h"
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -080060#include "linker_config.h"
Dimitry Ivanov6b788ee2016-02-17 16:08:03 -080061#include "linker_gdb_support.h"
Dimitry Ivanov48ec2882016-08-04 11:50:36 -070062#include "linker_globals.h"
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080063#include "linker_debug.h"
Dimitry Ivanov769b33f2016-07-21 11:33:40 -070064#include "linker_dlwarning.h"
Dimitry Ivanov3f660572016-09-09 10:00:39 -070065#include "linker_main.h"
Dimitry Ivanovb943f302016-08-03 16:00:10 -070066#include "linker_namespaces.h"
Dmitriy Ivanov18870d32015-04-22 13:10:04 -070067#include "linker_sleb128.h"
David 'Digit' Turner23363ed2012-06-18 18:13:49 +020068#include "linker_phdr.h"
Ryan Prichard339ecef2020-01-02 16:36:06 -080069#include "linker_relocate.h"
Ryan Pricharde5e69e02019-01-01 18:53:48 -080070#include "linker_tls.h"
Victor Khimenko01790fd2020-05-12 22:59:04 +020071#include "linker_translate_path.h"
Dmitriy Ivanova1feb112015-10-01 18:41:57 -070072#include "linker_utils.h"
tony.ys_liub4474402015-07-29 18:00:22 +080073
Peter Collingbournee9491952019-10-28 10:57:26 -070074#include "private/bionic_call_ifunc_resolver.h"
Ryan Pricharde5e69e02019-01-01 18:53:48 -080075#include "private/bionic_globals.h"
dimitryfe1b27c2017-08-11 14:43:21 +020076#include "android-base/macros.h"
Elliott Hughes939a7e02015-12-04 15:27:46 -080077#include "android-base/strings.h"
Dimitry Ivanovb996d602016-07-11 18:11:39 -070078#include "android-base/stringprintf.h"
Simon Baldwinaef71952015-01-16 13:22:54 +000079#include "ziparchive/zip_archive.h"
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080080
dimitry06016f22018-01-05 11:39:28 +010081static std::unordered_map<void*, size_t> g_dso_handle_counters;
82
Jiyong Park25bedfd2019-05-16 21:00:39 +090083static bool g_anonymous_namespace_set = false;
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -070084static android_namespace_t* g_anonymous_namespace = &g_default_namespace;
Jiyong Park01de74e2017-04-03 23:10:37 +090085static std::unordered_map<std::string, android_namespace_t*> g_exported_namespaces;
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -070086
Dmitriy Ivanov600bc3c2015-03-10 15:43:50 -070087static LinkerTypeAllocator<soinfo> g_soinfo_allocator;
88static LinkerTypeAllocator<LinkedListEntry<soinfo>> g_soinfo_links_allocator;
Magnus Malmbornba98d922012-09-12 13:00:55 +020089
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -070090static LinkerTypeAllocator<android_namespace_t> g_namespace_allocator;
Dimitry Ivanovaca299a2016-04-11 12:42:58 -070091static LinkerTypeAllocator<LinkedListEntry<android_namespace_t>> g_namespace_list_allocator;
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -070092
Ryan Pricharda2e83ab2019-08-16 17:25:43 -070093static uint64_t g_module_load_counter = 0;
94static uint64_t g_module_unload_counter = 0;
95
dimitryfe1b27c2017-08-11 14:43:21 +020096static const char* const kLdConfigArchFilePath = "/system/etc/ld.config." ABI_STRING ".txt";
97
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -080098static const char* const kLdConfigFilePath = "/system/etc/ld.config.txt";
Roland Levillain09bde952019-10-29 19:17:49 +000099static const char* const kLdConfigVndkLiteFilePath = "/system/etc/ld.config.vndk_lite.txt";
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -0800100
Kiyoung Kim1a2460d2019-11-22 14:38:25 +0900101static const char* const kLdGeneratedConfigFilePath = "/linkerconfig/ld.config.txt";
Kiyoung Kim35e3b4b2019-08-07 19:24:13 +0900102
Elliott Hughes4eeb1f12013-10-25 17:38:02 -0700103#if defined(__LP64__)
Victor Chang6cb719f2019-02-06 17:19:10 +0000104static const char* const kSystemLibDir = "/system/lib64";
105static const char* const kOdmLibDir = "/odm/lib64";
106static const char* const kVendorLibDir = "/vendor/lib64";
107static const char* const kAsanSystemLibDir = "/data/asan/system/lib64";
108static const char* const kAsanOdmLibDir = "/data/asan/odm/lib64";
109static const char* const kAsanVendorLibDir = "/data/asan/vendor/lib64";
Elliott Hughes011bc0b2013-10-08 14:27:10 -0700110#else
Victor Chang6cb719f2019-02-06 17:19:10 +0000111static const char* const kSystemLibDir = "/system/lib";
112static const char* const kOdmLibDir = "/odm/lib";
113static const char* const kVendorLibDir = "/vendor/lib";
114static const char* const kAsanSystemLibDir = "/data/asan/system/lib";
115static const char* const kAsanOdmLibDir = "/data/asan/odm/lib";
116static const char* const kAsanVendorLibDir = "/data/asan/vendor/lib";
Elliott Hughes011bc0b2013-10-08 14:27:10 -0700117#endif
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700118
Vishwath Mohan4113def2017-03-29 15:31:34 -0700119static const char* const kAsanLibDirPrefix = "/data/asan";
120
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700121static const char* const kDefaultLdPaths[] = {
122 kSystemLibDir,
Alin Jerpelea074a9fd2017-09-25 17:47:49 +0200123 kOdmLibDir,
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700124 kVendorLibDir,
Dmitriy Ivanov851135b2014-08-29 12:02:36 -0700125 nullptr
Elliott Hughes124fae92012-10-31 14:20:03 -0700126};
David Bartleybc3a5c22009-06-02 18:27:28 -0700127
Evgenii Stepanovd640b222015-07-10 17:54:01 -0700128static const char* const kAsanDefaultLdPaths[] = {
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700129 kAsanSystemLibDir,
130 kSystemLibDir,
Alin Jerpelea074a9fd2017-09-25 17:47:49 +0200131 kAsanOdmLibDir,
132 kOdmLibDir,
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700133 kAsanVendorLibDir,
134 kVendorLibDir,
Evgenii Stepanovd640b222015-07-10 17:54:01 -0700135 nullptr
136};
137
Florian Mayerc10d0642023-03-22 16:12:49 -0700138#if defined(__aarch64__)
139static const char* const kHwasanSystemLibDir = "/system/lib64/hwasan";
140static const char* const kHwasanOdmLibDir = "/odm/lib64/hwasan";
141static const char* const kHwasanVendorLibDir = "/vendor/lib64/hwasan";
142
143// HWASan is only supported on aarch64.
144static const char* const kHwsanDefaultLdPaths[] = {
145 kHwasanSystemLibDir,
146 kSystemLibDir,
147 kHwasanOdmLibDir,
148 kOdmLibDir,
149 kHwasanVendorLibDir,
150 kVendorLibDir,
151 nullptr
152};
153
154// Is HWASAN enabled?
155static bool g_is_hwasan = false;
156#else
157static const char* const kHwsanDefaultLdPaths[] = {
158 kSystemLibDir,
159 kOdmLibDir,
160 kVendorLibDir,
161 nullptr
162};
163
164// Never any HWASan. Help the compiler remove the code we don't need.
165constexpr bool g_is_hwasan = false;
166#endif
167
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700168// Is ASAN enabled?
169static bool g_is_asan = false;
170
Evgenii Stepanov0a3637d2016-07-06 13:20:59 -0700171static CFIShadowWriter g_cfi_shadow;
172
173CFIShadowWriter* get_cfi_shadow() {
174 return &g_cfi_shadow;
175}
176
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700177static bool is_system_library(const std::string& realpath) {
178 for (const auto& dir : g_default_namespace.get_default_library_paths()) {
179 if (file_is_in_dir(realpath, dir)) {
180 return true;
181 }
182 }
183 return false;
184}
185
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700186// Checks if the file exists and not a directory.
187static bool file_exists(const char* path) {
Dimitry Ivanov4cf70242016-08-11 11:11:52 -0700188 struct stat s;
189
190 if (stat(path, &s) != 0) {
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700191 return false;
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700192 }
Dimitry Ivanov4cf70242016-08-11 11:11:52 -0700193
194 return S_ISREG(s.st_mode);
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700195}
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700196
Dimitry Ivanov35c8e3b2017-02-27 12:17:47 -0800197static std::string resolve_soname(const std::string& name) {
198 // We assume that soname equals to basename here
199
200 // TODO(dimitry): consider having honest absolute-path -> soname resolution
201 // note that since we might end up refusing to load this library because
202 // it is not in shared libs list we need to get the soname without actually loading
203 // the library.
204 //
205 // On the other hand there are several places where we already assume that
206 // soname == basename in particular for any not-loaded library mentioned
207 // in DT_NEEDED list.
208 return basename(name.c_str());
209}
210
211static bool maybe_accessible_via_namespace_links(android_namespace_t* ns, const char* name) {
212 std::string soname = resolve_soname(name);
213 for (auto& ns_link : ns->linked_namespaces()) {
214 if (ns_link.is_accessible(soname.c_str())) {
215 return true;
216 }
217 }
218
219 return false;
220}
221
Ryan Prichardaff9a342020-08-03 15:29:12 -0700222// TODO(dimitry): The exempt-list is a workaround for http://b/26394120 ---
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700223// gradually remove libraries from this list until it is gone.
Ryan Prichardaff9a342020-08-03 15:29:12 -0700224static bool is_exempt_lib(android_namespace_t* ns, const char* name, const soinfo* needed_by) {
225 static const char* const kLibraryExemptList[] = {
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700226 "libandroid_runtime.so",
227 "libbinder.so",
228 "libcrypto.so",
229 "libcutils.so",
230 "libexpat.so",
231 "libgui.so",
232 "libmedia.so",
233 "libnativehelper.so",
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700234 "libssl.so",
235 "libstagefright.so",
236 "libsqlite.so",
237 "libui.so",
238 "libutils.so",
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700239 nullptr
240 };
241
Ryan Prichardaff9a342020-08-03 15:29:12 -0700242 // If you're targeting N, you don't get the exempt-list.
Ryan Prichard23860932020-07-30 19:16:20 -0700243 if (get_application_target_sdk_version() >= 24) {
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700244 return false;
245 }
246
247 // if the library needed by a system library - implicitly assume it
Ryan Prichardaff9a342020-08-03 15:29:12 -0700248 // is exempt unless it is in the list of shared libraries for one or
Dimitry Ivanov35c8e3b2017-02-27 12:17:47 -0800249 // more linked namespaces
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700250 if (needed_by != nullptr && is_system_library(needed_by->get_realpath())) {
Dimitry Ivanov35c8e3b2017-02-27 12:17:47 -0800251 return !maybe_accessible_via_namespace_links(ns, name);
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700252 }
253
254 // if this is an absolute path - make sure it points to /system/lib(64)
255 if (name[0] == '/' && dirname(name) == kSystemLibDir) {
256 // and reduce the path to basename
257 name = basename(name);
258 }
259
Ryan Prichardaff9a342020-08-03 15:29:12 -0700260 for (size_t i = 0; kLibraryExemptList[i] != nullptr; ++i) {
261 if (strcmp(name, kLibraryExemptList[i]) == 0) {
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700262 return true;
263 }
264 }
265
266 return false;
267}
268// END OF WORKAROUND
269
Dmitriy Ivanovd165f562015-03-23 18:43:02 -0700270static std::vector<std::string> g_ld_preload_names;
Elliott Hughesa4aafd12014-01-13 16:37:47 -0800271
Elliott Hughesbedfe382012-08-14 14:07:59 -0700272static void notify_gdb_of_load(soinfo* info) {
Dimitry Ivanove97d8ed2016-03-01 15:55:56 -0800273 if (info->is_linker() || info->is_main_executable()) {
274 // gdb already knows about the linker and the main executable.
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700275 return;
276 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800277
Dimitry Ivanov6b788ee2016-02-17 16:08:03 -0800278 link_map* map = &(info->link_map_head);
Nicolas Geoffray0fa54102016-02-18 09:31:24 +0000279
Dimitry Ivanov6b788ee2016-02-17 16:08:03 -0800280 map->l_addr = info->load_bias;
281 // link_map l_name field is not const.
282 map->l_name = const_cast<char*>(info->get_realpath());
283 map->l_ld = info->dynamic;
Nicolas Geoffray0fa54102016-02-18 09:31:24 +0000284
Dimitry Ivanove97d8ed2016-03-01 15:55:56 -0800285 CHECK(map->l_name != nullptr);
286 CHECK(map->l_name[0] != '\0');
287
Dimitry Ivanov6b788ee2016-02-17 16:08:03 -0800288 notify_gdb_of_load(map);
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -0700289}
290
Elliott Hughesbedfe382012-08-14 14:07:59 -0700291static void notify_gdb_of_unload(soinfo* info) {
Dimitry Ivanov6b788ee2016-02-17 16:08:03 -0800292 notify_gdb_of_unload(&(info->link_map_head));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800293}
294
Dmitriy Ivanovd59e5002014-05-09 09:10:14 -0700295LinkedListEntry<soinfo>* SoinfoListAllocator::alloc() {
296 return g_soinfo_links_allocator.alloc();
297}
298
299void SoinfoListAllocator::free(LinkedListEntry<soinfo>* entry) {
300 g_soinfo_links_allocator.free(entry);
301}
302
Dimitry Ivanovaca299a2016-04-11 12:42:58 -0700303LinkedListEntry<android_namespace_t>* NamespaceListAllocator::alloc() {
304 return g_namespace_list_allocator.alloc();
305}
306
307void NamespaceListAllocator::free(LinkedListEntry<android_namespace_t>* entry) {
308 g_namespace_list_allocator.free(entry);
309}
310
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700311soinfo* soinfo_alloc(android_namespace_t* ns, const char* name,
Ryan Prichard8f639a42018-10-01 23:10:05 -0700312 const struct stat* file_stat, off64_t file_offset,
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700313 uint32_t rtld_flags) {
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -0700314 if (strlen(name) >= PATH_MAX) {
Elliott Hughes7b0af7a2017-09-15 16:09:22 -0700315 async_safe_fatal("library name \"%s\" too long", name);
Magnus Malmbornba98d922012-09-12 13:00:55 +0200316 }
317
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700318 TRACE("name %s: allocating soinfo for ns=%p", name, ns);
319
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -0700320 soinfo* si = new (g_soinfo_allocator.alloc()) soinfo(ns, name, file_stat,
321 file_offset, rtld_flags);
Dmitriy Ivanovd59e5002014-05-09 09:10:14 -0700322
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700323 solist_add_soinfo(si);
Magnus Malmbornba98d922012-09-12 13:00:55 +0200324
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -0700325 si->generate_handle();
326 ns->add_soinfo(si);
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -0700327
Elliott Hughesca0c11b2013-03-12 10:40:45 -0700328 TRACE("name %s: allocated soinfo @ %p", name, si);
Magnus Malmbornba98d922012-09-12 13:00:55 +0200329 return si;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800330}
331
Elliott Hughesfaf05ba2014-02-11 16:59:37 -0800332static void soinfo_free(soinfo* si) {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700333 if (si == nullptr) {
334 return;
335 }
336
Evgenii Stepanov474f2f52020-07-06 19:25:43 +0000337 if (si->base != 0 && si->size != 0) {
Dimitry Ivanovf45b0e92016-01-15 11:13:35 -0800338 if (!si->is_mapped_by_caller()) {
Evgenii Stepanov474f2f52020-07-06 19:25:43 +0000339 munmap(reinterpret_cast<void*>(si->base), si->size);
Dimitry Ivanovf45b0e92016-01-15 11:13:35 -0800340 } else {
341 // remap the region as PROT_NONE, MAP_ANONYMOUS | MAP_NORESERVE
Evgenii Stepanov474f2f52020-07-06 19:25:43 +0000342 mmap(reinterpret_cast<void*>(si->base), si->size, PROT_NONE,
343 MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
Dimitry Ivanovf45b0e92016-01-15 11:13:35 -0800344 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700345 }
346
Evgenii Stepanove0848bb2020-07-14 16:44:57 -0700347 if (si->has_min_version(6) && si->get_gap_size()) {
348 munmap(reinterpret_cast<void*>(si->get_gap_start()), si->get_gap_size());
349 }
350
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -0700351 TRACE("name %s: freeing soinfo @ %p", si->get_realpath(), si);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700352
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700353 if (!solist_remove_soinfo(si)) {
dimitry965d06d2017-11-28 16:03:07 +0100354 async_safe_fatal("soinfo=%p is not in soinfo_list (double unload?)", si);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700355 }
Elliott Hughes46882792012-08-03 16:49:39 -0700356
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700357 // clear links to/from si
358 si->remove_all_links();
Dmitriy Ivanovd59e5002014-05-09 09:10:14 -0700359
Dmitriy Ivanov609f11b2015-07-08 15:26:46 -0700360 si->~soinfo();
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700361 g_soinfo_allocator.free(si);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800362}
363
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -0700364static void parse_path(const char* path, const char* delimiters,
365 std::vector<std::string>* resolved_paths) {
366 std::vector<std::string> paths;
367 split_path(path, delimiters, &paths);
368 resolve_paths(paths, resolved_paths);
369}
370
Elliott Hughescade4c32012-12-20 14:42:14 -0800371static void parse_LD_LIBRARY_PATH(const char* path) {
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -0700372 std::vector<std::string> ld_libary_paths;
373 parse_path(path, ":", &ld_libary_paths);
374 g_default_namespace.set_ld_library_paths(std::move(ld_libary_paths));
Elliott Hughescade4c32012-12-20 14:42:14 -0800375}
376
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -0700377static bool realpath_fd(int fd, std::string* realpath) {
Vic Yangd8bef672019-05-15 21:10:22 -0700378 // proc_self_fd needs to be large enough to hold "/proc/self/fd/" plus an
379 // integer, plus the NULL terminator.
380 char proc_self_fd[32];
381 // We want to statically allocate this large buffer so that we don't grow
382 // the stack by too much.
383 static char buf[PATH_MAX];
384
385 async_safe_format_buffer(proc_self_fd, sizeof(proc_self_fd), "/proc/self/fd/%d", fd);
386 auto length = readlink(proc_self_fd, buf, sizeof(buf));
387 if (length == -1) {
Tom Cherry66bc4282018-11-08 13:40:52 -0800388 if (!is_first_stage_init()) {
Vic Yangd8bef672019-05-15 21:10:22 -0700389 PRINT("readlink(\"%s\") failed: %s [fd=%d]", proc_self_fd, strerror(errno), fd);
Tom Cherry66bc4282018-11-08 13:40:52 -0800390 }
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -0700391 return false;
392 }
393
Vic Yangd8bef672019-05-15 21:10:22 -0700394 realpath->assign(buf, length);
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -0700395 return true;
396}
397
Ryan Pricharda2e83ab2019-08-16 17:25:43 -0700398// Returns the address of the current thread's copy of a TLS module. If the current thread doesn't
399// have a copy yet, allocate one on-demand if should_alloc is true, and return nullptr otherwise.
400static inline void* get_tls_block_for_this_thread(const soinfo_tls* si_tls, bool should_alloc) {
401 const TlsModule& tls_mod = get_tls_module(si_tls->module_id);
402 if (tls_mod.static_offset != SIZE_MAX) {
403 const StaticTlsLayout& layout = __libc_shared_globals()->static_tls_layout;
404 char* static_tls = reinterpret_cast<char*>(__get_bionic_tcb()) - layout.offset_bionic_tcb();
405 return static_tls + tls_mod.static_offset;
406 } else if (should_alloc) {
Elliott Hughes43462702022-10-10 19:21:44 +0000407 const TlsIndex ti { si_tls->module_id, static_cast<size_t>(0 - TLS_DTV_OFFSET) };
Ryan Pricharda2e83ab2019-08-16 17:25:43 -0700408 return TLS_GET_ADDR(&ti);
409 } else {
410 TlsDtv* dtv = __get_tcb_dtv(__get_bionic_tcb());
411 if (dtv->generation < tls_mod.first_generation) return nullptr;
412 return dtv->modules[__tls_module_id_to_idx(si_tls->module_id)];
413 }
414}
415
Elliott Hughes4eeb1f12013-10-25 17:38:02 -0700416#if defined(__arm__)
Elliott Hughes46882792012-08-03 16:49:39 -0700417
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700418// For a given PC, find the .so that it belongs to.
419// Returns the base address of the .ARM.exidx section
420// for that .so, and the number of 8-byte entries
421// in that section (via *pcount).
422//
423// Intended to be called by libc's __gnu_Unwind_Find_exidx().
Dimitry Ivanovd9e427c2016-11-22 16:55:25 -0800424_Unwind_Ptr do_dl_unwind_find_exidx(_Unwind_Ptr pc, int* pcount) {
Peter Collingbourneb39cb3c2019-03-01 13:12:49 -0800425 if (soinfo* si = find_containing_library(reinterpret_cast<void*>(pc))) {
426 *pcount = si->ARM_exidx_count;
427 return reinterpret_cast<_Unwind_Ptr>(si->ARM_exidx);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700428 }
429 *pcount = 0;
Elliott Hughesf2c6ad62017-04-21 10:25:56 -0700430 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800431}
Elliott Hughes46882792012-08-03 16:49:39 -0700432
Christopher Ferris24053a42013-08-19 17:45:09 -0700433#endif
Elliott Hughes46882792012-08-03 16:49:39 -0700434
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700435// Here, we only have to provide a callback to iterate across all the
436// loaded libraries. gcc_eh does the rest.
Dmitriy Ivanov7271caf2015-06-29 14:48:25 -0700437int do_dl_iterate_phdr(int (*cb)(dl_phdr_info* info, size_t size, void* data), void* data) {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700438 int rv = 0;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700439 for (soinfo* si = solist_get_head(); si != nullptr; si = si->next) {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700440 dl_phdr_info dl_info;
441 dl_info.dlpi_addr = si->link_map_head.l_addr;
442 dl_info.dlpi_name = si->link_map_head.l_name;
443 dl_info.dlpi_phdr = si->phdr;
444 dl_info.dlpi_phnum = si->phnum;
Ryan Pricharda2e83ab2019-08-16 17:25:43 -0700445 dl_info.dlpi_adds = g_module_load_counter;
446 dl_info.dlpi_subs = g_module_unload_counter;
447 if (soinfo_tls* tls_module = si->get_tls()) {
448 dl_info.dlpi_tls_modid = tls_module->module_id;
449 dl_info.dlpi_tls_data = get_tls_block_for_this_thread(tls_module, /*should_alloc=*/false);
450 } else {
451 dl_info.dlpi_tls_modid = 0;
452 dl_info.dlpi_tls_data = nullptr;
453 }
454
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700455 rv = cb(&dl_info, sizeof(dl_phdr_info), data);
456 if (rv != 0) {
457 break;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800458 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700459 }
460 return rv;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800461}
Elliott Hughes46882792012-08-03 16:49:39 -0700462
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700463ProtectedDataGuard::ProtectedDataGuard() {
464 if (ref_count_++ == 0) {
465 protect_data(PROT_READ | PROT_WRITE);
466 }
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700467
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700468 if (ref_count_ == 0) { // overflow
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700469 async_safe_fatal("Too many nested calls to dlopen()");
Dmitriy Ivanov279a22f2015-01-23 12:03:53 -0800470 }
Dimitry Ivanov68e6c032017-02-01 12:55:11 -0800471}
Dmitriy Ivanov279a22f2015-01-23 12:03:53 -0800472
Dimitry Ivanov68e6c032017-02-01 12:55:11 -0800473ProtectedDataGuard::~ProtectedDataGuard() {
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700474 if (--ref_count_ == 0) {
475 protect_data(PROT_READ);
Dmitriy Ivanov279a22f2015-01-23 12:03:53 -0800476 }
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700477}
Dmitriy Ivanov279a22f2015-01-23 12:03:53 -0800478
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700479void ProtectedDataGuard::protect_data(int protection) {
480 g_soinfo_allocator.protect_all(protection);
481 g_soinfo_links_allocator.protect_all(protection);
482 g_namespace_allocator.protect_all(protection);
483 g_namespace_list_allocator.protect_all(protection);
484}
Dmitriy Ivanov279a22f2015-01-23 12:03:53 -0800485
486size_t ProtectedDataGuard::ref_count_ = 0;
487
Dmitriy Ivanov0cd83eb2014-09-01 16:15:52 -0700488// Each size has it's own allocator.
489template<size_t size>
490class SizeBasedAllocator {
491 public:
492 static void* alloc() {
493 return allocator_.alloc();
494 }
Dmitriy Ivanov4bea4982014-08-29 14:01:48 -0700495
Dmitriy Ivanov0cd83eb2014-09-01 16:15:52 -0700496 static void free(void* ptr) {
497 allocator_.free(ptr);
498 }
Dmitriy Ivanov4bea4982014-08-29 14:01:48 -0700499
Vic Yangbb7e1232019-01-29 20:23:16 -0800500 static void purge() {
501 allocator_.purge();
502 }
503
Dmitriy Ivanov0cd83eb2014-09-01 16:15:52 -0700504 private:
505 static LinkerBlockAllocator allocator_;
506};
507
508template<size_t size>
509LinkerBlockAllocator SizeBasedAllocator<size>::allocator_(size);
510
511template<typename T>
512class TypeBasedAllocator {
513 public:
514 static T* alloc() {
515 return reinterpret_cast<T*>(SizeBasedAllocator<sizeof(T)>::alloc());
516 }
517
518 static void free(T* ptr) {
519 SizeBasedAllocator<sizeof(T)>::free(ptr);
520 }
Vic Yangbb7e1232019-01-29 20:23:16 -0800521
522 static void purge() {
523 SizeBasedAllocator<sizeof(T)>::purge();
524 }
Dmitriy Ivanov0cd83eb2014-09-01 16:15:52 -0700525};
526
Dmitriy Ivanov14669a92014-09-05 16:42:53 -0700527class LoadTask {
528 public:
529 struct deleter_t {
530 void operator()(LoadTask* t) {
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700531 t->~LoadTask();
Dmitriy Ivanov14669a92014-09-05 16:42:53 -0700532 TypeBasedAllocator<LoadTask>::free(t);
533 }
534 };
535
Dmitriy Ivanov14669a92014-09-05 16:42:53 -0700536 static deleter_t deleter;
537
Ryan Prichardaa2db962020-03-24 20:25:53 -0700538 // needed_by is NULL iff dlopen is called from memory that isn't part of any known soinfo.
539 static LoadTask* create(const char* _Nonnull name, soinfo* _Nullable needed_by,
540 android_namespace_t* _Nonnull start_from,
541 std::unordered_map<const soinfo*, ElfReader>* _Nonnull readers_map) {
Dmitriy Ivanov14669a92014-09-05 16:42:53 -0700542 LoadTask* ptr = TypeBasedAllocator<LoadTask>::alloc();
Jiyong Park02586a22017-05-20 01:01:24 +0900543 return new (ptr) LoadTask(name, needed_by, start_from, readers_map);
Dmitriy Ivanov14669a92014-09-05 16:42:53 -0700544 }
545
546 const char* get_name() const {
547 return name_;
548 }
549
550 soinfo* get_needed_by() const {
551 return needed_by_;
552 }
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700553
554 soinfo* get_soinfo() const {
555 return si_;
556 }
557
558 void set_soinfo(soinfo* si) {
559 si_ = si;
560 }
561
562 off64_t get_file_offset() const {
563 return file_offset_;
564 }
565
566 void set_file_offset(off64_t offset) {
567 file_offset_ = offset;
568 }
569
570 int get_fd() const {
571 return fd_;
572 }
573
574 void set_fd(int fd, bool assume_ownership) {
Martin Stjernholmde853ff2019-01-17 00:18:44 +0000575 if (fd_ != -1 && close_fd_) {
576 close(fd_);
577 }
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700578 fd_ = fd;
579 close_fd_ = assume_ownership;
580 }
581
582 const android_dlextinfo* get_extinfo() const {
583 return extinfo_;
584 }
585
586 void set_extinfo(const android_dlextinfo* extinfo) {
587 extinfo_ = extinfo;
588 }
589
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700590 bool is_dt_needed() const {
591 return is_dt_needed_;
592 }
593
594 void set_dt_needed(bool is_dt_needed) {
595 is_dt_needed_ = is_dt_needed;
596 }
597
Jiyong Park02586a22017-05-20 01:01:24 +0900598 // returns the namespace from where we need to start loading this.
599 const android_namespace_t* get_start_from() const {
600 return start_from_;
601 }
602
Ryan Prichard4fa6d992020-03-26 21:31:43 -0700603 void remove_cached_elf_reader() {
604 CHECK(si_ != nullptr);
605 (*elf_readers_map_).erase(si_);
606 }
607
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700608 const ElfReader& get_elf_reader() const {
609 CHECK(si_ != nullptr);
610 return (*elf_readers_map_)[si_];
611 }
612
613 ElfReader& get_elf_reader() {
614 CHECK(si_ != nullptr);
615 return (*elf_readers_map_)[si_];
616 }
617
618 std::unordered_map<const soinfo*, ElfReader>* get_readers_map() {
619 return elf_readers_map_;
620 }
621
622 bool read(const char* realpath, off64_t file_size) {
623 ElfReader& elf_reader = get_elf_reader();
624 return elf_reader.Read(realpath, fd_, file_offset_, file_size);
625 }
626
Torne (Richard Coles)efbe9a52018-10-17 15:59:38 -0400627 bool load(address_space_params* address_space) {
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700628 ElfReader& elf_reader = get_elf_reader();
Torne (Richard Coles)efbe9a52018-10-17 15:59:38 -0400629 if (!elf_reader.Load(address_space)) {
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700630 return false;
631 }
632
633 si_->base = elf_reader.load_start();
634 si_->size = elf_reader.load_size();
Dimitry Ivanovf45b0e92016-01-15 11:13:35 -0800635 si_->set_mapped_by_caller(elf_reader.is_mapped_by_caller());
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700636 si_->load_bias = elf_reader.load_bias();
637 si_->phnum = elf_reader.phdr_count();
638 si_->phdr = elf_reader.loaded_phdr();
Evgenii Stepanove0848bb2020-07-14 16:44:57 -0700639 si_->set_gap_start(elf_reader.gap_start());
640 si_->set_gap_size(elf_reader.gap_size());
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700641
642 return true;
643 }
644
Dmitriy Ivanov14669a92014-09-05 16:42:53 -0700645 private:
Dimitry Ivanov7d429d32017-02-01 15:28:52 -0800646 LoadTask(const char* name,
647 soinfo* needed_by,
Jiyong Park02586a22017-05-20 01:01:24 +0900648 android_namespace_t* start_from,
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700649 std::unordered_map<const soinfo*, ElfReader>* readers_map)
650 : name_(name), needed_by_(needed_by), si_(nullptr),
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700651 fd_(-1), close_fd_(false), file_offset_(0), elf_readers_map_(readers_map),
Jiyong Park02586a22017-05-20 01:01:24 +0900652 is_dt_needed_(false), start_from_(start_from) {}
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700653
654 ~LoadTask() {
655 if (fd_ != -1 && close_fd_) {
656 close(fd_);
657 }
658 }
Dmitriy Ivanov14669a92014-09-05 16:42:53 -0700659
660 const char* name_;
661 soinfo* needed_by_;
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700662 soinfo* si_;
663 const android_dlextinfo* extinfo_;
664 int fd_;
665 bool close_fd_;
666 off64_t file_offset_;
667 std::unordered_map<const soinfo*, ElfReader>* elf_readers_map_;
Ryan Prichardaff9a342020-08-03 15:29:12 -0700668 // TODO(dimitry): needed by workaround for http://b/26394120 (the exempt-list)
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700669 bool is_dt_needed_;
670 // END OF WORKAROUND
Jiyong Park02586a22017-05-20 01:01:24 +0900671 const android_namespace_t* const start_from_;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -0700672
673 DISALLOW_IMPLICIT_CONSTRUCTORS(LoadTask);
674};
675
Ningsheng Jiane93be992014-09-16 15:22:10 +0800676LoadTask::deleter_t LoadTask::deleter;
677
Dmitriy Ivanov0cd83eb2014-09-01 16:15:52 -0700678template <typename T>
679using linked_list_t = LinkedList<T, TypeBasedAllocator<LinkedListEntry<T>>>;
680
681typedef linked_list_t<soinfo> SoinfoLinkedList;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -0700682typedef linked_list_t<const char> StringLinkedList;
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700683typedef std::vector<LoadTask*> LoadTaskList;
Dmitriy Ivanov0cd83eb2014-09-01 16:15:52 -0700684
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800685enum walk_action_result_t : uint32_t {
686 kWalkStop = 0,
687 kWalkContinue = 1,
688 kWalkSkip = 2
689};
Dmitriy Ivanovaa0f2bd2014-07-28 17:32:20 -0700690
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700691// This function walks down the tree of soinfo dependencies
692// in breadth-first order and
693// * calls action(soinfo* si) for each node, and
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800694// * terminates walk if action returns kWalkStop
695// * skips children of the node if action
696// return kWalkSkip
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700697//
698// walk_dependencies_tree returns false if walk was terminated
699// by the action and true otherwise.
700template<typename F>
dimitry965d06d2017-11-28 16:03:07 +0100701static bool walk_dependencies_tree(soinfo* root_soinfo, F action) {
Dmitriy Ivanov0cd83eb2014-09-01 16:15:52 -0700702 SoinfoLinkedList visit_list;
703 SoinfoLinkedList visited;
704
dimitry965d06d2017-11-28 16:03:07 +0100705 visit_list.push_back(root_soinfo);
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700706
707 soinfo* si;
708 while ((si = visit_list.pop_front()) != nullptr) {
709 if (visited.contains(si)) {
Dmitriy Ivanov042426b2014-08-12 21:02:13 -0700710 continue;
711 }
712
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800713 walk_action_result_t result = action(si);
714
715 if (result == kWalkStop) {
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700716 return false;
Dmitriy Ivanovaa0f2bd2014-07-28 17:32:20 -0700717 }
718
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700719 visited.push_back(si);
720
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800721 if (result != kWalkSkip) {
722 si->get_children().for_each([&](soinfo* child) {
723 visit_list.push_back(child);
724 });
725 }
Dmitriy Ivanovaa0f2bd2014-07-28 17:32:20 -0700726 }
727
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700728 return true;
729}
730
731
Ryan Prichard272458e2020-01-23 16:07:27 -0800732static const ElfW(Sym)* dlsym_handle_lookup_impl(android_namespace_t* ns,
733 soinfo* root,
734 soinfo* skip_until,
735 soinfo** found,
736 SymbolName& symbol_name,
737 const version_info* vi) {
Dmitriy Ivanov2a815362015-04-09 13:42:33 -0700738 const ElfW(Sym)* result = nullptr;
Dmitriy Ivanov697bd9f2015-05-12 11:12:27 -0700739 bool skip_lookup = skip_until != nullptr;
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700740
dimitry965d06d2017-11-28 16:03:07 +0100741 walk_dependencies_tree(root, [&](soinfo* current_soinfo) {
Dmitriy Ivanov697bd9f2015-05-12 11:12:27 -0700742 if (skip_lookup) {
743 skip_lookup = current_soinfo != skip_until;
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800744 return kWalkContinue;
745 }
746
747 if (!ns->is_accessible(current_soinfo)) {
748 return kWalkSkip;
Dmitriy Ivanov697bd9f2015-05-12 11:12:27 -0700749 }
750
Ryan Prichard0e12cce2020-01-02 14:59:11 -0800751 result = current_soinfo->find_symbol_by_name(symbol_name, vi);
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700752 if (result != nullptr) {
753 *found = current_soinfo;
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800754 return kWalkStop;
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700755 }
756
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800757 return kWalkContinue;
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700758 });
759
760 return result;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800761}
762
Brian Carlstromd4ee82d2013-02-28 15:58:45 -0800763/* This is used by dlsym(3) to performs a global symbol lookup. If the
764 start value is null (for RTLD_DEFAULT), the search starts at the
765 beginning of the global solist. Otherwise the search starts at the
766 specified soinfo (for RTLD_NEXT).
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700767 */
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -0800768static const ElfW(Sym)* dlsym_linear_lookup(android_namespace_t* ns,
769 const char* name,
770 const version_info* vi,
771 soinfo** found,
772 soinfo* caller,
773 void* handle) {
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -0800774 SymbolName symbol_name(name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800775
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -0700776 auto& soinfo_list = ns->soinfo_list();
777 auto start = soinfo_list.begin();
Dmitriy Ivanov76ac1ac2015-04-01 14:45:10 -0700778
779 if (handle == RTLD_NEXT) {
Dmitriy Ivanovb96ac412015-05-22 12:34:42 -0700780 if (caller == nullptr) {
Dmitriy Ivanov76ac1ac2015-04-01 14:45:10 -0700781 return nullptr;
782 } else {
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -0700783 auto it = soinfo_list.find(caller);
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -0700784 CHECK (it != soinfo_list.end());
785 start = ++it;
Dmitriy Ivanov76ac1ac2015-04-01 14:45:10 -0700786 }
Elliott Hughescade4c32012-12-20 14:42:14 -0800787 }
788
Dmitriy Ivanov2a815362015-04-09 13:42:33 -0700789 const ElfW(Sym)* s = nullptr;
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -0700790 for (auto it = start, end = soinfo_list.end(); it != end; ++it) {
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -0700791 soinfo* si = *it;
Dmitriy Ivanov19133522015-06-02 17:36:54 -0700792 // Do not skip RTLD_LOCAL libraries in dlsym(RTLD_DEFAULT, ...)
Elliott Hughes5bc78c82016-11-16 11:35:43 -0800793 // if the library is opened by application with target api level < M.
Dmitriy Ivanov19133522015-06-02 17:36:54 -0700794 // See http://b/21565766
Elliott Hughes95c6cd72019-12-20 13:26:14 -0800795 if ((si->get_rtld_flags() & RTLD_GLOBAL) == 0 && si->get_target_sdk_version() >= 23) {
Dmitriy Ivanove8ba50f2014-09-15 17:00:10 -0700796 continue;
797 }
798
Ryan Prichard0e12cce2020-01-02 14:59:11 -0800799 s = si->find_symbol_by_name(symbol_name, vi);
Dmitriy Ivanov851135b2014-08-29 12:02:36 -0700800 if (s != nullptr) {
Elliott Hughescade4c32012-12-20 14:42:14 -0800801 *found = si;
802 break;
Matt Fischer1698d9e2009-12-31 12:17:56 -0600803 }
Elliott Hughescade4c32012-12-20 14:42:14 -0800804 }
Matt Fischer1698d9e2009-12-31 12:17:56 -0600805
Ryan Prichard272458e2020-01-23 16:07:27 -0800806 // If not found - use dlsym_handle_lookup_impl for caller's local_group
dimitry153168c2018-02-20 16:51:41 +0100807 if (s == nullptr && caller != nullptr) {
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800808 soinfo* local_group_root = caller->get_local_group_root();
809
Ryan Prichard272458e2020-01-23 16:07:27 -0800810 return dlsym_handle_lookup_impl(local_group_root->get_primary_namespace(),
811 local_group_root,
812 (handle == RTLD_NEXT) ? caller : nullptr,
813 found,
814 symbol_name,
815 vi);
Dmitriy Ivanov76ac1ac2015-04-01 14:45:10 -0700816 }
817
Dmitriy Ivanov851135b2014-08-29 12:02:36 -0700818 if (s != nullptr) {
Elliott Hughesc00f2cb2013-10-04 17:01:33 -0700819 TRACE_TYPE(LOOKUP, "%s s->st_value = %p, found->base = %p",
820 name, reinterpret_cast<void*>(s->st_value), reinterpret_cast<void*>((*found)->base));
Elliott Hughescade4c32012-12-20 14:42:14 -0800821 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800822
Elliott Hughescade4c32012-12-20 14:42:14 -0800823 return s;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800824}
825
Ryan Prichard272458e2020-01-23 16:07:27 -0800826// This is used by dlsym(3). It performs symbol lookup only within the
827// specified soinfo object and its dependencies in breadth first order.
828static const ElfW(Sym)* dlsym_handle_lookup(soinfo* si,
829 soinfo** found,
830 const char* name,
831 const version_info* vi) {
832 // According to man dlopen(3) and posix docs in the case when si is handle
833 // of the main executable we need to search not only in the executable and its
834 // dependencies but also in all libraries loaded with RTLD_GLOBAL.
835 //
836 // Since RTLD_GLOBAL is always set for the main executable and all dt_needed shared
837 // libraries and they are loaded in breath-first (correct) order we can just execute
838 // dlsym(RTLD_DEFAULT, ...); instead of doing two stage lookup.
839 if (si == solist_get_somain()) {
840 return dlsym_linear_lookup(&g_default_namespace, name, vi, found, nullptr, RTLD_DEFAULT);
841 }
842
843 SymbolName symbol_name(name);
844 // note that the namespace is not the namespace associated with caller_addr
845 // we use ns associated with root si intentionally here. Using caller_ns
846 // causes problems when user uses dlopen_ext to open a library in the separate
847 // namespace and then calls dlsym() on the handle.
848 return dlsym_handle_lookup_impl(si->get_primary_namespace(), si, nullptr, found, symbol_name, vi);
849}
850
Kito Chengfa8c05d2013-03-12 14:58:06 +0800851soinfo* find_containing_library(const void* p) {
Peter Collingbourne191ecdc2019-08-07 19:06:00 -0700852 // Addresses within a library may be tagged if they point to globals. Untag
853 // them so that the bounds check succeeds.
854 ElfW(Addr) address = reinterpret_cast<ElfW(Addr)>(untag_address(p));
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700855 for (soinfo* si = solist_get_head(); si != nullptr; si = si->next) {
Peter Collingbourneb39cb3c2019-03-01 13:12:49 -0800856 if (address < si->base || address - si->base >= si->size) {
857 continue;
858 }
859 ElfW(Addr) vaddr = address - si->load_bias;
860 for (size_t i = 0; i != si->phnum; ++i) {
861 const ElfW(Phdr)* phdr = &si->phdr[i];
862 if (phdr->p_type != PT_LOAD) {
863 continue;
864 }
865 if (vaddr >= phdr->p_vaddr && vaddr < phdr->p_vaddr + phdr->p_memsz) {
866 return si;
867 }
Matt Fischere2a8b1f2009-12-31 12:17:40 -0600868 }
Kito Chengfa8c05d2013-03-12 14:58:06 +0800869 }
Dmitriy Ivanov851135b2014-08-29 12:02:36 -0700870 return nullptr;
Matt Fischere2a8b1f2009-12-31 12:17:40 -0600871}
872
Dmitriy Ivanovb4827502015-09-28 16:38:31 -0700873class ZipArchiveCache {
874 public:
875 ZipArchiveCache() {}
876 ~ZipArchiveCache();
877
878 bool get_or_open(const char* zip_path, ZipArchiveHandle* handle);
879 private:
880 DISALLOW_COPY_AND_ASSIGN(ZipArchiveCache);
881
882 std::unordered_map<std::string, ZipArchiveHandle> cache_;
883};
884
885bool ZipArchiveCache::get_or_open(const char* zip_path, ZipArchiveHandle* handle) {
886 std::string key(zip_path);
887
888 auto it = cache_.find(key);
889 if (it != cache_.end()) {
890 *handle = it->second;
891 return true;
892 }
893
894 int fd = TEMP_FAILURE_RETRY(open(zip_path, O_RDONLY | O_CLOEXEC));
895 if (fd == -1) {
896 return false;
897 }
898
899 if (OpenArchiveFd(fd, "", handle) != 0) {
900 // invalid zip-file (?)
Ryan Prichard0adf09b2018-10-01 18:35:46 -0700901 CloseArchive(*handle);
Dmitriy Ivanovb4827502015-09-28 16:38:31 -0700902 return false;
903 }
904
905 cache_[key] = *handle;
906 return true;
907}
908
909ZipArchiveCache::~ZipArchiveCache() {
Dmitriy Ivanov5dce8942015-10-13 12:14:16 -0700910 for (const auto& it : cache_) {
Dmitriy Ivanovb4827502015-09-28 16:38:31 -0700911 CloseArchive(it.second);
912 }
913}
914
915static int open_library_in_zipfile(ZipArchiveCache* zip_archive_cache,
Dmitriy Ivanova1feb112015-10-01 18:41:57 -0700916 const char* const input_path,
917 off64_t* file_offset, std::string* realpath) {
918 std::string normalized_path;
919 if (!normalize_path(input_path, &normalized_path)) {
920 return -1;
921 }
922
923 const char* const path = normalized_path.c_str();
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700924 TRACE("Trying zip file open from path \"%s\" -> normalized \"%s\"", input_path, path);
Simon Baldwinaef71952015-01-16 13:22:54 +0000925
Dmitriy Ivanov402a7502015-06-09 13:46:51 -0700926 // Treat an '!/' separator inside a path as the separator between the name
Simon Baldwinaef71952015-01-16 13:22:54 +0000927 // of the zip file on disk and the subdirectory to search within it.
Dmitriy Ivanov402a7502015-06-09 13:46:51 -0700928 // For example, if path is "foo.zip!/bar/bas/x.so", then we search for
Simon Baldwinaef71952015-01-16 13:22:54 +0000929 // "bar/bas/x.so" within "foo.zip".
Dmitriy Ivanova1feb112015-10-01 18:41:57 -0700930 const char* const separator = strstr(path, kZipFileSeparator);
Simon Baldwinaef71952015-01-16 13:22:54 +0000931 if (separator == nullptr) {
932 return -1;
Elliott Hughes124fae92012-10-31 14:20:03 -0700933 }
Simon Baldwinaef71952015-01-16 13:22:54 +0000934
935 char buf[512];
936 if (strlcpy(buf, path, sizeof(buf)) >= sizeof(buf)) {
937 PRINT("Warning: ignoring very long library path: %s", path);
938 return -1;
939 }
940
941 buf[separator - path] = '\0';
942
943 const char* zip_path = buf;
Dmitriy Ivanov402a7502015-06-09 13:46:51 -0700944 const char* file_path = &buf[separator - path + 2];
Simon Baldwinaef71952015-01-16 13:22:54 +0000945 int fd = TEMP_FAILURE_RETRY(open(zip_path, O_RDONLY | O_CLOEXEC));
946 if (fd == -1) {
947 return -1;
948 }
949
950 ZipArchiveHandle handle;
Dmitriy Ivanovb4827502015-09-28 16:38:31 -0700951 if (!zip_archive_cache->get_or_open(zip_path, &handle)) {
Simon Baldwinaef71952015-01-16 13:22:54 +0000952 // invalid zip-file (?)
953 close(fd);
954 return -1;
955 }
956
Simon Baldwinaef71952015-01-16 13:22:54 +0000957 ZipEntry entry;
958
Elliott Hughesb51bb502019-05-03 22:45:41 -0700959 if (FindEntry(handle, file_path, &entry) != 0) {
Simon Baldwinaef71952015-01-16 13:22:54 +0000960 // Entry was not found.
961 close(fd);
962 return -1;
963 }
964
965 // Check if it is properly stored
Peter Collingbournebb11ee62022-05-02 12:26:16 -0700966 if (entry.method != kCompressStored || (entry.offset % page_size()) != 0) {
Simon Baldwinaef71952015-01-16 13:22:54 +0000967 close(fd);
968 return -1;
969 }
970
971 *file_offset = entry.offset;
Dmitriy Ivanova1feb112015-10-01 18:41:57 -0700972
973 if (realpath_fd(fd, realpath)) {
974 *realpath += separator;
975 } else {
Tom Cherry66bc4282018-11-08 13:40:52 -0800976 if (!is_first_stage_init()) {
977 PRINT("warning: unable to get realpath for the library \"%s\". Will use given path.",
978 normalized_path.c_str());
979 }
Dmitriy Ivanova1feb112015-10-01 18:41:57 -0700980 *realpath = normalized_path;
981 }
982
Simon Baldwinaef71952015-01-16 13:22:54 +0000983 return fd;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800984}
985
Dmitriy Ivanovd165f562015-03-23 18:43:02 -0700986static bool format_path(char* buf, size_t buf_size, const char* path, const char* name) {
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700987 int n = async_safe_format_buffer(buf, buf_size, "%s/%s", path, name);
Dmitriy Ivanovd165f562015-03-23 18:43:02 -0700988 if (n < 0 || n >= static_cast<int>(buf_size)) {
989 PRINT("Warning: ignoring very long library path: %s/%s", path, name);
990 return false;
991 }
Simon Baldwinaef71952015-01-16 13:22:54 +0000992
Dmitriy Ivanovd165f562015-03-23 18:43:02 -0700993 return true;
994}
995
Ryan Prichard8f639a42018-10-01 23:10:05 -0700996static int open_library_at_path(ZipArchiveCache* zip_archive_cache,
997 const char* path, off64_t* file_offset,
998 std::string* realpath) {
999 int fd = -1;
1000 if (strstr(path, kZipFileSeparator) != nullptr) {
1001 fd = open_library_in_zipfile(zip_archive_cache, path, file_offset, realpath);
1002 }
1003
1004 if (fd == -1) {
1005 fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC));
1006 if (fd != -1) {
1007 *file_offset = 0;
1008 if (!realpath_fd(fd, realpath)) {
Tom Cherry66bc4282018-11-08 13:40:52 -08001009 if (!is_first_stage_init()) {
1010 PRINT("warning: unable to get realpath for the library \"%s\". Will use given path.",
1011 path);
1012 }
Ryan Prichard8f639a42018-10-01 23:10:05 -07001013 *realpath = path;
1014 }
1015 }
1016 }
1017
1018 return fd;
1019}
1020
Dmitriy Ivanovb4827502015-09-28 16:38:31 -07001021static int open_library_on_paths(ZipArchiveCache* zip_archive_cache,
1022 const char* name, off64_t* file_offset,
Dmitriy Ivanova1feb112015-10-01 18:41:57 -07001023 const std::vector<std::string>& paths,
1024 std::string* realpath) {
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001025 for (const auto& path : paths) {
Dmitriy Ivanovd165f562015-03-23 18:43:02 -07001026 char buf[512];
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001027 if (!format_path(buf, sizeof(buf), path.c_str(), name)) {
Dmitriy Ivanovd165f562015-03-23 18:43:02 -07001028 continue;
1029 }
1030
Ryan Prichard8f639a42018-10-01 23:10:05 -07001031 int fd = open_library_at_path(zip_archive_cache, buf, file_offset, realpath);
Dmitriy Ivanovd165f562015-03-23 18:43:02 -07001032 if (fd != -1) {
1033 return fd;
1034 }
Simon Baldwinaef71952015-01-16 13:22:54 +00001035 }
1036
Dmitriy Ivanovd165f562015-03-23 18:43:02 -07001037 return -1;
Simon Baldwinaef71952015-01-16 13:22:54 +00001038}
1039
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001040static int open_library(android_namespace_t* ns,
1041 ZipArchiveCache* zip_archive_cache,
Dmitriy Ivanovb4827502015-09-28 16:38:31 -07001042 const char* name, soinfo *needed_by,
Dmitriy Ivanova1feb112015-10-01 18:41:57 -07001043 off64_t* file_offset, std::string* realpath) {
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001044 TRACE("[ opening %s from namespace %s ]", name, ns->get_name());
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001045
Elliott Hughes124fae92012-10-31 14:20:03 -07001046 // 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 -07001047 if (strchr(name, '/') != nullptr) {
Ryan Prichardaa2db962020-03-24 20:25:53 -07001048 return open_library_at_path(zip_archive_cache, name, file_offset, realpath);
Elliott Hughes124fae92012-10-31 14:20:03 -07001049 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001050
Ryan Prichardaa2db962020-03-24 20:25:53 -07001051 // LD_LIBRARY_PATH has the highest priority. We don't have to check accessibility when searching
1052 // the namespace's path lists, because anything found on a namespace path list should always be
1053 // accessible.
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001054 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 -07001055
1056 // Try the DT_RUNPATH, and verify that the library is accessible.
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001057 if (fd == -1 && needed_by != nullptr) {
Dmitriy Ivanova1feb112015-10-01 18:41:57 -07001058 fd = open_library_on_paths(zip_archive_cache, name, file_offset, needed_by->get_dt_runpath(), realpath);
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001059 if (fd != -1 && !ns->is_accessible(*realpath)) {
Vic Yang48b69112018-10-24 14:14:26 -07001060 close(fd);
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001061 fd = -1;
1062 }
Evgenii Stepanov68650822015-06-10 13:38:39 -07001063 }
Dmitriy Ivanovb4827502015-09-28 16:38:31 -07001064
Ryan Prichardaa2db962020-03-24 20:25:53 -07001065 // Finally search the namespace's main search path list.
Elliott Hughes124fae92012-10-31 14:20:03 -07001066 if (fd == -1) {
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001067 fd = open_library_on_paths(zip_archive_cache, name, file_offset, ns->get_default_library_paths(), realpath);
Elliott Hughes124fae92012-10-31 14:20:03 -07001068 }
Dmitriy Ivanovb4827502015-09-28 16:38:31 -07001069
Elliott Hughes124fae92012-10-31 14:20:03 -07001070 return fd;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001071}
1072
Ryan Prichard8f639a42018-10-01 23:10:05 -07001073int open_executable(const char* path, off64_t* file_offset, std::string* realpath) {
1074 ZipArchiveCache zip_archive_cache;
1075 return open_library_at_path(&zip_archive_cache, path, file_offset, realpath);
1076}
1077
Dimitry Ivanov3f660572016-09-09 10:00:39 -07001078const char* fix_dt_needed(const char* dt_needed, const char* sopath __unused) {
Dmitriy Ivanovd974e882015-05-27 18:29:41 -07001079#if !defined(__LP64__)
1080 // Work around incorrect DT_NEEDED entries for old apps: http://b/21364029
Elliott Hughes9076b0c2018-02-28 11:29:45 -08001081 int app_target_api_level = get_application_target_sdk_version();
Elliott Hughes95c6cd72019-12-20 13:26:14 -08001082 if (app_target_api_level < 23) {
Dmitriy Ivanovd974e882015-05-27 18:29:41 -07001083 const char* bname = basename(dt_needed);
1084 if (bname != dt_needed) {
Elliott Hughes95c6cd72019-12-20 13:26:14 -08001085 DL_WARN_documented_change(23,
Elliott Hughes9076b0c2018-02-28 11:29:45 -08001086 "invalid-dt_needed-entries-enforced-for-api-level-23",
1087 "library \"%s\" has invalid DT_NEEDED entry \"%s\"",
1088 sopath, dt_needed, app_target_api_level);
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07001089 add_dlwarning(sopath, "invalid DT_NEEDED entry", dt_needed);
Dmitriy Ivanovd974e882015-05-27 18:29:41 -07001090 }
1091
1092 return bname;
1093 }
1094#endif
1095 return dt_needed;
1096}
1097
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001098template<typename F>
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001099static void for_each_dt_needed(const ElfReader& elf_reader, F action) {
1100 for (const ElfW(Dyn)* d = elf_reader.dynamic(); d->d_tag != DT_NULL; ++d) {
1101 if (d->d_tag == DT_NEEDED) {
1102 action(fix_dt_needed(elf_reader.get_string(d->d_un.d_val), elf_reader.name()));
1103 }
1104 }
1105}
1106
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001107static bool find_loaded_library_by_inode(android_namespace_t* ns,
1108 const struct stat& file_stat,
1109 off64_t file_offset,
1110 bool search_linked_namespaces,
1111 soinfo** candidate) {
Vic Yang3ec16be2019-06-02 21:10:53 -07001112 if (file_stat.st_dev == 0 || file_stat.st_ino == 0) {
1113 *candidate = nullptr;
1114 return false;
1115 }
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001116
1117 auto predicate = [&](soinfo* si) {
Vic Yang3ec16be2019-06-02 21:10:53 -07001118 return si->get_st_ino() == file_stat.st_ino &&
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001119 si->get_st_dev() == file_stat.st_dev &&
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001120 si->get_file_offset() == file_offset;
1121 };
1122
1123 *candidate = ns->soinfo_list().find_if(predicate);
1124
1125 if (*candidate == nullptr && search_linked_namespaces) {
1126 for (auto& link : ns->linked_namespaces()) {
1127 android_namespace_t* linked_ns = link.linked_namespace();
1128 soinfo* si = linked_ns->soinfo_list().find_if(predicate);
1129
1130 if (si != nullptr && link.is_accessible(si->get_soname())) {
1131 *candidate = si;
1132 return true;
1133 }
1134 }
1135 }
1136
1137 return *candidate != nullptr;
1138}
1139
Evgenii Stepanov9e77a642017-07-27 14:55:44 -07001140static bool find_loaded_library_by_realpath(android_namespace_t* ns, const char* realpath,
1141 bool search_linked_namespaces, soinfo** candidate) {
1142 auto predicate = [&](soinfo* si) { return strcmp(realpath, si->get_realpath()) == 0; };
1143
1144 *candidate = ns->soinfo_list().find_if(predicate);
1145
1146 if (*candidate == nullptr && search_linked_namespaces) {
1147 for (auto& link : ns->linked_namespaces()) {
1148 android_namespace_t* linked_ns = link.linked_namespace();
1149 soinfo* si = linked_ns->soinfo_list().find_if(predicate);
1150
1151 if (si != nullptr && link.is_accessible(si->get_soname())) {
1152 *candidate = si;
1153 return true;
1154 }
1155 }
1156 }
1157
1158 return *candidate != nullptr;
1159}
1160
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001161static bool load_library(android_namespace_t* ns,
1162 LoadTask* task,
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001163 LoadTaskList* load_tasks,
1164 int rtld_flags,
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001165 const std::string& realpath,
1166 bool search_linked_namespaces) {
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001167 off64_t file_offset = task->get_file_offset();
1168 const char* name = task->get_name();
1169 const android_dlextinfo* extinfo = task->get_extinfo();
1170
Martin Stjernholm9fe38262019-08-27 17:08:45 +01001171 LD_LOG(kLogDlopen,
1172 "load_library(ns=%s, task=%s, flags=0x%x, realpath=%s, search_linked_namespaces=%d)",
1173 ns->get_name(), name, rtld_flags, realpath.c_str(), search_linked_namespaces);
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001174
Peter Collingbournebb11ee62022-05-02 12:26:16 -07001175 if ((file_offset % page_size()) != 0) {
Martin Stjernholm9fe38262019-08-27 17:08:45 +01001176 DL_OPEN_ERR("file offset for the library \"%s\" is not page-aligned: %" PRId64, name, file_offset);
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001177 return false;
Dmitriy Ivanov07e5bc12014-10-03 17:52:44 -07001178 }
Yabin Cui16f7f8d2014-11-04 11:08:05 -08001179 if (file_offset < 0) {
Martin Stjernholm9fe38262019-08-27 17:08:45 +01001180 DL_OPEN_ERR("file offset for the library \"%s\" is negative: %" PRId64, name, file_offset);
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001181 return false;
Yabin Cui16f7f8d2014-11-04 11:08:05 -08001182 }
Dmitriy Ivanov07e5bc12014-10-03 17:52:44 -07001183
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001184 struct stat file_stat;
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001185 if (TEMP_FAILURE_RETRY(fstat(task->get_fd(), &file_stat)) != 0) {
Martin Stjernholm9fe38262019-08-27 17:08:45 +01001186 DL_OPEN_ERR("unable to stat file for the library \"%s\": %s", name, strerror(errno));
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001187 return false;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001188 }
Yabin Cui16f7f8d2014-11-04 11:08:05 -08001189 if (file_offset >= file_stat.st_size) {
Martin Stjernholm9fe38262019-08-27 17:08:45 +01001190 DL_OPEN_ERR("file offset for the library \"%s\" >= file size: %" PRId64 " >= %" PRId64,
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07001191 name, file_offset, file_stat.st_size);
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001192 return false;
Yabin Cui16f7f8d2014-11-04 11:08:05 -08001193 }
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001194
1195 // Check for symlink and other situations where
Dmitriy Ivanov9b821362015-04-02 16:03:56 -07001196 // file can have different names, unless ANDROID_DLEXT_FORCE_LOAD is set
1197 if (extinfo == nullptr || (extinfo->flags & ANDROID_DLEXT_FORCE_LOAD) == 0) {
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001198 soinfo* si = nullptr;
1199 if (find_loaded_library_by_inode(ns, file_stat, file_offset, search_linked_namespaces, &si)) {
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001200 LD_LOG(kLogDlopen,
1201 "load_library(ns=%s, task=%s): Already loaded under different name/path \"%s\" - "
1202 "will return existing soinfo",
1203 ns->get_name(), name, si->get_realpath());
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001204 task->set_soinfo(si);
1205 return true;
1206 }
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001207 }
Dmitriy Ivanovd59e5002014-05-09 09:10:14 -07001208
Dmitriy Ivanove8ba50f2014-09-15 17:00:10 -07001209 if ((rtld_flags & RTLD_NOLOAD) != 0) {
Martin Stjernholm9fe38262019-08-27 17:08:45 +01001210 DL_OPEN_ERR("library \"%s\" wasn't loaded and RTLD_NOLOAD prevented it", name);
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001211 return false;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001212 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001213
Dimitry Ivanovbf34ba32017-04-21 13:12:05 -07001214 struct statfs fs_stat;
1215 if (TEMP_FAILURE_RETRY(fstatfs(task->get_fd(), &fs_stat)) != 0) {
Martin Stjernholm9fe38262019-08-27 17:08:45 +01001216 DL_OPEN_ERR("unable to fstatfs file for the library \"%s\": %s", name, strerror(errno));
Dimitry Ivanovbf34ba32017-04-21 13:12:05 -07001217 return false;
1218 }
1219
1220 // do not check accessibility using realpath if fd is located on tmpfs
1221 // this enables use of memfd_create() for apps
1222 if ((fs_stat.f_type != TMPFS_MAGIC) && (!ns->is_accessible(realpath))) {
Ryan Prichardaff9a342020-08-03 15:29:12 -07001223 // TODO(dimitry): workaround for http://b/26394120 - the exempt-list
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001224
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07001225 const soinfo* needed_by = task->is_dt_needed() ? task->get_needed_by() : nullptr;
Ryan Prichardaff9a342020-08-03 15:29:12 -07001226 if (is_exempt_lib(ns, name, needed_by)) {
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07001227 // print warning only if needed by non-system library
1228 if (needed_by == nullptr || !is_system_library(needed_by->get_realpath())) {
1229 const soinfo* needed_or_dlopened_by = task->get_needed_by();
1230 const char* sopath = needed_or_dlopened_by == nullptr ? "(unknown)" :
1231 needed_or_dlopened_by->get_realpath();
Elliott Hughes95c6cd72019-12-20 13:26:14 -08001232 DL_WARN_documented_change(24,
Elliott Hughes9076b0c2018-02-28 11:29:45 -08001233 "private-api-enforced-for-api-level-24",
1234 "library \"%s\" (\"%s\") needed or dlopened by \"%s\" "
1235 "is not accessible by namespace \"%s\"",
1236 name, realpath.c_str(), sopath, ns->get_name());
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07001237 add_dlwarning(sopath, "unauthorized access to", name);
1238 }
1239 } else {
1240 // do not load libraries if they are not accessible for the specified namespace.
1241 const char* needed_or_dlopened_by = task->get_needed_by() == nullptr ?
1242 "(unknown)" :
1243 task->get_needed_by()->get_realpath();
Dimitry Ivanovd17a3772016-03-01 13:11:28 -08001244
Martin Stjernholm9fe38262019-08-27 17:08:45 +01001245 DL_OPEN_ERR("library \"%s\" needed or dlopened by \"%s\" is not accessible for the namespace \"%s\"",
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07001246 name, needed_or_dlopened_by, ns->get_name());
Dimitry Ivanovd17a3772016-03-01 13:11:28 -08001247
Dimitry Ivanov35c8e3b2017-02-27 12:17:47 -08001248 // do not print this if a library is in the list of shared libraries for linked namespaces
1249 if (!maybe_accessible_via_namespace_links(ns, name)) {
1250 PRINT("library \"%s\" (\"%s\") needed or dlopened by \"%s\" is not accessible for the"
1251 " namespace: [name=\"%s\", ld_library_paths=\"%s\", default_library_paths=\"%s\","
1252 " permitted_paths=\"%s\"]",
1253 name, realpath.c_str(),
1254 needed_or_dlopened_by,
1255 ns->get_name(),
1256 android::base::Join(ns->get_ld_library_paths(), ':').c_str(),
1257 android::base::Join(ns->get_default_library_paths(), ':').c_str(),
1258 android::base::Join(ns->get_permitted_paths(), ':').c_str());
1259 }
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07001260 return false;
1261 }
Dimitry Ivanov22840aa2015-12-04 18:28:49 -08001262 }
1263
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001264 soinfo* si = soinfo_alloc(ns, realpath.c_str(), &file_stat, file_offset, rtld_flags);
Dmitriy Ivanovd59e5002014-05-09 09:10:14 -07001265
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001266 task->set_soinfo(si);
1267
1268 // Read the ELF header and some of the segments.
1269 if (!task->read(realpath.c_str(), file_stat.st_size)) {
Ryan Prichard4fa6d992020-03-26 21:31:43 -07001270 task->remove_cached_elf_reader();
Dmitriy Ivanovfd7a91e2015-11-06 10:44:37 -08001271 task->set_soinfo(nullptr);
Ryan Prichard4fa6d992020-03-26 21:31:43 -07001272 soinfo_free(si);
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001273 return false;
1274 }
1275
Ryan Prichard058eb8f2020-12-17 22:59:04 -08001276 // Find and set DT_RUNPATH, DT_SONAME, and DT_FLAGS_1.
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001277 // Note that these field values are temporary and are
1278 // going to be overwritten on soinfo::prelink_image
1279 // with values from PT_LOAD segments.
1280 const ElfReader& elf_reader = task->get_elf_reader();
1281 for (const ElfW(Dyn)* d = elf_reader.dynamic(); d->d_tag != DT_NULL; ++d) {
1282 if (d->d_tag == DT_RUNPATH) {
1283 si->set_dt_runpath(elf_reader.get_string(d->d_un.d_val));
1284 }
1285 if (d->d_tag == DT_SONAME) {
1286 si->set_soname(elf_reader.get_string(d->d_un.d_val));
1287 }
Ryan Prichard058eb8f2020-12-17 22:59:04 -08001288 // We need to identify a DF_1_GLOBAL library early so we can link it to namespaces.
1289 if (d->d_tag == DT_FLAGS_1) {
1290 si->set_dt_flags_1(d->d_un.d_val);
1291 }
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001292 }
1293
Dan Willemsen5038ef62018-10-21 17:45:04 -07001294#if !defined(__ANDROID__)
1295 // Bionic on the host currently uses some Android prebuilts, which don't set
1296 // DT_RUNPATH with any relative paths, so they can't find their dependencies.
1297 // b/118058804
1298 if (si->get_dt_runpath().empty()) {
1299 si->set_dt_runpath("$ORIGIN/../lib64:$ORIGIN/lib64");
1300 }
1301#endif
1302
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001303 for_each_dt_needed(task->get_elf_reader(), [&](const char* name) {
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001304 LD_LOG(kLogDlopen, "load_library(ns=%s, task=%s): Adding DT_NEEDED task: %s",
1305 ns->get_name(), task->get_name(), name);
Jiyong Park02586a22017-05-20 01:01:24 +09001306 load_tasks->push_back(LoadTask::create(name, si, ns, task->get_readers_map()));
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001307 });
Dmitriy Ivanovd59e5002014-05-09 09:10:14 -07001308
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001309 return true;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001310}
1311
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001312static bool load_library(android_namespace_t* ns,
1313 LoadTask* task,
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001314 ZipArchiveCache* zip_archive_cache,
1315 LoadTaskList* load_tasks,
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001316 int rtld_flags,
1317 bool search_linked_namespaces) {
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001318 const char* name = task->get_name();
1319 soinfo* needed_by = task->get_needed_by();
1320 const android_dlextinfo* extinfo = task->get_extinfo();
1321
Spencer Low0346ad72015-04-22 18:06:51 -07001322 if (extinfo != nullptr && (extinfo->flags & ANDROID_DLEXT_USE_LIBRARY_FD) != 0) {
Ryan Prichardaa2db962020-03-24 20:25:53 -07001323 off64_t file_offset = 0;
Spencer Low0346ad72015-04-22 18:06:51 -07001324 if ((extinfo->flags & ANDROID_DLEXT_USE_LIBRARY_FD_OFFSET) != 0) {
1325 file_offset = extinfo->library_fd_offset;
1326 }
Dmitriy Ivanova1feb112015-10-01 18:41:57 -07001327
Ryan Prichardaa2db962020-03-24 20:25:53 -07001328 std::string realpath;
Dmitriy Ivanova1feb112015-10-01 18:41:57 -07001329 if (!realpath_fd(extinfo->library_fd, &realpath)) {
Tom Cherry66bc4282018-11-08 13:40:52 -08001330 if (!is_first_stage_init()) {
1331 PRINT(
1332 "warning: unable to get realpath for the library \"%s\" by extinfo->library_fd. "
1333 "Will use given name.",
1334 name);
1335 }
Dmitriy Ivanova1feb112015-10-01 18:41:57 -07001336 realpath = name;
1337 }
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001338
1339 task->set_fd(extinfo->library_fd, false);
1340 task->set_file_offset(file_offset);
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001341 return load_library(ns, task, load_tasks, rtld_flags, realpath, search_linked_namespaces);
Spencer Low0346ad72015-04-22 18:06:51 -07001342 }
1343
Martin Stjernholm9fe38262019-08-27 17:08:45 +01001344 LD_LOG(kLogDlopen,
1345 "load_library(ns=%s, task=%s, flags=0x%x, search_linked_namespaces=%d): calling "
Ryan Prichardaa2db962020-03-24 20:25:53 -07001346 "open_library",
1347 ns->get_name(), name, rtld_flags, search_linked_namespaces);
Martin Stjernholm9fe38262019-08-27 17:08:45 +01001348
Spencer Low0346ad72015-04-22 18:06:51 -07001349 // Open the file.
Ryan Prichardaa2db962020-03-24 20:25:53 -07001350 off64_t file_offset;
1351 std::string realpath;
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001352 int fd = open_library(ns, zip_archive_cache, name, needed_by, &file_offset, &realpath);
Spencer Low0346ad72015-04-22 18:06:51 -07001353 if (fd == -1) {
Josh Gao16269572019-10-29 13:41:00 -07001354 if (task->is_dt_needed()) {
1355 if (needed_by->is_main_executable()) {
1356 DL_OPEN_ERR("library \"%s\" not found: needed by main executable", name);
1357 } else {
1358 DL_OPEN_ERR("library \"%s\" not found: needed by %s in namespace %s", name,
1359 needed_by->get_realpath(), task->get_start_from()->get_name());
1360 }
1361 } else {
1362 DL_OPEN_ERR("library \"%s\" not found", name);
1363 }
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001364 return false;
Spencer Low0346ad72015-04-22 18:06:51 -07001365 }
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001366
1367 task->set_fd(fd, true);
1368 task->set_file_offset(file_offset);
1369
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001370 return load_library(ns, task, load_tasks, rtld_flags, realpath, search_linked_namespaces);
Spencer Low0346ad72015-04-22 18:06:51 -07001371}
1372
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001373static bool find_loaded_library_by_soname(android_namespace_t* ns,
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001374 const char* name,
1375 soinfo** candidate) {
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001376 return !ns->soinfo_list().visit([&](soinfo* si) {
Elliott Hughesf9dd1a72021-01-11 09:04:58 -08001377 if (strcmp(name, si->get_soname()) == 0) {
Dimitry Ivanov3bd90612017-02-01 08:54:43 -08001378 *candidate = si;
1379 return false;
Ard Biesheuvel12c78bb2012-08-14 12:30:09 +02001380 }
Dmitriy Ivanova9703332015-06-16 15:38:21 -07001381
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001382 return true;
1383 });
Ard Biesheuvel12c78bb2012-08-14 12:30:09 +02001384}
1385
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001386// Returns true if library was found and false otherwise
1387static bool find_loaded_library_by_soname(android_namespace_t* ns,
1388 const char* name,
1389 bool search_linked_namespaces,
1390 soinfo** candidate) {
1391 *candidate = nullptr;
1392
1393 // Ignore filename with path.
1394 if (strchr(name, '/') != nullptr) {
1395 return false;
1396 }
1397
1398 bool found = find_loaded_library_by_soname(ns, name, candidate);
1399
1400 if (!found && search_linked_namespaces) {
1401 // if a library was not found - look into linked namespaces
1402 for (auto& link : ns->linked_namespaces()) {
1403 if (!link.is_accessible(name)) {
1404 continue;
1405 }
1406
1407 android_namespace_t* linked_ns = link.linked_namespace();
1408
1409 if (find_loaded_library_by_soname(linked_ns, name, candidate)) {
1410 return true;
1411 }
1412 }
1413 }
1414
1415 return found;
1416}
1417
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001418static bool find_library_in_linked_namespace(const android_namespace_link_t& namespace_link,
Jiyong Park02586a22017-05-20 01:01:24 +09001419 LoadTask* task) {
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001420 android_namespace_t* ns = namespace_link.linked_namespace();
1421
1422 soinfo* candidate;
1423 bool loaded = false;
1424
1425 std::string soname;
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001426 if (find_loaded_library_by_soname(ns, task->get_name(), false, &candidate)) {
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001427 loaded = true;
1428 soname = candidate->get_soname();
1429 } else {
1430 soname = resolve_soname(task->get_name());
1431 }
1432
1433 if (!namespace_link.is_accessible(soname.c_str())) {
1434 // the library is not accessible via namespace_link
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001435 LD_LOG(kLogDlopen,
1436 "find_library_in_linked_namespace(ns=%s, task=%s): Not accessible (soname=%s)",
1437 ns->get_name(), task->get_name(), soname.c_str());
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001438 return false;
1439 }
1440
1441 // if library is already loaded - return it
1442 if (loaded) {
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001443 LD_LOG(kLogDlopen, "find_library_in_linked_namespace(ns=%s, task=%s): Already loaded",
1444 ns->get_name(), task->get_name());
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001445 task->set_soinfo(candidate);
1446 return true;
1447 }
1448
Jiyong Park02586a22017-05-20 01:01:24 +09001449 // returning true with empty soinfo means that the library is okay to be
Logan Chien9ee45912018-01-18 12:05:09 +08001450 // loaded in the namespace but has not yet been loaded there before.
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001451 LD_LOG(kLogDlopen, "find_library_in_linked_namespace(ns=%s, task=%s): Ok to load", ns->get_name(),
1452 task->get_name());
Jiyong Park02586a22017-05-20 01:01:24 +09001453 task->set_soinfo(nullptr);
1454 return true;
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001455}
1456
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001457static bool find_library_internal(android_namespace_t* ns,
1458 LoadTask* task,
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001459 ZipArchiveCache* zip_archive_cache,
1460 LoadTaskList* load_tasks,
Ryan Prichard323d7df2020-03-24 21:19:06 -07001461 int rtld_flags) {
Dmitriy Ivanova9703332015-06-16 15:38:21 -07001462 soinfo* candidate;
1463
Ryan Prichard323d7df2020-03-24 21:19:06 -07001464 if (find_loaded_library_by_soname(ns, task->get_name(), true /* search_linked_namespaces */,
1465 &candidate)) {
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001466 LD_LOG(kLogDlopen,
1467 "find_library_internal(ns=%s, task=%s): Already loaded (by soname): %s",
1468 ns->get_name(), task->get_name(), candidate->get_realpath());
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001469 task->set_soinfo(candidate);
1470 return true;
Dmitriy Ivanova9703332015-06-16 15:38:21 -07001471 }
Dmitriy Ivanovb648a8a2014-05-19 15:06:58 -07001472
1473 // Library might still be loaded, the accurate detection
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001474 // of this fact is done by load_library.
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001475 TRACE("[ \"%s\" find_loaded_library_by_soname failed (*candidate=%s@%p). Trying harder... ]",
1476 task->get_name(), candidate == nullptr ? "n/a" : candidate->get_realpath(), candidate);
Dmitriy Ivanova9703332015-06-16 15:38:21 -07001477
Ryan Prichard323d7df2020-03-24 21:19:06 -07001478 if (load_library(ns, task, zip_archive_cache, load_tasks, rtld_flags,
1479 true /* search_linked_namespaces */)) {
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001480 return true;
1481 }
1482
Ryan Prichardaff9a342020-08-03 15:29:12 -07001483 // TODO(dimitry): workaround for http://b/26394120 (the exempt-list)
1484 if (ns->is_exempt_list_enabled() && is_exempt_lib(ns, task->get_name(), task->get_needed_by())) {
1485 // For the libs in the exempt-list, switch to the default namespace and then
Jiyong Parkefc503d2019-02-12 01:08:57 +09001486 // try the load again from there. The library could be loaded from the
1487 // default namespace or from another namespace (e.g. runtime) that is linked
1488 // from the default namespace.
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001489 LD_LOG(kLogDlopen,
Ryan Prichardaff9a342020-08-03 15:29:12 -07001490 "find_library_internal(ns=%s, task=%s): Exempt system library - trying namespace %s",
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001491 ns->get_name(), task->get_name(), g_default_namespace.get_name());
Jiyong Parkefc503d2019-02-12 01:08:57 +09001492 ns = &g_default_namespace;
1493 if (load_library(ns, task, zip_archive_cache, load_tasks, rtld_flags,
Ryan Prichard323d7df2020-03-24 21:19:06 -07001494 true /* search_linked_namespaces */)) {
Jiyong Parkefc503d2019-02-12 01:08:57 +09001495 return true;
1496 }
1497 }
1498 // END OF WORKAROUND
1499
Ryan Prichard323d7df2020-03-24 21:19:06 -07001500 // if a library was not found - look into linked namespaces
1501 // preserve current dlerror in the case it fails.
1502 DlErrorRestorer dlerror_restorer;
1503 LD_LOG(kLogDlopen, "find_library_internal(ns=%s, task=%s): Trying %zu linked namespaces",
1504 ns->get_name(), task->get_name(), ns->linked_namespaces().size());
1505 for (auto& linked_namespace : ns->linked_namespaces()) {
1506 if (find_library_in_linked_namespace(linked_namespace, task)) {
1507 // Library is already loaded.
1508 if (task->get_soinfo() != nullptr) {
1509 // n.b. This code path runs when find_library_in_linked_namespace found an already-loaded
Ryan Prichardaff9a342020-08-03 15:29:12 -07001510 // library by soname. That should only be possible with a exempt-list lookup, where we
1511 // switch the namespace, because otherwise, find_library_in_linked_namespace is duplicating
1512 // the soname scan done in this function's first call to find_loaded_library_by_soname.
Ryan Prichard323d7df2020-03-24 21:19:06 -07001513 return true;
1514 }
1515
1516 if (load_library(linked_namespace.linked_namespace(), task, zip_archive_cache, load_tasks,
1517 rtld_flags, false /* search_linked_namespaces */)) {
1518 LD_LOG(kLogDlopen, "find_library_internal(ns=%s, task=%s): Found in linked namespace %s",
1519 ns->get_name(), task->get_name(), linked_namespace.linked_namespace()->get_name());
1520 return true;
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001521 }
1522 }
1523 }
1524
1525 return false;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001526}
1527
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001528static void soinfo_unload(soinfo* si);
1529
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001530static void shuffle(std::vector<LoadTask*>* v) {
Tom Cherry66bc4282018-11-08 13:40:52 -08001531 if (is_first_stage_init()) {
1532 // arc4random* is not available in first stage init because /dev/random
1533 // hasn't yet been created.
Jiyong Park31cd08f2018-06-01 19:18:56 +09001534 return;
1535 }
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001536 for (size_t i = 0, size = v->size(); i < size; ++i) {
1537 size_t n = size - i;
1538 size_t r = arc4random_uniform(n);
1539 std::swap((*v)[n-1], (*v)[r]);
1540 }
1541}
1542
Evgenii Stepanov0cdef7e2015-07-06 17:56:31 -07001543// add_as_children - add first-level loaded libraries (i.e. library_names[], but
1544// not their transitive dependencies) as children of the start_with library.
1545// This is false when find_libraries is called for dlopen(), when newly loaded
1546// libraries must form a disjoint tree.
Dimitry Ivanov3f660572016-09-09 10:00:39 -07001547bool find_libraries(android_namespace_t* ns,
1548 soinfo* start_with,
1549 const char* const library_names[],
1550 size_t library_names_count,
1551 soinfo* soinfos[],
1552 std::vector<soinfo*>* ld_preloads,
1553 size_t ld_preloads_count,
1554 int rtld_flags,
1555 const android_dlextinfo* extinfo,
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001556 bool add_as_children,
Jiyong Park02586a22017-05-20 01:01:24 +09001557 std::vector<android_namespace_t*>* namespaces) {
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001558 // Step 0: prepare.
dimitry965d06d2017-11-28 16:03:07 +01001559 std::unordered_map<const soinfo*, ElfReader> readers_map;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001560 LoadTaskList load_tasks;
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001561
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -07001562 for (size_t i = 0; i < library_names_count; ++i) {
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001563 const char* name = library_names[i];
Jiyong Park02586a22017-05-20 01:01:24 +09001564 load_tasks.push_back(LoadTask::create(name, start_with, ns, &readers_map));
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001565 }
1566
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -07001567 // If soinfos array is null allocate one on stack.
1568 // The array is needed in case of failure; for example
1569 // when library_names[] = {libone.so, libtwo.so} and libone.so
1570 // is loaded correctly but libtwo.so failed for some reason.
1571 // In this case libone.so should be unloaded on return.
1572 // See also implementation of failure_guard below.
1573
1574 if (soinfos == nullptr) {
1575 size_t soinfos_size = sizeof(soinfo*)*library_names_count;
1576 soinfos = reinterpret_cast<soinfo**>(alloca(soinfos_size));
1577 memset(soinfos, 0, soinfos_size);
1578 }
1579
1580 // list of libraries to link - see step 2.
1581 size_t soinfos_count = 0;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001582
Tom Cherryb8ab6182017-04-05 16:20:29 -07001583 auto scope_guard = android::base::make_scope_guard([&]() {
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001584 for (LoadTask* t : load_tasks) {
1585 LoadTask::deleter(t);
1586 }
1587 });
1588
Dmitriy Ivanovb4827502015-09-28 16:38:31 -07001589 ZipArchiveCache zip_archive_cache;
Ryan Prichard058eb8f2020-12-17 22:59:04 -08001590 soinfo_list_t new_global_group_members;
Dmitriy Ivanovb4827502015-09-28 16:38:31 -07001591
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001592 // Step 1: expand the list of load_tasks to include
1593 // all DT_NEEDED libraries (do not load them just yet)
1594 for (size_t i = 0; i<load_tasks.size(); ++i) {
1595 LoadTask* task = load_tasks[i];
Evgenii Stepanov68650822015-06-10 13:38:39 -07001596 soinfo* needed_by = task->get_needed_by();
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001597
Dmitriy Ivanovedfc9f62015-09-02 16:32:02 -07001598 bool is_dt_needed = needed_by != nullptr && (needed_by != start_with || add_as_children);
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001599 task->set_extinfo(is_dt_needed ? nullptr : extinfo);
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07001600 task->set_dt_needed(is_dt_needed);
Dmitriy Ivanovedfc9f62015-09-02 16:32:02 -07001601
Jiyong Park02586a22017-05-20 01:01:24 +09001602 // Note: start from the namespace that is stored in the LoadTask. This namespace
1603 // is different from the current namespace when the LoadTask is for a transitive
1604 // dependency and the lib that created the LoadTask is not found in the
Martin Stjernholm964b14c2022-09-30 20:39:14 +01001605 // current namespace but in one of the linked namespaces.
1606 android_namespace_t* start_ns = const_cast<android_namespace_t*>(task->get_start_from());
1607
1608 LD_LOG(kLogDlopen, "find_library_internal(ns=%s@%p): task=%s, is_dt_needed=%d",
1609 start_ns->get_name(), start_ns, task->get_name(), is_dt_needed);
1610
1611 if (!find_library_internal(start_ns, task, &zip_archive_cache, &load_tasks, rtld_flags)) {
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001612 return false;
1613 }
1614
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001615 soinfo* si = task->get_soinfo();
1616
Dmitriy Ivanovedfc9f62015-09-02 16:32:02 -07001617 if (is_dt_needed) {
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001618 needed_by->add_child(si);
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08001619 }
1620
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -07001621 // When ld_preloads is not null, the first
1622 // ld_preloads_count libs are in fact ld_preloads.
Ryan Prichard058eb8f2020-12-17 22:59:04 -08001623 bool is_ld_preload = false;
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -07001624 if (ld_preloads != nullptr && soinfos_count < ld_preloads_count) {
Dmitriy Ivanovd165f562015-03-23 18:43:02 -07001625 ld_preloads->push_back(si);
Ryan Prichard058eb8f2020-12-17 22:59:04 -08001626 is_ld_preload = true;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001627 }
1628
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -07001629 if (soinfos_count < library_names_count) {
1630 soinfos[soinfos_count++] = si;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001631 }
Ryan Prichard058eb8f2020-12-17 22:59:04 -08001632
1633 // Add the new global group members to all initial namespaces. Do this secondary namespace setup
1634 // at the same time that libraries are added to their primary namespace so that the order of
1635 // global group members is the same in the every namespace. Only add a library to a namespace
1636 // once, even if it appears multiple times in the dependency graph.
1637 if (is_ld_preload || (si->get_dt_flags_1() & DF_1_GLOBAL) != 0) {
1638 if (!si->is_linked() && namespaces != nullptr && !new_global_group_members.contains(si)) {
1639 new_global_group_members.push_back(si);
1640 for (auto linked_ns : *namespaces) {
1641 if (si->get_primary_namespace() != linked_ns) {
1642 linked_ns->add_soinfo(si);
1643 si->add_secondary_namespace(linked_ns);
1644 }
1645 }
1646 }
1647 }
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001648 }
1649
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001650 // Step 2: Load libraries in random order (see b/24047022)
1651 LoadTaskList load_list;
1652 for (auto&& task : load_tasks) {
1653 soinfo* si = task->get_soinfo();
1654 auto pred = [&](const LoadTask* t) {
1655 return t->get_soinfo() == si;
1656 };
1657
1658 if (!si->is_linked() &&
1659 std::find_if(load_list.begin(), load_list.end(), pred) == load_list.end() ) {
1660 load_list.push_back(task);
1661 }
1662 }
Torne (Richard Coles)efbe9a52018-10-17 15:59:38 -04001663 bool reserved_address_recursive = false;
1664 if (extinfo) {
1665 reserved_address_recursive = extinfo->flags & ANDROID_DLEXT_RESERVED_ADDRESS_RECURSIVE;
1666 }
1667 if (!reserved_address_recursive) {
1668 // Shuffle the load order in the normal case, but not if we are loading all
1669 // the libraries to a reserved address range.
1670 shuffle(&load_list);
1671 }
1672
1673 // Set up address space parameters.
1674 address_space_params extinfo_params, default_params;
1675 size_t relro_fd_offset = 0;
1676 if (extinfo) {
1677 if (extinfo->flags & ANDROID_DLEXT_RESERVED_ADDRESS) {
1678 extinfo_params.start_addr = extinfo->reserved_addr;
1679 extinfo_params.reserved_size = extinfo->reserved_size;
1680 extinfo_params.must_use_address = true;
1681 } else if (extinfo->flags & ANDROID_DLEXT_RESERVED_ADDRESS_HINT) {
1682 extinfo_params.start_addr = extinfo->reserved_addr;
1683 extinfo_params.reserved_size = extinfo->reserved_size;
1684 }
1685 }
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001686
1687 for (auto&& task : load_list) {
Torne (Richard Coles)efbe9a52018-10-17 15:59:38 -04001688 address_space_params* address_space =
1689 (reserved_address_recursive || !task->is_dt_needed()) ? &extinfo_params : &default_params;
1690 if (!task->load(address_space)) {
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001691 return false;
1692 }
1693 }
1694
1695 // Step 3: pre-link all DT_NEEDED libraries in breadth first order.
1696 for (auto&& task : load_tasks) {
1697 soinfo* si = task->get_soinfo();
1698 if (!si->is_linked() && !si->prelink_image()) {
1699 return false;
1700 }
Ryan Pricharde5e69e02019-01-01 18:53:48 -08001701 register_soinfo_tls(si);
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001702 }
1703
Ryan Prichard058eb8f2020-12-17 22:59:04 -08001704 // Step 4: Construct the global group. DF_1_GLOBAL bit is force set for LD_PRELOADed libs because
1705 // they must be added to the global group. Note: The DF_1_GLOBAL bit for a library is normally set
1706 // in step 3.
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001707 if (ld_preloads != nullptr) {
1708 for (auto&& si : *ld_preloads) {
1709 si->set_dt_flags_1(si->get_dt_flags_1() | DF_1_GLOBAL);
1710 }
1711 }
1712
dimitry965d06d2017-11-28 16:03:07 +01001713 // Step 5: Collect roots of local_groups.
1714 // Whenever needed_by->si link crosses a namespace boundary it forms its own local_group.
1715 // Here we collect new roots to link them separately later on. Note that we need to avoid
1716 // collecting duplicates. Also the order is important. They need to be linked in the same
1717 // BFS order we link individual libraries.
1718 std::vector<soinfo*> local_group_roots;
1719 if (start_with != nullptr && add_as_children) {
1720 local_group_roots.push_back(start_with);
1721 } else {
1722 CHECK(soinfos_count == 1);
1723 local_group_roots.push_back(soinfos[0]);
1724 }
1725
Jiyong Park02586a22017-05-20 01:01:24 +09001726 for (auto&& task : load_tasks) {
1727 soinfo* si = task->get_soinfo();
dimitry965d06d2017-11-28 16:03:07 +01001728 soinfo* needed_by = task->get_needed_by();
1729 bool is_dt_needed = needed_by != nullptr && (needed_by != start_with || add_as_children);
1730 android_namespace_t* needed_by_ns =
1731 is_dt_needed ? needed_by->get_primary_namespace() : ns;
1732
1733 if (!si->is_linked() && si->get_primary_namespace() != needed_by_ns) {
1734 auto it = std::find(local_group_roots.begin(), local_group_roots.end(), si);
1735 LD_LOG(kLogDlopen,
1736 "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",
1737 si->get_realpath(),
1738 si,
1739 si->get_primary_namespace()->get_name(),
1740 si->get_primary_namespace(),
1741 needed_by == nullptr ? "(nullptr)" : needed_by->get_realpath(),
1742 needed_by,
1743 ns->get_name(),
1744 ns,
1745 needed_by_ns->get_name(),
1746 needed_by_ns,
1747 it == local_group_roots.end() ? "yes" : "no");
1748
1749 if (it == local_group_roots.end()) {
1750 local_group_roots.push_back(si);
Jiyong Park02586a22017-05-20 01:01:24 +09001751 }
1752 }
1753 }
1754
dimitry965d06d2017-11-28 16:03:07 +01001755 // Step 6: Link all local groups
1756 for (auto root : local_group_roots) {
1757 soinfo_list_t local_group;
1758 android_namespace_t* local_group_ns = root->get_primary_namespace();
1759
1760 walk_dependencies_tree(root,
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -07001761 [&] (soinfo* si) {
dimitry965d06d2017-11-28 16:03:07 +01001762 if (local_group_ns->is_accessible(si)) {
1763 local_group.push_back(si);
1764 return kWalkContinue;
1765 } else {
1766 return kWalkSkip;
1767 }
1768 });
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -07001769
dimitry965d06d2017-11-28 16:03:07 +01001770 soinfo_list_t global_group = local_group_ns->get_global_group();
Ryan Prichard339ecef2020-01-02 16:36:06 -08001771 SymbolLookupList lookup_list(global_group, local_group);
1772 soinfo* local_group_root = local_group.front();
1773
dimitry965d06d2017-11-28 16:03:07 +01001774 bool linked = local_group.visit([&](soinfo* si) {
Torne (Richard Coles)5d103742019-04-11 12:25:06 -04001775 // Even though local group may contain accessible soinfos from other namespaces
dimitry965d06d2017-11-28 16:03:07 +01001776 // we should avoid linking them (because if they are not linked -> they
1777 // are in the local_group_roots and will be linked later).
1778 if (!si->is_linked() && si->get_primary_namespace() == local_group_ns) {
Torne (Richard Coles)5d103742019-04-11 12:25:06 -04001779 const android_dlextinfo* link_extinfo = nullptr;
1780 if (si == soinfos[0] || reserved_address_recursive) {
1781 // Only forward extinfo for the first library unless the recursive
1782 // flag is set.
1783 link_extinfo = extinfo;
1784 }
Peter Collingbourne191ecdc2019-08-07 19:06:00 -07001785 if (__libc_shared_globals()->load_hook) {
1786 __libc_shared_globals()->load_hook(si->load_bias, si->phdr, si->phnum);
1787 }
Ryan Prichard339ecef2020-01-02 16:36:06 -08001788 lookup_list.set_dt_symbolic_lib(si->has_DT_SYMBOLIC ? si : nullptr);
1789 if (!si->link_image(lookup_list, local_group_root, link_extinfo, &relro_fd_offset) ||
dimitry965d06d2017-11-28 16:03:07 +01001790 !get_cfi_shadow()->AfterLoad(si, solist_get_head())) {
1791 return false;
1792 }
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001793 }
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -07001794
dimitry965d06d2017-11-28 16:03:07 +01001795 return true;
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001796 });
Elliott Hughes27f18062017-11-29 18:47:42 +00001797
dimitry965d06d2017-11-28 16:03:07 +01001798 if (!linked) {
1799 return false;
1800 }
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001801 }
1802
dimitry965d06d2017-11-28 16:03:07 +01001803 // Step 7: Mark all load_tasks as linked and increment refcounts
1804 // for references between load_groups (at this point it does not matter if
1805 // referenced load_groups were loaded by previous dlopen or as part of this
1806 // one on step 6)
1807 if (start_with != nullptr && add_as_children) {
1808 start_with->set_linked();
1809 }
1810
1811 for (auto&& task : load_tasks) {
1812 soinfo* si = task->get_soinfo();
1813 si->set_linked();
1814 }
1815
1816 for (auto&& task : load_tasks) {
1817 soinfo* si = task->get_soinfo();
1818 soinfo* needed_by = task->get_needed_by();
1819 if (needed_by != nullptr &&
1820 needed_by != start_with &&
1821 needed_by->get_local_group_root() != si->get_local_group_root()) {
1822 si->increment_ref_count();
1823 }
1824 }
1825
1826
1827 return true;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001828}
1829
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001830static soinfo* find_library(android_namespace_t* ns,
1831 const char* name, int rtld_flags,
Evgenii Stepanov0cdef7e2015-07-06 17:56:31 -07001832 const android_dlextinfo* extinfo,
1833 soinfo* needed_by) {
dimitry965d06d2017-11-28 16:03:07 +01001834 soinfo* si = nullptr;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001835
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08001836 if (name == nullptr) {
Dimitry Ivanov3f660572016-09-09 10:00:39 -07001837 si = solist_get_somain();
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001838 } else if (!find_libraries(ns,
1839 needed_by,
1840 &name,
1841 1,
1842 &si,
1843 nullptr,
1844 0,
1845 rtld_flags,
1846 extinfo,
Ryan Prichard323d7df2020-03-24 21:19:06 -07001847 false /* add_as_children */)) {
dimitry965d06d2017-11-28 16:03:07 +01001848 if (si != nullptr) {
1849 soinfo_unload(si);
1850 }
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001851 return nullptr;
1852 }
1853
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001854 si->increment_ref_count();
1855
Elliott Hughesd23736e2012-11-01 15:16:56 -07001856 return si;
1857}
Elliott Hughesbedfe382012-08-14 14:07:59 -07001858
dimitry06016f22018-01-05 11:39:28 +01001859static void soinfo_unload_impl(soinfo* root) {
Dimitry Ivanov6705e8c2017-03-21 10:29:06 -07001860 ScopedTrace trace((std::string("unload ") + root->get_realpath()).c_str());
dimitry06016f22018-01-05 11:39:28 +01001861 bool is_linked = root->is_linked();
Dimitry Ivanov6705e8c2017-03-21 10:29:06 -07001862
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08001863 if (!root->can_unload()) {
dimitryc92ce712017-10-27 14:12:53 +02001864 LD_LOG(kLogDlopen,
1865 "... dlclose(root=\"%s\"@%p) ... not unloading - the load group is flagged with NODELETE",
1866 root->get_realpath(),
1867 root);
Dmitriy Ivanov1b20daf2014-05-19 15:06:58 -07001868 return;
1869 }
1870
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08001871
Dimitry Ivanovb943f302016-08-03 16:00:10 -07001872 soinfo_list_t unload_list;
dimitry965d06d2017-11-28 16:03:07 +01001873 unload_list.push_back(root);
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001874
Dimitry Ivanovb943f302016-08-03 16:00:10 -07001875 soinfo_list_t local_unload_list;
1876 soinfo_list_t external_unload_list;
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001877 soinfo* si = nullptr;
1878
1879 while ((si = unload_list.pop_front()) != nullptr) {
1880 if (local_unload_list.contains(si)) {
1881 continue;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001882 }
Elliott Hughesd23736e2012-11-01 15:16:56 -07001883
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001884 local_unload_list.push_back(si);
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08001885
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001886 if (si->has_min_version(0)) {
1887 soinfo* child = nullptr;
1888 while ((child = si->get_children().pop_front()) != nullptr) {
1889 TRACE("%s@%p needs to unload %s@%p", si->get_realpath(), si,
1890 child->get_realpath(), child);
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08001891
Dimitry Ivanovec90e242017-02-10 11:04:20 -08001892 child->get_parents().remove(si);
1893
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001894 if (local_unload_list.contains(child)) {
1895 continue;
1896 } else if (child->is_linked() && child->get_local_group_root() != root) {
1897 external_unload_list.push_back(child);
Dimitry Ivanovec90e242017-02-10 11:04:20 -08001898 } else if (child->get_parents().empty()) {
1899 unload_list.push_back(child);
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001900 }
1901 }
1902 } else {
Christopher Ferris7a3681e2017-04-24 17:48:32 -07001903 async_safe_fatal("soinfo for \"%s\"@%p has no version", si->get_realpath(), si);
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08001904 }
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001905 }
1906
1907 local_unload_list.for_each([](soinfo* si) {
dimitryc92ce712017-10-27 14:12:53 +02001908 LD_LOG(kLogDlopen,
1909 "... dlclose: calling destructors for \"%s\"@%p ... ",
1910 si->get_realpath(),
1911 si);
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001912 si->call_destructors();
dimitryc92ce712017-10-27 14:12:53 +02001913 LD_LOG(kLogDlopen,
1914 "... dlclose: calling destructors for \"%s\"@%p ... done",
1915 si->get_realpath(),
1916 si);
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001917 });
1918
1919 while ((si = local_unload_list.pop_front()) != nullptr) {
dimitryc92ce712017-10-27 14:12:53 +02001920 LD_LOG(kLogDlopen,
1921 "... dlclose: unloading \"%s\"@%p ...",
1922 si->get_realpath(),
1923 si);
Ryan Pricharda2e83ab2019-08-16 17:25:43 -07001924 ++g_module_unload_counter;
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001925 notify_gdb_of_unload(si);
Ryan Pricharde5e69e02019-01-01 18:53:48 -08001926 unregister_soinfo_tls(si);
Peter Collingbourne65332082019-08-05 16:16:14 -07001927 if (__libc_shared_globals()->unload_hook) {
1928 __libc_shared_globals()->unload_hook(si->load_bias, si->phdr, si->phnum);
1929 }
Evgenii Stepanov0a3637d2016-07-06 13:20:59 -07001930 get_cfi_shadow()->BeforeUnload(si);
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001931 soinfo_free(si);
1932 }
1933
dimitry965d06d2017-11-28 16:03:07 +01001934 if (is_linked) {
1935 while ((si = external_unload_list.pop_front()) != nullptr) {
1936 LD_LOG(kLogDlopen,
1937 "... dlclose: unloading external reference \"%s\"@%p ...",
1938 si->get_realpath(),
1939 si);
1940 soinfo_unload(si);
1941 }
1942 } else {
1943 LD_LOG(kLogDlopen,
1944 "... dlclose: unload_si was not linked - not unloading external references ...");
Dmitriy Ivanova2547052014-11-18 12:03:09 -08001945 }
1946}
1947
dimitry06016f22018-01-05 11:39:28 +01001948static void soinfo_unload(soinfo* unload_si) {
1949 // Note that the library can be loaded but not linked;
1950 // in which case there is no root but we still need
1951 // to walk the tree and unload soinfos involved.
1952 //
1953 // This happens on unsuccessful dlopen, when one of
1954 // the DT_NEEDED libraries could not be linked/found.
1955 bool is_linked = unload_si->is_linked();
1956 soinfo* root = is_linked ? unload_si->get_local_group_root() : unload_si;
1957
1958 LD_LOG(kLogDlopen,
1959 "... dlclose(realpath=\"%s\"@%p) ... load group root is \"%s\"@%p",
1960 unload_si->get_realpath(),
1961 unload_si,
1962 root->get_realpath(),
1963 root);
1964
1965
1966 size_t ref_count = is_linked ? root->decrement_ref_count() : 0;
1967 if (ref_count > 0) {
1968 LD_LOG(kLogDlopen,
1969 "... dlclose(root=\"%s\"@%p) ... not unloading - decrementing ref_count to %zd",
1970 root->get_realpath(),
1971 root,
1972 ref_count);
1973 return;
1974 }
1975
1976 soinfo_unload_impl(root);
1977}
1978
1979void increment_dso_handle_reference_counter(void* dso_handle) {
1980 if (dso_handle == nullptr) {
1981 return;
1982 }
1983
1984 auto it = g_dso_handle_counters.find(dso_handle);
1985 if (it != g_dso_handle_counters.end()) {
1986 CHECK(++it->second != 0);
1987 } else {
1988 soinfo* si = find_containing_library(dso_handle);
1989 if (si != nullptr) {
1990 ProtectedDataGuard guard;
dimitry55547db2018-05-25 14:17:37 +02001991 si->increment_ref_count();
dimitry06016f22018-01-05 11:39:28 +01001992 } else {
1993 async_safe_fatal(
1994 "increment_dso_handle_reference_counter: Couldn't find soinfo by dso_handle=%p",
1995 dso_handle);
1996 }
1997 g_dso_handle_counters[dso_handle] = 1U;
1998 }
1999}
2000
2001void decrement_dso_handle_reference_counter(void* dso_handle) {
2002 if (dso_handle == nullptr) {
2003 return;
2004 }
2005
2006 auto it = g_dso_handle_counters.find(dso_handle);
2007 CHECK(it != g_dso_handle_counters.end());
2008 CHECK(it->second != 0);
2009
2010 if (--it->second == 0) {
2011 soinfo* si = find_containing_library(dso_handle);
2012 if (si != nullptr) {
2013 ProtectedDataGuard guard;
dimitry55547db2018-05-25 14:17:37 +02002014 soinfo_unload(si);
dimitry06016f22018-01-05 11:39:28 +01002015 } else {
2016 async_safe_fatal(
2017 "decrement_dso_handle_reference_counter: Couldn't find soinfo by dso_handle=%p",
2018 dso_handle);
2019 }
2020 g_dso_handle_counters.erase(it);
2021 }
2022}
2023
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002024static std::string symbol_display_name(const char* sym_name, const char* sym_ver) {
2025 if (sym_ver == nullptr) {
2026 return sym_name;
2027 }
2028
Dimitry Ivanov9cf99cb2015-12-11 14:22:24 -08002029 return std::string(sym_name) + ", version " + sym_ver;
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002030}
2031
Dimitry Ivanovaca299a2016-04-11 12:42:58 -07002032static android_namespace_t* get_caller_namespace(soinfo* caller) {
2033 return caller != nullptr ? caller->get_primary_namespace() : g_anonymous_namespace;
2034}
2035
Elliott Hughesa4aafd12014-01-13 16:37:47 -08002036void do_android_get_LD_LIBRARY_PATH(char* buffer, size_t buffer_size) {
Christopher Ferris052fa3a2014-08-26 20:48:11 -07002037 // Use basic string manipulation calls to avoid snprintf.
2038 // snprintf indirectly calls pthread_getspecific to get the size of a buffer.
2039 // When debug malloc is enabled, this call returns 0. This in turn causes
2040 // snprintf to do nothing, which causes libraries to fail to load.
2041 // See b/17302493 for further details.
2042 // Once the above bug is fixed, this code can be modified to use
2043 // snprintf again.
Dimitry Ivanov77ad6422017-03-06 13:02:29 -08002044 const auto& default_ld_paths = g_default_namespace.get_default_library_paths();
2045
2046 size_t required_size = 0;
2047 for (const auto& path : default_ld_paths) {
2048 required_size += path.size() + 1;
Evgenii Stepanovd640b222015-07-10 17:54:01 -07002049 }
Dimitry Ivanov77ad6422017-03-06 13:02:29 -08002050
2051 if (buffer_size < required_size) {
Christopher Ferris7a3681e2017-04-24 17:48:32 -07002052 async_safe_fatal("android_get_LD_LIBRARY_PATH failed, buffer too small: "
2053 "buffer len %zu, required len %zu", buffer_size, required_size);
Christopher Ferris052fa3a2014-08-26 20:48:11 -07002054 }
Dimitry Ivanov77ad6422017-03-06 13:02:29 -08002055
Evgenii Stepanovd640b222015-07-10 17:54:01 -07002056 char* end = buffer;
Dimitry Ivanov77ad6422017-03-06 13:02:29 -08002057 for (size_t i = 0; i < default_ld_paths.size(); ++i) {
Evgenii Stepanovd640b222015-07-10 17:54:01 -07002058 if (i > 0) *end++ = ':';
Dimitry Ivanov77ad6422017-03-06 13:02:29 -08002059 end = stpcpy(end, default_ld_paths[i].c_str());
Evgenii Stepanovd640b222015-07-10 17:54:01 -07002060 }
Elliott Hughesa4aafd12014-01-13 16:37:47 -08002061}
2062
Elliott Hughescade4c32012-12-20 14:42:14 -08002063void do_android_update_LD_LIBRARY_PATH(const char* ld_library_path) {
Nick Kralevich6bb01b62015-03-07 13:37:05 -08002064 parse_LD_LIBRARY_PATH(ld_library_path);
Elliott Hughescade4c32012-12-20 14:42:14 -08002065}
2066
Dimitry Ivanovb996d602016-07-11 18:11:39 -07002067static std::string android_dlextinfo_to_string(const android_dlextinfo* info) {
2068 if (info == nullptr) {
2069 return "(null)";
2070 }
2071
2072 return android::base::StringPrintf("[flags=0x%" PRIx64 ","
2073 " reserved_addr=%p,"
2074 " reserved_size=0x%zx,"
2075 " relro_fd=%d,"
2076 " library_fd=%d,"
2077 " library_fd_offset=0x%" PRIx64 ","
2078 " library_namespace=%s@%p]",
2079 info->flags,
2080 info->reserved_addr,
2081 info->reserved_size,
2082 info->relro_fd,
2083 info->library_fd,
2084 info->library_fd_offset,
2085 (info->flags & ANDROID_DLEXT_USE_NAMESPACE) != 0 ?
2086 (info->library_namespace != nullptr ?
2087 info->library_namespace->get_name() : "(null)") : "(n/a)",
2088 (info->flags & ANDROID_DLEXT_USE_NAMESPACE) != 0 ?
2089 info->library_namespace : nullptr);
2090}
2091
Dimitry Ivanovd9e427c2016-11-22 16:55:25 -08002092void* do_dlopen(const char* name, int flags,
2093 const android_dlextinfo* extinfo,
2094 const void* caller_addr) {
Dimitry Ivanov5c4a5802017-03-17 16:41:34 -07002095 std::string trace_prefix = std::string("dlopen: ") + (name == nullptr ? "(nullptr)" : name);
2096 ScopedTrace trace(trace_prefix.c_str());
2097 ScopedTrace loading_trace((trace_prefix + " - loading and linking").c_str());
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002098 soinfo* const caller = find_containing_library(caller_addr);
Dimitry Ivanovb996d602016-07-11 18:11:39 -07002099 android_namespace_t* ns = get_caller_namespace(caller);
2100
2101 LD_LOG(kLogDlopen,
Victor Chang6cb719f2019-02-06 17:19:10 +00002102 "dlopen(name=\"%s\", flags=0x%x, extinfo=%s, caller=\"%s\", caller_ns=%s@%p, targetSdkVersion=%i) ...",
Dimitry Ivanovb996d602016-07-11 18:11:39 -07002103 name,
2104 flags,
2105 android_dlextinfo_to_string(extinfo).c_str(),
2106 caller == nullptr ? "(null)" : caller->get_realpath(),
2107 ns == nullptr ? "(null)" : ns->get_name(),
Victor Chang6cb719f2019-02-06 17:19:10 +00002108 ns,
2109 get_application_target_sdk_version());
Dimitry Ivanovb996d602016-07-11 18:11:39 -07002110
Vic Yangbb7e1232019-01-29 20:23:16 -08002111 auto purge_guard = android::base::make_scope_guard([&]() { purge_unused_memory(); });
2112
Tom Cherryb8ab6182017-04-05 16:20:29 -07002113 auto failure_guard = android::base::make_scope_guard(
2114 [&]() { LD_LOG(kLogDlopen, "... dlopen failed: %s", linker_get_error_buffer()); });
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002115
Dmitriy Ivanov1b20daf2014-05-19 15:06:58 -07002116 if ((flags & ~(RTLD_NOW|RTLD_LAZY|RTLD_LOCAL|RTLD_GLOBAL|RTLD_NODELETE|RTLD_NOLOAD)) != 0) {
Martin Stjernholm9fe38262019-08-27 17:08:45 +01002117 DL_OPEN_ERR("invalid flags to dlopen: %x", flags);
Dmitriy Ivanov851135b2014-08-29 12:02:36 -07002118 return nullptr;
Elliott Hughese66190d2012-12-18 15:57:55 -08002119 }
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002120
Dmitriy Ivanov07e5bc12014-10-03 17:52:44 -07002121 if (extinfo != nullptr) {
2122 if ((extinfo->flags & ~(ANDROID_DLEXT_VALID_FLAG_BITS)) != 0) {
Martin Stjernholm9fe38262019-08-27 17:08:45 +01002123 DL_OPEN_ERR("invalid extended flags to android_dlopen_ext: 0x%" PRIx64, extinfo->flags);
Dmitriy Ivanov07e5bc12014-10-03 17:52:44 -07002124 return nullptr;
2125 }
Dmitriy Ivanov126af752015-10-07 16:34:20 -07002126
Dmitriy Ivanov07e5bc12014-10-03 17:52:44 -07002127 if ((extinfo->flags & ANDROID_DLEXT_USE_LIBRARY_FD) == 0 &&
Dmitriy Ivanova6c12792014-10-21 12:09:18 -07002128 (extinfo->flags & ANDROID_DLEXT_USE_LIBRARY_FD_OFFSET) != 0) {
Martin Stjernholm9fe38262019-08-27 17:08:45 +01002129 DL_OPEN_ERR("invalid extended flag combination (ANDROID_DLEXT_USE_LIBRARY_FD_OFFSET without "
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07002130 "ANDROID_DLEXT_USE_LIBRARY_FD): 0x%" PRIx64, extinfo->flags);
Dmitriy Ivanov07e5bc12014-10-03 17:52:44 -07002131 return nullptr;
2132 }
Dmitriy Ivanov126af752015-10-07 16:34:20 -07002133
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002134 if ((extinfo->flags & ANDROID_DLEXT_USE_NAMESPACE) != 0) {
2135 if (extinfo->library_namespace == nullptr) {
Martin Stjernholm9fe38262019-08-27 17:08:45 +01002136 DL_OPEN_ERR("ANDROID_DLEXT_USE_NAMESPACE is set but extinfo->library_namespace is null");
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002137 return nullptr;
2138 }
2139 ns = extinfo->library_namespace;
2140 }
Torne (Richard Coles)012cb452014-02-06 14:34:21 +00002141 }
Dmitriy Ivanov279a22f2015-01-23 12:03:53 -08002142
Victor Chang6cb719f2019-02-06 17:19:10 +00002143 // Workaround for dlopen(/system/lib/<soname>) when .so is in /apex. http://b/121248172
2144 // The workaround works only when targetSdkVersion < Q.
2145 std::string name_to_apex;
2146 if (translateSystemPathToApexPath(name, &name_to_apex)) {
2147 const char* new_name = name_to_apex.c_str();
2148 LD_LOG(kLogDlopen, "dlopen considering translation from %s to APEX path %s",
2149 name,
2150 new_name);
2151 // Some APEXs could be optionally disabled. Only translate the path
2152 // when the old file is absent and the new file exists.
Victor Changaf12c942019-02-11 19:35:24 +00002153 // TODO(b/124218500): Re-enable it once app compat issue is resolved
2154 /*
Victor Chang6cb719f2019-02-06 17:19:10 +00002155 if (file_exists(name)) {
2156 LD_LOG(kLogDlopen, "dlopen %s exists, not translating", name);
Victor Changaf12c942019-02-11 19:35:24 +00002157 } else
2158 */
2159 if (!file_exists(new_name)) {
Victor Chang6cb719f2019-02-06 17:19:10 +00002160 LD_LOG(kLogDlopen, "dlopen %s does not exist, not translating",
2161 new_name);
2162 } else {
2163 LD_LOG(kLogDlopen, "dlopen translation accepted: using %s", new_name);
2164 name = new_name;
2165 }
2166 }
2167 // End Workaround for dlopen(/system/lib/<soname>) when .so is in /apex.
2168
Florian Mayerc10d0642023-03-22 16:12:49 -07002169 std::string translated_name_holder;
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -07002170
Florian Mayerc10d0642023-03-22 16:12:49 -07002171 assert(!g_is_hwasan || !g_is_asan);
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -07002172 const char* translated_name = name;
Dimitry Ivanov6c14f862016-12-05 13:35:47 -08002173 if (g_is_asan && translated_name != nullptr && translated_name[0] == '/') {
Evgenii Stepanov9e77a642017-07-27 14:55:44 -07002174 char original_path[PATH_MAX];
2175 if (realpath(name, original_path) != nullptr) {
Florian Mayerc10d0642023-03-22 16:12:49 -07002176 translated_name_holder = std::string(kAsanLibDirPrefix) + original_path;
2177 if (file_exists(translated_name_holder.c_str())) {
Evgenii Stepanov9e77a642017-07-27 14:55:44 -07002178 soinfo* si = nullptr;
2179 if (find_loaded_library_by_realpath(ns, original_path, true, &si)) {
2180 PRINT("linker_asan dlopen NOT translating \"%s\" -> \"%s\": library already loaded", name,
Florian Mayerc10d0642023-03-22 16:12:49 -07002181 translated_name_holder.c_str());
Evgenii Stepanov9e77a642017-07-27 14:55:44 -07002182 } else {
2183 PRINT("linker_asan dlopen translating \"%s\" -> \"%s\"", name, translated_name);
Florian Mayerc10d0642023-03-22 16:12:49 -07002184 translated_name = translated_name_holder.c_str();
2185 }
2186 }
2187 }
2188 } else if (g_is_hwasan && translated_name != nullptr && translated_name[0] == '/') {
2189 char original_path[PATH_MAX];
2190 if (realpath(name, original_path) != nullptr) {
2191 // Keep this the same as CreateHwasanPath in system/linkerconfig/modules/namespace.cc.
2192 std::string path(original_path);
2193 auto slash = path.rfind('/');
2194 if (slash != std::string::npos || slash != path.size() - 1) {
2195 translated_name_holder = path.substr(0, slash) + "/hwasan" + path.substr(slash);
2196 }
2197 if (!translated_name_holder.empty() && file_exists(translated_name_holder.c_str())) {
2198 soinfo* si = nullptr;
2199 if (find_loaded_library_by_realpath(ns, original_path, true, &si)) {
2200 PRINT("linker_hwasan dlopen NOT translating \"%s\" -> \"%s\": library already loaded", name,
2201 translated_name_holder.c_str());
2202 } else {
2203 PRINT("linker_hwasan dlopen translating \"%s\" -> \"%s\"", name, translated_name);
2204 translated_name = translated_name_holder.c_str();
Evgenii Stepanov9e77a642017-07-27 14:55:44 -07002205 }
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -07002206 }
2207 }
2208 }
Dmitriy Ivanov279a22f2015-01-23 12:03:53 -08002209 ProtectedDataGuard guard;
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -07002210 soinfo* si = find_library(ns, translated_name, flags, extinfo, caller);
Dimitry Ivanov5c4a5802017-03-17 16:41:34 -07002211 loading_trace.End();
2212
Dmitriy Ivanov851135b2014-08-29 12:02:36 -07002213 if (si != nullptr) {
Dimitry Ivanovb996d602016-07-11 18:11:39 -07002214 void* handle = si->to_handle();
2215 LD_LOG(kLogDlopen,
Dimitry Ivanovae4a0c12016-11-21 10:44:35 -08002216 "... dlopen calling constructors: realpath=\"%s\", soname=\"%s\", handle=%p",
2217 si->get_realpath(), si->get_soname(), handle);
2218 si->call_constructors();
Tom Cherryb8ab6182017-04-05 16:20:29 -07002219 failure_guard.Disable();
Dimitry Ivanovae4a0c12016-11-21 10:44:35 -08002220 LD_LOG(kLogDlopen,
Dimitry Ivanovb996d602016-07-11 18:11:39 -07002221 "... dlopen successful: realpath=\"%s\", soname=\"%s\", handle=%p",
2222 si->get_realpath(), si->get_soname(), handle);
2223 return handle;
Elliott Hughesd23736e2012-11-01 15:16:56 -07002224 }
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002225
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -07002226 return nullptr;
Elliott Hughesd23736e2012-11-01 15:16:56 -07002227}
2228
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002229int do_dladdr(const void* addr, Dl_info* info) {
2230 // Determine if this address can be found in any library currently mapped.
2231 soinfo* si = find_containing_library(addr);
2232 if (si == nullptr) {
2233 return 0;
2234 }
2235
2236 memset(info, 0, sizeof(Dl_info));
2237
2238 info->dli_fname = si->get_realpath();
2239 // Address at which the shared object is loaded.
2240 info->dli_fbase = reinterpret_cast<void*>(si->base);
2241
2242 // Determine if any symbol in the library contains the specified address.
2243 ElfW(Sym)* sym = si->find_symbol_by_address(addr);
2244 if (sym != nullptr) {
2245 info->dli_sname = si->get_string(sym->st_name);
2246 info->dli_saddr = reinterpret_cast<void*>(si->resolve_symbol_address(sym));
2247 }
2248
2249 return 1;
2250}
2251
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -07002252static soinfo* soinfo_from_handle(void* handle) {
2253 if ((reinterpret_cast<uintptr_t>(handle) & 1) != 0) {
2254 auto it = g_soinfo_handles_map.find(reinterpret_cast<uintptr_t>(handle));
2255 if (it == g_soinfo_handles_map.end()) {
2256 return nullptr;
2257 } else {
2258 return it->second;
2259 }
2260 }
2261
2262 return static_cast<soinfo*>(handle);
2263}
2264
Dimitry Ivanovd9e427c2016-11-22 16:55:25 -08002265bool do_dlsym(void* handle,
2266 const char* sym_name,
2267 const char* sym_ver,
2268 const void* caller_addr,
2269 void** symbol) {
Dimitry Ivanov6705e8c2017-03-21 10:29:06 -07002270 ScopedTrace trace("dlsym");
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002271#if !defined(__LP64__)
2272 if (handle == nullptr) {
Martin Stjernholm9fe38262019-08-27 17:08:45 +01002273 DL_SYM_ERR("dlsym failed: library handle is null");
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002274 return false;
2275 }
2276#endif
2277
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002278 soinfo* found = nullptr;
2279 const ElfW(Sym)* sym = nullptr;
2280 soinfo* caller = find_containing_library(caller_addr);
Dimitry Ivanovaca299a2016-04-11 12:42:58 -07002281 android_namespace_t* ns = get_caller_namespace(caller);
Dimitry Ivanov4742abd2016-12-12 16:30:15 -08002282 soinfo* si = nullptr;
2283 if (handle != RTLD_DEFAULT && handle != RTLD_NEXT) {
2284 si = soinfo_from_handle(handle);
2285 }
2286
2287 LD_LOG(kLogDlsym,
2288 "dlsym(handle=%p(\"%s\"), sym_name=\"%s\", sym_ver=\"%s\", caller=\"%s\", caller_ns=%s@%p) ...",
2289 handle,
2290 si != nullptr ? si->get_realpath() : "n/a",
2291 sym_name,
2292 sym_ver,
2293 caller == nullptr ? "(null)" : caller->get_realpath(),
2294 ns == nullptr ? "(null)" : ns->get_name(),
2295 ns);
2296
Tom Cherryb8ab6182017-04-05 16:20:29 -07002297 auto failure_guard = android::base::make_scope_guard(
2298 [&]() { LD_LOG(kLogDlsym, "... dlsym failed: %s", linker_get_error_buffer()); });
Dimitry Ivanov4742abd2016-12-12 16:30:15 -08002299
2300 if (sym_name == nullptr) {
Martin Stjernholm9fe38262019-08-27 17:08:45 +01002301 DL_SYM_ERR("dlsym failed: symbol name is null");
Dimitry Ivanov4742abd2016-12-12 16:30:15 -08002302 return false;
2303 }
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002304
2305 version_info vi_instance;
2306 version_info* vi = nullptr;
2307
2308 if (sym_ver != nullptr) {
Dimitry Ivanov9cf99cb2015-12-11 14:22:24 -08002309 vi_instance.name = sym_ver;
2310 vi_instance.elf_hash = calculate_elf_hash(sym_ver);
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002311 vi = &vi_instance;
2312 }
2313
2314 if (handle == RTLD_DEFAULT || handle == RTLD_NEXT) {
2315 sym = dlsym_linear_lookup(ns, sym_name, vi, &found, caller, handle);
2316 } else {
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -07002317 if (si == nullptr) {
Martin Stjernholm9fe38262019-08-27 17:08:45 +01002318 DL_SYM_ERR("dlsym failed: invalid handle: %p", handle);
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -07002319 return false;
2320 }
2321 sym = dlsym_handle_lookup(si, &found, sym_name, vi);
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002322 }
2323
2324 if (sym != nullptr) {
2325 uint32_t bind = ELF_ST_BIND(sym->st_info);
Ryan Pricharde4d620b2019-04-01 17:42:14 -07002326 uint32_t type = ELF_ST_TYPE(sym->st_info);
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002327
2328 if ((bind == STB_GLOBAL || bind == STB_WEAK) && sym->st_shndx != 0) {
Ryan Pricharde4d620b2019-04-01 17:42:14 -07002329 if (type == STT_TLS) {
2330 // For a TLS symbol, dlsym returns the address of the current thread's
Ryan Pricharda2e83ab2019-08-16 17:25:43 -07002331 // copy of the symbol.
2332 const soinfo_tls* tls_module = found->get_tls();
Ryan Pricharde4d620b2019-04-01 17:42:14 -07002333 if (tls_module == nullptr) {
Martin Stjernholm9fe38262019-08-27 17:08:45 +01002334 DL_SYM_ERR("TLS symbol \"%s\" in solib \"%s\" with no TLS segment",
2335 sym_name, found->get_realpath());
Ryan Pricharde4d620b2019-04-01 17:42:14 -07002336 return false;
2337 }
Ryan Pricharda2e83ab2019-08-16 17:25:43 -07002338 void* tls_block = get_tls_block_for_this_thread(tls_module, /*should_alloc=*/true);
2339 *symbol = static_cast<char*>(tls_block) + sym->st_value;
Ryan Pricharde4d620b2019-04-01 17:42:14 -07002340 } else {
2341 *symbol = reinterpret_cast<void*>(found->resolve_symbol_address(sym));
2342 }
Tom Cherryb8ab6182017-04-05 16:20:29 -07002343 failure_guard.Disable();
Dimitry Ivanov4742abd2016-12-12 16:30:15 -08002344 LD_LOG(kLogDlsym,
2345 "... dlsym successful: sym_name=\"%s\", sym_ver=\"%s\", found in=\"%s\", address=%p",
2346 sym_name, sym_ver, found->get_soname(), *symbol);
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002347 return true;
2348 }
2349
Martin Stjernholm9fe38262019-08-27 17:08:45 +01002350 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 -08002351 return false;
2352 }
2353
Martin Stjernholm9fe38262019-08-27 17:08:45 +01002354 DL_SYM_ERR("undefined symbol: %s", symbol_display_name(sym_name, sym_ver).c_str());
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002355 return false;
2356}
2357
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -07002358int do_dlclose(void* handle) {
Dimitry Ivanov6705e8c2017-03-21 10:29:06 -07002359 ScopedTrace trace("dlclose");
Dmitriy Ivanov279a22f2015-01-23 12:03:53 -08002360 ProtectedDataGuard guard;
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -07002361 soinfo* si = soinfo_from_handle(handle);
2362 if (si == nullptr) {
Martin Stjernholm9fe38262019-08-27 17:08:45 +01002363 DL_OPEN_ERR("invalid handle: %p", handle);
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -07002364 return -1;
2365 }
2366
dimitryc92ce712017-10-27 14:12:53 +02002367 LD_LOG(kLogDlopen,
2368 "dlclose(handle=%p, realpath=\"%s\"@%p) ...",
2369 handle,
2370 si->get_realpath(),
2371 si);
Dmitriy Ivanovb648a8a2014-05-19 15:06:58 -07002372 soinfo_unload(si);
dimitryc92ce712017-10-27 14:12:53 +02002373 LD_LOG(kLogDlopen,
2374 "dlclose(handle=%p) ... done",
2375 handle);
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -07002376 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002377}
2378
Jiyong Park25bedfd2019-05-16 21:00:39 +09002379// Make ns as the anonymous namespace that is a namespace used when
2380// we fail to determine the caller address (e.g., call from mono-jited code)
2381// Since there can be multiple anonymous namespace in a process, subsequent
2382// call to this function causes an error.
2383static bool set_anonymous_namespace(android_namespace_t* ns) {
2384 if (!g_anonymous_namespace_set && ns != nullptr) {
2385 CHECK(ns->is_also_used_as_anonymous());
2386 g_anonymous_namespace = ns;
2387 g_anonymous_namespace_set = true;
2388 return true;
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002389 }
Jiyong Park25bedfd2019-05-16 21:00:39 +09002390 return false;
2391}
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002392
Jiyong Park25bedfd2019-05-16 21:00:39 +09002393// TODO(b/130388701) remove this. Currently, this is used only for testing
2394// where we don't have classloader namespace.
2395bool init_anonymous_namespace(const char* shared_lib_sonames, const char* library_search_path) {
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002396 ProtectedDataGuard guard;
2397
Jiyong Park25bedfd2019-05-16 21:00:39 +09002398 // Test-only feature: we need to change the anonymous namespace multiple times
2399 // while the test is running.
2400 g_anonymous_namespace_set = false;
2401
Dmitriy Ivanov1ffec1c2015-11-23 11:26:35 -08002402 // create anonymous namespace
Dimitry Ivanov7331fe12015-12-14 14:11:17 -08002403 // When the caller is nullptr - create_namespace will take global group
2404 // from the anonymous namespace, which is fine because anonymous namespace
2405 // is still pointing to the default one.
Dmitriy Ivanov1ffec1c2015-11-23 11:26:35 -08002406 android_namespace_t* anon_ns =
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -08002407 create_namespace(nullptr,
2408 "(anonymous)",
2409 nullptr,
2410 library_search_path,
Jiyong Park25bedfd2019-05-16 21:00:39 +09002411 ANDROID_NAMESPACE_TYPE_ISOLATED |
2412 ANDROID_NAMESPACE_TYPE_ALSO_USED_AS_ANONYMOUS,
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -08002413 nullptr,
2414 &g_default_namespace);
Dmitriy Ivanov1ffec1c2015-11-23 11:26:35 -08002415
Jiyong Park25bedfd2019-05-16 21:00:39 +09002416 CHECK(anon_ns != nullptr);
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -08002417
2418 if (!link_namespaces(anon_ns, &g_default_namespace, shared_lib_sonames)) {
Jiyong Park25bedfd2019-05-16 21:00:39 +09002419 // TODO: delete anon_ns
Dmitriy Ivanov1ffec1c2015-11-23 11:26:35 -08002420 return false;
2421 }
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08002422
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002423 return true;
2424}
2425
Dimitry Ivanovb943f302016-08-03 16:00:10 -07002426static void add_soinfos_to_namespace(const soinfo_list_t& soinfos, android_namespace_t* ns) {
2427 ns->add_soinfos(soinfos);
2428 for (auto si : soinfos) {
2429 si->add_secondary_namespace(ns);
2430 }
2431}
2432
Ryan Prichard40494402020-03-24 22:37:50 -07002433std::vector<std::string> fix_lib_paths(std::vector<std::string> paths) {
2434 // For the bootstrap linker, insert /system/${LIB}/bootstrap in front of /system/${LIB} in any
2435 // namespace search path. The bootstrap linker should prefer to use the bootstrap bionic libraries
2436 // (e.g. libc.so).
2437#if !defined(__ANDROID_APEX__)
2438 for (size_t i = 0; i < paths.size(); ++i) {
2439 if (paths[i] == kSystemLibDir) {
2440 paths.insert(paths.begin() + i, std::string(kSystemLibDir) + "/bootstrap");
2441 ++i;
2442 }
2443 }
2444#endif
2445 return paths;
2446}
2447
Dimitry Ivanov7331fe12015-12-14 14:11:17 -08002448android_namespace_t* create_namespace(const void* caller_addr,
2449 const char* name,
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002450 const char* ld_library_path,
2451 const char* default_library_path,
Dimitry Ivanov7331fe12015-12-14 14:11:17 -08002452 uint64_t type,
Dimitry Ivanovfc2da532016-05-12 15:20:21 -07002453 const char* permitted_when_isolated_path,
2454 android_namespace_t* parent_namespace) {
Dimitry Ivanovfc2da532016-05-12 15:20:21 -07002455 if (parent_namespace == nullptr) {
Dimitry Ivanov52408632016-05-23 10:31:11 -07002456 // if parent_namespace is nullptr -> set it to the caller namespace
2457 soinfo* caller_soinfo = find_containing_library(caller_addr);
2458
2459 parent_namespace = caller_soinfo != nullptr ?
2460 caller_soinfo->get_primary_namespace() :
2461 g_anonymous_namespace;
Dimitry Ivanovfc2da532016-05-12 15:20:21 -07002462 }
2463
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002464 ProtectedDataGuard guard;
2465 std::vector<std::string> ld_library_paths;
2466 std::vector<std::string> default_library_paths;
Dimitry Ivanov284ae352015-12-08 10:47:13 -08002467 std::vector<std::string> permitted_paths;
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002468
2469 parse_path(ld_library_path, ":", &ld_library_paths);
2470 parse_path(default_library_path, ":", &default_library_paths);
Dimitry Ivanov284ae352015-12-08 10:47:13 -08002471 parse_path(permitted_when_isolated_path, ":", &permitted_paths);
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002472
2473 android_namespace_t* ns = new (g_namespace_allocator.alloc()) android_namespace_t();
2474 ns->set_name(name);
Dimitry Ivanov7331fe12015-12-14 14:11:17 -08002475 ns->set_isolated((type & ANDROID_NAMESPACE_TYPE_ISOLATED) != 0);
Ryan Prichardaff9a342020-08-03 15:29:12 -07002476 ns->set_exempt_list_enabled((type & ANDROID_NAMESPACE_TYPE_EXEMPT_LIST_ENABLED) != 0);
Jiyong Park25bedfd2019-05-16 21:00:39 +09002477 ns->set_also_used_as_anonymous((type & ANDROID_NAMESPACE_TYPE_ALSO_USED_AS_ANONYMOUS) != 0);
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002478
Dimitry Ivanov7331fe12015-12-14 14:11:17 -08002479 if ((type & ANDROID_NAMESPACE_TYPE_SHARED) != 0) {
Dimitry Ivanovf1cb6692017-05-01 17:45:38 -07002480 // append parent namespace paths.
2481 std::copy(parent_namespace->get_ld_library_paths().begin(),
2482 parent_namespace->get_ld_library_paths().end(),
2483 back_inserter(ld_library_paths));
2484
2485 std::copy(parent_namespace->get_default_library_paths().begin(),
2486 parent_namespace->get_default_library_paths().end(),
2487 back_inserter(default_library_paths));
2488
2489 std::copy(parent_namespace->get_permitted_paths().begin(),
2490 parent_namespace->get_permitted_paths().end(),
2491 back_inserter(permitted_paths));
2492
Dimitry Ivanovfc2da532016-05-12 15:20:21 -07002493 // If shared - clone the parent namespace
Dimitry Ivanovb943f302016-08-03 16:00:10 -07002494 add_soinfos_to_namespace(parent_namespace->soinfo_list(), ns);
Dimitry Ivanovf1cb6692017-05-01 17:45:38 -07002495 // and copy parent namespace links
2496 for (auto& link : parent_namespace->linked_namespaces()) {
Logan Chien9ee45912018-01-18 12:05:09 +08002497 ns->add_linked_namespace(link.linked_namespace(), link.shared_lib_sonames(),
2498 link.allow_all_shared_libs());
Dimitry Ivanovf1cb6692017-05-01 17:45:38 -07002499 }
Dimitry Ivanov7331fe12015-12-14 14:11:17 -08002500 } else {
Dimitry Ivanovfc2da532016-05-12 15:20:21 -07002501 // If not shared - copy only the shared group
Jiyong Park02586a22017-05-20 01:01:24 +09002502 add_soinfos_to_namespace(parent_namespace->get_shared_group(), ns);
Dimitry Ivanov7331fe12015-12-14 14:11:17 -08002503 }
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002504
Dimitry Ivanovf1cb6692017-05-01 17:45:38 -07002505 ns->set_ld_library_paths(std::move(ld_library_paths));
2506 ns->set_default_library_paths(std::move(default_library_paths));
2507 ns->set_permitted_paths(std::move(permitted_paths));
2508
Jiyong Park25bedfd2019-05-16 21:00:39 +09002509 if (ns->is_also_used_as_anonymous() && !set_anonymous_namespace(ns)) {
2510 DL_ERR("failed to set namespace: [name=\"%s\", ld_library_path=\"%s\", default_library_paths=\"%s\""
2511 " permitted_paths=\"%s\"] as the anonymous namespace",
2512 ns->get_name(),
2513 android::base::Join(ns->get_ld_library_paths(), ':').c_str(),
2514 android::base::Join(ns->get_default_library_paths(), ':').c_str(),
2515 android::base::Join(ns->get_permitted_paths(), ':').c_str());
2516 return nullptr;
2517 }
2518
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002519 return ns;
2520}
2521
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -08002522bool link_namespaces(android_namespace_t* namespace_from,
2523 android_namespace_t* namespace_to,
2524 const char* shared_lib_sonames) {
2525 if (namespace_to == nullptr) {
2526 namespace_to = &g_default_namespace;
2527 }
2528
2529 if (namespace_from == nullptr) {
2530 DL_ERR("error linking namespaces: namespace_from is null.");
2531 return false;
2532 }
2533
2534 if (shared_lib_sonames == nullptr || shared_lib_sonames[0] == '\0') {
2535 DL_ERR("error linking namespaces \"%s\"->\"%s\": the list of shared libraries is empty.",
2536 namespace_from->get_name(), namespace_to->get_name());
2537 return false;
2538 }
2539
Jooyung Han57b03de2022-12-01 16:23:03 +09002540 std::vector<std::string> sonames = android::base::Split(shared_lib_sonames, ":");
2541 std::unordered_set<std::string> sonames_set(std::make_move_iterator(sonames.begin()),
2542 std::make_move_iterator(sonames.end()));
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -08002543
2544 ProtectedDataGuard guard;
Jooyung Han57b03de2022-12-01 16:23:03 +09002545 namespace_from->add_linked_namespace(namespace_to, std::move(sonames_set), false);
Logan Chien9ee45912018-01-18 12:05:09 +08002546
2547 return true;
2548}
2549
2550bool link_namespaces_all_libs(android_namespace_t* namespace_from,
2551 android_namespace_t* namespace_to) {
2552 if (namespace_from == nullptr) {
2553 DL_ERR("error linking namespaces: namespace_from is null.");
2554 return false;
2555 }
2556
2557 if (namespace_to == nullptr) {
2558 DL_ERR("error linking namespaces: namespace_to is null.");
2559 return false;
2560 }
2561
2562 ProtectedDataGuard guard;
2563 namespace_from->add_linked_namespace(namespace_to, std::unordered_set<std::string>(), true);
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -08002564
2565 return true;
2566}
2567
Dimitry Ivanov48ec2882016-08-04 11:50:36 -07002568ElfW(Addr) call_ifunc_resolver(ElfW(Addr) resolver_addr) {
Elliott Hughes90f96b92019-05-09 15:56:39 -07002569 if (g_is_ldd) return 0;
2570
Peter Collingbournee9491952019-10-28 10:57:26 -07002571 ElfW(Addr) ifunc_addr = __bionic_call_ifunc_resolver(resolver_addr);
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07002572 TRACE_TYPE(RELO, "Called ifunc_resolver@%p. The result is %p",
Peter Collingbournee9491952019-10-28 10:57:26 -07002573 reinterpret_cast<void *>(resolver_addr), reinterpret_cast<void*>(ifunc_addr));
Brigid Smithc5a13ef2014-07-23 11:22:25 -07002574
Dmitriy Ivanov9aea1642014-09-11 15:16:03 -07002575 return ifunc_addr;
Brigid Smithc5a13ef2014-07-23 11:22:25 -07002576}
Brigid Smithc5a13ef2014-07-23 11:22:25 -07002577
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07002578const version_info* VersionTracker::get_version_info(ElfW(Versym) source_symver) const {
2579 if (source_symver < 2 ||
2580 source_symver >= version_infos.size() ||
2581 version_infos[source_symver].name == nullptr) {
2582 return nullptr;
2583 }
2584
2585 return &version_infos[source_symver];
2586}
2587
2588void VersionTracker::add_version_info(size_t source_index,
2589 ElfW(Word) elf_hash,
2590 const char* ver_name,
2591 const soinfo* target_si) {
2592 if (source_index >= version_infos.size()) {
2593 version_infos.resize(source_index+1);
2594 }
2595
2596 version_infos[source_index].elf_hash = elf_hash;
2597 version_infos[source_index].name = ver_name;
2598 version_infos[source_index].target_si = target_si;
2599}
2600
2601bool VersionTracker::init_verneed(const soinfo* si_from) {
2602 uintptr_t verneed_ptr = si_from->get_verneed_ptr();
2603
2604 if (verneed_ptr == 0) {
2605 return true;
2606 }
2607
2608 size_t verneed_cnt = si_from->get_verneed_cnt();
2609
2610 for (size_t i = 0, offset = 0; i<verneed_cnt; ++i) {
2611 const ElfW(Verneed)* verneed = reinterpret_cast<ElfW(Verneed)*>(verneed_ptr + offset);
2612 size_t vernaux_offset = offset + verneed->vn_aux;
2613 offset += verneed->vn_next;
2614
2615 if (verneed->vn_version != 1) {
2616 DL_ERR("unsupported verneed[%zd] vn_version: %d (expected 1)", i, verneed->vn_version);
2617 return false;
2618 }
2619
2620 const char* target_soname = si_from->get_string(verneed->vn_file);
2621 // find it in dependencies
Elliott Hughesf9dd1a72021-01-11 09:04:58 -08002622 soinfo* target_si = si_from->get_children().find_if(
2623 [&](const soinfo* si) { return strcmp(si->get_soname(), target_soname) == 0; });
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07002624
2625 if (target_si == nullptr) {
2626 DL_ERR("cannot find \"%s\" from verneed[%zd] in DT_NEEDED list for \"%s\"",
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07002627 target_soname, i, si_from->get_realpath());
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07002628 return false;
2629 }
2630
2631 for (size_t j = 0; j<verneed->vn_cnt; ++j) {
2632 const ElfW(Vernaux)* vernaux = reinterpret_cast<ElfW(Vernaux)*>(verneed_ptr + vernaux_offset);
2633 vernaux_offset += vernaux->vna_next;
2634
2635 const ElfW(Word) elf_hash = vernaux->vna_hash;
2636 const char* ver_name = si_from->get_string(vernaux->vna_name);
2637 ElfW(Half) source_index = vernaux->vna_other;
2638
2639 add_version_info(source_index, elf_hash, ver_name, target_si);
2640 }
2641 }
2642
2643 return true;
2644}
2645
Dimitry Ivanov48ec2882016-08-04 11:50:36 -07002646template <typename F>
2647static bool for_each_verdef(const soinfo* si, F functor) {
2648 if (!si->has_min_version(2)) {
2649 return true;
2650 }
2651
2652 uintptr_t verdef_ptr = si->get_verdef_ptr();
2653 if (verdef_ptr == 0) {
2654 return true;
2655 }
2656
2657 size_t offset = 0;
2658
2659 size_t verdef_cnt = si->get_verdef_cnt();
2660 for (size_t i = 0; i<verdef_cnt; ++i) {
2661 const ElfW(Verdef)* verdef = reinterpret_cast<ElfW(Verdef)*>(verdef_ptr + offset);
2662 size_t verdaux_offset = offset + verdef->vd_aux;
2663 offset += verdef->vd_next;
2664
2665 if (verdef->vd_version != 1) {
2666 DL_ERR("unsupported verdef[%zd] vd_version: %d (expected 1) library: %s",
2667 i, verdef->vd_version, si->get_realpath());
2668 return false;
2669 }
2670
2671 if ((verdef->vd_flags & VER_FLG_BASE) != 0) {
2672 // "this is the version of the file itself. It must not be used for
2673 // matching a symbol. It can be used to match references."
2674 //
2675 // http://www.akkadia.org/drepper/symbol-versioning
2676 continue;
2677 }
2678
2679 if (verdef->vd_cnt == 0) {
2680 DL_ERR("invalid verdef[%zd] vd_cnt == 0 (version without a name)", i);
2681 return false;
2682 }
2683
2684 const ElfW(Verdaux)* verdaux = reinterpret_cast<ElfW(Verdaux)*>(verdef_ptr + verdaux_offset);
2685
2686 if (functor(i, verdef, verdaux) == true) {
2687 break;
2688 }
2689 }
2690
2691 return true;
2692}
2693
Ryan Prichard0e12cce2020-01-02 14:59:11 -08002694ElfW(Versym) find_verdef_version_index(const soinfo* si, const version_info* vi) {
Dimitry Ivanov48ec2882016-08-04 11:50:36 -07002695 if (vi == nullptr) {
Ryan Prichard0e12cce2020-01-02 14:59:11 -08002696 return kVersymNotNeeded;
Dimitry Ivanov48ec2882016-08-04 11:50:36 -07002697 }
2698
Ryan Prichard0e12cce2020-01-02 14:59:11 -08002699 ElfW(Versym) result = kVersymGlobal;
Dimitry Ivanov48ec2882016-08-04 11:50:36 -07002700
Ryan Prichard0e12cce2020-01-02 14:59:11 -08002701 if (!for_each_verdef(si,
Dimitry Ivanov48ec2882016-08-04 11:50:36 -07002702 [&](size_t, const ElfW(Verdef)* verdef, const ElfW(Verdaux)* verdaux) {
2703 if (verdef->vd_hash == vi->elf_hash &&
2704 strcmp(vi->name, si->get_string(verdaux->vda_name)) == 0) {
Ryan Prichard0e12cce2020-01-02 14:59:11 -08002705 result = verdef->vd_ndx;
Dimitry Ivanov48ec2882016-08-04 11:50:36 -07002706 return true;
2707 }
2708
2709 return false;
2710 }
Ryan Prichard0e12cce2020-01-02 14:59:11 -08002711 )) {
2712 // verdef should have already been validated in prelink_image.
2713 async_safe_fatal("invalid verdef after prelinking: %s, %s",
2714 si->get_realpath(), linker_get_error_buffer());
2715 }
2716
2717 return result;
2718}
2719
2720// Validate the library's verdef section. On error, returns false and invokes DL_ERR.
2721bool validate_verdef_section(const soinfo* si) {
2722 return for_each_verdef(si,
2723 [&](size_t, const ElfW(Verdef)*, const ElfW(Verdaux)*) {
2724 return false;
2725 });
Dimitry Ivanov48ec2882016-08-04 11:50:36 -07002726}
2727
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07002728bool VersionTracker::init_verdef(const soinfo* si_from) {
2729 return for_each_verdef(si_from,
2730 [&](size_t, const ElfW(Verdef)* verdef, const ElfW(Verdaux)* verdaux) {
2731 add_version_info(verdef->vd_ndx, verdef->vd_hash,
2732 si_from->get_string(verdaux->vda_name), si_from);
2733 return false;
2734 }
2735 );
2736}
2737
2738bool VersionTracker::init(const soinfo* si_from) {
2739 if (!si_from->has_min_version(2)) {
2740 return true;
2741 }
2742
2743 return init_verneed(si_from) && init_verdef(si_from);
2744}
2745
Dimitry Ivanov48ec2882016-08-04 11:50:36 -07002746// TODO (dimitry): Methods below need to be moved out of soinfo
2747// and in more isolated file in order minimize dependencies on
2748// unnecessary object in the linker binary. Consider making them
2749// independent from soinfo (?).
Dmitriy Ivanov31b408d2015-04-30 16:11:48 -07002750bool soinfo::lookup_version_info(const VersionTracker& version_tracker, ElfW(Word) sym,
2751 const char* sym_name, const version_info** vi) {
2752 const ElfW(Versym)* sym_ver_ptr = get_versym(sym);
2753 ElfW(Versym) sym_ver = sym_ver_ptr == nullptr ? 0 : *sym_ver_ptr;
2754
2755 if (sym_ver != VER_NDX_LOCAL && sym_ver != VER_NDX_GLOBAL) {
2756 *vi = version_tracker.get_version_info(sym_ver);
2757
2758 if (*vi == nullptr) {
2759 DL_ERR("cannot find verneed/verdef for version index=%d "
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07002760 "referenced by symbol \"%s\" at \"%s\"", sym_ver, sym_name, get_realpath());
Dmitriy Ivanov31b408d2015-04-30 16:11:48 -07002761 return false;
2762 }
2763 } else {
2764 // there is no version info
2765 *vi = nullptr;
2766 }
2767
2768 return true;
2769}
2770
Rahul Chaudhryf16b6592018-01-25 15:34:15 -08002771void soinfo::apply_relr_reloc(ElfW(Addr) offset) {
2772 ElfW(Addr) address = offset + load_bias;
2773 *reinterpret_cast<ElfW(Addr)*>(address) += load_bias;
2774}
2775
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08002776// Process relocations in SHT_RELR section (experimental).
Rahul Chaudhryf16b6592018-01-25 15:34:15 -08002777// Details of the encoding are described in this post:
2778// https://groups.google.com/d/msg/generic-abi/bX460iggiKg/Pi9aSwwABgAJ
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08002779bool soinfo::relocate_relr() {
2780 ElfW(Relr)* begin = relr_;
2781 ElfW(Relr)* end = relr_ + relr_count_;
Rahul Chaudhryf16b6592018-01-25 15:34:15 -08002782 constexpr size_t wordsize = sizeof(ElfW(Addr));
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08002783
Rahul Chaudhryf16b6592018-01-25 15:34:15 -08002784 ElfW(Addr) base = 0;
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08002785 for (ElfW(Relr)* current = begin; current < end; ++current) {
Rahul Chaudhryf16b6592018-01-25 15:34:15 -08002786 ElfW(Relr) entry = *current;
2787 ElfW(Addr) offset;
2788
2789 if ((entry&1) == 0) {
2790 // Even entry: encodes the offset for next relocation.
2791 offset = static_cast<ElfW(Addr)>(entry);
2792 apply_relr_reloc(offset);
2793 // Set base offset for subsequent bitmap entries.
2794 base = offset + wordsize;
2795 continue;
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08002796 }
Rahul Chaudhryf16b6592018-01-25 15:34:15 -08002797
2798 // Odd entry: encodes bitmap for relocations starting at base.
2799 offset = base;
2800 while (entry != 0) {
2801 entry >>= 1;
2802 if ((entry&1) != 0) {
2803 apply_relr_reloc(offset);
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08002804 }
Rahul Chaudhryf16b6592018-01-25 15:34:15 -08002805 offset += wordsize;
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08002806 }
Rahul Chaudhryf16b6592018-01-25 15:34:15 -08002807
2808 // Advance base offset by 63 words for 64-bit platforms,
2809 // or 31 words for 32-bit platforms.
2810 base += (8*wordsize - 1) * wordsize;
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08002811 }
2812 return true;
2813}
2814
Dimitry Ivanov48ec2882016-08-04 11:50:36 -07002815// An empty list of soinfos
Dimitry Ivanovb943f302016-08-03 16:00:10 -07002816static soinfo_list_t g_empty_list;
Dmitriy Ivanovd59e5002014-05-09 09:10:14 -07002817
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002818bool soinfo::prelink_image() {
Ryan Prichardae320cd2019-12-10 12:39:05 -08002819 if (flags_ & FLAG_PRELINKED) return true;
Ningsheng Jiane93be992014-09-16 15:22:10 +08002820 /* Extract dynamic section */
2821 ElfW(Word) dynamic_flags = 0;
2822 phdr_table_get_dynamic_section(phdr, phnum, load_bias, &dynamic, &dynamic_flags);
Dmitriy Ivanov498eb182014-09-05 14:57:59 -07002823
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002824 /* We can't log anything until the linker is relocated */
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08002825 bool relocating_linker = (flags_ & FLAG_LINKER) != 0;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002826 if (!relocating_linker) {
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07002827 INFO("[ Linking \"%s\" ]", get_realpath());
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08002828 DEBUG("si->base = %p si->flags = 0x%08x", reinterpret_cast<void*>(base), flags_);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002829 }
2830
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002831 if (dynamic == nullptr) {
David 'Digit' Turnerb52e4382012-06-19 01:24:17 +02002832 if (!relocating_linker) {
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07002833 DL_ERR("missing PT_DYNAMIC in \"%s\"", get_realpath());
David 'Digit' Turnerb52e4382012-06-19 01:24:17 +02002834 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002835 return false;
2836 } else {
2837 if (!relocating_linker) {
2838 DEBUG("dynamic = %p", dynamic);
David 'Digit' Turner63f99f42012-06-19 00:08:39 +02002839 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002840 }
David 'Digit' Turner63f99f42012-06-19 00:08:39 +02002841
Elliott Hughes4eeb1f12013-10-25 17:38:02 -07002842#if defined(__arm__)
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002843 (void) phdr_table_get_arm_exidx(phdr, phnum, load_bias,
2844 &ARM_exidx, &ARM_exidx_count);
David 'Digit' Turner63f99f42012-06-19 00:08:39 +02002845#endif
2846
Ryan Pricharde5e69e02019-01-01 18:53:48 -08002847 TlsSegment tls_segment;
Ryan Prichard19883502019-01-16 23:13:38 -08002848 if (__bionic_get_tls_segment(phdr, phnum, load_bias, &tls_segment)) {
2849 if (!__bionic_check_tls_alignment(&tls_segment.alignment)) {
2850 if (!relocating_linker) {
2851 DL_ERR("TLS segment alignment in \"%s\" is not a power of 2: %zu",
2852 get_realpath(), tls_segment.alignment);
2853 }
2854 return false;
2855 }
Ryan Pricharde5e69e02019-01-01 18:53:48 -08002856 tls_ = std::make_unique<soinfo_tls>();
2857 tls_->segment = tls_segment;
2858 }
2859
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002860 // Extract useful information from dynamic section.
Dmitriy Ivanov618f1a32015-03-17 20:06:36 -07002861 // Note that: "Except for the DT_NULL element at the end of the array,
2862 // and the relative order of DT_NEEDED elements, entries may appear in any order."
2863 //
2864 // source: http://www.sco.com/developers/gabi/1998-04-29/ch5.dynamic.html
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002865 uint32_t needed_count = 0;
2866 for (ElfW(Dyn)* d = dynamic; d->d_tag != DT_NULL; ++d) {
2867 DEBUG("d = %p, d[0](tag) = %p d[1](val) = %p",
2868 d, reinterpret_cast<void*>(d->d_tag), reinterpret_cast<void*>(d->d_un.d_val));
2869 switch (d->d_tag) {
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07002870 case DT_SONAME:
Dmitriy Ivanov618f1a32015-03-17 20:06:36 -07002871 // this is parsed after we have strtab initialized (see below).
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07002872 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002873
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002874 case DT_HASH:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002875 nbucket_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[0];
2876 nchain_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[1];
2877 bucket_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr + 8);
2878 chain_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr + 8 + nbucket_ * 4);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002879 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002880
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -08002881 case DT_GNU_HASH:
Dmitriy Ivanov3597b802015-03-09 12:02:02 -07002882 gnu_nbucket_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[0];
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -08002883 // skip symndx
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002884 gnu_maskwords_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[2];
2885 gnu_shift2_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[3];
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -08002886
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002887 gnu_bloom_filter_ = reinterpret_cast<ElfW(Addr)*>(load_bias + d->d_un.d_ptr + 16);
Dmitriy Ivanov3597b802015-03-09 12:02:02 -07002888 gnu_bucket_ = reinterpret_cast<uint32_t*>(gnu_bloom_filter_ + gnu_maskwords_);
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -08002889 // amend chain for symndx = header[1]
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07002890 gnu_chain_ = gnu_bucket_ + gnu_nbucket_ -
2891 reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[1];
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -08002892
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002893 if (!powerof2(gnu_maskwords_)) {
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07002894 DL_ERR("invalid maskwords for gnu_hash = 0x%x, in \"%s\" expecting power to two",
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07002895 gnu_maskwords_, get_realpath());
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -08002896 return false;
2897 }
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002898 --gnu_maskwords_;
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -08002899
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08002900 flags_ |= FLAG_GNU_HASH;
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -08002901 break;
2902
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002903 case DT_STRTAB:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002904 strtab_ = reinterpret_cast<const char*>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002905 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002906
Dmitriy Ivanov6cdeb522014-09-29 19:14:45 -07002907 case DT_STRSZ:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002908 strtab_size_ = d->d_un.d_val;
Dmitriy Ivanov6cdeb522014-09-29 19:14:45 -07002909 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002910
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002911 case DT_SYMTAB:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002912 symtab_ = reinterpret_cast<ElfW(Sym)*>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002913 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002914
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07002915 case DT_SYMENT:
2916 if (d->d_un.d_val != sizeof(ElfW(Sym))) {
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07002917 DL_ERR("invalid DT_SYMENT: %zd in \"%s\"",
2918 static_cast<size_t>(d->d_un.d_val), get_realpath());
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07002919 return false;
2920 }
2921 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002922
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002923 case DT_PLTREL:
Dmitriy Ivanov513e29e2014-10-06 11:30:43 -07002924#if defined(USE_RELA)
2925 if (d->d_un.d_val != DT_RELA) {
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07002926 DL_ERR("unsupported DT_PLTREL in \"%s\"; expected DT_RELA", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002927 return false;
2928 }
Dmitriy Ivanov513e29e2014-10-06 11:30:43 -07002929#else
2930 if (d->d_un.d_val != DT_REL) {
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07002931 DL_ERR("unsupported DT_PLTREL in \"%s\"; expected DT_REL", get_realpath());
Dmitriy Ivanov513e29e2014-10-06 11:30:43 -07002932 return false;
2933 }
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07002934#endif
Dmitriy Ivanov513e29e2014-10-06 11:30:43 -07002935 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002936
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002937 case DT_JMPREL:
Elliott Hughes4eeb1f12013-10-25 17:38:02 -07002938#if defined(USE_RELA)
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002939 plt_rela_ = reinterpret_cast<ElfW(Rela)*>(load_bias + d->d_un.d_ptr);
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07002940#else
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002941 plt_rel_ = reinterpret_cast<ElfW(Rel)*>(load_bias + d->d_un.d_ptr);
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07002942#endif
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002943 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002944
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002945 case DT_PLTRELSZ:
Elliott Hughes4eeb1f12013-10-25 17:38:02 -07002946#if defined(USE_RELA)
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002947 plt_rela_count_ = d->d_un.d_val / sizeof(ElfW(Rela));
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07002948#else
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002949 plt_rel_count_ = d->d_un.d_val / sizeof(ElfW(Rel));
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07002950#endif
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002951 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002952
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002953 case DT_PLTGOT:
Elliott Hughes14798932020-02-13 15:40:07 -08002954 // Ignored (because RTLD_LAZY is not supported).
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07002955 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002956
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002957 case DT_DEBUG:
2958 // Set the DT_DEBUG entry to the address of _r_debug for GDB
2959 // if the dynamic table is writable
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002960 if ((dynamic_flags & PF_W) != 0) {
2961 d->d_un.d_val = reinterpret_cast<uintptr_t>(&_r_debug);
2962 }
Dmitriy Ivanovc6292ea2015-02-13 16:29:50 -08002963 break;
Elliott Hughes4eeb1f12013-10-25 17:38:02 -07002964#if defined(USE_RELA)
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002965 case DT_RELA:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002966 rela_ = reinterpret_cast<ElfW(Rela)*>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002967 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002968
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002969 case DT_RELASZ:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002970 rela_count_ = d->d_un.d_val / sizeof(ElfW(Rela));
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002971 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002972
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08002973 case DT_ANDROID_RELA:
2974 android_relocs_ = reinterpret_cast<uint8_t*>(load_bias + d->d_un.d_ptr);
2975 break;
2976
2977 case DT_ANDROID_RELASZ:
2978 android_relocs_size_ = d->d_un.d_val;
2979 break;
2980
2981 case DT_ANDROID_REL:
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07002982 DL_ERR("unsupported DT_ANDROID_REL in \"%s\"", get_realpath());
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08002983 return false;
2984
2985 case DT_ANDROID_RELSZ:
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07002986 DL_ERR("unsupported DT_ANDROID_RELSZ in \"%s\"", get_realpath());
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08002987 return false;
2988
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07002989 case DT_RELAENT:
2990 if (d->d_un.d_val != sizeof(ElfW(Rela))) {
Dmitriy Ivanovf240aa82014-09-16 23:34:20 -07002991 DL_ERR("invalid DT_RELAENT: %zd", static_cast<size_t>(d->d_un.d_val));
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07002992 return false;
2993 }
2994 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002995
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08002996 // Ignored (see DT_RELCOUNT comments for details).
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07002997 case DT_RELACOUNT:
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07002998 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002999
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003000 case DT_REL:
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003001 DL_ERR("unsupported DT_REL in \"%s\"", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003002 return false;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003003
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003004 case DT_RELSZ:
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003005 DL_ERR("unsupported DT_RELSZ in \"%s\"", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003006 return false;
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08003007
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07003008#else
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003009 case DT_REL:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003010 rel_ = reinterpret_cast<ElfW(Rel)*>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003011 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003012
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003013 case DT_RELSZ:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003014 rel_count_ = d->d_un.d_val / sizeof(ElfW(Rel));
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003015 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003016
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07003017 case DT_RELENT:
3018 if (d->d_un.d_val != sizeof(ElfW(Rel))) {
Dmitriy Ivanovf240aa82014-09-16 23:34:20 -07003019 DL_ERR("invalid DT_RELENT: %zd", static_cast<size_t>(d->d_un.d_val));
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07003020 return false;
3021 }
3022 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003023
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08003024 case DT_ANDROID_REL:
3025 android_relocs_ = reinterpret_cast<uint8_t*>(load_bias + d->d_un.d_ptr);
3026 break;
3027
3028 case DT_ANDROID_RELSZ:
3029 android_relocs_size_ = d->d_un.d_val;
3030 break;
3031
3032 case DT_ANDROID_RELA:
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003033 DL_ERR("unsupported DT_ANDROID_RELA in \"%s\"", get_realpath());
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08003034 return false;
3035
3036 case DT_ANDROID_RELASZ:
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003037 DL_ERR("unsupported DT_ANDROID_RELASZ in \"%s\"", get_realpath());
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08003038 return false;
3039
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003040 // "Indicates that all RELATIVE relocations have been concatenated together,
3041 // and specifies the RELATIVE relocation count."
3042 //
3043 // TODO: Spec also mentions that this can be used to optimize relocation process;
3044 // Not currently used by bionic linker - ignored.
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07003045 case DT_RELCOUNT:
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07003046 break;
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08003047
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003048 case DT_RELA:
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003049 DL_ERR("unsupported DT_RELA in \"%s\"", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003050 return false;
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08003051
3052 case DT_RELASZ:
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003053 DL_ERR("unsupported DT_RELASZ in \"%s\"", get_realpath());
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08003054 return false;
3055
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07003056#endif
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08003057 case DT_RELR:
Elliott Hughes6663f552020-01-24 14:36:10 -08003058 case DT_ANDROID_RELR:
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08003059 relr_ = reinterpret_cast<ElfW(Relr)*>(load_bias + d->d_un.d_ptr);
3060 break;
3061
3062 case DT_RELRSZ:
Elliott Hughes6663f552020-01-24 14:36:10 -08003063 case DT_ANDROID_RELRSZ:
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08003064 relr_count_ = d->d_un.d_val / sizeof(ElfW(Relr));
3065 break;
3066
3067 case DT_RELRENT:
Elliott Hughes6663f552020-01-24 14:36:10 -08003068 case DT_ANDROID_RELRENT:
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08003069 if (d->d_un.d_val != sizeof(ElfW(Relr))) {
3070 DL_ERR("invalid DT_RELRENT: %zd", static_cast<size_t>(d->d_un.d_val));
3071 return false;
3072 }
3073 break;
3074
3075 // Ignored (see DT_RELCOUNT comments for details).
Elliott Hughes6663f552020-01-24 14:36:10 -08003076 // There is no DT_RELRCOUNT specifically because it would only be ignored.
3077 case DT_ANDROID_RELRCOUNT:
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08003078 break;
3079
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003080 case DT_INIT:
Dimitry Ivanov55437462016-07-20 15:33:07 -07003081 init_func_ = reinterpret_cast<linker_ctor_function_t>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003082 DEBUG("%s constructors (DT_INIT) found at %p", get_realpath(), init_func_);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003083 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003084
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003085 case DT_FINI:
Dimitry Ivanov55437462016-07-20 15:33:07 -07003086 fini_func_ = reinterpret_cast<linker_dtor_function_t>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003087 DEBUG("%s destructors (DT_FINI) found at %p", get_realpath(), fini_func_);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003088 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003089
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003090 case DT_INIT_ARRAY:
Dimitry Ivanov55437462016-07-20 15:33:07 -07003091 init_array_ = reinterpret_cast<linker_ctor_function_t*>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003092 DEBUG("%s constructors (DT_INIT_ARRAY) found at %p", get_realpath(), init_array_);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003093 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003094
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003095 case DT_INIT_ARRAYSZ:
Dmitriy Ivanov1649e7e2015-01-22 16:04:25 -08003096 init_array_count_ = static_cast<uint32_t>(d->d_un.d_val) / sizeof(ElfW(Addr));
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003097 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003098
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003099 case DT_FINI_ARRAY:
Dimitry Ivanov55437462016-07-20 15:33:07 -07003100 fini_array_ = reinterpret_cast<linker_dtor_function_t*>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003101 DEBUG("%s destructors (DT_FINI_ARRAY) found at %p", get_realpath(), fini_array_);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003102 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003103
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003104 case DT_FINI_ARRAYSZ:
Dmitriy Ivanov1649e7e2015-01-22 16:04:25 -08003105 fini_array_count_ = static_cast<uint32_t>(d->d_un.d_val) / sizeof(ElfW(Addr));
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003106 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003107
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003108 case DT_PREINIT_ARRAY:
Dimitry Ivanov55437462016-07-20 15:33:07 -07003109 preinit_array_ = reinterpret_cast<linker_ctor_function_t*>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003110 DEBUG("%s constructors (DT_PREINIT_ARRAY) found at %p", get_realpath(), preinit_array_);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003111 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003112
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003113 case DT_PREINIT_ARRAYSZ:
Dmitriy Ivanov1649e7e2015-01-22 16:04:25 -08003114 preinit_array_count_ = static_cast<uint32_t>(d->d_un.d_val) / sizeof(ElfW(Addr));
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003115 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003116
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003117 case DT_TEXTREL:
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003118#if defined(__LP64__)
Dimitry Ivanov816676e2016-10-19 11:00:28 -07003119 DL_ERR("\"%s\" has text relocations", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003120 return false;
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003121#else
3122 has_text_relocations = true;
3123 break;
3124#endif
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003125
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003126 case DT_SYMBOLIC:
Dmitriy Ivanov96bc37f2014-09-29 12:10:36 -07003127 has_DT_SYMBOLIC = true;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003128 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003129
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003130 case DT_NEEDED:
3131 ++needed_count;
3132 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003133
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003134 case DT_FLAGS:
3135 if (d->d_un.d_val & DF_TEXTREL) {
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003136#if defined(__LP64__)
Dimitry Ivanov816676e2016-10-19 11:00:28 -07003137 DL_ERR("\"%s\" has text relocations", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003138 return false;
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003139#else
3140 has_text_relocations = true;
3141#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08003142 }
Dmitriy Ivanov96bc37f2014-09-29 12:10:36 -07003143 if (d->d_un.d_val & DF_SYMBOLIC) {
3144 has_DT_SYMBOLIC = true;
3145 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003146 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003147
Dmitriy Ivanov6cdeb522014-09-29 19:14:45 -07003148 case DT_FLAGS_1:
Dmitriy Ivanovd225a5e2014-08-28 14:12:12 -07003149 set_dt_flags_1(d->d_un.d_val);
Dmitriy Ivanov1b20daf2014-05-19 15:06:58 -07003150
Dmitriy Ivanovd225a5e2014-08-28 14:12:12 -07003151 if ((d->d_un.d_val & ~SUPPORTED_DT_FLAGS_1) != 0) {
Elliott Hughes9076b0c2018-02-28 11:29:45 -08003152 DL_WARN("Warning: \"%s\" has unsupported flags DT_FLAGS_1=%p "
3153 "(ignoring unsupported flags)",
3154 get_realpath(), reinterpret_cast<void*>(d->d_un.d_val));
Dmitriy Ivanov6cdeb522014-09-29 19:14:45 -07003155 }
3156 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003157
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003158 // Ignored: "Its use has been superseded by the DF_BIND_NOW flag"
3159 case DT_BIND_NOW:
3160 break;
3161
Dmitriy Ivanov513e29e2014-10-06 11:30:43 -07003162 case DT_VERSYM:
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07003163 versym_ = reinterpret_cast<ElfW(Versym)*>(load_bias + d->d_un.d_ptr);
3164 break;
3165
Dmitriy Ivanov513e29e2014-10-06 11:30:43 -07003166 case DT_VERDEF:
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07003167 verdef_ptr_ = load_bias + d->d_un.d_ptr;
3168 break;
Dmitriy Ivanov513e29e2014-10-06 11:30:43 -07003169 case DT_VERDEFNUM:
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07003170 verdef_cnt_ = d->d_un.d_val;
3171 break;
3172
Alexander Ivchenkoe8314332014-12-02 15:32:25 +03003173 case DT_VERNEED:
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07003174 verneed_ptr_ = load_bias + d->d_un.d_ptr;
3175 break;
3176
Alexander Ivchenkoe8314332014-12-02 15:32:25 +03003177 case DT_VERNEEDNUM:
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07003178 verneed_cnt_ = d->d_un.d_val;
Dmitriy Ivanov513e29e2014-10-06 11:30:43 -07003179 break;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003180
Evgenii Stepanov68650822015-06-10 13:38:39 -07003181 case DT_RUNPATH:
3182 // this is parsed after we have strtab initialized (see below).
3183 break;
3184
Ryan Prichardea41ab02019-01-23 16:33:03 -08003185 case DT_TLSDESC_GOT:
3186 case DT_TLSDESC_PLT:
3187 // These DT entries are used for lazy TLSDESC relocations. Bionic
3188 // resolves everything eagerly, so these can be ignored.
3189 break;
3190
Tamas Petz8d55d182020-02-24 14:15:25 +01003191#if defined(__aarch64__)
3192 case DT_AARCH64_BTI_PLT:
3193 case DT_AARCH64_PAC_PLT:
3194 case DT_AARCH64_VARIANT_PCS:
3195 // Ignored: AArch64 processor-specific dynamic array tags.
3196 break;
Mitch Phillips2e25c0f2023-03-17 11:29:03 -07003197 // TODO(mitchp): Add support to libc_init_mte to use these dynamic array entries instead of
3198 // the Android-specific ELF note.
3199 case DT_AARCH64_MEMTAG_MODE:
3200 case DT_AARCH64_MEMTAG_HEAP:
3201 case DT_AARCH64_MEMTAG_STACK:
3202 case DT_AARCH64_MEMTAG_GLOBALS:
3203 case DT_AARCH64_MEMTAG_GLOBALSSZ:
3204 break;
Tamas Petz8d55d182020-02-24 14:15:25 +01003205#endif
3206
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003207 default:
Dmitriy Ivanov8f61d992014-09-16 14:31:06 -07003208 if (!relocating_linker) {
Elliott Hughes6eae4cc2017-08-30 09:02:33 -07003209 const char* tag_name;
3210 if (d->d_tag == DT_RPATH) {
3211 tag_name = "DT_RPATH";
3212 } else if (d->d_tag == DT_ENCODING) {
3213 tag_name = "DT_ENCODING";
3214 } else if (d->d_tag >= DT_LOOS && d->d_tag <= DT_HIOS) {
3215 tag_name = "unknown OS-specific";
3216 } else if (d->d_tag >= DT_LOPROC && d->d_tag <= DT_HIPROC) {
3217 tag_name = "unknown processor-specific";
3218 } else {
3219 tag_name = "unknown";
3220 }
Elliott Hughes9076b0c2018-02-28 11:29:45 -08003221 DL_WARN("Warning: \"%s\" unused DT entry: %s (type %p arg %p) (ignoring)",
Elliott Hughes6eae4cc2017-08-30 09:02:33 -07003222 get_realpath(),
3223 tag_name,
3224 reinterpret_cast<void*>(d->d_tag),
3225 reinterpret_cast<void*>(d->d_un.d_val));
Dmitriy Ivanov8f61d992014-09-16 14:31:06 -07003226 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003227 break;
Brian Carlstromd4ee82d2013-02-28 15:58:45 -08003228 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003229 }
3230
3231 DEBUG("si->base = %p, si->strtab = %p, si->symtab = %p",
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003232 reinterpret_cast<void*>(base), strtab_, symtab_);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003233
Elliott Hughes68ae6ad2020-07-21 16:11:30 -07003234 // Validity checks.
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003235 if (relocating_linker && needed_count != 0) {
3236 DL_ERR("linker cannot have DT_NEEDED dependencies on other libraries");
3237 return false;
3238 }
Dmitriy Ivanov3597b802015-03-09 12:02:02 -07003239 if (nbucket_ == 0 && gnu_nbucket_ == 0) {
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003240 DL_ERR("empty/missing DT_HASH/DT_GNU_HASH in \"%s\" "
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07003241 "(new hash type from the future?)", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003242 return false;
3243 }
Yi Kong32bc0fc2018-08-02 17:31:13 -07003244 if (strtab_ == nullptr) {
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07003245 DL_ERR("empty/missing DT_STRTAB in \"%s\"", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003246 return false;
3247 }
Yi Kong32bc0fc2018-08-02 17:31:13 -07003248 if (symtab_ == nullptr) {
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07003249 DL_ERR("empty/missing DT_SYMTAB in \"%s\"", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003250 return false;
3251 }
Dmitriy Ivanov75108f42015-06-02 13:28:06 -07003252
Ryan Prichardbb1e3732021-01-12 23:09:10 -08003253 // Second pass - parse entries relying on strtab. Skip this while relocating the linker so as to
3254 // avoid doing heap allocations until later in the linker's initialization.
3255 if (!relocating_linker) {
3256 for (ElfW(Dyn)* d = dynamic; d->d_tag != DT_NULL; ++d) {
3257 switch (d->d_tag) {
3258 case DT_SONAME:
3259 set_soname(get_string(d->d_un.d_val));
3260 break;
3261 case DT_RUNPATH:
3262 set_dt_runpath(get_string(d->d_un.d_val));
3263 break;
3264 }
Dmitriy Ivanov624b8f12015-06-08 10:41:33 -07003265 }
3266 }
3267
Ryan Prichardbb1e3732021-01-12 23:09:10 -08003268 // Before M release, linker was using basename in place of soname. In the case when DT_SONAME is
3269 // absent some apps stop working because they can't find DT_NEEDED library by soname. This
3270 // workaround should keep them working. (Applies only for apps targeting sdk version < M.) Make
3271 // an exception for the main executable, which does not need to have DT_SONAME. The linker has an
3272 // DT_SONAME but the soname_ field is initialized later on.
3273 if (soname_.empty() && this != solist_get_somain() && !relocating_linker &&
Elliott Hughes95c6cd72019-12-20 13:26:14 -08003274 get_application_target_sdk_version() < 23) {
Dmitriy Ivanov75108f42015-06-02 13:28:06 -07003275 soname_ = basename(realpath_.c_str());
Elliott Hughesf9dd1a72021-01-11 09:04:58 -08003276 DL_WARN_documented_change(23, "missing-soname-enforced-for-api-level-23",
3277 "\"%s\" has no DT_SONAME (will use %s instead)", get_realpath(),
3278 soname_.c_str());
Elliott Hughes9076b0c2018-02-28 11:29:45 -08003279
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07003280 // 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 -07003281 }
Ryan Prichardae320cd2019-12-10 12:39:05 -08003282
Ryan Prichard0e12cce2020-01-02 14:59:11 -08003283 // Validate each library's verdef section once, so we don't have to validate
3284 // it each time we look up a symbol with a version.
3285 if (!validate_verdef_section(this)) return false;
3286
Ryan Prichardae320cd2019-12-10 12:39:05 -08003287 flags_ |= FLAG_PRELINKED;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003288 return true;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07003289}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08003290
Ryan Prichard339ecef2020-01-02 16:36:06 -08003291bool soinfo::link_image(const SymbolLookupList& lookup_list, soinfo* local_group_root,
Torne (Richard Coles)efbe9a52018-10-17 15:59:38 -04003292 const android_dlextinfo* extinfo, size_t* relro_fd_offset) {
dimitry965d06d2017-11-28 16:03:07 +01003293 if (is_image_linked()) {
3294 // already linked.
3295 return true;
3296 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08003297
Elliott Hughes90f96b92019-05-09 15:56:39 -07003298 if (g_is_ldd && !is_main_executable()) {
3299 async_safe_format_fd(STDOUT_FILENO, "\t%s => %s (%p)\n", get_soname(),
3300 get_realpath(), reinterpret_cast<void*>(base));
3301 }
3302
Ryan Prichard339ecef2020-01-02 16:36:06 -08003303 local_group_root_ = local_group_root;
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08003304 if (local_group_root_ == nullptr) {
3305 local_group_root_ = this;
3306 }
3307
Dmitriy Ivanov19133522015-06-02 17:36:54 -07003308 if ((flags_ & FLAG_LINKER) == 0 && local_group_root_ == this) {
3309 target_sdk_version_ = get_application_target_sdk_version();
3310 }
3311
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003312#if !defined(__LP64__)
3313 if (has_text_relocations) {
Elliott Hughes5bc78c82016-11-16 11:35:43 -08003314 // Fail if app is targeting M or above.
Elliott Hughes9076b0c2018-02-28 11:29:45 -08003315 int app_target_api_level = get_application_target_sdk_version();
Elliott Hughes95c6cd72019-12-20 13:26:14 -08003316 if (app_target_api_level >= 23) {
Ryan Prichard146620b2020-03-26 19:55:05 -07003317 DL_ERR_AND_LOG("\"%s\" has text relocations (%s#Text-Relocations-Enforced-for-API-level-23)",
3318 get_realpath(), kBionicChangesUrl);
Dmitriy Ivanove4ad91f2015-06-12 15:00:31 -07003319 return false;
3320 }
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003321 // Make segments writable to allow text relocations to work properly. We will later call
Dmitriy Ivanov7e039932015-10-01 14:02:19 -07003322 // phdr_table_protect_segments() after all of them are applied.
Elliott Hughes95c6cd72019-12-20 13:26:14 -08003323 DL_WARN_documented_change(23,
Elliott Hughes9076b0c2018-02-28 11:29:45 -08003324 "Text-Relocations-Enforced-for-API-level-23",
3325 "\"%s\" has text relocations",
3326 get_realpath());
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07003327 add_dlwarning(get_realpath(), "text relocations");
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003328 if (phdr_table_unprotect_segments(phdr, phnum, load_bias) < 0) {
Elliott Hughes9076b0c2018-02-28 11:29:45 -08003329 DL_ERR("can't unprotect loadable segments for \"%s\": %s", get_realpath(), strerror(errno));
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003330 return false;
3331 }
3332 }
3333#endif
3334
Ryan Prichard339ecef2020-01-02 16:36:06 -08003335 if (!relocate(lookup_list)) {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003336 return false;
3337 }
Raghu Gandhamd7daacb2012-07-31 12:07:22 -07003338
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07003339 DEBUG("[ finished linking %s ]", get_realpath());
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08003340
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003341#if !defined(__LP64__)
3342 if (has_text_relocations) {
3343 // All relocations are done, we can protect our segments back to read-only.
3344 if (phdr_table_protect_segments(phdr, phnum, load_bias) < 0) {
3345 DL_ERR("can't protect segments for \"%s\": %s",
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07003346 get_realpath(), strerror(errno));
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003347 return false;
3348 }
3349 }
3350#endif
3351
Mingwei Shibe910522015-11-12 07:02:14 +00003352 // We can also turn on GNU RELRO protection if we're not linking the dynamic linker
3353 // itself --- it can't make system calls yet, and will have to call protect_relro later.
3354 if (!is_linker() && !protect_relro()) {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003355 return false;
3356 }
Nick Kralevich9ec0f032012-02-28 10:40:00 -08003357
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003358 /* Handle serializing/sharing the RELRO segment */
3359 if (extinfo && (extinfo->flags & ANDROID_DLEXT_WRITE_RELRO)) {
3360 if (phdr_table_serialize_gnu_relro(phdr, phnum, load_bias,
Torne (Richard Coles)fa9f7f22019-04-02 17:04:42 -04003361 extinfo->relro_fd, relro_fd_offset) < 0) {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003362 DL_ERR("failed serializing GNU RELRO section for \"%s\": %s",
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07003363 get_realpath(), strerror(errno));
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003364 return false;
Torne (Richard Coles)183ad9d2014-02-27 13:18:00 +00003365 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003366 } else if (extinfo && (extinfo->flags & ANDROID_DLEXT_USE_RELRO)) {
3367 if (phdr_table_map_gnu_relro(phdr, phnum, load_bias,
Torne (Richard Coles)efbe9a52018-10-17 15:59:38 -04003368 extinfo->relro_fd, relro_fd_offset) < 0) {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003369 DL_ERR("failed mapping GNU RELRO section for \"%s\": %s",
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07003370 get_realpath(), strerror(errno));
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003371 return false;
3372 }
3373 }
Torne (Richard Coles)183ad9d2014-02-27 13:18:00 +00003374
Ryan Pricharda2e83ab2019-08-16 17:25:43 -07003375 ++g_module_load_counter;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003376 notify_gdb_of_load(this);
dimitry965d06d2017-11-28 16:03:07 +01003377 set_image_linked();
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003378 return true;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08003379}
3380
Mingwei Shibe910522015-11-12 07:02:14 +00003381bool soinfo::protect_relro() {
3382 if (phdr_table_protect_gnu_relro(phdr, phnum, load_bias) < 0) {
3383 DL_ERR("can't enable GNU RELRO protection for \"%s\": %s",
3384 get_realpath(), strerror(errno));
3385 return false;
3386 }
3387 return true;
3388}
3389
Florian Mayerc10d0642023-03-22 16:12:49 -07003390static std::vector<android_namespace_t*> init_default_namespace_no_config(bool is_asan, bool is_hwasan) {
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07003391 g_default_namespace.set_isolated(false);
Florian Mayerc10d0642023-03-22 16:12:49 -07003392 auto default_ld_paths = is_asan ? kAsanDefaultLdPaths : (
3393 is_hwasan ? kHwsanDefaultLdPaths : kDefaultLdPaths);
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07003394
neo.chae2589f9d2016-10-04 11:00:27 +09003395 char real_path[PATH_MAX];
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07003396 std::vector<std::string> ld_default_paths;
Dimitry Ivanov77ad6422017-03-06 13:02:29 -08003397 for (size_t i = 0; default_ld_paths[i] != nullptr; ++i) {
3398 if (realpath(default_ld_paths[i], real_path) != nullptr) {
neo.chae2589f9d2016-10-04 11:00:27 +09003399 ld_default_paths.push_back(real_path);
3400 } else {
Dimitry Ivanov77ad6422017-03-06 13:02:29 -08003401 ld_default_paths.push_back(default_ld_paths[i]);
neo.chae2589f9d2016-10-04 11:00:27 +09003402 }
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07003403 }
3404
3405 g_default_namespace.set_default_library_paths(std::move(ld_default_paths));
Jiyong Park02586a22017-05-20 01:01:24 +09003406
3407 std::vector<android_namespace_t*> namespaces;
3408 namespaces.push_back(&g_default_namespace);
3409 return namespaces;
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08003410}
3411
Roland Levillain57e6b862020-02-12 17:34:20 +00003412// Given an `executable_path` starting with "/apex/<name>/bin/, return
Jiyong Park2bac1f82022-04-05 14:03:34 +09003413// "/linkerconfig/<name>/ld.config.txt", which is the auto-generated config file for the APEX by the
3414// linkerconfig tool.
Jiyong Park35833412018-10-26 14:45:21 +09003415static std::string get_ld_config_file_apex_path(const char* executable_path) {
3416 std::vector<std::string> paths = android::base::Split(executable_path, "/");
Roland Levillaindc25f6c2019-07-02 16:40:19 +01003417 if (paths.size() >= 5 && paths[1] == "apex" && paths[3] == "bin") {
Kiyoung Kimfb587442020-01-29 16:31:54 +09003418 std::string generated_apex_config = "/linkerconfig/" + paths[2] + "/ld.config.txt";
3419 if (file_exists(generated_apex_config.c_str())) {
3420 return generated_apex_config;
3421 }
Jiyong Park35833412018-10-26 14:45:21 +09003422 }
3423 return "";
3424}
3425
Logan Chien886b96e2018-05-08 17:52:18 +08003426static std::string get_ld_config_file_vndk_path() {
Roland Levillain09bde952019-10-29 19:17:49 +00003427 if (android::base::GetBoolProperty("ro.vndk.lite", false)) {
3428 return kLdConfigVndkLiteFilePath;
Logan Chienbcfe3cf2018-05-08 20:17:26 +08003429 }
3430
Roland Levillain09bde952019-10-29 19:17:49 +00003431 std::string ld_config_file_vndk = kLdConfigFilePath;
3432 size_t insert_pos = ld_config_file_vndk.find_last_of('.');
3433 if (insert_pos == std::string::npos) {
3434 insert_pos = ld_config_file_vndk.length();
3435 }
3436 ld_config_file_vndk.insert(insert_pos, Config::get_vndk_version_string('.'));
3437 return ld_config_file_vndk;
Logan Chien886b96e2018-05-08 17:52:18 +08003438}
3439
Kiyoung Kim46e731c2020-06-26 16:54:50 +09003440bool is_linker_config_expected(const char* executable_path) {
3441 // Do not raise message from a host environment which is expected to miss generated linker
3442 // configuration.
3443#if !defined(__ANDROID__)
3444 return false;
3445#endif
3446
3447 if (strcmp(executable_path, "/system/bin/init") == 0) {
3448 // Generated linker configuration can be missed from processes executed
3449 // with init binary
3450 return false;
3451 }
3452
3453 return true;
3454}
3455
Jiyong Park35833412018-10-26 14:45:21 +09003456static std::string get_ld_config_file_path(const char* executable_path) {
Logan Chien886b96e2018-05-08 17:52:18 +08003457#ifdef USE_LD_CONFIG_FILE
3458 // This is a debugging/testing only feature. Must not be available on
3459 // production builds.
3460 const char* ld_config_file_env = getenv("LD_CONFIG_FILE");
3461 if (ld_config_file_env != nullptr && file_exists(ld_config_file_env)) {
3462 return ld_config_file_env;
3463 }
3464#endif
3465
Jiyong Park35833412018-10-26 14:45:21 +09003466 std::string path = get_ld_config_file_apex_path(executable_path);
3467 if (!path.empty()) {
3468 if (file_exists(path.c_str())) {
3469 return path;
3470 }
3471 DL_WARN("Warning: couldn't read config file \"%s\" for \"%s\"",
3472 path.c_str(), executable_path);
Logan Chien886b96e2018-05-08 17:52:18 +08003473 }
3474
Evgeny Eltsinff43ec02019-12-16 19:22:07 +01003475 path = kLdConfigArchFilePath;
3476 if (file_exists(path.c_str())) {
3477 return path;
3478 }
3479
Kiyoung Kim18786902020-02-12 07:47:37 +09003480 if (file_exists(kLdGeneratedConfigFilePath)) {
3481 return kLdGeneratedConfigFilePath;
Kiyoung Kimef04c802019-12-13 12:19:56 +09003482 }
3483
Kiyoung Kim46e731c2020-06-26 16:54:50 +09003484 if (is_linker_config_expected(executable_path)) {
3485 DL_WARN("Warning: failed to find generated linker configuration from \"%s\"",
3486 kLdGeneratedConfigFilePath);
3487 }
Kiyoung Kim8bc03532020-03-16 13:22:27 +09003488
Jiyong Park35833412018-10-26 14:45:21 +09003489 path = get_ld_config_file_vndk_path();
Roland Levillain09bde952019-10-29 19:17:49 +00003490 if (file_exists(path.c_str())) {
Jiyong Park35833412018-10-26 14:45:21 +09003491 return path;
Logan Chien886b96e2018-05-08 17:52:18 +08003492 }
3493
3494 return kLdConfigFilePath;
3495}
3496
Florian Mayerc10d0642023-03-22 16:12:49 -07003497
Jiyong Park02586a22017-05-20 01:01:24 +09003498std::vector<android_namespace_t*> init_default_namespaces(const char* executable_path) {
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08003499 g_default_namespace.set_name("(default)");
3500
3501 soinfo* somain = solist_get_somain();
3502
3503 const char *interp = phdr_table_get_interpreter_name(somain->phdr, somain->phnum,
3504 somain->load_bias);
Dan Willemsen7ccc50d2017-09-18 21:28:14 -07003505 const char* bname = (interp != nullptr) ? basename(interp) : nullptr;
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08003506
3507 g_is_asan = bname != nullptr &&
3508 (strcmp(bname, "linker_asan") == 0 ||
3509 strcmp(bname, "linker_asan64") == 0);
3510
Florian Mayerc10d0642023-03-22 16:12:49 -07003511#if defined(__aarch64__)
3512 // HWASan is only supported on AArch64.
3513 // The AT_SECURE restriction is because this is a debug feature that does
3514 // not need to work on secure binaries, it doesn't hurt to disallow the
3515 // environment variable for them, as it impacts the program execution.
3516 char* hwasan_env = getenv("LD_HWASAN");
3517 g_is_hwasan = (bname != nullptr &&
3518 strcmp(bname, "linker_hwasan64") == 0) ||
3519 (hwasan_env != nullptr && !getauxval(AT_SECURE) && strcmp(hwasan_env, "1") == 0);
3520#endif
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08003521 const Config* config = nullptr;
3522
Elliott Hughes658b9382020-11-06 09:27:36 -08003523 {
3524 std::string ld_config_file_path = get_ld_config_file_path(executable_path);
3525 INFO("[ Reading linker config \"%s\" ]", ld_config_file_path.c_str());
3526 ScopedTrace trace(("linker config " + ld_config_file_path).c_str());
3527 std::string error_msg;
Florian Mayerc10d0642023-03-22 16:12:49 -07003528 if (!Config::read_binary_config(ld_config_file_path.c_str(), executable_path, g_is_asan, g_is_hwasan,
Elliott Hughes658b9382020-11-06 09:27:36 -08003529 &config, &error_msg)) {
3530 if (!error_msg.empty()) {
3531 DL_WARN("Warning: couldn't read '%s' for '%s' (using default configuration instead): %s",
3532 ld_config_file_path.c_str(), executable_path, error_msg.c_str());
3533 }
3534 config = nullptr;
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08003535 }
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08003536 }
3537
3538 if (config == nullptr) {
Florian Mayerc10d0642023-03-22 16:12:49 -07003539 return init_default_namespace_no_config(g_is_asan, g_is_hwasan);
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08003540 }
3541
3542 const auto& namespace_configs = config->namespace_configs();
3543 std::unordered_map<std::string, android_namespace_t*> namespaces;
3544
3545 // 1. Initialize default namespace
3546 const NamespaceConfig* default_ns_config = config->default_namespace_config();
3547
3548 g_default_namespace.set_isolated(default_ns_config->isolated());
3549 g_default_namespace.set_default_library_paths(default_ns_config->search_paths());
3550 g_default_namespace.set_permitted_paths(default_ns_config->permitted_paths());
3551
3552 namespaces[default_ns_config->name()] = &g_default_namespace;
Justin Yun90de9f02017-07-07 16:21:53 +09003553 if (default_ns_config->visible()) {
3554 g_exported_namespaces[default_ns_config->name()] = &g_default_namespace;
3555 }
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08003556
3557 // 2. Initialize other namespaces
3558
3559 for (auto& ns_config : namespace_configs) {
3560 if (namespaces.find(ns_config->name()) != namespaces.end()) {
3561 continue;
3562 }
3563
3564 android_namespace_t* ns = new (g_namespace_allocator.alloc()) android_namespace_t();
3565 ns->set_name(ns_config->name());
3566 ns->set_isolated(ns_config->isolated());
3567 ns->set_default_library_paths(ns_config->search_paths());
3568 ns->set_permitted_paths(ns_config->permitted_paths());
Luke Huang30f2f052020-07-30 15:09:18 +08003569 ns->set_allowed_libs(ns_config->allowed_libs());
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08003570
3571 namespaces[ns_config->name()] = ns;
Jiyong Park01de74e2017-04-03 23:10:37 +09003572 if (ns_config->visible()) {
3573 g_exported_namespaces[ns_config->name()] = ns;
3574 }
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08003575 }
3576
3577 // 3. Establish links between namespaces
3578 for (auto& ns_config : namespace_configs) {
3579 auto it_from = namespaces.find(ns_config->name());
3580 CHECK(it_from != namespaces.end());
3581 android_namespace_t* namespace_from = it_from->second;
3582 for (const NamespaceLinkConfig& ns_link : ns_config->links()) {
3583 auto it_to = namespaces.find(ns_link.ns_name());
3584 CHECK(it_to != namespaces.end());
3585 android_namespace_t* namespace_to = it_to->second;
Logan Chien9ee45912018-01-18 12:05:09 +08003586 if (ns_link.allow_all_shared_libs()) {
3587 link_namespaces_all_libs(namespace_from, namespace_to);
3588 } else {
3589 link_namespaces(namespace_from, namespace_to, ns_link.shared_libs().c_str());
3590 }
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08003591 }
3592 }
3593 // we can no longer rely on the fact that libdl.so is part of default namespace
3594 // this is why we want to add ld-android.so to all namespaces from ld.config.txt
3595 soinfo* ld_android_so = solist_get_head();
dimitry8b142562018-05-09 15:22:38 +02003596
3597 // we also need vdso to be available for all namespaces (if present)
3598 soinfo* vdso = solist_get_vdso();
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08003599 for (auto it : namespaces) {
NIEJuhue2871bd2019-12-20 18:51:21 +08003600 if (it.second != &g_default_namespace) {
3601 it.second->add_soinfo(ld_android_so);
3602 if (vdso != nullptr) {
3603 it.second->add_soinfo(vdso);
3604 }
3605 // somain and ld_preloads are added to these namespaces after LD_PRELOAD libs are linked
dimitry8b142562018-05-09 15:22:38 +02003606 }
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08003607 }
3608
3609 set_application_target_sdk_version(config->target_sdk_version());
Jiyong Park02586a22017-05-20 01:01:24 +09003610
3611 std::vector<android_namespace_t*> created_namespaces;
3612 created_namespaces.reserve(namespaces.size());
Chih-Hung Hsieh0218e922018-12-11 10:22:11 -08003613 for (const auto& kv : namespaces) {
Jiyong Park02586a22017-05-20 01:01:24 +09003614 created_namespaces.push_back(kv.second);
3615 }
3616 return created_namespaces;
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08003617}
Jiyong Park01de74e2017-04-03 23:10:37 +09003618
3619// This function finds a namespace exported in ld.config.txt by its name.
3620// A namespace can be exported by setting .visible property to true.
3621android_namespace_t* get_exported_namespace(const char* name) {
3622 if (name == nullptr) {
3623 return nullptr;
3624 }
3625 auto it = g_exported_namespaces.find(std::string(name));
3626 if (it == g_exported_namespaces.end()) {
3627 return nullptr;
3628 }
3629 return it->second;
3630}
Vic Yangbb7e1232019-01-29 20:23:16 -08003631
3632void purge_unused_memory() {
3633 // For now, we only purge the memory used by LoadTask because we know those
3634 // are temporary objects.
3635 //
3636 // Purging other LinkerBlockAllocator hardly yields much because they hold
3637 // information about namespaces and opened libraries, which are not freed
3638 // when the control leaves the linker.
3639 //
3640 // Purging BionicAllocator may give us a few dirty pages back, but those pages
3641 // would be already zeroed out, so they compress easily in ZRAM. Therefore,
3642 // it is not worth munmap()'ing those pages.
3643 TypeBasedAllocator<LoadTask>::purge();
3644}