blob: dc819c18d15311f368a0b89b59470bd34eb85ace [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
Jiyong Park25bedfd2019-05-16 21:00:39 +090079static bool g_anonymous_namespace_set = false;
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -070080static android_namespace_t* g_anonymous_namespace = &g_default_namespace;
Jiyong Park01de74e2017-04-03 23:10:37 +090081static std::unordered_map<std::string, android_namespace_t*> g_exported_namespaces;
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -070082
Dmitriy Ivanov600bc3c2015-03-10 15:43:50 -070083static LinkerTypeAllocator<soinfo> g_soinfo_allocator;
84static LinkerTypeAllocator<LinkedListEntry<soinfo>> g_soinfo_links_allocator;
Magnus Malmbornba98d922012-09-12 13:00:55 +020085
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -070086static LinkerTypeAllocator<android_namespace_t> g_namespace_allocator;
Dimitry Ivanovaca299a2016-04-11 12:42:58 -070087static LinkerTypeAllocator<LinkedListEntry<android_namespace_t>> g_namespace_list_allocator;
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -070088
dimitryfe1b27c2017-08-11 14:43:21 +020089static const char* const kLdConfigArchFilePath = "/system/etc/ld.config." ABI_STRING ".txt";
90
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -080091static const char* const kLdConfigFilePath = "/system/etc/ld.config.txt";
Logan Chienbcfe3cf2018-05-08 20:17:26 +080092static const char* const kLdConfigVndkLiteFilePath = "/system/etc/ld.config.vndk_lite.txt";
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -080093
Kiyoung Kim35e3b4b2019-08-07 19:24:13 +090094static const char* const kLdGeneratedConfigFilePath = "/dev/linkerconfig/ld.config.txt";
95
Elliott Hughes4eeb1f12013-10-25 17:38:02 -070096#if defined(__LP64__)
Victor Chang6cb719f2019-02-06 17:19:10 +000097static const char* const kSystemLibDir = "/system/lib64";
98static const char* const kOdmLibDir = "/odm/lib64";
99static const char* const kVendorLibDir = "/vendor/lib64";
100static const char* const kAsanSystemLibDir = "/data/asan/system/lib64";
101static const char* const kAsanOdmLibDir = "/data/asan/odm/lib64";
102static const char* const kAsanVendorLibDir = "/data/asan/vendor/lib64";
103static const char* const kRuntimeApexLibDir = "/apex/com.android.runtime/lib64";
Elliott Hughes011bc0b2013-10-08 14:27:10 -0700104#else
Victor Chang6cb719f2019-02-06 17:19:10 +0000105static const char* const kSystemLibDir = "/system/lib";
106static const char* const kOdmLibDir = "/odm/lib";
107static const char* const kVendorLibDir = "/vendor/lib";
108static const char* const kAsanSystemLibDir = "/data/asan/system/lib";
109static const char* const kAsanOdmLibDir = "/data/asan/odm/lib";
110static const char* const kAsanVendorLibDir = "/data/asan/vendor/lib";
111static const char* const kRuntimeApexLibDir = "/apex/com.android.runtime/lib";
Elliott Hughes011bc0b2013-10-08 14:27:10 -0700112#endif
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700113
Vishwath Mohan4113def2017-03-29 15:31:34 -0700114static const char* const kAsanLibDirPrefix = "/data/asan";
115
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700116static const char* const kDefaultLdPaths[] = {
117 kSystemLibDir,
Alin Jerpelea074a9fd2017-09-25 17:47:49 +0200118 kOdmLibDir,
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700119 kVendorLibDir,
Dmitriy Ivanov851135b2014-08-29 12:02:36 -0700120 nullptr
Elliott Hughes124fae92012-10-31 14:20:03 -0700121};
David Bartleybc3a5c22009-06-02 18:27:28 -0700122
Evgenii Stepanovd640b222015-07-10 17:54:01 -0700123static const char* const kAsanDefaultLdPaths[] = {
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700124 kAsanSystemLibDir,
125 kSystemLibDir,
Alin Jerpelea074a9fd2017-09-25 17:47:49 +0200126 kAsanOdmLibDir,
127 kOdmLibDir,
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700128 kAsanVendorLibDir,
129 kVendorLibDir,
Evgenii Stepanovd640b222015-07-10 17:54:01 -0700130 nullptr
131};
132
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700133// Is ASAN enabled?
134static bool g_is_asan = false;
135
Evgenii Stepanov0a3637d2016-07-06 13:20:59 -0700136static CFIShadowWriter g_cfi_shadow;
137
138CFIShadowWriter* get_cfi_shadow() {
139 return &g_cfi_shadow;
140}
141
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700142static bool is_system_library(const std::string& realpath) {
143 for (const auto& dir : g_default_namespace.get_default_library_paths()) {
144 if (file_is_in_dir(realpath, dir)) {
145 return true;
146 }
147 }
148 return false;
149}
150
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700151// Checks if the file exists and not a directory.
152static bool file_exists(const char* path) {
Dimitry Ivanov4cf70242016-08-11 11:11:52 -0700153 struct stat s;
154
155 if (stat(path, &s) != 0) {
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700156 return false;
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700157 }
Dimitry Ivanov4cf70242016-08-11 11:11:52 -0700158
159 return S_ISREG(s.st_mode);
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -0700160}
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700161
Dimitry Ivanov35c8e3b2017-02-27 12:17:47 -0800162static std::string resolve_soname(const std::string& name) {
163 // We assume that soname equals to basename here
164
165 // TODO(dimitry): consider having honest absolute-path -> soname resolution
166 // note that since we might end up refusing to load this library because
167 // it is not in shared libs list we need to get the soname without actually loading
168 // the library.
169 //
170 // On the other hand there are several places where we already assume that
171 // soname == basename in particular for any not-loaded library mentioned
172 // in DT_NEEDED list.
173 return basename(name.c_str());
174}
175
176static bool maybe_accessible_via_namespace_links(android_namespace_t* ns, const char* name) {
177 std::string soname = resolve_soname(name);
178 for (auto& ns_link : ns->linked_namespaces()) {
179 if (ns_link.is_accessible(soname.c_str())) {
180 return true;
181 }
182 }
183
184 return false;
185}
186
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700187// TODO(dimitry): The grey-list is a workaround for http://b/26394120 ---
188// gradually remove libraries from this list until it is gone.
Dimitry Ivanov35c8e3b2017-02-27 12:17:47 -0800189static bool is_greylisted(android_namespace_t* ns, const char* name, const soinfo* needed_by) {
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700190 static const char* const kLibraryGreyList[] = {
191 "libandroid_runtime.so",
192 "libbinder.so",
193 "libcrypto.so",
194 "libcutils.so",
195 "libexpat.so",
196 "libgui.so",
197 "libmedia.so",
198 "libnativehelper.so",
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700199 "libssl.so",
200 "libstagefright.so",
201 "libsqlite.so",
202 "libui.so",
203 "libutils.so",
204 "libvorbisidec.so",
205 nullptr
206 };
207
Elliott Hughes5bc78c82016-11-16 11:35:43 -0800208 // If you're targeting N, you don't get the greylist.
Elliott Hughes9e27e582017-03-23 17:42:49 -0700209 if (g_greylist_disabled || get_application_target_sdk_version() >= __ANDROID_API_N__) {
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700210 return false;
211 }
212
213 // if the library needed by a system library - implicitly assume it
Dimitry Ivanov35c8e3b2017-02-27 12:17:47 -0800214 // is greylisted unless it is in the list of shared libraries for one or
215 // more linked namespaces
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700216 if (needed_by != nullptr && is_system_library(needed_by->get_realpath())) {
Dimitry Ivanov35c8e3b2017-02-27 12:17:47 -0800217 return !maybe_accessible_via_namespace_links(ns, name);
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700218 }
219
220 // if this is an absolute path - make sure it points to /system/lib(64)
221 if (name[0] == '/' && dirname(name) == kSystemLibDir) {
222 // and reduce the path to basename
223 name = basename(name);
224 }
225
226 for (size_t i = 0; kLibraryGreyList[i] != nullptr; ++i) {
227 if (strcmp(name, kLibraryGreyList[i]) == 0) {
228 return true;
229 }
230 }
231
232 return false;
233}
234// END OF WORKAROUND
235
Victor Chang6cb719f2019-02-06 17:19:10 +0000236// Workaround for dlopen(/system/lib(64)/<soname>) when .so is in /apex. http://b/121248172
237/**
238 * Translate /system path to /apex path if needed
239 * The workaround should work only when targetSdkVersion < Q.
240 *
241 * param out_name_to_apex pointing to /apex path
242 * return true if translation is needed
243 */
244static bool translateSystemPathToApexPath(const char* name, std::string* out_name_to_apex) {
245 static const char* const kSystemToRuntimeApexLibs[] = {
246 "libicuuc.so",
247 "libicui18n.so",
248 };
249 // New mapping for new apex should be added below
250
251 // Nothing to do if target sdk version is Q or above
252 if (get_application_target_sdk_version() >= __ANDROID_API_Q__) {
253 return false;
254 }
255
256 // If the path isn't /system/lib, there's nothing to do.
257 if (name == nullptr || dirname(name) != kSystemLibDir) {
258 return false;
259 }
260
261 const char* base_name = basename(name);
262
263 for (const char* soname : kSystemToRuntimeApexLibs) {
264 if (strcmp(base_name, soname) == 0) {
265 *out_name_to_apex = std::string(kRuntimeApexLibDir) + "/" + base_name;
266 return true;
267 }
268 }
269
270 return false;
271}
272// End Workaround for dlopen(/system/lib/<soname>) when .so is in /apex.
273
Dmitriy Ivanovd165f562015-03-23 18:43:02 -0700274static std::vector<std::string> g_ld_preload_names;
Elliott Hughesa4aafd12014-01-13 16:37:47 -0800275
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800276#if STATS
Elliott Hughesbedfe382012-08-14 14:07:59 -0700277struct linker_stats_t {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700278 int count[kRelocMax];
Elliott Hughesbedfe382012-08-14 14:07:59 -0700279};
280
281static linker_stats_t linker_stats;
282
Dmitriy Ivanov114ff692015-01-14 11:36:38 -0800283void count_relocation(RelocationKind kind) {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700284 ++linker_stats.count[kind];
Elliott Hughesbedfe382012-08-14 14:07:59 -0700285}
Vic Yang542db792019-07-25 10:39:27 -0700286
287void print_linker_stats() {
Vic Yang521ad072019-07-25 11:05:33 -0700288 PRINT("RELO STATS: %s: %d abs, %d rel, %d copy, %d symbol (%d cached)",
289 g_argv[0],
Vic Yang542db792019-07-25 10:39:27 -0700290 linker_stats.count[kRelocAbsolute],
291 linker_stats.count[kRelocRelative],
292 linker_stats.count[kRelocCopy],
Vic Yang521ad072019-07-25 11:05:33 -0700293 linker_stats.count[kRelocSymbol],
294 linker_stats.count[kRelocSymbolCached]);
Vic Yang542db792019-07-25 10:39:27 -0700295}
Elliott Hughesbedfe382012-08-14 14:07:59 -0700296#else
Dmitriy Ivanov114ff692015-01-14 11:36:38 -0800297void count_relocation(RelocationKind) {
Elliott Hughesbedfe382012-08-14 14:07:59 -0700298}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800299#endif
300
301#if COUNT_PAGES
Dmitriy Ivanov114ff692015-01-14 11:36:38 -0800302uint32_t bitmask[4096];
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800303#endif
304
Elliott Hughesbedfe382012-08-14 14:07:59 -0700305static void notify_gdb_of_load(soinfo* info) {
Dimitry Ivanove97d8ed2016-03-01 15:55:56 -0800306 if (info->is_linker() || info->is_main_executable()) {
307 // gdb already knows about the linker and the main executable.
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700308 return;
309 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800310
Dimitry Ivanov6b788ee2016-02-17 16:08:03 -0800311 link_map* map = &(info->link_map_head);
Nicolas Geoffray0fa54102016-02-18 09:31:24 +0000312
Dimitry Ivanov6b788ee2016-02-17 16:08:03 -0800313 map->l_addr = info->load_bias;
314 // link_map l_name field is not const.
315 map->l_name = const_cast<char*>(info->get_realpath());
316 map->l_ld = info->dynamic;
Nicolas Geoffray0fa54102016-02-18 09:31:24 +0000317
Dimitry Ivanove97d8ed2016-03-01 15:55:56 -0800318 CHECK(map->l_name != nullptr);
319 CHECK(map->l_name[0] != '\0');
320
Dimitry Ivanov6b788ee2016-02-17 16:08:03 -0800321 notify_gdb_of_load(map);
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -0700322}
323
Elliott Hughesbedfe382012-08-14 14:07:59 -0700324static void notify_gdb_of_unload(soinfo* info) {
Dimitry Ivanov6b788ee2016-02-17 16:08:03 -0800325 notify_gdb_of_unload(&(info->link_map_head));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800326}
327
Dmitriy Ivanovd59e5002014-05-09 09:10:14 -0700328LinkedListEntry<soinfo>* SoinfoListAllocator::alloc() {
329 return g_soinfo_links_allocator.alloc();
330}
331
332void SoinfoListAllocator::free(LinkedListEntry<soinfo>* entry) {
333 g_soinfo_links_allocator.free(entry);
334}
335
Dimitry Ivanovaca299a2016-04-11 12:42:58 -0700336LinkedListEntry<android_namespace_t>* NamespaceListAllocator::alloc() {
337 return g_namespace_list_allocator.alloc();
338}
339
340void NamespaceListAllocator::free(LinkedListEntry<android_namespace_t>* entry) {
341 g_namespace_list_allocator.free(entry);
342}
343
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700344soinfo* soinfo_alloc(android_namespace_t* ns, const char* name,
Ryan Prichard8f639a42018-10-01 23:10:05 -0700345 const struct stat* file_stat, off64_t file_offset,
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700346 uint32_t rtld_flags) {
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -0700347 if (strlen(name) >= PATH_MAX) {
Elliott Hughes7b0af7a2017-09-15 16:09:22 -0700348 async_safe_fatal("library name \"%s\" too long", name);
Magnus Malmbornba98d922012-09-12 13:00:55 +0200349 }
350
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700351 TRACE("name %s: allocating soinfo for ns=%p", name, ns);
352
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -0700353 soinfo* si = new (g_soinfo_allocator.alloc()) soinfo(ns, name, file_stat,
354 file_offset, rtld_flags);
Dmitriy Ivanovd59e5002014-05-09 09:10:14 -0700355
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700356 solist_add_soinfo(si);
Magnus Malmbornba98d922012-09-12 13:00:55 +0200357
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -0700358 si->generate_handle();
359 ns->add_soinfo(si);
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -0700360
Elliott Hughesca0c11b2013-03-12 10:40:45 -0700361 TRACE("name %s: allocated soinfo @ %p", name, si);
Magnus Malmbornba98d922012-09-12 13:00:55 +0200362 return si;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800363}
364
Elliott Hughesfaf05ba2014-02-11 16:59:37 -0800365static void soinfo_free(soinfo* si) {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700366 if (si == nullptr) {
367 return;
368 }
369
370 if (si->base != 0 && si->size != 0) {
Dimitry Ivanovf45b0e92016-01-15 11:13:35 -0800371 if (!si->is_mapped_by_caller()) {
372 munmap(reinterpret_cast<void*>(si->base), si->size);
373 } else {
374 // remap the region as PROT_NONE, MAP_ANONYMOUS | MAP_NORESERVE
375 mmap(reinterpret_cast<void*>(si->base), si->size, PROT_NONE,
376 MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
377 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700378 }
379
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -0700380 TRACE("name %s: freeing soinfo @ %p", si->get_realpath(), si);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700381
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700382 if (!solist_remove_soinfo(si)) {
dimitry965d06d2017-11-28 16:03:07 +0100383 async_safe_fatal("soinfo=%p is not in soinfo_list (double unload?)", si);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700384 }
Elliott Hughes46882792012-08-03 16:49:39 -0700385
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700386 // clear links to/from si
387 si->remove_all_links();
Dmitriy Ivanovd59e5002014-05-09 09:10:14 -0700388
Dmitriy Ivanov609f11b2015-07-08 15:26:46 -0700389 si->~soinfo();
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700390 g_soinfo_allocator.free(si);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800391}
392
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -0700393static void parse_path(const char* path, const char* delimiters,
394 std::vector<std::string>* resolved_paths) {
395 std::vector<std::string> paths;
396 split_path(path, delimiters, &paths);
397 resolve_paths(paths, resolved_paths);
398}
399
Elliott Hughescade4c32012-12-20 14:42:14 -0800400static void parse_LD_LIBRARY_PATH(const char* path) {
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -0700401 std::vector<std::string> ld_libary_paths;
402 parse_path(path, ":", &ld_libary_paths);
403 g_default_namespace.set_ld_library_paths(std::move(ld_libary_paths));
Elliott Hughescade4c32012-12-20 14:42:14 -0800404}
405
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -0700406static bool realpath_fd(int fd, std::string* realpath) {
Vic Yangd8bef672019-05-15 21:10:22 -0700407 // proc_self_fd needs to be large enough to hold "/proc/self/fd/" plus an
408 // integer, plus the NULL terminator.
409 char proc_self_fd[32];
410 // We want to statically allocate this large buffer so that we don't grow
411 // the stack by too much.
412 static char buf[PATH_MAX];
413
414 async_safe_format_buffer(proc_self_fd, sizeof(proc_self_fd), "/proc/self/fd/%d", fd);
415 auto length = readlink(proc_self_fd, buf, sizeof(buf));
416 if (length == -1) {
Tom Cherry66bc4282018-11-08 13:40:52 -0800417 if (!is_first_stage_init()) {
Vic Yangd8bef672019-05-15 21:10:22 -0700418 PRINT("readlink(\"%s\") failed: %s [fd=%d]", proc_self_fd, strerror(errno), fd);
Tom Cherry66bc4282018-11-08 13:40:52 -0800419 }
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -0700420 return false;
421 }
422
Vic Yangd8bef672019-05-15 21:10:22 -0700423 realpath->assign(buf, length);
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -0700424 return true;
425}
426
Elliott Hughes4eeb1f12013-10-25 17:38:02 -0700427#if defined(__arm__)
Elliott Hughes46882792012-08-03 16:49:39 -0700428
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700429// For a given PC, find the .so that it belongs to.
430// Returns the base address of the .ARM.exidx section
431// for that .so, and the number of 8-byte entries
432// in that section (via *pcount).
433//
434// Intended to be called by libc's __gnu_Unwind_Find_exidx().
Dimitry Ivanovd9e427c2016-11-22 16:55:25 -0800435_Unwind_Ptr do_dl_unwind_find_exidx(_Unwind_Ptr pc, int* pcount) {
Peter Collingbourneb39cb3c2019-03-01 13:12:49 -0800436 if (soinfo* si = find_containing_library(reinterpret_cast<void*>(pc))) {
437 *pcount = si->ARM_exidx_count;
438 return reinterpret_cast<_Unwind_Ptr>(si->ARM_exidx);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700439 }
440 *pcount = 0;
Elliott Hughesf2c6ad62017-04-21 10:25:56 -0700441 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800442}
Elliott Hughes46882792012-08-03 16:49:39 -0700443
Christopher Ferris24053a42013-08-19 17:45:09 -0700444#endif
Elliott Hughes46882792012-08-03 16:49:39 -0700445
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700446// Here, we only have to provide a callback to iterate across all the
447// loaded libraries. gcc_eh does the rest.
Dmitriy Ivanov7271caf2015-06-29 14:48:25 -0700448int do_dl_iterate_phdr(int (*cb)(dl_phdr_info* info, size_t size, void* data), void* data) {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700449 int rv = 0;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700450 for (soinfo* si = solist_get_head(); si != nullptr; si = si->next) {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700451 dl_phdr_info dl_info;
452 dl_info.dlpi_addr = si->link_map_head.l_addr;
453 dl_info.dlpi_name = si->link_map_head.l_name;
454 dl_info.dlpi_phdr = si->phdr;
455 dl_info.dlpi_phnum = si->phnum;
456 rv = cb(&dl_info, sizeof(dl_phdr_info), data);
457 if (rv != 0) {
458 break;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800459 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700460 }
461 return rv;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800462}
Elliott Hughes46882792012-08-03 16:49:39 -0700463
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800464
Dmitriy Ivanov2a815362015-04-09 13:42:33 -0700465bool soinfo_do_lookup(soinfo* si_from, const char* name, const version_info* vi,
Dimitry Ivanovb943f302016-08-03 16:00:10 -0700466 soinfo** si_found_in, const soinfo_list_t& global_group,
467 const soinfo_list_t& local_group, const ElfW(Sym)** symbol) {
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -0800468 SymbolName symbol_name(name);
Dmitriy Ivanov2a815362015-04-09 13:42:33 -0700469 const ElfW(Sym)* s = nullptr;
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700470
Dmitriy Ivanov96bc37f2014-09-29 12:10:36 -0700471 /* "This element's presence in a shared object library alters the dynamic linker's
472 * symbol resolution algorithm for references within the library. Instead of starting
473 * a symbol search with the executable file, the dynamic linker starts from the shared
474 * object itself. If the shared object fails to supply the referenced symbol, the
475 * dynamic linker then searches the executable file and other shared objects as usual."
476 *
477 * http://www.sco.com/developers/gabi/2012-12-31/ch5.dynamic.html
478 *
479 * Note that this is unlikely since static linker avoids generating
480 * relocations for -Bsymbolic linked dynamic executables.
481 */
Dmitriy Ivanovd225a5e2014-08-28 14:12:12 -0700482 if (si_from->has_DT_SYMBOLIC) {
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -0700483 DEBUG("%s: looking up %s in local scope (DT_SYMBOLIC)", si_from->get_realpath(), name);
Dmitriy Ivanov2a815362015-04-09 13:42:33 -0700484 if (!si_from->find_symbol_by_name(symbol_name, vi, &s)) {
485 return false;
486 }
487
Dmitriy Ivanov8f61d992014-09-16 14:31:06 -0700488 if (s != nullptr) {
Dmitriy Ivanovd225a5e2014-08-28 14:12:12 -0700489 *si_found_in = si_from;
Dmitriy Ivanov96bc37f2014-09-29 12:10:36 -0700490 }
491 }
492
Dmitriy Ivanovd225a5e2014-08-28 14:12:12 -0700493 // 1. Look for it in global_group
494 if (s == nullptr) {
Dmitriy Ivanov2a815362015-04-09 13:42:33 -0700495 bool error = false;
Dmitriy Ivanovd225a5e2014-08-28 14:12:12 -0700496 global_group.visit([&](soinfo* global_si) {
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -0700497 DEBUG("%s: looking up %s in %s (from global group)",
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -0700498 si_from->get_realpath(), name, global_si->get_realpath());
Dmitriy Ivanov2a815362015-04-09 13:42:33 -0700499 if (!global_si->find_symbol_by_name(symbol_name, vi, &s)) {
500 error = true;
501 return false;
502 }
503
Dmitriy Ivanov96bc37f2014-09-29 12:10:36 -0700504 if (s != nullptr) {
Dmitriy Ivanovd225a5e2014-08-28 14:12:12 -0700505 *si_found_in = global_si;
506 return false;
Dmitriy Ivanov96bc37f2014-09-29 12:10:36 -0700507 }
Dmitriy Ivanovc2048942014-08-29 10:15:25 -0700508
Dmitriy Ivanovd225a5e2014-08-28 14:12:12 -0700509 return true;
510 });
Dmitriy Ivanov2a815362015-04-09 13:42:33 -0700511
512 if (error) {
513 return false;
514 }
Dmitriy Ivanov96bc37f2014-09-29 12:10:36 -0700515 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700516
Dmitriy Ivanovd225a5e2014-08-28 14:12:12 -0700517 // 2. Look for it in the local group
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700518 if (s == nullptr) {
Dmitriy Ivanov2a815362015-04-09 13:42:33 -0700519 bool error = false;
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700520 local_group.visit([&](soinfo* local_si) {
Dmitriy Ivanovd225a5e2014-08-28 14:12:12 -0700521 if (local_si == si_from && si_from->has_DT_SYMBOLIC) {
Dmitriy Ivanove47b3f82014-10-23 14:19:07 -0700522 // we already did this - skip
523 return true;
524 }
525
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -0700526 DEBUG("%s: looking up %s in %s (from local group)",
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -0700527 si_from->get_realpath(), name, local_si->get_realpath());
Dmitriy Ivanov2a815362015-04-09 13:42:33 -0700528 if (!local_si->find_symbol_by_name(symbol_name, vi, &s)) {
529 error = true;
530 return false;
531 }
532
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700533 if (s != nullptr) {
Dmitriy Ivanovd225a5e2014-08-28 14:12:12 -0700534 *si_found_in = local_si;
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700535 return false;
536 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700537
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700538 return true;
539 });
Dmitriy Ivanov2a815362015-04-09 13:42:33 -0700540
541 if (error) {
542 return false;
543 }
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700544 }
545
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700546 if (s != nullptr) {
547 TRACE_TYPE(LOOKUP, "si %s sym %s s->st_value = %p, "
548 "found in %s, base = %p, load bias = %p",
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -0700549 si_from->get_realpath(), name, reinterpret_cast<void*>(s->st_value),
550 (*si_found_in)->get_realpath(), reinterpret_cast<void*>((*si_found_in)->base),
Dmitriy Ivanovd225a5e2014-08-28 14:12:12 -0700551 reinterpret_cast<void*>((*si_found_in)->load_bias));
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -0700552 }
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700553
Dmitriy Ivanov2a815362015-04-09 13:42:33 -0700554 *symbol = s;
555 return true;
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700556}
557
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700558ProtectedDataGuard::ProtectedDataGuard() {
559 if (ref_count_++ == 0) {
560 protect_data(PROT_READ | PROT_WRITE);
561 }
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700562
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700563 if (ref_count_ == 0) { // overflow
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700564 async_safe_fatal("Too many nested calls to dlopen()");
Dmitriy Ivanov279a22f2015-01-23 12:03:53 -0800565 }
Dimitry Ivanov68e6c032017-02-01 12:55:11 -0800566}
Dmitriy Ivanov279a22f2015-01-23 12:03:53 -0800567
Dimitry Ivanov68e6c032017-02-01 12:55:11 -0800568ProtectedDataGuard::~ProtectedDataGuard() {
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700569 if (--ref_count_ == 0) {
570 protect_data(PROT_READ);
Dmitriy Ivanov279a22f2015-01-23 12:03:53 -0800571 }
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700572}
Dmitriy Ivanov279a22f2015-01-23 12:03:53 -0800573
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700574void ProtectedDataGuard::protect_data(int protection) {
575 g_soinfo_allocator.protect_all(protection);
576 g_soinfo_links_allocator.protect_all(protection);
577 g_namespace_allocator.protect_all(protection);
578 g_namespace_list_allocator.protect_all(protection);
579}
Dmitriy Ivanov279a22f2015-01-23 12:03:53 -0800580
581size_t ProtectedDataGuard::ref_count_ = 0;
582
Dmitriy Ivanov0cd83eb2014-09-01 16:15:52 -0700583// Each size has it's own allocator.
584template<size_t size>
585class SizeBasedAllocator {
586 public:
587 static void* alloc() {
588 return allocator_.alloc();
589 }
Dmitriy Ivanov4bea4982014-08-29 14:01:48 -0700590
Dmitriy Ivanov0cd83eb2014-09-01 16:15:52 -0700591 static void free(void* ptr) {
592 allocator_.free(ptr);
593 }
Dmitriy Ivanov4bea4982014-08-29 14:01:48 -0700594
Vic Yangbb7e1232019-01-29 20:23:16 -0800595 static void purge() {
596 allocator_.purge();
597 }
598
Dmitriy Ivanov0cd83eb2014-09-01 16:15:52 -0700599 private:
600 static LinkerBlockAllocator allocator_;
601};
602
603template<size_t size>
604LinkerBlockAllocator SizeBasedAllocator<size>::allocator_(size);
605
606template<typename T>
607class TypeBasedAllocator {
608 public:
609 static T* alloc() {
610 return reinterpret_cast<T*>(SizeBasedAllocator<sizeof(T)>::alloc());
611 }
612
613 static void free(T* ptr) {
614 SizeBasedAllocator<sizeof(T)>::free(ptr);
615 }
Vic Yangbb7e1232019-01-29 20:23:16 -0800616
617 static void purge() {
618 SizeBasedAllocator<sizeof(T)>::purge();
619 }
Dmitriy Ivanov0cd83eb2014-09-01 16:15:52 -0700620};
621
Dmitriy Ivanov14669a92014-09-05 16:42:53 -0700622class LoadTask {
623 public:
624 struct deleter_t {
625 void operator()(LoadTask* t) {
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700626 t->~LoadTask();
Dmitriy Ivanov14669a92014-09-05 16:42:53 -0700627 TypeBasedAllocator<LoadTask>::free(t);
628 }
629 };
630
Dmitriy Ivanov14669a92014-09-05 16:42:53 -0700631 static deleter_t deleter;
632
Dimitry Ivanov7d429d32017-02-01 15:28:52 -0800633 static LoadTask* create(const char* name,
634 soinfo* needed_by,
Jiyong Park02586a22017-05-20 01:01:24 +0900635 android_namespace_t* start_from,
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700636 std::unordered_map<const soinfo*, ElfReader>* readers_map) {
Dmitriy Ivanov14669a92014-09-05 16:42:53 -0700637 LoadTask* ptr = TypeBasedAllocator<LoadTask>::alloc();
Jiyong Park02586a22017-05-20 01:01:24 +0900638 return new (ptr) LoadTask(name, needed_by, start_from, readers_map);
Dmitriy Ivanov14669a92014-09-05 16:42:53 -0700639 }
640
641 const char* get_name() const {
642 return name_;
643 }
644
645 soinfo* get_needed_by() const {
646 return needed_by_;
647 }
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700648
649 soinfo* get_soinfo() const {
650 return si_;
651 }
652
653 void set_soinfo(soinfo* si) {
654 si_ = si;
655 }
656
657 off64_t get_file_offset() const {
658 return file_offset_;
659 }
660
661 void set_file_offset(off64_t offset) {
662 file_offset_ = offset;
663 }
664
665 int get_fd() const {
666 return fd_;
667 }
668
669 void set_fd(int fd, bool assume_ownership) {
Martin Stjernholmde853ff2019-01-17 00:18:44 +0000670 if (fd_ != -1 && close_fd_) {
671 close(fd_);
672 }
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700673 fd_ = fd;
674 close_fd_ = assume_ownership;
675 }
676
677 const android_dlextinfo* get_extinfo() const {
678 return extinfo_;
679 }
680
681 void set_extinfo(const android_dlextinfo* extinfo) {
682 extinfo_ = extinfo;
683 }
684
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700685 bool is_dt_needed() const {
686 return is_dt_needed_;
687 }
688
689 void set_dt_needed(bool is_dt_needed) {
690 is_dt_needed_ = is_dt_needed;
691 }
692
Jiyong Park02586a22017-05-20 01:01:24 +0900693 // returns the namespace from where we need to start loading this.
694 const android_namespace_t* get_start_from() const {
695 return start_from_;
696 }
697
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700698 const ElfReader& get_elf_reader() const {
699 CHECK(si_ != nullptr);
700 return (*elf_readers_map_)[si_];
701 }
702
703 ElfReader& get_elf_reader() {
704 CHECK(si_ != nullptr);
705 return (*elf_readers_map_)[si_];
706 }
707
708 std::unordered_map<const soinfo*, ElfReader>* get_readers_map() {
709 return elf_readers_map_;
710 }
711
712 bool read(const char* realpath, off64_t file_size) {
713 ElfReader& elf_reader = get_elf_reader();
714 return elf_reader.Read(realpath, fd_, file_offset_, file_size);
715 }
716
Torne (Richard Coles)efbe9a52018-10-17 15:59:38 -0400717 bool load(address_space_params* address_space) {
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700718 ElfReader& elf_reader = get_elf_reader();
Torne (Richard Coles)efbe9a52018-10-17 15:59:38 -0400719 if (!elf_reader.Load(address_space)) {
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700720 return false;
721 }
722
723 si_->base = elf_reader.load_start();
724 si_->size = elf_reader.load_size();
Dimitry Ivanovf45b0e92016-01-15 11:13:35 -0800725 si_->set_mapped_by_caller(elf_reader.is_mapped_by_caller());
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700726 si_->load_bias = elf_reader.load_bias();
727 si_->phnum = elf_reader.phdr_count();
728 si_->phdr = elf_reader.loaded_phdr();
729
730 return true;
731 }
732
Dmitriy Ivanov14669a92014-09-05 16:42:53 -0700733 private:
Dimitry Ivanov7d429d32017-02-01 15:28:52 -0800734 LoadTask(const char* name,
735 soinfo* needed_by,
Jiyong Park02586a22017-05-20 01:01:24 +0900736 android_namespace_t* start_from,
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700737 std::unordered_map<const soinfo*, ElfReader>* readers_map)
738 : name_(name), needed_by_(needed_by), si_(nullptr),
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700739 fd_(-1), close_fd_(false), file_offset_(0), elf_readers_map_(readers_map),
Jiyong Park02586a22017-05-20 01:01:24 +0900740 is_dt_needed_(false), start_from_(start_from) {}
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700741
742 ~LoadTask() {
743 if (fd_ != -1 && close_fd_) {
744 close(fd_);
745 }
746 }
Dmitriy Ivanov14669a92014-09-05 16:42:53 -0700747
748 const char* name_;
749 soinfo* needed_by_;
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700750 soinfo* si_;
751 const android_dlextinfo* extinfo_;
752 int fd_;
753 bool close_fd_;
754 off64_t file_offset_;
755 std::unordered_map<const soinfo*, ElfReader>* elf_readers_map_;
Dimitry Ivanov769b33f2016-07-21 11:33:40 -0700756 // TODO(dimitry): needed by workaround for http://b/26394120 (the grey-list)
757 bool is_dt_needed_;
758 // END OF WORKAROUND
Jiyong Park02586a22017-05-20 01:01:24 +0900759 const android_namespace_t* const start_from_;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -0700760
761 DISALLOW_IMPLICIT_CONSTRUCTORS(LoadTask);
762};
763
Ningsheng Jiane93be992014-09-16 15:22:10 +0800764LoadTask::deleter_t LoadTask::deleter;
765
Dmitriy Ivanov0cd83eb2014-09-01 16:15:52 -0700766template <typename T>
767using linked_list_t = LinkedList<T, TypeBasedAllocator<LinkedListEntry<T>>>;
768
769typedef linked_list_t<soinfo> SoinfoLinkedList;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -0700770typedef linked_list_t<const char> StringLinkedList;
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -0700771typedef std::vector<LoadTask*> LoadTaskList;
Dmitriy Ivanov0cd83eb2014-09-01 16:15:52 -0700772
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800773enum walk_action_result_t : uint32_t {
774 kWalkStop = 0,
775 kWalkContinue = 1,
776 kWalkSkip = 2
777};
Dmitriy Ivanovaa0f2bd2014-07-28 17:32:20 -0700778
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700779// This function walks down the tree of soinfo dependencies
780// in breadth-first order and
781// * calls action(soinfo* si) for each node, and
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800782// * terminates walk if action returns kWalkStop
783// * skips children of the node if action
784// return kWalkSkip
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700785//
786// walk_dependencies_tree returns false if walk was terminated
787// by the action and true otherwise.
788template<typename F>
dimitry965d06d2017-11-28 16:03:07 +0100789static bool walk_dependencies_tree(soinfo* root_soinfo, F action) {
Dmitriy Ivanov0cd83eb2014-09-01 16:15:52 -0700790 SoinfoLinkedList visit_list;
791 SoinfoLinkedList visited;
792
dimitry965d06d2017-11-28 16:03:07 +0100793 visit_list.push_back(root_soinfo);
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700794
795 soinfo* si;
796 while ((si = visit_list.pop_front()) != nullptr) {
797 if (visited.contains(si)) {
Dmitriy Ivanov042426b2014-08-12 21:02:13 -0700798 continue;
799 }
800
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800801 walk_action_result_t result = action(si);
802
803 if (result == kWalkStop) {
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700804 return false;
Dmitriy Ivanovaa0f2bd2014-07-28 17:32:20 -0700805 }
806
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700807 visited.push_back(si);
808
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800809 if (result != kWalkSkip) {
810 si->get_children().for_each([&](soinfo* child) {
811 visit_list.push_back(child);
812 });
813 }
Dmitriy Ivanovaa0f2bd2014-07-28 17:32:20 -0700814 }
815
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700816 return true;
817}
818
819
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800820static const ElfW(Sym)* dlsym_handle_lookup(android_namespace_t* ns,
821 soinfo* root,
822 soinfo* skip_until,
823 soinfo** found,
824 SymbolName& symbol_name,
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -0800825 const version_info* vi) {
Dmitriy Ivanov2a815362015-04-09 13:42:33 -0700826 const ElfW(Sym)* result = nullptr;
Dmitriy Ivanov697bd9f2015-05-12 11:12:27 -0700827 bool skip_lookup = skip_until != nullptr;
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700828
dimitry965d06d2017-11-28 16:03:07 +0100829 walk_dependencies_tree(root, [&](soinfo* current_soinfo) {
Dmitriy Ivanov697bd9f2015-05-12 11:12:27 -0700830 if (skip_lookup) {
831 skip_lookup = current_soinfo != skip_until;
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800832 return kWalkContinue;
833 }
834
835 if (!ns->is_accessible(current_soinfo)) {
836 return kWalkSkip;
Dmitriy Ivanov697bd9f2015-05-12 11:12:27 -0700837 }
838
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -0800839 if (!current_soinfo->find_symbol_by_name(symbol_name, vi, &result)) {
Dmitriy Ivanov2a815362015-04-09 13:42:33 -0700840 result = nullptr;
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800841 return kWalkStop;
Dmitriy Ivanov2a815362015-04-09 13:42:33 -0700842 }
843
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700844 if (result != nullptr) {
845 *found = current_soinfo;
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800846 return kWalkStop;
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700847 }
848
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800849 return kWalkContinue;
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -0700850 });
851
852 return result;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800853}
854
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -0800855static const ElfW(Sym)* dlsym_linear_lookup(android_namespace_t* ns,
856 const char* name,
857 const version_info* vi,
858 soinfo** found,
859 soinfo* caller,
860 void* handle);
861
Dmitriy Ivanov697bd9f2015-05-12 11:12:27 -0700862// This is used by dlsym(3). It performs symbol lookup only within the
863// specified soinfo object and its dependencies in breadth first order.
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800864static const ElfW(Sym)* dlsym_handle_lookup(soinfo* si,
865 soinfo** found,
866 const char* name,
867 const version_info* vi) {
Dmitriy Ivanovf439b5a2015-05-30 13:04:39 -0700868 // According to man dlopen(3) and posix docs in the case when si is handle
869 // of the main executable we need to search not only in the executable and its
870 // dependencies but also in all libraries loaded with RTLD_GLOBAL.
871 //
872 // Since RTLD_GLOBAL is always set for the main executable and all dt_needed shared
873 // libraries and they are loaded in breath-first (correct) order we can just execute
874 // dlsym(RTLD_DEFAULT, ...); instead of doing two stage lookup.
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700875 if (si == solist_get_somain()) {
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -0800876 return dlsym_linear_lookup(&g_default_namespace, name, vi, found, nullptr, RTLD_DEFAULT);
Dmitriy Ivanovf439b5a2015-05-30 13:04:39 -0700877 }
878
Dmitriy Ivanov697bd9f2015-05-12 11:12:27 -0700879 SymbolName symbol_name(name);
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800880 // note that the namespace is not the namespace associated with caller_addr
881 // we use ns associated with root si intentionally here. Using caller_ns
882 // causes problems when user uses dlopen_ext to open a library in the separate
883 // namespace and then calls dlsym() on the handle.
884 return dlsym_handle_lookup(si->get_primary_namespace(), si, nullptr, found, symbol_name, vi);
Dmitriy Ivanov697bd9f2015-05-12 11:12:27 -0700885}
886
Brian Carlstromd4ee82d2013-02-28 15:58:45 -0800887/* This is used by dlsym(3) to performs a global symbol lookup. If the
888 start value is null (for RTLD_DEFAULT), the search starts at the
889 beginning of the global solist. Otherwise the search starts at the
890 specified soinfo (for RTLD_NEXT).
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700891 */
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -0800892static const ElfW(Sym)* dlsym_linear_lookup(android_namespace_t* ns,
893 const char* name,
894 const version_info* vi,
895 soinfo** found,
896 soinfo* caller,
897 void* handle) {
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -0800898 SymbolName symbol_name(name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800899
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -0700900 auto& soinfo_list = ns->soinfo_list();
901 auto start = soinfo_list.begin();
Dmitriy Ivanov76ac1ac2015-04-01 14:45:10 -0700902
903 if (handle == RTLD_NEXT) {
Dmitriy Ivanovb96ac412015-05-22 12:34:42 -0700904 if (caller == nullptr) {
Dmitriy Ivanov76ac1ac2015-04-01 14:45:10 -0700905 return nullptr;
906 } else {
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -0700907 auto it = soinfo_list.find(caller);
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -0700908 CHECK (it != soinfo_list.end());
909 start = ++it;
Dmitriy Ivanov76ac1ac2015-04-01 14:45:10 -0700910 }
Elliott Hughescade4c32012-12-20 14:42:14 -0800911 }
912
Dmitriy Ivanov2a815362015-04-09 13:42:33 -0700913 const ElfW(Sym)* s = nullptr;
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -0700914 for (auto it = start, end = soinfo_list.end(); it != end; ++it) {
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -0700915 soinfo* si = *it;
Dmitriy Ivanov19133522015-06-02 17:36:54 -0700916 // Do not skip RTLD_LOCAL libraries in dlsym(RTLD_DEFAULT, ...)
Elliott Hughes5bc78c82016-11-16 11:35:43 -0800917 // if the library is opened by application with target api level < M.
Dmitriy Ivanov19133522015-06-02 17:36:54 -0700918 // See http://b/21565766
Elliott Hughes5bc78c82016-11-16 11:35:43 -0800919 if ((si->get_rtld_flags() & RTLD_GLOBAL) == 0 &&
920 si->get_target_sdk_version() >= __ANDROID_API_M__) {
Dmitriy Ivanove8ba50f2014-09-15 17:00:10 -0700921 continue;
922 }
923
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -0800924 if (!si->find_symbol_by_name(symbol_name, vi, &s)) {
Dmitriy Ivanov2a815362015-04-09 13:42:33 -0700925 return nullptr;
926 }
927
Dmitriy Ivanov851135b2014-08-29 12:02:36 -0700928 if (s != nullptr) {
Elliott Hughescade4c32012-12-20 14:42:14 -0800929 *found = si;
930 break;
Matt Fischer1698d9e2009-12-31 12:17:56 -0600931 }
Elliott Hughescade4c32012-12-20 14:42:14 -0800932 }
Matt Fischer1698d9e2009-12-31 12:17:56 -0600933
dimitry153168c2018-02-20 16:51:41 +0100934 // If not found - use dlsym_handle_lookup for caller's local_group
935 if (s == nullptr && caller != nullptr) {
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800936 soinfo* local_group_root = caller->get_local_group_root();
937
938 return dlsym_handle_lookup(local_group_root->get_primary_namespace(),
939 local_group_root,
940 (handle == RTLD_NEXT) ? caller : nullptr,
941 found,
942 symbol_name,
943 vi);
Dmitriy Ivanov76ac1ac2015-04-01 14:45:10 -0700944 }
945
Dmitriy Ivanov851135b2014-08-29 12:02:36 -0700946 if (s != nullptr) {
Elliott Hughesc00f2cb2013-10-04 17:01:33 -0700947 TRACE_TYPE(LOOKUP, "%s s->st_value = %p, found->base = %p",
948 name, reinterpret_cast<void*>(s->st_value), reinterpret_cast<void*>((*found)->base));
Elliott Hughescade4c32012-12-20 14:42:14 -0800949 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800950
Elliott Hughescade4c32012-12-20 14:42:14 -0800951 return s;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800952}
953
Kito Chengfa8c05d2013-03-12 14:58:06 +0800954soinfo* find_containing_library(const void* p) {
Elliott Hughes0266ae52014-02-10 17:46:57 -0800955 ElfW(Addr) address = reinterpret_cast<ElfW(Addr)>(p);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700956 for (soinfo* si = solist_get_head(); si != nullptr; si = si->next) {
Peter Collingbourneb39cb3c2019-03-01 13:12:49 -0800957 if (address < si->base || address - si->base >= si->size) {
958 continue;
959 }
960 ElfW(Addr) vaddr = address - si->load_bias;
961 for (size_t i = 0; i != si->phnum; ++i) {
962 const ElfW(Phdr)* phdr = &si->phdr[i];
963 if (phdr->p_type != PT_LOAD) {
964 continue;
965 }
966 if (vaddr >= phdr->p_vaddr && vaddr < phdr->p_vaddr + phdr->p_memsz) {
967 return si;
968 }
Matt Fischere2a8b1f2009-12-31 12:17:40 -0600969 }
Kito Chengfa8c05d2013-03-12 14:58:06 +0800970 }
Dmitriy Ivanov851135b2014-08-29 12:02:36 -0700971 return nullptr;
Matt Fischere2a8b1f2009-12-31 12:17:40 -0600972}
973
Dmitriy Ivanovb4827502015-09-28 16:38:31 -0700974class ZipArchiveCache {
975 public:
976 ZipArchiveCache() {}
977 ~ZipArchiveCache();
978
979 bool get_or_open(const char* zip_path, ZipArchiveHandle* handle);
980 private:
981 DISALLOW_COPY_AND_ASSIGN(ZipArchiveCache);
982
983 std::unordered_map<std::string, ZipArchiveHandle> cache_;
984};
985
986bool ZipArchiveCache::get_or_open(const char* zip_path, ZipArchiveHandle* handle) {
987 std::string key(zip_path);
988
989 auto it = cache_.find(key);
990 if (it != cache_.end()) {
991 *handle = it->second;
992 return true;
993 }
994
995 int fd = TEMP_FAILURE_RETRY(open(zip_path, O_RDONLY | O_CLOEXEC));
996 if (fd == -1) {
997 return false;
998 }
999
1000 if (OpenArchiveFd(fd, "", handle) != 0) {
1001 // invalid zip-file (?)
Ryan Prichard0adf09b2018-10-01 18:35:46 -07001002 CloseArchive(*handle);
Dmitriy Ivanovb4827502015-09-28 16:38:31 -07001003 return false;
1004 }
1005
1006 cache_[key] = *handle;
1007 return true;
1008}
1009
1010ZipArchiveCache::~ZipArchiveCache() {
Dmitriy Ivanov5dce8942015-10-13 12:14:16 -07001011 for (const auto& it : cache_) {
Dmitriy Ivanovb4827502015-09-28 16:38:31 -07001012 CloseArchive(it.second);
1013 }
1014}
1015
1016static int open_library_in_zipfile(ZipArchiveCache* zip_archive_cache,
Dmitriy Ivanova1feb112015-10-01 18:41:57 -07001017 const char* const input_path,
1018 off64_t* file_offset, std::string* realpath) {
1019 std::string normalized_path;
1020 if (!normalize_path(input_path, &normalized_path)) {
1021 return -1;
1022 }
1023
1024 const char* const path = normalized_path.c_str();
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07001025 TRACE("Trying zip file open from path \"%s\" -> normalized \"%s\"", input_path, path);
Simon Baldwinaef71952015-01-16 13:22:54 +00001026
Dmitriy Ivanov402a7502015-06-09 13:46:51 -07001027 // Treat an '!/' separator inside a path as the separator between the name
Simon Baldwinaef71952015-01-16 13:22:54 +00001028 // of the zip file on disk and the subdirectory to search within it.
Dmitriy Ivanov402a7502015-06-09 13:46:51 -07001029 // For example, if path is "foo.zip!/bar/bas/x.so", then we search for
Simon Baldwinaef71952015-01-16 13:22:54 +00001030 // "bar/bas/x.so" within "foo.zip".
Dmitriy Ivanova1feb112015-10-01 18:41:57 -07001031 const char* const separator = strstr(path, kZipFileSeparator);
Simon Baldwinaef71952015-01-16 13:22:54 +00001032 if (separator == nullptr) {
1033 return -1;
Elliott Hughes124fae92012-10-31 14:20:03 -07001034 }
Simon Baldwinaef71952015-01-16 13:22:54 +00001035
1036 char buf[512];
1037 if (strlcpy(buf, path, sizeof(buf)) >= sizeof(buf)) {
1038 PRINT("Warning: ignoring very long library path: %s", path);
1039 return -1;
1040 }
1041
1042 buf[separator - path] = '\0';
1043
1044 const char* zip_path = buf;
Dmitriy Ivanov402a7502015-06-09 13:46:51 -07001045 const char* file_path = &buf[separator - path + 2];
Simon Baldwinaef71952015-01-16 13:22:54 +00001046 int fd = TEMP_FAILURE_RETRY(open(zip_path, O_RDONLY | O_CLOEXEC));
1047 if (fd == -1) {
1048 return -1;
1049 }
1050
1051 ZipArchiveHandle handle;
Dmitriy Ivanovb4827502015-09-28 16:38:31 -07001052 if (!zip_archive_cache->get_or_open(zip_path, &handle)) {
Simon Baldwinaef71952015-01-16 13:22:54 +00001053 // invalid zip-file (?)
1054 close(fd);
1055 return -1;
1056 }
1057
Simon Baldwinaef71952015-01-16 13:22:54 +00001058 ZipEntry entry;
1059
Elliott Hughesb51bb502019-05-03 22:45:41 -07001060 if (FindEntry(handle, file_path, &entry) != 0) {
Simon Baldwinaef71952015-01-16 13:22:54 +00001061 // Entry was not found.
1062 close(fd);
1063 return -1;
1064 }
1065
1066 // Check if it is properly stored
1067 if (entry.method != kCompressStored || (entry.offset % PAGE_SIZE) != 0) {
1068 close(fd);
1069 return -1;
1070 }
1071
1072 *file_offset = entry.offset;
Dmitriy Ivanova1feb112015-10-01 18:41:57 -07001073
1074 if (realpath_fd(fd, realpath)) {
1075 *realpath += separator;
1076 } else {
Tom Cherry66bc4282018-11-08 13:40:52 -08001077 if (!is_first_stage_init()) {
1078 PRINT("warning: unable to get realpath for the library \"%s\". Will use given path.",
1079 normalized_path.c_str());
1080 }
Dmitriy Ivanova1feb112015-10-01 18:41:57 -07001081 *realpath = normalized_path;
1082 }
1083
Simon Baldwinaef71952015-01-16 13:22:54 +00001084 return fd;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001085}
1086
Dmitriy Ivanovd165f562015-03-23 18:43:02 -07001087static bool format_path(char* buf, size_t buf_size, const char* path, const char* name) {
Christopher Ferris7a3681e2017-04-24 17:48:32 -07001088 int n = async_safe_format_buffer(buf, buf_size, "%s/%s", path, name);
Dmitriy Ivanovd165f562015-03-23 18:43:02 -07001089 if (n < 0 || n >= static_cast<int>(buf_size)) {
1090 PRINT("Warning: ignoring very long library path: %s/%s", path, name);
1091 return false;
1092 }
Simon Baldwinaef71952015-01-16 13:22:54 +00001093
Dmitriy Ivanovd165f562015-03-23 18:43:02 -07001094 return true;
1095}
1096
Ryan Prichard8f639a42018-10-01 23:10:05 -07001097static int open_library_at_path(ZipArchiveCache* zip_archive_cache,
1098 const char* path, off64_t* file_offset,
1099 std::string* realpath) {
1100 int fd = -1;
1101 if (strstr(path, kZipFileSeparator) != nullptr) {
1102 fd = open_library_in_zipfile(zip_archive_cache, path, file_offset, realpath);
1103 }
1104
1105 if (fd == -1) {
1106 fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC));
1107 if (fd != -1) {
1108 *file_offset = 0;
1109 if (!realpath_fd(fd, realpath)) {
Tom Cherry66bc4282018-11-08 13:40:52 -08001110 if (!is_first_stage_init()) {
1111 PRINT("warning: unable to get realpath for the library \"%s\". Will use given path.",
1112 path);
1113 }
Ryan Prichard8f639a42018-10-01 23:10:05 -07001114 *realpath = path;
1115 }
1116 }
1117 }
1118
1119 return fd;
1120}
1121
Dmitriy Ivanovb4827502015-09-28 16:38:31 -07001122static int open_library_on_paths(ZipArchiveCache* zip_archive_cache,
1123 const char* name, off64_t* file_offset,
Dmitriy Ivanova1feb112015-10-01 18:41:57 -07001124 const std::vector<std::string>& paths,
1125 std::string* realpath) {
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001126 for (const auto& path : paths) {
Dmitriy Ivanovd165f562015-03-23 18:43:02 -07001127 char buf[512];
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001128 if (!format_path(buf, sizeof(buf), path.c_str(), name)) {
Dmitriy Ivanovd165f562015-03-23 18:43:02 -07001129 continue;
1130 }
1131
Ryan Prichard8f639a42018-10-01 23:10:05 -07001132 int fd = open_library_at_path(zip_archive_cache, buf, file_offset, realpath);
Dmitriy Ivanovd165f562015-03-23 18:43:02 -07001133 if (fd != -1) {
1134 return fd;
1135 }
Simon Baldwinaef71952015-01-16 13:22:54 +00001136 }
1137
Dmitriy Ivanovd165f562015-03-23 18:43:02 -07001138 return -1;
Simon Baldwinaef71952015-01-16 13:22:54 +00001139}
1140
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001141static int open_library(android_namespace_t* ns,
1142 ZipArchiveCache* zip_archive_cache,
Dmitriy Ivanovb4827502015-09-28 16:38:31 -07001143 const char* name, soinfo *needed_by,
Dmitriy Ivanova1feb112015-10-01 18:41:57 -07001144 off64_t* file_offset, std::string* realpath) {
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001145 TRACE("[ opening %s from namespace %s ]", name, ns->get_name());
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001146
Elliott Hughes124fae92012-10-31 14:20:03 -07001147 // 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 -07001148 if (strchr(name, '/') != nullptr) {
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001149 int fd = -1;
1150
Dmitriy Ivanov730ed9d2015-07-16 04:52:06 -07001151 if (strstr(name, kZipFileSeparator) != nullptr) {
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001152 fd = open_library_in_zipfile(zip_archive_cache, name, file_offset, realpath);
1153 }
1154
1155 if (fd == -1) {
1156 fd = TEMP_FAILURE_RETRY(open(name, O_RDONLY | O_CLOEXEC));
Simon Baldwinaef71952015-01-16 13:22:54 +00001157 if (fd != -1) {
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001158 *file_offset = 0;
1159 if (!realpath_fd(fd, realpath)) {
Tom Cherry66bc4282018-11-08 13:40:52 -08001160 if (!is_first_stage_init()) {
1161 PRINT("warning: unable to get realpath for the library \"%s\". Will use given path.",
1162 name);
1163 }
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001164 *realpath = name;
1165 }
Simon Baldwinaef71952015-01-16 13:22:54 +00001166 }
1167 }
1168
Dmitriy Ivanove44fffd2015-03-17 17:12:18 -07001169 return fd;
Elliott Hughes124fae92012-10-31 14:20:03 -07001170 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001171
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001172 // Otherwise we try LD_LIBRARY_PATH first, and fall back to the default library path
1173 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 -07001174 if (fd == -1 && needed_by != nullptr) {
Dmitriy Ivanova1feb112015-10-01 18:41:57 -07001175 fd = open_library_on_paths(zip_archive_cache, name, file_offset, needed_by->get_dt_runpath(), realpath);
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001176 // Check if the library is accessible
1177 if (fd != -1 && !ns->is_accessible(*realpath)) {
Vic Yang48b69112018-10-24 14:14:26 -07001178 close(fd);
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001179 fd = -1;
1180 }
Evgenii Stepanov68650822015-06-10 13:38:39 -07001181 }
Dmitriy Ivanovb4827502015-09-28 16:38:31 -07001182
Peter Collingbourneea11be02019-04-30 16:05:13 -07001183#if !defined(__ANDROID_APEX__)
1184 if (fd == -1) {
1185 std::vector<std::string> bootstrap_paths = { std::string(kSystemLibDir) + "/bootstrap" };
1186 fd = open_library_on_paths(zip_archive_cache, name, file_offset, bootstrap_paths, realpath);
1187 }
1188#endif
1189
Elliott Hughes124fae92012-10-31 14:20:03 -07001190 if (fd == -1) {
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001191 fd = open_library_on_paths(zip_archive_cache, name, file_offset, ns->get_default_library_paths(), realpath);
Elliott Hughes124fae92012-10-31 14:20:03 -07001192 }
Dmitriy Ivanovb4827502015-09-28 16:38:31 -07001193
Elliott Hughes124fae92012-10-31 14:20:03 -07001194 return fd;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001195}
1196
Ryan Prichard8f639a42018-10-01 23:10:05 -07001197int open_executable(const char* path, off64_t* file_offset, std::string* realpath) {
1198 ZipArchiveCache zip_archive_cache;
1199 return open_library_at_path(&zip_archive_cache, path, file_offset, realpath);
1200}
1201
Dimitry Ivanov3f660572016-09-09 10:00:39 -07001202const char* fix_dt_needed(const char* dt_needed, const char* sopath __unused) {
Dmitriy Ivanovd974e882015-05-27 18:29:41 -07001203#if !defined(__LP64__)
1204 // Work around incorrect DT_NEEDED entries for old apps: http://b/21364029
Elliott Hughes9076b0c2018-02-28 11:29:45 -08001205 int app_target_api_level = get_application_target_sdk_version();
1206 if (app_target_api_level < __ANDROID_API_M__) {
Dmitriy Ivanovd974e882015-05-27 18:29:41 -07001207 const char* bname = basename(dt_needed);
1208 if (bname != dt_needed) {
Elliott Hughes9076b0c2018-02-28 11:29:45 -08001209 DL_WARN_documented_change(__ANDROID_API_M__,
1210 "invalid-dt_needed-entries-enforced-for-api-level-23",
1211 "library \"%s\" has invalid DT_NEEDED entry \"%s\"",
1212 sopath, dt_needed, app_target_api_level);
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07001213 add_dlwarning(sopath, "invalid DT_NEEDED entry", dt_needed);
Dmitriy Ivanovd974e882015-05-27 18:29:41 -07001214 }
1215
1216 return bname;
1217 }
1218#endif
1219 return dt_needed;
1220}
1221
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001222template<typename F>
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001223static void for_each_dt_needed(const ElfReader& elf_reader, F action) {
1224 for (const ElfW(Dyn)* d = elf_reader.dynamic(); d->d_tag != DT_NULL; ++d) {
1225 if (d->d_tag == DT_NEEDED) {
1226 action(fix_dt_needed(elf_reader.get_string(d->d_un.d_val), elf_reader.name()));
1227 }
1228 }
1229}
1230
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001231static bool find_loaded_library_by_inode(android_namespace_t* ns,
1232 const struct stat& file_stat,
1233 off64_t file_offset,
1234 bool search_linked_namespaces,
1235 soinfo** candidate) {
Vic Yang3ec16be2019-06-02 21:10:53 -07001236 if (file_stat.st_dev == 0 || file_stat.st_ino == 0) {
1237 *candidate = nullptr;
1238 return false;
1239 }
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001240
1241 auto predicate = [&](soinfo* si) {
Vic Yang3ec16be2019-06-02 21:10:53 -07001242 return si->get_st_ino() == file_stat.st_ino &&
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001243 si->get_st_dev() == file_stat.st_dev &&
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001244 si->get_file_offset() == file_offset;
1245 };
1246
1247 *candidate = ns->soinfo_list().find_if(predicate);
1248
1249 if (*candidate == nullptr && search_linked_namespaces) {
1250 for (auto& link : ns->linked_namespaces()) {
1251 android_namespace_t* linked_ns = link.linked_namespace();
1252 soinfo* si = linked_ns->soinfo_list().find_if(predicate);
1253
1254 if (si != nullptr && link.is_accessible(si->get_soname())) {
1255 *candidate = si;
1256 return true;
1257 }
1258 }
1259 }
1260
1261 return *candidate != nullptr;
1262}
1263
Evgenii Stepanov9e77a642017-07-27 14:55:44 -07001264static bool find_loaded_library_by_realpath(android_namespace_t* ns, const char* realpath,
1265 bool search_linked_namespaces, soinfo** candidate) {
1266 auto predicate = [&](soinfo* si) { return strcmp(realpath, si->get_realpath()) == 0; };
1267
1268 *candidate = ns->soinfo_list().find_if(predicate);
1269
1270 if (*candidate == nullptr && search_linked_namespaces) {
1271 for (auto& link : ns->linked_namespaces()) {
1272 android_namespace_t* linked_ns = link.linked_namespace();
1273 soinfo* si = linked_ns->soinfo_list().find_if(predicate);
1274
1275 if (si != nullptr && link.is_accessible(si->get_soname())) {
1276 *candidate = si;
1277 return true;
1278 }
1279 }
1280 }
1281
1282 return *candidate != nullptr;
1283}
1284
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001285static bool load_library(android_namespace_t* ns,
1286 LoadTask* task,
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001287 LoadTaskList* load_tasks,
1288 int rtld_flags,
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001289 const std::string& realpath,
1290 bool search_linked_namespaces) {
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001291 off64_t file_offset = task->get_file_offset();
1292 const char* name = task->get_name();
1293 const android_dlextinfo* extinfo = task->get_extinfo();
1294
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001295 LD_LOG(kLogDlopen, "load_library(ns=%s, task=%s, flags=0x%x, realpath=%s)", ns->get_name(), name,
1296 rtld_flags, realpath.c_str());
1297
Dmitriy Ivanov07e5bc12014-10-03 17:52:44 -07001298 if ((file_offset % PAGE_SIZE) != 0) {
Dmitriy Ivanova6c12792014-10-21 12:09:18 -07001299 DL_ERR("file offset for the library \"%s\" is not page-aligned: %" PRId64, name, file_offset);
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001300 return false;
Dmitriy Ivanov07e5bc12014-10-03 17:52:44 -07001301 }
Yabin Cui16f7f8d2014-11-04 11:08:05 -08001302 if (file_offset < 0) {
1303 DL_ERR("file offset for the library \"%s\" is negative: %" PRId64, name, file_offset);
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001304 return false;
Yabin Cui16f7f8d2014-11-04 11:08:05 -08001305 }
Dmitriy Ivanov07e5bc12014-10-03 17:52:44 -07001306
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001307 struct stat file_stat;
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001308 if (TEMP_FAILURE_RETRY(fstat(task->get_fd(), &file_stat)) != 0) {
Dmitriy Ivanova6c12792014-10-21 12:09:18 -07001309 DL_ERR("unable to stat file for the library \"%s\": %s", name, strerror(errno));
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001310 return false;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001311 }
Yabin Cui16f7f8d2014-11-04 11:08:05 -08001312 if (file_offset >= file_stat.st_size) {
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07001313 DL_ERR("file offset for the library \"%s\" >= file size: %" PRId64 " >= %" PRId64,
1314 name, file_offset, file_stat.st_size);
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001315 return false;
Yabin Cui16f7f8d2014-11-04 11:08:05 -08001316 }
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001317
1318 // Check for symlink and other situations where
Dmitriy Ivanov9b821362015-04-02 16:03:56 -07001319 // file can have different names, unless ANDROID_DLEXT_FORCE_LOAD is set
1320 if (extinfo == nullptr || (extinfo->flags & ANDROID_DLEXT_FORCE_LOAD) == 0) {
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001321 soinfo* si = nullptr;
1322 if (find_loaded_library_by_inode(ns, file_stat, file_offset, search_linked_namespaces, &si)) {
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001323 LD_LOG(kLogDlopen,
1324 "load_library(ns=%s, task=%s): Already loaded under different name/path \"%s\" - "
1325 "will return existing soinfo",
1326 ns->get_name(), name, si->get_realpath());
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001327 task->set_soinfo(si);
1328 return true;
1329 }
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001330 }
Dmitriy Ivanovd59e5002014-05-09 09:10:14 -07001331
Dmitriy Ivanove8ba50f2014-09-15 17:00:10 -07001332 if ((rtld_flags & RTLD_NOLOAD) != 0) {
Dmitriy Ivanova6ac54a2014-09-09 10:21:42 -07001333 DL_ERR("library \"%s\" wasn't loaded and RTLD_NOLOAD prevented it", name);
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001334 return false;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001335 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001336
Dimitry Ivanovbf34ba32017-04-21 13:12:05 -07001337 struct statfs fs_stat;
1338 if (TEMP_FAILURE_RETRY(fstatfs(task->get_fd(), &fs_stat)) != 0) {
1339 DL_ERR("unable to fstatfs file for the library \"%s\": %s", name, strerror(errno));
1340 return false;
1341 }
1342
1343 // do not check accessibility using realpath if fd is located on tmpfs
1344 // this enables use of memfd_create() for apps
1345 if ((fs_stat.f_type != TMPFS_MAGIC) && (!ns->is_accessible(realpath))) {
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07001346 // TODO(dimitry): workaround for http://b/26394120 - the grey-list
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001347
1348 // TODO(dimitry) before O release: add a namespace attribute to have this enabled
1349 // only for classloader-namespaces
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07001350 const soinfo* needed_by = task->is_dt_needed() ? task->get_needed_by() : nullptr;
Dimitry Ivanov35c8e3b2017-02-27 12:17:47 -08001351 if (is_greylisted(ns, name, needed_by)) {
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07001352 // print warning only if needed by non-system library
1353 if (needed_by == nullptr || !is_system_library(needed_by->get_realpath())) {
1354 const soinfo* needed_or_dlopened_by = task->get_needed_by();
1355 const char* sopath = needed_or_dlopened_by == nullptr ? "(unknown)" :
1356 needed_or_dlopened_by->get_realpath();
Elliott Hughes9076b0c2018-02-28 11:29:45 -08001357 DL_WARN_documented_change(__ANDROID_API_N__,
1358 "private-api-enforced-for-api-level-24",
1359 "library \"%s\" (\"%s\") needed or dlopened by \"%s\" "
1360 "is not accessible by namespace \"%s\"",
1361 name, realpath.c_str(), sopath, ns->get_name());
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07001362 add_dlwarning(sopath, "unauthorized access to", name);
1363 }
1364 } else {
1365 // do not load libraries if they are not accessible for the specified namespace.
1366 const char* needed_or_dlopened_by = task->get_needed_by() == nullptr ?
1367 "(unknown)" :
1368 task->get_needed_by()->get_realpath();
Dimitry Ivanovd17a3772016-03-01 13:11:28 -08001369
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07001370 DL_ERR("library \"%s\" needed or dlopened by \"%s\" is not accessible for the namespace \"%s\"",
1371 name, needed_or_dlopened_by, ns->get_name());
Dimitry Ivanovd17a3772016-03-01 13:11:28 -08001372
Dimitry Ivanov35c8e3b2017-02-27 12:17:47 -08001373 // do not print this if a library is in the list of shared libraries for linked namespaces
1374 if (!maybe_accessible_via_namespace_links(ns, name)) {
1375 PRINT("library \"%s\" (\"%s\") needed or dlopened by \"%s\" is not accessible for the"
1376 " namespace: [name=\"%s\", ld_library_paths=\"%s\", default_library_paths=\"%s\","
1377 " permitted_paths=\"%s\"]",
1378 name, realpath.c_str(),
1379 needed_or_dlopened_by,
1380 ns->get_name(),
1381 android::base::Join(ns->get_ld_library_paths(), ':').c_str(),
1382 android::base::Join(ns->get_default_library_paths(), ':').c_str(),
1383 android::base::Join(ns->get_permitted_paths(), ':').c_str());
1384 }
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07001385 return false;
1386 }
Dimitry Ivanov22840aa2015-12-04 18:28:49 -08001387 }
1388
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001389 soinfo* si = soinfo_alloc(ns, realpath.c_str(), &file_stat, file_offset, rtld_flags);
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001390 if (si == nullptr) {
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001391 return false;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001392 }
Dmitriy Ivanovd59e5002014-05-09 09:10:14 -07001393
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001394 task->set_soinfo(si);
1395
1396 // Read the ELF header and some of the segments.
1397 if (!task->read(realpath.c_str(), file_stat.st_size)) {
Dmitriy Ivanovfd7a91e2015-11-06 10:44:37 -08001398 soinfo_free(si);
1399 task->set_soinfo(nullptr);
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001400 return false;
1401 }
1402
1403 // find and set DT_RUNPATH and dt_soname
1404 // Note that these field values are temporary and are
1405 // going to be overwritten on soinfo::prelink_image
1406 // with values from PT_LOAD segments.
1407 const ElfReader& elf_reader = task->get_elf_reader();
1408 for (const ElfW(Dyn)* d = elf_reader.dynamic(); d->d_tag != DT_NULL; ++d) {
1409 if (d->d_tag == DT_RUNPATH) {
1410 si->set_dt_runpath(elf_reader.get_string(d->d_un.d_val));
1411 }
1412 if (d->d_tag == DT_SONAME) {
1413 si->set_soname(elf_reader.get_string(d->d_un.d_val));
1414 }
1415 }
1416
Dan Willemsen5038ef62018-10-21 17:45:04 -07001417#if !defined(__ANDROID__)
1418 // Bionic on the host currently uses some Android prebuilts, which don't set
1419 // DT_RUNPATH with any relative paths, so they can't find their dependencies.
1420 // b/118058804
1421 if (si->get_dt_runpath().empty()) {
1422 si->set_dt_runpath("$ORIGIN/../lib64:$ORIGIN/lib64");
1423 }
1424#endif
1425
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001426 for_each_dt_needed(task->get_elf_reader(), [&](const char* name) {
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001427 LD_LOG(kLogDlopen, "load_library(ns=%s, task=%s): Adding DT_NEEDED task: %s",
1428 ns->get_name(), task->get_name(), name);
Jiyong Park02586a22017-05-20 01:01:24 +09001429 load_tasks->push_back(LoadTask::create(name, si, ns, task->get_readers_map()));
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001430 });
Dmitriy Ivanovd59e5002014-05-09 09:10:14 -07001431
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001432 return true;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001433}
1434
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001435static bool load_library(android_namespace_t* ns,
1436 LoadTask* task,
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001437 ZipArchiveCache* zip_archive_cache,
1438 LoadTaskList* load_tasks,
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001439 int rtld_flags,
1440 bool search_linked_namespaces) {
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001441 const char* name = task->get_name();
1442 soinfo* needed_by = task->get_needed_by();
1443 const android_dlextinfo* extinfo = task->get_extinfo();
1444
Dmitriy Ivanova1feb112015-10-01 18:41:57 -07001445 off64_t file_offset;
1446 std::string realpath;
Spencer Low0346ad72015-04-22 18:06:51 -07001447 if (extinfo != nullptr && (extinfo->flags & ANDROID_DLEXT_USE_LIBRARY_FD) != 0) {
Dmitriy Ivanova1feb112015-10-01 18:41:57 -07001448 file_offset = 0;
Spencer Low0346ad72015-04-22 18:06:51 -07001449 if ((extinfo->flags & ANDROID_DLEXT_USE_LIBRARY_FD_OFFSET) != 0) {
1450 file_offset = extinfo->library_fd_offset;
1451 }
Dmitriy Ivanova1feb112015-10-01 18:41:57 -07001452
1453 if (!realpath_fd(extinfo->library_fd, &realpath)) {
Tom Cherry66bc4282018-11-08 13:40:52 -08001454 if (!is_first_stage_init()) {
1455 PRINT(
1456 "warning: unable to get realpath for the library \"%s\" by extinfo->library_fd. "
1457 "Will use given name.",
1458 name);
1459 }
Dmitriy Ivanova1feb112015-10-01 18:41:57 -07001460 realpath = name;
1461 }
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001462
1463 task->set_fd(extinfo->library_fd, false);
1464 task->set_file_offset(file_offset);
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001465 return load_library(ns, task, load_tasks, rtld_flags, realpath, search_linked_namespaces);
Spencer Low0346ad72015-04-22 18:06:51 -07001466 }
1467
1468 // Open the file.
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001469 int fd = open_library(ns, zip_archive_cache, name, needed_by, &file_offset, &realpath);
Spencer Low0346ad72015-04-22 18:06:51 -07001470 if (fd == -1) {
1471 DL_ERR("library \"%s\" not found", name);
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001472 return false;
Spencer Low0346ad72015-04-22 18:06:51 -07001473 }
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001474
1475 task->set_fd(fd, true);
1476 task->set_file_offset(file_offset);
1477
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001478 return load_library(ns, task, load_tasks, rtld_flags, realpath, search_linked_namespaces);
Spencer Low0346ad72015-04-22 18:06:51 -07001479}
1480
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001481static bool find_loaded_library_by_soname(android_namespace_t* ns,
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001482 const char* name,
1483 soinfo** candidate) {
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001484 return !ns->soinfo_list().visit([&](soinfo* si) {
Dmitriy Ivanov618f1a32015-03-17 20:06:36 -07001485 const char* soname = si->get_soname();
1486 if (soname != nullptr && (strcmp(name, soname) == 0)) {
Dimitry Ivanov3bd90612017-02-01 08:54:43 -08001487 *candidate = si;
1488 return false;
Ard Biesheuvel12c78bb2012-08-14 12:30:09 +02001489 }
Dmitriy Ivanova9703332015-06-16 15:38:21 -07001490
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001491 return true;
1492 });
Ard Biesheuvel12c78bb2012-08-14 12:30:09 +02001493}
1494
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001495// Returns true if library was found and false otherwise
1496static bool find_loaded_library_by_soname(android_namespace_t* ns,
1497 const char* name,
1498 bool search_linked_namespaces,
1499 soinfo** candidate) {
1500 *candidate = nullptr;
1501
1502 // Ignore filename with path.
1503 if (strchr(name, '/') != nullptr) {
1504 return false;
1505 }
1506
1507 bool found = find_loaded_library_by_soname(ns, name, candidate);
1508
1509 if (!found && search_linked_namespaces) {
1510 // if a library was not found - look into linked namespaces
1511 for (auto& link : ns->linked_namespaces()) {
1512 if (!link.is_accessible(name)) {
1513 continue;
1514 }
1515
1516 android_namespace_t* linked_ns = link.linked_namespace();
1517
1518 if (find_loaded_library_by_soname(linked_ns, name, candidate)) {
1519 return true;
1520 }
1521 }
1522 }
1523
1524 return found;
1525}
1526
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001527static bool find_library_in_linked_namespace(const android_namespace_link_t& namespace_link,
Jiyong Park02586a22017-05-20 01:01:24 +09001528 LoadTask* task) {
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001529 android_namespace_t* ns = namespace_link.linked_namespace();
1530
1531 soinfo* candidate;
1532 bool loaded = false;
1533
1534 std::string soname;
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001535 if (find_loaded_library_by_soname(ns, task->get_name(), false, &candidate)) {
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001536 loaded = true;
1537 soname = candidate->get_soname();
1538 } else {
1539 soname = resolve_soname(task->get_name());
1540 }
1541
1542 if (!namespace_link.is_accessible(soname.c_str())) {
1543 // the library is not accessible via namespace_link
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001544 LD_LOG(kLogDlopen,
1545 "find_library_in_linked_namespace(ns=%s, task=%s): Not accessible (soname=%s)",
1546 ns->get_name(), task->get_name(), soname.c_str());
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001547 return false;
1548 }
1549
1550 // if library is already loaded - return it
1551 if (loaded) {
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001552 LD_LOG(kLogDlopen, "find_library_in_linked_namespace(ns=%s, task=%s): Already loaded",
1553 ns->get_name(), task->get_name());
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001554 task->set_soinfo(candidate);
1555 return true;
1556 }
1557
Jiyong Park02586a22017-05-20 01:01:24 +09001558 // returning true with empty soinfo means that the library is okay to be
Logan Chien9ee45912018-01-18 12:05:09 +08001559 // loaded in the namespace but has not yet been loaded there before.
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001560 LD_LOG(kLogDlopen, "find_library_in_linked_namespace(ns=%s, task=%s): Ok to load", ns->get_name(),
1561 task->get_name());
Jiyong Park02586a22017-05-20 01:01:24 +09001562 task->set_soinfo(nullptr);
1563 return true;
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001564}
1565
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001566static bool find_library_internal(android_namespace_t* ns,
1567 LoadTask* task,
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001568 ZipArchiveCache* zip_archive_cache,
1569 LoadTaskList* load_tasks,
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001570 int rtld_flags,
1571 bool search_linked_namespaces) {
Dmitriy Ivanova9703332015-06-16 15:38:21 -07001572 soinfo* candidate;
1573
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001574 if (find_loaded_library_by_soname(ns, task->get_name(), search_linked_namespaces, &candidate)) {
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001575 LD_LOG(kLogDlopen,
1576 "find_library_internal(ns=%s, task=%s): Already loaded (by soname): %s",
1577 ns->get_name(), task->get_name(), candidate->get_realpath());
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001578 task->set_soinfo(candidate);
1579 return true;
Dmitriy Ivanova9703332015-06-16 15:38:21 -07001580 }
Dmitriy Ivanovb648a8a2014-05-19 15:06:58 -07001581
1582 // Library might still be loaded, the accurate detection
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001583 // of this fact is done by load_library.
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001584 TRACE("[ \"%s\" find_loaded_library_by_soname failed (*candidate=%s@%p). Trying harder... ]",
1585 task->get_name(), candidate == nullptr ? "n/a" : candidate->get_realpath(), candidate);
Dmitriy Ivanova9703332015-06-16 15:38:21 -07001586
Dimitry Ivanovd3e7d082017-03-27 14:11:02 -07001587 if (load_library(ns, task, zip_archive_cache, load_tasks, rtld_flags, search_linked_namespaces)) {
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001588 return true;
1589 }
1590
Jiyong Parkefc503d2019-02-12 01:08:57 +09001591 // TODO(dimitry): workaround for http://b/26394120 (the grey-list)
1592 if (ns->is_greylist_enabled() && is_greylisted(ns, task->get_name(), task->get_needed_by())) {
1593 // For the libs in the greylist, switch to the default namespace and then
1594 // try the load again from there. The library could be loaded from the
1595 // default namespace or from another namespace (e.g. runtime) that is linked
1596 // from the default namespace.
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001597 LD_LOG(kLogDlopen,
1598 "find_library_internal(ns=%s, task=%s): Greylisted library - trying namespace %s",
1599 ns->get_name(), task->get_name(), g_default_namespace.get_name());
Jiyong Parkefc503d2019-02-12 01:08:57 +09001600 ns = &g_default_namespace;
1601 if (load_library(ns, task, zip_archive_cache, load_tasks, rtld_flags,
1602 search_linked_namespaces)) {
1603 return true;
1604 }
1605 }
1606 // END OF WORKAROUND
1607
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001608 if (search_linked_namespaces) {
1609 // if a library was not found - look into linked namespaces
dimitry8db36a52017-10-23 15:10:10 +02001610 // preserve current dlerror in the case it fails.
1611 DlErrorRestorer dlerror_restorer;
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001612 LD_LOG(kLogDlopen, "find_library_internal(ns=%s, task=%s): Trying %zu linked namespaces",
1613 ns->get_name(), task->get_name(), ns->linked_namespaces().size());
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001614 for (auto& linked_namespace : ns->linked_namespaces()) {
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001615 if (find_library_in_linked_namespace(linked_namespace, task)) {
Jiyong Park02586a22017-05-20 01:01:24 +09001616 if (task->get_soinfo() == nullptr) {
1617 // try to load the library - once namespace boundary is crossed
1618 // we need to load a library within separate load_group
1619 // to avoid using symbols from foreign namespace while.
1620 //
1621 // However, actual linking is deferred until when the global group
1622 // is fully identified and is applied to all namespaces.
1623 // Otherwise, the libs in the linked namespace won't get symbols from
1624 // the global group.
1625 if (load_library(linked_namespace.linked_namespace(), task, zip_archive_cache, load_tasks, rtld_flags, false)) {
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001626 LD_LOG(
1627 kLogDlopen, "find_library_internal(ns=%s, task=%s): Found in linked namespace %s",
1628 ns->get_name(), task->get_name(), linked_namespace.linked_namespace()->get_name());
Jiyong Park02586a22017-05-20 01:01:24 +09001629 return true;
1630 }
Jiyong Park02586a22017-05-20 01:01:24 +09001631 } else {
1632 // lib is already loaded
1633 return true;
1634 }
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001635 }
1636 }
1637 }
1638
1639 return false;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001640}
1641
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001642static void soinfo_unload(soinfo* si);
1643
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001644static void shuffle(std::vector<LoadTask*>* v) {
Tom Cherry66bc4282018-11-08 13:40:52 -08001645 if (is_first_stage_init()) {
1646 // arc4random* is not available in first stage init because /dev/random
1647 // hasn't yet been created.
Jiyong Park31cd08f2018-06-01 19:18:56 +09001648 return;
1649 }
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001650 for (size_t i = 0, size = v->size(); i < size; ++i) {
1651 size_t n = size - i;
1652 size_t r = arc4random_uniform(n);
1653 std::swap((*v)[n-1], (*v)[r]);
1654 }
1655}
1656
Evgenii Stepanov0cdef7e2015-07-06 17:56:31 -07001657// add_as_children - add first-level loaded libraries (i.e. library_names[], but
1658// not their transitive dependencies) as children of the start_with library.
1659// This is false when find_libraries is called for dlopen(), when newly loaded
1660// libraries must form a disjoint tree.
Dimitry Ivanov3f660572016-09-09 10:00:39 -07001661bool find_libraries(android_namespace_t* ns,
1662 soinfo* start_with,
1663 const char* const library_names[],
1664 size_t library_names_count,
1665 soinfo* soinfos[],
1666 std::vector<soinfo*>* ld_preloads,
1667 size_t ld_preloads_count,
1668 int rtld_flags,
1669 const android_dlextinfo* extinfo,
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001670 bool add_as_children,
Jiyong Park02586a22017-05-20 01:01:24 +09001671 bool search_linked_namespaces,
Jiyong Park02586a22017-05-20 01:01:24 +09001672 std::vector<android_namespace_t*>* namespaces) {
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001673 // Step 0: prepare.
dimitry965d06d2017-11-28 16:03:07 +01001674 std::unordered_map<const soinfo*, ElfReader> readers_map;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001675 LoadTaskList load_tasks;
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001676
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -07001677 for (size_t i = 0; i < library_names_count; ++i) {
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001678 const char* name = library_names[i];
Jiyong Park02586a22017-05-20 01:01:24 +09001679 load_tasks.push_back(LoadTask::create(name, start_with, ns, &readers_map));
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001680 }
1681
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -07001682 // If soinfos array is null allocate one on stack.
1683 // The array is needed in case of failure; for example
1684 // when library_names[] = {libone.so, libtwo.so} and libone.so
1685 // is loaded correctly but libtwo.so failed for some reason.
1686 // In this case libone.so should be unloaded on return.
1687 // See also implementation of failure_guard below.
1688
1689 if (soinfos == nullptr) {
1690 size_t soinfos_size = sizeof(soinfo*)*library_names_count;
1691 soinfos = reinterpret_cast<soinfo**>(alloca(soinfos_size));
1692 memset(soinfos, 0, soinfos_size);
1693 }
1694
1695 // list of libraries to link - see step 2.
1696 size_t soinfos_count = 0;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001697
Tom Cherryb8ab6182017-04-05 16:20:29 -07001698 auto scope_guard = android::base::make_scope_guard([&]() {
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001699 for (LoadTask* t : load_tasks) {
1700 LoadTask::deleter(t);
1701 }
1702 });
1703
Dmitriy Ivanovb4827502015-09-28 16:38:31 -07001704 ZipArchiveCache zip_archive_cache;
1705
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001706 // Step 1: expand the list of load_tasks to include
1707 // all DT_NEEDED libraries (do not load them just yet)
1708 for (size_t i = 0; i<load_tasks.size(); ++i) {
1709 LoadTask* task = load_tasks[i];
Evgenii Stepanov68650822015-06-10 13:38:39 -07001710 soinfo* needed_by = task->get_needed_by();
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001711
Dmitriy Ivanovedfc9f62015-09-02 16:32:02 -07001712 bool is_dt_needed = needed_by != nullptr && (needed_by != start_with || add_as_children);
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001713 task->set_extinfo(is_dt_needed ? nullptr : extinfo);
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07001714 task->set_dt_needed(is_dt_needed);
Dmitriy Ivanovedfc9f62015-09-02 16:32:02 -07001715
Martin Stjernholm95252ee2019-02-22 22:48:59 +00001716 LD_LOG(kLogDlopen, "find_libraries(ns=%s): task=%s, is_dt_needed=%d", ns->get_name(),
1717 task->get_name(), is_dt_needed);
1718
Jiyong Park02586a22017-05-20 01:01:24 +09001719 // Note: start from the namespace that is stored in the LoadTask. This namespace
1720 // is different from the current namespace when the LoadTask is for a transitive
1721 // dependency and the lib that created the LoadTask is not found in the
1722 // current namespace but in one of the linked namespace.
1723 if (!find_library_internal(const_cast<android_namespace_t*>(task->get_start_from()),
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001724 task,
1725 &zip_archive_cache,
1726 &load_tasks,
1727 rtld_flags,
1728 search_linked_namespaces || is_dt_needed)) {
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001729 return false;
1730 }
1731
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001732 soinfo* si = task->get_soinfo();
1733
Dmitriy Ivanovedfc9f62015-09-02 16:32:02 -07001734 if (is_dt_needed) {
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001735 needed_by->add_child(si);
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08001736 }
1737
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -07001738 // When ld_preloads is not null, the first
1739 // ld_preloads_count libs are in fact ld_preloads.
1740 if (ld_preloads != nullptr && soinfos_count < ld_preloads_count) {
Dmitriy Ivanovd165f562015-03-23 18:43:02 -07001741 ld_preloads->push_back(si);
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001742 }
1743
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -07001744 if (soinfos_count < library_names_count) {
1745 soinfos[soinfos_count++] = si;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001746 }
1747 }
1748
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001749 // Step 2: Load libraries in random order (see b/24047022)
1750 LoadTaskList load_list;
1751 for (auto&& task : load_tasks) {
1752 soinfo* si = task->get_soinfo();
1753 auto pred = [&](const LoadTask* t) {
1754 return t->get_soinfo() == si;
1755 };
1756
1757 if (!si->is_linked() &&
1758 std::find_if(load_list.begin(), load_list.end(), pred) == load_list.end() ) {
1759 load_list.push_back(task);
1760 }
1761 }
Torne (Richard Coles)efbe9a52018-10-17 15:59:38 -04001762 bool reserved_address_recursive = false;
1763 if (extinfo) {
1764 reserved_address_recursive = extinfo->flags & ANDROID_DLEXT_RESERVED_ADDRESS_RECURSIVE;
1765 }
1766 if (!reserved_address_recursive) {
1767 // Shuffle the load order in the normal case, but not if we are loading all
1768 // the libraries to a reserved address range.
1769 shuffle(&load_list);
1770 }
1771
1772 // Set up address space parameters.
1773 address_space_params extinfo_params, default_params;
1774 size_t relro_fd_offset = 0;
1775 if (extinfo) {
1776 if (extinfo->flags & ANDROID_DLEXT_RESERVED_ADDRESS) {
1777 extinfo_params.start_addr = extinfo->reserved_addr;
1778 extinfo_params.reserved_size = extinfo->reserved_size;
1779 extinfo_params.must_use_address = true;
1780 } else if (extinfo->flags & ANDROID_DLEXT_RESERVED_ADDRESS_HINT) {
1781 extinfo_params.start_addr = extinfo->reserved_addr;
1782 extinfo_params.reserved_size = extinfo->reserved_size;
1783 }
1784 }
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001785
1786 for (auto&& task : load_list) {
Torne (Richard Coles)efbe9a52018-10-17 15:59:38 -04001787 address_space_params* address_space =
1788 (reserved_address_recursive || !task->is_dt_needed()) ? &extinfo_params : &default_params;
1789 if (!task->load(address_space)) {
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001790 return false;
1791 }
1792 }
1793
1794 // Step 3: pre-link all DT_NEEDED libraries in breadth first order.
1795 for (auto&& task : load_tasks) {
1796 soinfo* si = task->get_soinfo();
1797 if (!si->is_linked() && !si->prelink_image()) {
1798 return false;
1799 }
Ryan Pricharde5e69e02019-01-01 18:53:48 -08001800 register_soinfo_tls(si);
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001801 }
1802
Jiyong Park02586a22017-05-20 01:01:24 +09001803 // Step 4: Construct the global group. Note: DF_1_GLOBAL bit of a library is
1804 // determined at step 3.
1805
1806 // Step 4-1: DF_1_GLOBAL bit is force set for LD_PRELOADed libs because they
1807 // must be added to the global group
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001808 if (ld_preloads != nullptr) {
1809 for (auto&& si : *ld_preloads) {
1810 si->set_dt_flags_1(si->get_dt_flags_1() | DF_1_GLOBAL);
1811 }
1812 }
1813
Jiyong Park02586a22017-05-20 01:01:24 +09001814 // Step 4-2: Gather all DF_1_GLOBAL libs which were newly loaded during this
1815 // run. These will be the new member of the global group
1816 soinfo_list_t new_global_group_members;
1817 for (auto&& task : load_tasks) {
1818 soinfo* si = task->get_soinfo();
1819 if (!si->is_linked() && (si->get_dt_flags_1() & DF_1_GLOBAL) != 0) {
1820 new_global_group_members.push_back(si);
1821 }
1822 }
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07001823
Jiyong Park02586a22017-05-20 01:01:24 +09001824 // Step 4-3: Add the new global group members to all the linked namespaces
Jiyong Park01162f22017-10-16 15:31:09 +09001825 if (namespaces != nullptr) {
Jiyong Park02586a22017-05-20 01:01:24 +09001826 for (auto linked_ns : *namespaces) {
Jiyong Park01162f22017-10-16 15:31:09 +09001827 for (auto si : new_global_group_members) {
1828 if (si->get_primary_namespace() != linked_ns) {
1829 linked_ns->add_soinfo(si);
1830 si->add_secondary_namespace(linked_ns);
1831 }
Jiyong Park02586a22017-05-20 01:01:24 +09001832 }
1833 }
1834 }
1835
dimitry965d06d2017-11-28 16:03:07 +01001836 // Step 5: Collect roots of local_groups.
1837 // Whenever needed_by->si link crosses a namespace boundary it forms its own local_group.
1838 // Here we collect new roots to link them separately later on. Note that we need to avoid
1839 // collecting duplicates. Also the order is important. They need to be linked in the same
1840 // BFS order we link individual libraries.
1841 std::vector<soinfo*> local_group_roots;
1842 if (start_with != nullptr && add_as_children) {
1843 local_group_roots.push_back(start_with);
1844 } else {
1845 CHECK(soinfos_count == 1);
1846 local_group_roots.push_back(soinfos[0]);
1847 }
1848
Jiyong Park02586a22017-05-20 01:01:24 +09001849 for (auto&& task : load_tasks) {
1850 soinfo* si = task->get_soinfo();
dimitry965d06d2017-11-28 16:03:07 +01001851 soinfo* needed_by = task->get_needed_by();
1852 bool is_dt_needed = needed_by != nullptr && (needed_by != start_with || add_as_children);
1853 android_namespace_t* needed_by_ns =
1854 is_dt_needed ? needed_by->get_primary_namespace() : ns;
1855
1856 if (!si->is_linked() && si->get_primary_namespace() != needed_by_ns) {
1857 auto it = std::find(local_group_roots.begin(), local_group_roots.end(), si);
1858 LD_LOG(kLogDlopen,
1859 "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",
1860 si->get_realpath(),
1861 si,
1862 si->get_primary_namespace()->get_name(),
1863 si->get_primary_namespace(),
1864 needed_by == nullptr ? "(nullptr)" : needed_by->get_realpath(),
1865 needed_by,
1866 ns->get_name(),
1867 ns,
1868 needed_by_ns->get_name(),
1869 needed_by_ns,
1870 it == local_group_roots.end() ? "yes" : "no");
1871
1872 if (it == local_group_roots.end()) {
1873 local_group_roots.push_back(si);
Jiyong Park02586a22017-05-20 01:01:24 +09001874 }
1875 }
1876 }
1877
dimitry965d06d2017-11-28 16:03:07 +01001878 // Step 6: Link all local groups
1879 for (auto root : local_group_roots) {
1880 soinfo_list_t local_group;
1881 android_namespace_t* local_group_ns = root->get_primary_namespace();
1882
1883 walk_dependencies_tree(root,
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -07001884 [&] (soinfo* si) {
dimitry965d06d2017-11-28 16:03:07 +01001885 if (local_group_ns->is_accessible(si)) {
1886 local_group.push_back(si);
1887 return kWalkContinue;
1888 } else {
1889 return kWalkSkip;
1890 }
1891 });
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -07001892
dimitry965d06d2017-11-28 16:03:07 +01001893 soinfo_list_t global_group = local_group_ns->get_global_group();
1894 bool linked = local_group.visit([&](soinfo* si) {
Torne (Richard Coles)5d103742019-04-11 12:25:06 -04001895 // Even though local group may contain accessible soinfos from other namespaces
dimitry965d06d2017-11-28 16:03:07 +01001896 // we should avoid linking them (because if they are not linked -> they
1897 // are in the local_group_roots and will be linked later).
1898 if (!si->is_linked() && si->get_primary_namespace() == local_group_ns) {
Torne (Richard Coles)5d103742019-04-11 12:25:06 -04001899 const android_dlextinfo* link_extinfo = nullptr;
1900 if (si == soinfos[0] || reserved_address_recursive) {
1901 // Only forward extinfo for the first library unless the recursive
1902 // flag is set.
1903 link_extinfo = extinfo;
1904 }
1905 if (!si->link_image(global_group, local_group, link_extinfo, &relro_fd_offset) ||
dimitry965d06d2017-11-28 16:03:07 +01001906 !get_cfi_shadow()->AfterLoad(si, solist_get_head())) {
1907 return false;
1908 }
Peter Collingbourne65332082019-08-05 16:16:14 -07001909 if (__libc_shared_globals()->load_hook) {
1910 __libc_shared_globals()->load_hook(si->load_bias, si->phdr, si->phnum);
1911 }
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001912 }
Dmitriy Ivanovcfa97f12014-10-21 09:23:18 -07001913
dimitry965d06d2017-11-28 16:03:07 +01001914 return true;
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001915 });
Elliott Hughes27f18062017-11-29 18:47:42 +00001916
dimitry965d06d2017-11-28 16:03:07 +01001917 if (!linked) {
1918 return false;
1919 }
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001920 }
1921
dimitry965d06d2017-11-28 16:03:07 +01001922 // Step 7: Mark all load_tasks as linked and increment refcounts
1923 // for references between load_groups (at this point it does not matter if
1924 // referenced load_groups were loaded by previous dlopen or as part of this
1925 // one on step 6)
1926 if (start_with != nullptr && add_as_children) {
1927 start_with->set_linked();
1928 }
1929
1930 for (auto&& task : load_tasks) {
1931 soinfo* si = task->get_soinfo();
1932 si->set_linked();
1933 }
1934
1935 for (auto&& task : load_tasks) {
1936 soinfo* si = task->get_soinfo();
1937 soinfo* needed_by = task->get_needed_by();
1938 if (needed_by != nullptr &&
1939 needed_by != start_with &&
1940 needed_by->get_local_group_root() != si->get_local_group_root()) {
1941 si->increment_ref_count();
1942 }
1943 }
1944
1945
1946 return true;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001947}
1948
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07001949static soinfo* find_library(android_namespace_t* ns,
1950 const char* name, int rtld_flags,
Evgenii Stepanov0cdef7e2015-07-06 17:56:31 -07001951 const android_dlextinfo* extinfo,
1952 soinfo* needed_by) {
dimitry965d06d2017-11-28 16:03:07 +01001953 soinfo* si = nullptr;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001954
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08001955 if (name == nullptr) {
Dimitry Ivanov3f660572016-09-09 10:00:39 -07001956 si = solist_get_somain();
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001957 } else if (!find_libraries(ns,
1958 needed_by,
1959 &name,
1960 1,
1961 &si,
1962 nullptr,
1963 0,
1964 rtld_flags,
1965 extinfo,
1966 false /* add_as_children */,
dimitry965d06d2017-11-28 16:03:07 +01001967 true /* search_linked_namespaces */)) {
1968 if (si != nullptr) {
1969 soinfo_unload(si);
1970 }
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07001971 return nullptr;
1972 }
1973
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08001974 si->increment_ref_count();
1975
Elliott Hughesd23736e2012-11-01 15:16:56 -07001976 return si;
1977}
Elliott Hughesbedfe382012-08-14 14:07:59 -07001978
dimitry06016f22018-01-05 11:39:28 +01001979static void soinfo_unload_impl(soinfo* root) {
Dimitry Ivanov6705e8c2017-03-21 10:29:06 -07001980 ScopedTrace trace((std::string("unload ") + root->get_realpath()).c_str());
dimitry06016f22018-01-05 11:39:28 +01001981 bool is_linked = root->is_linked();
Dimitry Ivanov6705e8c2017-03-21 10:29:06 -07001982
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08001983 if (!root->can_unload()) {
dimitryc92ce712017-10-27 14:12:53 +02001984 LD_LOG(kLogDlopen,
1985 "... dlclose(root=\"%s\"@%p) ... not unloading - the load group is flagged with NODELETE",
1986 root->get_realpath(),
1987 root);
Dmitriy Ivanov1b20daf2014-05-19 15:06:58 -07001988 return;
1989 }
1990
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08001991
Dimitry Ivanovb943f302016-08-03 16:00:10 -07001992 soinfo_list_t unload_list;
dimitry965d06d2017-11-28 16:03:07 +01001993 unload_list.push_back(root);
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001994
Dimitry Ivanovb943f302016-08-03 16:00:10 -07001995 soinfo_list_t local_unload_list;
1996 soinfo_list_t external_unload_list;
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07001997 soinfo* si = nullptr;
1998
1999 while ((si = unload_list.pop_front()) != nullptr) {
2000 if (local_unload_list.contains(si)) {
2001 continue;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002002 }
Elliott Hughesd23736e2012-11-01 15:16:56 -07002003
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07002004 local_unload_list.push_back(si);
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08002005
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07002006 if (si->has_min_version(0)) {
2007 soinfo* child = nullptr;
2008 while ((child = si->get_children().pop_front()) != nullptr) {
2009 TRACE("%s@%p needs to unload %s@%p", si->get_realpath(), si,
2010 child->get_realpath(), child);
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08002011
Dimitry Ivanovec90e242017-02-10 11:04:20 -08002012 child->get_parents().remove(si);
2013
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07002014 if (local_unload_list.contains(child)) {
2015 continue;
2016 } else if (child->is_linked() && child->get_local_group_root() != root) {
2017 external_unload_list.push_back(child);
Dimitry Ivanovec90e242017-02-10 11:04:20 -08002018 } else if (child->get_parents().empty()) {
2019 unload_list.push_back(child);
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07002020 }
2021 }
2022 } else {
Christopher Ferris7a3681e2017-04-24 17:48:32 -07002023 async_safe_fatal("soinfo for \"%s\"@%p has no version", si->get_realpath(), si);
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08002024 }
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07002025 }
2026
2027 local_unload_list.for_each([](soinfo* si) {
dimitryc92ce712017-10-27 14:12:53 +02002028 LD_LOG(kLogDlopen,
2029 "... dlclose: calling destructors for \"%s\"@%p ... ",
2030 si->get_realpath(),
2031 si);
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07002032 si->call_destructors();
dimitryc92ce712017-10-27 14:12:53 +02002033 LD_LOG(kLogDlopen,
2034 "... dlclose: calling destructors for \"%s\"@%p ... done",
2035 si->get_realpath(),
2036 si);
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07002037 });
2038
2039 while ((si = local_unload_list.pop_front()) != nullptr) {
dimitryc92ce712017-10-27 14:12:53 +02002040 LD_LOG(kLogDlopen,
2041 "... dlclose: unloading \"%s\"@%p ...",
2042 si->get_realpath(),
2043 si);
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07002044 notify_gdb_of_unload(si);
Ryan Pricharde5e69e02019-01-01 18:53:48 -08002045 unregister_soinfo_tls(si);
Peter Collingbourne65332082019-08-05 16:16:14 -07002046 if (__libc_shared_globals()->unload_hook) {
2047 __libc_shared_globals()->unload_hook(si->load_bias, si->phdr, si->phnum);
2048 }
Evgenii Stepanov0a3637d2016-07-06 13:20:59 -07002049 get_cfi_shadow()->BeforeUnload(si);
Dimitry Ivanov83fcb542016-05-04 17:19:14 -07002050 soinfo_free(si);
2051 }
2052
dimitry965d06d2017-11-28 16:03:07 +01002053 if (is_linked) {
2054 while ((si = external_unload_list.pop_front()) != nullptr) {
2055 LD_LOG(kLogDlopen,
2056 "... dlclose: unloading external reference \"%s\"@%p ...",
2057 si->get_realpath(),
2058 si);
2059 soinfo_unload(si);
2060 }
2061 } else {
2062 LD_LOG(kLogDlopen,
2063 "... dlclose: unload_si was not linked - not unloading external references ...");
Dmitriy Ivanova2547052014-11-18 12:03:09 -08002064 }
2065}
2066
dimitry06016f22018-01-05 11:39:28 +01002067static void soinfo_unload(soinfo* unload_si) {
2068 // Note that the library can be loaded but not linked;
2069 // in which case there is no root but we still need
2070 // to walk the tree and unload soinfos involved.
2071 //
2072 // This happens on unsuccessful dlopen, when one of
2073 // the DT_NEEDED libraries could not be linked/found.
2074 bool is_linked = unload_si->is_linked();
2075 soinfo* root = is_linked ? unload_si->get_local_group_root() : unload_si;
2076
2077 LD_LOG(kLogDlopen,
2078 "... dlclose(realpath=\"%s\"@%p) ... load group root is \"%s\"@%p",
2079 unload_si->get_realpath(),
2080 unload_si,
2081 root->get_realpath(),
2082 root);
2083
2084
2085 size_t ref_count = is_linked ? root->decrement_ref_count() : 0;
2086 if (ref_count > 0) {
2087 LD_LOG(kLogDlopen,
2088 "... dlclose(root=\"%s\"@%p) ... not unloading - decrementing ref_count to %zd",
2089 root->get_realpath(),
2090 root,
2091 ref_count);
2092 return;
2093 }
2094
2095 soinfo_unload_impl(root);
2096}
2097
2098void increment_dso_handle_reference_counter(void* dso_handle) {
2099 if (dso_handle == nullptr) {
2100 return;
2101 }
2102
2103 auto it = g_dso_handle_counters.find(dso_handle);
2104 if (it != g_dso_handle_counters.end()) {
2105 CHECK(++it->second != 0);
2106 } else {
2107 soinfo* si = find_containing_library(dso_handle);
2108 if (si != nullptr) {
2109 ProtectedDataGuard guard;
dimitry55547db2018-05-25 14:17:37 +02002110 si->increment_ref_count();
dimitry06016f22018-01-05 11:39:28 +01002111 } else {
2112 async_safe_fatal(
2113 "increment_dso_handle_reference_counter: Couldn't find soinfo by dso_handle=%p",
2114 dso_handle);
2115 }
2116 g_dso_handle_counters[dso_handle] = 1U;
2117 }
2118}
2119
2120void decrement_dso_handle_reference_counter(void* dso_handle) {
2121 if (dso_handle == nullptr) {
2122 return;
2123 }
2124
2125 auto it = g_dso_handle_counters.find(dso_handle);
2126 CHECK(it != g_dso_handle_counters.end());
2127 CHECK(it->second != 0);
2128
2129 if (--it->second == 0) {
2130 soinfo* si = find_containing_library(dso_handle);
2131 if (si != nullptr) {
2132 ProtectedDataGuard guard;
dimitry55547db2018-05-25 14:17:37 +02002133 soinfo_unload(si);
dimitry06016f22018-01-05 11:39:28 +01002134 } else {
2135 async_safe_fatal(
2136 "decrement_dso_handle_reference_counter: Couldn't find soinfo by dso_handle=%p",
2137 dso_handle);
2138 }
2139 g_dso_handle_counters.erase(it);
2140 }
2141}
2142
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002143static std::string symbol_display_name(const char* sym_name, const char* sym_ver) {
2144 if (sym_ver == nullptr) {
2145 return sym_name;
2146 }
2147
Dimitry Ivanov9cf99cb2015-12-11 14:22:24 -08002148 return std::string(sym_name) + ", version " + sym_ver;
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002149}
2150
Dimitry Ivanovaca299a2016-04-11 12:42:58 -07002151static android_namespace_t* get_caller_namespace(soinfo* caller) {
2152 return caller != nullptr ? caller->get_primary_namespace() : g_anonymous_namespace;
2153}
2154
Elliott Hughesa4aafd12014-01-13 16:37:47 -08002155void do_android_get_LD_LIBRARY_PATH(char* buffer, size_t buffer_size) {
Christopher Ferris052fa3a2014-08-26 20:48:11 -07002156 // Use basic string manipulation calls to avoid snprintf.
2157 // snprintf indirectly calls pthread_getspecific to get the size of a buffer.
2158 // When debug malloc is enabled, this call returns 0. This in turn causes
2159 // snprintf to do nothing, which causes libraries to fail to load.
2160 // See b/17302493 for further details.
2161 // Once the above bug is fixed, this code can be modified to use
2162 // snprintf again.
Dimitry Ivanov77ad6422017-03-06 13:02:29 -08002163 const auto& default_ld_paths = g_default_namespace.get_default_library_paths();
2164
2165 size_t required_size = 0;
2166 for (const auto& path : default_ld_paths) {
2167 required_size += path.size() + 1;
Evgenii Stepanovd640b222015-07-10 17:54:01 -07002168 }
Dimitry Ivanov77ad6422017-03-06 13:02:29 -08002169
2170 if (buffer_size < required_size) {
Christopher Ferris7a3681e2017-04-24 17:48:32 -07002171 async_safe_fatal("android_get_LD_LIBRARY_PATH failed, buffer too small: "
2172 "buffer len %zu, required len %zu", buffer_size, required_size);
Christopher Ferris052fa3a2014-08-26 20:48:11 -07002173 }
Dimitry Ivanov77ad6422017-03-06 13:02:29 -08002174
Evgenii Stepanovd640b222015-07-10 17:54:01 -07002175 char* end = buffer;
Dimitry Ivanov77ad6422017-03-06 13:02:29 -08002176 for (size_t i = 0; i < default_ld_paths.size(); ++i) {
Evgenii Stepanovd640b222015-07-10 17:54:01 -07002177 if (i > 0) *end++ = ':';
Dimitry Ivanov77ad6422017-03-06 13:02:29 -08002178 end = stpcpy(end, default_ld_paths[i].c_str());
Evgenii Stepanovd640b222015-07-10 17:54:01 -07002179 }
Elliott Hughesa4aafd12014-01-13 16:37:47 -08002180}
2181
Elliott Hughescade4c32012-12-20 14:42:14 -08002182void do_android_update_LD_LIBRARY_PATH(const char* ld_library_path) {
Nick Kralevich6bb01b62015-03-07 13:37:05 -08002183 parse_LD_LIBRARY_PATH(ld_library_path);
Elliott Hughescade4c32012-12-20 14:42:14 -08002184}
2185
Dimitry Ivanovb996d602016-07-11 18:11:39 -07002186static std::string android_dlextinfo_to_string(const android_dlextinfo* info) {
2187 if (info == nullptr) {
2188 return "(null)";
2189 }
2190
2191 return android::base::StringPrintf("[flags=0x%" PRIx64 ","
2192 " reserved_addr=%p,"
2193 " reserved_size=0x%zx,"
2194 " relro_fd=%d,"
2195 " library_fd=%d,"
2196 " library_fd_offset=0x%" PRIx64 ","
2197 " library_namespace=%s@%p]",
2198 info->flags,
2199 info->reserved_addr,
2200 info->reserved_size,
2201 info->relro_fd,
2202 info->library_fd,
2203 info->library_fd_offset,
2204 (info->flags & ANDROID_DLEXT_USE_NAMESPACE) != 0 ?
2205 (info->library_namespace != nullptr ?
2206 info->library_namespace->get_name() : "(null)") : "(n/a)",
2207 (info->flags & ANDROID_DLEXT_USE_NAMESPACE) != 0 ?
2208 info->library_namespace : nullptr);
2209}
2210
Dimitry Ivanovd9e427c2016-11-22 16:55:25 -08002211void* do_dlopen(const char* name, int flags,
2212 const android_dlextinfo* extinfo,
2213 const void* caller_addr) {
Dimitry Ivanov5c4a5802017-03-17 16:41:34 -07002214 std::string trace_prefix = std::string("dlopen: ") + (name == nullptr ? "(nullptr)" : name);
2215 ScopedTrace trace(trace_prefix.c_str());
2216 ScopedTrace loading_trace((trace_prefix + " - loading and linking").c_str());
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002217 soinfo* const caller = find_containing_library(caller_addr);
Dimitry Ivanovb996d602016-07-11 18:11:39 -07002218 android_namespace_t* ns = get_caller_namespace(caller);
2219
2220 LD_LOG(kLogDlopen,
Victor Chang6cb719f2019-02-06 17:19:10 +00002221 "dlopen(name=\"%s\", flags=0x%x, extinfo=%s, caller=\"%s\", caller_ns=%s@%p, targetSdkVersion=%i) ...",
Dimitry Ivanovb996d602016-07-11 18:11:39 -07002222 name,
2223 flags,
2224 android_dlextinfo_to_string(extinfo).c_str(),
2225 caller == nullptr ? "(null)" : caller->get_realpath(),
2226 ns == nullptr ? "(null)" : ns->get_name(),
Victor Chang6cb719f2019-02-06 17:19:10 +00002227 ns,
2228 get_application_target_sdk_version());
Dimitry Ivanovb996d602016-07-11 18:11:39 -07002229
Vic Yangbb7e1232019-01-29 20:23:16 -08002230 auto purge_guard = android::base::make_scope_guard([&]() { purge_unused_memory(); });
2231
Tom Cherryb8ab6182017-04-05 16:20:29 -07002232 auto failure_guard = android::base::make_scope_guard(
2233 [&]() { LD_LOG(kLogDlopen, "... dlopen failed: %s", linker_get_error_buffer()); });
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002234
Dmitriy Ivanov1b20daf2014-05-19 15:06:58 -07002235 if ((flags & ~(RTLD_NOW|RTLD_LAZY|RTLD_LOCAL|RTLD_GLOBAL|RTLD_NODELETE|RTLD_NOLOAD)) != 0) {
Elliott Hughese66190d2012-12-18 15:57:55 -08002236 DL_ERR("invalid flags to dlopen: %x", flags);
Dmitriy Ivanov851135b2014-08-29 12:02:36 -07002237 return nullptr;
Elliott Hughese66190d2012-12-18 15:57:55 -08002238 }
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002239
Dmitriy Ivanov07e5bc12014-10-03 17:52:44 -07002240 if (extinfo != nullptr) {
2241 if ((extinfo->flags & ~(ANDROID_DLEXT_VALID_FLAG_BITS)) != 0) {
2242 DL_ERR("invalid extended flags to android_dlopen_ext: 0x%" PRIx64, extinfo->flags);
2243 return nullptr;
2244 }
Dmitriy Ivanov126af752015-10-07 16:34:20 -07002245
Dmitriy Ivanov07e5bc12014-10-03 17:52:44 -07002246 if ((extinfo->flags & ANDROID_DLEXT_USE_LIBRARY_FD) == 0 &&
Dmitriy Ivanova6c12792014-10-21 12:09:18 -07002247 (extinfo->flags & ANDROID_DLEXT_USE_LIBRARY_FD_OFFSET) != 0) {
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07002248 DL_ERR("invalid extended flag combination (ANDROID_DLEXT_USE_LIBRARY_FD_OFFSET without "
2249 "ANDROID_DLEXT_USE_LIBRARY_FD): 0x%" PRIx64, extinfo->flags);
Dmitriy Ivanov07e5bc12014-10-03 17:52:44 -07002250 return nullptr;
2251 }
Dmitriy Ivanov126af752015-10-07 16:34:20 -07002252
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002253 if ((extinfo->flags & ANDROID_DLEXT_USE_NAMESPACE) != 0) {
2254 if (extinfo->library_namespace == nullptr) {
2255 DL_ERR("ANDROID_DLEXT_USE_NAMESPACE is set but extinfo->library_namespace is null");
2256 return nullptr;
2257 }
2258 ns = extinfo->library_namespace;
2259 }
Torne (Richard Coles)012cb452014-02-06 14:34:21 +00002260 }
Dmitriy Ivanov279a22f2015-01-23 12:03:53 -08002261
Victor Chang6cb719f2019-02-06 17:19:10 +00002262 // Workaround for dlopen(/system/lib/<soname>) when .so is in /apex. http://b/121248172
2263 // The workaround works only when targetSdkVersion < Q.
2264 std::string name_to_apex;
2265 if (translateSystemPathToApexPath(name, &name_to_apex)) {
2266 const char* new_name = name_to_apex.c_str();
2267 LD_LOG(kLogDlopen, "dlopen considering translation from %s to APEX path %s",
2268 name,
2269 new_name);
2270 // Some APEXs could be optionally disabled. Only translate the path
2271 // when the old file is absent and the new file exists.
Victor Changaf12c942019-02-11 19:35:24 +00002272 // TODO(b/124218500): Re-enable it once app compat issue is resolved
2273 /*
Victor Chang6cb719f2019-02-06 17:19:10 +00002274 if (file_exists(name)) {
2275 LD_LOG(kLogDlopen, "dlopen %s exists, not translating", name);
Victor Changaf12c942019-02-11 19:35:24 +00002276 } else
2277 */
2278 if (!file_exists(new_name)) {
Victor Chang6cb719f2019-02-06 17:19:10 +00002279 LD_LOG(kLogDlopen, "dlopen %s does not exist, not translating",
2280 new_name);
2281 } else {
2282 LD_LOG(kLogDlopen, "dlopen translation accepted: using %s", new_name);
2283 name = new_name;
2284 }
2285 }
2286 // End Workaround for dlopen(/system/lib/<soname>) when .so is in /apex.
2287
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -07002288 std::string asan_name_holder;
2289
2290 const char* translated_name = name;
Dimitry Ivanov6c14f862016-12-05 13:35:47 -08002291 if (g_is_asan && translated_name != nullptr && translated_name[0] == '/') {
Evgenii Stepanov9e77a642017-07-27 14:55:44 -07002292 char original_path[PATH_MAX];
2293 if (realpath(name, original_path) != nullptr) {
2294 asan_name_holder = std::string(kAsanLibDirPrefix) + original_path;
Vishwath Mohan4113def2017-03-29 15:31:34 -07002295 if (file_exists(asan_name_holder.c_str())) {
Evgenii Stepanov9e77a642017-07-27 14:55:44 -07002296 soinfo* si = nullptr;
2297 if (find_loaded_library_by_realpath(ns, original_path, true, &si)) {
2298 PRINT("linker_asan dlopen NOT translating \"%s\" -> \"%s\": library already loaded", name,
2299 asan_name_holder.c_str());
2300 } else {
2301 PRINT("linker_asan dlopen translating \"%s\" -> \"%s\"", name, translated_name);
2302 translated_name = asan_name_holder.c_str();
2303 }
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -07002304 }
2305 }
2306 }
2307
Dmitriy Ivanov279a22f2015-01-23 12:03:53 -08002308 ProtectedDataGuard guard;
Dimitry Ivanov45d25ca2016-08-09 19:38:43 -07002309 soinfo* si = find_library(ns, translated_name, flags, extinfo, caller);
Dimitry Ivanov5c4a5802017-03-17 16:41:34 -07002310 loading_trace.End();
2311
Dmitriy Ivanov851135b2014-08-29 12:02:36 -07002312 if (si != nullptr) {
Dimitry Ivanovb996d602016-07-11 18:11:39 -07002313 void* handle = si->to_handle();
2314 LD_LOG(kLogDlopen,
Dimitry Ivanovae4a0c12016-11-21 10:44:35 -08002315 "... dlopen calling constructors: realpath=\"%s\", soname=\"%s\", handle=%p",
2316 si->get_realpath(), si->get_soname(), handle);
2317 si->call_constructors();
Tom Cherryb8ab6182017-04-05 16:20:29 -07002318 failure_guard.Disable();
Dimitry Ivanovae4a0c12016-11-21 10:44:35 -08002319 LD_LOG(kLogDlopen,
Dimitry Ivanovb996d602016-07-11 18:11:39 -07002320 "... dlopen successful: realpath=\"%s\", soname=\"%s\", handle=%p",
2321 si->get_realpath(), si->get_soname(), handle);
2322 return handle;
Elliott Hughesd23736e2012-11-01 15:16:56 -07002323 }
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002324
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -07002325 return nullptr;
Elliott Hughesd23736e2012-11-01 15:16:56 -07002326}
2327
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002328int do_dladdr(const void* addr, Dl_info* info) {
2329 // Determine if this address can be found in any library currently mapped.
2330 soinfo* si = find_containing_library(addr);
2331 if (si == nullptr) {
2332 return 0;
2333 }
2334
2335 memset(info, 0, sizeof(Dl_info));
2336
2337 info->dli_fname = si->get_realpath();
2338 // Address at which the shared object is loaded.
2339 info->dli_fbase = reinterpret_cast<void*>(si->base);
2340
2341 // Determine if any symbol in the library contains the specified address.
2342 ElfW(Sym)* sym = si->find_symbol_by_address(addr);
2343 if (sym != nullptr) {
2344 info->dli_sname = si->get_string(sym->st_name);
2345 info->dli_saddr = reinterpret_cast<void*>(si->resolve_symbol_address(sym));
2346 }
2347
2348 return 1;
2349}
2350
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -07002351static soinfo* soinfo_from_handle(void* handle) {
2352 if ((reinterpret_cast<uintptr_t>(handle) & 1) != 0) {
2353 auto it = g_soinfo_handles_map.find(reinterpret_cast<uintptr_t>(handle));
2354 if (it == g_soinfo_handles_map.end()) {
2355 return nullptr;
2356 } else {
2357 return it->second;
2358 }
2359 }
2360
2361 return static_cast<soinfo*>(handle);
2362}
2363
Dimitry Ivanovd9e427c2016-11-22 16:55:25 -08002364bool do_dlsym(void* handle,
2365 const char* sym_name,
2366 const char* sym_ver,
2367 const void* caller_addr,
2368 void** symbol) {
Dimitry Ivanov6705e8c2017-03-21 10:29:06 -07002369 ScopedTrace trace("dlsym");
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002370#if !defined(__LP64__)
2371 if (handle == nullptr) {
2372 DL_ERR("dlsym failed: library handle is null");
2373 return false;
2374 }
2375#endif
2376
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002377 soinfo* found = nullptr;
2378 const ElfW(Sym)* sym = nullptr;
2379 soinfo* caller = find_containing_library(caller_addr);
Dimitry Ivanovaca299a2016-04-11 12:42:58 -07002380 android_namespace_t* ns = get_caller_namespace(caller);
Dimitry Ivanov4742abd2016-12-12 16:30:15 -08002381 soinfo* si = nullptr;
2382 if (handle != RTLD_DEFAULT && handle != RTLD_NEXT) {
2383 si = soinfo_from_handle(handle);
2384 }
2385
2386 LD_LOG(kLogDlsym,
2387 "dlsym(handle=%p(\"%s\"), sym_name=\"%s\", sym_ver=\"%s\", caller=\"%s\", caller_ns=%s@%p) ...",
2388 handle,
2389 si != nullptr ? si->get_realpath() : "n/a",
2390 sym_name,
2391 sym_ver,
2392 caller == nullptr ? "(null)" : caller->get_realpath(),
2393 ns == nullptr ? "(null)" : ns->get_name(),
2394 ns);
2395
Tom Cherryb8ab6182017-04-05 16:20:29 -07002396 auto failure_guard = android::base::make_scope_guard(
2397 [&]() { LD_LOG(kLogDlsym, "... dlsym failed: %s", linker_get_error_buffer()); });
Dimitry Ivanov4742abd2016-12-12 16:30:15 -08002398
2399 if (sym_name == nullptr) {
2400 DL_ERR("dlsym failed: symbol name is null");
2401 return false;
2402 }
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002403
2404 version_info vi_instance;
2405 version_info* vi = nullptr;
2406
2407 if (sym_ver != nullptr) {
Dimitry Ivanov9cf99cb2015-12-11 14:22:24 -08002408 vi_instance.name = sym_ver;
2409 vi_instance.elf_hash = calculate_elf_hash(sym_ver);
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002410 vi = &vi_instance;
2411 }
2412
2413 if (handle == RTLD_DEFAULT || handle == RTLD_NEXT) {
2414 sym = dlsym_linear_lookup(ns, sym_name, vi, &found, caller, handle);
2415 } else {
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -07002416 if (si == nullptr) {
2417 DL_ERR("dlsym failed: invalid handle: %p", handle);
2418 return false;
2419 }
2420 sym = dlsym_handle_lookup(si, &found, sym_name, vi);
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002421 }
2422
2423 if (sym != nullptr) {
2424 uint32_t bind = ELF_ST_BIND(sym->st_info);
Ryan Pricharde4d620b2019-04-01 17:42:14 -07002425 uint32_t type = ELF_ST_TYPE(sym->st_info);
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002426
2427 if ((bind == STB_GLOBAL || bind == STB_WEAK) && sym->st_shndx != 0) {
Ryan Pricharde4d620b2019-04-01 17:42:14 -07002428 if (type == STT_TLS) {
2429 // For a TLS symbol, dlsym returns the address of the current thread's
2430 // copy of the symbol. This function may allocate a DTV and/or storage
2431 // for the source TLS module. (Allocating a DTV isn't necessary if the
2432 // symbol is part of static TLS, but it's simpler to reuse
2433 // __tls_get_addr.)
2434 soinfo_tls* tls_module = found->get_tls();
2435 if (tls_module == nullptr) {
2436 DL_ERR("TLS symbol \"%s\" in solib \"%s\" with no TLS segment",
2437 sym_name, found->get_realpath());
2438 return false;
2439 }
2440 const TlsIndex ti { tls_module->module_id, sym->st_value };
2441 *symbol = TLS_GET_ADDR(&ti);
2442 } else {
2443 *symbol = reinterpret_cast<void*>(found->resolve_symbol_address(sym));
2444 }
Tom Cherryb8ab6182017-04-05 16:20:29 -07002445 failure_guard.Disable();
Dimitry Ivanov4742abd2016-12-12 16:30:15 -08002446 LD_LOG(kLogDlsym,
2447 "... dlsym successful: sym_name=\"%s\", sym_ver=\"%s\", found in=\"%s\", address=%p",
2448 sym_name, sym_ver, found->get_soname(), *symbol);
Dimitry Ivanov4a2c5aa2015-12-10 16:08:14 -08002449 return true;
2450 }
2451
2452 DL_ERR("symbol \"%s\" found but not global", symbol_display_name(sym_name, sym_ver).c_str());
2453 return false;
2454 }
2455
2456 DL_ERR("undefined symbol: %s", symbol_display_name(sym_name, sym_ver).c_str());
2457 return false;
2458}
2459
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -07002460int do_dlclose(void* handle) {
Dimitry Ivanov6705e8c2017-03-21 10:29:06 -07002461 ScopedTrace trace("dlclose");
Dmitriy Ivanov279a22f2015-01-23 12:03:53 -08002462 ProtectedDataGuard guard;
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -07002463 soinfo* si = soinfo_from_handle(handle);
2464 if (si == nullptr) {
2465 DL_ERR("invalid handle: %p", handle);
2466 return -1;
2467 }
2468
dimitryc92ce712017-10-27 14:12:53 +02002469 LD_LOG(kLogDlopen,
2470 "dlclose(handle=%p, realpath=\"%s\"@%p) ...",
2471 handle,
2472 si->get_realpath(),
2473 si);
Dmitriy Ivanovb648a8a2014-05-19 15:06:58 -07002474 soinfo_unload(si);
dimitryc92ce712017-10-27 14:12:53 +02002475 LD_LOG(kLogDlopen,
2476 "dlclose(handle=%p) ... done",
2477 handle);
Dimitry Ivanovd88e1f32016-03-24 15:30:30 -07002478 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002479}
2480
Jiyong Park25bedfd2019-05-16 21:00:39 +09002481// Make ns as the anonymous namespace that is a namespace used when
2482// we fail to determine the caller address (e.g., call from mono-jited code)
2483// Since there can be multiple anonymous namespace in a process, subsequent
2484// call to this function causes an error.
2485static bool set_anonymous_namespace(android_namespace_t* ns) {
2486 if (!g_anonymous_namespace_set && ns != nullptr) {
2487 CHECK(ns->is_also_used_as_anonymous());
2488 g_anonymous_namespace = ns;
2489 g_anonymous_namespace_set = true;
2490 return true;
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002491 }
Jiyong Park25bedfd2019-05-16 21:00:39 +09002492 return false;
2493}
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002494
Jiyong Park25bedfd2019-05-16 21:00:39 +09002495// TODO(b/130388701) remove this. Currently, this is used only for testing
2496// where we don't have classloader namespace.
2497bool init_anonymous_namespace(const char* shared_lib_sonames, const char* library_search_path) {
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002498 ProtectedDataGuard guard;
2499
Jiyong Park25bedfd2019-05-16 21:00:39 +09002500 // Test-only feature: we need to change the anonymous namespace multiple times
2501 // while the test is running.
2502 g_anonymous_namespace_set = false;
2503
Dmitriy Ivanov1ffec1c2015-11-23 11:26:35 -08002504 // create anonymous namespace
Dimitry Ivanov7331fe12015-12-14 14:11:17 -08002505 // When the caller is nullptr - create_namespace will take global group
2506 // from the anonymous namespace, which is fine because anonymous namespace
2507 // is still pointing to the default one.
Dmitriy Ivanov1ffec1c2015-11-23 11:26:35 -08002508 android_namespace_t* anon_ns =
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -08002509 create_namespace(nullptr,
2510 "(anonymous)",
2511 nullptr,
2512 library_search_path,
Jiyong Park25bedfd2019-05-16 21:00:39 +09002513 ANDROID_NAMESPACE_TYPE_ISOLATED |
2514 ANDROID_NAMESPACE_TYPE_ALSO_USED_AS_ANONYMOUS,
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -08002515 nullptr,
2516 &g_default_namespace);
Dmitriy Ivanov1ffec1c2015-11-23 11:26:35 -08002517
Jiyong Park25bedfd2019-05-16 21:00:39 +09002518 CHECK(anon_ns != nullptr);
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -08002519
2520 if (!link_namespaces(anon_ns, &g_default_namespace, shared_lib_sonames)) {
Jiyong Park25bedfd2019-05-16 21:00:39 +09002521 // TODO: delete anon_ns
Dmitriy Ivanov1ffec1c2015-11-23 11:26:35 -08002522 return false;
2523 }
Dimitry Ivanov7d429d32017-02-01 15:28:52 -08002524
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002525 return true;
2526}
2527
Dimitry Ivanovb943f302016-08-03 16:00:10 -07002528static void add_soinfos_to_namespace(const soinfo_list_t& soinfos, android_namespace_t* ns) {
2529 ns->add_soinfos(soinfos);
2530 for (auto si : soinfos) {
2531 si->add_secondary_namespace(ns);
2532 }
2533}
2534
Dimitry Ivanov7331fe12015-12-14 14:11:17 -08002535android_namespace_t* create_namespace(const void* caller_addr,
2536 const char* name,
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002537 const char* ld_library_path,
2538 const char* default_library_path,
Dimitry Ivanov7331fe12015-12-14 14:11:17 -08002539 uint64_t type,
Dimitry Ivanovfc2da532016-05-12 15:20:21 -07002540 const char* permitted_when_isolated_path,
2541 android_namespace_t* parent_namespace) {
Dimitry Ivanovfc2da532016-05-12 15:20:21 -07002542 if (parent_namespace == nullptr) {
Dimitry Ivanov52408632016-05-23 10:31:11 -07002543 // if parent_namespace is nullptr -> set it to the caller namespace
2544 soinfo* caller_soinfo = find_containing_library(caller_addr);
2545
2546 parent_namespace = caller_soinfo != nullptr ?
2547 caller_soinfo->get_primary_namespace() :
2548 g_anonymous_namespace;
Dimitry Ivanovfc2da532016-05-12 15:20:21 -07002549 }
2550
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002551 ProtectedDataGuard guard;
2552 std::vector<std::string> ld_library_paths;
2553 std::vector<std::string> default_library_paths;
Dimitry Ivanov284ae352015-12-08 10:47:13 -08002554 std::vector<std::string> permitted_paths;
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002555
2556 parse_path(ld_library_path, ":", &ld_library_paths);
2557 parse_path(default_library_path, ":", &default_library_paths);
Dimitry Ivanov284ae352015-12-08 10:47:13 -08002558 parse_path(permitted_when_isolated_path, ":", &permitted_paths);
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002559
2560 android_namespace_t* ns = new (g_namespace_allocator.alloc()) android_namespace_t();
2561 ns->set_name(name);
Dimitry Ivanov7331fe12015-12-14 14:11:17 -08002562 ns->set_isolated((type & ANDROID_NAMESPACE_TYPE_ISOLATED) != 0);
Jiyong Park37b91af2017-05-05 22:07:05 +09002563 ns->set_greylist_enabled((type & ANDROID_NAMESPACE_TYPE_GREYLIST_ENABLED) != 0);
Jiyong Park25bedfd2019-05-16 21:00:39 +09002564 ns->set_also_used_as_anonymous((type & ANDROID_NAMESPACE_TYPE_ALSO_USED_AS_ANONYMOUS) != 0);
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002565
Dimitry Ivanov7331fe12015-12-14 14:11:17 -08002566 if ((type & ANDROID_NAMESPACE_TYPE_SHARED) != 0) {
Dimitry Ivanovf1cb6692017-05-01 17:45:38 -07002567 // append parent namespace paths.
2568 std::copy(parent_namespace->get_ld_library_paths().begin(),
2569 parent_namespace->get_ld_library_paths().end(),
2570 back_inserter(ld_library_paths));
2571
2572 std::copy(parent_namespace->get_default_library_paths().begin(),
2573 parent_namespace->get_default_library_paths().end(),
2574 back_inserter(default_library_paths));
2575
2576 std::copy(parent_namespace->get_permitted_paths().begin(),
2577 parent_namespace->get_permitted_paths().end(),
2578 back_inserter(permitted_paths));
2579
Dimitry Ivanovfc2da532016-05-12 15:20:21 -07002580 // If shared - clone the parent namespace
Dimitry Ivanovb943f302016-08-03 16:00:10 -07002581 add_soinfos_to_namespace(parent_namespace->soinfo_list(), ns);
Dimitry Ivanovf1cb6692017-05-01 17:45:38 -07002582 // and copy parent namespace links
2583 for (auto& link : parent_namespace->linked_namespaces()) {
Logan Chien9ee45912018-01-18 12:05:09 +08002584 ns->add_linked_namespace(link.linked_namespace(), link.shared_lib_sonames(),
2585 link.allow_all_shared_libs());
Dimitry Ivanovf1cb6692017-05-01 17:45:38 -07002586 }
Dimitry Ivanov7331fe12015-12-14 14:11:17 -08002587 } else {
Dimitry Ivanovfc2da532016-05-12 15:20:21 -07002588 // If not shared - copy only the shared group
Jiyong Park02586a22017-05-20 01:01:24 +09002589 add_soinfos_to_namespace(parent_namespace->get_shared_group(), ns);
Dimitry Ivanov7331fe12015-12-14 14:11:17 -08002590 }
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002591
Dimitry Ivanovf1cb6692017-05-01 17:45:38 -07002592 ns->set_ld_library_paths(std::move(ld_library_paths));
2593 ns->set_default_library_paths(std::move(default_library_paths));
2594 ns->set_permitted_paths(std::move(permitted_paths));
2595
Jiyong Park25bedfd2019-05-16 21:00:39 +09002596 if (ns->is_also_used_as_anonymous() && !set_anonymous_namespace(ns)) {
2597 DL_ERR("failed to set namespace: [name=\"%s\", ld_library_path=\"%s\", default_library_paths=\"%s\""
2598 " permitted_paths=\"%s\"] as the anonymous namespace",
2599 ns->get_name(),
2600 android::base::Join(ns->get_ld_library_paths(), ':').c_str(),
2601 android::base::Join(ns->get_default_library_paths(), ':').c_str(),
2602 android::base::Join(ns->get_permitted_paths(), ':').c_str());
2603 return nullptr;
2604 }
2605
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07002606 return ns;
2607}
2608
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -08002609bool link_namespaces(android_namespace_t* namespace_from,
2610 android_namespace_t* namespace_to,
2611 const char* shared_lib_sonames) {
2612 if (namespace_to == nullptr) {
2613 namespace_to = &g_default_namespace;
2614 }
2615
2616 if (namespace_from == nullptr) {
2617 DL_ERR("error linking namespaces: namespace_from is null.");
2618 return false;
2619 }
2620
2621 if (shared_lib_sonames == nullptr || shared_lib_sonames[0] == '\0') {
2622 DL_ERR("error linking namespaces \"%s\"->\"%s\": the list of shared libraries is empty.",
2623 namespace_from->get_name(), namespace_to->get_name());
2624 return false;
2625 }
2626
2627 auto sonames = android::base::Split(shared_lib_sonames, ":");
2628 std::unordered_set<std::string> sonames_set(sonames.begin(), sonames.end());
2629
2630 ProtectedDataGuard guard;
Logan Chien9ee45912018-01-18 12:05:09 +08002631 namespace_from->add_linked_namespace(namespace_to, sonames_set, false);
2632
2633 return true;
2634}
2635
2636bool link_namespaces_all_libs(android_namespace_t* namespace_from,
2637 android_namespace_t* namespace_to) {
2638 if (namespace_from == nullptr) {
2639 DL_ERR("error linking namespaces: namespace_from is null.");
2640 return false;
2641 }
2642
2643 if (namespace_to == nullptr) {
2644 DL_ERR("error linking namespaces: namespace_to is null.");
2645 return false;
2646 }
2647
2648 ProtectedDataGuard guard;
2649 namespace_from->add_linked_namespace(namespace_to, std::unordered_set<std::string>(), true);
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -08002650
2651 return true;
2652}
2653
Dimitry Ivanov48ec2882016-08-04 11:50:36 -07002654ElfW(Addr) call_ifunc_resolver(ElfW(Addr) resolver_addr) {
Elliott Hughes90f96b92019-05-09 15:56:39 -07002655 if (g_is_ldd) return 0;
2656
Dmitriy Ivanov9aea1642014-09-11 15:16:03 -07002657 typedef ElfW(Addr) (*ifunc_resolver_t)(void);
2658 ifunc_resolver_t ifunc_resolver = reinterpret_cast<ifunc_resolver_t>(resolver_addr);
2659 ElfW(Addr) ifunc_addr = ifunc_resolver();
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07002660 TRACE_TYPE(RELO, "Called ifunc_resolver@%p. The result is %p",
2661 ifunc_resolver, reinterpret_cast<void*>(ifunc_addr));
Brigid Smithc5a13ef2014-07-23 11:22:25 -07002662
Dmitriy Ivanov9aea1642014-09-11 15:16:03 -07002663 return ifunc_addr;
Brigid Smithc5a13ef2014-07-23 11:22:25 -07002664}
Brigid Smithc5a13ef2014-07-23 11:22:25 -07002665
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07002666const version_info* VersionTracker::get_version_info(ElfW(Versym) source_symver) const {
2667 if (source_symver < 2 ||
2668 source_symver >= version_infos.size() ||
2669 version_infos[source_symver].name == nullptr) {
2670 return nullptr;
2671 }
2672
2673 return &version_infos[source_symver];
2674}
2675
2676void VersionTracker::add_version_info(size_t source_index,
2677 ElfW(Word) elf_hash,
2678 const char* ver_name,
2679 const soinfo* target_si) {
2680 if (source_index >= version_infos.size()) {
2681 version_infos.resize(source_index+1);
2682 }
2683
2684 version_infos[source_index].elf_hash = elf_hash;
2685 version_infos[source_index].name = ver_name;
2686 version_infos[source_index].target_si = target_si;
2687}
2688
2689bool VersionTracker::init_verneed(const soinfo* si_from) {
2690 uintptr_t verneed_ptr = si_from->get_verneed_ptr();
2691
2692 if (verneed_ptr == 0) {
2693 return true;
2694 }
2695
2696 size_t verneed_cnt = si_from->get_verneed_cnt();
2697
2698 for (size_t i = 0, offset = 0; i<verneed_cnt; ++i) {
2699 const ElfW(Verneed)* verneed = reinterpret_cast<ElfW(Verneed)*>(verneed_ptr + offset);
2700 size_t vernaux_offset = offset + verneed->vn_aux;
2701 offset += verneed->vn_next;
2702
2703 if (verneed->vn_version != 1) {
2704 DL_ERR("unsupported verneed[%zd] vn_version: %d (expected 1)", i, verneed->vn_version);
2705 return false;
2706 }
2707
2708 const char* target_soname = si_from->get_string(verneed->vn_file);
2709 // find it in dependencies
2710 soinfo* target_si = si_from->get_children().find_if([&](const soinfo* si) {
Dmitriy Ivanov406d9962015-05-06 11:05:27 -07002711 return si->get_soname() != nullptr && strcmp(si->get_soname(), target_soname) == 0;
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07002712 });
2713
2714 if (target_si == nullptr) {
2715 DL_ERR("cannot find \"%s\" from verneed[%zd] in DT_NEEDED list for \"%s\"",
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07002716 target_soname, i, si_from->get_realpath());
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07002717 return false;
2718 }
2719
2720 for (size_t j = 0; j<verneed->vn_cnt; ++j) {
2721 const ElfW(Vernaux)* vernaux = reinterpret_cast<ElfW(Vernaux)*>(verneed_ptr + vernaux_offset);
2722 vernaux_offset += vernaux->vna_next;
2723
2724 const ElfW(Word) elf_hash = vernaux->vna_hash;
2725 const char* ver_name = si_from->get_string(vernaux->vna_name);
2726 ElfW(Half) source_index = vernaux->vna_other;
2727
2728 add_version_info(source_index, elf_hash, ver_name, target_si);
2729 }
2730 }
2731
2732 return true;
2733}
2734
Dimitry Ivanov48ec2882016-08-04 11:50:36 -07002735template <typename F>
2736static bool for_each_verdef(const soinfo* si, F functor) {
2737 if (!si->has_min_version(2)) {
2738 return true;
2739 }
2740
2741 uintptr_t verdef_ptr = si->get_verdef_ptr();
2742 if (verdef_ptr == 0) {
2743 return true;
2744 }
2745
2746 size_t offset = 0;
2747
2748 size_t verdef_cnt = si->get_verdef_cnt();
2749 for (size_t i = 0; i<verdef_cnt; ++i) {
2750 const ElfW(Verdef)* verdef = reinterpret_cast<ElfW(Verdef)*>(verdef_ptr + offset);
2751 size_t verdaux_offset = offset + verdef->vd_aux;
2752 offset += verdef->vd_next;
2753
2754 if (verdef->vd_version != 1) {
2755 DL_ERR("unsupported verdef[%zd] vd_version: %d (expected 1) library: %s",
2756 i, verdef->vd_version, si->get_realpath());
2757 return false;
2758 }
2759
2760 if ((verdef->vd_flags & VER_FLG_BASE) != 0) {
2761 // "this is the version of the file itself. It must not be used for
2762 // matching a symbol. It can be used to match references."
2763 //
2764 // http://www.akkadia.org/drepper/symbol-versioning
2765 continue;
2766 }
2767
2768 if (verdef->vd_cnt == 0) {
2769 DL_ERR("invalid verdef[%zd] vd_cnt == 0 (version without a name)", i);
2770 return false;
2771 }
2772
2773 const ElfW(Verdaux)* verdaux = reinterpret_cast<ElfW(Verdaux)*>(verdef_ptr + verdaux_offset);
2774
2775 if (functor(i, verdef, verdaux) == true) {
2776 break;
2777 }
2778 }
2779
2780 return true;
2781}
2782
2783bool find_verdef_version_index(const soinfo* si, const version_info* vi, ElfW(Versym)* versym) {
2784 if (vi == nullptr) {
2785 *versym = kVersymNotNeeded;
2786 return true;
2787 }
2788
2789 *versym = kVersymGlobal;
2790
2791 return for_each_verdef(si,
2792 [&](size_t, const ElfW(Verdef)* verdef, const ElfW(Verdaux)* verdaux) {
2793 if (verdef->vd_hash == vi->elf_hash &&
2794 strcmp(vi->name, si->get_string(verdaux->vda_name)) == 0) {
2795 *versym = verdef->vd_ndx;
2796 return true;
2797 }
2798
2799 return false;
2800 }
2801 );
2802}
2803
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07002804bool VersionTracker::init_verdef(const soinfo* si_from) {
2805 return for_each_verdef(si_from,
2806 [&](size_t, const ElfW(Verdef)* verdef, const ElfW(Verdaux)* verdaux) {
2807 add_version_info(verdef->vd_ndx, verdef->vd_hash,
2808 si_from->get_string(verdaux->vda_name), si_from);
2809 return false;
2810 }
2811 );
2812}
2813
2814bool VersionTracker::init(const soinfo* si_from) {
2815 if (!si_from->has_min_version(2)) {
2816 return true;
2817 }
2818
2819 return init_verneed(si_from) && init_verdef(si_from);
2820}
2821
Dimitry Ivanov48ec2882016-08-04 11:50:36 -07002822// TODO (dimitry): Methods below need to be moved out of soinfo
2823// and in more isolated file in order minimize dependencies on
2824// unnecessary object in the linker binary. Consider making them
2825// independent from soinfo (?).
Dmitriy Ivanov31b408d2015-04-30 16:11:48 -07002826bool soinfo::lookup_version_info(const VersionTracker& version_tracker, ElfW(Word) sym,
2827 const char* sym_name, const version_info** vi) {
2828 const ElfW(Versym)* sym_ver_ptr = get_versym(sym);
2829 ElfW(Versym) sym_ver = sym_ver_ptr == nullptr ? 0 : *sym_ver_ptr;
2830
2831 if (sym_ver != VER_NDX_LOCAL && sym_ver != VER_NDX_GLOBAL) {
2832 *vi = version_tracker.get_version_info(sym_ver);
2833
2834 if (*vi == nullptr) {
2835 DL_ERR("cannot find verneed/verdef for version index=%d "
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07002836 "referenced by symbol \"%s\" at \"%s\"", sym_ver, sym_name, get_realpath());
Dmitriy Ivanov31b408d2015-04-30 16:11:48 -07002837 return false;
2838 }
2839 } else {
2840 // there is no version info
2841 *vi = nullptr;
2842 }
2843
2844 return true;
2845}
2846
Rahul Chaudhryf16b6592018-01-25 15:34:15 -08002847void soinfo::apply_relr_reloc(ElfW(Addr) offset) {
2848 ElfW(Addr) address = offset + load_bias;
2849 *reinterpret_cast<ElfW(Addr)*>(address) += load_bias;
2850}
2851
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08002852// Process relocations in SHT_RELR section (experimental).
Rahul Chaudhryf16b6592018-01-25 15:34:15 -08002853// Details of the encoding are described in this post:
2854// https://groups.google.com/d/msg/generic-abi/bX460iggiKg/Pi9aSwwABgAJ
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08002855bool soinfo::relocate_relr() {
2856 ElfW(Relr)* begin = relr_;
2857 ElfW(Relr)* end = relr_ + relr_count_;
Rahul Chaudhryf16b6592018-01-25 15:34:15 -08002858 constexpr size_t wordsize = sizeof(ElfW(Addr));
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08002859
Rahul Chaudhryf16b6592018-01-25 15:34:15 -08002860 ElfW(Addr) base = 0;
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08002861 for (ElfW(Relr)* current = begin; current < end; ++current) {
Rahul Chaudhryf16b6592018-01-25 15:34:15 -08002862 ElfW(Relr) entry = *current;
2863 ElfW(Addr) offset;
2864
2865 if ((entry&1) == 0) {
2866 // Even entry: encodes the offset for next relocation.
2867 offset = static_cast<ElfW(Addr)>(entry);
2868 apply_relr_reloc(offset);
2869 // Set base offset for subsequent bitmap entries.
2870 base = offset + wordsize;
2871 continue;
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08002872 }
Rahul Chaudhryf16b6592018-01-25 15:34:15 -08002873
2874 // Odd entry: encodes bitmap for relocations starting at base.
2875 offset = base;
2876 while (entry != 0) {
2877 entry >>= 1;
2878 if ((entry&1) != 0) {
2879 apply_relr_reloc(offset);
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08002880 }
Rahul Chaudhryf16b6592018-01-25 15:34:15 -08002881 offset += wordsize;
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08002882 }
Rahul Chaudhryf16b6592018-01-25 15:34:15 -08002883
2884 // Advance base offset by 63 words for 64-bit platforms,
2885 // or 31 words for 32-bit platforms.
2886 base += (8*wordsize - 1) * wordsize;
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08002887 }
2888 return true;
2889}
2890
Dimitry Ivanov576a3752016-08-09 06:58:55 -07002891#if !defined(__mips__)
2892#if defined(USE_RELA)
2893static ElfW(Addr) get_addend(ElfW(Rela)* rela, ElfW(Addr) reloc_addr __unused) {
2894 return rela->r_addend;
2895}
2896#else
2897static ElfW(Addr) get_addend(ElfW(Rel)* rel, ElfW(Addr) reloc_addr) {
2898 if (ELFW(R_TYPE)(rel->r_info) == R_GENERIC_RELATIVE ||
Ryan Prichardfb8730d2019-01-15 00:11:37 -08002899 ELFW(R_TYPE)(rel->r_info) == R_GENERIC_IRELATIVE ||
2900 ELFW(R_TYPE)(rel->r_info) == R_GENERIC_TLS_DTPREL ||
2901 ELFW(R_TYPE)(rel->r_info) == R_GENERIC_TLS_TPREL) {
Dimitry Ivanov576a3752016-08-09 06:58:55 -07002902 return *reinterpret_cast<ElfW(Addr)*>(reloc_addr);
2903 }
2904 return 0;
2905}
2906#endif
2907
Ryan Prichardfb8730d2019-01-15 00:11:37 -08002908static bool is_tls_reloc(ElfW(Word) type) {
2909 switch (type) {
2910 case R_GENERIC_TLS_DTPMOD:
2911 case R_GENERIC_TLS_DTPREL:
2912 case R_GENERIC_TLS_TPREL:
2913 case R_GENERIC_TLSDESC:
2914 return true;
2915 default:
2916 return false;
2917 }
2918}
2919
Dmitriy Ivanovfa26eee2015-02-03 16:06:47 -08002920template<typename ElfRelIteratorT>
Dmitriy Ivanov7e4bbba2015-04-30 19:49:19 -07002921bool soinfo::relocate(const VersionTracker& version_tracker, ElfRelIteratorT&& rel_iterator,
2922 const soinfo_list_t& global_group, const soinfo_list_t& local_group) {
Ryan Prichardfb8730d2019-01-15 00:11:37 -08002923 const size_t tls_tp_base = __libc_shared_globals()->static_tls_layout.offset_thread_pointer();
Ryan Prichardffaae702019-01-23 17:47:10 -08002924 std::vector<std::pair<TlsDescriptor*, size_t>> deferred_tlsdesc_relocs;
Ryan Prichardfb8730d2019-01-15 00:11:37 -08002925
Vic Yang521ad072019-07-25 11:05:33 -07002926 struct {
2927 // Cache key
2928 ElfW(Word) sym;
2929
2930 // Cache value
2931 const ElfW(Sym)* s;
2932 soinfo* lsi;
2933 } symbol_lookup_cache;
2934
2935 symbol_lookup_cache.sym = 0;
2936
Dmitriy Ivanovfa26eee2015-02-03 16:06:47 -08002937 for (size_t idx = 0; rel_iterator.has_next(); ++idx) {
2938 const auto rel = rel_iterator.next();
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08002939 if (rel == nullptr) {
2940 return false;
2941 }
2942
Dmitriy Ivanovbcc04d02015-01-13 12:12:38 -08002943 ElfW(Word) type = ELFW(R_TYPE)(rel->r_info);
2944 ElfW(Word) sym = ELFW(R_SYM)(rel->r_info);
2945
2946 ElfW(Addr) reloc = static_cast<ElfW(Addr)>(rel->r_offset + load_bias);
Elliott Hughes0266ae52014-02-10 17:46:57 -08002947 ElfW(Addr) sym_addr = 0;
Dmitriy Ivanov851135b2014-08-29 12:02:36 -07002948 const char* sym_name = nullptr;
Dmitriy Ivanovbcc04d02015-01-13 12:12:38 -08002949 ElfW(Addr) addend = get_addend(rel, reloc);
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07002950
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07002951 DEBUG("Processing \"%s\" relocation at index %zd", get_realpath(), idx);
Dmitriy Ivanovcefef7d2015-01-08 23:30:15 -08002952 if (type == R_GENERIC_NONE) {
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07002953 continue;
2954 }
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07002955
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07002956 const ElfW(Sym)* s = nullptr;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07002957 soinfo* lsi = nullptr;
2958
Ryan Prichardfb8730d2019-01-15 00:11:37 -08002959 if (sym == 0) {
Ryan Prichard3b463cf2019-01-22 22:49:22 -08002960 // By convention in ld.bfd and lld, an omitted symbol on a TLS relocation
2961 // is a reference to the current module.
2962 if (is_tls_reloc(type)) {
2963 lsi = this;
2964 }
Ryan Prichardfb8730d2019-01-15 00:11:37 -08002965 } else if (ELF_ST_BIND(symtab_[sym].st_info) == STB_LOCAL && is_tls_reloc(type)) {
2966 // In certain situations, the Gold linker accesses a TLS symbol using a
2967 // relocation to an STB_LOCAL symbol in .dynsym of either STT_SECTION or
2968 // STT_TLS type. Bionic doesn't support these relocations, so issue an
2969 // error. References:
2970 // - https://groups.google.com/d/topic/generic-abi/dJ4_Y78aQ2M/discussion
2971 // - https://sourceware.org/bugzilla/show_bug.cgi?id=17699
2972 s = &symtab_[sym];
2973 sym_name = get_string(s->st_name);
2974 DL_ERR("unexpected TLS reference to local symbol \"%s\": "
2975 "sym type %d, rel type %u (idx %zu of \"%s\")",
2976 sym_name, ELF_ST_TYPE(s->st_info), type, idx, get_realpath());
2977 return false;
2978 } else {
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08002979 sym_name = get_string(symtab_[sym].st_name);
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07002980
Vic Yang521ad072019-07-25 11:05:33 -07002981 if (sym == symbol_lookup_cache.sym) {
2982 s = symbol_lookup_cache.s;
2983 lsi = symbol_lookup_cache.lsi;
2984 count_relocation(kRelocSymbolCached);
2985 } else {
2986 const version_info* vi = nullptr;
Dmitriy Ivanov31b408d2015-04-30 16:11:48 -07002987
Vic Yang521ad072019-07-25 11:05:33 -07002988 if (!lookup_version_info(version_tracker, sym, sym_name, &vi)) {
2989 return false;
2990 }
2991
2992 if (!soinfo_do_lookup(this, sym_name, vi, &lsi, global_group, local_group, &s)) {
2993 return false;
2994 }
2995
2996 symbol_lookup_cache.sym = sym;
2997 symbol_lookup_cache.s = s;
2998 symbol_lookup_cache.lsi = lsi;
Dmitriy Ivanov31b408d2015-04-30 16:11:48 -07002999 }
3000
Dmitriy Ivanov851135b2014-08-29 12:02:36 -07003001 if (s == nullptr) {
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07003002 // We only allow an undefined symbol if this is a weak reference...
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003003 s = &symtab_[sym];
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07003004 if (ELF_ST_BIND(s->st_info) != STB_WEAK) {
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07003005 DL_ERR("cannot locate symbol \"%s\" referenced by \"%s\"...", sym_name, get_realpath());
Dmitriy Ivanov114ff692015-01-14 11:36:38 -08003006 return false;
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07003007 }
3008
3009 /* IHI0044C AAELF 4.5.1.1:
3010
3011 Libraries are not searched to resolve weak references.
3012 It is not an error for a weak reference to remain unsatisfied.
3013
3014 During linking, the value of an undefined weak reference is:
3015 - Zero if the relocation type is absolute
3016 - The address of the place if the relocation is pc-relative
3017 - The address of nominal base address if the relocation
3018 type is base-relative.
3019 */
3020
3021 switch (type) {
Dmitriy Ivanov1b694692015-01-13 12:17:31 -08003022 case R_GENERIC_JUMP_SLOT:
3023 case R_GENERIC_GLOB_DAT:
3024 case R_GENERIC_RELATIVE:
3025 case R_GENERIC_IRELATIVE:
Ryan Prichardfb8730d2019-01-15 00:11:37 -08003026 case R_GENERIC_TLS_DTPMOD:
3027 case R_GENERIC_TLS_DTPREL:
3028 case R_GENERIC_TLS_TPREL:
3029 case R_GENERIC_TLSDESC:
Marcus Oaklande365f9d2013-10-10 15:19:31 +01003030#if defined(__aarch64__)
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003031 case R_AARCH64_ABS64:
3032 case R_AARCH64_ABS32:
3033 case R_AARCH64_ABS16:
Dmitriy Ivanov1b694692015-01-13 12:17:31 -08003034#elif defined(__x86_64__)
3035 case R_X86_64_32:
3036 case R_X86_64_64:
Dmitriy Ivanovbcc04d02015-01-13 12:12:38 -08003037#elif defined(__arm__)
3038 case R_ARM_ABS32:
3039#elif defined(__i386__)
3040 case R_386_32:
Dmitriy Ivanov1b694692015-01-13 12:17:31 -08003041#endif
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003042 /*
3043 * The sym_addr was initialized to be zero above, or the relocation
3044 * code below does not care about value of sym_addr.
3045 * No need to do anything.
3046 */
3047 break;
Dmitriy Ivanov1b694692015-01-13 12:17:31 -08003048#if defined(__x86_64__)
Dimitry Ivanovd338aac2015-01-13 22:31:54 +00003049 case R_X86_64_PC32:
3050 sym_addr = reloc;
3051 break;
Dmitriy Ivanovbcc04d02015-01-13 12:12:38 -08003052#elif defined(__i386__)
3053 case R_386_PC32:
3054 sym_addr = reloc;
3055 break;
3056#endif
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003057 default:
Dmitriy Ivanovbcc04d02015-01-13 12:12:38 -08003058 DL_ERR("unknown weak reloc type %d @ %p (%zu)", type, rel, idx);
Dmitriy Ivanov114ff692015-01-14 11:36:38 -08003059 return false;
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07003060 }
Dmitriy Ivanovec83a612015-07-26 07:37:09 -07003061 } else { // We got a definition.
3062#if !defined(__LP64__)
3063 // When relocating dso with text_relocation .text segment is
3064 // not executable. We need to restore elf flags before resolving
3065 // STT_GNU_IFUNC symbol.
3066 bool protect_segments = has_text_relocations &&
3067 lsi == this &&
3068 ELF_ST_TYPE(s->st_info) == STT_GNU_IFUNC;
3069 if (protect_segments) {
3070 if (phdr_table_protect_segments(phdr, phnum, load_bias) < 0) {
3071 DL_ERR("can't protect segments for \"%s\": %s",
3072 get_realpath(), strerror(errno));
3073 return false;
3074 }
3075 }
3076#endif
Ryan Prichardfb8730d2019-01-15 00:11:37 -08003077 if (is_tls_reloc(type)) {
3078 if (ELF_ST_TYPE(s->st_info) != STT_TLS) {
3079 DL_ERR("reference to non-TLS symbol \"%s\" from TLS relocation in \"%s\"",
3080 sym_name, get_realpath());
3081 return false;
3082 }
Ryan Prichard3b463cf2019-01-22 22:49:22 -08003083 if (lsi->get_tls() == nullptr) {
3084 DL_ERR("TLS relocation refers to symbol \"%s\" in solib \"%s\" with no TLS segment",
3085 sym_name, lsi->get_realpath());
3086 return false;
3087 }
Ryan Prichardfb8730d2019-01-15 00:11:37 -08003088 sym_addr = s->st_value;
3089 } else {
3090 if (ELF_ST_TYPE(s->st_info) == STT_TLS) {
3091 DL_ERR("reference to TLS symbol \"%s\" from non-TLS relocation in \"%s\"",
3092 sym_name, get_realpath());
3093 return false;
3094 }
3095 sym_addr = lsi->resolve_symbol_address(s);
Elliott Hughes9724e932018-03-23 18:46:07 -07003096 }
Dmitriy Ivanovec83a612015-07-26 07:37:09 -07003097#if !defined(__LP64__)
3098 if (protect_segments) {
3099 if (phdr_table_unprotect_segments(phdr, phnum, load_bias) < 0) {
3100 DL_ERR("can't unprotect loadable segments for \"%s\": %s",
3101 get_realpath(), strerror(errno));
3102 return false;
3103 }
3104 }
3105#endif
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07003106 }
3107 count_relocation(kRelocSymbol);
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07003108 }
3109
3110 switch (type) {
Dmitriy Ivanovcefef7d2015-01-08 23:30:15 -08003111 case R_GENERIC_JUMP_SLOT:
Marcus Oaklande365f9d2013-10-10 15:19:31 +01003112 count_relocation(kRelocAbsolute);
Dmitriy Ivanovbcc04d02015-01-13 12:12:38 -08003113 MARK(rel->r_offset);
3114 TRACE_TYPE(RELO, "RELO JMP_SLOT %16p <- %16p %s\n",
3115 reinterpret_cast<void*>(reloc),
3116 reinterpret_cast<void*>(sym_addr + addend), sym_name);
3117
3118 *reinterpret_cast<ElfW(Addr)*>(reloc) = (sym_addr + addend);
Marcus Oaklande365f9d2013-10-10 15:19:31 +01003119 break;
Dmitriy Ivanovcefef7d2015-01-08 23:30:15 -08003120 case R_GENERIC_GLOB_DAT:
Marcus Oaklande365f9d2013-10-10 15:19:31 +01003121 count_relocation(kRelocAbsolute);
Dmitriy Ivanovbcc04d02015-01-13 12:12:38 -08003122 MARK(rel->r_offset);
3123 TRACE_TYPE(RELO, "RELO GLOB_DAT %16p <- %16p %s\n",
3124 reinterpret_cast<void*>(reloc),
3125 reinterpret_cast<void*>(sym_addr + addend), sym_name);
3126 *reinterpret_cast<ElfW(Addr)*>(reloc) = (sym_addr + addend);
Marcus Oaklande365f9d2013-10-10 15:19:31 +01003127 break;
Dmitriy Ivanovcefef7d2015-01-08 23:30:15 -08003128 case R_GENERIC_RELATIVE:
3129 count_relocation(kRelocRelative);
Dmitriy Ivanovbcc04d02015-01-13 12:12:38 -08003130 MARK(rel->r_offset);
3131 TRACE_TYPE(RELO, "RELO RELATIVE %16p <- %16p\n",
3132 reinterpret_cast<void*>(reloc),
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08003133 reinterpret_cast<void*>(load_bias + addend));
3134 *reinterpret_cast<ElfW(Addr)*>(reloc) = (load_bias + addend);
Dmitriy Ivanovcefef7d2015-01-08 23:30:15 -08003135 break;
Dmitriy Ivanovcefef7d2015-01-08 23:30:15 -08003136 case R_GENERIC_IRELATIVE:
3137 count_relocation(kRelocRelative);
Dmitriy Ivanovbcc04d02015-01-13 12:12:38 -08003138 MARK(rel->r_offset);
3139 TRACE_TYPE(RELO, "RELO IRELATIVE %16p <- %16p\n",
3140 reinterpret_cast<void*>(reloc),
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08003141 reinterpret_cast<void*>(load_bias + addend));
Dmitriy Ivanovec83a612015-07-26 07:37:09 -07003142 {
3143#if !defined(__LP64__)
3144 // When relocating dso with text_relocation .text segment is
3145 // not executable. We need to restore elf flags for this
3146 // particular call.
3147 if (has_text_relocations) {
3148 if (phdr_table_protect_segments(phdr, phnum, load_bias) < 0) {
3149 DL_ERR("can't protect segments for \"%s\": %s",
3150 get_realpath(), strerror(errno));
3151 return false;
3152 }
3153 }
3154#endif
3155 ElfW(Addr) ifunc_addr = call_ifunc_resolver(load_bias + addend);
3156#if !defined(__LP64__)
3157 // Unprotect it afterwards...
3158 if (has_text_relocations) {
3159 if (phdr_table_unprotect_segments(phdr, phnum, load_bias) < 0) {
3160 DL_ERR("can't unprotect loadable segments for \"%s\": %s",
3161 get_realpath(), strerror(errno));
3162 return false;
3163 }
3164 }
3165#endif
3166 *reinterpret_cast<ElfW(Addr)*>(reloc) = ifunc_addr;
3167 }
Dmitriy Ivanovcefef7d2015-01-08 23:30:15 -08003168 break;
Ryan Prichardfb8730d2019-01-15 00:11:37 -08003169 case R_GENERIC_TLS_TPREL:
3170 count_relocation(kRelocRelative);
3171 MARK(rel->r_offset);
3172 {
3173 ElfW(Addr) tpoff = 0;
Ryan Prichardfb8730d2019-01-15 00:11:37 -08003174 if (lsi == nullptr) {
3175 // Unresolved weak relocation. Leave tpoff at 0 to resolve
3176 // &weak_tls_symbol to __get_tls().
Ryan Prichard3b463cf2019-01-22 22:49:22 -08003177 } else {
3178 CHECK(lsi->get_tls() != nullptr); // We rejected a missing TLS segment above.
3179 const TlsModule& mod = get_tls_module(lsi->get_tls()->module_id);
Ryan Prichardbf427f42019-01-17 16:37:11 -08003180 if (mod.static_offset != SIZE_MAX) {
3181 tpoff += mod.static_offset - tls_tp_base;
Ryan Prichardfb8730d2019-01-15 00:11:37 -08003182 } else {
3183 DL_ERR("TLS symbol \"%s\" in dlopened \"%s\" referenced from \"%s\" using IE access model",
3184 sym_name, lsi->get_realpath(), get_realpath());
3185 return false;
3186 }
Ryan Prichardfb8730d2019-01-15 00:11:37 -08003187 }
3188 tpoff += sym_addr + addend;
3189 TRACE_TYPE(RELO, "RELO TLS_TPREL %16p <- %16p %s\n",
3190 reinterpret_cast<void*>(reloc),
3191 reinterpret_cast<void*>(tpoff), sym_name);
3192 *reinterpret_cast<ElfW(Addr)*>(reloc) = tpoff;
3193 }
3194 break;
Ryan Prichard3b463cf2019-01-22 22:49:22 -08003195 case R_GENERIC_TLS_DTPMOD:
3196 count_relocation(kRelocRelative);
3197 MARK(rel->r_offset);
3198 {
3199 size_t module_id = 0;
3200 if (lsi == nullptr) {
3201 // Unresolved weak relocation. Evaluate the module ID to 0.
3202 } else {
3203 CHECK(lsi->get_tls() != nullptr); // We rejected a missing TLS segment above.
3204 module_id = lsi->get_tls()->module_id;
3205 }
3206 TRACE_TYPE(RELO, "RELO TLS_DTPMOD %16p <- %zu %s\n",
3207 reinterpret_cast<void*>(reloc), module_id, sym_name);
3208 *reinterpret_cast<ElfW(Addr)*>(reloc) = module_id;
3209 }
3210 break;
3211 case R_GENERIC_TLS_DTPREL:
3212 count_relocation(kRelocRelative);
3213 MARK(rel->r_offset);
3214 TRACE_TYPE(RELO, "RELO TLS_DTPREL %16p <- %16p %s\n",
3215 reinterpret_cast<void*>(reloc),
3216 reinterpret_cast<void*>(sym_addr + addend), sym_name);
3217 *reinterpret_cast<ElfW(Addr)*>(reloc) = sym_addr + addend;
3218 break;
Ryan Prichard3b463cf2019-01-22 22:49:22 -08003219
Dmitriy Ivanovcefef7d2015-01-08 23:30:15 -08003220#if defined(__aarch64__)
Ryan Prichardffaae702019-01-23 17:47:10 -08003221 // Bionic currently only implements TLSDESC for arm64. This implementation should work with
3222 // other architectures, as long as the resolver functions are implemented.
3223 case R_GENERIC_TLSDESC:
3224 count_relocation(kRelocRelative);
3225 MARK(rel->r_offset);
3226 {
3227 TlsDescriptor* desc = reinterpret_cast<TlsDescriptor*>(reloc);
3228 if (lsi == nullptr) {
3229 // Unresolved weak relocation.
3230 desc->func = tlsdesc_resolver_unresolved_weak;
3231 desc->arg = addend;
3232 TRACE_TYPE(RELO, "RELO TLSDESC %16p <- unresolved weak 0x%zx %s\n",
3233 reinterpret_cast<void*>(reloc), static_cast<size_t>(addend), sym_name);
3234 } else {
3235 CHECK(lsi->get_tls() != nullptr); // We rejected a missing TLS segment above.
3236 size_t module_id = lsi->get_tls()->module_id;
3237 const TlsModule& mod = get_tls_module(module_id);
3238 if (mod.static_offset != SIZE_MAX) {
3239 desc->func = tlsdesc_resolver_static;
3240 desc->arg = mod.static_offset - tls_tp_base + sym_addr + addend;
3241 TRACE_TYPE(RELO, "RELO TLSDESC %16p <- static (0x%zx - 0x%zx + 0x%zx + 0x%zx) %s\n",
3242 reinterpret_cast<void*>(reloc), mod.static_offset, tls_tp_base,
3243 static_cast<size_t>(sym_addr), static_cast<size_t>(addend), sym_name);
3244 } else {
3245 tlsdesc_args_.push_back({
3246 .generation = mod.first_generation,
3247 .index.module_id = module_id,
3248 .index.offset = sym_addr + addend,
3249 });
3250 // Defer the TLSDESC relocation until the address of the TlsDynamicResolverArg object
3251 // is finalized.
3252 deferred_tlsdesc_relocs.push_back({ desc, tlsdesc_args_.size() - 1 });
3253 const TlsDynamicResolverArg& desc_arg = tlsdesc_args_.back();
3254 TRACE_TYPE(RELO, "RELO TLSDESC %16p <- dynamic (gen %zu, mod %zu, off %zu) %s",
3255 reinterpret_cast<void*>(reloc), desc_arg.generation,
3256 desc_arg.index.module_id, desc_arg.index.offset, sym_name);
3257 }
3258 }
3259 }
3260 break;
Ryan Prichardb0e2dd02019-03-11 17:06:02 -07003261#endif // defined(__aarch64__)
Ryan Prichardffaae702019-01-23 17:47:10 -08003262
3263#if defined(__aarch64__)
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003264 case R_AARCH64_ABS64:
Marcus Oaklande365f9d2013-10-10 15:19:31 +01003265 count_relocation(kRelocAbsolute);
Dmitriy Ivanovbcc04d02015-01-13 12:12:38 -08003266 MARK(rel->r_offset);
Elliott Hughes0266ae52014-02-10 17:46:57 -08003267 TRACE_TYPE(RELO, "RELO ABS64 %16llx <- %16llx %s\n",
Dmitriy Ivanov77f91c62015-10-15 13:26:03 -07003268 reloc, sym_addr + addend, sym_name);
3269 *reinterpret_cast<ElfW(Addr)*>(reloc) = sym_addr + addend;
Marcus Oaklande365f9d2013-10-10 15:19:31 +01003270 break;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003271 case R_AARCH64_ABS32:
Marcus Oaklande365f9d2013-10-10 15:19:31 +01003272 count_relocation(kRelocAbsolute);
Dmitriy Ivanovbcc04d02015-01-13 12:12:38 -08003273 MARK(rel->r_offset);
Elliott Hughes0266ae52014-02-10 17:46:57 -08003274 TRACE_TYPE(RELO, "RELO ABS32 %16llx <- %16llx %s\n",
Dmitriy Ivanov77f91c62015-10-15 13:26:03 -07003275 reloc, sym_addr + addend, sym_name);
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07003276 {
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07003277 const ElfW(Addr) min_value = static_cast<ElfW(Addr)>(INT32_MIN);
3278 const ElfW(Addr) max_value = static_cast<ElfW(Addr)>(UINT32_MAX);
Dmitriy Ivanov77f91c62015-10-15 13:26:03 -07003279 if ((min_value <= (sym_addr + addend)) &&
3280 ((sym_addr + addend) <= max_value)) {
3281 *reinterpret_cast<ElfW(Addr)*>(reloc) = sym_addr + addend;
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07003282 } else {
3283 DL_ERR("0x%016llx out of range 0x%016llx to 0x%016llx",
Dmitriy Ivanov77f91c62015-10-15 13:26:03 -07003284 sym_addr + addend, min_value, max_value);
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07003285 return false;
3286 }
Marcus Oaklande365f9d2013-10-10 15:19:31 +01003287 }
3288 break;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003289 case R_AARCH64_ABS16:
Marcus Oaklande365f9d2013-10-10 15:19:31 +01003290 count_relocation(kRelocAbsolute);
Dmitriy Ivanovbcc04d02015-01-13 12:12:38 -08003291 MARK(rel->r_offset);
Elliott Hughes0266ae52014-02-10 17:46:57 -08003292 TRACE_TYPE(RELO, "RELO ABS16 %16llx <- %16llx %s\n",
Dmitriy Ivanov77f91c62015-10-15 13:26:03 -07003293 reloc, sym_addr + addend, sym_name);
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07003294 {
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07003295 const ElfW(Addr) min_value = static_cast<ElfW(Addr)>(INT16_MIN);
3296 const ElfW(Addr) max_value = static_cast<ElfW(Addr)>(UINT16_MAX);
Dmitriy Ivanov77f91c62015-10-15 13:26:03 -07003297 if ((min_value <= (sym_addr + addend)) &&
3298 ((sym_addr + addend) <= max_value)) {
3299 *reinterpret_cast<ElfW(Addr)*>(reloc) = (sym_addr + addend);
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07003300 } else {
3301 DL_ERR("0x%016llx out of range 0x%016llx to 0x%016llx",
Dmitriy Ivanov77f91c62015-10-15 13:26:03 -07003302 sym_addr + addend, min_value, max_value);
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07003303 return false;
3304 }
Marcus Oaklande365f9d2013-10-10 15:19:31 +01003305 }
3306 break;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003307 case R_AARCH64_PREL64:
Marcus Oaklande365f9d2013-10-10 15:19:31 +01003308 count_relocation(kRelocRelative);
Dmitriy Ivanovbcc04d02015-01-13 12:12:38 -08003309 MARK(rel->r_offset);
Elliott Hughes0266ae52014-02-10 17:46:57 -08003310 TRACE_TYPE(RELO, "RELO REL64 %16llx <- %16llx - %16llx %s\n",
Dmitriy Ivanov77f91c62015-10-15 13:26:03 -07003311 reloc, sym_addr + addend, rel->r_offset, sym_name);
3312 *reinterpret_cast<ElfW(Addr)*>(reloc) = sym_addr + addend - rel->r_offset;
Marcus Oaklande365f9d2013-10-10 15:19:31 +01003313 break;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003314 case R_AARCH64_PREL32:
Marcus Oaklande365f9d2013-10-10 15:19:31 +01003315 count_relocation(kRelocRelative);
Dmitriy Ivanovbcc04d02015-01-13 12:12:38 -08003316 MARK(rel->r_offset);
Elliott Hughes0266ae52014-02-10 17:46:57 -08003317 TRACE_TYPE(RELO, "RELO REL32 %16llx <- %16llx - %16llx %s\n",
Dmitriy Ivanov77f91c62015-10-15 13:26:03 -07003318 reloc, sym_addr + addend, rel->r_offset, sym_name);
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07003319 {
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07003320 const ElfW(Addr) min_value = static_cast<ElfW(Addr)>(INT32_MIN);
3321 const ElfW(Addr) max_value = static_cast<ElfW(Addr)>(UINT32_MAX);
Dmitriy Ivanov77f91c62015-10-15 13:26:03 -07003322 if ((min_value <= (sym_addr + addend - rel->r_offset)) &&
3323 ((sym_addr + addend - rel->r_offset) <= max_value)) {
3324 *reinterpret_cast<ElfW(Addr)*>(reloc) = sym_addr + addend - rel->r_offset;
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07003325 } else {
3326 DL_ERR("0x%016llx out of range 0x%016llx to 0x%016llx",
Dmitriy Ivanov77f91c62015-10-15 13:26:03 -07003327 sym_addr + addend - rel->r_offset, min_value, max_value);
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07003328 return false;
3329 }
Marcus Oaklande365f9d2013-10-10 15:19:31 +01003330 }
3331 break;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003332 case R_AARCH64_PREL16:
Marcus Oaklande365f9d2013-10-10 15:19:31 +01003333 count_relocation(kRelocRelative);
Dmitriy Ivanovbcc04d02015-01-13 12:12:38 -08003334 MARK(rel->r_offset);
Elliott Hughes0266ae52014-02-10 17:46:57 -08003335 TRACE_TYPE(RELO, "RELO REL16 %16llx <- %16llx - %16llx %s\n",
Dmitriy Ivanov77f91c62015-10-15 13:26:03 -07003336 reloc, sym_addr + addend, rel->r_offset, sym_name);
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07003337 {
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07003338 const ElfW(Addr) min_value = static_cast<ElfW(Addr)>(INT16_MIN);
3339 const ElfW(Addr) max_value = static_cast<ElfW(Addr)>(UINT16_MAX);
Dmitriy Ivanov77f91c62015-10-15 13:26:03 -07003340 if ((min_value <= (sym_addr + addend - rel->r_offset)) &&
3341 ((sym_addr + addend - rel->r_offset) <= max_value)) {
3342 *reinterpret_cast<ElfW(Addr)*>(reloc) = sym_addr + addend - rel->r_offset;
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07003343 } else {
3344 DL_ERR("0x%016llx out of range 0x%016llx to 0x%016llx",
Dmitriy Ivanov77f91c62015-10-15 13:26:03 -07003345 sym_addr + addend - rel->r_offset, min_value, max_value);
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07003346 return false;
3347 }
Marcus Oaklande365f9d2013-10-10 15:19:31 +01003348 }
3349 break;
3350
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003351 case R_AARCH64_COPY:
Nick Kralevich76e289c2014-07-03 12:04:31 -07003352 /*
3353 * ET_EXEC is not supported so this should not happen.
3354 *
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003355 * http://infocenter.arm.com/help/topic/com.arm.doc.ihi0056b/IHI0056B_aaelf64.pdf
Nick Kralevich76e289c2014-07-03 12:04:31 -07003356 *
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003357 * Section 4.6.11 "Dynamic relocations"
Nick Kralevich76e289c2014-07-03 12:04:31 -07003358 * R_AARCH64_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_AARCH64_COPY relocations are not supported", get_realpath());
Dmitriy Ivanov114ff692015-01-14 11:36:38 -08003362 return false;
Marcus Oaklande365f9d2013-10-10 15:19:31 +01003363#elif defined(__x86_64__)
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003364 case R_X86_64_32:
3365 count_relocation(kRelocRelative);
Dmitriy Ivanovbcc04d02015-01-13 12:12:38 -08003366 MARK(rel->r_offset);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003367 TRACE_TYPE(RELO, "RELO R_X86_64_32 %08zx <- +%08zx %s", static_cast<size_t>(reloc),
3368 static_cast<size_t>(sym_addr), sym_name);
Junichi Uekawaff35b1e2015-11-18 10:18:59 +09003369 *reinterpret_cast<Elf32_Addr*>(reloc) = sym_addr + addend;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003370 break;
3371 case R_X86_64_64:
3372 count_relocation(kRelocRelative);
Dmitriy Ivanovbcc04d02015-01-13 12:12:38 -08003373 MARK(rel->r_offset);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003374 TRACE_TYPE(RELO, "RELO R_X86_64_64 %08zx <- +%08zx %s", static_cast<size_t>(reloc),
3375 static_cast<size_t>(sym_addr), sym_name);
Junichi Uekawaff35b1e2015-11-18 10:18:59 +09003376 *reinterpret_cast<Elf64_Addr*>(reloc) = sym_addr + addend;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003377 break;
3378 case R_X86_64_PC32:
3379 count_relocation(kRelocRelative);
Dmitriy Ivanovbcc04d02015-01-13 12:12:38 -08003380 MARK(rel->r_offset);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003381 TRACE_TYPE(RELO, "RELO R_X86_64_PC32 %08zx <- +%08zx (%08zx - %08zx) %s",
3382 static_cast<size_t>(reloc), static_cast<size_t>(sym_addr - reloc),
3383 static_cast<size_t>(sym_addr), static_cast<size_t>(reloc), sym_name);
Junichi Uekawaff35b1e2015-11-18 10:18:59 +09003384 *reinterpret_cast<Elf32_Addr*>(reloc) = sym_addr + addend - reloc;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003385 break;
Dmitriy Ivanovbcc04d02015-01-13 12:12:38 -08003386#elif defined(__arm__)
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003387 case R_ARM_ABS32:
3388 count_relocation(kRelocAbsolute);
3389 MARK(rel->r_offset);
3390 TRACE_TYPE(RELO, "RELO ABS %08x <- %08x %s", reloc, sym_addr, sym_name);
3391 *reinterpret_cast<ElfW(Addr)*>(reloc) += sym_addr;
3392 break;
3393 case R_ARM_REL32:
3394 count_relocation(kRelocRelative);
3395 MARK(rel->r_offset);
3396 TRACE_TYPE(RELO, "RELO REL32 %08x <- %08x - %08x %s",
3397 reloc, sym_addr, rel->r_offset, sym_name);
3398 *reinterpret_cast<ElfW(Addr)*>(reloc) += sym_addr - rel->r_offset;
3399 break;
3400 case R_ARM_COPY:
3401 /*
3402 * ET_EXEC is not supported so this should not happen.
3403 *
3404 * http://infocenter.arm.com/help/topic/com.arm.doc.ihi0044d/IHI0044D_aaelf.pdf
3405 *
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003406 * Section 4.6.1.10 "Dynamic relocations"
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003407 * R_ARM_COPY may only appear in executable objects where e_type is
3408 * set to ET_EXEC.
3409 */
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07003410 DL_ERR("%s R_ARM_COPY relocations are not supported", get_realpath());
Dmitriy Ivanov114ff692015-01-14 11:36:38 -08003411 return false;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003412#elif defined(__i386__)
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003413 case R_386_32:
3414 count_relocation(kRelocRelative);
3415 MARK(rel->r_offset);
3416 TRACE_TYPE(RELO, "RELO R_386_32 %08x <- +%08x %s", reloc, sym_addr, sym_name);
3417 *reinterpret_cast<ElfW(Addr)*>(reloc) += sym_addr;
3418 break;
3419 case R_386_PC32:
3420 count_relocation(kRelocRelative);
3421 MARK(rel->r_offset);
3422 TRACE_TYPE(RELO, "RELO R_386_PC32 %08x <- +%08x (%08x - %08x) %s",
3423 reloc, (sym_addr - reloc), sym_addr, reloc, sym_name);
3424 *reinterpret_cast<ElfW(Addr)*>(reloc) += (sym_addr - reloc);
3425 break;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003426#endif
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003427 default:
3428 DL_ERR("unknown reloc type %d @ %p (%zu)", type, rel, idx);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003429 return false;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003430 }
3431 }
Ryan Prichardffaae702019-01-23 17:47:10 -08003432
Ryan Prichardb0e2dd02019-03-11 17:06:02 -07003433#if defined(__aarch64__)
3434 // Bionic currently only implements TLSDESC for arm64.
Ryan Prichardffaae702019-01-23 17:47:10 -08003435 for (const std::pair<TlsDescriptor*, size_t>& pair : deferred_tlsdesc_relocs) {
3436 TlsDescriptor* desc = pair.first;
3437 desc->func = tlsdesc_resolver_dynamic;
3438 desc->arg = reinterpret_cast<size_t>(&tlsdesc_args_[pair.second]);
3439 }
Ryan Prichardb0e2dd02019-03-11 17:06:02 -07003440#endif
Ryan Prichardffaae702019-01-23 17:47:10 -08003441
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003442 return true;
Raghu Gandhamd7daacb2012-07-31 12:07:22 -07003443}
Dmitriy Ivanov114ff692015-01-14 11:36:38 -08003444#endif // !defined(__mips__)
Raghu Gandhamd7daacb2012-07-31 12:07:22 -07003445
Dimitry Ivanov48ec2882016-08-04 11:50:36 -07003446// An empty list of soinfos
Dimitry Ivanovb943f302016-08-03 16:00:10 -07003447static soinfo_list_t g_empty_list;
Dmitriy Ivanovd59e5002014-05-09 09:10:14 -07003448
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003449bool soinfo::prelink_image() {
Ningsheng Jiane93be992014-09-16 15:22:10 +08003450 /* Extract dynamic section */
3451 ElfW(Word) dynamic_flags = 0;
3452 phdr_table_get_dynamic_section(phdr, phnum, load_bias, &dynamic, &dynamic_flags);
Dmitriy Ivanov498eb182014-09-05 14:57:59 -07003453
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003454 /* We can't log anything until the linker is relocated */
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08003455 bool relocating_linker = (flags_ & FLAG_LINKER) != 0;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003456 if (!relocating_linker) {
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07003457 INFO("[ Linking \"%s\" ]", get_realpath());
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08003458 DEBUG("si->base = %p si->flags = 0x%08x", reinterpret_cast<void*>(base), flags_);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003459 }
3460
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003461 if (dynamic == nullptr) {
David 'Digit' Turnerb52e4382012-06-19 01:24:17 +02003462 if (!relocating_linker) {
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07003463 DL_ERR("missing PT_DYNAMIC in \"%s\"", get_realpath());
David 'Digit' Turnerb52e4382012-06-19 01:24:17 +02003464 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003465 return false;
3466 } else {
3467 if (!relocating_linker) {
3468 DEBUG("dynamic = %p", dynamic);
David 'Digit' Turner63f99f42012-06-19 00:08:39 +02003469 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003470 }
David 'Digit' Turner63f99f42012-06-19 00:08:39 +02003471
Elliott Hughes4eeb1f12013-10-25 17:38:02 -07003472#if defined(__arm__)
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003473 (void) phdr_table_get_arm_exidx(phdr, phnum, load_bias,
3474 &ARM_exidx, &ARM_exidx_count);
David 'Digit' Turner63f99f42012-06-19 00:08:39 +02003475#endif
3476
Ryan Pricharde5e69e02019-01-01 18:53:48 -08003477 TlsSegment tls_segment;
Ryan Prichard19883502019-01-16 23:13:38 -08003478 if (__bionic_get_tls_segment(phdr, phnum, load_bias, &tls_segment)) {
3479 if (!__bionic_check_tls_alignment(&tls_segment.alignment)) {
3480 if (!relocating_linker) {
3481 DL_ERR("TLS segment alignment in \"%s\" is not a power of 2: %zu",
3482 get_realpath(), tls_segment.alignment);
3483 }
3484 return false;
3485 }
Ryan Pricharde5e69e02019-01-01 18:53:48 -08003486 tls_ = std::make_unique<soinfo_tls>();
3487 tls_->segment = tls_segment;
3488 }
3489
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003490 // Extract useful information from dynamic section.
Dmitriy Ivanov618f1a32015-03-17 20:06:36 -07003491 // Note that: "Except for the DT_NULL element at the end of the array,
3492 // and the relative order of DT_NEEDED elements, entries may appear in any order."
3493 //
3494 // source: http://www.sco.com/developers/gabi/1998-04-29/ch5.dynamic.html
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003495 uint32_t needed_count = 0;
3496 for (ElfW(Dyn)* d = dynamic; d->d_tag != DT_NULL; ++d) {
3497 DEBUG("d = %p, d[0](tag) = %p d[1](val) = %p",
3498 d, reinterpret_cast<void*>(d->d_tag), reinterpret_cast<void*>(d->d_un.d_val));
3499 switch (d->d_tag) {
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07003500 case DT_SONAME:
Dmitriy Ivanov618f1a32015-03-17 20:06:36 -07003501 // this is parsed after we have strtab initialized (see below).
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07003502 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003503
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003504 case DT_HASH:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003505 nbucket_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[0];
3506 nchain_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[1];
3507 bucket_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr + 8);
3508 chain_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr + 8 + nbucket_ * 4);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003509 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003510
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -08003511 case DT_GNU_HASH:
Dmitriy Ivanov3597b802015-03-09 12:02:02 -07003512 gnu_nbucket_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[0];
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -08003513 // skip symndx
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003514 gnu_maskwords_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[2];
3515 gnu_shift2_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[3];
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -08003516
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003517 gnu_bloom_filter_ = reinterpret_cast<ElfW(Addr)*>(load_bias + d->d_un.d_ptr + 16);
Dmitriy Ivanov3597b802015-03-09 12:02:02 -07003518 gnu_bucket_ = reinterpret_cast<uint32_t*>(gnu_bloom_filter_ + gnu_maskwords_);
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -08003519 // amend chain for symndx = header[1]
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07003520 gnu_chain_ = gnu_bucket_ + gnu_nbucket_ -
3521 reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[1];
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -08003522
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003523 if (!powerof2(gnu_maskwords_)) {
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07003524 DL_ERR("invalid maskwords for gnu_hash = 0x%x, in \"%s\" expecting power to two",
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003525 gnu_maskwords_, get_realpath());
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -08003526 return false;
3527 }
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003528 --gnu_maskwords_;
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -08003529
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08003530 flags_ |= FLAG_GNU_HASH;
Dmitriy Ivanovec18ce02014-11-09 19:27:20 -08003531 break;
3532
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003533 case DT_STRTAB:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003534 strtab_ = reinterpret_cast<const char*>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003535 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003536
Dmitriy Ivanov6cdeb522014-09-29 19:14:45 -07003537 case DT_STRSZ:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003538 strtab_size_ = d->d_un.d_val;
Dmitriy Ivanov6cdeb522014-09-29 19:14:45 -07003539 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003540
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003541 case DT_SYMTAB:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003542 symtab_ = reinterpret_cast<ElfW(Sym)*>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003543 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003544
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07003545 case DT_SYMENT:
3546 if (d->d_un.d_val != sizeof(ElfW(Sym))) {
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003547 DL_ERR("invalid DT_SYMENT: %zd in \"%s\"",
3548 static_cast<size_t>(d->d_un.d_val), get_realpath());
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07003549 return false;
3550 }
3551 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003552
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003553 case DT_PLTREL:
Dmitriy Ivanov513e29e2014-10-06 11:30:43 -07003554#if defined(USE_RELA)
3555 if (d->d_un.d_val != DT_RELA) {
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003556 DL_ERR("unsupported DT_PLTREL in \"%s\"; expected DT_RELA", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003557 return false;
3558 }
Dmitriy Ivanov513e29e2014-10-06 11:30:43 -07003559#else
3560 if (d->d_un.d_val != DT_REL) {
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003561 DL_ERR("unsupported DT_PLTREL in \"%s\"; expected DT_REL", get_realpath());
Dmitriy Ivanov513e29e2014-10-06 11:30:43 -07003562 return false;
3563 }
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07003564#endif
Dmitriy Ivanov513e29e2014-10-06 11:30:43 -07003565 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003566
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003567 case DT_JMPREL:
Elliott Hughes4eeb1f12013-10-25 17:38:02 -07003568#if defined(USE_RELA)
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003569 plt_rela_ = reinterpret_cast<ElfW(Rela)*>(load_bias + d->d_un.d_ptr);
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07003570#else
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003571 plt_rel_ = reinterpret_cast<ElfW(Rel)*>(load_bias + d->d_un.d_ptr);
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07003572#endif
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003573 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003574
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003575 case DT_PLTRELSZ:
Elliott Hughes4eeb1f12013-10-25 17:38:02 -07003576#if defined(USE_RELA)
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003577 plt_rela_count_ = d->d_un.d_val / sizeof(ElfW(Rela));
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07003578#else
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003579 plt_rel_count_ = d->d_un.d_val / sizeof(ElfW(Rel));
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07003580#endif
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003581 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003582
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003583 case DT_PLTGOT:
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07003584#if defined(__mips__)
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003585 // Used by mips and mips64.
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003586 plt_got_ = reinterpret_cast<ElfW(Addr)**>(load_bias + d->d_un.d_ptr);
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07003587#endif
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07003588 // Ignore for other platforms... (because RTLD_LAZY is not supported)
3589 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003590
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003591 case DT_DEBUG:
3592 // Set the DT_DEBUG entry to the address of _r_debug for GDB
3593 // if the dynamic table is writable
Chris Dearman99186652014-02-06 20:36:51 -08003594// FIXME: not working currently for N64
3595// The flags for the LOAD and DYNAMIC program headers do not agree.
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07003596// The LOAD section containing the dynamic table has been mapped as
Chris Dearman99186652014-02-06 20:36:51 -08003597// read-only, but the DYNAMIC header claims it is writable.
3598#if !(defined(__mips__) && defined(__LP64__))
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003599 if ((dynamic_flags & PF_W) != 0) {
3600 d->d_un.d_val = reinterpret_cast<uintptr_t>(&_r_debug);
3601 }
Chris Dearman99186652014-02-06 20:36:51 -08003602#endif
Dmitriy Ivanovc6292ea2015-02-13 16:29:50 -08003603 break;
Elliott Hughes4eeb1f12013-10-25 17:38:02 -07003604#if defined(USE_RELA)
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003605 case DT_RELA:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003606 rela_ = reinterpret_cast<ElfW(Rela)*>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003607 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003608
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003609 case DT_RELASZ:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003610 rela_count_ = d->d_un.d_val / sizeof(ElfW(Rela));
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003611 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003612
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08003613 case DT_ANDROID_RELA:
3614 android_relocs_ = reinterpret_cast<uint8_t*>(load_bias + d->d_un.d_ptr);
3615 break;
3616
3617 case DT_ANDROID_RELASZ:
3618 android_relocs_size_ = d->d_un.d_val;
3619 break;
3620
3621 case DT_ANDROID_REL:
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003622 DL_ERR("unsupported DT_ANDROID_REL in \"%s\"", get_realpath());
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08003623 return false;
3624
3625 case DT_ANDROID_RELSZ:
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003626 DL_ERR("unsupported DT_ANDROID_RELSZ in \"%s\"", get_realpath());
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08003627 return false;
3628
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07003629 case DT_RELAENT:
3630 if (d->d_un.d_val != sizeof(ElfW(Rela))) {
Dmitriy Ivanovf240aa82014-09-16 23:34:20 -07003631 DL_ERR("invalid DT_RELAENT: %zd", static_cast<size_t>(d->d_un.d_val));
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07003632 return false;
3633 }
3634 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003635
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08003636 // Ignored (see DT_RELCOUNT comments for details).
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07003637 case DT_RELACOUNT:
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07003638 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003639
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003640 case DT_REL:
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003641 DL_ERR("unsupported DT_REL in \"%s\"", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003642 return false;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003643
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003644 case DT_RELSZ:
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003645 DL_ERR("unsupported DT_RELSZ in \"%s\"", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003646 return false;
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08003647
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07003648#else
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003649 case DT_REL:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003650 rel_ = reinterpret_cast<ElfW(Rel)*>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003651 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003652
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003653 case DT_RELSZ:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003654 rel_count_ = d->d_un.d_val / sizeof(ElfW(Rel));
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003655 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003656
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07003657 case DT_RELENT:
3658 if (d->d_un.d_val != sizeof(ElfW(Rel))) {
Dmitriy Ivanovf240aa82014-09-16 23:34:20 -07003659 DL_ERR("invalid DT_RELENT: %zd", static_cast<size_t>(d->d_un.d_val));
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07003660 return false;
3661 }
3662 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003663
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08003664 case DT_ANDROID_REL:
3665 android_relocs_ = reinterpret_cast<uint8_t*>(load_bias + d->d_un.d_ptr);
3666 break;
3667
3668 case DT_ANDROID_RELSZ:
3669 android_relocs_size_ = d->d_un.d_val;
3670 break;
3671
3672 case DT_ANDROID_RELA:
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003673 DL_ERR("unsupported DT_ANDROID_RELA in \"%s\"", get_realpath());
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08003674 return false;
3675
3676 case DT_ANDROID_RELASZ:
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003677 DL_ERR("unsupported DT_ANDROID_RELASZ in \"%s\"", get_realpath());
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08003678 return false;
3679
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003680 // "Indicates that all RELATIVE relocations have been concatenated together,
3681 // and specifies the RELATIVE relocation count."
3682 //
3683 // TODO: Spec also mentions that this can be used to optimize relocation process;
3684 // Not currently used by bionic linker - ignored.
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07003685 case DT_RELCOUNT:
Dmitriy Ivanov4a6e9a82014-09-16 15:51:25 -07003686 break;
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08003687
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003688 case DT_RELA:
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003689 DL_ERR("unsupported DT_RELA in \"%s\"", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003690 return false;
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08003691
3692 case DT_RELASZ:
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003693 DL_ERR("unsupported DT_RELASZ in \"%s\"", get_realpath());
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08003694 return false;
3695
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07003696#endif
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08003697 case DT_RELR:
3698 relr_ = reinterpret_cast<ElfW(Relr)*>(load_bias + d->d_un.d_ptr);
3699 break;
3700
3701 case DT_RELRSZ:
3702 relr_count_ = d->d_un.d_val / sizeof(ElfW(Relr));
3703 break;
3704
3705 case DT_RELRENT:
3706 if (d->d_un.d_val != sizeof(ElfW(Relr))) {
3707 DL_ERR("invalid DT_RELRENT: %zd", static_cast<size_t>(d->d_un.d_val));
3708 return false;
3709 }
3710 break;
3711
3712 // Ignored (see DT_RELCOUNT comments for details).
3713 case DT_RELRCOUNT:
3714 break;
3715
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003716 case DT_INIT:
Dimitry Ivanov55437462016-07-20 15:33:07 -07003717 init_func_ = reinterpret_cast<linker_ctor_function_t>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003718 DEBUG("%s constructors (DT_INIT) found at %p", get_realpath(), init_func_);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003719 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003720
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003721 case DT_FINI:
Dimitry Ivanov55437462016-07-20 15:33:07 -07003722 fini_func_ = reinterpret_cast<linker_dtor_function_t>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003723 DEBUG("%s destructors (DT_FINI) found at %p", get_realpath(), fini_func_);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003724 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003725
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003726 case DT_INIT_ARRAY:
Dimitry Ivanov55437462016-07-20 15:33:07 -07003727 init_array_ = reinterpret_cast<linker_ctor_function_t*>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003728 DEBUG("%s constructors (DT_INIT_ARRAY) found at %p", get_realpath(), init_array_);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003729 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003730
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003731 case DT_INIT_ARRAYSZ:
Dmitriy Ivanov1649e7e2015-01-22 16:04:25 -08003732 init_array_count_ = static_cast<uint32_t>(d->d_un.d_val) / sizeof(ElfW(Addr));
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003733 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003734
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003735 case DT_FINI_ARRAY:
Dimitry Ivanov55437462016-07-20 15:33:07 -07003736 fini_array_ = reinterpret_cast<linker_dtor_function_t*>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003737 DEBUG("%s destructors (DT_FINI_ARRAY) found at %p", get_realpath(), fini_array_);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003738 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003739
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003740 case DT_FINI_ARRAYSZ:
Dmitriy Ivanov1649e7e2015-01-22 16:04:25 -08003741 fini_array_count_ = static_cast<uint32_t>(d->d_un.d_val) / sizeof(ElfW(Addr));
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003742 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003743
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003744 case DT_PREINIT_ARRAY:
Dimitry Ivanov55437462016-07-20 15:33:07 -07003745 preinit_array_ = reinterpret_cast<linker_ctor_function_t*>(load_bias + d->d_un.d_ptr);
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003746 DEBUG("%s constructors (DT_PREINIT_ARRAY) found at %p", get_realpath(), preinit_array_);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003747 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003748
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003749 case DT_PREINIT_ARRAYSZ:
Dmitriy Ivanov1649e7e2015-01-22 16:04:25 -08003750 preinit_array_count_ = static_cast<uint32_t>(d->d_un.d_val) / sizeof(ElfW(Addr));
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003751 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003752
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003753 case DT_TEXTREL:
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003754#if defined(__LP64__)
Dimitry Ivanov816676e2016-10-19 11:00:28 -07003755 DL_ERR("\"%s\" has text relocations", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003756 return false;
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003757#else
3758 has_text_relocations = true;
3759 break;
3760#endif
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003761
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003762 case DT_SYMBOLIC:
Dmitriy Ivanov96bc37f2014-09-29 12:10:36 -07003763 has_DT_SYMBOLIC = true;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003764 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003765
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003766 case DT_NEEDED:
3767 ++needed_count;
3768 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003769
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003770 case DT_FLAGS:
3771 if (d->d_un.d_val & DF_TEXTREL) {
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003772#if defined(__LP64__)
Dimitry Ivanov816676e2016-10-19 11:00:28 -07003773 DL_ERR("\"%s\" has text relocations", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003774 return false;
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003775#else
3776 has_text_relocations = true;
3777#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08003778 }
Dmitriy Ivanov96bc37f2014-09-29 12:10:36 -07003779 if (d->d_un.d_val & DF_SYMBOLIC) {
3780 has_DT_SYMBOLIC = true;
3781 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003782 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003783
Dmitriy Ivanov6cdeb522014-09-29 19:14:45 -07003784 case DT_FLAGS_1:
Dmitriy Ivanovd225a5e2014-08-28 14:12:12 -07003785 set_dt_flags_1(d->d_un.d_val);
Dmitriy Ivanov1b20daf2014-05-19 15:06:58 -07003786
Dmitriy Ivanovd225a5e2014-08-28 14:12:12 -07003787 if ((d->d_un.d_val & ~SUPPORTED_DT_FLAGS_1) != 0) {
Elliott Hughes9076b0c2018-02-28 11:29:45 -08003788 DL_WARN("Warning: \"%s\" has unsupported flags DT_FLAGS_1=%p "
3789 "(ignoring unsupported flags)",
3790 get_realpath(), reinterpret_cast<void*>(d->d_un.d_val));
Dmitriy Ivanov6cdeb522014-09-29 19:14:45 -07003791 }
3792 break;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003793#if defined(__mips__)
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003794 case DT_MIPS_RLD_MAP:
3795 // Set the DT_MIPS_RLD_MAP entry to the address of _r_debug for GDB.
3796 {
3797 r_debug** dp = reinterpret_cast<r_debug**>(load_bias + d->d_un.d_ptr);
3798 *dp = &_r_debug;
3799 }
3800 break;
Lazar Trsic83b44a92016-04-06 13:39:17 +02003801 case DT_MIPS_RLD_MAP_REL:
3802 // Set the DT_MIPS_RLD_MAP_REL entry to the address of _r_debug for GDB.
Raghu Gandham68815722014-12-18 19:12:19 -08003803 {
Dmitriy Ivanov20d89cb2015-03-30 18:43:38 -07003804 r_debug** dp = reinterpret_cast<r_debug**>(
3805 reinterpret_cast<ElfW(Addr)>(d) + d->d_un.d_val);
Raghu Gandham68815722014-12-18 19:12:19 -08003806 *dp = &_r_debug;
3807 }
3808 break;
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003809
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003810 case DT_MIPS_RLD_VERSION:
3811 case DT_MIPS_FLAGS:
3812 case DT_MIPS_BASE_ADDRESS:
3813 case DT_MIPS_UNREFEXTNO:
3814 break;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08003815
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003816 case DT_MIPS_SYMTABNO:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003817 mips_symtabno_ = d->d_un.d_val;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003818 break;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08003819
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003820 case DT_MIPS_LOCAL_GOTNO:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003821 mips_local_gotno_ = d->d_un.d_val;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003822 break;
3823
3824 case DT_MIPS_GOTSYM:
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003825 mips_gotsym_ = d->d_un.d_val;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003826 break;
3827#endif
Dmitriy Ivanovea6eae12014-10-15 14:59:01 -07003828 // Ignored: "Its use has been superseded by the DF_BIND_NOW flag"
3829 case DT_BIND_NOW:
3830 break;
3831
Dmitriy Ivanov513e29e2014-10-06 11:30:43 -07003832 case DT_VERSYM:
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07003833 versym_ = reinterpret_cast<ElfW(Versym)*>(load_bias + d->d_un.d_ptr);
3834 break;
3835
Dmitriy Ivanov513e29e2014-10-06 11:30:43 -07003836 case DT_VERDEF:
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07003837 verdef_ptr_ = load_bias + d->d_un.d_ptr;
3838 break;
Dmitriy Ivanov513e29e2014-10-06 11:30:43 -07003839 case DT_VERDEFNUM:
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07003840 verdef_cnt_ = d->d_un.d_val;
3841 break;
3842
Alexander Ivchenkoe8314332014-12-02 15:32:25 +03003843 case DT_VERNEED:
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07003844 verneed_ptr_ = load_bias + d->d_un.d_ptr;
3845 break;
3846
Alexander Ivchenkoe8314332014-12-02 15:32:25 +03003847 case DT_VERNEEDNUM:
Dmitriy Ivanov2a815362015-04-09 13:42:33 -07003848 verneed_cnt_ = d->d_un.d_val;
Dmitriy Ivanov513e29e2014-10-06 11:30:43 -07003849 break;
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003850
Evgenii Stepanov68650822015-06-10 13:38:39 -07003851 case DT_RUNPATH:
3852 // this is parsed after we have strtab initialized (see below).
3853 break;
3854
Ryan Prichardea41ab02019-01-23 16:33:03 -08003855 case DT_TLSDESC_GOT:
3856 case DT_TLSDESC_PLT:
3857 // These DT entries are used for lazy TLSDESC relocations. Bionic
3858 // resolves everything eagerly, so these can be ignored.
3859 break;
3860
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003861 default:
Dmitriy Ivanov8f61d992014-09-16 14:31:06 -07003862 if (!relocating_linker) {
Elliott Hughes6eae4cc2017-08-30 09:02:33 -07003863 const char* tag_name;
3864 if (d->d_tag == DT_RPATH) {
3865 tag_name = "DT_RPATH";
3866 } else if (d->d_tag == DT_ENCODING) {
3867 tag_name = "DT_ENCODING";
3868 } else if (d->d_tag >= DT_LOOS && d->d_tag <= DT_HIOS) {
3869 tag_name = "unknown OS-specific";
3870 } else if (d->d_tag >= DT_LOPROC && d->d_tag <= DT_HIPROC) {
3871 tag_name = "unknown processor-specific";
3872 } else {
3873 tag_name = "unknown";
3874 }
Elliott Hughes9076b0c2018-02-28 11:29:45 -08003875 DL_WARN("Warning: \"%s\" unused DT entry: %s (type %p arg %p) (ignoring)",
Elliott Hughes6eae4cc2017-08-30 09:02:33 -07003876 get_realpath(),
3877 tag_name,
3878 reinterpret_cast<void*>(d->d_tag),
3879 reinterpret_cast<void*>(d->d_un.d_val));
Dmitriy Ivanov8f61d992014-09-16 14:31:06 -07003880 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003881 break;
Brian Carlstromd4ee82d2013-02-28 15:58:45 -08003882 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003883 }
3884
Duane Sandbc425c72015-06-01 16:29:14 -07003885#if defined(__mips__) && !defined(__LP64__)
3886 if (!mips_check_and_adjust_fp_modes()) {
3887 return false;
3888 }
3889#endif
3890
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003891 DEBUG("si->base = %p, si->strtab = %p, si->symtab = %p",
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08003892 reinterpret_cast<void*>(base), strtab_, symtab_);
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003893
3894 // Sanity checks.
3895 if (relocating_linker && needed_count != 0) {
3896 DL_ERR("linker cannot have DT_NEEDED dependencies on other libraries");
3897 return false;
3898 }
Dmitriy Ivanov3597b802015-03-09 12:02:02 -07003899 if (nbucket_ == 0 && gnu_nbucket_ == 0) {
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07003900 DL_ERR("empty/missing DT_HASH/DT_GNU_HASH in \"%s\" "
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07003901 "(new hash type from the future?)", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003902 return false;
3903 }
Yi Kong32bc0fc2018-08-02 17:31:13 -07003904 if (strtab_ == nullptr) {
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07003905 DL_ERR("empty/missing DT_STRTAB in \"%s\"", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003906 return false;
3907 }
Yi Kong32bc0fc2018-08-02 17:31:13 -07003908 if (symtab_ == nullptr) {
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07003909 DL_ERR("empty/missing DT_SYMTAB in \"%s\"", get_realpath());
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003910 return false;
3911 }
Dmitriy Ivanov75108f42015-06-02 13:28:06 -07003912
Dmitriy Ivanov624b8f12015-06-08 10:41:33 -07003913 // second pass - parse entries relying on strtab
3914 for (ElfW(Dyn)* d = dynamic; d->d_tag != DT_NULL; ++d) {
Evgenii Stepanov68650822015-06-10 13:38:39 -07003915 switch (d->d_tag) {
3916 case DT_SONAME:
Dmitriy Ivanov4f7a7ad2015-10-15 12:07:25 -07003917 set_soname(get_string(d->d_un.d_val));
Evgenii Stepanov68650822015-06-10 13:38:39 -07003918 break;
3919 case DT_RUNPATH:
Evgenii Stepanov68650822015-06-10 13:38:39 -07003920 set_dt_runpath(get_string(d->d_un.d_val));
3921 break;
Dmitriy Ivanov624b8f12015-06-08 10:41:33 -07003922 }
3923 }
3924
Dmitriy Ivanov75108f42015-06-02 13:28:06 -07003925 // Before M release linker was using basename in place of soname.
Dmitriy Ivanov19133522015-06-02 17:36:54 -07003926 // In the case when dt_soname is absent some apps stop working
Dmitriy Ivanov75108f42015-06-02 13:28:06 -07003927 // because they can't find dt_needed library by soname.
Elliott Hughes9076b0c2018-02-28 11:29:45 -08003928 // This workaround should keep them working. (Applies only
3929 // for apps targeting sdk version < M.) Make an exception for
3930 // the main executable and linker; they do not need to have dt_soname.
3931 // TODO: >= O the linker doesn't need this workaround.
Dimitry Ivanov3f660572016-09-09 10:00:39 -07003932 if (soname_ == nullptr &&
3933 this != solist_get_somain() &&
3934 (flags_ & FLAG_LINKER) == 0 &&
Elliott Hughes5bc78c82016-11-16 11:35:43 -08003935 get_application_target_sdk_version() < __ANDROID_API_M__) {
Dmitriy Ivanov75108f42015-06-02 13:28:06 -07003936 soname_ = basename(realpath_.c_str());
Elliott Hughes9076b0c2018-02-28 11:29:45 -08003937 DL_WARN_documented_change(__ANDROID_API_M__,
3938 "missing-soname-enforced-for-api-level-23",
3939 "\"%s\" has no DT_SONAME (will use %s instead)",
3940 get_realpath(), soname_);
3941
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07003942 // 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 -07003943 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07003944 return true;
Dmitriy Ivanov14669a92014-09-05 16:42:53 -07003945}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08003946
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08003947bool soinfo::link_image(const soinfo_list_t& global_group, const soinfo_list_t& local_group,
Torne (Richard Coles)efbe9a52018-10-17 15:59:38 -04003948 const android_dlextinfo* extinfo, size_t* relro_fd_offset) {
dimitry965d06d2017-11-28 16:03:07 +01003949 if (is_image_linked()) {
3950 // already linked.
3951 return true;
3952 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08003953
Elliott Hughes90f96b92019-05-09 15:56:39 -07003954 if (g_is_ldd && !is_main_executable()) {
3955 async_safe_format_fd(STDOUT_FILENO, "\t%s => %s (%p)\n", get_soname(),
3956 get_realpath(), reinterpret_cast<void*>(base));
3957 }
3958
Dmitriy Ivanovab972b92014-11-29 13:57:41 -08003959 local_group_root_ = local_group.front();
3960 if (local_group_root_ == nullptr) {
3961 local_group_root_ = this;
3962 }
3963
Dmitriy Ivanov19133522015-06-02 17:36:54 -07003964 if ((flags_ & FLAG_LINKER) == 0 && local_group_root_ == this) {
3965 target_sdk_version_ = get_application_target_sdk_version();
3966 }
3967
Dmitriy Ivanov7e4bbba2015-04-30 19:49:19 -07003968 VersionTracker version_tracker;
3969
3970 if (!version_tracker.init(this)) {
3971 return false;
3972 }
3973
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003974#if !defined(__LP64__)
3975 if (has_text_relocations) {
Elliott Hughes5bc78c82016-11-16 11:35:43 -08003976 // Fail if app is targeting M or above.
Elliott Hughes9076b0c2018-02-28 11:29:45 -08003977 int app_target_api_level = get_application_target_sdk_version();
3978 if (app_target_api_level >= __ANDROID_API_M__) {
Elliott Hughes763f6e12017-04-10 09:52:33 -07003979 DL_ERR_AND_LOG("\"%s\" has text relocations (https://android.googlesource.com/platform/"
3980 "bionic/+/master/android-changes-for-ndk-developers.md#Text-Relocations-"
3981 "Enforced-for-API-level-23)", get_realpath());
Dmitriy Ivanove4ad91f2015-06-12 15:00:31 -07003982 return false;
3983 }
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003984 // Make segments writable to allow text relocations to work properly. We will later call
Dmitriy Ivanov7e039932015-10-01 14:02:19 -07003985 // phdr_table_protect_segments() after all of them are applied.
Elliott Hughes9076b0c2018-02-28 11:29:45 -08003986 DL_WARN_documented_change(__ANDROID_API_M__,
3987 "Text-Relocations-Enforced-for-API-level-23",
3988 "\"%s\" has text relocations",
3989 get_realpath());
Dimitry Ivanov769b33f2016-07-21 11:33:40 -07003990 add_dlwarning(get_realpath(), "text relocations");
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003991 if (phdr_table_unprotect_segments(phdr, phnum, load_bias) < 0) {
Elliott Hughes9076b0c2018-02-28 11:29:45 -08003992 DL_ERR("can't unprotect loadable segments for \"%s\": %s", get_realpath(), strerror(errno));
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00003993 return false;
3994 }
3995 }
3996#endif
3997
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08003998 if (android_relocs_ != nullptr) {
3999 // check signature
4000 if (android_relocs_size_ > 3 &&
4001 android_relocs_[0] == 'A' &&
4002 android_relocs_[1] == 'P' &&
Dmitriy Ivanov18870d32015-04-22 13:10:04 -07004003 android_relocs_[2] == 'S' &&
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08004004 android_relocs_[3] == '2') {
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07004005 DEBUG("[ android relocating %s ]", get_realpath());
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08004006
4007 bool relocated = false;
4008 const uint8_t* packed_relocs = android_relocs_ + 4;
4009 const size_t packed_relocs_size = android_relocs_size_ - 4;
4010
Dmitriy Ivanov18870d32015-04-22 13:10:04 -07004011 relocated = relocate(
Dmitriy Ivanov7e4bbba2015-04-30 19:49:19 -07004012 version_tracker,
Dmitriy Ivanov18870d32015-04-22 13:10:04 -07004013 packed_reloc_iterator<sleb128_decoder>(
4014 sleb128_decoder(packed_relocs, packed_relocs_size)),
4015 global_group, local_group);
Dmitriy Ivanov18a69562015-02-04 16:05:30 -08004016
4017 if (!relocated) {
4018 return false;
4019 }
4020 } else {
4021 DL_ERR("bad android relocation header.");
4022 return false;
4023 }
4024 }
4025
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08004026 if (relr_ != nullptr) {
4027 DEBUG("[ relocating %s relr ]", get_realpath());
4028 if (!relocate_relr()) {
4029 return false;
4030 }
4031 }
4032
Elliott Hughes4eeb1f12013-10-25 17:38:02 -07004033#if defined(USE_RELA)
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08004034 if (rela_ != nullptr) {
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08004035 DEBUG("[ relocating %s rela ]", get_realpath());
Dmitriy Ivanov7e4bbba2015-04-30 19:49:19 -07004036 if (!relocate(version_tracker,
4037 plain_reloc_iterator(rela_, rela_count_), global_group, local_group)) {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07004038 return false;
Elliott Hughesc00f2cb2013-10-04 17:01:33 -07004039 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07004040 }
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08004041 if (plt_rela_ != nullptr) {
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08004042 DEBUG("[ relocating %s plt rela ]", get_realpath());
Dmitriy Ivanov7e4bbba2015-04-30 19:49:19 -07004043 if (!relocate(version_tracker,
4044 plain_reloc_iterator(plt_rela_, plt_rela_count_), global_group, local_group)) {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07004045 return false;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08004046 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07004047 }
Dmitriy Ivanov9aea1642014-09-11 15:16:03 -07004048#else
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08004049 if (rel_ != nullptr) {
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08004050 DEBUG("[ relocating %s rel ]", get_realpath());
Dmitriy Ivanov7e4bbba2015-04-30 19:49:19 -07004051 if (!relocate(version_tracker,
4052 plain_reloc_iterator(rel_, rel_count_), global_group, local_group)) {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07004053 return false;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08004054 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07004055 }
Dmitriy Ivanov047b5932014-11-13 09:39:20 -08004056 if (plt_rel_ != nullptr) {
Rahul Chaudhryb7feec72017-12-19 15:25:23 -08004057 DEBUG("[ relocating %s plt rel ]", get_realpath());
Dmitriy Ivanov7e4bbba2015-04-30 19:49:19 -07004058 if (!relocate(version_tracker,
4059 plain_reloc_iterator(plt_rel_, plt_rel_count_), global_group, local_group)) {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07004060 return false;
Brigid Smithc5a13ef2014-07-23 11:22:25 -07004061 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07004062 }
Dmitriy Ivanov9aea1642014-09-11 15:16:03 -07004063#endif
Brigid Smithc5a13ef2014-07-23 11:22:25 -07004064
Elliott Hughes4eeb1f12013-10-25 17:38:02 -07004065#if defined(__mips__)
Dmitriy Ivanovf39cb632015-04-30 20:17:03 -07004066 if (!mips_relocate_got(version_tracker, global_group, local_group)) {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07004067 return false;
4068 }
Raghu Gandhamd7daacb2012-07-31 12:07:22 -07004069#endif
4070
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07004071 DEBUG("[ finished linking %s ]", get_realpath());
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08004072
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00004073#if !defined(__LP64__)
4074 if (has_text_relocations) {
4075 // All relocations are done, we can protect our segments back to read-only.
4076 if (phdr_table_protect_segments(phdr, phnum, load_bias) < 0) {
4077 DL_ERR("can't protect segments for \"%s\": %s",
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07004078 get_realpath(), strerror(errno));
Dimitry Ivanov56be6ed2015-04-01 21:18:48 +00004079 return false;
4080 }
4081 }
4082#endif
4083
Mingwei Shibe910522015-11-12 07:02:14 +00004084 // We can also turn on GNU RELRO protection if we're not linking the dynamic linker
4085 // itself --- it can't make system calls yet, and will have to call protect_relro later.
4086 if (!is_linker() && !protect_relro()) {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07004087 return false;
4088 }
Nick Kralevich9ec0f032012-02-28 10:40:00 -08004089
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07004090 /* Handle serializing/sharing the RELRO segment */
4091 if (extinfo && (extinfo->flags & ANDROID_DLEXT_WRITE_RELRO)) {
4092 if (phdr_table_serialize_gnu_relro(phdr, phnum, load_bias,
Torne (Richard Coles)fa9f7f22019-04-02 17:04:42 -04004093 extinfo->relro_fd, relro_fd_offset) < 0) {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07004094 DL_ERR("failed serializing GNU RELRO section for \"%s\": %s",
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07004095 get_realpath(), strerror(errno));
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07004096 return false;
Torne (Richard Coles)183ad9d2014-02-27 13:18:00 +00004097 }
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07004098 } else if (extinfo && (extinfo->flags & ANDROID_DLEXT_USE_RELRO)) {
4099 if (phdr_table_map_gnu_relro(phdr, phnum, load_bias,
Torne (Richard Coles)efbe9a52018-10-17 15:59:38 -04004100 extinfo->relro_fd, relro_fd_offset) < 0) {
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07004101 DL_ERR("failed mapping GNU RELRO section for \"%s\": %s",
Dmitriy Ivanov3edb9182015-05-07 10:48:00 -07004102 get_realpath(), strerror(errno));
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07004103 return false;
4104 }
4105 }
Torne (Richard Coles)183ad9d2014-02-27 13:18:00 +00004106
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07004107 notify_gdb_of_load(this);
dimitry965d06d2017-11-28 16:03:07 +01004108 set_image_linked();
Dmitriy Ivanov6abf6242014-09-12 09:43:13 -07004109 return true;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08004110}
4111
Mingwei Shibe910522015-11-12 07:02:14 +00004112bool soinfo::protect_relro() {
4113 if (phdr_table_protect_gnu_relro(phdr, phnum, load_bias) < 0) {
4114 DL_ERR("can't enable GNU RELRO protection for \"%s\": %s",
4115 get_realpath(), strerror(errno));
4116 return false;
4117 }
4118 return true;
4119}
4120
Jiyong Park02586a22017-05-20 01:01:24 +09004121static std::vector<android_namespace_t*> init_default_namespace_no_config(bool is_asan) {
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07004122 g_default_namespace.set_isolated(false);
Dimitry Ivanov77ad6422017-03-06 13:02:29 -08004123 auto default_ld_paths = is_asan ? kAsanDefaultLdPaths : kDefaultLdPaths;
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07004124
neo.chae2589f9d2016-10-04 11:00:27 +09004125 char real_path[PATH_MAX];
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07004126 std::vector<std::string> ld_default_paths;
Dimitry Ivanov77ad6422017-03-06 13:02:29 -08004127 for (size_t i = 0; default_ld_paths[i] != nullptr; ++i) {
4128 if (realpath(default_ld_paths[i], real_path) != nullptr) {
neo.chae2589f9d2016-10-04 11:00:27 +09004129 ld_default_paths.push_back(real_path);
4130 } else {
Dimitry Ivanov77ad6422017-03-06 13:02:29 -08004131 ld_default_paths.push_back(default_ld_paths[i]);
neo.chae2589f9d2016-10-04 11:00:27 +09004132 }
Dmitriy Ivanov42d5fcb2015-10-29 17:01:24 -07004133 }
4134
4135 g_default_namespace.set_default_library_paths(std::move(ld_default_paths));
Jiyong Park02586a22017-05-20 01:01:24 +09004136
4137 std::vector<android_namespace_t*> namespaces;
4138 namespaces.push_back(&g_default_namespace);
4139 return namespaces;
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08004140}
4141
Roland Levillaindc25f6c2019-07-02 16:40:19 +01004142// return /apex/<name>/etc/ld.config.txt from /apex/<name>/bin/*
Jiyong Park35833412018-10-26 14:45:21 +09004143static std::string get_ld_config_file_apex_path(const char* executable_path) {
4144 std::vector<std::string> paths = android::base::Split(executable_path, "/");
Roland Levillaindc25f6c2019-07-02 16:40:19 +01004145 if (paths.size() >= 5 && paths[1] == "apex" && paths[3] == "bin") {
Jiyong Park35833412018-10-26 14:45:21 +09004146 return std::string("/apex/") + paths[2] + "/etc/ld.config.txt";
4147 }
4148 return "";
4149}
4150
Logan Chien886b96e2018-05-08 17:52:18 +08004151static std::string get_ld_config_file_vndk_path() {
Logan Chienbcfe3cf2018-05-08 20:17:26 +08004152 if (android::base::GetBoolProperty("ro.vndk.lite", false)) {
4153 return kLdConfigVndkLiteFilePath;
4154 }
4155
Logan Chien886b96e2018-05-08 17:52:18 +08004156 std::string ld_config_file_vndk = kLdConfigFilePath;
4157 size_t insert_pos = ld_config_file_vndk.find_last_of('.');
4158 if (insert_pos == std::string::npos) {
4159 insert_pos = ld_config_file_vndk.length();
4160 }
4161 ld_config_file_vndk.insert(insert_pos, Config::get_vndk_version_string('.'));
4162 return ld_config_file_vndk;
4163}
4164
Jiyong Park35833412018-10-26 14:45:21 +09004165static std::string get_ld_config_file_path(const char* executable_path) {
Logan Chien886b96e2018-05-08 17:52:18 +08004166#ifdef USE_LD_CONFIG_FILE
4167 // This is a debugging/testing only feature. Must not be available on
4168 // production builds.
4169 const char* ld_config_file_env = getenv("LD_CONFIG_FILE");
4170 if (ld_config_file_env != nullptr && file_exists(ld_config_file_env)) {
4171 return ld_config_file_env;
4172 }
4173#endif
4174
Kiyoung Kim35e3b4b2019-08-07 19:24:13 +09004175 // Use generated linker config if flag is set
4176 // TODO(b/138920271) Do not check property once it is confirmed as stable
4177 if (android::base::GetBoolProperty("sys.linker.use_generated_config", false) &&
4178 file_exists(kLdGeneratedConfigFilePath)) {
4179 return kLdGeneratedConfigFilePath;
4180 }
4181
Jiyong Park35833412018-10-26 14:45:21 +09004182 std::string path = get_ld_config_file_apex_path(executable_path);
4183 if (!path.empty()) {
4184 if (file_exists(path.c_str())) {
4185 return path;
4186 }
4187 DL_WARN("Warning: couldn't read config file \"%s\" for \"%s\"",
4188 path.c_str(), executable_path);
Logan Chien886b96e2018-05-08 17:52:18 +08004189 }
4190
Jiyong Park35833412018-10-26 14:45:21 +09004191 path = kLdConfigArchFilePath;
4192 if (file_exists(path.c_str())) {
4193 return path;
4194 }
4195
4196 path = get_ld_config_file_vndk_path();
4197 if (file_exists(path.c_str())) {
4198 return path;
Logan Chien886b96e2018-05-08 17:52:18 +08004199 }
4200
4201 return kLdConfigFilePath;
4202}
4203
Jiyong Park02586a22017-05-20 01:01:24 +09004204std::vector<android_namespace_t*> init_default_namespaces(const char* executable_path) {
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08004205 g_default_namespace.set_name("(default)");
4206
4207 soinfo* somain = solist_get_somain();
4208
4209 const char *interp = phdr_table_get_interpreter_name(somain->phdr, somain->phnum,
4210 somain->load_bias);
Dan Willemsen7ccc50d2017-09-18 21:28:14 -07004211 const char* bname = (interp != nullptr) ? basename(interp) : nullptr;
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08004212
4213 g_is_asan = bname != nullptr &&
4214 (strcmp(bname, "linker_asan") == 0 ||
4215 strcmp(bname, "linker_asan64") == 0);
4216
4217 const Config* config = nullptr;
4218
4219 std::string error_msg;
4220
Jiyong Park35833412018-10-26 14:45:21 +09004221 std::string ld_config_file_path = get_ld_config_file_path(executable_path);
Jiyong Park02586a22017-05-20 01:01:24 +09004222
Martin Stjernholm95252ee2019-02-22 22:48:59 +00004223 INFO("[ Reading linker config \"%s\" ]", ld_config_file_path.c_str());
Logan Chien886b96e2018-05-08 17:52:18 +08004224 if (!Config::read_binary_config(ld_config_file_path.c_str(),
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08004225 executable_path,
4226 g_is_asan,
4227 &config,
4228 &error_msg)) {
4229 if (!error_msg.empty()) {
Elliott Hughes9076b0c2018-02-28 11:29:45 -08004230 DL_WARN("Warning: couldn't read \"%s\" for \"%s\" (using default configuration instead): %s",
Logan Chien886b96e2018-05-08 17:52:18 +08004231 ld_config_file_path.c_str(),
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08004232 executable_path,
4233 error_msg.c_str());
4234 }
4235 config = nullptr;
4236 }
4237
4238 if (config == nullptr) {
Jiyong Park02586a22017-05-20 01:01:24 +09004239 return init_default_namespace_no_config(g_is_asan);
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08004240 }
4241
4242 const auto& namespace_configs = config->namespace_configs();
4243 std::unordered_map<std::string, android_namespace_t*> namespaces;
4244
4245 // 1. Initialize default namespace
4246 const NamespaceConfig* default_ns_config = config->default_namespace_config();
4247
4248 g_default_namespace.set_isolated(default_ns_config->isolated());
4249 g_default_namespace.set_default_library_paths(default_ns_config->search_paths());
4250 g_default_namespace.set_permitted_paths(default_ns_config->permitted_paths());
4251
4252 namespaces[default_ns_config->name()] = &g_default_namespace;
Justin Yun90de9f02017-07-07 16:21:53 +09004253 if (default_ns_config->visible()) {
4254 g_exported_namespaces[default_ns_config->name()] = &g_default_namespace;
4255 }
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08004256
4257 // 2. Initialize other namespaces
4258
4259 for (auto& ns_config : namespace_configs) {
4260 if (namespaces.find(ns_config->name()) != namespaces.end()) {
4261 continue;
4262 }
4263
4264 android_namespace_t* ns = new (g_namespace_allocator.alloc()) android_namespace_t();
4265 ns->set_name(ns_config->name());
4266 ns->set_isolated(ns_config->isolated());
4267 ns->set_default_library_paths(ns_config->search_paths());
4268 ns->set_permitted_paths(ns_config->permitted_paths());
Vic Yang2d020e42019-01-12 21:03:25 -08004269 ns->set_whitelisted_libs(ns_config->whitelisted_libs());
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08004270
4271 namespaces[ns_config->name()] = ns;
Jiyong Park01de74e2017-04-03 23:10:37 +09004272 if (ns_config->visible()) {
4273 g_exported_namespaces[ns_config->name()] = ns;
4274 }
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08004275 }
4276
4277 // 3. Establish links between namespaces
4278 for (auto& ns_config : namespace_configs) {
4279 auto it_from = namespaces.find(ns_config->name());
4280 CHECK(it_from != namespaces.end());
4281 android_namespace_t* namespace_from = it_from->second;
4282 for (const NamespaceLinkConfig& ns_link : ns_config->links()) {
4283 auto it_to = namespaces.find(ns_link.ns_name());
4284 CHECK(it_to != namespaces.end());
4285 android_namespace_t* namespace_to = it_to->second;
Logan Chien9ee45912018-01-18 12:05:09 +08004286 if (ns_link.allow_all_shared_libs()) {
4287 link_namespaces_all_libs(namespace_from, namespace_to);
4288 } else {
4289 link_namespaces(namespace_from, namespace_to, ns_link.shared_libs().c_str());
4290 }
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08004291 }
4292 }
4293 // we can no longer rely on the fact that libdl.so is part of default namespace
4294 // this is why we want to add ld-android.so to all namespaces from ld.config.txt
4295 soinfo* ld_android_so = solist_get_head();
dimitry8b142562018-05-09 15:22:38 +02004296
4297 // we also need vdso to be available for all namespaces (if present)
4298 soinfo* vdso = solist_get_vdso();
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08004299 for (auto it : namespaces) {
4300 it.second->add_soinfo(ld_android_so);
dimitry8b142562018-05-09 15:22:38 +02004301 if (vdso != nullptr) {
4302 it.second->add_soinfo(vdso);
4303 }
Jiyong Park02586a22017-05-20 01:01:24 +09004304 // somain and ld_preloads are added to these namespaces after LD_PRELOAD libs are linked
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08004305 }
4306
4307 set_application_target_sdk_version(config->target_sdk_version());
Jiyong Park02586a22017-05-20 01:01:24 +09004308
4309 std::vector<android_namespace_t*> created_namespaces;
4310 created_namespaces.reserve(namespaces.size());
Chih-Hung Hsieh0218e922018-12-11 10:22:11 -08004311 for (const auto& kv : namespaces) {
Jiyong Park02586a22017-05-20 01:01:24 +09004312 created_namespaces.push_back(kv.second);
4313 }
4314 return created_namespaces;
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -08004315}
Jiyong Park01de74e2017-04-03 23:10:37 +09004316
4317// This function finds a namespace exported in ld.config.txt by its name.
4318// A namespace can be exported by setting .visible property to true.
4319android_namespace_t* get_exported_namespace(const char* name) {
4320 if (name == nullptr) {
4321 return nullptr;
4322 }
4323 auto it = g_exported_namespaces.find(std::string(name));
4324 if (it == g_exported_namespaces.end()) {
4325 return nullptr;
4326 }
4327 return it->second;
4328}
Vic Yangbb7e1232019-01-29 20:23:16 -08004329
4330void purge_unused_memory() {
4331 // For now, we only purge the memory used by LoadTask because we know those
4332 // are temporary objects.
4333 //
4334 // Purging other LinkerBlockAllocator hardly yields much because they hold
4335 // information about namespaces and opened libraries, which are not freed
4336 // when the control leaves the linker.
4337 //
4338 // Purging BionicAllocator may give us a few dirty pages back, but those pages
4339 // would be already zeroed out, so they compress easily in ZRAM. Therefore,
4340 // it is not worth munmap()'ing those pages.
4341 TypeBasedAllocator<LoadTask>::purge();
4342}