-
Notifications
You must be signed in to change notification settings - Fork 205
/
Copy pathlinker.cpp
3676 lines (3116 loc) · 123 KB
/
linker.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2008 The Android Open Source Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include <android/api-level.h>
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/auxv.h>
#include <sys/mman.h>
#include <sys/param.h>
#include <sys/vfs.h>
#include <unistd.h>
#include <iterator>
#include <new>
#include <string>
#include <unordered_map>
#include <vector>
#include <android-base/properties.h>
#include <android-base/scopeguard.h>
#include <async_safe/log.h>
#include <bionic/pthread_internal.h>
// Private C library headers.
#include "linker.h"
#include "linker_block_allocator.h"
#include "linker_cfi.h"
#include "linker_config.h"
#include "linker_gdb_support.h"
#include "linker_globals.h"
#include "linker_debug.h"
#include "linker_dlwarning.h"
#include "linker_main.h"
#include "linker_namespaces.h"
#include "linker_sleb128.h"
#include "linker_phdr.h"
#include "linker_relocate.h"
#include "linker_tls.h"
#include "linker_translate_path.h"
#include "linker_utils.h"
#include "android-base/macros.h"
#include "android-base/stringprintf.h"
#include "android-base/strings.h"
#include "private/bionic_asm_note.h"
#include "private/bionic_call_ifunc_resolver.h"
#include "private/bionic_globals.h"
#include "ziparchive/zip_archive.h"
static std::unordered_map<void*, size_t> g_dso_handle_counters;
static bool g_anonymous_namespace_set = false;
static android_namespace_t* g_anonymous_namespace = &g_default_namespace;
static std::unordered_map<std::string, android_namespace_t*> g_exported_namespaces;
static LinkerTypeAllocator<soinfo> g_soinfo_allocator;
static LinkerTypeAllocator<LinkedListEntry<soinfo>> g_soinfo_links_allocator;
static LinkerTypeAllocator<android_namespace_t> g_namespace_allocator;
static LinkerTypeAllocator<LinkedListEntry<android_namespace_t>> g_namespace_list_allocator;
static uint64_t g_module_load_counter = 0;
static uint64_t g_module_unload_counter = 0;
static const char* const kLdConfigArchFilePath = "/system/etc/ld.config." ABI_STRING ".txt";
static const char* const kLdConfigFilePath = "/system/etc/ld.config.txt";
static const char* const kLdConfigVndkLiteFilePath = "/system/etc/ld.config.vndk_lite.txt";
static const char* const kLdGeneratedConfigFilePath = "/linkerconfig/ld.config.txt";
#if defined(__LP64__)
static const char* const kSystemLibDir = "/system/lib64";
static const char* const kOdmLibDir = "/odm/lib64";
static const char* const kVendorLibDir = "/vendor/lib64";
static const char* const kAsanSystemLibDir = "/data/asan/system/lib64";
static const char* const kAsanOdmLibDir = "/data/asan/odm/lib64";
static const char* const kAsanVendorLibDir = "/data/asan/vendor/lib64";
#else
static const char* const kSystemLibDir = "/system/lib";
static const char* const kOdmLibDir = "/odm/lib";
static const char* const kVendorLibDir = "/vendor/lib";
static const char* const kAsanSystemLibDir = "/data/asan/system/lib";
static const char* const kAsanOdmLibDir = "/data/asan/odm/lib";
static const char* const kAsanVendorLibDir = "/data/asan/vendor/lib";
#endif
static const char* const kAsanLibDirPrefix = "/data/asan";
static const char* const kDefaultLdPaths[] = {
kSystemLibDir,
kOdmLibDir,
kVendorLibDir,
nullptr
};
static const char* const kAsanDefaultLdPaths[] = {
kAsanSystemLibDir,
kSystemLibDir,
kAsanOdmLibDir,
kOdmLibDir,
kAsanVendorLibDir,
kVendorLibDir,
nullptr
};
#if defined(__aarch64__)
static const char* const kHwasanSystemLibDir = "/system/lib64/hwasan";
static const char* const kHwasanOdmLibDir = "/odm/lib64/hwasan";
static const char* const kHwasanVendorLibDir = "/vendor/lib64/hwasan";
// HWASan is only supported on aarch64.
static const char* const kHwsanDefaultLdPaths[] = {
kHwasanSystemLibDir,
kSystemLibDir,
kHwasanOdmLibDir,
kOdmLibDir,
kHwasanVendorLibDir,
kVendorLibDir,
nullptr
};
// Is HWASAN enabled?
static bool g_is_hwasan = false;
#else
static const char* const kHwsanDefaultLdPaths[] = {
kSystemLibDir,
kOdmLibDir,
kVendorLibDir,
nullptr
};
// Never any HWASan. Help the compiler remove the code we don't need.
constexpr bool g_is_hwasan = false;
#endif
// Is ASAN enabled?
static bool g_is_asan = false;
static CFIShadowWriter g_cfi_shadow;
CFIShadowWriter* get_cfi_shadow() {
return &g_cfi_shadow;
}
static bool is_system_library(const std::string& realpath) {
for (const auto& dir : g_default_namespace.get_default_library_paths()) {
if (file_is_in_dir(realpath, dir)) {
return true;
}
}
return false;
}
// Checks if the file exists and not a directory.
static bool file_exists(const char* path) {
struct stat s;
if (stat(path, &s) != 0) {
return false;
}
return S_ISREG(s.st_mode);
}
static std::string resolve_soname(const std::string& name) {
// We assume that soname equals to basename here
// TODO(dimitry): consider having honest absolute-path -> soname resolution
// note that since we might end up refusing to load this library because
// it is not in shared libs list we need to get the soname without actually loading
// the library.
//
// On the other hand there are several places where we already assume that
// soname == basename in particular for any not-loaded library mentioned
// in DT_NEEDED list.
return basename(name.c_str());
}
static bool maybe_accessible_via_namespace_links(android_namespace_t* ns, const char* name) {
std::string soname = resolve_soname(name);
for (auto& ns_link : ns->linked_namespaces()) {
if (ns_link.is_accessible(soname.c_str())) {
return true;
}
}
return false;
}
// TODO(dimitry): The exempt-list is a workaround for http://b/26394120 ---
// gradually remove libraries from this list until it is gone.
static bool is_exempt_lib(android_namespace_t* ns, const char* name, const soinfo* needed_by) {
static const char* const kLibraryExemptList[] = {
"libandroid_runtime.so",
"libbinder.so",
"libcrypto.so",
"libcutils.so",
"libexpat.so",
"libgui.so",
"libmedia.so",
"libnativehelper.so",
"libssl.so",
"libstagefright.so",
"libsqlite.so",
"libui.so",
"libutils.so",
nullptr
};
// If you're targeting N, you don't get the exempt-list.
if (get_application_target_sdk_version() >= 24) {
return false;
}
// if the library needed by a system library - implicitly assume it
// is exempt unless it is in the list of shared libraries for one or
// more linked namespaces
if (needed_by != nullptr && is_system_library(needed_by->get_realpath())) {
return !maybe_accessible_via_namespace_links(ns, name);
}
// if this is an absolute path - make sure it points to /system/lib(64)
if (name[0] == '/' && dirname(name) == kSystemLibDir) {
// and reduce the path to basename
name = basename(name);
}
for (size_t i = 0; kLibraryExemptList[i] != nullptr; ++i) {
if (strcmp(name, kLibraryExemptList[i]) == 0) {
return true;
}
}
return false;
}
// END OF WORKAROUND
static std::vector<std::string> g_ld_preload_names;
static void notify_gdb_of_load(soinfo* info) {
if (info->is_linker() || info->is_main_executable()) {
// gdb already knows about the linker and the main executable.
return;
}
link_map* map = &(info->link_map_head);
map->l_addr = info->load_bias;
// link_map l_name field is not const.
map->l_name = const_cast<char*>(info->get_realpath());
map->l_ld = info->dynamic;
CHECK(map->l_name != nullptr);
CHECK(map->l_name[0] != '\0');
notify_gdb_of_load(map);
}
static void notify_gdb_of_unload(soinfo* info) {
notify_gdb_of_unload(&(info->link_map_head));
}
LinkedListEntry<soinfo>* SoinfoListAllocator::alloc() {
return g_soinfo_links_allocator.alloc();
}
void SoinfoListAllocator::free(LinkedListEntry<soinfo>* entry) {
g_soinfo_links_allocator.free(entry);
}
LinkedListEntry<android_namespace_t>* NamespaceListAllocator::alloc() {
return g_namespace_list_allocator.alloc();
}
void NamespaceListAllocator::free(LinkedListEntry<android_namespace_t>* entry) {
g_namespace_list_allocator.free(entry);
}
soinfo* soinfo_alloc(android_namespace_t* ns, const char* name,
const struct stat* file_stat, off64_t file_offset,
uint32_t rtld_flags) {
if (strlen(name) >= PATH_MAX) {
async_safe_fatal("library name \"%s\" too long", name);
}
LD_DEBUG(any, "name %s: allocating soinfo for ns=%p", name, ns);
soinfo* si = new (g_soinfo_allocator.alloc()) soinfo(ns, name, file_stat,
file_offset, rtld_flags);
solist_add_soinfo(si);
si->generate_handle();
ns->add_soinfo(si);
LD_DEBUG(any, "name %s: allocated soinfo @ %p", name, si);
return si;
}
static void soinfo_free(soinfo* si) {
if (si == nullptr) {
return;
}
if (si->base != 0 && si->size != 0) {
if (!si->is_mapped_by_caller()) {
munmap(reinterpret_cast<void*>(si->base), si->size);
} else {
// remap the region as PROT_NONE, MAP_ANONYMOUS | MAP_NORESERVE
mmap(reinterpret_cast<void*>(si->base), si->size, PROT_NONE,
MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
}
}
if (si->has_min_version(6) && si->get_gap_size()) {
munmap(reinterpret_cast<void*>(si->get_gap_start()), si->get_gap_size());
}
LD_DEBUG(any, "name %s: freeing soinfo @ %p", si->get_realpath(), si);
if (!solist_remove_soinfo(si)) {
async_safe_fatal("soinfo=%p is not in soinfo_list (double unload?)", si);
}
// clear links to/from si
si->remove_all_links();
si->~soinfo();
g_soinfo_allocator.free(si);
}
static void parse_path(const char* path, const char* delimiters,
std::vector<std::string>* resolved_paths) {
std::vector<std::string> paths;
split_path(path, delimiters, &paths);
resolve_paths(paths, resolved_paths);
}
static void parse_LD_LIBRARY_PATH(const char* path) {
std::vector<std::string> ld_libary_paths;
parse_path(path, ":", &ld_libary_paths);
g_default_namespace.set_ld_library_paths(std::move(ld_libary_paths));
}
static bool realpath_fd(int fd, std::string* realpath) {
// proc_self_fd needs to be large enough to hold "/proc/self/fd/" plus an
// integer, plus the NULL terminator.
char proc_self_fd[32];
// We want to statically allocate this large buffer so that we don't grow
// the stack by too much.
static char buf[PATH_MAX];
async_safe_format_buffer(proc_self_fd, sizeof(proc_self_fd), "/proc/self/fd/%d", fd);
auto length = readlink(proc_self_fd, buf, sizeof(buf));
if (length == -1) {
if (!is_first_stage_init()) {
DL_WARN("readlink(\"%s\" [fd=%d]) failed: %m", proc_self_fd, fd);
}
return false;
}
realpath->assign(buf, length);
return true;
}
// Returns the address of the current thread's copy of a TLS module. If the current thread doesn't
// have a copy yet, allocate one on-demand if should_alloc is true, and return nullptr otherwise.
static inline void* get_tls_block_for_this_thread(const soinfo_tls* si_tls, bool should_alloc) {
const TlsModule& tls_mod = get_tls_module(si_tls->module_id);
if (tls_mod.static_offset != SIZE_MAX) {
const StaticTlsLayout& layout = __libc_shared_globals()->static_tls_layout;
char* static_tls = reinterpret_cast<char*>(__get_bionic_tcb()) - layout.offset_bionic_tcb();
return static_tls + tls_mod.static_offset;
} else if (should_alloc) {
const TlsIndex ti { si_tls->module_id, static_cast<size_t>(0 - TLS_DTV_OFFSET) };
return TLS_GET_ADDR(&ti);
} else {
TlsDtv* dtv = __get_tcb_dtv(__get_bionic_tcb());
if (dtv->generation < tls_mod.first_generation) return nullptr;
return dtv->modules[__tls_module_id_to_idx(si_tls->module_id)];
}
}
#if defined(__arm__)
// For a given PC, find the .so that it belongs to.
// Returns the base address of the .ARM.exidx section
// for that .so, and the number of 8-byte entries
// in that section (via *pcount).
//
// Intended to be called by libc's __gnu_Unwind_Find_exidx().
_Unwind_Ptr do_dl_unwind_find_exidx(_Unwind_Ptr pc, int* pcount) {
if (soinfo* si = find_containing_library(reinterpret_cast<void*>(pc))) {
*pcount = si->ARM_exidx_count;
return reinterpret_cast<_Unwind_Ptr>(si->ARM_exidx);
}
*pcount = 0;
return 0;
}
#endif
// Here, we only have to provide a callback to iterate across all the
// loaded libraries. gcc_eh does the rest.
int do_dl_iterate_phdr(int (*cb)(dl_phdr_info* info, size_t size, void* data), void* data) {
int rv = 0;
for (soinfo* si = solist_get_head(); si != nullptr; si = si->next) {
dl_phdr_info dl_info;
dl_info.dlpi_addr = si->link_map_head.l_addr;
dl_info.dlpi_name = si->link_map_head.l_name;
dl_info.dlpi_phdr = si->phdr;
dl_info.dlpi_phnum = si->phnum;
dl_info.dlpi_adds = g_module_load_counter;
dl_info.dlpi_subs = g_module_unload_counter;
if (soinfo_tls* tls_module = si->get_tls()) {
dl_info.dlpi_tls_modid = tls_module->module_id;
dl_info.dlpi_tls_data = get_tls_block_for_this_thread(tls_module, /*should_alloc=*/false);
} else {
dl_info.dlpi_tls_modid = 0;
dl_info.dlpi_tls_data = nullptr;
}
rv = cb(&dl_info, sizeof(dl_phdr_info), data);
if (rv != 0) {
break;
}
}
return rv;
}
ProtectedDataGuard::ProtectedDataGuard() {
if (ref_count_++ == 0) {
protect_data(PROT_READ | PROT_WRITE);
}
if (ref_count_ == 0) { // overflow
async_safe_fatal("Too many nested calls to dlopen()");
}
}
ProtectedDataGuard::~ProtectedDataGuard() {
if (--ref_count_ == 0) {
protect_data(PROT_READ);
}
}
void ProtectedDataGuard::protect_data(int protection) {
g_soinfo_allocator.protect_all(protection);
g_soinfo_links_allocator.protect_all(protection);
g_namespace_allocator.protect_all(protection);
g_namespace_list_allocator.protect_all(protection);
}
size_t ProtectedDataGuard::ref_count_ = 0;
// Each size has it's own allocator.
template<size_t size>
class SizeBasedAllocator {
public:
static void* alloc() {
return allocator_.alloc();
}
static void free(void* ptr) {
allocator_.free(ptr);
}
static void purge() {
allocator_.purge();
}
private:
static LinkerBlockAllocator allocator_;
};
template<size_t size>
LinkerBlockAllocator SizeBasedAllocator<size>::allocator_(size);
template<typename T>
class TypeBasedAllocator {
public:
static T* alloc() {
return reinterpret_cast<T*>(SizeBasedAllocator<sizeof(T)>::alloc());
}
static void free(T* ptr) {
SizeBasedAllocator<sizeof(T)>::free(ptr);
}
static void purge() {
SizeBasedAllocator<sizeof(T)>::purge();
}
};
class LoadTask {
public:
struct deleter_t {
void operator()(LoadTask* t) {
t->~LoadTask();
TypeBasedAllocator<LoadTask>::free(t);
}
};
static deleter_t deleter;
// needed_by is NULL iff dlopen is called from memory that isn't part of any known soinfo.
static LoadTask* create(const char* _Nonnull name, soinfo* _Nullable needed_by,
android_namespace_t* _Nonnull start_from,
std::unordered_map<const soinfo*, ElfReader>* _Nonnull readers_map) {
LoadTask* ptr = TypeBasedAllocator<LoadTask>::alloc();
return new (ptr) LoadTask(name, needed_by, start_from, readers_map);
}
const char* get_name() const {
return name_;
}
soinfo* get_needed_by() const {
return needed_by_;
}
soinfo* get_soinfo() const {
return si_;
}
void set_soinfo(soinfo* si) {
si_ = si;
}
off64_t get_file_offset() const {
return file_offset_;
}
void set_file_offset(off64_t offset) {
file_offset_ = offset;
}
int get_fd() const {
return fd_;
}
void set_fd(int fd, bool assume_ownership) {
if (fd_ != -1 && close_fd_) {
close(fd_);
}
fd_ = fd;
close_fd_ = assume_ownership;
}
const android_dlextinfo* get_extinfo() const {
return extinfo_;
}
void set_extinfo(const android_dlextinfo* extinfo) {
extinfo_ = extinfo;
}
bool is_dt_needed() const {
return is_dt_needed_;
}
void set_dt_needed(bool is_dt_needed) {
is_dt_needed_ = is_dt_needed;
}
// returns the namespace from where we need to start loading this.
const android_namespace_t* get_start_from() const {
return start_from_;
}
void remove_cached_elf_reader() {
CHECK(si_ != nullptr);
(*elf_readers_map_).erase(si_);
}
const ElfReader& get_elf_reader() const {
CHECK(si_ != nullptr);
return (*elf_readers_map_)[si_];
}
ElfReader& get_elf_reader() {
CHECK(si_ != nullptr);
return (*elf_readers_map_)[si_];
}
std::unordered_map<const soinfo*, ElfReader>* get_readers_map() {
return elf_readers_map_;
}
bool read(const char* realpath, off64_t file_size) {
ElfReader& elf_reader = get_elf_reader();
return elf_reader.Read(realpath, fd_, file_offset_, file_size);
}
bool load(address_space_params* address_space) {
ElfReader& elf_reader = get_elf_reader();
if (!elf_reader.Load(address_space)) {
return false;
}
si_->base = elf_reader.load_start();
si_->size = elf_reader.load_size();
si_->set_mapped_by_caller(elf_reader.is_mapped_by_caller());
si_->load_bias = elf_reader.load_bias();
si_->phnum = elf_reader.phdr_count();
si_->phdr = elf_reader.loaded_phdr();
si_->set_gap_start(elf_reader.gap_start());
si_->set_gap_size(elf_reader.gap_size());
si_->set_should_pad_segments(elf_reader.should_pad_segments());
return true;
}
private:
LoadTask(const char* name,
soinfo* needed_by,
android_namespace_t* start_from,
std::unordered_map<const soinfo*, ElfReader>* readers_map)
: name_(name), needed_by_(needed_by), si_(nullptr),
fd_(-1), close_fd_(false), file_offset_(0), elf_readers_map_(readers_map),
is_dt_needed_(false), start_from_(start_from) {}
~LoadTask() {
if (fd_ != -1 && close_fd_) {
close(fd_);
}
}
const char* name_;
soinfo* needed_by_;
soinfo* si_;
const android_dlextinfo* extinfo_;
int fd_;
bool close_fd_;
off64_t file_offset_;
std::unordered_map<const soinfo*, ElfReader>* elf_readers_map_;
// TODO(dimitry): needed by workaround for http://b/26394120 (the exempt-list)
bool is_dt_needed_;
// END OF WORKAROUND
const android_namespace_t* const start_from_;
DISALLOW_IMPLICIT_CONSTRUCTORS(LoadTask);
};
LoadTask::deleter_t LoadTask::deleter;
template <typename T>
using linked_list_t = LinkedList<T, TypeBasedAllocator<LinkedListEntry<T>>>;
typedef linked_list_t<soinfo> SoinfoLinkedList;
typedef linked_list_t<const char> StringLinkedList;
typedef std::vector<LoadTask*> LoadTaskList;
enum walk_action_result_t : uint32_t {
kWalkStop = 0,
kWalkContinue = 1,
kWalkSkip = 2
};
// This function walks down the tree of soinfo dependencies
// in breadth-first order and
// * calls action(soinfo* si) for each node, and
// * terminates walk if action returns kWalkStop
// * skips children of the node if action
// return kWalkSkip
//
// walk_dependencies_tree returns false if walk was terminated
// by the action and true otherwise.
template<typename F>
static bool walk_dependencies_tree(soinfo* root_soinfo, F action) {
SoinfoLinkedList visit_list;
SoinfoLinkedList visited;
visit_list.push_back(root_soinfo);
soinfo* si;
while ((si = visit_list.pop_front()) != nullptr) {
if (visited.contains(si)) {
continue;
}
walk_action_result_t result = action(si);
if (result == kWalkStop) {
return false;
}
visited.push_back(si);
if (result != kWalkSkip) {
si->get_children().for_each([&](soinfo* child) {
visit_list.push_back(child);
});
}
}
return true;
}
static const ElfW(Sym)* dlsym_handle_lookup_impl(android_namespace_t* ns,
soinfo* root,
soinfo* skip_until,
soinfo** found,
SymbolName& symbol_name,
const version_info* vi) {
const ElfW(Sym)* result = nullptr;
bool skip_lookup = skip_until != nullptr;
walk_dependencies_tree(root, [&](soinfo* current_soinfo) {
if (skip_lookup) {
skip_lookup = current_soinfo != skip_until;
return kWalkContinue;
}
if (!ns->is_accessible(current_soinfo)) {
return kWalkSkip;
}
result = current_soinfo->find_symbol_by_name(symbol_name, vi);
if (result != nullptr) {
*found = current_soinfo;
return kWalkStop;
}
return kWalkContinue;
});
return result;
}
/* This is used by dlsym(3) to performs a global symbol lookup. If the
start value is null (for RTLD_DEFAULT), the search starts at the
beginning of the global solist. Otherwise the search starts at the
specified soinfo (for RTLD_NEXT).
*/
static const ElfW(Sym)* dlsym_linear_lookup(android_namespace_t* ns,
const char* name,
const version_info* vi,
soinfo** found,
soinfo* caller,
void* handle) {
SymbolName symbol_name(name);
auto& soinfo_list = ns->soinfo_list();
auto start = soinfo_list.begin();
if (handle == RTLD_NEXT) {
if (caller == nullptr) {
return nullptr;
} else {
auto it = soinfo_list.find(caller);
CHECK (it != soinfo_list.end());
start = ++it;
}
}
const ElfW(Sym)* s = nullptr;
for (auto it = start, end = soinfo_list.end(); it != end; ++it) {
soinfo* si = *it;
// Do not skip RTLD_LOCAL libraries in dlsym(RTLD_DEFAULT, ...)
// if the library is opened by application with target api level < M.
// See http://b/21565766
if ((si->get_rtld_flags() & RTLD_GLOBAL) == 0 && si->get_target_sdk_version() >= 23) {
continue;
}
s = si->find_symbol_by_name(symbol_name, vi);
if (s != nullptr) {
*found = si;
break;
}
}
// If not found - use dlsym_handle_lookup_impl for caller's local_group
if (s == nullptr && caller != nullptr) {
soinfo* local_group_root = caller->get_local_group_root();
return dlsym_handle_lookup_impl(local_group_root->get_primary_namespace(),
local_group_root,
(handle == RTLD_NEXT) ? caller : nullptr,
found,
symbol_name,
vi);
}
if (s != nullptr) {
LD_DEBUG(lookup, "%s s->st_value = %p, found->base = %p",
name, reinterpret_cast<void*>(s->st_value), reinterpret_cast<void*>((*found)->base));
}
return s;
}
// This is used by dlsym(3). It performs symbol lookup only within the
// specified soinfo object and its dependencies in breadth first order.
static const ElfW(Sym)* dlsym_handle_lookup(soinfo* si,
soinfo** found,
const char* name,
const version_info* vi) {
// According to man dlopen(3) and posix docs in the case when si is handle
// of the main executable we need to search not only in the executable and its
// dependencies but also in all libraries loaded with RTLD_GLOBAL.
//
// Since RTLD_GLOBAL is always set for the main executable and all dt_needed shared
// libraries and they are loaded in breath-first (correct) order we can just execute
// dlsym(RTLD_DEFAULT, ...); instead of doing two stage lookup.
if (si == solist_get_somain()) {
return dlsym_linear_lookup(&g_default_namespace, name, vi, found, nullptr, RTLD_DEFAULT);
}
SymbolName symbol_name(name);
// note that the namespace is not the namespace associated with caller_addr
// we use ns associated with root si intentionally here. Using caller_ns
// causes problems when user uses dlopen_ext to open a library in the separate
// namespace and then calls dlsym() on the handle.
return dlsym_handle_lookup_impl(si->get_primary_namespace(), si, nullptr, found, symbol_name, vi);
}
soinfo* find_containing_library(const void* p) {
// Addresses within a library may be tagged if they point to globals. Untag
// them so that the bounds check succeeds.
ElfW(Addr) address = reinterpret_cast<ElfW(Addr)>(untag_address(p));
for (soinfo* si = solist_get_head(); si != nullptr; si = si->next) {
if (address < si->base || address - si->base >= si->size) {
continue;
}
ElfW(Addr) vaddr = address - si->load_bias;
for (size_t i = 0; i != si->phnum; ++i) {
const ElfW(Phdr)* phdr = &si->phdr[i];
if (phdr->p_type != PT_LOAD) {
continue;
}
if (vaddr >= phdr->p_vaddr && vaddr < phdr->p_vaddr + phdr->p_memsz) {
return si;
}
}
}
return nullptr;
}
class ZipArchiveCache {
public:
ZipArchiveCache() {}
~ZipArchiveCache();
bool get_or_open(const char* zip_path, ZipArchiveHandle* handle);
private:
DISALLOW_COPY_AND_ASSIGN(ZipArchiveCache);
std::unordered_map<std::string, ZipArchiveHandle> cache_;
};
bool ZipArchiveCache::get_or_open(const char* zip_path, ZipArchiveHandle* handle) {
std::string key(zip_path);
auto it = cache_.find(key);
if (it != cache_.end()) {
*handle = it->second;
return true;
}
int fd = TEMP_FAILURE_RETRY(open(zip_path, O_RDONLY | O_CLOEXEC));
if (fd == -1) {
return false;
}
if (OpenArchiveFd(fd, "", handle) != 0) {
// invalid zip-file (?)
CloseArchive(*handle);
return false;
}
cache_[key] = *handle;
return true;
}
ZipArchiveCache::~ZipArchiveCache() {
for (const auto& it : cache_) {
CloseArchive(it.second);
}
}
static int open_library_in_zipfile(ZipArchiveCache* zip_archive_cache,
const char* const input_path,
off64_t* file_offset, std::string* realpath) {
std::string normalized_path;
if (!normalize_path(input_path, &normalized_path)) {
return -1;
}
const char* const path = normalized_path.c_str();
LD_DEBUG(any, "Trying zip file open from path \"%s\" -> normalized \"%s\"", input_path, path);
// Treat an '!/' separator inside a path as the separator between the name
// of the zip file on disk and the subdirectory to search within it.
// For example, if path is "foo.zip!/bar/bas/x.so", then we search for
// "bar/bas/x.so" within "foo.zip".
const char* const separator = strstr(path, kZipFileSeparator);
if (separator == nullptr) {
return -1;
}
char buf[512];
if (strlcpy(buf, path, sizeof(buf)) >= sizeof(buf)) {
DL_WARN("ignoring very long library path: %s", path);
return -1;
}
buf[separator - path] = '\0';
const char* zip_path = buf;
const char* file_path = &buf[separator - path + 2];
int fd = TEMP_FAILURE_RETRY(open(zip_path, O_RDONLY | O_CLOEXEC));
if (fd == -1) {
return -1;
}
ZipArchiveHandle handle;
if (!zip_archive_cache->get_or_open(zip_path, &handle)) {
// invalid zip-file (?)
close(fd);
return -1;
}
ZipEntry entry;
if (FindEntry(handle, file_path, &entry) != 0) {
// Entry was not found.
close(fd);
return -1;
}
// Check if it is properly stored
if (entry.method != kCompressStored || (entry.offset % page_size()) != 0) {
close(fd);
return -1;
}
*file_offset = entry.offset;
if (realpath_fd(fd, realpath)) {
*realpath += separator;
} else {
if (!is_first_stage_init()) {
DL_WARN("unable to get realpath for the library \"%s\". Will use given path.",
normalized_path.c_str());
}
*realpath = normalized_path;
}
return fd;
}
static bool format_path(char* buf, size_t buf_size, const char* path, const char* name) {
int n = async_safe_format_buffer(buf, buf_size, "%s/%s", path, name);
if (n < 0 || n >= static_cast<int>(buf_size)) {
DL_WARN("ignoring very long library path: %s/%s", path, name);
return false;
}
return true;
}
static int open_library_at_path(ZipArchiveCache* zip_archive_cache,
const char* path, off64_t* file_offset,
std::string* realpath) {