blob: ac7455babf0e4d737b377ee1b25d6fff03db4939 [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"
Dmitriy Ivanovcefef7d2015-01-08 23:30:15 -080066#include "linker_relocs.h"
Dmitriy Ivanovfa26eee2015-02-03 16:06:47 -080067#include "linker_reloc_iterators.h"
Ryan Pricharde5e69e02019-01-01 18:53:48 -080068#include "linker_tls.h"
Dmitriy Ivanova1feb112015-10-01 18:41:57 -070069#include "linker_utils.h"
tony.ys_liub4474402015-07-29 18:00:22 +080070
Ryan Pricharde5e69e02019-01-01 18:53:48 -080071#include "private/bionic_globals.h"
dimitryfe1b27c2017-08-11 14:43:21 +020072#include "android-base/macros.h"
Elliott Hughes939a7e02015-12-04 15:27:46 -080073#include "android-base/strings.h"
Dimitry Ivanovb996d602016-07-11 18:11:39 -070074#include "android-base/stringprintf.h"
Simon Baldwinaef71952015-01-16 13:22:54 +000075#include "ziparchive/zip_archive.h"
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080076
dimitry06016f22018-01-05 11:39:28 +010077static std::unordered_map<void*, size_t> g_dso_handle_counters;
78
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -070079static android_namespace_t* g_anonymous_namespace = &g_default_namespace;
Jiyong Park01de74e2017-04-03 23:10:37 +090080static std::unordered_map<std::string, android_namespace_t*> g_exported_namespaces;
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -070081
Dmitriy Ivanov600bc3c2015-03-10 15:43:50 -070082static LinkerTypeAllocator<soinfo> g_soinfo_allocator;
83static LinkerTypeAllocator<LinkedListEntry<soinfo>> g_soinfo_links_allocator;
Magnus Malmbornba98d922012-09-12 13:00:55 +020084
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -070085static LinkerTypeAllocator<android_namespace_t> g_namespace_allocator;
Dimitry Ivanovaca299a2016-04-11 12:42:58 -070086static LinkerTypeAllocator<LinkedListEntry<android_namespace_t>> g_namespace_list_allocator;
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -070087
dimitryfe1b27c2017-08-11 14:43:21 +020088static const char* const kLdConfigArchFilePath = "/system/etc/ld.config." ABI_STRING ".txt";
89
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -080090static const char* const kLdConfigFilePath = "/system/etc/ld.config.txt";
Logan Chienbcfe3cf2018-05-08 20:17:26 +080091static const char* const kLdConfigVndkLiteFilePath = "/system/etc/ld.config.vndk_lite.txt";
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -080092
Elliott Hughes4eeb1f12013-10-25 17:38:02 -070093#if defined(__LP64__)
Victor Chang6cb719f2019-02-06 17:19:10 +000094static const char* const kSystemLibDir = "/system/lib64";
95static const char* const kOdmLibDir = "/odm/lib64";
96static const char* const kVendorLibDir = "/vendor/lib64";
97static const char* const kAsanSystemLibDir = "/data/asan/system/lib64";
98static const char* const kAsanOdmLibDir = "/data/asan/odm/lib64";
99static const char* const kAsanVendorLibDir = "/data/asan/vendor/lib64";
100static const char* const kRuntimeApexLibDir = "/apex/com.android.runtime/lib64";
Elliott Hughes011bc0b2013-10-08 14:27:10 -0700101#else
Victor Chang6cb719f2019-02-06 17:19:10 +0000102static const char* const kSystemLibDir = "/system/lib";
103static const char* const kOdmLibDir = "/odm/lib";
104static const char* const kVendorLibDir = "/vendor/lib";
105static const char* const kAsanSystemLibDir = "/data/asan/system/lib";
106static const char* const kAsanOdmLibDir = "/data/asan/odm/lib";
107static const char* const kAsanVendorLibDir = "/data/asan/vendor/lib";
108static const char* const kRuntimeApexLibDir = "/apex/com.android.runtime/lib";
Elliott Hughes011bc0b2013-10-08 14:27:10 -0700109#endif
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700110
Vishwath Mohan4113def2017-03-29 15:31:34 -0700111static const char* const kAsanLibDirPrefix = "/data/asan";
112
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700113static const char* const kDefaultLdPaths[] = {
114 kSystemLibDir,
Alin Jerpelea074a9fd2017-09-25 17:47:49 +0200115 kOdmLibDir,
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700116 kVendorLibDir,
Dmitriy Ivanov851135b2014-08-29 12:02:36 -0700117 nullptr
Elliott Hughes124fae92012-10-31 14:20:03 -0700118};
David Bartleybc3a5c22009-06-02 18:27:28 -0700119
Evgenii Stepanovd640b222015-07-10 17:54:01 -0700120static const char* const kAsanDefaultLdPaths[] = {
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700121 kAsanSystemLibDir,
122 kSystemLibDir,
Alin Jerpelea074a9fd2017-09-25 17:47:49 +0200123 kAsanOdmLibDir,
124 kOdmLibDir,
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700125 kAsanVendorLibDir,
126 kVendorLibDir,
Evgenii Stepanovd640b222015-07-10 17:54:01 -0700127 nullptr
128};
129
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700130// Is ASAN enabled?
131static bool g_is_asan = false;
132
Evgenii Stepanov0a3637d2016-07-06 13:20:59 -0700133static CFIShadowWriter g_cfi_shadow;
134
135CFIShadowWriter* get_cfi_shadow() {
136 return &g_cfi_shadow;
137}
138
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700139static bool is_system_library(const std::string& realpath) {
140 for (const auto& dir : g_default_namespace.get_default_library_paths()) {
141 if (file_is_in_dir(realpath, dir)) {
142 return true;
143 }
144 }
145 return false;
146}
147
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700148// Checks if the file exists and not a directory.
149static bool file_exists(const char* path) {
Dimitry Ivanov4cf70242016-08-11 11:11:52 -0700150 struct stat s;
151
152 if (stat(path, &s) != 0) {
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700153 return false;
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700154 }
Dimitry Ivanov4cf70242016-08-11 11:11:52 -0700155
156 return S_ISREG(s.st_mode);
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700157}
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700158
Dimitry Ivanov35c8e3b2017-02-27 12:17:47 -0800159static std::string resolve_soname(const std::string& name) {
160 // We assume that soname equals to basename here
161
162 // TODO(dimitry): consider having honest absolute-path -> soname resolution
163 // note that since we might end up refusing to load this library because
164 // it is not in shared libs list we need to get the soname without actually loading
165 // the library.
166 //
167 // On the other hand there are several places where we already assume that
168 // soname == basename in particular for any not-loaded library mentioned
169 // in DT_NEEDED list.
170 return basename(name.c_str());
171}
172
173static bool maybe_accessible_via_namespace_links(android_namespace_t* ns, const char* name) {
174 std::string soname = resolve_soname(name);
175 for (auto& ns_link : ns->linked_namespaces()) {
176 if (ns_link.is_accessible(soname.c_str())) {
177 return true;
178 }
179 }
180
181 return false;
182}
183
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700184// TODO(dimitry): The grey-list is a workaround for http://b/26394120 ---
185// gradually remove libraries from this list until it is gone.
Dimitry Ivanov35c8e3b2017-02-27 12:17:47 -0800186static bool is_greylisted(android_namespace_t* ns, const char* name, const soinfo* needed_by) {
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700187 static const char* const kLibraryGreyList[] = {
188 "libandroid_runtime.so",
189 "libbinder.so",
190 "libcrypto.so",
191 "libcutils.so",
192 "libexpat.so",
193 "libgui.so",
194 "libmedia.so",
195 "libnativehelper.so",
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700196 "libssl.so",
197 "libstagefright.so",
198 "libsqlite.so",
199 "libui.so",
200 "libutils.so",
201 "libvorbisidec.so",
202 nullptr
203 };
204
Elliott Hughes5bc78c82016-11-16 11:35:43 -0800205 // If you're targeting N, you don't get the greylist.
Elliott Hughes9e27e582017-03-23 17:42:49 -0700206 if (g_greylist_disabled || get_application_target_sdk_version() >= __ANDROID_API_N__) {
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700207 return false;
208 }
209
210 // if the library needed by a system library - implicitly assume it
Dimitry Ivanov35c8e3b2017-02-27 12:17:47 -0800211 // is greylisted unless it is in the list of shared libraries for one or
212 // more linked namespaces
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700213 if (needed_by != nullptr && is_system_library(needed_by->get_realpath())) {
Dimitry Ivanov35c8e3b2017-02-27 12:17:47 -0800214 return !maybe_accessible_via_namespace_links(ns, name);
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700215 }
216
217 // if this is an absolute path - make sure it points to /system/lib(64)
218 if (name[0] == '/' && dirname(name) == kSystemLibDir) {
219 // and reduce the path to basename
220 name = basename(name);
221 }
222
223 for (size_t i = 0; kLibraryGreyList[i] != nullptr; ++i) {
224 if (strcmp(name, kLibraryGreyList[i]) == 0) {
225 return true;
226 }
227 }
228
229 return false;
230}
231// END OF WORKAROUND
232
Victor Chang6cb719f2019-02-06 17:19:10 +0000233// Workaround for dlopen(/system/lib(64)/<soname>) when .so is in /apex. http://b/121248172
234/**
235 * Translate /system path to /apex path if needed
236 * The workaround should work only when targetSdkVersion < Q.
237 *
238 * param out_name_to_apex pointing to /apex path
239 * return true if translation is needed
240 */
241static bool translateSystemPathToApexPath(const char* name, std::string* out_name_to_apex) {
242 static const char* const kSystemToRuntimeApexLibs[] = {
243 "libicuuc.so",
244 "libicui18n.so",
245 };
246 // New mapping for new apex should be added below
247
248 // Nothing to do if target sdk version is Q or above
249 if (get_application_target_sdk_version() >= __ANDROID_API_Q__) {
250 return false;
251 }
252
253 // If the path isn't /system/lib, there's nothing to do.
254 if (name == nullptr || dirname(name) != kSystemLibDir) {
255 return false;
256 }
257
258 const char* base_name = basename(name);
259
260 for (const char* soname : kSystemToRuntimeApexLibs) {
261 if (strcmp(base_name, soname) == 0) {
262 *out_name_to_apex = std::string(kRuntimeApexLibDir) + "/" + base_name;
263 return true;
264 }
265 }
266
267 return false;
268}
269// End Workaround for dlopen(/system/lib/<soname>) when .so is in /apex.
270
Dmitriy Ivanovd165f562015-03-23 18:43:02 -0700271static std::vector<std::string> g_ld_preload_names;
Elliott Hughesa4aafd12014-01-13 16:37:47 -0800272
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800273static bool g_anonymous_namespace_initialized;
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -0700274
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800275#if STATS
Elliott Hughesbedfe382012-08-14 14:07:59 -0700276struct linker_stats_t {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700277 int count[kRelocMax];
Elliott Hughesbedfe382012-08-14 14:07:59 -0700278};
279
280static linker_stats_t linker_stats;
281
Dmitriy Ivanov114ff692015-01-14 11:36:38 -0800282void count_relocation(RelocationKind kind) {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700283 ++linker_stats.count[kind];
Elliott Hughesbedfe382012-08-14 14:07:59 -0700284}
Vic Yang542db792019-07-25 10:39:27 -0700285
286void print_linker_stats() {
287 PRINT("RELO STATS: %s: %d abs, %d rel, %d copy, %d symbol", g_argv[0],
288 linker_stats.count[kRelocAbsolute],
289 linker_stats.count[kRelocRelative],
290 linker_stats.count[kRelocCopy],
291 linker_stats.count[kRelocSymbol]);
292}
Elliott Hughesbedfe382012-08-14 14:07:59 -0700293#else
Dmitriy Ivanov114ff692015-01-14 11:36:38 -0800294void count_relocation(RelocationKind) {
Elliott Hughesbedfe382012-08-14 14:07:59 -0700295}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800296#endif
297
298#if COUNT_PAGES
Dmitriy Ivanov114ff692015-01-14 11:36:38 -0800299uint32_t bitmask[4096];
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800300#endif
301
Elliott Hughesbedfe382012-08-14 14:07:59 -0700302static void notify_gdb_of_load(soinfo* info) {
Dimitry Ivanove97d8ed2016-03-01 15:55:56 -0800303 if (info->is_linker() || info->is_main_executable()) {
304 // gdb already knows about the linker and the main executable.
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700305 return;
306 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800307
Dimitry Ivanov6b788ee2016-02-17 16:08:03 -0800308 link_map* map = &(info->link_map_head);
Nicolas Geoffray0fa54102016-02-18 09:31:24 +0000309
Dimitry Ivanov6b788ee2016-02-17 16:08:03 -0800310 map->l_addr = info->load_bias;
311 // link_map l_name field is not const.
312 map->l_name = const_cast<char*>(info->get_realpath());
313 map->l_ld = info->dynamic;
Nicolas Geoffray0fa54102016-02-18 09:31:24 +0000314
Dimitry Ivanove97d8ed2016-03-01 15:55:56 -0800315 CHECK(map->l_name != nullptr);
316 CHECK(map->l_name[0] != '\0');
317
Dimitry Ivanov6b788ee2016-02-17 16:08:03 -0800318 notify_gdb_of_load(map);
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -0700319}
320
Elliott Hughesbedfe382012-08-14 14:07:59 -0700321static void notify_gdb_of_unload(soinfo* info) {
Dimitry Ivanov6b788ee2016-02-17 16:08:03 -0800322 notify_gdb_of_unload(&(info->link_map_head));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800323}
324
Dmitriy Ivanovd59e5002014-05-09 09:10:14 -0700325LinkedListEntry<soinfo>* SoinfoListAllocator::alloc() {
326 return g_soinfo_links_allocator.alloc();
327}
328
329void SoinfoListAllocator::free(LinkedListEntry<soinfo>* entry) {
330 g_soinfo_links_allocator.free(entry);
331}
332
Dimitry Ivanovaca299a2016-04-11 12:42:58 -0700333LinkedListEntry<android_namespace_t>* NamespaceListAllocator::alloc() {
334 return g_namespace_list_allocator.alloc();
335}
336
337void NamespaceListAllocator::free(LinkedListEntry<android_namespace_t>* entry) {
338 g_namespace_list_allocator.free(entry);
339}
340
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700341soinfo* soinfo_alloc(android_namespace_t* ns, const char* name,
Ryan Prichard8f639a42018-10-01 23:10:05 -0700342 const struct stat* file_stat, off64_t file_offset,
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700343 uint32_t rtld_flags) {
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -0700344 if (strlen(name) >= PATH_MAX) {
Elliott Hughes7b0af7a2017-09-15 16:09:22 -0700345 async_safe_fatal("library name \"%s\" too long", name);
Magnus Malmbornba98d922012-09-12 13:00:55 +0200346 }
347
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700348 TRACE("name %s: allocating soinfo for ns=%p", name, ns);
349
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -0700350 soinfo* si = new (g_soinfo_allocator.alloc()) soinfo(ns, name, file_stat,
351 file_offset, rtld_flags);
Dmitriy Ivanovd59e5002014-05-09 09:10:14 -0700352
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700353 solist_add_soinfo(si);
Magnus Malmbornba98d922012-09-12 13:00:55 +0200354
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -0700355 si->generate_handle();
356 ns->add_soinfo(si);
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -0700357
Elliott Hughesca0c11b2013-03-12 10:40:45 -0700358 TRACE("name %s: allocated soinfo @ %p", name, si);
Magnus Malmbornba98d922012-09-12 13:00:55 +0200359 return si;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800360}
361
Elliott Hughesfaf05ba2014-02-11 16:59:37 -0800362static void soinfo_free(soinfo* si) {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700363 if (si == nullptr) {
364 return;
365 }
366
367 if (si->base != 0 && si->size != 0) {
Dimitry Ivanovf45b0e92016-01-15 11:13:35 -0800368 if (!si->is_mapped_by_caller()) {
369 munmap(reinterpret_cast<void*>(si->base), si->size);
370 } else {
371 // remap the region as PROT_NONE, MAP_ANONYMOUS | MAP_NORESERVE
372 mmap(reinterpret_cast<void*>(si->base), si->size, PROT_NONE,
373 MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
374 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700375 }
376
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -0700377 TRACE("name %s: freeing soinfo @ %p", si->get_realpath(), si);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700378
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700379 if (!solist_remove_soinfo(si)) {
dimitry965d06d2017-11-28 16:03:07 +0100380 async_safe_fatal("soinfo=%p is not in soinfo_list (double unload?)", si);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700381 }
Elliott Hughes46882792012-08-03 16:49:39 -0700382
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700383 // clear links to/from si
384 si->remove_all_links();
Dmitriy Ivanovd59e5002014-05-09 09:10:14 -0700385
Dmitriy Ivanov609f11b2015-07-08 15:26:46 -0700386 si->~soinfo();
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700387 g_soinfo_allocator.free(si);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800388}
389
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -0700390static void parse_path(const char* path, const char* delimiters,
391 std::vector<std::string>* resolved_paths) {
392 std::vector<std::string> paths;
393 split_path(path, delimiters, &paths);
394 resolve_paths(paths, resolved_paths);
395}
396
Elliott Hughescade4c32012-12-20 14:42:14 -0800397static void parse_LD_LIBRARY_PATH(const char* path) {
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -0700398 std::vector<std::string> ld_libary_paths;
399 parse_path(path, ":", &ld_libary_paths);
400 g_default_namespace.set_ld_library_paths(std::move(ld_libary_paths));
Elliott Hughescade4c32012-12-20 14:42:14 -0800401}
402
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -0700403static bool realpath_fd(int fd, std::string* realpath) {
Vic Yangd8bef672019-05-15 21:10:22 -0700404 // proc_self_fd needs to be large enough to hold "/proc/self/fd/" plus an
405 // integer, plus the NULL terminator.
406 char proc_self_fd[32];
407 // We want to statically allocate this large buffer so that we don't grow
408 // the stack by too much.
409 static char buf[PATH_MAX];
410
411 async_safe_format_buffer(proc_self_fd, sizeof(proc_self_fd), "/proc/self/fd/%d", fd);
412 auto length = readlink(proc_self_fd, buf, sizeof(buf));
413 if (length == -1) {
Tom Cherry66bc4282018-11-08 13:40:52 -0800414 if (!is_first_stage_init()) {
Vic Yangd8bef672019-05-15 21:10:22 -0700415 PRINT("readlink(\"%s\") failed: %s [fd=%d]", proc_self_fd, strerror(errno), fd);
Tom Cherry66bc4282018-11-08 13:40:52 -0800416 }
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -0700417 return false;
418 }
419
Vic Yangd8bef672019-05-15 21:10:22 -0700420 realpath->assign(buf, length);
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -0700421 return true;
422}
423
Elliott Hughes4eeb1f12013-10-25 17:38:02 -0700424#if defined(__arm__)
Elliott Hughes46882792012-08-03 16:49:39 -0700425
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700426// For a given PC, find the .so that it belongs to.
427// Returns the base address of the .ARM.exidx section
428// for that .so, and the number of 8-byte entries
429// in that section (via *pcount).
430//
431// Intended to be called by libc's __gnu_Unwind_Find_exidx().
Dimitry Ivanovd9e427c2016-11-22 16:55:25 -0800432_Unwind_Ptr do_dl_unwind_find_exidx(_Unwind_Ptr pc, int* pcount) {
Peter Collingbourneb39cb3c2019-03-01 13:12:49 -0800433 if (soinfo* si = find_containing_library(reinterpret_cast<void*>(pc))) {
434 *pcount = si->ARM_exidx_count;
435 return reinterpret_cast<_Unwind_Ptr>(si->ARM_exidx);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700436 }
437 *pcount = 0;
Elliott Hughesf2c6ad62017-04-21 10:25:56 -0700438 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800439}
Elliott Hughes46882792012-08-03 16:49:39 -0700440
Christopher Ferris24053a42013-08-19 17:45:09 -0700441#endif
Elliott Hughes46882792012-08-03 16:49:39 -0700442
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700443// Here, we only have to provide a callback to iterate across all the
444// loaded libraries. gcc_eh does the rest.
Dmitriy Ivanov7271caf2015-06-29 14:48:25 -0700445int do_dl_iterate_phdr(int (*cb)(dl_phdr_info* info, size_t size, void* data), void* data) {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700446 int rv = 0;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700447 for (soinfo* si = solist_get_head(); si != nullptr; si = si->next) {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700448 dl_phdr_info dl_info;
449 dl_info.dlpi_addr = si->link_map_head.l_addr;
450 dl_info.dlpi_name = si->link_map_head.l_name;
451 dl_info.dlpi_phdr = si->phdr;
452 dl_info.dlpi_phnum = si->phnum;
453 rv = cb(&dl_info, sizeof(dl_phdr_info), data);
454 if (rv != 0) {
455 break;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800456 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700457 }
458 return rv;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800459}
Elliott Hughes46882792012-08-03 16:49:39 -0700460
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800461
Dmitriy Ivanov2a815362015-04-09 13:42:33 -0700462bool soinfo_do_lookup(soinfo* si_from, const char* name, const version_info* vi,
Dimitry Ivanovb943f302016-08-03 16:00:10 -0700463 soinfo** si_found_in, const soinfo_list_t& global_group,
464 const soinfo_list_t& local_group, const ElfW(Sym)** symbol) {
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -0800465 SymbolName symbol_name(name);
Dmitriy Ivanov2a815362015-04-09 13:42:33 -0700466 const ElfW(Sym)* s = nullptr;
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700467
Dmitriy Ivanov96bc37f2014-09-29 12:10:36 -0700468 /* "This element's presence in a shared object library alters the dynamic linker's
469 * symbol resolution algorithm for references within the library. Instead of starting
470 * a symbol search with the executable file, the dynamic linker starts from the shared
471 * object itself. If the shared object fails to supply the referenced symbol, the
472 * dynamic linker then searches the executable file and other shared objects as usual."
473 *
474 * http://www.sco.com/developers/gabi/2012-12-31/ch5.dynamic.html
475 *
476 * Note that this is unlikely since static linker avoids generating
477 * relocations for -Bsymbolic linked dynamic executables.
478 */
Dmitriy Ivanovd225a5e2014-08-28 14:12:12 -0700479 if (si_from->has_DT_SYMBOLIC) {
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -0700480 DEBUG("%s: looking up %s in local scope (DT_SYMBOLIC)", si_from->get_realpath(), name);
Dmitriy Ivanov2a815362015-04-09 13:42:33 -0700481 if (!si_from->find_symbol_by_name(symbol_name, vi, &s)) {
482 return false;
483 }
484
Dmitriy Ivanov8f61d992014-09-16 14:31:06 -0700485 if (s != nullptr) {
Dmitriy Ivanovd225a5e2014-08-28 14:12:12 -0700486 *si_found_in = si_from;
Dmitriy Ivanov96bc37f2014-09-29 12:10:36 -0700487 }
488 }
489
Dmitriy Ivanovd225a5e2014-08-28 14:12:12 -0700490 // 1. Look for it in global_group
491 if (s == nullptr) {
Dmitriy Ivanov2a815362015-04-09 13:42:33 -0700492 bool error = false;
Dmitriy Ivanovd225a5e2014-08-28 14:12:12 -0700493 global_group.visit([&](soinfo* global_si) {
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -0700494 DEBUG("%s: looking up %s in %s (from global group)",
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -0700495 si_from->get_realpath(), name, global_si->get_realpath());
Dmitriy Ivanov2a815362015-04-09 13:42:33 -0700496 if (!global_si->find_symbol_by_name(symbol_name, vi, &s)) {
497 error = true;
498 return false;
499 }
500
Dmitriy Ivanov96bc37f2014-09-29 12:10:36 -0700501 if (s != nullptr) {
Dmitriy Ivanovd225a5e2014-08-28 14:12:12 -0700502 *si_found_in = global_si;
503 return false;
Dmitriy Ivanov96bc37f2014-09-29 12:10:36 -0700504 }
Dmitriy Ivanovc2048942014-08-29 10:15:25 -0700505
Dmitriy Ivanovd225a5e2014-08-28 14:12:12 -0700506 return true;
507 });
Dmitriy Ivanov2a815362015-04-09 13:42:33 -0700508
509 if (error) {
510 return false;
511 }
Dmitriy Ivanov96bc37f2014-09-29 12:10:36 -0700512 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700513
Dmitriy Ivanovd225a5e2014-08-28 14:12:12 -0700514 // 2. Look for it in the local group
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700515 if (s == nullptr) {
Dmitriy Ivanov2a815362015-04-09 13:42:33 -0700516 bool error = false;
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700517 local_group.visit([&](soinfo* local_si) {
Dmitriy Ivanovd225a5e2014-08-28 14:12:12 -0700518 if (local_si == si_from && si_from->has_DT_SYMBOLIC) {
Dmitriy Ivanove47b3f82014-10-23 14:19:07 -0700519 // we already did this - skip
520 return true;
521 }
522
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -0700523 DEBUG("%s: looking up %s in %s (from local group)",
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -0700524 si_from->get_realpath(), name, local_si->get_realpath());
Dmitriy Ivanov2a815362015-04-09 13:42:33 -0700525 if (!local_si->find_symbol_by_name(symbol_name, vi, &s)) {
526 error = true;
527 return false;
528 }
529
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700530 if (s != nullptr) {
Dmitriy Ivanovd225a5e2014-08-28 14:12:12 -0700531 *si_found_in = local_si;
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700532 return false;
533 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700534
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700535 return true;
536 });
Dmitriy Ivanov2a815362015-04-09 13:42:33 -0700537
538 if (error) {
539 return false;
540 }
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700541 }
542
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700543 if (s != nullptr) {
544 TRACE_TYPE(LOOKUP, "si %s sym %s s->st_value = %p, "
545 "found in %s, base = %p, load bias = %p",
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -0700546 si_from->get_realpath(), name, reinterpret_cast<void*>(s->st_value),
547 (*si_found_in)->get_realpath(), reinterpret_cast<void*>((*si_found_in)->base),
Dmitriy Ivanovd225a5e2014-08-28 14:12:12 -0700548 reinterpret_cast<void*>((*si_found_in)->load_bias));
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700549 }
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700550
Dmitriy Ivanov2a815362015-04-09 13:42:33 -0700551 *symbol = s;
552 return true;
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700553}
554
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700555ProtectedDataGuard::ProtectedDataGuard() {
556 if (ref_count_++ == 0) {
557 protect_data(PROT_READ | PROT_WRITE);
558 }
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700559
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700560 if (ref_count_ == 0) { // overflow
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700561 async_safe_fatal("Too many nested calls to dlopen()");
Dmitriy Ivanov279a22f2015-01-23 12:03:53 -0800562 }
Dimitry Ivanov68e6c032017-02-01 12:55:11 -0800563}
Dmitriy Ivanov279a22f2015-01-23 12:03:53 -0800564
Dimitry Ivanov68e6c032017-02-01 12:55:11 -0800565ProtectedDataGuard::~ProtectedDataGuard() {
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700566 if (--ref_count_ == 0) {
567 protect_data(PROT_READ);
Dmitriy Ivanov279a22f2015-01-23 12:03:53 -0800568 }
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700569}
Dmitriy Ivanov279a22f2015-01-23 12:03:53 -0800570
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700571void ProtectedDataGuard::protect_data(int protection) {
572 g_soinfo_allocator.protect_all(protection);
573 g_soinfo_links_allocator.protect_all(protection);
574 g_namespace_allocator.protect_all(protection);
575 g_namespace_list_allocator.protect_all(protection);
576}
Dmitriy Ivanov279a22f2015-01-23 12:03:53 -0800577
578size_t ProtectedDataGuard::ref_count_ = 0;
579
Dmitriy Ivanov0cd83eb2014-09-01 16:15:52 -0700580// Each size has it's own allocator.
581template<size_t size>
582class SizeBasedAllocator {
583 public:
584 static void* alloc() {
585 return allocator_.alloc();
586 }
Dmitriy Ivanov4bea4982014-08-29 14:01:48 -0700587
Dmitriy Ivanov0cd83eb2014-09-01 16:15:52 -0700588 static void free(void* ptr) {
589 allocator_.free(ptr);
590 }
Dmitriy Ivanov4bea4982014-08-29 14:01:48 -0700591
Vic Yangbb7e1232019-01-29 20:23:16 -0800592 static void purge() {
593 allocator_.purge();
594 }
595
Dmitriy Ivanov0cd83eb2014-09-01 16:15:52 -0700596 private:
597 static LinkerBlockAllocator allocator_;
598};
599
600template<size_t size>
601LinkerBlockAllocator SizeBasedAllocator<size>::allocator_(size);
602
603template<typename T>
604class TypeBasedAllocator {
605 public:
606 static T* alloc() {
607 return reinterpret_cast<T*>(SizeBasedAllocator<sizeof(T)>::alloc());
608 }
609
610 static void free(T* ptr) {
611 SizeBasedAllocator<sizeof(T)>::free(ptr);
612 }
Vic Yangbb7e1232019-01-29 20:23:16 -0800613
614 static void purge() {
615 SizeBasedAllocator<sizeof(T)>::purge();
616 }
Dmitriy Ivanov0cd83eb2014-09-01 16:15:52 -0700617};
618
Dmitriy Ivanov14669a92014-09-05 16:42:53 -0700619class LoadTask {
620 public:
621 struct deleter_t {
622 void operator()(LoadTask* t) {
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700623 t->~LoadTask();
Dmitriy Ivanov14669a92014-09-05 16:42:53 -0700624 TypeBasedAllocator<LoadTask>::free(t);
625 }
626 };
627
Dmitriy Ivanov14669a92014-09-05 16:42:53 -0700628 static deleter_t deleter;
629
Dimitry Ivanov7d429d32017-02-01 15:28:52 -0800630 static LoadTask* create(const char* name,
631 soinfo* needed_by,
Jiyong Park02586a22017-05-20 01:01:24 +0900632 android_namespace_t* start_from,
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700633 std::unordered_map<const soinfo*, ElfReader>* readers_map) {
Dmitriy Ivanov14669a92014-09-05 16:42:53 -0700634 LoadTask* ptr = TypeBasedAllocator<LoadTask>::alloc();
Jiyong Park02586a22017-05-20 01:01:24 +0900635 return new (ptr) LoadTask(name, needed_by, start_from, readers_map);
Dmitriy Ivanov14669a92014-09-05 16:42:53 -0700636 }
637
638 const char* get_name() const {
639 return name_;
640 }
641
642 soinfo* get_needed_by() const {
643 return needed_by_;
644 }
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700645
646 soinfo* get_soinfo() const {
647 return si_;
648 }
649
650 void set_soinfo(soinfo* si) {
651 si_ = si;
652 }
653
654 off64_t get_file_offset() const {
655 return file_offset_;
656 }
657
658 void set_file_offset(off64_t offset) {
659 file_offset_ = offset;
660 }
661
662 int get_fd() const {
663 return fd_;
664 }
665
666 void set_fd(int fd, bool assume_ownership) {
Martin Stjernholmde853ff2019-01-17 00:18:44 +0000667 if (fd_ != -1 && close_fd_) {
668 close(fd_);
669 }
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700670 fd_ = fd;
671 close_fd_ = assume_ownership;
672 }
673
674 const android_dlextinfo* get_extinfo() const {
675 return extinfo_;
676 }
677
678 void set_extinfo(const android_dlextinfo* extinfo) {
679 extinfo_ = extinfo;
680 }
681
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700682 bool is_dt_needed() const {
683 return is_dt_needed_;
684 }
685
686 void set_dt_needed(bool is_dt_needed) {
687 is_dt_needed_ = is_dt_needed;
688 }
689
Jiyong Park02586a22017-05-20 01:01:24 +0900690 // returns the namespace from where we need to start loading this.
691 const android_namespace_t* get_start_from() const {
692 return start_from_;
693 }
694
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700695 const ElfReader& get_elf_reader() const {
696 CHECK(si_ != nullptr);
697 return (*elf_readers_map_)[si_];
698 }
699
700 ElfReader& get_elf_reader() {
701 CHECK(si_ != nullptr);
702 return (*elf_readers_map_)[si_];
703 }
704
705 std::unordered_map<const soinfo*, ElfReader>* get_readers_map() {
706 return elf_readers_map_;
707 }
708
709 bool read(const char* realpath, off64_t file_size) {
710 ElfReader& elf_reader = get_elf_reader();
711 return elf_reader.Read(realpath, fd_, file_offset_, file_size);
712 }
713
Torne (Richard Coles)efbe9a52018-10-17 15:59:38 -0400714 bool load(address_space_params* address_space) {
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700715 ElfReader& elf_reader = get_elf_reader();
Torne (Richard Coles)efbe9a52018-10-17 15:59:38 -0400716 if (!elf_reader.Load(address_space)) {
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700717 return false;
718 }
719
720 si_->base = elf_reader.load_start();
721 si_->size = elf_reader.load_size();
Dimitry Ivanovf45b0e92016-01-15 11:13:35 -0800722 si_->set_mapped_by_caller(elf_reader.is_mapped_by_caller());
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700723 si_->load_bias = elf_reader.load_bias();
724 si_->phnum = elf_reader.phdr_count();
725 si_->phdr = elf_reader.loaded_phdr();
726
727 return true;
728 }
729
Dmitriy Ivanov14669a92014-09-05 16:42:53 -0700730 private:
Dimitry Ivanov7d429d32017-02-01 15:28:52 -0800731 LoadTask(const char* name,
732 soinfo* needed_by,
Jiyong Park02586a22017-05-20 01:01:24 +0900733 android_namespace_t* start_from,
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700734 std::unordered_map<const soinfo*, ElfReader>* readers_map)
735 : name_(name), needed_by_(needed_by), si_(nullptr),
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700736 fd_(-1), close_fd_(false), file_offset_(0), elf_readers_map_(readers_map),
Jiyong Park02586a22017-05-20 01:01:24 +0900737 is_dt_needed_(false), start_from_(start_from) {}
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700738
739 ~LoadTask() {
740 if (fd_ != -1 && close_fd_) {
741 close(fd_);
742 }
743 }
Dmitriy Ivanov14669a92014-09-05 16:42:53 -0700744
745 const char* name_;
746 soinfo* needed_by_;
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700747 soinfo* si_;
748 const android_dlextinfo* extinfo_;
749 int fd_;
750 bool close_fd_;
751 off64_t file_offset_;
752 std::unordered_map<const soinfo*, ElfReader>* elf_readers_map_;
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700753 // TODO(dimitry): needed by workaround for http://b/26394120 (the grey-list)
754 bool is_dt_needed_;
755 // END OF WORKAROUND
Jiyong Park02586a22017-05-20 01:01:24 +0900756 const android_namespace_t* const start_from_;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -0700757
758 DISALLOW_IMPLICIT_CONSTRUCTORS(LoadTask);
759};
760
Ningsheng Jiane93be992014-09-16 15:22:10 +0800761LoadTask::deleter_t LoadTask::deleter;
762
Dmitriy Ivanov0cd83eb2014-09-01 16:15:52 -0700763template <typename T>
764using linked_list_t = LinkedList<T, TypeBasedAllocator<LinkedListEntry<T>>>;
765
766typedef linked_list_t<soinfo> SoinfoLinkedList;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -0700767typedef linked_list_t<const char> StringLinkedList;
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700768typedef std::vector<LoadTask*> LoadTaskList;
Dmitriy Ivanov0cd83eb2014-09-01 16:15:52 -0700769
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800770enum walk_action_result_t : uint32_t {
771 kWalkStop = 0,
772 kWalkContinue = 1,
773 kWalkSkip = 2
774};
Dmitriy Ivanovaa0f2bd2014-07-28 17:32:20 -0700775
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700776// This function walks down the tree of soinfo dependencies
777// in breadth-first order and
778// * calls action(soinfo* si) for each node, and
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800779// * terminates walk if action returns kWalkStop
780// * skips children of the node if action
781// return kWalkSkip
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700782//
783// walk_dependencies_tree returns false if walk was terminated
784// by the action and true otherwise.
785template<typename F>
dimitry965d06d2017-11-28 16:03:07 +0100786static bool walk_dependencies_tree(soinfo* root_soinfo, F action) {
Dmitriy Ivanov0cd83eb2014-09-01 16:15:52 -0700787 SoinfoLinkedList visit_list;
788 SoinfoLinkedList visited;
789
dimitry965d06d2017-11-28 16:03:07 +0100790 visit_list.push_back(root_soinfo);
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700791
792 soinfo* si;
793 while ((si = visit_list.pop_front()) != nullptr) {
794 if (visited.contains(si)) {
Dmitriy Ivanov042426b2014-08-12 21:02:13 -0700795 continue;
796 }
797
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800798 walk_action_result_t result = action(si);
799
800 if (result == kWalkStop) {
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700801 return false;
Dmitriy Ivanovaa0f2bd2014-07-28 17:32:20 -0700802 }
803
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700804 visited.push_back(si);
805
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800806 if (result != kWalkSkip) {
807 si->get_children().for_each([&](soinfo* child) {
808 visit_list.push_back(child);
809 });
810 }
Dmitriy Ivanovaa0f2bd2014-07-28 17:32:20 -0700811 }
812
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700813 return true;
814}
815
816
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800817static const ElfW(Sym)* dlsym_handle_lookup(android_namespace_t* ns,
818 soinfo* root,
819 soinfo* skip_until,
820 soinfo** found,
821 SymbolName& symbol_name,
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -0800822 const version_info* vi) {
Dmitriy Ivanov2a815362015-04-09 13:42:33 -0700823 const ElfW(Sym)* result = nullptr;
Dmitriy Ivanov697bd9f2015-05-12 11:12:27 -0700824 bool skip_lookup = skip_until != nullptr;
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700825
dimitry965d06d2017-11-28 16:03:07 +0100826 walk_dependencies_tree(root, [&](soinfo* current_soinfo) {
Dmitriy Ivanov697bd9f2015-05-12 11:12:27 -0700827 if (skip_lookup) {
828 skip_lookup = current_soinfo != skip_until;
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800829 return kWalkContinue;
830 }
831
832 if (!ns->is_accessible(current_soinfo)) {
833 return kWalkSkip;
Dmitriy Ivanov697bd9f2015-05-12 11:12:27 -0700834 }
835
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -0800836 if (!current_soinfo->find_symbol_by_name(symbol_name, vi, &result)) {
Dmitriy Ivanov2a815362015-04-09 13:42:33 -0700837 result = nullptr;
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800838 return kWalkStop;
Dmitriy Ivanov2a815362015-04-09 13:42:33 -0700839 }
840
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700841 if (result != nullptr) {
842 *found = current_soinfo;
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800843 return kWalkStop;
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700844 }
845
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800846 return kWalkContinue;
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700847 });
848
849 return result;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800850}
851
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -0800852static const ElfW(Sym)* dlsym_linear_lookup(android_namespace_t* ns,
853 const char* name,
854 const version_info* vi,
855 soinfo** found,
856 soinfo* caller,
857 void* handle);
858
Dmitriy Ivanov697bd9f2015-05-12 11:12:27 -0700859// This is used by dlsym(3). It performs symbol lookup only within the
860// specified soinfo object and its dependencies in breadth first order.
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800861static const ElfW(Sym)* dlsym_handle_lookup(soinfo* si,
862 soinfo** found,
863 const char* name,
864 const version_info* vi) {
Dmitriy Ivanovf439b5a2015-05-30 13:04:39 -0700865 // According to man dlopen(3) and posix docs in the case when si is handle
866 // of the main executable we need to search not only in the executable and its
867 // dependencies but also in all libraries loaded with RTLD_GLOBAL.
868 //
869 // Since RTLD_GLOBAL is always set for the main executable and all dt_needed shared
870 // libraries and they are loaded in breath-first (correct) order we can just execute
871 // dlsym(RTLD_DEFAULT, ...); instead of doing two stage lookup.
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700872 if (si == solist_get_somain()) {
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -0800873 return dlsym_linear_lookup(&g_default_namespace, name, vi, found, nullptr, RTLD_DEFAULT);
Dmitriy Ivanovf439b5a2015-05-30 13:04:39 -0700874 }
875
Dmitriy Ivanov697bd9f2015-05-12 11:12:27 -0700876 SymbolName symbol_name(name);
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800877 // note that the namespace is not the namespace associated with caller_addr
878 // we use ns associated with root si intentionally here. Using caller_ns
879 // causes problems when user uses dlopen_ext to open a library in the separate
880 // namespace and then calls dlsym() on the handle.
881 return dlsym_handle_lookup(si->get_primary_namespace(), si, nullptr, found, symbol_name, vi);
Dmitriy Ivanov697bd9f2015-05-12 11:12:27 -0700882}
883
Brian Carlstromd4ee82d2013-02-28 15:58:45 -0800884/* This is used by dlsym(3) to performs a global symbol lookup. If the
885 start value is null (for RTLD_DEFAULT), the search starts at the
886 beginning of the global solist. Otherwise the search starts at the
887 specified soinfo (for RTLD_NEXT).
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700888 */
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -0800889static const ElfW(Sym)* dlsym_linear_lookup(android_namespace_t* ns,
890 const char* name,
891 const version_info* vi,
892 soinfo** found,
893 soinfo* caller,
894 void* handle) {
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -0800895 SymbolName symbol_name(name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800896
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -0700897 auto& soinfo_list = ns->soinfo_list();
898 auto start = soinfo_list.begin();
Dmitriy Ivanov76ac1ac2015-04-01 14:45:10 -0700899
900 if (handle == RTLD_NEXT) {
Dmitriy Ivanovb96ac412015-05-22 12:34:42 -0700901 if (caller == nullptr) {
Dmitriy Ivanov76ac1ac2015-04-01 14:45:10 -0700902 return nullptr;
903 } else {
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -0700904 auto it = soinfo_list.find(caller);
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -0700905 CHECK (it != soinfo_list.end());
906 start = ++it;
Dmitriy Ivanov76ac1ac2015-04-01 14:45:10 -0700907 }
Elliott Hughescade4c32012-12-20 14:42:14 -0800908 }
909
Dmitriy Ivanov2a815362015-04-09 13:42:33 -0700910 const ElfW(Sym)* s = nullptr;
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -0700911 for (auto it = start, end = soinfo_list.end(); it != end; ++it) {
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -0700912 soinfo* si = *it;
Dmitriy Ivanov19133522015-06-02 17:36:54 -0700913 // Do not skip RTLD_LOCAL libraries in dlsym(RTLD_DEFAULT, ...)
Elliott Hughes5bc78c82016-11-16 11:35:43 -0800914 // if the library is opened by application with target api level < M.
Dmitriy Ivanov19133522015-06-02 17:36:54 -0700915 // See http://b/21565766
Elliott Hughes5bc78c82016-11-16 11:35:43 -0800916 if ((si->get_rtld_flags() & RTLD_GLOBAL) == 0 &&
917 si->get_target_sdk_version() >= __ANDROID_API_M__) {
Dmitriy Ivanove8ba50f2014-09-15 17:00:10 -0700918 continue;
919 }
920
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -0800921 if (!si->find_symbol_by_name(symbol_name, vi, &s)) {
Dmitriy Ivanov2a815362015-04-09 13:42:33 -0700922 return nullptr;
923 }
924
Dmitriy Ivanov851135b2014-08-29 12:02:36 -0700925 if (s != nullptr) {
Elliott Hughescade4c32012-12-20 14:42:14 -0800926 *found = si;
927 break;
Matt Fischer1698d9e2009-12-31 12:17:56 -0600928 }
Elliott Hughescade4c32012-12-20 14:42:14 -0800929 }
Matt Fischer1698d9e2009-12-31 12:17:56 -0600930
dimitry153168c2018-02-20 16:51:41 +0100931 // If not found - use dlsym_handle_lookup for caller's local_group
932 if (s == nullptr && caller != nullptr) {
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800933 soinfo* local_group_root = caller->get_local_group_root();
934
935 return dlsym_handle_lookup(local_group_root->get_primary_namespace(),
936 local_group_root,
937 (handle == RTLD_NEXT) ? caller : nullptr,
938 found,
939 symbol_name,
940 vi);
Dmitriy Ivanov76ac1ac2015-04-01 14:45:10 -0700941 }
942
Dmitriy Ivanov851135b2014-08-29 12:02:36 -0700943 if (s != nullptr) {
Elliott Hughesc00f2cb2013-10-04 17:01:33 -0700944 TRACE_TYPE(LOOKUP, "%s s->st_value = %p, found->base = %p",
945 name, reinterpret_cast<void*>(s->st_value), reinterpret_cast<void*>((*found)->base));
Elliott Hughescade4c32012-12-20 14:42:14 -0800946 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800947
Elliott Hughescade4c32012-12-20 14:42:14 -0800948 return s;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800949}
950
Kito Chengfa8c05d2013-03-12 14:58:06 +0800951soinfo* find_containing_library(const void* p) {
Elliott Hughes0266ae52014-02-10 17:46:57 -0800952 ElfW(Addr) address = reinterpret_cast<ElfW(Addr)>(p);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700953 for (soinfo* si = solist_get_head(); si != nullptr; si = si->next) {
Peter Collingbourneb39cb3c2019-03-01 13:12:49 -0800954 if (address < si->base || address - si->base >= si->size) {
955 continue;
956 }
957 ElfW(Addr) vaddr = address - si->load_bias;
958 for (size_t i = 0; i != si->phnum; ++i) {
959 const ElfW(Phdr)* phdr = &si->phdr[i];
960 if (phdr->p_type != PT_LOAD) {
961 continue;
962 }
963 if (vaddr >= phdr->p_vaddr && vaddr < phdr->p_vaddr + phdr->p_memsz) {
964 return si;
965 }
Matt Fischere2a8b1f2009-12-31 12:17:40 -0600966 }
Kito Chengfa8c05d2013-03-12 14:58:06 +0800967 }
Dmitriy Ivanov851135b2014-08-29 12:02:36 -0700968 return nullptr;
Matt Fischere2a8b1f2009-12-31 12:17:40 -0600969}
970
Dmitriy Ivanovb4827502015-09-28 16:38:31 -0700971class ZipArchiveCache {
972 public:
973 ZipArchiveCache() {}
974 ~ZipArchiveCache();
975
976 bool get_or_open(const char* zip_path, ZipArchiveHandle* handle);
977 private:
978 DISALLOW_COPY_AND_ASSIGN(ZipArchiveCache);
979
980 std::unordered_map<std::string, ZipArchiveHandle> cache_;
981};
982
983bool ZipArchiveCache::get_or_open(const char* zip_path, ZipArchiveHandle* handle) {
984 std::string key(zip_path);
985
986 auto it = cache_.find(key);
987 if (it != cache_.end()) {
988 *handle = it->second;
989 return true;
990 }
991
992 int fd = TEMP_FAILURE_RETRY(open(zip_path, O_RDONLY | O_CLOEXEC));
993 if (fd == -1) {
994 return false;
995 }
996
997 if (OpenArchiveFd(fd, "", handle) != 0) {
998 // invalid zip-file (?)
Ryan Prichard0adf09b2018-10-01 18:35:46 -0700999 CloseArchive(*handle);
Dmitriy Ivanovb4827502015-09-28 16:38:31 -07001000 return false;
1001 }
1002
1003 cache_[key] = *handle;
1004 return true;
1005}
1006
1007ZipArchiveCache::~ZipArchiveCache() {
Dmitriy Ivanov5dce8942015-10-13 12:14:16 -07001008 for (const auto& it : cache_) {
Dmitriy Ivanovb4827502015-09-28 16:38:31 -07001009 CloseArchive(it.second);
1010 }
1011}
1012
1013static int open_library_in_zipfile(ZipArchiveCache* zip_archive_cache,
Dmitriy Ivanova1feb112015-10-01 18:41:57 -07001014 const char* const input_path,
1015 off64_t* file_offset, std::string* realpath) {
1016 std::string normalized_path;
1017 if (!normalize_path(input_path, &normalized_path)) {
1018 return -1;
1019 }
1020
1021 const char* const path = normalized_path.c_str();
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07001022 TRACE("Trying zip file open from path \"%s\" -> normalized \"%s\"", input_path, path);
Simon Baldwinaef71952015-01-16 13:22:54 +00001023
Dmitriy Ivanov402a7502015-06-09 13:46:51 -07001024 // Treat an '!/' separator inside a path as the separator between the name
Simon Baldwinaef71952015-01-16 13:22:54 +00001025 // of the zip file on disk and the subdirectory to search within it.
Dmitriy Ivanov402a7502015-06-09 13:46:51 -07001026 // For example, if path is "foo.zip!/bar/bas/x.so", then we search for
Simon Baldwinaef71952015-01-16 13:22:54 +00001027 // "bar/bas/x.so" within "foo.zip".
Dmitriy Ivanova1feb112015-10-01 18:41:57 -07001028 const char* const separator = strstr(path, kZipFileSeparator);
Simon Baldwinaef71952015-01-16 13:22:54 +00001029 if (separator == nullptr) {
1030 return -1;
Elliott Hughes124fae92012-10-31 14:20:03 -07001031 }
Simon Baldwinaef71952015-01-16 13:22:54 +00001032
1033 char buf[512];
1034 if (strlcpy(buf, path, sizeof(buf)) >= sizeof(buf)) {
1035 PRINT("Warning: ignoring very long library path: %s", path);
1036 return -1;
1037 }
1038
1039 buf[separator - path] = '\0';
1040
1041 const char* zip_path = buf;
Dmitriy Ivanov402a7502015-06-09 13:46:51 -07001042 const char* file_path = &buf[separator - path + 2];
Simon Baldwinaef71952015-01-16 13:22:54 +00001043 int fd = TEMP_FAILURE_RETRY(open(zip_path, O_RDONLY | O_CLOEXEC));
1044 if (fd == -1) {
1045 return -1;
1046 }
1047
1048 ZipArchiveHandle handle;
Dmitriy Ivanovb4827502015-09-28 16:38:31 -07001049 if (!zip_archive_cache->get_or_open(zip_path, &handle)) {
Simon Baldwinaef71952015-01-16 13:22:54 +00001050 // invalid zip-file (?)
1051 close(fd);
1052 return -1;
1053 }
1054
Simon Baldwinaef71952015-01-16 13:22:54 +00001055 ZipEntry entry;
1056
Elliott Hughesb51bb502019-05-03 22:45:41 -07001057 if (FindEntry(handle, file_path, &entry) != 0) {
Simon Baldwinaef71952015-01-16 13:22:54 +00001058 // Entry was not found.
1059 close(fd);
1060 return -1;
1061 }
1062
1063 // Check if it is properly stored
1064 if (entry.method != kCompressStored || (entry.offset % PAGE_SIZE) != 0) {
1065 close(fd);
1066 return -1;
1067 }
1068
1069 *file_offset = entry.offset;
Dmitriy Ivanova1feb112015-10-01 18:41:57 -07001070
1071 if (realpath_fd(fd, realpath)) {
1072 *realpath += separator;
1073 } else {
Tom Cherry66bc4282018-11-08 13:40:52 -08001074 if (!is_first_stage_init()) {
1075 PRINT("warning: unable to get realpath for the library \"%s\". Will use given path.",
1076 normalized_path.c_str());
1077 }
Dmitriy Ivanova1feb112015-10-01 18:41:57 -07001078 *realpath = normalized_path;
1079 }
1080
Simon Baldwinaef71952015-01-16 13:22:54 +00001081 return fd;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001082}
1083
Dmitriy Ivanovd165f562015-03-23 18:43:02 -07001084static bool format_path(char* buf, size_t buf_size, const char* path, const char* name) {
Christopher Ferris7a3681e2017-04-24 17:48:32 -07001085 int n = async_safe_format_buffer(buf, buf_size, "%s/%s", path, name);
Dmitriy Ivanovd165f562015-03-23 18:43:02 -07001086 if (n < 0 || n >= static_cast<int>(buf_size)) {
1087 PRINT("Warning: ignoring very long library path: %s/%s", path, name);
1088 return false;
1089 }
Simon Baldwinaef71952015-01-16 13:22:54 +00001090
Dmitriy Ivanovd165f562015-03-23 18:43:02 -07001091 return true;
1092}
1093
Ryan Prichard8f639a42018-10-01 23:10:05 -07001094static int open_library_at_path(ZipArchiveCache* zip_archive_cache,
1095 const char* path, off64_t* file_offset,
1096 std::string* realpath) {
1097 int fd = -1;
1098 if (strstr(path, kZipFileSeparator) != nullptr) {
1099 fd = open_library_in_zipfile(zip_archive_cache, path, file_offset, realpath);
1100 }
1101
1102 if (fd == -1) {
1103 fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC));
1104 if (fd != -1) {
1105 *file_offset = 0;
1106 if (!realpath_fd(fd, realpath)) {
Tom Cherry66bc4282018-11-08 13:40:52 -08001107 if (!is_first_stage_init()) {
1108 PRINT("warning: unable to get realpath for the library \"%s\". Will use given path.",
1109 path);
1110 }
Ryan Prichard8f639a42018-10-01 23:10:05 -07001111 *realpath = path;
1112 }
1113 }
1114 }
1115
1116 return fd;
1117}
1118
Dmitriy Ivanovb4827502015-09-28 16:38:31 -07001119static int open_library_on_paths(ZipArchiveCache* zip_archive_cache,
1120 const char* name, off64_t* file_offset,
Dmitriy Ivanova1feb112015-10-01 18:41:57 -07001121 const std::vector<std::string>& paths,
1122 std::string* realpath) {
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001123 for (const auto& path : paths) {
Dmitriy Ivanovd165f562015-03-23 18:43:02 -07001124 char buf[512];
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001125 if (!format_path(buf, sizeof(buf), path.c_str(), name)) {
Dmitriy Ivanovd165f562015-03-23 18:43:02 -07001126 continue;
1127 }
1128
Ryan Prichard8f639a42018-10-01 23:10:05 -07001129 int fd = open_library_at_path(zip_archive_cache, buf, file_offset, realpath);
Dmitriy Ivanovd165f562015-03-23 18:43:02 -07001130 if (fd != -1) {
1131 return fd;
1132 }
Simon Baldwinaef71952015-01-16 13:22:54 +00001133 }
1134
Dmitriy Ivanovd165f562015-03-23 18:43:02 -07001135 return -1;
Simon Baldwinaef71952015-01-16 13:22:54 +00001136}
1137
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001138static int open_library(android_namespace_t* ns,
1139 ZipArchiveCache* zip_archive_cache,
Dmitriy Ivanovb4827502015-09-28 16:38:31 -07001140 const char* name, soinfo *needed_by,
Dmitriy Ivanova1feb112015-10-01 18:41:57 -07001141 off64_t* file_offset, std::string* realpath) {
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001142 TRACE("[ opening %s from namespace %s ]", name, ns->get_name());
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001143
Elliott Hughes124fae92012-10-31 14:20:03 -07001144 // 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 -07001145 if (strchr(name, '/') != nullptr) {
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001146 int fd = -1;
1147
Dmitriy Ivanov730ed9d2015-07-16 04:52:06 -07001148 if (strstr(name, kZipFileSeparator) != nullptr) {
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001149 fd = open_library_in_zipfile(zip_archive_cache, name, file_offset, realpath);
1150 }
1151
1152 if (fd == -1) {
1153 fd = TEMP_FAILURE_RETRY(open(name, O_RDONLY | O_CLOEXEC));
Simon Baldwinaef71952015-01-16 13:22:54 +00001154 if (fd != -1) {
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001155 *file_offset = 0;
1156 if (!realpath_fd(fd, realpath)) {
Tom Cherry66bc4282018-11-08 13:40:52 -08001157 if (!is_first_stage_init()) {
1158 PRINT("warning: unable to get realpath for the library \"%s\". Will use given path.",
1159 name);
1160 }
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001161 *realpath = name;
1162 }
Simon Baldwinaef71952015-01-16 13:22:54 +00001163 }
1164 }
1165
Dmitriy Ivanove44fffd2015-03-17 17:12:18 -07001166 return fd;
Elliott Hughes124fae92012-10-31 14:20:03 -07001167 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001168
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001169 // Otherwise we try LD_LIBRARY_PATH first, and fall back to the default library path
1170 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 -07001171 if (fd == -1 && needed_by != nullptr) {
Dmitriy Ivanova1feb112015-10-01 18:41:57 -07001172 fd = open_library_on_paths(zip_archive_cache, name, file_offset, needed_by->get_dt_runpath(), realpath);
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001173 // Check if the library is accessible
1174 if (fd != -1 && !ns->is_accessible(*realpath)) {
Vic Yang48b69112018-10-24 14:14:26 -07001175 close(fd);
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001176 fd = -1;
1177 }
Evgenii Stepanov68650822015-06-10 13:38:39 -07001178 }
Dmitriy Ivanovb4827502015-09-28 16:38:31 -07001179
Peter Collingbourneea11be02019-04-30 16:05:13 -07001180#if !defined(__ANDROID_APEX__)
1181 if (fd == -1) {
1182 std::vector<std::string> bootstrap_paths = { std::string(kSystemLibDir) + "/bootstrap" };
1183 fd = open_library_on_paths(zip_archive_cache, name, file_offset, bootstrap_paths, realpath);
1184 }
1185#endif
1186
Elliott Hughes124fae92012-10-31 14:20:03 -07001187 if (fd == -1) {
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001188 fd = open_library_on_paths(zip_archive_cache, name, file_offset, ns->get_default_library_paths(), realpath);
Elliott Hughes124fae92012-10-31 14:20:03 -07001189 }
Dmitriy Ivanovb4827502015-09-28 16:38:31 -07001190
Elliott Hughes124fae92012-10-31 14:20:03 -07001191 return fd;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001192}
1193
Ryan Prichard8f639a42018-10-01 23:10:05 -07001194int open_executable(const char* path, off64_t* file_offset, std::string* realpath) {
1195 ZipArchiveCache zip_archive_cache;
1196 return open_library_at_path(&zip_archive_cache, path, file_offset, realpath);
1197}
1198
Dimitry Ivanov3f660572016-09-09 10:00:39 -07001199const char* fix_dt_needed(const char* dt_needed, const char* sopath __unused) {
Dmitriy Ivanovd974e882015-05-27 18:29:41 -07001200#if !defined(__LP64__)
1201 // Work around incorrect DT_NEEDED entries for old apps: http://b/21364029
Elliott Hughes9076b0c2018-02-28 11:29:45 -08001202 int app_target_api_level = get_application_target_sdk_version();
1203 if (app_target_api_level < __ANDROID_API_M__) {
Dmitriy Ivanovd974e882015-05-27 18:29:41 -07001204 const char* bname = basename(dt_needed);
1205 if (bname != dt_needed) {
Elliott Hughes9076b0c2018-02-28 11:29:45 -08001206 DL_WARN_documented_change(__ANDROID_API_M__,
1207 "invalid-dt_needed-entries-enforced-for-api-level-23",
1208 "library \"%s\" has invalid DT_NEEDED entry \"%s\"",
1209 sopath, dt_needed, app_target_api_level);
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07001210 add_dlwarning(sopath, "invalid DT_NEEDED entry", dt_needed);
Dmitriy Ivanovd974e882015-05-27 18:29:41 -07001211 }
1212
1213 return bname;
1214 }
1215#endif
1216 return dt_needed;
1217}
1218
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001219template<typename F>
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001220static void for_each_dt_needed(const ElfReader& elf_reader, F action) {
1221 for (const ElfW(Dyn)* d = elf_reader.dynamic(); d->d_tag != DT_NULL; ++d) {
1222 if (d->d_tag == DT_NEEDED) {
1223 action(fix_dt_needed(elf_reader.get_string(d->d_un.d_val), elf_reader.name()));
1224 }
1225 }
1226}
1227
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001228static bool find_loaded_library_by_inode(android_namespace_t* ns,
1229 const struct stat& file_stat,
1230 off64_t file_offset,
1231 bool search_linked_namespaces,
1232 soinfo** candidate) {
Vic Yang3ec16be2019-06-02 21:10:53 -07001233 if (file_stat.st_dev == 0 || file_stat.st_ino == 0) {
1234 *candidate = nullptr;
1235 return false;
1236 }
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001237
1238 auto predicate = [&](soinfo* si) {
Vic Yang3ec16be2019-06-02 21:10:53 -07001239 return si->get_st_ino() == file_stat.st_ino &&
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001240 si->get_st_dev() == file_stat.st_dev &&
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001241 si->get_file_offset() == file_offset;
1242 };
1243
1244 *candidate = ns->soinfo_list().find_if(predicate);
1245
1246 if (*candidate == nullptr && search_linked_namespaces) {
1247 for (auto& link : ns->linked_namespaces()) {
1248 android_namespace_t* linked_ns = link.linked_namespace();
1249 soinfo* si = linked_ns->soinfo_list().find_if(predicate);
1250
1251 if (si != nullptr && link.is_accessible(si->get_soname())) {
1252 *candidate = si;
1253 return true;
1254 }
1255 }
1256 }
1257
1258 return *candidate != nullptr;
1259}
1260
Evgenii Stepanov9e77a642017-07-27 14:55:44 -07001261static bool find_loaded_library_by_realpath(android_namespace_t* ns, const char* realpath,
1262 bool search_linked_namespaces, soinfo** candidate) {
1263 auto predicate = [&](soinfo* si) { return strcmp(realpath, si->get_realpath()) == 0; };
1264
1265 *candidate = ns->soinfo_list().find_if(predicate);
1266
1267 if (*candidate == nullptr && search_linked_namespaces) {
1268 for (auto& link : ns->linked_namespaces()) {
1269 android_namespace_t* linked_ns = link.linked_namespace();
1270 soinfo* si = linked_ns->soinfo_list().find_if(predicate);
1271
1272 if (si != nullptr && link.is_accessible(si->get_soname())) {
1273 *candidate = si;
1274 return true;
1275 }
1276 }
1277 }
1278
1279 return *candidate != nullptr;
1280}
1281
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001282static bool load_library(android_namespace_t* ns,
1283 LoadTask* task,
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001284 LoadTaskList* load_tasks,
1285 int rtld_flags,
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001286 const std::string& realpath,
1287 bool search_linked_namespaces) {
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001288 off64_t file_offset = task->get_file_offset();
1289 const char* name = task->get_name();
1290 const android_dlextinfo* extinfo = task->get_extinfo();
1291
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001292 LD_LOG(kLogDlopen, "load_library(ns=%s, task=%s, flags=0x%x, realpath=%s)", ns->get_name(), name,
1293 rtld_flags, realpath.c_str());
1294
Dmitriy Ivanov07e5bc12014-10-03 17:52:44 -07001295 if ((file_offset % PAGE_SIZE) != 0) {
Dmitriy Ivanova6c12792014-10-21 12:09:18 -07001296 DL_ERR("file offset for the library \"%s\" is not page-aligned: %" PRId64, name, file_offset);
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001297 return false;
Dmitriy Ivanov07e5bc12014-10-03 17:52:44 -07001298 }
Yabin Cui16f7f8d2014-11-04 11:08:05 -08001299 if (file_offset < 0) {
1300 DL_ERR("file offset for the library \"%s\" is negative: %" PRId64, name, file_offset);
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001301 return false;
Yabin Cui16f7f8d2014-11-04 11:08:05 -08001302 }
Dmitriy Ivanov07e5bc12014-10-03 17:52:44 -07001303
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001304 struct stat file_stat;
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001305 if (TEMP_FAILURE_RETRY(fstat(task->get_fd(), &file_stat)) != 0) {
Dmitriy Ivanova6c12792014-10-21 12:09:18 -07001306 DL_ERR("unable to stat file for the library \"%s\": %s", name, strerror(errno));
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001307 return false;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001308 }
Yabin Cui16f7f8d2014-11-04 11:08:05 -08001309 if (file_offset >= file_stat.st_size) {
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07001310 DL_ERR("file offset for the library \"%s\" >= file size: %" PRId64 " >= %" PRId64,
1311 name, file_offset, file_stat.st_size);
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001312 return false;
Yabin Cui16f7f8d2014-11-04 11:08:05 -08001313 }
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001314
1315 // Check for symlink and other situations where
Dmitriy Ivanov9b821362015-04-02 16:03:56 -07001316 // file can have different names, unless ANDROID_DLEXT_FORCE_LOAD is set
1317 if (extinfo == nullptr || (extinfo->flags & ANDROID_DLEXT_FORCE_LOAD) == 0) {
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001318 soinfo* si = nullptr;
1319 if (find_loaded_library_by_inode(ns, file_stat, file_offset, search_linked_namespaces, &si)) {
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001320 LD_LOG(kLogDlopen,
1321 "load_library(ns=%s, task=%s): Already loaded under different name/path \"%s\" - "
1322 "will return existing soinfo",
1323 ns->get_name(), name, si->get_realpath());
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001324 task->set_soinfo(si);
1325 return true;
1326 }
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001327 }
Dmitriy Ivanovd59e5002014-05-09 09:10:14 -07001328
Dmitriy Ivanove8ba50f2014-09-15 17:00:10 -07001329 if ((rtld_flags & RTLD_NOLOAD) != 0) {
Dmitriy Ivanova6ac54a2014-09-09 10:21:42 -07001330 DL_ERR("library \"%s\" wasn't loaded and RTLD_NOLOAD prevented it", name);
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001331 return false;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001332 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001333
Dimitry Ivanovbf34ba32017-04-21 13:12:05 -07001334 struct statfs fs_stat;
1335 if (TEMP_FAILURE_RETRY(fstatfs(task->get_fd(), &fs_stat)) != 0) {
1336 DL_ERR("unable to fstatfs file for the library \"%s\": %s", name, strerror(errno));
1337 return false;
1338 }
1339
1340 // do not check accessibility using realpath if fd is located on tmpfs
1341 // this enables use of memfd_create() for apps
1342 if ((fs_stat.f_type != TMPFS_MAGIC) && (!ns->is_accessible(realpath))) {
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07001343 // TODO(dimitry): workaround for http://b/26394120 - the grey-list
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001344
1345 // TODO(dimitry) before O release: add a namespace attribute to have this enabled
1346 // only for classloader-namespaces
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07001347 const soinfo* needed_by = task->is_dt_needed() ? task->get_needed_by() : nullptr;
Dimitry Ivanov35c8e3b2017-02-27 12:17:47 -08001348 if (is_greylisted(ns, name, needed_by)) {
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07001349 // print warning only if needed by non-system library
1350 if (needed_by == nullptr || !is_system_library(needed_by->get_realpath())) {
1351 const soinfo* needed_or_dlopened_by = task->get_needed_by();
1352 const char* sopath = needed_or_dlopened_by == nullptr ? "(unknown)" :
1353 needed_or_dlopened_by->get_realpath();
Elliott Hughes9076b0c2018-02-28 11:29:45 -08001354 DL_WARN_documented_change(__ANDROID_API_N__,
1355 "private-api-enforced-for-api-level-24",
1356 "library \"%s\" (\"%s\") needed or dlopened by \"%s\" "
1357 "is not accessible by namespace \"%s\"",
1358 name, realpath.c_str(), sopath, ns->get_name());
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07001359 add_dlwarning(sopath, "unauthorized access to", name);
1360 }
1361 } else {
1362 // do not load libraries if they are not accessible for the specified namespace.
1363 const char* needed_or_dlopened_by = task->get_needed_by() == nullptr ?
1364 "(unknown)" :
1365 task->get_needed_by()->get_realpath();
Dimitry Ivanovd17a3772016-03-01 13:11:28 -08001366
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07001367 DL_ERR("library \"%s\" needed or dlopened by \"%s\" is not accessible for the namespace \"%s\"",
1368 name, needed_or_dlopened_by, ns->get_name());
Dimitry Ivanovd17a3772016-03-01 13:11:28 -08001369
Dimitry Ivanov35c8e3b2017-02-27 12:17:47 -08001370 // do not print this if a library is in the list of shared libraries for linked namespaces
1371 if (!maybe_accessible_via_namespace_links(ns, name)) {
1372 PRINT("library \"%s\" (\"%s\") needed or dlopened by \"%s\" is not accessible for the"
1373 " namespace: [name=\"%s\", ld_library_paths=\"%s\", default_library_paths=\"%s\","
1374 " permitted_paths=\"%s\"]",
1375 name, realpath.c_str(),
1376 needed_or_dlopened_by,
1377 ns->get_name(),
1378 android::base::Join(ns->get_ld_library_paths(), ':').c_str(),
1379 android::base::Join(ns->get_default_library_paths(), ':').c_str(),
1380 android::base::Join(ns->get_permitted_paths(), ':').c_str());
1381 }
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07001382 return false;
1383 }
Dimitry Ivanov22840aa2015-12-04 18:28:49 -08001384 }
1385
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001386 soinfo* si = soinfo_alloc(ns, realpath.c_str(), &file_stat, file_offset, rtld_flags);
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001387 if (si == nullptr) {
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001388 return false;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001389 }
Dmitriy Ivanovd59e5002014-05-09 09:10:14 -07001390
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001391 task->set_soinfo(si);
1392
1393 // Read the ELF header and some of the segments.
1394 if (!task->read(realpath.c_str(), file_stat.st_size)) {
Dmitriy Ivanovfd7a91e2015-11-06 10:44:37 -08001395 soinfo_free(si);
1396 task->set_soinfo(nullptr);
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001397 return false;
1398 }
1399
1400 // find and set DT_RUNPATH and dt_soname
1401 // Note that these field values are temporary and are
1402 // going to be overwritten on soinfo::prelink_image
1403 // with values from PT_LOAD segments.
1404 const ElfReader& elf_reader = task->get_elf_reader();
1405 for (const ElfW(Dyn)* d = elf_reader.dynamic(); d->d_tag != DT_NULL; ++d) {
1406 if (d->d_tag == DT_RUNPATH) {
1407 si->set_dt_runpath(elf_reader.get_string(d->d_un.d_val));
1408 }
1409 if (d->d_tag == DT_SONAME) {
1410 si->set_soname(elf_reader.get_string(d->d_un.d_val));
1411 }
1412 }
1413
Dan Willemsen5038ef62018-10-21 17:45:04 -07001414#if !defined(__ANDROID__)
1415 // Bionic on the host currently uses some Android prebuilts, which don't set
1416 // DT_RUNPATH with any relative paths, so they can't find their dependencies.
1417 // b/118058804
1418 if (si->get_dt_runpath().empty()) {
1419 si->set_dt_runpath("$ORIGIN/../lib64:$ORIGIN/lib64");
1420 }
1421#endif
1422
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001423 for_each_dt_needed(task->get_elf_reader(), [&](const char* name) {
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001424 LD_LOG(kLogDlopen, "load_library(ns=%s, task=%s): Adding DT_NEEDED task: %s",
1425 ns->get_name(), task->get_name(), name);
Jiyong Park02586a22017-05-20 01:01:24 +09001426 load_tasks->push_back(LoadTask::create(name, si, ns, task->get_readers_map()));
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001427 });
Dmitriy Ivanovd59e5002014-05-09 09:10:14 -07001428
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001429 return true;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001430}
1431
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001432static bool load_library(android_namespace_t* ns,
1433 LoadTask* task,
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001434 ZipArchiveCache* zip_archive_cache,
1435 LoadTaskList* load_tasks,
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001436 int rtld_flags,
1437 bool search_linked_namespaces) {
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001438 const char* name = task->get_name();
1439 soinfo* needed_by = task->get_needed_by();
1440 const android_dlextinfo* extinfo = task->get_extinfo();
1441
Dmitriy Ivanova1feb112015-10-01 18:41:57 -07001442 off64_t file_offset;
1443 std::string realpath;
Spencer Low0346ad72015-04-22 18:06:51 -07001444 if (extinfo != nullptr && (extinfo->flags & ANDROID_DLEXT_USE_LIBRARY_FD) != 0) {
Dmitriy Ivanova1feb112015-10-01 18:41:57 -07001445 file_offset = 0;
Spencer Low0346ad72015-04-22 18:06:51 -07001446 if ((extinfo->flags & ANDROID_DLEXT_USE_LIBRARY_FD_OFFSET) != 0) {
1447 file_offset = extinfo->library_fd_offset;
1448 }
Dmitriy Ivanova1feb112015-10-01 18:41:57 -07001449
1450 if (!realpath_fd(extinfo->library_fd, &realpath)) {
Tom Cherry66bc4282018-11-08 13:40:52 -08001451 if (!is_first_stage_init()) {
1452 PRINT(
1453 "warning: unable to get realpath for the library \"%s\" by extinfo->library_fd. "
1454 "Will use given name.",
1455 name);
1456 }
Dmitriy Ivanova1feb112015-10-01 18:41:57 -07001457 realpath = name;
1458 }
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001459
1460 task->set_fd(extinfo->library_fd, false);
1461 task->set_file_offset(file_offset);
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001462 return load_library(ns, task, load_tasks, rtld_flags, realpath, search_linked_namespaces);
Spencer Low0346ad72015-04-22 18:06:51 -07001463 }
1464
1465 // Open the file.
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001466 int fd = open_library(ns, zip_archive_cache, name, needed_by, &file_offset, &realpath);
Spencer Low0346ad72015-04-22 18:06:51 -07001467 if (fd == -1) {
1468 DL_ERR("library \"%s\" not found", name);
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001469 return false;
Spencer Low0346ad72015-04-22 18:06:51 -07001470 }
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001471
1472 task->set_fd(fd, true);
1473 task->set_file_offset(file_offset);
1474
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001475 return load_library(ns, task, load_tasks, rtld_flags, realpath, search_linked_namespaces);
Spencer Low0346ad72015-04-22 18:06:51 -07001476}
1477
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001478static bool find_loaded_library_by_soname(android_namespace_t* ns,
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001479 const char* name,
1480 soinfo** candidate) {
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001481 return !ns->soinfo_list().visit([&](soinfo* si) {
Dmitriy Ivanov618f1a32015-03-17 20:06:36 -07001482 const char* soname = si->get_soname();
1483 if (soname != nullptr && (strcmp(name, soname) == 0)) {
Dimitry Ivanov3bd90612017-02-01 08:54:43 -08001484 *candidate = si;
1485 return false;
Ard Biesheuvel12c78bb2012-08-14 12:30:09 +02001486 }
Dmitriy Ivanova9703332015-06-16 15:38:21 -07001487
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001488 return true;
1489 });
Ard Biesheuvel12c78bb2012-08-14 12:30:09 +02001490}
1491
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001492// Returns true if library was found and false otherwise
1493static bool find_loaded_library_by_soname(android_namespace_t* ns,
1494 const char* name,
1495 bool search_linked_namespaces,
1496 soinfo** candidate) {
1497 *candidate = nullptr;
1498
1499 // Ignore filename with path.
1500 if (strchr(name, '/') != nullptr) {
1501 return false;
1502 }
1503
1504 bool found = find_loaded_library_by_soname(ns, name, candidate);
1505
1506 if (!found && search_linked_namespaces) {
1507 // if a library was not found - look into linked namespaces
1508 for (auto& link : ns->linked_namespaces()) {
1509 if (!link.is_accessible(name)) {
1510 continue;
1511 }
1512
1513 android_namespace_t* linked_ns = link.linked_namespace();
1514
1515 if (find_loaded_library_by_soname(linked_ns, name, candidate)) {
1516 return true;
1517 }
1518 }
1519 }
1520
1521 return found;
1522}
1523
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001524static bool find_library_in_linked_namespace(const android_namespace_link_t& namespace_link,
Jiyong Park02586a22017-05-20 01:01:24 +09001525 LoadTask* task) {
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001526 android_namespace_t* ns = namespace_link.linked_namespace();
1527
1528 soinfo* candidate;
1529 bool loaded = false;
1530
1531 std::string soname;
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001532 if (find_loaded_library_by_soname(ns, task->get_name(), false, &candidate)) {
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001533 loaded = true;
1534 soname = candidate->get_soname();
1535 } else {
1536 soname = resolve_soname(task->get_name());
1537 }
1538
1539 if (!namespace_link.is_accessible(soname.c_str())) {
1540 // the library is not accessible via namespace_link
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001541 LD_LOG(kLogDlopen,
1542 "find_library_in_linked_namespace(ns=%s, task=%s): Not accessible (soname=%s)",
1543 ns->get_name(), task->get_name(), soname.c_str());
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001544 return false;
1545 }
1546
1547 // if library is already loaded - return it
1548 if (loaded) {
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001549 LD_LOG(kLogDlopen, "find_library_in_linked_namespace(ns=%s, task=%s): Already loaded",
1550 ns->get_name(), task->get_name());
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001551 task->set_soinfo(candidate);
1552 return true;
1553 }
1554
Jiyong Park02586a22017-05-20 01:01:24 +09001555 // returning true with empty soinfo means that the library is okay to be
Logan Chien9ee45912018-01-18 12:05:09 +08001556 // loaded in the namespace but has not yet been loaded there before.
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001557 LD_LOG(kLogDlopen, "find_library_in_linked_namespace(ns=%s, task=%s): Ok to load", ns->get_name(),
1558 task->get_name());
Jiyong Park02586a22017-05-20 01:01:24 +09001559 task->set_soinfo(nullptr);
1560 return true;
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001561}
1562
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001563static bool find_library_internal(android_namespace_t* ns,
1564 LoadTask* task,
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001565 ZipArchiveCache* zip_archive_cache,
1566 LoadTaskList* load_tasks,
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001567 int rtld_flags,
1568 bool search_linked_namespaces) {
Dmitriy Ivanova9703332015-06-16 15:38:21 -07001569 soinfo* candidate;
1570
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001571 if (find_loaded_library_by_soname(ns, task->get_name(), search_linked_namespaces, &candidate)) {
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001572 LD_LOG(kLogDlopen,
1573 "find_library_internal(ns=%s, task=%s): Already loaded (by soname): %s",
1574 ns->get_name(), task->get_name(), candidate->get_realpath());
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001575 task->set_soinfo(candidate);
1576 return true;
Dmitriy Ivanova9703332015-06-16 15:38:21 -07001577 }
Dmitriy Ivanovb648a8a2014-05-19 15:06:58 -07001578
1579 // Library might still be loaded, the accurate detection
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001580 // of this fact is done by load_library.
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001581 TRACE("[ \"%s\" find_loaded_library_by_soname failed (*candidate=%s@%p). Trying harder... ]",
1582 task->get_name(), candidate == nullptr ? "n/a" : candidate->get_realpath(), candidate);
Dmitriy Ivanova9703332015-06-16 15:38:21 -07001583
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001584 if (load_library(ns, task, zip_archive_cache, load_tasks, rtld_flags, search_linked_namespaces)) {
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001585 return true;
1586 }
1587
Jiyong Parkefc503d2019-02-12 01:08:57 +09001588 // TODO(dimitry): workaround for http://b/26394120 (the grey-list)
1589 if (ns->is_greylist_enabled() && is_greylisted(ns, task->get_name(), task->get_needed_by())) {
1590 // For the libs in the greylist, switch to the default namespace and then
1591 // try the load again from there. The library could be loaded from the
1592 // default namespace or from another namespace (e.g. runtime) that is linked
1593 // from the default namespace.
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001594 LD_LOG(kLogDlopen,
1595 "find_library_internal(ns=%s, task=%s): Greylisted library - trying namespace %s",
1596 ns->get_name(), task->get_name(), g_default_namespace.get_name());
Jiyong Parkefc503d2019-02-12 01:08:57 +09001597 ns = &g_default_namespace;
1598 if (load_library(ns, task, zip_archive_cache, load_tasks, rtld_flags,
1599 search_linked_namespaces)) {
1600 return true;
1601 }
1602 }
1603 // END OF WORKAROUND
1604
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001605 if (search_linked_namespaces) {
1606 // if a library was not found - look into linked namespaces
dimitry8db36a52017-10-23 15:10:10 +02001607 // preserve current dlerror in the case it fails.
1608 DlErrorRestorer dlerror_restorer;
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001609 LD_LOG(kLogDlopen, "find_library_internal(ns=%s, task=%s): Trying %zu linked namespaces",
1610 ns->get_name(), task->get_name(), ns->linked_namespaces().size());
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001611 for (auto& linked_namespace : ns->linked_namespaces()) {
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001612 if (find_library_in_linked_namespace(linked_namespace, task)) {
Jiyong Park02586a22017-05-20 01:01:24 +09001613 if (task->get_soinfo() == nullptr) {
1614 // try to load the library - once namespace boundary is crossed
1615 // we need to load a library within separate load_group
1616 // to avoid using symbols from foreign namespace while.
1617 //
1618 // However, actual linking is deferred until when the global group
1619 // is fully identified and is applied to all namespaces.
1620 // Otherwise, the libs in the linked namespace won't get symbols from
1621 // the global group.
1622 if (load_library(linked_namespace.linked_namespace(), task, zip_archive_cache, load_tasks, rtld_flags, false)) {
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001623 LD_LOG(
1624 kLogDlopen, "find_library_internal(ns=%s, task=%s): Found in linked namespace %s",
1625 ns->get_name(), task->get_name(), linked_namespace.linked_namespace()->get_name());
Jiyong Park02586a22017-05-20 01:01:24 +09001626 return true;
1627 }
Jiyong Park02586a22017-05-20 01:01:24 +09001628 } else {
1629 // lib is already loaded
1630 return true;
1631 }
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001632 }
1633 }
1634 }
1635
1636 return false;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001637}
1638
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001639static void soinfo_unload(soinfo* si);
1640
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001641static void shuffle(std::vector<LoadTask*>* v) {
Tom Cherry66bc4282018-11-08 13:40:52 -08001642 if (is_first_stage_init()) {
1643 // arc4random* is not available in first stage init because /dev/random
1644 // hasn't yet been created.
Jiyong Park31cd08f2018-06-01 19:18:56 +09001645 return;
1646 }
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001647 for (size_t i = 0, size = v->size(); i < size; ++i) {
1648 size_t n = size - i;
1649 size_t r = arc4random_uniform(n);
1650 std::swap((*v)[n-1], (*v)[r]);
1651 }
1652}
1653
Evgenii Stepanov0cdef7e2015-07-06 17:56:31 -07001654// add_as_children - add first-level loaded libraries (i.e. library_names[], but
1655// not their transitive dependencies) as children of the start_with library.
1656// This is false when find_libraries is called for dlopen(), when newly loaded
1657// libraries must form a disjoint tree.
Dimitry Ivanov3f660572016-09-09 10:00:39 -07001658bool find_libraries(android_namespace_t* ns,
1659 soinfo* start_with,
1660 const char* const library_names[],
1661 size_t library_names_count,
1662 soinfo* soinfos[],
1663 std::vector<soinfo*>* ld_preloads,
1664 size_t ld_preloads_count,
1665 int rtld_flags,
1666 const android_dlextinfo* extinfo,
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001667 bool add_as_children,
Jiyong Park02586a22017-05-20 01:01:24 +09001668 bool search_linked_namespaces,
Jiyong Park02586a22017-05-20 01:01:24 +09001669 std::vector<android_namespace_t*>* namespaces) {
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001670 // Step 0: prepare.
dimitry965d06d2017-11-28 16:03:07 +01001671 std::unordered_map<const soinfo*, ElfReader> readers_map;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001672 LoadTaskList load_tasks;
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001673
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -07001674 for (size_t i = 0; i < library_names_count; ++i) {
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001675 const char* name = library_names[i];
Jiyong Park02586a22017-05-20 01:01:24 +09001676 load_tasks.push_back(LoadTask::create(name, start_with, ns, &readers_map));
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001677 }
1678
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -07001679 // If soinfos array is null allocate one on stack.
1680 // The array is needed in case of failure; for example
1681 // when library_names[] = {libone.so, libtwo.so} and libone.so
1682 // is loaded correctly but libtwo.so failed for some reason.
1683 // In this case libone.so should be unloaded on return.
1684 // See also implementation of failure_guard below.
1685
1686 if (soinfos == nullptr) {
1687 size_t soinfos_size = sizeof(soinfo*)*library_names_count;
1688 soinfos = reinterpret_cast<soinfo**>(alloca(soinfos_size));
1689 memset(soinfos, 0, soinfos_size);
1690 }
1691
1692 // list of libraries to link - see step 2.
1693 size_t soinfos_count = 0;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001694
Tom Cherryb8ab6182017-04-05 16:20:29 -07001695 auto scope_guard = android::base::make_scope_guard([&]() {
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001696 for (LoadTask* t : load_tasks) {
1697 LoadTask::deleter(t);
1698 }
1699 });
1700
Dmitriy Ivanovb4827502015-09-28 16:38:31 -07001701 ZipArchiveCache zip_archive_cache;
1702
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001703 // Step 1: expand the list of load_tasks to include
1704 // all DT_NEEDED libraries (do not load them just yet)
1705 for (size_t i = 0; i<load_tasks.size(); ++i) {
1706 LoadTask* task = load_tasks[i];
Evgenii Stepanov68650822015-06-10 13:38:39 -07001707 soinfo* needed_by = task->get_needed_by();
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001708
Dmitriy Ivanovedfc9f62015-09-02 16:32:02 -07001709 bool is_dt_needed = needed_by != nullptr && (needed_by != start_with || add_as_children);
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001710 task->set_extinfo(is_dt_needed ? nullptr : extinfo);
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07001711 task->set_dt_needed(is_dt_needed);
Dmitriy Ivanovedfc9f62015-09-02 16:32:02 -07001712
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001713 LD_LOG(kLogDlopen, "find_libraries(ns=%s): task=%s, is_dt_needed=%d", ns->get_name(),
1714 task->get_name(), is_dt_needed);
1715
Jiyong Park02586a22017-05-20 01:01:24 +09001716 // Note: start from the namespace that is stored in the LoadTask. This namespace
1717 // is different from the current namespace when the LoadTask is for a transitive
1718 // dependency and the lib that created the LoadTask is not found in the
1719 // current namespace but in one of the linked namespace.
1720 if (!find_library_internal(const_cast<android_namespace_t*>(task->get_start_from()),
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001721 task,
1722 &zip_archive_cache,
1723 &load_tasks,
1724 rtld_flags,
1725 search_linked_namespaces || is_dt_needed)) {
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001726 return false;
1727 }
1728
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001729 soinfo* si = task->get_soinfo();
1730
Dmitriy Ivanovedfc9f62015-09-02 16:32:02 -07001731 if (is_dt_needed) {
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001732 needed_by->add_child(si);
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08001733 }
1734
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -07001735 // When ld_preloads is not null, the first
1736 // ld_preloads_count libs are in fact ld_preloads.
1737 if (ld_preloads != nullptr && soinfos_count < ld_preloads_count) {
Dmitriy Ivanovd165f562015-03-23 18:43:02 -07001738 ld_preloads->push_back(si);
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001739 }
1740
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -07001741 if (soinfos_count < library_names_count) {
1742 soinfos[soinfos_count++] = si;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001743 }
1744 }
1745
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001746 // Step 2: Load libraries in random order (see b/24047022)
1747 LoadTaskList load_list;
1748 for (auto&& task : load_tasks) {
1749 soinfo* si = task->get_soinfo();
1750 auto pred = [&](const LoadTask* t) {
1751 return t->get_soinfo() == si;
1752 };
1753
1754 if (!si->is_linked() &&
1755 std::find_if(load_list.begin(), load_list.end(), pred) == load_list.end() ) {
1756 load_list.push_back(task);
1757 }
1758 }
Torne (Richard Coles)efbe9a52018-10-17 15:59:38 -04001759 bool reserved_address_recursive = false;
1760 if (extinfo) {
1761 reserved_address_recursive = extinfo->flags & ANDROID_DLEXT_RESERVED_ADDRESS_RECURSIVE;
1762 }
1763 if (!reserved_address_recursive) {
1764 // Shuffle the load order in the normal case, but not if we are loading all
1765 // the libraries to a reserved address range.
1766 shuffle(&load_list);
1767 }
1768
1769 // Set up address space parameters.
1770 address_space_params extinfo_params, default_params;
1771 size_t relro_fd_offset = 0;
1772 if (extinfo) {
1773 if (extinfo->flags & ANDROID_DLEXT_RESERVED_ADDRESS) {
1774 extinfo_params.start_addr = extinfo->reserved_addr;
1775 extinfo_params.reserved_size = extinfo->reserved_size;
1776 extinfo_params.must_use_address = true;
1777 } else if (extinfo->flags & ANDROID_DLEXT_RESERVED_ADDRESS_HINT) {
1778 extinfo_params.start_addr = extinfo->reserved_addr;
1779 extinfo_params.reserved_size = extinfo->reserved_size;
1780 }
1781 }
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001782
1783 for (auto&& task : load_list) {
Torne (Richard Coles)efbe9a52018-10-17 15:59:38 -04001784 address_space_params* address_space =
1785 (reserved_address_recursive || !task->is_dt_needed()) ? &extinfo_params : &default_params;
1786 if (!task->load(address_space)) {
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001787 return false;
1788 }
1789 }
1790
1791 // Step 3: pre-link all DT_NEEDED libraries in breadth first order.
1792 for (auto&& task : load_tasks) {
1793 soinfo* si = task->get_soinfo();
1794 if (!si->is_linked() && !si->prelink_image()) {
1795 return false;
1796 }
Ryan Pricharde5e69e02019-01-01 18:53:48 -08001797 register_soinfo_tls(si);
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001798 }
1799
Jiyong Park02586a22017-05-20 01:01:24 +09001800 // Step 4: Construct the global group. Note: DF_1_GLOBAL bit of a library is
1801 // determined at step 3.
1802
1803 // Step 4-1: DF_1_GLOBAL bit is force set for LD_PRELOADed libs because they
1804 // must be added to the global group
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001805 if (ld_preloads != nullptr) {
1806 for (auto&& si : *ld_preloads) {
1807 si->set_dt_flags_1(si->get_dt_flags_1() | DF_1_GLOBAL);
1808 }
1809 }
1810
Jiyong Park02586a22017-05-20 01:01:24 +09001811 // Step 4-2: Gather all DF_1_GLOBAL libs which were newly loaded during this
1812 // run. These will be the new member of the global group
1813 soinfo_list_t new_global_group_members;
1814 for (auto&& task : load_tasks) {
1815 soinfo* si = task->get_soinfo();
1816 if (!si->is_linked() && (si->get_dt_flags_1() & DF_1_GLOBAL) != 0) {
1817 new_global_group_members.push_back(si);
1818 }
1819 }
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001820
Jiyong Park02586a22017-05-20 01:01:24 +09001821 // Step 4-3: Add the new global group members to all the linked namespaces
Jiyong Park01162f22017-10-16 15:31:09 +09001822 if (namespaces != nullptr) {
Jiyong Park02586a22017-05-20 01:01:24 +09001823 for (auto linked_ns : *namespaces) {
Jiyong Park01162f22017-10-16 15:31:09 +09001824 for (auto si : new_global_group_members) {
1825 if (si->get_primary_namespace() != linked_ns) {
1826 linked_ns->add_soinfo(si);
1827 si->add_secondary_namespace(linked_ns);
1828 }
Jiyong Park02586a22017-05-20 01:01:24 +09001829 }
1830 }
1831 }
1832
dimitry965d06d2017-11-28 16:03:07 +01001833 // Step 5: Collect roots of local_groups.
1834 // Whenever needed_by->si link crosses a namespace boundary it forms its own local_group.
1835 // Here we collect new roots to link them separately later on. Note that we need to avoid
1836 // collecting duplicates. Also the order is important. They need to be linked in the same
1837 // BFS order we link individual libraries.
1838 std::vector<soinfo*> local_group_roots;
1839 if (start_with != nullptr && add_as_children) {
1840 local_group_roots.push_back(start_with);
1841 } else {
1842 CHECK(soinfos_count == 1);
1843 local_group_roots.push_back(soinfos[0]);
1844 }
1845
Jiyong Park02586a22017-05-20 01:01:24 +09001846 for (auto&& task : load_tasks) {
1847 soinfo* si = task->get_soinfo();
dimitry965d06d2017-11-28 16:03:07 +01001848 soinfo* needed_by = task->get_needed_by();
1849 bool is_dt_needed = needed_by != nullptr && (needed_by != start_with || add_as_children);
1850 android_namespace_t* needed_by_ns =
1851 is_dt_needed ? needed_by->get_primary_namespace() : ns;
1852
1853 if (!si->is_linked() && si->get_primary_namespace() != needed_by_ns) {
1854 auto it = std::find(local_group_roots.begin(), local_group_roots.end(), si);
1855 LD_LOG(kLogDlopen,
1856 "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",
1857 si->get_realpath(),
1858 si,
1859 si->get_primary_namespace()->get_name(),
1860 si->get_primary_namespace(),
1861 needed_by == nullptr ? "(nullptr)" : needed_by->get_realpath(),
1862 needed_by,
1863 ns->get_name(),
1864 ns,
1865 needed_by_ns->get_name(),
1866 needed_by_ns,
1867 it == local_group_roots.end() ? "yes" : "no");
1868
1869 if (it == local_group_roots.end()) {
1870 local_group_roots.push_back(si);
Jiyong Park02586a22017-05-20 01:01:24 +09001871 }
1872 }
1873 }
1874
dimitry965d06d2017-11-28 16:03:07 +01001875 // Step 6: Link all local groups
1876 for (auto root : local_group_roots) {
1877 soinfo_list_t local_group;
1878 android_namespace_t* local_group_ns = root->get_primary_namespace();
1879
1880 walk_dependencies_tree(root,
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -07001881 [&] (soinfo* si) {
dimitry965d06d2017-11-28 16:03:07 +01001882 if (local_group_ns->is_accessible(si)) {
1883 local_group.push_back(si);
1884 return kWalkContinue;
1885 } else {
1886 return kWalkSkip;
1887 }
1888 });
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -07001889
dimitry965d06d2017-11-28 16:03:07 +01001890 soinfo_list_t global_group = local_group_ns->get_global_group();
1891 bool linked = local_group.visit([&](soinfo* si) {
Torne (Richard Coles)5d103742019-04-11 12:25:06 -04001892 // Even though local group may contain accessible soinfos from other namespaces
dimitry965d06d2017-11-28 16:03:07 +01001893 // we should avoid linking them (because if they are not linked -> they
1894 // are in the local_group_roots and will be linked later).
1895 if (!si->is_linked() && si->get_primary_namespace() == local_group_ns) {
Torne (Richard Coles)5d103742019-04-11 12:25:06 -04001896 const android_dlextinfo* link_extinfo = nullptr;
1897 if (si == soinfos[0] || reserved_address_recursive) {
1898 // Only forward extinfo for the first library unless the recursive
1899 // flag is set.
1900 link_extinfo = extinfo;
1901 }
1902 if (!si->link_image(global_group, local_group, link_extinfo, &relro_fd_offset) ||
dimitry965d06d2017-11-28 16:03:07 +01001903 !get_cfi_shadow()->AfterLoad(si, solist_get_head())) {
1904 return false;
1905 }
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001906 }
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -07001907
dimitry965d06d2017-11-28 16:03:07 +01001908 return true;
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001909 });
Elliott Hughes27f18062017-11-29 18:47:42 +00001910
dimitry965d06d2017-11-28 16:03:07 +01001911 if (!linked) {
1912 return false;
1913 }
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001914 }
1915
dimitry965d06d2017-11-28 16:03:07 +01001916 // Step 7: Mark all load_tasks as linked and increment refcounts
1917 // for references between load_groups (at this point it does not matter if
1918 // referenced load_groups were loaded by previous dlopen or as part of this
1919 // one on step 6)
1920 if (start_with != nullptr && add_as_children) {
1921 start_with->set_linked();
1922 }
1923
1924 for (auto&& task : load_tasks) {
1925 soinfo* si = task->get_soinfo();
1926 si->set_linked();
1927 }
1928
1929 for (auto&& task : load_tasks) {
1930 soinfo* si = task->get_soinfo();
1931 soinfo* needed_by = task->get_needed_by();
1932 if (needed_by != nullptr &&
1933 needed_by != start_with &&
1934 needed_by->get_local_group_root() != si->get_local_group_root()) {
1935 si->increment_ref_count();
1936 }
1937 }
1938
1939
1940 return true;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001941}
1942
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001943static soinfo* find_library(android_namespace_t* ns,
1944 const char* name, int rtld_flags,
Evgenii Stepanov0cdef7e2015-07-06 17:56:31 -07001945 const android_dlextinfo* extinfo,
1946 soinfo* needed_by) {
dimitry965d06d2017-11-28 16:03:07 +01001947 soinfo* si = nullptr;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001948
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08001949 if (name == nullptr) {
Dimitry Ivanov3f660572016-09-09 10:00:39 -07001950 si = solist_get_somain();
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001951 } else if (!find_libraries(ns,
1952 needed_by,
1953 &name,
1954 1,
1955 &si,
1956 nullptr,
1957 0,
1958 rtld_flags,
1959 extinfo,
1960 false /* add_as_children */,
dimitry965d06d2017-11-28 16:03:07 +01001961 true /* search_linked_namespaces */)) {
1962 if (si != nullptr) {
1963 soinfo_unload(si);
1964 }
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001965 return nullptr;
1966 }
1967
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001968 si->increment_ref_count();
1969
Elliott Hughesd23736e2012-11-01 15:16:56 -07001970 return si;
1971}
Elliott Hughesbedfe382012-08-14 14:07:59 -07001972
dimitry06016f22018-01-05 11:39:28 +01001973static void soinfo_unload_impl(soinfo* root) {
Dimitry Ivanov6705e8c2017-03-21 10:29:06 -07001974 ScopedTrace trace((std::string("unload ") + root->get_realpath()).c_str());
dimitry06016f22018-01-05 11:39:28 +01001975 bool is_linked = root->is_linked();
Dimitry Ivanov6705e8c2017-03-21 10:29:06 -07001976
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08001977 if (!root->can_unload()) {
dimitryc92ce712017-10-27 14:12:53 +02001978 LD_LOG(kLogDlopen,
1979 "... dlclose(root=\"%s\"@%p) ... not unloading - the load group is flagged with NODELETE",
1980 root->get_realpath(),
1981 root);
Dmitriy Ivanov1b20daf2014-05-19 15:06:58 -07001982 return;
1983 }
1984
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08001985
Dimitry Ivanovb943f302016-08-03 16:00:10 -07001986 soinfo_list_t unload_list;
dimitry965d06d2017-11-28 16:03:07 +01001987 unload_list.push_back(root);
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001988
Dimitry Ivanovb943f302016-08-03 16:00:10 -07001989 soinfo_list_t local_unload_list;
1990 soinfo_list_t external_unload_list;
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001991 soinfo* si = nullptr;
1992
1993 while ((si = unload_list.pop_front()) != nullptr) {
1994 if (local_unload_list.contains(si)) {
1995 continue;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001996 }
Elliott Hughesd23736e2012-11-01 15:16:56 -07001997
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001998 local_unload_list.push_back(si);
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08001999
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07002000 if (si->has_min_version(0)) {
2001 soinfo* child = nullptr;
2002 while ((child = si->get_children().pop_front()) != nullptr) {
2003 TRACE("%s@%p needs to unload %s@%p", si->get_realpath(), si,
2004 child->get_realpath(), child);
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08002005
Dimitry Ivanovec90e242017-02-10 11:04:20 -08002006 child->get_parents().remove(si);
2007
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07002008 if (local_unload_list.contains(child)) {
2009 continue;
2010 } else if (child->is_linked() && child->get_local_group_root() != root) {
2011 external_unload_list.push_back(child);
Dimitry Ivanovec90e242017-02-10 11:04:20 -08002012 } else if (child->get_parents().empty()) {
2013 unload_list.push_back(child);
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07002014 }
2015 }
2016 } else {
Christopher Ferris7a3681e2017-04-24 17:48:32 -07002017 async_safe_fatal("soinfo for \"%s\"@%p has no version", si->get_realpath(), si);
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08002018 }
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07002019 }
2020
2021 local_unload_list.for_each([](soinfo* si) {
dimitryc92ce712017-10-27 14:12:53 +02002022 LD_LOG(kLogDlopen,
2023 "... dlclose: calling destructors for \"%s\"@%p ... ",
2024 si->get_realpath(),
2025 si);
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07002026 si->call_destructors();
dimitryc92ce712017-10-27 14:12:53 +02002027 LD_LOG(kLogDlopen,
2028 "... dlclose: calling destructors for \"%s\"@%p ... done",
2029 si->get_realpath(),
2030 si);
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07002031 });
2032
2033 while ((si = local_unload_list.pop_front()) != nullptr) {
dimitryc92ce712017-10-27 14:12:53 +02002034 LD_LOG(kLogDlopen,
2035 "... dlclose: unloading \"%s\"@%p ...",
2036 si->get_realpath(),
2037 si);
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07002038 notify_gdb_of_unload(si);
Ryan Pricharde5e69e02019-01-01 18:53:48 -08002039 unregister_soinfo_tls(si);
Evgenii Stepanov0a3637d2016-07-06 13:20:59 -07002040 get_cfi_shadow()->BeforeUnload(si);
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07002041 soinfo_free(si);
2042 }
2043
dimitry965d06d2017-11-28 16:03:07 +01002044 if (is_linked) {
2045 while ((si = external_unload_list.pop_front()) != nullptr) {
2046 LD_LOG(kLogDlopen,
2047 "... dlclose: unloading external reference \"%s\"@%p ...",
2048 si->get_realpath(),
2049 si);
2050 soinfo_unload(si);
2051 }
2052 } else {
2053 LD_LOG(kLogDlopen,
2054 "... dlclose: unload_si was not linked - not unloading external references ...");
Dmitriy Ivanova2547052014-11-18 12:03:09 -08002055 }
2056}
2057
dimitry06016f22018-01-05 11:39:28 +01002058static void soinfo_unload(soinfo* unload_si) {
2059 // Note that the library can be loaded but not linked;
2060 // in which case there is no root but we still need
2061 // to walk the tree and unload soinfos involved.
2062 //
2063 // This happens on unsuccessful dlopen, when one of
2064 // the DT_NEEDED libraries could not be linked/found.
2065 bool is_linked = unload_si->is_linked();
2066 soinfo* root = is_linked ? unload_si->get_local_group_root() : unload_si;
2067
2068 LD_LOG(kLogDlopen,
2069 "... dlclose(realpath=\"%s\"@%p) ... load group root is \"%s\"@%p",
2070 unload_si->get_realpath(),
2071 unload_si,
2072 root->get_realpath(),
2073 root);
2074
2075
2076 size_t ref_count = is_linked ? root->decrement_ref_count() : 0;
2077 if (ref_count > 0) {
2078 LD_LOG(kLogDlopen,
2079 "... dlclose(root=\"%s\"@%p) ... not unloading - decrementing ref_count to %zd",
2080 root->get_realpath(),
2081 root,
2082 ref_count);
2083 return;
2084 }
2085
2086 soinfo_unload_impl(root);
2087}
2088
2089void increment_dso_handle_reference_counter(void* dso_handle) {
2090 if (dso_handle == nullptr) {
2091 return;
2092 }
2093
2094 auto it = g_dso_handle_counters.find(dso_handle);
2095 if (it != g_dso_handle_counters.end()) {
2096 CHECK(++it->second != 0);
2097 } else {
2098 soinfo* si = find_containing_library(dso_handle);
2099 if (si != nullptr) {
2100 ProtectedDataGuard guard;
dimitry55547db2018-05-25 14:17:37 +02002101 si->increment_ref_count();
dimitry06016f22018-01-05 11:39:28 +01002102 } else {
2103 async_safe_fatal(
2104 "increment_dso_handle_reference_counter: Couldn't find soinfo by dso_handle=%p",
2105 dso_handle);
2106 }
2107 g_dso_handle_counters[dso_handle] = 1U;
2108 }
2109}
2110
2111void decrement_dso_handle_reference_counter(void* dso_handle) {
2112 if (dso_handle == nullptr) {
2113 return;
2114 }
2115
2116 auto it = g_dso_handle_counters.find(dso_handle);
2117 CHECK(it != g_dso_handle_counters.end());
2118 CHECK(it->second != 0);
2119
2120 if (--it->second == 0) {
2121 soinfo* si = find_containing_library(dso_handle);
2122 if (si != nullptr) {
2123 ProtectedDataGuard guard;
dimitry55547db2018-05-25 14:17:37 +02002124 soinfo_unload(si);
dimitry06016f22018-01-05 11:39:28 +01002125 } else {
2126 async_safe_fatal(
2127 "decrement_dso_handle_reference_counter: Couldn't find soinfo by dso_handle=%p",
2128 dso_handle);
2129 }
2130 g_dso_handle_counters.erase(it);
2131 }
2132}
2133
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002134static std::string symbol_display_name(const char* sym_name, const char* sym_ver) {
2135 if (sym_ver == nullptr) {
2136 return sym_name;
2137 }
2138
Dimitry Ivanov9cf99cb2015-12-11 14:22:24 -08002139 return std::string(sym_name) + ", version " + sym_ver;
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002140}
2141
Dimitry Ivanovaca299a2016-04-11 12:42:58 -07002142static android_namespace_t* get_caller_namespace(soinfo* caller) {
2143 return caller != nullptr ? caller->get_primary_namespace() : g_anonymous_namespace;
2144}
2145
Elliott Hughesa4aafd12014-01-13 16:37:47 -08002146void do_android_get_LD_LIBRARY_PATH(char* buffer, size_t buffer_size) {
Christopher Ferris052fa3a2014-08-26 20:48:11 -07002147 // Use basic string manipulation calls to avoid snprintf.
2148 // snprintf indirectly calls pthread_getspecific to get the size of a buffer.
2149 // When debug malloc is enabled, this call returns 0. This in turn causes
2150 // snprintf to do nothing, which causes libraries to fail to load.
2151 // See b/17302493 for further details.
2152 // Once the above bug is fixed, this code can be modified to use
2153 // snprintf again.
Dimitry Ivanov77ad6422017-03-06 13:02:29 -08002154 const auto& default_ld_paths = g_default_namespace.get_default_library_paths();
2155
2156 size_t required_size = 0;
2157 for (const auto& path : default_ld_paths) {
2158 required_size += path.size() + 1;
Evgenii Stepanovd640b222015-07-10 17:54:01 -07002159 }
Dimitry Ivanov77ad6422017-03-06 13:02:29 -08002160
2161 if (buffer_size < required_size) {
Christopher Ferris7a3681e2017-04-24 17:48:32 -07002162 async_safe_fatal("android_get_LD_LIBRARY_PATH failed, buffer too small: "
2163 "buffer len %zu, required len %zu", buffer_size, required_size);
Christopher Ferris052fa3a2014-08-26 20:48:11 -07002164 }
Dimitry Ivanov77ad6422017-03-06 13:02:29 -08002165
Evgenii Stepanovd640b222015-07-10 17:54:01 -07002166 char* end = buffer;
Dimitry Ivanov77ad6422017-03-06 13:02:29 -08002167 for (size_t i = 0; i < default_ld_paths.size(); ++i) {
Evgenii Stepanovd640b222015-07-10 17:54:01 -07002168 if (i > 0) *end++ = ':';
Dimitry Ivanov77ad6422017-03-06 13:02:29 -08002169 end = stpcpy(end, default_ld_paths[i].c_str());
Evgenii Stepanovd640b222015-07-10 17:54:01 -07002170 }
Elliott Hughesa4aafd12014-01-13 16:37:47 -08002171}
2172
Elliott Hughescade4c32012-12-20 14:42:14 -08002173void do_android_update_LD_LIBRARY_PATH(const char* ld_library_path) {
Nick Kralevich6bb01b62015-03-07 13:37:05 -08002174 parse_LD_LIBRARY_PATH(ld_library_path);
Elliott Hughescade4c32012-12-20 14:42:14 -08002175}
2176
Dimitry Ivanovb996d602016-07-11 18:11:39 -07002177static std::string android_dlextinfo_to_string(const android_dlextinfo* info) {
2178 if (info == nullptr) {
2179 return "(null)";
2180 }
2181
2182 return android::base::StringPrintf("[flags=0x%" PRIx64 ","
2183 " reserved_addr=%p,"
2184 " reserved_size=0x%zx,"
2185 " relro_fd=%d,"
2186 " library_fd=%d,"
2187 " library_fd_offset=0x%" PRIx64 ","
2188 " library_namespace=%s@%p]",
2189 info->flags,
2190 info->reserved_addr,
2191 info->reserved_size,
2192 info->relro_fd,
2193 info->library_fd,
2194 info->library_fd_offset,
2195 (info->flags & ANDROID_DLEXT_USE_NAMESPACE) != 0 ?
2196 (info->library_namespace != nullptr ?
2197 info->library_namespace->get_name() : "(null)") : "(n/a)",
2198 (info->flags & ANDROID_DLEXT_USE_NAMESPACE) != 0 ?
2199 info->library_namespace : nullptr);
2200}
2201
Dimitry Ivanovd9e427c2016-11-22 16:55:25 -08002202void* do_dlopen(const char* name, int flags,
2203 const android_dlextinfo* extinfo,
2204 const void* caller_addr) {
Dimitry Ivanov5c4a5802017-03-17 16:41:34 -07002205 std::string trace_prefix = std::string("dlopen: ") + (name == nullptr ? "(nullptr)" : name);
2206 ScopedTrace trace(trace_prefix.c_str());
2207 ScopedTrace loading_trace((trace_prefix + " - loading and linking").c_str());
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002208 soinfo* const caller = find_containing_library(caller_addr);
Dimitry Ivanovb996d602016-07-11 18:11:39 -07002209 android_namespace_t* ns = get_caller_namespace(caller);
2210
2211 LD_LOG(kLogDlopen,
Victor Chang6cb719f2019-02-06 17:19:10 +00002212 "dlopen(name=\"%s\", flags=0x%x, extinfo=%s, caller=\"%s\", caller_ns=%s@%p, targetSdkVersion=%i) ...",
Dimitry Ivanovb996d602016-07-11 18:11:39 -07002213 name,
2214 flags,
2215 android_dlextinfo_to_string(extinfo).c_str(),
2216 caller == nullptr ? "(null)" : caller->get_realpath(),
2217 ns == nullptr ? "(null)" : ns->get_name(),
Victor Chang6cb719f2019-02-06 17:19:10 +00002218 ns,
2219 get_application_target_sdk_version());
Dimitry Ivanovb996d602016-07-11 18:11:39 -07002220
Vic Yangbb7e1232019-01-29 20:23:16 -08002221 auto purge_guard = android::base::make_scope_guard([&]() { purge_unused_memory(); });
2222
Tom Cherryb8ab6182017-04-05 16:20:29 -07002223 auto failure_guard = android::base::make_scope_guard(
2224 [&]() { LD_LOG(kLogDlopen, "... dlopen failed: %s", linker_get_error_buffer()); });
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002225
Dmitriy Ivanov1b20daf2014-05-19 15:06:58 -07002226 if ((flags & ~(RTLD_NOW|RTLD_LAZY|RTLD_LOCAL|RTLD_GLOBAL|RTLD_NODELETE|RTLD_NOLOAD)) != 0) {
Elliott Hughese66190d2012-12-18 15:57:55 -08002227 DL_ERR("invalid flags to dlopen: %x", flags);
Dmitriy Ivanov851135b2014-08-29 12:02:36 -07002228 return nullptr;
Elliott Hughese66190d2012-12-18 15:57:55 -08002229 }
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002230
Dmitriy Ivanov07e5bc12014-10-03 17:52:44 -07002231 if (extinfo != nullptr) {
2232 if ((extinfo->flags & ~(ANDROID_DLEXT_VALID_FLAG_BITS)) != 0) {
2233 DL_ERR("invalid extended flags to android_dlopen_ext: 0x%" PRIx64, extinfo->flags);
2234 return nullptr;
2235 }
Dmitriy Ivanov126af752015-10-07 16:34:20 -07002236
Dmitriy Ivanov07e5bc12014-10-03 17:52:44 -07002237 if ((extinfo->flags & ANDROID_DLEXT_USE_LIBRARY_FD) == 0 &&
Dmitriy Ivanova6c12792014-10-21 12:09:18 -07002238 (extinfo->flags & ANDROID_DLEXT_USE_LIBRARY_FD_OFFSET) != 0) {
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07002239 DL_ERR("invalid extended flag combination (ANDROID_DLEXT_USE_LIBRARY_FD_OFFSET without "
2240 "ANDROID_DLEXT_USE_LIBRARY_FD): 0x%" PRIx64, extinfo->flags);
Dmitriy Ivanov07e5bc12014-10-03 17:52:44 -07002241 return nullptr;
2242 }
Dmitriy Ivanov126af752015-10-07 16:34:20 -07002243
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002244 if ((extinfo->flags & ANDROID_DLEXT_USE_NAMESPACE) != 0) {
2245 if (extinfo->library_namespace == nullptr) {
2246 DL_ERR("ANDROID_DLEXT_USE_NAMESPACE is set but extinfo->library_namespace is null");
2247 return nullptr;
2248 }
2249 ns = extinfo->library_namespace;
2250 }
Torne (Richard Coles)012cb452014-02-06 14:34:21 +00002251 }
Dmitriy Ivanov279a22f2015-01-23 12:03:53 -08002252
Victor Chang6cb719f2019-02-06 17:19:10 +00002253 // Workaround for dlopen(/system/lib/<soname>) when .so is in /apex. http://b/121248172
2254 // The workaround works only when targetSdkVersion < Q.
2255 std::string name_to_apex;
2256 if (translateSystemPathToApexPath(name, &name_to_apex)) {
2257 const char* new_name = name_to_apex.c_str();
2258 LD_LOG(kLogDlopen, "dlopen considering translation from %s to APEX path %s",
2259 name,
2260 new_name);
2261 // Some APEXs could be optionally disabled. Only translate the path
2262 // when the old file is absent and the new file exists.
Victor Changaf12c942019-02-11 19:35:24 +00002263 // TODO(b/124218500): Re-enable it once app compat issue is resolved
2264 /*
Victor Chang6cb719f2019-02-06 17:19:10 +00002265 if (file_exists(name)) {
2266 LD_LOG(kLogDlopen, "dlopen %s exists, not translating", name);
Victor Changaf12c942019-02-11 19:35:24 +00002267 } else
2268 */
2269 if (!file_exists(new_name)) {
Victor Chang6cb719f2019-02-06 17:19:10 +00002270 LD_LOG(kLogDlopen, "dlopen %s does not exist, not translating",
2271 new_name);
2272 } else {
2273 LD_LOG(kLogDlopen, "dlopen translation accepted: using %s", new_name);
2274 name = new_name;
2275 }
2276 }
2277 // End Workaround for dlopen(/system/lib/<soname>) when .so is in /apex.
2278
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -07002279 std::string asan_name_holder;
2280
2281 const char* translated_name = name;
Dimitry Ivanov6c14f862016-12-05 13:35:47 -08002282 if (g_is_asan && translated_name != nullptr && translated_name[0] == '/') {
Evgenii Stepanov9e77a642017-07-27 14:55:44 -07002283 char original_path[PATH_MAX];
2284 if (realpath(name, original_path) != nullptr) {
2285 asan_name_holder = std::string(kAsanLibDirPrefix) + original_path;
Vishwath Mohan4113def2017-03-29 15:31:34 -07002286 if (file_exists(asan_name_holder.c_str())) {
Evgenii Stepanov9e77a642017-07-27 14:55:44 -07002287 soinfo* si = nullptr;
2288 if (find_loaded_library_by_realpath(ns, original_path, true, &si)) {
2289 PRINT("linker_asan dlopen NOT translating \"%s\" -> \"%s\": library already loaded", name,
2290 asan_name_holder.c_str());
2291 } else {
2292 PRINT("linker_asan dlopen translating \"%s\" -> \"%s\"", name, translated_name);
2293 translated_name = asan_name_holder.c_str();
2294 }
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -07002295 }
2296 }
2297 }
2298
Dmitriy Ivanov279a22f2015-01-23 12:03:53 -08002299 ProtectedDataGuard guard;
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -07002300 soinfo* si = find_library(ns, translated_name, flags, extinfo, caller);
Dimitry Ivanov5c4a5802017-03-17 16:41:34 -07002301 loading_trace.End();
2302
Dmitriy Ivanov851135b2014-08-29 12:02:36 -07002303 if (si != nullptr) {
Dimitry Ivanovb996d602016-07-11 18:11:39 -07002304 void* handle = si->to_handle();
2305 LD_LOG(kLogDlopen,
Dimitry Ivanovae4a0c12016-11-21 10:44:35 -08002306 "... dlopen calling constructors: realpath=\"%s\", soname=\"%s\", handle=%p",
2307 si->get_realpath(), si->get_soname(), handle);
2308 si->call_constructors();
Tom Cherryb8ab6182017-04-05 16:20:29 -07002309 failure_guard.Disable();
Dimitry Ivanovae4a0c12016-11-21 10:44:35 -08002310 LD_LOG(kLogDlopen,
Dimitry Ivanovb996d602016-07-11 18:11:39 -07002311 "... dlopen successful: realpath=\"%s\", soname=\"%s\", handle=%p",
2312 si->get_realpath(), si->get_soname(), handle);
2313 return handle;
Elliott Hughesd23736e2012-11-01 15:16:56 -07002314 }
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002315
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -07002316 return nullptr;
Elliott Hughesd23736e2012-11-01 15:16:56 -07002317}
2318
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002319int do_dladdr(const void* addr, Dl_info* info) {
2320 // Determine if this address can be found in any library currently mapped.
2321 soinfo* si = find_containing_library(addr);
2322 if (si == nullptr) {
2323 return 0;
2324 }
2325
2326 memset(info, 0, sizeof(Dl_info));
2327
2328 info->dli_fname = si->get_realpath();
2329 // Address at which the shared object is loaded.
2330 info->dli_fbase = reinterpret_cast<void*>(si->base);
2331
2332 // Determine if any symbol in the library contains the specified address.
2333 ElfW(Sym)* sym = si->find_symbol_by_address(addr);
2334 if (sym != nullptr) {
2335 info->dli_sname = si->get_string(sym->st_name);
2336 info->dli_saddr = reinterpret_cast<void*>(si->resolve_symbol_address(sym));
2337 }
2338
2339 return 1;
2340}
2341
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -07002342static soinfo* soinfo_from_handle(void* handle) {
2343 if ((reinterpret_cast<uintptr_t>(handle) & 1) != 0) {
2344 auto it = g_soinfo_handles_map.find(reinterpret_cast<uintptr_t>(handle));
2345 if (it == g_soinfo_handles_map.end()) {
2346 return nullptr;
2347 } else {
2348 return it->second;
2349 }
2350 }
2351
2352 return static_cast<soinfo*>(handle);
2353}
2354
Dimitry Ivanovd9e427c2016-11-22 16:55:25 -08002355bool do_dlsym(void* handle,
2356 const char* sym_name,
2357 const char* sym_ver,
2358 const void* caller_addr,
2359 void** symbol) {
Dimitry Ivanov6705e8c2017-03-21 10:29:06 -07002360 ScopedTrace trace("dlsym");
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002361#if !defined(__LP64__)
2362 if (handle == nullptr) {
2363 DL_ERR("dlsym failed: library handle is null");
2364 return false;
2365 }
2366#endif
2367
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002368 soinfo* found = nullptr;
2369 const ElfW(Sym)* sym = nullptr;
2370 soinfo* caller = find_containing_library(caller_addr);
Dimitry Ivanovaca299a2016-04-11 12:42:58 -07002371 android_namespace_t* ns = get_caller_namespace(caller);
Dimitry Ivanov4742abd2016-12-12 16:30:15 -08002372 soinfo* si = nullptr;
2373 if (handle != RTLD_DEFAULT && handle != RTLD_NEXT) {
2374 si = soinfo_from_handle(handle);
2375 }
2376
2377 LD_LOG(kLogDlsym,
2378 "dlsym(handle=%p(\"%s\"), sym_name=\"%s\", sym_ver=\"%s\", caller=\"%s\", caller_ns=%s@%p) ...",
2379 handle,
2380 si != nullptr ? si->get_realpath() : "n/a",
2381 sym_name,
2382 sym_ver,
2383 caller == nullptr ? "(null)" : caller->get_realpath(),
2384 ns == nullptr ? "(null)" : ns->get_name(),
2385 ns);
2386
Tom Cherryb8ab6182017-04-05 16:20:29 -07002387 auto failure_guard = android::base::make_scope_guard(
2388 [&]() { LD_LOG(kLogDlsym, "... dlsym failed: %s", linker_get_error_buffer()); });
Dimitry Ivanov4742abd2016-12-12 16:30:15 -08002389
2390 if (sym_name == nullptr) {
2391 DL_ERR("dlsym failed: symbol name is null");
2392 return false;
2393 }
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002394
2395 version_info vi_instance;
2396 version_info* vi = nullptr;
2397
2398 if (sym_ver != nullptr) {
Dimitry Ivanov9cf99cb2015-12-11 14:22:24 -08002399 vi_instance.name = sym_ver;
2400 vi_instance.elf_hash = calculate_elf_hash(sym_ver);
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002401 vi = &vi_instance;
2402 }
2403
2404 if (handle == RTLD_DEFAULT || handle == RTLD_NEXT) {
2405 sym = dlsym_linear_lookup(ns, sym_name, vi, &found, caller, handle);
2406 } else {
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -07002407 if (si == nullptr) {
2408 DL_ERR("dlsym failed: invalid handle: %p", handle);
2409 return false;
2410 }
2411 sym = dlsym_handle_lookup(si, &found, sym_name, vi);
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002412 }
2413
2414 if (sym != nullptr) {
2415 uint32_t bind = ELF_ST_BIND(sym->st_info);
Ryan Pricharde4d620b2019-04-01 17:42:14 -07002416 uint32_t type = ELF_ST_TYPE(sym->st_info);
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002417
2418 if ((bind == STB_GLOBAL || bind == STB_WEAK) && sym->st_shndx != 0) {
Ryan Pricharde4d620b2019-04-01 17:42:14 -07002419 if (type == STT_TLS) {
2420 // For a TLS symbol, dlsym returns the address of the current thread's
2421 // copy of the symbol. This function may allocate a DTV and/or storage
2422 // for the source TLS module. (Allocating a DTV isn't necessary if the
2423 // symbol is part of static TLS, but it's simpler to reuse
2424 // __tls_get_addr.)
2425 soinfo_tls* tls_module = found->get_tls();
2426 if (tls_module == nullptr) {
2427 DL_ERR("TLS symbol \"%s\" in solib \"%s\" with no TLS segment",
2428 sym_name, found->get_realpath());
2429 return false;
2430 }
2431 const TlsIndex ti { tls_module->module_id, sym->st_value };
2432 *symbol = TLS_GET_ADDR(&ti);
2433 } else {
2434 *symbol = reinterpret_cast<void*>(found->resolve_symbol_address(sym));
2435 }
Tom Cherryb8ab6182017-04-05 16:20:29 -07002436 failure_guard.Disable();
Dimitry Ivanov4742abd2016-12-12 16:30:15 -08002437 LD_LOG(kLogDlsym,
2438 "... dlsym successful: sym_name=\"%s\", sym_ver=\"%s\", found in=\"%s\", address=%p",
2439 sym_name, sym_ver, found->get_soname(), *symbol);
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002440 return true;
2441 }
2442
2443 DL_ERR("symbol \"%s\" found but not global", symbol_display_name(sym_name, sym_ver).c_str());
2444 return false;
2445 }
2446
2447 DL_ERR("undefined symbol: %s", symbol_display_name(sym_name, sym_ver).c_str());
2448 return false;
2449}
2450
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -07002451int do_dlclose(void* handle) {
Dimitry Ivanov6705e8c2017-03-21 10:29:06 -07002452 ScopedTrace trace("dlclose");
Dmitriy Ivanov279a22f2015-01-23 12:03:53 -08002453 ProtectedDataGuard guard;
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -07002454 soinfo* si = soinfo_from_handle(handle);
2455 if (si == nullptr) {
2456 DL_ERR("invalid handle: %p", handle);
2457 return -1;
2458 }
2459
dimitryc92ce712017-10-27 14:12:53 +02002460 LD_LOG(kLogDlopen,
2461 "dlclose(handle=%p, realpath=\"%s\"@%p) ...",
2462 handle,
2463 si->get_realpath(),
2464 si);
Dmitriy Ivanovb648a8a2014-05-19 15:06:58 -07002465 soinfo_unload(si);
dimitryc92ce712017-10-27 14:12:53 +02002466 LD_LOG(kLogDlopen,
2467 "dlclose(handle=%p) ... done",
2468 handle);
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -07002469 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002470}
2471
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -08002472bool init_anonymous_namespace(const char* shared_lib_sonames, const char* library_search_path) {
2473 if (g_anonymous_namespace_initialized) {
2474 DL_ERR("anonymous namespace has already been initialized.");
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002475 return false;
2476 }
2477
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002478 ProtectedDataGuard guard;
2479
Dmitriy Ivanov1ffec1c2015-11-23 11:26:35 -08002480 // create anonymous namespace
Dimitry Ivanov7331fe12015-12-14 14:11:17 -08002481 // When the caller is nullptr - create_namespace will take global group
2482 // from the anonymous namespace, which is fine because anonymous namespace
2483 // is still pointing to the default one.
Dmitriy Ivanov1ffec1c2015-11-23 11:26:35 -08002484 android_namespace_t* anon_ns =
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -08002485 create_namespace(nullptr,
2486 "(anonymous)",
2487 nullptr,
2488 library_search_path,
Dimitry Ivanovc9dced22017-03-27 15:42:17 -07002489 ANDROID_NAMESPACE_TYPE_ISOLATED,
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -08002490 nullptr,
2491 &g_default_namespace);
Dmitriy Ivanov1ffec1c2015-11-23 11:26:35 -08002492
2493 if (anon_ns == nullptr) {
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -08002494 return false;
2495 }
2496
2497 if (!link_namespaces(anon_ns, &g_default_namespace, shared_lib_sonames)) {
Dmitriy Ivanov1ffec1c2015-11-23 11:26:35 -08002498 return false;
2499 }
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08002500
Dmitriy Ivanov1ffec1c2015-11-23 11:26:35 -08002501 g_anonymous_namespace = anon_ns;
Dimitry Ivanov3e0821d2017-03-07 11:02:10 -08002502 g_anonymous_namespace_initialized = true;
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -08002503
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002504 return true;
2505}
2506
Dimitry Ivanovb943f302016-08-03 16:00:10 -07002507static void add_soinfos_to_namespace(const soinfo_list_t& soinfos, android_namespace_t* ns) {
2508 ns->add_soinfos(soinfos);
2509 for (auto si : soinfos) {
2510 si->add_secondary_namespace(ns);
2511 }
2512}
2513
Dimitry Ivanov7331fe12015-12-14 14:11:17 -08002514android_namespace_t* create_namespace(const void* caller_addr,
2515 const char* name,
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002516 const char* ld_library_path,
2517 const char* default_library_path,
Dimitry Ivanov7331fe12015-12-14 14:11:17 -08002518 uint64_t type,
Dimitry Ivanovfc2da532016-05-12 15:20:21 -07002519 const char* permitted_when_isolated_path,
2520 android_namespace_t* parent_namespace) {
Dimitry Ivanovfc2da532016-05-12 15:20:21 -07002521 if (parent_namespace == nullptr) {
Dimitry Ivanov52408632016-05-23 10:31:11 -07002522 // if parent_namespace is nullptr -> set it to the caller namespace
2523 soinfo* caller_soinfo = find_containing_library(caller_addr);
2524
2525 parent_namespace = caller_soinfo != nullptr ?
2526 caller_soinfo->get_primary_namespace() :
2527 g_anonymous_namespace;
Dimitry Ivanovfc2da532016-05-12 15:20:21 -07002528 }
2529
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002530 ProtectedDataGuard guard;
2531 std::vector<std::string> ld_library_paths;
2532 std::vector<std::string> default_library_paths;
Dimitry Ivanov284ae352015-12-08 10:47:13 -08002533 std::vector<std::string> permitted_paths;
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002534
2535 parse_path(ld_library_path, ":", &ld_library_paths);
2536 parse_path(default_library_path, ":", &default_library_paths);
Dimitry Ivanov284ae352015-12-08 10:47:13 -08002537 parse_path(permitted_when_isolated_path, ":", &permitted_paths);
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002538
2539 android_namespace_t* ns = new (g_namespace_allocator.alloc()) android_namespace_t();
2540 ns->set_name(name);
Dimitry Ivanov7331fe12015-12-14 14:11:17 -08002541 ns->set_isolated((type & ANDROID_NAMESPACE_TYPE_ISOLATED) != 0);
Jiyong Park37b91af2017-05-05 22:07:05 +09002542 ns->set_greylist_enabled((type & ANDROID_NAMESPACE_TYPE_GREYLIST_ENABLED) != 0);
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002543
Dimitry Ivanov7331fe12015-12-14 14:11:17 -08002544 if ((type & ANDROID_NAMESPACE_TYPE_SHARED) != 0) {
Dimitry Ivanovf1cb6692017-05-01 17:45:38 -07002545 // append parent namespace paths.
2546 std::copy(parent_namespace->get_ld_library_paths().begin(),
2547 parent_namespace->get_ld_library_paths().end(),
2548 back_inserter(ld_library_paths));
2549
2550 std::copy(parent_namespace->get_default_library_paths().begin(),
2551 parent_namespace->get_default_library_paths().end(),
2552 back_inserter(default_library_paths));
2553
2554 std::copy(parent_namespace->get_permitted_paths().begin(),
2555 parent_namespace->get_permitted_paths().end(),
2556 back_inserter(permitted_paths));
2557
Dimitry Ivanovfc2da532016-05-12 15:20:21 -07002558 // If shared - clone the parent namespace
Dimitry Ivanovb943f302016-08-03 16:00:10 -07002559 add_soinfos_to_namespace(parent_namespace->soinfo_list(), ns);
Dimitry Ivanovf1cb6692017-05-01 17:45:38 -07002560 // and copy parent namespace links
2561 for (auto& link : parent_namespace->linked_namespaces()) {
Logan Chien9ee45912018-01-18 12:05:09 +08002562 ns->add_linked_namespace(link.linked_namespace(), link.shared_lib_sonames(),
2563 link.allow_all_shared_libs());
Dimitry Ivanovf1cb6692017-05-01 17:45:38 -07002564 }
Dimitry Ivanov7331fe12015-12-14 14:11:17 -08002565 } else {
Dimitry Ivanovfc2da532016-05-12 15:20:21 -07002566 // If not shared - copy only the shared group
Jiyong Park02586a22017-05-20 01:01:24 +09002567 add_soinfos_to_namespace(parent_namespace->get_shared_group(), ns);
Dimitry Ivanov7331fe12015-12-14 14:11:17 -08002568 }
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002569
Dimitry Ivanovf1cb6692017-05-01 17:45:38 -07002570 ns->set_ld_library_paths(std::move(ld_library_paths));
2571 ns->set_default_library_paths(std::move(default_library_paths));
2572 ns->set_permitted_paths(std::move(permitted_paths));
2573
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002574 return ns;
2575}
2576
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -08002577bool link_namespaces(android_namespace_t* namespace_from,
2578 android_namespace_t* namespace_to,
2579 const char* shared_lib_sonames) {
2580 if (namespace_to == nullptr) {
2581 namespace_to = &g_default_namespace;
2582 }
2583
2584 if (namespace_from == nullptr) {
2585 DL_ERR("error linking namespaces: namespace_from is null.");
2586 return false;
2587 }
2588
2589 if (shared_lib_sonames == nullptr || shared_lib_sonames[0] == '\0') {
2590 DL_ERR("error linking namespaces \"%s\"->\"%s\": the list of shared libraries is empty.",
2591 namespace_from->get_name(), namespace_to->get_name());
2592 return false;
2593 }
2594
2595 auto sonames = android::base::Split(shared_lib_sonames, ":");
2596 std::unordered_set<std::string> sonames_set(sonames.begin(), sonames.end());
2597
2598 ProtectedDataGuard guard;
Logan Chien9ee45912018-01-18 12:05:09 +08002599 namespace_from->add_linked_namespace(namespace_to, sonames_set, false);
2600
2601 return true;
2602}
2603
2604bool link_namespaces_all_libs(android_namespace_t* namespace_from,
2605 android_namespace_t* namespace_to) {
2606 if (namespace_from == nullptr) {
2607 DL_ERR("error linking namespaces: namespace_from is null.");
2608 return false;
2609 }
2610
2611 if (namespace_to == nullptr) {
2612 DL_ERR("error linking namespaces: namespace_to is null.");
2613 return false;
2614 }
2615
2616 ProtectedDataGuard guard;
2617 namespace_from->add_linked_namespace(namespace_to, std::unordered_set<std::string>(), true);
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -08002618
2619 return true;
2620}
2621
Dimitry Ivanov48ec2882016-08-04 11:50:36 -07002622ElfW(Addr) call_ifunc_resolver(ElfW(Addr) resolver_addr) {
Elliott Hughes90f96b92019-05-09 15:56:39 -07002623 if (g_is_ldd) return 0;
2624
Dmitriy Ivanov9aea1642014-09-11 15:16:03 -07002625 typedef ElfW(Addr) (*ifunc_resolver_t)(void);
2626 ifunc_resolver_t ifunc_resolver = reinterpret_cast<ifunc_resolver_t>(resolver_addr);
2627 ElfW(Addr) ifunc_addr = ifunc_resolver();
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07002628 TRACE_TYPE(RELO, "Called ifunc_resolver@%p. The result is %p",
2629 ifunc_resolver, reinterpret_cast<void*>(ifunc_addr));
Brigid Smithc5a13ef2014-07-23 11:22:25 -07002630
Dmitriy Ivanov9aea1642014-09-11 15:16:03 -07002631 return ifunc_addr;
Brigid Smithc5a13ef2014-07-23 11:22:25 -07002632}
Brigid Smithc5a13ef2014-07-23 11:22:25 -07002633
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07002634const version_info* VersionTracker::get_version_info(ElfW(Versym) source_symver) const {
2635 if (source_symver < 2 ||
2636 source_symver >= version_infos.size() ||
2637 version_infos[source_symver].name == nullptr) {
2638 return nullptr;
2639 }
2640
2641 return &version_infos[source_symver];
2642}
2643
2644void VersionTracker::add_version_info(size_t source_index,
2645 ElfW(Word) elf_hash,
2646 const char* ver_name,
2647 const soinfo* target_si) {
2648 if (source_index >= version_infos.size()) {
2649 version_infos.resize(source_index+1);
2650 }
2651
2652 version_infos[source_index].elf_hash = elf_hash;
2653 version_infos[source_index].name = ver_name;
2654 version_infos[source_index].target_si = target_si;
2655}
2656
2657bool VersionTracker::init_verneed(const soinfo* si_from) {
2658 uintptr_t verneed_ptr = si_from->get_verneed_ptr();
2659
2660 if (verneed_ptr == 0) {
2661 return true;
2662 }
2663
2664 size_t verneed_cnt = si_from->get_verneed_cnt();
2665
2666 for (size_t i = 0, offset = 0; i<verneed_cnt; ++i) {
2667 const ElfW(Verneed)* verneed = reinterpret_cast<ElfW(Verneed)*>(verneed_ptr + offset);
2668 size_t vernaux_offset = offset + verneed->vn_aux;
2669 offset += verneed->vn_next;
2670
2671 if (verneed->vn_version != 1) {
2672 DL_ERR("unsupported verneed[%zd] vn_version: %d (expected 1)", i, verneed->vn_version);
2673 return false;
2674 }
2675
2676 const char* target_soname = si_from->get_string(verneed->vn_file);
2677 // find it in dependencies
2678 soinfo* target_si = si_from->get_children().find_if([&](const soinfo* si) {
Dmitriy Ivanov406d9962015-05-06 11:05:27 -07002679 return si->get_soname() != nullptr && strcmp(si->get_soname(), target_soname) == 0;
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07002680 });
2681
2682 if (target_si == nullptr) {
2683 DL_ERR("cannot find \"%s\" from verneed[%zd] in DT_NEEDED list for \"%s\"",
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07002684 target_soname, i, si_from->get_realpath());
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07002685 return false;
2686 }
2687
2688 for (size_t j = 0; j<verneed->vn_cnt; ++j) {
2689 const ElfW(Vernaux)* vernaux = reinterpret_cast<ElfW(Vernaux)*>(verneed_ptr + vernaux_offset);
2690 vernaux_offset += vernaux->vna_next;
2691
2692 const ElfW(Word) elf_hash = vernaux->vna_hash;
2693 const char* ver_name = si_from->get_string(vernaux->vna_name);
2694 ElfW(Half) source_index = vernaux->vna_other;
2695
2696 add_version_info(source_index, elf_hash, ver_name, target_si);
2697 }
2698 }
2699
2700 return true;
2701}
2702
Dimitry Ivanov48ec2882016-08-04 11:50:36 -07002703template <typename F>
2704static bool for_each_verdef(const soinfo* si, F functor) {
2705 if (!si->has_min_version(2)) {
2706 return true;
2707 }
2708
2709 uintptr_t verdef_ptr = si->get_verdef_ptr();
2710 if (verdef_ptr == 0) {
2711 return true;
2712 }
2713
2714 size_t offset = 0;
2715
2716 size_t verdef_cnt = si->get_verdef_cnt();
2717 for (size_t i = 0; i<verdef_cnt; ++i) {
2718 const ElfW(Verdef)* verdef = reinterpret_cast<ElfW(Verdef)*>(verdef_ptr + offset);
2719 size_t verdaux_offset = offset + verdef->vd_aux;
2720 offset += verdef->vd_next;
2721
2722 if (verdef->vd_version != 1) {
2723 DL_ERR("unsupported verdef[%zd] vd_version: %d (expected 1) library: %s",
2724 i, verdef->vd_version, si->get_realpath());
2725 return false;
2726 }
2727
2728 if ((verdef->vd_flags & VER_FLG_BASE) != 0) {
2729 // "this is the version of the file itself. It must not be used for
2730 // matching a symbol. It can be used to match references."
2731 //
2732 // http://www.akkadia.org/drepper/symbol-versioning
2733 continue;
2734 }
2735
2736 if (verdef->vd_cnt == 0) {
2737 DL_ERR("invalid verdef[%zd] vd_cnt == 0 (version without a name)", i);
2738 return false;
2739 }
2740
2741 const ElfW(Verdaux)* verdaux = reinterpret_cast<ElfW(Verdaux)*>(verdef_ptr + verdaux_offset);
2742
2743 if (functor(i, verdef, verdaux) == true) {
2744 break;
2745 }
2746 }
2747
2748 return true;
2749}
2750
2751bool find_verdef_version_index(const soinfo* si, const version_info* vi, ElfW(Versym)* versym) {
2752 if (vi == nullptr) {
2753 *versym = kVersymNotNeeded;
2754 return true;
2755 }
2756
2757 *versym = kVersymGlobal;
2758
2759 return for_each_verdef(si,
2760 [&](size_t, const ElfW(Verdef)* verdef, const ElfW(Verdaux)* verdaux) {
2761 if (verdef->vd_hash == vi->elf_hash &&
2762 strcmp(vi->name, si->get_string(verdaux->vda_name)) == 0) {
2763 *versym = verdef->vd_ndx;
2764 return true;
2765 }
2766
2767 return false;
2768 }
2769 );
2770}
2771
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07002772bool VersionTracker::init_verdef(const soinfo* si_from) {
2773 return for_each_verdef(si_from,
2774 [&](size_t, const ElfW(Verdef)* verdef, const ElfW(Verdaux)* verdaux) {
2775 add_version_info(verdef->vd_ndx, verdef->vd_hash,
2776 si_from->get_string(verdaux->vda_name), si_from);
2777 return false;
2778 }
2779 );
2780}
2781
2782bool VersionTracker::init(const soinfo* si_from) {
2783 if (!si_from->has_min_version(2)) {
2784 return true;
2785 }
2786
2787 return init_verneed(si_from) && init_verdef(si_from);
2788}
2789
Dimitry Ivanov48ec2882016-08-04 11:50:36 -07002790// TODO (dimitry): Methods below need to be moved out of soinfo
2791// and in more isolated file in order minimize dependencies on
2792// unnecessary object in the linker binary. Consider making them
2793// independent from soinfo (?).
Dmitriy Ivanov31b408d2015-04-30 16:11:48 -07002794bool soinfo::lookup_version_info(const VersionTracker& version_tracker, ElfW(Word) sym,
2795 const char* sym_name, const version_info** vi) {
2796 const ElfW(Versym)* sym_ver_ptr = get_versym(sym);
2797 ElfW(Versym) sym_ver = sym_ver_ptr == nullptr ? 0 : *sym_ver_ptr;
2798
2799 if (sym_ver != VER_NDX_LOCAL && sym_ver != VER_NDX_GLOBAL) {
2800 *vi = version_tracker.get_version_info(sym_ver);
2801
2802 if (*vi == nullptr) {
2803 DL_ERR("cannot find verneed/verdef for version index=%d "
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07002804 "referenced by symbol \"%s\" at \"%s\"", sym_ver, sym_name, get_realpath());
Dmitriy Ivanov31b408d2015-04-30 16:11:48 -07002805 return false;
2806 }
2807 } else {
2808 // there is no version info
2809 *vi = nullptr;
2810 }
2811
2812 return true;
2813}
2814
Rahul Chaudhryf16b6592018-01-25 15:34:15 -08002815void soinfo::apply_relr_reloc(ElfW(Addr) offset) {
2816 ElfW(Addr) address = offset + load_bias;
2817 *reinterpret_cast<ElfW(Addr)*>(address) += load_bias;
2818}
2819
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08002820// Process relocations in SHT_RELR section (experimental).
Rahul Chaudhryf16b6592018-01-25 15:34:15 -08002821// Details of the encoding are described in this post:
2822// https://groups.google.com/d/msg/generic-abi/bX460iggiKg/Pi9aSwwABgAJ
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08002823bool soinfo::relocate_relr() {
2824 ElfW(Relr)* begin = relr_;
2825 ElfW(Relr)* end = relr_ + relr_count_;
Rahul Chaudhryf16b6592018-01-25 15:34:15 -08002826 constexpr size_t wordsize = sizeof(ElfW(Addr));
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08002827
Rahul Chaudhryf16b6592018-01-25 15:34:15 -08002828 ElfW(Addr) base = 0;
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08002829 for (ElfW(Relr)* current = begin; current < end; ++current) {
Rahul Chaudhryf16b6592018-01-25 15:34:15 -08002830 ElfW(Relr) entry = *current;
2831 ElfW(Addr) offset;
2832
2833 if ((entry&1) == 0) {
2834 // Even entry: encodes the offset for next relocation.
2835 offset = static_cast<ElfW(Addr)>(entry);
2836 apply_relr_reloc(offset);
2837 // Set base offset for subsequent bitmap entries.
2838 base = offset + wordsize;
2839 continue;
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08002840 }
Rahul Chaudhryf16b6592018-01-25 15:34:15 -08002841
2842 // Odd entry: encodes bitmap for relocations starting at base.
2843 offset = base;
2844 while (entry != 0) {
2845 entry >>= 1;
2846 if ((entry&1) != 0) {
2847 apply_relr_reloc(offset);
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08002848 }
Rahul Chaudhryf16b6592018-01-25 15:34:15 -08002849 offset += wordsize;
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08002850 }
Rahul Chaudhryf16b6592018-01-25 15:34:15 -08002851
2852 // Advance base offset by 63 words for 64-bit platforms,
2853 // or 31 words for 32-bit platforms.
2854 base += (8*wordsize - 1) * wordsize;
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08002855 }
2856 return true;
2857}
2858
Dimitry Ivanov576a3752016-08-09 06:58:55 -07002859#if !defined(__mips__)
2860#if defined(USE_RELA)
2861static ElfW(Addr) get_addend(ElfW(Rela)* rela, ElfW(Addr) reloc_addr __unused) {
2862 return rela->r_addend;
2863}
2864#else
2865static ElfW(Addr) get_addend(ElfW(Rel)* rel, ElfW(Addr) reloc_addr) {
2866 if (ELFW(R_TYPE)(rel->r_info) == R_GENERIC_RELATIVE ||
Ryan Prichardfb8730d2019-01-15 00:11:37 -08002867 ELFW(R_TYPE)(rel->r_info) == R_GENERIC_IRELATIVE ||
2868 ELFW(R_TYPE)(rel->r_info) == R_GENERIC_TLS_DTPREL ||
2869 ELFW(R_TYPE)(rel->r_info) == R_GENERIC_TLS_TPREL) {
Dimitry Ivanov576a3752016-08-09 06:58:55 -07002870 return *reinterpret_cast<ElfW(Addr)*>(reloc_addr);
2871 }
2872 return 0;
2873}
2874#endif
2875
Ryan Prichardfb8730d2019-01-15 00:11:37 -08002876static bool is_tls_reloc(ElfW(Word) type) {
2877 switch (type) {
2878 case R_GENERIC_TLS_DTPMOD:
2879 case R_GENERIC_TLS_DTPREL:
2880 case R_GENERIC_TLS_TPREL:
2881 case R_GENERIC_TLSDESC:
2882 return true;
2883 default:
2884 return false;
2885 }
2886}
2887
Dmitriy Ivanovfa26eee2015-02-03 16:06:47 -08002888template<typename ElfRelIteratorT>
Dmitriy Ivanov7e4bbba2015-04-30 19:49:19 -07002889bool soinfo::relocate(const VersionTracker& version_tracker, ElfRelIteratorT&& rel_iterator,
2890 const soinfo_list_t& global_group, const soinfo_list_t& local_group) {
Ryan Prichardfb8730d2019-01-15 00:11:37 -08002891 const size_t tls_tp_base = __libc_shared_globals()->static_tls_layout.offset_thread_pointer();
Ryan Prichardffaae702019-01-23 17:47:10 -08002892 std::vector<std::pair<TlsDescriptor*, size_t>> deferred_tlsdesc_relocs;
Ryan Prichardfb8730d2019-01-15 00:11:37 -08002893
Dmitriy Ivanovfa26eee2015-02-03 16:06:47 -08002894 for (size_t idx = 0; rel_iterator.has_next(); ++idx) {
2895 const auto rel = rel_iterator.next();
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08002896 if (rel == nullptr) {
2897 return false;
2898 }
2899
Dmitriy Ivanovbcc04d02015-01-13 12:12:38 -08002900 ElfW(Word) type = ELFW(R_TYPE)(rel->r_info);
2901 ElfW(Word) sym = ELFW(R_SYM)(rel->r_info);
2902
2903 ElfW(Addr) reloc = static_cast<ElfW(Addr)>(rel->r_offset + load_bias);
Elliott Hughes0266ae52014-02-10 17:46:57 -08002904 ElfW(Addr) sym_addr = 0;
Dmitriy Ivanov851135b2014-08-29 12:02:36 -07002905 const char* sym_name = nullptr;
Dmitriy Ivanovbcc04d02015-01-13 12:12:38 -08002906 ElfW(Addr) addend = get_addend(rel, reloc);
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07002907
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07002908 DEBUG("Processing \"%s\" relocation at index %zd", get_realpath(), idx);
Dmitriy Ivanovcefef7d2015-01-08 23:30:15 -08002909 if (type == R_GENERIC_NONE) {
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07002910 continue;
2911 }
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07002912
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07002913 const ElfW(Sym)* s = nullptr;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07002914 soinfo* lsi = nullptr;
2915
Ryan Prichardfb8730d2019-01-15 00:11:37 -08002916 if (sym == 0) {
Ryan Prichard3b463cf2019-01-22 22:49:22 -08002917 // By convention in ld.bfd and lld, an omitted symbol on a TLS relocation
2918 // is a reference to the current module.
2919 if (is_tls_reloc(type)) {
2920 lsi = this;
2921 }
Ryan Prichardfb8730d2019-01-15 00:11:37 -08002922 } else if (ELF_ST_BIND(symtab_[sym].st_info) == STB_LOCAL && is_tls_reloc(type)) {
2923 // In certain situations, the Gold linker accesses a TLS symbol using a
2924 // relocation to an STB_LOCAL symbol in .dynsym of either STT_SECTION or
2925 // STT_TLS type. Bionic doesn't support these relocations, so issue an
2926 // error. References:
2927 // - https://groups.google.com/d/topic/generic-abi/dJ4_Y78aQ2M/discussion
2928 // - https://sourceware.org/bugzilla/show_bug.cgi?id=17699
2929 s = &symtab_[sym];
2930 sym_name = get_string(s->st_name);
2931 DL_ERR("unexpected TLS reference to local symbol \"%s\": "
2932 "sym type %d, rel type %u (idx %zu of \"%s\")",
2933 sym_name, ELF_ST_TYPE(s->st_info), type, idx, get_realpath());
2934 return false;
2935 } else {
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002936 sym_name = get_string(symtab_[sym].st_name);
Dmitriy Ivanov31b408d2015-04-30 16:11:48 -07002937 const version_info* vi = nullptr;
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07002938
Dmitriy Ivanov31b408d2015-04-30 16:11:48 -07002939 if (!lookup_version_info(version_tracker, sym, sym_name, &vi)) {
2940 return false;
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07002941 }
Dmitriy Ivanov31b408d2015-04-30 16:11:48 -07002942
2943 if (!soinfo_do_lookup(this, sym_name, vi, &lsi, global_group, local_group, &s)) {
2944 return false;
2945 }
2946
Dmitriy Ivanov851135b2014-08-29 12:02:36 -07002947 if (s == nullptr) {
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07002948 // We only allow an undefined symbol if this is a weak reference...
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002949 s = &symtab_[sym];
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07002950 if (ELF_ST_BIND(s->st_info) != STB_WEAK) {
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07002951 DL_ERR("cannot locate symbol \"%s\" referenced by \"%s\"...", sym_name, get_realpath());
Dmitriy Ivanov114ff692015-01-14 11:36:38 -08002952 return false;
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07002953 }
2954
2955 /* IHI0044C AAELF 4.5.1.1:
2956
2957 Libraries are not searched to resolve weak references.
2958 It is not an error for a weak reference to remain unsatisfied.
2959
2960 During linking, the value of an undefined weak reference is:
2961 - Zero if the relocation type is absolute
2962 - The address of the place if the relocation is pc-relative
2963 - The address of nominal base address if the relocation
2964 type is base-relative.
2965 */
2966
2967 switch (type) {
Dmitriy Ivanov1b694692015-01-13 12:17:31 -08002968 case R_GENERIC_JUMP_SLOT:
2969 case R_GENERIC_GLOB_DAT:
2970 case R_GENERIC_RELATIVE:
2971 case R_GENERIC_IRELATIVE:
Ryan Prichardfb8730d2019-01-15 00:11:37 -08002972 case R_GENERIC_TLS_DTPMOD:
2973 case R_GENERIC_TLS_DTPREL:
2974 case R_GENERIC_TLS_TPREL:
2975 case R_GENERIC_TLSDESC:
Marcus Oaklande365f9d2013-10-10 15:19:31 +01002976#if defined(__aarch64__)
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002977 case R_AARCH64_ABS64:
2978 case R_AARCH64_ABS32:
2979 case R_AARCH64_ABS16:
Dmitriy Ivanov1b694692015-01-13 12:17:31 -08002980#elif defined(__x86_64__)
2981 case R_X86_64_32:
2982 case R_X86_64_64:
Dmitriy Ivanovbcc04d02015-01-13 12:12:38 -08002983#elif defined(__arm__)
2984 case R_ARM_ABS32:
2985#elif defined(__i386__)
2986 case R_386_32:
Dmitriy Ivanov1b694692015-01-13 12:17:31 -08002987#endif
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07002988 /*
2989 * The sym_addr was initialized to be zero above, or the relocation
2990 * code below does not care about value of sym_addr.
2991 * No need to do anything.
2992 */
2993 break;
Dmitriy Ivanov1b694692015-01-13 12:17:31 -08002994#if defined(__x86_64__)
Dimitry Ivanovd338aac2015-01-13 22:31:54 +00002995 case R_X86_64_PC32:
2996 sym_addr = reloc;
2997 break;
Dmitriy Ivanovbcc04d02015-01-13 12:12:38 -08002998#elif defined(__i386__)
2999 case R_386_PC32:
3000 sym_addr = reloc;
3001 break;
3002#endif
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003003 default:
Dmitriy Ivanovbcc04d02015-01-13 12:12:38 -08003004 DL_ERR("unknown weak reloc type %d @ %p (%zu)", type, rel, idx);
Dmitriy Ivanov114ff692015-01-14 11:36:38 -08003005 return false;
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07003006 }
Dmitriy Ivanovec83a612015-07-26 07:37:09 -07003007 } else { // We got a definition.
3008#if !defined(__LP64__)
3009 // When relocating dso with text_relocation .text segment is
3010 // not executable. We need to restore elf flags before resolving
3011 // STT_GNU_IFUNC symbol.
3012 bool protect_segments = has_text_relocations &&
3013 lsi == this &&
3014 ELF_ST_TYPE(s->st_info) == STT_GNU_IFUNC;
3015 if (protect_segments) {
3016 if (phdr_table_protect_segments(phdr, phnum, load_bias) < 0) {
3017 DL_ERR("can't protect segments for \"%s\": %s",
3018 get_realpath(), strerror(errno));
3019 return false;
3020 }
3021 }
3022#endif
Ryan Prichardfb8730d2019-01-15 00:11:37 -08003023 if (is_tls_reloc(type)) {
3024 if (ELF_ST_TYPE(s->st_info) != STT_TLS) {
3025 DL_ERR("reference to non-TLS symbol \"%s\" from TLS relocation in \"%s\"",
3026 sym_name, get_realpath());
3027 return false;
3028 }
Ryan Prichard3b463cf2019-01-22 22:49:22 -08003029 if (lsi->get_tls() == nullptr) {
3030 DL_ERR("TLS relocation refers to symbol \"%s\" in solib \"%s\" with no TLS segment",
3031 sym_name, lsi->get_realpath());
3032 return false;
3033 }
Ryan Prichardfb8730d2019-01-15 00:11:37 -08003034 sym_addr = s->st_value;
3035 } else {
3036 if (ELF_ST_TYPE(s->st_info) == STT_TLS) {
3037 DL_ERR("reference to TLS symbol \"%s\" from non-TLS relocation in \"%s\"",
3038 sym_name, get_realpath());
3039 return false;
3040 }
3041 sym_addr = lsi->resolve_symbol_address(s);
Elliott Hughes9724e932018-03-23 18:46:07 -07003042 }
Dmitriy Ivanovec83a612015-07-26 07:37:09 -07003043#if !defined(__LP64__)
3044 if (protect_segments) {
3045 if (phdr_table_unprotect_segments(phdr, phnum, load_bias) < 0) {
3046 DL_ERR("can't unprotect loadable segments for \"%s\": %s",
3047 get_realpath(), strerror(errno));
3048 return false;
3049 }
3050 }
3051#endif
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07003052 }
3053 count_relocation(kRelocSymbol);
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07003054 }
3055
3056 switch (type) {
Dmitriy Ivanovcefef7d2015-01-08 23:30:15 -08003057 case R_GENERIC_JUMP_SLOT:
Marcus Oaklande365f9d2013-10-10 15:19:31 +01003058 count_relocation(kRelocAbsolute);
Dmitriy Ivanovbcc04d02015-01-13 12:12:38 -08003059 MARK(rel->r_offset);
3060 TRACE_TYPE(RELO, "RELO JMP_SLOT %16p <- %16p %s\n",
3061 reinterpret_cast<void*>(reloc),
3062 reinterpret_cast<void*>(sym_addr + addend), sym_name);
3063
3064 *reinterpret_cast<ElfW(Addr)*>(reloc) = (sym_addr + addend);
Marcus Oaklande365f9d2013-10-10 15:19:31 +01003065 break;
Dmitriy Ivanovcefef7d2015-01-08 23:30:15 -08003066 case R_GENERIC_GLOB_DAT:
Marcus Oaklande365f9d2013-10-10 15:19:31 +01003067 count_relocation(kRelocAbsolute);
Dmitriy Ivanovbcc04d02015-01-13 12:12:38 -08003068 MARK(rel->r_offset);
3069 TRACE_TYPE(RELO, "RELO GLOB_DAT %16p <- %16p %s\n",
3070 reinterpret_cast<void*>(reloc),
3071 reinterpret_cast<void*>(sym_addr + addend), sym_name);
3072 *reinterpret_cast<ElfW(Addr)*>(reloc) = (sym_addr + addend);
Marcus Oaklande365f9d2013-10-10 15:19:31 +01003073 break;
Dmitriy Ivanovcefef7d2015-01-08 23:30:15 -08003074 case R_GENERIC_RELATIVE:
3075 count_relocation(kRelocRelative);
Dmitriy Ivanovbcc04d02015-01-13 12:12:38 -08003076 MARK(rel->r_offset);
3077 TRACE_TYPE(RELO, "RELO RELATIVE %16p <- %16p\n",
3078 reinterpret_cast<void*>(reloc),
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08003079 reinterpret_cast<void*>(load_bias + addend));
3080 *reinterpret_cast<ElfW(Addr)*>(reloc) = (load_bias + addend);
Dmitriy Ivanovcefef7d2015-01-08 23:30:15 -08003081 break;
Dmitriy Ivanovcefef7d2015-01-08 23:30:15 -08003082 case R_GENERIC_IRELATIVE:
3083 count_relocation(kRelocRelative);
Dmitriy Ivanovbcc04d02015-01-13 12:12:38 -08003084 MARK(rel->r_offset);
3085 TRACE_TYPE(RELO, "RELO IRELATIVE %16p <- %16p\n",
3086 reinterpret_cast<void*>(reloc),
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08003087 reinterpret_cast<void*>(load_bias + addend));
Dmitriy Ivanovec83a612015-07-26 07:37:09 -07003088 {
3089#if !defined(__LP64__)
3090 // When relocating dso with text_relocation .text segment is
3091 // not executable. We need to restore elf flags for this
3092 // particular call.
3093 if (has_text_relocations) {
3094 if (phdr_table_protect_segments(phdr, phnum, load_bias) < 0) {
3095 DL_ERR("can't protect segments for \"%s\": %s",
3096 get_realpath(), strerror(errno));
3097 return false;
3098 }
3099 }
3100#endif
3101 ElfW(Addr) ifunc_addr = call_ifunc_resolver(load_bias + addend);
3102#if !defined(__LP64__)
3103 // Unprotect it afterwards...
3104 if (has_text_relocations) {
3105 if (phdr_table_unprotect_segments(phdr, phnum, load_bias) < 0) {
3106 DL_ERR("can't unprotect loadable segments for \"%s\": %s",
3107 get_realpath(), strerror(errno));
3108 return false;
3109 }
3110 }
3111#endif
3112 *reinterpret_cast<ElfW(Addr)*>(reloc) = ifunc_addr;
3113 }
Dmitriy Ivanovcefef7d2015-01-08 23:30:15 -08003114 break;
Ryan Prichardfb8730d2019-01-15 00:11:37 -08003115 case R_GENERIC_TLS_TPREL:
3116 count_relocation(kRelocRelative);
3117 MARK(rel->r_offset);
3118 {
3119 ElfW(Addr) tpoff = 0;
Ryan Prichardfb8730d2019-01-15 00:11:37 -08003120 if (lsi == nullptr) {
3121 // Unresolved weak relocation. Leave tpoff at 0 to resolve
3122 // &weak_tls_symbol to __get_tls().
Ryan Prichard3b463cf2019-01-22 22:49:22 -08003123 } else {
3124 CHECK(lsi->get_tls() != nullptr); // We rejected a missing TLS segment above.
3125 const TlsModule& mod = get_tls_module(lsi->get_tls()->module_id);
Ryan Prichardbf427f42019-01-17 16:37:11 -08003126 if (mod.static_offset != SIZE_MAX) {
3127 tpoff += mod.static_offset - tls_tp_base;
Ryan Prichardfb8730d2019-01-15 00:11:37 -08003128 } else {
3129 DL_ERR("TLS symbol \"%s\" in dlopened \"%s\" referenced from \"%s\" using IE access model",
3130 sym_name, lsi->get_realpath(), get_realpath());
3131 return false;
3132 }
Ryan Prichardfb8730d2019-01-15 00:11:37 -08003133 }
3134 tpoff += sym_addr + addend;
3135 TRACE_TYPE(RELO, "RELO TLS_TPREL %16p <- %16p %s\n",
3136 reinterpret_cast<void*>(reloc),
3137 reinterpret_cast<void*>(tpoff), sym_name);
3138 *reinterpret_cast<ElfW(Addr)*>(reloc) = tpoff;
3139 }
3140 break;
Dmitriy Ivanovcefef7d2015-01-08 23:30:15 -08003141
Ryan Prichard3b463cf2019-01-22 22:49:22 -08003142#if !defined(__aarch64__)
3143 // Omit support for DTPMOD/DTPREL on arm64, at least until
3144 // http://b/123385182 is fixed. arm64 uses TLSDESC instead.
3145 case R_GENERIC_TLS_DTPMOD:
3146 count_relocation(kRelocRelative);
3147 MARK(rel->r_offset);
3148 {
3149 size_t module_id = 0;
3150 if (lsi == nullptr) {
3151 // Unresolved weak relocation. Evaluate the module ID to 0.
3152 } else {
3153 CHECK(lsi->get_tls() != nullptr); // We rejected a missing TLS segment above.
3154 module_id = lsi->get_tls()->module_id;
3155 }
3156 TRACE_TYPE(RELO, "RELO TLS_DTPMOD %16p <- %zu %s\n",
3157 reinterpret_cast<void*>(reloc), module_id, sym_name);
3158 *reinterpret_cast<ElfW(Addr)*>(reloc) = module_id;
3159 }
3160 break;
3161 case R_GENERIC_TLS_DTPREL:
3162 count_relocation(kRelocRelative);
3163 MARK(rel->r_offset);
3164 TRACE_TYPE(RELO, "RELO TLS_DTPREL %16p <- %16p %s\n",
3165 reinterpret_cast<void*>(reloc),
3166 reinterpret_cast<void*>(sym_addr + addend), sym_name);
3167 *reinterpret_cast<ElfW(Addr)*>(reloc) = sym_addr + addend;
3168 break;
3169#endif // !defined(__aarch64__)
3170
Dmitriy Ivanovcefef7d2015-01-08 23:30:15 -08003171#if defined(__aarch64__)
Ryan Prichardffaae702019-01-23 17:47:10 -08003172 // Bionic currently only implements TLSDESC for arm64. This implementation should work with
3173 // other architectures, as long as the resolver functions are implemented.
3174 case R_GENERIC_TLSDESC:
3175 count_relocation(kRelocRelative);
3176 MARK(rel->r_offset);
3177 {
3178 TlsDescriptor* desc = reinterpret_cast<TlsDescriptor*>(reloc);
3179 if (lsi == nullptr) {
3180 // Unresolved weak relocation.
3181 desc->func = tlsdesc_resolver_unresolved_weak;
3182 desc->arg = addend;
3183 TRACE_TYPE(RELO, "RELO TLSDESC %16p <- unresolved weak 0x%zx %s\n",
3184 reinterpret_cast<void*>(reloc), static_cast<size_t>(addend), sym_name);
3185 } else {
3186 CHECK(lsi->get_tls() != nullptr); // We rejected a missing TLS segment above.
3187 size_t module_id = lsi->get_tls()->module_id;
3188 const TlsModule& mod = get_tls_module(module_id);
3189 if (mod.static_offset != SIZE_MAX) {
3190 desc->func = tlsdesc_resolver_static;
3191 desc->arg = mod.static_offset - tls_tp_base + sym_addr + addend;
3192 TRACE_TYPE(RELO, "RELO TLSDESC %16p <- static (0x%zx - 0x%zx + 0x%zx + 0x%zx) %s\n",
3193 reinterpret_cast<void*>(reloc), mod.static_offset, tls_tp_base,
3194 static_cast<size_t>(sym_addr), static_cast<size_t>(addend), sym_name);
3195 } else {
3196 tlsdesc_args_.push_back({
3197 .generation = mod.first_generation,
3198 .index.module_id = module_id,
3199 .index.offset = sym_addr + addend,
3200 });
3201 // Defer the TLSDESC relocation until the address of the TlsDynamicResolverArg object
3202 // is finalized.
3203 deferred_tlsdesc_relocs.push_back({ desc, tlsdesc_args_.size() - 1 });
3204 const TlsDynamicResolverArg& desc_arg = tlsdesc_args_.back();
3205 TRACE_TYPE(RELO, "RELO TLSDESC %16p <- dynamic (gen %zu, mod %zu, off %zu) %s",
3206 reinterpret_cast<void*>(reloc), desc_arg.generation,
3207 desc_arg.index.module_id, desc_arg.index.offset, sym_name);
3208 }
3209 }
3210 }
3211 break;
Ryan Prichardb0e2dd02019-03-11 17:06:02 -07003212#endif // defined(__aarch64__)
Ryan Prichardffaae702019-01-23 17:47:10 -08003213
3214#if defined(__aarch64__)
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003215 case R_AARCH64_ABS64:
Marcus Oaklande365f9d2013-10-10 15:19:31 +01003216 count_relocation(kRelocAbsolute);
Dmitriy Ivanovbcc04d02015-01-13 12:12:38 -08003217 MARK(rel->r_offset);
Elliott Hughes0266ae52014-02-10 17:46:57 -08003218 TRACE_TYPE(RELO, "RELO ABS64 %16llx <- %16llx %s\n",
Dmitriy Ivanov77f91c62015-10-15 13:26:03 -07003219 reloc, sym_addr + addend, sym_name);
3220 *reinterpret_cast<ElfW(Addr)*>(reloc) = sym_addr + addend;
Marcus Oaklande365f9d2013-10-10 15:19:31 +01003221 break;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003222 case R_AARCH64_ABS32:
Marcus Oaklande365f9d2013-10-10 15:19:31 +01003223 count_relocation(kRelocAbsolute);
Dmitriy Ivanovbcc04d02015-01-13 12:12:38 -08003224 MARK(rel->r_offset);
Elliott Hughes0266ae52014-02-10 17:46:57 -08003225 TRACE_TYPE(RELO, "RELO ABS32 %16llx <- %16llx %s\n",
Dmitriy Ivanov77f91c62015-10-15 13:26:03 -07003226 reloc, sym_addr + addend, sym_name);
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07003227 {
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07003228 const ElfW(Addr) min_value = static_cast<ElfW(Addr)>(INT32_MIN);
3229 const ElfW(Addr) max_value = static_cast<ElfW(Addr)>(UINT32_MAX);
Dmitriy Ivanov77f91c62015-10-15 13:26:03 -07003230 if ((min_value <= (sym_addr + addend)) &&
3231 ((sym_addr + addend) <= max_value)) {
3232 *reinterpret_cast<ElfW(Addr)*>(reloc) = sym_addr + addend;
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07003233 } else {
3234 DL_ERR("0x%016llx out of range 0x%016llx to 0x%016llx",
Dmitriy Ivanov77f91c62015-10-15 13:26:03 -07003235 sym_addr + addend, min_value, max_value);
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07003236 return false;
3237 }
Marcus Oaklande365f9d2013-10-10 15:19:31 +01003238 }
3239 break;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003240 case R_AARCH64_ABS16:
Marcus Oaklande365f9d2013-10-10 15:19:31 +01003241 count_relocation(kRelocAbsolute);
Dmitriy Ivanovbcc04d02015-01-13 12:12:38 -08003242 MARK(rel->r_offset);
Elliott Hughes0266ae52014-02-10 17:46:57 -08003243 TRACE_TYPE(RELO, "RELO ABS16 %16llx <- %16llx %s\n",
Dmitriy Ivanov77f91c62015-10-15 13:26:03 -07003244 reloc, sym_addr + addend, sym_name);
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07003245 {
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07003246 const ElfW(Addr) min_value = static_cast<ElfW(Addr)>(INT16_MIN);
3247 const ElfW(Addr) max_value = static_cast<ElfW(Addr)>(UINT16_MAX);
Dmitriy Ivanov77f91c62015-10-15 13:26:03 -07003248 if ((min_value <= (sym_addr + addend)) &&
3249 ((sym_addr + addend) <= max_value)) {
3250 *reinterpret_cast<ElfW(Addr)*>(reloc) = (sym_addr + addend);
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07003251 } else {
3252 DL_ERR("0x%016llx out of range 0x%016llx to 0x%016llx",
Dmitriy Ivanov77f91c62015-10-15 13:26:03 -07003253 sym_addr + addend, min_value, max_value);
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07003254 return false;
3255 }
Marcus Oaklande365f9d2013-10-10 15:19:31 +01003256 }
3257 break;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003258 case R_AARCH64_PREL64:
Marcus Oaklande365f9d2013-10-10 15:19:31 +01003259 count_relocation(kRelocRelative);
Dmitriy Ivanovbcc04d02015-01-13 12:12:38 -08003260 MARK(rel->r_offset);
Elliott Hughes0266ae52014-02-10 17:46:57 -08003261 TRACE_TYPE(RELO, "RELO REL64 %16llx <- %16llx - %16llx %s\n",
Dmitriy Ivanov77f91c62015-10-15 13:26:03 -07003262 reloc, sym_addr + addend, rel->r_offset, sym_name);
3263 *reinterpret_cast<ElfW(Addr)*>(reloc) = sym_addr + addend - rel->r_offset;
Marcus Oaklande365f9d2013-10-10 15:19:31 +01003264 break;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003265 case R_AARCH64_PREL32:
Marcus Oaklande365f9d2013-10-10 15:19:31 +01003266 count_relocation(kRelocRelative);
Dmitriy Ivanovbcc04d02015-01-13 12:12:38 -08003267 MARK(rel->r_offset);
Elliott Hughes0266ae52014-02-10 17:46:57 -08003268 TRACE_TYPE(RELO, "RELO REL32 %16llx <- %16llx - %16llx %s\n",
Dmitriy Ivanov77f91c62015-10-15 13:26:03 -07003269 reloc, sym_addr + addend, rel->r_offset, sym_name);
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07003270 {
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07003271 const ElfW(Addr) min_value = static_cast<ElfW(Addr)>(INT32_MIN);
3272 const ElfW(Addr) max_value = static_cast<ElfW(Addr)>(UINT32_MAX);
Dmitriy Ivanov77f91c62015-10-15 13:26:03 -07003273 if ((min_value <= (sym_addr + addend - rel->r_offset)) &&
3274 ((sym_addr + addend - rel->r_offset) <= max_value)) {
3275 *reinterpret_cast<ElfW(Addr)*>(reloc) = sym_addr + addend - rel->r_offset;
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07003276 } else {
3277 DL_ERR("0x%016llx out of range 0x%016llx to 0x%016llx",
Dmitriy Ivanov77f91c62015-10-15 13:26:03 -07003278 sym_addr + addend - rel->r_offset, min_value, max_value);
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07003279 return false;
3280 }
Marcus Oaklande365f9d2013-10-10 15:19:31 +01003281 }
3282 break;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003283 case R_AARCH64_PREL16:
Marcus Oaklande365f9d2013-10-10 15:19:31 +01003284 count_relocation(kRelocRelative);
Dmitriy Ivanovbcc04d02015-01-13 12:12:38 -08003285 MARK(rel->r_offset);
Elliott Hughes0266ae52014-02-10 17:46:57 -08003286 TRACE_TYPE(RELO, "RELO REL16 %16llx <- %16llx - %16llx %s\n",
Dmitriy Ivanov77f91c62015-10-15 13:26:03 -07003287 reloc, sym_addr + addend, rel->r_offset, sym_name);
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07003288 {
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07003289 const ElfW(Addr) min_value = static_cast<ElfW(Addr)>(INT16_MIN);
3290 const ElfW(Addr) max_value = static_cast<ElfW(Addr)>(UINT16_MAX);
Dmitriy Ivanov77f91c62015-10-15 13:26:03 -07003291 if ((min_value <= (sym_addr + addend - rel->r_offset)) &&
3292 ((sym_addr + addend - rel->r_offset) <= max_value)) {
3293 *reinterpret_cast<ElfW(Addr)*>(reloc) = sym_addr + addend - rel->r_offset;
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07003294 } else {
3295 DL_ERR("0x%016llx out of range 0x%016llx to 0x%016llx",
Dmitriy Ivanov77f91c62015-10-15 13:26:03 -07003296 sym_addr + addend - rel->r_offset, min_value, max_value);
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07003297 return false;
3298 }
Marcus Oaklande365f9d2013-10-10 15:19:31 +01003299 }
3300 break;
3301
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003302 case R_AARCH64_COPY:
Nick Kralevich76e289c2014-07-03 12:04:31 -07003303 /*
3304 * ET_EXEC is not supported so this should not happen.
3305 *
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003306 * http://infocenter.arm.com/help/topic/com.arm.doc.ihi0056b/IHI0056B_aaelf64.pdf
Nick Kralevich76e289c2014-07-03 12:04:31 -07003307 *
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003308 * Section 4.6.11 "Dynamic relocations"
Nick Kralevich76e289c2014-07-03 12:04:31 -07003309 * R_AARCH64_COPY may only appear in executable objects where e_type is
3310 * set to ET_EXEC.
3311 */
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07003312 DL_ERR("%s R_AARCH64_COPY relocations are not supported", get_realpath());
Dmitriy Ivanov114ff692015-01-14 11:36:38 -08003313 return false;
Marcus Oaklande365f9d2013-10-10 15:19:31 +01003314#elif defined(__x86_64__)
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003315 case R_X86_64_32:
3316 count_relocation(kRelocRelative);
Dmitriy Ivanovbcc04d02015-01-13 12:12:38 -08003317 MARK(rel->r_offset);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003318 TRACE_TYPE(RELO, "RELO R_X86_64_32 %08zx <- +%08zx %s", static_cast<size_t>(reloc),
3319 static_cast<size_t>(sym_addr), sym_name);
Junichi Uekawaff35b1e2015-11-18 10:18:59 +09003320 *reinterpret_cast<Elf32_Addr*>(reloc) = sym_addr + addend;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003321 break;
3322 case R_X86_64_64:
3323 count_relocation(kRelocRelative);
Dmitriy Ivanovbcc04d02015-01-13 12:12:38 -08003324 MARK(rel->r_offset);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003325 TRACE_TYPE(RELO, "RELO R_X86_64_64 %08zx <- +%08zx %s", static_cast<size_t>(reloc),
3326 static_cast<size_t>(sym_addr), sym_name);
Junichi Uekawaff35b1e2015-11-18 10:18:59 +09003327 *reinterpret_cast<Elf64_Addr*>(reloc) = sym_addr + addend;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003328 break;
3329 case R_X86_64_PC32:
3330 count_relocation(kRelocRelative);
Dmitriy Ivanovbcc04d02015-01-13 12:12:38 -08003331 MARK(rel->r_offset);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003332 TRACE_TYPE(RELO, "RELO R_X86_64_PC32 %08zx <- +%08zx (%08zx - %08zx) %s",
3333 static_cast<size_t>(reloc), static_cast<size_t>(sym_addr - reloc),
3334 static_cast<size_t>(sym_addr), static_cast<size_t>(reloc), sym_name);
Junichi Uekawaff35b1e2015-11-18 10:18:59 +09003335 *reinterpret_cast<Elf32_Addr*>(reloc) = sym_addr + addend - reloc;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003336 break;
Dmitriy Ivanovbcc04d02015-01-13 12:12:38 -08003337#elif defined(__arm__)
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003338 case R_ARM_ABS32:
3339 count_relocation(kRelocAbsolute);
3340 MARK(rel->r_offset);
3341 TRACE_TYPE(RELO, "RELO ABS %08x <- %08x %s", reloc, sym_addr, sym_name);
3342 *reinterpret_cast<ElfW(Addr)*>(reloc) += sym_addr;
3343 break;
3344 case R_ARM_REL32:
3345 count_relocation(kRelocRelative);
3346 MARK(rel->r_offset);
3347 TRACE_TYPE(RELO, "RELO REL32 %08x <- %08x - %08x %s",
3348 reloc, sym_addr, rel->r_offset, sym_name);
3349 *reinterpret_cast<ElfW(Addr)*>(reloc) += sym_addr - rel->r_offset;
3350 break;
3351 case R_ARM_COPY:
3352 /*
3353 * ET_EXEC is not supported so this should not happen.
3354 *
3355 * http://infocenter.arm.com/help/topic/com.arm.doc.ihi0044d/IHI0044D_aaelf.pdf
3356 *
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003357 * Section 4.6.1.10 "Dynamic relocations"
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003358 * R_ARM_COPY may only appear in executable objects where e_type is
3359 * set to ET_EXEC.
3360 */
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07003361 DL_ERR("%s R_ARM_COPY relocations are not supported", get_realpath());
Dmitriy Ivanov114ff692015-01-14 11:36:38 -08003362 return false;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003363#elif defined(__i386__)
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003364 case R_386_32:
3365 count_relocation(kRelocRelative);
3366 MARK(rel->r_offset);
3367 TRACE_TYPE(RELO, "RELO R_386_32 %08x <- +%08x %s", reloc, sym_addr, sym_name);
3368 *reinterpret_cast<ElfW(Addr)*>(reloc) += sym_addr;
3369 break;
3370 case R_386_PC32:
3371 count_relocation(kRelocRelative);
3372 MARK(rel->r_offset);
3373 TRACE_TYPE(RELO, "RELO R_386_PC32 %08x <- +%08x (%08x - %08x) %s",
3374 reloc, (sym_addr - reloc), sym_addr, reloc, sym_name);
3375 *reinterpret_cast<ElfW(Addr)*>(reloc) += (sym_addr - reloc);
3376 break;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003377#endif
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003378 default:
3379 DL_ERR("unknown reloc type %d @ %p (%zu)", type, rel, idx);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003380 return false;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003381 }
3382 }
Ryan Prichardffaae702019-01-23 17:47:10 -08003383
Ryan Prichardb0e2dd02019-03-11 17:06:02 -07003384#if defined(__aarch64__)
3385 // Bionic currently only implements TLSDESC for arm64.
Ryan Prichardffaae702019-01-23 17:47:10 -08003386 for (const std::pair<TlsDescriptor*, size_t>& pair : deferred_tlsdesc_relocs) {
3387 TlsDescriptor* desc = pair.first;
3388 desc->func = tlsdesc_resolver_dynamic;
3389 desc->arg = reinterpret_cast<size_t>(&tlsdesc_args_[pair.second]);
3390 }
Ryan Prichardb0e2dd02019-03-11 17:06:02 -07003391#endif
Ryan Prichardffaae702019-01-23 17:47:10 -08003392
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003393 return true;
Raghu Gandhamd7daacb2012-07-31 12:07:22 -07003394}
Dmitriy Ivanov114ff692015-01-14 11:36:38 -08003395#endif // !defined(__mips__)
Raghu Gandhamd7daacb2012-07-31 12:07:22 -07003396
Dimitry Ivanov48ec2882016-08-04 11:50:36 -07003397// An empty list of soinfos
Dimitry Ivanovb943f302016-08-03 16:00:10 -07003398static soinfo_list_t g_empty_list;
Dmitriy Ivanovd59e5002014-05-09 09:10:14 -07003399
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003400bool soinfo::prelink_image() {
Ningsheng Jiane93be992014-09-16 15:22:10 +08003401 /* Extract dynamic section */
3402 ElfW(Word) dynamic_flags = 0;
3403 phdr_table_get_dynamic_section(phdr, phnum, load_bias, &dynamic, &dynamic_flags);
Dmitriy Ivanov498eb182014-09-05 14:57:59 -07003404
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003405 /* We can't log anything until the linker is relocated */
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08003406 bool relocating_linker = (flags_ & FLAG_LINKER) != 0;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003407 if (!relocating_linker) {
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07003408 INFO("[ Linking \"%s\" ]", get_realpath());
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08003409 DEBUG("si->base = %p si->flags = 0x%08x", reinterpret_cast<void*>(base), flags_);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003410 }
3411
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003412 if (dynamic == nullptr) {
David 'Digit' Turnerb52e4382012-06-19 01:24:17 +02003413 if (!relocating_linker) {
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07003414 DL_ERR("missing PT_DYNAMIC in \"%s\"", get_realpath());
David 'Digit' Turnerb52e4382012-06-19 01:24:17 +02003415 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003416 return false;
3417 } else {
3418 if (!relocating_linker) {
3419 DEBUG("dynamic = %p", dynamic);
David 'Digit' Turner63f99f42012-06-19 00:08:39 +02003420 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003421 }
David 'Digit' Turner63f99f42012-06-19 00:08:39 +02003422
Elliott Hughes4eeb1f12013-10-25 17:38:02 -07003423#if defined(__arm__)
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003424 (void) phdr_table_get_arm_exidx(phdr, phnum, load_bias,
3425 &ARM_exidx, &ARM_exidx_count);
David 'Digit' Turner63f99f42012-06-19 00:08:39 +02003426#endif
3427
Ryan Pricharde5e69e02019-01-01 18:53:48 -08003428 TlsSegment tls_segment;
Ryan Prichard19883502019-01-16 23:13:38 -08003429 if (__bionic_get_tls_segment(phdr, phnum, load_bias, &tls_segment)) {
3430 if (!__bionic_check_tls_alignment(&tls_segment.alignment)) {
3431 if (!relocating_linker) {
3432 DL_ERR("TLS segment alignment in \"%s\" is not a power of 2: %zu",
3433 get_realpath(), tls_segment.alignment);
3434 }
3435 return false;
3436 }
Ryan Pricharde5e69e02019-01-01 18:53:48 -08003437 tls_ = std::make_unique<soinfo_tls>();
3438 tls_->segment = tls_segment;
3439 }
3440
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003441 // Extract useful information from dynamic section.
Dmitriy Ivanov618f1a32015-03-17 20:06:36 -07003442 // Note that: "Except for the DT_NULL element at the end of the array,
3443 // and the relative order of DT_NEEDED elements, entries may appear in any order."
3444 //
3445 // source: http://www.sco.com/developers/gabi/1998-04-29/ch5.dynamic.html
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003446 uint32_t needed_count = 0;
3447 for (ElfW(Dyn)* d = dynamic; d->d_tag != DT_NULL; ++d) {
3448 DEBUG("d = %p, d[0](tag) = %p d[1](val) = %p",
3449 d, reinterpret_cast<void*>(d->d_tag), reinterpret_cast<void*>(d->d_un.d_val));
3450 switch (d->d_tag) {
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07003451 case DT_SONAME:
Dmitriy Ivanov618f1a32015-03-17 20:06:36 -07003452 // this is parsed after we have strtab initialized (see below).
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07003453 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003454
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003455 case DT_HASH:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003456 nbucket_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[0];
3457 nchain_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[1];
3458 bucket_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr + 8);
3459 chain_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr + 8 + nbucket_ * 4);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003460 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003461
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -08003462 case DT_GNU_HASH:
Dmitriy Ivanov3597b802015-03-09 12:02:02 -07003463 gnu_nbucket_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[0];
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -08003464 // skip symndx
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003465 gnu_maskwords_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[2];
3466 gnu_shift2_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[3];
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -08003467
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003468 gnu_bloom_filter_ = reinterpret_cast<ElfW(Addr)*>(load_bias + d->d_un.d_ptr + 16);
Dmitriy Ivanov3597b802015-03-09 12:02:02 -07003469 gnu_bucket_ = reinterpret_cast<uint32_t*>(gnu_bloom_filter_ + gnu_maskwords_);
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -08003470 // amend chain for symndx = header[1]
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07003471 gnu_chain_ = gnu_bucket_ + gnu_nbucket_ -
3472 reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[1];
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -08003473
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003474 if (!powerof2(gnu_maskwords_)) {
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07003475 DL_ERR("invalid maskwords for gnu_hash = 0x%x, in \"%s\" expecting power to two",
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003476 gnu_maskwords_, get_realpath());
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -08003477 return false;
3478 }
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003479 --gnu_maskwords_;
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -08003480
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08003481 flags_ |= FLAG_GNU_HASH;
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -08003482 break;
3483
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003484 case DT_STRTAB:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003485 strtab_ = reinterpret_cast<const char*>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003486 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003487
Dmitriy Ivanov6cdeb522014-09-29 19:14:45 -07003488 case DT_STRSZ:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003489 strtab_size_ = d->d_un.d_val;
Dmitriy Ivanov6cdeb522014-09-29 19:14:45 -07003490 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003491
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003492 case DT_SYMTAB:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003493 symtab_ = reinterpret_cast<ElfW(Sym)*>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003494 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003495
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07003496 case DT_SYMENT:
3497 if (d->d_un.d_val != sizeof(ElfW(Sym))) {
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003498 DL_ERR("invalid DT_SYMENT: %zd in \"%s\"",
3499 static_cast<size_t>(d->d_un.d_val), get_realpath());
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07003500 return false;
3501 }
3502 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003503
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003504 case DT_PLTREL:
Dmitriy Ivanov513e29e2014-10-06 11:30:43 -07003505#if defined(USE_RELA)
3506 if (d->d_un.d_val != DT_RELA) {
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003507 DL_ERR("unsupported DT_PLTREL in \"%s\"; expected DT_RELA", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003508 return false;
3509 }
Dmitriy Ivanov513e29e2014-10-06 11:30:43 -07003510#else
3511 if (d->d_un.d_val != DT_REL) {
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003512 DL_ERR("unsupported DT_PLTREL in \"%s\"; expected DT_REL", get_realpath());
Dmitriy Ivanov513e29e2014-10-06 11:30:43 -07003513 return false;
3514 }
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07003515#endif
Dmitriy Ivanov513e29e2014-10-06 11:30:43 -07003516 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003517
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003518 case DT_JMPREL:
Elliott Hughes4eeb1f12013-10-25 17:38:02 -07003519#if defined(USE_RELA)
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003520 plt_rela_ = reinterpret_cast<ElfW(Rela)*>(load_bias + d->d_un.d_ptr);
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07003521#else
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003522 plt_rel_ = reinterpret_cast<ElfW(Rel)*>(load_bias + d->d_un.d_ptr);
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07003523#endif
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003524 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003525
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003526 case DT_PLTRELSZ:
Elliott Hughes4eeb1f12013-10-25 17:38:02 -07003527#if defined(USE_RELA)
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003528 plt_rela_count_ = d->d_un.d_val / sizeof(ElfW(Rela));
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07003529#else
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003530 plt_rel_count_ = d->d_un.d_val / sizeof(ElfW(Rel));
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07003531#endif
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003532 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003533
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003534 case DT_PLTGOT:
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07003535#if defined(__mips__)
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003536 // Used by mips and mips64.
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003537 plt_got_ = reinterpret_cast<ElfW(Addr)**>(load_bias + d->d_un.d_ptr);
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07003538#endif
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07003539 // Ignore for other platforms... (because RTLD_LAZY is not supported)
3540 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003541
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003542 case DT_DEBUG:
3543 // Set the DT_DEBUG entry to the address of _r_debug for GDB
3544 // if the dynamic table is writable
Chris Dearman99186652014-02-06 20:36:51 -08003545// FIXME: not working currently for N64
3546// The flags for the LOAD and DYNAMIC program headers do not agree.
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07003547// The LOAD section containing the dynamic table has been mapped as
Chris Dearman99186652014-02-06 20:36:51 -08003548// read-only, but the DYNAMIC header claims it is writable.
3549#if !(defined(__mips__) && defined(__LP64__))
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003550 if ((dynamic_flags & PF_W) != 0) {
3551 d->d_un.d_val = reinterpret_cast<uintptr_t>(&_r_debug);
3552 }
Chris Dearman99186652014-02-06 20:36:51 -08003553#endif
Dmitriy Ivanovc6292ea2015-02-13 16:29:50 -08003554 break;
Elliott Hughes4eeb1f12013-10-25 17:38:02 -07003555#if defined(USE_RELA)
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003556 case DT_RELA:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003557 rela_ = reinterpret_cast<ElfW(Rela)*>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003558 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003559
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003560 case DT_RELASZ:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003561 rela_count_ = d->d_un.d_val / sizeof(ElfW(Rela));
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003562 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003563
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08003564 case DT_ANDROID_RELA:
3565 android_relocs_ = reinterpret_cast<uint8_t*>(load_bias + d->d_un.d_ptr);
3566 break;
3567
3568 case DT_ANDROID_RELASZ:
3569 android_relocs_size_ = d->d_un.d_val;
3570 break;
3571
3572 case DT_ANDROID_REL:
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003573 DL_ERR("unsupported DT_ANDROID_REL in \"%s\"", get_realpath());
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08003574 return false;
3575
3576 case DT_ANDROID_RELSZ:
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003577 DL_ERR("unsupported DT_ANDROID_RELSZ in \"%s\"", get_realpath());
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08003578 return false;
3579
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07003580 case DT_RELAENT:
3581 if (d->d_un.d_val != sizeof(ElfW(Rela))) {
Dmitriy Ivanovf240aa82014-09-16 23:34:20 -07003582 DL_ERR("invalid DT_RELAENT: %zd", static_cast<size_t>(d->d_un.d_val));
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07003583 return false;
3584 }
3585 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003586
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08003587 // Ignored (see DT_RELCOUNT comments for details).
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07003588 case DT_RELACOUNT:
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07003589 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003590
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003591 case DT_REL:
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003592 DL_ERR("unsupported DT_REL in \"%s\"", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003593 return false;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003594
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003595 case DT_RELSZ:
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003596 DL_ERR("unsupported DT_RELSZ in \"%s\"", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003597 return false;
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08003598
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07003599#else
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003600 case DT_REL:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003601 rel_ = reinterpret_cast<ElfW(Rel)*>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003602 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003603
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003604 case DT_RELSZ:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003605 rel_count_ = d->d_un.d_val / sizeof(ElfW(Rel));
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003606 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003607
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07003608 case DT_RELENT:
3609 if (d->d_un.d_val != sizeof(ElfW(Rel))) {
Dmitriy Ivanovf240aa82014-09-16 23:34:20 -07003610 DL_ERR("invalid DT_RELENT: %zd", static_cast<size_t>(d->d_un.d_val));
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07003611 return false;
3612 }
3613 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003614
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08003615 case DT_ANDROID_REL:
3616 android_relocs_ = reinterpret_cast<uint8_t*>(load_bias + d->d_un.d_ptr);
3617 break;
3618
3619 case DT_ANDROID_RELSZ:
3620 android_relocs_size_ = d->d_un.d_val;
3621 break;
3622
3623 case DT_ANDROID_RELA:
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003624 DL_ERR("unsupported DT_ANDROID_RELA in \"%s\"", get_realpath());
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08003625 return false;
3626
3627 case DT_ANDROID_RELASZ:
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003628 DL_ERR("unsupported DT_ANDROID_RELASZ in \"%s\"", get_realpath());
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08003629 return false;
3630
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003631 // "Indicates that all RELATIVE relocations have been concatenated together,
3632 // and specifies the RELATIVE relocation count."
3633 //
3634 // TODO: Spec also mentions that this can be used to optimize relocation process;
3635 // Not currently used by bionic linker - ignored.
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07003636 case DT_RELCOUNT:
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07003637 break;
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08003638
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003639 case DT_RELA:
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003640 DL_ERR("unsupported DT_RELA in \"%s\"", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003641 return false;
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08003642
3643 case DT_RELASZ:
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003644 DL_ERR("unsupported DT_RELASZ in \"%s\"", get_realpath());
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08003645 return false;
3646
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07003647#endif
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08003648 case DT_RELR:
3649 relr_ = reinterpret_cast<ElfW(Relr)*>(load_bias + d->d_un.d_ptr);
3650 break;
3651
3652 case DT_RELRSZ:
3653 relr_count_ = d->d_un.d_val / sizeof(ElfW(Relr));
3654 break;
3655
3656 case DT_RELRENT:
3657 if (d->d_un.d_val != sizeof(ElfW(Relr))) {
3658 DL_ERR("invalid DT_RELRENT: %zd", static_cast<size_t>(d->d_un.d_val));
3659 return false;
3660 }
3661 break;
3662
3663 // Ignored (see DT_RELCOUNT comments for details).
3664 case DT_RELRCOUNT:
3665 break;
3666
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003667 case DT_INIT:
Dimitry Ivanov55437462016-07-20 15:33:07 -07003668 init_func_ = reinterpret_cast<linker_ctor_function_t>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003669 DEBUG("%s constructors (DT_INIT) found at %p", get_realpath(), init_func_);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003670 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003671
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003672 case DT_FINI:
Dimitry Ivanov55437462016-07-20 15:33:07 -07003673 fini_func_ = reinterpret_cast<linker_dtor_function_t>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003674 DEBUG("%s destructors (DT_FINI) found at %p", get_realpath(), fini_func_);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003675 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003676
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003677 case DT_INIT_ARRAY:
Dimitry Ivanov55437462016-07-20 15:33:07 -07003678 init_array_ = reinterpret_cast<linker_ctor_function_t*>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003679 DEBUG("%s constructors (DT_INIT_ARRAY) found at %p", get_realpath(), init_array_);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003680 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003681
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003682 case DT_INIT_ARRAYSZ:
Dmitriy Ivanov1649e7e2015-01-22 16:04:25 -08003683 init_array_count_ = static_cast<uint32_t>(d->d_un.d_val) / sizeof(ElfW(Addr));
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003684 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003685
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003686 case DT_FINI_ARRAY:
Dimitry Ivanov55437462016-07-20 15:33:07 -07003687 fini_array_ = reinterpret_cast<linker_dtor_function_t*>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003688 DEBUG("%s destructors (DT_FINI_ARRAY) found at %p", get_realpath(), fini_array_);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003689 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003690
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003691 case DT_FINI_ARRAYSZ:
Dmitriy Ivanov1649e7e2015-01-22 16:04:25 -08003692 fini_array_count_ = static_cast<uint32_t>(d->d_un.d_val) / sizeof(ElfW(Addr));
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003693 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003694
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003695 case DT_PREINIT_ARRAY:
Dimitry Ivanov55437462016-07-20 15:33:07 -07003696 preinit_array_ = reinterpret_cast<linker_ctor_function_t*>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003697 DEBUG("%s constructors (DT_PREINIT_ARRAY) found at %p", get_realpath(), preinit_array_);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003698 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003699
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003700 case DT_PREINIT_ARRAYSZ:
Dmitriy Ivanov1649e7e2015-01-22 16:04:25 -08003701 preinit_array_count_ = static_cast<uint32_t>(d->d_un.d_val) / sizeof(ElfW(Addr));
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003702 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003703
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003704 case DT_TEXTREL:
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003705#if defined(__LP64__)
Dimitry Ivanov816676e2016-10-19 11:00:28 -07003706 DL_ERR("\"%s\" has text relocations", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003707 return false;
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003708#else
3709 has_text_relocations = true;
3710 break;
3711#endif
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003712
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003713 case DT_SYMBOLIC:
Dmitriy Ivanov96bc37f2014-09-29 12:10:36 -07003714 has_DT_SYMBOLIC = true;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003715 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003716
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003717 case DT_NEEDED:
3718 ++needed_count;
3719 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003720
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003721 case DT_FLAGS:
3722 if (d->d_un.d_val & DF_TEXTREL) {
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003723#if defined(__LP64__)
Dimitry Ivanov816676e2016-10-19 11:00:28 -07003724 DL_ERR("\"%s\" has text relocations", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003725 return false;
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003726#else
3727 has_text_relocations = true;
3728#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08003729 }
Dmitriy Ivanov96bc37f2014-09-29 12:10:36 -07003730 if (d->d_un.d_val & DF_SYMBOLIC) {
3731 has_DT_SYMBOLIC = true;
3732 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003733 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003734
Dmitriy Ivanov6cdeb522014-09-29 19:14:45 -07003735 case DT_FLAGS_1:
Dmitriy Ivanovd225a5e2014-08-28 14:12:12 -07003736 set_dt_flags_1(d->d_un.d_val);
Dmitriy Ivanov1b20daf2014-05-19 15:06:58 -07003737
Dmitriy Ivanovd225a5e2014-08-28 14:12:12 -07003738 if ((d->d_un.d_val & ~SUPPORTED_DT_FLAGS_1) != 0) {
Elliott Hughes9076b0c2018-02-28 11:29:45 -08003739 DL_WARN("Warning: \"%s\" has unsupported flags DT_FLAGS_1=%p "
3740 "(ignoring unsupported flags)",
3741 get_realpath(), reinterpret_cast<void*>(d->d_un.d_val));
Dmitriy Ivanov6cdeb522014-09-29 19:14:45 -07003742 }
3743 break;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003744#if defined(__mips__)
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003745 case DT_MIPS_RLD_MAP:
3746 // Set the DT_MIPS_RLD_MAP entry to the address of _r_debug for GDB.
3747 {
3748 r_debug** dp = reinterpret_cast<r_debug**>(load_bias + d->d_un.d_ptr);
3749 *dp = &_r_debug;
3750 }
3751 break;
Lazar Trsic83b44a92016-04-06 13:39:17 +02003752 case DT_MIPS_RLD_MAP_REL:
3753 // Set the DT_MIPS_RLD_MAP_REL entry to the address of _r_debug for GDB.
Raghu Gandham68815722014-12-18 19:12:19 -08003754 {
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07003755 r_debug** dp = reinterpret_cast<r_debug**>(
3756 reinterpret_cast<ElfW(Addr)>(d) + d->d_un.d_val);
Raghu Gandham68815722014-12-18 19:12:19 -08003757 *dp = &_r_debug;
3758 }
3759 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003760
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003761 case DT_MIPS_RLD_VERSION:
3762 case DT_MIPS_FLAGS:
3763 case DT_MIPS_BASE_ADDRESS:
3764 case DT_MIPS_UNREFEXTNO:
3765 break;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08003766
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003767 case DT_MIPS_SYMTABNO:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003768 mips_symtabno_ = d->d_un.d_val;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003769 break;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08003770
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003771 case DT_MIPS_LOCAL_GOTNO:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003772 mips_local_gotno_ = d->d_un.d_val;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003773 break;
3774
3775 case DT_MIPS_GOTSYM:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003776 mips_gotsym_ = d->d_un.d_val;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003777 break;
3778#endif
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003779 // Ignored: "Its use has been superseded by the DF_BIND_NOW flag"
3780 case DT_BIND_NOW:
3781 break;
3782
Dmitriy Ivanov513e29e2014-10-06 11:30:43 -07003783 case DT_VERSYM:
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07003784 versym_ = reinterpret_cast<ElfW(Versym)*>(load_bias + d->d_un.d_ptr);
3785 break;
3786
Dmitriy Ivanov513e29e2014-10-06 11:30:43 -07003787 case DT_VERDEF:
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07003788 verdef_ptr_ = load_bias + d->d_un.d_ptr;
3789 break;
Dmitriy Ivanov513e29e2014-10-06 11:30:43 -07003790 case DT_VERDEFNUM:
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07003791 verdef_cnt_ = d->d_un.d_val;
3792 break;
3793
Alexander Ivchenkoe8314332014-12-02 15:32:25 +03003794 case DT_VERNEED:
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07003795 verneed_ptr_ = load_bias + d->d_un.d_ptr;
3796 break;
3797
Alexander Ivchenkoe8314332014-12-02 15:32:25 +03003798 case DT_VERNEEDNUM:
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07003799 verneed_cnt_ = d->d_un.d_val;
Dmitriy Ivanov513e29e2014-10-06 11:30:43 -07003800 break;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003801
Evgenii Stepanov68650822015-06-10 13:38:39 -07003802 case DT_RUNPATH:
3803 // this is parsed after we have strtab initialized (see below).
3804 break;
3805
Ryan Prichardea41ab02019-01-23 16:33:03 -08003806 case DT_TLSDESC_GOT:
3807 case DT_TLSDESC_PLT:
3808 // These DT entries are used for lazy TLSDESC relocations. Bionic
3809 // resolves everything eagerly, so these can be ignored.
3810 break;
3811
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003812 default:
Dmitriy Ivanov8f61d992014-09-16 14:31:06 -07003813 if (!relocating_linker) {
Elliott Hughes6eae4cc2017-08-30 09:02:33 -07003814 const char* tag_name;
3815 if (d->d_tag == DT_RPATH) {
3816 tag_name = "DT_RPATH";
3817 } else if (d->d_tag == DT_ENCODING) {
3818 tag_name = "DT_ENCODING";
3819 } else if (d->d_tag >= DT_LOOS && d->d_tag <= DT_HIOS) {
3820 tag_name = "unknown OS-specific";
3821 } else if (d->d_tag >= DT_LOPROC && d->d_tag <= DT_HIPROC) {
3822 tag_name = "unknown processor-specific";
3823 } else {
3824 tag_name = "unknown";
3825 }
Elliott Hughes9076b0c2018-02-28 11:29:45 -08003826 DL_WARN("Warning: \"%s\" unused DT entry: %s (type %p arg %p) (ignoring)",
Elliott Hughes6eae4cc2017-08-30 09:02:33 -07003827 get_realpath(),
3828 tag_name,
3829 reinterpret_cast<void*>(d->d_tag),
3830 reinterpret_cast<void*>(d->d_un.d_val));
Dmitriy Ivanov8f61d992014-09-16 14:31:06 -07003831 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003832 break;
Brian Carlstromd4ee82d2013-02-28 15:58:45 -08003833 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003834 }
3835
Duane Sandbc425c72015-06-01 16:29:14 -07003836#if defined(__mips__) && !defined(__LP64__)
3837 if (!mips_check_and_adjust_fp_modes()) {
3838 return false;
3839 }
3840#endif
3841
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003842 DEBUG("si->base = %p, si->strtab = %p, si->symtab = %p",
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003843 reinterpret_cast<void*>(base), strtab_, symtab_);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003844
3845 // Sanity checks.
3846 if (relocating_linker && needed_count != 0) {
3847 DL_ERR("linker cannot have DT_NEEDED dependencies on other libraries");
3848 return false;
3849 }
Dmitriy Ivanov3597b802015-03-09 12:02:02 -07003850 if (nbucket_ == 0 && gnu_nbucket_ == 0) {
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003851 DL_ERR("empty/missing DT_HASH/DT_GNU_HASH in \"%s\" "
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07003852 "(new hash type from the future?)", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003853 return false;
3854 }
Yi Kong32bc0fc2018-08-02 17:31:13 -07003855 if (strtab_ == nullptr) {
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07003856 DL_ERR("empty/missing DT_STRTAB in \"%s\"", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003857 return false;
3858 }
Yi Kong32bc0fc2018-08-02 17:31:13 -07003859 if (symtab_ == nullptr) {
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07003860 DL_ERR("empty/missing DT_SYMTAB in \"%s\"", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003861 return false;
3862 }
Dmitriy Ivanov75108f42015-06-02 13:28:06 -07003863
Dmitriy Ivanov624b8f12015-06-08 10:41:33 -07003864 // second pass - parse entries relying on strtab
3865 for (ElfW(Dyn)* d = dynamic; d->d_tag != DT_NULL; ++d) {
Evgenii Stepanov68650822015-06-10 13:38:39 -07003866 switch (d->d_tag) {
3867 case DT_SONAME:
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07003868 set_soname(get_string(d->d_un.d_val));
Evgenii Stepanov68650822015-06-10 13:38:39 -07003869 break;
3870 case DT_RUNPATH:
Evgenii Stepanov68650822015-06-10 13:38:39 -07003871 set_dt_runpath(get_string(d->d_un.d_val));
3872 break;
Dmitriy Ivanov624b8f12015-06-08 10:41:33 -07003873 }
3874 }
3875
Dmitriy Ivanov75108f42015-06-02 13:28:06 -07003876 // Before M release linker was using basename in place of soname.
Dmitriy Ivanov19133522015-06-02 17:36:54 -07003877 // In the case when dt_soname is absent some apps stop working
Dmitriy Ivanov75108f42015-06-02 13:28:06 -07003878 // because they can't find dt_needed library by soname.
Elliott Hughes9076b0c2018-02-28 11:29:45 -08003879 // This workaround should keep them working. (Applies only
3880 // for apps targeting sdk version < M.) Make an exception for
3881 // the main executable and linker; they do not need to have dt_soname.
3882 // TODO: >= O the linker doesn't need this workaround.
Dimitry Ivanov3f660572016-09-09 10:00:39 -07003883 if (soname_ == nullptr &&
3884 this != solist_get_somain() &&
3885 (flags_ & FLAG_LINKER) == 0 &&
Elliott Hughes5bc78c82016-11-16 11:35:43 -08003886 get_application_target_sdk_version() < __ANDROID_API_M__) {
Dmitriy Ivanov75108f42015-06-02 13:28:06 -07003887 soname_ = basename(realpath_.c_str());
Elliott Hughes9076b0c2018-02-28 11:29:45 -08003888 DL_WARN_documented_change(__ANDROID_API_M__,
3889 "missing-soname-enforced-for-api-level-23",
3890 "\"%s\" has no DT_SONAME (will use %s instead)",
3891 get_realpath(), soname_);
3892
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07003893 // 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 -07003894 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003895 return true;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07003896}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08003897
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08003898bool soinfo::link_image(const soinfo_list_t& global_group, const soinfo_list_t& local_group,
Torne (Richard Coles)efbe9a52018-10-17 15:59:38 -04003899 const android_dlextinfo* extinfo, size_t* relro_fd_offset) {
dimitry965d06d2017-11-28 16:03:07 +01003900 if (is_image_linked()) {
3901 // already linked.
3902 return true;
3903 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08003904
Elliott Hughes90f96b92019-05-09 15:56:39 -07003905 if (g_is_ldd && !is_main_executable()) {
3906 async_safe_format_fd(STDOUT_FILENO, "\t%s => %s (%p)\n", get_soname(),
3907 get_realpath(), reinterpret_cast<void*>(base));
3908 }
3909
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08003910 local_group_root_ = local_group.front();
3911 if (local_group_root_ == nullptr) {
3912 local_group_root_ = this;
3913 }
3914
Dmitriy Ivanov19133522015-06-02 17:36:54 -07003915 if ((flags_ & FLAG_LINKER) == 0 && local_group_root_ == this) {
3916 target_sdk_version_ = get_application_target_sdk_version();
3917 }
3918
Dmitriy Ivanov7e4bbba2015-04-30 19:49:19 -07003919 VersionTracker version_tracker;
3920
3921 if (!version_tracker.init(this)) {
3922 return false;
3923 }
3924
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003925#if !defined(__LP64__)
3926 if (has_text_relocations) {
Elliott Hughes5bc78c82016-11-16 11:35:43 -08003927 // Fail if app is targeting M or above.
Elliott Hughes9076b0c2018-02-28 11:29:45 -08003928 int app_target_api_level = get_application_target_sdk_version();
3929 if (app_target_api_level >= __ANDROID_API_M__) {
Elliott Hughes763f6e12017-04-10 09:52:33 -07003930 DL_ERR_AND_LOG("\"%s\" has text relocations (https://android.googlesource.com/platform/"
3931 "bionic/+/master/android-changes-for-ndk-developers.md#Text-Relocations-"
3932 "Enforced-for-API-level-23)", get_realpath());
Dmitriy Ivanove4ad91f2015-06-12 15:00:31 -07003933 return false;
3934 }
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003935 // Make segments writable to allow text relocations to work properly. We will later call
Dmitriy Ivanov7e039932015-10-01 14:02:19 -07003936 // phdr_table_protect_segments() after all of them are applied.
Elliott Hughes9076b0c2018-02-28 11:29:45 -08003937 DL_WARN_documented_change(__ANDROID_API_M__,
3938 "Text-Relocations-Enforced-for-API-level-23",
3939 "\"%s\" has text relocations",
3940 get_realpath());
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07003941 add_dlwarning(get_realpath(), "text relocations");
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003942 if (phdr_table_unprotect_segments(phdr, phnum, load_bias) < 0) {
Elliott Hughes9076b0c2018-02-28 11:29:45 -08003943 DL_ERR("can't unprotect loadable segments for \"%s\": %s", get_realpath(), strerror(errno));
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003944 return false;
3945 }
3946 }
3947#endif
3948
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08003949 if (android_relocs_ != nullptr) {
3950 // check signature
3951 if (android_relocs_size_ > 3 &&
3952 android_relocs_[0] == 'A' &&
3953 android_relocs_[1] == 'P' &&
Dmitriy Ivanov18870d32015-04-22 13:10:04 -07003954 android_relocs_[2] == 'S' &&
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08003955 android_relocs_[3] == '2') {
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07003956 DEBUG("[ android relocating %s ]", get_realpath());
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08003957
3958 bool relocated = false;
3959 const uint8_t* packed_relocs = android_relocs_ + 4;
3960 const size_t packed_relocs_size = android_relocs_size_ - 4;
3961
Dmitriy Ivanov18870d32015-04-22 13:10:04 -07003962 relocated = relocate(
Dmitriy Ivanov7e4bbba2015-04-30 19:49:19 -07003963 version_tracker,
Dmitriy Ivanov18870d32015-04-22 13:10:04 -07003964 packed_reloc_iterator<sleb128_decoder>(
3965 sleb128_decoder(packed_relocs, packed_relocs_size)),
3966 global_group, local_group);
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08003967
3968 if (!relocated) {
3969 return false;
3970 }
3971 } else {
3972 DL_ERR("bad android relocation header.");
3973 return false;
3974 }
3975 }
3976
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08003977 if (relr_ != nullptr) {
3978 DEBUG("[ relocating %s relr ]", get_realpath());
3979 if (!relocate_relr()) {
3980 return false;
3981 }
3982 }
3983
Elliott Hughes4eeb1f12013-10-25 17:38:02 -07003984#if defined(USE_RELA)
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003985 if (rela_ != nullptr) {
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08003986 DEBUG("[ relocating %s rela ]", get_realpath());
Dmitriy Ivanov7e4bbba2015-04-30 19:49:19 -07003987 if (!relocate(version_tracker,
3988 plain_reloc_iterator(rela_, rela_count_), global_group, local_group)) {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003989 return false;
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07003990 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003991 }
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003992 if (plt_rela_ != nullptr) {
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08003993 DEBUG("[ relocating %s plt rela ]", get_realpath());
Dmitriy Ivanov7e4bbba2015-04-30 19:49:19 -07003994 if (!relocate(version_tracker,
3995 plain_reloc_iterator(plt_rela_, plt_rela_count_), global_group, local_group)) {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003996 return false;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08003997 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003998 }
Dmitriy Ivanov9aea1642014-09-11 15:16:03 -07003999#else
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08004000 if (rel_ != nullptr) {
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08004001 DEBUG("[ relocating %s rel ]", get_realpath());
Dmitriy Ivanov7e4bbba2015-04-30 19:49:19 -07004002 if (!relocate(version_tracker,
4003 plain_reloc_iterator(rel_, rel_count_), global_group, local_group)) {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07004004 return false;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08004005 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07004006 }
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08004007 if (plt_rel_ != nullptr) {
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08004008 DEBUG("[ relocating %s plt rel ]", get_realpath());
Dmitriy Ivanov7e4bbba2015-04-30 19:49:19 -07004009 if (!relocate(version_tracker,
4010 plain_reloc_iterator(plt_rel_, plt_rel_count_), global_group, local_group)) {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07004011 return false;
Brigid Smithc5a13ef2014-07-23 11:22:25 -07004012 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07004013 }
Dmitriy Ivanov9aea1642014-09-11 15:16:03 -07004014#endif
Brigid Smithc5a13ef2014-07-23 11:22:25 -07004015
Elliott Hughes4eeb1f12013-10-25 17:38:02 -07004016#if defined(__mips__)
Dmitriy Ivanovf39cb632015-04-30 20:17:03 -07004017 if (!mips_relocate_got(version_tracker, global_group, local_group)) {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07004018 return false;
4019 }
Raghu Gandhamd7daacb2012-07-31 12:07:22 -07004020#endif
4021
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07004022 DEBUG("[ finished linking %s ]", get_realpath());
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08004023
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00004024#if !defined(__LP64__)
4025 if (has_text_relocations) {
4026 // All relocations are done, we can protect our segments back to read-only.
4027 if (phdr_table_protect_segments(phdr, phnum, load_bias) < 0) {
4028 DL_ERR("can't protect segments for \"%s\": %s",
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07004029 get_realpath(), strerror(errno));
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00004030 return false;
4031 }
4032 }
4033#endif
4034
Mingwei Shibe910522015-11-12 07:02:14 +00004035 // We can also turn on GNU RELRO protection if we're not linking the dynamic linker
4036 // itself --- it can't make system calls yet, and will have to call protect_relro later.
4037 if (!is_linker() && !protect_relro()) {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07004038 return false;
4039 }
Nick Kralevich9ec0f032012-02-28 10:40:00 -08004040
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07004041 /* Handle serializing/sharing the RELRO segment */
4042 if (extinfo && (extinfo->flags & ANDROID_DLEXT_WRITE_RELRO)) {
4043 if (phdr_table_serialize_gnu_relro(phdr, phnum, load_bias,
Torne (Richard Coles)fa9f7f22019-04-02 17:04:42 -04004044 extinfo->relro_fd, relro_fd_offset) < 0) {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07004045 DL_ERR("failed serializing GNU RELRO section for \"%s\": %s",
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07004046 get_realpath(), strerror(errno));
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07004047 return false;
Torne (Richard Coles)183ad9d2014-02-27 13:18:00 +00004048 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07004049 } else if (extinfo && (extinfo->flags & ANDROID_DLEXT_USE_RELRO)) {
4050 if (phdr_table_map_gnu_relro(phdr, phnum, load_bias,
Torne (Richard Coles)efbe9a52018-10-17 15:59:38 -04004051 extinfo->relro_fd, relro_fd_offset) < 0) {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07004052 DL_ERR("failed mapping GNU RELRO section for \"%s\": %s",
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07004053 get_realpath(), strerror(errno));
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07004054 return false;
4055 }
4056 }
Torne (Richard Coles)183ad9d2014-02-27 13:18:00 +00004057
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07004058 notify_gdb_of_load(this);
dimitry965d06d2017-11-28 16:03:07 +01004059 set_image_linked();
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07004060 return true;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08004061}
4062
Mingwei Shibe910522015-11-12 07:02:14 +00004063bool soinfo::protect_relro() {
4064 if (phdr_table_protect_gnu_relro(phdr, phnum, load_bias) < 0) {
4065 DL_ERR("can't enable GNU RELRO protection for \"%s\": %s",
4066 get_realpath(), strerror(errno));
4067 return false;
4068 }
4069 return true;
4070}
4071
Jiyong Park02586a22017-05-20 01:01:24 +09004072static std::vector<android_namespace_t*> init_default_namespace_no_config(bool is_asan) {
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07004073 g_default_namespace.set_isolated(false);
Dimitry Ivanov77ad6422017-03-06 13:02:29 -08004074 auto default_ld_paths = is_asan ? kAsanDefaultLdPaths : kDefaultLdPaths;
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07004075
neo.chae2589f9d2016-10-04 11:00:27 +09004076 char real_path[PATH_MAX];
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07004077 std::vector<std::string> ld_default_paths;
Dimitry Ivanov77ad6422017-03-06 13:02:29 -08004078 for (size_t i = 0; default_ld_paths[i] != nullptr; ++i) {
4079 if (realpath(default_ld_paths[i], real_path) != nullptr) {
neo.chae2589f9d2016-10-04 11:00:27 +09004080 ld_default_paths.push_back(real_path);
4081 } else {
Dimitry Ivanov77ad6422017-03-06 13:02:29 -08004082 ld_default_paths.push_back(default_ld_paths[i]);
neo.chae2589f9d2016-10-04 11:00:27 +09004083 }
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07004084 }
4085
4086 g_default_namespace.set_default_library_paths(std::move(ld_default_paths));
Jiyong Park02586a22017-05-20 01:01:24 +09004087
4088 std::vector<android_namespace_t*> namespaces;
4089 namespaces.push_back(&g_default_namespace);
4090 return namespaces;
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08004091}
4092
Roland Levillaindc25f6c2019-07-02 16:40:19 +01004093// return /apex/<name>/etc/ld.config.txt from /apex/<name>/bin/*
Jiyong Park35833412018-10-26 14:45:21 +09004094static std::string get_ld_config_file_apex_path(const char* executable_path) {
4095 std::vector<std::string> paths = android::base::Split(executable_path, "/");
Roland Levillaindc25f6c2019-07-02 16:40:19 +01004096 if (paths.size() >= 5 && paths[1] == "apex" && paths[3] == "bin") {
Jiyong Park35833412018-10-26 14:45:21 +09004097 return std::string("/apex/") + paths[2] + "/etc/ld.config.txt";
4098 }
4099 return "";
4100}
4101
Logan Chien886b96e2018-05-08 17:52:18 +08004102static std::string get_ld_config_file_vndk_path() {
Logan Chienbcfe3cf2018-05-08 20:17:26 +08004103 if (android::base::GetBoolProperty("ro.vndk.lite", false)) {
4104 return kLdConfigVndkLiteFilePath;
4105 }
4106
Logan Chien886b96e2018-05-08 17:52:18 +08004107 std::string ld_config_file_vndk = kLdConfigFilePath;
4108 size_t insert_pos = ld_config_file_vndk.find_last_of('.');
4109 if (insert_pos == std::string::npos) {
4110 insert_pos = ld_config_file_vndk.length();
4111 }
4112 ld_config_file_vndk.insert(insert_pos, Config::get_vndk_version_string('.'));
4113 return ld_config_file_vndk;
4114}
4115
Jiyong Park35833412018-10-26 14:45:21 +09004116static std::string get_ld_config_file_path(const char* executable_path) {
Logan Chien886b96e2018-05-08 17:52:18 +08004117#ifdef USE_LD_CONFIG_FILE
4118 // This is a debugging/testing only feature. Must not be available on
4119 // production builds.
4120 const char* ld_config_file_env = getenv("LD_CONFIG_FILE");
4121 if (ld_config_file_env != nullptr && file_exists(ld_config_file_env)) {
4122 return ld_config_file_env;
4123 }
4124#endif
4125
Jiyong Park35833412018-10-26 14:45:21 +09004126 std::string path = get_ld_config_file_apex_path(executable_path);
4127 if (!path.empty()) {
4128 if (file_exists(path.c_str())) {
4129 return path;
4130 }
4131 DL_WARN("Warning: couldn't read config file \"%s\" for \"%s\"",
4132 path.c_str(), executable_path);
Logan Chien886b96e2018-05-08 17:52:18 +08004133 }
4134
Jiyong Park35833412018-10-26 14:45:21 +09004135 path = kLdConfigArchFilePath;
4136 if (file_exists(path.c_str())) {
4137 return path;
4138 }
4139
4140 path = get_ld_config_file_vndk_path();
4141 if (file_exists(path.c_str())) {
4142 return path;
Logan Chien886b96e2018-05-08 17:52:18 +08004143 }
4144
4145 return kLdConfigFilePath;
4146}
4147
Jiyong Park02586a22017-05-20 01:01:24 +09004148std::vector<android_namespace_t*> init_default_namespaces(const char* executable_path) {
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08004149 g_default_namespace.set_name("(default)");
4150
4151 soinfo* somain = solist_get_somain();
4152
4153 const char *interp = phdr_table_get_interpreter_name(somain->phdr, somain->phnum,
4154 somain->load_bias);
Dan Willemsen7ccc50d2017-09-18 21:28:14 -07004155 const char* bname = (interp != nullptr) ? basename(interp) : nullptr;
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08004156
4157 g_is_asan = bname != nullptr &&
4158 (strcmp(bname, "linker_asan") == 0 ||
4159 strcmp(bname, "linker_asan64") == 0);
4160
4161 const Config* config = nullptr;
4162
4163 std::string error_msg;
4164
Jiyong Park35833412018-10-26 14:45:21 +09004165 std::string ld_config_file_path = get_ld_config_file_path(executable_path);
Jiyong Park02586a22017-05-20 01:01:24 +09004166
Martin Stjernholm95252ee2019-02-22 22:48:59 +00004167 INFO("[ Reading linker config \"%s\" ]", ld_config_file_path.c_str());
Logan Chien886b96e2018-05-08 17:52:18 +08004168 if (!Config::read_binary_config(ld_config_file_path.c_str(),
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08004169 executable_path,
4170 g_is_asan,
4171 &config,
4172 &error_msg)) {
4173 if (!error_msg.empty()) {
Elliott Hughes9076b0c2018-02-28 11:29:45 -08004174 DL_WARN("Warning: couldn't read \"%s\" for \"%s\" (using default configuration instead): %s",
Logan Chien886b96e2018-05-08 17:52:18 +08004175 ld_config_file_path.c_str(),
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08004176 executable_path,
4177 error_msg.c_str());
4178 }
4179 config = nullptr;
4180 }
4181
4182 if (config == nullptr) {
Jiyong Park02586a22017-05-20 01:01:24 +09004183 return init_default_namespace_no_config(g_is_asan);
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08004184 }
4185
4186 const auto& namespace_configs = config->namespace_configs();
4187 std::unordered_map<std::string, android_namespace_t*> namespaces;
4188
4189 // 1. Initialize default namespace
4190 const NamespaceConfig* default_ns_config = config->default_namespace_config();
4191
4192 g_default_namespace.set_isolated(default_ns_config->isolated());
4193 g_default_namespace.set_default_library_paths(default_ns_config->search_paths());
4194 g_default_namespace.set_permitted_paths(default_ns_config->permitted_paths());
4195
4196 namespaces[default_ns_config->name()] = &g_default_namespace;
Justin Yun90de9f02017-07-07 16:21:53 +09004197 if (default_ns_config->visible()) {
4198 g_exported_namespaces[default_ns_config->name()] = &g_default_namespace;
4199 }
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08004200
4201 // 2. Initialize other namespaces
4202
4203 for (auto& ns_config : namespace_configs) {
4204 if (namespaces.find(ns_config->name()) != namespaces.end()) {
4205 continue;
4206 }
4207
4208 android_namespace_t* ns = new (g_namespace_allocator.alloc()) android_namespace_t();
4209 ns->set_name(ns_config->name());
4210 ns->set_isolated(ns_config->isolated());
4211 ns->set_default_library_paths(ns_config->search_paths());
4212 ns->set_permitted_paths(ns_config->permitted_paths());
Vic Yang2d020e42019-01-12 21:03:25 -08004213 ns->set_whitelisted_libs(ns_config->whitelisted_libs());
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08004214
4215 namespaces[ns_config->name()] = ns;
Jiyong Park01de74e2017-04-03 23:10:37 +09004216 if (ns_config->visible()) {
4217 g_exported_namespaces[ns_config->name()] = ns;
4218 }
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08004219 }
4220
4221 // 3. Establish links between namespaces
4222 for (auto& ns_config : namespace_configs) {
4223 auto it_from = namespaces.find(ns_config->name());
4224 CHECK(it_from != namespaces.end());
4225 android_namespace_t* namespace_from = it_from->second;
4226 for (const NamespaceLinkConfig& ns_link : ns_config->links()) {
4227 auto it_to = namespaces.find(ns_link.ns_name());
4228 CHECK(it_to != namespaces.end());
4229 android_namespace_t* namespace_to = it_to->second;
Logan Chien9ee45912018-01-18 12:05:09 +08004230 if (ns_link.allow_all_shared_libs()) {
4231 link_namespaces_all_libs(namespace_from, namespace_to);
4232 } else {
4233 link_namespaces(namespace_from, namespace_to, ns_link.shared_libs().c_str());
4234 }
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08004235 }
4236 }
4237 // we can no longer rely on the fact that libdl.so is part of default namespace
4238 // this is why we want to add ld-android.so to all namespaces from ld.config.txt
4239 soinfo* ld_android_so = solist_get_head();
dimitry8b142562018-05-09 15:22:38 +02004240
4241 // we also need vdso to be available for all namespaces (if present)
4242 soinfo* vdso = solist_get_vdso();
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08004243 for (auto it : namespaces) {
4244 it.second->add_soinfo(ld_android_so);
dimitry8b142562018-05-09 15:22:38 +02004245 if (vdso != nullptr) {
4246 it.second->add_soinfo(vdso);
4247 }
Jiyong Park02586a22017-05-20 01:01:24 +09004248 // somain and ld_preloads are added to these namespaces after LD_PRELOAD libs are linked
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08004249 }
4250
4251 set_application_target_sdk_version(config->target_sdk_version());
Jiyong Park02586a22017-05-20 01:01:24 +09004252
4253 std::vector<android_namespace_t*> created_namespaces;
4254 created_namespaces.reserve(namespaces.size());
Chih-Hung Hsieh0218e922018-12-11 10:22:11 -08004255 for (const auto& kv : namespaces) {
Jiyong Park02586a22017-05-20 01:01:24 +09004256 created_namespaces.push_back(kv.second);
4257 }
4258 return created_namespaces;
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08004259}
Jiyong Park01de74e2017-04-03 23:10:37 +09004260
4261// This function finds a namespace exported in ld.config.txt by its name.
4262// A namespace can be exported by setting .visible property to true.
4263android_namespace_t* get_exported_namespace(const char* name) {
4264 if (name == nullptr) {
4265 return nullptr;
4266 }
4267 auto it = g_exported_namespaces.find(std::string(name));
4268 if (it == g_exported_namespaces.end()) {
4269 return nullptr;
4270 }
4271 return it->second;
4272}
Vic Yangbb7e1232019-01-29 20:23:16 -08004273
4274void purge_unused_memory() {
4275 // For now, we only purge the memory used by LoadTask because we know those
4276 // are temporary objects.
4277 //
4278 // Purging other LinkerBlockAllocator hardly yields much because they hold
4279 // information about namespaces and opened libraries, which are not freed
4280 // when the control leaves the linker.
4281 //
4282 // Purging BionicAllocator may give us a few dirty pages back, but those pages
4283 // would be already zeroed out, so they compress easily in ZRAM. Therefore,
4284 // it is not worth munmap()'ing those pages.
4285 TypeBasedAllocator<LoadTask>::purge();
4286}