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