1 //===- LinkerScript.cpp ---------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains the parser/evaluator of the linker script.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "LinkerScript.h"
14 #include "Config.h"
15 #include "InputSection.h"
16 #include "OutputSections.h"
17 #include "SymbolTable.h"
18 #include "Symbols.h"
19 #include "SyntheticSections.h"
20 #include "Target.h"
21 #include "Writer.h"
22 #include "lld/Common/Memory.h"
23 #include "lld/Common/Strings.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/BinaryFormat/ELF.h"
27 #include "llvm/Support/Casting.h"
28 #include "llvm/Support/Endian.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/FileSystem.h"
31 #include "llvm/Support/Parallel.h"
32 #include "llvm/Support/Path.h"
33 #include "llvm/Support/TimeProfiler.h"
34 #include <algorithm>
35 #include <cassert>
36 #include <cstddef>
37 #include <cstdint>
38 #include <iterator>
39 #include <limits>
40 #include <string>
41 #include <vector>
42
43 using namespace llvm;
44 using namespace llvm::ELF;
45 using namespace llvm::object;
46 using namespace llvm::support::endian;
47 using namespace lld;
48 using namespace lld::elf;
49
50 LinkerScript *elf::script;
51
getOutputSectionVA(SectionBase * sec)52 static uint64_t getOutputSectionVA(SectionBase *sec) {
53 OutputSection *os = sec->getOutputSection();
54 assert(os && "input section has no output section assigned");
55 return os ? os->addr : 0;
56 }
57
getValue() const58 uint64_t ExprValue::getValue() const {
59 if (sec)
60 return alignTo(sec->getOffset(val) + getOutputSectionVA(sec),
61 alignment);
62 return alignTo(val, alignment);
63 }
64
getSecAddr() const65 uint64_t ExprValue::getSecAddr() const {
66 if (sec)
67 return sec->getOffset(0) + getOutputSectionVA(sec);
68 return 0;
69 }
70
getSectionOffset() const71 uint64_t ExprValue::getSectionOffset() const {
72 // If the alignment is trivial, we don't have to compute the full
73 // value to know the offset. This allows this function to succeed in
74 // cases where the output section is not yet known.
75 if (alignment == 1 && !sec)
76 return val;
77 return getValue() - getSecAddr();
78 }
79
createOutputSection(StringRef name,StringRef location)80 OutputSection *LinkerScript::createOutputSection(StringRef name,
81 StringRef location) {
82 OutputSection *&secRef = nameToOutputSection[name];
83 OutputSection *sec;
84 if (secRef && secRef->location.empty()) {
85 // There was a forward reference.
86 sec = secRef;
87 } else {
88 sec = make<OutputSection>(name, SHT_PROGBITS, 0);
89 if (!secRef)
90 secRef = sec;
91 }
92 sec->location = std::string(location);
93 return sec;
94 }
95
getOrCreateOutputSection(StringRef name)96 OutputSection *LinkerScript::getOrCreateOutputSection(StringRef name) {
97 OutputSection *&cmdRef = nameToOutputSection[name];
98 if (!cmdRef)
99 cmdRef = make<OutputSection>(name, SHT_PROGBITS, 0);
100 return cmdRef;
101 }
102
103 // Expands the memory region by the specified size.
expandMemoryRegion(MemoryRegion * memRegion,uint64_t size,StringRef regionName,StringRef secName)104 static void expandMemoryRegion(MemoryRegion *memRegion, uint64_t size,
105 StringRef regionName, StringRef secName) {
106 memRegion->curPos += size;
107 uint64_t newSize = memRegion->curPos - (memRegion->origin)().getValue();
108 uint64_t length = (memRegion->length)().getValue();
109 if (newSize > length)
110 error("section '" + secName + "' will not fit in region '" + regionName +
111 "': overflowed by " + Twine(newSize - length) + " bytes");
112 }
113
expandMemoryRegions(uint64_t size)114 void LinkerScript::expandMemoryRegions(uint64_t size) {
115 if (ctx->memRegion)
116 expandMemoryRegion(ctx->memRegion, size, ctx->memRegion->name,
117 ctx->outSec->name);
118 // Only expand the LMARegion if it is different from memRegion.
119 if (ctx->lmaRegion && ctx->memRegion != ctx->lmaRegion)
120 expandMemoryRegion(ctx->lmaRegion, size, ctx->lmaRegion->name,
121 ctx->outSec->name);
122 }
123
expandOutputSection(uint64_t size)124 void LinkerScript::expandOutputSection(uint64_t size) {
125 ctx->outSec->size += size;
126 expandMemoryRegions(size);
127 }
128
setDot(Expr e,const Twine & loc,bool inSec)129 void LinkerScript::setDot(Expr e, const Twine &loc, bool inSec) {
130 uint64_t val = e().getValue();
131 if (val < dot && inSec)
132 error(loc + ": unable to move location counter backward for: " +
133 ctx->outSec->name);
134
135 // Update to location counter means update to section size.
136 if (inSec)
137 expandOutputSection(val - dot);
138
139 dot = val;
140 }
141
142 // Used for handling linker symbol assignments, for both finalizing
143 // their values and doing early declarations. Returns true if symbol
144 // should be defined from linker script.
shouldDefineSym(SymbolAssignment * cmd)145 static bool shouldDefineSym(SymbolAssignment *cmd) {
146 if (cmd->name == ".")
147 return false;
148
149 if (!cmd->provide)
150 return true;
151
152 // If a symbol was in PROVIDE(), we need to define it only
153 // when it is a referenced undefined symbol.
154 Symbol *b = symtab->find(cmd->name);
155 if (b && !b->isDefined())
156 return true;
157 return false;
158 }
159
160 // Called by processSymbolAssignments() to assign definitions to
161 // linker-script-defined symbols.
addSymbol(SymbolAssignment * cmd)162 void LinkerScript::addSymbol(SymbolAssignment *cmd) {
163 if (!shouldDefineSym(cmd))
164 return;
165
166 // Define a symbol.
167 ExprValue value = cmd->expression();
168 SectionBase *sec = value.isAbsolute() ? nullptr : value.sec;
169 uint8_t visibility = cmd->hidden ? STV_HIDDEN : STV_DEFAULT;
170
171 // When this function is called, section addresses have not been
172 // fixed yet. So, we may or may not know the value of the RHS
173 // expression.
174 //
175 // For example, if an expression is `x = 42`, we know x is always 42.
176 // However, if an expression is `x = .`, there's no way to know its
177 // value at the moment.
178 //
179 // We want to set symbol values early if we can. This allows us to
180 // use symbols as variables in linker scripts. Doing so allows us to
181 // write expressions like this: `alignment = 16; . = ALIGN(., alignment)`.
182 uint64_t symValue = value.sec ? 0 : value.getValue();
183
184 Defined newSym(nullptr, cmd->name, STB_GLOBAL, visibility, value.type,
185 symValue, 0, sec);
186
187 Symbol *sym = symtab->insert(cmd->name);
188 sym->mergeProperties(newSym);
189 sym->replace(newSym);
190 cmd->sym = cast<Defined>(sym);
191 }
192
193 // This function is called from LinkerScript::declareSymbols.
194 // It creates a placeholder symbol if needed.
declareSymbol(SymbolAssignment * cmd)195 static void declareSymbol(SymbolAssignment *cmd) {
196 if (!shouldDefineSym(cmd))
197 return;
198
199 uint8_t visibility = cmd->hidden ? STV_HIDDEN : STV_DEFAULT;
200 Defined newSym(nullptr, cmd->name, STB_GLOBAL, visibility, STT_NOTYPE, 0, 0,
201 nullptr);
202
203 // We can't calculate final value right now.
204 Symbol *sym = symtab->insert(cmd->name);
205 sym->mergeProperties(newSym);
206 sym->replace(newSym);
207
208 cmd->sym = cast<Defined>(sym);
209 cmd->provide = false;
210 sym->scriptDefined = true;
211 }
212
213 using SymbolAssignmentMap =
214 DenseMap<const Defined *, std::pair<SectionBase *, uint64_t>>;
215
216 // Collect section/value pairs of linker-script-defined symbols. This is used to
217 // check whether symbol values converge.
218 static SymbolAssignmentMap
getSymbolAssignmentValues(const std::vector<BaseCommand * > & sectionCommands)219 getSymbolAssignmentValues(const std::vector<BaseCommand *> §ionCommands) {
220 SymbolAssignmentMap ret;
221 for (BaseCommand *base : sectionCommands) {
222 if (auto *cmd = dyn_cast<SymbolAssignment>(base)) {
223 if (cmd->sym) // sym is nullptr for dot.
224 ret.try_emplace(cmd->sym,
225 std::make_pair(cmd->sym->section, cmd->sym->value));
226 continue;
227 }
228 for (BaseCommand *sub_base : cast<OutputSection>(base)->sectionCommands)
229 if (auto *cmd = dyn_cast<SymbolAssignment>(sub_base))
230 if (cmd->sym)
231 ret.try_emplace(cmd->sym,
232 std::make_pair(cmd->sym->section, cmd->sym->value));
233 }
234 return ret;
235 }
236
237 // Returns the lexicographical smallest (for determinism) Defined whose
238 // section/value has changed.
239 static const Defined *
getChangedSymbolAssignment(const SymbolAssignmentMap & oldValues)240 getChangedSymbolAssignment(const SymbolAssignmentMap &oldValues) {
241 const Defined *changed = nullptr;
242 for (auto &it : oldValues) {
243 const Defined *sym = it.first;
244 if (std::make_pair(sym->section, sym->value) != it.second &&
245 (!changed || sym->getName() < changed->getName()))
246 changed = sym;
247 }
248 return changed;
249 }
250
251 // Process INSERT [AFTER|BEFORE] commands. For each command, we move the
252 // specified output section to the designated place.
processInsertCommands()253 void LinkerScript::processInsertCommands() {
254 for (const InsertCommand &cmd : insertCommands) {
255 // If cmd.os is empty, it may have been discarded by
256 // adjustSectionsBeforeSorting(). We do not handle such output sections.
257 auto from = llvm::find(sectionCommands, cmd.os);
258 if (from == sectionCommands.end())
259 continue;
260 sectionCommands.erase(from);
261
262 auto insertPos = llvm::find_if(sectionCommands, [&cmd](BaseCommand *base) {
263 auto *to = dyn_cast<OutputSection>(base);
264 return to != nullptr && to->name == cmd.where;
265 });
266 if (insertPos == sectionCommands.end()) {
267 error("unable to insert " + cmd.os->name +
268 (cmd.isAfter ? " after " : " before ") + cmd.where);
269 } else {
270 if (cmd.isAfter)
271 ++insertPos;
272 sectionCommands.insert(insertPos, cmd.os);
273 }
274 }
275 }
276
277 // Symbols defined in script should not be inlined by LTO. At the same time
278 // we don't know their final values until late stages of link. Here we scan
279 // over symbol assignment commands and create placeholder symbols if needed.
declareSymbols()280 void LinkerScript::declareSymbols() {
281 assert(!ctx);
282 for (BaseCommand *base : sectionCommands) {
283 if (auto *cmd = dyn_cast<SymbolAssignment>(base)) {
284 declareSymbol(cmd);
285 continue;
286 }
287
288 // If the output section directive has constraints,
289 // we can't say for sure if it is going to be included or not.
290 // Skip such sections for now. Improve the checks if we ever
291 // need symbols from that sections to be declared early.
292 auto *sec = cast<OutputSection>(base);
293 if (sec->constraint != ConstraintKind::NoConstraint)
294 continue;
295 for (BaseCommand *base2 : sec->sectionCommands)
296 if (auto *cmd = dyn_cast<SymbolAssignment>(base2))
297 declareSymbol(cmd);
298 }
299 }
300
301 // This function is called from assignAddresses, while we are
302 // fixing the output section addresses. This function is supposed
303 // to set the final value for a given symbol assignment.
assignSymbol(SymbolAssignment * cmd,bool inSec)304 void LinkerScript::assignSymbol(SymbolAssignment *cmd, bool inSec) {
305 if (cmd->name == ".") {
306 setDot(cmd->expression, cmd->location, inSec);
307 return;
308 }
309
310 if (!cmd->sym)
311 return;
312
313 ExprValue v = cmd->expression();
314 if (v.isAbsolute()) {
315 cmd->sym->section = nullptr;
316 cmd->sym->value = v.getValue();
317 } else {
318 cmd->sym->section = v.sec;
319 cmd->sym->value = v.getSectionOffset();
320 }
321 cmd->sym->type = v.type;
322 }
323
getFilename(const InputFile * file)324 static inline StringRef getFilename(const InputFile *file) {
325 return file ? file->getNameForScript() : StringRef();
326 }
327
matchesFile(const InputFile * file) const328 bool InputSectionDescription::matchesFile(const InputFile *file) const {
329 if (filePat.isTrivialMatchAll())
330 return true;
331
332 if (!matchesFileCache || matchesFileCache->first != file)
333 matchesFileCache.emplace(file, filePat.match(getFilename(file)));
334
335 return matchesFileCache->second;
336 }
337
excludesFile(const InputFile * file) const338 bool SectionPattern::excludesFile(const InputFile *file) const {
339 if (excludedFilePat.empty())
340 return false;
341
342 if (!excludesFileCache || excludesFileCache->first != file)
343 excludesFileCache.emplace(file, excludedFilePat.match(getFilename(file)));
344
345 return excludesFileCache->second;
346 }
347
shouldKeep(InputSectionBase * s)348 bool LinkerScript::shouldKeep(InputSectionBase *s) {
349 for (InputSectionDescription *id : keptSections)
350 if (id->matchesFile(s->file))
351 for (SectionPattern &p : id->sectionPatterns)
352 if (p.sectionPat.match(s->name) &&
353 (s->flags & id->withFlags) == id->withFlags &&
354 (s->flags & id->withoutFlags) == 0)
355 return true;
356 return false;
357 }
358
359 // A helper function for the SORT() command.
matchConstraints(ArrayRef<InputSectionBase * > sections,ConstraintKind kind)360 static bool matchConstraints(ArrayRef<InputSectionBase *> sections,
361 ConstraintKind kind) {
362 if (kind == ConstraintKind::NoConstraint)
363 return true;
364
365 bool isRW = llvm::any_of(
366 sections, [](InputSectionBase *sec) { return sec->flags & SHF_WRITE; });
367
368 return (isRW && kind == ConstraintKind::ReadWrite) ||
369 (!isRW && kind == ConstraintKind::ReadOnly);
370 }
371
sortSections(MutableArrayRef<InputSectionBase * > vec,SortSectionPolicy k)372 static void sortSections(MutableArrayRef<InputSectionBase *> vec,
373 SortSectionPolicy k) {
374 auto alignmentComparator = [](InputSectionBase *a, InputSectionBase *b) {
375 // ">" is not a mistake. Sections with larger alignments are placed
376 // before sections with smaller alignments in order to reduce the
377 // amount of padding necessary. This is compatible with GNU.
378 return a->alignment > b->alignment;
379 };
380 auto nameComparator = [](InputSectionBase *a, InputSectionBase *b) {
381 return a->name < b->name;
382 };
383 auto priorityComparator = [](InputSectionBase *a, InputSectionBase *b) {
384 return getPriority(a->name) < getPriority(b->name);
385 };
386
387 switch (k) {
388 case SortSectionPolicy::Default:
389 case SortSectionPolicy::None:
390 return;
391 case SortSectionPolicy::Alignment:
392 return llvm::stable_sort(vec, alignmentComparator);
393 case SortSectionPolicy::Name:
394 return llvm::stable_sort(vec, nameComparator);
395 case SortSectionPolicy::Priority:
396 return llvm::stable_sort(vec, priorityComparator);
397 }
398 }
399
400 // Sort sections as instructed by SORT-family commands and --sort-section
401 // option. Because SORT-family commands can be nested at most two depth
402 // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
403 // line option is respected even if a SORT command is given, the exact
404 // behavior we have here is a bit complicated. Here are the rules.
405 //
406 // 1. If two SORT commands are given, --sort-section is ignored.
407 // 2. If one SORT command is given, and if it is not SORT_NONE,
408 // --sort-section is handled as an inner SORT command.
409 // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
410 // 4. If no SORT command is given, sort according to --sort-section.
sortInputSections(MutableArrayRef<InputSectionBase * > vec,SortSectionPolicy outer,SortSectionPolicy inner)411 static void sortInputSections(MutableArrayRef<InputSectionBase *> vec,
412 SortSectionPolicy outer,
413 SortSectionPolicy inner) {
414 if (outer == SortSectionPolicy::None)
415 return;
416
417 if (inner == SortSectionPolicy::Default)
418 sortSections(vec, config->sortSection);
419 else
420 sortSections(vec, inner);
421 sortSections(vec, outer);
422 }
423
424 // Compute and remember which sections the InputSectionDescription matches.
425 std::vector<InputSectionBase *>
computeInputSections(const InputSectionDescription * cmd,ArrayRef<InputSectionBase * > sections)426 LinkerScript::computeInputSections(const InputSectionDescription *cmd,
427 ArrayRef<InputSectionBase *> sections) {
428 std::vector<InputSectionBase *> ret;
429 std::vector<size_t> indexes;
430 DenseSet<size_t> seen;
431 auto sortByPositionThenCommandLine = [&](size_t begin, size_t end) {
432 llvm::sort(MutableArrayRef<size_t>(indexes).slice(begin, end - begin));
433 for (size_t i = begin; i != end; ++i)
434 ret[i] = sections[indexes[i]];
435 sortInputSections(
436 MutableArrayRef<InputSectionBase *>(ret).slice(begin, end - begin),
437 config->sortSection, SortSectionPolicy::None);
438 };
439
440 // Collects all sections that satisfy constraints of Cmd.
441 size_t sizeAfterPrevSort = 0;
442 for (const SectionPattern &pat : cmd->sectionPatterns) {
443 size_t sizeBeforeCurrPat = ret.size();
444
445 for (size_t i = 0, e = sections.size(); i != e; ++i) {
446 // Skip if the section is dead or has been matched by a previous input
447 // section description or a previous pattern.
448 InputSectionBase *sec = sections[i];
449 if (!sec->isLive() || sec->parent || seen.contains(i))
450 continue;
451
452 // For -emit-relocs we have to ignore entries like
453 // .rela.dyn : { *(.rela.data) }
454 // which are common because they are in the default bfd script.
455 // We do not ignore SHT_REL[A] linker-synthesized sections here because
456 // want to support scripts that do custom layout for them.
457 if (isa<InputSection>(sec) &&
458 cast<InputSection>(sec)->getRelocatedSection())
459 continue;
460
461 // Check the name early to improve performance in the common case.
462 if (!pat.sectionPat.match(sec->name))
463 continue;
464
465 if (!cmd->matchesFile(sec->file) || pat.excludesFile(sec->file) ||
466 (sec->flags & cmd->withFlags) != cmd->withFlags ||
467 (sec->flags & cmd->withoutFlags) != 0)
468 continue;
469
470 ret.push_back(sec);
471 indexes.push_back(i);
472 seen.insert(i);
473 }
474
475 if (pat.sortOuter == SortSectionPolicy::Default)
476 continue;
477
478 // Matched sections are ordered by radix sort with the keys being (SORT*,
479 // --sort-section, input order), where SORT* (if present) is most
480 // significant.
481 //
482 // Matched sections between the previous SORT* and this SORT* are sorted by
483 // (--sort-alignment, input order).
484 sortByPositionThenCommandLine(sizeAfterPrevSort, sizeBeforeCurrPat);
485 // Matched sections by this SORT* pattern are sorted using all 3 keys.
486 // ret[sizeBeforeCurrPat,ret.size()) are already in the input order, so we
487 // just sort by sortOuter and sortInner.
488 sortInputSections(
489 MutableArrayRef<InputSectionBase *>(ret).slice(sizeBeforeCurrPat),
490 pat.sortOuter, pat.sortInner);
491 sizeAfterPrevSort = ret.size();
492 }
493 // Matched sections after the last SORT* are sorted by (--sort-alignment,
494 // input order).
495 sortByPositionThenCommandLine(sizeAfterPrevSort, ret.size());
496 return ret;
497 }
498
discard(InputSectionBase * s)499 void LinkerScript::discard(InputSectionBase *s) {
500 if (s == in.shStrTab || s == mainPart->relrDyn)
501 error("discarding " + s->name + " section is not allowed");
502
503 // You can discard .hash and .gnu.hash sections by linker scripts. Since
504 // they are synthesized sections, we need to handle them differently than
505 // other regular sections.
506 if (s == mainPart->gnuHashTab)
507 mainPart->gnuHashTab = nullptr;
508 if (s == mainPart->hashTab)
509 mainPart->hashTab = nullptr;
510
511 s->markDead();
512 s->parent = nullptr;
513 for (InputSection *ds : s->dependentSections)
514 discard(ds);
515 }
516
discardSynthetic(OutputSection & outCmd)517 void LinkerScript::discardSynthetic(OutputSection &outCmd) {
518 for (Partition &part : partitions) {
519 if (!part.armExidx || !part.armExidx->isLive())
520 continue;
521 std::vector<InputSectionBase *> secs(part.armExidx->exidxSections.begin(),
522 part.armExidx->exidxSections.end());
523 for (BaseCommand *base : outCmd.sectionCommands)
524 if (auto *cmd = dyn_cast<InputSectionDescription>(base)) {
525 std::vector<InputSectionBase *> matches =
526 computeInputSections(cmd, secs);
527 for (InputSectionBase *s : matches)
528 discard(s);
529 }
530 }
531 }
532
533 std::vector<InputSectionBase *>
createInputSectionList(OutputSection & outCmd)534 LinkerScript::createInputSectionList(OutputSection &outCmd) {
535 std::vector<InputSectionBase *> ret;
536
537 for (BaseCommand *base : outCmd.sectionCommands) {
538 if (auto *cmd = dyn_cast<InputSectionDescription>(base)) {
539 cmd->sectionBases = computeInputSections(cmd, inputSections);
540 for (InputSectionBase *s : cmd->sectionBases)
541 s->parent = &outCmd;
542 ret.insert(ret.end(), cmd->sectionBases.begin(), cmd->sectionBases.end());
543 }
544 }
545 return ret;
546 }
547
548 // Create output sections described by SECTIONS commands.
processSectionCommands()549 void LinkerScript::processSectionCommands() {
550 size_t i = 0;
551 for (BaseCommand *base : sectionCommands) {
552 if (auto *sec = dyn_cast<OutputSection>(base)) {
553 std::vector<InputSectionBase *> v = createInputSectionList(*sec);
554
555 // The output section name `/DISCARD/' is special.
556 // Any input section assigned to it is discarded.
557 if (sec->name == "/DISCARD/") {
558 for (InputSectionBase *s : v)
559 discard(s);
560 discardSynthetic(*sec);
561 sec->sectionCommands.clear();
562 continue;
563 }
564
565 // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive
566 // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input
567 // sections satisfy a given constraint. If not, a directive is handled
568 // as if it wasn't present from the beginning.
569 //
570 // Because we'll iterate over SectionCommands many more times, the easy
571 // way to "make it as if it wasn't present" is to make it empty.
572 if (!matchConstraints(v, sec->constraint)) {
573 for (InputSectionBase *s : v)
574 s->parent = nullptr;
575 sec->sectionCommands.clear();
576 continue;
577 }
578
579 // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign
580 // is given, input sections are aligned to that value, whether the
581 // given value is larger or smaller than the original section alignment.
582 if (sec->subalignExpr) {
583 uint32_t subalign = sec->subalignExpr().getValue();
584 for (InputSectionBase *s : v)
585 s->alignment = subalign;
586 }
587
588 // Set the partition field the same way OutputSection::recordSection()
589 // does. Partitions cannot be used with the SECTIONS command, so this is
590 // always 1.
591 sec->partition = 1;
592
593 sec->sectionIndex = i++;
594 }
595 }
596 }
597
processSymbolAssignments()598 void LinkerScript::processSymbolAssignments() {
599 // Dot outside an output section still represents a relative address, whose
600 // sh_shndx should not be SHN_UNDEF or SHN_ABS. Create a dummy aether section
601 // that fills the void outside a section. It has an index of one, which is
602 // indistinguishable from any other regular section index.
603 aether = make<OutputSection>("", 0, SHF_ALLOC);
604 aether->sectionIndex = 1;
605
606 // ctx captures the local AddressState and makes it accessible deliberately.
607 // This is needed as there are some cases where we cannot just thread the
608 // current state through to a lambda function created by the script parser.
609 AddressState state;
610 ctx = &state;
611 ctx->outSec = aether;
612
613 for (BaseCommand *base : sectionCommands) {
614 if (auto *cmd = dyn_cast<SymbolAssignment>(base))
615 addSymbol(cmd);
616 else
617 for (BaseCommand *sub_base : cast<OutputSection>(base)->sectionCommands)
618 if (auto *cmd = dyn_cast<SymbolAssignment>(sub_base))
619 addSymbol(cmd);
620 }
621
622 ctx = nullptr;
623 }
624
findByName(ArrayRef<BaseCommand * > vec,StringRef name)625 static OutputSection *findByName(ArrayRef<BaseCommand *> vec,
626 StringRef name) {
627 for (BaseCommand *base : vec)
628 if (auto *sec = dyn_cast<OutputSection>(base))
629 if (sec->name == name)
630 return sec;
631 return nullptr;
632 }
633
createSection(InputSectionBase * isec,StringRef outsecName)634 static OutputSection *createSection(InputSectionBase *isec,
635 StringRef outsecName) {
636 OutputSection *sec = script->createOutputSection(outsecName, "<internal>");
637 sec->recordSection(isec);
638 return sec;
639 }
640
641 static OutputSection *
addInputSec(StringMap<TinyPtrVector<OutputSection * >> & map,InputSectionBase * isec,StringRef outsecName)642 addInputSec(StringMap<TinyPtrVector<OutputSection *>> &map,
643 InputSectionBase *isec, StringRef outsecName) {
644 // Sections with SHT_GROUP or SHF_GROUP attributes reach here only when the -r
645 // option is given. A section with SHT_GROUP defines a "section group", and
646 // its members have SHF_GROUP attribute. Usually these flags have already been
647 // stripped by InputFiles.cpp as section groups are processed and uniquified.
648 // However, for the -r option, we want to pass through all section groups
649 // as-is because adding/removing members or merging them with other groups
650 // change their semantics.
651 if (isec->type == SHT_GROUP || (isec->flags & SHF_GROUP))
652 return createSection(isec, outsecName);
653
654 // Imagine .zed : { *(.foo) *(.bar) } script. Both foo and bar may have
655 // relocation sections .rela.foo and .rela.bar for example. Most tools do
656 // not allow multiple REL[A] sections for output section. Hence we
657 // should combine these relocation sections into single output.
658 // We skip synthetic sections because it can be .rela.dyn/.rela.plt or any
659 // other REL[A] sections created by linker itself.
660 if (!isa<SyntheticSection>(isec) &&
661 (isec->type == SHT_REL || isec->type == SHT_RELA)) {
662 auto *sec = cast<InputSection>(isec);
663 OutputSection *out = sec->getRelocatedSection()->getOutputSection();
664
665 if (out->relocationSection) {
666 out->relocationSection->recordSection(sec);
667 return nullptr;
668 }
669
670 out->relocationSection = createSection(isec, outsecName);
671 return out->relocationSection;
672 }
673
674 // The ELF spec just says
675 // ----------------------------------------------------------------
676 // In the first phase, input sections that match in name, type and
677 // attribute flags should be concatenated into single sections.
678 // ----------------------------------------------------------------
679 //
680 // However, it is clear that at least some flags have to be ignored for
681 // section merging. At the very least SHF_GROUP and SHF_COMPRESSED have to be
682 // ignored. We should not have two output .text sections just because one was
683 // in a group and another was not for example.
684 //
685 // It also seems that wording was a late addition and didn't get the
686 // necessary scrutiny.
687 //
688 // Merging sections with different flags is expected by some users. One
689 // reason is that if one file has
690 //
691 // int *const bar __attribute__((section(".foo"))) = (int *)0;
692 //
693 // gcc with -fPIC will produce a read only .foo section. But if another
694 // file has
695 //
696 // int zed;
697 // int *const bar __attribute__((section(".foo"))) = (int *)&zed;
698 //
699 // gcc with -fPIC will produce a read write section.
700 //
701 // Last but not least, when using linker script the merge rules are forced by
702 // the script. Unfortunately, linker scripts are name based. This means that
703 // expressions like *(.foo*) can refer to multiple input sections with
704 // different flags. We cannot put them in different output sections or we
705 // would produce wrong results for
706 //
707 // start = .; *(.foo.*) end = .; *(.bar)
708 //
709 // and a mapping of .foo1 and .bar1 to one section and .foo2 and .bar2 to
710 // another. The problem is that there is no way to layout those output
711 // sections such that the .foo sections are the only thing between the start
712 // and end symbols.
713 //
714 // Given the above issues, we instead merge sections by name and error on
715 // incompatible types and flags.
716 TinyPtrVector<OutputSection *> &v = map[outsecName];
717 for (OutputSection *sec : v) {
718 if (sec->partition != isec->partition)
719 continue;
720
721 if (config->relocatable && (isec->flags & SHF_LINK_ORDER)) {
722 // Merging two SHF_LINK_ORDER sections with different sh_link fields will
723 // change their semantics, so we only merge them in -r links if they will
724 // end up being linked to the same output section. The casts are fine
725 // because everything in the map was created by the orphan placement code.
726 auto *firstIsec = cast<InputSectionBase>(
727 cast<InputSectionDescription>(sec->sectionCommands[0])
728 ->sectionBases[0]);
729 OutputSection *firstIsecOut =
730 firstIsec->flags & SHF_LINK_ORDER
731 ? firstIsec->getLinkOrderDep()->getOutputSection()
732 : nullptr;
733 if (firstIsecOut != isec->getLinkOrderDep()->getOutputSection())
734 continue;
735 }
736
737 sec->recordSection(isec);
738 return nullptr;
739 }
740
741 OutputSection *sec = createSection(isec, outsecName);
742 v.push_back(sec);
743 return sec;
744 }
745
746 // Add sections that didn't match any sections command.
addOrphanSections()747 void LinkerScript::addOrphanSections() {
748 StringMap<TinyPtrVector<OutputSection *>> map;
749 std::vector<OutputSection *> v;
750
751 std::function<void(InputSectionBase *)> add;
752 add = [&](InputSectionBase *s) {
753 if (s->isLive() && !s->parent) {
754 orphanSections.push_back(s);
755
756 StringRef name = getOutputSectionName(s);
757 if (config->unique) {
758 v.push_back(createSection(s, name));
759 } else if (OutputSection *sec = findByName(sectionCommands, name)) {
760 sec->recordSection(s);
761 } else {
762 if (OutputSection *os = addInputSec(map, s, name))
763 v.push_back(os);
764 assert(isa<MergeInputSection>(s) ||
765 s->getOutputSection()->sectionIndex == UINT32_MAX);
766 }
767 }
768
769 if (config->relocatable)
770 for (InputSectionBase *depSec : s->dependentSections)
771 if (depSec->flags & SHF_LINK_ORDER)
772 add(depSec);
773 };
774
775 // For futher --emit-reloc handling code we need target output section
776 // to be created before we create relocation output section, so we want
777 // to create target sections first. We do not want priority handling
778 // for synthetic sections because them are special.
779 for (InputSectionBase *isec : inputSections) {
780 // In -r links, SHF_LINK_ORDER sections are added while adding their parent
781 // sections because we need to know the parent's output section before we
782 // can select an output section for the SHF_LINK_ORDER section.
783 if (config->relocatable && (isec->flags & SHF_LINK_ORDER))
784 continue;
785
786 if (auto *sec = dyn_cast<InputSection>(isec))
787 if (InputSectionBase *rel = sec->getRelocatedSection())
788 if (auto *relIS = dyn_cast_or_null<InputSectionBase>(rel->parent))
789 add(relIS);
790 add(isec);
791 }
792
793 // If no SECTIONS command was given, we should insert sections commands
794 // before others, so that we can handle scripts which refers them,
795 // for example: "foo = ABSOLUTE(ADDR(.text)));".
796 // When SECTIONS command is present we just add all orphans to the end.
797 if (hasSectionsCommand)
798 sectionCommands.insert(sectionCommands.end(), v.begin(), v.end());
799 else
800 sectionCommands.insert(sectionCommands.begin(), v.begin(), v.end());
801 }
802
diagnoseOrphanHandling() const803 void LinkerScript::diagnoseOrphanHandling() const {
804 llvm::TimeTraceScope timeScope("Diagnose orphan sections");
805 if (config->orphanHandling == OrphanHandlingPolicy::Place)
806 return;
807 for (const InputSectionBase *sec : orphanSections) {
808 // Input SHT_REL[A] retained by --emit-relocs are ignored by
809 // computeInputSections(). Don't warn/error.
810 if (isa<InputSection>(sec) &&
811 cast<InputSection>(sec)->getRelocatedSection())
812 continue;
813
814 StringRef name = getOutputSectionName(sec);
815 if (config->orphanHandling == OrphanHandlingPolicy::Error)
816 error(toString(sec) + " is being placed in '" + name + "'");
817 else
818 warn(toString(sec) + " is being placed in '" + name + "'");
819 }
820 }
821
advance(uint64_t size,unsigned alignment)822 uint64_t LinkerScript::advance(uint64_t size, unsigned alignment) {
823 bool isTbss =
824 (ctx->outSec->flags & SHF_TLS) && ctx->outSec->type == SHT_NOBITS;
825 uint64_t start = isTbss ? dot + ctx->threadBssOffset : dot;
826 start = alignTo(start, alignment);
827 uint64_t end = start + size;
828
829 if (isTbss)
830 ctx->threadBssOffset = end - dot;
831 else
832 dot = end;
833 return end;
834 }
835
output(InputSection * s)836 void LinkerScript::output(InputSection *s) {
837 assert(ctx->outSec == s->getParent());
838 uint64_t before = advance(0, 1);
839 uint64_t pos = advance(s->getSize(), s->alignment);
840 s->outSecOff = pos - s->getSize() - ctx->outSec->addr;
841
842 // Update output section size after adding each section. This is so that
843 // SIZEOF works correctly in the case below:
844 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
845 expandOutputSection(pos - before);
846 }
847
switchTo(OutputSection * sec)848 void LinkerScript::switchTo(OutputSection *sec) {
849 ctx->outSec = sec;
850
851 uint64_t pos = advance(0, 1);
852 if (sec->addrExpr && script->hasSectionsCommand) {
853 // The alignment is ignored.
854 ctx->outSec->addr = pos;
855 } else {
856 // ctx->outSec->alignment is the max of ALIGN and the maximum of input
857 // section alignments.
858 ctx->outSec->addr = advance(0, ctx->outSec->alignment);
859 expandMemoryRegions(ctx->outSec->addr - pos);
860 }
861 }
862
863 // This function searches for a memory region to place the given output
864 // section in. If found, a pointer to the appropriate memory region is
865 // returned. Otherwise, a nullptr is returned.
findMemoryRegion(OutputSection * sec)866 MemoryRegion *LinkerScript::findMemoryRegion(OutputSection *sec) {
867 // If a memory region name was specified in the output section command,
868 // then try to find that region first.
869 if (!sec->memoryRegionName.empty()) {
870 if (MemoryRegion *m = memoryRegions.lookup(sec->memoryRegionName))
871 return m;
872 error("memory region '" + sec->memoryRegionName + "' not declared");
873 return nullptr;
874 }
875
876 // If at least one memory region is defined, all sections must
877 // belong to some memory region. Otherwise, we don't need to do
878 // anything for memory regions.
879 if (memoryRegions.empty())
880 return nullptr;
881
882 // See if a region can be found by matching section flags.
883 for (auto &pair : memoryRegions) {
884 MemoryRegion *m = pair.second;
885 if ((m->flags & sec->flags) && (m->negFlags & sec->flags) == 0)
886 return m;
887 }
888
889 // Otherwise, no suitable region was found.
890 if (sec->flags & SHF_ALLOC)
891 error("no memory region specified for section '" + sec->name + "'");
892 return nullptr;
893 }
894
findFirstSection(PhdrEntry * load)895 static OutputSection *findFirstSection(PhdrEntry *load) {
896 for (OutputSection *sec : outputSections)
897 if (sec->ptLoad == load)
898 return sec;
899 return nullptr;
900 }
901
902 // This function assigns offsets to input sections and an output section
903 // for a single sections command (e.g. ".text { *(.text); }").
assignOffsets(OutputSection * sec)904 void LinkerScript::assignOffsets(OutputSection *sec) {
905 const bool sameMemRegion = ctx->memRegion == sec->memRegion;
906 const bool prevLMARegionIsDefault = ctx->lmaRegion == nullptr;
907 const uint64_t savedDot = dot;
908 ctx->memRegion = sec->memRegion;
909 ctx->lmaRegion = sec->lmaRegion;
910
911 if (sec->flags & SHF_ALLOC) {
912 if (ctx->memRegion)
913 dot = ctx->memRegion->curPos;
914 if (sec->addrExpr)
915 setDot(sec->addrExpr, sec->location, false);
916
917 // If the address of the section has been moved forward by an explicit
918 // expression so that it now starts past the current curPos of the enclosing
919 // region, we need to expand the current region to account for the space
920 // between the previous section, if any, and the start of this section.
921 if (ctx->memRegion && ctx->memRegion->curPos < dot)
922 expandMemoryRegion(ctx->memRegion, dot - ctx->memRegion->curPos,
923 ctx->memRegion->name, sec->name);
924 } else {
925 // Non-SHF_ALLOC sections have zero addresses.
926 dot = 0;
927 }
928
929 switchTo(sec);
930
931 // ctx->lmaOffset is LMA minus VMA. If LMA is explicitly specified via AT() or
932 // AT>, recompute ctx->lmaOffset; otherwise, if both previous/current LMA
933 // region is the default, and the two sections are in the same memory region,
934 // reuse previous lmaOffset; otherwise, reset lmaOffset to 0. This emulates
935 // heuristics described in
936 // https://sourceware.org/binutils/docs/ld/Output-Section-LMA.html
937 if (sec->lmaExpr)
938 ctx->lmaOffset = sec->lmaExpr().getValue() - dot;
939 else if (MemoryRegion *mr = sec->lmaRegion)
940 ctx->lmaOffset = alignTo(mr->curPos, sec->alignment) - dot;
941 else if (!sameMemRegion || !prevLMARegionIsDefault)
942 ctx->lmaOffset = 0;
943
944 // Propagate ctx->lmaOffset to the first "non-header" section.
945 if (PhdrEntry *l = ctx->outSec->ptLoad)
946 if (sec == findFirstSection(l))
947 l->lmaOffset = ctx->lmaOffset;
948
949 // We can call this method multiple times during the creation of
950 // thunks and want to start over calculation each time.
951 sec->size = 0;
952
953 // We visited SectionsCommands from processSectionCommands to
954 // layout sections. Now, we visit SectionsCommands again to fix
955 // section offsets.
956 for (BaseCommand *base : sec->sectionCommands) {
957 // This handles the assignments to symbol or to the dot.
958 if (auto *cmd = dyn_cast<SymbolAssignment>(base)) {
959 cmd->addr = dot;
960 assignSymbol(cmd, true);
961 cmd->size = dot - cmd->addr;
962 continue;
963 }
964
965 // Handle BYTE(), SHORT(), LONG(), or QUAD().
966 if (auto *cmd = dyn_cast<ByteCommand>(base)) {
967 cmd->offset = dot - ctx->outSec->addr;
968 dot += cmd->size;
969 expandOutputSection(cmd->size);
970 continue;
971 }
972
973 // Handle a single input section description command.
974 // It calculates and assigns the offsets for each section and also
975 // updates the output section size.
976 for (InputSection *sec : cast<InputSectionDescription>(base)->sections)
977 output(sec);
978 }
979
980 // Non-SHF_ALLOC sections do not affect the addresses of other OutputSections
981 // as they are not part of the process image.
982 if (!(sec->flags & SHF_ALLOC))
983 dot = savedDot;
984 }
985
isDiscardable(OutputSection & sec)986 static bool isDiscardable(OutputSection &sec) {
987 if (sec.name == "/DISCARD/")
988 return true;
989
990 // We do not want to remove OutputSections with expressions that reference
991 // symbols even if the OutputSection is empty. We want to ensure that the
992 // expressions can be evaluated and report an error if they cannot.
993 if (sec.expressionsUseSymbols)
994 return false;
995
996 // OutputSections may be referenced by name in ADDR and LOADADDR expressions,
997 // as an empty Section can has a valid VMA and LMA we keep the OutputSection
998 // to maintain the integrity of the other Expression.
999 if (sec.usedInExpression)
1000 return false;
1001
1002 for (BaseCommand *base : sec.sectionCommands) {
1003 if (auto cmd = dyn_cast<SymbolAssignment>(base))
1004 // Don't create empty output sections just for unreferenced PROVIDE
1005 // symbols.
1006 if (cmd->name != "." && !cmd->sym)
1007 continue;
1008
1009 if (!isa<InputSectionDescription>(*base))
1010 return false;
1011 }
1012 return true;
1013 }
1014
maybePropagatePhdrs(OutputSection & sec,std::vector<StringRef> & phdrs)1015 static void maybePropagatePhdrs(OutputSection &sec,
1016 std::vector<StringRef> &phdrs) {
1017 if (sec.phdrs.empty()) {
1018 // To match the bfd linker script behaviour, only propagate program
1019 // headers to sections that are allocated.
1020 if (sec.flags & SHF_ALLOC)
1021 sec.phdrs = phdrs;
1022 } else {
1023 phdrs = sec.phdrs;
1024 }
1025 }
1026
adjustSectionsBeforeSorting()1027 void LinkerScript::adjustSectionsBeforeSorting() {
1028 // If the output section contains only symbol assignments, create a
1029 // corresponding output section. The issue is what to do with linker script
1030 // like ".foo : { symbol = 42; }". One option would be to convert it to
1031 // "symbol = 42;". That is, move the symbol out of the empty section
1032 // description. That seems to be what bfd does for this simple case. The
1033 // problem is that this is not completely general. bfd will give up and
1034 // create a dummy section too if there is a ". = . + 1" inside the section
1035 // for example.
1036 // Given that we want to create the section, we have to worry what impact
1037 // it will have on the link. For example, if we just create a section with
1038 // 0 for flags, it would change which PT_LOADs are created.
1039 // We could remember that particular section is dummy and ignore it in
1040 // other parts of the linker, but unfortunately there are quite a few places
1041 // that would need to change:
1042 // * The program header creation.
1043 // * The orphan section placement.
1044 // * The address assignment.
1045 // The other option is to pick flags that minimize the impact the section
1046 // will have on the rest of the linker. That is why we copy the flags from
1047 // the previous sections. Only a few flags are needed to keep the impact low.
1048 uint64_t flags = SHF_ALLOC;
1049
1050 std::vector<StringRef> defPhdrs;
1051 for (BaseCommand *&cmd : sectionCommands) {
1052 auto *sec = dyn_cast<OutputSection>(cmd);
1053 if (!sec)
1054 continue;
1055
1056 // Handle align (e.g. ".foo : ALIGN(16) { ... }").
1057 if (sec->alignExpr)
1058 sec->alignment =
1059 std::max<uint32_t>(sec->alignment, sec->alignExpr().getValue());
1060
1061 // The input section might have been removed (if it was an empty synthetic
1062 // section), but we at least know the flags.
1063 if (sec->hasInputSections)
1064 flags = sec->flags;
1065
1066 // We do not want to keep any special flags for output section
1067 // in case it is empty.
1068 bool isEmpty = (getFirstInputSection(sec) == nullptr);
1069 if (isEmpty)
1070 sec->flags = flags & ((sec->nonAlloc ? 0 : (uint64_t)SHF_ALLOC) |
1071 SHF_WRITE | SHF_EXECINSTR);
1072
1073 // The code below may remove empty output sections. We should save the
1074 // specified program headers (if exist) and propagate them to subsequent
1075 // sections which do not specify program headers.
1076 // An example of such a linker script is:
1077 // SECTIONS { .empty : { *(.empty) } :rw
1078 // .foo : { *(.foo) } }
1079 // Note: at this point the order of output sections has not been finalized,
1080 // because orphans have not been inserted into their expected positions. We
1081 // will handle them in adjustSectionsAfterSorting().
1082 if (sec->sectionIndex != UINT32_MAX)
1083 maybePropagatePhdrs(*sec, defPhdrs);
1084
1085 if (isEmpty && isDiscardable(*sec)) {
1086 sec->markDead();
1087 cmd = nullptr;
1088 }
1089 }
1090
1091 // It is common practice to use very generic linker scripts. So for any
1092 // given run some of the output sections in the script will be empty.
1093 // We could create corresponding empty output sections, but that would
1094 // clutter the output.
1095 // We instead remove trivially empty sections. The bfd linker seems even
1096 // more aggressive at removing them.
1097 llvm::erase_if(sectionCommands, [&](BaseCommand *base) { return !base; });
1098 }
1099
adjustSectionsAfterSorting()1100 void LinkerScript::adjustSectionsAfterSorting() {
1101 // Try and find an appropriate memory region to assign offsets in.
1102 for (BaseCommand *base : sectionCommands) {
1103 if (auto *sec = dyn_cast<OutputSection>(base)) {
1104 if (!sec->lmaRegionName.empty()) {
1105 if (MemoryRegion *m = memoryRegions.lookup(sec->lmaRegionName))
1106 sec->lmaRegion = m;
1107 else
1108 error("memory region '" + sec->lmaRegionName + "' not declared");
1109 }
1110 sec->memRegion = findMemoryRegion(sec);
1111 }
1112 }
1113
1114 // If output section command doesn't specify any segments,
1115 // and we haven't previously assigned any section to segment,
1116 // then we simply assign section to the very first load segment.
1117 // Below is an example of such linker script:
1118 // PHDRS { seg PT_LOAD; }
1119 // SECTIONS { .aaa : { *(.aaa) } }
1120 std::vector<StringRef> defPhdrs;
1121 auto firstPtLoad = llvm::find_if(phdrsCommands, [](const PhdrsCommand &cmd) {
1122 return cmd.type == PT_LOAD;
1123 });
1124 if (firstPtLoad != phdrsCommands.end())
1125 defPhdrs.push_back(firstPtLoad->name);
1126
1127 // Walk the commands and propagate the program headers to commands that don't
1128 // explicitly specify them.
1129 for (BaseCommand *base : sectionCommands)
1130 if (auto *sec = dyn_cast<OutputSection>(base))
1131 maybePropagatePhdrs(*sec, defPhdrs);
1132 }
1133
computeBase(uint64_t min,bool allocateHeaders)1134 static uint64_t computeBase(uint64_t min, bool allocateHeaders) {
1135 // If there is no SECTIONS or if the linkerscript is explicit about program
1136 // headers, do our best to allocate them.
1137 if (!script->hasSectionsCommand || allocateHeaders)
1138 return 0;
1139 // Otherwise only allocate program headers if that would not add a page.
1140 return alignDown(min, config->maxPageSize);
1141 }
1142
1143 // When the SECTIONS command is used, try to find an address for the file and
1144 // program headers output sections, which can be added to the first PT_LOAD
1145 // segment when program headers are created.
1146 //
1147 // We check if the headers fit below the first allocated section. If there isn't
1148 // enough space for these sections, we'll remove them from the PT_LOAD segment,
1149 // and we'll also remove the PT_PHDR segment.
allocateHeaders(std::vector<PhdrEntry * > & phdrs)1150 void LinkerScript::allocateHeaders(std::vector<PhdrEntry *> &phdrs) {
1151 uint64_t min = std::numeric_limits<uint64_t>::max();
1152 for (OutputSection *sec : outputSections)
1153 if (sec->flags & SHF_ALLOC)
1154 min = std::min<uint64_t>(min, sec->addr);
1155
1156 auto it = llvm::find_if(
1157 phdrs, [](const PhdrEntry *e) { return e->p_type == PT_LOAD; });
1158 if (it == phdrs.end())
1159 return;
1160 PhdrEntry *firstPTLoad = *it;
1161
1162 bool hasExplicitHeaders =
1163 llvm::any_of(phdrsCommands, [](const PhdrsCommand &cmd) {
1164 return cmd.hasPhdrs || cmd.hasFilehdr;
1165 });
1166 bool paged = !config->omagic && !config->nmagic;
1167 uint64_t headerSize = getHeaderSize();
1168 if ((paged || hasExplicitHeaders) &&
1169 headerSize <= min - computeBase(min, hasExplicitHeaders)) {
1170 min = alignDown(min - headerSize, config->maxPageSize);
1171 Out::elfHeader->addr = min;
1172 Out::programHeaders->addr = min + Out::elfHeader->size;
1173 return;
1174 }
1175
1176 // Error if we were explicitly asked to allocate headers.
1177 if (hasExplicitHeaders)
1178 error("could not allocate headers");
1179
1180 Out::elfHeader->ptLoad = nullptr;
1181 Out::programHeaders->ptLoad = nullptr;
1182 firstPTLoad->firstSec = findFirstSection(firstPTLoad);
1183
1184 llvm::erase_if(phdrs,
1185 [](const PhdrEntry *e) { return e->p_type == PT_PHDR; });
1186 }
1187
AddressState()1188 LinkerScript::AddressState::AddressState() {
1189 for (auto &mri : script->memoryRegions) {
1190 MemoryRegion *mr = mri.second;
1191 mr->curPos = (mr->origin)().getValue();
1192 }
1193 }
1194
1195 // Here we assign addresses as instructed by linker script SECTIONS
1196 // sub-commands. Doing that allows us to use final VA values, so here
1197 // we also handle rest commands like symbol assignments and ASSERTs.
1198 // Returns a symbol that has changed its section or value, or nullptr if no
1199 // symbol has changed.
assignAddresses()1200 const Defined *LinkerScript::assignAddresses() {
1201 if (script->hasSectionsCommand) {
1202 // With a linker script, assignment of addresses to headers is covered by
1203 // allocateHeaders().
1204 dot = config->imageBase.getValueOr(0);
1205 } else {
1206 // Assign addresses to headers right now.
1207 dot = target->getImageBase();
1208 Out::elfHeader->addr = dot;
1209 Out::programHeaders->addr = dot + Out::elfHeader->size;
1210 dot += getHeaderSize();
1211 }
1212
1213 auto deleter = std::make_unique<AddressState>();
1214 ctx = deleter.get();
1215 errorOnMissingSection = true;
1216 switchTo(aether);
1217
1218 SymbolAssignmentMap oldValues = getSymbolAssignmentValues(sectionCommands);
1219 for (BaseCommand *base : sectionCommands) {
1220 if (auto *cmd = dyn_cast<SymbolAssignment>(base)) {
1221 cmd->addr = dot;
1222 assignSymbol(cmd, false);
1223 cmd->size = dot - cmd->addr;
1224 continue;
1225 }
1226 assignOffsets(cast<OutputSection>(base));
1227 }
1228
1229 ctx = nullptr;
1230 return getChangedSymbolAssignment(oldValues);
1231 }
1232
1233 // Creates program headers as instructed by PHDRS linker script command.
createPhdrs()1234 std::vector<PhdrEntry *> LinkerScript::createPhdrs() {
1235 std::vector<PhdrEntry *> ret;
1236
1237 // Process PHDRS and FILEHDR keywords because they are not
1238 // real output sections and cannot be added in the following loop.
1239 for (const PhdrsCommand &cmd : phdrsCommands) {
1240 PhdrEntry *phdr = make<PhdrEntry>(cmd.type, cmd.flags ? *cmd.flags : PF_R);
1241
1242 if (cmd.hasFilehdr)
1243 phdr->add(Out::elfHeader);
1244 if (cmd.hasPhdrs)
1245 phdr->add(Out::programHeaders);
1246
1247 if (cmd.lmaExpr) {
1248 phdr->p_paddr = cmd.lmaExpr().getValue();
1249 phdr->hasLMA = true;
1250 }
1251 ret.push_back(phdr);
1252 }
1253
1254 // Add output sections to program headers.
1255 for (OutputSection *sec : outputSections) {
1256 // Assign headers specified by linker script
1257 for (size_t id : getPhdrIndices(sec)) {
1258 ret[id]->add(sec);
1259 if (!phdrsCommands[id].flags.hasValue())
1260 ret[id]->p_flags |= sec->getPhdrFlags();
1261 }
1262 }
1263 return ret;
1264 }
1265
1266 // Returns true if we should emit an .interp section.
1267 //
1268 // We usually do. But if PHDRS commands are given, and
1269 // no PT_INTERP is there, there's no place to emit an
1270 // .interp, so we don't do that in that case.
needsInterpSection()1271 bool LinkerScript::needsInterpSection() {
1272 if (phdrsCommands.empty())
1273 return true;
1274 for (PhdrsCommand &cmd : phdrsCommands)
1275 if (cmd.type == PT_INTERP)
1276 return true;
1277 return false;
1278 }
1279
getSymbolValue(StringRef name,const Twine & loc)1280 ExprValue LinkerScript::getSymbolValue(StringRef name, const Twine &loc) {
1281 if (name == ".") {
1282 if (ctx)
1283 return {ctx->outSec, false, dot - ctx->outSec->addr, loc};
1284 error(loc + ": unable to get location counter value");
1285 return 0;
1286 }
1287
1288 if (Symbol *sym = symtab->find(name)) {
1289 if (auto *ds = dyn_cast<Defined>(sym)) {
1290 ExprValue v{ds->section, false, ds->value, loc};
1291 // Retain the original st_type, so that the alias will get the same
1292 // behavior in relocation processing. Any operation will reset st_type to
1293 // STT_NOTYPE.
1294 v.type = ds->type;
1295 return v;
1296 }
1297 if (isa<SharedSymbol>(sym))
1298 if (!errorOnMissingSection)
1299 return {nullptr, false, 0, loc};
1300 }
1301
1302 error(loc + ": symbol not found: " + name);
1303 return 0;
1304 }
1305
1306 // Returns the index of the segment named Name.
getPhdrIndex(ArrayRef<PhdrsCommand> vec,StringRef name)1307 static Optional<size_t> getPhdrIndex(ArrayRef<PhdrsCommand> vec,
1308 StringRef name) {
1309 for (size_t i = 0; i < vec.size(); ++i)
1310 if (vec[i].name == name)
1311 return i;
1312 return None;
1313 }
1314
1315 // Returns indices of ELF headers containing specific section. Each index is a
1316 // zero based number of ELF header listed within PHDRS {} script block.
getPhdrIndices(OutputSection * cmd)1317 std::vector<size_t> LinkerScript::getPhdrIndices(OutputSection *cmd) {
1318 std::vector<size_t> ret;
1319
1320 for (StringRef s : cmd->phdrs) {
1321 if (Optional<size_t> idx = getPhdrIndex(phdrsCommands, s))
1322 ret.push_back(*idx);
1323 else if (s != "NONE")
1324 error(cmd->location + ": program header '" + s +
1325 "' is not listed in PHDRS");
1326 }
1327 return ret;
1328 }
1329