forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSyntheticSections.cpp
1518 lines (1347 loc) · 53.4 KB
/
SyntheticSections.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
//===- SyntheticSections.cpp ---------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "SyntheticSections.h"
#include "ConcatOutputSection.h"
#include "Config.h"
#include "ExportTrie.h"
#include "InputFiles.h"
#include "MachOStructs.h"
#include "OutputSegment.h"
#include "SymbolTable.h"
#include "Symbols.h"
#include "lld/Common/CommonLinkerContext.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Config/llvm-config.h"
#include "llvm/Support/EndianStream.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/LEB128.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/SHA256.h"
#if defined(__APPLE__)
#include <sys/mman.h>
#endif
#ifdef LLVM_HAVE_LIBXAR
#include <fcntl.h>
extern "C" {
#include <xar/xar.h>
}
#endif
using namespace llvm;
using namespace llvm::MachO;
using namespace llvm::support;
using namespace llvm::support::endian;
using namespace lld;
using namespace lld::macho;
InStruct macho::in;
std::vector<SyntheticSection *> macho::syntheticSections;
SyntheticSection::SyntheticSection(const char *segname, const char *name)
: OutputSection(SyntheticKind, name) {
std::tie(this->segname, this->name) = maybeRenameSection({segname, name});
isec = makeSyntheticInputSection(segname, name);
isec->parent = this;
syntheticSections.push_back(this);
}
// dyld3's MachOLoaded::getSlide() assumes that the __TEXT segment starts
// from the beginning of the file (i.e. the header).
MachHeaderSection::MachHeaderSection()
: SyntheticSection(segment_names::text, section_names::header) {
// XXX: This is a hack. (See D97007)
// Setting the index to 1 to pretend that this section is the text
// section.
index = 1;
isec->isFinal = true;
}
void MachHeaderSection::addLoadCommand(LoadCommand *lc) {
loadCommands.push_back(lc);
sizeOfCmds += lc->getSize();
}
uint64_t MachHeaderSection::getSize() const {
uint64_t size = target->headerSize + sizeOfCmds + config->headerPad;
// If we are emitting an encryptable binary, our load commands must have a
// separate (non-encrypted) page to themselves.
if (config->emitEncryptionInfo)
size = alignTo(size, target->getPageSize());
return size;
}
static uint32_t cpuSubtype() {
uint32_t subtype = target->cpuSubtype;
if (config->outputType == MH_EXECUTE && !config->staticLink &&
target->cpuSubtype == CPU_SUBTYPE_X86_64_ALL &&
config->platform() == PLATFORM_MACOS &&
config->platformInfo.minimum >= VersionTuple(10, 5))
subtype |= CPU_SUBTYPE_LIB64;
return subtype;
}
void MachHeaderSection::writeTo(uint8_t *buf) const {
auto *hdr = reinterpret_cast<mach_header *>(buf);
hdr->magic = target->magic;
hdr->cputype = target->cpuType;
hdr->cpusubtype = cpuSubtype();
hdr->filetype = config->outputType;
hdr->ncmds = loadCommands.size();
hdr->sizeofcmds = sizeOfCmds;
hdr->flags = MH_DYLDLINK;
if (config->namespaceKind == NamespaceKind::twolevel)
hdr->flags |= MH_NOUNDEFS | MH_TWOLEVEL;
if (config->outputType == MH_DYLIB && !config->hasReexports)
hdr->flags |= MH_NO_REEXPORTED_DYLIBS;
if (config->markDeadStrippableDylib)
hdr->flags |= MH_DEAD_STRIPPABLE_DYLIB;
if (config->outputType == MH_EXECUTE && config->isPic)
hdr->flags |= MH_PIE;
if (config->outputType == MH_DYLIB && config->applicationExtension)
hdr->flags |= MH_APP_EXTENSION_SAFE;
if (in.exports->hasWeakSymbol || in.weakBinding->hasNonWeakDefinition())
hdr->flags |= MH_WEAK_DEFINES;
if (in.exports->hasWeakSymbol || in.weakBinding->hasEntry())
hdr->flags |= MH_BINDS_TO_WEAK;
for (const OutputSegment *seg : outputSegments) {
for (const OutputSection *osec : seg->getSections()) {
if (isThreadLocalVariables(osec->flags)) {
hdr->flags |= MH_HAS_TLV_DESCRIPTORS;
break;
}
}
}
uint8_t *p = reinterpret_cast<uint8_t *>(hdr) + target->headerSize;
for (const LoadCommand *lc : loadCommands) {
lc->writeTo(p);
p += lc->getSize();
}
}
PageZeroSection::PageZeroSection()
: SyntheticSection(segment_names::pageZero, section_names::pageZero) {}
RebaseSection::RebaseSection()
: LinkEditSection(segment_names::linkEdit, section_names::rebase) {}
namespace {
struct Rebase {
OutputSegment *segment = nullptr;
uint64_t offset = 0;
uint64_t consecutiveCount = 0;
};
} // namespace
// Rebase opcodes allow us to describe a contiguous sequence of rebase location
// using a single DO_REBASE opcode. To take advantage of it, we delay emitting
// `DO_REBASE` until we have reached the end of a contiguous sequence.
static void encodeDoRebase(Rebase &rebase, raw_svector_ostream &os) {
assert(rebase.consecutiveCount != 0);
if (rebase.consecutiveCount <= REBASE_IMMEDIATE_MASK) {
os << static_cast<uint8_t>(REBASE_OPCODE_DO_REBASE_IMM_TIMES |
rebase.consecutiveCount);
} else {
os << static_cast<uint8_t>(REBASE_OPCODE_DO_REBASE_ULEB_TIMES);
encodeULEB128(rebase.consecutiveCount, os);
}
rebase.consecutiveCount = 0;
}
static void encodeRebase(const OutputSection *osec, uint64_t outSecOff,
Rebase &lastRebase, raw_svector_ostream &os) {
OutputSegment *seg = osec->parent;
uint64_t offset = osec->getSegmentOffset() + outSecOff;
if (lastRebase.segment != seg || lastRebase.offset != offset) {
if (lastRebase.consecutiveCount != 0)
encodeDoRebase(lastRebase, os);
if (lastRebase.segment != seg) {
os << static_cast<uint8_t>(REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB |
seg->index);
encodeULEB128(offset, os);
lastRebase.segment = seg;
lastRebase.offset = offset;
} else {
assert(lastRebase.offset != offset);
os << static_cast<uint8_t>(REBASE_OPCODE_ADD_ADDR_ULEB);
encodeULEB128(offset - lastRebase.offset, os);
lastRebase.offset = offset;
}
}
++lastRebase.consecutiveCount;
// DO_REBASE causes dyld to both perform the binding and increment the offset
lastRebase.offset += target->wordSize;
}
void RebaseSection::finalizeContents() {
if (locations.empty())
return;
raw_svector_ostream os{contents};
Rebase lastRebase;
os << static_cast<uint8_t>(REBASE_OPCODE_SET_TYPE_IMM | REBASE_TYPE_POINTER);
llvm::sort(locations, [](const Location &a, const Location &b) {
return a.isec->getVA(a.offset) < b.isec->getVA(b.offset);
});
for (const Location &loc : locations)
encodeRebase(loc.isec->parent, loc.isec->getOffset(loc.offset), lastRebase,
os);
if (lastRebase.consecutiveCount != 0)
encodeDoRebase(lastRebase, os);
os << static_cast<uint8_t>(REBASE_OPCODE_DONE);
}
void RebaseSection::writeTo(uint8_t *buf) const {
memcpy(buf, contents.data(), contents.size());
}
NonLazyPointerSectionBase::NonLazyPointerSectionBase(const char *segname,
const char *name)
: SyntheticSection(segname, name) {
align = target->wordSize;
}
void macho::addNonLazyBindingEntries(const Symbol *sym,
const InputSection *isec, uint64_t offset,
int64_t addend) {
if (const auto *dysym = dyn_cast<DylibSymbol>(sym)) {
in.binding->addEntry(dysym, isec, offset, addend);
if (dysym->isWeakDef())
in.weakBinding->addEntry(sym, isec, offset, addend);
} else if (const auto *defined = dyn_cast<Defined>(sym)) {
in.rebase->addEntry(isec, offset);
if (defined->isExternalWeakDef())
in.weakBinding->addEntry(sym, isec, offset, addend);
} else {
// Undefined symbols are filtered out in scanRelocations(); we should never
// get here
llvm_unreachable("cannot bind to an undefined symbol");
}
}
void NonLazyPointerSectionBase::addEntry(Symbol *sym) {
if (entries.insert(sym)) {
assert(!sym->isInGot());
sym->gotIndex = entries.size() - 1;
addNonLazyBindingEntries(sym, isec, sym->gotIndex * target->wordSize);
}
}
void NonLazyPointerSectionBase::writeTo(uint8_t *buf) const {
for (size_t i = 0, n = entries.size(); i < n; ++i)
if (auto *defined = dyn_cast<Defined>(entries[i]))
write64le(&buf[i * target->wordSize], defined->getVA());
}
GotSection::GotSection()
: NonLazyPointerSectionBase(segment_names::data, section_names::got) {
flags = S_NON_LAZY_SYMBOL_POINTERS;
}
TlvPointerSection::TlvPointerSection()
: NonLazyPointerSectionBase(segment_names::data,
section_names::threadPtrs) {
flags = S_THREAD_LOCAL_VARIABLE_POINTERS;
}
BindingSection::BindingSection()
: LinkEditSection(segment_names::linkEdit, section_names::binding) {}
namespace {
struct Binding {
OutputSegment *segment = nullptr;
uint64_t offset = 0;
int64_t addend = 0;
};
struct BindIR {
// Default value of 0xF0 is not valid opcode and should make the program
// scream instead of accidentally writing "valid" values.
uint8_t opcode = 0xF0;
uint64_t data = 0;
uint64_t consecutiveCount = 0;
};
} // namespace
// Encode a sequence of opcodes that tell dyld to write the address of symbol +
// addend at osec->addr + outSecOff.
//
// The bind opcode "interpreter" remembers the values of each binding field, so
// we only need to encode the differences between bindings. Hence the use of
// lastBinding.
static void encodeBinding(const OutputSection *osec, uint64_t outSecOff,
int64_t addend, Binding &lastBinding,
std::vector<BindIR> &opcodes) {
OutputSegment *seg = osec->parent;
uint64_t offset = osec->getSegmentOffset() + outSecOff;
if (lastBinding.segment != seg) {
opcodes.push_back(
{static_cast<uint8_t>(BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB |
seg->index),
offset});
lastBinding.segment = seg;
lastBinding.offset = offset;
} else if (lastBinding.offset != offset) {
opcodes.push_back({BIND_OPCODE_ADD_ADDR_ULEB, offset - lastBinding.offset});
lastBinding.offset = offset;
}
if (lastBinding.addend != addend) {
opcodes.push_back(
{BIND_OPCODE_SET_ADDEND_SLEB, static_cast<uint64_t>(addend)});
lastBinding.addend = addend;
}
opcodes.push_back({BIND_OPCODE_DO_BIND, 0});
// DO_BIND causes dyld to both perform the binding and increment the offset
lastBinding.offset += target->wordSize;
}
static void optimizeOpcodes(std::vector<BindIR> &opcodes) {
// Pass 1: Combine bind/add pairs
size_t i;
int pWrite = 0;
for (i = 1; i < opcodes.size(); ++i, ++pWrite) {
if ((opcodes[i].opcode == BIND_OPCODE_ADD_ADDR_ULEB) &&
(opcodes[i - 1].opcode == BIND_OPCODE_DO_BIND)) {
opcodes[pWrite].opcode = BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB;
opcodes[pWrite].data = opcodes[i].data;
++i;
} else {
opcodes[pWrite] = opcodes[i - 1];
}
}
if (i == opcodes.size())
opcodes[pWrite] = opcodes[i - 1];
opcodes.resize(pWrite + 1);
// Pass 2: Compress two or more bind_add opcodes
pWrite = 0;
for (i = 1; i < opcodes.size(); ++i, ++pWrite) {
if ((opcodes[i].opcode == BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB) &&
(opcodes[i - 1].opcode == BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB) &&
(opcodes[i].data == opcodes[i - 1].data)) {
opcodes[pWrite].opcode = BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB;
opcodes[pWrite].consecutiveCount = 2;
opcodes[pWrite].data = opcodes[i].data;
++i;
while (i < opcodes.size() &&
(opcodes[i].opcode == BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB) &&
(opcodes[i].data == opcodes[i - 1].data)) {
opcodes[pWrite].consecutiveCount++;
++i;
}
} else {
opcodes[pWrite] = opcodes[i - 1];
}
}
if (i == opcodes.size())
opcodes[pWrite] = opcodes[i - 1];
opcodes.resize(pWrite + 1);
// Pass 3: Use immediate encodings
// Every binding is the size of one pointer. If the next binding is a
// multiple of wordSize away that is within BIND_IMMEDIATE_MASK, the
// opcode can be scaled by wordSize into a single byte and dyld will
// expand it to the correct address.
for (auto &p : opcodes) {
// It's unclear why the check needs to be less than BIND_IMMEDIATE_MASK,
// but ld64 currently does this. This could be a potential bug, but
// for now, perform the same behavior to prevent mysterious bugs.
if ((p.opcode == BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB) &&
((p.data / target->wordSize) < BIND_IMMEDIATE_MASK) &&
((p.data % target->wordSize) == 0)) {
p.opcode = BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED;
p.data /= target->wordSize;
}
}
}
static void flushOpcodes(const BindIR &op, raw_svector_ostream &os) {
uint8_t opcode = op.opcode & BIND_OPCODE_MASK;
switch (opcode) {
case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
case BIND_OPCODE_ADD_ADDR_ULEB:
case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB:
os << op.opcode;
encodeULEB128(op.data, os);
break;
case BIND_OPCODE_SET_ADDEND_SLEB:
os << op.opcode;
encodeSLEB128(static_cast<int64_t>(op.data), os);
break;
case BIND_OPCODE_DO_BIND:
os << op.opcode;
break;
case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB:
os << op.opcode;
encodeULEB128(op.consecutiveCount, os);
encodeULEB128(op.data, os);
break;
case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED:
os << static_cast<uint8_t>(op.opcode | op.data);
break;
default:
llvm_unreachable("cannot bind to an unrecognized symbol");
}
}
// Non-weak bindings need to have their dylib ordinal encoded as well.
static int16_t ordinalForDylibSymbol(const DylibSymbol &dysym) {
if (config->namespaceKind == NamespaceKind::flat || dysym.isDynamicLookup())
return static_cast<int16_t>(BIND_SPECIAL_DYLIB_FLAT_LOOKUP);
assert(dysym.getFile()->isReferenced());
return dysym.getFile()->ordinal;
}
static void encodeDylibOrdinal(int16_t ordinal, raw_svector_ostream &os) {
if (ordinal <= 0) {
os << static_cast<uint8_t>(BIND_OPCODE_SET_DYLIB_SPECIAL_IMM |
(ordinal & BIND_IMMEDIATE_MASK));
} else if (ordinal <= BIND_IMMEDIATE_MASK) {
os << static_cast<uint8_t>(BIND_OPCODE_SET_DYLIB_ORDINAL_IMM | ordinal);
} else {
os << static_cast<uint8_t>(BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB);
encodeULEB128(ordinal, os);
}
}
static void encodeWeakOverride(const Defined *defined,
raw_svector_ostream &os) {
os << static_cast<uint8_t>(BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM |
BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION)
<< defined->getName() << '\0';
}
// Organize the bindings so we can encoded them with fewer opcodes.
//
// First, all bindings for a given symbol should be grouped together.
// BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM is the largest opcode (since it
// has an associated symbol string), so we only want to emit it once per symbol.
//
// Within each group, we sort the bindings by address. Since bindings are
// delta-encoded, sorting them allows for a more compact result. Note that
// sorting by address alone ensures that bindings for the same segment / section
// are located together, minimizing the number of times we have to emit
// BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB.
//
// Finally, we sort the symbols by the address of their first binding, again
// to facilitate the delta-encoding process.
template <class Sym>
std::vector<std::pair<const Sym *, std::vector<BindingEntry>>>
sortBindings(const BindingsMap<const Sym *> &bindingsMap) {
std::vector<std::pair<const Sym *, std::vector<BindingEntry>>> bindingsVec(
bindingsMap.begin(), bindingsMap.end());
for (auto &p : bindingsVec) {
std::vector<BindingEntry> &bindings = p.second;
llvm::sort(bindings, [](const BindingEntry &a, const BindingEntry &b) {
return a.target.getVA() < b.target.getVA();
});
}
llvm::sort(bindingsVec, [](const auto &a, const auto &b) {
return a.second[0].target.getVA() < b.second[0].target.getVA();
});
return bindingsVec;
}
// Emit bind opcodes, which are a stream of byte-sized opcodes that dyld
// interprets to update a record with the following fields:
// * segment index (of the segment to write the symbol addresses to, typically
// the __DATA_CONST segment which contains the GOT)
// * offset within the segment, indicating the next location to write a binding
// * symbol type
// * symbol library ordinal (the index of its library's LC_LOAD_DYLIB command)
// * symbol name
// * addend
// When dyld sees BIND_OPCODE_DO_BIND, it uses the current record state to bind
// a symbol in the GOT, and increments the segment offset to point to the next
// entry. It does *not* clear the record state after doing the bind, so
// subsequent opcodes only need to encode the differences between bindings.
void BindingSection::finalizeContents() {
raw_svector_ostream os{contents};
Binding lastBinding;
int16_t lastOrdinal = 0;
for (auto &p : sortBindings(bindingsMap)) {
const DylibSymbol *sym = p.first;
std::vector<BindingEntry> &bindings = p.second;
uint8_t flags = BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM;
if (sym->isWeakRef())
flags |= BIND_SYMBOL_FLAGS_WEAK_IMPORT;
os << flags << sym->getName() << '\0'
<< static_cast<uint8_t>(BIND_OPCODE_SET_TYPE_IMM | BIND_TYPE_POINTER);
int16_t ordinal = ordinalForDylibSymbol(*sym);
if (ordinal != lastOrdinal) {
encodeDylibOrdinal(ordinal, os);
lastOrdinal = ordinal;
}
std::vector<BindIR> opcodes;
for (const BindingEntry &b : bindings)
encodeBinding(b.target.isec->parent,
b.target.isec->getOffset(b.target.offset), b.addend,
lastBinding, opcodes);
if (config->optimize > 1)
optimizeOpcodes(opcodes);
for (const auto &op : opcodes)
flushOpcodes(op, os);
}
if (!bindingsMap.empty())
os << static_cast<uint8_t>(BIND_OPCODE_DONE);
}
void BindingSection::writeTo(uint8_t *buf) const {
memcpy(buf, contents.data(), contents.size());
}
WeakBindingSection::WeakBindingSection()
: LinkEditSection(segment_names::linkEdit, section_names::weakBinding) {}
void WeakBindingSection::finalizeContents() {
raw_svector_ostream os{contents};
Binding lastBinding;
for (const Defined *defined : definitions)
encodeWeakOverride(defined, os);
for (auto &p : sortBindings(bindingsMap)) {
const Symbol *sym = p.first;
std::vector<BindingEntry> &bindings = p.second;
os << static_cast<uint8_t>(BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM)
<< sym->getName() << '\0'
<< static_cast<uint8_t>(BIND_OPCODE_SET_TYPE_IMM | BIND_TYPE_POINTER);
std::vector<BindIR> opcodes;
for (const BindingEntry &b : bindings)
encodeBinding(b.target.isec->parent,
b.target.isec->getOffset(b.target.offset), b.addend,
lastBinding, opcodes);
if (config->optimize > 1)
optimizeOpcodes(opcodes);
for (const auto &op : opcodes)
flushOpcodes(op, os);
}
if (!bindingsMap.empty() || !definitions.empty())
os << static_cast<uint8_t>(BIND_OPCODE_DONE);
}
void WeakBindingSection::writeTo(uint8_t *buf) const {
memcpy(buf, contents.data(), contents.size());
}
StubsSection::StubsSection()
: SyntheticSection(segment_names::text, section_names::stubs) {
flags = S_SYMBOL_STUBS | S_ATTR_SOME_INSTRUCTIONS | S_ATTR_PURE_INSTRUCTIONS;
// The stubs section comprises machine instructions, which are aligned to
// 4 bytes on the archs we care about.
align = 4;
reserved2 = target->stubSize;
}
uint64_t StubsSection::getSize() const {
return entries.size() * target->stubSize;
}
void StubsSection::writeTo(uint8_t *buf) const {
size_t off = 0;
for (const Symbol *sym : entries) {
target->writeStub(buf + off, *sym);
off += target->stubSize;
}
}
void StubsSection::finalize() { isFinal = true; }
bool StubsSection::addEntry(Symbol *sym) {
bool inserted = entries.insert(sym);
if (inserted)
sym->stubsIndex = entries.size() - 1;
return inserted;
}
StubHelperSection::StubHelperSection()
: SyntheticSection(segment_names::text, section_names::stubHelper) {
flags = S_ATTR_SOME_INSTRUCTIONS | S_ATTR_PURE_INSTRUCTIONS;
align = 4; // This section comprises machine instructions
}
uint64_t StubHelperSection::getSize() const {
return target->stubHelperHeaderSize +
in.lazyBinding->getEntries().size() * target->stubHelperEntrySize;
}
bool StubHelperSection::isNeeded() const { return in.lazyBinding->isNeeded(); }
void StubHelperSection::writeTo(uint8_t *buf) const {
target->writeStubHelperHeader(buf);
size_t off = target->stubHelperHeaderSize;
for (const DylibSymbol *sym : in.lazyBinding->getEntries()) {
target->writeStubHelperEntry(buf + off, *sym, addr + off);
off += target->stubHelperEntrySize;
}
}
void StubHelperSection::setup() {
Symbol *binder = symtab->addUndefined("dyld_stub_binder", /*file=*/nullptr,
/*isWeakRef=*/false);
if (auto *undefined = dyn_cast<Undefined>(binder))
treatUndefinedSymbol(*undefined,
"lazy binding (normally in libSystem.dylib)");
// treatUndefinedSymbol() can replace binder with a DylibSymbol; re-check.
stubBinder = dyn_cast_or_null<DylibSymbol>(binder);
if (stubBinder == nullptr)
return;
in.got->addEntry(stubBinder);
in.imageLoaderCache->parent =
ConcatOutputSection::getOrCreateForInput(in.imageLoaderCache);
inputSections.push_back(in.imageLoaderCache);
// Since this isn't in the symbol table or in any input file, the noDeadStrip
// argument doesn't matter.
dyldPrivate =
make<Defined>("__dyld_private", nullptr, in.imageLoaderCache, 0, 0,
/*isWeakDef=*/false,
/*isExternal=*/false, /*isPrivateExtern=*/false,
/*isThumb=*/false, /*isReferencedDynamically=*/false,
/*noDeadStrip=*/false);
dyldPrivate->used = true;
}
LazyPointerSection::LazyPointerSection()
: SyntheticSection(segment_names::data, section_names::lazySymbolPtr) {
align = target->wordSize;
flags = S_LAZY_SYMBOL_POINTERS;
}
uint64_t LazyPointerSection::getSize() const {
return in.stubs->getEntries().size() * target->wordSize;
}
bool LazyPointerSection::isNeeded() const {
return !in.stubs->getEntries().empty();
}
void LazyPointerSection::writeTo(uint8_t *buf) const {
size_t off = 0;
for (const Symbol *sym : in.stubs->getEntries()) {
if (const auto *dysym = dyn_cast<DylibSymbol>(sym)) {
if (dysym->hasStubsHelper()) {
uint64_t stubHelperOffset =
target->stubHelperHeaderSize +
dysym->stubsHelperIndex * target->stubHelperEntrySize;
write64le(buf + off, in.stubHelper->addr + stubHelperOffset);
}
} else {
write64le(buf + off, sym->getVA());
}
off += target->wordSize;
}
}
LazyBindingSection::LazyBindingSection()
: LinkEditSection(segment_names::linkEdit, section_names::lazyBinding) {}
void LazyBindingSection::finalizeContents() {
// TODO: Just precompute output size here instead of writing to a temporary
// buffer
for (DylibSymbol *sym : entries)
sym->lazyBindOffset = encode(*sym);
}
void LazyBindingSection::writeTo(uint8_t *buf) const {
memcpy(buf, contents.data(), contents.size());
}
void LazyBindingSection::addEntry(DylibSymbol *dysym) {
if (entries.insert(dysym)) {
dysym->stubsHelperIndex = entries.size() - 1;
in.rebase->addEntry(in.lazyPointers->isec,
dysym->stubsIndex * target->wordSize);
}
}
// Unlike the non-lazy binding section, the bind opcodes in this section aren't
// interpreted all at once. Rather, dyld will start interpreting opcodes at a
// given offset, typically only binding a single symbol before it finds a
// BIND_OPCODE_DONE terminator. As such, unlike in the non-lazy-binding case,
// we cannot encode just the differences between symbols; we have to emit the
// complete bind information for each symbol.
uint32_t LazyBindingSection::encode(const DylibSymbol &sym) {
uint32_t opstreamOffset = contents.size();
OutputSegment *dataSeg = in.lazyPointers->parent;
os << static_cast<uint8_t>(BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB |
dataSeg->index);
uint64_t offset = in.lazyPointers->addr - dataSeg->addr +
sym.stubsIndex * target->wordSize;
encodeULEB128(offset, os);
encodeDylibOrdinal(ordinalForDylibSymbol(sym), os);
uint8_t flags = BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM;
if (sym.isWeakRef())
flags |= BIND_SYMBOL_FLAGS_WEAK_IMPORT;
os << flags << sym.getName() << '\0'
<< static_cast<uint8_t>(BIND_OPCODE_DO_BIND)
<< static_cast<uint8_t>(BIND_OPCODE_DONE);
return opstreamOffset;
}
ExportSection::ExportSection()
: LinkEditSection(segment_names::linkEdit, section_names::export_) {}
void ExportSection::finalizeContents() {
trieBuilder.setImageBase(in.header->addr);
for (const Symbol *sym : symtab->getSymbols()) {
if (const auto *defined = dyn_cast<Defined>(sym)) {
if (defined->privateExtern || !defined->isLive())
continue;
trieBuilder.addSymbol(*defined);
hasWeakSymbol = hasWeakSymbol || sym->isWeakDef();
}
}
size = trieBuilder.build();
}
void ExportSection::writeTo(uint8_t *buf) const { trieBuilder.writeTo(buf); }
DataInCodeSection::DataInCodeSection()
: LinkEditSection(segment_names::linkEdit, section_names::dataInCode) {}
template <class LP>
static std::vector<MachO::data_in_code_entry> collectDataInCodeEntries() {
std::vector<MachO::data_in_code_entry> dataInCodeEntries;
for (const InputFile *inputFile : inputFiles) {
if (!isa<ObjFile>(inputFile))
continue;
const ObjFile *objFile = cast<ObjFile>(inputFile);
ArrayRef<MachO::data_in_code_entry> entries = objFile->getDataInCode();
if (entries.empty())
continue;
assert(is_sorted(dataInCodeEntries, [](const data_in_code_entry &lhs,
const data_in_code_entry &rhs) {
return lhs.offset < rhs.offset;
}));
// For each code subsection find 'data in code' entries residing in it.
// Compute the new offset values as
// <offset within subsection> + <subsection address> - <__TEXT address>.
for (const Section *section : objFile->sections) {
for (const Subsection &subsec : section->subsections) {
const InputSection *isec = subsec.isec;
if (!isCodeSection(isec))
continue;
if (cast<ConcatInputSection>(isec)->shouldOmitFromOutput())
continue;
const uint64_t beginAddr = section->addr + subsec.offset;
auto it = llvm::lower_bound(
entries, beginAddr,
[](const MachO::data_in_code_entry &entry, uint64_t addr) {
return entry.offset < addr;
});
const uint64_t endAddr = beginAddr + isec->getFileSize();
for (const auto end = entries.end();
it != end && it->offset + it->length <= endAddr; ++it)
dataInCodeEntries.push_back(
{static_cast<uint32_t>(isec->getVA(it->offset - beginAddr) -
in.header->addr),
it->length, it->kind});
}
}
}
return dataInCodeEntries;
}
void DataInCodeSection::finalizeContents() {
entries = target->wordSize == 8 ? collectDataInCodeEntries<LP64>()
: collectDataInCodeEntries<ILP32>();
}
void DataInCodeSection::writeTo(uint8_t *buf) const {
if (!entries.empty())
memcpy(buf, entries.data(), getRawSize());
}
FunctionStartsSection::FunctionStartsSection()
: LinkEditSection(segment_names::linkEdit, section_names::functionStarts) {}
void FunctionStartsSection::finalizeContents() {
raw_svector_ostream os{contents};
std::vector<uint64_t> addrs;
for (const InputFile *file : inputFiles) {
if (auto *objFile = dyn_cast<ObjFile>(file)) {
for (const Symbol *sym : objFile->symbols) {
if (const auto *defined = dyn_cast_or_null<Defined>(sym)) {
if (!defined->isec || !isCodeSection(defined->isec) ||
!defined->isLive())
continue;
// TODO: Add support for thumbs, in that case
// the lowest bit of nextAddr needs to be set to 1.
addrs.push_back(defined->getVA());
}
}
}
}
llvm::sort(addrs);
uint64_t addr = in.header->addr;
for (uint64_t nextAddr : addrs) {
uint64_t delta = nextAddr - addr;
if (delta == 0)
continue;
encodeULEB128(delta, os);
addr = nextAddr;
}
os << '\0';
}
void FunctionStartsSection::writeTo(uint8_t *buf) const {
memcpy(buf, contents.data(), contents.size());
}
SymtabSection::SymtabSection(StringTableSection &stringTableSection)
: LinkEditSection(segment_names::linkEdit, section_names::symbolTable),
stringTableSection(stringTableSection) {}
void SymtabSection::emitBeginSourceStab(DWARFUnit *compileUnit) {
StabsEntry stab(N_SO);
SmallString<261> dir(compileUnit->getCompilationDir());
StringRef sep = sys::path::get_separator();
// We don't use `path::append` here because we want an empty `dir` to result
// in an absolute path. `append` would give us a relative path for that case.
if (!dir.endswith(sep))
dir += sep;
stab.strx = stringTableSection.addString(
saver().save(dir + compileUnit->getUnitDIE().getShortName()));
stabs.emplace_back(std::move(stab));
}
void SymtabSection::emitEndSourceStab() {
StabsEntry stab(N_SO);
stab.sect = 1;
stabs.emplace_back(std::move(stab));
}
void SymtabSection::emitObjectFileStab(ObjFile *file) {
StabsEntry stab(N_OSO);
stab.sect = target->cpuSubtype;
SmallString<261> path(!file->archiveName.empty() ? file->archiveName
: file->getName());
std::error_code ec = sys::fs::make_absolute(path);
if (ec)
fatal("failed to get absolute path for " + path);
if (!file->archiveName.empty())
path.append({"(", file->getName(), ")"});
StringRef adjustedPath = saver().save(path.str());
adjustedPath.consume_front(config->osoPrefix);
stab.strx = stringTableSection.addString(adjustedPath);
stab.desc = 1;
stab.value = file->modTime;
stabs.emplace_back(std::move(stab));
}
void SymtabSection::emitEndFunStab(Defined *defined) {
StabsEntry stab(N_FUN);
stab.value = defined->size;
stabs.emplace_back(std::move(stab));
}
void SymtabSection::emitStabs() {
if (config->omitDebugInfo)
return;
for (const std::string &s : config->astPaths) {
StabsEntry astStab(N_AST);
astStab.strx = stringTableSection.addString(s);
stabs.emplace_back(std::move(astStab));
}
std::vector<Defined *> symbolsNeedingStabs;
for (const SymtabEntry &entry :
concat<SymtabEntry>(localSymbols, externalSymbols)) {
Symbol *sym = entry.sym;
assert(sym->isLive() &&
"dead symbols should not be in localSymbols, externalSymbols");
if (auto *defined = dyn_cast<Defined>(sym)) {
if (defined->isAbsolute())
continue;
InputSection *isec = defined->isec;
ObjFile *file = dyn_cast_or_null<ObjFile>(isec->getFile());
if (!file || !file->compileUnit)
continue;
symbolsNeedingStabs.push_back(defined);
}
}
llvm::stable_sort(symbolsNeedingStabs, [&](Defined *a, Defined *b) {
return a->isec->getFile()->id < b->isec->getFile()->id;
});
// Emit STABS symbols so that dsymutil and/or the debugger can map address
// regions in the final binary to the source and object files from which they
// originated.
InputFile *lastFile = nullptr;
for (Defined *defined : symbolsNeedingStabs) {
InputSection *isec = defined->isec;
ObjFile *file = cast<ObjFile>(isec->getFile());
if (lastFile == nullptr || lastFile != file) {
if (lastFile != nullptr)
emitEndSourceStab();
lastFile = file;
emitBeginSourceStab(file->compileUnit);
emitObjectFileStab(file);
}
StabsEntry symStab;
symStab.sect = defined->isec->parent->index;
symStab.strx = stringTableSection.addString(defined->getName());
symStab.value = defined->getVA();
if (isCodeSection(isec)) {
symStab.type = N_FUN;
stabs.emplace_back(std::move(symStab));
emitEndFunStab(defined);
} else {
symStab.type = defined->isExternal() ? N_GSYM : N_STSYM;
stabs.emplace_back(std::move(symStab));
}
}
if (!stabs.empty())
emitEndSourceStab();
}
void SymtabSection::finalizeContents() {
auto addSymbol = [&](std::vector<SymtabEntry> &symbols, Symbol *sym) {
uint32_t strx = stringTableSection.addString(sym->getName());
symbols.push_back({sym, strx});
};
// Local symbols aren't in the SymbolTable, so we walk the list of object
// files to gather them.
for (const InputFile *file : inputFiles) {
if (auto *objFile = dyn_cast<ObjFile>(file)) {
for (Symbol *sym : objFile->symbols) {
if (auto *defined = dyn_cast_or_null<Defined>(sym)) {
if (!defined->isExternal() && defined->isLive()) {
StringRef name = defined->getName();
if (!name.startswith("l") && !name.startswith("L"))
addSymbol(localSymbols, sym);
}
}
}
}
}
// __dyld_private is a local symbol too. It's linker-created and doesn't
// exist in any object file.
if (Defined *dyldPrivate = in.stubHelper->dyldPrivate)
addSymbol(localSymbols, dyldPrivate);
for (Symbol *sym : symtab->getSymbols()) {
if (!sym->isLive())
continue;
if (auto *defined = dyn_cast<Defined>(sym)) {
if (!defined->includeInSymtab)
continue;
assert(defined->isExternal());
if (defined->privateExtern)
addSymbol(localSymbols, defined);
else
addSymbol(externalSymbols, defined);
} else if (auto *dysym = dyn_cast<DylibSymbol>(sym)) {
if (dysym->isReferenced())
addSymbol(undefinedSymbols, sym);
}
}
emitStabs();
uint32_t symtabIndex = stabs.size();
for (const SymtabEntry &entry :
concat<SymtabEntry>(localSymbols, externalSymbols, undefinedSymbols)) {
entry.sym->symtabIndex = symtabIndex++;
}
}
uint32_t SymtabSection::getNumSymbols() const {
return stabs.size() + localSymbols.size() + externalSymbols.size() +
undefinedSymbols.size();
}
// This serves to hide (type-erase) the template parameter from SymtabSection.
template <class LP> class SymtabSectionImpl final : public SymtabSection {
public:
SymtabSectionImpl(StringTableSection &stringTableSection)