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