-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathelf_loader.cpp
More file actions
2139 lines (1782 loc) · 71.6 KB
/
Copy pathelf_loader.cpp
File metadata and controls
2139 lines (1782 loc) · 71.6 KB
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
#include "elf_loader.h"
#include "dlfcn.h"
#include "bionic_shim.h"
#include "glibc_shim.h"
#include "thread_tls.h"
#include <elf.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/auxv.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#include <algorithm>
#include <array>
#include <deque>
#include <map>
#include <memory>
#include <mutex>
#include <optional>
#include <stdexcept>
#include <string>
#include <string_view>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
using namespace dyn;
#ifndef DT_RELR
#define DT_RELR 36
#define DT_RELRSZ 35
#define DT_RELRENT 37
#endif
#ifndef DT_RUNPATH
#define DT_RUNPATH 29
#endif
#ifndef DT_FLAGS
#define DT_FLAGS 30
#endif
#ifndef DF_BIND_NOW
#define DF_BIND_NOW 0x8
#endif
#ifndef DF_SYMBOLIC
#define DF_SYMBOLIC 0x2
#endif
#ifndef DT_FLAGS_1
#define DT_FLAGS_1 0x6ffffffb
#endif
#ifndef DF_1_NOW
#define DF_1_NOW 0x1
#endif
// The dynamic relocations of the supported architectures under one set of
// names; numeric values, because libc elf.h coverage varies.
#if defined(__x86_64__)
#define ELF_MACHINE EM_X86_64
#define R_ARCH_ABS64 1 /* R_ARCH_ABS64 */
#define R_ARCH_GLOB_DAT 6
#define R_ARCH_JUMP_SLOT 7
#define R_ARCH_RELATIVE 8
#define R_ARCH_TLS_DTPMOD 16 /* R_ARCH_TLS_DTPMOD */
#define R_ARCH_TLS_DTPREL 17 /* R_ARCH_TLS_DTPREL */
#define R_ARCH_TLS_TPREL 18 /* R_ARCH_TLS_TPREL */
#define R_ARCH_TLSDESC 36
#define R_ARCH_IRELATIVE 37
#elif defined(__aarch64__)
#define ELF_MACHINE EM_AARCH64
#define R_ARCH_ABS64 257 /* R_AARCH64_ABS64 */
#define R_ARCH_GLOB_DAT 1025
#define R_ARCH_JUMP_SLOT 1026
#define R_ARCH_RELATIVE 1027
#define R_ARCH_TLS_DTPMOD 1028
#define R_ARCH_TLS_DTPREL 1029
#define R_ARCH_TLS_TPREL 1030
#define R_ARCH_TLSDESC 1031
#define R_ARCH_IRELATIVE 1032
#else
#error "unsupported architecture"
#endif
#ifndef STT_GNU_IFUNC
#define STT_GNU_IFUNC 10
#endif
namespace {
[[noreturn]] static void throwError(const char* format, ...) {
std::array<char, 1024> buffer;
va_list arguments;
va_start(arguments, format);
vsnprintf(buffer.data(), buffer.size(), format, arguments);
va_end(arguments);
throw std::runtime_error(buffer.data());
}
static uintptr_t alignDown(uintptr_t value, uintptr_t alignment) {
return value & ~(alignment - 1);
}
static uintptr_t alignUp(uintptr_t value, uintptr_t alignment) {
return (value + alignment - 1) & ~(alignment - 1);
}
static int segmentProtection(uint32_t flags) {
int protection = 0;
if (flags & PF_R) {
protection |= PROT_READ;
}
if (flags & PF_W) {
protection |= PROT_WRITE;
}
if (flags & PF_X) {
protection |= PROT_EXEC;
}
return protection;
}
// Surplus static TLS for initial-exec guests. An initial-exec GOT slot is
// one process-wide number added to every thread's own thread pointer, so
// the storage it names must sit at the same thread-pointer-relative
// offset in every thread. The arena is ordinary thread_local data of the
// host executable, which gives it exactly that property: unmodified musl
// lays out a copy per thread and seeds threads created later from the
// executable's TLS template, into which the loader writes each placed
// guest's own template. The sentinel byte keeps the arena in .tdata; an
// all-zero arena would land in .tbss, which has no template bytes to
// write guest initial values into.
constexpr size_t staticTlsSize = 16 * 1024;
constexpr size_t staticTlsAlignment = 64;
struct StaticTlsArena {
alignas(staticTlsAlignment) unsigned char bytes[staticTlsSize];
unsigned char sentinel;
};
thread_local StaticTlsArena staticTlsArena = {{}, 1};
// Finding the arena inside the executable's TLS template without
// re-deriving the linker's thread-pointer layout: search the template for
// this marker's bytes, then shift by the marker-to-arena distance, which
// is the same in the template and in every thread's copy of it.
thread_local unsigned char staticTlsMarker[16] = {
0x53, 0x6f, 0x4c, 0x6f, 0x9d, 0x11, 0xc4, 0x7e,
0x2a, 0x68, 0xb0, 0xf5, 0x3c, 0x81, 0xd6, 0x4b,
};
// An ifunc resolver call. The aarch64 ABI hands resolvers the hwcaps so
// they can pick an implementation without reading the auxv themselves;
// bit 62 of the first argument says the second one is present.
static uintptr_t resolveIfunc(uintptr_t resolver) {
#if defined(__x86_64__)
return reinterpret_cast<uintptr_t (*)()>(resolver)();
#elif defined(__aarch64__)
struct {
unsigned long size;
unsigned long hwcap;
unsigned long hwcap2;
} arguments = {
sizeof(arguments),
getauxval(AT_HWCAP),
getauxval(AT_HWCAP2),
};
return reinterpret_cast<uintptr_t (*)(unsigned long, const void*)>(resolver)(arguments.hwcap | (1UL << 62), &arguments);
#endif
}
static uintptr_t threadPointer() {
uintptr_t pointer;
#if defined(__x86_64__)
// musl keeps the pthread self pointer, whose value is the thread
// pointer itself, at %fs:0.
__asm__("mov %%fs:0, %0" : "=r"(pointer));
#elif defined(__aarch64__)
__asm__("mrs %0, tpidr_el0" : "=r"(pointer));
#endif
return pointer;
}
struct File {
explicit File(const std::string& path);
~File();
void read(void* destination, size_t size, off_t offset) const;
int descriptor_;
};
struct LinkMap;
struct Definition {
uintptr_t address = 0;
LinkMap* image = nullptr;
Elf64_Sym* symbol = nullptr;
explicit operator bool() const noexcept;
};
struct Dependency {
std::string name;
void* handle = nullptr;
LinkMap* image = nullptr;
};
struct TlsDescArgument {
const LinkMap* image;
uintptr_t offset;
};
struct LinkMap {
enum class State {
Loading,
Ready,
Failed,
};
std::string path;
std::string soname;
// The image's library search paths with $ORIGIN substituted; per the
// ld.so rules at most one of the two is in effect.
std::string rpath;
std::string runPath;
uintptr_t base = 0;
uintptr_t mapStart = 0;
size_t mapSize = 0;
std::vector<Elf64_Phdr> programHeaders;
Elf64_Dyn* dynamic = nullptr;
const char* strings = nullptr;
size_t stringsSize = 0;
Elf64_Sym* symbols = nullptr;
size_t symbolCount = 0;
uint32_t* gnuHash = nullptr;
uint32_t* sysvHash = nullptr;
Elf64_Half* symbolVersions = nullptr;
std::vector<std::string_view> versionNames;
std::vector<Dependency> dependencies;
bool glibcAbi = false;
bool bionicAbi = false;
Elf64_Rela* relocations = nullptr;
size_t relocationCount = 0;
Elf64_Rela* pltRelocations = nullptr;
size_t pltRelocationCount = 0;
Elf64_Addr* relativeRelocations = nullptr;
size_t relativeRelocationCount = 0;
uintptr_t pltGot = 0;
bool bindNow = false;
// DT_SYMBOLIC / -Bsymbolic: the image's own definitions win for its
// own references.
bool symbolic = false;
// RTLD_DEEPBIND: the local dependency closure is searched before the
// global scope instead of after it.
bool deepBind = false;
uintptr_t initializer = 0;
uintptr_t initializerArray = 0;
size_t initializerCount = 0;
uintptr_t finalizer = 0;
uintptr_t finalizerArray = 0;
size_t finalizerCount = 0;
uintptr_t relroStart = 0;
size_t relroSize = 0;
size_t tlsModule = 0;
uintptr_t tlsTemplate = 0;
size_t tlsFileSize = 0;
size_t tlsMemorySize = 0;
size_t tlsAlignment = 0;
// Thread-pointer-relative offset of the module's block in the static
// TLS arena: negative on x86-64 (TLS below the thread pointer),
// positive on aarch64 (above it), and never 0, which marks modules
// served from the dynamic per-thread blocks instead.
intptr_t staticTlsOffset = 0;
std::unique_ptr<ElfImage> wrapper;
State state = State::Loading;
void parseDynamic();
void parseVersions(uintptr_t needAddress, size_t needCount, uintptr_t definitionAddress, size_t definitionCount);
void setVersionName(size_t index, size_t nameOffset);
size_t countSymbols() const noexcept;
std::string substituteOrigin(std::string_view directories) const;
std::string_view symbolVersion(size_t symbolIndex) const noexcept;
Definition findSymbol(const std::string_view& name, const std::string_view& version) noexcept;
Definition matchSymbol(size_t index, const std::string_view& name, const std::string_view& version) noexcept;
void* tlsAddress(size_t offset) const;
void applyRelativeRelocations();
void protect();
void applyRelro();
void runInitializers();
void runFinalizers();
};
struct DeferredRelocation {
LinkMap* image;
const Elf64_Rela* relocation;
};
struct MarkFailed {
explicit MarkFailed(LinkMap& image);
~MarkFailed();
LinkMap& image_;
};
// The image whose DT_NEEDED list is being resolved, for its search paths.
// Nested loads save and restore the previous requester.
struct ScopedRequester {
ScopedRequester(LinkMap*& slot, LinkMap& image);
~ScopedRequester();
LinkMap*& slot_;
LinkMap* previous_;
};
struct StringHash {
using is_transparent = void;
size_t operator()(const std::string_view& value) const noexcept;
};
extern "C" uintptr_t elfTlsDescEntry();
extern "C" uintptr_t elfPltResolveEntry();
struct Loader {
Loader();
static Loader& instance();
LinkMap* load(const std::string_view& requestedPath, int flags);
void runPendingInitializers();
void* lookup(LinkMap& image, std::string_view name, std::string_view version);
void* lookupGlobal(std::string_view name);
void* lookupNext(const void* caller, std::string_view name, std::string_view version);
void makeGlobal(LinkMap& image);
bool findAddress(const void* address, ElfAddress* res);
int iterateProgramHeaders(ElfProgramHeaderCallback& callback);
LinkMap* findByName(const std::string_view& name) const noexcept;
LinkMap* findByPath(const std::string& path) const noexcept;
static std::optional<std::string> realPath(const std::string& path);
static std::optional<std::string> inDirectory(const std::string_view& directory, const std::string_view& name);
static std::optional<std::string> inSearchPath(std::string_view directories, const std::string_view& name, bool emptyIsCurrentDirectory);
static std::optional<std::string> inCache(const std::string_view& name);
std::optional<std::string> resolvePath(const std::string_view& path) const;
void rememberLibraryDirectory(const std::string& path);
size_t addTlsModule();
void initializeStaticTls();
void allocateStaticTls(LinkMap& image);
static bool isGlibcDependency(const std::string_view& name) noexcept;
void loadDependencies(LinkMap& image);
static Definition searchScope(LinkMap& image, const std::string_view& name, const std::string_view& version);
Definition resolveSymbol(LinkMap& image, size_t symbolIndex);
void debugBinding(const LinkMap& image, const std::string_view& name, const char* provider) const;
static void* materialize(Definition definition);
bool applyRelocation(LinkMap& image, const Elf64_Rela& relocation, bool allowIfunc);
void applyRelocations(LinkMap& image, std::vector<DeferredRelocation>& deferred, bool lazy);
void* pltResolve(LinkMap& image, size_t index);
static void runAllFinalizers();
std::recursive_mutex mutex_;
std::vector<std::unique_ptr<LinkMap>> images_;
std::unordered_map<std::string, LinkMap*, StringHash, std::equal_to<>> imagesByName_;
std::map<uintptr_t, LinkMap*> imagesByAddress_;
size_t tlsModuleCount_ = 0;
// The arena's thread-pointer-relative offset, its bytes inside the
// executable's TLS template, and the bump allocator's high mark.
intptr_t staticTlsArenaOffset_ = 0;
unsigned char* staticTlsTemplate_ = nullptr;
size_t staticTlsUsed_ = 0;
std::string libraryDirectory_;
LinkMap* requester_ = nullptr;
std::vector<LinkMap*> pendingInitializers_;
bool bindNow_ = false;
bool debugLibs_ = false;
bool debugBindings_ = false;
// Images whose symbols every later relocation may use, in load order.
std::vector<LinkMap*> globalImages_;
};
struct LoadedElf final: public ElfImage {
explicit LoadedElf(LinkMap& image);
void* lookup(std::string_view symbol) const override;
void* lookupVersion(std::string_view symbol, std::string_view version) const override;
std::string_view path() const override;
uintptr_t base() const override;
const void* dynamicSection() const override;
LinkMap& image_;
};
}
File::File(const std::string& path)
: descriptor_(open(path.c_str(), O_RDONLY | O_CLOEXEC))
{
if (descriptor_ < 0) {
throwError("open(%s): %s", path.c_str(), strerror(errno));
}
}
File::~File() {
if (descriptor_ >= 0) {
close(descriptor_);
}
}
void File::read(void* destination, size_t size, off_t offset) const {
auto* cursor = static_cast<unsigned char*>(destination);
while (size) {
auto result = pread(descriptor_, cursor, size, offset);
if (result < 0 && errno == EINTR) {
continue;
}
if (result <= 0) {
throwError("pread: %s", result ? strerror(errno) : "unexpected EOF");
}
cursor += result;
size -= result;
offset += result;
}
}
Definition::operator bool() const noexcept {
return address != 0;
}
size_t StringHash::operator()(const std::string_view& value) const noexcept {
return std::hash<std::string_view>()(value);
}
MarkFailed::MarkFailed(LinkMap& image)
: image_(image)
{
}
MarkFailed::~MarkFailed() {
if (image_.state == LinkMap::State::Loading) {
image_.state = LinkMap::State::Failed;
}
}
ScopedRequester::ScopedRequester(LinkMap*& slot, LinkMap& image)
: slot_(slot)
, previous_(slot)
{
slot_ = ℑ
}
ScopedRequester::~ScopedRequester() {
slot_ = previous_;
}
// Registered before any loaded DSO can register its own atexit handlers, so
// like glibc's _dl_fini it runs after them.
Loader::Loader() {
bindNow_ = getenv("LD_BIND_NOW") != nullptr;
if (const auto* debug = getenv("DL_DEBUG"); debug) {
std::string_view flags(debug);
debugLibs_ = flags.find("libs") != std::string_view::npos || flags == "all";
debugBindings_ = flags.find("bindings") != std::string_view::npos || flags == "all";
}
initializeStaticTls();
atexit(runAllFinalizers);
}
Loader& Loader::instance() {
static auto* loader = new Loader();
return *loader;
}
LinkMap* Loader::load(const std::string_view& requestedPath, int flags) {
std::lock_guard lock(mutex_);
if (requestedPath.empty()) {
throwError("empty ELF image path");
}
if (auto* image = findByName(requestedPath); image) {
if (image->state == LinkMap::State::Failed) {
throwError("%s: a previous load failed", image->path.c_str());
}
if (flags & RTLD_GLOBAL) {
makeGlobal(*image);
}
return image;
}
auto resolved = resolvePath(requestedPath);
if (!resolved) {
throwError("cannot resolve ELF image: %.*s", static_cast<int>(requestedPath.size()), requestedPath.data());
}
if (auto* image = findByPath(*resolved); image) {
if (image->state == LinkMap::State::Failed) {
throwError("%s: a previous load failed", image->path.c_str());
}
if (flags & RTLD_GLOBAL) {
makeGlobal(*image);
}
return image;
}
if (flags & RTLD_NOLOAD) {
throwError("%s: image is not loaded", resolved->c_str());
}
rememberLibraryDirectory(*resolved);
File file(*resolved);
Elf64_Ehdr header;
file.read(&header, sizeof(header), 0);
if (memcmp(header.e_ident, ELFMAG, SELFMAG) != 0 || header.e_ident[EI_CLASS] != ELFCLASS64 || header.e_ident[EI_DATA] != ELFDATA2LSB || header.e_machine != ELF_MACHINE || header.e_type != ET_DYN || header.e_phentsize != sizeof(Elf64_Phdr)) {
throwError("%s: not an ET_DYN ELF for this machine", resolved->c_str());
}
auto imageOwner = std::make_unique<LinkMap>();
auto& image = *imageOwner;
image.path = *resolved;
image.programHeaders.resize(header.e_phnum);
file.read(image.programHeaders.data(), image.programHeaders.size() * sizeof(Elf64_Phdr), static_cast<off_t>(header.e_phoff));
auto pageSize = sysconf(_SC_PAGESIZE);
if (pageSize <= 0) {
throwError("%s: cannot determine page size", image.path.c_str());
}
uintptr_t minimumAddress = UINTPTR_MAX;
uintptr_t maximumAddress = 0;
for (const auto& programHeader : image.programHeaders) {
if (programHeader.p_type != PT_LOAD) {
continue;
}
auto start = alignDown(programHeader.p_vaddr, pageSize);
auto end = alignUp(programHeader.p_vaddr + programHeader.p_memsz, pageSize);
minimumAddress = std::min(minimumAddress, start);
maximumAddress = std::max(maximumAddress, end);
}
if (minimumAddress == UINTPTR_MAX || maximumAddress <= minimumAddress) {
throwError("%s: no loadable segments", image.path.c_str());
}
image.mapSize = maximumAddress - minimumAddress;
// A reservation for the whole span; the segments are mapped into it from
// the file below.
auto* mapping = mmap(nullptr, image.mapSize, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (mapping == MAP_FAILED) {
throwError("%s: mmap: %s", image.path.c_str(), strerror(errno));
}
image.mapStart = reinterpret_cast<uintptr_t>(mapping);
image.base = image.mapStart - minimumAddress;
auto* imagePointer = ℑ
images_.push_back(std::move(imageOwner));
imagesByName_.emplace(image.path, &image);
imagesByName_.emplace(std::string(requestedPath), &image);
imagesByAddress_.emplace(image.mapStart, &image);
MarkFailed markFailed(image);
for (const auto& programHeader : image.programHeaders) {
if (programHeader.p_type == PT_LOAD) {
if (programHeader.p_filesz > programHeader.p_memsz) {
throwError("%s: PT_LOAD file size exceeds memory size", image.path.c_str());
}
if ((programHeader.p_vaddr - programHeader.p_offset) % pageSize) {
throwError("%s: PT_LOAD file offset is not congruent with its address", image.path.c_str());
}
// The segments map from the file, copy-on-write: untouched pages
// stay shared with the page cache, and /proc/self/maps names the
// library for debuggers and profilers. Everything is writable
// until protect() runs, so relocations just work.
auto start = alignDown(image.base + programHeader.p_vaddr, pageSize);
auto fileEnd = image.base + programHeader.p_vaddr + programHeader.p_filesz;
auto memoryEnd = alignUp(image.base + programHeader.p_vaddr + programHeader.p_memsz, pageSize);
if (programHeader.p_filesz) {
if (mmap(reinterpret_cast<void*>(start), alignUp(fileEnd, pageSize) - start, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_FIXED, file.descriptor_, static_cast<off_t>(alignDown(programHeader.p_offset, pageSize))) == MAP_FAILED) {
throwError("%s: mmap segment: %s", image.path.c_str(), strerror(errno));
}
}
if (programHeader.p_memsz > programHeader.p_filesz) {
// The zero-fill tail: the rest of the last file page by hand,
// fresh anonymous pages beyond it.
auto anonymousStart = start;
if (programHeader.p_filesz) {
anonymousStart = alignUp(fileEnd, pageSize);
memset(reinterpret_cast<void*>(fileEnd), 0, anonymousStart - fileEnd);
}
if (anonymousStart < memoryEnd && mmap(reinterpret_cast<void*>(anonymousStart), memoryEnd - anonymousStart, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0) == MAP_FAILED) {
throwError("%s: mmap zero fill: %s", image.path.c_str(), strerror(errno));
}
}
} else if (programHeader.p_type == PT_DYNAMIC) {
image.dynamic = reinterpret_cast<Elf64_Dyn*>(image.base + programHeader.p_vaddr);
} else if (programHeader.p_type == PT_GNU_RELRO) {
image.relroStart = programHeader.p_vaddr;
image.relroSize = programHeader.p_memsz;
} else if (programHeader.p_type == PT_TLS) {
image.tlsModule = addTlsModule();
image.tlsTemplate = image.base + programHeader.p_vaddr;
image.tlsFileSize = programHeader.p_filesz;
image.tlsMemorySize = programHeader.p_memsz;
image.tlsAlignment = programHeader.p_align;
}
}
if (!image.dynamic) {
throwError("%s: missing PT_DYNAMIC", image.path.c_str());
}
if (image.tlsModule) {
allocateStaticTls(image);
}
image.parseDynamic();
if (!image.soname.empty()) {
imagesByName_.emplace(image.soname, &image);
}
loadDependencies(image);
image.deepBind = (flags & RTLD_DEEPBIND) != 0;
std::vector<DeferredRelocation> deferred;
auto lazy = !(flags & RTLD_NOW) && !image.bindNow && !bindNow_;
applyRelocations(image, deferred, lazy);
image.protect();
for (const auto& item : deferred) {
applyRelocation(*item.image, *item.relocation, true);
}
image.applyRelro();
image.wrapper.reset(new LoadedElf(image));
image.state = LinkMap::State::Ready;
if (flags & RTLD_GLOBAL) {
makeGlobal(image);
}
if (debugLibs_) {
fprintf(stderr, "solo: loaded %s at %#lx%s\n", image.path.c_str(), image.base, lazy ? " (lazy)" : "");
}
pendingInitializers_.push_back(&image);
return imagePointer;
}
// Initializers run without the loader mutex, so a thread an initializer
// spawns can enter the loader; the queue is drained by the public entry once
// the outermost load released the lock.
void Loader::runPendingInitializers() {
for (;;) {
LinkMap* image = nullptr;
{
std::lock_guard lock(mutex_);
if (pendingInitializers_.empty()) {
return;
}
image = pendingInitializers_.front();
pendingInitializers_.erase(pendingInitializers_.begin());
}
image->runInitializers();
}
}
// RTLD_GLOBAL publishes the image's whole local scope, so the global search
// list grows by the dependency closure in breadth-first order, like ld.so.
void Loader::makeGlobal(LinkMap& image) {
std::deque<LinkMap*> queue({&image});
while (!queue.empty()) {
auto* current = queue.front();
queue.pop_front();
if (std::find(globalImages_.begin(), globalImages_.end(), current) != globalImages_.end()) {
continue;
}
globalImages_.push_back(current);
for (const auto& dependency : current->dependencies) {
if (dependency.image) {
queue.push_back(dependency.image);
}
}
}
}
void* Loader::lookupGlobal(std::string_view name) {
std::lock_guard lock(mutex_);
for (auto* image : globalImages_) {
if (auto definition = image->findSymbol(name, {}); definition) {
return materialize(definition);
}
}
return nullptr;
}
void* Loader::lookupNext(const void* caller, std::string_view name, std::string_view version) {
std::lock_guard lock(mutex_);
auto needle = reinterpret_cast<uintptr_t>(caller);
bool after = false;
for (const auto& image : images_) {
if (!after) {
after = needle >= image->mapStart && needle < image->mapStart + image->mapSize;
continue;
}
if (image->state != LinkMap::State::Ready) {
continue;
}
if (auto definition = image->findSymbol(name, version); definition) {
return materialize(definition);
}
}
return nullptr;
}
void* Loader::lookup(LinkMap& image, std::string_view name, std::string_view version) {
std::lock_guard lock(mutex_);
return materialize(searchScope(image, name, version));
}
// Breadth-first over the image and its dependency closure, in load order at
// each depth, matching the search order of ld.so. A dependency backed by a
// static provider is probed at its depth through its handle.
Definition Loader::searchScope(LinkMap& image, const std::string_view& name, const std::string_view& version) {
if (auto definition = image.findSymbol(name, version); definition) {
return definition;
}
std::unordered_set<LinkMap*> visited({&image});
std::deque<const Dependency*> queue;
auto enqueue = [&](const LinkMap& parent) {
for (const auto& dependency : parent.dependencies) {
if (!dependency.image || visited.insert(dependency.image).second) {
queue.push_back(&dependency);
}
}
};
std::string symbol(name);
enqueue(image);
while (!queue.empty()) {
const auto* dependency = queue.front();
queue.pop_front();
if (!dependency->image) {
if (auto* address = stub_dlsym(dependency->handle, symbol.c_str()); address) {
return {reinterpret_cast<uintptr_t>(address), nullptr, nullptr};
}
stub_dlerror();
continue;
}
if (auto definition = dependency->image->findSymbol(name, version); definition) {
return definition;
}
enqueue(*dependency->image);
}
return {};
}
// Touches only the caller's ThreadTls and the image's immutable TLS metadata,
// so a thread spawned by an initializer can reach its TLS while the loader
// mutex is still held.
void* LinkMap::tlsAddress(size_t offset) const {
if (offset >= tlsMemorySize) {
throwError("%s: TLS offset %zu exceeds size %zu", path.c_str(), offset, tlsMemorySize);
}
// A module placed in the static arena must be served from it through
// every TLS model, or general-dynamic and initial-exec accesses to the
// same variable would see different memory.
if (staticTlsOffset) {
return reinterpret_cast<unsigned char*>(threadPointer() + staticTlsOffset) + offset;
}
auto* slot = ThreadTls::current()->tlsBlock(tlsModule);
if (!*slot) {
auto alignment = std::max(tlsAlignment, sizeof(void*));
void* block = nullptr;
if (posix_memalign(&block, alignment, tlsMemorySize)) {
throwError("%s: cannot allocate TLS block", path.c_str());
}
memset(block, 0, tlsMemorySize);
memcpy(block, reinterpret_cast<const void*>(tlsTemplate), tlsFileSize);
*slot = block;
}
return static_cast<unsigned char*>(*slot) + offset;
}
bool Loader::findAddress(const void* address, ElfAddress* res) {
std::lock_guard lock(mutex_);
auto needle = reinterpret_cast<uintptr_t>(address);
auto found = imagesByAddress_.upper_bound(needle);
if (found == imagesByAddress_.begin()) {
return false;
}
--found;
const auto& image = *found->second;
if (needle >= image.mapStart + image.mapSize) {
return false;
}
*res = ElfAddress{
image.path,
reinterpret_cast<void*>(image.base),
};
// The nearest defined symbol whose storage covers the address.
uintptr_t best = 0;
for (size_t index = 0; index < image.symbolCount; ++index) {
const auto& symbol = image.symbols[index];
auto type = ELF64_ST_TYPE(symbol.st_info);
if (symbol.st_shndx == SHN_UNDEF || (type != STT_FUNC && type != STT_OBJECT && type != STT_GNU_IFUNC)) {
continue;
}
auto start = image.base + symbol.st_value;
if (needle < start || start < best || symbol.st_name >= image.stringsSize) {
continue;
}
if (symbol.st_size ? needle >= start + symbol.st_size : needle != start) {
continue;
}
best = start;
res->symbol = image.strings + symbol.st_name;
res->symbolAddress = reinterpret_cast<void*>(start);
}
return true;
}
int Loader::iterateProgramHeaders(ElfProgramHeaderCallback& callback) {
std::vector<LinkMap*> images;
{
std::lock_guard lock(mutex_);
images.reserve(images_.size());
for (const auto& image : images_) {
if (image->state == LinkMap::State::Ready) {
images.push_back(image.get());
}
}
}
for (const auto* image : images) {
void* tlsData = nullptr;
if (image->staticTlsOffset) {
tlsData = reinterpret_cast<void*>(threadPointer() + image->staticTlsOffset);
} else if (image->tlsModule) {
tlsData = *ThreadTls::current()->tlsBlock(image->tlsModule);
}
const ElfProgramHeaders headers{
image->path.c_str(),
image->base,
image->programHeaders.data(),
static_cast<Elf64_Half>(image->programHeaders.size()),
image->tlsModule,
tlsData,
};
if (const int result = callback.call(headers); result) {
return result;
}
}
return 0;
}
LinkMap* Loader::findByName(const std::string_view& name) const noexcept {
if (auto image = imagesByName_.find(name); image != imagesByName_.end()) {
return image->second;
}
return nullptr;
}
LinkMap* Loader::findByPath(const std::string& path) const noexcept {
return findByName(path);
}
std::optional<std::string> Loader::realPath(const std::string& path) {
std::array<char, PATH_MAX> resolved;
if (!realpath(path.c_str(), resolved.data())) {
return std::nullopt;
}
return std::string(resolved.data());
}
std::optional<std::string> Loader::inDirectory(const std::string_view& directory, const std::string_view& name) {
std::string candidate(directory);
if (!candidate.empty() && candidate.back() != '/') {
candidate.push_back('/');
}
candidate.append(name);
return realPath(candidate);
}
std::optional<std::string> Loader::inSearchPath(std::string_view directories, const std::string_view& name, bool emptyIsCurrentDirectory) {
while (true) {
auto separator = directories.find(':');
auto directory = directories.substr(0, separator);
if (!directory.empty() || emptyIsCurrentDirectory) {
if (auto resolved = inDirectory(directory.empty() ? "." : directory, name); resolved) {
return resolved;
}
}
if (separator == std::string_view::npos) {
return std::nullopt;
}
directories.remove_prefix(separator + 1);
}
}
// ldconfig's /etc/ld.so.cache, in the standalone new format: a header, an
// entry table, and a string table the entries' offsets index from the start
// of the file. This is how ld.so.conf.d directories reach us without parsing
// the configuration ourselves.
std::optional<std::string> Loader::inCache(const std::string_view& name) {
struct Header {
char magic[17];
char version[3];
uint32_t count;
uint32_t stringsLength;
uint8_t flags;
uint8_t padding[3];
uint32_t extensionOffset;
uint32_t unused[3];
};
struct Entry {
int32_t flags;
uint32_t key;
uint32_t value;