-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathelf_loader.cpp
More file actions
2707 lines (2270 loc) · 93.4 KB
/
Copy pathelf_loader.cpp
File metadata and controls
2707 lines (2270 loc) · 93.4 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 "musl_tls.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 MAP_FIXED_NOREPLACE
#define MAP_FIXED_NOREPLACE 0x100000
#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_COPY 5
#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_COPY 1024
#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;
}
// 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 {
// Loading covers the mapping and parsing of the image itself; Mapped
// means the image sits in the current closure, symbols findable,
// relocations still pending — ld.so maps a whole dependency closure
// breadth-first before relocating any of it.
enum class State {
Loading,
Mapped,
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;
// The image's slot in the dlopen caller-thunk pool, assigned on the
// first relocation of its dlopen or dlmopen import.
int callerThunkIndex = -1;
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;
// The main guest executable: its entry point and mapped program
// headers feed the auxiliary vector, and its initializers wait for
// the bridge's __libc_start_main instead of the load-time queue.
bool executable = false;
uintptr_t entry = 0;
uintptr_t programHeadersAddress = 0;
uintptr_t preinitializerArray = 0;
size_t preinitializerCount = 0;
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;
// DT_TEXTREL: relocations land in read-only segments, glibc-style
// mprotect dance around the relocation pass.
bool textRelocations = false;
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 window: 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;
// How the image was requested, for the relocation phase: the dlopen
// flags, and whether the kernel mapped the segments (an adopted
// executable keeps the kernel's protections).
int requestFlags = 0;
bool adopted = false;
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 unprotect();
void applyRelro();
void runInitializers();
void runFinalizers();
};
struct DeferredRelocation {
LinkMap* image;
const Elf64_Rela* relocation;
};
struct MarkFailed {
explicit MarkFailed(LinkMap& image);
~MarkFailed();
LinkMap& image_;
};
// Held under the loader lock for the whole of a load; the counter tells
// reentered public entries that the closure is not complete yet.
struct LoadDepth {
explicit LoadDepth(size_t& depth);
~LoadDepth();
size_t& depth_;
};
// 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, LinkMap* dlopenCaller);
LinkMap* adopt(const char* path, const Elf64_Phdr* headers, size_t count, uintptr_t entry);
void prepareImage(LinkMap& image, int flags, bool adopted);
void completeImage(LinkMap& image);
void orderForRelocation(LinkMap& image, std::vector<LinkMap*>& order, std::unordered_set<const LinkMap*>& placed);
void linkClosure();
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);
void* callerThunk(LinkMap& image, bool dlmopen);
LinkMap* callerImage(unsigned index);
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 LinkMap* dlopenCaller) const;
void rememberLibraryDirectory(const std::string& path);
size_t addTlsModule();
void allocateStaticTls(LinkMap& image);
void seedStaticTls(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, bool skipSelf);
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;
std::string libraryDirectory_;
LinkMap* requester_ = nullptr;
// Consumed by the next load(): it is loading the main guest
// executable, not a shared object.
bool loadingExecutable_ = false;
// Loads in flight on this thread's recursive lock; initializers wait
// for the outermost one to finish relocating the whole closure.
size_t loadDepth_ = 0;
// The closure the outermost load is assembling, in breadth-first
// mapping order; relocated back-to-front once complete.
std::vector<LinkMap*> closure_;
LinkMap* mainExecutable_ = 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_;
// The images behind the numbered dlopen caller thunks; write-once
// slots, published before the thunk address escapes.
std::array<LinkMap*, 512> callerImages_{};
size_t callerCount_ = 0;
};
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;
}
}
LoadDepth::LoadDepth(size_t& depth)
: depth_(depth)
{
++depth_;
}
LoadDepth::~LoadDepth() {
--depth_;
}
ScopedRequester::ScopedRequester(LinkMap*& slot, LinkMap& image)
: slot_(slot)
, previous_(slot)
{
slot_ = ℑ
}
ScopedRequester::~ScopedRequester() {
slot_ = previous_;
}
bool dyn::secureExecution() {
static const bool secure = [] {
errno = 0;
if (getauxval(AT_SECURE)) {
return true;
}
if (errno != ENOENT) {
// The auxv answered: the kernel says not secure.
return false;
}
return getuid() != geteuid() || getgid() != getegid();
}();
return secure;
}
bool dyn::traceLoadedObjects() {
static const bool enabled = !secureExecution() && getenv("LD_TRACE_LOADED_OBJECTS");
return enabled;
}
// Each provided name prints once, like ldd's one line per object; callers
// arrive both under the loader mutex and outside it.
void dyn::traceProvider(std::string_view name, const char* provider) {
static std::mutex tracedMutex;
static std::unordered_set<std::string> traced;
if (!traceLoadedObjects()) {
return;
}
std::lock_guard lock(tracedMutex);
if (traced.emplace(name).second) {
fprintf(stdout, "\t%.*s => %s\n", static_cast<int>(name.size()), name.data(), provider);
}
}
bool dyn::debugFlag(std::string_view flag) {
static const std::string flags = [] {
const auto* debug = secureExecution() ? nullptr : getenv("LD_DEBUG");
return std::string(debug ? debug : "");
}();
std::string_view remaining(flags);
while (!remaining.empty()) {
auto comma = remaining.find(',');
auto entry = remaining.substr(0, comma);
remaining.remove_prefix(comma == std::string_view::npos ? remaining.size() : comma + 1);
if (entry == flag || entry == "all") {
return true;
}
}
return false;
}
// 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;
debugLibs_ = debugFlag("libs");
debugBindings_ = debugFlag("bindings");
atexit(runAllFinalizers);
}
Loader& Loader::instance() {
static auto* loader = new Loader();
return *loader;
}
LinkMap* Loader::load(const std::string_view& requestedPath, int flags, LinkMap* dlopenCaller) {
std::lock_guard lock(mutex_);
LoadDepth depth(loadDepth_);
// The flag names only the outermost load; the dependencies this load
// pulls in are ordinary shared objects.
auto asExecutable = std::exchange(loadingExecutable_, false);
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, dlopenCaller);
if (!resolved) {
traceProvider(requestedPath, "not found");
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);
// Shared objects are ET_DYN; the main guest executable may equally be a
// non-PIE ET_EXEC, which owns its link-time addresses.
auto validType = header.e_type == ET_DYN || (asExecutable && header.e_type == ET_EXEC);
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 || !validType || 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. An ET_EXEC image must land exactly on its link-time
// addresses, and an occupied range there is a hard error — nothing can
// relocate it. This is why solo itself links static-PIE: its own image
// randomizes away from the low addresses such guests own.
auto* desired = header.e_type == ET_EXEC ? reinterpret_cast<void*>(minimumAddress) : nullptr;
auto* mapping = mmap(desired, image.mapSize, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS | (desired ? MAP_FIXED_NOREPLACE : 0), -1, 0);
if (mapping == MAP_FAILED) {
throwError("%s: mmap%s: %s", image.path.c_str(), desired ? " at the fixed load addresses" : "", strerror(errno));
}
// A kernel too old for MAP_FIXED_NOREPLACE ignores the flag and treats
// the address as a hint; a reservation that landed elsewhere is as fatal
// as a refused one.
if (desired && mapping != desired) {
munmap(mapping, image.mapSize);
throwError("%s: the fixed load addresses %#zx-%#zx are already occupied", image.path.c_str(), minimumAddress, maximumAddress);
}
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);
// ldd lists the objects an executable pulls in, never the executable
// itself.
if (traceLoadedObjects() && !asExecutable) {
fprintf(stdout, "\t%.*s => %s (0x%zx)\n", static_cast<int>(requestedPath.size()), requestedPath.data(), image.path.c_str(), image.mapStart);
}
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, each with its
// final protections straight away — ld.so's discipline.
// Relocations only ever touch writable segments, so nothing
// needs a writable-then-executable transition and a sandbox
// that forbids one (MemoryDenyWriteExecute) stays satisfied;
// the rare DT_TEXTREL image gets glibc's mprotect dance at
// relocation time instead. /proc/self/maps names the library
// for debuggers and profilers.
auto protection = segmentProtection(programHeader.p_flags);
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, protection, 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 — only a writable segment can carry one — and fresh
// anonymous pages beyond it.
auto anonymousStart = start;
if (programHeader.p_filesz) {
anonymousStart = alignUp(fileEnd, pageSize);
if (protection & PROT_WRITE) {
memset(reinterpret_cast<void*>(fileEnd), 0, anonymousStart - fileEnd);
}
}
if (anonymousStart < memoryEnd && mmap(reinterpret_cast<void*>(anonymousStart), memoryEnd - anonymousStart, protection, 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 (asExecutable) {
image.executable = true;
image.entry = image.base + header.e_entry;
// What the kernel would publish as AT_PHDR: the program header table
// inside the mapped image, by PT_PHDR when the link editor recorded
// one, by the ELF header's table offset otherwise.
image.programHeadersAddress = image.base + header.e_phoff;
for (const auto& programHeader : image.programHeaders) {
if (programHeader.p_type == PT_PHDR) {
image.programHeadersAddress = image.base + programHeader.p_vaddr;
}
}
}
prepareImage(image, flags, false);
if (loadDepth_ == 1) {
linkClosure();
}
return imagePointer;
}
// The guest the kernel already mapped, solo running as its PT_INTERP: the
// auxiliary vector's program headers, entry point, and execution path stand
// in for the file. The segments are in place with their final protections;
// everything after the mapping is the same back half a loaded image takes.
LinkMap* Loader::adopt(const char* path, const Elf64_Phdr* headers, size_t count, uintptr_t entry) {
std::lock_guard lock(mutex_);
LoadDepth depth(loadDepth_);
if (!headers || !count) {
throwError("the auxiliary vector describes no program headers to adopt");
}
auto imageOwner = std::make_unique<LinkMap>();
auto& image = *imageOwner;
image.path = realPath(path).value_or(path);
rememberLibraryDirectory(image.path);
// The load bias, anchored by PT_PHDR: the table's runtime address is in
// hand, and the entry names its link-time one. Every dynamically linked
// executable carries the entry — the link editor emits it alongside
// PT_INTERP, and only a guest with an interpreter can arrive here.
auto biasKnown = false;
image.programHeaders.assign(headers, headers + count);
for (const auto& programHeader : image.programHeaders) {
if (programHeader.p_type == PT_PHDR) {
image.base = reinterpret_cast<uintptr_t>(headers) - programHeader.p_vaddr;
biasKnown = true;
}
}
if (!biasKnown) {
throwError("%s: the kernel-mapped executable has no PT_PHDR to anchor its load base", image.path.c_str());
}
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) {
minimumAddress = std::min(minimumAddress, alignDown(programHeader.p_vaddr, pageSize));
maximumAddress = std::max(maximumAddress, alignUp(programHeader.p_vaddr + programHeader.p_memsz, pageSize));
} 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 (minimumAddress == UINTPTR_MAX || maximumAddress <= minimumAddress) {
throwError("%s: no loadable segments", image.path.c_str());
}
image.mapStart = image.base + minimumAddress;
image.mapSize = maximumAddress - minimumAddress;
image.executable = true;
image.entry = entry;
image.programHeadersAddress = reinterpret_cast<uintptr_t>(headers);
auto* imagePointer = ℑ
images_.push_back(std::move(imageOwner));
imagesByName_.emplace(image.path, &image);
imagesByName_.emplace(std::string(path), &image);
imagesByAddress_.emplace(image.mapStart, &image);
MarkFailed markFailed(image);
prepareImage(image, RTLD_GLOBAL, true);
if (loadDepth_ == 1) {
linkClosure();
}
return imagePointer;
}
// The mapped image's front half: parsed, named, and queued into the current
// closure. Its dependencies are not touched here — the closure maps
// breadth-first, so every requester's DT_NEEDED list lands before any
// dependency's own list resolves.
void Loader::prepareImage(LinkMap& image, int flags, bool adopted) {
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);
}
// The executable leads every scope ld.so would build, and it must lead
// it already while the dependencies relocate: their references to a
// COPY-relocated global — rpm's option state, glibc's stdout — have to
// bind to the executable's copy, not to the library's own definition.
// Symbol addresses are load-base arithmetic, valid before relocations.
if (image.executable && std::find(globalImages_.begin(), globalImages_.end(), &image) == globalImages_.end()) {
globalImages_.push_back(&image);
}
image.requestFlags = flags;
image.adopted = adopted;
image.deepBind = (flags & RTLD_DEEPBIND) != 0;
// The dlfcn wrapper exists as soon as the image is findable: a
// dependency's stub_dlopen returns it while the closure is still
// assembling.
image.wrapper.reset(new LoadedElf(image));
image.state = LinkMap::State::Mapped;
closure_.push_back(&image);
}
// The back half: relocations, protections, TLS seeding, and the initializer
// queue. An adopted image keeps the kernel's segment protections — they are
// already final — but RELRO stays ours to seal; the kernel never applies it.
void Loader::completeImage(LinkMap& image) {
std::vector<DeferredRelocation> deferred;
auto lazy = !(image.requestFlags & RTLD_NOW) && !image.bindNow && !bindNow_;
// Segments carry their final protections from the mapping; only a
// DT_TEXTREL image opens its read-only segments for the pass, the way
// glibc does.
if (image.textRelocations && !image.adopted) {
image.unprotect();
}
applyRelocations(image, deferred, lazy);
if (image.textRelocations && !image.adopted) {
image.protect();
}
for (const auto& item : deferred) {
applyRelocation(*item.image, *item.relocation, true);
}
image.applyRelro();
if (image.tlsModule) {
seedStaticTls(image);
}
image.state = LinkMap::State::Ready;
if (image.executable) {
mainExecutable_ = ℑ
}
if (image.requestFlags & 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);
}
// Dependencies before dependents, glibc's _dl_sort_maps discipline: an
// IFUNC resolver in a dependency executes during the dependent's
// relocation, so the dependency's own relocations must already be in
// place — breadth-first order alone does not guarantee that between
// siblings. Cycles place in first-seen order, like ld.so.
void Loader::orderForRelocation(LinkMap& image, std::vector<LinkMap*>& order, std::unordered_set<const LinkMap*>& placed) {
if (!placed.insert(&image).second) {
return;
}
for (const auto& dependency : image.dependencies) {
if (dependency.image && dependency.image->state == LinkMap::State::Mapped) {
orderForRelocation(*dependency.image, order, placed);
}
}
order.push_back(&image);
}
// ld.so's two phases over the whole closure, run by the outermost load.
// First the dependency lists, breadth-first: each image's stub_dlopen either
// finds its dependency already mapped or maps and appends it, growing the
// queue this loop is walking. Then relocations, dependency-sorted, the
// requested image last.
void Loader::linkClosure() {
try {
for (size_t index = 0; index < closure_.size(); ++index) {
loadDependencies(*closure_[index]);
}