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