-
Notifications
You must be signed in to change notification settings - Fork 10.8k
/
Writer.cpp
1552 lines (1359 loc) · 53.9 KB
/
Writer.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
//===- Writer.cpp ---------------------------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "Writer.h"
#include "Config.h"
#include "LinkerScript.h"
#include "OutputSections.h"
#include "SymbolTable.h"
#include "Target.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/FileOutputBuffer.h"
#include "llvm/Support/StringSaver.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
using namespace llvm::ELF;
using namespace llvm::object;
using namespace lld;
using namespace lld::elf;
namespace {
// The writer writes a SymbolTable result to a file.
template <class ELFT> class Writer {
public:
typedef typename ELFFile<ELFT>::uintX_t uintX_t;
typedef typename ELFFile<ELFT>::Elf_Shdr Elf_Shdr;
typedef typename ELFFile<ELFT>::Elf_Ehdr Elf_Ehdr;
typedef typename ELFFile<ELFT>::Elf_Phdr Elf_Phdr;
typedef typename ELFFile<ELFT>::Elf_Sym Elf_Sym;
typedef typename ELFFile<ELFT>::Elf_Sym_Range Elf_Sym_Range;
typedef typename ELFFile<ELFT>::Elf_Rela Elf_Rela;
Writer(SymbolTable<ELFT> &S) : Symtab(S) {}
void run();
private:
// This describes a program header entry.
// Each contains type, access flags and range of output sections that will be
// placed in it.
struct Phdr {
Phdr(unsigned Type, unsigned Flags) {
H.p_type = Type;
H.p_flags = Flags;
}
Elf_Phdr H = {};
OutputSectionBase<ELFT> *First = nullptr;
OutputSectionBase<ELFT> *Last = nullptr;
};
void copyLocalSymbols();
void addReservedSymbols();
bool createSections();
void addPredefinedSections();
bool needsGot();
template <bool isRela>
void scanRelocs(InputSectionBase<ELFT> &C,
iterator_range<const Elf_Rel_Impl<ELFT, isRela> *> Rels);
void scanRelocs(InputSection<ELFT> &C);
void scanRelocs(InputSectionBase<ELFT> &S, const Elf_Shdr &RelSec);
void createPhdrs();
void assignAddresses();
void assignAddressesRelocatable();
void fixAbsoluteSymbols();
bool openFile();
void writeHeader();
void writeSections();
bool isDiscarded(InputSectionBase<ELFT> *IS) const;
StringRef getOutputSectionName(InputSectionBase<ELFT> *S) const;
bool needsInterpSection() const {
return !Symtab.getSharedFiles().empty() && !Config->DynamicLinker.empty();
}
bool isOutputDynamic() const {
return !Symtab.getSharedFiles().empty() || Config->Shared;
}
OutputSection<ELFT> *getBss();
void addCommonSymbols(std::vector<DefinedCommon *> &Syms);
void addCopyRelSymbols(std::vector<SharedSymbol<ELFT> *> &Syms);
std::unique_ptr<llvm::FileOutputBuffer> Buffer;
BumpPtrAllocator Alloc;
std::vector<OutputSectionBase<ELFT> *> OutputSections;
std::vector<std::unique_ptr<OutputSectionBase<ELFT>>> OwningSections;
// We create a section for the ELF header and one for the program headers.
ArrayRef<OutputSectionBase<ELFT> *> getSections() const {
return makeArrayRef(OutputSections).slice(dummySectionsNum());
}
unsigned getNumSections() const {
return OutputSections.size() + 1 - dummySectionsNum();
}
// Usually there are 2 dummies sections: ELF header and program header.
// Relocatable output does not require program headers to be created.
unsigned dummySectionsNum() const { return Config->Relocatable ? 1 : 2; }
void addRelIpltSymbols();
void addStartEndSymbols();
void addStartStopSymbols(OutputSectionBase<ELFT> *Sec);
SymbolTable<ELFT> &Symtab;
std::vector<Phdr> Phdrs;
uintX_t FileSize;
uintX_t SectionHeaderOff;
// Flag to force GOT to be in output if we have relocations
// that relies on its address.
bool HasGotOffRel = false;
};
} // anonymous namespace
template <class ELFT> static bool shouldUseRela() { return ELFT::Is64Bits; }
template <class ELFT> void elf::writeResult(SymbolTable<ELFT> *Symtab) {
typedef typename ELFFile<ELFT>::uintX_t uintX_t;
// Create singleton output sections.
bool IsRela = shouldUseRela<ELFT>();
DynamicSection<ELFT> Dynamic(*Symtab);
EhFrameHeader<ELFT> EhFrameHdr;
GotSection<ELFT> Got;
InterpSection<ELFT> Interp;
PltSection<ELFT> Plt;
RelocationSection<ELFT> RelaDyn(IsRela ? ".rela.dyn" : ".rel.dyn", IsRela);
StringTableSection<ELFT> DynStrTab(".dynstr", true);
StringTableSection<ELFT> ShStrTab(".shstrtab", false);
SymbolTableSection<ELFT> DynSymTab(*Symtab, DynStrTab);
OutputSectionBase<ELFT> ElfHeader("", 0, SHF_ALLOC);
OutputSectionBase<ELFT> ProgramHeaders("", 0, SHF_ALLOC);
ProgramHeaders.updateAlign(sizeof(uintX_t));
// Instantiate optional output sections if they are needed.
std::unique_ptr<GnuHashTableSection<ELFT>> GnuHashTab;
std::unique_ptr<GotPltSection<ELFT>> GotPlt;
std::unique_ptr<HashTableSection<ELFT>> HashTab;
std::unique_ptr<RelocationSection<ELFT>> RelaPlt;
std::unique_ptr<StringTableSection<ELFT>> StrTab;
std::unique_ptr<SymbolTableSection<ELFT>> SymTabSec;
std::unique_ptr<OutputSection<ELFT>> MipsRldMap;
if (Config->GnuHash)
GnuHashTab.reset(new GnuHashTableSection<ELFT>);
if (Config->SysvHash)
HashTab.reset(new HashTableSection<ELFT>);
if (Target->UseLazyBinding) {
StringRef S = IsRela ? ".rela.plt" : ".rel.plt";
GotPlt.reset(new GotPltSection<ELFT>);
RelaPlt.reset(new RelocationSection<ELFT>(S, IsRela));
}
if (!Config->StripAll) {
StrTab.reset(new StringTableSection<ELFT>(".strtab", false));
SymTabSec.reset(new SymbolTableSection<ELFT>(*Symtab, *StrTab));
}
if (Config->EMachine == EM_MIPS && !Config->Shared) {
// This is a MIPS specific section to hold a space within the data segment
// of executable file which is pointed to by the DT_MIPS_RLD_MAP entry.
// See "Dynamic section" in Chapter 5 in the following document:
// ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
MipsRldMap.reset(new OutputSection<ELFT>(".rld_map", SHT_PROGBITS,
SHF_ALLOC | SHF_WRITE));
MipsRldMap->setSize(sizeof(uintX_t));
MipsRldMap->updateAlign(sizeof(uintX_t));
}
Out<ELFT>::DynStrTab = &DynStrTab;
Out<ELFT>::DynSymTab = &DynSymTab;
Out<ELFT>::Dynamic = &Dynamic;
Out<ELFT>::EhFrameHdr = &EhFrameHdr;
Out<ELFT>::GnuHashTab = GnuHashTab.get();
Out<ELFT>::Got = &Got;
Out<ELFT>::GotPlt = GotPlt.get();
Out<ELFT>::HashTab = HashTab.get();
Out<ELFT>::Interp = &Interp;
Out<ELFT>::Plt = &Plt;
Out<ELFT>::RelaDyn = &RelaDyn;
Out<ELFT>::RelaPlt = RelaPlt.get();
Out<ELFT>::ShStrTab = &ShStrTab;
Out<ELFT>::StrTab = StrTab.get();
Out<ELFT>::SymTab = SymTabSec.get();
Out<ELFT>::Bss = nullptr;
Out<ELFT>::MipsRldMap = MipsRldMap.get();
Out<ELFT>::Opd = nullptr;
Out<ELFT>::OpdBuf = nullptr;
Out<ELFT>::TlsPhdr = nullptr;
Out<ELFT>::ElfHeader = &ElfHeader;
Out<ELFT>::ProgramHeaders = &ProgramHeaders;
Writer<ELFT>(*Symtab).run();
}
// The main function of the writer.
template <class ELFT> void Writer<ELFT>::run() {
if (!Config->DiscardAll)
copyLocalSymbols();
addReservedSymbols();
if (!createSections())
return;
if (!Config->Relocatable) {
createPhdrs();
assignAddresses();
} else {
assignAddressesRelocatable();
}
fixAbsoluteSymbols();
if (!openFile())
return;
writeHeader();
writeSections();
if (HasError)
return;
fatal(Buffer->commit());
}
namespace {
template <bool Is64Bits> struct SectionKey {
typedef typename std::conditional<Is64Bits, uint64_t, uint32_t>::type uintX_t;
StringRef Name;
uint32_t Type;
uintX_t Flags;
uintX_t Alignment;
};
}
namespace llvm {
template <bool Is64Bits> struct DenseMapInfo<SectionKey<Is64Bits>> {
static SectionKey<Is64Bits> getEmptyKey() {
return SectionKey<Is64Bits>{DenseMapInfo<StringRef>::getEmptyKey(), 0, 0,
0};
}
static SectionKey<Is64Bits> getTombstoneKey() {
return SectionKey<Is64Bits>{DenseMapInfo<StringRef>::getTombstoneKey(), 0,
0, 0};
}
static unsigned getHashValue(const SectionKey<Is64Bits> &Val) {
return hash_combine(Val.Name, Val.Type, Val.Flags, Val.Alignment);
}
static bool isEqual(const SectionKey<Is64Bits> &LHS,
const SectionKey<Is64Bits> &RHS) {
return DenseMapInfo<StringRef>::isEqual(LHS.Name, RHS.Name) &&
LHS.Type == RHS.Type && LHS.Flags == RHS.Flags &&
LHS.Alignment == RHS.Alignment;
}
};
}
template <class ELFT, class RelT>
static bool handleTlsRelocation(unsigned Type, SymbolBody *Body,
InputSectionBase<ELFT> &C, RelT &RI) {
if (Target->isTlsLocalDynamicRel(Type)) {
if (Target->canRelaxTls(Type, nullptr))
return true;
if (Out<ELFT>::Got->addTlsIndex())
Out<ELFT>::RelaDyn->addReloc({Target->TlsModuleIndexRel,
DynamicReloc<ELFT>::Off_LTlsIndex,
nullptr});
return true;
}
if (!Body || !Body->IsTls)
return false;
if (Target->isTlsGlobalDynamicRel(Type)) {
if (!Target->canRelaxTls(Type, Body)) {
if (Out<ELFT>::Got->addDynTlsEntry(Body)) {
Out<ELFT>::RelaDyn->addReloc({Target->TlsModuleIndexRel,
DynamicReloc<ELFT>::Off_GTlsIndex, Body});
Out<ELFT>::RelaDyn->addReloc(
{Target->TlsOffsetRel, DynamicReloc<ELFT>::Off_GTlsOffset, Body});
}
return true;
}
if (!canBePreempted(Body))
return true;
}
return !Target->isTlsDynRel(Type, *Body);
}
// The reason we have to do this early scan is as follows
// * To mmap the output file, we need to know the size
// * For that, we need to know how many dynamic relocs we will have.
// It might be possible to avoid this by outputting the file with write:
// * Write the allocated output sections, computing addresses.
// * Apply relocations, recording which ones require a dynamic reloc.
// * Write the dynamic relocations.
// * Write the rest of the file.
// This would have some drawbacks. For example, we would only know if .rela.dyn
// is needed after applying relocations. If it is, it will go after rw and rx
// sections. Given that it is ro, we will need an extra PT_LOAD. This
// complicates things for the dynamic linker and means we would have to reserve
// space for the extra PT_LOAD even if we end up not using it.
template <class ELFT>
template <bool isRela>
void Writer<ELFT>::scanRelocs(
InputSectionBase<ELFT> &C,
iterator_range<const Elf_Rel_Impl<ELFT, isRela> *> Rels) {
typedef Elf_Rel_Impl<ELFT, isRela> RelType;
const ObjectFile<ELFT> &File = *C.getFile();
for (const RelType &RI : Rels) {
uint32_t SymIndex = RI.getSymbol(Config->Mips64EL);
SymbolBody *Body = File.getSymbolBody(SymIndex);
uint32_t Type = RI.getType(Config->Mips64EL);
// Ignore "hint" relocation because it is for optional code optimization.
if (Target->isHintRel(Type))
continue;
if (Target->isGotRelative(Type))
HasGotOffRel = true;
// Set "used" bit for --as-needed.
if (Body && Body->isUndefined() && !Body->isWeak())
if (auto *S = dyn_cast<SharedSymbol<ELFT>>(Body->repl()))
S->File->IsUsed = true;
if (Body)
Body = Body->repl();
bool CBP = canBePreempted(Body);
if (handleTlsRelocation<ELFT>(Type, Body, C, RI))
continue;
if (Target->needsDynRelative(Type))
Out<ELFT>::RelaDyn->addReloc({Target->RelativeRel, &C, RI.r_offset, true,
Body, getAddend<ELFT>(RI)});
// MIPS has a special rule to create GOTs for local symbols.
if (Config->EMachine == EM_MIPS && !CBP &&
(Type == R_MIPS_GOT16 || Type == R_MIPS_CALL16)) {
// FIXME (simon): Do not add so many redundant entries.
Out<ELFT>::Got->addMipsLocalEntry();
continue;
}
// If a symbol in a DSO is referenced directly instead of through GOT,
// we need to create a copy relocation for the symbol.
if (auto *B = dyn_cast_or_null<SharedSymbol<ELFT>>(Body)) {
if (B->needsCopy())
continue;
if (Target->needsCopyRel<ELFT>(Type, *B)) {
B->NeedsCopyOrPltAddr = true;
Out<ELFT>::RelaDyn->addReloc(
{Target->CopyRel, DynamicReloc<ELFT>::Off_Bss, B});
continue;
}
}
// An STT_GNU_IFUNC symbol always uses a PLT entry, and all references
// to the symbol go through the PLT. This is true even for a local
// symbol, although local symbols normally do not require PLT entries.
if (Body && isGnuIFunc<ELFT>(*Body)) {
if (Body->isInPlt())
continue;
Out<ELFT>::Plt->addEntry(Body);
if (Target->UseLazyBinding) {
Out<ELFT>::GotPlt->addEntry(Body);
Out<ELFT>::RelaPlt->addReloc(
{CBP ? Target->PltRel : Target->IRelativeRel,
DynamicReloc<ELFT>::Off_GotPlt, !CBP, Body});
} else {
Out<ELFT>::Got->addEntry(Body);
Out<ELFT>::RelaDyn->addReloc(
{CBP ? Target->PltRel : Target->IRelativeRel,
DynamicReloc<ELFT>::Off_Got, !CBP, Body});
}
continue;
}
// If a relocation needs PLT, we create a PLT and a GOT slot
// for the symbol.
TargetInfo::PltNeed NeedPlt = TargetInfo::Plt_No;
if (Body)
NeedPlt = Target->needsPlt<ELFT>(Type, *Body);
if (NeedPlt) {
if (NeedPlt == TargetInfo::Plt_Implicit)
Body->NeedsCopyOrPltAddr = true;
if (Body->isInPlt())
continue;
Out<ELFT>::Plt->addEntry(Body);
if (Target->UseLazyBinding) {
Out<ELFT>::GotPlt->addEntry(Body);
Out<ELFT>::RelaPlt->addReloc(
{Target->PltRel, DynamicReloc<ELFT>::Off_GotPlt, Body});
} else {
if (Body->isInGot())
continue;
Out<ELFT>::Got->addEntry(Body);
Out<ELFT>::RelaDyn->addReloc(
{Target->GotRel, DynamicReloc<ELFT>::Off_Got, Body});
}
continue;
}
// If a relocation needs GOT, we create a GOT slot for the symbol.
if (Body && Target->needsGot(Type, *Body)) {
if (Body->isInGot())
continue;
Out<ELFT>::Got->addEntry(Body);
if (Config->EMachine == EM_MIPS) {
// MIPS ABI has special rules to process GOT entries
// and doesn't require relocation entries for them.
// See "Global Offset Table" in Chapter 5 in the following document
// for detailed description:
// ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
Body->MustBeInDynSym = true;
continue;
}
bool Dynrel = Config->Shared && !Target->isRelRelative(Type) &&
!Target->isSizeRel(Type);
if (CBP || Dynrel) {
uint32_t DynType;
if (CBP)
DynType = Body->IsTls ? Target->TlsGotRel : Target->GotRel;
else
DynType = Target->RelativeRel;
Out<ELFT>::RelaDyn->addReloc(
{DynType, DynamicReloc<ELFT>::Off_Got, !CBP, Body});
}
continue;
}
if (Config->EMachine == EM_MIPS) {
if (Type == R_MIPS_LO16)
// Ignore R_MIPS_LO16 relocation. If it is a pair for R_MIPS_GOT16 we
// already completed all required action (GOT entry allocation) when
// handle R_MIPS_GOT16a. If it is a pair for R_MIPS_HI16 against
// _gp_disp it does not require dynamic relocation. If its a pair for
// R_MIPS_HI16 against a regular symbol it does not require dynamic
// relocation too because that case is possible for executable file
// linking only.
continue;
if (Body == Config->MipsGpDisp || Body == Config->MipsLocalGp)
// MIPS _gp_disp designates offset between start of function and 'gp'
// pointer into GOT. __gnu_local_gp is equal to the current value of
// the 'gp'. Therefore any relocations against them do not require
// dynamic relocation.
continue;
}
if (CBP) {
// We don't know anything about the finaly symbol. Just ask the dynamic
// linker to handle the relocation for us.
Out<ELFT>::RelaDyn->addReloc({Target->getDynRel(Type), &C, RI.r_offset,
false, Body, getAddend<ELFT>(RI)});
continue;
}
// We know that this is the final symbol. If the program being produced
// is position independent, the final value is still not known.
// If the relocation depends on the symbol value (not the size or distances
// in the output), we still need some help from the dynamic linker.
// We can however do better than just copying the incoming relocation. We
// can process some of it and and just ask the dynamic linker to add the
// load address.
if (!Config->Shared || Target->isRelRelative(Type) ||
Target->isSizeRel(Type))
continue;
uintX_t Addend = getAddend<ELFT>(RI);
if (Config->EMachine == EM_PPC64 && RI.getType(false) == R_PPC64_TOC) {
Out<ELFT>::RelaDyn->addReloc({R_PPC64_RELATIVE, &C, RI.r_offset, false,
nullptr,
(uintX_t)getPPC64TocBase() + Addend});
continue;
}
if (Body) {
Out<ELFT>::RelaDyn->addReloc(
{Target->RelativeRel, &C, RI.r_offset, true, Body, Addend});
continue;
}
const Elf_Sym *Sym =
File.getObj().getRelocationSymbol(&RI, File.getSymbolTable());
InputSectionBase<ELFT> *Section = File.getSection(*Sym);
uintX_t Offset = Sym->st_value;
if (Sym->getType() == STT_SECTION) {
Offset += Addend;
Addend = 0;
}
Out<ELFT>::RelaDyn->addReloc(
{Target->RelativeRel, &C, RI.r_offset, Section, Offset, Addend});
}
}
template <class ELFT> void Writer<ELFT>::scanRelocs(InputSection<ELFT> &C) {
if (C.getSectionHdr()->sh_flags & SHF_ALLOC)
for (const Elf_Shdr *RelSec : C.RelocSections)
scanRelocs(C, *RelSec);
}
template <class ELFT>
void Writer<ELFT>::scanRelocs(InputSectionBase<ELFT> &S,
const Elf_Shdr &RelSec) {
ELFFile<ELFT> &EObj = S.getFile()->getObj();
if (RelSec.sh_type == SHT_RELA)
scanRelocs(S, EObj.relas(&RelSec));
else
scanRelocs(S, EObj.rels(&RelSec));
}
template <class ELFT>
static void reportUndefined(SymbolTable<ELFT> &Symtab, SymbolBody *Sym) {
if ((Config->Relocatable || Config->Shared) && !Config->NoUndefined)
return;
std::string Msg = "undefined symbol: " + Sym->getName().str();
if (InputFile *File = Symtab.findFile(Sym))
Msg += " in " + File->getName().str();
if (Config->NoInhibitExec)
warning(Msg);
else
error(Msg);
}
template <class ELFT>
static bool shouldKeepInSymtab(const ObjectFile<ELFT> &File, StringRef SymName,
const typename ELFFile<ELFT>::Elf_Sym &Sym) {
if (Sym.getType() == STT_SECTION || Sym.getType() == STT_FILE)
return false;
InputSectionBase<ELFT> *Sec = File.getSection(Sym);
// If sym references a section in a discarded group, don't keep it.
if (Sec == InputSection<ELFT>::Discarded)
return false;
if (Config->DiscardNone)
return true;
// In ELF assembly .L symbols are normally discarded by the assembler.
// If the assembler fails to do so, the linker discards them if
// * --discard-locals is used.
// * The symbol is in a SHF_MERGE section, which is normally the reason for
// the assembler keeping the .L symbol.
if (!SymName.startswith(".L") && !SymName.empty())
return true;
if (Config->DiscardLocals)
return false;
return !(Sec->getSectionHdr()->sh_flags & SHF_MERGE);
}
// Local symbols are not in the linker's symbol table. This function scans
// each object file's symbol table to copy local symbols to the output.
template <class ELFT> void Writer<ELFT>::copyLocalSymbols() {
if (!Out<ELFT>::SymTab)
return;
for (const std::unique_ptr<ObjectFile<ELFT>> &F : Symtab.getObjectFiles()) {
for (const Elf_Sym &Sym : F->getLocalSymbols()) {
ErrorOr<StringRef> SymNameOrErr = Sym.getName(F->getStringTable());
fatal(SymNameOrErr);
StringRef SymName = *SymNameOrErr;
if (!shouldKeepInSymtab<ELFT>(*F, SymName, Sym))
continue;
if (Sym.st_shndx != SHN_ABS) {
InputSectionBase<ELFT> *Section = F->getSection(Sym);
if (!Section->Live)
continue;
}
++Out<ELFT>::SymTab->NumLocals;
F->KeptLocalSyms.push_back(std::make_pair(
&Sym, Out<ELFT>::SymTab->StrTabSec.addString(SymName)));
}
}
}
// PPC64 has a number of special SHT_PROGBITS+SHF_ALLOC+SHF_WRITE sections that
// we would like to make sure appear is a specific order to maximize their
// coverage by a single signed 16-bit offset from the TOC base pointer.
// Conversely, the special .tocbss section should be first among all SHT_NOBITS
// sections. This will put it next to the loaded special PPC64 sections (and,
// thus, within reach of the TOC base pointer).
static int getPPC64SectionRank(StringRef SectionName) {
return StringSwitch<int>(SectionName)
.Case(".tocbss", 0)
.Case(".branch_lt", 2)
.Case(".toc", 3)
.Case(".toc1", 4)
.Case(".opd", 5)
.Default(1);
}
template <class ELFT> static bool isRelroSection(OutputSectionBase<ELFT> *Sec) {
if (!Config->ZRelro)
return false;
typename OutputSectionBase<ELFT>::uintX_t Flags = Sec->getFlags();
if (!(Flags & SHF_ALLOC) || !(Flags & SHF_WRITE))
return false;
if (Flags & SHF_TLS)
return true;
uint32_t Type = Sec->getType();
if (Type == SHT_INIT_ARRAY || Type == SHT_FINI_ARRAY ||
Type == SHT_PREINIT_ARRAY)
return true;
if (Sec == Out<ELFT>::GotPlt)
return Config->ZNow;
if (Sec == Out<ELFT>::Dynamic || Sec == Out<ELFT>::Got)
return true;
StringRef S = Sec->getName();
return S == ".data.rel.ro" || S == ".ctors" || S == ".dtors" || S == ".jcr" ||
S == ".eh_frame";
}
// Output section ordering is determined by this function.
template <class ELFT>
static bool compareSections(OutputSectionBase<ELFT> *A,
OutputSectionBase<ELFT> *B) {
typedef typename ELFFile<ELFT>::uintX_t uintX_t;
int Comp = Script->compareSections(A->getName(), B->getName());
if (Comp != 0)
return Comp < 0;
uintX_t AFlags = A->getFlags();
uintX_t BFlags = B->getFlags();
// Allocatable sections go first to reduce the total PT_LOAD size and
// so debug info doesn't change addresses in actual code.
bool AIsAlloc = AFlags & SHF_ALLOC;
bool BIsAlloc = BFlags & SHF_ALLOC;
if (AIsAlloc != BIsAlloc)
return AIsAlloc;
// We don't have any special requirements for the relative order of
// two non allocatable sections.
if (!AIsAlloc)
return false;
// We want the read only sections first so that they go in the PT_LOAD
// covering the program headers at the start of the file.
bool AIsWritable = AFlags & SHF_WRITE;
bool BIsWritable = BFlags & SHF_WRITE;
if (AIsWritable != BIsWritable)
return BIsWritable;
// For a corresponding reason, put non exec sections first (the program
// header PT_LOAD is not executable).
bool AIsExec = AFlags & SHF_EXECINSTR;
bool BIsExec = BFlags & SHF_EXECINSTR;
if (AIsExec != BIsExec)
return BIsExec;
// If we got here we know that both A and B are in the same PT_LOAD.
// The TLS initialization block needs to be a single contiguous block in a R/W
// PT_LOAD, so stick TLS sections directly before R/W sections. The TLS NOBITS
// sections are placed here as they don't take up virtual address space in the
// PT_LOAD.
bool AIsTls = AFlags & SHF_TLS;
bool BIsTls = BFlags & SHF_TLS;
if (AIsTls != BIsTls)
return AIsTls;
// The next requirement we have is to put nobits sections last. The
// reason is that the only thing the dynamic linker will see about
// them is a p_memsz that is larger than p_filesz. Seeing that it
// zeros the end of the PT_LOAD, so that has to correspond to the
// nobits sections.
bool AIsNoBits = A->getType() == SHT_NOBITS;
bool BIsNoBits = B->getType() == SHT_NOBITS;
if (AIsNoBits != BIsNoBits)
return BIsNoBits;
// We place RelRo section before plain r/w ones.
bool AIsRelRo = isRelroSection(A);
bool BIsRelRo = isRelroSection(B);
if (AIsRelRo != BIsRelRo)
return AIsRelRo;
// Some architectures have additional ordering restrictions for sections
// within the same PT_LOAD.
if (Config->EMachine == EM_PPC64)
return getPPC64SectionRank(A->getName()) <
getPPC64SectionRank(B->getName());
return false;
}
template <class ELFT> OutputSection<ELFT> *Writer<ELFT>::getBss() {
if (!Out<ELFT>::Bss) {
Out<ELFT>::Bss =
new OutputSection<ELFT>(".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE);
OwningSections.emplace_back(Out<ELFT>::Bss);
OutputSections.push_back(Out<ELFT>::Bss);
}
return Out<ELFT>::Bss;
}
// Until this function is called, common symbols do not belong to any section.
// This function adds them to end of BSS section.
template <class ELFT>
void Writer<ELFT>::addCommonSymbols(std::vector<DefinedCommon *> &Syms) {
if (Syms.empty())
return;
// Sort the common symbols by alignment as an heuristic to pack them better.
std::stable_sort(Syms.begin(), Syms.end(),
[](const DefinedCommon *A, const DefinedCommon *B) {
return A->MaxAlignment > B->MaxAlignment;
});
uintX_t Off = getBss()->getSize();
for (DefinedCommon *C : Syms) {
Off = alignTo(Off, C->MaxAlignment);
C->OffsetInBss = Off;
Off += C->Size;
}
Out<ELFT>::Bss->setSize(Off);
}
// Reserve space in .bss for copy relocations.
template <class ELFT>
void Writer<ELFT>::addCopyRelSymbols(std::vector<SharedSymbol<ELFT> *> &Syms) {
if (Syms.empty())
return;
uintX_t Off = getBss()->getSize();
for (SharedSymbol<ELFT> *C : Syms) {
const Elf_Sym &Sym = C->Sym;
const Elf_Shdr *Sec = C->File->getSection(Sym);
uintX_t SecAlign = Sec->sh_addralign;
unsigned TrailingZeros =
std::min(countTrailingZeros(SecAlign),
countTrailingZeros((uintX_t)Sym.st_value));
uintX_t Align = 1 << TrailingZeros;
Out<ELFT>::Bss->updateAlign(Align);
Off = alignTo(Off, Align);
C->OffsetInBss = Off;
Off += Sym.st_size;
}
Out<ELFT>::Bss->setSize(Off);
}
template <class ELFT>
StringRef Writer<ELFT>::getOutputSectionName(InputSectionBase<ELFT> *S) const {
StringRef Dest = Script->getOutputSection<ELFT>(S);
if (!Dest.empty())
return Dest;
StringRef Name = S->getSectionName();
for (StringRef V : {".text.", ".rodata.", ".data.rel.ro.", ".data.", ".bss.",
".init_array.", ".fini_array.", ".ctors.", ".dtors.",
".tbss.", ".gcc_except_table.", ".tdata."})
if (Name.startswith(V))
return V.drop_back();
return Name;
}
template <class ELFT>
void reportDiscarded(InputSectionBase<ELFT> *IS,
const std::unique_ptr<ObjectFile<ELFT>> &File) {
if (!Config->PrintGcSections || !IS || IS->Live)
return;
llvm::errs() << "removing unused section from '" << IS->getSectionName()
<< "' in file '" << File->getName() << "'\n";
}
template <class ELFT>
bool Writer<ELFT>::isDiscarded(InputSectionBase<ELFT> *S) const {
return !S || S == InputSection<ELFT>::Discarded || !S->Live ||
Script->isDiscarded(S);
}
// The beginning and the ending of .rel[a].plt section are marked
// with __rel[a]_iplt_{start,end} symbols if it is a statically linked
// executable. The runtime needs these symbols in order to resolve
// all IRELATIVE relocs on startup. For dynamic executables, we don't
// need these symbols, since IRELATIVE relocs are resolved through GOT
// and PLT. For details, see http://www.airs.com/blog/archives/403.
template <class ELFT>
void Writer<ELFT>::addRelIpltSymbols() {
if (isOutputDynamic() || !Out<ELFT>::RelaPlt)
return;
bool IsRela = shouldUseRela<ELFT>();
StringRef S = IsRela ? "__rela_iplt_start" : "__rel_iplt_start";
if (Symtab.find(S))
Symtab.addAbsolute(S, ElfSym<ELFT>::RelaIpltStart);
S = IsRela ? "__rela_iplt_end" : "__rel_iplt_end";
if (Symtab.find(S))
Symtab.addAbsolute(S, ElfSym<ELFT>::RelaIpltEnd);
}
template <class ELFT> static bool includeInSymtab(const SymbolBody &B) {
if (!B.isUsedInRegularObj())
return false;
if (auto *D = dyn_cast<DefinedRegular<ELFT>>(&B)) {
// Don't include synthetic symbols like __init_array_start in every output.
if (&D->Sym == &ElfSym<ELFT>::Ignored)
return false;
// Exclude symbols pointing to garbage-collected sections.
if (D->Section && !D->Section->Live)
return false;
}
return true;
}
static bool includeInDynsym(const SymbolBody &B) {
uint8_t V = B.getVisibility();
if (V != STV_DEFAULT && V != STV_PROTECTED)
return false;
if (Config->ExportDynamic || Config->Shared)
return true;
return B.MustBeInDynSym;
}
// This class knows how to create an output section for a given
// input section. Output section type is determined by various
// factors, including input section's sh_flags, sh_type and
// linker scripts.
namespace {
template <class ELFT> class OutputSectionFactory {
typedef typename ELFFile<ELFT>::Elf_Shdr Elf_Shdr;
typedef typename ELFFile<ELFT>::uintX_t uintX_t;
public:
std::pair<OutputSectionBase<ELFT> *, bool> create(InputSectionBase<ELFT> *C,
StringRef OutsecName);
OutputSectionBase<ELFT> *lookup(StringRef Name, uint32_t Type, uintX_t Flags);
private:
SectionKey<ELFT::Is64Bits> createKey(InputSectionBase<ELFT> *C,
StringRef OutsecName);
SmallDenseMap<SectionKey<ELFT::Is64Bits>, OutputSectionBase<ELFT> *> Map;
};
}
template <class ELFT>
std::pair<OutputSectionBase<ELFT> *, bool>
OutputSectionFactory<ELFT>::create(InputSectionBase<ELFT> *C,
StringRef OutsecName) {
SectionKey<ELFT::Is64Bits> Key = createKey(C, OutsecName);
OutputSectionBase<ELFT> *&Sec = Map[Key];
if (Sec)
return {Sec, false};
switch (C->SectionKind) {
case InputSectionBase<ELFT>::Regular:
Sec = new OutputSection<ELFT>(Key.Name, Key.Type, Key.Flags);
break;
case InputSectionBase<ELFT>::EHFrame:
Sec = new EHOutputSection<ELFT>(Key.Name, Key.Type, Key.Flags);
break;
case InputSectionBase<ELFT>::Merge:
Sec = new MergeOutputSection<ELFT>(Key.Name, Key.Type, Key.Flags,
Key.Alignment);
break;
case InputSectionBase<ELFT>::MipsReginfo:
Sec = new MipsReginfoOutputSection<ELFT>();
break;
}
return {Sec, true};
}
template <class ELFT>
OutputSectionBase<ELFT> *OutputSectionFactory<ELFT>::lookup(StringRef Name,
uint32_t Type,
uintX_t Flags) {
return Map.lookup({Name, Type, Flags, 0});
}
template <class ELFT>
SectionKey<ELFT::Is64Bits>
OutputSectionFactory<ELFT>::createKey(InputSectionBase<ELFT> *C,
StringRef OutsecName) {
const Elf_Shdr *H = C->getSectionHdr();
uintX_t Flags = H->sh_flags & ~SHF_GROUP;
// For SHF_MERGE we create different output sections for each alignment.
// This makes each output section simple and keeps a single level mapping from
// input to output.
uintX_t Alignment = 0;
if (isa<MergeInputSection<ELFT>>(C)) {
Alignment = H->sh_addralign;
if (H->sh_entsize > Alignment)
Alignment = H->sh_entsize;
}
// GNU as can give .eh_frame secion type SHT_PROGBITS or SHT_X86_64_UNWIND
// depending on the construct. We want to canonicalize it so that
// there is only one .eh_frame in the end.
uint32_t Type = H->sh_type;
if (Type == SHT_PROGBITS && Config->EMachine == EM_X86_64 &&
isa<EHInputSection<ELFT>>(C))
Type = SHT_X86_64_UNWIND;
return SectionKey<ELFT::Is64Bits>{OutsecName, Type, Flags, Alignment};
}
// The linker is expected to define some symbols depending on
// the linking result. This function defines such symbols.
template <class ELFT> void Writer<ELFT>::addReservedSymbols() {
// __tls_get_addr is defined by the dynamic linker for dynamic ELFs. For
// static linking the linker is required to optimize away any references to
// __tls_get_addr, so it's not defined anywhere. Create a hidden definition
// to avoid the undefined symbol error.
if (!isOutputDynamic())
Symtab.addIgnored("__tls_get_addr");
auto Define = [this](StringRef S, Elf_Sym &Sym) {
if (Symtab.find(S))
Symtab.addAbsolute(S, Sym);
// The name without the underscore is not a reserved name,
// so it is defined only when there is a reference against it.
assert(S.startswith("_"));
S = S.substr(1);
if (SymbolBody *B = Symtab.find(S))
if (B->isUndefined())
Symtab.addAbsolute(S, Sym);
};
Define("_end", ElfSym<ELFT>::End);
Define("_etext", ElfSym<ELFT>::Etext);
Define("_edata", ElfSym<ELFT>::Edata);
}
// Sort input sections by section name suffixes for
// __attribute__((init_priority(N))).
template <class ELFT> static void sortInitFini(OutputSectionBase<ELFT> *S) {
if (S)
reinterpret_cast<OutputSection<ELFT> *>(S)->sortInitFini();
}
// Sort input sections by the special rule for .ctors and .dtors.
template <class ELFT> static void sortCtorsDtors(OutputSectionBase<ELFT> *S) {
if (S)
reinterpret_cast<OutputSection<ELFT> *>(S)->sortCtorsDtors();
}
// Create output section objects and add them to OutputSections.
template <class ELFT> bool Writer<ELFT>::createSections() {
OutputSections.push_back(Out<ELFT>::ElfHeader);
if (!Config->Relocatable)
OutputSections.push_back(Out<ELFT>::ProgramHeaders);
// Add .interp first because some loaders want to see that section
// on the first page of the executable file when loaded into memory.
if (needsInterpSection())
OutputSections.push_back(Out<ELFT>::Interp);
// Create output sections for input object file sections.
std::vector<OutputSectionBase<ELFT> *> RegularSections;
OutputSectionFactory<ELFT> Factory;
for (const std::unique_ptr<ObjectFile<ELFT>> &F : Symtab.getObjectFiles()) {
for (InputSectionBase<ELFT> *C : F->getSections()) {
if (isDiscarded(C)) {
reportDiscarded(C, F);
continue;
}
OutputSectionBase<ELFT> *Sec;
bool IsNew;
std::tie(Sec, IsNew) = Factory.create(C, getOutputSectionName(C));
if (IsNew) {
OwningSections.emplace_back(Sec);
OutputSections.push_back(Sec);
RegularSections.push_back(Sec);
}
Sec->addSection(C);
}
}
Out<ELFT>::Bss = static_cast<OutputSection<ELFT> *>(
Factory.lookup(".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE));
// If we have a .opd section (used under PPC64 for function descriptors),
// store a pointer to it here so that we can use it later when processing
// relocations.
Out<ELFT>::Opd = Factory.lookup(".opd", SHT_PROGBITS, SHF_WRITE | SHF_ALLOC);
Out<ELFT>::Dynamic->PreInitArraySec = Factory.lookup(
".preinit_array", SHT_PREINIT_ARRAY, SHF_WRITE | SHF_ALLOC);
Out<ELFT>::Dynamic->InitArraySec =
Factory.lookup(".init_array", SHT_INIT_ARRAY, SHF_WRITE | SHF_ALLOC);
Out<ELFT>::Dynamic->FiniArraySec =
Factory.lookup(".fini_array", SHT_FINI_ARRAY, SHF_WRITE | SHF_ALLOC);
// Sort section contents for __attribute__((init_priority(N)).
sortInitFini(Out<ELFT>::Dynamic->InitArraySec);
sortInitFini(Out<ELFT>::Dynamic->FiniArraySec);
sortCtorsDtors(Factory.lookup(".ctors", SHT_PROGBITS, SHF_WRITE | SHF_ALLOC));
sortCtorsDtors(Factory.lookup(".dtors", SHT_PROGBITS, SHF_WRITE | SHF_ALLOC));