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