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