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