forked from llvm-mirror/llvm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSyntheticSections.cpp
4051 lines (3560 loc) · 145 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
//
//===----------------------------------------------------------------------===//
//
// This file contains linker-synthesized sections. Currently,
// synthetic sections are created either output sections or input sections,
// but we are rewriting code so that all synthetic sections are created as
// input sections.
//
//===----------------------------------------------------------------------===//
#include "SyntheticSections.h"
#include "Config.h"
#include "DWARF.h"
#include "EhFrame.h"
#include "InputFiles.h"
#include "LinkerScript.h"
#include "OutputSections.h"
#include "SymbolTable.h"
#include "Symbols.h"
#include "Target.h"
#include "Thunks.h"
#include "Writer.h"
#include "lld/Common/CommonLinkerContext.h"
#include "lld/Common/DWARF.h"
#include "lld/Common/Strings.h"
#include "lld/Common/Version.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SetOperations.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/BinaryFormat/Dwarf.h"
#include "llvm/BinaryFormat/ELF.h"
#include "llvm/DebugInfo/DWARF/DWARFDebugPubTable.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/LEB128.h"
#include "llvm/Support/Parallel.h"
#include "llvm/Support/TimeProfiler.h"
#include <cstdlib>
using namespace llvm;
using namespace llvm::dwarf;
using namespace llvm::ELF;
using namespace llvm::object;
using namespace llvm::support;
using namespace lld;
using namespace lld::elf;
using llvm::support::endian::read32le;
using llvm::support::endian::write32le;
using llvm::support::endian::write64le;
constexpr size_t MergeNoTailSection::numShards;
static uint64_t readUint(uint8_t *buf) {
return config->is64 ? read64(buf) : read32(buf);
}
static void writeUint(uint8_t *buf, uint64_t val) {
if (config->is64)
write64(buf, val);
else
write32(buf, val);
}
// Returns an LLD version string.
static ArrayRef<uint8_t> getVersion() {
// Check LLD_VERSION first for ease of testing.
// You can get consistent output by using the environment variable.
// This is only for testing.
StringRef s = getenv("LLD_VERSION");
if (s.empty())
s = saver().save(Twine("Linker: ") + getLLDVersion());
// +1 to include the terminating '\0'.
return {(const uint8_t *)s.data(), s.size() + 1};
}
// Creates a .comment section containing LLD version info.
// With this feature, you can identify LLD-generated binaries easily
// by "readelf --string-dump .comment <file>".
// The returned object is a mergeable string section.
MergeInputSection *elf::createCommentSection() {
auto *sec = make<MergeInputSection>(SHF_MERGE | SHF_STRINGS, SHT_PROGBITS, 1,
getVersion(), ".comment");
sec->splitIntoPieces();
return sec;
}
// .MIPS.abiflags section.
template <class ELFT>
MipsAbiFlagsSection<ELFT>::MipsAbiFlagsSection(Elf_Mips_ABIFlags flags)
: SyntheticSection(SHF_ALLOC, SHT_MIPS_ABIFLAGS, 8, ".MIPS.abiflags"),
flags(flags) {
this->entsize = sizeof(Elf_Mips_ABIFlags);
}
template <class ELFT> void MipsAbiFlagsSection<ELFT>::writeTo(uint8_t *buf) {
memcpy(buf, &flags, sizeof(flags));
}
template <class ELFT>
std::unique_ptr<MipsAbiFlagsSection<ELFT>> MipsAbiFlagsSection<ELFT>::create() {
Elf_Mips_ABIFlags flags = {};
bool create = false;
for (InputSectionBase *sec : ctx.inputSections) {
if (sec->type != SHT_MIPS_ABIFLAGS)
continue;
sec->markDead();
create = true;
std::string filename = toString(sec->file);
const size_t size = sec->content().size();
// Older version of BFD (such as the default FreeBSD linker) concatenate
// .MIPS.abiflags instead of merging. To allow for this case (or potential
// zero padding) we ignore everything after the first Elf_Mips_ABIFlags
if (size < sizeof(Elf_Mips_ABIFlags)) {
error(filename + ": invalid size of .MIPS.abiflags section: got " +
Twine(size) + " instead of " + Twine(sizeof(Elf_Mips_ABIFlags)));
return nullptr;
}
auto *s =
reinterpret_cast<const Elf_Mips_ABIFlags *>(sec->content().data());
if (s->version != 0) {
error(filename + ": unexpected .MIPS.abiflags version " +
Twine(s->version));
return nullptr;
}
// LLD checks ISA compatibility in calcMipsEFlags(). Here we just
// select the highest number of ISA/Rev/Ext.
flags.isa_level = std::max(flags.isa_level, s->isa_level);
flags.isa_rev = std::max(flags.isa_rev, s->isa_rev);
flags.isa_ext = std::max(flags.isa_ext, s->isa_ext);
flags.gpr_size = std::max(flags.gpr_size, s->gpr_size);
flags.cpr1_size = std::max(flags.cpr1_size, s->cpr1_size);
flags.cpr2_size = std::max(flags.cpr2_size, s->cpr2_size);
flags.ases |= s->ases;
flags.flags1 |= s->flags1;
flags.flags2 |= s->flags2;
flags.fp_abi = elf::getMipsFpAbiFlag(flags.fp_abi, s->fp_abi, filename);
};
if (create)
return std::make_unique<MipsAbiFlagsSection<ELFT>>(flags);
return nullptr;
}
// .MIPS.options section.
template <class ELFT>
MipsOptionsSection<ELFT>::MipsOptionsSection(Elf_Mips_RegInfo reginfo)
: SyntheticSection(SHF_ALLOC, SHT_MIPS_OPTIONS, 8, ".MIPS.options"),
reginfo(reginfo) {
this->entsize = sizeof(Elf_Mips_Options) + sizeof(Elf_Mips_RegInfo);
}
template <class ELFT> void MipsOptionsSection<ELFT>::writeTo(uint8_t *buf) {
auto *options = reinterpret_cast<Elf_Mips_Options *>(buf);
options->kind = ODK_REGINFO;
options->size = getSize();
if (!config->relocatable)
reginfo.ri_gp_value = in.mipsGot->getGp();
memcpy(buf + sizeof(Elf_Mips_Options), ®info, sizeof(reginfo));
}
template <class ELFT>
std::unique_ptr<MipsOptionsSection<ELFT>> MipsOptionsSection<ELFT>::create() {
// N64 ABI only.
if (!ELFT::Is64Bits)
return nullptr;
SmallVector<InputSectionBase *, 0> sections;
for (InputSectionBase *sec : ctx.inputSections)
if (sec->type == SHT_MIPS_OPTIONS)
sections.push_back(sec);
if (sections.empty())
return nullptr;
Elf_Mips_RegInfo reginfo = {};
for (InputSectionBase *sec : sections) {
sec->markDead();
std::string filename = toString(sec->file);
ArrayRef<uint8_t> d = sec->content();
while (!d.empty()) {
if (d.size() < sizeof(Elf_Mips_Options)) {
error(filename + ": invalid size of .MIPS.options section");
break;
}
auto *opt = reinterpret_cast<const Elf_Mips_Options *>(d.data());
if (opt->kind == ODK_REGINFO) {
reginfo.ri_gprmask |= opt->getRegInfo().ri_gprmask;
sec->getFile<ELFT>()->mipsGp0 = opt->getRegInfo().ri_gp_value;
break;
}
if (!opt->size)
fatal(filename + ": zero option descriptor size");
d = d.slice(opt->size);
}
};
return std::make_unique<MipsOptionsSection<ELFT>>(reginfo);
}
// MIPS .reginfo section.
template <class ELFT>
MipsReginfoSection<ELFT>::MipsReginfoSection(Elf_Mips_RegInfo reginfo)
: SyntheticSection(SHF_ALLOC, SHT_MIPS_REGINFO, 4, ".reginfo"),
reginfo(reginfo) {
this->entsize = sizeof(Elf_Mips_RegInfo);
}
template <class ELFT> void MipsReginfoSection<ELFT>::writeTo(uint8_t *buf) {
if (!config->relocatable)
reginfo.ri_gp_value = in.mipsGot->getGp();
memcpy(buf, ®info, sizeof(reginfo));
}
template <class ELFT>
std::unique_ptr<MipsReginfoSection<ELFT>> MipsReginfoSection<ELFT>::create() {
// Section should be alive for O32 and N32 ABIs only.
if (ELFT::Is64Bits)
return nullptr;
SmallVector<InputSectionBase *, 0> sections;
for (InputSectionBase *sec : ctx.inputSections)
if (sec->type == SHT_MIPS_REGINFO)
sections.push_back(sec);
if (sections.empty())
return nullptr;
Elf_Mips_RegInfo reginfo = {};
for (InputSectionBase *sec : sections) {
sec->markDead();
if (sec->content().size() != sizeof(Elf_Mips_RegInfo)) {
error(toString(sec->file) + ": invalid size of .reginfo section");
return nullptr;
}
auto *r = reinterpret_cast<const Elf_Mips_RegInfo *>(sec->content().data());
reginfo.ri_gprmask |= r->ri_gprmask;
sec->getFile<ELFT>()->mipsGp0 = r->ri_gp_value;
};
return std::make_unique<MipsReginfoSection<ELFT>>(reginfo);
}
InputSection *elf::createInterpSection() {
// StringSaver guarantees that the returned string ends with '\0'.
StringRef s = saver().save(config->dynamicLinker);
ArrayRef<uint8_t> contents = {(const uint8_t *)s.data(), s.size() + 1};
return make<InputSection>(ctx.internalFile, SHF_ALLOC, SHT_PROGBITS, 1,
contents, ".interp");
}
Defined *elf::addSyntheticLocal(StringRef name, uint8_t type, uint64_t value,
uint64_t size, InputSectionBase §ion) {
Defined *s = makeDefined(section.file, name, STB_LOCAL, STV_DEFAULT, type,
value, size, §ion);
if (in.symTab)
in.symTab->addSymbol(s);
if (config->emachine == EM_ARM && !config->isLE && config->armBe8 &&
(section.flags & SHF_EXECINSTR))
// Adding Linker generated mapping symbols to the arm specific mapping
// symbols list.
addArmSyntheticSectionMappingSymbol(s);
return s;
}
static size_t getHashSize() {
switch (config->buildId) {
case BuildIdKind::Fast:
return 8;
case BuildIdKind::Md5:
case BuildIdKind::Uuid:
return 16;
case BuildIdKind::Sha1:
return 20;
case BuildIdKind::Hexstring:
return config->buildIdVector.size();
default:
llvm_unreachable("unknown BuildIdKind");
}
}
// This class represents a linker-synthesized .note.gnu.property section.
//
// In x86 and AArch64, object files may contain feature flags indicating the
// features that they have used. The flags are stored in a .note.gnu.property
// section.
//
// lld reads the sections from input files and merges them by computing AND of
// the flags. The result is written as a new .note.gnu.property section.
//
// If the flag is zero (which indicates that the intersection of the feature
// sets is empty, or some input files didn't have .note.gnu.property sections),
// we don't create this section.
GnuPropertySection::GnuPropertySection()
: SyntheticSection(llvm::ELF::SHF_ALLOC, llvm::ELF::SHT_NOTE,
config->wordsize, ".note.gnu.property") {}
void GnuPropertySection::writeTo(uint8_t *buf) {
uint32_t featureAndType = config->emachine == EM_AARCH64
? GNU_PROPERTY_AARCH64_FEATURE_1_AND
: GNU_PROPERTY_X86_FEATURE_1_AND;
write32(buf, 4); // Name size
write32(buf + 4, config->is64 ? 16 : 12); // Content size
write32(buf + 8, NT_GNU_PROPERTY_TYPE_0); // Type
memcpy(buf + 12, "GNU", 4); // Name string
write32(buf + 16, featureAndType); // Feature type
write32(buf + 20, 4); // Feature size
write32(buf + 24, config->andFeatures); // Feature flags
if (config->is64)
write32(buf + 28, 0); // Padding
}
size_t GnuPropertySection::getSize() const { return config->is64 ? 32 : 28; }
BuildIdSection::BuildIdSection()
: SyntheticSection(SHF_ALLOC, SHT_NOTE, 4, ".note.gnu.build-id"),
hashSize(getHashSize()) {}
void BuildIdSection::writeTo(uint8_t *buf) {
write32(buf, 4); // Name size
write32(buf + 4, hashSize); // Content size
write32(buf + 8, NT_GNU_BUILD_ID); // Type
memcpy(buf + 12, "GNU", 4); // Name string
hashBuf = buf + 16;
}
void BuildIdSection::writeBuildId(ArrayRef<uint8_t> buf) {
assert(buf.size() == hashSize);
memcpy(hashBuf, buf.data(), hashSize);
}
BssSection::BssSection(StringRef name, uint64_t size, uint32_t alignment)
: SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_NOBITS, alignment, name) {
this->bss = true;
this->size = size;
}
EhFrameSection::EhFrameSection()
: SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame") {}
// Search for an existing CIE record or create a new one.
// CIE records from input object files are uniquified by their contents
// and where their relocations point to.
template <class ELFT, class RelTy>
CieRecord *EhFrameSection::addCie(EhSectionPiece &cie, ArrayRef<RelTy> rels) {
Symbol *personality = nullptr;
unsigned firstRelI = cie.firstRelocation;
if (firstRelI != (unsigned)-1)
personality = &cie.sec->file->getRelocTargetSym(rels[firstRelI]);
// Search for an existing CIE by CIE contents/relocation target pair.
CieRecord *&rec = cieMap[{cie.data(), personality}];
// If not found, create a new one.
if (!rec) {
rec = make<CieRecord>();
rec->cie = &cie;
cieRecords.push_back(rec);
}
return rec;
}
// There is one FDE per function. Returns a non-null pointer to the function
// symbol if the given FDE points to a live function.
template <class ELFT, class RelTy>
Defined *EhFrameSection::isFdeLive(EhSectionPiece &fde, ArrayRef<RelTy> rels) {
auto *sec = cast<EhInputSection>(fde.sec);
unsigned firstRelI = fde.firstRelocation;
// An FDE should point to some function because FDEs are to describe
// functions. That's however not always the case due to an issue of
// ld.gold with -r. ld.gold may discard only functions and leave their
// corresponding FDEs, which results in creating bad .eh_frame sections.
// To deal with that, we ignore such FDEs.
if (firstRelI == (unsigned)-1)
return nullptr;
const RelTy &rel = rels[firstRelI];
Symbol &b = sec->file->getRelocTargetSym(rel);
// FDEs for garbage-collected or merged-by-ICF sections, or sections in
// another partition, are dead.
if (auto *d = dyn_cast<Defined>(&b))
if (!d->folded && d->section && d->section->partition == partition)
return d;
return nullptr;
}
// .eh_frame is a sequence of CIE or FDE records. In general, there
// is one CIE record per input object file which is followed by
// a list of FDEs. This function searches an existing CIE or create a new
// one and associates FDEs to the CIE.
template <class ELFT, class RelTy>
void EhFrameSection::addRecords(EhInputSection *sec, ArrayRef<RelTy> rels) {
offsetToCie.clear();
for (EhSectionPiece &cie : sec->cies)
offsetToCie[cie.inputOff] = addCie<ELFT>(cie, rels);
for (EhSectionPiece &fde : sec->fdes) {
uint32_t id = endian::read32<ELFT::Endianness>(fde.data().data() + 4);
CieRecord *rec = offsetToCie[fde.inputOff + 4 - id];
if (!rec)
fatal(toString(sec) + ": invalid CIE reference");
if (!isFdeLive<ELFT>(fde, rels))
continue;
rec->fdes.push_back(&fde);
numFdes++;
}
}
template <class ELFT>
void EhFrameSection::addSectionAux(EhInputSection *sec) {
if (!sec->isLive())
return;
const RelsOrRelas<ELFT> rels = sec->template relsOrRelas<ELFT>();
if (rels.areRelocsRel())
addRecords<ELFT>(sec, rels.rels);
else
addRecords<ELFT>(sec, rels.relas);
}
// Used by ICF<ELFT>::handleLSDA(). This function is very similar to
// EhFrameSection::addRecords().
template <class ELFT, class RelTy>
void EhFrameSection::iterateFDEWithLSDAAux(
EhInputSection &sec, ArrayRef<RelTy> rels, DenseSet<size_t> &ciesWithLSDA,
llvm::function_ref<void(InputSection &)> fn) {
for (EhSectionPiece &cie : sec.cies)
if (hasLSDA(cie))
ciesWithLSDA.insert(cie.inputOff);
for (EhSectionPiece &fde : sec.fdes) {
uint32_t id = endian::read32<ELFT::Endianness>(fde.data().data() + 4);
if (!ciesWithLSDA.contains(fde.inputOff + 4 - id))
continue;
// The CIE has a LSDA argument. Call fn with d's section.
if (Defined *d = isFdeLive<ELFT>(fde, rels))
if (auto *s = dyn_cast_or_null<InputSection>(d->section))
fn(*s);
}
}
template <class ELFT>
void EhFrameSection::iterateFDEWithLSDA(
llvm::function_ref<void(InputSection &)> fn) {
DenseSet<size_t> ciesWithLSDA;
for (EhInputSection *sec : sections) {
ciesWithLSDA.clear();
const RelsOrRelas<ELFT> rels = sec->template relsOrRelas<ELFT>();
if (rels.areRelocsRel())
iterateFDEWithLSDAAux<ELFT>(*sec, rels.rels, ciesWithLSDA, fn);
else
iterateFDEWithLSDAAux<ELFT>(*sec, rels.relas, ciesWithLSDA, fn);
}
}
static void writeCieFde(uint8_t *buf, ArrayRef<uint8_t> d) {
memcpy(buf, d.data(), d.size());
// Fix the size field. -4 since size does not include the size field itself.
write32(buf, d.size() - 4);
}
void EhFrameSection::finalizeContents() {
assert(!this->size); // Not finalized.
switch (config->ekind) {
case ELFNoneKind:
llvm_unreachable("invalid ekind");
case ELF32LEKind:
for (EhInputSection *sec : sections)
addSectionAux<ELF32LE>(sec);
break;
case ELF32BEKind:
for (EhInputSection *sec : sections)
addSectionAux<ELF32BE>(sec);
break;
case ELF64LEKind:
for (EhInputSection *sec : sections)
addSectionAux<ELF64LE>(sec);
break;
case ELF64BEKind:
for (EhInputSection *sec : sections)
addSectionAux<ELF64BE>(sec);
break;
}
size_t off = 0;
for (CieRecord *rec : cieRecords) {
rec->cie->outputOff = off;
off += rec->cie->size;
for (EhSectionPiece *fde : rec->fdes) {
fde->outputOff = off;
off += fde->size;
}
}
// The LSB standard does not allow a .eh_frame section with zero
// Call Frame Information records. glibc unwind-dw2-fde.c
// classify_object_over_fdes expects there is a CIE record length 0 as a
// terminator. Thus we add one unconditionally.
off += 4;
this->size = off;
}
// Returns data for .eh_frame_hdr. .eh_frame_hdr is a binary search table
// to get an FDE from an address to which FDE is applied. This function
// returns a list of such pairs.
SmallVector<EhFrameSection::FdeData, 0> EhFrameSection::getFdeData() const {
uint8_t *buf = Out::bufferStart + getParent()->offset + outSecOff;
SmallVector<FdeData, 0> ret;
uint64_t va = getPartition().ehFrameHdr->getVA();
for (CieRecord *rec : cieRecords) {
uint8_t enc = getFdeEncoding(rec->cie);
for (EhSectionPiece *fde : rec->fdes) {
uint64_t pc = getFdePc(buf, fde->outputOff, enc);
uint64_t fdeVA = getParent()->addr + fde->outputOff;
if (!isInt<32>(pc - va)) {
errorOrWarn(toString(fde->sec) + ": PC offset is too large: 0x" +
Twine::utohexstr(pc - va));
continue;
}
ret.push_back({uint32_t(pc - va), uint32_t(fdeVA - va)});
}
}
// Sort the FDE list by their PC and uniqueify. Usually there is only
// one FDE for a PC (i.e. function), but if ICF merges two functions
// into one, there can be more than one FDEs pointing to the address.
auto less = [](const FdeData &a, const FdeData &b) {
return a.pcRel < b.pcRel;
};
llvm::stable_sort(ret, less);
auto eq = [](const FdeData &a, const FdeData &b) {
return a.pcRel == b.pcRel;
};
ret.erase(std::unique(ret.begin(), ret.end(), eq), ret.end());
return ret;
}
static uint64_t readFdeAddr(uint8_t *buf, int size) {
switch (size) {
case DW_EH_PE_udata2:
return read16(buf);
case DW_EH_PE_sdata2:
return (int16_t)read16(buf);
case DW_EH_PE_udata4:
return read32(buf);
case DW_EH_PE_sdata4:
return (int32_t)read32(buf);
case DW_EH_PE_udata8:
case DW_EH_PE_sdata8:
return read64(buf);
case DW_EH_PE_absptr:
return readUint(buf);
}
fatal("unknown FDE size encoding");
}
// Returns the VA to which a given FDE (on a mmap'ed buffer) is applied to.
// We need it to create .eh_frame_hdr section.
uint64_t EhFrameSection::getFdePc(uint8_t *buf, size_t fdeOff,
uint8_t enc) const {
// The starting address to which this FDE applies is
// stored at FDE + 8 byte. And this offset is within
// the .eh_frame section.
size_t off = fdeOff + 8;
uint64_t addr = readFdeAddr(buf + off, enc & 0xf);
if ((enc & 0x70) == DW_EH_PE_absptr)
return addr;
if ((enc & 0x70) == DW_EH_PE_pcrel)
return addr + getParent()->addr + off + outSecOff;
fatal("unknown FDE size relative encoding");
}
void EhFrameSection::writeTo(uint8_t *buf) {
// Write CIE and FDE records.
for (CieRecord *rec : cieRecords) {
size_t cieOffset = rec->cie->outputOff;
writeCieFde(buf + cieOffset, rec->cie->data());
for (EhSectionPiece *fde : rec->fdes) {
size_t off = fde->outputOff;
writeCieFde(buf + off, fde->data());
// FDE's second word should have the offset to an associated CIE.
// Write it.
write32(buf + off + 4, off + 4 - cieOffset);
}
}
// Apply relocations. .eh_frame section contents are not contiguous
// in the output buffer, but relocateAlloc() still works because
// getOffset() takes care of discontiguous section pieces.
for (EhInputSection *s : sections)
target->relocateAlloc(*s, buf);
if (getPartition().ehFrameHdr && getPartition().ehFrameHdr->getParent())
getPartition().ehFrameHdr->write();
}
GotSection::GotSection()
: SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
target->gotEntrySize, ".got") {
numEntries = target->gotHeaderEntriesNum;
}
void GotSection::addConstant(const Relocation &r) { relocations.push_back(r); }
void GotSection::addEntry(const Symbol &sym) {
assert(sym.auxIdx == symAux.size() - 1);
symAux.back().gotIdx = numEntries++;
}
bool GotSection::addTlsDescEntry(const Symbol &sym) {
assert(sym.auxIdx == symAux.size() - 1);
symAux.back().tlsDescIdx = numEntries;
numEntries += 2;
return true;
}
bool GotSection::addDynTlsEntry(const Symbol &sym) {
assert(sym.auxIdx == symAux.size() - 1);
symAux.back().tlsGdIdx = numEntries;
// Global Dynamic TLS entries take two GOT slots.
numEntries += 2;
return true;
}
// Reserves TLS entries for a TLS module ID and a TLS block offset.
// In total it takes two GOT slots.
bool GotSection::addTlsIndex() {
if (tlsIndexOff != uint32_t(-1))
return false;
tlsIndexOff = numEntries * config->wordsize;
numEntries += 2;
return true;
}
uint32_t GotSection::getTlsDescOffset(const Symbol &sym) const {
return sym.getTlsDescIdx() * config->wordsize;
}
uint64_t GotSection::getTlsDescAddr(const Symbol &sym) const {
return getVA() + getTlsDescOffset(sym);
}
uint64_t GotSection::getGlobalDynAddr(const Symbol &b) const {
return this->getVA() + b.getTlsGdIdx() * config->wordsize;
}
uint64_t GotSection::getGlobalDynOffset(const Symbol &b) const {
return b.getTlsGdIdx() * config->wordsize;
}
void GotSection::finalizeContents() {
if (config->emachine == EM_PPC64 &&
numEntries <= target->gotHeaderEntriesNum && !ElfSym::globalOffsetTable)
size = 0;
else
size = numEntries * config->wordsize;
}
bool GotSection::isNeeded() const {
// Needed if the GOT symbol is used or the number of entries is more than just
// the header. A GOT with just the header may not be needed.
return hasGotOffRel || numEntries > target->gotHeaderEntriesNum;
}
void GotSection::writeTo(uint8_t *buf) {
// On PPC64 .got may be needed but empty. Skip the write.
if (size == 0)
return;
target->writeGotHeader(buf);
target->relocateAlloc(*this, buf);
}
static uint64_t getMipsPageAddr(uint64_t addr) {
return (addr + 0x8000) & ~0xffff;
}
static uint64_t getMipsPageCount(uint64_t size) {
return (size + 0xfffe) / 0xffff + 1;
}
MipsGotSection::MipsGotSection()
: SyntheticSection(SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL, SHT_PROGBITS, 16,
".got") {}
void MipsGotSection::addEntry(InputFile &file, Symbol &sym, int64_t addend,
RelExpr expr) {
FileGot &g = getGot(file);
if (expr == R_MIPS_GOT_LOCAL_PAGE) {
if (const OutputSection *os = sym.getOutputSection())
g.pagesMap.insert({os, {}});
else
g.local16.insert({{nullptr, getMipsPageAddr(sym.getVA(addend))}, 0});
} else if (sym.isTls())
g.tls.insert({&sym, 0});
else if (sym.isPreemptible && expr == R_ABS)
g.relocs.insert({&sym, 0});
else if (sym.isPreemptible)
g.global.insert({&sym, 0});
else if (expr == R_MIPS_GOT_OFF32)
g.local32.insert({{&sym, addend}, 0});
else
g.local16.insert({{&sym, addend}, 0});
}
void MipsGotSection::addDynTlsEntry(InputFile &file, Symbol &sym) {
getGot(file).dynTlsSymbols.insert({&sym, 0});
}
void MipsGotSection::addTlsIndex(InputFile &file) {
getGot(file).dynTlsSymbols.insert({nullptr, 0});
}
size_t MipsGotSection::FileGot::getEntriesNum() const {
return getPageEntriesNum() + local16.size() + global.size() + relocs.size() +
tls.size() + dynTlsSymbols.size() * 2;
}
size_t MipsGotSection::FileGot::getPageEntriesNum() const {
size_t num = 0;
for (const std::pair<const OutputSection *, FileGot::PageBlock> &p : pagesMap)
num += p.second.count;
return num;
}
size_t MipsGotSection::FileGot::getIndexedEntriesNum() const {
size_t count = getPageEntriesNum() + local16.size() + global.size();
// If there are relocation-only entries in the GOT, TLS entries
// are allocated after them. TLS entries should be addressable
// by 16-bit index so count both reloc-only and TLS entries.
if (!tls.empty() || !dynTlsSymbols.empty())
count += relocs.size() + tls.size() + dynTlsSymbols.size() * 2;
return count;
}
MipsGotSection::FileGot &MipsGotSection::getGot(InputFile &f) {
if (f.mipsGotIndex == uint32_t(-1)) {
gots.emplace_back();
gots.back().file = &f;
f.mipsGotIndex = gots.size() - 1;
}
return gots[f.mipsGotIndex];
}
uint64_t MipsGotSection::getPageEntryOffset(const InputFile *f,
const Symbol &sym,
int64_t addend) const {
const FileGot &g = gots[f->mipsGotIndex];
uint64_t index = 0;
if (const OutputSection *outSec = sym.getOutputSection()) {
uint64_t secAddr = getMipsPageAddr(outSec->addr);
uint64_t symAddr = getMipsPageAddr(sym.getVA(addend));
index = g.pagesMap.lookup(outSec).firstIndex + (symAddr - secAddr) / 0xffff;
} else {
index = g.local16.lookup({nullptr, getMipsPageAddr(sym.getVA(addend))});
}
return index * config->wordsize;
}
uint64_t MipsGotSection::getSymEntryOffset(const InputFile *f, const Symbol &s,
int64_t addend) const {
const FileGot &g = gots[f->mipsGotIndex];
Symbol *sym = const_cast<Symbol *>(&s);
if (sym->isTls())
return g.tls.lookup(sym) * config->wordsize;
if (sym->isPreemptible)
return g.global.lookup(sym) * config->wordsize;
return g.local16.lookup({sym, addend}) * config->wordsize;
}
uint64_t MipsGotSection::getTlsIndexOffset(const InputFile *f) const {
const FileGot &g = gots[f->mipsGotIndex];
return g.dynTlsSymbols.lookup(nullptr) * config->wordsize;
}
uint64_t MipsGotSection::getGlobalDynOffset(const InputFile *f,
const Symbol &s) const {
const FileGot &g = gots[f->mipsGotIndex];
Symbol *sym = const_cast<Symbol *>(&s);
return g.dynTlsSymbols.lookup(sym) * config->wordsize;
}
const Symbol *MipsGotSection::getFirstGlobalEntry() const {
if (gots.empty())
return nullptr;
const FileGot &primGot = gots.front();
if (!primGot.global.empty())
return primGot.global.front().first;
if (!primGot.relocs.empty())
return primGot.relocs.front().first;
return nullptr;
}
unsigned MipsGotSection::getLocalEntriesNum() const {
if (gots.empty())
return headerEntriesNum;
return headerEntriesNum + gots.front().getPageEntriesNum() +
gots.front().local16.size();
}
bool MipsGotSection::tryMergeGots(FileGot &dst, FileGot &src, bool isPrimary) {
FileGot tmp = dst;
set_union(tmp.pagesMap, src.pagesMap);
set_union(tmp.local16, src.local16);
set_union(tmp.global, src.global);
set_union(tmp.relocs, src.relocs);
set_union(tmp.tls, src.tls);
set_union(tmp.dynTlsSymbols, src.dynTlsSymbols);
size_t count = isPrimary ? headerEntriesNum : 0;
count += tmp.getIndexedEntriesNum();
if (count * config->wordsize > config->mipsGotSize)
return false;
std::swap(tmp, dst);
return true;
}
void MipsGotSection::finalizeContents() { updateAllocSize(); }
bool MipsGotSection::updateAllocSize() {
size = headerEntriesNum * config->wordsize;
for (const FileGot &g : gots)
size += g.getEntriesNum() * config->wordsize;
return false;
}
void MipsGotSection::build() {
if (gots.empty())
return;
std::vector<FileGot> mergedGots(1);
// For each GOT move non-preemptible symbols from the `Global`
// to `Local16` list. Preemptible symbol might become non-preemptible
// one if, for example, it gets a related copy relocation.
for (FileGot &got : gots) {
for (auto &p: got.global)
if (!p.first->isPreemptible)
got.local16.insert({{p.first, 0}, 0});
got.global.remove_if([&](const std::pair<Symbol *, size_t> &p) {
return !p.first->isPreemptible;
});
}
// For each GOT remove "reloc-only" entry if there is "global"
// entry for the same symbol. And add local entries which indexed
// using 32-bit value at the end of 16-bit entries.
for (FileGot &got : gots) {
got.relocs.remove_if([&](const std::pair<Symbol *, size_t> &p) {
return got.global.count(p.first);
});
set_union(got.local16, got.local32);
got.local32.clear();
}
// Evaluate number of "reloc-only" entries in the resulting GOT.
// To do that put all unique "reloc-only" and "global" entries
// from all GOTs to the future primary GOT.
FileGot *primGot = &mergedGots.front();
for (FileGot &got : gots) {
set_union(primGot->relocs, got.global);
set_union(primGot->relocs, got.relocs);
got.relocs.clear();
}
// Evaluate number of "page" entries in each GOT.
for (FileGot &got : gots) {
for (std::pair<const OutputSection *, FileGot::PageBlock> &p :
got.pagesMap) {
const OutputSection *os = p.first;
uint64_t secSize = 0;
for (SectionCommand *cmd : os->commands) {
if (auto *isd = dyn_cast<InputSectionDescription>(cmd))
for (InputSection *isec : isd->sections) {
uint64_t off = alignToPowerOf2(secSize, isec->addralign);
secSize = off + isec->getSize();
}
}
p.second.count = getMipsPageCount(secSize);
}
}
// Merge GOTs. Try to join as much as possible GOTs but do not exceed
// maximum GOT size. At first, try to fill the primary GOT because
// the primary GOT can be accessed in the most effective way. If it
// is not possible, try to fill the last GOT in the list, and finally
// create a new GOT if both attempts failed.
for (FileGot &srcGot : gots) {
InputFile *file = srcGot.file;
if (tryMergeGots(mergedGots.front(), srcGot, true)) {
file->mipsGotIndex = 0;
} else {
// If this is the first time we failed to merge with the primary GOT,
// MergedGots.back() will also be the primary GOT. We must make sure not
// to try to merge again with isPrimary=false, as otherwise, if the
// inputs are just right, we could allow the primary GOT to become 1 or 2
// words bigger due to ignoring the header size.
if (mergedGots.size() == 1 ||
!tryMergeGots(mergedGots.back(), srcGot, false)) {
mergedGots.emplace_back();
std::swap(mergedGots.back(), srcGot);
}
file->mipsGotIndex = mergedGots.size() - 1;
}
}
std::swap(gots, mergedGots);
// Reduce number of "reloc-only" entries in the primary GOT
// by subtracting "global" entries in the primary GOT.
primGot = &gots.front();
primGot->relocs.remove_if([&](const std::pair<Symbol *, size_t> &p) {
return primGot->global.count(p.first);
});
// Calculate indexes for each GOT entry.
size_t index = headerEntriesNum;
for (FileGot &got : gots) {
got.startIndex = &got == primGot ? 0 : index;
for (std::pair<const OutputSection *, FileGot::PageBlock> &p :
got.pagesMap) {
// For each output section referenced by GOT page relocations calculate
// and save into pagesMap an upper bound of MIPS GOT entries required
// to store page addresses of local symbols. We assume the worst case -
// each 64kb page of the output section has at least one GOT relocation
// against it. And take in account the case when the section intersects
// page boundaries.
p.second.firstIndex = index;
index += p.second.count;
}
for (auto &p: got.local16)
p.second = index++;
for (auto &p: got.global)
p.second = index++;
for (auto &p: got.relocs)
p.second = index++;
for (auto &p: got.tls)
p.second = index++;
for (auto &p: got.dynTlsSymbols) {
p.second = index;
index += 2;
}
}
// Update SymbolAux::gotIdx field to use this
// value later in the `sortMipsSymbols` function.
for (auto &p : primGot->global) {
if (p.first->auxIdx == 0)
p.first->allocateAux();
symAux.back().gotIdx = p.second;
}
for (auto &p : primGot->relocs) {
if (p.first->auxIdx == 0)
p.first->allocateAux();
symAux.back().gotIdx = p.second;
}
// Create dynamic relocations.
for (FileGot &got : gots) {
// Create dynamic relocations for TLS entries.
for (std::pair<Symbol *, size_t> &p : got.tls) {
Symbol *s = p.first;
uint64_t offset = p.second * config->wordsize;
// When building a shared library we still need a dynamic relocation
// for the TP-relative offset as we don't know how much other data will
// be allocated before us in the static TLS block.
if (s->isPreemptible || config->shared)
mainPart->relaDyn->addReloc({target->tlsGotRel, this, offset,
DynamicReloc::AgainstSymbolWithTargetVA,
*s, 0, R_ABS});
}
for (std::pair<Symbol *, size_t> &p : got.dynTlsSymbols) {
Symbol *s = p.first;
uint64_t offset = p.second * config->wordsize;