xref: /llvm-project/lld/ELF/LinkerScript.cpp (revision 18078605046c50f01f31e826ea3591f99019de38)
1 //===- LinkerScript.cpp ---------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains the parser/evaluator of the linker script.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "LinkerScript.h"
14 #include "Config.h"
15 #include "InputFiles.h"
16 #include "InputSection.h"
17 #include "OutputSections.h"
18 #include "SymbolTable.h"
19 #include "Symbols.h"
20 #include "SyntheticSections.h"
21 #include "Target.h"
22 #include "Writer.h"
23 #include "lld/Common/CommonLinkerContext.h"
24 #include "lld/Common/Strings.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/BinaryFormat/ELF.h"
28 #include "llvm/Support/Casting.h"
29 #include "llvm/Support/Endian.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/TimeProfiler.h"
32 #include <algorithm>
33 #include <cassert>
34 #include <cstddef>
35 #include <cstdint>
36 #include <limits>
37 #include <string>
38 #include <vector>
39 
40 using namespace llvm;
41 using namespace llvm::ELF;
42 using namespace llvm::object;
43 using namespace llvm::support::endian;
44 using namespace lld;
45 using namespace lld::elf;
46 
47 static bool isSectionPrefix(StringRef prefix, StringRef name) {
48   return name.consume_front(prefix) && (name.empty() || name[0] == '.');
49 }
50 
51 StringRef LinkerScript::getOutputSectionName(const InputSectionBase *s) const {
52   // This is for --emit-relocs and -r. If .text.foo is emitted as .text.bar, we
53   // want to emit .rela.text.foo as .rela.text.bar for consistency (this is not
54   // technically required, but not doing it is odd). This code guarantees that.
55   if (auto *isec = dyn_cast<InputSection>(s)) {
56     if (InputSectionBase *rel = isec->getRelocatedSection()) {
57       OutputSection *out = rel->getOutputSection();
58       if (!out) {
59         assert(ctx.arg.relocatable && (rel->flags & SHF_LINK_ORDER));
60         return s->name;
61       }
62       StringSaver &ss = ctx.saver;
63       if (s->type == SHT_CREL)
64         return ss.save(".crel" + out->name);
65       if (s->type == SHT_RELA)
66         return ss.save(".rela" + out->name);
67       return ss.save(".rel" + out->name);
68     }
69   }
70 
71   if (ctx.arg.relocatable)
72     return s->name;
73 
74   // A BssSection created for a common symbol is identified as "COMMON" in
75   // linker scripts. It should go to .bss section.
76   if (s->name == "COMMON")
77     return ".bss";
78 
79   if (hasSectionsCommand)
80     return s->name;
81 
82   // When no SECTIONS is specified, emulate GNU ld's internal linker scripts
83   // by grouping sections with certain prefixes.
84 
85   // GNU ld places text sections with prefix ".text.hot.", ".text.unknown.",
86   // ".text.unlikely.", ".text.startup." or ".text.exit." before others.
87   // We provide an option -z keep-text-section-prefix to group such sections
88   // into separate output sections. This is more flexible. See also
89   // sortISDBySectionOrder().
90   // ".text.unknown" means the hotness of the section is unknown. When
91   // SampleFDO is used, if a function doesn't have sample, it could be very
92   // cold or it could be a new function never being sampled. Those functions
93   // will be kept in the ".text.unknown" section.
94   // ".text.split." holds symbols which are split out from functions in other
95   // input sections. For example, with -fsplit-machine-functions, placing the
96   // cold parts in .text.split instead of .text.unlikely mitigates against poor
97   // profile inaccuracy. Techniques such as hugepage remapping can make
98   // conservative decisions at the section granularity.
99   if (isSectionPrefix(".text", s->name)) {
100     if (ctx.arg.zKeepTextSectionPrefix)
101       for (StringRef v : {".text.hot", ".text.unknown", ".text.unlikely",
102                           ".text.startup", ".text.exit", ".text.split"})
103         if (isSectionPrefix(v.substr(5), s->name.substr(5)))
104           return v;
105     return ".text";
106   }
107 
108   for (StringRef v : {".data.rel.ro", ".data",       ".rodata",
109                       ".bss.rel.ro",  ".bss",        ".ldata",
110                       ".lrodata",     ".lbss",       ".gcc_except_table",
111                       ".init_array",  ".fini_array", ".tbss",
112                       ".tdata",       ".ARM.exidx",  ".ARM.extab",
113                       ".ctors",       ".dtors",      ".sbss",
114                       ".sdata",       ".srodata"})
115     if (isSectionPrefix(v, s->name))
116       return v;
117 
118   return s->name;
119 }
120 
121 uint64_t ExprValue::getValue() const {
122   if (sec)
123     return alignToPowerOf2(sec->getOutputSection()->addr + sec->getOffset(val),
124                            alignment);
125   return alignToPowerOf2(val, alignment);
126 }
127 
128 uint64_t ExprValue::getSecAddr() const {
129   return sec ? sec->getOutputSection()->addr + sec->getOffset(0) : 0;
130 }
131 
132 uint64_t ExprValue::getSectionOffset() const {
133   return getValue() - getSecAddr();
134 }
135 
136 // std::unique_ptr<OutputSection> may be incomplete type.
137 LinkerScript::LinkerScript(Ctx &ctx) : ctx(ctx) {}
138 LinkerScript::~LinkerScript() {}
139 
140 OutputDesc *LinkerScript::createOutputSection(StringRef name,
141                                               StringRef location) {
142   OutputDesc *&secRef = nameToOutputSection[CachedHashStringRef(name)];
143   OutputDesc *sec;
144   if (secRef && secRef->osec.location.empty()) {
145     // There was a forward reference.
146     sec = secRef;
147   } else {
148     descPool.emplace_back(
149         std::make_unique<OutputDesc>(ctx, name, SHT_PROGBITS, 0));
150     sec = descPool.back().get();
151     if (!secRef)
152       secRef = sec;
153   }
154   sec->osec.location = std::string(location);
155   return sec;
156 }
157 
158 OutputDesc *LinkerScript::getOrCreateOutputSection(StringRef name) {
159   auto &secRef = nameToOutputSection[CachedHashStringRef(name)];
160   if (!secRef) {
161     secRef = descPool
162                  .emplace_back(
163                      std::make_unique<OutputDesc>(ctx, name, SHT_PROGBITS, 0))
164                  .get();
165   }
166   return secRef;
167 }
168 
169 // Expands the memory region by the specified size.
170 static void expandMemoryRegion(MemoryRegion *memRegion, uint64_t size,
171                                StringRef secName) {
172   memRegion->curPos += size;
173 }
174 
175 void LinkerScript::expandMemoryRegions(uint64_t size) {
176   if (state->memRegion)
177     expandMemoryRegion(state->memRegion, size, state->outSec->name);
178   // Only expand the LMARegion if it is different from memRegion.
179   if (state->lmaRegion && state->memRegion != state->lmaRegion)
180     expandMemoryRegion(state->lmaRegion, size, state->outSec->name);
181 }
182 
183 void LinkerScript::expandOutputSection(uint64_t size) {
184   state->outSec->size += size;
185   expandMemoryRegions(size);
186 }
187 
188 void LinkerScript::setDot(Expr e, const Twine &loc, bool inSec) {
189   uint64_t val = e().getValue();
190   // If val is smaller and we are in an output section, record the error and
191   // report it if this is the last assignAddresses iteration. dot may be smaller
192   // if there is another assignAddresses iteration.
193   if (val < dot && inSec) {
194     recordError(loc + ": unable to move location counter (0x" +
195                 Twine::utohexstr(dot) + ") backward to 0x" +
196                 Twine::utohexstr(val) + " for section '" + state->outSec->name +
197                 "'");
198   }
199 
200   // Update to location counter means update to section size.
201   if (inSec)
202     expandOutputSection(val - dot);
203 
204   dot = val;
205 }
206 
207 // Used for handling linker symbol assignments, for both finalizing
208 // their values and doing early declarations. Returns true if symbol
209 // should be defined from linker script.
210 static bool shouldDefineSym(Ctx &ctx, SymbolAssignment *cmd) {
211   if (cmd->name == ".")
212     return false;
213 
214   return !cmd->provide || ctx.script->shouldAddProvideSym(cmd->name);
215 }
216 
217 // Called by processSymbolAssignments() to assign definitions to
218 // linker-script-defined symbols.
219 void LinkerScript::addSymbol(SymbolAssignment *cmd) {
220   if (!shouldDefineSym(ctx, cmd))
221     return;
222 
223   // Define a symbol.
224   ExprValue value = cmd->expression();
225   SectionBase *sec = value.isAbsolute() ? nullptr : value.sec;
226   uint8_t visibility = cmd->hidden ? STV_HIDDEN : STV_DEFAULT;
227 
228   // When this function is called, section addresses have not been
229   // fixed yet. So, we may or may not know the value of the RHS
230   // expression.
231   //
232   // For example, if an expression is `x = 42`, we know x is always 42.
233   // However, if an expression is `x = .`, there's no way to know its
234   // value at the moment.
235   //
236   // We want to set symbol values early if we can. This allows us to
237   // use symbols as variables in linker scripts. Doing so allows us to
238   // write expressions like this: `alignment = 16; . = ALIGN(., alignment)`.
239   uint64_t symValue = value.sec ? 0 : value.getValue();
240 
241   Defined newSym(ctx, createInternalFile(ctx, cmd->location), cmd->name,
242                  STB_GLOBAL, visibility, value.type, symValue, 0, sec);
243 
244   Symbol *sym = ctx.symtab->insert(cmd->name);
245   sym->mergeProperties(newSym);
246   newSym.overwrite(*sym);
247   sym->isUsedInRegularObj = true;
248   cmd->sym = cast<Defined>(sym);
249 }
250 
251 // This function is called from LinkerScript::declareSymbols.
252 // It creates a placeholder symbol if needed.
253 void LinkerScript::declareSymbol(SymbolAssignment *cmd) {
254   if (!shouldDefineSym(ctx, cmd))
255     return;
256 
257   uint8_t visibility = cmd->hidden ? STV_HIDDEN : STV_DEFAULT;
258   Defined newSym(ctx, ctx.internalFile, cmd->name, STB_GLOBAL, visibility,
259                  STT_NOTYPE, 0, 0, nullptr);
260 
261   // If the symbol is already defined, its order is 0 (with absence indicating
262   // 0); otherwise it's assigned the order of the SymbolAssignment.
263   Symbol *sym = ctx.symtab->insert(cmd->name);
264   if (!sym->isDefined())
265     ctx.scriptSymOrder.insert({sym, cmd->symOrder});
266 
267   // We can't calculate final value right now.
268   sym->mergeProperties(newSym);
269   newSym.overwrite(*sym);
270 
271   cmd->sym = cast<Defined>(sym);
272   cmd->provide = false;
273   sym->isUsedInRegularObj = true;
274   sym->scriptDefined = true;
275 }
276 
277 using SymbolAssignmentMap =
278     DenseMap<const Defined *, std::pair<SectionBase *, uint64_t>>;
279 
280 // Collect section/value pairs of linker-script-defined symbols. This is used to
281 // check whether symbol values converge.
282 static SymbolAssignmentMap
283 getSymbolAssignmentValues(ArrayRef<SectionCommand *> sectionCommands) {
284   SymbolAssignmentMap ret;
285   for (SectionCommand *cmd : sectionCommands) {
286     if (auto *assign = dyn_cast<SymbolAssignment>(cmd)) {
287       if (assign->sym) // sym is nullptr for dot.
288         ret.try_emplace(assign->sym, std::make_pair(assign->sym->section,
289                                                     assign->sym->value));
290       continue;
291     }
292     if (isa<SectionClassDesc>(cmd))
293       continue;
294     for (SectionCommand *subCmd : cast<OutputDesc>(cmd)->osec.commands)
295       if (auto *assign = dyn_cast<SymbolAssignment>(subCmd))
296         if (assign->sym)
297           ret.try_emplace(assign->sym, std::make_pair(assign->sym->section,
298                                                       assign->sym->value));
299   }
300   return ret;
301 }
302 
303 // Returns the lexicographical smallest (for determinism) Defined whose
304 // section/value has changed.
305 static const Defined *
306 getChangedSymbolAssignment(const SymbolAssignmentMap &oldValues) {
307   const Defined *changed = nullptr;
308   for (auto &it : oldValues) {
309     const Defined *sym = it.first;
310     if (std::make_pair(sym->section, sym->value) != it.second &&
311         (!changed || sym->getName() < changed->getName()))
312       changed = sym;
313   }
314   return changed;
315 }
316 
317 // Process INSERT [AFTER|BEFORE] commands. For each command, we move the
318 // specified output section to the designated place.
319 void LinkerScript::processInsertCommands() {
320   SmallVector<OutputDesc *, 0> moves;
321   for (const InsertCommand &cmd : insertCommands) {
322     if (ctx.arg.enableNonContiguousRegions)
323       ErrAlways(ctx)
324           << "INSERT cannot be used with --enable-non-contiguous-regions";
325 
326     for (StringRef name : cmd.names) {
327       // If base is empty, it may have been discarded by
328       // adjustOutputSections(). We do not handle such output sections.
329       auto from = llvm::find_if(sectionCommands, [&](SectionCommand *subCmd) {
330         return isa<OutputDesc>(subCmd) &&
331                cast<OutputDesc>(subCmd)->osec.name == name;
332       });
333       if (from == sectionCommands.end())
334         continue;
335       moves.push_back(cast<OutputDesc>(*from));
336       sectionCommands.erase(from);
337     }
338 
339     auto insertPos =
340         llvm::find_if(sectionCommands, [&cmd](SectionCommand *subCmd) {
341           auto *to = dyn_cast<OutputDesc>(subCmd);
342           return to != nullptr && to->osec.name == cmd.where;
343         });
344     if (insertPos == sectionCommands.end()) {
345       ErrAlways(ctx) << "unable to insert " << cmd.names[0]
346                      << (cmd.isAfter ? " after " : " before ") << cmd.where;
347     } else {
348       if (cmd.isAfter)
349         ++insertPos;
350       sectionCommands.insert(insertPos, moves.begin(), moves.end());
351     }
352     moves.clear();
353   }
354 }
355 
356 // Symbols defined in script should not be inlined by LTO. At the same time
357 // we don't know their final values until late stages of link. Here we scan
358 // over symbol assignment commands and create placeholder symbols if needed.
359 void LinkerScript::declareSymbols() {
360   assert(!state);
361   for (SectionCommand *cmd : sectionCommands) {
362     if (auto *assign = dyn_cast<SymbolAssignment>(cmd)) {
363       declareSymbol(assign);
364       continue;
365     }
366     if (isa<SectionClassDesc>(cmd))
367       continue;
368 
369     // If the output section directive has constraints,
370     // we can't say for sure if it is going to be included or not.
371     // Skip such sections for now. Improve the checks if we ever
372     // need symbols from that sections to be declared early.
373     const OutputSection &sec = cast<OutputDesc>(cmd)->osec;
374     if (sec.constraint != ConstraintKind::NoConstraint)
375       continue;
376     for (SectionCommand *cmd : sec.commands)
377       if (auto *assign = dyn_cast<SymbolAssignment>(cmd))
378         declareSymbol(assign);
379   }
380 }
381 
382 // This function is called from assignAddresses, while we are
383 // fixing the output section addresses. This function is supposed
384 // to set the final value for a given symbol assignment.
385 void LinkerScript::assignSymbol(SymbolAssignment *cmd, bool inSec) {
386   if (cmd->name == ".") {
387     setDot(cmd->expression, cmd->location, inSec);
388     return;
389   }
390 
391   if (!cmd->sym)
392     return;
393 
394   ExprValue v = cmd->expression();
395   if (v.isAbsolute()) {
396     cmd->sym->section = nullptr;
397     cmd->sym->value = v.getValue();
398   } else {
399     cmd->sym->section = v.sec;
400     cmd->sym->value = v.getSectionOffset();
401   }
402   cmd->sym->type = v.type;
403 }
404 
405 bool InputSectionDescription::matchesFile(const InputFile &file) const {
406   if (filePat.isTrivialMatchAll())
407     return true;
408 
409   if (!matchesFileCache || matchesFileCache->first != &file) {
410     if (matchType == MatchType::WholeArchive) {
411       matchesFileCache.emplace(&file, filePat.match(file.archiveName));
412     } else {
413       if (matchType == MatchType::ArchivesExcluded && !file.archiveName.empty())
414         matchesFileCache.emplace(&file, false);
415       else
416         matchesFileCache.emplace(&file, filePat.match(file.getNameForScript()));
417     }
418   }
419 
420   return matchesFileCache->second;
421 }
422 
423 bool SectionPattern::excludesFile(const InputFile &file) const {
424   if (excludedFilePat.empty())
425     return false;
426 
427   if (!excludesFileCache || excludesFileCache->first != &file)
428     excludesFileCache.emplace(&file,
429                               excludedFilePat.match(file.getNameForScript()));
430 
431   return excludesFileCache->second;
432 }
433 
434 bool LinkerScript::shouldKeep(InputSectionBase *s) {
435   for (InputSectionDescription *id : keptSections)
436     if (id->matchesFile(*s->file))
437       for (SectionPattern &p : id->sectionPatterns)
438         if (p.sectionPat.match(s->name) &&
439             (s->flags & id->withFlags) == id->withFlags &&
440             (s->flags & id->withoutFlags) == 0)
441           return true;
442   return false;
443 }
444 
445 // A helper function for the SORT() command.
446 static bool matchConstraints(ArrayRef<InputSectionBase *> sections,
447                              ConstraintKind kind) {
448   if (kind == ConstraintKind::NoConstraint)
449     return true;
450 
451   bool isRW = llvm::any_of(
452       sections, [](InputSectionBase *sec) { return sec->flags & SHF_WRITE; });
453 
454   return (isRW && kind == ConstraintKind::ReadWrite) ||
455          (!isRW && kind == ConstraintKind::ReadOnly);
456 }
457 
458 static void sortSections(MutableArrayRef<InputSectionBase *> vec,
459                          SortSectionPolicy k) {
460   auto alignmentComparator = [](InputSectionBase *a, InputSectionBase *b) {
461     // ">" is not a mistake. Sections with larger alignments are placed
462     // before sections with smaller alignments in order to reduce the
463     // amount of padding necessary. This is compatible with GNU.
464     return a->addralign > b->addralign;
465   };
466   auto nameComparator = [](InputSectionBase *a, InputSectionBase *b) {
467     return a->name < b->name;
468   };
469   auto priorityComparator = [](InputSectionBase *a, InputSectionBase *b) {
470     return getPriority(a->name) < getPriority(b->name);
471   };
472 
473   switch (k) {
474   case SortSectionPolicy::Default:
475   case SortSectionPolicy::None:
476     return;
477   case SortSectionPolicy::Alignment:
478     return llvm::stable_sort(vec, alignmentComparator);
479   case SortSectionPolicy::Name:
480     return llvm::stable_sort(vec, nameComparator);
481   case SortSectionPolicy::Priority:
482     return llvm::stable_sort(vec, priorityComparator);
483   case SortSectionPolicy::Reverse:
484     return std::reverse(vec.begin(), vec.end());
485   }
486 }
487 
488 // Sort sections as instructed by SORT-family commands and --sort-section
489 // option. Because SORT-family commands can be nested at most two depth
490 // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
491 // line option is respected even if a SORT command is given, the exact
492 // behavior we have here is a bit complicated. Here are the rules.
493 //
494 // 1. If two SORT commands are given, --sort-section is ignored.
495 // 2. If one SORT command is given, and if it is not SORT_NONE,
496 //    --sort-section is handled as an inner SORT command.
497 // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
498 // 4. If no SORT command is given, sort according to --sort-section.
499 static void sortInputSections(Ctx &ctx, MutableArrayRef<InputSectionBase *> vec,
500                               SortSectionPolicy outer,
501                               SortSectionPolicy inner) {
502   if (outer == SortSectionPolicy::None)
503     return;
504 
505   if (inner == SortSectionPolicy::Default)
506     sortSections(vec, ctx.arg.sortSection);
507   else
508     sortSections(vec, inner);
509   sortSections(vec, outer);
510 }
511 
512 // Compute and remember which sections the InputSectionDescription matches.
513 SmallVector<InputSectionBase *, 0>
514 LinkerScript::computeInputSections(const InputSectionDescription *cmd,
515                                    ArrayRef<InputSectionBase *> sections,
516                                    const SectionBase &outCmd) {
517   SmallVector<InputSectionBase *, 0> ret;
518   DenseSet<InputSectionBase *> spills;
519 
520   // Returns whether an input section's flags match the input section
521   // description's specifiers.
522   auto flagsMatch = [cmd](InputSectionBase *sec) {
523     return (sec->flags & cmd->withFlags) == cmd->withFlags &&
524            (sec->flags & cmd->withoutFlags) == 0;
525   };
526 
527   // Collects all sections that satisfy constraints of Cmd.
528   if (cmd->classRef.empty()) {
529     DenseSet<size_t> seen;
530     size_t sizeAfterPrevSort = 0;
531     SmallVector<size_t, 0> indexes;
532     auto sortByPositionThenCommandLine = [&](size_t begin, size_t end) {
533       llvm::sort(MutableArrayRef<size_t>(indexes).slice(begin, end - begin));
534       for (size_t i = begin; i != end; ++i)
535         ret[i] = sections[indexes[i]];
536       sortInputSections(
537           ctx,
538           MutableArrayRef<InputSectionBase *>(ret).slice(begin, end - begin),
539           ctx.arg.sortSection, SortSectionPolicy::None);
540     };
541 
542     for (const SectionPattern &pat : cmd->sectionPatterns) {
543       size_t sizeBeforeCurrPat = ret.size();
544 
545       for (size_t i = 0, e = sections.size(); i != e; ++i) {
546         // Skip if the section is dead or has been matched by a previous pattern
547         // in this input section description.
548         InputSectionBase *sec = sections[i];
549         if (!sec->isLive() || seen.contains(i))
550           continue;
551 
552         // For --emit-relocs we have to ignore entries like
553         //   .rela.dyn : { *(.rela.data) }
554         // which are common because they are in the default bfd script.
555         // We do not ignore SHT_REL[A] linker-synthesized sections here because
556         // want to support scripts that do custom layout for them.
557         if (isa<InputSection>(sec) &&
558             cast<InputSection>(sec)->getRelocatedSection())
559           continue;
560 
561         // Check the name early to improve performance in the common case.
562         if (!pat.sectionPat.match(sec->name))
563           continue;
564 
565         if (!cmd->matchesFile(*sec->file) || pat.excludesFile(*sec->file) ||
566             sec->parent == &outCmd || !flagsMatch(sec))
567           continue;
568 
569         if (sec->parent) {
570           // Skip if not allowing multiple matches.
571           if (!ctx.arg.enableNonContiguousRegions)
572             continue;
573 
574           // Disallow spilling into /DISCARD/; special handling would be needed
575           // for this in address assignment, and the semantics are nebulous.
576           if (outCmd.name == "/DISCARD/")
577             continue;
578 
579           // Class definitions cannot contain spills, nor can a class definition
580           // generate a spill in a subsequent match. Those behaviors belong to
581           // class references and additional matches.
582           if (!isa<SectionClass>(outCmd) && !isa<SectionClass>(sec->parent))
583             spills.insert(sec);
584         }
585 
586         ret.push_back(sec);
587         indexes.push_back(i);
588         seen.insert(i);
589       }
590 
591       if (pat.sortOuter == SortSectionPolicy::Default)
592         continue;
593 
594       // Matched sections are ordered by radix sort with the keys being (SORT*,
595       // --sort-section, input order), where SORT* (if present) is most
596       // significant.
597       //
598       // Matched sections between the previous SORT* and this SORT* are sorted
599       // by (--sort-alignment, input order).
600       sortByPositionThenCommandLine(sizeAfterPrevSort, sizeBeforeCurrPat);
601       // Matched sections by this SORT* pattern are sorted using all 3 keys.
602       // ret[sizeBeforeCurrPat,ret.size()) are already in the input order, so we
603       // just sort by sortOuter and sortInner.
604       sortInputSections(
605           ctx,
606           MutableArrayRef<InputSectionBase *>(ret).slice(sizeBeforeCurrPat),
607           pat.sortOuter, pat.sortInner);
608       sizeAfterPrevSort = ret.size();
609     }
610 
611     // Matched sections after the last SORT* are sorted by (--sort-alignment,
612     // input order).
613     sortByPositionThenCommandLine(sizeAfterPrevSort, ret.size());
614   } else {
615     SectionClassDesc *scd =
616         sectionClasses.lookup(CachedHashStringRef(cmd->classRef));
617     if (!scd) {
618       Err(ctx) << "undefined section class '" << cmd->classRef << "'";
619       return ret;
620     }
621     if (!scd->sc.assigned) {
622       Err(ctx) << "section class '" << cmd->classRef << "' referenced by '"
623                << outCmd.name << "' before class definition";
624       return ret;
625     }
626 
627     for (InputSectionDescription *isd : scd->sc.commands) {
628       for (InputSectionBase *sec : isd->sectionBases) {
629         if (sec->parent == &outCmd || !flagsMatch(sec))
630           continue;
631         bool isSpill = sec->parent && isa<OutputSection>(sec->parent);
632         if (!sec->parent || (isSpill && outCmd.name == "/DISCARD/")) {
633           Err(ctx) << "section '" << sec->name
634                    << "' cannot spill from/to /DISCARD/";
635           continue;
636         }
637         if (isSpill)
638           spills.insert(sec);
639         ret.push_back(sec);
640       }
641     }
642   }
643 
644   // The flag --enable-non-contiguous-regions or the section CLASS syntax may
645   // cause sections to match an InputSectionDescription in more than one
646   // OutputSection. Matches after the first were collected in the spills set, so
647   // replace these with potential spill sections.
648   if (!spills.empty()) {
649     for (InputSectionBase *&sec : ret) {
650       if (!spills.contains(sec))
651         continue;
652 
653       // Append the spill input section to the list for the input section,
654       // creating it if necessary.
655       PotentialSpillSection *pss = make<PotentialSpillSection>(
656           *sec, const_cast<InputSectionDescription &>(*cmd));
657       auto [it, inserted] =
658           potentialSpillLists.try_emplace(sec, PotentialSpillList{pss, pss});
659       if (!inserted) {
660         PotentialSpillSection *&tail = it->second.tail;
661         tail = tail->next = pss;
662       }
663       sec = pss;
664     }
665   }
666 
667   return ret;
668 }
669 
670 void LinkerScript::discard(InputSectionBase &s) {
671   if (&s == ctx.in.shStrTab.get())
672     ErrAlways(ctx) << "discarding " << s.name << " section is not allowed";
673 
674   s.markDead();
675   s.parent = nullptr;
676   for (InputSection *sec : s.dependentSections)
677     discard(*sec);
678 }
679 
680 void LinkerScript::discardSynthetic(OutputSection &outCmd) {
681   for (Partition &part : ctx.partitions) {
682     if (!part.armExidx || !part.armExidx->isLive())
683       continue;
684     SmallVector<InputSectionBase *, 0> secs(
685         part.armExidx->exidxSections.begin(),
686         part.armExidx->exidxSections.end());
687     for (SectionCommand *cmd : outCmd.commands)
688       if (auto *isd = dyn_cast<InputSectionDescription>(cmd))
689         for (InputSectionBase *s : computeInputSections(isd, secs, outCmd))
690           discard(*s);
691   }
692 }
693 
694 SmallVector<InputSectionBase *, 0>
695 LinkerScript::createInputSectionList(OutputSection &outCmd) {
696   SmallVector<InputSectionBase *, 0> ret;
697 
698   for (SectionCommand *cmd : outCmd.commands) {
699     if (auto *isd = dyn_cast<InputSectionDescription>(cmd)) {
700       isd->sectionBases = computeInputSections(isd, ctx.inputSections, outCmd);
701       for (InputSectionBase *s : isd->sectionBases)
702         s->parent = &outCmd;
703       ret.insert(ret.end(), isd->sectionBases.begin(), isd->sectionBases.end());
704     }
705   }
706   return ret;
707 }
708 
709 // Create output sections described by SECTIONS commands.
710 void LinkerScript::processSectionCommands() {
711   auto process = [this](OutputSection *osec) {
712     SmallVector<InputSectionBase *, 0> v = createInputSectionList(*osec);
713 
714     // The output section name `/DISCARD/' is special.
715     // Any input section assigned to it is discarded.
716     if (osec->name == "/DISCARD/") {
717       for (InputSectionBase *s : v)
718         discard(*s);
719       discardSynthetic(*osec);
720       osec->commands.clear();
721       return false;
722     }
723 
724     // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive
725     // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input
726     // sections satisfy a given constraint. If not, a directive is handled
727     // as if it wasn't present from the beginning.
728     //
729     // Because we'll iterate over SectionCommands many more times, the easy
730     // way to "make it as if it wasn't present" is to make it empty.
731     if (!matchConstraints(v, osec->constraint)) {
732       for (InputSectionBase *s : v)
733         s->parent = nullptr;
734       osec->commands.clear();
735       return false;
736     }
737 
738     // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign
739     // is given, input sections are aligned to that value, whether the
740     // given value is larger or smaller than the original section alignment.
741     if (osec->subalignExpr) {
742       uint32_t subalign = osec->subalignExpr().getValue();
743       for (InputSectionBase *s : v)
744         s->addralign = subalign;
745     }
746 
747     // Set the partition field the same way OutputSection::recordSection()
748     // does. Partitions cannot be used with the SECTIONS command, so this is
749     // always 1.
750     osec->partition = 1;
751     return true;
752   };
753 
754   // Process OVERWRITE_SECTIONS first so that it can overwrite the main script
755   // or orphans.
756   if (ctx.arg.enableNonContiguousRegions && !overwriteSections.empty())
757     ErrAlways(ctx) << "OVERWRITE_SECTIONS cannot be used with "
758                       "--enable-non-contiguous-regions";
759   DenseMap<CachedHashStringRef, OutputDesc *> map;
760   size_t i = 0;
761   for (OutputDesc *osd : overwriteSections) {
762     OutputSection *osec = &osd->osec;
763     if (process(osec) &&
764         !map.try_emplace(CachedHashStringRef(osec->name), osd).second)
765       Warn(ctx) << "OVERWRITE_SECTIONS specifies duplicate " << osec->name;
766   }
767   for (SectionCommand *&base : sectionCommands) {
768     if (auto *osd = dyn_cast<OutputDesc>(base)) {
769       OutputSection *osec = &osd->osec;
770       if (OutputDesc *overwrite = map.lookup(CachedHashStringRef(osec->name))) {
771         Log(ctx) << overwrite->osec.location << " overwrites " << osec->name;
772         overwrite->osec.sectionIndex = i++;
773         base = overwrite;
774       } else if (process(osec)) {
775         osec->sectionIndex = i++;
776       }
777     } else if (auto *sc = dyn_cast<SectionClassDesc>(base)) {
778       for (InputSectionDescription *isd : sc->sc.commands) {
779         isd->sectionBases =
780             computeInputSections(isd, ctx.inputSections, sc->sc);
781         for (InputSectionBase *s : isd->sectionBases) {
782           // A section class containing a section with different parent isn't
783           // necessarily an error due to --enable-non-contiguous-regions. Such
784           // sections all become potential spills when the class is referenced.
785           if (!s->parent)
786             s->parent = &sc->sc;
787         }
788       }
789       sc->sc.assigned = true;
790     }
791   }
792 
793   // Check that input sections cannot spill into or out of INSERT,
794   // since the semantics are nebulous. This is also true for OVERWRITE_SECTIONS,
795   // but no check is needed, since the order of processing ensures they cannot
796   // legally reference classes.
797   if (!potentialSpillLists.empty()) {
798     DenseSet<StringRef> insertNames;
799     for (InsertCommand &ic : insertCommands)
800       insertNames.insert(ic.names.begin(), ic.names.end());
801     for (SectionCommand *&base : sectionCommands) {
802       auto *osd = dyn_cast<OutputDesc>(base);
803       if (!osd)
804         continue;
805       OutputSection *os = &osd->osec;
806       if (!insertNames.contains(os->name))
807         continue;
808       for (SectionCommand *sc : os->commands) {
809         auto *isd = dyn_cast<InputSectionDescription>(sc);
810         if (!isd)
811           continue;
812         for (InputSectionBase *isec : isd->sectionBases)
813           if (isa<PotentialSpillSection>(isec) ||
814               potentialSpillLists.contains(isec))
815             Err(ctx) << "section '" << isec->name
816                      << "' cannot spill from/to INSERT section '" << os->name
817                      << "'";
818       }
819     }
820   }
821 
822   // If an OVERWRITE_SECTIONS specified output section is not in
823   // sectionCommands, append it to the end. The section will be inserted by
824   // orphan placement.
825   for (OutputDesc *osd : overwriteSections)
826     if (osd->osec.partition == 1 && osd->osec.sectionIndex == UINT32_MAX)
827       sectionCommands.push_back(osd);
828 
829   // Input sections cannot have a section class parent past this point; they
830   // must have been assigned to an output section.
831   for (const auto &[_, sc] : sectionClasses) {
832     for (InputSectionDescription *isd : sc->sc.commands) {
833       for (InputSectionBase *sec : isd->sectionBases) {
834         if (sec->parent && isa<SectionClass>(sec->parent)) {
835           Err(ctx) << "section class '" << sec->parent->name
836                    << "' is unreferenced";
837           goto nextClass;
838         }
839       }
840     }
841   nextClass:;
842   }
843 }
844 
845 void LinkerScript::processSymbolAssignments() {
846   // Dot outside an output section still represents a relative address, whose
847   // sh_shndx should not be SHN_UNDEF or SHN_ABS. Create a dummy aether section
848   // that fills the void outside a section. It has an index of one, which is
849   // indistinguishable from any other regular section index.
850   aether = std::make_unique<OutputSection>(ctx, "", 0, SHF_ALLOC);
851   aether->sectionIndex = 1;
852 
853   // `st` captures the local AddressState and makes it accessible deliberately.
854   // This is needed as there are some cases where we cannot just thread the
855   // current state through to a lambda function created by the script parser.
856   AddressState st(*this);
857   state = &st;
858   st.outSec = aether.get();
859 
860   for (SectionCommand *cmd : sectionCommands) {
861     if (auto *assign = dyn_cast<SymbolAssignment>(cmd))
862       addSymbol(assign);
863     else if (auto *osd = dyn_cast<OutputDesc>(cmd))
864       for (SectionCommand *subCmd : osd->osec.commands)
865         if (auto *assign = dyn_cast<SymbolAssignment>(subCmd))
866           addSymbol(assign);
867   }
868 
869   state = nullptr;
870 }
871 
872 static OutputSection *findByName(ArrayRef<SectionCommand *> vec,
873                                  StringRef name) {
874   for (SectionCommand *cmd : vec)
875     if (auto *osd = dyn_cast<OutputDesc>(cmd))
876       if (osd->osec.name == name)
877         return &osd->osec;
878   return nullptr;
879 }
880 
881 static OutputDesc *createSection(Ctx &ctx, InputSectionBase *isec,
882                                  StringRef outsecName) {
883   OutputDesc *osd = ctx.script->createOutputSection(outsecName, "<internal>");
884   osd->osec.recordSection(isec);
885   return osd;
886 }
887 
888 static OutputDesc *addInputSec(Ctx &ctx,
889                                StringMap<TinyPtrVector<OutputSection *>> &map,
890                                InputSectionBase *isec, StringRef outsecName) {
891   // Sections with SHT_GROUP or SHF_GROUP attributes reach here only when the -r
892   // option is given. A section with SHT_GROUP defines a "section group", and
893   // its members have SHF_GROUP attribute. Usually these flags have already been
894   // stripped by InputFiles.cpp as section groups are processed and uniquified.
895   // However, for the -r option, we want to pass through all section groups
896   // as-is because adding/removing members or merging them with other groups
897   // change their semantics.
898   if (isec->type == SHT_GROUP || (isec->flags & SHF_GROUP))
899     return createSection(ctx, isec, outsecName);
900 
901   // Imagine .zed : { *(.foo) *(.bar) } script. Both foo and bar may have
902   // relocation sections .rela.foo and .rela.bar for example. Most tools do
903   // not allow multiple REL[A] sections for output section. Hence we
904   // should combine these relocation sections into single output.
905   // We skip synthetic sections because it can be .rela.dyn/.rela.plt or any
906   // other REL[A] sections created by linker itself.
907   if (!isa<SyntheticSection>(isec) && isStaticRelSecType(isec->type)) {
908     auto *sec = cast<InputSection>(isec);
909     OutputSection *out = sec->getRelocatedSection()->getOutputSection();
910 
911     if (auto *relSec = out->relocationSection) {
912       relSec->recordSection(sec);
913       return nullptr;
914     }
915 
916     OutputDesc *osd = createSection(ctx, isec, outsecName);
917     out->relocationSection = &osd->osec;
918     return osd;
919   }
920 
921   //  The ELF spec just says
922   // ----------------------------------------------------------------
923   // In the first phase, input sections that match in name, type and
924   // attribute flags should be concatenated into single sections.
925   // ----------------------------------------------------------------
926   //
927   // However, it is clear that at least some flags have to be ignored for
928   // section merging. At the very least SHF_GROUP and SHF_COMPRESSED have to be
929   // ignored. We should not have two output .text sections just because one was
930   // in a group and another was not for example.
931   //
932   // It also seems that wording was a late addition and didn't get the
933   // necessary scrutiny.
934   //
935   // Merging sections with different flags is expected by some users. One
936   // reason is that if one file has
937   //
938   // int *const bar __attribute__((section(".foo"))) = (int *)0;
939   //
940   // gcc with -fPIC will produce a read only .foo section. But if another
941   // file has
942   //
943   // int zed;
944   // int *const bar __attribute__((section(".foo"))) = (int *)&zed;
945   //
946   // gcc with -fPIC will produce a read write section.
947   //
948   // Last but not least, when using linker script the merge rules are forced by
949   // the script. Unfortunately, linker scripts are name based. This means that
950   // expressions like *(.foo*) can refer to multiple input sections with
951   // different flags. We cannot put them in different output sections or we
952   // would produce wrong results for
953   //
954   // start = .; *(.foo.*) end = .; *(.bar)
955   //
956   // and a mapping of .foo1 and .bar1 to one section and .foo2 and .bar2 to
957   // another. The problem is that there is no way to layout those output
958   // sections such that the .foo sections are the only thing between the start
959   // and end symbols.
960   //
961   // Given the above issues, we instead merge sections by name and error on
962   // incompatible types and flags.
963   TinyPtrVector<OutputSection *> &v = map[outsecName];
964   for (OutputSection *sec : v) {
965     if (sec->partition != isec->partition)
966       continue;
967 
968     if (ctx.arg.relocatable && (isec->flags & SHF_LINK_ORDER)) {
969       // Merging two SHF_LINK_ORDER sections with different sh_link fields will
970       // change their semantics, so we only merge them in -r links if they will
971       // end up being linked to the same output section. The casts are fine
972       // because everything in the map was created by the orphan placement code.
973       auto *firstIsec = cast<InputSectionBase>(
974           cast<InputSectionDescription>(sec->commands[0])->sectionBases[0]);
975       OutputSection *firstIsecOut =
976           (firstIsec->flags & SHF_LINK_ORDER)
977               ? firstIsec->getLinkOrderDep()->getOutputSection()
978               : nullptr;
979       if (firstIsecOut != isec->getLinkOrderDep()->getOutputSection())
980         continue;
981     }
982 
983     sec->recordSection(isec);
984     return nullptr;
985   }
986 
987   OutputDesc *osd = createSection(ctx, isec, outsecName);
988   v.push_back(&osd->osec);
989   return osd;
990 }
991 
992 // Add sections that didn't match any sections command.
993 void LinkerScript::addOrphanSections() {
994   StringMap<TinyPtrVector<OutputSection *>> map;
995   SmallVector<OutputDesc *, 0> v;
996 
997   auto add = [&](InputSectionBase *s) {
998     if (s->isLive() && !s->parent) {
999       orphanSections.push_back(s);
1000 
1001       StringRef name = getOutputSectionName(s);
1002       if (ctx.arg.unique) {
1003         v.push_back(createSection(ctx, s, name));
1004       } else if (OutputSection *sec = findByName(sectionCommands, name)) {
1005         sec->recordSection(s);
1006       } else {
1007         if (OutputDesc *osd = addInputSec(ctx, map, s, name))
1008           v.push_back(osd);
1009         assert(isa<MergeInputSection>(s) ||
1010                s->getOutputSection()->sectionIndex == UINT32_MAX);
1011       }
1012     }
1013   };
1014 
1015   // For further --emit-reloc handling code we need target output section
1016   // to be created before we create relocation output section, so we want
1017   // to create target sections first. We do not want priority handling
1018   // for synthetic sections because them are special.
1019   size_t n = 0;
1020   for (InputSectionBase *isec : ctx.inputSections) {
1021     // Process InputSection and MergeInputSection.
1022     if (LLVM_LIKELY(isa<InputSection>(isec)))
1023       ctx.inputSections[n++] = isec;
1024 
1025     // In -r links, SHF_LINK_ORDER sections are added while adding their parent
1026     // sections because we need to know the parent's output section before we
1027     // can select an output section for the SHF_LINK_ORDER section.
1028     if (ctx.arg.relocatable && (isec->flags & SHF_LINK_ORDER))
1029       continue;
1030 
1031     if (auto *sec = dyn_cast<InputSection>(isec))
1032       if (InputSectionBase *rel = sec->getRelocatedSection())
1033         if (auto *relIS = dyn_cast_or_null<InputSectionBase>(rel->parent))
1034           add(relIS);
1035     add(isec);
1036     if (ctx.arg.relocatable)
1037       for (InputSectionBase *depSec : isec->dependentSections)
1038         if (depSec->flags & SHF_LINK_ORDER)
1039           add(depSec);
1040   }
1041   // Keep just InputSection.
1042   ctx.inputSections.resize(n);
1043 
1044   // If no SECTIONS command was given, we should insert sections commands
1045   // before others, so that we can handle scripts which refers them,
1046   // for example: "foo = ABSOLUTE(ADDR(.text)));".
1047   // When SECTIONS command is present we just add all orphans to the end.
1048   if (hasSectionsCommand)
1049     sectionCommands.insert(sectionCommands.end(), v.begin(), v.end());
1050   else
1051     sectionCommands.insert(sectionCommands.begin(), v.begin(), v.end());
1052 }
1053 
1054 void LinkerScript::diagnoseOrphanHandling() const {
1055   llvm::TimeTraceScope timeScope("Diagnose orphan sections");
1056   if (ctx.arg.orphanHandling == OrphanHandlingPolicy::Place ||
1057       !hasSectionsCommand)
1058     return;
1059   for (const InputSectionBase *sec : orphanSections) {
1060     // .relro_padding is inserted before DATA_SEGMENT_RELRO_END, if present,
1061     // automatically. The section is not supposed to be specified by scripts.
1062     if (sec == ctx.in.relroPadding.get())
1063       continue;
1064     // Input SHT_REL[A] retained by --emit-relocs are ignored by
1065     // computeInputSections(). Don't warn/error.
1066     if (isa<InputSection>(sec) &&
1067         cast<InputSection>(sec)->getRelocatedSection())
1068       continue;
1069 
1070     StringRef name = getOutputSectionName(sec);
1071     if (ctx.arg.orphanHandling == OrphanHandlingPolicy::Error)
1072       ErrAlways(ctx) << sec << " is being placed in '" << name << "'";
1073     else
1074       Warn(ctx) << sec << " is being placed in '" << name << "'";
1075   }
1076 }
1077 
1078 void LinkerScript::diagnoseMissingSGSectionAddress() const {
1079   if (!ctx.arg.cmseImplib || !ctx.in.armCmseSGSection->isNeeded())
1080     return;
1081 
1082   OutputSection *sec = findByName(sectionCommands, ".gnu.sgstubs");
1083   if (sec && !sec->addrExpr && !ctx.arg.sectionStartMap.count(".gnu.sgstubs"))
1084     ErrAlways(ctx) << "no address assigned to the veneers output section "
1085                    << sec->name;
1086 }
1087 
1088 // This function searches for a memory region to place the given output
1089 // section in. If found, a pointer to the appropriate memory region is
1090 // returned in the first member of the pair. Otherwise, a nullptr is returned.
1091 // The second member of the pair is a hint that should be passed to the
1092 // subsequent call of this method.
1093 std::pair<MemoryRegion *, MemoryRegion *>
1094 LinkerScript::findMemoryRegion(OutputSection *sec, MemoryRegion *hint) {
1095   // Non-allocatable sections are not part of the process image.
1096   if (!(sec->flags & SHF_ALLOC)) {
1097     bool hasInputOrByteCommand =
1098         sec->hasInputSections ||
1099         llvm::any_of(sec->commands, [](SectionCommand *comm) {
1100           return ByteCommand::classof(comm);
1101         });
1102     if (!sec->memoryRegionName.empty() && hasInputOrByteCommand)
1103       Warn(ctx)
1104           << "ignoring memory region assignment for non-allocatable section '"
1105           << sec->name << "'";
1106     return {nullptr, nullptr};
1107   }
1108 
1109   // If a memory region name was specified in the output section command,
1110   // then try to find that region first.
1111   if (!sec->memoryRegionName.empty()) {
1112     if (MemoryRegion *m = memoryRegions.lookup(sec->memoryRegionName))
1113       return {m, m};
1114     ErrAlways(ctx) << "memory region '" << sec->memoryRegionName
1115                    << "' not declared";
1116     return {nullptr, nullptr};
1117   }
1118 
1119   // If at least one memory region is defined, all sections must
1120   // belong to some memory region. Otherwise, we don't need to do
1121   // anything for memory regions.
1122   if (memoryRegions.empty())
1123     return {nullptr, nullptr};
1124 
1125   // An orphan section should continue the previous memory region.
1126   if (sec->sectionIndex == UINT32_MAX && hint)
1127     return {hint, hint};
1128 
1129   // See if a region can be found by matching section flags.
1130   for (auto &pair : memoryRegions) {
1131     MemoryRegion *m = pair.second;
1132     if (m->compatibleWith(sec->flags))
1133       return {m, nullptr};
1134   }
1135 
1136   // Otherwise, no suitable region was found.
1137   ErrAlways(ctx) << "no memory region specified for section '" << sec->name
1138                  << "'";
1139   return {nullptr, nullptr};
1140 }
1141 
1142 static OutputSection *findFirstSection(Ctx &ctx, PhdrEntry *load) {
1143   for (OutputSection *sec : ctx.outputSections)
1144     if (sec->ptLoad == load)
1145       return sec;
1146   return nullptr;
1147 }
1148 
1149 // Assign addresses to an output section and offsets to its input sections and
1150 // symbol assignments. Return true if the output section's address has changed.
1151 bool LinkerScript::assignOffsets(OutputSection *sec) {
1152   const bool isTbss = (sec->flags & SHF_TLS) && sec->type == SHT_NOBITS;
1153   const bool sameMemRegion = state->memRegion == sec->memRegion;
1154   const bool prevLMARegionIsDefault = state->lmaRegion == nullptr;
1155   const uint64_t savedDot = dot;
1156   bool addressChanged = false;
1157   state->memRegion = sec->memRegion;
1158   state->lmaRegion = sec->lmaRegion;
1159 
1160   if (!(sec->flags & SHF_ALLOC)) {
1161     // Non-SHF_ALLOC sections have zero addresses.
1162     dot = 0;
1163   } else if (isTbss) {
1164     // Allow consecutive SHF_TLS SHT_NOBITS output sections. The address range
1165     // starts from the end address of the previous tbss section.
1166     if (state->tbssAddr == 0)
1167       state->tbssAddr = dot;
1168     else
1169       dot = state->tbssAddr;
1170   } else {
1171     if (state->memRegion)
1172       dot = state->memRegion->curPos;
1173     if (sec->addrExpr)
1174       setDot(sec->addrExpr, sec->location, false);
1175 
1176     // If the address of the section has been moved forward by an explicit
1177     // expression so that it now starts past the current curPos of the enclosing
1178     // region, we need to expand the current region to account for the space
1179     // between the previous section, if any, and the start of this section.
1180     if (state->memRegion && state->memRegion->curPos < dot)
1181       expandMemoryRegion(state->memRegion, dot - state->memRegion->curPos,
1182                          sec->name);
1183   }
1184 
1185   state->outSec = sec;
1186   if (!(sec->addrExpr && hasSectionsCommand)) {
1187     // ALIGN is respected. sec->alignment is the max of ALIGN and the maximum of
1188     // input section alignments.
1189     const uint64_t pos = dot;
1190     dot = alignToPowerOf2(dot, sec->addralign);
1191     expandMemoryRegions(dot - pos);
1192   }
1193   addressChanged = sec->addr != dot;
1194   sec->addr = dot;
1195 
1196   // state->lmaOffset is LMA minus VMA. If LMA is explicitly specified via AT()
1197   // or AT>, recompute state->lmaOffset; otherwise, if both previous/current LMA
1198   // region is the default, and the two sections are in the same memory region,
1199   // reuse previous lmaOffset; otherwise, reset lmaOffset to 0. This emulates
1200   // heuristics described in
1201   // https://sourceware.org/binutils/docs/ld/Output-Section-LMA.html
1202   if (sec->lmaExpr) {
1203     state->lmaOffset = sec->lmaExpr().getValue() - dot;
1204   } else if (MemoryRegion *mr = sec->lmaRegion) {
1205     uint64_t lmaStart = alignToPowerOf2(mr->curPos, sec->addralign);
1206     if (mr->curPos < lmaStart)
1207       expandMemoryRegion(mr, lmaStart - mr->curPos, sec->name);
1208     state->lmaOffset = lmaStart - dot;
1209   } else if (!sameMemRegion || !prevLMARegionIsDefault) {
1210     state->lmaOffset = 0;
1211   }
1212 
1213   // Propagate state->lmaOffset to the first "non-header" section.
1214   if (PhdrEntry *l = sec->ptLoad)
1215     if (sec == findFirstSection(ctx, l))
1216       l->lmaOffset = state->lmaOffset;
1217 
1218   // We can call this method multiple times during the creation of
1219   // thunks and want to start over calculation each time.
1220   sec->size = 0;
1221 
1222   // We visited SectionsCommands from processSectionCommands to
1223   // layout sections. Now, we visit SectionsCommands again to fix
1224   // section offsets.
1225   for (SectionCommand *cmd : sec->commands) {
1226     // This handles the assignments to symbol or to the dot.
1227     if (auto *assign = dyn_cast<SymbolAssignment>(cmd)) {
1228       assign->addr = dot;
1229       assignSymbol(assign, true);
1230       assign->size = dot - assign->addr;
1231       continue;
1232     }
1233 
1234     // Handle BYTE(), SHORT(), LONG(), or QUAD().
1235     if (auto *data = dyn_cast<ByteCommand>(cmd)) {
1236       data->offset = dot - sec->addr;
1237       dot += data->size;
1238       expandOutputSection(data->size);
1239       continue;
1240     }
1241 
1242     // Handle a single input section description command.
1243     // It calculates and assigns the offsets for each section and also
1244     // updates the output section size.
1245 
1246     auto &sections = cast<InputSectionDescription>(cmd)->sections;
1247     for (InputSection *isec : sections) {
1248       assert(isec->getParent() == sec);
1249       if (isa<PotentialSpillSection>(isec))
1250         continue;
1251       const uint64_t pos = dot;
1252       dot = alignToPowerOf2(dot, isec->addralign);
1253       isec->outSecOff = dot - sec->addr;
1254       dot += isec->getSize();
1255 
1256       // Update output section size after adding each section. This is so that
1257       // SIZEOF works correctly in the case below:
1258       // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
1259       expandOutputSection(dot - pos);
1260     }
1261   }
1262 
1263   // If .relro_padding is present, round up the end to a common-page-size
1264   // boundary to protect the last page.
1265   if (ctx.in.relroPadding && sec == ctx.in.relroPadding->getParent())
1266     expandOutputSection(alignToPowerOf2(dot, ctx.arg.commonPageSize) - dot);
1267 
1268   // Non-SHF_ALLOC sections do not affect the addresses of other OutputSections
1269   // as they are not part of the process image.
1270   if (!(sec->flags & SHF_ALLOC)) {
1271     dot = savedDot;
1272   } else if (isTbss) {
1273     // NOBITS TLS sections are similar. Additionally save the end address.
1274     state->tbssAddr = dot;
1275     dot = savedDot;
1276   }
1277   return addressChanged;
1278 }
1279 
1280 static bool isDiscardable(const OutputSection &sec) {
1281   if (sec.name == "/DISCARD/")
1282     return true;
1283 
1284   // We do not want to remove OutputSections with expressions that reference
1285   // symbols even if the OutputSection is empty. We want to ensure that the
1286   // expressions can be evaluated and report an error if they cannot.
1287   if (sec.expressionsUseSymbols)
1288     return false;
1289 
1290   // OutputSections may be referenced by name in ADDR and LOADADDR expressions,
1291   // as an empty Section can has a valid VMA and LMA we keep the OutputSection
1292   // to maintain the integrity of the other Expression.
1293   if (sec.usedInExpression)
1294     return false;
1295 
1296   for (SectionCommand *cmd : sec.commands) {
1297     if (auto assign = dyn_cast<SymbolAssignment>(cmd))
1298       // Don't create empty output sections just for unreferenced PROVIDE
1299       // symbols.
1300       if (assign->name != "." && !assign->sym)
1301         continue;
1302 
1303     if (!isa<InputSectionDescription>(*cmd))
1304       return false;
1305   }
1306   return true;
1307 }
1308 
1309 static void maybePropagatePhdrs(OutputSection &sec,
1310                                 SmallVector<StringRef, 0> &phdrs) {
1311   if (sec.phdrs.empty()) {
1312     // To match the bfd linker script behaviour, only propagate program
1313     // headers to sections that are allocated.
1314     if (sec.flags & SHF_ALLOC)
1315       sec.phdrs = phdrs;
1316   } else {
1317     phdrs = sec.phdrs;
1318   }
1319 }
1320 
1321 void LinkerScript::adjustOutputSections() {
1322   // If the output section contains only symbol assignments, create a
1323   // corresponding output section. The issue is what to do with linker script
1324   // like ".foo : { symbol = 42; }". One option would be to convert it to
1325   // "symbol = 42;". That is, move the symbol out of the empty section
1326   // description. That seems to be what bfd does for this simple case. The
1327   // problem is that this is not completely general. bfd will give up and
1328   // create a dummy section too if there is a ". = . + 1" inside the section
1329   // for example.
1330   // Given that we want to create the section, we have to worry what impact
1331   // it will have on the link. For example, if we just create a section with
1332   // 0 for flags, it would change which PT_LOADs are created.
1333   // We could remember that particular section is dummy and ignore it in
1334   // other parts of the linker, but unfortunately there are quite a few places
1335   // that would need to change:
1336   //   * The program header creation.
1337   //   * The orphan section placement.
1338   //   * The address assignment.
1339   // The other option is to pick flags that minimize the impact the section
1340   // will have on the rest of the linker. That is why we copy the flags from
1341   // the previous sections. We copy just SHF_ALLOC and SHF_WRITE to keep the
1342   // impact low. We do not propagate SHF_EXECINSTR as in some cases this can
1343   // lead to executable writeable section.
1344   uint64_t flags = SHF_ALLOC;
1345 
1346   SmallVector<StringRef, 0> defPhdrs;
1347   bool seenRelro = false;
1348   for (SectionCommand *&cmd : sectionCommands) {
1349     if (!isa<OutputDesc>(cmd))
1350       continue;
1351     auto *sec = &cast<OutputDesc>(cmd)->osec;
1352 
1353     // Handle align (e.g. ".foo : ALIGN(16) { ... }").
1354     if (sec->alignExpr)
1355       sec->addralign =
1356           std::max<uint32_t>(sec->addralign, sec->alignExpr().getValue());
1357 
1358     bool isEmpty = (getFirstInputSection(sec) == nullptr);
1359     bool discardable = isEmpty && isDiscardable(*sec);
1360     // If sec has at least one input section and not discarded, remember its
1361     // flags to be inherited by subsequent output sections. (sec may contain
1362     // just one empty synthetic section.)
1363     if (sec->hasInputSections && !discardable)
1364       flags = sec->flags;
1365 
1366     // We do not want to keep any special flags for output section
1367     // in case it is empty.
1368     if (isEmpty) {
1369       sec->flags =
1370           flags & ((sec->nonAlloc ? 0 : (uint64_t)SHF_ALLOC) | SHF_WRITE);
1371       sec->sortRank = getSectionRank(ctx, *sec);
1372     }
1373 
1374     // The code below may remove empty output sections. We should save the
1375     // specified program headers (if exist) and propagate them to subsequent
1376     // sections which do not specify program headers.
1377     // An example of such a linker script is:
1378     // SECTIONS { .empty : { *(.empty) } :rw
1379     //            .foo : { *(.foo) } }
1380     // Note: at this point the order of output sections has not been finalized,
1381     // because orphans have not been inserted into their expected positions. We
1382     // will handle them in adjustSectionsAfterSorting().
1383     if (sec->sectionIndex != UINT32_MAX)
1384       maybePropagatePhdrs(*sec, defPhdrs);
1385 
1386     // Discard .relro_padding if we have not seen one RELRO section. Note: when
1387     // .tbss is the only RELRO section, there is no associated PT_LOAD segment
1388     // (needsPtLoad), so we don't append .relro_padding in the case.
1389     if (ctx.in.relroPadding && ctx.in.relroPadding->getParent() == sec &&
1390         !seenRelro)
1391       discardable = true;
1392     if (discardable) {
1393       sec->markDead();
1394       cmd = nullptr;
1395     } else {
1396       seenRelro |=
1397           sec->relro && !(sec->type == SHT_NOBITS && (sec->flags & SHF_TLS));
1398     }
1399   }
1400 
1401   // It is common practice to use very generic linker scripts. So for any
1402   // given run some of the output sections in the script will be empty.
1403   // We could create corresponding empty output sections, but that would
1404   // clutter the output.
1405   // We instead remove trivially empty sections. The bfd linker seems even
1406   // more aggressive at removing them.
1407   llvm::erase_if(sectionCommands, [&](SectionCommand *cmd) { return !cmd; });
1408 }
1409 
1410 void LinkerScript::adjustSectionsAfterSorting() {
1411   // Try and find an appropriate memory region to assign offsets in.
1412   MemoryRegion *hint = nullptr;
1413   for (SectionCommand *cmd : sectionCommands) {
1414     if (auto *osd = dyn_cast<OutputDesc>(cmd)) {
1415       OutputSection *sec = &osd->osec;
1416       if (!sec->lmaRegionName.empty()) {
1417         if (MemoryRegion *m = memoryRegions.lookup(sec->lmaRegionName))
1418           sec->lmaRegion = m;
1419         else
1420           ErrAlways(ctx) << "memory region '" << sec->lmaRegionName
1421                          << "' not declared";
1422       }
1423       std::tie(sec->memRegion, hint) = findMemoryRegion(sec, hint);
1424     }
1425   }
1426 
1427   // If output section command doesn't specify any segments,
1428   // and we haven't previously assigned any section to segment,
1429   // then we simply assign section to the very first load segment.
1430   // Below is an example of such linker script:
1431   // PHDRS { seg PT_LOAD; }
1432   // SECTIONS { .aaa : { *(.aaa) } }
1433   SmallVector<StringRef, 0> defPhdrs;
1434   auto firstPtLoad = llvm::find_if(phdrsCommands, [](const PhdrsCommand &cmd) {
1435     return cmd.type == PT_LOAD;
1436   });
1437   if (firstPtLoad != phdrsCommands.end())
1438     defPhdrs.push_back(firstPtLoad->name);
1439 
1440   // Walk the commands and propagate the program headers to commands that don't
1441   // explicitly specify them.
1442   for (SectionCommand *cmd : sectionCommands)
1443     if (auto *osd = dyn_cast<OutputDesc>(cmd))
1444       maybePropagatePhdrs(osd->osec, defPhdrs);
1445 }
1446 
1447 // When the SECTIONS command is used, try to find an address for the file and
1448 // program headers output sections, which can be added to the first PT_LOAD
1449 // segment when program headers are created.
1450 //
1451 // We check if the headers fit below the first allocated section. If there isn't
1452 // enough space for these sections, we'll remove them from the PT_LOAD segment,
1453 // and we'll also remove the PT_PHDR segment.
1454 void LinkerScript::allocateHeaders(
1455     SmallVector<std::unique_ptr<PhdrEntry>, 0> &phdrs) {
1456   uint64_t min = std::numeric_limits<uint64_t>::max();
1457   for (OutputSection *sec : ctx.outputSections)
1458     if (sec->flags & SHF_ALLOC)
1459       min = std::min<uint64_t>(min, sec->addr);
1460 
1461   auto it = llvm::find_if(phdrs, [](auto &e) { return e->p_type == PT_LOAD; });
1462   if (it == phdrs.end())
1463     return;
1464   PhdrEntry *firstPTLoad = it->get();
1465 
1466   bool hasExplicitHeaders =
1467       llvm::any_of(phdrsCommands, [](const PhdrsCommand &cmd) {
1468         return cmd.hasPhdrs || cmd.hasFilehdr;
1469       });
1470   bool paged = !ctx.arg.omagic && !ctx.arg.nmagic;
1471   uint64_t headerSize = getHeaderSize(ctx);
1472 
1473   uint64_t base = 0;
1474   // If SECTIONS is present and the linkerscript is not explicit about program
1475   // headers, only allocate program headers if that would not add a page.
1476   if (hasSectionsCommand && !hasExplicitHeaders)
1477     base = alignDown(min, ctx.arg.maxPageSize);
1478   if ((paged || hasExplicitHeaders) && headerSize <= min - base) {
1479     min = alignDown(min - headerSize, ctx.arg.maxPageSize);
1480     ctx.out.elfHeader->addr = min;
1481     ctx.out.programHeaders->addr = min + ctx.out.elfHeader->size;
1482     return;
1483   }
1484 
1485   // Error if we were explicitly asked to allocate headers.
1486   if (hasExplicitHeaders)
1487     ErrAlways(ctx) << "could not allocate headers";
1488 
1489   ctx.out.elfHeader->ptLoad = nullptr;
1490   ctx.out.programHeaders->ptLoad = nullptr;
1491   firstPTLoad->firstSec = findFirstSection(ctx, firstPTLoad);
1492 
1493   llvm::erase_if(phdrs, [](auto &e) { return e->p_type == PT_PHDR; });
1494 }
1495 
1496 LinkerScript::AddressState::AddressState(const LinkerScript &script) {
1497   for (auto &mri : script.memoryRegions) {
1498     MemoryRegion *mr = mri.second;
1499     mr->curPos = (mr->origin)().getValue();
1500   }
1501 }
1502 
1503 // Here we assign addresses as instructed by linker script SECTIONS
1504 // sub-commands. Doing that allows us to use final VA values, so here
1505 // we also handle rest commands like symbol assignments and ASSERTs.
1506 // Return an output section that has changed its address or null, and a symbol
1507 // that has changed its section or value (or nullptr if no symbol has changed).
1508 std::pair<const OutputSection *, const Defined *>
1509 LinkerScript::assignAddresses() {
1510   if (hasSectionsCommand) {
1511     // With a linker script, assignment of addresses to headers is covered by
1512     // allocateHeaders().
1513     dot = ctx.arg.imageBase.value_or(0);
1514   } else {
1515     // Assign addresses to headers right now.
1516     dot = ctx.target->getImageBase();
1517     ctx.out.elfHeader->addr = dot;
1518     ctx.out.programHeaders->addr = dot + ctx.out.elfHeader->size;
1519     dot += getHeaderSize(ctx);
1520   }
1521 
1522   OutputSection *changedOsec = nullptr;
1523   AddressState st(*this);
1524   state = &st;
1525   errorOnMissingSection = true;
1526   st.outSec = aether.get();
1527   recordedErrors.clear();
1528 
1529   SymbolAssignmentMap oldValues = getSymbolAssignmentValues(sectionCommands);
1530   for (SectionCommand *cmd : sectionCommands) {
1531     if (auto *assign = dyn_cast<SymbolAssignment>(cmd)) {
1532       assign->addr = dot;
1533       assignSymbol(assign, false);
1534       assign->size = dot - assign->addr;
1535       continue;
1536     }
1537     if (isa<SectionClassDesc>(cmd))
1538       continue;
1539     if (assignOffsets(&cast<OutputDesc>(cmd)->osec) && !changedOsec)
1540       changedOsec = &cast<OutputDesc>(cmd)->osec;
1541   }
1542 
1543   state = nullptr;
1544   return {changedOsec, getChangedSymbolAssignment(oldValues)};
1545 }
1546 
1547 static bool hasRegionOverflowed(MemoryRegion *mr) {
1548   if (!mr)
1549     return false;
1550   return mr->curPos - mr->getOrigin() > mr->getLength();
1551 }
1552 
1553 // Spill input sections in reverse order of address assignment to (potentially)
1554 // bring memory regions out of overflow. The size savings of a spill can only be
1555 // estimated, since general linker script arithmetic may occur afterwards.
1556 // Under-estimates may cause unnecessary spills, but over-estimates can always
1557 // be corrected on the next pass.
1558 bool LinkerScript::spillSections() {
1559   if (potentialSpillLists.empty())
1560     return false;
1561 
1562   bool spilled = false;
1563   for (SectionCommand *cmd : reverse(sectionCommands)) {
1564     auto *osd = dyn_cast<OutputDesc>(cmd);
1565     if (!osd)
1566       continue;
1567     OutputSection *osec = &osd->osec;
1568     if (!osec->memRegion)
1569       continue;
1570 
1571     // Input sections that have replaced a potential spill and should be removed
1572     // from their input section description.
1573     DenseSet<InputSection *> spilledInputSections;
1574 
1575     for (SectionCommand *cmd : reverse(osec->commands)) {
1576       if (!hasRegionOverflowed(osec->memRegion) &&
1577           !hasRegionOverflowed(osec->lmaRegion))
1578         break;
1579 
1580       auto *isd = dyn_cast<InputSectionDescription>(cmd);
1581       if (!isd)
1582         continue;
1583       for (InputSection *isec : reverse(isd->sections)) {
1584         // Potential spill locations cannot be spilled.
1585         if (isa<PotentialSpillSection>(isec))
1586           continue;
1587 
1588         // Find the next potential spill location and remove it from the list.
1589         auto it = potentialSpillLists.find(isec);
1590         if (it == potentialSpillLists.end())
1591           continue;
1592         PotentialSpillList &list = it->second;
1593         PotentialSpillSection *spill = list.head;
1594         if (spill->next)
1595           list.head = spill->next;
1596         else
1597           potentialSpillLists.erase(isec);
1598 
1599         // Replace the next spill location with the spilled section and adjust
1600         // its properties to match the new location. Note that the alignment of
1601         // the spill section may have diverged from the original due to e.g. a
1602         // SUBALIGN. Correct assignment requires the spill's alignment to be
1603         // used, not the original.
1604         spilledInputSections.insert(isec);
1605         *llvm::find(spill->isd->sections, spill) = isec;
1606         isec->parent = spill->parent;
1607         isec->addralign = spill->addralign;
1608 
1609         // Record the (potential) reduction in the region's end position.
1610         osec->memRegion->curPos -= isec->getSize();
1611         if (osec->lmaRegion)
1612           osec->lmaRegion->curPos -= isec->getSize();
1613 
1614         // Spilling continues until the end position no longer overflows the
1615         // region. Then, another round of address assignment will either confirm
1616         // the spill's success or lead to yet more spilling.
1617         if (!hasRegionOverflowed(osec->memRegion) &&
1618             !hasRegionOverflowed(osec->lmaRegion))
1619           break;
1620       }
1621 
1622       // Remove any spilled input sections to complete their move.
1623       if (!spilledInputSections.empty()) {
1624         spilled = true;
1625         llvm::erase_if(isd->sections, [&](InputSection *isec) {
1626           return spilledInputSections.contains(isec);
1627         });
1628       }
1629     }
1630   }
1631 
1632   return spilled;
1633 }
1634 
1635 // Erase any potential spill sections that were not used.
1636 void LinkerScript::erasePotentialSpillSections() {
1637   if (potentialSpillLists.empty())
1638     return;
1639 
1640   // Collect the set of input section descriptions that contain potential
1641   // spills.
1642   DenseSet<InputSectionDescription *> isds;
1643   for (const auto &[_, list] : potentialSpillLists)
1644     for (PotentialSpillSection *s = list.head; s; s = s->next)
1645       isds.insert(s->isd);
1646 
1647   for (InputSectionDescription *isd : isds)
1648     llvm::erase_if(isd->sections, [](InputSection *s) {
1649       return isa<PotentialSpillSection>(s);
1650     });
1651 
1652   potentialSpillLists.clear();
1653 }
1654 
1655 // Creates program headers as instructed by PHDRS linker script command.
1656 SmallVector<std::unique_ptr<PhdrEntry>, 0> LinkerScript::createPhdrs() {
1657   SmallVector<std::unique_ptr<PhdrEntry>, 0> ret;
1658 
1659   // Process PHDRS and FILEHDR keywords because they are not
1660   // real output sections and cannot be added in the following loop.
1661   for (const PhdrsCommand &cmd : phdrsCommands) {
1662     auto phdr =
1663         std::make_unique<PhdrEntry>(ctx, cmd.type, cmd.flags.value_or(PF_R));
1664 
1665     if (cmd.hasFilehdr)
1666       phdr->add(ctx.out.elfHeader.get());
1667     if (cmd.hasPhdrs)
1668       phdr->add(ctx.out.programHeaders.get());
1669 
1670     if (cmd.lmaExpr) {
1671       phdr->p_paddr = cmd.lmaExpr().getValue();
1672       phdr->hasLMA = true;
1673     }
1674     ret.push_back(std::move(phdr));
1675   }
1676 
1677   // Add output sections to program headers.
1678   for (OutputSection *sec : ctx.outputSections) {
1679     // Assign headers specified by linker script
1680     for (size_t id : getPhdrIndices(sec)) {
1681       ret[id]->add(sec);
1682       if (!phdrsCommands[id].flags)
1683         ret[id]->p_flags |= sec->getPhdrFlags();
1684     }
1685   }
1686   return ret;
1687 }
1688 
1689 // Returns true if we should emit an .interp section.
1690 //
1691 // We usually do. But if PHDRS commands are given, and
1692 // no PT_INTERP is there, there's no place to emit an
1693 // .interp, so we don't do that in that case.
1694 bool LinkerScript::needsInterpSection() {
1695   if (phdrsCommands.empty())
1696     return true;
1697   for (PhdrsCommand &cmd : phdrsCommands)
1698     if (cmd.type == PT_INTERP)
1699       return true;
1700   return false;
1701 }
1702 
1703 ExprValue LinkerScript::getSymbolValue(StringRef name, const Twine &loc) {
1704   if (name == ".") {
1705     if (state)
1706       return {state->outSec, false, dot - state->outSec->addr, loc};
1707     ErrAlways(ctx) << loc << ": unable to get location counter value";
1708     return 0;
1709   }
1710 
1711   if (Symbol *sym = ctx.symtab->find(name)) {
1712     if (auto *ds = dyn_cast<Defined>(sym)) {
1713       ExprValue v{ds->section, false, ds->value, loc};
1714       // Retain the original st_type, so that the alias will get the same
1715       // behavior in relocation processing. Any operation will reset st_type to
1716       // STT_NOTYPE.
1717       v.type = ds->type;
1718       return v;
1719     }
1720     if (isa<SharedSymbol>(sym))
1721       if (!errorOnMissingSection)
1722         return {nullptr, false, 0, loc};
1723   }
1724 
1725   ErrAlways(ctx) << loc << ": symbol not found: " << name;
1726   return 0;
1727 }
1728 
1729 // Returns the index of the segment named Name.
1730 static std::optional<size_t> getPhdrIndex(ArrayRef<PhdrsCommand> vec,
1731                                           StringRef name) {
1732   for (size_t i = 0; i < vec.size(); ++i)
1733     if (vec[i].name == name)
1734       return i;
1735   return std::nullopt;
1736 }
1737 
1738 // Returns indices of ELF headers containing specific section. Each index is a
1739 // zero based number of ELF header listed within PHDRS {} script block.
1740 SmallVector<size_t, 0> LinkerScript::getPhdrIndices(OutputSection *cmd) {
1741   SmallVector<size_t, 0> ret;
1742 
1743   for (StringRef s : cmd->phdrs) {
1744     if (std::optional<size_t> idx = getPhdrIndex(phdrsCommands, s))
1745       ret.push_back(*idx);
1746     else if (s != "NONE")
1747       ErrAlways(ctx) << cmd->location << ": program header '" << s
1748                      << "' is not listed in PHDRS";
1749   }
1750   return ret;
1751 }
1752 
1753 void LinkerScript::printMemoryUsage(raw_ostream& os) {
1754   auto printSize = [&](uint64_t size) {
1755     if ((size & 0x3fffffff) == 0)
1756       os << format_decimal(size >> 30, 10) << " GB";
1757     else if ((size & 0xfffff) == 0)
1758       os << format_decimal(size >> 20, 10) << " MB";
1759     else if ((size & 0x3ff) == 0)
1760       os << format_decimal(size >> 10, 10) << " KB";
1761     else
1762       os << " " << format_decimal(size, 10) << " B";
1763   };
1764   os << "Memory region         Used Size  Region Size  %age Used\n";
1765   for (auto &pair : memoryRegions) {
1766     MemoryRegion *m = pair.second;
1767     uint64_t usedLength = m->curPos - m->getOrigin();
1768     os << right_justify(m->name, 16) << ": ";
1769     printSize(usedLength);
1770     uint64_t length = m->getLength();
1771     if (length != 0) {
1772       printSize(length);
1773       double percent = usedLength * 100.0 / length;
1774       os << "    " << format("%6.2f%%", percent);
1775     }
1776     os << '\n';
1777   }
1778 }
1779 
1780 void LinkerScript::recordError(const Twine &msg) {
1781   auto &str = recordedErrors.emplace_back();
1782   msg.toVector(str);
1783 }
1784 
1785 static void checkMemoryRegion(Ctx &ctx, const MemoryRegion *region,
1786                               const OutputSection *osec, uint64_t addr) {
1787   uint64_t osecEnd = addr + osec->size;
1788   uint64_t regionEnd = region->getOrigin() + region->getLength();
1789   if (osecEnd > regionEnd) {
1790     ErrAlways(ctx) << "section '" << osec->name << "' will not fit in region '"
1791                    << region->name << "': overflowed by "
1792                    << (osecEnd - regionEnd) << " bytes";
1793   }
1794 }
1795 
1796 void LinkerScript::checkFinalScriptConditions() const {
1797   for (StringRef err : recordedErrors)
1798     Err(ctx) << err;
1799   for (const OutputSection *sec : ctx.outputSections) {
1800     if (const MemoryRegion *memoryRegion = sec->memRegion)
1801       checkMemoryRegion(ctx, memoryRegion, sec, sec->addr);
1802     if (const MemoryRegion *lmaRegion = sec->lmaRegion)
1803       checkMemoryRegion(ctx, lmaRegion, sec, sec->getLMA());
1804   }
1805 }
1806 
1807 void LinkerScript::addScriptReferencedSymbolsToSymTable() {
1808   // Some symbols (such as __ehdr_start) are defined lazily only when there
1809   // are undefined symbols for them, so we add these to trigger that logic.
1810   auto reference = [&ctx = ctx](StringRef name) {
1811     Symbol *sym = ctx.symtab->addUnusedUndefined(name);
1812     sym->isUsedInRegularObj = true;
1813     sym->referenced = true;
1814   };
1815   for (StringRef name : referencedSymbols)
1816     reference(name);
1817 
1818   // Keeps track of references from which PROVIDE symbols have been added to the
1819   // symbol table.
1820   DenseSet<StringRef> added;
1821   SmallVector<const SmallVector<StringRef, 0> *, 0> symRefsVec;
1822   for (const auto &[name, symRefs] : provideMap)
1823     if (shouldAddProvideSym(name) && added.insert(name).second)
1824       symRefsVec.push_back(&symRefs);
1825   while (symRefsVec.size()) {
1826     for (StringRef name : *symRefsVec.pop_back_val()) {
1827       reference(name);
1828       // Prevent the symbol from being discarded by --gc-sections.
1829       referencedSymbols.push_back(name);
1830       auto it = provideMap.find(name);
1831       if (it != provideMap.end() && shouldAddProvideSym(name) &&
1832           added.insert(name).second) {
1833         symRefsVec.push_back(&it->second);
1834       }
1835     }
1836   }
1837 }
1838 
1839 bool LinkerScript::shouldAddProvideSym(StringRef symName) {
1840   // This function is called before and after garbage collection. To prevent
1841   // undefined references from the RHS, the result of this function for a
1842   // symbol must be the same for each call. We use unusedProvideSyms to not
1843   // change the return value of a demoted symbol.
1844   Symbol *sym = ctx.symtab->find(symName);
1845   if (!sym)
1846     return false;
1847   if (sym->isDefined() || sym->isCommon()) {
1848     unusedProvideSyms.insert(sym);
1849     return false;
1850   }
1851   return !unusedProvideSyms.count(sym);
1852 }
1853