-
Notifications
You must be signed in to change notification settings - Fork 10.7k
/
LinkerScript.cpp
1974 lines (1758 loc) · 60.9 KB
/
LinkerScript.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
//===- LinkerScript.cpp ---------------------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the parser/evaluator of the linker script.
//
//===----------------------------------------------------------------------===//
#include "LinkerScript.h"
#include "Config.h"
#include "Driver.h"
#include "InputSection.h"
#include "OutputSections.h"
#include "ScriptParser.h"
#include "Strings.h"
#include "SymbolTable.h"
#include "Symbols.h"
#include "SyntheticSections.h"
#include "Target.h"
#include "Writer.h"
#include "lld/Support/Memory.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/ELF.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/Path.h"
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <iterator>
#include <limits>
#include <memory>
#include <string>
#include <tuple>
#include <vector>
using namespace llvm;
using namespace llvm::ELF;
using namespace llvm::object;
using namespace llvm::support::endian;
using namespace lld;
using namespace lld::elf;
LinkerScriptBase *elf::ScriptBase;
ScriptConfiguration *elf::ScriptConfig;
template <class ELFT> static void addRegular(SymbolAssignment *Cmd) {
uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
Symbol *Sym = Symtab<ELFT>::X->addRegular(Cmd->Name, Visibility, STT_NOTYPE,
0, 0, STB_GLOBAL, nullptr, nullptr);
Cmd->Sym = Sym->body();
// If we have no SECTIONS then we don't have '.' and don't call
// assignAddresses(). We calculate symbol value immediately in this case.
if (!ScriptConfig->HasSections)
cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(0);
}
template <class ELFT> static void addSynthetic(SymbolAssignment *Cmd) {
// If we have SECTIONS block then output sections haven't been created yet.
const OutputSectionBase *Sec =
ScriptConfig->HasSections ? nullptr : Cmd->Expression.Section();
Symbol *Sym = Symtab<ELFT>::X->addSynthetic(
Cmd->Name, Sec, 0, Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT);
Cmd->Sym = Sym->body();
// If we already know section then we can calculate symbol value immediately.
if (Sec)
cast<DefinedSynthetic<ELFT>>(Cmd->Sym)->Value =
Cmd->Expression(0) - Sec->Addr;
}
static bool isUnderSysroot(StringRef Path) {
if (Config->Sysroot == "")
return false;
for (; !Path.empty(); Path = sys::path::parent_path(Path))
if (sys::fs::equivalent(Config->Sysroot, Path))
return true;
return false;
}
template <class ELFT> static void addSymbol(SymbolAssignment *Cmd) {
if (Cmd->Expression.IsAbsolute())
addRegular<ELFT>(Cmd);
else
addSynthetic<ELFT>(Cmd);
}
// If a symbol was in PROVIDE(), we need to define it only when
// it is an undefined symbol.
template <class ELFT> static bool shouldDefine(SymbolAssignment *Cmd) {
if (Cmd->Name == ".")
return false;
if (!Cmd->Provide)
return true;
SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
return B && B->isUndefined();
}
bool SymbolAssignment::classof(const BaseCommand *C) {
return C->Kind == AssignmentKind;
}
bool OutputSectionCommand::classof(const BaseCommand *C) {
return C->Kind == OutputSectionKind;
}
bool InputSectionDescription::classof(const BaseCommand *C) {
return C->Kind == InputSectionKind;
}
bool AssertCommand::classof(const BaseCommand *C) {
return C->Kind == AssertKind;
}
bool BytesDataCommand::classof(const BaseCommand *C) {
return C->Kind == BytesDataKind;
}
template <class ELFT> LinkerScript<ELFT>::LinkerScript() = default;
template <class ELFT> LinkerScript<ELFT>::~LinkerScript() = default;
template <class ELFT> static StringRef basename(InputSectionBase<ELFT> *S) {
if (S->getFile())
return sys::path::filename(S->getFile()->getName());
return "";
}
template <class ELFT>
bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) {
for (InputSectionDescription *ID : Opt.KeptSections)
if (ID->FilePat.match(basename(S)))
for (SectionPattern &P : ID->SectionPatterns)
if (P.SectionPat.match(S->Name))
return true;
return false;
}
static bool comparePriority(InputSectionData *A, InputSectionData *B) {
return getPriority(A->Name) < getPriority(B->Name);
}
static bool compareName(InputSectionData *A, InputSectionData *B) {
return A->Name < B->Name;
}
static bool compareAlignment(InputSectionData *A, InputSectionData *B) {
// ">" is not a mistake. Larger alignments are placed before smaller
// alignments in order to reduce the amount of padding necessary.
// This is compatible with GNU.
return A->Alignment > B->Alignment;
}
static std::function<bool(InputSectionData *, InputSectionData *)>
getComparator(SortSectionPolicy K) {
switch (K) {
case SortSectionPolicy::Alignment:
return compareAlignment;
case SortSectionPolicy::Name:
return compareName;
case SortSectionPolicy::Priority:
return comparePriority;
default:
llvm_unreachable("unknown sort policy");
}
}
template <class ELFT>
static bool matchConstraints(ArrayRef<InputSectionBase<ELFT> *> Sections,
ConstraintKind Kind) {
if (Kind == ConstraintKind::NoConstraint)
return true;
bool IsRW = llvm::any_of(Sections, [=](InputSectionData *Sec2) {
auto *Sec = static_cast<InputSectionBase<ELFT> *>(Sec2);
return Sec->Flags & SHF_WRITE;
});
return (IsRW && Kind == ConstraintKind::ReadWrite) ||
(!IsRW && Kind == ConstraintKind::ReadOnly);
}
static void sortSections(InputSectionData **Begin, InputSectionData **End,
SortSectionPolicy K) {
if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
std::stable_sort(Begin, End, getComparator(K));
}
// Compute and remember which sections the InputSectionDescription matches.
template <class ELFT>
void LinkerScript<ELFT>::computeInputSections(InputSectionDescription *I) {
// Collects all sections that satisfy constraints of I
// and attach them to I.
for (SectionPattern &Pat : I->SectionPatterns) {
size_t SizeBefore = I->Sections.size();
for (InputSectionBase<ELFT> *S : Symtab<ELFT>::X->Sections) {
if (!S->Live || S->Assigned)
continue;
StringRef Filename = basename(S);
if (!I->FilePat.match(Filename) || Pat.ExcludedFilePat.match(Filename))
continue;
if (!Pat.SectionPat.match(S->Name))
continue;
I->Sections.push_back(S);
S->Assigned = true;
}
// Sort sections as instructed by SORT-family commands and --sort-section
// option. Because SORT-family commands can be nested at most two depth
// (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
// line option is respected even if a SORT command is given, the exact
// behavior we have here is a bit complicated. Here are the rules.
//
// 1. If two SORT commands are given, --sort-section is ignored.
// 2. If one SORT command is given, and if it is not SORT_NONE,
// --sort-section is handled as an inner SORT command.
// 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
// 4. If no SORT command is given, sort according to --sort-section.
InputSectionData **Begin = I->Sections.data() + SizeBefore;
InputSectionData **End = I->Sections.data() + I->Sections.size();
if (Pat.SortOuter != SortSectionPolicy::None) {
if (Pat.SortInner == SortSectionPolicy::Default)
sortSections(Begin, End, Config->SortSection);
else
sortSections(Begin, End, Pat.SortInner);
sortSections(Begin, End, Pat.SortOuter);
}
}
}
template <class ELFT>
void LinkerScript<ELFT>::discard(ArrayRef<InputSectionBase<ELFT> *> V) {
for (InputSectionBase<ELFT> *S : V) {
S->Live = false;
reportDiscarded(S);
}
}
template <class ELFT>
std::vector<InputSectionBase<ELFT> *>
LinkerScript<ELFT>::createInputSectionList(OutputSectionCommand &OutCmd) {
std::vector<InputSectionBase<ELFT> *> Ret;
for (const std::unique_ptr<BaseCommand> &Base : OutCmd.Commands) {
auto *Cmd = dyn_cast<InputSectionDescription>(Base.get());
if (!Cmd)
continue;
computeInputSections(Cmd);
for (InputSectionData *S : Cmd->Sections)
Ret.push_back(static_cast<InputSectionBase<ELFT> *>(S));
}
return Ret;
}
template <class ELFT>
static SectionKey<ELFT::Is64Bits> createKey(InputSectionBase<ELFT> *C,
StringRef OutsecName) {
// When using linker script the merge rules are different.
// Unfortunately, linker scripts are name based. This means that expressions
// like *(.foo*) can refer to multiple input sections that would normally be
// placed in different output sections. We cannot put them in different
// output sections or we would produce wrong results for
// start = .; *(.foo.*) end = .; *(.bar)
// and a mapping of .foo1 and .bar1 to one section and .foo2 and .bar2 to
// another. The problem is that there is no way to layout those output
// sections such that the .foo sections are the only thing between the
// start and end symbols.
// An extra annoyance is that we cannot simply disable merging of the contents
// of SHF_MERGE sections, but our implementation requires one output section
// per "kind" (string or not, which size/aligment).
// Fortunately, creating symbols in the middle of a merge section is not
// supported by bfd or gold, so we can just create multiple section in that
// case.
typedef typename ELFT::uint uintX_t;
uintX_t Flags = C->Flags & (SHF_MERGE | SHF_STRINGS);
uintX_t Alignment = 0;
if (isa<MergeInputSection<ELFT>>(C))
Alignment = std::max<uintX_t>(C->Alignment, C->Entsize);
return SectionKey<ELFT::Is64Bits>{OutsecName, /*Type*/ 0, Flags, Alignment};
}
template <class ELFT>
void LinkerScript<ELFT>::addSection(OutputSectionFactory<ELFT> &Factory,
InputSectionBase<ELFT> *Sec,
StringRef Name) {
OutputSectionBase *OutSec;
bool IsNew;
std::tie(OutSec, IsNew) = Factory.create(createKey(Sec, Name), Sec);
if (IsNew)
OutputSections->push_back(OutSec);
OutSec->addSection(Sec);
}
template <class ELFT>
void LinkerScript<ELFT>::processCommands(OutputSectionFactory<ELFT> &Factory) {
for (unsigned I = 0; I < Opt.Commands.size(); ++I) {
auto Iter = Opt.Commands.begin() + I;
const std::unique_ptr<BaseCommand> &Base1 = *Iter;
// Handle symbol assignments outside of any output section.
if (auto *Cmd = dyn_cast<SymbolAssignment>(Base1.get())) {
if (shouldDefine<ELFT>(Cmd))
addSymbol<ELFT>(Cmd);
continue;
}
if (auto *Cmd = dyn_cast<AssertCommand>(Base1.get())) {
// If we don't have SECTIONS then output sections have already been
// created by Writer<ELFT>. The LinkerScript<ELFT>::assignAddresses
// will not be called, so ASSERT should be evaluated now.
if (!Opt.HasSections)
Cmd->Expression(0);
continue;
}
if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
std::vector<InputSectionBase<ELFT> *> V = createInputSectionList(*Cmd);
// The output section name `/DISCARD/' is special.
// Any input section assigned to it is discarded.
if (Cmd->Name == "/DISCARD/") {
discard(V);
continue;
}
// This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive
// ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input
// sections satisfy a given constraint. If not, a directive is handled
// as if it wasn't present from the beginning.
//
// Because we'll iterate over Commands many more times, the easiest
// way to "make it as if it wasn't present" is to just remove it.
if (!matchConstraints<ELFT>(V, Cmd->Constraint)) {
for (InputSectionBase<ELFT> *S : V)
S->Assigned = false;
Opt.Commands.erase(Iter);
--I;
continue;
}
// A directive may contain symbol definitions like this:
// ".foo : { ...; bar = .; }". Handle them.
for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base.get()))
if (shouldDefine<ELFT>(OutCmd))
addSymbol<ELFT>(OutCmd);
// Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign
// is given, input sections are aligned to that value, whether the
// given value is larger or smaller than the original section alignment.
if (Cmd->SubalignExpr) {
uint32_t Subalign = Cmd->SubalignExpr(0);
for (InputSectionBase<ELFT> *S : V)
S->Alignment = Subalign;
}
// Add input sections to an output section.
for (InputSectionBase<ELFT> *S : V)
addSection(Factory, S, Cmd->Name);
}
}
}
// Add sections that didn't match any sections command.
template <class ELFT>
void LinkerScript<ELFT>::addOrphanSections(OutputSectionFactory<ELFT> &Factory) {
for (InputSectionBase<ELFT> *S : Symtab<ELFT>::X->Sections)
if (S->Live && !S->OutSec)
addSection(Factory, S, getOutputSectionName(S->Name));
}
// Sets value of a section-defined symbol. Two kinds of
// symbols are processed: synthetic symbols, whose value
// is an offset from beginning of section and regular
// symbols whose value is absolute.
template <class ELFT>
static void assignSectionSymbol(SymbolAssignment *Cmd,
typename ELFT::uint Value) {
if (!Cmd->Sym)
return;
if (auto *Body = dyn_cast<DefinedSynthetic<ELFT>>(Cmd->Sym)) {
Body->Section = Cmd->Expression.Section();
Body->Value = Cmd->Expression(Value) - Body->Section->Addr;
return;
}
auto *Body = cast<DefinedRegular<ELFT>>(Cmd->Sym);
Body->Value = Cmd->Expression(Value);
}
template <class ELFT> static bool isTbss(OutputSectionBase *Sec) {
return (Sec->Flags & SHF_TLS) && Sec->Type == SHT_NOBITS;
}
template <class ELFT> void LinkerScript<ELFT>::output(InputSection<ELFT> *S) {
if (!AlreadyOutputIS.insert(S).second)
return;
bool IsTbss = isTbss<ELFT>(CurOutSec);
uintX_t Pos = IsTbss ? Dot + ThreadBssOffset : Dot;
Pos = alignTo(Pos, S->Alignment);
S->OutSecOff = Pos - CurOutSec->Addr;
Pos += S->getSize();
// Update output section size after adding each section. This is so that
// SIZEOF works correctly in the case below:
// .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
CurOutSec->Size = Pos - CurOutSec->Addr;
if (IsTbss)
ThreadBssOffset = Pos - Dot;
else
Dot = Pos;
}
template <class ELFT> void LinkerScript<ELFT>::flush() {
if (!CurOutSec || !AlreadyOutputOS.insert(CurOutSec).second)
return;
if (auto *OutSec = dyn_cast<OutputSection<ELFT>>(CurOutSec)) {
for (InputSection<ELFT> *I : OutSec->Sections)
output(I);
} else {
Dot += CurOutSec->Size;
}
}
template <class ELFT>
void LinkerScript<ELFT>::switchTo(OutputSectionBase *Sec) {
if (CurOutSec == Sec)
return;
if (AlreadyOutputOS.count(Sec))
return;
flush();
CurOutSec = Sec;
Dot = alignTo(Dot, CurOutSec->Addralign);
CurOutSec->Addr = isTbss<ELFT>(CurOutSec) ? Dot + ThreadBssOffset : Dot;
// If neither AT nor AT> is specified for an allocatable section, the linker
// will set the LMA such that the difference between VMA and LMA for the
// section is the same as the preceding output section in the same region
// https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
CurOutSec->setLMAOffset(LMAOffset);
}
template <class ELFT> void LinkerScript<ELFT>::process(BaseCommand &Base) {
// This handles the assignments to symbol or to a location counter (.)
if (auto *AssignCmd = dyn_cast<SymbolAssignment>(&Base)) {
if (AssignCmd->Name == ".") {
// Update to location counter means update to section size.
uintX_t Val = AssignCmd->Expression(Dot);
if (Val < Dot)
error("unable to move location counter backward for: " +
CurOutSec->Name);
Dot = Val;
CurOutSec->Size = Dot - CurOutSec->Addr;
return;
}
assignSectionSymbol<ELFT>(AssignCmd, Dot);
return;
}
// Handle BYTE(), SHORT(), LONG(), or QUAD().
if (auto *DataCmd = dyn_cast<BytesDataCommand>(&Base)) {
DataCmd->Offset = Dot - CurOutSec->Addr;
Dot += DataCmd->Size;
CurOutSec->Size = Dot - CurOutSec->Addr;
return;
}
if (auto *AssertCmd = dyn_cast<AssertCommand>(&Base)) {
AssertCmd->Expression(Dot);
return;
}
// It handles single input section description command,
// calculates and assigns the offsets for each section and also
// updates the output section size.
auto &ICmd = cast<InputSectionDescription>(Base);
for (InputSectionData *ID : ICmd.Sections) {
// We tentatively added all synthetic sections at the beginning and removed
// empty ones afterwards (because there is no way to know whether they were
// going be empty or not other than actually running linker scripts.)
// We need to ignore remains of empty sections.
if (auto *Sec = dyn_cast<SyntheticSection<ELFT>>(ID))
if (Sec->empty())
continue;
auto *IB = static_cast<InputSectionBase<ELFT> *>(ID);
switchTo(IB->OutSec);
if (auto *I = dyn_cast<InputSection<ELFT>>(IB))
output(I);
else
flush();
}
}
template <class ELFT>
static std::vector<OutputSectionBase *>
findSections(StringRef Name, const std::vector<OutputSectionBase *> &Sections) {
std::vector<OutputSectionBase *> Ret;
for (OutputSectionBase *Sec : Sections)
if (Sec->getName() == Name)
Ret.push_back(Sec);
return Ret;
}
// This function assigns offsets to input sections and an output section
// for a single sections command (e.g. ".text { *(.text); }").
template <class ELFT>
void LinkerScript<ELFT>::assignOffsets(OutputSectionCommand *Cmd) {
if (Cmd->LMAExpr)
LMAOffset = Cmd->LMAExpr(Dot) - Dot;
std::vector<OutputSectionBase *> Sections =
findSections<ELFT>(Cmd->Name, *OutputSections);
if (Sections.empty())
return;
switchTo(Sections[0]);
// Find the last section output location. We will output orphan sections
// there so that end symbols point to the correct location.
auto E = std::find_if(Cmd->Commands.rbegin(), Cmd->Commands.rend(),
[](const std::unique_ptr<BaseCommand> &Cmd) {
return !isa<SymbolAssignment>(*Cmd);
})
.base();
for (auto I = Cmd->Commands.begin(); I != E; ++I)
process(**I);
for (OutputSectionBase *Base : Sections)
switchTo(Base);
flush();
std::for_each(E, Cmd->Commands.end(),
[this](std::unique_ptr<BaseCommand> &B) { process(*B.get()); });
}
template <class ELFT> void LinkerScript<ELFT>::removeEmptyCommands() {
// It is common practice to use very generic linker scripts. So for any
// given run some of the output sections in the script will be empty.
// We could create corresponding empty output sections, but that would
// clutter the output.
// We instead remove trivially empty sections. The bfd linker seems even
// more aggressive at removing them.
auto Pos = std::remove_if(
Opt.Commands.begin(), Opt.Commands.end(),
[&](const std::unique_ptr<BaseCommand> &Base) {
if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
return findSections<ELFT>(Cmd->Name, *OutputSections).empty();
return false;
});
Opt.Commands.erase(Pos, Opt.Commands.end());
}
static bool isAllSectionDescription(const OutputSectionCommand &Cmd) {
for (const std::unique_ptr<BaseCommand> &I : Cmd.Commands)
if (!isa<InputSectionDescription>(*I))
return false;
return true;
}
template <class ELFT> void LinkerScript<ELFT>::adjustSectionsBeforeSorting() {
// If the output section contains only symbol assignments, create a
// corresponding output section. The bfd linker seems to only create them if
// '.' is assigned to, but creating these section should not have any bad
// consequeces and gives us a section to put the symbol in.
uintX_t Flags = SHF_ALLOC;
uint32_t Type = SHT_NOBITS;
for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
if (!Cmd)
continue;
std::vector<OutputSectionBase *> Secs =
findSections<ELFT>(Cmd->Name, *OutputSections);
if (!Secs.empty()) {
Flags = Secs[0]->Flags;
Type = Secs[0]->Type;
continue;
}
if (isAllSectionDescription(*Cmd))
continue;
auto *OutSec = make<OutputSection<ELFT>>(Cmd->Name, Type, Flags);
OutputSections->push_back(OutSec);
}
}
template <class ELFT> void LinkerScript<ELFT>::adjustSectionsAfterSorting() {
placeOrphanSections();
// If output section command doesn't specify any segments,
// and we haven't previously assigned any section to segment,
// then we simply assign section to the very first load segment.
// Below is an example of such linker script:
// PHDRS { seg PT_LOAD; }
// SECTIONS { .aaa : { *(.aaa) } }
std::vector<StringRef> DefPhdrs;
auto FirstPtLoad =
std::find_if(Opt.PhdrsCommands.begin(), Opt.PhdrsCommands.end(),
[](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; });
if (FirstPtLoad != Opt.PhdrsCommands.end())
DefPhdrs.push_back(FirstPtLoad->Name);
// Walk the commands and propagate the program headers to commands that don't
// explicitly specify them.
for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
if (!Cmd)
continue;
if (Cmd->Phdrs.empty())
Cmd->Phdrs = DefPhdrs;
else
DefPhdrs = Cmd->Phdrs;
}
removeEmptyCommands();
}
// When placing orphan sections, we want to place them after symbol assignments
// so that an orphan after
// begin_foo = .;
// foo : { *(foo) }
// end_foo = .;
// doesn't break the intended meaning of the begin/end symbols.
// We don't want to go over sections since Writer<ELFT>::sortSections is the
// one in charge of deciding the order of the sections.
// We don't want to go over alignments, since doing so in
// rx_sec : { *(rx_sec) }
// . = ALIGN(0x1000);
// /* The RW PT_LOAD starts here*/
// rw_sec : { *(rw_sec) }
// would mean that the RW PT_LOAD would become unaligned.
static bool shouldSkip(const BaseCommand &Cmd) {
if (isa<OutputSectionCommand>(Cmd))
return false;
const auto *Assign = dyn_cast<SymbolAssignment>(&Cmd);
if (!Assign)
return true;
return Assign->Name != ".";
}
// Orphan sections are sections present in the input files which are not
// explicitly placed into the output file by the linker script. This just
// places them in the order already decided in OutputSections.
template <class ELFT>
void LinkerScript<ELFT>::placeOrphanSections() {
// The OutputSections are already in the correct order.
// This loops creates or moves commands as needed so that they are in the
// correct order.
int CmdIndex = 0;
// As a horrible special case, skip the first . assignment if it is before any
// section. We do this because it is common to set a load address by starting
// the script with ". = 0xabcd" and the expectation is that every section is
// after that.
auto FirstSectionOrDotAssignment =
std::find_if(Opt.Commands.begin(), Opt.Commands.end(),
[](const std::unique_ptr<BaseCommand> &Cmd) {
if (isa<OutputSectionCommand>(*Cmd))
return true;
const auto *Assign = dyn_cast<SymbolAssignment>(Cmd.get());
if (!Assign)
return false;
return Assign->Name == ".";
});
if (FirstSectionOrDotAssignment != Opt.Commands.end()) {
CmdIndex = FirstSectionOrDotAssignment - Opt.Commands.begin();
if (isa<SymbolAssignment>(**FirstSectionOrDotAssignment))
++CmdIndex;
}
for (OutputSectionBase *Sec : *OutputSections) {
StringRef Name = Sec->getName();
// Find the last spot where we can insert a command and still get the
// correct result.
auto CmdIter = Opt.Commands.begin() + CmdIndex;
auto E = Opt.Commands.end();
while (CmdIter != E && shouldSkip(**CmdIter)) {
++CmdIter;
++CmdIndex;
}
auto Pos =
std::find_if(CmdIter, E, [&](const std::unique_ptr<BaseCommand> &Base) {
auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
return Cmd && Cmd->Name == Name;
});
if (Pos == E) {
Opt.Commands.insert(CmdIter,
llvm::make_unique<OutputSectionCommand>(Name));
++CmdIndex;
continue;
}
// Continue from where we found it.
CmdIndex = (Pos - Opt.Commands.begin()) + 1;
}
}
template <class ELFT>
void LinkerScript<ELFT>::assignAddresses(std::vector<PhdrEntry<ELFT>> &Phdrs) {
// Assign addresses as instructed by linker script SECTIONS sub-commands.
Dot = 0;
for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
if (Cmd->Name == ".") {
Dot = Cmd->Expression(Dot);
} else if (Cmd->Sym) {
assignSectionSymbol<ELFT>(Cmd, Dot);
}
continue;
}
if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
Cmd->Expression(Dot);
continue;
}
auto *Cmd = cast<OutputSectionCommand>(Base.get());
if (Cmd->AddrExpr)
Dot = Cmd->AddrExpr(Dot);
assignOffsets(Cmd);
}
uintX_t MinVA = std::numeric_limits<uintX_t>::max();
for (OutputSectionBase *Sec : *OutputSections) {
if (Sec->Flags & SHF_ALLOC)
MinVA = std::min<uint64_t>(MinVA, Sec->Addr);
else
Sec->Addr = 0;
}
uintX_t HeaderSize = getHeaderSize();
auto FirstPTLoad =
std::find_if(Phdrs.begin(), Phdrs.end(), [](const PhdrEntry<ELFT> &E) {
return E.H.p_type == PT_LOAD;
});
if (FirstPTLoad == Phdrs.end())
return;
// If the linker script doesn't have PHDRS, add ElfHeader and ProgramHeaders
// now that we know we have space.
if (HeaderSize <= MinVA && !hasPhdrsCommands()) {
FirstPTLoad->First = Out<ELFT>::ElfHeader;
if (!FirstPTLoad->Last)
FirstPTLoad->Last = Out<ELFT>::ProgramHeaders;
}
// ELF and Program headers need to be right before the first section in
// memory. Set their addresses accordingly.
MinVA = alignDown(MinVA - HeaderSize, Config->MaxPageSize);
Out<ELFT>::ElfHeader->Addr = MinVA;
Out<ELFT>::ProgramHeaders->Addr = Out<ELFT>::ElfHeader->Size + MinVA;
}
// Creates program headers as instructed by PHDRS linker script command.
template <class ELFT>
std::vector<PhdrEntry<ELFT>> LinkerScript<ELFT>::createPhdrs() {
std::vector<PhdrEntry<ELFT>> Ret;
// Process PHDRS and FILEHDR keywords because they are not
// real output sections and cannot be added in the following loop.
for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
PhdrEntry<ELFT> &Phdr = Ret.back();
if (Cmd.HasFilehdr)
Phdr.add(Out<ELFT>::ElfHeader);
if (Cmd.HasPhdrs)
Phdr.add(Out<ELFT>::ProgramHeaders);
if (Cmd.LMAExpr) {
Phdr.H.p_paddr = Cmd.LMAExpr(0);
Phdr.HasLMA = true;
}
}
// Add output sections to program headers.
for (OutputSectionBase *Sec : *OutputSections) {
if (!(Sec->Flags & SHF_ALLOC))
break;
// Assign headers specified by linker script
for (size_t Id : getPhdrIndices(Sec->getName())) {
Ret[Id].add(Sec);
if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
Ret[Id].H.p_flags |= Sec->getPhdrFlags();
}
}
return Ret;
}
template <class ELFT> bool LinkerScript<ELFT>::ignoreInterpSection() {
// Ignore .interp section in case we have PHDRS specification
// and PT_INTERP isn't listed.
return !Opt.PhdrsCommands.empty() &&
llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
return Cmd.Type == PT_INTERP;
}) == Opt.PhdrsCommands.end();
}
template <class ELFT>
uint32_t LinkerScript<ELFT>::getFiller(StringRef Name) {
for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
if (Cmd->Name == Name)
return Cmd->Filler;
return 0;
}
template <class ELFT>
static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) {
const endianness E = ELFT::TargetEndianness;
switch (Size) {
case 1:
*Buf = (uint8_t)Data;
break;
case 2:
write16<E>(Buf, Data);
break;
case 4:
write32<E>(Buf, Data);
break;
case 8:
write64<E>(Buf, Data);
break;
default:
llvm_unreachable("unsupported Size argument");
}
}
template <class ELFT>
void LinkerScript<ELFT>::writeDataBytes(StringRef Name, uint8_t *Buf) {
int I = getSectionIndex(Name);
if (I == INT_MAX)
return;
auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I].get());
for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
if (auto *Data = dyn_cast<BytesDataCommand>(Base.get()))
writeInt<ELFT>(Buf + Data->Offset, Data->Expression(0), Data->Size);
}
template <class ELFT> bool LinkerScript<ELFT>::hasLMA(StringRef Name) {
for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
if (Cmd->LMAExpr && Cmd->Name == Name)
return true;
return false;
}
// Returns the index of the given section name in linker script
// SECTIONS commands. Sections are laid out as the same order as they
// were in the script. If a given name did not appear in the script,
// it returns INT_MAX, so that it will be laid out at end of file.
template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
for (int I = 0, E = Opt.Commands.size(); I != E; ++I)
if (auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I].get()))
if (Cmd->Name == Name)
return I;
return INT_MAX;
}
template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
return !Opt.PhdrsCommands.empty();
}
template <class ELFT>
const OutputSectionBase *LinkerScript<ELFT>::getOutputSection(const Twine &Loc,
StringRef Name) {
static OutputSectionBase FakeSec("", 0, 0);
for (OutputSectionBase *Sec : *OutputSections)
if (Sec->getName() == Name)
return Sec;
error(Loc + ": undefined section " + Name);
return &FakeSec;
}
// This function is essentially the same as getOutputSection(Name)->Size,
// but it won't print out an error message if a given section is not found.
//
// Linker script does not create an output section if its content is empty.
// We want to allow SIZEOF(.foo) where .foo is a section which happened to
// be empty. That is why this function is different from getOutputSection().
template <class ELFT>
uint64_t LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
for (OutputSectionBase *Sec : *OutputSections)
if (Sec->getName() == Name)
return Sec->Size;
return 0;
}
template <class ELFT> uint64_t LinkerScript<ELFT>::getHeaderSize() {
return elf::getHeaderSize<ELFT>();
}
template <class ELFT> uint64_t LinkerScript<ELFT>::getSymbolValue(StringRef S) {
if (SymbolBody *B = Symtab<ELFT>::X->find(S))
return B->getVA<ELFT>();
error("symbol not found: " + S);
return 0;
}
template <class ELFT> bool LinkerScript<ELFT>::isDefined(StringRef S) {
return Symtab<ELFT>::X->find(S) != nullptr;
}
template <class ELFT> bool LinkerScript<ELFT>::isAbsolute(StringRef S) {
SymbolBody *Sym = Symtab<ELFT>::X->find(S);
auto *DR = dyn_cast_or_null<DefinedRegular<ELFT>>(Sym);
return DR && !DR->Section;
}
// Gets section symbol belongs to. Symbol "." doesn't belong to any
// specific section but isn't absolute at the same time, so we try
// to find suitable section for it as well.
template <class ELFT>
const OutputSectionBase *LinkerScript<ELFT>::getSymbolSection(StringRef S) {
SymbolBody *Sym = Symtab<ELFT>::X->find(S);
if (!Sym) {
if (OutputSections->empty())
return nullptr;
return CurOutSec ? CurOutSec : (*OutputSections)[0];
}
if (auto *DR = dyn_cast_or_null<DefinedRegular<ELFT>>(Sym))
return DR->Section ? DR->Section->OutSec : nullptr;
if (auto *DS = dyn_cast_or_null<DefinedSynthetic<ELFT>>(Sym))
return DS->Section;
return nullptr;
}
// Returns indices of ELF headers containing specific section, identified
// by Name. Each index is a zero based number of ELF header listed within
// PHDRS {} script block.
template <class ELFT>
std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
if (!Cmd || Cmd->Name != SectionName)
continue;
std::vector<size_t> Ret;
for (StringRef PhdrName : Cmd->Phdrs)
Ret.push_back(getPhdrIndex(Cmd->Location, PhdrName));
return Ret;
}
return {};
}
template <class ELFT>
size_t LinkerScript<ELFT>::getPhdrIndex(const Twine &Loc, StringRef PhdrName) {
size_t I = 0;
for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
if (Cmd.Name == PhdrName)
return I;
++I;
}
error(Loc + ": section header '" + PhdrName + "' is not listed in PHDRS");
return 0;
}
class elf::ScriptParser final : public ScriptParserBase {
typedef void (ScriptParser::*Handler)();
public:
ScriptParser(MemoryBufferRef MB)
: ScriptParserBase(MB),
IsUnderSysroot(isUnderSysroot(MB.getBufferIdentifier())) {}
void readLinkerScript();
void readVersionScript();
void readDynamicList();
private:
void addFile(StringRef Path);
void readAsNeeded();
void readEntry();