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