blob: 6246f8c20d385ae2ef9b1944ccb8135d316545c7 [file] [log] [blame]
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001/*
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07002 * Copyright (C) 2008 The Android Open Source Project
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08003 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in
12 * the documentation and/or other materials provided with the
13 * distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28
Dmitriy Ivanov19133522015-06-02 17:36:54 -070029#include <android/api-level.h>
Elliott Hughes46882792012-08-03 16:49:39 -070030#include <errno.h>
31#include <fcntl.h>
Elliott Hughes0266ae52014-02-10 17:46:57 -080032#include <inttypes.h>
Elliott Hughes46882792012-08-03 16:49:39 -070033#include <pthread.h>
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080034#include <stdio.h>
35#include <stdlib.h>
36#include <string.h>
Elliott Hughes46882792012-08-03 16:49:39 -070037#include <sys/mman.h>
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -080038#include <sys/param.h>
Dimitry Ivanovbf34ba32017-04-21 13:12:05 -070039#include <sys/vfs.h>
Elliott Hughes46882792012-08-03 16:49:39 -070040#include <unistd.h>
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080041
Jooyung Han57b03de2022-12-01 16:23:03 +090042#include <iterator>
Dmitriy Ivanov0d150942014-08-22 12:25:04 -070043#include <new>
Dmitriy Ivanovd165f562015-03-23 18:43:02 -070044#include <string>
Dmitriy Ivanovb4827502015-09-28 16:38:31 -070045#include <unordered_map>
Dmitriy Ivanovd165f562015-03-23 18:43:02 -070046#include <vector>
Dmitriy Ivanov0d150942014-08-22 12:25:04 -070047
Logan Chienbcfe3cf2018-05-08 20:17:26 +080048#include <android-base/properties.h>
Tom Cherryb8ab6182017-04-05 16:20:29 -070049#include <android-base/scopeguard.h>
Christopher Ferris7a3681e2017-04-24 17:48:32 -070050#include <async_safe/log.h>
Ryan Pricharda2e83ab2019-08-16 17:25:43 -070051#include <bionic/pthread_internal.h>
Christopher Ferris7a3681e2017-04-24 17:48:32 -070052
Elliott Hughes46882792012-08-03 16:49:39 -070053// Private C library headers.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080054
55#include "linker.h"
Dmitriy Ivanovc9ce70d2015-03-10 15:30:26 -070056#include "linker_block_allocator.h"
Evgenii Stepanov0a3637d2016-07-06 13:20:59 -070057#include "linker_cfi.h"
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -080058#include "linker_config.h"
Dimitry Ivanov6b788ee2016-02-17 16:08:03 -080059#include "linker_gdb_support.h"
Dimitry Ivanov48ec2882016-08-04 11:50:36 -070060#include "linker_globals.h"
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080061#include "linker_debug.h"
Dimitry Ivanov769b33f2016-07-21 11:33:40 -070062#include "linker_dlwarning.h"
Dimitry Ivanov3f660572016-09-09 10:00:39 -070063#include "linker_main.h"
Dimitry Ivanovb943f302016-08-03 16:00:10 -070064#include "linker_namespaces.h"
Dmitriy Ivanov18870d32015-04-22 13:10:04 -070065#include "linker_sleb128.h"
David 'Digit' Turner23363ed2012-06-18 18:13:49 +020066#include "linker_phdr.h"
Ryan Prichard339ecef2020-01-02 16:36:06 -080067#include "linker_relocate.h"
Ryan Pricharde5e69e02019-01-01 18:53:48 -080068#include "linker_tls.h"
Victor Khimenko01790fd2020-05-12 22:59:04 +020069#include "linker_translate_path.h"
Dmitriy Ivanova1feb112015-10-01 18:41:57 -070070#include "linker_utils.h"
tony.ys_liub4474402015-07-29 18:00:22 +080071
Peter Collingbournee9491952019-10-28 10:57:26 -070072#include "private/bionic_call_ifunc_resolver.h"
Ryan Pricharde5e69e02019-01-01 18:53:48 -080073#include "private/bionic_globals.h"
dimitryfe1b27c2017-08-11 14:43:21 +020074#include "android-base/macros.h"
Elliott Hughes939a7e02015-12-04 15:27:46 -080075#include "android-base/strings.h"
Dimitry Ivanovb996d602016-07-11 18:11:39 -070076#include "android-base/stringprintf.h"
Simon Baldwinaef71952015-01-16 13:22:54 +000077#include "ziparchive/zip_archive.h"
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080078
dimitry06016f22018-01-05 11:39:28 +010079static std::unordered_map<void*, size_t> g_dso_handle_counters;
80
Jiyong Park25bedfd2019-05-16 21:00:39 +090081static bool g_anonymous_namespace_set = false;
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -070082static android_namespace_t* g_anonymous_namespace = &g_default_namespace;
Jiyong Park01de74e2017-04-03 23:10:37 +090083static std::unordered_map<std::string, android_namespace_t*> g_exported_namespaces;
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -070084
Dmitriy Ivanov600bc3c2015-03-10 15:43:50 -070085static LinkerTypeAllocator<soinfo> g_soinfo_allocator;
86static LinkerTypeAllocator<LinkedListEntry<soinfo>> g_soinfo_links_allocator;
Magnus Malmbornba98d922012-09-12 13:00:55 +020087
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -070088static LinkerTypeAllocator<android_namespace_t> g_namespace_allocator;
Dimitry Ivanovaca299a2016-04-11 12:42:58 -070089static LinkerTypeAllocator<LinkedListEntry<android_namespace_t>> g_namespace_list_allocator;
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -070090
Ryan Pricharda2e83ab2019-08-16 17:25:43 -070091static uint64_t g_module_load_counter = 0;
92static uint64_t g_module_unload_counter = 0;
93
dimitryfe1b27c2017-08-11 14:43:21 +020094static const char* const kLdConfigArchFilePath = "/system/etc/ld.config." ABI_STRING ".txt";
95
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -080096static const char* const kLdConfigFilePath = "/system/etc/ld.config.txt";
Roland Levillain09bde952019-10-29 19:17:49 +000097static const char* const kLdConfigVndkLiteFilePath = "/system/etc/ld.config.vndk_lite.txt";
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -080098
Kiyoung Kim1a2460d2019-11-22 14:38:25 +090099static const char* const kLdGeneratedConfigFilePath = "/linkerconfig/ld.config.txt";
Kiyoung Kim35e3b4b2019-08-07 19:24:13 +0900100
Elliott Hughes4eeb1f12013-10-25 17:38:02 -0700101#if defined(__LP64__)
Victor Chang6cb719f2019-02-06 17:19:10 +0000102static const char* const kSystemLibDir = "/system/lib64";
103static const char* const kOdmLibDir = "/odm/lib64";
104static const char* const kVendorLibDir = "/vendor/lib64";
105static const char* const kAsanSystemLibDir = "/data/asan/system/lib64";
106static const char* const kAsanOdmLibDir = "/data/asan/odm/lib64";
107static const char* const kAsanVendorLibDir = "/data/asan/vendor/lib64";
Elliott Hughes011bc0b2013-10-08 14:27:10 -0700108#else
Victor Chang6cb719f2019-02-06 17:19:10 +0000109static const char* const kSystemLibDir = "/system/lib";
110static const char* const kOdmLibDir = "/odm/lib";
111static const char* const kVendorLibDir = "/vendor/lib";
112static const char* const kAsanSystemLibDir = "/data/asan/system/lib";
113static const char* const kAsanOdmLibDir = "/data/asan/odm/lib";
114static const char* const kAsanVendorLibDir = "/data/asan/vendor/lib";
Elliott Hughes011bc0b2013-10-08 14:27:10 -0700115#endif
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700116
Vishwath Mohan4113def2017-03-29 15:31:34 -0700117static const char* const kAsanLibDirPrefix = "/data/asan";
118
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700119static const char* const kDefaultLdPaths[] = {
120 kSystemLibDir,
Alin Jerpelea074a9fd2017-09-25 17:47:49 +0200121 kOdmLibDir,
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700122 kVendorLibDir,
Dmitriy Ivanov851135b2014-08-29 12:02:36 -0700123 nullptr
Elliott Hughes124fae92012-10-31 14:20:03 -0700124};
David Bartleybc3a5c22009-06-02 18:27:28 -0700125
Evgenii Stepanovd640b222015-07-10 17:54:01 -0700126static const char* const kAsanDefaultLdPaths[] = {
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700127 kAsanSystemLibDir,
128 kSystemLibDir,
Alin Jerpelea074a9fd2017-09-25 17:47:49 +0200129 kAsanOdmLibDir,
130 kOdmLibDir,
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700131 kAsanVendorLibDir,
132 kVendorLibDir,
Evgenii Stepanovd640b222015-07-10 17:54:01 -0700133 nullptr
134};
135
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700136// Is ASAN enabled?
137static bool g_is_asan = false;
138
Evgenii Stepanov0a3637d2016-07-06 13:20:59 -0700139static CFIShadowWriter g_cfi_shadow;
140
141CFIShadowWriter* get_cfi_shadow() {
142 return &g_cfi_shadow;
143}
144
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700145static bool is_system_library(const std::string& realpath) {
146 for (const auto& dir : g_default_namespace.get_default_library_paths()) {
147 if (file_is_in_dir(realpath, dir)) {
148 return true;
149 }
150 }
151 return false;
152}
153
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700154// Checks if the file exists and not a directory.
155static bool file_exists(const char* path) {
Dimitry Ivanov4cf70242016-08-11 11:11:52 -0700156 struct stat s;
157
158 if (stat(path, &s) != 0) {
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700159 return false;
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700160 }
Dimitry Ivanov4cf70242016-08-11 11:11:52 -0700161
162 return S_ISREG(s.st_mode);
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700163}
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700164
Dimitry Ivanov35c8e3b2017-02-27 12:17:47 -0800165static std::string resolve_soname(const std::string& name) {
166 // We assume that soname equals to basename here
167
168 // TODO(dimitry): consider having honest absolute-path -> soname resolution
169 // note that since we might end up refusing to load this library because
170 // it is not in shared libs list we need to get the soname without actually loading
171 // the library.
172 //
173 // On the other hand there are several places where we already assume that
174 // soname == basename in particular for any not-loaded library mentioned
175 // in DT_NEEDED list.
176 return basename(name.c_str());
177}
178
179static bool maybe_accessible_via_namespace_links(android_namespace_t* ns, const char* name) {
180 std::string soname = resolve_soname(name);
181 for (auto& ns_link : ns->linked_namespaces()) {
182 if (ns_link.is_accessible(soname.c_str())) {
183 return true;
184 }
185 }
186
187 return false;
188}
189
Ryan Prichardaff9a342020-08-03 15:29:12 -0700190// TODO(dimitry): The exempt-list is a workaround for http://b/26394120 ---
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700191// gradually remove libraries from this list until it is gone.
Ryan Prichardaff9a342020-08-03 15:29:12 -0700192static bool is_exempt_lib(android_namespace_t* ns, const char* name, const soinfo* needed_by) {
193 static const char* const kLibraryExemptList[] = {
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700194 "libandroid_runtime.so",
195 "libbinder.so",
196 "libcrypto.so",
197 "libcutils.so",
198 "libexpat.so",
199 "libgui.so",
200 "libmedia.so",
201 "libnativehelper.so",
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700202 "libssl.so",
203 "libstagefright.so",
204 "libsqlite.so",
205 "libui.so",
206 "libutils.so",
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700207 nullptr
208 };
209
Ryan Prichardaff9a342020-08-03 15:29:12 -0700210 // If you're targeting N, you don't get the exempt-list.
Ryan Prichard23860932020-07-30 19:16:20 -0700211 if (get_application_target_sdk_version() >= 24) {
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700212 return false;
213 }
214
215 // if the library needed by a system library - implicitly assume it
Ryan Prichardaff9a342020-08-03 15:29:12 -0700216 // is exempt unless it is in the list of shared libraries for one or
Dimitry Ivanov35c8e3b2017-02-27 12:17:47 -0800217 // more linked namespaces
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700218 if (needed_by != nullptr && is_system_library(needed_by->get_realpath())) {
Dimitry Ivanov35c8e3b2017-02-27 12:17:47 -0800219 return !maybe_accessible_via_namespace_links(ns, name);
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700220 }
221
222 // if this is an absolute path - make sure it points to /system/lib(64)
223 if (name[0] == '/' && dirname(name) == kSystemLibDir) {
224 // and reduce the path to basename
225 name = basename(name);
226 }
227
Ryan Prichardaff9a342020-08-03 15:29:12 -0700228 for (size_t i = 0; kLibraryExemptList[i] != nullptr; ++i) {
229 if (strcmp(name, kLibraryExemptList[i]) == 0) {
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700230 return true;
231 }
232 }
233
234 return false;
235}
236// END OF WORKAROUND
237
Dmitriy Ivanovd165f562015-03-23 18:43:02 -0700238static std::vector<std::string> g_ld_preload_names;
Elliott Hughesa4aafd12014-01-13 16:37:47 -0800239
Elliott Hughesbedfe382012-08-14 14:07:59 -0700240static void notify_gdb_of_load(soinfo* info) {
Dimitry Ivanove97d8ed2016-03-01 15:55:56 -0800241 if (info->is_linker() || info->is_main_executable()) {
242 // gdb already knows about the linker and the main executable.
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700243 return;
244 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800245
Dimitry Ivanov6b788ee2016-02-17 16:08:03 -0800246 link_map* map = &(info->link_map_head);
Nicolas Geoffray0fa54102016-02-18 09:31:24 +0000247
Dimitry Ivanov6b788ee2016-02-17 16:08:03 -0800248 map->l_addr = info->load_bias;
249 // link_map l_name field is not const.
250 map->l_name = const_cast<char*>(info->get_realpath());
251 map->l_ld = info->dynamic;
Nicolas Geoffray0fa54102016-02-18 09:31:24 +0000252
Dimitry Ivanove97d8ed2016-03-01 15:55:56 -0800253 CHECK(map->l_name != nullptr);
254 CHECK(map->l_name[0] != '\0');
255
Dimitry Ivanov6b788ee2016-02-17 16:08:03 -0800256 notify_gdb_of_load(map);
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -0700257}
258
Elliott Hughesbedfe382012-08-14 14:07:59 -0700259static void notify_gdb_of_unload(soinfo* info) {
Dimitry Ivanov6b788ee2016-02-17 16:08:03 -0800260 notify_gdb_of_unload(&(info->link_map_head));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800261}
262
Dmitriy Ivanovd59e5002014-05-09 09:10:14 -0700263LinkedListEntry<soinfo>* SoinfoListAllocator::alloc() {
264 return g_soinfo_links_allocator.alloc();
265}
266
267void SoinfoListAllocator::free(LinkedListEntry<soinfo>* entry) {
268 g_soinfo_links_allocator.free(entry);
269}
270
Dimitry Ivanovaca299a2016-04-11 12:42:58 -0700271LinkedListEntry<android_namespace_t>* NamespaceListAllocator::alloc() {
272 return g_namespace_list_allocator.alloc();
273}
274
275void NamespaceListAllocator::free(LinkedListEntry<android_namespace_t>* entry) {
276 g_namespace_list_allocator.free(entry);
277}
278
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700279soinfo* soinfo_alloc(android_namespace_t* ns, const char* name,
Ryan Prichard8f639a42018-10-01 23:10:05 -0700280 const struct stat* file_stat, off64_t file_offset,
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700281 uint32_t rtld_flags) {
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -0700282 if (strlen(name) >= PATH_MAX) {
Elliott Hughes7b0af7a2017-09-15 16:09:22 -0700283 async_safe_fatal("library name \"%s\" too long", name);
Magnus Malmbornba98d922012-09-12 13:00:55 +0200284 }
285
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700286 TRACE("name %s: allocating soinfo for ns=%p", name, ns);
287
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -0700288 soinfo* si = new (g_soinfo_allocator.alloc()) soinfo(ns, name, file_stat,
289 file_offset, rtld_flags);
Dmitriy Ivanovd59e5002014-05-09 09:10:14 -0700290
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700291 solist_add_soinfo(si);
Magnus Malmbornba98d922012-09-12 13:00:55 +0200292
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -0700293 si->generate_handle();
294 ns->add_soinfo(si);
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -0700295
Elliott Hughesca0c11b2013-03-12 10:40:45 -0700296 TRACE("name %s: allocated soinfo @ %p", name, si);
Magnus Malmbornba98d922012-09-12 13:00:55 +0200297 return si;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800298}
299
Elliott Hughesfaf05ba2014-02-11 16:59:37 -0800300static void soinfo_free(soinfo* si) {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700301 if (si == nullptr) {
302 return;
303 }
304
Evgenii Stepanov474f2f52020-07-06 19:25:43 +0000305 if (si->base != 0 && si->size != 0) {
Dimitry Ivanovf45b0e92016-01-15 11:13:35 -0800306 if (!si->is_mapped_by_caller()) {
Evgenii Stepanov474f2f52020-07-06 19:25:43 +0000307 munmap(reinterpret_cast<void*>(si->base), si->size);
Dimitry Ivanovf45b0e92016-01-15 11:13:35 -0800308 } else {
309 // remap the region as PROT_NONE, MAP_ANONYMOUS | MAP_NORESERVE
Evgenii Stepanov474f2f52020-07-06 19:25:43 +0000310 mmap(reinterpret_cast<void*>(si->base), si->size, PROT_NONE,
311 MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
Dimitry Ivanovf45b0e92016-01-15 11:13:35 -0800312 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700313 }
314
Evgenii Stepanove0848bb2020-07-14 16:44:57 -0700315 if (si->has_min_version(6) && si->get_gap_size()) {
316 munmap(reinterpret_cast<void*>(si->get_gap_start()), si->get_gap_size());
317 }
318
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -0700319 TRACE("name %s: freeing soinfo @ %p", si->get_realpath(), si);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700320
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700321 if (!solist_remove_soinfo(si)) {
dimitry965d06d2017-11-28 16:03:07 +0100322 async_safe_fatal("soinfo=%p is not in soinfo_list (double unload?)", si);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700323 }
Elliott Hughes46882792012-08-03 16:49:39 -0700324
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700325 // clear links to/from si
326 si->remove_all_links();
Dmitriy Ivanovd59e5002014-05-09 09:10:14 -0700327
Dmitriy Ivanov609f11b2015-07-08 15:26:46 -0700328 si->~soinfo();
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700329 g_soinfo_allocator.free(si);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800330}
331
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -0700332static void parse_path(const char* path, const char* delimiters,
333 std::vector<std::string>* resolved_paths) {
334 std::vector<std::string> paths;
335 split_path(path, delimiters, &paths);
336 resolve_paths(paths, resolved_paths);
337}
338
Elliott Hughescade4c32012-12-20 14:42:14 -0800339static void parse_LD_LIBRARY_PATH(const char* path) {
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -0700340 std::vector<std::string> ld_libary_paths;
341 parse_path(path, ":", &ld_libary_paths);
342 g_default_namespace.set_ld_library_paths(std::move(ld_libary_paths));
Elliott Hughescade4c32012-12-20 14:42:14 -0800343}
344
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -0700345static bool realpath_fd(int fd, std::string* realpath) {
Vic Yangd8bef672019-05-15 21:10:22 -0700346 // proc_self_fd needs to be large enough to hold "/proc/self/fd/" plus an
347 // integer, plus the NULL terminator.
348 char proc_self_fd[32];
349 // We want to statically allocate this large buffer so that we don't grow
350 // the stack by too much.
351 static char buf[PATH_MAX];
352
353 async_safe_format_buffer(proc_self_fd, sizeof(proc_self_fd), "/proc/self/fd/%d", fd);
354 auto length = readlink(proc_self_fd, buf, sizeof(buf));
355 if (length == -1) {
Tom Cherry66bc4282018-11-08 13:40:52 -0800356 if (!is_first_stage_init()) {
Vic Yangd8bef672019-05-15 21:10:22 -0700357 PRINT("readlink(\"%s\") failed: %s [fd=%d]", proc_self_fd, strerror(errno), fd);
Tom Cherry66bc4282018-11-08 13:40:52 -0800358 }
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -0700359 return false;
360 }
361
Vic Yangd8bef672019-05-15 21:10:22 -0700362 realpath->assign(buf, length);
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -0700363 return true;
364}
365
Ryan Pricharda2e83ab2019-08-16 17:25:43 -0700366// Returns the address of the current thread's copy of a TLS module. If the current thread doesn't
367// have a copy yet, allocate one on-demand if should_alloc is true, and return nullptr otherwise.
368static inline void* get_tls_block_for_this_thread(const soinfo_tls* si_tls, bool should_alloc) {
369 const TlsModule& tls_mod = get_tls_module(si_tls->module_id);
370 if (tls_mod.static_offset != SIZE_MAX) {
371 const StaticTlsLayout& layout = __libc_shared_globals()->static_tls_layout;
372 char* static_tls = reinterpret_cast<char*>(__get_bionic_tcb()) - layout.offset_bionic_tcb();
373 return static_tls + tls_mod.static_offset;
374 } else if (should_alloc) {
Elliott Hughes43462702022-10-10 19:21:44 +0000375 const TlsIndex ti { si_tls->module_id, static_cast<size_t>(0 - TLS_DTV_OFFSET) };
Ryan Pricharda2e83ab2019-08-16 17:25:43 -0700376 return TLS_GET_ADDR(&ti);
377 } else {
378 TlsDtv* dtv = __get_tcb_dtv(__get_bionic_tcb());
379 if (dtv->generation < tls_mod.first_generation) return nullptr;
380 return dtv->modules[__tls_module_id_to_idx(si_tls->module_id)];
381 }
382}
383
Elliott Hughes4eeb1f12013-10-25 17:38:02 -0700384#if defined(__arm__)
Elliott Hughes46882792012-08-03 16:49:39 -0700385
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700386// For a given PC, find the .so that it belongs to.
387// Returns the base address of the .ARM.exidx section
388// for that .so, and the number of 8-byte entries
389// in that section (via *pcount).
390//
391// Intended to be called by libc's __gnu_Unwind_Find_exidx().
Dimitry Ivanovd9e427c2016-11-22 16:55:25 -0800392_Unwind_Ptr do_dl_unwind_find_exidx(_Unwind_Ptr pc, int* pcount) {
Peter Collingbourneb39cb3c2019-03-01 13:12:49 -0800393 if (soinfo* si = find_containing_library(reinterpret_cast<void*>(pc))) {
394 *pcount = si->ARM_exidx_count;
395 return reinterpret_cast<_Unwind_Ptr>(si->ARM_exidx);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700396 }
397 *pcount = 0;
Elliott Hughesf2c6ad62017-04-21 10:25:56 -0700398 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800399}
Elliott Hughes46882792012-08-03 16:49:39 -0700400
Christopher Ferris24053a42013-08-19 17:45:09 -0700401#endif
Elliott Hughes46882792012-08-03 16:49:39 -0700402
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700403// Here, we only have to provide a callback to iterate across all the
404// loaded libraries. gcc_eh does the rest.
Dmitriy Ivanov7271caf2015-06-29 14:48:25 -0700405int do_dl_iterate_phdr(int (*cb)(dl_phdr_info* info, size_t size, void* data), void* data) {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700406 int rv = 0;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700407 for (soinfo* si = solist_get_head(); si != nullptr; si = si->next) {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700408 dl_phdr_info dl_info;
409 dl_info.dlpi_addr = si->link_map_head.l_addr;
410 dl_info.dlpi_name = si->link_map_head.l_name;
411 dl_info.dlpi_phdr = si->phdr;
412 dl_info.dlpi_phnum = si->phnum;
Ryan Pricharda2e83ab2019-08-16 17:25:43 -0700413 dl_info.dlpi_adds = g_module_load_counter;
414 dl_info.dlpi_subs = g_module_unload_counter;
415 if (soinfo_tls* tls_module = si->get_tls()) {
416 dl_info.dlpi_tls_modid = tls_module->module_id;
417 dl_info.dlpi_tls_data = get_tls_block_for_this_thread(tls_module, /*should_alloc=*/false);
418 } else {
419 dl_info.dlpi_tls_modid = 0;
420 dl_info.dlpi_tls_data = nullptr;
421 }
422
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700423 rv = cb(&dl_info, sizeof(dl_phdr_info), data);
424 if (rv != 0) {
425 break;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800426 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700427 }
428 return rv;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800429}
Elliott Hughes46882792012-08-03 16:49:39 -0700430
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700431ProtectedDataGuard::ProtectedDataGuard() {
432 if (ref_count_++ == 0) {
433 protect_data(PROT_READ | PROT_WRITE);
434 }
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700435
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700436 if (ref_count_ == 0) { // overflow
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700437 async_safe_fatal("Too many nested calls to dlopen()");
Dmitriy Ivanov279a22f2015-01-23 12:03:53 -0800438 }
Dimitry Ivanov68e6c032017-02-01 12:55:11 -0800439}
Dmitriy Ivanov279a22f2015-01-23 12:03:53 -0800440
Dimitry Ivanov68e6c032017-02-01 12:55:11 -0800441ProtectedDataGuard::~ProtectedDataGuard() {
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700442 if (--ref_count_ == 0) {
443 protect_data(PROT_READ);
Dmitriy Ivanov279a22f2015-01-23 12:03:53 -0800444 }
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700445}
Dmitriy Ivanov279a22f2015-01-23 12:03:53 -0800446
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700447void ProtectedDataGuard::protect_data(int protection) {
448 g_soinfo_allocator.protect_all(protection);
449 g_soinfo_links_allocator.protect_all(protection);
450 g_namespace_allocator.protect_all(protection);
451 g_namespace_list_allocator.protect_all(protection);
452}
Dmitriy Ivanov279a22f2015-01-23 12:03:53 -0800453
454size_t ProtectedDataGuard::ref_count_ = 0;
455
Dmitriy Ivanov0cd83eb2014-09-01 16:15:52 -0700456// Each size has it's own allocator.
457template<size_t size>
458class SizeBasedAllocator {
459 public:
460 static void* alloc() {
461 return allocator_.alloc();
462 }
Dmitriy Ivanov4bea4982014-08-29 14:01:48 -0700463
Dmitriy Ivanov0cd83eb2014-09-01 16:15:52 -0700464 static void free(void* ptr) {
465 allocator_.free(ptr);
466 }
Dmitriy Ivanov4bea4982014-08-29 14:01:48 -0700467
Vic Yangbb7e1232019-01-29 20:23:16 -0800468 static void purge() {
469 allocator_.purge();
470 }
471
Dmitriy Ivanov0cd83eb2014-09-01 16:15:52 -0700472 private:
473 static LinkerBlockAllocator allocator_;
474};
475
476template<size_t size>
477LinkerBlockAllocator SizeBasedAllocator<size>::allocator_(size);
478
479template<typename T>
480class TypeBasedAllocator {
481 public:
482 static T* alloc() {
483 return reinterpret_cast<T*>(SizeBasedAllocator<sizeof(T)>::alloc());
484 }
485
486 static void free(T* ptr) {
487 SizeBasedAllocator<sizeof(T)>::free(ptr);
488 }
Vic Yangbb7e1232019-01-29 20:23:16 -0800489
490 static void purge() {
491 SizeBasedAllocator<sizeof(T)>::purge();
492 }
Dmitriy Ivanov0cd83eb2014-09-01 16:15:52 -0700493};
494
Dmitriy Ivanov14669a92014-09-05 16:42:53 -0700495class LoadTask {
496 public:
497 struct deleter_t {
498 void operator()(LoadTask* t) {
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700499 t->~LoadTask();
Dmitriy Ivanov14669a92014-09-05 16:42:53 -0700500 TypeBasedAllocator<LoadTask>::free(t);
501 }
502 };
503
Dmitriy Ivanov14669a92014-09-05 16:42:53 -0700504 static deleter_t deleter;
505
Ryan Prichardaa2db962020-03-24 20:25:53 -0700506 // needed_by is NULL iff dlopen is called from memory that isn't part of any known soinfo.
507 static LoadTask* create(const char* _Nonnull name, soinfo* _Nullable needed_by,
508 android_namespace_t* _Nonnull start_from,
509 std::unordered_map<const soinfo*, ElfReader>* _Nonnull readers_map) {
Dmitriy Ivanov14669a92014-09-05 16:42:53 -0700510 LoadTask* ptr = TypeBasedAllocator<LoadTask>::alloc();
Jiyong Park02586a22017-05-20 01:01:24 +0900511 return new (ptr) LoadTask(name, needed_by, start_from, readers_map);
Dmitriy Ivanov14669a92014-09-05 16:42:53 -0700512 }
513
514 const char* get_name() const {
515 return name_;
516 }
517
518 soinfo* get_needed_by() const {
519 return needed_by_;
520 }
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700521
522 soinfo* get_soinfo() const {
523 return si_;
524 }
525
526 void set_soinfo(soinfo* si) {
527 si_ = si;
528 }
529
530 off64_t get_file_offset() const {
531 return file_offset_;
532 }
533
534 void set_file_offset(off64_t offset) {
535 file_offset_ = offset;
536 }
537
538 int get_fd() const {
539 return fd_;
540 }
541
542 void set_fd(int fd, bool assume_ownership) {
Martin Stjernholmde853ff2019-01-17 00:18:44 +0000543 if (fd_ != -1 && close_fd_) {
544 close(fd_);
545 }
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700546 fd_ = fd;
547 close_fd_ = assume_ownership;
548 }
549
550 const android_dlextinfo* get_extinfo() const {
551 return extinfo_;
552 }
553
554 void set_extinfo(const android_dlextinfo* extinfo) {
555 extinfo_ = extinfo;
556 }
557
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700558 bool is_dt_needed() const {
559 return is_dt_needed_;
560 }
561
562 void set_dt_needed(bool is_dt_needed) {
563 is_dt_needed_ = is_dt_needed;
564 }
565
Jiyong Park02586a22017-05-20 01:01:24 +0900566 // returns the namespace from where we need to start loading this.
567 const android_namespace_t* get_start_from() const {
568 return start_from_;
569 }
570
Ryan Prichard4fa6d992020-03-26 21:31:43 -0700571 void remove_cached_elf_reader() {
572 CHECK(si_ != nullptr);
573 (*elf_readers_map_).erase(si_);
574 }
575
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700576 const ElfReader& get_elf_reader() const {
577 CHECK(si_ != nullptr);
578 return (*elf_readers_map_)[si_];
579 }
580
581 ElfReader& get_elf_reader() {
582 CHECK(si_ != nullptr);
583 return (*elf_readers_map_)[si_];
584 }
585
586 std::unordered_map<const soinfo*, ElfReader>* get_readers_map() {
587 return elf_readers_map_;
588 }
589
590 bool read(const char* realpath, off64_t file_size) {
591 ElfReader& elf_reader = get_elf_reader();
592 return elf_reader.Read(realpath, fd_, file_offset_, file_size);
593 }
594
Torne (Richard Coles)efbe9a52018-10-17 15:59:38 -0400595 bool load(address_space_params* address_space) {
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700596 ElfReader& elf_reader = get_elf_reader();
Torne (Richard Coles)efbe9a52018-10-17 15:59:38 -0400597 if (!elf_reader.Load(address_space)) {
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700598 return false;
599 }
600
601 si_->base = elf_reader.load_start();
602 si_->size = elf_reader.load_size();
Dimitry Ivanovf45b0e92016-01-15 11:13:35 -0800603 si_->set_mapped_by_caller(elf_reader.is_mapped_by_caller());
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700604 si_->load_bias = elf_reader.load_bias();
605 si_->phnum = elf_reader.phdr_count();
606 si_->phdr = elf_reader.loaded_phdr();
Evgenii Stepanove0848bb2020-07-14 16:44:57 -0700607 si_->set_gap_start(elf_reader.gap_start());
608 si_->set_gap_size(elf_reader.gap_size());
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700609
610 return true;
611 }
612
Dmitriy Ivanov14669a92014-09-05 16:42:53 -0700613 private:
Dimitry Ivanov7d429d32017-02-01 15:28:52 -0800614 LoadTask(const char* name,
615 soinfo* needed_by,
Jiyong Park02586a22017-05-20 01:01:24 +0900616 android_namespace_t* start_from,
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700617 std::unordered_map<const soinfo*, ElfReader>* readers_map)
618 : name_(name), needed_by_(needed_by), si_(nullptr),
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700619 fd_(-1), close_fd_(false), file_offset_(0), elf_readers_map_(readers_map),
Jiyong Park02586a22017-05-20 01:01:24 +0900620 is_dt_needed_(false), start_from_(start_from) {}
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700621
622 ~LoadTask() {
623 if (fd_ != -1 && close_fd_) {
624 close(fd_);
625 }
626 }
Dmitriy Ivanov14669a92014-09-05 16:42:53 -0700627
628 const char* name_;
629 soinfo* needed_by_;
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700630 soinfo* si_;
631 const android_dlextinfo* extinfo_;
632 int fd_;
633 bool close_fd_;
634 off64_t file_offset_;
635 std::unordered_map<const soinfo*, ElfReader>* elf_readers_map_;
Ryan Prichardaff9a342020-08-03 15:29:12 -0700636 // TODO(dimitry): needed by workaround for http://b/26394120 (the exempt-list)
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700637 bool is_dt_needed_;
638 // END OF WORKAROUND
Jiyong Park02586a22017-05-20 01:01:24 +0900639 const android_namespace_t* const start_from_;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -0700640
641 DISALLOW_IMPLICIT_CONSTRUCTORS(LoadTask);
642};
643
Ningsheng Jiane93be992014-09-16 15:22:10 +0800644LoadTask::deleter_t LoadTask::deleter;
645
Dmitriy Ivanov0cd83eb2014-09-01 16:15:52 -0700646template <typename T>
647using linked_list_t = LinkedList<T, TypeBasedAllocator<LinkedListEntry<T>>>;
648
649typedef linked_list_t<soinfo> SoinfoLinkedList;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -0700650typedef linked_list_t<const char> StringLinkedList;
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700651typedef std::vector<LoadTask*> LoadTaskList;
Dmitriy Ivanov0cd83eb2014-09-01 16:15:52 -0700652
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800653enum walk_action_result_t : uint32_t {
654 kWalkStop = 0,
655 kWalkContinue = 1,
656 kWalkSkip = 2
657};
Dmitriy Ivanovaa0f2bd2014-07-28 17:32:20 -0700658
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700659// This function walks down the tree of soinfo dependencies
660// in breadth-first order and
661// * calls action(soinfo* si) for each node, and
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800662// * terminates walk if action returns kWalkStop
663// * skips children of the node if action
664// return kWalkSkip
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700665//
666// walk_dependencies_tree returns false if walk was terminated
667// by the action and true otherwise.
668template<typename F>
dimitry965d06d2017-11-28 16:03:07 +0100669static bool walk_dependencies_tree(soinfo* root_soinfo, F action) {
Dmitriy Ivanov0cd83eb2014-09-01 16:15:52 -0700670 SoinfoLinkedList visit_list;
671 SoinfoLinkedList visited;
672
dimitry965d06d2017-11-28 16:03:07 +0100673 visit_list.push_back(root_soinfo);
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700674
675 soinfo* si;
676 while ((si = visit_list.pop_front()) != nullptr) {
677 if (visited.contains(si)) {
Dmitriy Ivanov042426b2014-08-12 21:02:13 -0700678 continue;
679 }
680
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800681 walk_action_result_t result = action(si);
682
683 if (result == kWalkStop) {
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700684 return false;
Dmitriy Ivanovaa0f2bd2014-07-28 17:32:20 -0700685 }
686
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700687 visited.push_back(si);
688
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800689 if (result != kWalkSkip) {
690 si->get_children().for_each([&](soinfo* child) {
691 visit_list.push_back(child);
692 });
693 }
Dmitriy Ivanovaa0f2bd2014-07-28 17:32:20 -0700694 }
695
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700696 return true;
697}
698
699
Ryan Prichard272458e2020-01-23 16:07:27 -0800700static const ElfW(Sym)* dlsym_handle_lookup_impl(android_namespace_t* ns,
701 soinfo* root,
702 soinfo* skip_until,
703 soinfo** found,
704 SymbolName& symbol_name,
705 const version_info* vi) {
Dmitriy Ivanov2a815362015-04-09 13:42:33 -0700706 const ElfW(Sym)* result = nullptr;
Dmitriy Ivanov697bd9f2015-05-12 11:12:27 -0700707 bool skip_lookup = skip_until != nullptr;
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700708
dimitry965d06d2017-11-28 16:03:07 +0100709 walk_dependencies_tree(root, [&](soinfo* current_soinfo) {
Dmitriy Ivanov697bd9f2015-05-12 11:12:27 -0700710 if (skip_lookup) {
711 skip_lookup = current_soinfo != skip_until;
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800712 return kWalkContinue;
713 }
714
715 if (!ns->is_accessible(current_soinfo)) {
716 return kWalkSkip;
Dmitriy Ivanov697bd9f2015-05-12 11:12:27 -0700717 }
718
Ryan Prichard0e12cce2020-01-02 14:59:11 -0800719 result = current_soinfo->find_symbol_by_name(symbol_name, vi);
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700720 if (result != nullptr) {
721 *found = current_soinfo;
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800722 return kWalkStop;
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700723 }
724
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800725 return kWalkContinue;
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700726 });
727
728 return result;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800729}
730
Brian Carlstromd4ee82d2013-02-28 15:58:45 -0800731/* This is used by dlsym(3) to performs a global symbol lookup. If the
732 start value is null (for RTLD_DEFAULT), the search starts at the
733 beginning of the global solist. Otherwise the search starts at the
734 specified soinfo (for RTLD_NEXT).
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700735 */
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -0800736static const ElfW(Sym)* dlsym_linear_lookup(android_namespace_t* ns,
737 const char* name,
738 const version_info* vi,
739 soinfo** found,
740 soinfo* caller,
741 void* handle) {
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -0800742 SymbolName symbol_name(name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800743
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -0700744 auto& soinfo_list = ns->soinfo_list();
745 auto start = soinfo_list.begin();
Dmitriy Ivanov76ac1ac2015-04-01 14:45:10 -0700746
747 if (handle == RTLD_NEXT) {
Dmitriy Ivanovb96ac412015-05-22 12:34:42 -0700748 if (caller == nullptr) {
Dmitriy Ivanov76ac1ac2015-04-01 14:45:10 -0700749 return nullptr;
750 } else {
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -0700751 auto it = soinfo_list.find(caller);
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -0700752 CHECK (it != soinfo_list.end());
753 start = ++it;
Dmitriy Ivanov76ac1ac2015-04-01 14:45:10 -0700754 }
Elliott Hughescade4c32012-12-20 14:42:14 -0800755 }
756
Dmitriy Ivanov2a815362015-04-09 13:42:33 -0700757 const ElfW(Sym)* s = nullptr;
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -0700758 for (auto it = start, end = soinfo_list.end(); it != end; ++it) {
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -0700759 soinfo* si = *it;
Dmitriy Ivanov19133522015-06-02 17:36:54 -0700760 // Do not skip RTLD_LOCAL libraries in dlsym(RTLD_DEFAULT, ...)
Elliott Hughes5bc78c82016-11-16 11:35:43 -0800761 // if the library is opened by application with target api level < M.
Dmitriy Ivanov19133522015-06-02 17:36:54 -0700762 // See http://b/21565766
Elliott Hughes95c6cd72019-12-20 13:26:14 -0800763 if ((si->get_rtld_flags() & RTLD_GLOBAL) == 0 && si->get_target_sdk_version() >= 23) {
Dmitriy Ivanove8ba50f2014-09-15 17:00:10 -0700764 continue;
765 }
766
Ryan Prichard0e12cce2020-01-02 14:59:11 -0800767 s = si->find_symbol_by_name(symbol_name, vi);
Dmitriy Ivanov851135b2014-08-29 12:02:36 -0700768 if (s != nullptr) {
Elliott Hughescade4c32012-12-20 14:42:14 -0800769 *found = si;
770 break;
Matt Fischer1698d9e2009-12-31 12:17:56 -0600771 }
Elliott Hughescade4c32012-12-20 14:42:14 -0800772 }
Matt Fischer1698d9e2009-12-31 12:17:56 -0600773
Ryan Prichard272458e2020-01-23 16:07:27 -0800774 // If not found - use dlsym_handle_lookup_impl for caller's local_group
dimitry153168c2018-02-20 16:51:41 +0100775 if (s == nullptr && caller != nullptr) {
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800776 soinfo* local_group_root = caller->get_local_group_root();
777
Ryan Prichard272458e2020-01-23 16:07:27 -0800778 return dlsym_handle_lookup_impl(local_group_root->get_primary_namespace(),
779 local_group_root,
780 (handle == RTLD_NEXT) ? caller : nullptr,
781 found,
782 symbol_name,
783 vi);
Dmitriy Ivanov76ac1ac2015-04-01 14:45:10 -0700784 }
785
Dmitriy Ivanov851135b2014-08-29 12:02:36 -0700786 if (s != nullptr) {
Elliott Hughesc00f2cb2013-10-04 17:01:33 -0700787 TRACE_TYPE(LOOKUP, "%s s->st_value = %p, found->base = %p",
788 name, reinterpret_cast<void*>(s->st_value), reinterpret_cast<void*>((*found)->base));
Elliott Hughescade4c32012-12-20 14:42:14 -0800789 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800790
Elliott Hughescade4c32012-12-20 14:42:14 -0800791 return s;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800792}
793
Ryan Prichard272458e2020-01-23 16:07:27 -0800794// This is used by dlsym(3). It performs symbol lookup only within the
795// specified soinfo object and its dependencies in breadth first order.
796static const ElfW(Sym)* dlsym_handle_lookup(soinfo* si,
797 soinfo** found,
798 const char* name,
799 const version_info* vi) {
800 // According to man dlopen(3) and posix docs in the case when si is handle
801 // of the main executable we need to search not only in the executable and its
802 // dependencies but also in all libraries loaded with RTLD_GLOBAL.
803 //
804 // Since RTLD_GLOBAL is always set for the main executable and all dt_needed shared
805 // libraries and they are loaded in breath-first (correct) order we can just execute
806 // dlsym(RTLD_DEFAULT, ...); instead of doing two stage lookup.
807 if (si == solist_get_somain()) {
808 return dlsym_linear_lookup(&g_default_namespace, name, vi, found, nullptr, RTLD_DEFAULT);
809 }
810
811 SymbolName symbol_name(name);
812 // note that the namespace is not the namespace associated with caller_addr
813 // we use ns associated with root si intentionally here. Using caller_ns
814 // causes problems when user uses dlopen_ext to open a library in the separate
815 // namespace and then calls dlsym() on the handle.
816 return dlsym_handle_lookup_impl(si->get_primary_namespace(), si, nullptr, found, symbol_name, vi);
817}
818
Kito Chengfa8c05d2013-03-12 14:58:06 +0800819soinfo* find_containing_library(const void* p) {
Peter Collingbourne191ecdc2019-08-07 19:06:00 -0700820 // Addresses within a library may be tagged if they point to globals. Untag
821 // them so that the bounds check succeeds.
822 ElfW(Addr) address = reinterpret_cast<ElfW(Addr)>(untag_address(p));
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700823 for (soinfo* si = solist_get_head(); si != nullptr; si = si->next) {
Peter Collingbourneb39cb3c2019-03-01 13:12:49 -0800824 if (address < si->base || address - si->base >= si->size) {
825 continue;
826 }
827 ElfW(Addr) vaddr = address - si->load_bias;
828 for (size_t i = 0; i != si->phnum; ++i) {
829 const ElfW(Phdr)* phdr = &si->phdr[i];
830 if (phdr->p_type != PT_LOAD) {
831 continue;
832 }
833 if (vaddr >= phdr->p_vaddr && vaddr < phdr->p_vaddr + phdr->p_memsz) {
834 return si;
835 }
Matt Fischere2a8b1f2009-12-31 12:17:40 -0600836 }
Kito Chengfa8c05d2013-03-12 14:58:06 +0800837 }
Dmitriy Ivanov851135b2014-08-29 12:02:36 -0700838 return nullptr;
Matt Fischere2a8b1f2009-12-31 12:17:40 -0600839}
840
Dmitriy Ivanovb4827502015-09-28 16:38:31 -0700841class ZipArchiveCache {
842 public:
843 ZipArchiveCache() {}
844 ~ZipArchiveCache();
845
846 bool get_or_open(const char* zip_path, ZipArchiveHandle* handle);
847 private:
848 DISALLOW_COPY_AND_ASSIGN(ZipArchiveCache);
849
850 std::unordered_map<std::string, ZipArchiveHandle> cache_;
851};
852
853bool ZipArchiveCache::get_or_open(const char* zip_path, ZipArchiveHandle* handle) {
854 std::string key(zip_path);
855
856 auto it = cache_.find(key);
857 if (it != cache_.end()) {
858 *handle = it->second;
859 return true;
860 }
861
862 int fd = TEMP_FAILURE_RETRY(open(zip_path, O_RDONLY | O_CLOEXEC));
863 if (fd == -1) {
864 return false;
865 }
866
867 if (OpenArchiveFd(fd, "", handle) != 0) {
868 // invalid zip-file (?)
Ryan Prichard0adf09b2018-10-01 18:35:46 -0700869 CloseArchive(*handle);
Dmitriy Ivanovb4827502015-09-28 16:38:31 -0700870 return false;
871 }
872
873 cache_[key] = *handle;
874 return true;
875}
876
877ZipArchiveCache::~ZipArchiveCache() {
Dmitriy Ivanov5dce8942015-10-13 12:14:16 -0700878 for (const auto& it : cache_) {
Dmitriy Ivanovb4827502015-09-28 16:38:31 -0700879 CloseArchive(it.second);
880 }
881}
882
883static int open_library_in_zipfile(ZipArchiveCache* zip_archive_cache,
Dmitriy Ivanova1feb112015-10-01 18:41:57 -0700884 const char* const input_path,
885 off64_t* file_offset, std::string* realpath) {
886 std::string normalized_path;
887 if (!normalize_path(input_path, &normalized_path)) {
888 return -1;
889 }
890
891 const char* const path = normalized_path.c_str();
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700892 TRACE("Trying zip file open from path \"%s\" -> normalized \"%s\"", input_path, path);
Simon Baldwinaef71952015-01-16 13:22:54 +0000893
Dmitriy Ivanov402a7502015-06-09 13:46:51 -0700894 // Treat an '!/' separator inside a path as the separator between the name
Simon Baldwinaef71952015-01-16 13:22:54 +0000895 // of the zip file on disk and the subdirectory to search within it.
Dmitriy Ivanov402a7502015-06-09 13:46:51 -0700896 // For example, if path is "foo.zip!/bar/bas/x.so", then we search for
Simon Baldwinaef71952015-01-16 13:22:54 +0000897 // "bar/bas/x.so" within "foo.zip".
Dmitriy Ivanova1feb112015-10-01 18:41:57 -0700898 const char* const separator = strstr(path, kZipFileSeparator);
Simon Baldwinaef71952015-01-16 13:22:54 +0000899 if (separator == nullptr) {
900 return -1;
Elliott Hughes124fae92012-10-31 14:20:03 -0700901 }
Simon Baldwinaef71952015-01-16 13:22:54 +0000902
903 char buf[512];
904 if (strlcpy(buf, path, sizeof(buf)) >= sizeof(buf)) {
905 PRINT("Warning: ignoring very long library path: %s", path);
906 return -1;
907 }
908
909 buf[separator - path] = '\0';
910
911 const char* zip_path = buf;
Dmitriy Ivanov402a7502015-06-09 13:46:51 -0700912 const char* file_path = &buf[separator - path + 2];
Simon Baldwinaef71952015-01-16 13:22:54 +0000913 int fd = TEMP_FAILURE_RETRY(open(zip_path, O_RDONLY | O_CLOEXEC));
914 if (fd == -1) {
915 return -1;
916 }
917
918 ZipArchiveHandle handle;
Dmitriy Ivanovb4827502015-09-28 16:38:31 -0700919 if (!zip_archive_cache->get_or_open(zip_path, &handle)) {
Simon Baldwinaef71952015-01-16 13:22:54 +0000920 // invalid zip-file (?)
921 close(fd);
922 return -1;
923 }
924
Simon Baldwinaef71952015-01-16 13:22:54 +0000925 ZipEntry entry;
926
Elliott Hughesb51bb502019-05-03 22:45:41 -0700927 if (FindEntry(handle, file_path, &entry) != 0) {
Simon Baldwinaef71952015-01-16 13:22:54 +0000928 // Entry was not found.
929 close(fd);
930 return -1;
931 }
932
933 // Check if it is properly stored
934 if (entry.method != kCompressStored || (entry.offset % PAGE_SIZE) != 0) {
935 close(fd);
936 return -1;
937 }
938
939 *file_offset = entry.offset;
Dmitriy Ivanova1feb112015-10-01 18:41:57 -0700940
941 if (realpath_fd(fd, realpath)) {
942 *realpath += separator;
943 } else {
Tom Cherry66bc4282018-11-08 13:40:52 -0800944 if (!is_first_stage_init()) {
945 PRINT("warning: unable to get realpath for the library \"%s\". Will use given path.",
946 normalized_path.c_str());
947 }
Dmitriy Ivanova1feb112015-10-01 18:41:57 -0700948 *realpath = normalized_path;
949 }
950
Simon Baldwinaef71952015-01-16 13:22:54 +0000951 return fd;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800952}
953
Dmitriy Ivanovd165f562015-03-23 18:43:02 -0700954static bool format_path(char* buf, size_t buf_size, const char* path, const char* name) {
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700955 int n = async_safe_format_buffer(buf, buf_size, "%s/%s", path, name);
Dmitriy Ivanovd165f562015-03-23 18:43:02 -0700956 if (n < 0 || n >= static_cast<int>(buf_size)) {
957 PRINT("Warning: ignoring very long library path: %s/%s", path, name);
958 return false;
959 }
Simon Baldwinaef71952015-01-16 13:22:54 +0000960
Dmitriy Ivanovd165f562015-03-23 18:43:02 -0700961 return true;
962}
963
Ryan Prichard8f639a42018-10-01 23:10:05 -0700964static int open_library_at_path(ZipArchiveCache* zip_archive_cache,
965 const char* path, off64_t* file_offset,
966 std::string* realpath) {
967 int fd = -1;
968 if (strstr(path, kZipFileSeparator) != nullptr) {
969 fd = open_library_in_zipfile(zip_archive_cache, path, file_offset, realpath);
970 }
971
972 if (fd == -1) {
973 fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC));
974 if (fd != -1) {
975 *file_offset = 0;
976 if (!realpath_fd(fd, realpath)) {
Tom Cherry66bc4282018-11-08 13:40:52 -0800977 if (!is_first_stage_init()) {
978 PRINT("warning: unable to get realpath for the library \"%s\". Will use given path.",
979 path);
980 }
Ryan Prichard8f639a42018-10-01 23:10:05 -0700981 *realpath = path;
982 }
983 }
984 }
985
986 return fd;
987}
988
Dmitriy Ivanovb4827502015-09-28 16:38:31 -0700989static int open_library_on_paths(ZipArchiveCache* zip_archive_cache,
990 const char* name, off64_t* file_offset,
Dmitriy Ivanova1feb112015-10-01 18:41:57 -0700991 const std::vector<std::string>& paths,
992 std::string* realpath) {
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -0700993 for (const auto& path : paths) {
Dmitriy Ivanovd165f562015-03-23 18:43:02 -0700994 char buf[512];
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -0700995 if (!format_path(buf, sizeof(buf), path.c_str(), name)) {
Dmitriy Ivanovd165f562015-03-23 18:43:02 -0700996 continue;
997 }
998
Ryan Prichard8f639a42018-10-01 23:10:05 -0700999 int fd = open_library_at_path(zip_archive_cache, buf, file_offset, realpath);
Dmitriy Ivanovd165f562015-03-23 18:43:02 -07001000 if (fd != -1) {
1001 return fd;
1002 }
Simon Baldwinaef71952015-01-16 13:22:54 +00001003 }
1004
Dmitriy Ivanovd165f562015-03-23 18:43:02 -07001005 return -1;
Simon Baldwinaef71952015-01-16 13:22:54 +00001006}
1007
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001008static int open_library(android_namespace_t* ns,
1009 ZipArchiveCache* zip_archive_cache,
Dmitriy Ivanovb4827502015-09-28 16:38:31 -07001010 const char* name, soinfo *needed_by,
Dmitriy Ivanova1feb112015-10-01 18:41:57 -07001011 off64_t* file_offset, std::string* realpath) {
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001012 TRACE("[ opening %s from namespace %s ]", name, ns->get_name());
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001013
Elliott Hughes124fae92012-10-31 14:20:03 -07001014 // 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 -07001015 if (strchr(name, '/') != nullptr) {
Ryan Prichardaa2db962020-03-24 20:25:53 -07001016 return open_library_at_path(zip_archive_cache, name, file_offset, realpath);
Elliott Hughes124fae92012-10-31 14:20:03 -07001017 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001018
Ryan Prichardaa2db962020-03-24 20:25:53 -07001019 // LD_LIBRARY_PATH has the highest priority. We don't have to check accessibility when searching
1020 // the namespace's path lists, because anything found on a namespace path list should always be
1021 // accessible.
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001022 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 -07001023
1024 // Try the DT_RUNPATH, and verify that the library is accessible.
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001025 if (fd == -1 && needed_by != nullptr) {
Dmitriy Ivanova1feb112015-10-01 18:41:57 -07001026 fd = open_library_on_paths(zip_archive_cache, name, file_offset, needed_by->get_dt_runpath(), realpath);
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001027 if (fd != -1 && !ns->is_accessible(*realpath)) {
Vic Yang48b69112018-10-24 14:14:26 -07001028 close(fd);
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001029 fd = -1;
1030 }
Evgenii Stepanov68650822015-06-10 13:38:39 -07001031 }
Dmitriy Ivanovb4827502015-09-28 16:38:31 -07001032
Ryan Prichardaa2db962020-03-24 20:25:53 -07001033 // Finally search the namespace's main search path list.
Elliott Hughes124fae92012-10-31 14:20:03 -07001034 if (fd == -1) {
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001035 fd = open_library_on_paths(zip_archive_cache, name, file_offset, ns->get_default_library_paths(), realpath);
Elliott Hughes124fae92012-10-31 14:20:03 -07001036 }
Dmitriy Ivanovb4827502015-09-28 16:38:31 -07001037
Elliott Hughes124fae92012-10-31 14:20:03 -07001038 return fd;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001039}
1040
Ryan Prichard8f639a42018-10-01 23:10:05 -07001041int open_executable(const char* path, off64_t* file_offset, std::string* realpath) {
1042 ZipArchiveCache zip_archive_cache;
1043 return open_library_at_path(&zip_archive_cache, path, file_offset, realpath);
1044}
1045
Dimitry Ivanov3f660572016-09-09 10:00:39 -07001046const char* fix_dt_needed(const char* dt_needed, const char* sopath __unused) {
Dmitriy Ivanovd974e882015-05-27 18:29:41 -07001047#if !defined(__LP64__)
1048 // Work around incorrect DT_NEEDED entries for old apps: http://b/21364029
Elliott Hughes9076b0c2018-02-28 11:29:45 -08001049 int app_target_api_level = get_application_target_sdk_version();
Elliott Hughes95c6cd72019-12-20 13:26:14 -08001050 if (app_target_api_level < 23) {
Dmitriy Ivanovd974e882015-05-27 18:29:41 -07001051 const char* bname = basename(dt_needed);
1052 if (bname != dt_needed) {
Elliott Hughes95c6cd72019-12-20 13:26:14 -08001053 DL_WARN_documented_change(23,
Elliott Hughes9076b0c2018-02-28 11:29:45 -08001054 "invalid-dt_needed-entries-enforced-for-api-level-23",
1055 "library \"%s\" has invalid DT_NEEDED entry \"%s\"",
1056 sopath, dt_needed, app_target_api_level);
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07001057 add_dlwarning(sopath, "invalid DT_NEEDED entry", dt_needed);
Dmitriy Ivanovd974e882015-05-27 18:29:41 -07001058 }
1059
1060 return bname;
1061 }
1062#endif
1063 return dt_needed;
1064}
1065
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001066template<typename F>
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001067static void for_each_dt_needed(const ElfReader& elf_reader, F action) {
1068 for (const ElfW(Dyn)* d = elf_reader.dynamic(); d->d_tag != DT_NULL; ++d) {
1069 if (d->d_tag == DT_NEEDED) {
1070 action(fix_dt_needed(elf_reader.get_string(d->d_un.d_val), elf_reader.name()));
1071 }
1072 }
1073}
1074
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001075static bool find_loaded_library_by_inode(android_namespace_t* ns,
1076 const struct stat& file_stat,
1077 off64_t file_offset,
1078 bool search_linked_namespaces,
1079 soinfo** candidate) {
Vic Yang3ec16be2019-06-02 21:10:53 -07001080 if (file_stat.st_dev == 0 || file_stat.st_ino == 0) {
1081 *candidate = nullptr;
1082 return false;
1083 }
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001084
1085 auto predicate = [&](soinfo* si) {
Vic Yang3ec16be2019-06-02 21:10:53 -07001086 return si->get_st_ino() == file_stat.st_ino &&
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001087 si->get_st_dev() == file_stat.st_dev &&
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001088 si->get_file_offset() == file_offset;
1089 };
1090
1091 *candidate = ns->soinfo_list().find_if(predicate);
1092
1093 if (*candidate == nullptr && search_linked_namespaces) {
1094 for (auto& link : ns->linked_namespaces()) {
1095 android_namespace_t* linked_ns = link.linked_namespace();
1096 soinfo* si = linked_ns->soinfo_list().find_if(predicate);
1097
1098 if (si != nullptr && link.is_accessible(si->get_soname())) {
1099 *candidate = si;
1100 return true;
1101 }
1102 }
1103 }
1104
1105 return *candidate != nullptr;
1106}
1107
Evgenii Stepanov9e77a642017-07-27 14:55:44 -07001108static bool find_loaded_library_by_realpath(android_namespace_t* ns, const char* realpath,
1109 bool search_linked_namespaces, soinfo** candidate) {
1110 auto predicate = [&](soinfo* si) { return strcmp(realpath, si->get_realpath()) == 0; };
1111
1112 *candidate = ns->soinfo_list().find_if(predicate);
1113
1114 if (*candidate == nullptr && search_linked_namespaces) {
1115 for (auto& link : ns->linked_namespaces()) {
1116 android_namespace_t* linked_ns = link.linked_namespace();
1117 soinfo* si = linked_ns->soinfo_list().find_if(predicate);
1118
1119 if (si != nullptr && link.is_accessible(si->get_soname())) {
1120 *candidate = si;
1121 return true;
1122 }
1123 }
1124 }
1125
1126 return *candidate != nullptr;
1127}
1128
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001129static bool load_library(android_namespace_t* ns,
1130 LoadTask* task,
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001131 LoadTaskList* load_tasks,
1132 int rtld_flags,
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001133 const std::string& realpath,
1134 bool search_linked_namespaces) {
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001135 off64_t file_offset = task->get_file_offset();
1136 const char* name = task->get_name();
1137 const android_dlextinfo* extinfo = task->get_extinfo();
1138
Martin Stjernholm9fe38262019-08-27 17:08:45 +01001139 LD_LOG(kLogDlopen,
1140 "load_library(ns=%s, task=%s, flags=0x%x, realpath=%s, search_linked_namespaces=%d)",
1141 ns->get_name(), name, rtld_flags, realpath.c_str(), search_linked_namespaces);
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001142
Dmitriy Ivanov07e5bc12014-10-03 17:52:44 -07001143 if ((file_offset % PAGE_SIZE) != 0) {
Martin Stjernholm9fe38262019-08-27 17:08:45 +01001144 DL_OPEN_ERR("file offset for the library \"%s\" is not page-aligned: %" PRId64, name, file_offset);
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001145 return false;
Dmitriy Ivanov07e5bc12014-10-03 17:52:44 -07001146 }
Yabin Cui16f7f8d2014-11-04 11:08:05 -08001147 if (file_offset < 0) {
Martin Stjernholm9fe38262019-08-27 17:08:45 +01001148 DL_OPEN_ERR("file offset for the library \"%s\" is negative: %" PRId64, name, file_offset);
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001149 return false;
Yabin Cui16f7f8d2014-11-04 11:08:05 -08001150 }
Dmitriy Ivanov07e5bc12014-10-03 17:52:44 -07001151
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001152 struct stat file_stat;
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001153 if (TEMP_FAILURE_RETRY(fstat(task->get_fd(), &file_stat)) != 0) {
Martin Stjernholm9fe38262019-08-27 17:08:45 +01001154 DL_OPEN_ERR("unable to stat file for the library \"%s\": %s", name, strerror(errno));
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001155 return false;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001156 }
Yabin Cui16f7f8d2014-11-04 11:08:05 -08001157 if (file_offset >= file_stat.st_size) {
Martin Stjernholm9fe38262019-08-27 17:08:45 +01001158 DL_OPEN_ERR("file offset for the library \"%s\" >= file size: %" PRId64 " >= %" PRId64,
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07001159 name, file_offset, file_stat.st_size);
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001160 return false;
Yabin Cui16f7f8d2014-11-04 11:08:05 -08001161 }
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001162
1163 // Check for symlink and other situations where
Dmitriy Ivanov9b821362015-04-02 16:03:56 -07001164 // file can have different names, unless ANDROID_DLEXT_FORCE_LOAD is set
1165 if (extinfo == nullptr || (extinfo->flags & ANDROID_DLEXT_FORCE_LOAD) == 0) {
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001166 soinfo* si = nullptr;
1167 if (find_loaded_library_by_inode(ns, file_stat, file_offset, search_linked_namespaces, &si)) {
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001168 LD_LOG(kLogDlopen,
1169 "load_library(ns=%s, task=%s): Already loaded under different name/path \"%s\" - "
1170 "will return existing soinfo",
1171 ns->get_name(), name, si->get_realpath());
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001172 task->set_soinfo(si);
1173 return true;
1174 }
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001175 }
Dmitriy Ivanovd59e5002014-05-09 09:10:14 -07001176
Dmitriy Ivanove8ba50f2014-09-15 17:00:10 -07001177 if ((rtld_flags & RTLD_NOLOAD) != 0) {
Martin Stjernholm9fe38262019-08-27 17:08:45 +01001178 DL_OPEN_ERR("library \"%s\" wasn't loaded and RTLD_NOLOAD prevented it", name);
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001179 return false;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001180 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001181
Dimitry Ivanovbf34ba32017-04-21 13:12:05 -07001182 struct statfs fs_stat;
1183 if (TEMP_FAILURE_RETRY(fstatfs(task->get_fd(), &fs_stat)) != 0) {
Martin Stjernholm9fe38262019-08-27 17:08:45 +01001184 DL_OPEN_ERR("unable to fstatfs file for the library \"%s\": %s", name, strerror(errno));
Dimitry Ivanovbf34ba32017-04-21 13:12:05 -07001185 return false;
1186 }
1187
1188 // do not check accessibility using realpath if fd is located on tmpfs
1189 // this enables use of memfd_create() for apps
1190 if ((fs_stat.f_type != TMPFS_MAGIC) && (!ns->is_accessible(realpath))) {
Ryan Prichardaff9a342020-08-03 15:29:12 -07001191 // TODO(dimitry): workaround for http://b/26394120 - the exempt-list
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001192
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07001193 const soinfo* needed_by = task->is_dt_needed() ? task->get_needed_by() : nullptr;
Ryan Prichardaff9a342020-08-03 15:29:12 -07001194 if (is_exempt_lib(ns, name, needed_by)) {
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07001195 // print warning only if needed by non-system library
1196 if (needed_by == nullptr || !is_system_library(needed_by->get_realpath())) {
1197 const soinfo* needed_or_dlopened_by = task->get_needed_by();
1198 const char* sopath = needed_or_dlopened_by == nullptr ? "(unknown)" :
1199 needed_or_dlopened_by->get_realpath();
Elliott Hughes95c6cd72019-12-20 13:26:14 -08001200 DL_WARN_documented_change(24,
Elliott Hughes9076b0c2018-02-28 11:29:45 -08001201 "private-api-enforced-for-api-level-24",
1202 "library \"%s\" (\"%s\") needed or dlopened by \"%s\" "
1203 "is not accessible by namespace \"%s\"",
1204 name, realpath.c_str(), sopath, ns->get_name());
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07001205 add_dlwarning(sopath, "unauthorized access to", name);
1206 }
1207 } else {
1208 // do not load libraries if they are not accessible for the specified namespace.
1209 const char* needed_or_dlopened_by = task->get_needed_by() == nullptr ?
1210 "(unknown)" :
1211 task->get_needed_by()->get_realpath();
Dimitry Ivanovd17a3772016-03-01 13:11:28 -08001212
Martin Stjernholm9fe38262019-08-27 17:08:45 +01001213 DL_OPEN_ERR("library \"%s\" needed or dlopened by \"%s\" is not accessible for the namespace \"%s\"",
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07001214 name, needed_or_dlopened_by, ns->get_name());
Dimitry Ivanovd17a3772016-03-01 13:11:28 -08001215
Dimitry Ivanov35c8e3b2017-02-27 12:17:47 -08001216 // do not print this if a library is in the list of shared libraries for linked namespaces
1217 if (!maybe_accessible_via_namespace_links(ns, name)) {
1218 PRINT("library \"%s\" (\"%s\") needed or dlopened by \"%s\" is not accessible for the"
1219 " namespace: [name=\"%s\", ld_library_paths=\"%s\", default_library_paths=\"%s\","
1220 " permitted_paths=\"%s\"]",
1221 name, realpath.c_str(),
1222 needed_or_dlopened_by,
1223 ns->get_name(),
1224 android::base::Join(ns->get_ld_library_paths(), ':').c_str(),
1225 android::base::Join(ns->get_default_library_paths(), ':').c_str(),
1226 android::base::Join(ns->get_permitted_paths(), ':').c_str());
1227 }
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07001228 return false;
1229 }
Dimitry Ivanov22840aa2015-12-04 18:28:49 -08001230 }
1231
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001232 soinfo* si = soinfo_alloc(ns, realpath.c_str(), &file_stat, file_offset, rtld_flags);
Dmitriy Ivanovd59e5002014-05-09 09:10:14 -07001233
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001234 task->set_soinfo(si);
1235
1236 // Read the ELF header and some of the segments.
1237 if (!task->read(realpath.c_str(), file_stat.st_size)) {
Ryan Prichard4fa6d992020-03-26 21:31:43 -07001238 task->remove_cached_elf_reader();
Dmitriy Ivanovfd7a91e2015-11-06 10:44:37 -08001239 task->set_soinfo(nullptr);
Ryan Prichard4fa6d992020-03-26 21:31:43 -07001240 soinfo_free(si);
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001241 return false;
1242 }
1243
Ryan Prichard058eb8f2020-12-17 22:59:04 -08001244 // Find and set DT_RUNPATH, DT_SONAME, and DT_FLAGS_1.
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001245 // Note that these field values are temporary and are
1246 // going to be overwritten on soinfo::prelink_image
1247 // with values from PT_LOAD segments.
1248 const ElfReader& elf_reader = task->get_elf_reader();
1249 for (const ElfW(Dyn)* d = elf_reader.dynamic(); d->d_tag != DT_NULL; ++d) {
1250 if (d->d_tag == DT_RUNPATH) {
1251 si->set_dt_runpath(elf_reader.get_string(d->d_un.d_val));
1252 }
1253 if (d->d_tag == DT_SONAME) {
1254 si->set_soname(elf_reader.get_string(d->d_un.d_val));
1255 }
Ryan Prichard058eb8f2020-12-17 22:59:04 -08001256 // We need to identify a DF_1_GLOBAL library early so we can link it to namespaces.
1257 if (d->d_tag == DT_FLAGS_1) {
1258 si->set_dt_flags_1(d->d_un.d_val);
1259 }
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001260 }
1261
Dan Willemsen5038ef62018-10-21 17:45:04 -07001262#if !defined(__ANDROID__)
1263 // Bionic on the host currently uses some Android prebuilts, which don't set
1264 // DT_RUNPATH with any relative paths, so they can't find their dependencies.
1265 // b/118058804
1266 if (si->get_dt_runpath().empty()) {
1267 si->set_dt_runpath("$ORIGIN/../lib64:$ORIGIN/lib64");
1268 }
1269#endif
1270
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001271 for_each_dt_needed(task->get_elf_reader(), [&](const char* name) {
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001272 LD_LOG(kLogDlopen, "load_library(ns=%s, task=%s): Adding DT_NEEDED task: %s",
1273 ns->get_name(), task->get_name(), name);
Jiyong Park02586a22017-05-20 01:01:24 +09001274 load_tasks->push_back(LoadTask::create(name, si, ns, task->get_readers_map()));
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001275 });
Dmitriy Ivanovd59e5002014-05-09 09:10:14 -07001276
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001277 return true;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001278}
1279
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001280static bool load_library(android_namespace_t* ns,
1281 LoadTask* task,
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001282 ZipArchiveCache* zip_archive_cache,
1283 LoadTaskList* load_tasks,
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001284 int rtld_flags,
1285 bool search_linked_namespaces) {
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001286 const char* name = task->get_name();
1287 soinfo* needed_by = task->get_needed_by();
1288 const android_dlextinfo* extinfo = task->get_extinfo();
1289
Spencer Low0346ad72015-04-22 18:06:51 -07001290 if (extinfo != nullptr && (extinfo->flags & ANDROID_DLEXT_USE_LIBRARY_FD) != 0) {
Ryan Prichardaa2db962020-03-24 20:25:53 -07001291 off64_t file_offset = 0;
Spencer Low0346ad72015-04-22 18:06:51 -07001292 if ((extinfo->flags & ANDROID_DLEXT_USE_LIBRARY_FD_OFFSET) != 0) {
1293 file_offset = extinfo->library_fd_offset;
1294 }
Dmitriy Ivanova1feb112015-10-01 18:41:57 -07001295
Ryan Prichardaa2db962020-03-24 20:25:53 -07001296 std::string realpath;
Dmitriy Ivanova1feb112015-10-01 18:41:57 -07001297 if (!realpath_fd(extinfo->library_fd, &realpath)) {
Tom Cherry66bc4282018-11-08 13:40:52 -08001298 if (!is_first_stage_init()) {
1299 PRINT(
1300 "warning: unable to get realpath for the library \"%s\" by extinfo->library_fd. "
1301 "Will use given name.",
1302 name);
1303 }
Dmitriy Ivanova1feb112015-10-01 18:41:57 -07001304 realpath = name;
1305 }
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001306
1307 task->set_fd(extinfo->library_fd, false);
1308 task->set_file_offset(file_offset);
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001309 return load_library(ns, task, load_tasks, rtld_flags, realpath, search_linked_namespaces);
Spencer Low0346ad72015-04-22 18:06:51 -07001310 }
1311
Martin Stjernholm9fe38262019-08-27 17:08:45 +01001312 LD_LOG(kLogDlopen,
1313 "load_library(ns=%s, task=%s, flags=0x%x, search_linked_namespaces=%d): calling "
Ryan Prichardaa2db962020-03-24 20:25:53 -07001314 "open_library",
1315 ns->get_name(), name, rtld_flags, search_linked_namespaces);
Martin Stjernholm9fe38262019-08-27 17:08:45 +01001316
Spencer Low0346ad72015-04-22 18:06:51 -07001317 // Open the file.
Ryan Prichardaa2db962020-03-24 20:25:53 -07001318 off64_t file_offset;
1319 std::string realpath;
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001320 int fd = open_library(ns, zip_archive_cache, name, needed_by, &file_offset, &realpath);
Spencer Low0346ad72015-04-22 18:06:51 -07001321 if (fd == -1) {
Josh Gao16269572019-10-29 13:41:00 -07001322 if (task->is_dt_needed()) {
1323 if (needed_by->is_main_executable()) {
1324 DL_OPEN_ERR("library \"%s\" not found: needed by main executable", name);
1325 } else {
1326 DL_OPEN_ERR("library \"%s\" not found: needed by %s in namespace %s", name,
1327 needed_by->get_realpath(), task->get_start_from()->get_name());
1328 }
1329 } else {
1330 DL_OPEN_ERR("library \"%s\" not found", name);
1331 }
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001332 return false;
Spencer Low0346ad72015-04-22 18:06:51 -07001333 }
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001334
1335 task->set_fd(fd, true);
1336 task->set_file_offset(file_offset);
1337
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001338 return load_library(ns, task, load_tasks, rtld_flags, realpath, search_linked_namespaces);
Spencer Low0346ad72015-04-22 18:06:51 -07001339}
1340
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001341static bool find_loaded_library_by_soname(android_namespace_t* ns,
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001342 const char* name,
1343 soinfo** candidate) {
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001344 return !ns->soinfo_list().visit([&](soinfo* si) {
Elliott Hughesf9dd1a72021-01-11 09:04:58 -08001345 if (strcmp(name, si->get_soname()) == 0) {
Dimitry Ivanov3bd90612017-02-01 08:54:43 -08001346 *candidate = si;
1347 return false;
Ard Biesheuvel12c78bb2012-08-14 12:30:09 +02001348 }
Dmitriy Ivanova9703332015-06-16 15:38:21 -07001349
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001350 return true;
1351 });
Ard Biesheuvel12c78bb2012-08-14 12:30:09 +02001352}
1353
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001354// Returns true if library was found and false otherwise
1355static bool find_loaded_library_by_soname(android_namespace_t* ns,
1356 const char* name,
1357 bool search_linked_namespaces,
1358 soinfo** candidate) {
1359 *candidate = nullptr;
1360
1361 // Ignore filename with path.
1362 if (strchr(name, '/') != nullptr) {
1363 return false;
1364 }
1365
1366 bool found = find_loaded_library_by_soname(ns, name, candidate);
1367
1368 if (!found && search_linked_namespaces) {
1369 // if a library was not found - look into linked namespaces
1370 for (auto& link : ns->linked_namespaces()) {
1371 if (!link.is_accessible(name)) {
1372 continue;
1373 }
1374
1375 android_namespace_t* linked_ns = link.linked_namespace();
1376
1377 if (find_loaded_library_by_soname(linked_ns, name, candidate)) {
1378 return true;
1379 }
1380 }
1381 }
1382
1383 return found;
1384}
1385
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001386static bool find_library_in_linked_namespace(const android_namespace_link_t& namespace_link,
Jiyong Park02586a22017-05-20 01:01:24 +09001387 LoadTask* task) {
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001388 android_namespace_t* ns = namespace_link.linked_namespace();
1389
1390 soinfo* candidate;
1391 bool loaded = false;
1392
1393 std::string soname;
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001394 if (find_loaded_library_by_soname(ns, task->get_name(), false, &candidate)) {
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001395 loaded = true;
1396 soname = candidate->get_soname();
1397 } else {
1398 soname = resolve_soname(task->get_name());
1399 }
1400
1401 if (!namespace_link.is_accessible(soname.c_str())) {
1402 // the library is not accessible via namespace_link
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001403 LD_LOG(kLogDlopen,
1404 "find_library_in_linked_namespace(ns=%s, task=%s): Not accessible (soname=%s)",
1405 ns->get_name(), task->get_name(), soname.c_str());
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001406 return false;
1407 }
1408
1409 // if library is already loaded - return it
1410 if (loaded) {
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001411 LD_LOG(kLogDlopen, "find_library_in_linked_namespace(ns=%s, task=%s): Already loaded",
1412 ns->get_name(), task->get_name());
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001413 task->set_soinfo(candidate);
1414 return true;
1415 }
1416
Jiyong Park02586a22017-05-20 01:01:24 +09001417 // returning true with empty soinfo means that the library is okay to be
Logan Chien9ee45912018-01-18 12:05:09 +08001418 // loaded in the namespace but has not yet been loaded there before.
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001419 LD_LOG(kLogDlopen, "find_library_in_linked_namespace(ns=%s, task=%s): Ok to load", ns->get_name(),
1420 task->get_name());
Jiyong Park02586a22017-05-20 01:01:24 +09001421 task->set_soinfo(nullptr);
1422 return true;
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001423}
1424
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001425static bool find_library_internal(android_namespace_t* ns,
1426 LoadTask* task,
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001427 ZipArchiveCache* zip_archive_cache,
1428 LoadTaskList* load_tasks,
Ryan Prichard323d7df2020-03-24 21:19:06 -07001429 int rtld_flags) {
Dmitriy Ivanova9703332015-06-16 15:38:21 -07001430 soinfo* candidate;
1431
Ryan Prichard323d7df2020-03-24 21:19:06 -07001432 if (find_loaded_library_by_soname(ns, task->get_name(), true /* search_linked_namespaces */,
1433 &candidate)) {
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001434 LD_LOG(kLogDlopen,
1435 "find_library_internal(ns=%s, task=%s): Already loaded (by soname): %s",
1436 ns->get_name(), task->get_name(), candidate->get_realpath());
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001437 task->set_soinfo(candidate);
1438 return true;
Dmitriy Ivanova9703332015-06-16 15:38:21 -07001439 }
Dmitriy Ivanovb648a8a2014-05-19 15:06:58 -07001440
1441 // Library might still be loaded, the accurate detection
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001442 // of this fact is done by load_library.
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001443 TRACE("[ \"%s\" find_loaded_library_by_soname failed (*candidate=%s@%p). Trying harder... ]",
1444 task->get_name(), candidate == nullptr ? "n/a" : candidate->get_realpath(), candidate);
Dmitriy Ivanova9703332015-06-16 15:38:21 -07001445
Ryan Prichard323d7df2020-03-24 21:19:06 -07001446 if (load_library(ns, task, zip_archive_cache, load_tasks, rtld_flags,
1447 true /* search_linked_namespaces */)) {
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001448 return true;
1449 }
1450
Ryan Prichardaff9a342020-08-03 15:29:12 -07001451 // TODO(dimitry): workaround for http://b/26394120 (the exempt-list)
1452 if (ns->is_exempt_list_enabled() && is_exempt_lib(ns, task->get_name(), task->get_needed_by())) {
1453 // For the libs in the exempt-list, switch to the default namespace and then
Jiyong Parkefc503d2019-02-12 01:08:57 +09001454 // try the load again from there. The library could be loaded from the
1455 // default namespace or from another namespace (e.g. runtime) that is linked
1456 // from the default namespace.
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001457 LD_LOG(kLogDlopen,
Ryan Prichardaff9a342020-08-03 15:29:12 -07001458 "find_library_internal(ns=%s, task=%s): Exempt system library - trying namespace %s",
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001459 ns->get_name(), task->get_name(), g_default_namespace.get_name());
Jiyong Parkefc503d2019-02-12 01:08:57 +09001460 ns = &g_default_namespace;
1461 if (load_library(ns, task, zip_archive_cache, load_tasks, rtld_flags,
Ryan Prichard323d7df2020-03-24 21:19:06 -07001462 true /* search_linked_namespaces */)) {
Jiyong Parkefc503d2019-02-12 01:08:57 +09001463 return true;
1464 }
1465 }
1466 // END OF WORKAROUND
1467
Ryan Prichard323d7df2020-03-24 21:19:06 -07001468 // if a library was not found - look into linked namespaces
1469 // preserve current dlerror in the case it fails.
1470 DlErrorRestorer dlerror_restorer;
1471 LD_LOG(kLogDlopen, "find_library_internal(ns=%s, task=%s): Trying %zu linked namespaces",
1472 ns->get_name(), task->get_name(), ns->linked_namespaces().size());
1473 for (auto& linked_namespace : ns->linked_namespaces()) {
1474 if (find_library_in_linked_namespace(linked_namespace, task)) {
1475 // Library is already loaded.
1476 if (task->get_soinfo() != nullptr) {
1477 // n.b. This code path runs when find_library_in_linked_namespace found an already-loaded
Ryan Prichardaff9a342020-08-03 15:29:12 -07001478 // library by soname. That should only be possible with a exempt-list lookup, where we
1479 // switch the namespace, because otherwise, find_library_in_linked_namespace is duplicating
1480 // the soname scan done in this function's first call to find_loaded_library_by_soname.
Ryan Prichard323d7df2020-03-24 21:19:06 -07001481 return true;
1482 }
1483
1484 if (load_library(linked_namespace.linked_namespace(), task, zip_archive_cache, load_tasks,
1485 rtld_flags, false /* search_linked_namespaces */)) {
1486 LD_LOG(kLogDlopen, "find_library_internal(ns=%s, task=%s): Found in linked namespace %s",
1487 ns->get_name(), task->get_name(), linked_namespace.linked_namespace()->get_name());
1488 return true;
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001489 }
1490 }
1491 }
1492
1493 return false;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001494}
1495
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001496static void soinfo_unload(soinfo* si);
1497
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001498static void shuffle(std::vector<LoadTask*>* v) {
Tom Cherry66bc4282018-11-08 13:40:52 -08001499 if (is_first_stage_init()) {
1500 // arc4random* is not available in first stage init because /dev/random
1501 // hasn't yet been created.
Jiyong Park31cd08f2018-06-01 19:18:56 +09001502 return;
1503 }
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001504 for (size_t i = 0, size = v->size(); i < size; ++i) {
1505 size_t n = size - i;
1506 size_t r = arc4random_uniform(n);
1507 std::swap((*v)[n-1], (*v)[r]);
1508 }
1509}
1510
Evgenii Stepanov0cdef7e2015-07-06 17:56:31 -07001511// add_as_children - add first-level loaded libraries (i.e. library_names[], but
1512// not their transitive dependencies) as children of the start_with library.
1513// This is false when find_libraries is called for dlopen(), when newly loaded
1514// libraries must form a disjoint tree.
Dimitry Ivanov3f660572016-09-09 10:00:39 -07001515bool find_libraries(android_namespace_t* ns,
1516 soinfo* start_with,
1517 const char* const library_names[],
1518 size_t library_names_count,
1519 soinfo* soinfos[],
1520 std::vector<soinfo*>* ld_preloads,
1521 size_t ld_preloads_count,
1522 int rtld_flags,
1523 const android_dlextinfo* extinfo,
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001524 bool add_as_children,
Jiyong Park02586a22017-05-20 01:01:24 +09001525 std::vector<android_namespace_t*>* namespaces) {
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001526 // Step 0: prepare.
dimitry965d06d2017-11-28 16:03:07 +01001527 std::unordered_map<const soinfo*, ElfReader> readers_map;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001528 LoadTaskList load_tasks;
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001529
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -07001530 for (size_t i = 0; i < library_names_count; ++i) {
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001531 const char* name = library_names[i];
Jiyong Park02586a22017-05-20 01:01:24 +09001532 load_tasks.push_back(LoadTask::create(name, start_with, ns, &readers_map));
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001533 }
1534
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -07001535 // If soinfos array is null allocate one on stack.
1536 // The array is needed in case of failure; for example
1537 // when library_names[] = {libone.so, libtwo.so} and libone.so
1538 // is loaded correctly but libtwo.so failed for some reason.
1539 // In this case libone.so should be unloaded on return.
1540 // See also implementation of failure_guard below.
1541
1542 if (soinfos == nullptr) {
1543 size_t soinfos_size = sizeof(soinfo*)*library_names_count;
1544 soinfos = reinterpret_cast<soinfo**>(alloca(soinfos_size));
1545 memset(soinfos, 0, soinfos_size);
1546 }
1547
1548 // list of libraries to link - see step 2.
1549 size_t soinfos_count = 0;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001550
Tom Cherryb8ab6182017-04-05 16:20:29 -07001551 auto scope_guard = android::base::make_scope_guard([&]() {
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001552 for (LoadTask* t : load_tasks) {
1553 LoadTask::deleter(t);
1554 }
1555 });
1556
Dmitriy Ivanovb4827502015-09-28 16:38:31 -07001557 ZipArchiveCache zip_archive_cache;
Ryan Prichard058eb8f2020-12-17 22:59:04 -08001558 soinfo_list_t new_global_group_members;
Dmitriy Ivanovb4827502015-09-28 16:38:31 -07001559
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001560 // Step 1: expand the list of load_tasks to include
1561 // all DT_NEEDED libraries (do not load them just yet)
1562 for (size_t i = 0; i<load_tasks.size(); ++i) {
1563 LoadTask* task = load_tasks[i];
Evgenii Stepanov68650822015-06-10 13:38:39 -07001564 soinfo* needed_by = task->get_needed_by();
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001565
Dmitriy Ivanovedfc9f62015-09-02 16:32:02 -07001566 bool is_dt_needed = needed_by != nullptr && (needed_by != start_with || add_as_children);
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001567 task->set_extinfo(is_dt_needed ? nullptr : extinfo);
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07001568 task->set_dt_needed(is_dt_needed);
Dmitriy Ivanovedfc9f62015-09-02 16:32:02 -07001569
Jiyong Park02586a22017-05-20 01:01:24 +09001570 // Note: start from the namespace that is stored in the LoadTask. This namespace
1571 // is different from the current namespace when the LoadTask is for a transitive
1572 // dependency and the lib that created the LoadTask is not found in the
Martin Stjernholm964b14c2022-09-30 20:39:14 +01001573 // current namespace but in one of the linked namespaces.
1574 android_namespace_t* start_ns = const_cast<android_namespace_t*>(task->get_start_from());
1575
1576 LD_LOG(kLogDlopen, "find_library_internal(ns=%s@%p): task=%s, is_dt_needed=%d",
1577 start_ns->get_name(), start_ns, task->get_name(), is_dt_needed);
1578
1579 if (!find_library_internal(start_ns, task, &zip_archive_cache, &load_tasks, rtld_flags)) {
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001580 return false;
1581 }
1582
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001583 soinfo* si = task->get_soinfo();
1584
Dmitriy Ivanovedfc9f62015-09-02 16:32:02 -07001585 if (is_dt_needed) {
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001586 needed_by->add_child(si);
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08001587 }
1588
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -07001589 // When ld_preloads is not null, the first
1590 // ld_preloads_count libs are in fact ld_preloads.
Ryan Prichard058eb8f2020-12-17 22:59:04 -08001591 bool is_ld_preload = false;
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -07001592 if (ld_preloads != nullptr && soinfos_count < ld_preloads_count) {
Dmitriy Ivanovd165f562015-03-23 18:43:02 -07001593 ld_preloads->push_back(si);
Ryan Prichard058eb8f2020-12-17 22:59:04 -08001594 is_ld_preload = true;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001595 }
1596
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -07001597 if (soinfos_count < library_names_count) {
1598 soinfos[soinfos_count++] = si;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001599 }
Ryan Prichard058eb8f2020-12-17 22:59:04 -08001600
1601 // Add the new global group members to all initial namespaces. Do this secondary namespace setup
1602 // at the same time that libraries are added to their primary namespace so that the order of
1603 // global group members is the same in the every namespace. Only add a library to a namespace
1604 // once, even if it appears multiple times in the dependency graph.
1605 if (is_ld_preload || (si->get_dt_flags_1() & DF_1_GLOBAL) != 0) {
1606 if (!si->is_linked() && namespaces != nullptr && !new_global_group_members.contains(si)) {
1607 new_global_group_members.push_back(si);
1608 for (auto linked_ns : *namespaces) {
1609 if (si->get_primary_namespace() != linked_ns) {
1610 linked_ns->add_soinfo(si);
1611 si->add_secondary_namespace(linked_ns);
1612 }
1613 }
1614 }
1615 }
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001616 }
1617
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001618 // Step 2: Load libraries in random order (see b/24047022)
1619 LoadTaskList load_list;
1620 for (auto&& task : load_tasks) {
1621 soinfo* si = task->get_soinfo();
1622 auto pred = [&](const LoadTask* t) {
1623 return t->get_soinfo() == si;
1624 };
1625
1626 if (!si->is_linked() &&
1627 std::find_if(load_list.begin(), load_list.end(), pred) == load_list.end() ) {
1628 load_list.push_back(task);
1629 }
1630 }
Torne (Richard Coles)efbe9a52018-10-17 15:59:38 -04001631 bool reserved_address_recursive = false;
1632 if (extinfo) {
1633 reserved_address_recursive = extinfo->flags & ANDROID_DLEXT_RESERVED_ADDRESS_RECURSIVE;
1634 }
1635 if (!reserved_address_recursive) {
1636 // Shuffle the load order in the normal case, but not if we are loading all
1637 // the libraries to a reserved address range.
1638 shuffle(&load_list);
1639 }
1640
1641 // Set up address space parameters.
1642 address_space_params extinfo_params, default_params;
1643 size_t relro_fd_offset = 0;
1644 if (extinfo) {
1645 if (extinfo->flags & ANDROID_DLEXT_RESERVED_ADDRESS) {
1646 extinfo_params.start_addr = extinfo->reserved_addr;
1647 extinfo_params.reserved_size = extinfo->reserved_size;
1648 extinfo_params.must_use_address = true;
1649 } else if (extinfo->flags & ANDROID_DLEXT_RESERVED_ADDRESS_HINT) {
1650 extinfo_params.start_addr = extinfo->reserved_addr;
1651 extinfo_params.reserved_size = extinfo->reserved_size;
1652 }
1653 }
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001654
1655 for (auto&& task : load_list) {
Torne (Richard Coles)efbe9a52018-10-17 15:59:38 -04001656 address_space_params* address_space =
1657 (reserved_address_recursive || !task->is_dt_needed()) ? &extinfo_params : &default_params;
1658 if (!task->load(address_space)) {
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001659 return false;
1660 }
1661 }
1662
1663 // Step 3: pre-link all DT_NEEDED libraries in breadth first order.
1664 for (auto&& task : load_tasks) {
1665 soinfo* si = task->get_soinfo();
1666 if (!si->is_linked() && !si->prelink_image()) {
1667 return false;
1668 }
Ryan Pricharde5e69e02019-01-01 18:53:48 -08001669 register_soinfo_tls(si);
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001670 }
1671
Ryan Prichard058eb8f2020-12-17 22:59:04 -08001672 // Step 4: Construct the global group. DF_1_GLOBAL bit is force set for LD_PRELOADed libs because
1673 // they must be added to the global group. Note: The DF_1_GLOBAL bit for a library is normally set
1674 // in step 3.
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001675 if (ld_preloads != nullptr) {
1676 for (auto&& si : *ld_preloads) {
1677 si->set_dt_flags_1(si->get_dt_flags_1() | DF_1_GLOBAL);
1678 }
1679 }
1680
dimitry965d06d2017-11-28 16:03:07 +01001681 // Step 5: Collect roots of local_groups.
1682 // Whenever needed_by->si link crosses a namespace boundary it forms its own local_group.
1683 // Here we collect new roots to link them separately later on. Note that we need to avoid
1684 // collecting duplicates. Also the order is important. They need to be linked in the same
1685 // BFS order we link individual libraries.
1686 std::vector<soinfo*> local_group_roots;
1687 if (start_with != nullptr && add_as_children) {
1688 local_group_roots.push_back(start_with);
1689 } else {
1690 CHECK(soinfos_count == 1);
1691 local_group_roots.push_back(soinfos[0]);
1692 }
1693
Jiyong Park02586a22017-05-20 01:01:24 +09001694 for (auto&& task : load_tasks) {
1695 soinfo* si = task->get_soinfo();
dimitry965d06d2017-11-28 16:03:07 +01001696 soinfo* needed_by = task->get_needed_by();
1697 bool is_dt_needed = needed_by != nullptr && (needed_by != start_with || add_as_children);
1698 android_namespace_t* needed_by_ns =
1699 is_dt_needed ? needed_by->get_primary_namespace() : ns;
1700
1701 if (!si->is_linked() && si->get_primary_namespace() != needed_by_ns) {
1702 auto it = std::find(local_group_roots.begin(), local_group_roots.end(), si);
1703 LD_LOG(kLogDlopen,
1704 "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",
1705 si->get_realpath(),
1706 si,
1707 si->get_primary_namespace()->get_name(),
1708 si->get_primary_namespace(),
1709 needed_by == nullptr ? "(nullptr)" : needed_by->get_realpath(),
1710 needed_by,
1711 ns->get_name(),
1712 ns,
1713 needed_by_ns->get_name(),
1714 needed_by_ns,
1715 it == local_group_roots.end() ? "yes" : "no");
1716
1717 if (it == local_group_roots.end()) {
1718 local_group_roots.push_back(si);
Jiyong Park02586a22017-05-20 01:01:24 +09001719 }
1720 }
1721 }
1722
dimitry965d06d2017-11-28 16:03:07 +01001723 // Step 6: Link all local groups
1724 for (auto root : local_group_roots) {
1725 soinfo_list_t local_group;
1726 android_namespace_t* local_group_ns = root->get_primary_namespace();
1727
1728 walk_dependencies_tree(root,
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -07001729 [&] (soinfo* si) {
dimitry965d06d2017-11-28 16:03:07 +01001730 if (local_group_ns->is_accessible(si)) {
1731 local_group.push_back(si);
1732 return kWalkContinue;
1733 } else {
1734 return kWalkSkip;
1735 }
1736 });
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -07001737
dimitry965d06d2017-11-28 16:03:07 +01001738 soinfo_list_t global_group = local_group_ns->get_global_group();
Ryan Prichard339ecef2020-01-02 16:36:06 -08001739 SymbolLookupList lookup_list(global_group, local_group);
1740 soinfo* local_group_root = local_group.front();
1741
dimitry965d06d2017-11-28 16:03:07 +01001742 bool linked = local_group.visit([&](soinfo* si) {
Torne (Richard Coles)5d103742019-04-11 12:25:06 -04001743 // Even though local group may contain accessible soinfos from other namespaces
dimitry965d06d2017-11-28 16:03:07 +01001744 // we should avoid linking them (because if they are not linked -> they
1745 // are in the local_group_roots and will be linked later).
1746 if (!si->is_linked() && si->get_primary_namespace() == local_group_ns) {
Torne (Richard Coles)5d103742019-04-11 12:25:06 -04001747 const android_dlextinfo* link_extinfo = nullptr;
1748 if (si == soinfos[0] || reserved_address_recursive) {
1749 // Only forward extinfo for the first library unless the recursive
1750 // flag is set.
1751 link_extinfo = extinfo;
1752 }
Peter Collingbourne191ecdc2019-08-07 19:06:00 -07001753 if (__libc_shared_globals()->load_hook) {
1754 __libc_shared_globals()->load_hook(si->load_bias, si->phdr, si->phnum);
1755 }
Ryan Prichard339ecef2020-01-02 16:36:06 -08001756 lookup_list.set_dt_symbolic_lib(si->has_DT_SYMBOLIC ? si : nullptr);
1757 if (!si->link_image(lookup_list, local_group_root, link_extinfo, &relro_fd_offset) ||
dimitry965d06d2017-11-28 16:03:07 +01001758 !get_cfi_shadow()->AfterLoad(si, solist_get_head())) {
1759 return false;
1760 }
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001761 }
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -07001762
dimitry965d06d2017-11-28 16:03:07 +01001763 return true;
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001764 });
Elliott Hughes27f18062017-11-29 18:47:42 +00001765
dimitry965d06d2017-11-28 16:03:07 +01001766 if (!linked) {
1767 return false;
1768 }
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001769 }
1770
dimitry965d06d2017-11-28 16:03:07 +01001771 // Step 7: Mark all load_tasks as linked and increment refcounts
1772 // for references between load_groups (at this point it does not matter if
1773 // referenced load_groups were loaded by previous dlopen or as part of this
1774 // one on step 6)
1775 if (start_with != nullptr && add_as_children) {
1776 start_with->set_linked();
1777 }
1778
1779 for (auto&& task : load_tasks) {
1780 soinfo* si = task->get_soinfo();
1781 si->set_linked();
1782 }
1783
1784 for (auto&& task : load_tasks) {
1785 soinfo* si = task->get_soinfo();
1786 soinfo* needed_by = task->get_needed_by();
1787 if (needed_by != nullptr &&
1788 needed_by != start_with &&
1789 needed_by->get_local_group_root() != si->get_local_group_root()) {
1790 si->increment_ref_count();
1791 }
1792 }
1793
1794
1795 return true;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001796}
1797
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001798static soinfo* find_library(android_namespace_t* ns,
1799 const char* name, int rtld_flags,
Evgenii Stepanov0cdef7e2015-07-06 17:56:31 -07001800 const android_dlextinfo* extinfo,
1801 soinfo* needed_by) {
dimitry965d06d2017-11-28 16:03:07 +01001802 soinfo* si = nullptr;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001803
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08001804 if (name == nullptr) {
Dimitry Ivanov3f660572016-09-09 10:00:39 -07001805 si = solist_get_somain();
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001806 } else if (!find_libraries(ns,
1807 needed_by,
1808 &name,
1809 1,
1810 &si,
1811 nullptr,
1812 0,
1813 rtld_flags,
1814 extinfo,
Ryan Prichard323d7df2020-03-24 21:19:06 -07001815 false /* add_as_children */)) {
dimitry965d06d2017-11-28 16:03:07 +01001816 if (si != nullptr) {
1817 soinfo_unload(si);
1818 }
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001819 return nullptr;
1820 }
1821
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001822 si->increment_ref_count();
1823
Elliott Hughesd23736e2012-11-01 15:16:56 -07001824 return si;
1825}
Elliott Hughesbedfe382012-08-14 14:07:59 -07001826
dimitry06016f22018-01-05 11:39:28 +01001827static void soinfo_unload_impl(soinfo* root) {
Dimitry Ivanov6705e8c2017-03-21 10:29:06 -07001828 ScopedTrace trace((std::string("unload ") + root->get_realpath()).c_str());
dimitry06016f22018-01-05 11:39:28 +01001829 bool is_linked = root->is_linked();
Dimitry Ivanov6705e8c2017-03-21 10:29:06 -07001830
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08001831 if (!root->can_unload()) {
dimitryc92ce712017-10-27 14:12:53 +02001832 LD_LOG(kLogDlopen,
1833 "... dlclose(root=\"%s\"@%p) ... not unloading - the load group is flagged with NODELETE",
1834 root->get_realpath(),
1835 root);
Dmitriy Ivanov1b20daf2014-05-19 15:06:58 -07001836 return;
1837 }
1838
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08001839
Dimitry Ivanovb943f302016-08-03 16:00:10 -07001840 soinfo_list_t unload_list;
dimitry965d06d2017-11-28 16:03:07 +01001841 unload_list.push_back(root);
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001842
Dimitry Ivanovb943f302016-08-03 16:00:10 -07001843 soinfo_list_t local_unload_list;
1844 soinfo_list_t external_unload_list;
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001845 soinfo* si = nullptr;
1846
1847 while ((si = unload_list.pop_front()) != nullptr) {
1848 if (local_unload_list.contains(si)) {
1849 continue;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001850 }
Elliott Hughesd23736e2012-11-01 15:16:56 -07001851
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001852 local_unload_list.push_back(si);
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08001853
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001854 if (si->has_min_version(0)) {
1855 soinfo* child = nullptr;
1856 while ((child = si->get_children().pop_front()) != nullptr) {
1857 TRACE("%s@%p needs to unload %s@%p", si->get_realpath(), si,
1858 child->get_realpath(), child);
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08001859
Dimitry Ivanovec90e242017-02-10 11:04:20 -08001860 child->get_parents().remove(si);
1861
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001862 if (local_unload_list.contains(child)) {
1863 continue;
1864 } else if (child->is_linked() && child->get_local_group_root() != root) {
1865 external_unload_list.push_back(child);
Dimitry Ivanovec90e242017-02-10 11:04:20 -08001866 } else if (child->get_parents().empty()) {
1867 unload_list.push_back(child);
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001868 }
1869 }
1870 } else {
Christopher Ferris7a3681e2017-04-24 17:48:32 -07001871 async_safe_fatal("soinfo for \"%s\"@%p has no version", si->get_realpath(), si);
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08001872 }
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001873 }
1874
1875 local_unload_list.for_each([](soinfo* si) {
dimitryc92ce712017-10-27 14:12:53 +02001876 LD_LOG(kLogDlopen,
1877 "... dlclose: calling destructors for \"%s\"@%p ... ",
1878 si->get_realpath(),
1879 si);
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001880 si->call_destructors();
dimitryc92ce712017-10-27 14:12:53 +02001881 LD_LOG(kLogDlopen,
1882 "... dlclose: calling destructors for \"%s\"@%p ... done",
1883 si->get_realpath(),
1884 si);
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001885 });
1886
1887 while ((si = local_unload_list.pop_front()) != nullptr) {
dimitryc92ce712017-10-27 14:12:53 +02001888 LD_LOG(kLogDlopen,
1889 "... dlclose: unloading \"%s\"@%p ...",
1890 si->get_realpath(),
1891 si);
Ryan Pricharda2e83ab2019-08-16 17:25:43 -07001892 ++g_module_unload_counter;
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001893 notify_gdb_of_unload(si);
Ryan Pricharde5e69e02019-01-01 18:53:48 -08001894 unregister_soinfo_tls(si);
Peter Collingbourne65332082019-08-05 16:16:14 -07001895 if (__libc_shared_globals()->unload_hook) {
1896 __libc_shared_globals()->unload_hook(si->load_bias, si->phdr, si->phnum);
1897 }
Evgenii Stepanov0a3637d2016-07-06 13:20:59 -07001898 get_cfi_shadow()->BeforeUnload(si);
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001899 soinfo_free(si);
1900 }
1901
dimitry965d06d2017-11-28 16:03:07 +01001902 if (is_linked) {
1903 while ((si = external_unload_list.pop_front()) != nullptr) {
1904 LD_LOG(kLogDlopen,
1905 "... dlclose: unloading external reference \"%s\"@%p ...",
1906 si->get_realpath(),
1907 si);
1908 soinfo_unload(si);
1909 }
1910 } else {
1911 LD_LOG(kLogDlopen,
1912 "... dlclose: unload_si was not linked - not unloading external references ...");
Dmitriy Ivanova2547052014-11-18 12:03:09 -08001913 }
1914}
1915
dimitry06016f22018-01-05 11:39:28 +01001916static void soinfo_unload(soinfo* unload_si) {
1917 // Note that the library can be loaded but not linked;
1918 // in which case there is no root but we still need
1919 // to walk the tree and unload soinfos involved.
1920 //
1921 // This happens on unsuccessful dlopen, when one of
1922 // the DT_NEEDED libraries could not be linked/found.
1923 bool is_linked = unload_si->is_linked();
1924 soinfo* root = is_linked ? unload_si->get_local_group_root() : unload_si;
1925
1926 LD_LOG(kLogDlopen,
1927 "... dlclose(realpath=\"%s\"@%p) ... load group root is \"%s\"@%p",
1928 unload_si->get_realpath(),
1929 unload_si,
1930 root->get_realpath(),
1931 root);
1932
1933
1934 size_t ref_count = is_linked ? root->decrement_ref_count() : 0;
1935 if (ref_count > 0) {
1936 LD_LOG(kLogDlopen,
1937 "... dlclose(root=\"%s\"@%p) ... not unloading - decrementing ref_count to %zd",
1938 root->get_realpath(),
1939 root,
1940 ref_count);
1941 return;
1942 }
1943
1944 soinfo_unload_impl(root);
1945}
1946
1947void increment_dso_handle_reference_counter(void* dso_handle) {
1948 if (dso_handle == nullptr) {
1949 return;
1950 }
1951
1952 auto it = g_dso_handle_counters.find(dso_handle);
1953 if (it != g_dso_handle_counters.end()) {
1954 CHECK(++it->second != 0);
1955 } else {
1956 soinfo* si = find_containing_library(dso_handle);
1957 if (si != nullptr) {
1958 ProtectedDataGuard guard;
dimitry55547db2018-05-25 14:17:37 +02001959 si->increment_ref_count();
dimitry06016f22018-01-05 11:39:28 +01001960 } else {
1961 async_safe_fatal(
1962 "increment_dso_handle_reference_counter: Couldn't find soinfo by dso_handle=%p",
1963 dso_handle);
1964 }
1965 g_dso_handle_counters[dso_handle] = 1U;
1966 }
1967}
1968
1969void decrement_dso_handle_reference_counter(void* dso_handle) {
1970 if (dso_handle == nullptr) {
1971 return;
1972 }
1973
1974 auto it = g_dso_handle_counters.find(dso_handle);
1975 CHECK(it != g_dso_handle_counters.end());
1976 CHECK(it->second != 0);
1977
1978 if (--it->second == 0) {
1979 soinfo* si = find_containing_library(dso_handle);
1980 if (si != nullptr) {
1981 ProtectedDataGuard guard;
dimitry55547db2018-05-25 14:17:37 +02001982 soinfo_unload(si);
dimitry06016f22018-01-05 11:39:28 +01001983 } else {
1984 async_safe_fatal(
1985 "decrement_dso_handle_reference_counter: Couldn't find soinfo by dso_handle=%p",
1986 dso_handle);
1987 }
1988 g_dso_handle_counters.erase(it);
1989 }
1990}
1991
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08001992static std::string symbol_display_name(const char* sym_name, const char* sym_ver) {
1993 if (sym_ver == nullptr) {
1994 return sym_name;
1995 }
1996
Dimitry Ivanov9cf99cb2015-12-11 14:22:24 -08001997 return std::string(sym_name) + ", version " + sym_ver;
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08001998}
1999
Dimitry Ivanovaca299a2016-04-11 12:42:58 -07002000static android_namespace_t* get_caller_namespace(soinfo* caller) {
2001 return caller != nullptr ? caller->get_primary_namespace() : g_anonymous_namespace;
2002}
2003
Elliott Hughesa4aafd12014-01-13 16:37:47 -08002004void do_android_get_LD_LIBRARY_PATH(char* buffer, size_t buffer_size) {
Christopher Ferris052fa3a2014-08-26 20:48:11 -07002005 // Use basic string manipulation calls to avoid snprintf.
2006 // snprintf indirectly calls pthread_getspecific to get the size of a buffer.
2007 // When debug malloc is enabled, this call returns 0. This in turn causes
2008 // snprintf to do nothing, which causes libraries to fail to load.
2009 // See b/17302493 for further details.
2010 // Once the above bug is fixed, this code can be modified to use
2011 // snprintf again.
Dimitry Ivanov77ad6422017-03-06 13:02:29 -08002012 const auto& default_ld_paths = g_default_namespace.get_default_library_paths();
2013
2014 size_t required_size = 0;
2015 for (const auto& path : default_ld_paths) {
2016 required_size += path.size() + 1;
Evgenii Stepanovd640b222015-07-10 17:54:01 -07002017 }
Dimitry Ivanov77ad6422017-03-06 13:02:29 -08002018
2019 if (buffer_size < required_size) {
Christopher Ferris7a3681e2017-04-24 17:48:32 -07002020 async_safe_fatal("android_get_LD_LIBRARY_PATH failed, buffer too small: "
2021 "buffer len %zu, required len %zu", buffer_size, required_size);
Christopher Ferris052fa3a2014-08-26 20:48:11 -07002022 }
Dimitry Ivanov77ad6422017-03-06 13:02:29 -08002023
Evgenii Stepanovd640b222015-07-10 17:54:01 -07002024 char* end = buffer;
Dimitry Ivanov77ad6422017-03-06 13:02:29 -08002025 for (size_t i = 0; i < default_ld_paths.size(); ++i) {
Evgenii Stepanovd640b222015-07-10 17:54:01 -07002026 if (i > 0) *end++ = ':';
Dimitry Ivanov77ad6422017-03-06 13:02:29 -08002027 end = stpcpy(end, default_ld_paths[i].c_str());
Evgenii Stepanovd640b222015-07-10 17:54:01 -07002028 }
Elliott Hughesa4aafd12014-01-13 16:37:47 -08002029}
2030
Elliott Hughescade4c32012-12-20 14:42:14 -08002031void do_android_update_LD_LIBRARY_PATH(const char* ld_library_path) {
Nick Kralevich6bb01b62015-03-07 13:37:05 -08002032 parse_LD_LIBRARY_PATH(ld_library_path);
Elliott Hughescade4c32012-12-20 14:42:14 -08002033}
2034
Dimitry Ivanovb996d602016-07-11 18:11:39 -07002035static std::string android_dlextinfo_to_string(const android_dlextinfo* info) {
2036 if (info == nullptr) {
2037 return "(null)";
2038 }
2039
2040 return android::base::StringPrintf("[flags=0x%" PRIx64 ","
2041 " reserved_addr=%p,"
2042 " reserved_size=0x%zx,"
2043 " relro_fd=%d,"
2044 " library_fd=%d,"
2045 " library_fd_offset=0x%" PRIx64 ","
2046 " library_namespace=%s@%p]",
2047 info->flags,
2048 info->reserved_addr,
2049 info->reserved_size,
2050 info->relro_fd,
2051 info->library_fd,
2052 info->library_fd_offset,
2053 (info->flags & ANDROID_DLEXT_USE_NAMESPACE) != 0 ?
2054 (info->library_namespace != nullptr ?
2055 info->library_namespace->get_name() : "(null)") : "(n/a)",
2056 (info->flags & ANDROID_DLEXT_USE_NAMESPACE) != 0 ?
2057 info->library_namespace : nullptr);
2058}
2059
Dimitry Ivanovd9e427c2016-11-22 16:55:25 -08002060void* do_dlopen(const char* name, int flags,
2061 const android_dlextinfo* extinfo,
2062 const void* caller_addr) {
Dimitry Ivanov5c4a5802017-03-17 16:41:34 -07002063 std::string trace_prefix = std::string("dlopen: ") + (name == nullptr ? "(nullptr)" : name);
2064 ScopedTrace trace(trace_prefix.c_str());
2065 ScopedTrace loading_trace((trace_prefix + " - loading and linking").c_str());
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002066 soinfo* const caller = find_containing_library(caller_addr);
Dimitry Ivanovb996d602016-07-11 18:11:39 -07002067 android_namespace_t* ns = get_caller_namespace(caller);
2068
2069 LD_LOG(kLogDlopen,
Victor Chang6cb719f2019-02-06 17:19:10 +00002070 "dlopen(name=\"%s\", flags=0x%x, extinfo=%s, caller=\"%s\", caller_ns=%s@%p, targetSdkVersion=%i) ...",
Dimitry Ivanovb996d602016-07-11 18:11:39 -07002071 name,
2072 flags,
2073 android_dlextinfo_to_string(extinfo).c_str(),
2074 caller == nullptr ? "(null)" : caller->get_realpath(),
2075 ns == nullptr ? "(null)" : ns->get_name(),
Victor Chang6cb719f2019-02-06 17:19:10 +00002076 ns,
2077 get_application_target_sdk_version());
Dimitry Ivanovb996d602016-07-11 18:11:39 -07002078
Vic Yangbb7e1232019-01-29 20:23:16 -08002079 auto purge_guard = android::base::make_scope_guard([&]() { purge_unused_memory(); });
2080
Tom Cherryb8ab6182017-04-05 16:20:29 -07002081 auto failure_guard = android::base::make_scope_guard(
2082 [&]() { LD_LOG(kLogDlopen, "... dlopen failed: %s", linker_get_error_buffer()); });
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002083
Dmitriy Ivanov1b20daf2014-05-19 15:06:58 -07002084 if ((flags & ~(RTLD_NOW|RTLD_LAZY|RTLD_LOCAL|RTLD_GLOBAL|RTLD_NODELETE|RTLD_NOLOAD)) != 0) {
Martin Stjernholm9fe38262019-08-27 17:08:45 +01002085 DL_OPEN_ERR("invalid flags to dlopen: %x", flags);
Dmitriy Ivanov851135b2014-08-29 12:02:36 -07002086 return nullptr;
Elliott Hughese66190d2012-12-18 15:57:55 -08002087 }
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002088
Dmitriy Ivanov07e5bc12014-10-03 17:52:44 -07002089 if (extinfo != nullptr) {
2090 if ((extinfo->flags & ~(ANDROID_DLEXT_VALID_FLAG_BITS)) != 0) {
Martin Stjernholm9fe38262019-08-27 17:08:45 +01002091 DL_OPEN_ERR("invalid extended flags to android_dlopen_ext: 0x%" PRIx64, extinfo->flags);
Dmitriy Ivanov07e5bc12014-10-03 17:52:44 -07002092 return nullptr;
2093 }
Dmitriy Ivanov126af752015-10-07 16:34:20 -07002094
Dmitriy Ivanov07e5bc12014-10-03 17:52:44 -07002095 if ((extinfo->flags & ANDROID_DLEXT_USE_LIBRARY_FD) == 0 &&
Dmitriy Ivanova6c12792014-10-21 12:09:18 -07002096 (extinfo->flags & ANDROID_DLEXT_USE_LIBRARY_FD_OFFSET) != 0) {
Martin Stjernholm9fe38262019-08-27 17:08:45 +01002097 DL_OPEN_ERR("invalid extended flag combination (ANDROID_DLEXT_USE_LIBRARY_FD_OFFSET without "
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07002098 "ANDROID_DLEXT_USE_LIBRARY_FD): 0x%" PRIx64, extinfo->flags);
Dmitriy Ivanov07e5bc12014-10-03 17:52:44 -07002099 return nullptr;
2100 }
Dmitriy Ivanov126af752015-10-07 16:34:20 -07002101
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002102 if ((extinfo->flags & ANDROID_DLEXT_USE_NAMESPACE) != 0) {
2103 if (extinfo->library_namespace == nullptr) {
Martin Stjernholm9fe38262019-08-27 17:08:45 +01002104 DL_OPEN_ERR("ANDROID_DLEXT_USE_NAMESPACE is set but extinfo->library_namespace is null");
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002105 return nullptr;
2106 }
2107 ns = extinfo->library_namespace;
2108 }
Torne (Richard Coles)012cb452014-02-06 14:34:21 +00002109 }
Dmitriy Ivanov279a22f2015-01-23 12:03:53 -08002110
Victor Chang6cb719f2019-02-06 17:19:10 +00002111 // Workaround for dlopen(/system/lib/<soname>) when .so is in /apex. http://b/121248172
2112 // The workaround works only when targetSdkVersion < Q.
2113 std::string name_to_apex;
2114 if (translateSystemPathToApexPath(name, &name_to_apex)) {
2115 const char* new_name = name_to_apex.c_str();
2116 LD_LOG(kLogDlopen, "dlopen considering translation from %s to APEX path %s",
2117 name,
2118 new_name);
2119 // Some APEXs could be optionally disabled. Only translate the path
2120 // when the old file is absent and the new file exists.
Victor Changaf12c942019-02-11 19:35:24 +00002121 // TODO(b/124218500): Re-enable it once app compat issue is resolved
2122 /*
Victor Chang6cb719f2019-02-06 17:19:10 +00002123 if (file_exists(name)) {
2124 LD_LOG(kLogDlopen, "dlopen %s exists, not translating", name);
Victor Changaf12c942019-02-11 19:35:24 +00002125 } else
2126 */
2127 if (!file_exists(new_name)) {
Victor Chang6cb719f2019-02-06 17:19:10 +00002128 LD_LOG(kLogDlopen, "dlopen %s does not exist, not translating",
2129 new_name);
2130 } else {
2131 LD_LOG(kLogDlopen, "dlopen translation accepted: using %s", new_name);
2132 name = new_name;
2133 }
2134 }
2135 // End Workaround for dlopen(/system/lib/<soname>) when .so is in /apex.
2136
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -07002137 std::string asan_name_holder;
2138
2139 const char* translated_name = name;
Dimitry Ivanov6c14f862016-12-05 13:35:47 -08002140 if (g_is_asan && translated_name != nullptr && translated_name[0] == '/') {
Evgenii Stepanov9e77a642017-07-27 14:55:44 -07002141 char original_path[PATH_MAX];
2142 if (realpath(name, original_path) != nullptr) {
2143 asan_name_holder = std::string(kAsanLibDirPrefix) + original_path;
Vishwath Mohan4113def2017-03-29 15:31:34 -07002144 if (file_exists(asan_name_holder.c_str())) {
Evgenii Stepanov9e77a642017-07-27 14:55:44 -07002145 soinfo* si = nullptr;
2146 if (find_loaded_library_by_realpath(ns, original_path, true, &si)) {
2147 PRINT("linker_asan dlopen NOT translating \"%s\" -> \"%s\": library already loaded", name,
2148 asan_name_holder.c_str());
2149 } else {
2150 PRINT("linker_asan dlopen translating \"%s\" -> \"%s\"", name, translated_name);
2151 translated_name = asan_name_holder.c_str();
2152 }
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -07002153 }
2154 }
2155 }
2156
Dmitriy Ivanov279a22f2015-01-23 12:03:53 -08002157 ProtectedDataGuard guard;
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -07002158 soinfo* si = find_library(ns, translated_name, flags, extinfo, caller);
Dimitry Ivanov5c4a5802017-03-17 16:41:34 -07002159 loading_trace.End();
2160
Dmitriy Ivanov851135b2014-08-29 12:02:36 -07002161 if (si != nullptr) {
Dimitry Ivanovb996d602016-07-11 18:11:39 -07002162 void* handle = si->to_handle();
2163 LD_LOG(kLogDlopen,
Dimitry Ivanovae4a0c12016-11-21 10:44:35 -08002164 "... dlopen calling constructors: realpath=\"%s\", soname=\"%s\", handle=%p",
2165 si->get_realpath(), si->get_soname(), handle);
2166 si->call_constructors();
Tom Cherryb8ab6182017-04-05 16:20:29 -07002167 failure_guard.Disable();
Dimitry Ivanovae4a0c12016-11-21 10:44:35 -08002168 LD_LOG(kLogDlopen,
Dimitry Ivanovb996d602016-07-11 18:11:39 -07002169 "... dlopen successful: realpath=\"%s\", soname=\"%s\", handle=%p",
2170 si->get_realpath(), si->get_soname(), handle);
2171 return handle;
Elliott Hughesd23736e2012-11-01 15:16:56 -07002172 }
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002173
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -07002174 return nullptr;
Elliott Hughesd23736e2012-11-01 15:16:56 -07002175}
2176
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002177int do_dladdr(const void* addr, Dl_info* info) {
2178 // Determine if this address can be found in any library currently mapped.
2179 soinfo* si = find_containing_library(addr);
2180 if (si == nullptr) {
2181 return 0;
2182 }
2183
2184 memset(info, 0, sizeof(Dl_info));
2185
2186 info->dli_fname = si->get_realpath();
2187 // Address at which the shared object is loaded.
2188 info->dli_fbase = reinterpret_cast<void*>(si->base);
2189
2190 // Determine if any symbol in the library contains the specified address.
2191 ElfW(Sym)* sym = si->find_symbol_by_address(addr);
2192 if (sym != nullptr) {
2193 info->dli_sname = si->get_string(sym->st_name);
2194 info->dli_saddr = reinterpret_cast<void*>(si->resolve_symbol_address(sym));
2195 }
2196
2197 return 1;
2198}
2199
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -07002200static soinfo* soinfo_from_handle(void* handle) {
2201 if ((reinterpret_cast<uintptr_t>(handle) & 1) != 0) {
2202 auto it = g_soinfo_handles_map.find(reinterpret_cast<uintptr_t>(handle));
2203 if (it == g_soinfo_handles_map.end()) {
2204 return nullptr;
2205 } else {
2206 return it->second;
2207 }
2208 }
2209
2210 return static_cast<soinfo*>(handle);
2211}
2212
Dimitry Ivanovd9e427c2016-11-22 16:55:25 -08002213bool do_dlsym(void* handle,
2214 const char* sym_name,
2215 const char* sym_ver,
2216 const void* caller_addr,
2217 void** symbol) {
Dimitry Ivanov6705e8c2017-03-21 10:29:06 -07002218 ScopedTrace trace("dlsym");
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002219#if !defined(__LP64__)
2220 if (handle == nullptr) {
Martin Stjernholm9fe38262019-08-27 17:08:45 +01002221 DL_SYM_ERR("dlsym failed: library handle is null");
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002222 return false;
2223 }
2224#endif
2225
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002226 soinfo* found = nullptr;
2227 const ElfW(Sym)* sym = nullptr;
2228 soinfo* caller = find_containing_library(caller_addr);
Dimitry Ivanovaca299a2016-04-11 12:42:58 -07002229 android_namespace_t* ns = get_caller_namespace(caller);
Dimitry Ivanov4742abd2016-12-12 16:30:15 -08002230 soinfo* si = nullptr;
2231 if (handle != RTLD_DEFAULT && handle != RTLD_NEXT) {
2232 si = soinfo_from_handle(handle);
2233 }
2234
2235 LD_LOG(kLogDlsym,
2236 "dlsym(handle=%p(\"%s\"), sym_name=\"%s\", sym_ver=\"%s\", caller=\"%s\", caller_ns=%s@%p) ...",
2237 handle,
2238 si != nullptr ? si->get_realpath() : "n/a",
2239 sym_name,
2240 sym_ver,
2241 caller == nullptr ? "(null)" : caller->get_realpath(),
2242 ns == nullptr ? "(null)" : ns->get_name(),
2243 ns);
2244
Tom Cherryb8ab6182017-04-05 16:20:29 -07002245 auto failure_guard = android::base::make_scope_guard(
2246 [&]() { LD_LOG(kLogDlsym, "... dlsym failed: %s", linker_get_error_buffer()); });
Dimitry Ivanov4742abd2016-12-12 16:30:15 -08002247
2248 if (sym_name == nullptr) {
Martin Stjernholm9fe38262019-08-27 17:08:45 +01002249 DL_SYM_ERR("dlsym failed: symbol name is null");
Dimitry Ivanov4742abd2016-12-12 16:30:15 -08002250 return false;
2251 }
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002252
2253 version_info vi_instance;
2254 version_info* vi = nullptr;
2255
2256 if (sym_ver != nullptr) {
Dimitry Ivanov9cf99cb2015-12-11 14:22:24 -08002257 vi_instance.name = sym_ver;
2258 vi_instance.elf_hash = calculate_elf_hash(sym_ver);
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002259 vi = &vi_instance;
2260 }
2261
2262 if (handle == RTLD_DEFAULT || handle == RTLD_NEXT) {
2263 sym = dlsym_linear_lookup(ns, sym_name, vi, &found, caller, handle);
2264 } else {
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -07002265 if (si == nullptr) {
Martin Stjernholm9fe38262019-08-27 17:08:45 +01002266 DL_SYM_ERR("dlsym failed: invalid handle: %p", handle);
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -07002267 return false;
2268 }
2269 sym = dlsym_handle_lookup(si, &found, sym_name, vi);
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002270 }
2271
2272 if (sym != nullptr) {
2273 uint32_t bind = ELF_ST_BIND(sym->st_info);
Ryan Pricharde4d620b2019-04-01 17:42:14 -07002274 uint32_t type = ELF_ST_TYPE(sym->st_info);
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002275
2276 if ((bind == STB_GLOBAL || bind == STB_WEAK) && sym->st_shndx != 0) {
Ryan Pricharde4d620b2019-04-01 17:42:14 -07002277 if (type == STT_TLS) {
2278 // For a TLS symbol, dlsym returns the address of the current thread's
Ryan Pricharda2e83ab2019-08-16 17:25:43 -07002279 // copy of the symbol.
2280 const soinfo_tls* tls_module = found->get_tls();
Ryan Pricharde4d620b2019-04-01 17:42:14 -07002281 if (tls_module == nullptr) {
Martin Stjernholm9fe38262019-08-27 17:08:45 +01002282 DL_SYM_ERR("TLS symbol \"%s\" in solib \"%s\" with no TLS segment",
2283 sym_name, found->get_realpath());
Ryan Pricharde4d620b2019-04-01 17:42:14 -07002284 return false;
2285 }
Ryan Pricharda2e83ab2019-08-16 17:25:43 -07002286 void* tls_block = get_tls_block_for_this_thread(tls_module, /*should_alloc=*/true);
2287 *symbol = static_cast<char*>(tls_block) + sym->st_value;
Ryan Pricharde4d620b2019-04-01 17:42:14 -07002288 } else {
2289 *symbol = reinterpret_cast<void*>(found->resolve_symbol_address(sym));
2290 }
Tom Cherryb8ab6182017-04-05 16:20:29 -07002291 failure_guard.Disable();
Dimitry Ivanov4742abd2016-12-12 16:30:15 -08002292 LD_LOG(kLogDlsym,
2293 "... dlsym successful: sym_name=\"%s\", sym_ver=\"%s\", found in=\"%s\", address=%p",
2294 sym_name, sym_ver, found->get_soname(), *symbol);
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002295 return true;
2296 }
2297
Martin Stjernholm9fe38262019-08-27 17:08:45 +01002298 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 -08002299 return false;
2300 }
2301
Martin Stjernholm9fe38262019-08-27 17:08:45 +01002302 DL_SYM_ERR("undefined symbol: %s", symbol_display_name(sym_name, sym_ver).c_str());
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002303 return false;
2304}
2305
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -07002306int do_dlclose(void* handle) {
Dimitry Ivanov6705e8c2017-03-21 10:29:06 -07002307 ScopedTrace trace("dlclose");
Dmitriy Ivanov279a22f2015-01-23 12:03:53 -08002308 ProtectedDataGuard guard;
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -07002309 soinfo* si = soinfo_from_handle(handle);
2310 if (si == nullptr) {
Martin Stjernholm9fe38262019-08-27 17:08:45 +01002311 DL_OPEN_ERR("invalid handle: %p", handle);
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -07002312 return -1;
2313 }
2314
dimitryc92ce712017-10-27 14:12:53 +02002315 LD_LOG(kLogDlopen,
2316 "dlclose(handle=%p, realpath=\"%s\"@%p) ...",
2317 handle,
2318 si->get_realpath(),
2319 si);
Dmitriy Ivanovb648a8a2014-05-19 15:06:58 -07002320 soinfo_unload(si);
dimitryc92ce712017-10-27 14:12:53 +02002321 LD_LOG(kLogDlopen,
2322 "dlclose(handle=%p) ... done",
2323 handle);
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -07002324 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002325}
2326
Jiyong Park25bedfd2019-05-16 21:00:39 +09002327// Make ns as the anonymous namespace that is a namespace used when
2328// we fail to determine the caller address (e.g., call from mono-jited code)
2329// Since there can be multiple anonymous namespace in a process, subsequent
2330// call to this function causes an error.
2331static bool set_anonymous_namespace(android_namespace_t* ns) {
2332 if (!g_anonymous_namespace_set && ns != nullptr) {
2333 CHECK(ns->is_also_used_as_anonymous());
2334 g_anonymous_namespace = ns;
2335 g_anonymous_namespace_set = true;
2336 return true;
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002337 }
Jiyong Park25bedfd2019-05-16 21:00:39 +09002338 return false;
2339}
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002340
Jiyong Park25bedfd2019-05-16 21:00:39 +09002341// TODO(b/130388701) remove this. Currently, this is used only for testing
2342// where we don't have classloader namespace.
2343bool init_anonymous_namespace(const char* shared_lib_sonames, const char* library_search_path) {
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002344 ProtectedDataGuard guard;
2345
Jiyong Park25bedfd2019-05-16 21:00:39 +09002346 // Test-only feature: we need to change the anonymous namespace multiple times
2347 // while the test is running.
2348 g_anonymous_namespace_set = false;
2349
Dmitriy Ivanov1ffec1c2015-11-23 11:26:35 -08002350 // create anonymous namespace
Dimitry Ivanov7331fe12015-12-14 14:11:17 -08002351 // When the caller is nullptr - create_namespace will take global group
2352 // from the anonymous namespace, which is fine because anonymous namespace
2353 // is still pointing to the default one.
Dmitriy Ivanov1ffec1c2015-11-23 11:26:35 -08002354 android_namespace_t* anon_ns =
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -08002355 create_namespace(nullptr,
2356 "(anonymous)",
2357 nullptr,
2358 library_search_path,
Jiyong Park25bedfd2019-05-16 21:00:39 +09002359 ANDROID_NAMESPACE_TYPE_ISOLATED |
2360 ANDROID_NAMESPACE_TYPE_ALSO_USED_AS_ANONYMOUS,
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -08002361 nullptr,
2362 &g_default_namespace);
Dmitriy Ivanov1ffec1c2015-11-23 11:26:35 -08002363
Jiyong Park25bedfd2019-05-16 21:00:39 +09002364 CHECK(anon_ns != nullptr);
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -08002365
2366 if (!link_namespaces(anon_ns, &g_default_namespace, shared_lib_sonames)) {
Jiyong Park25bedfd2019-05-16 21:00:39 +09002367 // TODO: delete anon_ns
Dmitriy Ivanov1ffec1c2015-11-23 11:26:35 -08002368 return false;
2369 }
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08002370
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002371 return true;
2372}
2373
Dimitry Ivanovb943f302016-08-03 16:00:10 -07002374static void add_soinfos_to_namespace(const soinfo_list_t& soinfos, android_namespace_t* ns) {
2375 ns->add_soinfos(soinfos);
2376 for (auto si : soinfos) {
2377 si->add_secondary_namespace(ns);
2378 }
2379}
2380
Ryan Prichard40494402020-03-24 22:37:50 -07002381std::vector<std::string> fix_lib_paths(std::vector<std::string> paths) {
2382 // For the bootstrap linker, insert /system/${LIB}/bootstrap in front of /system/${LIB} in any
2383 // namespace search path. The bootstrap linker should prefer to use the bootstrap bionic libraries
2384 // (e.g. libc.so).
2385#if !defined(__ANDROID_APEX__)
2386 for (size_t i = 0; i < paths.size(); ++i) {
2387 if (paths[i] == kSystemLibDir) {
2388 paths.insert(paths.begin() + i, std::string(kSystemLibDir) + "/bootstrap");
2389 ++i;
2390 }
2391 }
2392#endif
2393 return paths;
2394}
2395
Dimitry Ivanov7331fe12015-12-14 14:11:17 -08002396android_namespace_t* create_namespace(const void* caller_addr,
2397 const char* name,
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002398 const char* ld_library_path,
2399 const char* default_library_path,
Dimitry Ivanov7331fe12015-12-14 14:11:17 -08002400 uint64_t type,
Dimitry Ivanovfc2da532016-05-12 15:20:21 -07002401 const char* permitted_when_isolated_path,
2402 android_namespace_t* parent_namespace) {
Dimitry Ivanovfc2da532016-05-12 15:20:21 -07002403 if (parent_namespace == nullptr) {
Dimitry Ivanov52408632016-05-23 10:31:11 -07002404 // if parent_namespace is nullptr -> set it to the caller namespace
2405 soinfo* caller_soinfo = find_containing_library(caller_addr);
2406
2407 parent_namespace = caller_soinfo != nullptr ?
2408 caller_soinfo->get_primary_namespace() :
2409 g_anonymous_namespace;
Dimitry Ivanovfc2da532016-05-12 15:20:21 -07002410 }
2411
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002412 ProtectedDataGuard guard;
2413 std::vector<std::string> ld_library_paths;
2414 std::vector<std::string> default_library_paths;
Dimitry Ivanov284ae352015-12-08 10:47:13 -08002415 std::vector<std::string> permitted_paths;
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002416
2417 parse_path(ld_library_path, ":", &ld_library_paths);
2418 parse_path(default_library_path, ":", &default_library_paths);
Dimitry Ivanov284ae352015-12-08 10:47:13 -08002419 parse_path(permitted_when_isolated_path, ":", &permitted_paths);
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002420
2421 android_namespace_t* ns = new (g_namespace_allocator.alloc()) android_namespace_t();
2422 ns->set_name(name);
Dimitry Ivanov7331fe12015-12-14 14:11:17 -08002423 ns->set_isolated((type & ANDROID_NAMESPACE_TYPE_ISOLATED) != 0);
Ryan Prichardaff9a342020-08-03 15:29:12 -07002424 ns->set_exempt_list_enabled((type & ANDROID_NAMESPACE_TYPE_EXEMPT_LIST_ENABLED) != 0);
Jiyong Park25bedfd2019-05-16 21:00:39 +09002425 ns->set_also_used_as_anonymous((type & ANDROID_NAMESPACE_TYPE_ALSO_USED_AS_ANONYMOUS) != 0);
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002426
Dimitry Ivanov7331fe12015-12-14 14:11:17 -08002427 if ((type & ANDROID_NAMESPACE_TYPE_SHARED) != 0) {
Dimitry Ivanovf1cb6692017-05-01 17:45:38 -07002428 // append parent namespace paths.
2429 std::copy(parent_namespace->get_ld_library_paths().begin(),
2430 parent_namespace->get_ld_library_paths().end(),
2431 back_inserter(ld_library_paths));
2432
2433 std::copy(parent_namespace->get_default_library_paths().begin(),
2434 parent_namespace->get_default_library_paths().end(),
2435 back_inserter(default_library_paths));
2436
2437 std::copy(parent_namespace->get_permitted_paths().begin(),
2438 parent_namespace->get_permitted_paths().end(),
2439 back_inserter(permitted_paths));
2440
Dimitry Ivanovfc2da532016-05-12 15:20:21 -07002441 // If shared - clone the parent namespace
Dimitry Ivanovb943f302016-08-03 16:00:10 -07002442 add_soinfos_to_namespace(parent_namespace->soinfo_list(), ns);
Dimitry Ivanovf1cb6692017-05-01 17:45:38 -07002443 // and copy parent namespace links
2444 for (auto& link : parent_namespace->linked_namespaces()) {
Logan Chien9ee45912018-01-18 12:05:09 +08002445 ns->add_linked_namespace(link.linked_namespace(), link.shared_lib_sonames(),
2446 link.allow_all_shared_libs());
Dimitry Ivanovf1cb6692017-05-01 17:45:38 -07002447 }
Dimitry Ivanov7331fe12015-12-14 14:11:17 -08002448 } else {
Dimitry Ivanovfc2da532016-05-12 15:20:21 -07002449 // If not shared - copy only the shared group
Jiyong Park02586a22017-05-20 01:01:24 +09002450 add_soinfos_to_namespace(parent_namespace->get_shared_group(), ns);
Dimitry Ivanov7331fe12015-12-14 14:11:17 -08002451 }
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002452
Dimitry Ivanovf1cb6692017-05-01 17:45:38 -07002453 ns->set_ld_library_paths(std::move(ld_library_paths));
2454 ns->set_default_library_paths(std::move(default_library_paths));
2455 ns->set_permitted_paths(std::move(permitted_paths));
2456
Jiyong Park25bedfd2019-05-16 21:00:39 +09002457 if (ns->is_also_used_as_anonymous() && !set_anonymous_namespace(ns)) {
2458 DL_ERR("failed to set namespace: [name=\"%s\", ld_library_path=\"%s\", default_library_paths=\"%s\""
2459 " permitted_paths=\"%s\"] as the anonymous namespace",
2460 ns->get_name(),
2461 android::base::Join(ns->get_ld_library_paths(), ':').c_str(),
2462 android::base::Join(ns->get_default_library_paths(), ':').c_str(),
2463 android::base::Join(ns->get_permitted_paths(), ':').c_str());
2464 return nullptr;
2465 }
2466
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002467 return ns;
2468}
2469
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -08002470bool link_namespaces(android_namespace_t* namespace_from,
2471 android_namespace_t* namespace_to,
2472 const char* shared_lib_sonames) {
2473 if (namespace_to == nullptr) {
2474 namespace_to = &g_default_namespace;
2475 }
2476
2477 if (namespace_from == nullptr) {
2478 DL_ERR("error linking namespaces: namespace_from is null.");
2479 return false;
2480 }
2481
2482 if (shared_lib_sonames == nullptr || shared_lib_sonames[0] == '\0') {
2483 DL_ERR("error linking namespaces \"%s\"->\"%s\": the list of shared libraries is empty.",
2484 namespace_from->get_name(), namespace_to->get_name());
2485 return false;
2486 }
2487
Jooyung Han57b03de2022-12-01 16:23:03 +09002488 std::vector<std::string> sonames = android::base::Split(shared_lib_sonames, ":");
2489 std::unordered_set<std::string> sonames_set(std::make_move_iterator(sonames.begin()),
2490 std::make_move_iterator(sonames.end()));
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -08002491
2492 ProtectedDataGuard guard;
Jooyung Han57b03de2022-12-01 16:23:03 +09002493 namespace_from->add_linked_namespace(namespace_to, std::move(sonames_set), false);
Logan Chien9ee45912018-01-18 12:05:09 +08002494
2495 return true;
2496}
2497
2498bool link_namespaces_all_libs(android_namespace_t* namespace_from,
2499 android_namespace_t* namespace_to) {
2500 if (namespace_from == nullptr) {
2501 DL_ERR("error linking namespaces: namespace_from is null.");
2502 return false;
2503 }
2504
2505 if (namespace_to == nullptr) {
2506 DL_ERR("error linking namespaces: namespace_to is null.");
2507 return false;
2508 }
2509
2510 ProtectedDataGuard guard;
2511 namespace_from->add_linked_namespace(namespace_to, std::unordered_set<std::string>(), true);
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -08002512
2513 return true;
2514}
2515
Dimitry Ivanov48ec2882016-08-04 11:50:36 -07002516ElfW(Addr) call_ifunc_resolver(ElfW(Addr) resolver_addr) {
Elliott Hughes90f96b92019-05-09 15:56:39 -07002517 if (g_is_ldd) return 0;
2518
Peter Collingbournee9491952019-10-28 10:57:26 -07002519 ElfW(Addr) ifunc_addr = __bionic_call_ifunc_resolver(resolver_addr);
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07002520 TRACE_TYPE(RELO, "Called ifunc_resolver@%p. The result is %p",
Peter Collingbournee9491952019-10-28 10:57:26 -07002521 reinterpret_cast<void *>(resolver_addr), reinterpret_cast<void*>(ifunc_addr));
Brigid Smithc5a13ef2014-07-23 11:22:25 -07002522
Dmitriy Ivanov9aea1642014-09-11 15:16:03 -07002523 return ifunc_addr;
Brigid Smithc5a13ef2014-07-23 11:22:25 -07002524}
Brigid Smithc5a13ef2014-07-23 11:22:25 -07002525
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07002526const version_info* VersionTracker::get_version_info(ElfW(Versym) source_symver) const {
2527 if (source_symver < 2 ||
2528 source_symver >= version_infos.size() ||
2529 version_infos[source_symver].name == nullptr) {
2530 return nullptr;
2531 }
2532
2533 return &version_infos[source_symver];
2534}
2535
2536void VersionTracker::add_version_info(size_t source_index,
2537 ElfW(Word) elf_hash,
2538 const char* ver_name,
2539 const soinfo* target_si) {
2540 if (source_index >= version_infos.size()) {
2541 version_infos.resize(source_index+1);
2542 }
2543
2544 version_infos[source_index].elf_hash = elf_hash;
2545 version_infos[source_index].name = ver_name;
2546 version_infos[source_index].target_si = target_si;
2547}
2548
2549bool VersionTracker::init_verneed(const soinfo* si_from) {
2550 uintptr_t verneed_ptr = si_from->get_verneed_ptr();
2551
2552 if (verneed_ptr == 0) {
2553 return true;
2554 }
2555
2556 size_t verneed_cnt = si_from->get_verneed_cnt();
2557
2558 for (size_t i = 0, offset = 0; i<verneed_cnt; ++i) {
2559 const ElfW(Verneed)* verneed = reinterpret_cast<ElfW(Verneed)*>(verneed_ptr + offset);
2560 size_t vernaux_offset = offset + verneed->vn_aux;
2561 offset += verneed->vn_next;
2562
2563 if (verneed->vn_version != 1) {
2564 DL_ERR("unsupported verneed[%zd] vn_version: %d (expected 1)", i, verneed->vn_version);
2565 return false;
2566 }
2567
2568 const char* target_soname = si_from->get_string(verneed->vn_file);
2569 // find it in dependencies
Elliott Hughesf9dd1a72021-01-11 09:04:58 -08002570 soinfo* target_si = si_from->get_children().find_if(
2571 [&](const soinfo* si) { return strcmp(si->get_soname(), target_soname) == 0; });
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07002572
2573 if (target_si == nullptr) {
2574 DL_ERR("cannot find \"%s\" from verneed[%zd] in DT_NEEDED list for \"%s\"",
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07002575 target_soname, i, si_from->get_realpath());
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07002576 return false;
2577 }
2578
2579 for (size_t j = 0; j<verneed->vn_cnt; ++j) {
2580 const ElfW(Vernaux)* vernaux = reinterpret_cast<ElfW(Vernaux)*>(verneed_ptr + vernaux_offset);
2581 vernaux_offset += vernaux->vna_next;
2582
2583 const ElfW(Word) elf_hash = vernaux->vna_hash;
2584 const char* ver_name = si_from->get_string(vernaux->vna_name);
2585 ElfW(Half) source_index = vernaux->vna_other;
2586
2587 add_version_info(source_index, elf_hash, ver_name, target_si);
2588 }
2589 }
2590
2591 return true;
2592}
2593
Dimitry Ivanov48ec2882016-08-04 11:50:36 -07002594template <typename F>
2595static bool for_each_verdef(const soinfo* si, F functor) {
2596 if (!si->has_min_version(2)) {
2597 return true;
2598 }
2599
2600 uintptr_t verdef_ptr = si->get_verdef_ptr();
2601 if (verdef_ptr == 0) {
2602 return true;
2603 }
2604
2605 size_t offset = 0;
2606
2607 size_t verdef_cnt = si->get_verdef_cnt();
2608 for (size_t i = 0; i<verdef_cnt; ++i) {
2609 const ElfW(Verdef)* verdef = reinterpret_cast<ElfW(Verdef)*>(verdef_ptr + offset);
2610 size_t verdaux_offset = offset + verdef->vd_aux;
2611 offset += verdef->vd_next;
2612
2613 if (verdef->vd_version != 1) {
2614 DL_ERR("unsupported verdef[%zd] vd_version: %d (expected 1) library: %s",
2615 i, verdef->vd_version, si->get_realpath());
2616 return false;
2617 }
2618
2619 if ((verdef->vd_flags & VER_FLG_BASE) != 0) {
2620 // "this is the version of the file itself. It must not be used for
2621 // matching a symbol. It can be used to match references."
2622 //
2623 // http://www.akkadia.org/drepper/symbol-versioning
2624 continue;
2625 }
2626
2627 if (verdef->vd_cnt == 0) {
2628 DL_ERR("invalid verdef[%zd] vd_cnt == 0 (version without a name)", i);
2629 return false;
2630 }
2631
2632 const ElfW(Verdaux)* verdaux = reinterpret_cast<ElfW(Verdaux)*>(verdef_ptr + verdaux_offset);
2633
2634 if (functor(i, verdef, verdaux) == true) {
2635 break;
2636 }
2637 }
2638
2639 return true;
2640}
2641
Ryan Prichard0e12cce2020-01-02 14:59:11 -08002642ElfW(Versym) find_verdef_version_index(const soinfo* si, const version_info* vi) {
Dimitry Ivanov48ec2882016-08-04 11:50:36 -07002643 if (vi == nullptr) {
Ryan Prichard0e12cce2020-01-02 14:59:11 -08002644 return kVersymNotNeeded;
Dimitry Ivanov48ec2882016-08-04 11:50:36 -07002645 }
2646
Ryan Prichard0e12cce2020-01-02 14:59:11 -08002647 ElfW(Versym) result = kVersymGlobal;
Dimitry Ivanov48ec2882016-08-04 11:50:36 -07002648
Ryan Prichard0e12cce2020-01-02 14:59:11 -08002649 if (!for_each_verdef(si,
Dimitry Ivanov48ec2882016-08-04 11:50:36 -07002650 [&](size_t, const ElfW(Verdef)* verdef, const ElfW(Verdaux)* verdaux) {
2651 if (verdef->vd_hash == vi->elf_hash &&
2652 strcmp(vi->name, si->get_string(verdaux->vda_name)) == 0) {
Ryan Prichard0e12cce2020-01-02 14:59:11 -08002653 result = verdef->vd_ndx;
Dimitry Ivanov48ec2882016-08-04 11:50:36 -07002654 return true;
2655 }
2656
2657 return false;
2658 }
Ryan Prichard0e12cce2020-01-02 14:59:11 -08002659 )) {
2660 // verdef should have already been validated in prelink_image.
2661 async_safe_fatal("invalid verdef after prelinking: %s, %s",
2662 si->get_realpath(), linker_get_error_buffer());
2663 }
2664
2665 return result;
2666}
2667
2668// Validate the library's verdef section. On error, returns false and invokes DL_ERR.
2669bool validate_verdef_section(const soinfo* si) {
2670 return for_each_verdef(si,
2671 [&](size_t, const ElfW(Verdef)*, const ElfW(Verdaux)*) {
2672 return false;
2673 });
Dimitry Ivanov48ec2882016-08-04 11:50:36 -07002674}
2675
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07002676bool VersionTracker::init_verdef(const soinfo* si_from) {
2677 return for_each_verdef(si_from,
2678 [&](size_t, const ElfW(Verdef)* verdef, const ElfW(Verdaux)* verdaux) {
2679 add_version_info(verdef->vd_ndx, verdef->vd_hash,
2680 si_from->get_string(verdaux->vda_name), si_from);
2681 return false;
2682 }
2683 );
2684}
2685
2686bool VersionTracker::init(const soinfo* si_from) {
2687 if (!si_from->has_min_version(2)) {
2688 return true;
2689 }
2690
2691 return init_verneed(si_from) && init_verdef(si_from);
2692}
2693
Dimitry Ivanov48ec2882016-08-04 11:50:36 -07002694// TODO (dimitry): Methods below need to be moved out of soinfo
2695// and in more isolated file in order minimize dependencies on
2696// unnecessary object in the linker binary. Consider making them
2697// independent from soinfo (?).
Dmitriy Ivanov31b408d2015-04-30 16:11:48 -07002698bool soinfo::lookup_version_info(const VersionTracker& version_tracker, ElfW(Word) sym,
2699 const char* sym_name, const version_info** vi) {
2700 const ElfW(Versym)* sym_ver_ptr = get_versym(sym);
2701 ElfW(Versym) sym_ver = sym_ver_ptr == nullptr ? 0 : *sym_ver_ptr;
2702
2703 if (sym_ver != VER_NDX_LOCAL && sym_ver != VER_NDX_GLOBAL) {
2704 *vi = version_tracker.get_version_info(sym_ver);
2705
2706 if (*vi == nullptr) {
2707 DL_ERR("cannot find verneed/verdef for version index=%d "
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07002708 "referenced by symbol \"%s\" at \"%s\"", sym_ver, sym_name, get_realpath());
Dmitriy Ivanov31b408d2015-04-30 16:11:48 -07002709 return false;
2710 }
2711 } else {
2712 // there is no version info
2713 *vi = nullptr;
2714 }
2715
2716 return true;
2717}
2718
Rahul Chaudhryf16b6592018-01-25 15:34:15 -08002719void soinfo::apply_relr_reloc(ElfW(Addr) offset) {
2720 ElfW(Addr) address = offset + load_bias;
2721 *reinterpret_cast<ElfW(Addr)*>(address) += load_bias;
2722}
2723
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08002724// Process relocations in SHT_RELR section (experimental).
Rahul Chaudhryf16b6592018-01-25 15:34:15 -08002725// Details of the encoding are described in this post:
2726// https://groups.google.com/d/msg/generic-abi/bX460iggiKg/Pi9aSwwABgAJ
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08002727bool soinfo::relocate_relr() {
2728 ElfW(Relr)* begin = relr_;
2729 ElfW(Relr)* end = relr_ + relr_count_;
Rahul Chaudhryf16b6592018-01-25 15:34:15 -08002730 constexpr size_t wordsize = sizeof(ElfW(Addr));
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08002731
Rahul Chaudhryf16b6592018-01-25 15:34:15 -08002732 ElfW(Addr) base = 0;
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08002733 for (ElfW(Relr)* current = begin; current < end; ++current) {
Rahul Chaudhryf16b6592018-01-25 15:34:15 -08002734 ElfW(Relr) entry = *current;
2735 ElfW(Addr) offset;
2736
2737 if ((entry&1) == 0) {
2738 // Even entry: encodes the offset for next relocation.
2739 offset = static_cast<ElfW(Addr)>(entry);
2740 apply_relr_reloc(offset);
2741 // Set base offset for subsequent bitmap entries.
2742 base = offset + wordsize;
2743 continue;
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08002744 }
Rahul Chaudhryf16b6592018-01-25 15:34:15 -08002745
2746 // Odd entry: encodes bitmap for relocations starting at base.
2747 offset = base;
2748 while (entry != 0) {
2749 entry >>= 1;
2750 if ((entry&1) != 0) {
2751 apply_relr_reloc(offset);
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08002752 }
Rahul Chaudhryf16b6592018-01-25 15:34:15 -08002753 offset += wordsize;
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08002754 }
Rahul Chaudhryf16b6592018-01-25 15:34:15 -08002755
2756 // Advance base offset by 63 words for 64-bit platforms,
2757 // or 31 words for 32-bit platforms.
2758 base += (8*wordsize - 1) * wordsize;
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08002759 }
2760 return true;
2761}
2762
Dimitry Ivanov48ec2882016-08-04 11:50:36 -07002763// An empty list of soinfos
Dimitry Ivanovb943f302016-08-03 16:00:10 -07002764static soinfo_list_t g_empty_list;
Dmitriy Ivanovd59e5002014-05-09 09:10:14 -07002765
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002766bool soinfo::prelink_image() {
Ryan Prichardae320cd2019-12-10 12:39:05 -08002767 if (flags_ & FLAG_PRELINKED) return true;
Ningsheng Jiane93be992014-09-16 15:22:10 +08002768 /* Extract dynamic section */
2769 ElfW(Word) dynamic_flags = 0;
2770 phdr_table_get_dynamic_section(phdr, phnum, load_bias, &dynamic, &dynamic_flags);
Dmitriy Ivanov498eb182014-09-05 14:57:59 -07002771
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002772 /* We can't log anything until the linker is relocated */
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08002773 bool relocating_linker = (flags_ & FLAG_LINKER) != 0;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002774 if (!relocating_linker) {
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07002775 INFO("[ Linking \"%s\" ]", get_realpath());
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08002776 DEBUG("si->base = %p si->flags = 0x%08x", reinterpret_cast<void*>(base), flags_);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002777 }
2778
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002779 if (dynamic == nullptr) {
David 'Digit' Turnerb52e4382012-06-19 01:24:17 +02002780 if (!relocating_linker) {
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07002781 DL_ERR("missing PT_DYNAMIC in \"%s\"", get_realpath());
David 'Digit' Turnerb52e4382012-06-19 01:24:17 +02002782 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002783 return false;
2784 } else {
2785 if (!relocating_linker) {
2786 DEBUG("dynamic = %p", dynamic);
David 'Digit' Turner63f99f42012-06-19 00:08:39 +02002787 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002788 }
David 'Digit' Turner63f99f42012-06-19 00:08:39 +02002789
Elliott Hughes4eeb1f12013-10-25 17:38:02 -07002790#if defined(__arm__)
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002791 (void) phdr_table_get_arm_exidx(phdr, phnum, load_bias,
2792 &ARM_exidx, &ARM_exidx_count);
David 'Digit' Turner63f99f42012-06-19 00:08:39 +02002793#endif
2794
Ryan Pricharde5e69e02019-01-01 18:53:48 -08002795 TlsSegment tls_segment;
Ryan Prichard19883502019-01-16 23:13:38 -08002796 if (__bionic_get_tls_segment(phdr, phnum, load_bias, &tls_segment)) {
2797 if (!__bionic_check_tls_alignment(&tls_segment.alignment)) {
2798 if (!relocating_linker) {
2799 DL_ERR("TLS segment alignment in \"%s\" is not a power of 2: %zu",
2800 get_realpath(), tls_segment.alignment);
2801 }
2802 return false;
2803 }
Ryan Pricharde5e69e02019-01-01 18:53:48 -08002804 tls_ = std::make_unique<soinfo_tls>();
2805 tls_->segment = tls_segment;
2806 }
2807
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002808 // Extract useful information from dynamic section.
Dmitriy Ivanov618f1a32015-03-17 20:06:36 -07002809 // Note that: "Except for the DT_NULL element at the end of the array,
2810 // and the relative order of DT_NEEDED elements, entries may appear in any order."
2811 //
2812 // source: http://www.sco.com/developers/gabi/1998-04-29/ch5.dynamic.html
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002813 uint32_t needed_count = 0;
2814 for (ElfW(Dyn)* d = dynamic; d->d_tag != DT_NULL; ++d) {
2815 DEBUG("d = %p, d[0](tag) = %p d[1](val) = %p",
2816 d, reinterpret_cast<void*>(d->d_tag), reinterpret_cast<void*>(d->d_un.d_val));
2817 switch (d->d_tag) {
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07002818 case DT_SONAME:
Dmitriy Ivanov618f1a32015-03-17 20:06:36 -07002819 // this is parsed after we have strtab initialized (see below).
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07002820 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002821
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002822 case DT_HASH:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002823 nbucket_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[0];
2824 nchain_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[1];
2825 bucket_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr + 8);
2826 chain_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr + 8 + nbucket_ * 4);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002827 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002828
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -08002829 case DT_GNU_HASH:
Dmitriy Ivanov3597b802015-03-09 12:02:02 -07002830 gnu_nbucket_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[0];
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -08002831 // skip symndx
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002832 gnu_maskwords_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[2];
2833 gnu_shift2_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[3];
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -08002834
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002835 gnu_bloom_filter_ = reinterpret_cast<ElfW(Addr)*>(load_bias + d->d_un.d_ptr + 16);
Dmitriy Ivanov3597b802015-03-09 12:02:02 -07002836 gnu_bucket_ = reinterpret_cast<uint32_t*>(gnu_bloom_filter_ + gnu_maskwords_);
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -08002837 // amend chain for symndx = header[1]
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07002838 gnu_chain_ = gnu_bucket_ + gnu_nbucket_ -
2839 reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[1];
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -08002840
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002841 if (!powerof2(gnu_maskwords_)) {
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07002842 DL_ERR("invalid maskwords for gnu_hash = 0x%x, in \"%s\" expecting power to two",
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07002843 gnu_maskwords_, get_realpath());
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -08002844 return false;
2845 }
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002846 --gnu_maskwords_;
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -08002847
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08002848 flags_ |= FLAG_GNU_HASH;
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -08002849 break;
2850
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002851 case DT_STRTAB:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002852 strtab_ = reinterpret_cast<const char*>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002853 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002854
Dmitriy Ivanov6cdeb522014-09-29 19:14:45 -07002855 case DT_STRSZ:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002856 strtab_size_ = d->d_un.d_val;
Dmitriy Ivanov6cdeb522014-09-29 19:14:45 -07002857 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002858
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002859 case DT_SYMTAB:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002860 symtab_ = reinterpret_cast<ElfW(Sym)*>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002861 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002862
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07002863 case DT_SYMENT:
2864 if (d->d_un.d_val != sizeof(ElfW(Sym))) {
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07002865 DL_ERR("invalid DT_SYMENT: %zd in \"%s\"",
2866 static_cast<size_t>(d->d_un.d_val), get_realpath());
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07002867 return false;
2868 }
2869 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002870
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002871 case DT_PLTREL:
Dmitriy Ivanov513e29e2014-10-06 11:30:43 -07002872#if defined(USE_RELA)
2873 if (d->d_un.d_val != DT_RELA) {
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07002874 DL_ERR("unsupported DT_PLTREL in \"%s\"; expected DT_RELA", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002875 return false;
2876 }
Dmitriy Ivanov513e29e2014-10-06 11:30:43 -07002877#else
2878 if (d->d_un.d_val != DT_REL) {
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07002879 DL_ERR("unsupported DT_PLTREL in \"%s\"; expected DT_REL", get_realpath());
Dmitriy Ivanov513e29e2014-10-06 11:30:43 -07002880 return false;
2881 }
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07002882#endif
Dmitriy Ivanov513e29e2014-10-06 11:30:43 -07002883 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002884
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002885 case DT_JMPREL:
Elliott Hughes4eeb1f12013-10-25 17:38:02 -07002886#if defined(USE_RELA)
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002887 plt_rela_ = reinterpret_cast<ElfW(Rela)*>(load_bias + d->d_un.d_ptr);
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07002888#else
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002889 plt_rel_ = reinterpret_cast<ElfW(Rel)*>(load_bias + d->d_un.d_ptr);
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07002890#endif
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002891 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002892
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002893 case DT_PLTRELSZ:
Elliott Hughes4eeb1f12013-10-25 17:38:02 -07002894#if defined(USE_RELA)
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002895 plt_rela_count_ = d->d_un.d_val / sizeof(ElfW(Rela));
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07002896#else
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002897 plt_rel_count_ = d->d_un.d_val / sizeof(ElfW(Rel));
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07002898#endif
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002899 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002900
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002901 case DT_PLTGOT:
Elliott Hughes14798932020-02-13 15:40:07 -08002902 // Ignored (because RTLD_LAZY is not supported).
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07002903 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002904
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002905 case DT_DEBUG:
2906 // Set the DT_DEBUG entry to the address of _r_debug for GDB
2907 // if the dynamic table is writable
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002908 if ((dynamic_flags & PF_W) != 0) {
2909 d->d_un.d_val = reinterpret_cast<uintptr_t>(&_r_debug);
2910 }
Dmitriy Ivanovc6292ea2015-02-13 16:29:50 -08002911 break;
Elliott Hughes4eeb1f12013-10-25 17:38:02 -07002912#if defined(USE_RELA)
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002913 case DT_RELA:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002914 rela_ = reinterpret_cast<ElfW(Rela)*>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002915 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002916
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002917 case DT_RELASZ:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002918 rela_count_ = d->d_un.d_val / sizeof(ElfW(Rela));
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002919 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002920
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08002921 case DT_ANDROID_RELA:
2922 android_relocs_ = reinterpret_cast<uint8_t*>(load_bias + d->d_un.d_ptr);
2923 break;
2924
2925 case DT_ANDROID_RELASZ:
2926 android_relocs_size_ = d->d_un.d_val;
2927 break;
2928
2929 case DT_ANDROID_REL:
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07002930 DL_ERR("unsupported DT_ANDROID_REL in \"%s\"", get_realpath());
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08002931 return false;
2932
2933 case DT_ANDROID_RELSZ:
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07002934 DL_ERR("unsupported DT_ANDROID_RELSZ in \"%s\"", get_realpath());
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08002935 return false;
2936
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07002937 case DT_RELAENT:
2938 if (d->d_un.d_val != sizeof(ElfW(Rela))) {
Dmitriy Ivanovf240aa82014-09-16 23:34:20 -07002939 DL_ERR("invalid DT_RELAENT: %zd", static_cast<size_t>(d->d_un.d_val));
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07002940 return false;
2941 }
2942 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002943
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08002944 // Ignored (see DT_RELCOUNT comments for details).
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07002945 case DT_RELACOUNT:
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07002946 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002947
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002948 case DT_REL:
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07002949 DL_ERR("unsupported DT_REL in \"%s\"", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002950 return false;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002951
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002952 case DT_RELSZ:
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07002953 DL_ERR("unsupported DT_RELSZ in \"%s\"", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002954 return false;
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08002955
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07002956#else
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002957 case DT_REL:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002958 rel_ = reinterpret_cast<ElfW(Rel)*>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002959 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002960
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002961 case DT_RELSZ:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002962 rel_count_ = d->d_un.d_val / sizeof(ElfW(Rel));
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002963 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002964
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07002965 case DT_RELENT:
2966 if (d->d_un.d_val != sizeof(ElfW(Rel))) {
Dmitriy Ivanovf240aa82014-09-16 23:34:20 -07002967 DL_ERR("invalid DT_RELENT: %zd", static_cast<size_t>(d->d_un.d_val));
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07002968 return false;
2969 }
2970 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002971
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08002972 case DT_ANDROID_REL:
2973 android_relocs_ = reinterpret_cast<uint8_t*>(load_bias + d->d_un.d_ptr);
2974 break;
2975
2976 case DT_ANDROID_RELSZ:
2977 android_relocs_size_ = d->d_un.d_val;
2978 break;
2979
2980 case DT_ANDROID_RELA:
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07002981 DL_ERR("unsupported DT_ANDROID_RELA in \"%s\"", get_realpath());
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08002982 return false;
2983
2984 case DT_ANDROID_RELASZ:
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07002985 DL_ERR("unsupported DT_ANDROID_RELASZ in \"%s\"", get_realpath());
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08002986 return false;
2987
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002988 // "Indicates that all RELATIVE relocations have been concatenated together,
2989 // and specifies the RELATIVE relocation count."
2990 //
2991 // TODO: Spec also mentions that this can be used to optimize relocation process;
2992 // Not currently used by bionic linker - ignored.
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07002993 case DT_RELCOUNT:
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07002994 break;
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08002995
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002996 case DT_RELA:
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07002997 DL_ERR("unsupported DT_RELA in \"%s\"", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002998 return false;
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08002999
3000 case DT_RELASZ:
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003001 DL_ERR("unsupported DT_RELASZ in \"%s\"", get_realpath());
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08003002 return false;
3003
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07003004#endif
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08003005 case DT_RELR:
Elliott Hughes6663f552020-01-24 14:36:10 -08003006 case DT_ANDROID_RELR:
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08003007 relr_ = reinterpret_cast<ElfW(Relr)*>(load_bias + d->d_un.d_ptr);
3008 break;
3009
3010 case DT_RELRSZ:
Elliott Hughes6663f552020-01-24 14:36:10 -08003011 case DT_ANDROID_RELRSZ:
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08003012 relr_count_ = d->d_un.d_val / sizeof(ElfW(Relr));
3013 break;
3014
3015 case DT_RELRENT:
Elliott Hughes6663f552020-01-24 14:36:10 -08003016 case DT_ANDROID_RELRENT:
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08003017 if (d->d_un.d_val != sizeof(ElfW(Relr))) {
3018 DL_ERR("invalid DT_RELRENT: %zd", static_cast<size_t>(d->d_un.d_val));
3019 return false;
3020 }
3021 break;
3022
3023 // Ignored (see DT_RELCOUNT comments for details).
Elliott Hughes6663f552020-01-24 14:36:10 -08003024 // There is no DT_RELRCOUNT specifically because it would only be ignored.
3025 case DT_ANDROID_RELRCOUNT:
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08003026 break;
3027
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003028 case DT_INIT:
Dimitry Ivanov55437462016-07-20 15:33:07 -07003029 init_func_ = reinterpret_cast<linker_ctor_function_t>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003030 DEBUG("%s constructors (DT_INIT) found at %p", get_realpath(), init_func_);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003031 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003032
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003033 case DT_FINI:
Dimitry Ivanov55437462016-07-20 15:33:07 -07003034 fini_func_ = reinterpret_cast<linker_dtor_function_t>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003035 DEBUG("%s destructors (DT_FINI) found at %p", get_realpath(), fini_func_);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003036 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003037
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003038 case DT_INIT_ARRAY:
Dimitry Ivanov55437462016-07-20 15:33:07 -07003039 init_array_ = reinterpret_cast<linker_ctor_function_t*>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003040 DEBUG("%s constructors (DT_INIT_ARRAY) found at %p", get_realpath(), init_array_);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003041 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003042
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003043 case DT_INIT_ARRAYSZ:
Dmitriy Ivanov1649e7e2015-01-22 16:04:25 -08003044 init_array_count_ = static_cast<uint32_t>(d->d_un.d_val) / sizeof(ElfW(Addr));
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003045 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003046
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003047 case DT_FINI_ARRAY:
Dimitry Ivanov55437462016-07-20 15:33:07 -07003048 fini_array_ = reinterpret_cast<linker_dtor_function_t*>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003049 DEBUG("%s destructors (DT_FINI_ARRAY) found at %p", get_realpath(), fini_array_);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003050 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003051
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003052 case DT_FINI_ARRAYSZ:
Dmitriy Ivanov1649e7e2015-01-22 16:04:25 -08003053 fini_array_count_ = static_cast<uint32_t>(d->d_un.d_val) / sizeof(ElfW(Addr));
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003054 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003055
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003056 case DT_PREINIT_ARRAY:
Dimitry Ivanov55437462016-07-20 15:33:07 -07003057 preinit_array_ = reinterpret_cast<linker_ctor_function_t*>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003058 DEBUG("%s constructors (DT_PREINIT_ARRAY) found at %p", get_realpath(), preinit_array_);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003059 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003060
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003061 case DT_PREINIT_ARRAYSZ:
Dmitriy Ivanov1649e7e2015-01-22 16:04:25 -08003062 preinit_array_count_ = static_cast<uint32_t>(d->d_un.d_val) / sizeof(ElfW(Addr));
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003063 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003064
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003065 case DT_TEXTREL:
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003066#if defined(__LP64__)
Dimitry Ivanov816676e2016-10-19 11:00:28 -07003067 DL_ERR("\"%s\" has text relocations", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003068 return false;
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003069#else
3070 has_text_relocations = true;
3071 break;
3072#endif
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003073
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003074 case DT_SYMBOLIC:
Dmitriy Ivanov96bc37f2014-09-29 12:10:36 -07003075 has_DT_SYMBOLIC = true;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003076 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003077
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003078 case DT_NEEDED:
3079 ++needed_count;
3080 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003081
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003082 case DT_FLAGS:
3083 if (d->d_un.d_val & DF_TEXTREL) {
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003084#if defined(__LP64__)
Dimitry Ivanov816676e2016-10-19 11:00:28 -07003085 DL_ERR("\"%s\" has text relocations", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003086 return false;
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003087#else
3088 has_text_relocations = true;
3089#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08003090 }
Dmitriy Ivanov96bc37f2014-09-29 12:10:36 -07003091 if (d->d_un.d_val & DF_SYMBOLIC) {
3092 has_DT_SYMBOLIC = true;
3093 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003094 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003095
Dmitriy Ivanov6cdeb522014-09-29 19:14:45 -07003096 case DT_FLAGS_1:
Dmitriy Ivanovd225a5e2014-08-28 14:12:12 -07003097 set_dt_flags_1(d->d_un.d_val);
Dmitriy Ivanov1b20daf2014-05-19 15:06:58 -07003098
Dmitriy Ivanovd225a5e2014-08-28 14:12:12 -07003099 if ((d->d_un.d_val & ~SUPPORTED_DT_FLAGS_1) != 0) {
Elliott Hughes9076b0c2018-02-28 11:29:45 -08003100 DL_WARN("Warning: \"%s\" has unsupported flags DT_FLAGS_1=%p "
3101 "(ignoring unsupported flags)",
3102 get_realpath(), reinterpret_cast<void*>(d->d_un.d_val));
Dmitriy Ivanov6cdeb522014-09-29 19:14:45 -07003103 }
3104 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003105
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003106 // Ignored: "Its use has been superseded by the DF_BIND_NOW flag"
3107 case DT_BIND_NOW:
3108 break;
3109
Dmitriy Ivanov513e29e2014-10-06 11:30:43 -07003110 case DT_VERSYM:
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07003111 versym_ = reinterpret_cast<ElfW(Versym)*>(load_bias + d->d_un.d_ptr);
3112 break;
3113
Dmitriy Ivanov513e29e2014-10-06 11:30:43 -07003114 case DT_VERDEF:
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07003115 verdef_ptr_ = load_bias + d->d_un.d_ptr;
3116 break;
Dmitriy Ivanov513e29e2014-10-06 11:30:43 -07003117 case DT_VERDEFNUM:
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07003118 verdef_cnt_ = d->d_un.d_val;
3119 break;
3120
Alexander Ivchenkoe8314332014-12-02 15:32:25 +03003121 case DT_VERNEED:
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07003122 verneed_ptr_ = load_bias + d->d_un.d_ptr;
3123 break;
3124
Alexander Ivchenkoe8314332014-12-02 15:32:25 +03003125 case DT_VERNEEDNUM:
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07003126 verneed_cnt_ = d->d_un.d_val;
Dmitriy Ivanov513e29e2014-10-06 11:30:43 -07003127 break;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003128
Evgenii Stepanov68650822015-06-10 13:38:39 -07003129 case DT_RUNPATH:
3130 // this is parsed after we have strtab initialized (see below).
3131 break;
3132
Ryan Prichardea41ab02019-01-23 16:33:03 -08003133 case DT_TLSDESC_GOT:
3134 case DT_TLSDESC_PLT:
3135 // These DT entries are used for lazy TLSDESC relocations. Bionic
3136 // resolves everything eagerly, so these can be ignored.
3137 break;
3138
Tamas Petz8d55d182020-02-24 14:15:25 +01003139#if defined(__aarch64__)
3140 case DT_AARCH64_BTI_PLT:
3141 case DT_AARCH64_PAC_PLT:
3142 case DT_AARCH64_VARIANT_PCS:
3143 // Ignored: AArch64 processor-specific dynamic array tags.
3144 break;
3145#endif
3146
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003147 default:
Dmitriy Ivanov8f61d992014-09-16 14:31:06 -07003148 if (!relocating_linker) {
Elliott Hughes6eae4cc2017-08-30 09:02:33 -07003149 const char* tag_name;
3150 if (d->d_tag == DT_RPATH) {
3151 tag_name = "DT_RPATH";
3152 } else if (d->d_tag == DT_ENCODING) {
3153 tag_name = "DT_ENCODING";
3154 } else if (d->d_tag >= DT_LOOS && d->d_tag <= DT_HIOS) {
3155 tag_name = "unknown OS-specific";
3156 } else if (d->d_tag >= DT_LOPROC && d->d_tag <= DT_HIPROC) {
3157 tag_name = "unknown processor-specific";
3158 } else {
3159 tag_name = "unknown";
3160 }
Elliott Hughes9076b0c2018-02-28 11:29:45 -08003161 DL_WARN("Warning: \"%s\" unused DT entry: %s (type %p arg %p) (ignoring)",
Elliott Hughes6eae4cc2017-08-30 09:02:33 -07003162 get_realpath(),
3163 tag_name,
3164 reinterpret_cast<void*>(d->d_tag),
3165 reinterpret_cast<void*>(d->d_un.d_val));
Dmitriy Ivanov8f61d992014-09-16 14:31:06 -07003166 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003167 break;
Brian Carlstromd4ee82d2013-02-28 15:58:45 -08003168 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003169 }
3170
3171 DEBUG("si->base = %p, si->strtab = %p, si->symtab = %p",
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003172 reinterpret_cast<void*>(base), strtab_, symtab_);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003173
Elliott Hughes68ae6ad2020-07-21 16:11:30 -07003174 // Validity checks.
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003175 if (relocating_linker && needed_count != 0) {
3176 DL_ERR("linker cannot have DT_NEEDED dependencies on other libraries");
3177 return false;
3178 }
Dmitriy Ivanov3597b802015-03-09 12:02:02 -07003179 if (nbucket_ == 0 && gnu_nbucket_ == 0) {
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003180 DL_ERR("empty/missing DT_HASH/DT_GNU_HASH in \"%s\" "
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07003181 "(new hash type from the future?)", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003182 return false;
3183 }
Yi Kong32bc0fc2018-08-02 17:31:13 -07003184 if (strtab_ == nullptr) {
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07003185 DL_ERR("empty/missing DT_STRTAB in \"%s\"", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003186 return false;
3187 }
Yi Kong32bc0fc2018-08-02 17:31:13 -07003188 if (symtab_ == nullptr) {
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07003189 DL_ERR("empty/missing DT_SYMTAB in \"%s\"", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003190 return false;
3191 }
Dmitriy Ivanov75108f42015-06-02 13:28:06 -07003192
Ryan Prichardbb1e3732021-01-12 23:09:10 -08003193 // Second pass - parse entries relying on strtab. Skip this while relocating the linker so as to
3194 // avoid doing heap allocations until later in the linker's initialization.
3195 if (!relocating_linker) {
3196 for (ElfW(Dyn)* d = dynamic; d->d_tag != DT_NULL; ++d) {
3197 switch (d->d_tag) {
3198 case DT_SONAME:
3199 set_soname(get_string(d->d_un.d_val));
3200 break;
3201 case DT_RUNPATH:
3202 set_dt_runpath(get_string(d->d_un.d_val));
3203 break;
3204 }
Dmitriy Ivanov624b8f12015-06-08 10:41:33 -07003205 }
3206 }
3207
Ryan Prichardbb1e3732021-01-12 23:09:10 -08003208 // Before M release, linker was using basename in place of soname. In the case when DT_SONAME is
3209 // absent some apps stop working because they can't find DT_NEEDED library by soname. This
3210 // workaround should keep them working. (Applies only for apps targeting sdk version < M.) Make
3211 // an exception for the main executable, which does not need to have DT_SONAME. The linker has an
3212 // DT_SONAME but the soname_ field is initialized later on.
3213 if (soname_.empty() && this != solist_get_somain() && !relocating_linker &&
Elliott Hughes95c6cd72019-12-20 13:26:14 -08003214 get_application_target_sdk_version() < 23) {
Dmitriy Ivanov75108f42015-06-02 13:28:06 -07003215 soname_ = basename(realpath_.c_str());
Elliott Hughesf9dd1a72021-01-11 09:04:58 -08003216 DL_WARN_documented_change(23, "missing-soname-enforced-for-api-level-23",
3217 "\"%s\" has no DT_SONAME (will use %s instead)", get_realpath(),
3218 soname_.c_str());
Elliott Hughes9076b0c2018-02-28 11:29:45 -08003219
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07003220 // 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 -07003221 }
Ryan Prichardae320cd2019-12-10 12:39:05 -08003222
Ryan Prichard0e12cce2020-01-02 14:59:11 -08003223 // Validate each library's verdef section once, so we don't have to validate
3224 // it each time we look up a symbol with a version.
3225 if (!validate_verdef_section(this)) return false;
3226
Ryan Prichardae320cd2019-12-10 12:39:05 -08003227 flags_ |= FLAG_PRELINKED;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003228 return true;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07003229}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08003230
Ryan Prichard339ecef2020-01-02 16:36:06 -08003231bool soinfo::link_image(const SymbolLookupList& lookup_list, soinfo* local_group_root,
Torne (Richard Coles)efbe9a52018-10-17 15:59:38 -04003232 const android_dlextinfo* extinfo, size_t* relro_fd_offset) {
dimitry965d06d2017-11-28 16:03:07 +01003233 if (is_image_linked()) {
3234 // already linked.
3235 return true;
3236 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08003237
Elliott Hughes90f96b92019-05-09 15:56:39 -07003238 if (g_is_ldd && !is_main_executable()) {
3239 async_safe_format_fd(STDOUT_FILENO, "\t%s => %s (%p)\n", get_soname(),
3240 get_realpath(), reinterpret_cast<void*>(base));
3241 }
3242
Ryan Prichard339ecef2020-01-02 16:36:06 -08003243 local_group_root_ = local_group_root;
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08003244 if (local_group_root_ == nullptr) {
3245 local_group_root_ = this;
3246 }
3247
Dmitriy Ivanov19133522015-06-02 17:36:54 -07003248 if ((flags_ & FLAG_LINKER) == 0 && local_group_root_ == this) {
3249 target_sdk_version_ = get_application_target_sdk_version();
3250 }
3251
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003252#if !defined(__LP64__)
3253 if (has_text_relocations) {
Elliott Hughes5bc78c82016-11-16 11:35:43 -08003254 // Fail if app is targeting M or above.
Elliott Hughes9076b0c2018-02-28 11:29:45 -08003255 int app_target_api_level = get_application_target_sdk_version();
Elliott Hughes95c6cd72019-12-20 13:26:14 -08003256 if (app_target_api_level >= 23) {
Ryan Prichard146620b2020-03-26 19:55:05 -07003257 DL_ERR_AND_LOG("\"%s\" has text relocations (%s#Text-Relocations-Enforced-for-API-level-23)",
3258 get_realpath(), kBionicChangesUrl);
Dmitriy Ivanove4ad91f2015-06-12 15:00:31 -07003259 return false;
3260 }
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003261 // Make segments writable to allow text relocations to work properly. We will later call
Dmitriy Ivanov7e039932015-10-01 14:02:19 -07003262 // phdr_table_protect_segments() after all of them are applied.
Elliott Hughes95c6cd72019-12-20 13:26:14 -08003263 DL_WARN_documented_change(23,
Elliott Hughes9076b0c2018-02-28 11:29:45 -08003264 "Text-Relocations-Enforced-for-API-level-23",
3265 "\"%s\" has text relocations",
3266 get_realpath());
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07003267 add_dlwarning(get_realpath(), "text relocations");
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003268 if (phdr_table_unprotect_segments(phdr, phnum, load_bias) < 0) {
Elliott Hughes9076b0c2018-02-28 11:29:45 -08003269 DL_ERR("can't unprotect loadable segments for \"%s\": %s", get_realpath(), strerror(errno));
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003270 return false;
3271 }
3272 }
3273#endif
3274
Ryan Prichard339ecef2020-01-02 16:36:06 -08003275 if (!relocate(lookup_list)) {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003276 return false;
3277 }
Raghu Gandhamd7daacb2012-07-31 12:07:22 -07003278
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07003279 DEBUG("[ finished linking %s ]", get_realpath());
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08003280
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003281#if !defined(__LP64__)
3282 if (has_text_relocations) {
3283 // All relocations are done, we can protect our segments back to read-only.
3284 if (phdr_table_protect_segments(phdr, phnum, load_bias) < 0) {
3285 DL_ERR("can't protect segments for \"%s\": %s",
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07003286 get_realpath(), strerror(errno));
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003287 return false;
3288 }
3289 }
3290#endif
3291
Mingwei Shibe910522015-11-12 07:02:14 +00003292 // We can also turn on GNU RELRO protection if we're not linking the dynamic linker
3293 // itself --- it can't make system calls yet, and will have to call protect_relro later.
3294 if (!is_linker() && !protect_relro()) {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003295 return false;
3296 }
Nick Kralevich9ec0f032012-02-28 10:40:00 -08003297
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003298 /* Handle serializing/sharing the RELRO segment */
3299 if (extinfo && (extinfo->flags & ANDROID_DLEXT_WRITE_RELRO)) {
3300 if (phdr_table_serialize_gnu_relro(phdr, phnum, load_bias,
Torne (Richard Coles)fa9f7f22019-04-02 17:04:42 -04003301 extinfo->relro_fd, relro_fd_offset) < 0) {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003302 DL_ERR("failed serializing GNU RELRO section for \"%s\": %s",
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07003303 get_realpath(), strerror(errno));
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003304 return false;
Torne (Richard Coles)183ad9d2014-02-27 13:18:00 +00003305 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003306 } else if (extinfo && (extinfo->flags & ANDROID_DLEXT_USE_RELRO)) {
3307 if (phdr_table_map_gnu_relro(phdr, phnum, load_bias,
Torne (Richard Coles)efbe9a52018-10-17 15:59:38 -04003308 extinfo->relro_fd, relro_fd_offset) < 0) {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003309 DL_ERR("failed mapping GNU RELRO section for \"%s\": %s",
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07003310 get_realpath(), strerror(errno));
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003311 return false;
3312 }
3313 }
Torne (Richard Coles)183ad9d2014-02-27 13:18:00 +00003314
Ryan Pricharda2e83ab2019-08-16 17:25:43 -07003315 ++g_module_load_counter;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003316 notify_gdb_of_load(this);
dimitry965d06d2017-11-28 16:03:07 +01003317 set_image_linked();
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003318 return true;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08003319}
3320
Mingwei Shibe910522015-11-12 07:02:14 +00003321bool soinfo::protect_relro() {
3322 if (phdr_table_protect_gnu_relro(phdr, phnum, load_bias) < 0) {
3323 DL_ERR("can't enable GNU RELRO protection for \"%s\": %s",
3324 get_realpath(), strerror(errno));
3325 return false;
3326 }
3327 return true;
3328}
3329
Jiyong Park02586a22017-05-20 01:01:24 +09003330static std::vector<android_namespace_t*> init_default_namespace_no_config(bool is_asan) {
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07003331 g_default_namespace.set_isolated(false);
Dimitry Ivanov77ad6422017-03-06 13:02:29 -08003332 auto default_ld_paths = is_asan ? kAsanDefaultLdPaths : kDefaultLdPaths;
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07003333
neo.chae2589f9d2016-10-04 11:00:27 +09003334 char real_path[PATH_MAX];
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07003335 std::vector<std::string> ld_default_paths;
Dimitry Ivanov77ad6422017-03-06 13:02:29 -08003336 for (size_t i = 0; default_ld_paths[i] != nullptr; ++i) {
3337 if (realpath(default_ld_paths[i], real_path) != nullptr) {
neo.chae2589f9d2016-10-04 11:00:27 +09003338 ld_default_paths.push_back(real_path);
3339 } else {
Dimitry Ivanov77ad6422017-03-06 13:02:29 -08003340 ld_default_paths.push_back(default_ld_paths[i]);
neo.chae2589f9d2016-10-04 11:00:27 +09003341 }
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07003342 }
3343
3344 g_default_namespace.set_default_library_paths(std::move(ld_default_paths));
Jiyong Park02586a22017-05-20 01:01:24 +09003345
3346 std::vector<android_namespace_t*> namespaces;
3347 namespaces.push_back(&g_default_namespace);
3348 return namespaces;
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08003349}
3350
Roland Levillain57e6b862020-02-12 17:34:20 +00003351// Given an `executable_path` starting with "/apex/<name>/bin/, return
Jiyong Park2bac1f82022-04-05 14:03:34 +09003352// "/linkerconfig/<name>/ld.config.txt", which is the auto-generated config file for the APEX by the
3353// linkerconfig tool.
Jiyong Park35833412018-10-26 14:45:21 +09003354static std::string get_ld_config_file_apex_path(const char* executable_path) {
3355 std::vector<std::string> paths = android::base::Split(executable_path, "/");
Roland Levillaindc25f6c2019-07-02 16:40:19 +01003356 if (paths.size() >= 5 && paths[1] == "apex" && paths[3] == "bin") {
Kiyoung Kimfb587442020-01-29 16:31:54 +09003357 std::string generated_apex_config = "/linkerconfig/" + paths[2] + "/ld.config.txt";
3358 if (file_exists(generated_apex_config.c_str())) {
3359 return generated_apex_config;
3360 }
Jiyong Park35833412018-10-26 14:45:21 +09003361 }
3362 return "";
3363}
3364
Logan Chien886b96e2018-05-08 17:52:18 +08003365static std::string get_ld_config_file_vndk_path() {
Roland Levillain09bde952019-10-29 19:17:49 +00003366 if (android::base::GetBoolProperty("ro.vndk.lite", false)) {
3367 return kLdConfigVndkLiteFilePath;
Logan Chienbcfe3cf2018-05-08 20:17:26 +08003368 }
3369
Roland Levillain09bde952019-10-29 19:17:49 +00003370 std::string ld_config_file_vndk = kLdConfigFilePath;
3371 size_t insert_pos = ld_config_file_vndk.find_last_of('.');
3372 if (insert_pos == std::string::npos) {
3373 insert_pos = ld_config_file_vndk.length();
3374 }
3375 ld_config_file_vndk.insert(insert_pos, Config::get_vndk_version_string('.'));
3376 return ld_config_file_vndk;
Logan Chien886b96e2018-05-08 17:52:18 +08003377}
3378
Kiyoung Kim46e731c2020-06-26 16:54:50 +09003379bool is_linker_config_expected(const char* executable_path) {
3380 // Do not raise message from a host environment which is expected to miss generated linker
3381 // configuration.
3382#if !defined(__ANDROID__)
3383 return false;
3384#endif
3385
3386 if (strcmp(executable_path, "/system/bin/init") == 0) {
3387 // Generated linker configuration can be missed from processes executed
3388 // with init binary
3389 return false;
3390 }
3391
3392 return true;
3393}
3394
Jiyong Park35833412018-10-26 14:45:21 +09003395static std::string get_ld_config_file_path(const char* executable_path) {
Logan Chien886b96e2018-05-08 17:52:18 +08003396#ifdef USE_LD_CONFIG_FILE
3397 // This is a debugging/testing only feature. Must not be available on
3398 // production builds.
3399 const char* ld_config_file_env = getenv("LD_CONFIG_FILE");
3400 if (ld_config_file_env != nullptr && file_exists(ld_config_file_env)) {
3401 return ld_config_file_env;
3402 }
3403#endif
3404
Jiyong Park35833412018-10-26 14:45:21 +09003405 std::string path = get_ld_config_file_apex_path(executable_path);
3406 if (!path.empty()) {
3407 if (file_exists(path.c_str())) {
3408 return path;
3409 }
3410 DL_WARN("Warning: couldn't read config file \"%s\" for \"%s\"",
3411 path.c_str(), executable_path);
Logan Chien886b96e2018-05-08 17:52:18 +08003412 }
3413
Evgeny Eltsinff43ec02019-12-16 19:22:07 +01003414 path = kLdConfigArchFilePath;
3415 if (file_exists(path.c_str())) {
3416 return path;
3417 }
3418
Kiyoung Kim18786902020-02-12 07:47:37 +09003419 if (file_exists(kLdGeneratedConfigFilePath)) {
3420 return kLdGeneratedConfigFilePath;
Kiyoung Kimef04c802019-12-13 12:19:56 +09003421 }
3422
Kiyoung Kim46e731c2020-06-26 16:54:50 +09003423 if (is_linker_config_expected(executable_path)) {
3424 DL_WARN("Warning: failed to find generated linker configuration from \"%s\"",
3425 kLdGeneratedConfigFilePath);
3426 }
Kiyoung Kim8bc03532020-03-16 13:22:27 +09003427
Jiyong Park35833412018-10-26 14:45:21 +09003428 path = get_ld_config_file_vndk_path();
Roland Levillain09bde952019-10-29 19:17:49 +00003429 if (file_exists(path.c_str())) {
Jiyong Park35833412018-10-26 14:45:21 +09003430 return path;
Logan Chien886b96e2018-05-08 17:52:18 +08003431 }
3432
3433 return kLdConfigFilePath;
3434}
3435
Jiyong Park02586a22017-05-20 01:01:24 +09003436std::vector<android_namespace_t*> init_default_namespaces(const char* executable_path) {
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08003437 g_default_namespace.set_name("(default)");
3438
3439 soinfo* somain = solist_get_somain();
3440
3441 const char *interp = phdr_table_get_interpreter_name(somain->phdr, somain->phnum,
3442 somain->load_bias);
Dan Willemsen7ccc50d2017-09-18 21:28:14 -07003443 const char* bname = (interp != nullptr) ? basename(interp) : nullptr;
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08003444
3445 g_is_asan = bname != nullptr &&
3446 (strcmp(bname, "linker_asan") == 0 ||
3447 strcmp(bname, "linker_asan64") == 0);
3448
3449 const Config* config = nullptr;
3450
Elliott Hughes658b9382020-11-06 09:27:36 -08003451 {
3452 std::string ld_config_file_path = get_ld_config_file_path(executable_path);
3453 INFO("[ Reading linker config \"%s\" ]", ld_config_file_path.c_str());
3454 ScopedTrace trace(("linker config " + ld_config_file_path).c_str());
3455 std::string error_msg;
3456 if (!Config::read_binary_config(ld_config_file_path.c_str(), executable_path, g_is_asan,
3457 &config, &error_msg)) {
3458 if (!error_msg.empty()) {
3459 DL_WARN("Warning: couldn't read '%s' for '%s' (using default configuration instead): %s",
3460 ld_config_file_path.c_str(), executable_path, error_msg.c_str());
3461 }
3462 config = nullptr;
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08003463 }
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08003464 }
3465
3466 if (config == nullptr) {
Jiyong Park02586a22017-05-20 01:01:24 +09003467 return init_default_namespace_no_config(g_is_asan);
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08003468 }
3469
3470 const auto& namespace_configs = config->namespace_configs();
3471 std::unordered_map<std::string, android_namespace_t*> namespaces;
3472
3473 // 1. Initialize default namespace
3474 const NamespaceConfig* default_ns_config = config->default_namespace_config();
3475
3476 g_default_namespace.set_isolated(default_ns_config->isolated());
3477 g_default_namespace.set_default_library_paths(default_ns_config->search_paths());
3478 g_default_namespace.set_permitted_paths(default_ns_config->permitted_paths());
3479
3480 namespaces[default_ns_config->name()] = &g_default_namespace;
Justin Yun90de9f02017-07-07 16:21:53 +09003481 if (default_ns_config->visible()) {
3482 g_exported_namespaces[default_ns_config->name()] = &g_default_namespace;
3483 }
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08003484
3485 // 2. Initialize other namespaces
3486
3487 for (auto& ns_config : namespace_configs) {
3488 if (namespaces.find(ns_config->name()) != namespaces.end()) {
3489 continue;
3490 }
3491
3492 android_namespace_t* ns = new (g_namespace_allocator.alloc()) android_namespace_t();
3493 ns->set_name(ns_config->name());
3494 ns->set_isolated(ns_config->isolated());
3495 ns->set_default_library_paths(ns_config->search_paths());
3496 ns->set_permitted_paths(ns_config->permitted_paths());
Luke Huang30f2f052020-07-30 15:09:18 +08003497 ns->set_allowed_libs(ns_config->allowed_libs());
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08003498
3499 namespaces[ns_config->name()] = ns;
Jiyong Park01de74e2017-04-03 23:10:37 +09003500 if (ns_config->visible()) {
3501 g_exported_namespaces[ns_config->name()] = ns;
3502 }
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08003503 }
3504
3505 // 3. Establish links between namespaces
3506 for (auto& ns_config : namespace_configs) {
3507 auto it_from = namespaces.find(ns_config->name());
3508 CHECK(it_from != namespaces.end());
3509 android_namespace_t* namespace_from = it_from->second;
3510 for (const NamespaceLinkConfig& ns_link : ns_config->links()) {
3511 auto it_to = namespaces.find(ns_link.ns_name());
3512 CHECK(it_to != namespaces.end());
3513 android_namespace_t* namespace_to = it_to->second;
Logan Chien9ee45912018-01-18 12:05:09 +08003514 if (ns_link.allow_all_shared_libs()) {
3515 link_namespaces_all_libs(namespace_from, namespace_to);
3516 } else {
3517 link_namespaces(namespace_from, namespace_to, ns_link.shared_libs().c_str());
3518 }
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08003519 }
3520 }
3521 // we can no longer rely on the fact that libdl.so is part of default namespace
3522 // this is why we want to add ld-android.so to all namespaces from ld.config.txt
3523 soinfo* ld_android_so = solist_get_head();
dimitry8b142562018-05-09 15:22:38 +02003524
3525 // we also need vdso to be available for all namespaces (if present)
3526 soinfo* vdso = solist_get_vdso();
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08003527 for (auto it : namespaces) {
NIEJuhue2871bd2019-12-20 18:51:21 +08003528 if (it.second != &g_default_namespace) {
3529 it.second->add_soinfo(ld_android_so);
3530 if (vdso != nullptr) {
3531 it.second->add_soinfo(vdso);
3532 }
3533 // somain and ld_preloads are added to these namespaces after LD_PRELOAD libs are linked
dimitry8b142562018-05-09 15:22:38 +02003534 }
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08003535 }
3536
3537 set_application_target_sdk_version(config->target_sdk_version());
Jiyong Park02586a22017-05-20 01:01:24 +09003538
3539 std::vector<android_namespace_t*> created_namespaces;
3540 created_namespaces.reserve(namespaces.size());
Chih-Hung Hsieh0218e922018-12-11 10:22:11 -08003541 for (const auto& kv : namespaces) {
Jiyong Park02586a22017-05-20 01:01:24 +09003542 created_namespaces.push_back(kv.second);
3543 }
3544 return created_namespaces;
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08003545}
Jiyong Park01de74e2017-04-03 23:10:37 +09003546
3547// This function finds a namespace exported in ld.config.txt by its name.
3548// A namespace can be exported by setting .visible property to true.
3549android_namespace_t* get_exported_namespace(const char* name) {
3550 if (name == nullptr) {
3551 return nullptr;
3552 }
3553 auto it = g_exported_namespaces.find(std::string(name));
3554 if (it == g_exported_namespaces.end()) {
3555 return nullptr;
3556 }
3557 return it->second;
3558}
Vic Yangbb7e1232019-01-29 20:23:16 -08003559
3560void purge_unused_memory() {
3561 // For now, we only purge the memory used by LoadTask because we know those
3562 // are temporary objects.
3563 //
3564 // Purging other LinkerBlockAllocator hardly yields much because they hold
3565 // information about namespaces and opened libraries, which are not freed
3566 // when the control leaves the linker.
3567 //
3568 // Purging BionicAllocator may give us a few dirty pages back, but those pages
3569 // would be already zeroed out, so they compress easily in ZRAM. Therefore,
3570 // it is not worth munmap()'ing those pages.
3571 TypeBasedAllocator<LoadTask>::purge();
3572}