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 && script->hasSectionsCommand) {
781     // The alignment is ignored.
782     ctx->outSec->addr = pos;
783   } else {
784     // ctx->outSec->alignment is the max of ALIGN and the maximum of input
785     // section alignments.
786     ctx->outSec->addr = advance(0, ctx->outSec->alignment);
787     expandMemoryRegions(ctx->outSec->addr - pos);
788   }
789 }
790 
791 // This function searches for a memory region to place the given output
792 // section in. If found, a pointer to the appropriate memory region is
793 // returned. Otherwise, a nullptr is returned.
794 MemoryRegion *LinkerScript::findMemoryRegion(OutputSection *sec) {
795   // If a memory region name was specified in the output section command,
796   // then try to find that region first.
797   if (!sec->memoryRegionName.empty()) {
798     if (MemoryRegion *m = memoryRegions.lookup(sec->memoryRegionName))
799       return m;
800     error("memory region '" + sec->memoryRegionName + "' not declared");
801     return nullptr;
802   }
803 
804   // If at least one memory region is defined, all sections must
805   // belong to some memory region. Otherwise, we don't need to do
806   // anything for memory regions.
807   if (memoryRegions.empty())
808     return nullptr;
809 
810   // See if a region can be found by matching section flags.
811   for (auto &pair : memoryRegions) {
812     MemoryRegion *m = pair.second;
813     if ((m->flags & sec->flags) && (m->negFlags & sec->flags) == 0)
814       return m;
815   }
816 
817   // Otherwise, no suitable region was found.
818   if (sec->flags & SHF_ALLOC)
819     error("no memory region specified for section '" + sec->name + "'");
820   return nullptr;
821 }
822 
823 static OutputSection *findFirstSection(PhdrEntry *load) {
824   for (OutputSection *sec : outputSections)
825     if (sec->ptLoad == load)
826       return sec;
827   return nullptr;
828 }
829 
830 // This function assigns offsets to input sections and an output section
831 // for a single sections command (e.g. ".text { *(.text); }").
832 void LinkerScript::assignOffsets(OutputSection *sec) {
833   if (!(sec->flags & SHF_ALLOC))
834     dot = 0;
835 
836   ctx->memRegion = sec->memRegion;
837   ctx->lmaRegion = sec->lmaRegion;
838   if (ctx->memRegion)
839     dot = ctx->memRegion->curPos;
840 
841   if ((sec->flags & SHF_ALLOC) && sec->addrExpr)
842     setDot(sec->addrExpr, sec->location, false);
843 
844   // If the address of the section has been moved forward by an explicit
845   // expression so that it now starts past the current curPos of the enclosing
846   // region, we need to expand the current region to account for the space
847   // between the previous section, if any, and the start of this section.
848   if (ctx->memRegion && ctx->memRegion->curPos < dot)
849     expandMemoryRegion(ctx->memRegion, dot - ctx->memRegion->curPos,
850                        ctx->memRegion->name, sec->name);
851 
852   switchTo(sec);
853 
854   ctx->lmaOffset = 0;
855 
856   if (sec->lmaExpr)
857     ctx->lmaOffset = sec->lmaExpr().getValue() - dot;
858   if (MemoryRegion *mr = sec->lmaRegion)
859     ctx->lmaOffset = alignTo(mr->curPos, sec->alignment) - dot;
860 
861   // If neither AT nor AT> is specified for an allocatable section, the linker
862   // will set the LMA such that the difference between VMA and LMA for the
863   // section is the same as the preceding output section in the same region
864   // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
865   // This, however, should only be done by the first "non-header" section
866   // in the segment.
867   if (PhdrEntry *l = ctx->outSec->ptLoad)
868     if (sec == findFirstSection(l))
869       l->lmaOffset = ctx->lmaOffset;
870 
871   // We can call this method multiple times during the creation of
872   // thunks and want to start over calculation each time.
873   sec->size = 0;
874 
875   // We visited SectionsCommands from processSectionCommands to
876   // layout sections. Now, we visit SectionsCommands again to fix
877   // section offsets.
878   for (BaseCommand *base : sec->sectionCommands) {
879     // This handles the assignments to symbol or to the dot.
880     if (auto *cmd = dyn_cast<SymbolAssignment>(base)) {
881       cmd->addr = dot;
882       assignSymbol(cmd, true);
883       cmd->size = dot - cmd->addr;
884       continue;
885     }
886 
887     // Handle BYTE(), SHORT(), LONG(), or QUAD().
888     if (auto *cmd = dyn_cast<ByteCommand>(base)) {
889       cmd->offset = dot - ctx->outSec->addr;
890       dot += cmd->size;
891       expandOutputSection(cmd->size);
892       continue;
893     }
894 
895     // Handle a single input section description command.
896     // It calculates and assigns the offsets for each section and also
897     // updates the output section size.
898     for (InputSection *sec : cast<InputSectionDescription>(base)->sections)
899       output(sec);
900   }
901 }
902 
903 static bool isDiscardable(OutputSection &sec) {
904   if (sec.name == "/DISCARD/")
905     return true;
906 
907   // We do not remove empty sections that are explicitly
908   // assigned to any segment.
909   if (!sec.phdrs.empty())
910     return false;
911 
912   // We do not want to remove OutputSections with expressions that reference
913   // symbols even if the OutputSection is empty. We want to ensure that the
914   // expressions can be evaluated and report an error if they cannot.
915   if (sec.expressionsUseSymbols)
916     return false;
917 
918   // OutputSections may be referenced by name in ADDR and LOADADDR expressions,
919   // as an empty Section can has a valid VMA and LMA we keep the OutputSection
920   // to maintain the integrity of the other Expression.
921   if (sec.usedInExpression)
922     return false;
923 
924   for (BaseCommand *base : sec.sectionCommands) {
925     if (auto cmd = dyn_cast<SymbolAssignment>(base))
926       // Don't create empty output sections just for unreferenced PROVIDE
927       // symbols.
928       if (cmd->name != "." && !cmd->sym)
929         continue;
930 
931     if (!isa<InputSectionDescription>(*base))
932       return false;
933   }
934   return true;
935 }
936 
937 void LinkerScript::adjustSectionsBeforeSorting() {
938   // If the output section contains only symbol assignments, create a
939   // corresponding output section. The issue is what to do with linker script
940   // like ".foo : { symbol = 42; }". One option would be to convert it to
941   // "symbol = 42;". That is, move the symbol out of the empty section
942   // description. That seems to be what bfd does for this simple case. The
943   // problem is that this is not completely general. bfd will give up and
944   // create a dummy section too if there is a ". = . + 1" inside the section
945   // for example.
946   // Given that we want to create the section, we have to worry what impact
947   // it will have on the link. For example, if we just create a section with
948   // 0 for flags, it would change which PT_LOADs are created.
949   // We could remember that particular section is dummy and ignore it in
950   // other parts of the linker, but unfortunately there are quite a few places
951   // that would need to change:
952   //   * The program header creation.
953   //   * The orphan section placement.
954   //   * The address assignment.
955   // The other option is to pick flags that minimize the impact the section
956   // will have on the rest of the linker. That is why we copy the flags from
957   // the previous sections. Only a few flags are needed to keep the impact low.
958   uint64_t flags = SHF_ALLOC;
959 
960   for (BaseCommand *&cmd : sectionCommands) {
961     auto *sec = dyn_cast<OutputSection>(cmd);
962     if (!sec)
963       continue;
964 
965     // Handle align (e.g. ".foo : ALIGN(16) { ... }").
966     if (sec->alignExpr)
967       sec->alignment =
968           std::max<uint32_t>(sec->alignment, sec->alignExpr().getValue());
969 
970     // The input section might have been removed (if it was an empty synthetic
971     // section), but we at least know the flags.
972     if (sec->hasInputSections)
973       flags = sec->flags;
974 
975     // We do not want to keep any special flags for output section
976     // in case it is empty.
977     bool isEmpty = (getFirstInputSection(sec) == nullptr);
978     if (isEmpty)
979       sec->flags = flags & ((sec->nonAlloc ? 0 : (uint64_t)SHF_ALLOC) |
980                             SHF_WRITE | SHF_EXECINSTR);
981 
982     if (isEmpty && isDiscardable(*sec)) {
983       sec->markDead();
984       cmd = nullptr;
985     }
986   }
987 
988   // It is common practice to use very generic linker scripts. So for any
989   // given run some of the output sections in the script will be empty.
990   // We could create corresponding empty output sections, but that would
991   // clutter the output.
992   // We instead remove trivially empty sections. The bfd linker seems even
993   // more aggressive at removing them.
994   llvm::erase_if(sectionCommands, [&](BaseCommand *base) { return !base; });
995 }
996 
997 void LinkerScript::adjustSectionsAfterSorting() {
998   // Try and find an appropriate memory region to assign offsets in.
999   for (BaseCommand *base : sectionCommands) {
1000     if (auto *sec = dyn_cast<OutputSection>(base)) {
1001       if (!sec->lmaRegionName.empty()) {
1002         if (MemoryRegion *m = memoryRegions.lookup(sec->lmaRegionName))
1003           sec->lmaRegion = m;
1004         else
1005           error("memory region '" + sec->lmaRegionName + "' not declared");
1006       }
1007       sec->memRegion = findMemoryRegion(sec);
1008     }
1009   }
1010 
1011   // If output section command doesn't specify any segments,
1012   // and we haven't previously assigned any section to segment,
1013   // then we simply assign section to the very first load segment.
1014   // Below is an example of such linker script:
1015   // PHDRS { seg PT_LOAD; }
1016   // SECTIONS { .aaa : { *(.aaa) } }
1017   std::vector<StringRef> defPhdrs;
1018   auto firstPtLoad = llvm::find_if(phdrsCommands, [](const PhdrsCommand &cmd) {
1019     return cmd.type == PT_LOAD;
1020   });
1021   if (firstPtLoad != phdrsCommands.end())
1022     defPhdrs.push_back(firstPtLoad->name);
1023 
1024   // Walk the commands and propagate the program headers to commands that don't
1025   // explicitly specify them.
1026   for (BaseCommand *base : sectionCommands) {
1027     auto *sec = dyn_cast<OutputSection>(base);
1028     if (!sec)
1029       continue;
1030 
1031     if (sec->phdrs.empty()) {
1032       // To match the bfd linker script behaviour, only propagate program
1033       // headers to sections that are allocated.
1034       if (sec->flags & SHF_ALLOC)
1035         sec->phdrs = defPhdrs;
1036     } else {
1037       defPhdrs = sec->phdrs;
1038     }
1039   }
1040 }
1041 
1042 static uint64_t computeBase(uint64_t min, bool allocateHeaders) {
1043   // If there is no SECTIONS or if the linkerscript is explicit about program
1044   // headers, do our best to allocate them.
1045   if (!script->hasSectionsCommand || allocateHeaders)
1046     return 0;
1047   // Otherwise only allocate program headers if that would not add a page.
1048   return alignDown(min, config->maxPageSize);
1049 }
1050 
1051 // When the SECTIONS command is used, try to find an address for the file and
1052 // program headers output sections, which can be added to the first PT_LOAD
1053 // segment when program headers are created.
1054 //
1055 // We check if the headers fit below the first allocated section. If there isn't
1056 // enough space for these sections, we'll remove them from the PT_LOAD segment,
1057 // and we'll also remove the PT_PHDR segment.
1058 void LinkerScript::allocateHeaders(std::vector<PhdrEntry *> &phdrs) {
1059   uint64_t min = std::numeric_limits<uint64_t>::max();
1060   for (OutputSection *sec : outputSections)
1061     if (sec->flags & SHF_ALLOC)
1062       min = std::min<uint64_t>(min, sec->addr);
1063 
1064   auto it = llvm::find_if(
1065       phdrs, [](const PhdrEntry *e) { return e->p_type == PT_LOAD; });
1066   if (it == phdrs.end())
1067     return;
1068   PhdrEntry *firstPTLoad = *it;
1069 
1070   bool hasExplicitHeaders =
1071       llvm::any_of(phdrsCommands, [](const PhdrsCommand &cmd) {
1072         return cmd.hasPhdrs || cmd.hasFilehdr;
1073       });
1074   bool paged = !config->omagic && !config->nmagic;
1075   uint64_t headerSize = getHeaderSize();
1076   if ((paged || hasExplicitHeaders) &&
1077       headerSize <= min - computeBase(min, hasExplicitHeaders)) {
1078     min = alignDown(min - headerSize, config->maxPageSize);
1079     Out::elfHeader->addr = min;
1080     Out::programHeaders->addr = min + Out::elfHeader->size;
1081     return;
1082   }
1083 
1084   // Error if we were explicitly asked to allocate headers.
1085   if (hasExplicitHeaders)
1086     error("could not allocate headers");
1087 
1088   Out::elfHeader->ptLoad = nullptr;
1089   Out::programHeaders->ptLoad = nullptr;
1090   firstPTLoad->firstSec = findFirstSection(firstPTLoad);
1091 
1092   llvm::erase_if(phdrs,
1093                  [](const PhdrEntry *e) { return e->p_type == PT_PHDR; });
1094 }
1095 
1096 LinkerScript::AddressState::AddressState() {
1097   for (auto &mri : script->memoryRegions) {
1098     MemoryRegion *mr = mri.second;
1099     mr->curPos = (mr->origin)().getValue();
1100   }
1101 }
1102 
1103 // Here we assign addresses as instructed by linker script SECTIONS
1104 // sub-commands. Doing that allows us to use final VA values, so here
1105 // we also handle rest commands like symbol assignments and ASSERTs.
1106 // Returns a symbol that has changed its section or value, or nullptr if no
1107 // symbol has changed.
1108 const Defined *LinkerScript::assignAddresses() {
1109   if (script->hasSectionsCommand) {
1110     // With a linker script, assignment of addresses to headers is covered by
1111     // allocateHeaders().
1112     dot = config->imageBase.getValueOr(0);
1113   } else {
1114     // Assign addresses to headers right now.
1115     dot = target->getImageBase();
1116     Out::elfHeader->addr = dot;
1117     Out::programHeaders->addr = dot + Out::elfHeader->size;
1118     dot += getHeaderSize();
1119   }
1120 
1121   auto deleter = std::make_unique<AddressState>();
1122   ctx = deleter.get();
1123   errorOnMissingSection = true;
1124   switchTo(aether);
1125 
1126   SymbolAssignmentMap oldValues = getSymbolAssignmentValues(sectionCommands);
1127   for (BaseCommand *base : sectionCommands) {
1128     if (auto *cmd = dyn_cast<SymbolAssignment>(base)) {
1129       cmd->addr = dot;
1130       assignSymbol(cmd, false);
1131       cmd->size = dot - cmd->addr;
1132       continue;
1133     }
1134     assignOffsets(cast<OutputSection>(base));
1135   }
1136 
1137   ctx = nullptr;
1138   return getChangedSymbolAssignment(oldValues);
1139 }
1140 
1141 // Creates program headers as instructed by PHDRS linker script command.
1142 std::vector<PhdrEntry *> LinkerScript::createPhdrs() {
1143   std::vector<PhdrEntry *> ret;
1144 
1145   // Process PHDRS and FILEHDR keywords because they are not
1146   // real output sections and cannot be added in the following loop.
1147   for (const PhdrsCommand &cmd : phdrsCommands) {
1148     PhdrEntry *phdr = make<PhdrEntry>(cmd.type, cmd.flags ? *cmd.flags : PF_R);
1149 
1150     if (cmd.hasFilehdr)
1151       phdr->add(Out::elfHeader);
1152     if (cmd.hasPhdrs)
1153       phdr->add(Out::programHeaders);
1154 
1155     if (cmd.lmaExpr) {
1156       phdr->p_paddr = cmd.lmaExpr().getValue();
1157       phdr->hasLMA = true;
1158     }
1159     ret.push_back(phdr);
1160   }
1161 
1162   // Add output sections to program headers.
1163   for (OutputSection *sec : outputSections) {
1164     // Assign headers specified by linker script
1165     for (size_t id : getPhdrIndices(sec)) {
1166       ret[id]->add(sec);
1167       if (!phdrsCommands[id].flags.hasValue())
1168         ret[id]->p_flags |= sec->getPhdrFlags();
1169     }
1170   }
1171   return ret;
1172 }
1173 
1174 // Returns true if we should emit an .interp section.
1175 //
1176 // We usually do. But if PHDRS commands are given, and
1177 // no PT_INTERP is there, there's no place to emit an
1178 // .interp, so we don't do that in that case.
1179 bool LinkerScript::needsInterpSection() {
1180   if (phdrsCommands.empty())
1181     return true;
1182   for (PhdrsCommand &cmd : phdrsCommands)
1183     if (cmd.type == PT_INTERP)
1184       return true;
1185   return false;
1186 }
1187 
1188 ExprValue LinkerScript::getSymbolValue(StringRef name, const Twine &loc) {
1189   if (name == ".") {
1190     if (ctx)
1191       return {ctx->outSec, false, dot - ctx->outSec->addr, loc};
1192     error(loc + ": unable to get location counter value");
1193     return 0;
1194   }
1195 
1196   if (Symbol *sym = symtab->find(name)) {
1197     if (auto *ds = dyn_cast<Defined>(sym))
1198       return {ds->section, false, ds->value, loc};
1199     if (isa<SharedSymbol>(sym))
1200       if (!errorOnMissingSection)
1201         return {nullptr, false, 0, loc};
1202   }
1203 
1204   error(loc + ": symbol not found: " + name);
1205   return 0;
1206 }
1207 
1208 // Returns the index of the segment named Name.
1209 static Optional<size_t> getPhdrIndex(ArrayRef<PhdrsCommand> vec,
1210                                      StringRef name) {
1211   for (size_t i = 0; i < vec.size(); ++i)
1212     if (vec[i].name == name)
1213       return i;
1214   return None;
1215 }
1216 
1217 // Returns indices of ELF headers containing specific section. Each index is a
1218 // zero based number of ELF header listed within PHDRS {} script block.
1219 std::vector<size_t> LinkerScript::getPhdrIndices(OutputSection *cmd) {
1220   std::vector<size_t> ret;
1221 
1222   for (StringRef s : cmd->phdrs) {
1223     if (Optional<size_t> idx = getPhdrIndex(phdrsCommands, s))
1224       ret.push_back(*idx);
1225     else if (s != "NONE")
1226       error(cmd->location + ": section header '" + s +
1227             "' is not listed in PHDRS");
1228   }
1229   return ret;
1230 }
1231 
1232 } // namespace elf
1233 } // namespace lld
1234