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