blob: 7c091f373040ed4c5330bc46c477c17b3ae320e9 [file] [log] [blame]
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001/*
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07002 * Copyright (C) 2008 The Android Open Source Project
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08003 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in
12 * the documentation and/or other materials provided with the
13 * distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28
Dmitriy Ivanov19133522015-06-02 17:36:54 -070029#include <android/api-level.h>
Elliott Hughes46882792012-08-03 16:49:39 -070030#include <errno.h>
31#include <fcntl.h>
Elliott Hughes0266ae52014-02-10 17:46:57 -080032#include <inttypes.h>
Elliott Hughes46882792012-08-03 16:49:39 -070033#include <pthread.h>
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080034#include <stdio.h>
35#include <stdlib.h>
36#include <string.h>
Elliott Hughes46882792012-08-03 16:49:39 -070037#include <sys/mman.h>
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -080038#include <sys/param.h>
Dimitry Ivanovbf34ba32017-04-21 13:12:05 -070039#include <sys/vfs.h>
Elliott Hughes46882792012-08-03 16:49:39 -070040#include <unistd.h>
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080041
Dmitriy Ivanov0d150942014-08-22 12:25:04 -070042#include <new>
Dmitriy Ivanovd165f562015-03-23 18:43:02 -070043#include <string>
Dmitriy Ivanovb4827502015-09-28 16:38:31 -070044#include <unordered_map>
Dmitriy Ivanovd165f562015-03-23 18:43:02 -070045#include <vector>
Dmitriy Ivanov0d150942014-08-22 12:25:04 -070046
Logan Chienbcfe3cf2018-05-08 20:17:26 +080047#include <android-base/properties.h>
Tom Cherryb8ab6182017-04-05 16:20:29 -070048#include <android-base/scopeguard.h>
49
Christopher Ferris7a3681e2017-04-24 17:48:32 -070050#include <async_safe/log.h>
51
Elliott Hughes46882792012-08-03 16:49:39 -070052// Private C library headers.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080053
54#include "linker.h"
Dmitriy Ivanovc9ce70d2015-03-10 15:30:26 -070055#include "linker_block_allocator.h"
Evgenii Stepanov0a3637d2016-07-06 13:20:59 -070056#include "linker_cfi.h"
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -080057#include "linker_config.h"
Dimitry Ivanov6b788ee2016-02-17 16:08:03 -080058#include "linker_gdb_support.h"
Dimitry Ivanov48ec2882016-08-04 11:50:36 -070059#include "linker_globals.h"
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080060#include "linker_debug.h"
Dimitry Ivanov769b33f2016-07-21 11:33:40 -070061#include "linker_dlwarning.h"
Dimitry Ivanov3f660572016-09-09 10:00:39 -070062#include "linker_main.h"
Dimitry Ivanovb943f302016-08-03 16:00:10 -070063#include "linker_namespaces.h"
Dmitriy Ivanov18870d32015-04-22 13:10:04 -070064#include "linker_sleb128.h"
David 'Digit' Turner23363ed2012-06-18 18:13:49 +020065#include "linker_phdr.h"
Ryan Prichardf56ac992020-01-02 16:36:06 -080066#include "linker_relocate.h"
Ryan Pricharde5e69e02019-01-01 18:53:48 -080067#include "linker_tls.h"
Dmitriy Ivanova1feb112015-10-01 18:41:57 -070068#include "linker_utils.h"
tony.ys_liub4474402015-07-29 18:00:22 +080069
Ryan Pricharde5e69e02019-01-01 18:53:48 -080070#include "private/bionic_globals.h"
dimitryfe1b27c2017-08-11 14:43:21 +020071#include "android-base/macros.h"
Elliott Hughes939a7e02015-12-04 15:27:46 -080072#include "android-base/strings.h"
Dimitry Ivanovb996d602016-07-11 18:11:39 -070073#include "android-base/stringprintf.h"
Simon Baldwinaef71952015-01-16 13:22:54 +000074#include "ziparchive/zip_archive.h"
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080075
dimitry06016f22018-01-05 11:39:28 +010076static std::unordered_map<void*, size_t> g_dso_handle_counters;
77
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -070078static android_namespace_t* g_anonymous_namespace = &g_default_namespace;
Jiyong Park01de74e2017-04-03 23:10:37 +090079static std::unordered_map<std::string, android_namespace_t*> g_exported_namespaces;
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -070080
Dmitriy Ivanov600bc3c2015-03-10 15:43:50 -070081static LinkerTypeAllocator<soinfo> g_soinfo_allocator;
82static LinkerTypeAllocator<LinkedListEntry<soinfo>> g_soinfo_links_allocator;
Magnus Malmbornba98d922012-09-12 13:00:55 +020083
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -070084static LinkerTypeAllocator<android_namespace_t> g_namespace_allocator;
Dimitry Ivanovaca299a2016-04-11 12:42:58 -070085static LinkerTypeAllocator<LinkedListEntry<android_namespace_t>> g_namespace_list_allocator;
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -070086
dimitryfe1b27c2017-08-11 14:43:21 +020087static const char* const kLdConfigArchFilePath = "/system/etc/ld.config." ABI_STRING ".txt";
88
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -080089static const char* const kLdConfigFilePath = "/system/etc/ld.config.txt";
Logan Chienbcfe3cf2018-05-08 20:17:26 +080090static const char* const kLdConfigVndkLiteFilePath = "/system/etc/ld.config.vndk_lite.txt";
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -080091
Elliott Hughes4eeb1f12013-10-25 17:38:02 -070092#if defined(__LP64__)
Victor Chang6cb719f2019-02-06 17:19:10 +000093static const char* const kSystemLibDir = "/system/lib64";
94static const char* const kOdmLibDir = "/odm/lib64";
95static const char* const kVendorLibDir = "/vendor/lib64";
96static const char* const kAsanSystemLibDir = "/data/asan/system/lib64";
97static const char* const kAsanOdmLibDir = "/data/asan/odm/lib64";
98static const char* const kAsanVendorLibDir = "/data/asan/vendor/lib64";
99static const char* const kRuntimeApexLibDir = "/apex/com.android.runtime/lib64";
Elliott Hughes011bc0b2013-10-08 14:27:10 -0700100#else
Victor Chang6cb719f2019-02-06 17:19:10 +0000101static const char* const kSystemLibDir = "/system/lib";
102static const char* const kOdmLibDir = "/odm/lib";
103static const char* const kVendorLibDir = "/vendor/lib";
104static const char* const kAsanSystemLibDir = "/data/asan/system/lib";
105static const char* const kAsanOdmLibDir = "/data/asan/odm/lib";
106static const char* const kAsanVendorLibDir = "/data/asan/vendor/lib";
107static const char* const kRuntimeApexLibDir = "/apex/com.android.runtime/lib";
Elliott Hughes011bc0b2013-10-08 14:27:10 -0700108#endif
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700109
Vishwath Mohan4113def2017-03-29 15:31:34 -0700110static const char* const kAsanLibDirPrefix = "/data/asan";
111
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700112static const char* const kDefaultLdPaths[] = {
113 kSystemLibDir,
Alin Jerpelea074a9fd2017-09-25 17:47:49 +0200114 kOdmLibDir,
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700115 kVendorLibDir,
Dmitriy Ivanov851135b2014-08-29 12:02:36 -0700116 nullptr
Elliott Hughes124fae92012-10-31 14:20:03 -0700117};
David Bartleybc3a5c22009-06-02 18:27:28 -0700118
Evgenii Stepanovd640b222015-07-10 17:54:01 -0700119static const char* const kAsanDefaultLdPaths[] = {
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700120 kAsanSystemLibDir,
121 kSystemLibDir,
Alin Jerpelea074a9fd2017-09-25 17:47:49 +0200122 kAsanOdmLibDir,
123 kOdmLibDir,
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700124 kAsanVendorLibDir,
125 kVendorLibDir,
Evgenii Stepanovd640b222015-07-10 17:54:01 -0700126 nullptr
127};
128
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700129// Is ASAN enabled?
130static bool g_is_asan = false;
131
Evgenii Stepanov0a3637d2016-07-06 13:20:59 -0700132static CFIShadowWriter g_cfi_shadow;
133
134CFIShadowWriter* get_cfi_shadow() {
135 return &g_cfi_shadow;
136}
137
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700138static bool is_system_library(const std::string& realpath) {
139 for (const auto& dir : g_default_namespace.get_default_library_paths()) {
140 if (file_is_in_dir(realpath, dir)) {
141 return true;
142 }
143 }
144 return false;
145}
146
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700147// Checks if the file exists and not a directory.
148static bool file_exists(const char* path) {
Dimitry Ivanov4cf70242016-08-11 11:11:52 -0700149 struct stat s;
150
151 if (stat(path, &s) != 0) {
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700152 return false;
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700153 }
Dimitry Ivanov4cf70242016-08-11 11:11:52 -0700154
155 return S_ISREG(s.st_mode);
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700156}
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700157
Dimitry Ivanov35c8e3b2017-02-27 12:17:47 -0800158static std::string resolve_soname(const std::string& name) {
159 // We assume that soname equals to basename here
160
161 // TODO(dimitry): consider having honest absolute-path -> soname resolution
162 // note that since we might end up refusing to load this library because
163 // it is not in shared libs list we need to get the soname without actually loading
164 // the library.
165 //
166 // On the other hand there are several places where we already assume that
167 // soname == basename in particular for any not-loaded library mentioned
168 // in DT_NEEDED list.
169 return basename(name.c_str());
170}
171
172static bool maybe_accessible_via_namespace_links(android_namespace_t* ns, const char* name) {
173 std::string soname = resolve_soname(name);
174 for (auto& ns_link : ns->linked_namespaces()) {
175 if (ns_link.is_accessible(soname.c_str())) {
176 return true;
177 }
178 }
179
180 return false;
181}
182
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700183// TODO(dimitry): The grey-list is a workaround for http://b/26394120 ---
184// gradually remove libraries from this list until it is gone.
Dimitry Ivanov35c8e3b2017-02-27 12:17:47 -0800185static bool is_greylisted(android_namespace_t* ns, const char* name, const soinfo* needed_by) {
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700186 static const char* const kLibraryGreyList[] = {
187 "libandroid_runtime.so",
188 "libbinder.so",
189 "libcrypto.so",
190 "libcutils.so",
191 "libexpat.so",
192 "libgui.so",
193 "libmedia.so",
194 "libnativehelper.so",
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700195 "libssl.so",
196 "libstagefright.so",
197 "libsqlite.so",
198 "libui.so",
199 "libutils.so",
200 "libvorbisidec.so",
201 nullptr
202 };
203
Elliott Hughes5bc78c82016-11-16 11:35:43 -0800204 // If you're targeting N, you don't get the greylist.
Elliott Hughes9e27e582017-03-23 17:42:49 -0700205 if (g_greylist_disabled || get_application_target_sdk_version() >= __ANDROID_API_N__) {
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700206 return false;
207 }
208
209 // if the library needed by a system library - implicitly assume it
Dimitry Ivanov35c8e3b2017-02-27 12:17:47 -0800210 // is greylisted unless it is in the list of shared libraries for one or
211 // more linked namespaces
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700212 if (needed_by != nullptr && is_system_library(needed_by->get_realpath())) {
Dimitry Ivanov35c8e3b2017-02-27 12:17:47 -0800213 return !maybe_accessible_via_namespace_links(ns, name);
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700214 }
215
216 // if this is an absolute path - make sure it points to /system/lib(64)
217 if (name[0] == '/' && dirname(name) == kSystemLibDir) {
218 // and reduce the path to basename
219 name = basename(name);
220 }
221
222 for (size_t i = 0; kLibraryGreyList[i] != nullptr; ++i) {
223 if (strcmp(name, kLibraryGreyList[i]) == 0) {
224 return true;
225 }
226 }
227
228 return false;
229}
230// END OF WORKAROUND
231
Victor Chang6cb719f2019-02-06 17:19:10 +0000232// Workaround for dlopen(/system/lib(64)/<soname>) when .so is in /apex. http://b/121248172
233/**
234 * Translate /system path to /apex path if needed
235 * The workaround should work only when targetSdkVersion < Q.
236 *
237 * param out_name_to_apex pointing to /apex path
238 * return true if translation is needed
239 */
240static bool translateSystemPathToApexPath(const char* name, std::string* out_name_to_apex) {
241 static const char* const kSystemToRuntimeApexLibs[] = {
242 "libicuuc.so",
243 "libicui18n.so",
244 };
245 // New mapping for new apex should be added below
246
247 // Nothing to do if target sdk version is Q or above
248 if (get_application_target_sdk_version() >= __ANDROID_API_Q__) {
249 return false;
250 }
251
252 // If the path isn't /system/lib, there's nothing to do.
253 if (name == nullptr || dirname(name) != kSystemLibDir) {
254 return false;
255 }
256
257 const char* base_name = basename(name);
258
259 for (const char* soname : kSystemToRuntimeApexLibs) {
260 if (strcmp(base_name, soname) == 0) {
261 *out_name_to_apex = std::string(kRuntimeApexLibDir) + "/" + base_name;
262 return true;
263 }
264 }
265
266 return false;
267}
268// End Workaround for dlopen(/system/lib/<soname>) when .so is in /apex.
269
Dmitriy Ivanovd165f562015-03-23 18:43:02 -0700270static std::vector<std::string> g_ld_preload_names;
Elliott Hughesa4aafd12014-01-13 16:37:47 -0800271
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800272static bool g_anonymous_namespace_initialized;
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -0700273
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800274#if COUNT_PAGES
Dmitriy Ivanov114ff692015-01-14 11:36:38 -0800275uint32_t bitmask[4096];
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800276#endif
277
Elliott Hughesbedfe382012-08-14 14:07:59 -0700278static void notify_gdb_of_load(soinfo* info) {
Dimitry Ivanove97d8ed2016-03-01 15:55:56 -0800279 if (info->is_linker() || info->is_main_executable()) {
280 // gdb already knows about the linker and the main executable.
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700281 return;
282 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800283
Dimitry Ivanov6b788ee2016-02-17 16:08:03 -0800284 link_map* map = &(info->link_map_head);
Nicolas Geoffray0fa54102016-02-18 09:31:24 +0000285
Dimitry Ivanov6b788ee2016-02-17 16:08:03 -0800286 map->l_addr = info->load_bias;
287 // link_map l_name field is not const.
288 map->l_name = const_cast<char*>(info->get_realpath());
289 map->l_ld = info->dynamic;
Nicolas Geoffray0fa54102016-02-18 09:31:24 +0000290
Dimitry Ivanove97d8ed2016-03-01 15:55:56 -0800291 CHECK(map->l_name != nullptr);
292 CHECK(map->l_name[0] != '\0');
293
Dimitry Ivanov6b788ee2016-02-17 16:08:03 -0800294 notify_gdb_of_load(map);
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -0700295}
296
Elliott Hughesbedfe382012-08-14 14:07:59 -0700297static void notify_gdb_of_unload(soinfo* info) {
Dimitry Ivanov6b788ee2016-02-17 16:08:03 -0800298 notify_gdb_of_unload(&(info->link_map_head));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800299}
300
Dmitriy Ivanovd59e5002014-05-09 09:10:14 -0700301LinkedListEntry<soinfo>* SoinfoListAllocator::alloc() {
302 return g_soinfo_links_allocator.alloc();
303}
304
305void SoinfoListAllocator::free(LinkedListEntry<soinfo>* entry) {
306 g_soinfo_links_allocator.free(entry);
307}
308
Dimitry Ivanovaca299a2016-04-11 12:42:58 -0700309LinkedListEntry<android_namespace_t>* NamespaceListAllocator::alloc() {
310 return g_namespace_list_allocator.alloc();
311}
312
313void NamespaceListAllocator::free(LinkedListEntry<android_namespace_t>* entry) {
314 g_namespace_list_allocator.free(entry);
315}
316
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700317soinfo* soinfo_alloc(android_namespace_t* ns, const char* name,
Ryan Prichard8f639a42018-10-01 23:10:05 -0700318 const struct stat* file_stat, off64_t file_offset,
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700319 uint32_t rtld_flags) {
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -0700320 if (strlen(name) >= PATH_MAX) {
Elliott Hughes7b0af7a2017-09-15 16:09:22 -0700321 async_safe_fatal("library name \"%s\" too long", name);
Magnus Malmbornba98d922012-09-12 13:00:55 +0200322 }
323
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700324 TRACE("name %s: allocating soinfo for ns=%p", name, ns);
325
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -0700326 soinfo* si = new (g_soinfo_allocator.alloc()) soinfo(ns, name, file_stat,
327 file_offset, rtld_flags);
Dmitriy Ivanovd59e5002014-05-09 09:10:14 -0700328
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700329 solist_add_soinfo(si);
Magnus Malmbornba98d922012-09-12 13:00:55 +0200330
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -0700331 si->generate_handle();
332 ns->add_soinfo(si);
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -0700333
Elliott Hughesca0c11b2013-03-12 10:40:45 -0700334 TRACE("name %s: allocated soinfo @ %p", name, si);
Magnus Malmbornba98d922012-09-12 13:00:55 +0200335 return si;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800336}
337
Elliott Hughesfaf05ba2014-02-11 16:59:37 -0800338static void soinfo_free(soinfo* si) {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700339 if (si == nullptr) {
340 return;
341 }
342
343 if (si->base != 0 && si->size != 0) {
Dimitry Ivanovf45b0e92016-01-15 11:13:35 -0800344 if (!si->is_mapped_by_caller()) {
345 munmap(reinterpret_cast<void*>(si->base), si->size);
346 } else {
347 // remap the region as PROT_NONE, MAP_ANONYMOUS | MAP_NORESERVE
348 mmap(reinterpret_cast<void*>(si->base), si->size, PROT_NONE,
349 MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
350 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700351 }
352
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -0700353 TRACE("name %s: freeing soinfo @ %p", si->get_realpath(), si);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700354
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700355 if (!solist_remove_soinfo(si)) {
dimitry965d06d2017-11-28 16:03:07 +0100356 async_safe_fatal("soinfo=%p is not in soinfo_list (double unload?)", si);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700357 }
Elliott Hughes46882792012-08-03 16:49:39 -0700358
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700359 // clear links to/from si
360 si->remove_all_links();
Dmitriy Ivanovd59e5002014-05-09 09:10:14 -0700361
Dmitriy Ivanov609f11b2015-07-08 15:26:46 -0700362 si->~soinfo();
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700363 g_soinfo_allocator.free(si);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800364}
365
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -0700366static void parse_path(const char* path, const char* delimiters,
367 std::vector<std::string>* resolved_paths) {
368 std::vector<std::string> paths;
369 split_path(path, delimiters, &paths);
370 resolve_paths(paths, resolved_paths);
371}
372
Elliott Hughescade4c32012-12-20 14:42:14 -0800373static void parse_LD_LIBRARY_PATH(const char* path) {
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -0700374 std::vector<std::string> ld_libary_paths;
375 parse_path(path, ":", &ld_libary_paths);
376 g_default_namespace.set_ld_library_paths(std::move(ld_libary_paths));
Elliott Hughescade4c32012-12-20 14:42:14 -0800377}
378
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -0700379static bool realpath_fd(int fd, std::string* realpath) {
Vic Yang99168362019-05-15 21:10:22 -0700380 // proc_self_fd needs to be large enough to hold "/proc/self/fd/" plus an
381 // integer, plus the NULL terminator.
382 char proc_self_fd[32];
383 // We want to statically allocate this large buffer so that we don't grow
384 // the stack by too much.
385 static char buf[PATH_MAX];
386
387 async_safe_format_buffer(proc_self_fd, sizeof(proc_self_fd), "/proc/self/fd/%d", fd);
388 auto length = readlink(proc_self_fd, buf, sizeof(buf));
389 if (length == -1) {
Tom Cherry66bc4282018-11-08 13:40:52 -0800390 if (!is_first_stage_init()) {
Vic Yang99168362019-05-15 21:10:22 -0700391 PRINT("readlink(\"%s\") failed: %s [fd=%d]", proc_self_fd, strerror(errno), fd);
Tom Cherry66bc4282018-11-08 13:40:52 -0800392 }
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -0700393 return false;
394 }
395
Vic Yang99168362019-05-15 21:10:22 -0700396 realpath->assign(buf, length);
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -0700397 return true;
398}
399
Elliott Hughes4eeb1f12013-10-25 17:38:02 -0700400#if defined(__arm__)
Elliott Hughes46882792012-08-03 16:49:39 -0700401
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700402// For a given PC, find the .so that it belongs to.
403// Returns the base address of the .ARM.exidx section
404// for that .so, and the number of 8-byte entries
405// in that section (via *pcount).
406//
407// Intended to be called by libc's __gnu_Unwind_Find_exidx().
Dimitry Ivanovd9e427c2016-11-22 16:55:25 -0800408_Unwind_Ptr do_dl_unwind_find_exidx(_Unwind_Ptr pc, int* pcount) {
Peter Collingbourneb39cb3c2019-03-01 13:12:49 -0800409 if (soinfo* si = find_containing_library(reinterpret_cast<void*>(pc))) {
410 *pcount = si->ARM_exidx_count;
411 return reinterpret_cast<_Unwind_Ptr>(si->ARM_exidx);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700412 }
413 *pcount = 0;
Elliott Hughesf2c6ad62017-04-21 10:25:56 -0700414 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800415}
Elliott Hughes46882792012-08-03 16:49:39 -0700416
Christopher Ferris24053a42013-08-19 17:45:09 -0700417#endif
Elliott Hughes46882792012-08-03 16:49:39 -0700418
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700419// Here, we only have to provide a callback to iterate across all the
420// loaded libraries. gcc_eh does the rest.
Dmitriy Ivanov7271caf2015-06-29 14:48:25 -0700421int do_dl_iterate_phdr(int (*cb)(dl_phdr_info* info, size_t size, void* data), void* data) {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700422 int rv = 0;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700423 for (soinfo* si = solist_get_head(); si != nullptr; si = si->next) {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700424 dl_phdr_info dl_info;
425 dl_info.dlpi_addr = si->link_map_head.l_addr;
426 dl_info.dlpi_name = si->link_map_head.l_name;
427 dl_info.dlpi_phdr = si->phdr;
428 dl_info.dlpi_phnum = si->phnum;
429 rv = cb(&dl_info, sizeof(dl_phdr_info), data);
430 if (rv != 0) {
431 break;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800432 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700433 }
434 return rv;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800435}
Elliott Hughes46882792012-08-03 16:49:39 -0700436
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800437
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700438ProtectedDataGuard::ProtectedDataGuard() {
439 if (ref_count_++ == 0) {
440 protect_data(PROT_READ | PROT_WRITE);
441 }
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700442
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700443 if (ref_count_ == 0) { // overflow
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700444 async_safe_fatal("Too many nested calls to dlopen()");
Dmitriy Ivanov279a22f2015-01-23 12:03:53 -0800445 }
Dimitry Ivanov68e6c032017-02-01 12:55:11 -0800446}
Dmitriy Ivanov279a22f2015-01-23 12:03:53 -0800447
Dimitry Ivanov68e6c032017-02-01 12:55:11 -0800448ProtectedDataGuard::~ProtectedDataGuard() {
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700449 if (--ref_count_ == 0) {
450 protect_data(PROT_READ);
Dmitriy Ivanov279a22f2015-01-23 12:03:53 -0800451 }
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700452}
Dmitriy Ivanov279a22f2015-01-23 12:03:53 -0800453
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700454void ProtectedDataGuard::protect_data(int protection) {
455 g_soinfo_allocator.protect_all(protection);
456 g_soinfo_links_allocator.protect_all(protection);
457 g_namespace_allocator.protect_all(protection);
458 g_namespace_list_allocator.protect_all(protection);
459}
Dmitriy Ivanov279a22f2015-01-23 12:03:53 -0800460
461size_t ProtectedDataGuard::ref_count_ = 0;
462
Dmitriy Ivanov0cd83eb2014-09-01 16:15:52 -0700463// Each size has it's own allocator.
464template<size_t size>
465class SizeBasedAllocator {
466 public:
467 static void* alloc() {
468 return allocator_.alloc();
469 }
Dmitriy Ivanov4bea4982014-08-29 14:01:48 -0700470
Dmitriy Ivanov0cd83eb2014-09-01 16:15:52 -0700471 static void free(void* ptr) {
472 allocator_.free(ptr);
473 }
Dmitriy Ivanov4bea4982014-08-29 14:01:48 -0700474
Vic Yangbb7e1232019-01-29 20:23:16 -0800475 static void purge() {
476 allocator_.purge();
477 }
478
Dmitriy Ivanov0cd83eb2014-09-01 16:15:52 -0700479 private:
480 static LinkerBlockAllocator allocator_;
481};
482
483template<size_t size>
484LinkerBlockAllocator SizeBasedAllocator<size>::allocator_(size);
485
486template<typename T>
487class TypeBasedAllocator {
488 public:
489 static T* alloc() {
490 return reinterpret_cast<T*>(SizeBasedAllocator<sizeof(T)>::alloc());
491 }
492
493 static void free(T* ptr) {
494 SizeBasedAllocator<sizeof(T)>::free(ptr);
495 }
Vic Yangbb7e1232019-01-29 20:23:16 -0800496
497 static void purge() {
498 SizeBasedAllocator<sizeof(T)>::purge();
499 }
Dmitriy Ivanov0cd83eb2014-09-01 16:15:52 -0700500};
501
Dmitriy Ivanov14669a92014-09-05 16:42:53 -0700502class LoadTask {
503 public:
504 struct deleter_t {
505 void operator()(LoadTask* t) {
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700506 t->~LoadTask();
Dmitriy Ivanov14669a92014-09-05 16:42:53 -0700507 TypeBasedAllocator<LoadTask>::free(t);
508 }
509 };
510
Dmitriy Ivanov14669a92014-09-05 16:42:53 -0700511 static deleter_t deleter;
512
Dimitry Ivanov7d429d32017-02-01 15:28:52 -0800513 static LoadTask* create(const char* name,
514 soinfo* needed_by,
Jiyong Park02586a22017-05-20 01:01:24 +0900515 android_namespace_t* start_from,
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700516 std::unordered_map<const soinfo*, ElfReader>* readers_map) {
Dmitriy Ivanov14669a92014-09-05 16:42:53 -0700517 LoadTask* ptr = TypeBasedAllocator<LoadTask>::alloc();
Jiyong Park02586a22017-05-20 01:01:24 +0900518 return new (ptr) LoadTask(name, needed_by, start_from, readers_map);
Dmitriy Ivanov14669a92014-09-05 16:42:53 -0700519 }
520
521 const char* get_name() const {
522 return name_;
523 }
524
525 soinfo* get_needed_by() const {
526 return needed_by_;
527 }
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700528
529 soinfo* get_soinfo() const {
530 return si_;
531 }
532
533 void set_soinfo(soinfo* si) {
534 si_ = si;
535 }
536
537 off64_t get_file_offset() const {
538 return file_offset_;
539 }
540
541 void set_file_offset(off64_t offset) {
542 file_offset_ = offset;
543 }
544
545 int get_fd() const {
546 return fd_;
547 }
548
549 void set_fd(int fd, bool assume_ownership) {
Martin Stjernholmde853ff2019-01-17 00:18:44 +0000550 if (fd_ != -1 && close_fd_) {
551 close(fd_);
552 }
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700553 fd_ = fd;
554 close_fd_ = assume_ownership;
555 }
556
557 const android_dlextinfo* get_extinfo() const {
558 return extinfo_;
559 }
560
561 void set_extinfo(const android_dlextinfo* extinfo) {
562 extinfo_ = extinfo;
563 }
564
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700565 bool is_dt_needed() const {
566 return is_dt_needed_;
567 }
568
569 void set_dt_needed(bool is_dt_needed) {
570 is_dt_needed_ = is_dt_needed;
571 }
572
Jiyong Park02586a22017-05-20 01:01:24 +0900573 // returns the namespace from where we need to start loading this.
574 const android_namespace_t* get_start_from() const {
575 return start_from_;
576 }
577
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700578 const ElfReader& get_elf_reader() const {
579 CHECK(si_ != nullptr);
580 return (*elf_readers_map_)[si_];
581 }
582
583 ElfReader& get_elf_reader() {
584 CHECK(si_ != nullptr);
585 return (*elf_readers_map_)[si_];
586 }
587
588 std::unordered_map<const soinfo*, ElfReader>* get_readers_map() {
589 return elf_readers_map_;
590 }
591
592 bool read(const char* realpath, off64_t file_size) {
593 ElfReader& elf_reader = get_elf_reader();
594 return elf_reader.Read(realpath, fd_, file_offset_, file_size);
595 }
596
Torne (Richard Coles)efbe9a52018-10-17 15:59:38 -0400597 bool load(address_space_params* address_space) {
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700598 ElfReader& elf_reader = get_elf_reader();
Torne (Richard Coles)efbe9a52018-10-17 15:59:38 -0400599 if (!elf_reader.Load(address_space)) {
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700600 return false;
601 }
602
603 si_->base = elf_reader.load_start();
604 si_->size = elf_reader.load_size();
Dimitry Ivanovf45b0e92016-01-15 11:13:35 -0800605 si_->set_mapped_by_caller(elf_reader.is_mapped_by_caller());
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700606 si_->load_bias = elf_reader.load_bias();
607 si_->phnum = elf_reader.phdr_count();
608 si_->phdr = elf_reader.loaded_phdr();
609
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_;
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700636 // TODO(dimitry): needed by workaround for http://b/26394120 (the grey-list)
637 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
Christopher R. Palmer9dc396a2017-04-08 22:40:01 +0200659#ifdef LD_SHIM_LIBS
660// g_ld_all_shim_libs maintains the references to memory as it used
661// in the soinfo structures and in the g_active_shim_libs list.
662
663static std::vector<ShimDescriptor> g_ld_all_shim_libs;
664
665// g_active_shim_libs are all shim libs that are still eligible
666// to be loaded. We must remove a shim lib from the list before
667// we load the library to avoid recursive loops (load shim libA
668// for libB where libA also links against libB).
669static linked_list_t<const ShimDescriptor> g_active_shim_libs;
670
671static void reset_g_active_shim_libs(void) {
672 g_active_shim_libs.clear();
673 for (const auto& pair : g_ld_all_shim_libs) {
674 g_active_shim_libs.push_back(&pair);
675 }
676}
677
678void parse_LD_SHIM_LIBS(const char* path) {
679 g_ld_all_shim_libs.clear();
680 if (path != nullptr) {
681 for (const auto& pair : android::base::Split(path, ":")) {
682 std::vector<std::string> pieces = android::base::Split(pair, "|");
683 if (pieces.size() != 2) continue;
684 // If the path can be resolved, resolve it
685 char buf[PATH_MAX];
686 std::string resolved_path = pieces[0];
687 if (access(pieces[0].c_str(), R_OK) != 0) {
688 if (errno == ENOENT) {
689 // no need to test for non-existing path. skip.
690 continue;
691 }
692 // If not accessible, don't call realpath as it will just cause
693 // SELinux denial spam. Use the path unresolved.
694 } else if (realpath(pieces[0].c_str(), buf) != nullptr) {
695 resolved_path = buf;
696 }
697 auto desc = std::pair<std::string, std::string>(resolved_path, pieces[1]);
698 g_ld_all_shim_libs.push_back(desc);
699 }
700 }
701 reset_g_active_shim_libs();
702}
703
704std::vector<const ShimDescriptor*> shim_matching_pairs(const char* path) {
705 std::vector<const ShimDescriptor*> matched_pairs;
706
707 g_active_shim_libs.for_each([&](const ShimDescriptor* a_pair) {
708 if (a_pair->first == path) {
709 matched_pairs.push_back(a_pair);
710 }
711 });
712
713 g_active_shim_libs.remove_if([&](const ShimDescriptor* a_pair) {
714 return a_pair->first == path;
715 });
716
717 return matched_pairs;
718}
719#endif
720
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700721// This function walks down the tree of soinfo dependencies
722// in breadth-first order and
723// * calls action(soinfo* si) for each node, and
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800724// * terminates walk if action returns kWalkStop
725// * skips children of the node if action
726// return kWalkSkip
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700727//
728// walk_dependencies_tree returns false if walk was terminated
729// by the action and true otherwise.
730template<typename F>
dimitry965d06d2017-11-28 16:03:07 +0100731static bool walk_dependencies_tree(soinfo* root_soinfo, F action) {
Dmitriy Ivanov0cd83eb2014-09-01 16:15:52 -0700732 SoinfoLinkedList visit_list;
733 SoinfoLinkedList visited;
734
dimitry965d06d2017-11-28 16:03:07 +0100735 visit_list.push_back(root_soinfo);
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700736
737 soinfo* si;
738 while ((si = visit_list.pop_front()) != nullptr) {
739 if (visited.contains(si)) {
Dmitriy Ivanov042426b2014-08-12 21:02:13 -0700740 continue;
741 }
742
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800743 walk_action_result_t result = action(si);
744
745 if (result == kWalkStop) {
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700746 return false;
Dmitriy Ivanovaa0f2bd2014-07-28 17:32:20 -0700747 }
748
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700749 visited.push_back(si);
750
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800751 if (result != kWalkSkip) {
752 si->get_children().for_each([&](soinfo* child) {
753 visit_list.push_back(child);
754 });
755 }
Dmitriy Ivanovaa0f2bd2014-07-28 17:32:20 -0700756 }
757
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700758 return true;
759}
760
761
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800762static const ElfW(Sym)* dlsym_handle_lookup(android_namespace_t* ns,
763 soinfo* root,
764 soinfo* skip_until,
765 soinfo** found,
766 SymbolName& symbol_name,
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -0800767 const version_info* vi) {
Dmitriy Ivanov2a815362015-04-09 13:42:33 -0700768 const ElfW(Sym)* result = nullptr;
Dmitriy Ivanov697bd9f2015-05-12 11:12:27 -0700769 bool skip_lookup = skip_until != nullptr;
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700770
dimitry965d06d2017-11-28 16:03:07 +0100771 walk_dependencies_tree(root, [&](soinfo* current_soinfo) {
Dmitriy Ivanov697bd9f2015-05-12 11:12:27 -0700772 if (skip_lookup) {
773 skip_lookup = current_soinfo != skip_until;
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800774 return kWalkContinue;
775 }
776
777 if (!ns->is_accessible(current_soinfo)) {
778 return kWalkSkip;
Dmitriy Ivanov697bd9f2015-05-12 11:12:27 -0700779 }
780
Ryan Prichardbbc2cb42020-01-02 14:59:11 -0800781 result = current_soinfo->find_symbol_by_name(symbol_name, vi);
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700782 if (result != nullptr) {
783 *found = current_soinfo;
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800784 return kWalkStop;
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700785 }
786
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800787 return kWalkContinue;
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700788 });
789
790 return result;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800791}
792
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -0800793static const ElfW(Sym)* dlsym_linear_lookup(android_namespace_t* ns,
794 const char* name,
795 const version_info* vi,
796 soinfo** found,
797 soinfo* caller,
798 void* handle);
799
Dmitriy Ivanov697bd9f2015-05-12 11:12:27 -0700800// This is used by dlsym(3). It performs symbol lookup only within the
801// specified soinfo object and its dependencies in breadth first order.
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800802static const ElfW(Sym)* dlsym_handle_lookup(soinfo* si,
803 soinfo** found,
804 const char* name,
805 const version_info* vi) {
Dmitriy Ivanovf439b5a2015-05-30 13:04:39 -0700806 // According to man dlopen(3) and posix docs in the case when si is handle
807 // of the main executable we need to search not only in the executable and its
808 // dependencies but also in all libraries loaded with RTLD_GLOBAL.
809 //
810 // Since RTLD_GLOBAL is always set for the main executable and all dt_needed shared
811 // libraries and they are loaded in breath-first (correct) order we can just execute
812 // dlsym(RTLD_DEFAULT, ...); instead of doing two stage lookup.
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700813 if (si == solist_get_somain()) {
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -0800814 return dlsym_linear_lookup(&g_default_namespace, name, vi, found, nullptr, RTLD_DEFAULT);
Dmitriy Ivanovf439b5a2015-05-30 13:04:39 -0700815 }
816
Dmitriy Ivanov697bd9f2015-05-12 11:12:27 -0700817 SymbolName symbol_name(name);
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800818 // note that the namespace is not the namespace associated with caller_addr
819 // we use ns associated with root si intentionally here. Using caller_ns
820 // causes problems when user uses dlopen_ext to open a library in the separate
821 // namespace and then calls dlsym() on the handle.
822 return dlsym_handle_lookup(si->get_primary_namespace(), si, nullptr, found, symbol_name, vi);
Dmitriy Ivanov697bd9f2015-05-12 11:12:27 -0700823}
824
Brian Carlstromd4ee82d2013-02-28 15:58:45 -0800825/* This is used by dlsym(3) to performs a global symbol lookup. If the
826 start value is null (for RTLD_DEFAULT), the search starts at the
827 beginning of the global solist. Otherwise the search starts at the
828 specified soinfo (for RTLD_NEXT).
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700829 */
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -0800830static const ElfW(Sym)* dlsym_linear_lookup(android_namespace_t* ns,
831 const char* name,
832 const version_info* vi,
833 soinfo** found,
834 soinfo* caller,
835 void* handle) {
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -0800836 SymbolName symbol_name(name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800837
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -0700838 auto& soinfo_list = ns->soinfo_list();
839 auto start = soinfo_list.begin();
Dmitriy Ivanov76ac1ac2015-04-01 14:45:10 -0700840
841 if (handle == RTLD_NEXT) {
Dmitriy Ivanovb96ac412015-05-22 12:34:42 -0700842 if (caller == nullptr) {
Dmitriy Ivanov76ac1ac2015-04-01 14:45:10 -0700843 return nullptr;
844 } else {
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -0700845 auto it = soinfo_list.find(caller);
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -0700846 CHECK (it != soinfo_list.end());
847 start = ++it;
Dmitriy Ivanov76ac1ac2015-04-01 14:45:10 -0700848 }
Elliott Hughescade4c32012-12-20 14:42:14 -0800849 }
850
Dmitriy Ivanov2a815362015-04-09 13:42:33 -0700851 const ElfW(Sym)* s = nullptr;
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -0700852 for (auto it = start, end = soinfo_list.end(); it != end; ++it) {
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -0700853 soinfo* si = *it;
Dmitriy Ivanov19133522015-06-02 17:36:54 -0700854 // Do not skip RTLD_LOCAL libraries in dlsym(RTLD_DEFAULT, ...)
Elliott Hughes5bc78c82016-11-16 11:35:43 -0800855 // if the library is opened by application with target api level < M.
Dmitriy Ivanov19133522015-06-02 17:36:54 -0700856 // See http://b/21565766
Elliott Hughes5bc78c82016-11-16 11:35:43 -0800857 if ((si->get_rtld_flags() & RTLD_GLOBAL) == 0 &&
858 si->get_target_sdk_version() >= __ANDROID_API_M__) {
Dmitriy Ivanove8ba50f2014-09-15 17:00:10 -0700859 continue;
860 }
861
Ryan Prichardbbc2cb42020-01-02 14:59:11 -0800862 s = si->find_symbol_by_name(symbol_name, vi);
Dmitriy Ivanov851135b2014-08-29 12:02:36 -0700863 if (s != nullptr) {
Elliott Hughescade4c32012-12-20 14:42:14 -0800864 *found = si;
865 break;
Matt Fischer1698d9e2009-12-31 12:17:56 -0600866 }
Elliott Hughescade4c32012-12-20 14:42:14 -0800867 }
Matt Fischer1698d9e2009-12-31 12:17:56 -0600868
dimitry153168c2018-02-20 16:51:41 +0100869 // If not found - use dlsym_handle_lookup for caller's local_group
870 if (s == nullptr && caller != nullptr) {
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800871 soinfo* local_group_root = caller->get_local_group_root();
872
873 return dlsym_handle_lookup(local_group_root->get_primary_namespace(),
874 local_group_root,
875 (handle == RTLD_NEXT) ? caller : nullptr,
876 found,
877 symbol_name,
878 vi);
Dmitriy Ivanov76ac1ac2015-04-01 14:45:10 -0700879 }
880
Dmitriy Ivanov851135b2014-08-29 12:02:36 -0700881 if (s != nullptr) {
Elliott Hughesc00f2cb2013-10-04 17:01:33 -0700882 TRACE_TYPE(LOOKUP, "%s s->st_value = %p, found->base = %p",
883 name, reinterpret_cast<void*>(s->st_value), reinterpret_cast<void*>((*found)->base));
Elliott Hughescade4c32012-12-20 14:42:14 -0800884 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800885
Elliott Hughescade4c32012-12-20 14:42:14 -0800886 return s;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800887}
888
Kito Chengfa8c05d2013-03-12 14:58:06 +0800889soinfo* find_containing_library(const void* p) {
Elliott Hughes0266ae52014-02-10 17:46:57 -0800890 ElfW(Addr) address = reinterpret_cast<ElfW(Addr)>(p);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700891 for (soinfo* si = solist_get_head(); si != nullptr; si = si->next) {
Peter Collingbourneb39cb3c2019-03-01 13:12:49 -0800892 if (address < si->base || address - si->base >= si->size) {
893 continue;
894 }
895 ElfW(Addr) vaddr = address - si->load_bias;
896 for (size_t i = 0; i != si->phnum; ++i) {
897 const ElfW(Phdr)* phdr = &si->phdr[i];
898 if (phdr->p_type != PT_LOAD) {
899 continue;
900 }
901 if (vaddr >= phdr->p_vaddr && vaddr < phdr->p_vaddr + phdr->p_memsz) {
902 return si;
903 }
Matt Fischere2a8b1f2009-12-31 12:17:40 -0600904 }
Kito Chengfa8c05d2013-03-12 14:58:06 +0800905 }
Dmitriy Ivanov851135b2014-08-29 12:02:36 -0700906 return nullptr;
Matt Fischere2a8b1f2009-12-31 12:17:40 -0600907}
908
Dmitriy Ivanovb4827502015-09-28 16:38:31 -0700909class ZipArchiveCache {
910 public:
911 ZipArchiveCache() {}
912 ~ZipArchiveCache();
913
914 bool get_or_open(const char* zip_path, ZipArchiveHandle* handle);
915 private:
916 DISALLOW_COPY_AND_ASSIGN(ZipArchiveCache);
917
918 std::unordered_map<std::string, ZipArchiveHandle> cache_;
919};
920
921bool ZipArchiveCache::get_or_open(const char* zip_path, ZipArchiveHandle* handle) {
922 std::string key(zip_path);
923
924 auto it = cache_.find(key);
925 if (it != cache_.end()) {
926 *handle = it->second;
927 return true;
928 }
929
930 int fd = TEMP_FAILURE_RETRY(open(zip_path, O_RDONLY | O_CLOEXEC));
931 if (fd == -1) {
932 return false;
933 }
934
935 if (OpenArchiveFd(fd, "", handle) != 0) {
936 // invalid zip-file (?)
Ryan Prichard0adf09b2018-10-01 18:35:46 -0700937 CloseArchive(*handle);
Dmitriy Ivanovb4827502015-09-28 16:38:31 -0700938 return false;
939 }
940
941 cache_[key] = *handle;
942 return true;
943}
944
945ZipArchiveCache::~ZipArchiveCache() {
Dmitriy Ivanov5dce8942015-10-13 12:14:16 -0700946 for (const auto& it : cache_) {
Dmitriy Ivanovb4827502015-09-28 16:38:31 -0700947 CloseArchive(it.second);
948 }
949}
950
951static int open_library_in_zipfile(ZipArchiveCache* zip_archive_cache,
Dmitriy Ivanova1feb112015-10-01 18:41:57 -0700952 const char* const input_path,
953 off64_t* file_offset, std::string* realpath) {
954 std::string normalized_path;
955 if (!normalize_path(input_path, &normalized_path)) {
956 return -1;
957 }
958
959 const char* const path = normalized_path.c_str();
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700960 TRACE("Trying zip file open from path \"%s\" -> normalized \"%s\"", input_path, path);
Simon Baldwinaef71952015-01-16 13:22:54 +0000961
Dmitriy Ivanov402a7502015-06-09 13:46:51 -0700962 // Treat an '!/' separator inside a path as the separator between the name
Simon Baldwinaef71952015-01-16 13:22:54 +0000963 // of the zip file on disk and the subdirectory to search within it.
Dmitriy Ivanov402a7502015-06-09 13:46:51 -0700964 // For example, if path is "foo.zip!/bar/bas/x.so", then we search for
Simon Baldwinaef71952015-01-16 13:22:54 +0000965 // "bar/bas/x.so" within "foo.zip".
Dmitriy Ivanova1feb112015-10-01 18:41:57 -0700966 const char* const separator = strstr(path, kZipFileSeparator);
Simon Baldwinaef71952015-01-16 13:22:54 +0000967 if (separator == nullptr) {
968 return -1;
Elliott Hughes124fae92012-10-31 14:20:03 -0700969 }
Simon Baldwinaef71952015-01-16 13:22:54 +0000970
971 char buf[512];
972 if (strlcpy(buf, path, sizeof(buf)) >= sizeof(buf)) {
973 PRINT("Warning: ignoring very long library path: %s", path);
974 return -1;
975 }
976
977 buf[separator - path] = '\0';
978
979 const char* zip_path = buf;
Dmitriy Ivanov402a7502015-06-09 13:46:51 -0700980 const char* file_path = &buf[separator - path + 2];
Simon Baldwinaef71952015-01-16 13:22:54 +0000981 int fd = TEMP_FAILURE_RETRY(open(zip_path, O_RDONLY | O_CLOEXEC));
982 if (fd == -1) {
983 return -1;
984 }
985
986 ZipArchiveHandle handle;
Dmitriy Ivanovb4827502015-09-28 16:38:31 -0700987 if (!zip_archive_cache->get_or_open(zip_path, &handle)) {
Simon Baldwinaef71952015-01-16 13:22:54 +0000988 // invalid zip-file (?)
989 close(fd);
990 return -1;
991 }
992
Simon Baldwinaef71952015-01-16 13:22:54 +0000993 ZipEntry entry;
994
Yusuke Sato56f40fb2015-06-25 14:56:07 -0700995 if (FindEntry(handle, ZipString(file_path), &entry) != 0) {
Simon Baldwinaef71952015-01-16 13:22:54 +0000996 // Entry was not found.
997 close(fd);
998 return -1;
999 }
1000
1001 // Check if it is properly stored
1002 if (entry.method != kCompressStored || (entry.offset % PAGE_SIZE) != 0) {
1003 close(fd);
1004 return -1;
1005 }
1006
1007 *file_offset = entry.offset;
Dmitriy Ivanova1feb112015-10-01 18:41:57 -07001008
1009 if (realpath_fd(fd, realpath)) {
1010 *realpath += separator;
1011 } else {
Tom Cherry66bc4282018-11-08 13:40:52 -08001012 if (!is_first_stage_init()) {
1013 PRINT("warning: unable to get realpath for the library \"%s\". Will use given path.",
1014 normalized_path.c_str());
1015 }
Dmitriy Ivanova1feb112015-10-01 18:41:57 -07001016 *realpath = normalized_path;
1017 }
1018
Simon Baldwinaef71952015-01-16 13:22:54 +00001019 return fd;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001020}
1021
Dmitriy Ivanovd165f562015-03-23 18:43:02 -07001022static bool format_path(char* buf, size_t buf_size, const char* path, const char* name) {
Christopher Ferris7a3681e2017-04-24 17:48:32 -07001023 int n = async_safe_format_buffer(buf, buf_size, "%s/%s", path, name);
Dmitriy Ivanovd165f562015-03-23 18:43:02 -07001024 if (n < 0 || n >= static_cast<int>(buf_size)) {
1025 PRINT("Warning: ignoring very long library path: %s/%s", path, name);
1026 return false;
1027 }
Simon Baldwinaef71952015-01-16 13:22:54 +00001028
Dmitriy Ivanovd165f562015-03-23 18:43:02 -07001029 return true;
1030}
1031
Ryan Prichard8f639a42018-10-01 23:10:05 -07001032static int open_library_at_path(ZipArchiveCache* zip_archive_cache,
1033 const char* path, off64_t* file_offset,
1034 std::string* realpath) {
1035 int fd = -1;
1036 if (strstr(path, kZipFileSeparator) != nullptr) {
1037 fd = open_library_in_zipfile(zip_archive_cache, path, file_offset, realpath);
1038 }
1039
1040 if (fd == -1) {
1041 fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC));
1042 if (fd != -1) {
1043 *file_offset = 0;
1044 if (!realpath_fd(fd, realpath)) {
Tom Cherry66bc4282018-11-08 13:40:52 -08001045 if (!is_first_stage_init()) {
1046 PRINT("warning: unable to get realpath for the library \"%s\". Will use given path.",
1047 path);
1048 }
Ryan Prichard8f639a42018-10-01 23:10:05 -07001049 *realpath = path;
1050 }
1051 }
1052 }
1053
1054 return fd;
1055}
1056
Dmitriy Ivanovb4827502015-09-28 16:38:31 -07001057static int open_library_on_paths(ZipArchiveCache* zip_archive_cache,
1058 const char* name, off64_t* file_offset,
Dmitriy Ivanova1feb112015-10-01 18:41:57 -07001059 const std::vector<std::string>& paths,
1060 std::string* realpath) {
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001061 for (const auto& path : paths) {
Dmitriy Ivanovd165f562015-03-23 18:43:02 -07001062 char buf[512];
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001063 if (!format_path(buf, sizeof(buf), path.c_str(), name)) {
Dmitriy Ivanovd165f562015-03-23 18:43:02 -07001064 continue;
1065 }
1066
Ryan Prichard8f639a42018-10-01 23:10:05 -07001067 int fd = open_library_at_path(zip_archive_cache, buf, file_offset, realpath);
Dmitriy Ivanovd165f562015-03-23 18:43:02 -07001068 if (fd != -1) {
1069 return fd;
1070 }
Simon Baldwinaef71952015-01-16 13:22:54 +00001071 }
1072
Dmitriy Ivanovd165f562015-03-23 18:43:02 -07001073 return -1;
Simon Baldwinaef71952015-01-16 13:22:54 +00001074}
1075
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001076static int open_library(android_namespace_t* ns,
1077 ZipArchiveCache* zip_archive_cache,
Dmitriy Ivanovb4827502015-09-28 16:38:31 -07001078 const char* name, soinfo *needed_by,
Dmitriy Ivanova1feb112015-10-01 18:41:57 -07001079 off64_t* file_offset, std::string* realpath) {
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001080 TRACE("[ opening %s from namespace %s ]", name, ns->get_name());
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001081
Elliott Hughes124fae92012-10-31 14:20:03 -07001082 // 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 -07001083 if (strchr(name, '/') != nullptr) {
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001084 int fd = -1;
1085
Dmitriy Ivanov730ed9d2015-07-16 04:52:06 -07001086 if (strstr(name, kZipFileSeparator) != nullptr) {
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001087 fd = open_library_in_zipfile(zip_archive_cache, name, file_offset, realpath);
1088 }
1089
1090 if (fd == -1) {
1091 fd = TEMP_FAILURE_RETRY(open(name, O_RDONLY | O_CLOEXEC));
Simon Baldwinaef71952015-01-16 13:22:54 +00001092 if (fd != -1) {
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001093 *file_offset = 0;
1094 if (!realpath_fd(fd, realpath)) {
Tom Cherry66bc4282018-11-08 13:40:52 -08001095 if (!is_first_stage_init()) {
1096 PRINT("warning: unable to get realpath for the library \"%s\". Will use given path.",
1097 name);
1098 }
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001099 *realpath = name;
1100 }
Simon Baldwinaef71952015-01-16 13:22:54 +00001101 }
1102 }
1103
Dmitriy Ivanove44fffd2015-03-17 17:12:18 -07001104 return fd;
Elliott Hughes124fae92012-10-31 14:20:03 -07001105 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001106
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001107 // Otherwise we try LD_LIBRARY_PATH first, and fall back to the default library path
1108 int fd = open_library_on_paths(zip_archive_cache, name, file_offset, ns->get_ld_library_paths(), realpath);
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001109 if (fd == -1 && needed_by != nullptr) {
Dmitriy Ivanova1feb112015-10-01 18:41:57 -07001110 fd = open_library_on_paths(zip_archive_cache, name, file_offset, needed_by->get_dt_runpath(), realpath);
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001111 // Check if the library is accessible
1112 if (fd != -1 && !ns->is_accessible(*realpath)) {
Vic Yang48b69112018-10-24 14:14:26 -07001113 close(fd);
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001114 fd = -1;
1115 }
Evgenii Stepanov68650822015-06-10 13:38:39 -07001116 }
Dmitriy Ivanovb4827502015-09-28 16:38:31 -07001117
Peter Collingbourned13cb582019-04-30 16:05:13 -07001118#if !defined(__ANDROID_APEX__)
1119 if (fd == -1) {
1120 std::vector<std::string> bootstrap_paths = { std::string(kSystemLibDir) + "/bootstrap" };
1121 fd = open_library_on_paths(zip_archive_cache, name, file_offset, bootstrap_paths, realpath);
1122 }
1123#endif
1124
Elliott Hughes124fae92012-10-31 14:20:03 -07001125 if (fd == -1) {
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001126 fd = open_library_on_paths(zip_archive_cache, name, file_offset, ns->get_default_library_paths(), realpath);
Elliott Hughes124fae92012-10-31 14:20:03 -07001127 }
Dmitriy Ivanovb4827502015-09-28 16:38:31 -07001128
Elliott Hughes124fae92012-10-31 14:20:03 -07001129 return fd;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001130}
1131
Ryan Prichard8f639a42018-10-01 23:10:05 -07001132int open_executable(const char* path, off64_t* file_offset, std::string* realpath) {
1133 ZipArchiveCache zip_archive_cache;
1134 return open_library_at_path(&zip_archive_cache, path, file_offset, realpath);
1135}
1136
Dimitry Ivanov3f660572016-09-09 10:00:39 -07001137const char* fix_dt_needed(const char* dt_needed, const char* sopath __unused) {
Dmitriy Ivanovd974e882015-05-27 18:29:41 -07001138#if !defined(__LP64__)
1139 // Work around incorrect DT_NEEDED entries for old apps: http://b/21364029
Elliott Hughes9076b0c2018-02-28 11:29:45 -08001140 int app_target_api_level = get_application_target_sdk_version();
1141 if (app_target_api_level < __ANDROID_API_M__) {
Dmitriy Ivanovd974e882015-05-27 18:29:41 -07001142 const char* bname = basename(dt_needed);
1143 if (bname != dt_needed) {
Elliott Hughes9076b0c2018-02-28 11:29:45 -08001144 DL_WARN_documented_change(__ANDROID_API_M__,
1145 "invalid-dt_needed-entries-enforced-for-api-level-23",
1146 "library \"%s\" has invalid DT_NEEDED entry \"%s\"",
1147 sopath, dt_needed, app_target_api_level);
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07001148 add_dlwarning(sopath, "invalid DT_NEEDED entry", dt_needed);
Dmitriy Ivanovd974e882015-05-27 18:29:41 -07001149 }
1150
1151 return bname;
1152 }
1153#endif
1154 return dt_needed;
1155}
1156
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001157template<typename F>
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001158static void for_each_dt_needed(const ElfReader& elf_reader, F action) {
1159 for (const ElfW(Dyn)* d = elf_reader.dynamic(); d->d_tag != DT_NULL; ++d) {
1160 if (d->d_tag == DT_NEEDED) {
1161 action(fix_dt_needed(elf_reader.get_string(d->d_un.d_val), elf_reader.name()));
1162 }
1163 }
1164}
1165
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001166static bool find_loaded_library_by_inode(android_namespace_t* ns,
1167 const struct stat& file_stat,
1168 off64_t file_offset,
1169 bool search_linked_namespaces,
1170 soinfo** candidate) {
Vic Yang54720732019-06-02 21:10:53 -07001171 if (file_stat.st_dev == 0 || file_stat.st_ino == 0) {
1172 *candidate = nullptr;
1173 return false;
1174 }
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001175
1176 auto predicate = [&](soinfo* si) {
Vic Yang54720732019-06-02 21:10:53 -07001177 return si->get_st_ino() == file_stat.st_ino &&
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001178 si->get_st_dev() == file_stat.st_dev &&
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001179 si->get_file_offset() == file_offset;
1180 };
1181
1182 *candidate = ns->soinfo_list().find_if(predicate);
1183
1184 if (*candidate == nullptr && search_linked_namespaces) {
1185 for (auto& link : ns->linked_namespaces()) {
1186 android_namespace_t* linked_ns = link.linked_namespace();
1187 soinfo* si = linked_ns->soinfo_list().find_if(predicate);
1188
1189 if (si != nullptr && link.is_accessible(si->get_soname())) {
1190 *candidate = si;
1191 return true;
1192 }
1193 }
1194 }
1195
1196 return *candidate != nullptr;
1197}
1198
Evgenii Stepanov9e77a642017-07-27 14:55:44 -07001199static bool find_loaded_library_by_realpath(android_namespace_t* ns, const char* realpath,
1200 bool search_linked_namespaces, soinfo** candidate) {
1201 auto predicate = [&](soinfo* si) { return strcmp(realpath, si->get_realpath()) == 0; };
1202
1203 *candidate = ns->soinfo_list().find_if(predicate);
1204
1205 if (*candidate == nullptr && search_linked_namespaces) {
1206 for (auto& link : ns->linked_namespaces()) {
1207 android_namespace_t* linked_ns = link.linked_namespace();
1208 soinfo* si = linked_ns->soinfo_list().find_if(predicate);
1209
1210 if (si != nullptr && link.is_accessible(si->get_soname())) {
1211 *candidate = si;
1212 return true;
1213 }
1214 }
1215 }
1216
1217 return *candidate != nullptr;
1218}
1219
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001220static bool load_library(android_namespace_t* ns,
1221 LoadTask* task,
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001222 LoadTaskList* load_tasks,
1223 int rtld_flags,
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001224 const std::string& realpath,
1225 bool search_linked_namespaces) {
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001226 off64_t file_offset = task->get_file_offset();
1227 const char* name = task->get_name();
1228 const android_dlextinfo* extinfo = task->get_extinfo();
1229
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001230 LD_LOG(kLogDlopen, "load_library(ns=%s, task=%s, flags=0x%x, realpath=%s)", ns->get_name(), name,
1231 rtld_flags, realpath.c_str());
1232
Dmitriy Ivanov07e5bc12014-10-03 17:52:44 -07001233 if ((file_offset % PAGE_SIZE) != 0) {
Dmitriy Ivanova6c12792014-10-21 12:09:18 -07001234 DL_ERR("file offset for the library \"%s\" is not page-aligned: %" PRId64, name, file_offset);
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001235 return false;
Dmitriy Ivanov07e5bc12014-10-03 17:52:44 -07001236 }
Yabin Cui16f7f8d2014-11-04 11:08:05 -08001237 if (file_offset < 0) {
1238 DL_ERR("file offset for the library \"%s\" is negative: %" PRId64, name, file_offset);
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001239 return false;
Yabin Cui16f7f8d2014-11-04 11:08:05 -08001240 }
Dmitriy Ivanov07e5bc12014-10-03 17:52:44 -07001241
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001242 struct stat file_stat;
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001243 if (TEMP_FAILURE_RETRY(fstat(task->get_fd(), &file_stat)) != 0) {
Dmitriy Ivanova6c12792014-10-21 12:09:18 -07001244 DL_ERR("unable to stat file for the library \"%s\": %s", name, strerror(errno));
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001245 return false;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001246 }
Yabin Cui16f7f8d2014-11-04 11:08:05 -08001247 if (file_offset >= file_stat.st_size) {
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07001248 DL_ERR("file offset for the library \"%s\" >= file size: %" PRId64 " >= %" PRId64,
1249 name, file_offset, file_stat.st_size);
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001250 return false;
Yabin Cui16f7f8d2014-11-04 11:08:05 -08001251 }
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001252
1253 // Check for symlink and other situations where
Dmitriy Ivanov9b821362015-04-02 16:03:56 -07001254 // file can have different names, unless ANDROID_DLEXT_FORCE_LOAD is set
1255 if (extinfo == nullptr || (extinfo->flags & ANDROID_DLEXT_FORCE_LOAD) == 0) {
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001256 soinfo* si = nullptr;
1257 if (find_loaded_library_by_inode(ns, file_stat, file_offset, search_linked_namespaces, &si)) {
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001258 LD_LOG(kLogDlopen,
1259 "load_library(ns=%s, task=%s): Already loaded under different name/path \"%s\" - "
1260 "will return existing soinfo",
1261 ns->get_name(), name, si->get_realpath());
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001262 task->set_soinfo(si);
1263 return true;
1264 }
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001265 }
Dmitriy Ivanovd59e5002014-05-09 09:10:14 -07001266
Dmitriy Ivanove8ba50f2014-09-15 17:00:10 -07001267 if ((rtld_flags & RTLD_NOLOAD) != 0) {
Dmitriy Ivanova6ac54a2014-09-09 10:21:42 -07001268 DL_ERR("library \"%s\" wasn't loaded and RTLD_NOLOAD prevented it", name);
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001269 return false;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001270 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001271
Dimitry Ivanovbf34ba32017-04-21 13:12:05 -07001272 struct statfs fs_stat;
1273 if (TEMP_FAILURE_RETRY(fstatfs(task->get_fd(), &fs_stat)) != 0) {
1274 DL_ERR("unable to fstatfs file for the library \"%s\": %s", name, strerror(errno));
1275 return false;
1276 }
1277
1278 // do not check accessibility using realpath if fd is located on tmpfs
1279 // this enables use of memfd_create() for apps
1280 if ((fs_stat.f_type != TMPFS_MAGIC) && (!ns->is_accessible(realpath))) {
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07001281 // TODO(dimitry): workaround for http://b/26394120 - the grey-list
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001282
1283 // TODO(dimitry) before O release: add a namespace attribute to have this enabled
1284 // only for classloader-namespaces
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07001285 const soinfo* needed_by = task->is_dt_needed() ? task->get_needed_by() : nullptr;
Dimitry Ivanov35c8e3b2017-02-27 12:17:47 -08001286 if (is_greylisted(ns, name, needed_by)) {
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07001287 // print warning only if needed by non-system library
1288 if (needed_by == nullptr || !is_system_library(needed_by->get_realpath())) {
1289 const soinfo* needed_or_dlopened_by = task->get_needed_by();
1290 const char* sopath = needed_or_dlopened_by == nullptr ? "(unknown)" :
1291 needed_or_dlopened_by->get_realpath();
Elliott Hughes9076b0c2018-02-28 11:29:45 -08001292 DL_WARN_documented_change(__ANDROID_API_N__,
1293 "private-api-enforced-for-api-level-24",
1294 "library \"%s\" (\"%s\") needed or dlopened by \"%s\" "
1295 "is not accessible by namespace \"%s\"",
1296 name, realpath.c_str(), sopath, ns->get_name());
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07001297 add_dlwarning(sopath, "unauthorized access to", name);
1298 }
1299 } else {
1300 // do not load libraries if they are not accessible for the specified namespace.
1301 const char* needed_or_dlopened_by = task->get_needed_by() == nullptr ?
1302 "(unknown)" :
1303 task->get_needed_by()->get_realpath();
Dimitry Ivanovd17a3772016-03-01 13:11:28 -08001304
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07001305 DL_ERR("library \"%s\" needed or dlopened by \"%s\" is not accessible for the namespace \"%s\"",
1306 name, needed_or_dlopened_by, ns->get_name());
Dimitry Ivanovd17a3772016-03-01 13:11:28 -08001307
Dimitry Ivanov35c8e3b2017-02-27 12:17:47 -08001308 // do not print this if a library is in the list of shared libraries for linked namespaces
1309 if (!maybe_accessible_via_namespace_links(ns, name)) {
1310 PRINT("library \"%s\" (\"%s\") needed or dlopened by \"%s\" is not accessible for the"
1311 " namespace: [name=\"%s\", ld_library_paths=\"%s\", default_library_paths=\"%s\","
1312 " permitted_paths=\"%s\"]",
1313 name, realpath.c_str(),
1314 needed_or_dlopened_by,
1315 ns->get_name(),
1316 android::base::Join(ns->get_ld_library_paths(), ':').c_str(),
1317 android::base::Join(ns->get_default_library_paths(), ':').c_str(),
1318 android::base::Join(ns->get_permitted_paths(), ':').c_str());
1319 }
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07001320 return false;
1321 }
Dimitry Ivanov22840aa2015-12-04 18:28:49 -08001322 }
1323
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001324 soinfo* si = soinfo_alloc(ns, realpath.c_str(), &file_stat, file_offset, rtld_flags);
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001325 if (si == nullptr) {
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001326 return false;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001327 }
Dmitriy Ivanovd59e5002014-05-09 09:10:14 -07001328
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001329 task->set_soinfo(si);
1330
1331 // Read the ELF header and some of the segments.
1332 if (!task->read(realpath.c_str(), file_stat.st_size)) {
Dmitriy Ivanovfd7a91e2015-11-06 10:44:37 -08001333 soinfo_free(si);
1334 task->set_soinfo(nullptr);
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001335 return false;
1336 }
1337
1338 // find and set DT_RUNPATH and dt_soname
1339 // Note that these field values are temporary and are
1340 // going to be overwritten on soinfo::prelink_image
1341 // with values from PT_LOAD segments.
1342 const ElfReader& elf_reader = task->get_elf_reader();
1343 for (const ElfW(Dyn)* d = elf_reader.dynamic(); d->d_tag != DT_NULL; ++d) {
1344 if (d->d_tag == DT_RUNPATH) {
1345 si->set_dt_runpath(elf_reader.get_string(d->d_un.d_val));
1346 }
1347 if (d->d_tag == DT_SONAME) {
1348 si->set_soname(elf_reader.get_string(d->d_un.d_val));
1349 }
1350 }
1351
Dan Willemsen5038ef62018-10-21 17:45:04 -07001352#if !defined(__ANDROID__)
1353 // Bionic on the host currently uses some Android prebuilts, which don't set
1354 // DT_RUNPATH with any relative paths, so they can't find their dependencies.
1355 // b/118058804
1356 if (si->get_dt_runpath().empty()) {
1357 si->set_dt_runpath("$ORIGIN/../lib64:$ORIGIN/lib64");
1358 }
1359#endif
1360
Christopher R. Palmer9dc396a2017-04-08 22:40:01 +02001361#ifdef LD_SHIM_LIBS
1362 for_each_matching_shim(realpath.c_str(), [&](const char* name) {
1363 load_tasks->push_back(LoadTask::create(name, si, ns, task->get_readers_map()));
1364 });
1365#endif
1366
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001367 for_each_dt_needed(task->get_elf_reader(), [&](const char* name) {
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001368 LD_LOG(kLogDlopen, "load_library(ns=%s, task=%s): Adding DT_NEEDED task: %s",
1369 ns->get_name(), task->get_name(), name);
Jiyong Park02586a22017-05-20 01:01:24 +09001370 load_tasks->push_back(LoadTask::create(name, si, ns, task->get_readers_map()));
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001371 });
Dmitriy Ivanovd59e5002014-05-09 09:10:14 -07001372
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001373 return true;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001374}
1375
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001376static bool load_library(android_namespace_t* ns,
1377 LoadTask* task,
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001378 ZipArchiveCache* zip_archive_cache,
1379 LoadTaskList* load_tasks,
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001380 int rtld_flags,
1381 bool search_linked_namespaces) {
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001382 const char* name = task->get_name();
1383 soinfo* needed_by = task->get_needed_by();
1384 const android_dlextinfo* extinfo = task->get_extinfo();
1385
Dmitriy Ivanova1feb112015-10-01 18:41:57 -07001386 off64_t file_offset;
1387 std::string realpath;
Spencer Low0346ad72015-04-22 18:06:51 -07001388 if (extinfo != nullptr && (extinfo->flags & ANDROID_DLEXT_USE_LIBRARY_FD) != 0) {
Dmitriy Ivanova1feb112015-10-01 18:41:57 -07001389 file_offset = 0;
Spencer Low0346ad72015-04-22 18:06:51 -07001390 if ((extinfo->flags & ANDROID_DLEXT_USE_LIBRARY_FD_OFFSET) != 0) {
1391 file_offset = extinfo->library_fd_offset;
1392 }
Dmitriy Ivanova1feb112015-10-01 18:41:57 -07001393
1394 if (!realpath_fd(extinfo->library_fd, &realpath)) {
Tom Cherry66bc4282018-11-08 13:40:52 -08001395 if (!is_first_stage_init()) {
1396 PRINT(
1397 "warning: unable to get realpath for the library \"%s\" by extinfo->library_fd. "
1398 "Will use given name.",
1399 name);
1400 }
Dmitriy Ivanova1feb112015-10-01 18:41:57 -07001401 realpath = name;
1402 }
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001403
1404 task->set_fd(extinfo->library_fd, false);
1405 task->set_file_offset(file_offset);
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001406 return load_library(ns, task, load_tasks, rtld_flags, realpath, search_linked_namespaces);
Spencer Low0346ad72015-04-22 18:06:51 -07001407 }
1408
1409 // Open the file.
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001410 int fd = open_library(ns, zip_archive_cache, name, needed_by, &file_offset, &realpath);
Spencer Low0346ad72015-04-22 18:06:51 -07001411 if (fd == -1) {
1412 DL_ERR("library \"%s\" not found", name);
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001413 return false;
Spencer Low0346ad72015-04-22 18:06:51 -07001414 }
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001415
1416 task->set_fd(fd, true);
1417 task->set_file_offset(file_offset);
1418
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001419 return load_library(ns, task, load_tasks, rtld_flags, realpath, search_linked_namespaces);
Spencer Low0346ad72015-04-22 18:06:51 -07001420}
1421
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001422static bool find_loaded_library_by_soname(android_namespace_t* ns,
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001423 const char* name,
1424 soinfo** candidate) {
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001425 return !ns->soinfo_list().visit([&](soinfo* si) {
Dmitriy Ivanov618f1a32015-03-17 20:06:36 -07001426 const char* soname = si->get_soname();
1427 if (soname != nullptr && (strcmp(name, soname) == 0)) {
Dimitry Ivanov3bd90612017-02-01 08:54:43 -08001428 *candidate = si;
1429 return false;
Ard Biesheuvel12c78bb2012-08-14 12:30:09 +02001430 }
Dmitriy Ivanova9703332015-06-16 15:38:21 -07001431
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001432 return true;
1433 });
Ard Biesheuvel12c78bb2012-08-14 12:30:09 +02001434}
1435
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001436// Returns true if library was found and false otherwise
1437static bool find_loaded_library_by_soname(android_namespace_t* ns,
1438 const char* name,
1439 bool search_linked_namespaces,
1440 soinfo** candidate) {
1441 *candidate = nullptr;
1442
1443 // Ignore filename with path.
1444 if (strchr(name, '/') != nullptr) {
1445 return false;
1446 }
1447
1448 bool found = find_loaded_library_by_soname(ns, name, candidate);
1449
1450 if (!found && search_linked_namespaces) {
1451 // if a library was not found - look into linked namespaces
1452 for (auto& link : ns->linked_namespaces()) {
1453 if (!link.is_accessible(name)) {
1454 continue;
1455 }
1456
1457 android_namespace_t* linked_ns = link.linked_namespace();
1458
1459 if (find_loaded_library_by_soname(linked_ns, name, candidate)) {
1460 return true;
1461 }
1462 }
1463 }
1464
1465 return found;
1466}
1467
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001468static bool find_library_in_linked_namespace(const android_namespace_link_t& namespace_link,
Jiyong Park02586a22017-05-20 01:01:24 +09001469 LoadTask* task) {
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001470 android_namespace_t* ns = namespace_link.linked_namespace();
1471
1472 soinfo* candidate;
1473 bool loaded = false;
1474
1475 std::string soname;
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001476 if (find_loaded_library_by_soname(ns, task->get_name(), false, &candidate)) {
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001477 loaded = true;
1478 soname = candidate->get_soname();
1479 } else {
1480 soname = resolve_soname(task->get_name());
1481 }
1482
1483 if (!namespace_link.is_accessible(soname.c_str())) {
1484 // the library is not accessible via namespace_link
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001485 LD_LOG(kLogDlopen,
1486 "find_library_in_linked_namespace(ns=%s, task=%s): Not accessible (soname=%s)",
1487 ns->get_name(), task->get_name(), soname.c_str());
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001488 return false;
1489 }
1490
1491 // if library is already loaded - return it
1492 if (loaded) {
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001493 LD_LOG(kLogDlopen, "find_library_in_linked_namespace(ns=%s, task=%s): Already loaded",
1494 ns->get_name(), task->get_name());
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001495 task->set_soinfo(candidate);
1496 return true;
1497 }
1498
Jiyong Park02586a22017-05-20 01:01:24 +09001499 // returning true with empty soinfo means that the library is okay to be
Logan Chien9ee45912018-01-18 12:05:09 +08001500 // loaded in the namespace but has not yet been loaded there before.
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001501 LD_LOG(kLogDlopen, "find_library_in_linked_namespace(ns=%s, task=%s): Ok to load", ns->get_name(),
1502 task->get_name());
Jiyong Park02586a22017-05-20 01:01:24 +09001503 task->set_soinfo(nullptr);
1504 return true;
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001505}
1506
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001507static bool find_library_internal(android_namespace_t* ns,
1508 LoadTask* task,
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001509 ZipArchiveCache* zip_archive_cache,
1510 LoadTaskList* load_tasks,
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001511 int rtld_flags,
1512 bool search_linked_namespaces) {
Dmitriy Ivanova9703332015-06-16 15:38:21 -07001513 soinfo* candidate;
1514
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001515 if (find_loaded_library_by_soname(ns, task->get_name(), search_linked_namespaces, &candidate)) {
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001516 LD_LOG(kLogDlopen,
1517 "find_library_internal(ns=%s, task=%s): Already loaded (by soname): %s",
1518 ns->get_name(), task->get_name(), candidate->get_realpath());
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001519 task->set_soinfo(candidate);
1520 return true;
Dmitriy Ivanova9703332015-06-16 15:38:21 -07001521 }
Dmitriy Ivanovb648a8a2014-05-19 15:06:58 -07001522
1523 // Library might still be loaded, the accurate detection
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001524 // of this fact is done by load_library.
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001525 TRACE("[ \"%s\" find_loaded_library_by_soname failed (*candidate=%s@%p). Trying harder... ]",
1526 task->get_name(), candidate == nullptr ? "n/a" : candidate->get_realpath(), candidate);
Dmitriy Ivanova9703332015-06-16 15:38:21 -07001527
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001528 if (load_library(ns, task, zip_archive_cache, load_tasks, rtld_flags, search_linked_namespaces)) {
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001529 return true;
1530 }
1531
Jiyong Parkefc503d2019-02-12 01:08:57 +09001532 // TODO(dimitry): workaround for http://b/26394120 (the grey-list)
1533 if (ns->is_greylist_enabled() && is_greylisted(ns, task->get_name(), task->get_needed_by())) {
1534 // For the libs in the greylist, switch to the default namespace and then
1535 // try the load again from there. The library could be loaded from the
1536 // default namespace or from another namespace (e.g. runtime) that is linked
1537 // from the default namespace.
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001538 LD_LOG(kLogDlopen,
1539 "find_library_internal(ns=%s, task=%s): Greylisted library - trying namespace %s",
1540 ns->get_name(), task->get_name(), g_default_namespace.get_name());
Jiyong Parkefc503d2019-02-12 01:08:57 +09001541 ns = &g_default_namespace;
1542 if (load_library(ns, task, zip_archive_cache, load_tasks, rtld_flags,
1543 search_linked_namespaces)) {
1544 return true;
1545 }
1546 }
1547 // END OF WORKAROUND
1548
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001549 if (search_linked_namespaces) {
1550 // if a library was not found - look into linked namespaces
dimitry8db36a52017-10-23 15:10:10 +02001551 // preserve current dlerror in the case it fails.
1552 DlErrorRestorer dlerror_restorer;
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001553 LD_LOG(kLogDlopen, "find_library_internal(ns=%s, task=%s): Trying %zu linked namespaces",
1554 ns->get_name(), task->get_name(), ns->linked_namespaces().size());
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001555 for (auto& linked_namespace : ns->linked_namespaces()) {
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001556 if (find_library_in_linked_namespace(linked_namespace, task)) {
Jiyong Park02586a22017-05-20 01:01:24 +09001557 if (task->get_soinfo() == nullptr) {
1558 // try to load the library - once namespace boundary is crossed
1559 // we need to load a library within separate load_group
1560 // to avoid using symbols from foreign namespace while.
1561 //
1562 // However, actual linking is deferred until when the global group
1563 // is fully identified and is applied to all namespaces.
1564 // Otherwise, the libs in the linked namespace won't get symbols from
1565 // the global group.
1566 if (load_library(linked_namespace.linked_namespace(), task, zip_archive_cache, load_tasks, rtld_flags, false)) {
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001567 LD_LOG(
1568 kLogDlopen, "find_library_internal(ns=%s, task=%s): Found in linked namespace %s",
1569 ns->get_name(), task->get_name(), linked_namespace.linked_namespace()->get_name());
Jiyong Park02586a22017-05-20 01:01:24 +09001570 return true;
1571 }
Jiyong Park02586a22017-05-20 01:01:24 +09001572 } else {
1573 // lib is already loaded
1574 return true;
1575 }
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001576 }
1577 }
1578 }
1579
1580 return false;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001581}
1582
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001583static void soinfo_unload(soinfo* si);
1584
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001585static void shuffle(std::vector<LoadTask*>* v) {
Tom Cherry66bc4282018-11-08 13:40:52 -08001586 if (is_first_stage_init()) {
1587 // arc4random* is not available in first stage init because /dev/random
1588 // hasn't yet been created.
Jiyong Park31cd08f2018-06-01 19:18:56 +09001589 return;
1590 }
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001591 for (size_t i = 0, size = v->size(); i < size; ++i) {
1592 size_t n = size - i;
1593 size_t r = arc4random_uniform(n);
1594 std::swap((*v)[n-1], (*v)[r]);
1595 }
1596}
1597
Evgenii Stepanov0cdef7e2015-07-06 17:56:31 -07001598// add_as_children - add first-level loaded libraries (i.e. library_names[], but
1599// not their transitive dependencies) as children of the start_with library.
1600// This is false when find_libraries is called for dlopen(), when newly loaded
1601// libraries must form a disjoint tree.
Dimitry Ivanov3f660572016-09-09 10:00:39 -07001602bool find_libraries(android_namespace_t* ns,
1603 soinfo* start_with,
1604 const char* const library_names[],
1605 size_t library_names_count,
1606 soinfo* soinfos[],
1607 std::vector<soinfo*>* ld_preloads,
1608 size_t ld_preloads_count,
1609 int rtld_flags,
1610 const android_dlextinfo* extinfo,
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001611 bool add_as_children,
Jiyong Park02586a22017-05-20 01:01:24 +09001612 bool search_linked_namespaces,
Jiyong Park02586a22017-05-20 01:01:24 +09001613 std::vector<android_namespace_t*>* namespaces) {
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001614 // Step 0: prepare.
dimitry965d06d2017-11-28 16:03:07 +01001615 std::unordered_map<const soinfo*, ElfReader> readers_map;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001616 LoadTaskList load_tasks;
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001617
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -07001618 for (size_t i = 0; i < library_names_count; ++i) {
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001619 const char* name = library_names[i];
Jiyong Park02586a22017-05-20 01:01:24 +09001620 load_tasks.push_back(LoadTask::create(name, start_with, ns, &readers_map));
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001621 }
1622
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -07001623 // If soinfos array is null allocate one on stack.
1624 // The array is needed in case of failure; for example
1625 // when library_names[] = {libone.so, libtwo.so} and libone.so
1626 // is loaded correctly but libtwo.so failed for some reason.
1627 // In this case libone.so should be unloaded on return.
1628 // See also implementation of failure_guard below.
1629
1630 if (soinfos == nullptr) {
1631 size_t soinfos_size = sizeof(soinfo*)*library_names_count;
1632 soinfos = reinterpret_cast<soinfo**>(alloca(soinfos_size));
1633 memset(soinfos, 0, soinfos_size);
1634 }
1635
1636 // list of libraries to link - see step 2.
1637 size_t soinfos_count = 0;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001638
Tom Cherryb8ab6182017-04-05 16:20:29 -07001639 auto scope_guard = android::base::make_scope_guard([&]() {
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001640 for (LoadTask* t : load_tasks) {
1641 LoadTask::deleter(t);
1642 }
1643 });
1644
Dmitriy Ivanovb4827502015-09-28 16:38:31 -07001645 ZipArchiveCache zip_archive_cache;
1646
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001647 // Step 1: expand the list of load_tasks to include
1648 // all DT_NEEDED libraries (do not load them just yet)
1649 for (size_t i = 0; i<load_tasks.size(); ++i) {
1650 LoadTask* task = load_tasks[i];
Evgenii Stepanov68650822015-06-10 13:38:39 -07001651 soinfo* needed_by = task->get_needed_by();
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001652
Dmitriy Ivanovedfc9f62015-09-02 16:32:02 -07001653 bool is_dt_needed = needed_by != nullptr && (needed_by != start_with || add_as_children);
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001654 task->set_extinfo(is_dt_needed ? nullptr : extinfo);
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07001655 task->set_dt_needed(is_dt_needed);
Dmitriy Ivanovedfc9f62015-09-02 16:32:02 -07001656
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001657 LD_LOG(kLogDlopen, "find_libraries(ns=%s): task=%s, is_dt_needed=%d", ns->get_name(),
1658 task->get_name(), is_dt_needed);
1659
Jiyong Park02586a22017-05-20 01:01:24 +09001660 // Note: start from the namespace that is stored in the LoadTask. This namespace
1661 // is different from the current namespace when the LoadTask is for a transitive
1662 // dependency and the lib that created the LoadTask is not found in the
1663 // current namespace but in one of the linked namespace.
1664 if (!find_library_internal(const_cast<android_namespace_t*>(task->get_start_from()),
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001665 task,
1666 &zip_archive_cache,
1667 &load_tasks,
1668 rtld_flags,
1669 search_linked_namespaces || is_dt_needed)) {
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001670 return false;
1671 }
1672
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001673 soinfo* si = task->get_soinfo();
1674
Dmitriy Ivanovedfc9f62015-09-02 16:32:02 -07001675 if (is_dt_needed) {
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001676 needed_by->add_child(si);
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08001677 }
1678
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -07001679 // When ld_preloads is not null, the first
1680 // ld_preloads_count libs are in fact ld_preloads.
1681 if (ld_preloads != nullptr && soinfos_count < ld_preloads_count) {
Dmitriy Ivanovd165f562015-03-23 18:43:02 -07001682 ld_preloads->push_back(si);
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001683 }
1684
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -07001685 if (soinfos_count < library_names_count) {
1686 soinfos[soinfos_count++] = si;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001687 }
1688 }
1689
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001690 // Step 2: Load libraries in random order (see b/24047022)
1691 LoadTaskList load_list;
1692 for (auto&& task : load_tasks) {
1693 soinfo* si = task->get_soinfo();
1694 auto pred = [&](const LoadTask* t) {
1695 return t->get_soinfo() == si;
1696 };
1697
1698 if (!si->is_linked() &&
1699 std::find_if(load_list.begin(), load_list.end(), pred) == load_list.end() ) {
1700 load_list.push_back(task);
1701 }
1702 }
Torne (Richard Coles)efbe9a52018-10-17 15:59:38 -04001703 bool reserved_address_recursive = false;
1704 if (extinfo) {
1705 reserved_address_recursive = extinfo->flags & ANDROID_DLEXT_RESERVED_ADDRESS_RECURSIVE;
1706 }
1707 if (!reserved_address_recursive) {
1708 // Shuffle the load order in the normal case, but not if we are loading all
1709 // the libraries to a reserved address range.
1710 shuffle(&load_list);
1711 }
1712
1713 // Set up address space parameters.
1714 address_space_params extinfo_params, default_params;
1715 size_t relro_fd_offset = 0;
1716 if (extinfo) {
1717 if (extinfo->flags & ANDROID_DLEXT_RESERVED_ADDRESS) {
1718 extinfo_params.start_addr = extinfo->reserved_addr;
1719 extinfo_params.reserved_size = extinfo->reserved_size;
1720 extinfo_params.must_use_address = true;
1721 } else if (extinfo->flags & ANDROID_DLEXT_RESERVED_ADDRESS_HINT) {
1722 extinfo_params.start_addr = extinfo->reserved_addr;
1723 extinfo_params.reserved_size = extinfo->reserved_size;
1724 }
1725 }
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001726
1727 for (auto&& task : load_list) {
Torne (Richard Coles)efbe9a52018-10-17 15:59:38 -04001728 address_space_params* address_space =
1729 (reserved_address_recursive || !task->is_dt_needed()) ? &extinfo_params : &default_params;
1730 if (!task->load(address_space)) {
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001731 return false;
1732 }
1733 }
1734
1735 // Step 3: pre-link all DT_NEEDED libraries in breadth first order.
1736 for (auto&& task : load_tasks) {
1737 soinfo* si = task->get_soinfo();
1738 if (!si->is_linked() && !si->prelink_image()) {
1739 return false;
1740 }
Ryan Pricharde5e69e02019-01-01 18:53:48 -08001741 register_soinfo_tls(si);
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001742 }
1743
Jiyong Park02586a22017-05-20 01:01:24 +09001744 // Step 4: Construct the global group. Note: DF_1_GLOBAL bit of a library is
1745 // determined at step 3.
1746
1747 // Step 4-1: DF_1_GLOBAL bit is force set for LD_PRELOADed libs because they
1748 // must be added to the global group
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001749 if (ld_preloads != nullptr) {
1750 for (auto&& si : *ld_preloads) {
1751 si->set_dt_flags_1(si->get_dt_flags_1() | DF_1_GLOBAL);
1752 }
1753 }
1754
Jiyong Park02586a22017-05-20 01:01:24 +09001755 // Step 4-2: Gather all DF_1_GLOBAL libs which were newly loaded during this
1756 // run. These will be the new member of the global group
1757 soinfo_list_t new_global_group_members;
1758 for (auto&& task : load_tasks) {
1759 soinfo* si = task->get_soinfo();
1760 if (!si->is_linked() && (si->get_dt_flags_1() & DF_1_GLOBAL) != 0) {
1761 new_global_group_members.push_back(si);
1762 }
1763 }
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001764
Jiyong Park02586a22017-05-20 01:01:24 +09001765 // Step 4-3: Add the new global group members to all the linked namespaces
Jiyong Park01162f22017-10-16 15:31:09 +09001766 if (namespaces != nullptr) {
Jiyong Park02586a22017-05-20 01:01:24 +09001767 for (auto linked_ns : *namespaces) {
Jiyong Park01162f22017-10-16 15:31:09 +09001768 for (auto si : new_global_group_members) {
1769 if (si->get_primary_namespace() != linked_ns) {
1770 linked_ns->add_soinfo(si);
1771 si->add_secondary_namespace(linked_ns);
1772 }
Jiyong Park02586a22017-05-20 01:01:24 +09001773 }
1774 }
1775 }
1776
dimitry965d06d2017-11-28 16:03:07 +01001777 // Step 5: Collect roots of local_groups.
1778 // Whenever needed_by->si link crosses a namespace boundary it forms its own local_group.
1779 // Here we collect new roots to link them separately later on. Note that we need to avoid
1780 // collecting duplicates. Also the order is important. They need to be linked in the same
1781 // BFS order we link individual libraries.
1782 std::vector<soinfo*> local_group_roots;
1783 if (start_with != nullptr && add_as_children) {
1784 local_group_roots.push_back(start_with);
1785 } else {
1786 CHECK(soinfos_count == 1);
1787 local_group_roots.push_back(soinfos[0]);
1788 }
1789
Jiyong Park02586a22017-05-20 01:01:24 +09001790 for (auto&& task : load_tasks) {
1791 soinfo* si = task->get_soinfo();
dimitry965d06d2017-11-28 16:03:07 +01001792 soinfo* needed_by = task->get_needed_by();
1793 bool is_dt_needed = needed_by != nullptr && (needed_by != start_with || add_as_children);
1794 android_namespace_t* needed_by_ns =
1795 is_dt_needed ? needed_by->get_primary_namespace() : ns;
1796
1797 if (!si->is_linked() && si->get_primary_namespace() != needed_by_ns) {
1798 auto it = std::find(local_group_roots.begin(), local_group_roots.end(), si);
1799 LD_LOG(kLogDlopen,
1800 "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",
1801 si->get_realpath(),
1802 si,
1803 si->get_primary_namespace()->get_name(),
1804 si->get_primary_namespace(),
1805 needed_by == nullptr ? "(nullptr)" : needed_by->get_realpath(),
1806 needed_by,
1807 ns->get_name(),
1808 ns,
1809 needed_by_ns->get_name(),
1810 needed_by_ns,
1811 it == local_group_roots.end() ? "yes" : "no");
1812
1813 if (it == local_group_roots.end()) {
1814 local_group_roots.push_back(si);
Jiyong Park02586a22017-05-20 01:01:24 +09001815 }
1816 }
1817 }
1818
dimitry965d06d2017-11-28 16:03:07 +01001819 // Step 6: Link all local groups
1820 for (auto root : local_group_roots) {
1821 soinfo_list_t local_group;
1822 android_namespace_t* local_group_ns = root->get_primary_namespace();
1823
1824 walk_dependencies_tree(root,
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -07001825 [&] (soinfo* si) {
dimitry965d06d2017-11-28 16:03:07 +01001826 if (local_group_ns->is_accessible(si)) {
1827 local_group.push_back(si);
1828 return kWalkContinue;
1829 } else {
1830 return kWalkSkip;
1831 }
1832 });
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -07001833
dimitry965d06d2017-11-28 16:03:07 +01001834 soinfo_list_t global_group = local_group_ns->get_global_group();
Ryan Prichardf56ac992020-01-02 16:36:06 -08001835 SymbolLookupList lookup_list(global_group, local_group);
1836 soinfo* local_group_root = local_group.front();
dimitry965d06d2017-11-28 16:03:07 +01001837 bool linked = local_group.visit([&](soinfo* si) {
Torne (Richard Coles)ebfebd02019-04-11 12:25:06 -04001838 // Even though local group may contain accessible soinfos from other namespaces
dimitry965d06d2017-11-28 16:03:07 +01001839 // we should avoid linking them (because if they are not linked -> they
1840 // are in the local_group_roots and will be linked later).
1841 if (!si->is_linked() && si->get_primary_namespace() == local_group_ns) {
Torne (Richard Coles)ebfebd02019-04-11 12:25:06 -04001842 const android_dlextinfo* link_extinfo = nullptr;
1843 if (si == soinfos[0] || reserved_address_recursive) {
1844 // Only forward extinfo for the first library unless the recursive
1845 // flag is set.
1846 link_extinfo = extinfo;
1847 }
Ryan Prichardf56ac992020-01-02 16:36:06 -08001848 lookup_list.set_dt_symbolic_lib(si->has_DT_SYMBOLIC ? si : nullptr);
1849 if (!si->link_image(lookup_list, local_group_root, link_extinfo, &relro_fd_offset) ||
dimitry965d06d2017-11-28 16:03:07 +01001850 !get_cfi_shadow()->AfterLoad(si, solist_get_head())) {
1851 return false;
1852 }
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001853 }
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -07001854
dimitry965d06d2017-11-28 16:03:07 +01001855 return true;
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001856 });
Elliott Hughes27f18062017-11-29 18:47:42 +00001857
dimitry965d06d2017-11-28 16:03:07 +01001858 if (!linked) {
1859 return false;
1860 }
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001861 }
1862
dimitry965d06d2017-11-28 16:03:07 +01001863 // Step 7: Mark all load_tasks as linked and increment refcounts
1864 // for references between load_groups (at this point it does not matter if
1865 // referenced load_groups were loaded by previous dlopen or as part of this
1866 // one on step 6)
1867 if (start_with != nullptr && add_as_children) {
1868 start_with->set_linked();
1869 }
1870
1871 for (auto&& task : load_tasks) {
1872 soinfo* si = task->get_soinfo();
1873 si->set_linked();
1874 }
1875
1876 for (auto&& task : load_tasks) {
1877 soinfo* si = task->get_soinfo();
1878 soinfo* needed_by = task->get_needed_by();
1879 if (needed_by != nullptr &&
1880 needed_by != start_with &&
1881 needed_by->get_local_group_root() != si->get_local_group_root()) {
1882 si->increment_ref_count();
1883 }
1884 }
1885
1886
1887 return true;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001888}
1889
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001890static soinfo* find_library(android_namespace_t* ns,
1891 const char* name, int rtld_flags,
Evgenii Stepanov0cdef7e2015-07-06 17:56:31 -07001892 const android_dlextinfo* extinfo,
1893 soinfo* needed_by) {
dimitry965d06d2017-11-28 16:03:07 +01001894 soinfo* si = nullptr;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001895
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08001896 if (name == nullptr) {
Dimitry Ivanov3f660572016-09-09 10:00:39 -07001897 si = solist_get_somain();
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001898 } else if (!find_libraries(ns,
1899 needed_by,
1900 &name,
1901 1,
1902 &si,
1903 nullptr,
1904 0,
1905 rtld_flags,
1906 extinfo,
1907 false /* add_as_children */,
dimitry965d06d2017-11-28 16:03:07 +01001908 true /* search_linked_namespaces */)) {
1909 if (si != nullptr) {
1910 soinfo_unload(si);
1911 }
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001912 return nullptr;
1913 }
1914
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001915 si->increment_ref_count();
1916
Elliott Hughesd23736e2012-11-01 15:16:56 -07001917 return si;
1918}
Elliott Hughesbedfe382012-08-14 14:07:59 -07001919
dimitry06016f22018-01-05 11:39:28 +01001920static void soinfo_unload_impl(soinfo* root) {
Dimitry Ivanov6705e8c2017-03-21 10:29:06 -07001921 ScopedTrace trace((std::string("unload ") + root->get_realpath()).c_str());
dimitry06016f22018-01-05 11:39:28 +01001922 bool is_linked = root->is_linked();
Dimitry Ivanov6705e8c2017-03-21 10:29:06 -07001923
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08001924 if (!root->can_unload()) {
dimitryc92ce712017-10-27 14:12:53 +02001925 LD_LOG(kLogDlopen,
1926 "... dlclose(root=\"%s\"@%p) ... not unloading - the load group is flagged with NODELETE",
1927 root->get_realpath(),
1928 root);
Dmitriy Ivanov1b20daf2014-05-19 15:06:58 -07001929 return;
1930 }
1931
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08001932
Dimitry Ivanovb943f302016-08-03 16:00:10 -07001933 soinfo_list_t unload_list;
dimitry965d06d2017-11-28 16:03:07 +01001934 unload_list.push_back(root);
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001935
Dimitry Ivanovb943f302016-08-03 16:00:10 -07001936 soinfo_list_t local_unload_list;
1937 soinfo_list_t external_unload_list;
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001938 soinfo* si = nullptr;
1939
1940 while ((si = unload_list.pop_front()) != nullptr) {
1941 if (local_unload_list.contains(si)) {
1942 continue;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001943 }
Elliott Hughesd23736e2012-11-01 15:16:56 -07001944
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001945 local_unload_list.push_back(si);
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08001946
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001947 if (si->has_min_version(0)) {
1948 soinfo* child = nullptr;
1949 while ((child = si->get_children().pop_front()) != nullptr) {
1950 TRACE("%s@%p needs to unload %s@%p", si->get_realpath(), si,
1951 child->get_realpath(), child);
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08001952
Dimitry Ivanovec90e242017-02-10 11:04:20 -08001953 child->get_parents().remove(si);
1954
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001955 if (local_unload_list.contains(child)) {
1956 continue;
1957 } else if (child->is_linked() && child->get_local_group_root() != root) {
1958 external_unload_list.push_back(child);
Dimitry Ivanovec90e242017-02-10 11:04:20 -08001959 } else if (child->get_parents().empty()) {
1960 unload_list.push_back(child);
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001961 }
1962 }
1963 } else {
Christopher Ferris7a3681e2017-04-24 17:48:32 -07001964 async_safe_fatal("soinfo for \"%s\"@%p has no version", si->get_realpath(), si);
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08001965 }
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001966 }
1967
1968 local_unload_list.for_each([](soinfo* si) {
dimitryc92ce712017-10-27 14:12:53 +02001969 LD_LOG(kLogDlopen,
1970 "... dlclose: calling destructors for \"%s\"@%p ... ",
1971 si->get_realpath(),
1972 si);
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001973 si->call_destructors();
dimitryc92ce712017-10-27 14:12:53 +02001974 LD_LOG(kLogDlopen,
1975 "... dlclose: calling destructors for \"%s\"@%p ... done",
1976 si->get_realpath(),
1977 si);
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001978 });
1979
1980 while ((si = local_unload_list.pop_front()) != nullptr) {
dimitryc92ce712017-10-27 14:12:53 +02001981 LD_LOG(kLogDlopen,
1982 "... dlclose: unloading \"%s\"@%p ...",
1983 si->get_realpath(),
1984 si);
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001985 notify_gdb_of_unload(si);
Ryan Pricharde5e69e02019-01-01 18:53:48 -08001986 unregister_soinfo_tls(si);
Evgenii Stepanov0a3637d2016-07-06 13:20:59 -07001987 get_cfi_shadow()->BeforeUnload(si);
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001988 soinfo_free(si);
1989 }
1990
dimitry965d06d2017-11-28 16:03:07 +01001991 if (is_linked) {
1992 while ((si = external_unload_list.pop_front()) != nullptr) {
1993 LD_LOG(kLogDlopen,
1994 "... dlclose: unloading external reference \"%s\"@%p ...",
1995 si->get_realpath(),
1996 si);
1997 soinfo_unload(si);
1998 }
1999 } else {
2000 LD_LOG(kLogDlopen,
2001 "... dlclose: unload_si was not linked - not unloading external references ...");
Dmitriy Ivanova2547052014-11-18 12:03:09 -08002002 }
2003}
2004
dimitry06016f22018-01-05 11:39:28 +01002005static void soinfo_unload(soinfo* unload_si) {
2006 // Note that the library can be loaded but not linked;
2007 // in which case there is no root but we still need
2008 // to walk the tree and unload soinfos involved.
2009 //
2010 // This happens on unsuccessful dlopen, when one of
2011 // the DT_NEEDED libraries could not be linked/found.
2012 bool is_linked = unload_si->is_linked();
2013 soinfo* root = is_linked ? unload_si->get_local_group_root() : unload_si;
2014
2015 LD_LOG(kLogDlopen,
2016 "... dlclose(realpath=\"%s\"@%p) ... load group root is \"%s\"@%p",
2017 unload_si->get_realpath(),
2018 unload_si,
2019 root->get_realpath(),
2020 root);
2021
2022
2023 size_t ref_count = is_linked ? root->decrement_ref_count() : 0;
2024 if (ref_count > 0) {
2025 LD_LOG(kLogDlopen,
2026 "... dlclose(root=\"%s\"@%p) ... not unloading - decrementing ref_count to %zd",
2027 root->get_realpath(),
2028 root,
2029 ref_count);
2030 return;
2031 }
2032
2033 soinfo_unload_impl(root);
2034}
2035
2036void increment_dso_handle_reference_counter(void* dso_handle) {
2037 if (dso_handle == nullptr) {
2038 return;
2039 }
2040
2041 auto it = g_dso_handle_counters.find(dso_handle);
2042 if (it != g_dso_handle_counters.end()) {
2043 CHECK(++it->second != 0);
2044 } else {
2045 soinfo* si = find_containing_library(dso_handle);
2046 if (si != nullptr) {
2047 ProtectedDataGuard guard;
dimitry55547db2018-05-25 14:17:37 +02002048 si->increment_ref_count();
dimitry06016f22018-01-05 11:39:28 +01002049 } else {
2050 async_safe_fatal(
2051 "increment_dso_handle_reference_counter: Couldn't find soinfo by dso_handle=%p",
2052 dso_handle);
2053 }
2054 g_dso_handle_counters[dso_handle] = 1U;
2055 }
2056}
2057
2058void decrement_dso_handle_reference_counter(void* dso_handle) {
2059 if (dso_handle == nullptr) {
2060 return;
2061 }
2062
2063 auto it = g_dso_handle_counters.find(dso_handle);
2064 CHECK(it != g_dso_handle_counters.end());
2065 CHECK(it->second != 0);
2066
2067 if (--it->second == 0) {
2068 soinfo* si = find_containing_library(dso_handle);
2069 if (si != nullptr) {
2070 ProtectedDataGuard guard;
dimitry55547db2018-05-25 14:17:37 +02002071 soinfo_unload(si);
dimitry06016f22018-01-05 11:39:28 +01002072 } else {
2073 async_safe_fatal(
2074 "decrement_dso_handle_reference_counter: Couldn't find soinfo by dso_handle=%p",
2075 dso_handle);
2076 }
2077 g_dso_handle_counters.erase(it);
2078 }
2079}
2080
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002081static std::string symbol_display_name(const char* sym_name, const char* sym_ver) {
2082 if (sym_ver == nullptr) {
2083 return sym_name;
2084 }
2085
Dimitry Ivanov9cf99cb2015-12-11 14:22:24 -08002086 return std::string(sym_name) + ", version " + sym_ver;
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002087}
2088
Dimitry Ivanovaca299a2016-04-11 12:42:58 -07002089static android_namespace_t* get_caller_namespace(soinfo* caller) {
2090 return caller != nullptr ? caller->get_primary_namespace() : g_anonymous_namespace;
2091}
2092
Elliott Hughesa4aafd12014-01-13 16:37:47 -08002093void do_android_get_LD_LIBRARY_PATH(char* buffer, size_t buffer_size) {
Christopher Ferris052fa3a2014-08-26 20:48:11 -07002094 // Use basic string manipulation calls to avoid snprintf.
2095 // snprintf indirectly calls pthread_getspecific to get the size of a buffer.
2096 // When debug malloc is enabled, this call returns 0. This in turn causes
2097 // snprintf to do nothing, which causes libraries to fail to load.
2098 // See b/17302493 for further details.
2099 // Once the above bug is fixed, this code can be modified to use
2100 // snprintf again.
Dimitry Ivanov77ad6422017-03-06 13:02:29 -08002101 const auto& default_ld_paths = g_default_namespace.get_default_library_paths();
2102
2103 size_t required_size = 0;
2104 for (const auto& path : default_ld_paths) {
2105 required_size += path.size() + 1;
Evgenii Stepanovd640b222015-07-10 17:54:01 -07002106 }
Dimitry Ivanov77ad6422017-03-06 13:02:29 -08002107
2108 if (buffer_size < required_size) {
Christopher Ferris7a3681e2017-04-24 17:48:32 -07002109 async_safe_fatal("android_get_LD_LIBRARY_PATH failed, buffer too small: "
2110 "buffer len %zu, required len %zu", buffer_size, required_size);
Christopher Ferris052fa3a2014-08-26 20:48:11 -07002111 }
Dimitry Ivanov77ad6422017-03-06 13:02:29 -08002112
Evgenii Stepanovd640b222015-07-10 17:54:01 -07002113 char* end = buffer;
Dimitry Ivanov77ad6422017-03-06 13:02:29 -08002114 for (size_t i = 0; i < default_ld_paths.size(); ++i) {
Evgenii Stepanovd640b222015-07-10 17:54:01 -07002115 if (i > 0) *end++ = ':';
Dimitry Ivanov77ad6422017-03-06 13:02:29 -08002116 end = stpcpy(end, default_ld_paths[i].c_str());
Evgenii Stepanovd640b222015-07-10 17:54:01 -07002117 }
Elliott Hughesa4aafd12014-01-13 16:37:47 -08002118}
2119
Elliott Hughescade4c32012-12-20 14:42:14 -08002120void do_android_update_LD_LIBRARY_PATH(const char* ld_library_path) {
Nick Kralevich6bb01b62015-03-07 13:37:05 -08002121 parse_LD_LIBRARY_PATH(ld_library_path);
Elliott Hughescade4c32012-12-20 14:42:14 -08002122}
2123
Dimitry Ivanovb996d602016-07-11 18:11:39 -07002124static std::string android_dlextinfo_to_string(const android_dlextinfo* info) {
2125 if (info == nullptr) {
2126 return "(null)";
2127 }
2128
2129 return android::base::StringPrintf("[flags=0x%" PRIx64 ","
2130 " reserved_addr=%p,"
2131 " reserved_size=0x%zx,"
2132 " relro_fd=%d,"
2133 " library_fd=%d,"
2134 " library_fd_offset=0x%" PRIx64 ","
2135 " library_namespace=%s@%p]",
2136 info->flags,
2137 info->reserved_addr,
2138 info->reserved_size,
2139 info->relro_fd,
2140 info->library_fd,
2141 info->library_fd_offset,
2142 (info->flags & ANDROID_DLEXT_USE_NAMESPACE) != 0 ?
2143 (info->library_namespace != nullptr ?
2144 info->library_namespace->get_name() : "(null)") : "(n/a)",
2145 (info->flags & ANDROID_DLEXT_USE_NAMESPACE) != 0 ?
2146 info->library_namespace : nullptr);
2147}
2148
Dimitry Ivanovd9e427c2016-11-22 16:55:25 -08002149void* do_dlopen(const char* name, int flags,
2150 const android_dlextinfo* extinfo,
2151 const void* caller_addr) {
Dimitry Ivanov5c4a5802017-03-17 16:41:34 -07002152 std::string trace_prefix = std::string("dlopen: ") + (name == nullptr ? "(nullptr)" : name);
2153 ScopedTrace trace(trace_prefix.c_str());
2154 ScopedTrace loading_trace((trace_prefix + " - loading and linking").c_str());
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002155 soinfo* const caller = find_containing_library(caller_addr);
Dimitry Ivanovb996d602016-07-11 18:11:39 -07002156 android_namespace_t* ns = get_caller_namespace(caller);
2157
2158 LD_LOG(kLogDlopen,
Victor Chang6cb719f2019-02-06 17:19:10 +00002159 "dlopen(name=\"%s\", flags=0x%x, extinfo=%s, caller=\"%s\", caller_ns=%s@%p, targetSdkVersion=%i) ...",
Dimitry Ivanovb996d602016-07-11 18:11:39 -07002160 name,
2161 flags,
2162 android_dlextinfo_to_string(extinfo).c_str(),
2163 caller == nullptr ? "(null)" : caller->get_realpath(),
2164 ns == nullptr ? "(null)" : ns->get_name(),
Victor Chang6cb719f2019-02-06 17:19:10 +00002165 ns,
2166 get_application_target_sdk_version());
Dimitry Ivanovb996d602016-07-11 18:11:39 -07002167
Vic Yangbb7e1232019-01-29 20:23:16 -08002168 auto purge_guard = android::base::make_scope_guard([&]() { purge_unused_memory(); });
2169
Tom Cherryb8ab6182017-04-05 16:20:29 -07002170 auto failure_guard = android::base::make_scope_guard(
2171 [&]() { LD_LOG(kLogDlopen, "... dlopen failed: %s", linker_get_error_buffer()); });
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002172
Dmitriy Ivanov1b20daf2014-05-19 15:06:58 -07002173 if ((flags & ~(RTLD_NOW|RTLD_LAZY|RTLD_LOCAL|RTLD_GLOBAL|RTLD_NODELETE|RTLD_NOLOAD)) != 0) {
Elliott Hughese66190d2012-12-18 15:57:55 -08002174 DL_ERR("invalid flags to dlopen: %x", flags);
Dmitriy Ivanov851135b2014-08-29 12:02:36 -07002175 return nullptr;
Elliott Hughese66190d2012-12-18 15:57:55 -08002176 }
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002177
Dmitriy Ivanov07e5bc12014-10-03 17:52:44 -07002178 if (extinfo != nullptr) {
2179 if ((extinfo->flags & ~(ANDROID_DLEXT_VALID_FLAG_BITS)) != 0) {
2180 DL_ERR("invalid extended flags to android_dlopen_ext: 0x%" PRIx64, extinfo->flags);
2181 return nullptr;
2182 }
Dmitriy Ivanov126af752015-10-07 16:34:20 -07002183
Dmitriy Ivanov07e5bc12014-10-03 17:52:44 -07002184 if ((extinfo->flags & ANDROID_DLEXT_USE_LIBRARY_FD) == 0 &&
Dmitriy Ivanova6c12792014-10-21 12:09:18 -07002185 (extinfo->flags & ANDROID_DLEXT_USE_LIBRARY_FD_OFFSET) != 0) {
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07002186 DL_ERR("invalid extended flag combination (ANDROID_DLEXT_USE_LIBRARY_FD_OFFSET without "
2187 "ANDROID_DLEXT_USE_LIBRARY_FD): 0x%" PRIx64, extinfo->flags);
Dmitriy Ivanov07e5bc12014-10-03 17:52:44 -07002188 return nullptr;
2189 }
Dmitriy Ivanov126af752015-10-07 16:34:20 -07002190
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002191 if ((extinfo->flags & ANDROID_DLEXT_USE_NAMESPACE) != 0) {
2192 if (extinfo->library_namespace == nullptr) {
2193 DL_ERR("ANDROID_DLEXT_USE_NAMESPACE is set but extinfo->library_namespace is null");
2194 return nullptr;
2195 }
2196 ns = extinfo->library_namespace;
2197 }
Torne (Richard Coles)012cb452014-02-06 14:34:21 +00002198 }
Dmitriy Ivanov279a22f2015-01-23 12:03:53 -08002199
Victor Chang6cb719f2019-02-06 17:19:10 +00002200 // Workaround for dlopen(/system/lib/<soname>) when .so is in /apex. http://b/121248172
2201 // The workaround works only when targetSdkVersion < Q.
2202 std::string name_to_apex;
2203 if (translateSystemPathToApexPath(name, &name_to_apex)) {
2204 const char* new_name = name_to_apex.c_str();
2205 LD_LOG(kLogDlopen, "dlopen considering translation from %s to APEX path %s",
2206 name,
2207 new_name);
2208 // Some APEXs could be optionally disabled. Only translate the path
2209 // when the old file is absent and the new file exists.
Victor Changaf12c942019-02-11 19:35:24 +00002210 // TODO(b/124218500): Re-enable it once app compat issue is resolved
2211 /*
Victor Chang6cb719f2019-02-06 17:19:10 +00002212 if (file_exists(name)) {
2213 LD_LOG(kLogDlopen, "dlopen %s exists, not translating", name);
Victor Changaf12c942019-02-11 19:35:24 +00002214 } else
2215 */
2216 if (!file_exists(new_name)) {
Victor Chang6cb719f2019-02-06 17:19:10 +00002217 LD_LOG(kLogDlopen, "dlopen %s does not exist, not translating",
2218 new_name);
2219 } else {
2220 LD_LOG(kLogDlopen, "dlopen translation accepted: using %s", new_name);
2221 name = new_name;
2222 }
2223 }
2224 // End Workaround for dlopen(/system/lib/<soname>) when .so is in /apex.
2225
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -07002226 std::string asan_name_holder;
2227
2228 const char* translated_name = name;
Dimitry Ivanov6c14f862016-12-05 13:35:47 -08002229 if (g_is_asan && translated_name != nullptr && translated_name[0] == '/') {
Evgenii Stepanov9e77a642017-07-27 14:55:44 -07002230 char original_path[PATH_MAX];
2231 if (realpath(name, original_path) != nullptr) {
2232 asan_name_holder = std::string(kAsanLibDirPrefix) + original_path;
Vishwath Mohan4113def2017-03-29 15:31:34 -07002233 if (file_exists(asan_name_holder.c_str())) {
Evgenii Stepanov9e77a642017-07-27 14:55:44 -07002234 soinfo* si = nullptr;
2235 if (find_loaded_library_by_realpath(ns, original_path, true, &si)) {
2236 PRINT("linker_asan dlopen NOT translating \"%s\" -> \"%s\": library already loaded", name,
2237 asan_name_holder.c_str());
2238 } else {
2239 PRINT("linker_asan dlopen translating \"%s\" -> \"%s\"", name, translated_name);
2240 translated_name = asan_name_holder.c_str();
2241 }
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -07002242 }
2243 }
2244 }
2245
Dmitriy Ivanov279a22f2015-01-23 12:03:53 -08002246 ProtectedDataGuard guard;
Christopher R. Palmer9dc396a2017-04-08 22:40:01 +02002247#ifdef LD_SHIM_LIBS
2248 reset_g_active_shim_libs();
2249#endif
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -07002250 soinfo* si = find_library(ns, translated_name, flags, extinfo, caller);
Dimitry Ivanov5c4a5802017-03-17 16:41:34 -07002251 loading_trace.End();
2252
Dmitriy Ivanov851135b2014-08-29 12:02:36 -07002253 if (si != nullptr) {
Dimitry Ivanovb996d602016-07-11 18:11:39 -07002254 void* handle = si->to_handle();
2255 LD_LOG(kLogDlopen,
Dimitry Ivanovae4a0c12016-11-21 10:44:35 -08002256 "... dlopen calling constructors: realpath=\"%s\", soname=\"%s\", handle=%p",
2257 si->get_realpath(), si->get_soname(), handle);
2258 si->call_constructors();
Tom Cherryb8ab6182017-04-05 16:20:29 -07002259 failure_guard.Disable();
Dimitry Ivanovae4a0c12016-11-21 10:44:35 -08002260 LD_LOG(kLogDlopen,
Dimitry Ivanovb996d602016-07-11 18:11:39 -07002261 "... dlopen successful: realpath=\"%s\", soname=\"%s\", handle=%p",
2262 si->get_realpath(), si->get_soname(), handle);
2263 return handle;
Elliott Hughesd23736e2012-11-01 15:16:56 -07002264 }
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002265
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -07002266 return nullptr;
Elliott Hughesd23736e2012-11-01 15:16:56 -07002267}
2268
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002269int do_dladdr(const void* addr, Dl_info* info) {
2270 // Determine if this address can be found in any library currently mapped.
2271 soinfo* si = find_containing_library(addr);
2272 if (si == nullptr) {
2273 return 0;
2274 }
2275
2276 memset(info, 0, sizeof(Dl_info));
2277
2278 info->dli_fname = si->get_realpath();
2279 // Address at which the shared object is loaded.
2280 info->dli_fbase = reinterpret_cast<void*>(si->base);
2281
2282 // Determine if any symbol in the library contains the specified address.
2283 ElfW(Sym)* sym = si->find_symbol_by_address(addr);
2284 if (sym != nullptr) {
2285 info->dli_sname = si->get_string(sym->st_name);
2286 info->dli_saddr = reinterpret_cast<void*>(si->resolve_symbol_address(sym));
2287 }
2288
2289 return 1;
2290}
2291
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -07002292static soinfo* soinfo_from_handle(void* handle) {
2293 if ((reinterpret_cast<uintptr_t>(handle) & 1) != 0) {
2294 auto it = g_soinfo_handles_map.find(reinterpret_cast<uintptr_t>(handle));
2295 if (it == g_soinfo_handles_map.end()) {
2296 return nullptr;
2297 } else {
2298 return it->second;
2299 }
2300 }
2301
2302 return static_cast<soinfo*>(handle);
2303}
2304
Dimitry Ivanovd9e427c2016-11-22 16:55:25 -08002305bool do_dlsym(void* handle,
2306 const char* sym_name,
2307 const char* sym_ver,
2308 const void* caller_addr,
2309 void** symbol) {
Dimitry Ivanov6705e8c2017-03-21 10:29:06 -07002310 ScopedTrace trace("dlsym");
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002311#if !defined(__LP64__)
2312 if (handle == nullptr) {
2313 DL_ERR("dlsym failed: library handle is null");
2314 return false;
2315 }
2316#endif
2317
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002318 soinfo* found = nullptr;
2319 const ElfW(Sym)* sym = nullptr;
2320 soinfo* caller = find_containing_library(caller_addr);
Dimitry Ivanovaca299a2016-04-11 12:42:58 -07002321 android_namespace_t* ns = get_caller_namespace(caller);
Dimitry Ivanov4742abd2016-12-12 16:30:15 -08002322 soinfo* si = nullptr;
2323 if (handle != RTLD_DEFAULT && handle != RTLD_NEXT) {
2324 si = soinfo_from_handle(handle);
2325 }
2326
2327 LD_LOG(kLogDlsym,
2328 "dlsym(handle=%p(\"%s\"), sym_name=\"%s\", sym_ver=\"%s\", caller=\"%s\", caller_ns=%s@%p) ...",
2329 handle,
2330 si != nullptr ? si->get_realpath() : "n/a",
2331 sym_name,
2332 sym_ver,
2333 caller == nullptr ? "(null)" : caller->get_realpath(),
2334 ns == nullptr ? "(null)" : ns->get_name(),
2335 ns);
2336
Tom Cherryb8ab6182017-04-05 16:20:29 -07002337 auto failure_guard = android::base::make_scope_guard(
2338 [&]() { LD_LOG(kLogDlsym, "... dlsym failed: %s", linker_get_error_buffer()); });
Dimitry Ivanov4742abd2016-12-12 16:30:15 -08002339
2340 if (sym_name == nullptr) {
2341 DL_ERR("dlsym failed: symbol name is null");
2342 return false;
2343 }
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002344
2345 version_info vi_instance;
2346 version_info* vi = nullptr;
2347
2348 if (sym_ver != nullptr) {
Dimitry Ivanov9cf99cb2015-12-11 14:22:24 -08002349 vi_instance.name = sym_ver;
2350 vi_instance.elf_hash = calculate_elf_hash(sym_ver);
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002351 vi = &vi_instance;
2352 }
2353
2354 if (handle == RTLD_DEFAULT || handle == RTLD_NEXT) {
2355 sym = dlsym_linear_lookup(ns, sym_name, vi, &found, caller, handle);
2356 } else {
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -07002357 if (si == nullptr) {
2358 DL_ERR("dlsym failed: invalid handle: %p", handle);
2359 return false;
2360 }
2361 sym = dlsym_handle_lookup(si, &found, sym_name, vi);
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002362 }
2363
2364 if (sym != nullptr) {
2365 uint32_t bind = ELF_ST_BIND(sym->st_info);
Ryan Prichard3f05d3e2019-04-01 17:42:14 -07002366 uint32_t type = ELF_ST_TYPE(sym->st_info);
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002367
2368 if ((bind == STB_GLOBAL || bind == STB_WEAK) && sym->st_shndx != 0) {
Ryan Prichard3f05d3e2019-04-01 17:42:14 -07002369 if (type == STT_TLS) {
2370 // For a TLS symbol, dlsym returns the address of the current thread's
2371 // copy of the symbol. This function may allocate a DTV and/or storage
2372 // for the source TLS module. (Allocating a DTV isn't necessary if the
2373 // symbol is part of static TLS, but it's simpler to reuse
2374 // __tls_get_addr.)
2375 soinfo_tls* tls_module = found->get_tls();
2376 if (tls_module == nullptr) {
2377 DL_ERR("TLS symbol \"%s\" in solib \"%s\" with no TLS segment",
2378 sym_name, found->get_realpath());
2379 return false;
2380 }
2381 const TlsIndex ti { tls_module->module_id, sym->st_value };
2382 *symbol = TLS_GET_ADDR(&ti);
2383 } else {
2384 *symbol = reinterpret_cast<void*>(found->resolve_symbol_address(sym));
2385 }
Tom Cherryb8ab6182017-04-05 16:20:29 -07002386 failure_guard.Disable();
Dimitry Ivanov4742abd2016-12-12 16:30:15 -08002387 LD_LOG(kLogDlsym,
2388 "... dlsym successful: sym_name=\"%s\", sym_ver=\"%s\", found in=\"%s\", address=%p",
2389 sym_name, sym_ver, found->get_soname(), *symbol);
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002390 return true;
2391 }
2392
2393 DL_ERR("symbol \"%s\" found but not global", symbol_display_name(sym_name, sym_ver).c_str());
2394 return false;
2395 }
2396
2397 DL_ERR("undefined symbol: %s", symbol_display_name(sym_name, sym_ver).c_str());
2398 return false;
2399}
2400
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -07002401int do_dlclose(void* handle) {
Dimitry Ivanov6705e8c2017-03-21 10:29:06 -07002402 ScopedTrace trace("dlclose");
Dmitriy Ivanov279a22f2015-01-23 12:03:53 -08002403 ProtectedDataGuard guard;
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -07002404 soinfo* si = soinfo_from_handle(handle);
2405 if (si == nullptr) {
2406 DL_ERR("invalid handle: %p", handle);
2407 return -1;
2408 }
2409
dimitryc92ce712017-10-27 14:12:53 +02002410 LD_LOG(kLogDlopen,
2411 "dlclose(handle=%p, realpath=\"%s\"@%p) ...",
2412 handle,
2413 si->get_realpath(),
2414 si);
Dmitriy Ivanovb648a8a2014-05-19 15:06:58 -07002415 soinfo_unload(si);
dimitryc92ce712017-10-27 14:12:53 +02002416 LD_LOG(kLogDlopen,
2417 "dlclose(handle=%p) ... done",
2418 handle);
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -07002419 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002420}
2421
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -08002422bool init_anonymous_namespace(const char* shared_lib_sonames, const char* library_search_path) {
2423 if (g_anonymous_namespace_initialized) {
2424 DL_ERR("anonymous namespace has already been initialized.");
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002425 return false;
2426 }
2427
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002428 ProtectedDataGuard guard;
2429
Dmitriy Ivanov1ffec1c2015-11-23 11:26:35 -08002430 // create anonymous namespace
Dimitry Ivanov7331fe12015-12-14 14:11:17 -08002431 // When the caller is nullptr - create_namespace will take global group
2432 // from the anonymous namespace, which is fine because anonymous namespace
2433 // is still pointing to the default one.
Dmitriy Ivanov1ffec1c2015-11-23 11:26:35 -08002434 android_namespace_t* anon_ns =
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -08002435 create_namespace(nullptr,
2436 "(anonymous)",
2437 nullptr,
2438 library_search_path,
Dimitry Ivanovc9dced22017-03-27 15:42:17 -07002439 ANDROID_NAMESPACE_TYPE_ISOLATED,
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -08002440 nullptr,
2441 &g_default_namespace);
Dmitriy Ivanov1ffec1c2015-11-23 11:26:35 -08002442
2443 if (anon_ns == nullptr) {
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -08002444 return false;
2445 }
2446
2447 if (!link_namespaces(anon_ns, &g_default_namespace, shared_lib_sonames)) {
Dmitriy Ivanov1ffec1c2015-11-23 11:26:35 -08002448 return false;
2449 }
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08002450
Dmitriy Ivanov1ffec1c2015-11-23 11:26:35 -08002451 g_anonymous_namespace = anon_ns;
Dimitry Ivanov3e0821d2017-03-07 11:02:10 -08002452 g_anonymous_namespace_initialized = true;
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -08002453
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002454 return true;
2455}
2456
Dimitry Ivanovb943f302016-08-03 16:00:10 -07002457static void add_soinfos_to_namespace(const soinfo_list_t& soinfos, android_namespace_t* ns) {
2458 ns->add_soinfos(soinfos);
2459 for (auto si : soinfos) {
2460 si->add_secondary_namespace(ns);
2461 }
2462}
2463
Dimitry Ivanov7331fe12015-12-14 14:11:17 -08002464android_namespace_t* create_namespace(const void* caller_addr,
2465 const char* name,
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002466 const char* ld_library_path,
2467 const char* default_library_path,
Dimitry Ivanov7331fe12015-12-14 14:11:17 -08002468 uint64_t type,
Dimitry Ivanovfc2da532016-05-12 15:20:21 -07002469 const char* permitted_when_isolated_path,
2470 android_namespace_t* parent_namespace) {
Dimitry Ivanovfc2da532016-05-12 15:20:21 -07002471 if (parent_namespace == nullptr) {
Dimitry Ivanov52408632016-05-23 10:31:11 -07002472 // if parent_namespace is nullptr -> set it to the caller namespace
2473 soinfo* caller_soinfo = find_containing_library(caller_addr);
2474
2475 parent_namespace = caller_soinfo != nullptr ?
2476 caller_soinfo->get_primary_namespace() :
2477 g_anonymous_namespace;
Dimitry Ivanovfc2da532016-05-12 15:20:21 -07002478 }
2479
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002480 ProtectedDataGuard guard;
2481 std::vector<std::string> ld_library_paths;
2482 std::vector<std::string> default_library_paths;
Dimitry Ivanov284ae352015-12-08 10:47:13 -08002483 std::vector<std::string> permitted_paths;
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002484
2485 parse_path(ld_library_path, ":", &ld_library_paths);
2486 parse_path(default_library_path, ":", &default_library_paths);
Dimitry Ivanov284ae352015-12-08 10:47:13 -08002487 parse_path(permitted_when_isolated_path, ":", &permitted_paths);
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002488
2489 android_namespace_t* ns = new (g_namespace_allocator.alloc()) android_namespace_t();
2490 ns->set_name(name);
Dimitry Ivanov7331fe12015-12-14 14:11:17 -08002491 ns->set_isolated((type & ANDROID_NAMESPACE_TYPE_ISOLATED) != 0);
Jiyong Park37b91af2017-05-05 22:07:05 +09002492 ns->set_greylist_enabled((type & ANDROID_NAMESPACE_TYPE_GREYLIST_ENABLED) != 0);
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002493
Dimitry Ivanov7331fe12015-12-14 14:11:17 -08002494 if ((type & ANDROID_NAMESPACE_TYPE_SHARED) != 0) {
Dimitry Ivanovf1cb6692017-05-01 17:45:38 -07002495 // append parent namespace paths.
2496 std::copy(parent_namespace->get_ld_library_paths().begin(),
2497 parent_namespace->get_ld_library_paths().end(),
2498 back_inserter(ld_library_paths));
2499
2500 std::copy(parent_namespace->get_default_library_paths().begin(),
2501 parent_namespace->get_default_library_paths().end(),
2502 back_inserter(default_library_paths));
2503
2504 std::copy(parent_namespace->get_permitted_paths().begin(),
2505 parent_namespace->get_permitted_paths().end(),
2506 back_inserter(permitted_paths));
2507
Dimitry Ivanovfc2da532016-05-12 15:20:21 -07002508 // If shared - clone the parent namespace
Dimitry Ivanovb943f302016-08-03 16:00:10 -07002509 add_soinfos_to_namespace(parent_namespace->soinfo_list(), ns);
Dimitry Ivanovf1cb6692017-05-01 17:45:38 -07002510 // and copy parent namespace links
2511 for (auto& link : parent_namespace->linked_namespaces()) {
Logan Chien9ee45912018-01-18 12:05:09 +08002512 ns->add_linked_namespace(link.linked_namespace(), link.shared_lib_sonames(),
2513 link.allow_all_shared_libs());
Dimitry Ivanovf1cb6692017-05-01 17:45:38 -07002514 }
Dimitry Ivanov7331fe12015-12-14 14:11:17 -08002515 } else {
Dimitry Ivanovfc2da532016-05-12 15:20:21 -07002516 // If not shared - copy only the shared group
Jiyong Park02586a22017-05-20 01:01:24 +09002517 add_soinfos_to_namespace(parent_namespace->get_shared_group(), ns);
Dimitry Ivanov7331fe12015-12-14 14:11:17 -08002518 }
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002519
Dimitry Ivanovf1cb6692017-05-01 17:45:38 -07002520 ns->set_ld_library_paths(std::move(ld_library_paths));
2521 ns->set_default_library_paths(std::move(default_library_paths));
2522 ns->set_permitted_paths(std::move(permitted_paths));
2523
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002524 return ns;
2525}
2526
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -08002527bool link_namespaces(android_namespace_t* namespace_from,
2528 android_namespace_t* namespace_to,
2529 const char* shared_lib_sonames) {
2530 if (namespace_to == nullptr) {
2531 namespace_to = &g_default_namespace;
2532 }
2533
2534 if (namespace_from == nullptr) {
2535 DL_ERR("error linking namespaces: namespace_from is null.");
2536 return false;
2537 }
2538
2539 if (shared_lib_sonames == nullptr || shared_lib_sonames[0] == '\0') {
2540 DL_ERR("error linking namespaces \"%s\"->\"%s\": the list of shared libraries is empty.",
2541 namespace_from->get_name(), namespace_to->get_name());
2542 return false;
2543 }
2544
2545 auto sonames = android::base::Split(shared_lib_sonames, ":");
2546 std::unordered_set<std::string> sonames_set(sonames.begin(), sonames.end());
2547
2548 ProtectedDataGuard guard;
Logan Chien9ee45912018-01-18 12:05:09 +08002549 namespace_from->add_linked_namespace(namespace_to, sonames_set, false);
2550
2551 return true;
2552}
2553
2554bool link_namespaces_all_libs(android_namespace_t* namespace_from,
2555 android_namespace_t* namespace_to) {
2556 if (namespace_from == nullptr) {
2557 DL_ERR("error linking namespaces: namespace_from is null.");
2558 return false;
2559 }
2560
2561 if (namespace_to == nullptr) {
2562 DL_ERR("error linking namespaces: namespace_to is null.");
2563 return false;
2564 }
2565
2566 ProtectedDataGuard guard;
2567 namespace_from->add_linked_namespace(namespace_to, std::unordered_set<std::string>(), true);
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -08002568
2569 return true;
2570}
2571
Dimitry Ivanov48ec2882016-08-04 11:50:36 -07002572ElfW(Addr) call_ifunc_resolver(ElfW(Addr) resolver_addr) {
Dmitriy Ivanov9aea1642014-09-11 15:16:03 -07002573 typedef ElfW(Addr) (*ifunc_resolver_t)(void);
2574 ifunc_resolver_t ifunc_resolver = reinterpret_cast<ifunc_resolver_t>(resolver_addr);
2575 ElfW(Addr) ifunc_addr = ifunc_resolver();
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07002576 TRACE_TYPE(RELO, "Called ifunc_resolver@%p. The result is %p",
2577 ifunc_resolver, reinterpret_cast<void*>(ifunc_addr));
Brigid Smithc5a13ef2014-07-23 11:22:25 -07002578
Dmitriy Ivanov9aea1642014-09-11 15:16:03 -07002579 return ifunc_addr;
Brigid Smithc5a13ef2014-07-23 11:22:25 -07002580}
Brigid Smithc5a13ef2014-07-23 11:22:25 -07002581
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07002582const version_info* VersionTracker::get_version_info(ElfW(Versym) source_symver) const {
2583 if (source_symver < 2 ||
2584 source_symver >= version_infos.size() ||
2585 version_infos[source_symver].name == nullptr) {
2586 return nullptr;
2587 }
2588
2589 return &version_infos[source_symver];
2590}
2591
2592void VersionTracker::add_version_info(size_t source_index,
2593 ElfW(Word) elf_hash,
2594 const char* ver_name,
2595 const soinfo* target_si) {
2596 if (source_index >= version_infos.size()) {
2597 version_infos.resize(source_index+1);
2598 }
2599
2600 version_infos[source_index].elf_hash = elf_hash;
2601 version_infos[source_index].name = ver_name;
2602 version_infos[source_index].target_si = target_si;
2603}
2604
2605bool VersionTracker::init_verneed(const soinfo* si_from) {
2606 uintptr_t verneed_ptr = si_from->get_verneed_ptr();
2607
2608 if (verneed_ptr == 0) {
2609 return true;
2610 }
2611
2612 size_t verneed_cnt = si_from->get_verneed_cnt();
2613
2614 for (size_t i = 0, offset = 0; i<verneed_cnt; ++i) {
2615 const ElfW(Verneed)* verneed = reinterpret_cast<ElfW(Verneed)*>(verneed_ptr + offset);
2616 size_t vernaux_offset = offset + verneed->vn_aux;
2617 offset += verneed->vn_next;
2618
2619 if (verneed->vn_version != 1) {
2620 DL_ERR("unsupported verneed[%zd] vn_version: %d (expected 1)", i, verneed->vn_version);
2621 return false;
2622 }
2623
2624 const char* target_soname = si_from->get_string(verneed->vn_file);
2625 // find it in dependencies
2626 soinfo* target_si = si_from->get_children().find_if([&](const soinfo* si) {
Dmitriy Ivanov406d9962015-05-06 11:05:27 -07002627 return si->get_soname() != nullptr && strcmp(si->get_soname(), target_soname) == 0;
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07002628 });
2629
2630 if (target_si == nullptr) {
2631 DL_ERR("cannot find \"%s\" from verneed[%zd] in DT_NEEDED list for \"%s\"",
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07002632 target_soname, i, si_from->get_realpath());
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07002633 return false;
2634 }
2635
2636 for (size_t j = 0; j<verneed->vn_cnt; ++j) {
2637 const ElfW(Vernaux)* vernaux = reinterpret_cast<ElfW(Vernaux)*>(verneed_ptr + vernaux_offset);
2638 vernaux_offset += vernaux->vna_next;
2639
2640 const ElfW(Word) elf_hash = vernaux->vna_hash;
2641 const char* ver_name = si_from->get_string(vernaux->vna_name);
2642 ElfW(Half) source_index = vernaux->vna_other;
2643
2644 add_version_info(source_index, elf_hash, ver_name, target_si);
2645 }
2646 }
2647
2648 return true;
2649}
2650
Dimitry Ivanov48ec2882016-08-04 11:50:36 -07002651template <typename F>
2652static bool for_each_verdef(const soinfo* si, F functor) {
2653 if (!si->has_min_version(2)) {
2654 return true;
2655 }
2656
2657 uintptr_t verdef_ptr = si->get_verdef_ptr();
2658 if (verdef_ptr == 0) {
2659 return true;
2660 }
2661
2662 size_t offset = 0;
2663
2664 size_t verdef_cnt = si->get_verdef_cnt();
2665 for (size_t i = 0; i<verdef_cnt; ++i) {
2666 const ElfW(Verdef)* verdef = reinterpret_cast<ElfW(Verdef)*>(verdef_ptr + offset);
2667 size_t verdaux_offset = offset + verdef->vd_aux;
2668 offset += verdef->vd_next;
2669
2670 if (verdef->vd_version != 1) {
2671 DL_ERR("unsupported verdef[%zd] vd_version: %d (expected 1) library: %s",
2672 i, verdef->vd_version, si->get_realpath());
2673 return false;
2674 }
2675
2676 if ((verdef->vd_flags & VER_FLG_BASE) != 0) {
2677 // "this is the version of the file itself. It must not be used for
2678 // matching a symbol. It can be used to match references."
2679 //
2680 // http://www.akkadia.org/drepper/symbol-versioning
2681 continue;
2682 }
2683
2684 if (verdef->vd_cnt == 0) {
2685 DL_ERR("invalid verdef[%zd] vd_cnt == 0 (version without a name)", i);
2686 return false;
2687 }
2688
2689 const ElfW(Verdaux)* verdaux = reinterpret_cast<ElfW(Verdaux)*>(verdef_ptr + verdaux_offset);
2690
2691 if (functor(i, verdef, verdaux) == true) {
2692 break;
2693 }
2694 }
2695
2696 return true;
2697}
2698
Ryan Prichardbbc2cb42020-01-02 14:59:11 -08002699ElfW(Versym) find_verdef_version_index(const soinfo* si, const version_info* vi) {
Dimitry Ivanov48ec2882016-08-04 11:50:36 -07002700 if (vi == nullptr) {
Ryan Prichardbbc2cb42020-01-02 14:59:11 -08002701 return kVersymNotNeeded;
Dimitry Ivanov48ec2882016-08-04 11:50:36 -07002702 }
2703
Ryan Prichardbbc2cb42020-01-02 14:59:11 -08002704 ElfW(Versym) result = kVersymGlobal;
Dimitry Ivanov48ec2882016-08-04 11:50:36 -07002705
Ryan Prichardbbc2cb42020-01-02 14:59:11 -08002706 if (!for_each_verdef(si,
Dimitry Ivanov48ec2882016-08-04 11:50:36 -07002707 [&](size_t, const ElfW(Verdef)* verdef, const ElfW(Verdaux)* verdaux) {
2708 if (verdef->vd_hash == vi->elf_hash &&
2709 strcmp(vi->name, si->get_string(verdaux->vda_name)) == 0) {
Ryan Prichardbbc2cb42020-01-02 14:59:11 -08002710 result = verdef->vd_ndx;
Dimitry Ivanov48ec2882016-08-04 11:50:36 -07002711 return true;
2712 }
2713
2714 return false;
2715 }
Ryan Prichardbbc2cb42020-01-02 14:59:11 -08002716 )) {
2717 // verdef should have already been validated in prelink_image.
2718 async_safe_fatal("invalid verdef after prelinking: %s, %s",
2719 si->get_realpath(), linker_get_error_buffer());
2720 }
2721
2722 return result;
2723}
2724
2725// Validate the library's verdef section. On error, returns false and invokes DL_ERR.
2726bool validate_verdef_section(const soinfo* si) {
2727 return for_each_verdef(si,
2728 [&](size_t, const ElfW(Verdef)*, const ElfW(Verdaux)*) {
2729 return false;
2730 });
Dimitry Ivanov48ec2882016-08-04 11:50:36 -07002731}
2732
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07002733bool VersionTracker::init_verdef(const soinfo* si_from) {
2734 return for_each_verdef(si_from,
2735 [&](size_t, const ElfW(Verdef)* verdef, const ElfW(Verdaux)* verdaux) {
2736 add_version_info(verdef->vd_ndx, verdef->vd_hash,
2737 si_from->get_string(verdaux->vda_name), si_from);
2738 return false;
2739 }
2740 );
2741}
2742
2743bool VersionTracker::init(const soinfo* si_from) {
2744 if (!si_from->has_min_version(2)) {
2745 return true;
2746 }
2747
2748 return init_verneed(si_from) && init_verdef(si_from);
2749}
2750
Dimitry Ivanov48ec2882016-08-04 11:50:36 -07002751// TODO (dimitry): Methods below need to be moved out of soinfo
2752// and in more isolated file in order minimize dependencies on
2753// unnecessary object in the linker binary. Consider making them
2754// independent from soinfo (?).
Dmitriy Ivanov31b408d2015-04-30 16:11:48 -07002755bool soinfo::lookup_version_info(const VersionTracker& version_tracker, ElfW(Word) sym,
2756 const char* sym_name, const version_info** vi) {
2757 const ElfW(Versym)* sym_ver_ptr = get_versym(sym);
2758 ElfW(Versym) sym_ver = sym_ver_ptr == nullptr ? 0 : *sym_ver_ptr;
2759
2760 if (sym_ver != VER_NDX_LOCAL && sym_ver != VER_NDX_GLOBAL) {
2761 *vi = version_tracker.get_version_info(sym_ver);
2762
2763 if (*vi == nullptr) {
2764 DL_ERR("cannot find verneed/verdef for version index=%d "
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07002765 "referenced by symbol \"%s\" at \"%s\"", sym_ver, sym_name, get_realpath());
Dmitriy Ivanov31b408d2015-04-30 16:11:48 -07002766 return false;
2767 }
2768 } else {
2769 // there is no version info
2770 *vi = nullptr;
2771 }
2772
2773 return true;
2774}
2775
Rahul Chaudhryf16b6592018-01-25 15:34:15 -08002776void soinfo::apply_relr_reloc(ElfW(Addr) offset) {
2777 ElfW(Addr) address = offset + load_bias;
2778 *reinterpret_cast<ElfW(Addr)*>(address) += load_bias;
2779}
2780
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08002781// Process relocations in SHT_RELR section (experimental).
Rahul Chaudhryf16b6592018-01-25 15:34:15 -08002782// Details of the encoding are described in this post:
2783// https://groups.google.com/d/msg/generic-abi/bX460iggiKg/Pi9aSwwABgAJ
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08002784bool soinfo::relocate_relr() {
2785 ElfW(Relr)* begin = relr_;
2786 ElfW(Relr)* end = relr_ + relr_count_;
Rahul Chaudhryf16b6592018-01-25 15:34:15 -08002787 constexpr size_t wordsize = sizeof(ElfW(Addr));
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08002788
Rahul Chaudhryf16b6592018-01-25 15:34:15 -08002789 ElfW(Addr) base = 0;
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08002790 for (ElfW(Relr)* current = begin; current < end; ++current) {
Rahul Chaudhryf16b6592018-01-25 15:34:15 -08002791 ElfW(Relr) entry = *current;
2792 ElfW(Addr) offset;
2793
2794 if ((entry&1) == 0) {
2795 // Even entry: encodes the offset for next relocation.
2796 offset = static_cast<ElfW(Addr)>(entry);
2797 apply_relr_reloc(offset);
2798 // Set base offset for subsequent bitmap entries.
2799 base = offset + wordsize;
2800 continue;
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08002801 }
Rahul Chaudhryf16b6592018-01-25 15:34:15 -08002802
2803 // Odd entry: encodes bitmap for relocations starting at base.
2804 offset = base;
2805 while (entry != 0) {
2806 entry >>= 1;
2807 if ((entry&1) != 0) {
2808 apply_relr_reloc(offset);
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08002809 }
Rahul Chaudhryf16b6592018-01-25 15:34:15 -08002810 offset += wordsize;
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08002811 }
Rahul Chaudhryf16b6592018-01-25 15:34:15 -08002812
2813 // Advance base offset by 63 words for 64-bit platforms,
2814 // or 31 words for 32-bit platforms.
2815 base += (8*wordsize - 1) * wordsize;
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08002816 }
2817 return true;
2818}
2819
Dimitry Ivanov48ec2882016-08-04 11:50:36 -07002820// An empty list of soinfos
Dimitry Ivanovb943f302016-08-03 16:00:10 -07002821static soinfo_list_t g_empty_list;
Dmitriy Ivanovd59e5002014-05-09 09:10:14 -07002822
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002823bool soinfo::prelink_image() {
Ryan Prichardc5a6cef2019-12-10 12:39:05 -08002824 if (flags_ & FLAG_PRELINKED) return true;
Ningsheng Jiane93be992014-09-16 15:22:10 +08002825 /* Extract dynamic section */
2826 ElfW(Word) dynamic_flags = 0;
2827 phdr_table_get_dynamic_section(phdr, phnum, load_bias, &dynamic, &dynamic_flags);
Dmitriy Ivanov498eb182014-09-05 14:57:59 -07002828
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002829 /* We can't log anything until the linker is relocated */
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08002830 bool relocating_linker = (flags_ & FLAG_LINKER) != 0;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002831 if (!relocating_linker) {
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07002832 INFO("[ Linking \"%s\" ]", get_realpath());
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08002833 DEBUG("si->base = %p si->flags = 0x%08x", reinterpret_cast<void*>(base), flags_);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002834 }
2835
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002836 if (dynamic == nullptr) {
David 'Digit' Turnerb52e4382012-06-19 01:24:17 +02002837 if (!relocating_linker) {
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07002838 DL_ERR("missing PT_DYNAMIC in \"%s\"", get_realpath());
David 'Digit' Turnerb52e4382012-06-19 01:24:17 +02002839 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002840 return false;
2841 } else {
2842 if (!relocating_linker) {
2843 DEBUG("dynamic = %p", dynamic);
David 'Digit' Turner63f99f42012-06-19 00:08:39 +02002844 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002845 }
David 'Digit' Turner63f99f42012-06-19 00:08:39 +02002846
Elliott Hughes4eeb1f12013-10-25 17:38:02 -07002847#if defined(__arm__)
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002848 (void) phdr_table_get_arm_exidx(phdr, phnum, load_bias,
2849 &ARM_exidx, &ARM_exidx_count);
David 'Digit' Turner63f99f42012-06-19 00:08:39 +02002850#endif
2851
Ryan Pricharde5e69e02019-01-01 18:53:48 -08002852 TlsSegment tls_segment;
Ryan Prichard19883502019-01-16 23:13:38 -08002853 if (__bionic_get_tls_segment(phdr, phnum, load_bias, &tls_segment)) {
2854 if (!__bionic_check_tls_alignment(&tls_segment.alignment)) {
2855 if (!relocating_linker) {
2856 DL_ERR("TLS segment alignment in \"%s\" is not a power of 2: %zu",
2857 get_realpath(), tls_segment.alignment);
2858 }
2859 return false;
2860 }
Ryan Pricharde5e69e02019-01-01 18:53:48 -08002861 tls_ = std::make_unique<soinfo_tls>();
2862 tls_->segment = tls_segment;
2863 }
2864
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002865 // Extract useful information from dynamic section.
Dmitriy Ivanov618f1a32015-03-17 20:06:36 -07002866 // Note that: "Except for the DT_NULL element at the end of the array,
2867 // and the relative order of DT_NEEDED elements, entries may appear in any order."
2868 //
2869 // source: http://www.sco.com/developers/gabi/1998-04-29/ch5.dynamic.html
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002870 uint32_t needed_count = 0;
2871 for (ElfW(Dyn)* d = dynamic; d->d_tag != DT_NULL; ++d) {
2872 DEBUG("d = %p, d[0](tag) = %p d[1](val) = %p",
2873 d, reinterpret_cast<void*>(d->d_tag), reinterpret_cast<void*>(d->d_un.d_val));
2874 switch (d->d_tag) {
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07002875 case DT_SONAME:
Dmitriy Ivanov618f1a32015-03-17 20:06:36 -07002876 // this is parsed after we have strtab initialized (see below).
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07002877 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002878
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002879 case DT_HASH:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002880 nbucket_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[0];
2881 nchain_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[1];
2882 bucket_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr + 8);
2883 chain_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr + 8 + nbucket_ * 4);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002884 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002885
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -08002886 case DT_GNU_HASH:
Dmitriy Ivanov3597b802015-03-09 12:02:02 -07002887 gnu_nbucket_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[0];
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -08002888 // skip symndx
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002889 gnu_maskwords_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[2];
2890 gnu_shift2_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[3];
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -08002891
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002892 gnu_bloom_filter_ = reinterpret_cast<ElfW(Addr)*>(load_bias + d->d_un.d_ptr + 16);
Dmitriy Ivanov3597b802015-03-09 12:02:02 -07002893 gnu_bucket_ = reinterpret_cast<uint32_t*>(gnu_bloom_filter_ + gnu_maskwords_);
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -08002894 // amend chain for symndx = header[1]
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07002895 gnu_chain_ = gnu_bucket_ + gnu_nbucket_ -
2896 reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[1];
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -08002897
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002898 if (!powerof2(gnu_maskwords_)) {
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07002899 DL_ERR("invalid maskwords for gnu_hash = 0x%x, in \"%s\" expecting power to two",
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07002900 gnu_maskwords_, get_realpath());
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -08002901 return false;
2902 }
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002903 --gnu_maskwords_;
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -08002904
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08002905 flags_ |= FLAG_GNU_HASH;
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -08002906 break;
2907
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002908 case DT_STRTAB:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002909 strtab_ = reinterpret_cast<const char*>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002910 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002911
Dmitriy Ivanov6cdeb522014-09-29 19:14:45 -07002912 case DT_STRSZ:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002913 strtab_size_ = d->d_un.d_val;
Dmitriy Ivanov6cdeb522014-09-29 19:14:45 -07002914 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002915
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002916 case DT_SYMTAB:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002917 symtab_ = reinterpret_cast<ElfW(Sym)*>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002918 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002919
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07002920 case DT_SYMENT:
2921 if (d->d_un.d_val != sizeof(ElfW(Sym))) {
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07002922 DL_ERR("invalid DT_SYMENT: %zd in \"%s\"",
2923 static_cast<size_t>(d->d_un.d_val), get_realpath());
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07002924 return false;
2925 }
2926 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002927
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002928 case DT_PLTREL:
Dmitriy Ivanov513e29e2014-10-06 11:30:43 -07002929#if defined(USE_RELA)
2930 if (d->d_un.d_val != DT_RELA) {
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07002931 DL_ERR("unsupported DT_PLTREL in \"%s\"; expected DT_RELA", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002932 return false;
2933 }
Dmitriy Ivanov513e29e2014-10-06 11:30:43 -07002934#else
2935 if (d->d_un.d_val != DT_REL) {
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07002936 DL_ERR("unsupported DT_PLTREL in \"%s\"; expected DT_REL", get_realpath());
Dmitriy Ivanov513e29e2014-10-06 11:30:43 -07002937 return false;
2938 }
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07002939#endif
Dmitriy Ivanov513e29e2014-10-06 11:30:43 -07002940 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002941
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002942 case DT_JMPREL:
Elliott Hughes4eeb1f12013-10-25 17:38:02 -07002943#if defined(USE_RELA)
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002944 plt_rela_ = reinterpret_cast<ElfW(Rela)*>(load_bias + d->d_un.d_ptr);
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07002945#else
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002946 plt_rel_ = reinterpret_cast<ElfW(Rel)*>(load_bias + d->d_un.d_ptr);
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07002947#endif
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002948 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002949
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002950 case DT_PLTRELSZ:
Elliott Hughes4eeb1f12013-10-25 17:38:02 -07002951#if defined(USE_RELA)
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002952 plt_rela_count_ = d->d_un.d_val / sizeof(ElfW(Rela));
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07002953#else
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002954 plt_rel_count_ = d->d_un.d_val / sizeof(ElfW(Rel));
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07002955#endif
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002956 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002957
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002958 case DT_PLTGOT:
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07002959#if defined(__mips__)
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002960 // Used by mips and mips64.
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002961 plt_got_ = reinterpret_cast<ElfW(Addr)**>(load_bias + d->d_un.d_ptr);
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07002962#endif
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07002963 // Ignore for other platforms... (because RTLD_LAZY is not supported)
2964 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002965
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002966 case DT_DEBUG:
2967 // Set the DT_DEBUG entry to the address of _r_debug for GDB
2968 // if the dynamic table is writable
Chris Dearman99186652014-02-06 20:36:51 -08002969// FIXME: not working currently for N64
2970// The flags for the LOAD and DYNAMIC program headers do not agree.
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07002971// The LOAD section containing the dynamic table has been mapped as
Chris Dearman99186652014-02-06 20:36:51 -08002972// read-only, but the DYNAMIC header claims it is writable.
2973#if !(defined(__mips__) && defined(__LP64__))
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002974 if ((dynamic_flags & PF_W) != 0) {
2975 d->d_un.d_val = reinterpret_cast<uintptr_t>(&_r_debug);
2976 }
Chris Dearman99186652014-02-06 20:36:51 -08002977#endif
Dmitriy Ivanovc6292ea2015-02-13 16:29:50 -08002978 break;
Elliott Hughes4eeb1f12013-10-25 17:38:02 -07002979#if defined(USE_RELA)
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002980 case DT_RELA:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002981 rela_ = reinterpret_cast<ElfW(Rela)*>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002982 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002983
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002984 case DT_RELASZ:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002985 rela_count_ = d->d_un.d_val / sizeof(ElfW(Rela));
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002986 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07002987
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08002988 case DT_ANDROID_RELA:
2989 android_relocs_ = reinterpret_cast<uint8_t*>(load_bias + d->d_un.d_ptr);
2990 break;
2991
2992 case DT_ANDROID_RELASZ:
2993 android_relocs_size_ = d->d_un.d_val;
2994 break;
2995
2996 case DT_ANDROID_REL:
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07002997 DL_ERR("unsupported DT_ANDROID_REL in \"%s\"", get_realpath());
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08002998 return false;
2999
3000 case DT_ANDROID_RELSZ:
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003001 DL_ERR("unsupported DT_ANDROID_RELSZ in \"%s\"", get_realpath());
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08003002 return false;
3003
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07003004 case DT_RELAENT:
3005 if (d->d_un.d_val != sizeof(ElfW(Rela))) {
Dmitriy Ivanovf240aa82014-09-16 23:34:20 -07003006 DL_ERR("invalid DT_RELAENT: %zd", static_cast<size_t>(d->d_un.d_val));
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07003007 return false;
3008 }
3009 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003010
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08003011 // Ignored (see DT_RELCOUNT comments for details).
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07003012 case DT_RELACOUNT:
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07003013 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003014
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003015 case DT_REL:
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003016 DL_ERR("unsupported DT_REL in \"%s\"", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003017 return false;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003018
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003019 case DT_RELSZ:
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003020 DL_ERR("unsupported DT_RELSZ in \"%s\"", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003021 return false;
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08003022
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07003023#else
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003024 case DT_REL:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003025 rel_ = reinterpret_cast<ElfW(Rel)*>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003026 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003027
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003028 case DT_RELSZ:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003029 rel_count_ = d->d_un.d_val / sizeof(ElfW(Rel));
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003030 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003031
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07003032 case DT_RELENT:
3033 if (d->d_un.d_val != sizeof(ElfW(Rel))) {
Dmitriy Ivanovf240aa82014-09-16 23:34:20 -07003034 DL_ERR("invalid DT_RELENT: %zd", static_cast<size_t>(d->d_un.d_val));
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07003035 return false;
3036 }
3037 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003038
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08003039 case DT_ANDROID_REL:
3040 android_relocs_ = reinterpret_cast<uint8_t*>(load_bias + d->d_un.d_ptr);
3041 break;
3042
3043 case DT_ANDROID_RELSZ:
3044 android_relocs_size_ = d->d_un.d_val;
3045 break;
3046
3047 case DT_ANDROID_RELA:
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003048 DL_ERR("unsupported DT_ANDROID_RELA in \"%s\"", get_realpath());
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08003049 return false;
3050
3051 case DT_ANDROID_RELASZ:
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003052 DL_ERR("unsupported DT_ANDROID_RELASZ in \"%s\"", get_realpath());
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08003053 return false;
3054
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003055 // "Indicates that all RELATIVE relocations have been concatenated together,
3056 // and specifies the RELATIVE relocation count."
3057 //
3058 // TODO: Spec also mentions that this can be used to optimize relocation process;
3059 // Not currently used by bionic linker - ignored.
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07003060 case DT_RELCOUNT:
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07003061 break;
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08003062
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003063 case DT_RELA:
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003064 DL_ERR("unsupported DT_RELA in \"%s\"", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003065 return false;
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08003066
3067 case DT_RELASZ:
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003068 DL_ERR("unsupported DT_RELASZ in \"%s\"", get_realpath());
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08003069 return false;
3070
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07003071#endif
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08003072 case DT_RELR:
3073 relr_ = reinterpret_cast<ElfW(Relr)*>(load_bias + d->d_un.d_ptr);
3074 break;
3075
3076 case DT_RELRSZ:
3077 relr_count_ = d->d_un.d_val / sizeof(ElfW(Relr));
3078 break;
3079
3080 case DT_RELRENT:
3081 if (d->d_un.d_val != sizeof(ElfW(Relr))) {
3082 DL_ERR("invalid DT_RELRENT: %zd", static_cast<size_t>(d->d_un.d_val));
3083 return false;
3084 }
3085 break;
3086
3087 // Ignored (see DT_RELCOUNT comments for details).
3088 case DT_RELRCOUNT:
3089 break;
3090
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003091 case DT_INIT:
Dimitry Ivanov55437462016-07-20 15:33:07 -07003092 init_func_ = reinterpret_cast<linker_ctor_function_t>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003093 DEBUG("%s constructors (DT_INIT) found at %p", get_realpath(), init_func_);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003094 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003095
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003096 case DT_FINI:
Dimitry Ivanov55437462016-07-20 15:33:07 -07003097 fini_func_ = reinterpret_cast<linker_dtor_function_t>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003098 DEBUG("%s destructors (DT_FINI) found at %p", get_realpath(), fini_func_);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003099 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003100
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003101 case DT_INIT_ARRAY:
Dimitry Ivanov55437462016-07-20 15:33:07 -07003102 init_array_ = reinterpret_cast<linker_ctor_function_t*>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003103 DEBUG("%s constructors (DT_INIT_ARRAY) found at %p", get_realpath(), init_array_);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003104 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003105
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003106 case DT_INIT_ARRAYSZ:
Dmitriy Ivanov1649e7e2015-01-22 16:04:25 -08003107 init_array_count_ = static_cast<uint32_t>(d->d_un.d_val) / sizeof(ElfW(Addr));
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003108 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003109
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003110 case DT_FINI_ARRAY:
Dimitry Ivanov55437462016-07-20 15:33:07 -07003111 fini_array_ = reinterpret_cast<linker_dtor_function_t*>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003112 DEBUG("%s destructors (DT_FINI_ARRAY) found at %p", get_realpath(), fini_array_);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003113 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003114
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003115 case DT_FINI_ARRAYSZ:
Dmitriy Ivanov1649e7e2015-01-22 16:04:25 -08003116 fini_array_count_ = static_cast<uint32_t>(d->d_un.d_val) / sizeof(ElfW(Addr));
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003117 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003118
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003119 case DT_PREINIT_ARRAY:
Dimitry Ivanov55437462016-07-20 15:33:07 -07003120 preinit_array_ = reinterpret_cast<linker_ctor_function_t*>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003121 DEBUG("%s constructors (DT_PREINIT_ARRAY) found at %p", get_realpath(), preinit_array_);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003122 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003123
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003124 case DT_PREINIT_ARRAYSZ:
Dmitriy Ivanov1649e7e2015-01-22 16:04:25 -08003125 preinit_array_count_ = static_cast<uint32_t>(d->d_un.d_val) / sizeof(ElfW(Addr));
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003126 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003127
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003128 case DT_TEXTREL:
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003129#if defined(__LP64__)
Dimitry Ivanov816676e2016-10-19 11:00:28 -07003130 DL_ERR("\"%s\" has text relocations", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003131 return false;
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003132#else
3133 has_text_relocations = true;
3134 break;
3135#endif
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003136
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003137 case DT_SYMBOLIC:
Dmitriy Ivanov96bc37f2014-09-29 12:10:36 -07003138 has_DT_SYMBOLIC = true;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003139 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003140
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003141 case DT_NEEDED:
3142 ++needed_count;
3143 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003144
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003145 case DT_FLAGS:
3146 if (d->d_un.d_val & DF_TEXTREL) {
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003147#if defined(__LP64__)
Dimitry Ivanov816676e2016-10-19 11:00:28 -07003148 DL_ERR("\"%s\" has text relocations", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003149 return false;
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003150#else
3151 has_text_relocations = true;
3152#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08003153 }
Dmitriy Ivanov96bc37f2014-09-29 12:10:36 -07003154 if (d->d_un.d_val & DF_SYMBOLIC) {
3155 has_DT_SYMBOLIC = true;
3156 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003157 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003158
Dmitriy Ivanov6cdeb522014-09-29 19:14:45 -07003159 case DT_FLAGS_1:
Dmitriy Ivanovd225a5e2014-08-28 14:12:12 -07003160 set_dt_flags_1(d->d_un.d_val);
Dmitriy Ivanov1b20daf2014-05-19 15:06:58 -07003161
Dmitriy Ivanovd225a5e2014-08-28 14:12:12 -07003162 if ((d->d_un.d_val & ~SUPPORTED_DT_FLAGS_1) != 0) {
Elliott Hughes9076b0c2018-02-28 11:29:45 -08003163 DL_WARN("Warning: \"%s\" has unsupported flags DT_FLAGS_1=%p "
3164 "(ignoring unsupported flags)",
3165 get_realpath(), reinterpret_cast<void*>(d->d_un.d_val));
Dmitriy Ivanov6cdeb522014-09-29 19:14:45 -07003166 }
3167 break;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003168#if defined(__mips__)
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003169 case DT_MIPS_RLD_MAP:
3170 // Set the DT_MIPS_RLD_MAP entry to the address of _r_debug for GDB.
3171 {
3172 r_debug** dp = reinterpret_cast<r_debug**>(load_bias + d->d_un.d_ptr);
3173 *dp = &_r_debug;
3174 }
3175 break;
Lazar Trsic83b44a92016-04-06 13:39:17 +02003176 case DT_MIPS_RLD_MAP_REL:
3177 // Set the DT_MIPS_RLD_MAP_REL entry to the address of _r_debug for GDB.
Raghu Gandham68815722014-12-18 19:12:19 -08003178 {
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07003179 r_debug** dp = reinterpret_cast<r_debug**>(
3180 reinterpret_cast<ElfW(Addr)>(d) + d->d_un.d_val);
Raghu Gandham68815722014-12-18 19:12:19 -08003181 *dp = &_r_debug;
3182 }
3183 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003184
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003185 case DT_MIPS_RLD_VERSION:
3186 case DT_MIPS_FLAGS:
3187 case DT_MIPS_BASE_ADDRESS:
3188 case DT_MIPS_UNREFEXTNO:
3189 break;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08003190
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003191 case DT_MIPS_SYMTABNO:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003192 mips_symtabno_ = d->d_un.d_val;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003193 break;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08003194
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003195 case DT_MIPS_LOCAL_GOTNO:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003196 mips_local_gotno_ = d->d_un.d_val;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003197 break;
3198
3199 case DT_MIPS_GOTSYM:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003200 mips_gotsym_ = d->d_un.d_val;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003201 break;
3202#endif
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003203 // Ignored: "Its use has been superseded by the DF_BIND_NOW flag"
3204 case DT_BIND_NOW:
3205 break;
3206
Dmitriy Ivanov513e29e2014-10-06 11:30:43 -07003207 case DT_VERSYM:
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07003208 versym_ = reinterpret_cast<ElfW(Versym)*>(load_bias + d->d_un.d_ptr);
3209 break;
3210
Dmitriy Ivanov513e29e2014-10-06 11:30:43 -07003211 case DT_VERDEF:
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07003212 verdef_ptr_ = load_bias + d->d_un.d_ptr;
3213 break;
Dmitriy Ivanov513e29e2014-10-06 11:30:43 -07003214 case DT_VERDEFNUM:
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07003215 verdef_cnt_ = d->d_un.d_val;
3216 break;
3217
Alexander Ivchenkoe8314332014-12-02 15:32:25 +03003218 case DT_VERNEED:
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07003219 verneed_ptr_ = load_bias + d->d_un.d_ptr;
3220 break;
3221
Alexander Ivchenkoe8314332014-12-02 15:32:25 +03003222 case DT_VERNEEDNUM:
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07003223 verneed_cnt_ = d->d_un.d_val;
Dmitriy Ivanov513e29e2014-10-06 11:30:43 -07003224 break;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003225
Evgenii Stepanov68650822015-06-10 13:38:39 -07003226 case DT_RUNPATH:
3227 // this is parsed after we have strtab initialized (see below).
3228 break;
3229
Ryan Prichardea41ab02019-01-23 16:33:03 -08003230 case DT_TLSDESC_GOT:
3231 case DT_TLSDESC_PLT:
3232 // These DT entries are used for lazy TLSDESC relocations. Bionic
3233 // resolves everything eagerly, so these can be ignored.
3234 break;
3235
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003236 default:
Dmitriy Ivanov8f61d992014-09-16 14:31:06 -07003237 if (!relocating_linker) {
Elliott Hughes6eae4cc2017-08-30 09:02:33 -07003238 const char* tag_name;
3239 if (d->d_tag == DT_RPATH) {
3240 tag_name = "DT_RPATH";
3241 } else if (d->d_tag == DT_ENCODING) {
3242 tag_name = "DT_ENCODING";
3243 } else if (d->d_tag >= DT_LOOS && d->d_tag <= DT_HIOS) {
3244 tag_name = "unknown OS-specific";
3245 } else if (d->d_tag >= DT_LOPROC && d->d_tag <= DT_HIPROC) {
3246 tag_name = "unknown processor-specific";
3247 } else {
3248 tag_name = "unknown";
3249 }
Elliott Hughes9076b0c2018-02-28 11:29:45 -08003250 DL_WARN("Warning: \"%s\" unused DT entry: %s (type %p arg %p) (ignoring)",
Elliott Hughes6eae4cc2017-08-30 09:02:33 -07003251 get_realpath(),
3252 tag_name,
3253 reinterpret_cast<void*>(d->d_tag),
3254 reinterpret_cast<void*>(d->d_un.d_val));
Dmitriy Ivanov8f61d992014-09-16 14:31:06 -07003255 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003256 break;
Brian Carlstromd4ee82d2013-02-28 15:58:45 -08003257 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003258 }
3259
Duane Sandbc425c72015-06-01 16:29:14 -07003260#if defined(__mips__) && !defined(__LP64__)
3261 if (!mips_check_and_adjust_fp_modes()) {
3262 return false;
3263 }
3264#endif
3265
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003266 DEBUG("si->base = %p, si->strtab = %p, si->symtab = %p",
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003267 reinterpret_cast<void*>(base), strtab_, symtab_);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003268
3269 // Sanity checks.
3270 if (relocating_linker && needed_count != 0) {
3271 DL_ERR("linker cannot have DT_NEEDED dependencies on other libraries");
3272 return false;
3273 }
Dmitriy Ivanov3597b802015-03-09 12:02:02 -07003274 if (nbucket_ == 0 && gnu_nbucket_ == 0) {
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003275 DL_ERR("empty/missing DT_HASH/DT_GNU_HASH in \"%s\" "
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07003276 "(new hash type from the future?)", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003277 return false;
3278 }
Yi Kong32bc0fc2018-08-02 17:31:13 -07003279 if (strtab_ == nullptr) {
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07003280 DL_ERR("empty/missing DT_STRTAB in \"%s\"", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003281 return false;
3282 }
Yi Kong32bc0fc2018-08-02 17:31:13 -07003283 if (symtab_ == nullptr) {
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07003284 DL_ERR("empty/missing DT_SYMTAB in \"%s\"", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003285 return false;
3286 }
Dmitriy Ivanov75108f42015-06-02 13:28:06 -07003287
Dmitriy Ivanov624b8f12015-06-08 10:41:33 -07003288 // second pass - parse entries relying on strtab
3289 for (ElfW(Dyn)* d = dynamic; d->d_tag != DT_NULL; ++d) {
Evgenii Stepanov68650822015-06-10 13:38:39 -07003290 switch (d->d_tag) {
3291 case DT_SONAME:
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07003292 set_soname(get_string(d->d_un.d_val));
Evgenii Stepanov68650822015-06-10 13:38:39 -07003293 break;
3294 case DT_RUNPATH:
Evgenii Stepanov68650822015-06-10 13:38:39 -07003295 set_dt_runpath(get_string(d->d_un.d_val));
3296 break;
Dmitriy Ivanov624b8f12015-06-08 10:41:33 -07003297 }
3298 }
3299
Dmitriy Ivanov75108f42015-06-02 13:28:06 -07003300 // Before M release linker was using basename in place of soname.
Dmitriy Ivanov19133522015-06-02 17:36:54 -07003301 // In the case when dt_soname is absent some apps stop working
Dmitriy Ivanov75108f42015-06-02 13:28:06 -07003302 // because they can't find dt_needed library by soname.
Elliott Hughes9076b0c2018-02-28 11:29:45 -08003303 // This workaround should keep them working. (Applies only
3304 // for apps targeting sdk version < M.) Make an exception for
3305 // the main executable and linker; they do not need to have dt_soname.
3306 // TODO: >= O the linker doesn't need this workaround.
Dimitry Ivanov3f660572016-09-09 10:00:39 -07003307 if (soname_ == nullptr &&
3308 this != solist_get_somain() &&
3309 (flags_ & FLAG_LINKER) == 0 &&
Elliott Hughes5bc78c82016-11-16 11:35:43 -08003310 get_application_target_sdk_version() < __ANDROID_API_M__) {
Dmitriy Ivanov75108f42015-06-02 13:28:06 -07003311 soname_ = basename(realpath_.c_str());
Elliott Hughes9076b0c2018-02-28 11:29:45 -08003312 DL_WARN_documented_change(__ANDROID_API_M__,
3313 "missing-soname-enforced-for-api-level-23",
3314 "\"%s\" has no DT_SONAME (will use %s instead)",
3315 get_realpath(), soname_);
3316
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07003317 // 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 -07003318 }
Ryan Prichardc5a6cef2019-12-10 12:39:05 -08003319
Ryan Prichardbbc2cb42020-01-02 14:59:11 -08003320 // Validate each library's verdef section once, so we don't have to validate
3321 // it each time we look up a symbol with a version.
3322 if (!validate_verdef_section(this)) return false;
3323
Ryan Prichardc5a6cef2019-12-10 12:39:05 -08003324 flags_ |= FLAG_PRELINKED;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003325 return true;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07003326}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08003327
Ryan Prichardf56ac992020-01-02 16:36:06 -08003328bool soinfo::link_image(const SymbolLookupList& lookup_list, soinfo* local_group_root,
Torne (Richard Coles)efbe9a52018-10-17 15:59:38 -04003329 const android_dlextinfo* extinfo, size_t* relro_fd_offset) {
dimitry965d06d2017-11-28 16:03:07 +01003330 if (is_image_linked()) {
3331 // already linked.
3332 return true;
3333 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08003334
Ryan Prichardf56ac992020-01-02 16:36:06 -08003335 local_group_root_ = local_group_root;
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08003336 if (local_group_root_ == nullptr) {
3337 local_group_root_ = this;
3338 }
3339
Dmitriy Ivanov19133522015-06-02 17:36:54 -07003340 if ((flags_ & FLAG_LINKER) == 0 && local_group_root_ == this) {
3341 target_sdk_version_ = get_application_target_sdk_version();
3342 }
3343
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003344#if !defined(__LP64__)
3345 if (has_text_relocations) {
Elliott Hughes5bc78c82016-11-16 11:35:43 -08003346 // Fail if app is targeting M or above.
Elliott Hughes9076b0c2018-02-28 11:29:45 -08003347 int app_target_api_level = get_application_target_sdk_version();
3348 if (app_target_api_level >= __ANDROID_API_M__) {
Elliott Hughes763f6e12017-04-10 09:52:33 -07003349 DL_ERR_AND_LOG("\"%s\" has text relocations (https://android.googlesource.com/platform/"
3350 "bionic/+/master/android-changes-for-ndk-developers.md#Text-Relocations-"
3351 "Enforced-for-API-level-23)", get_realpath());
Dmitriy Ivanove4ad91f2015-06-12 15:00:31 -07003352 return false;
3353 }
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003354 // Make segments writable to allow text relocations to work properly. We will later call
Dmitriy Ivanov7e039932015-10-01 14:02:19 -07003355 // phdr_table_protect_segments() after all of them are applied.
Elliott Hughes9076b0c2018-02-28 11:29:45 -08003356 DL_WARN_documented_change(__ANDROID_API_M__,
3357 "Text-Relocations-Enforced-for-API-level-23",
3358 "\"%s\" has text relocations",
3359 get_realpath());
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07003360 add_dlwarning(get_realpath(), "text relocations");
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003361 if (phdr_table_unprotect_segments(phdr, phnum, load_bias) < 0) {
Elliott Hughes9076b0c2018-02-28 11:29:45 -08003362 DL_ERR("can't unprotect loadable segments for \"%s\": %s", get_realpath(), strerror(errno));
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003363 return false;
3364 }
3365 }
3366#endif
3367
Ryan Prichardf56ac992020-01-02 16:36:06 -08003368 if (!relocate(lookup_list)) {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003369 return false;
3370 }
Raghu Gandhamd7daacb2012-07-31 12:07:22 -07003371
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07003372 DEBUG("[ finished linking %s ]", get_realpath());
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08003373
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003374#if !defined(__LP64__)
3375 if (has_text_relocations) {
3376 // All relocations are done, we can protect our segments back to read-only.
3377 if (phdr_table_protect_segments(phdr, phnum, load_bias) < 0) {
3378 DL_ERR("can't protect segments for \"%s\": %s",
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07003379 get_realpath(), strerror(errno));
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003380 return false;
3381 }
3382 }
3383#endif
3384
Mingwei Shibe910522015-11-12 07:02:14 +00003385 // We can also turn on GNU RELRO protection if we're not linking the dynamic linker
3386 // itself --- it can't make system calls yet, and will have to call protect_relro later.
3387 if (!is_linker() && !protect_relro()) {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003388 return false;
3389 }
Nick Kralevich9ec0f032012-02-28 10:40:00 -08003390
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003391 /* Handle serializing/sharing the RELRO segment */
3392 if (extinfo && (extinfo->flags & ANDROID_DLEXT_WRITE_RELRO)) {
3393 if (phdr_table_serialize_gnu_relro(phdr, phnum, load_bias,
Torne (Richard Coles)fa9f7f22019-04-02 17:04:42 -04003394 extinfo->relro_fd, relro_fd_offset) < 0) {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003395 DL_ERR("failed serializing GNU RELRO section for \"%s\": %s",
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07003396 get_realpath(), strerror(errno));
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003397 return false;
Torne (Richard Coles)183ad9d2014-02-27 13:18:00 +00003398 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003399 } else if (extinfo && (extinfo->flags & ANDROID_DLEXT_USE_RELRO)) {
3400 if (phdr_table_map_gnu_relro(phdr, phnum, load_bias,
Torne (Richard Coles)efbe9a52018-10-17 15:59:38 -04003401 extinfo->relro_fd, relro_fd_offset) < 0) {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003402 DL_ERR("failed mapping GNU RELRO section for \"%s\": %s",
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07003403 get_realpath(), strerror(errno));
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003404 return false;
3405 }
3406 }
Torne (Richard Coles)183ad9d2014-02-27 13:18:00 +00003407
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003408 notify_gdb_of_load(this);
dimitry965d06d2017-11-28 16:03:07 +01003409 set_image_linked();
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003410 return true;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08003411}
3412
Mingwei Shibe910522015-11-12 07:02:14 +00003413bool soinfo::protect_relro() {
3414 if (phdr_table_protect_gnu_relro(phdr, phnum, load_bias) < 0) {
3415 DL_ERR("can't enable GNU RELRO protection for \"%s\": %s",
3416 get_realpath(), strerror(errno));
3417 return false;
3418 }
3419 return true;
3420}
3421
Jiyong Park02586a22017-05-20 01:01:24 +09003422static std::vector<android_namespace_t*> init_default_namespace_no_config(bool is_asan) {
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07003423 g_default_namespace.set_isolated(false);
Dimitry Ivanov77ad6422017-03-06 13:02:29 -08003424 auto default_ld_paths = is_asan ? kAsanDefaultLdPaths : kDefaultLdPaths;
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07003425
neo.chae2589f9d2016-10-04 11:00:27 +09003426 char real_path[PATH_MAX];
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07003427 std::vector<std::string> ld_default_paths;
Dimitry Ivanov77ad6422017-03-06 13:02:29 -08003428 for (size_t i = 0; default_ld_paths[i] != nullptr; ++i) {
3429 if (realpath(default_ld_paths[i], real_path) != nullptr) {
neo.chae2589f9d2016-10-04 11:00:27 +09003430 ld_default_paths.push_back(real_path);
3431 } else {
Dimitry Ivanov77ad6422017-03-06 13:02:29 -08003432 ld_default_paths.push_back(default_ld_paths[i]);
neo.chae2589f9d2016-10-04 11:00:27 +09003433 }
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07003434 }
3435
3436 g_default_namespace.set_default_library_paths(std::move(ld_default_paths));
Jiyong Park02586a22017-05-20 01:01:24 +09003437
3438 std::vector<android_namespace_t*> namespaces;
3439 namespaces.push_back(&g_default_namespace);
3440 return namespaces;
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08003441}
3442
Jiyong Park35833412018-10-26 14:45:21 +09003443// return /apex/<name>/etc/ld.config.txt from /apex/<name>/bin/<exec>
3444static std::string get_ld_config_file_apex_path(const char* executable_path) {
3445 std::vector<std::string> paths = android::base::Split(executable_path, "/");
3446 if (paths.size() == 5 && paths[1] == "apex" && paths[3] == "bin") {
3447 return std::string("/apex/") + paths[2] + "/etc/ld.config.txt";
3448 }
3449 return "";
3450}
3451
Logan Chien886b96e2018-05-08 17:52:18 +08003452static std::string get_ld_config_file_vndk_path() {
Logan Chienbcfe3cf2018-05-08 20:17:26 +08003453 if (android::base::GetBoolProperty("ro.vndk.lite", false)) {
3454 return kLdConfigVndkLiteFilePath;
3455 }
3456
Logan Chien886b96e2018-05-08 17:52:18 +08003457 std::string ld_config_file_vndk = kLdConfigFilePath;
3458 size_t insert_pos = ld_config_file_vndk.find_last_of('.');
3459 if (insert_pos == std::string::npos) {
3460 insert_pos = ld_config_file_vndk.length();
3461 }
3462 ld_config_file_vndk.insert(insert_pos, Config::get_vndk_version_string('.'));
3463 return ld_config_file_vndk;
3464}
3465
Jiyong Park35833412018-10-26 14:45:21 +09003466static std::string get_ld_config_file_path(const char* executable_path) {
Logan Chien886b96e2018-05-08 17:52:18 +08003467#ifdef USE_LD_CONFIG_FILE
3468 // This is a debugging/testing only feature. Must not be available on
3469 // production builds.
3470 const char* ld_config_file_env = getenv("LD_CONFIG_FILE");
3471 if (ld_config_file_env != nullptr && file_exists(ld_config_file_env)) {
3472 return ld_config_file_env;
3473 }
3474#endif
3475
Jiyong Park35833412018-10-26 14:45:21 +09003476 std::string path = get_ld_config_file_apex_path(executable_path);
3477 if (!path.empty()) {
3478 if (file_exists(path.c_str())) {
3479 return path;
3480 }
3481 DL_WARN("Warning: couldn't read config file \"%s\" for \"%s\"",
3482 path.c_str(), executable_path);
Logan Chien886b96e2018-05-08 17:52:18 +08003483 }
3484
Jiyong Park35833412018-10-26 14:45:21 +09003485 path = kLdConfigArchFilePath;
3486 if (file_exists(path.c_str())) {
3487 return path;
3488 }
3489
3490 path = get_ld_config_file_vndk_path();
3491 if (file_exists(path.c_str())) {
3492 return path;
Logan Chien886b96e2018-05-08 17:52:18 +08003493 }
3494
3495 return kLdConfigFilePath;
3496}
3497
Jiyong Park02586a22017-05-20 01:01:24 +09003498std::vector<android_namespace_t*> init_default_namespaces(const char* executable_path) {
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08003499 g_default_namespace.set_name("(default)");
3500
3501 soinfo* somain = solist_get_somain();
3502
3503 const char *interp = phdr_table_get_interpreter_name(somain->phdr, somain->phnum,
3504 somain->load_bias);
Dan Willemsen7ccc50d2017-09-18 21:28:14 -07003505 const char* bname = (interp != nullptr) ? basename(interp) : nullptr;
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08003506
3507 g_is_asan = bname != nullptr &&
3508 (strcmp(bname, "linker_asan") == 0 ||
3509 strcmp(bname, "linker_asan64") == 0);
3510
3511 const Config* config = nullptr;
3512
3513 std::string error_msg;
3514
Jiyong Park35833412018-10-26 14:45:21 +09003515 std::string ld_config_file_path = get_ld_config_file_path(executable_path);
Jiyong Park02586a22017-05-20 01:01:24 +09003516
Martin Stjernholm95252ee2019-02-22 22:48:59 +00003517 INFO("[ Reading linker config \"%s\" ]", ld_config_file_path.c_str());
Logan Chien886b96e2018-05-08 17:52:18 +08003518 if (!Config::read_binary_config(ld_config_file_path.c_str(),
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08003519 executable_path,
3520 g_is_asan,
3521 &config,
3522 &error_msg)) {
3523 if (!error_msg.empty()) {
Elliott Hughes9076b0c2018-02-28 11:29:45 -08003524 DL_WARN("Warning: couldn't read \"%s\" for \"%s\" (using default configuration instead): %s",
Logan Chien886b96e2018-05-08 17:52:18 +08003525 ld_config_file_path.c_str(),
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08003526 executable_path,
3527 error_msg.c_str());
3528 }
3529 config = nullptr;
3530 }
3531
3532 if (config == nullptr) {
Jiyong Park02586a22017-05-20 01:01:24 +09003533 return init_default_namespace_no_config(g_is_asan);
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08003534 }
3535
3536 const auto& namespace_configs = config->namespace_configs();
3537 std::unordered_map<std::string, android_namespace_t*> namespaces;
3538
3539 // 1. Initialize default namespace
3540 const NamespaceConfig* default_ns_config = config->default_namespace_config();
3541
3542 g_default_namespace.set_isolated(default_ns_config->isolated());
3543 g_default_namespace.set_default_library_paths(default_ns_config->search_paths());
3544 g_default_namespace.set_permitted_paths(default_ns_config->permitted_paths());
3545
3546 namespaces[default_ns_config->name()] = &g_default_namespace;
Justin Yun90de9f02017-07-07 16:21:53 +09003547 if (default_ns_config->visible()) {
3548 g_exported_namespaces[default_ns_config->name()] = &g_default_namespace;
3549 }
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08003550
3551 // 2. Initialize other namespaces
3552
3553 for (auto& ns_config : namespace_configs) {
3554 if (namespaces.find(ns_config->name()) != namespaces.end()) {
3555 continue;
3556 }
3557
3558 android_namespace_t* ns = new (g_namespace_allocator.alloc()) android_namespace_t();
3559 ns->set_name(ns_config->name());
3560 ns->set_isolated(ns_config->isolated());
3561 ns->set_default_library_paths(ns_config->search_paths());
3562 ns->set_permitted_paths(ns_config->permitted_paths());
Vic Yang2d020e42019-01-12 21:03:25 -08003563 ns->set_whitelisted_libs(ns_config->whitelisted_libs());
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08003564
3565 namespaces[ns_config->name()] = ns;
Jiyong Park01de74e2017-04-03 23:10:37 +09003566 if (ns_config->visible()) {
3567 g_exported_namespaces[ns_config->name()] = ns;
3568 }
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08003569 }
3570
3571 // 3. Establish links between namespaces
3572 for (auto& ns_config : namespace_configs) {
3573 auto it_from = namespaces.find(ns_config->name());
3574 CHECK(it_from != namespaces.end());
3575 android_namespace_t* namespace_from = it_from->second;
3576 for (const NamespaceLinkConfig& ns_link : ns_config->links()) {
3577 auto it_to = namespaces.find(ns_link.ns_name());
3578 CHECK(it_to != namespaces.end());
3579 android_namespace_t* namespace_to = it_to->second;
Logan Chien9ee45912018-01-18 12:05:09 +08003580 if (ns_link.allow_all_shared_libs()) {
3581 link_namespaces_all_libs(namespace_from, namespace_to);
3582 } else {
3583 link_namespaces(namespace_from, namespace_to, ns_link.shared_libs().c_str());
3584 }
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08003585 }
3586 }
3587 // we can no longer rely on the fact that libdl.so is part of default namespace
3588 // this is why we want to add ld-android.so to all namespaces from ld.config.txt
3589 soinfo* ld_android_so = solist_get_head();
dimitry8b142562018-05-09 15:22:38 +02003590
3591 // we also need vdso to be available for all namespaces (if present)
3592 soinfo* vdso = solist_get_vdso();
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08003593 for (auto it : namespaces) {
3594 it.second->add_soinfo(ld_android_so);
dimitry8b142562018-05-09 15:22:38 +02003595 if (vdso != nullptr) {
3596 it.second->add_soinfo(vdso);
3597 }
Jiyong Park02586a22017-05-20 01:01:24 +09003598 // somain and ld_preloads are added to these namespaces after LD_PRELOAD libs are linked
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08003599 }
3600
Danny Baumann7b6b6c92018-08-29 11:21:52 +02003601 uint32_t target_sdk = config->target_sdk_version();
3602#ifdef SDK_VERSION_OVERRIDES
3603 for (const auto& entry : android::base::Split(SDK_VERSION_OVERRIDES, " ")) {
3604 auto splitted = android::base::Split(entry, "=");
3605 if (splitted.size() == 2 && splitted[0] == executable_path) {
3606 target_sdk = static_cast<uint32_t>(std::stoul(splitted[1]));
3607 break;
3608 }
3609 }
3610 DEBUG("Target SDK for %s = %d", executable_path, target_sdk);
3611#endif
3612 set_application_target_sdk_version(target_sdk);
Jiyong Park02586a22017-05-20 01:01:24 +09003613
3614 std::vector<android_namespace_t*> created_namespaces;
3615 created_namespaces.reserve(namespaces.size());
Chih-Hung Hsieh0218e922018-12-11 10:22:11 -08003616 for (const auto& kv : namespaces) {
Jiyong Park02586a22017-05-20 01:01:24 +09003617 created_namespaces.push_back(kv.second);
3618 }
3619 return created_namespaces;
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08003620}
Jiyong Park01de74e2017-04-03 23:10:37 +09003621
3622// This function finds a namespace exported in ld.config.txt by its name.
3623// A namespace can be exported by setting .visible property to true.
3624android_namespace_t* get_exported_namespace(const char* name) {
3625 if (name == nullptr) {
3626 return nullptr;
3627 }
3628 auto it = g_exported_namespaces.find(std::string(name));
3629 if (it == g_exported_namespaces.end()) {
3630 return nullptr;
3631 }
3632 return it->second;
3633}
Vic Yangbb7e1232019-01-29 20:23:16 -08003634
3635void purge_unused_memory() {
3636 // For now, we only purge the memory used by LoadTask because we know those
3637 // are temporary objects.
3638 //
3639 // Purging other LinkerBlockAllocator hardly yields much because they hold
3640 // information about namespaces and opened libraries, which are not freed
3641 // when the control leaves the linker.
3642 //
3643 // Purging BionicAllocator may give us a few dirty pages back, but those pages
3644 // would be already zeroed out, so they compress easily in ZRAM. Therefore,
3645 // it is not worth munmap()'ing those pages.
3646 TypeBasedAllocator<LoadTask>::purge();
3647}