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