forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinkerScript.cpp
1844 lines (1641 loc) · 68.4 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 ---------------------------------------------------===//
//
// 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 the parser/evaluator of the linker script.
//
//===----------------------------------------------------------------------===//
#include "LinkerScript.h"
#include "Config.h"
#include "InputFiles.h"
#include "InputSection.h"
#include "OutputSections.h"
#include "SymbolTable.h"
#include "Symbols.h"
#include "SyntheticSections.h"
#include "Target.h"
#include "Writer.h"
#include "lld/Common/CommonLinkerContext.h"
#include "lld/Common/Strings.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/BinaryFormat/ELF.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/TimeProfiler.h"
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <string>
#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;
static bool isSectionPrefix(StringRef prefix, StringRef name) {
return name.consume_front(prefix) && (name.empty() || name[0] == '.');
}
StringRef LinkerScript::getOutputSectionName(const InputSectionBase *s) const {
// This is for --emit-relocs and -r. If .text.foo is emitted as .text.bar, we
// want to emit .rela.text.foo as .rela.text.bar for consistency (this is not
// technically required, but not doing it is odd). This code guarantees that.
if (auto *isec = dyn_cast<InputSection>(s)) {
if (InputSectionBase *rel = isec->getRelocatedSection()) {
OutputSection *out = rel->getOutputSection();
if (!out) {
assert(ctx.arg.relocatable && (rel->flags & SHF_LINK_ORDER));
return s->name;
}
StringSaver &ss = ctx.saver;
if (s->type == SHT_CREL)
return ss.save(".crel" + out->name);
if (s->type == SHT_RELA)
return ss.save(".rela" + out->name);
return ss.save(".rel" + out->name);
}
}
if (ctx.arg.relocatable)
return s->name;
// A BssSection created for a common symbol is identified as "COMMON" in
// linker scripts. It should go to .bss section.
if (s->name == "COMMON")
return ".bss";
if (hasSectionsCommand)
return s->name;
// When no SECTIONS is specified, emulate GNU ld's internal linker scripts
// by grouping sections with certain prefixes.
// GNU ld places text sections with prefix ".text.hot.", ".text.unknown.",
// ".text.unlikely.", ".text.startup." or ".text.exit." before others.
// We provide an option -z keep-text-section-prefix to group such sections
// into separate output sections. This is more flexible. See also
// sortISDBySectionOrder().
// ".text.unknown" means the hotness of the section is unknown. When
// SampleFDO is used, if a function doesn't have sample, it could be very
// cold or it could be a new function never being sampled. Those functions
// will be kept in the ".text.unknown" section.
// ".text.split." holds symbols which are split out from functions in other
// input sections. For example, with -fsplit-machine-functions, placing the
// cold parts in .text.split instead of .text.unlikely mitigates against poor
// profile inaccuracy. Techniques such as hugepage remapping can make
// conservative decisions at the section granularity.
if (isSectionPrefix(".text", s->name)) {
if (ctx.arg.zKeepTextSectionPrefix)
for (StringRef v : {".text.hot", ".text.unknown", ".text.unlikely",
".text.startup", ".text.exit", ".text.split"})
if (isSectionPrefix(v.substr(5), s->name.substr(5)))
return v;
return ".text";
}
for (StringRef v : {".data.rel.ro", ".data", ".rodata",
".bss.rel.ro", ".bss", ".ldata",
".lrodata", ".lbss", ".gcc_except_table",
".init_array", ".fini_array", ".tbss",
".tdata", ".ARM.exidx", ".ARM.extab",
".ctors", ".dtors", ".sbss",
".sdata", ".srodata"})
if (isSectionPrefix(v, s->name))
return v;
return s->name;
}
uint64_t ExprValue::getValue() const {
if (sec)
return alignToPowerOf2(sec->getOutputSection()->addr + sec->getOffset(val),
alignment);
return alignToPowerOf2(val, alignment);
}
uint64_t ExprValue::getSecAddr() const {
return sec ? sec->getOutputSection()->addr + sec->getOffset(0) : 0;
}
uint64_t ExprValue::getSectionOffset() const {
return getValue() - getSecAddr();
}
// std::unique_ptr<OutputSection> may be incomplete type.
LinkerScript::LinkerScript(Ctx &ctx) : ctx(ctx) {}
LinkerScript::~LinkerScript() {}
OutputDesc *LinkerScript::createOutputSection(StringRef name,
StringRef location) {
OutputDesc *&secRef = nameToOutputSection[CachedHashStringRef(name)];
OutputDesc *sec;
if (secRef && secRef->osec.location.empty()) {
// There was a forward reference.
sec = secRef;
} else {
descPool.emplace_back(
std::make_unique<OutputDesc>(ctx, name, SHT_PROGBITS, 0));
sec = descPool.back().get();
if (!secRef)
secRef = sec;
}
sec->osec.location = std::string(location);
return sec;
}
OutputDesc *LinkerScript::getOrCreateOutputSection(StringRef name) {
auto &secRef = nameToOutputSection[CachedHashStringRef(name)];
if (!secRef) {
secRef = descPool
.emplace_back(
std::make_unique<OutputDesc>(ctx, name, SHT_PROGBITS, 0))
.get();
}
return secRef;
}
// Expands the memory region by the specified size.
static void expandMemoryRegion(MemoryRegion *memRegion, uint64_t size,
StringRef secName) {
memRegion->curPos += size;
}
void LinkerScript::expandMemoryRegions(uint64_t size) {
if (state->memRegion)
expandMemoryRegion(state->memRegion, size, state->outSec->name);
// Only expand the LMARegion if it is different from memRegion.
if (state->lmaRegion && state->memRegion != state->lmaRegion)
expandMemoryRegion(state->lmaRegion, size, state->outSec->name);
}
void LinkerScript::expandOutputSection(uint64_t size) {
state->outSec->size += size;
expandMemoryRegions(size);
}
void LinkerScript::setDot(Expr e, const Twine &loc, bool inSec) {
uint64_t val = e().getValue();
// If val is smaller and we are in an output section, record the error and
// report it if this is the last assignAddresses iteration. dot may be smaller
// if there is another assignAddresses iteration.
if (val < dot && inSec) {
recordError(loc + ": unable to move location counter (0x" +
Twine::utohexstr(dot) + ") backward to 0x" +
Twine::utohexstr(val) + " for section '" + state->outSec->name +
"'");
}
// Update to location counter means update to section size.
if (inSec)
expandOutputSection(val - dot);
dot = val;
}
// Used for handling linker symbol assignments, for both finalizing
// their values and doing early declarations. Returns true if symbol
// should be defined from linker script.
static bool shouldDefineSym(Ctx &ctx, SymbolAssignment *cmd) {
if (cmd->name == ".")
return false;
return !cmd->provide || ctx.script->shouldAddProvideSym(cmd->name);
}
// Called by processSymbolAssignments() to assign definitions to
// linker-script-defined symbols.
void LinkerScript::addSymbol(SymbolAssignment *cmd) {
if (!shouldDefineSym(ctx, cmd))
return;
// Define a symbol.
ExprValue value = cmd->expression();
SectionBase *sec = value.isAbsolute() ? nullptr : value.sec;
uint8_t visibility = cmd->hidden ? STV_HIDDEN : STV_DEFAULT;
// When this function is called, section addresses have not been
// fixed yet. So, we may or may not know the value of the RHS
// expression.
//
// For example, if an expression is `x = 42`, we know x is always 42.
// However, if an expression is `x = .`, there's no way to know its
// value at the moment.
//
// We want to set symbol values early if we can. This allows us to
// use symbols as variables in linker scripts. Doing so allows us to
// write expressions like this: `alignment = 16; . = ALIGN(., alignment)`.
uint64_t symValue = value.sec ? 0 : value.getValue();
Defined newSym(ctx, createInternalFile(ctx, cmd->location), cmd->name,
STB_GLOBAL, visibility, value.type, symValue, 0, sec);
Symbol *sym = ctx.symtab->insert(cmd->name);
sym->mergeProperties(newSym);
newSym.overwrite(*sym);
sym->isUsedInRegularObj = true;
cmd->sym = cast<Defined>(sym);
}
// This function is called from LinkerScript::declareSymbols.
// It creates a placeholder symbol if needed.
void LinkerScript::declareSymbol(SymbolAssignment *cmd) {
if (!shouldDefineSym(ctx, cmd))
return;
uint8_t visibility = cmd->hidden ? STV_HIDDEN : STV_DEFAULT;
Defined newSym(ctx, ctx.internalFile, cmd->name, STB_GLOBAL, visibility,
STT_NOTYPE, 0, 0, nullptr);
// If the symbol is already defined, its order is 0 (with absence indicating
// 0); otherwise it's assigned the order of the SymbolAssignment.
Symbol *sym = ctx.symtab->insert(cmd->name);
if (!sym->isDefined())
ctx.scriptSymOrder.insert({sym, cmd->symOrder});
// We can't calculate final value right now.
sym->mergeProperties(newSym);
newSym.overwrite(*sym);
cmd->sym = cast<Defined>(sym);
cmd->provide = false;
sym->isUsedInRegularObj = true;
sym->scriptDefined = true;
}
using SymbolAssignmentMap =
DenseMap<const Defined *, std::pair<SectionBase *, uint64_t>>;
// Collect section/value pairs of linker-script-defined symbols. This is used to
// check whether symbol values converge.
static SymbolAssignmentMap
getSymbolAssignmentValues(ArrayRef<SectionCommand *> sectionCommands) {
SymbolAssignmentMap ret;
for (SectionCommand *cmd : sectionCommands) {
if (auto *assign = dyn_cast<SymbolAssignment>(cmd)) {
if (assign->sym) // sym is nullptr for dot.
ret.try_emplace(assign->sym, std::make_pair(assign->sym->section,
assign->sym->value));
continue;
}
if (isa<SectionClassDesc>(cmd))
continue;
for (SectionCommand *subCmd : cast<OutputDesc>(cmd)->osec.commands)
if (auto *assign = dyn_cast<SymbolAssignment>(subCmd))
if (assign->sym)
ret.try_emplace(assign->sym, std::make_pair(assign->sym->section,
assign->sym->value));
}
return ret;
}
// Returns the lexicographical smallest (for determinism) Defined whose
// section/value has changed.
static const Defined *
getChangedSymbolAssignment(const SymbolAssignmentMap &oldValues) {
const Defined *changed = nullptr;
for (auto &it : oldValues) {
const Defined *sym = it.first;
if (std::make_pair(sym->section, sym->value) != it.second &&
(!changed || sym->getName() < changed->getName()))
changed = sym;
}
return changed;
}
// Process INSERT [AFTER|BEFORE] commands. For each command, we move the
// specified output section to the designated place.
void LinkerScript::processInsertCommands() {
SmallVector<OutputDesc *, 0> moves;
for (const InsertCommand &cmd : insertCommands) {
if (ctx.arg.enableNonContiguousRegions)
ErrAlways(ctx)
<< "INSERT cannot be used with --enable-non-contiguous-regions";
for (StringRef name : cmd.names) {
// If base is empty, it may have been discarded by
// adjustOutputSections(). We do not handle such output sections.
auto from = llvm::find_if(sectionCommands, [&](SectionCommand *subCmd) {
return isa<OutputDesc>(subCmd) &&
cast<OutputDesc>(subCmd)->osec.name == name;
});
if (from == sectionCommands.end())
continue;
moves.push_back(cast<OutputDesc>(*from));
sectionCommands.erase(from);
}
auto insertPos =
llvm::find_if(sectionCommands, [&cmd](SectionCommand *subCmd) {
auto *to = dyn_cast<OutputDesc>(subCmd);
return to != nullptr && to->osec.name == cmd.where;
});
if (insertPos == sectionCommands.end()) {
ErrAlways(ctx) << "unable to insert " << cmd.names[0]
<< (cmd.isAfter ? " after " : " before ") << cmd.where;
} else {
if (cmd.isAfter)
++insertPos;
sectionCommands.insert(insertPos, moves.begin(), moves.end());
}
moves.clear();
}
}
// Symbols defined in script should not be inlined by LTO. At the same time
// we don't know their final values until late stages of link. Here we scan
// over symbol assignment commands and create placeholder symbols if needed.
void LinkerScript::declareSymbols() {
assert(!state);
for (SectionCommand *cmd : sectionCommands) {
if (auto *assign = dyn_cast<SymbolAssignment>(cmd)) {
declareSymbol(assign);
continue;
}
if (isa<SectionClassDesc>(cmd))
continue;
// If the output section directive has constraints,
// we can't say for sure if it is going to be included or not.
// Skip such sections for now. Improve the checks if we ever
// need symbols from that sections to be declared early.
const OutputSection &sec = cast<OutputDesc>(cmd)->osec;
if (sec.constraint != ConstraintKind::NoConstraint)
continue;
for (SectionCommand *cmd : sec.commands)
if (auto *assign = dyn_cast<SymbolAssignment>(cmd))
declareSymbol(assign);
}
}
// This function is called from assignAddresses, while we are
// fixing the output section addresses. This function is supposed
// to set the final value for a given symbol assignment.
void LinkerScript::assignSymbol(SymbolAssignment *cmd, bool inSec) {
if (cmd->name == ".") {
setDot(cmd->expression, cmd->location, inSec);
return;
}
if (!cmd->sym)
return;
ExprValue v = cmd->expression();
if (v.isAbsolute()) {
cmd->sym->section = nullptr;
cmd->sym->value = v.getValue();
} else {
cmd->sym->section = v.sec;
cmd->sym->value = v.getSectionOffset();
}
cmd->sym->type = v.type;
}
bool InputSectionDescription::matchesFile(const InputFile &file) const {
if (filePat.isTrivialMatchAll())
return true;
if (!matchesFileCache || matchesFileCache->first != &file)
matchesFileCache.emplace(&file, filePat.match(file.getNameForScript()));
return matchesFileCache->second;
}
bool SectionPattern::excludesFile(const InputFile &file) const {
if (excludedFilePat.empty())
return false;
if (!excludesFileCache || excludesFileCache->first != &file)
excludesFileCache.emplace(&file,
excludedFilePat.match(file.getNameForScript()));
return excludesFileCache->second;
}
bool LinkerScript::shouldKeep(InputSectionBase *s) {
for (InputSectionDescription *id : keptSections)
if (id->matchesFile(*s->file))
for (SectionPattern &p : id->sectionPatterns)
if (p.sectionPat.match(s->name) &&
(s->flags & id->withFlags) == id->withFlags &&
(s->flags & id->withoutFlags) == 0)
return true;
return false;
}
// A helper function for the SORT() command.
static bool matchConstraints(ArrayRef<InputSectionBase *> sections,
ConstraintKind kind) {
if (kind == ConstraintKind::NoConstraint)
return true;
bool isRW = llvm::any_of(
sections, [](InputSectionBase *sec) { return sec->flags & SHF_WRITE; });
return (isRW && kind == ConstraintKind::ReadWrite) ||
(!isRW && kind == ConstraintKind::ReadOnly);
}
static void sortSections(MutableArrayRef<InputSectionBase *> vec,
SortSectionPolicy k) {
auto alignmentComparator = [](InputSectionBase *a, InputSectionBase *b) {
// ">" is not a mistake. Sections with larger alignments are placed
// before sections with smaller alignments in order to reduce the
// amount of padding necessary. This is compatible with GNU.
return a->addralign > b->addralign;
};
auto nameComparator = [](InputSectionBase *a, InputSectionBase *b) {
return a->name < b->name;
};
auto priorityComparator = [](InputSectionBase *a, InputSectionBase *b) {
return getPriority(a->name) < getPriority(b->name);
};
switch (k) {
case SortSectionPolicy::Default:
case SortSectionPolicy::None:
return;
case SortSectionPolicy::Alignment:
return llvm::stable_sort(vec, alignmentComparator);
case SortSectionPolicy::Name:
return llvm::stable_sort(vec, nameComparator);
case SortSectionPolicy::Priority:
return llvm::stable_sort(vec, priorityComparator);
case SortSectionPolicy::Reverse:
return std::reverse(vec.begin(), vec.end());
}
}
// 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.
static void sortInputSections(Ctx &ctx, MutableArrayRef<InputSectionBase *> vec,
SortSectionPolicy outer,
SortSectionPolicy inner) {
if (outer == SortSectionPolicy::None)
return;
if (inner == SortSectionPolicy::Default)
sortSections(vec, ctx.arg.sortSection);
else
sortSections(vec, inner);
sortSections(vec, outer);
}
// Compute and remember which sections the InputSectionDescription matches.
SmallVector<InputSectionBase *, 0>
LinkerScript::computeInputSections(const InputSectionDescription *cmd,
ArrayRef<InputSectionBase *> sections,
const SectionBase &outCmd) {
SmallVector<InputSectionBase *, 0> ret;
DenseSet<InputSectionBase *> spills;
// Returns whether an input section's flags match the input section
// description's specifiers.
auto flagsMatch = [cmd](InputSectionBase *sec) {
return (sec->flags & cmd->withFlags) == cmd->withFlags &&
(sec->flags & cmd->withoutFlags) == 0;
};
// Collects all sections that satisfy constraints of Cmd.
if (cmd->classRef.empty()) {
DenseSet<size_t> seen;
size_t sizeAfterPrevSort = 0;
SmallVector<size_t, 0> indexes;
auto sortByPositionThenCommandLine = [&](size_t begin, size_t end) {
llvm::sort(MutableArrayRef<size_t>(indexes).slice(begin, end - begin));
for (size_t i = begin; i != end; ++i)
ret[i] = sections[indexes[i]];
sortInputSections(
ctx,
MutableArrayRef<InputSectionBase *>(ret).slice(begin, end - begin),
ctx.arg.sortSection, SortSectionPolicy::None);
};
for (const SectionPattern &pat : cmd->sectionPatterns) {
size_t sizeBeforeCurrPat = ret.size();
for (size_t i = 0, e = sections.size(); i != e; ++i) {
// Skip if the section is dead or has been matched by a previous pattern
// in this input section description.
InputSectionBase *sec = sections[i];
if (!sec->isLive() || seen.contains(i))
continue;
// For --emit-relocs we have to ignore entries like
// .rela.dyn : { *(.rela.data) }
// which are common because they are in the default bfd script.
// We do not ignore SHT_REL[A] linker-synthesized sections here because
// want to support scripts that do custom layout for them.
if (isa<InputSection>(sec) &&
cast<InputSection>(sec)->getRelocatedSection())
continue;
// Check the name early to improve performance in the common case.
if (!pat.sectionPat.match(sec->name))
continue;
if (!cmd->matchesFile(*sec->file) || pat.excludesFile(*sec->file) ||
sec->parent == &outCmd || !flagsMatch(sec))
continue;
if (sec->parent) {
// Skip if not allowing multiple matches.
if (!ctx.arg.enableNonContiguousRegions)
continue;
// Disallow spilling into /DISCARD/; special handling would be needed
// for this in address assignment, and the semantics are nebulous.
if (outCmd.name == "/DISCARD/")
continue;
// Class definitions cannot contain spills, nor can a class definition
// generate a spill in a subsequent match. Those behaviors belong to
// class references and additional matches.
if (!isa<SectionClass>(outCmd) && !isa<SectionClass>(sec->parent))
spills.insert(sec);
}
ret.push_back(sec);
indexes.push_back(i);
seen.insert(i);
}
if (pat.sortOuter == SortSectionPolicy::Default)
continue;
// Matched sections are ordered by radix sort with the keys being (SORT*,
// --sort-section, input order), where SORT* (if present) is most
// significant.
//
// Matched sections between the previous SORT* and this SORT* are sorted
// by (--sort-alignment, input order).
sortByPositionThenCommandLine(sizeAfterPrevSort, sizeBeforeCurrPat);
// Matched sections by this SORT* pattern are sorted using all 3 keys.
// ret[sizeBeforeCurrPat,ret.size()) are already in the input order, so we
// just sort by sortOuter and sortInner.
sortInputSections(
ctx,
MutableArrayRef<InputSectionBase *>(ret).slice(sizeBeforeCurrPat),
pat.sortOuter, pat.sortInner);
sizeAfterPrevSort = ret.size();
}
// Matched sections after the last SORT* are sorted by (--sort-alignment,
// input order).
sortByPositionThenCommandLine(sizeAfterPrevSort, ret.size());
} else {
SectionClassDesc *scd =
sectionClasses.lookup(CachedHashStringRef(cmd->classRef));
if (!scd) {
Err(ctx) << "undefined section class '" << cmd->classRef << "'";
return ret;
}
if (!scd->sc.assigned) {
Err(ctx) << "section class '" << cmd->classRef << "' referenced by '"
<< outCmd.name << "' before class definition";
return ret;
}
for (InputSectionDescription *isd : scd->sc.commands) {
for (InputSectionBase *sec : isd->sectionBases) {
if (sec->parent == &outCmd || !flagsMatch(sec))
continue;
bool isSpill = sec->parent && isa<OutputSection>(sec->parent);
if (!sec->parent || (isSpill && outCmd.name == "/DISCARD/")) {
Err(ctx) << "section '" << sec->name
<< "' cannot spill from/to /DISCARD/";
continue;
}
if (isSpill)
spills.insert(sec);
ret.push_back(sec);
}
}
}
// The flag --enable-non-contiguous-regions or the section CLASS syntax may
// cause sections to match an InputSectionDescription in more than one
// OutputSection. Matches after the first were collected in the spills set, so
// replace these with potential spill sections.
if (!spills.empty()) {
for (InputSectionBase *&sec : ret) {
if (!spills.contains(sec))
continue;
// Append the spill input section to the list for the input section,
// creating it if necessary.
PotentialSpillSection *pss = make<PotentialSpillSection>(
*sec, const_cast<InputSectionDescription &>(*cmd));
auto [it, inserted] =
potentialSpillLists.try_emplace(sec, PotentialSpillList{pss, pss});
if (!inserted) {
PotentialSpillSection *&tail = it->second.tail;
tail = tail->next = pss;
}
sec = pss;
}
}
return ret;
}
void LinkerScript::discard(InputSectionBase &s) {
if (&s == ctx.in.shStrTab.get())
ErrAlways(ctx) << "discarding " << s.name << " section is not allowed";
s.markDead();
s.parent = nullptr;
for (InputSection *sec : s.dependentSections)
discard(*sec);
}
void LinkerScript::discardSynthetic(OutputSection &outCmd) {
for (Partition &part : ctx.partitions) {
if (!part.armExidx || !part.armExidx->isLive())
continue;
SmallVector<InputSectionBase *, 0> secs(
part.armExidx->exidxSections.begin(),
part.armExidx->exidxSections.end());
for (SectionCommand *cmd : outCmd.commands)
if (auto *isd = dyn_cast<InputSectionDescription>(cmd))
for (InputSectionBase *s : computeInputSections(isd, secs, outCmd))
discard(*s);
}
}
SmallVector<InputSectionBase *, 0>
LinkerScript::createInputSectionList(OutputSection &outCmd) {
SmallVector<InputSectionBase *, 0> ret;
for (SectionCommand *cmd : outCmd.commands) {
if (auto *isd = dyn_cast<InputSectionDescription>(cmd)) {
isd->sectionBases = computeInputSections(isd, ctx.inputSections, outCmd);
for (InputSectionBase *s : isd->sectionBases)
s->parent = &outCmd;
ret.insert(ret.end(), isd->sectionBases.begin(), isd->sectionBases.end());
}
}
return ret;
}
// Create output sections described by SECTIONS commands.
void LinkerScript::processSectionCommands() {
auto process = [this](OutputSection *osec) {
SmallVector<InputSectionBase *, 0> v = createInputSectionList(*osec);
// The output section name `/DISCARD/' is special.
// Any input section assigned to it is discarded.
if (osec->name == "/DISCARD/") {
for (InputSectionBase *s : v)
discard(*s);
discardSynthetic(*osec);
osec->commands.clear();
return false;
}
// 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 SectionCommands many more times, the easy
// way to "make it as if it wasn't present" is to make it empty.
if (!matchConstraints(v, osec->constraint)) {
for (InputSectionBase *s : v)
s->parent = nullptr;
osec->commands.clear();
return false;
}
// 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 (osec->subalignExpr) {
uint32_t subalign = osec->subalignExpr().getValue();
for (InputSectionBase *s : v)
s->addralign = subalign;
}
// Set the partition field the same way OutputSection::recordSection()
// does. Partitions cannot be used with the SECTIONS command, so this is
// always 1.
osec->partition = 1;
return true;
};
// Process OVERWRITE_SECTIONS first so that it can overwrite the main script
// or orphans.
if (ctx.arg.enableNonContiguousRegions && !overwriteSections.empty())
ErrAlways(ctx) << "OVERWRITE_SECTIONS cannot be used with "
"--enable-non-contiguous-regions";
DenseMap<CachedHashStringRef, OutputDesc *> map;
size_t i = 0;
for (OutputDesc *osd : overwriteSections) {
OutputSection *osec = &osd->osec;
if (process(osec) &&
!map.try_emplace(CachedHashStringRef(osec->name), osd).second)
Warn(ctx) << "OVERWRITE_SECTIONS specifies duplicate " << osec->name;
}
for (SectionCommand *&base : sectionCommands) {
if (auto *osd = dyn_cast<OutputDesc>(base)) {
OutputSection *osec = &osd->osec;
if (OutputDesc *overwrite = map.lookup(CachedHashStringRef(osec->name))) {
Log(ctx) << overwrite->osec.location << " overwrites " << osec->name;
overwrite->osec.sectionIndex = i++;
base = overwrite;
} else if (process(osec)) {
osec->sectionIndex = i++;
}
} else if (auto *sc = dyn_cast<SectionClassDesc>(base)) {
for (InputSectionDescription *isd : sc->sc.commands) {
isd->sectionBases =
computeInputSections(isd, ctx.inputSections, sc->sc);
for (InputSectionBase *s : isd->sectionBases) {
// A section class containing a section with different parent isn't
// necessarily an error due to --enable-non-contiguous-regions. Such
// sections all become potential spills when the class is referenced.
if (!s->parent)
s->parent = &sc->sc;
}
}
sc->sc.assigned = true;
}
}
// Check that input sections cannot spill into or out of INSERT,
// since the semantics are nebulous. This is also true for OVERWRITE_SECTIONS,
// but no check is needed, since the order of processing ensures they cannot
// legally reference classes.
if (!potentialSpillLists.empty()) {
DenseSet<StringRef> insertNames;
for (InsertCommand &ic : insertCommands)
insertNames.insert(ic.names.begin(), ic.names.end());
for (SectionCommand *&base : sectionCommands) {
auto *osd = dyn_cast<OutputDesc>(base);
if (!osd)
continue;
OutputSection *os = &osd->osec;
if (!insertNames.contains(os->name))
continue;
for (SectionCommand *sc : os->commands) {
auto *isd = dyn_cast<InputSectionDescription>(sc);
if (!isd)
continue;
for (InputSectionBase *isec : isd->sectionBases)
if (isa<PotentialSpillSection>(isec) ||
potentialSpillLists.contains(isec))
Err(ctx) << "section '" << isec->name
<< "' cannot spill from/to INSERT section '" << os->name
<< "'";
}
}
}
// If an OVERWRITE_SECTIONS specified output section is not in
// sectionCommands, append it to the end. The section will be inserted by
// orphan placement.
for (OutputDesc *osd : overwriteSections)
if (osd->osec.partition == 1 && osd->osec.sectionIndex == UINT32_MAX)
sectionCommands.push_back(osd);
// Input sections cannot have a section class parent past this point; they
// must have been assigned to an output section.
for (const auto &[_, sc] : sectionClasses) {
for (InputSectionDescription *isd : sc->sc.commands) {
for (InputSectionBase *sec : isd->sectionBases) {
if (sec->parent && isa<SectionClass>(sec->parent)) {
Err(ctx) << "section class '" << sec->parent->name
<< "' is unreferenced";
goto nextClass;
}
}
}
nextClass:;
}
}
void LinkerScript::processSymbolAssignments() {
// Dot outside an output section still represents a relative address, whose
// sh_shndx should not be SHN_UNDEF or SHN_ABS. Create a dummy aether section
// that fills the void outside a section. It has an index of one, which is
// indistinguishable from any other regular section index.
aether = std::make_unique<OutputSection>(ctx, "", 0, SHF_ALLOC);
aether->sectionIndex = 1;
// `st` captures the local AddressState and makes it accessible deliberately.
// This is needed as there are some cases where we cannot just thread the
// current state through to a lambda function created by the script parser.
AddressState st(*this);
state = &st;
st.outSec = aether.get();
for (SectionCommand *cmd : sectionCommands) {
if (auto *assign = dyn_cast<SymbolAssignment>(cmd))
addSymbol(assign);
else if (auto *osd = dyn_cast<OutputDesc>(cmd))
for (SectionCommand *subCmd : osd->osec.commands)
if (auto *assign = dyn_cast<SymbolAssignment>(subCmd))
addSymbol(assign);
}
state = nullptr;
}
static OutputSection *findByName(ArrayRef<SectionCommand *> vec,
StringRef name) {
for (SectionCommand *cmd : vec)
if (auto *osd = dyn_cast<OutputDesc>(cmd))
if (osd->osec.name == name)
return &osd->osec;
return nullptr;
}
static OutputDesc *createSection(Ctx &ctx, InputSectionBase *isec,
StringRef outsecName) {
OutputDesc *osd = ctx.script->createOutputSection(outsecName, "<internal>");
osd->osec.recordSection(isec);
return osd;
}
static OutputDesc *addInputSec(Ctx &ctx,
StringMap<TinyPtrVector<OutputSection *>> &map,
InputSectionBase *isec, StringRef outsecName) {
// Sections with SHT_GROUP or SHF_GROUP attributes reach here only when the -r
// option is given. A section with SHT_GROUP defines a "section group", and
// its members have SHF_GROUP attribute. Usually these flags have already been
// stripped by InputFiles.cpp as section groups are processed and uniquified.
// However, for the -r option, we want to pass through all section groups
// as-is because adding/removing members or merging them with other groups
// change their semantics.
if (isec->type == SHT_GROUP || (isec->flags & SHF_GROUP))
return createSection(ctx, isec, outsecName);
// Imagine .zed : { *(.foo) *(.bar) } script. Both foo and bar may have
// relocation sections .rela.foo and .rela.bar for example. Most tools do
// not allow multiple REL[A] sections for output section. Hence we
// should combine these relocation sections into single output.
// We skip synthetic sections because it can be .rela.dyn/.rela.plt or any
// other REL[A] sections created by linker itself.
if (!isa<SyntheticSection>(isec) && isStaticRelSecType(isec->type)) {
auto *sec = cast<InputSection>(isec);
OutputSection *out = sec->getRelocatedSection()->getOutputSection();
if (auto *relSec = out->relocationSection) {
relSec->recordSection(sec);
return nullptr;
}
OutputDesc *osd = createSection(ctx, isec, outsecName);
out->relocationSection = &osd->osec;
return osd;
}
// The ELF spec just says
// ----------------------------------------------------------------
// In the first phase, input sections that match in name, type and
// attribute flags should be concatenated into single sections.
// ----------------------------------------------------------------
//
// However, it is clear that at least some flags have to be ignored for
// section merging. At the very least SHF_GROUP and SHF_COMPRESSED have to be
// ignored. We should not have two output .text sections just because one was
// in a group and another was not for example.
//
// It also seems that wording was a late addition and didn't get the
// necessary scrutiny.
//
// Merging sections with different flags is expected by some users. One
// reason is that if one file has
//
// int *const bar __attribute__((section(".foo"))) = (int *)0;
//
// gcc with -fPIC will produce a read only .foo section. But if another
// file has
//
// int zed;
// int *const bar __attribute__((section(".foo"))) = (int *)&zed;
//
// gcc with -fPIC will produce a read write section.
//
// Last but not least, when using linker script the merge rules are forced by
// the script. Unfortunately, linker scripts are name based. This means that
// expressions like *(.foo*) can refer to multiple input sections with
// different flags. 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.
//
// Given the above issues, we instead merge sections by name and error on
// incompatible types and flags.
TinyPtrVector<OutputSection *> &v = map[outsecName];
for (OutputSection *sec : v) {
if (sec->partition != isec->partition)
continue;
if (ctx.arg.relocatable && (isec->flags & SHF_LINK_ORDER)) {
// Merging two SHF_LINK_ORDER sections with different sh_link fields will
// change their semantics, so we only merge them in -r links if they will
// end up being linked to the same output section. The casts are fine
// because everything in the map was created by the orphan placement code.
auto *firstIsec = cast<InputSectionBase>(
cast<InputSectionDescription>(sec->commands[0])->sectionBases[0]);
OutputSection *firstIsecOut =
(firstIsec->flags & SHF_LINK_ORDER)
? firstIsec->getLinkOrderDep()->getOutputSection()
: nullptr;
if (firstIsecOut != isec->getLinkOrderDep()->getOutputSection())
continue;
}
sec->recordSection(isec);
return nullptr;
}
OutputDesc *osd = createSection(ctx, isec, outsecName);
v.push_back(&osd->osec);
return osd;
}
// Add sections that didn't match any sections command.
void LinkerScript::addOrphanSections() {
StringMap<TinyPtrVector<OutputSection *>> map;
SmallVector<OutputDesc *, 0> v;
auto add = [&](InputSectionBase *s) {
if (s->isLive() && !s->parent) {
orphanSections.push_back(s);
StringRef name = getOutputSectionName(s);
if (ctx.arg.unique) {
v.push_back(createSection(ctx, s, name));
} else if (OutputSection *sec = findByName(sectionCommands, name)) {
sec->recordSection(s);
} else {
if (OutputDesc *osd = addInputSec(ctx, map, s, name))
v.push_back(osd);