]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lld/ELF/LinkerScript.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r304460, and update
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / lld / ELF / LinkerScript.cpp
1 //===- LinkerScript.cpp ---------------------------------------------------===//
2 //
3 //                             The LLVM Linker
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the parser/evaluator of the linker script.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "LinkerScript.h"
15 #include "Config.h"
16 #include "InputSection.h"
17 #include "Memory.h"
18 #include "OutputSections.h"
19 #include "Strings.h"
20 #include "SymbolTable.h"
21 #include "Symbols.h"
22 #include "SyntheticSections.h"
23 #include "Target.h"
24 #include "Threads.h"
25 #include "Writer.h"
26 #include "llvm/ADT/STLExtras.h"
27 #include "llvm/ADT/StringRef.h"
28 #include "llvm/Support/Casting.h"
29 #include "llvm/Support/Compression.h"
30 #include "llvm/Support/ELF.h"
31 #include "llvm/Support/Endian.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/FileSystem.h"
34 #include "llvm/Support/Path.h"
35 #include <algorithm>
36 #include <cassert>
37 #include <cstddef>
38 #include <cstdint>
39 #include <iterator>
40 #include <limits>
41 #include <string>
42 #include <vector>
43
44 using namespace llvm;
45 using namespace llvm::ELF;
46 using namespace llvm::object;
47 using namespace llvm::support::endian;
48 using namespace lld;
49 using namespace lld::elf;
50
51 LinkerScript *elf::Script;
52
53 uint64_t ExprValue::getValue() const {
54   if (Sec) {
55     if (OutputSection *OS = Sec->getOutputSection())
56       return alignTo(Sec->getOffset(Val) + OS->Addr, Alignment);
57     error("unable to evaluate expression: input section " + Sec->Name +
58           " has no output section assigned");
59   }
60   return alignTo(Val, Alignment);
61 }
62
63 uint64_t ExprValue::getSecAddr() const {
64   if (Sec)
65     return Sec->getOffset(0) + Sec->getOutputSection()->Addr;
66   return 0;
67 }
68
69 template <class ELFT> static SymbolBody *addRegular(SymbolAssignment *Cmd) {
70   Symbol *Sym;
71   uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
72   std::tie(Sym, std::ignore) = Symtab<ELFT>::X->insert(
73       Cmd->Name, /*Type*/ 0, Visibility, /*CanOmitFromDynSym*/ false,
74       /*File*/ nullptr);
75   Sym->Binding = STB_GLOBAL;
76   ExprValue Value = Cmd->Expression();
77   SectionBase *Sec = Value.isAbsolute() ? nullptr : Value.Sec;
78
79   // We want to set symbol values early if we can. This allows us to use symbols
80   // as variables in linker scripts. Doing so allows us to write expressions
81   // like this: `alignment = 16; . = ALIGN(., alignment)`
82   uint64_t SymValue = Value.isAbsolute() ? Value.getValue() : 0;
83   replaceBody<DefinedRegular>(Sym, Cmd->Name, /*IsLocal=*/false, Visibility,
84                               STT_NOTYPE, SymValue, 0, Sec, nullptr);
85   return Sym->body();
86 }
87
88 OutputSectionCommand *
89 LinkerScript::createOutputSectionCommand(StringRef Name, StringRef Location) {
90   OutputSectionCommand *&CmdRef = NameToOutputSectionCommand[Name];
91   OutputSectionCommand *Cmd;
92   if (CmdRef && CmdRef->Location.empty()) {
93     // There was a forward reference.
94     Cmd = CmdRef;
95   } else {
96     Cmd = make<OutputSectionCommand>(Name);
97     if (!CmdRef)
98       CmdRef = Cmd;
99   }
100   Cmd->Location = Location;
101   return Cmd;
102 }
103
104 OutputSectionCommand *
105 LinkerScript::getOrCreateOutputSectionCommand(StringRef Name) {
106   OutputSectionCommand *&CmdRef = NameToOutputSectionCommand[Name];
107   if (!CmdRef)
108     CmdRef = make<OutputSectionCommand>(Name);
109   return CmdRef;
110 }
111
112 void LinkerScript::setDot(Expr E, const Twine &Loc, bool InSec) {
113   uint64_t Val = E().getValue();
114   if (Val < Dot) {
115     if (InSec)
116       error(Loc + ": unable to move location counter backward for: " +
117             CurOutSec->Name);
118     else
119       error(Loc + ": unable to move location counter backward");
120   }
121   Dot = Val;
122   // Update to location counter means update to section size.
123   if (InSec)
124     CurOutSec->Size = Dot - CurOutSec->Addr;
125 }
126
127 // Sets value of a symbol. Two kinds of symbols are processed: synthetic
128 // symbols, whose value is an offset from beginning of section and regular
129 // symbols whose value is absolute.
130 void LinkerScript::assignSymbol(SymbolAssignment *Cmd, bool InSec) {
131   if (Cmd->Name == ".") {
132     setDot(Cmd->Expression, Cmd->Location, InSec);
133     return;
134   }
135
136   if (!Cmd->Sym)
137     return;
138
139   auto *Sym = cast<DefinedRegular>(Cmd->Sym);
140   ExprValue V = Cmd->Expression();
141   if (V.isAbsolute()) {
142     Sym->Value = V.getValue();
143   } else {
144     Sym->Section = V.Sec;
145     if (Sym->Section->Flags & SHF_ALLOC)
146       Sym->Value = alignTo(V.Val, V.Alignment);
147     else
148       Sym->Value = V.getValue();
149   }
150 }
151
152 static SymbolBody *findSymbol(StringRef S) {
153   switch (Config->EKind) {
154   case ELF32LEKind:
155     return Symtab<ELF32LE>::X->find(S);
156   case ELF32BEKind:
157     return Symtab<ELF32BE>::X->find(S);
158   case ELF64LEKind:
159     return Symtab<ELF64LE>::X->find(S);
160   case ELF64BEKind:
161     return Symtab<ELF64BE>::X->find(S);
162   default:
163     llvm_unreachable("unknown Config->EKind");
164   }
165 }
166
167 static SymbolBody *addRegularSymbol(SymbolAssignment *Cmd) {
168   switch (Config->EKind) {
169   case ELF32LEKind:
170     return addRegular<ELF32LE>(Cmd);
171   case ELF32BEKind:
172     return addRegular<ELF32BE>(Cmd);
173   case ELF64LEKind:
174     return addRegular<ELF64LE>(Cmd);
175   case ELF64BEKind:
176     return addRegular<ELF64BE>(Cmd);
177   default:
178     llvm_unreachable("unknown Config->EKind");
179   }
180 }
181
182 void LinkerScript::addSymbol(SymbolAssignment *Cmd) {
183   if (Cmd->Name == ".")
184     return;
185
186   // If a symbol was in PROVIDE(), we need to define it only when
187   // it is a referenced undefined symbol.
188   SymbolBody *B = findSymbol(Cmd->Name);
189   if (Cmd->Provide && (!B || B->isDefined()))
190     return;
191
192   Cmd->Sym = addRegularSymbol(Cmd);
193 }
194
195 bool SymbolAssignment::classof(const BaseCommand *C) {
196   return C->Kind == AssignmentKind;
197 }
198
199 bool OutputSectionCommand::classof(const BaseCommand *C) {
200   return C->Kind == OutputSectionKind;
201 }
202
203 // Fill [Buf, Buf + Size) with Filler.
204 // This is used for linker script "=fillexp" command.
205 static void fill(uint8_t *Buf, size_t Size, uint32_t Filler) {
206   size_t I = 0;
207   for (; I + 4 < Size; I += 4)
208     memcpy(Buf + I, &Filler, 4);
209   memcpy(Buf + I, &Filler, Size - I);
210 }
211
212 bool InputSectionDescription::classof(const BaseCommand *C) {
213   return C->Kind == InputSectionKind;
214 }
215
216 bool AssertCommand::classof(const BaseCommand *C) {
217   return C->Kind == AssertKind;
218 }
219
220 bool BytesDataCommand::classof(const BaseCommand *C) {
221   return C->Kind == BytesDataKind;
222 }
223
224 static StringRef basename(InputSectionBase *S) {
225   if (S->File)
226     return sys::path::filename(S->File->getName());
227   return "";
228 }
229
230 bool LinkerScript::shouldKeep(InputSectionBase *S) {
231   for (InputSectionDescription *ID : Opt.KeptSections)
232     if (ID->FilePat.match(basename(S)))
233       for (SectionPattern &P : ID->SectionPatterns)
234         if (P.SectionPat.match(S->Name))
235           return true;
236   return false;
237 }
238
239 // A helper function for the SORT() command.
240 static std::function<bool(InputSectionBase *, InputSectionBase *)>
241 getComparator(SortSectionPolicy K) {
242   switch (K) {
243   case SortSectionPolicy::Alignment:
244     return [](InputSectionBase *A, InputSectionBase *B) {
245       // ">" is not a mistake. Sections with larger alignments are placed
246       // before sections with smaller alignments in order to reduce the
247       // amount of padding necessary. This is compatible with GNU.
248       return A->Alignment > B->Alignment;
249     };
250   case SortSectionPolicy::Name:
251     return [](InputSectionBase *A, InputSectionBase *B) {
252       return A->Name < B->Name;
253     };
254   case SortSectionPolicy::Priority:
255     return [](InputSectionBase *A, InputSectionBase *B) {
256       return getPriority(A->Name) < getPriority(B->Name);
257     };
258   default:
259     llvm_unreachable("unknown sort policy");
260   }
261 }
262
263 // A helper function for the SORT() command.
264 static bool matchConstraints(ArrayRef<InputSectionBase *> Sections,
265                              ConstraintKind Kind) {
266   if (Kind == ConstraintKind::NoConstraint)
267     return true;
268
269   bool IsRW = llvm::any_of(Sections, [](InputSectionBase *Sec) {
270     return static_cast<InputSectionBase *>(Sec)->Flags & SHF_WRITE;
271   });
272
273   return (IsRW && Kind == ConstraintKind::ReadWrite) ||
274          (!IsRW && Kind == ConstraintKind::ReadOnly);
275 }
276
277 static void sortSections(InputSection **Begin, InputSection **End,
278                          SortSectionPolicy K) {
279   if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
280     std::stable_sort(Begin, End, getComparator(K));
281 }
282
283 // Compute and remember which sections the InputSectionDescription matches.
284 std::vector<InputSection *>
285 LinkerScript::computeInputSections(const InputSectionDescription *Cmd) {
286   std::vector<InputSection *> Ret;
287
288   // Collects all sections that satisfy constraints of Cmd.
289   for (const SectionPattern &Pat : Cmd->SectionPatterns) {
290     size_t SizeBefore = Ret.size();
291
292     for (InputSectionBase *Sec : InputSections) {
293       if (Sec->Assigned)
294         continue;
295
296       if (!Sec->Live) {
297         reportDiscarded(Sec);
298         continue;
299       }
300
301       // For -emit-relocs we have to ignore entries like
302       //   .rela.dyn : { *(.rela.data) }
303       // which are common because they are in the default bfd script.
304       if (Sec->Type == SHT_REL || Sec->Type == SHT_RELA)
305         continue;
306
307       StringRef Filename = basename(Sec);
308       if (!Cmd->FilePat.match(Filename) ||
309           Pat.ExcludedFilePat.match(Filename) ||
310           !Pat.SectionPat.match(Sec->Name))
311         continue;
312
313       Ret.push_back(cast<InputSection>(Sec));
314       Sec->Assigned = true;
315     }
316
317     // Sort sections as instructed by SORT-family commands and --sort-section
318     // option. Because SORT-family commands can be nested at most two depth
319     // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
320     // line option is respected even if a SORT command is given, the exact
321     // behavior we have here is a bit complicated. Here are the rules.
322     //
323     // 1. If two SORT commands are given, --sort-section is ignored.
324     // 2. If one SORT command is given, and if it is not SORT_NONE,
325     //    --sort-section is handled as an inner SORT command.
326     // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
327     // 4. If no SORT command is given, sort according to --sort-section.
328     InputSection **Begin = Ret.data() + SizeBefore;
329     InputSection **End = Ret.data() + Ret.size();
330     if (Pat.SortOuter != SortSectionPolicy::None) {
331       if (Pat.SortInner == SortSectionPolicy::Default)
332         sortSections(Begin, End, Config->SortSection);
333       else
334         sortSections(Begin, End, Pat.SortInner);
335       sortSections(Begin, End, Pat.SortOuter);
336     }
337   }
338   return Ret;
339 }
340
341 void LinkerScript::discard(ArrayRef<InputSectionBase *> V) {
342   for (InputSectionBase *S : V) {
343     S->Live = false;
344     if (S == InX::ShStrTab)
345       error("discarding .shstrtab section is not allowed");
346     discard(S->DependentSections);
347   }
348 }
349
350 std::vector<InputSectionBase *>
351 LinkerScript::createInputSectionList(OutputSectionCommand &OutCmd) {
352   std::vector<InputSectionBase *> Ret;
353
354   for (BaseCommand *Base : OutCmd.Commands) {
355     auto *Cmd = dyn_cast<InputSectionDescription>(Base);
356     if (!Cmd)
357       continue;
358
359     Cmd->Sections = computeInputSections(Cmd);
360     Ret.insert(Ret.end(), Cmd->Sections.begin(), Cmd->Sections.end());
361   }
362
363   return Ret;
364 }
365
366 void LinkerScript::processCommands(OutputSectionFactory &Factory) {
367   // A symbol can be assigned before any section is mentioned in the linker
368   // script. In an DSO, the symbol values are addresses, so the only important
369   // section values are:
370   // * SHN_UNDEF
371   // * SHN_ABS
372   // * Any value meaning a regular section.
373   // To handle that, create a dummy aether section that fills the void before
374   // the linker scripts switches to another section. It has an index of one
375   // which will map to whatever the first actual section is.
376   Aether = make<OutputSection>("", 0, SHF_ALLOC);
377   Aether->SectionIndex = 1;
378   CurOutSec = Aether;
379   Dot = 0;
380
381   for (size_t I = 0; I < Opt.Commands.size(); ++I) {
382     // Handle symbol assignments outside of any output section.
383     if (auto *Cmd = dyn_cast<SymbolAssignment>(Opt.Commands[I])) {
384       addSymbol(Cmd);
385       continue;
386     }
387
388     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I])) {
389       std::vector<InputSectionBase *> V = createInputSectionList(*Cmd);
390
391       // The output section name `/DISCARD/' is special.
392       // Any input section assigned to it is discarded.
393       if (Cmd->Name == "/DISCARD/") {
394         discard(V);
395         continue;
396       }
397
398       // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive
399       // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input
400       // sections satisfy a given constraint. If not, a directive is handled
401       // as if it wasn't present from the beginning.
402       //
403       // Because we'll iterate over Commands many more times, the easiest
404       // way to "make it as if it wasn't present" is to just remove it.
405       if (!matchConstraints(V, Cmd->Constraint)) {
406         for (InputSectionBase *S : V)
407           S->Assigned = false;
408         Opt.Commands.erase(Opt.Commands.begin() + I);
409         --I;
410         continue;
411       }
412
413       // A directive may contain symbol definitions like this:
414       // ".foo : { ...; bar = .; }". Handle them.
415       for (BaseCommand *Base : Cmd->Commands)
416         if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base))
417           addSymbol(OutCmd);
418
419       // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign
420       // is given, input sections are aligned to that value, whether the
421       // given value is larger or smaller than the original section alignment.
422       if (Cmd->SubalignExpr) {
423         uint32_t Subalign = Cmd->SubalignExpr().getValue();
424         for (InputSectionBase *S : V)
425           S->Alignment = Subalign;
426       }
427
428       // Add input sections to an output section.
429       for (InputSectionBase *S : V)
430         Factory.addInputSec(S, Cmd->Name, Cmd->Sec);
431       if (OutputSection *Sec = Cmd->Sec) {
432         assert(Sec->SectionIndex == INT_MAX);
433         Sec->SectionIndex = I;
434         SecToCommand[Sec] = Cmd;
435       }
436     }
437   }
438   CurOutSec = nullptr;
439 }
440
441 void LinkerScript::fabricateDefaultCommands() {
442   std::vector<BaseCommand *> Commands;
443
444   // Define start address
445   uint64_t StartAddr = Config->ImageBase + elf::getHeaderSize();
446
447   // The Sections with -T<section> have been sorted in order of ascending
448   // address. We must lower StartAddr if the lowest -T<section address> as
449   // calls to setDot() must be monotonically increasing.
450   for (auto& KV : Config->SectionStartMap)
451     StartAddr = std::min(StartAddr, KV.second);
452
453   Commands.push_back(
454       make<SymbolAssignment>(".", [=] { return StartAddr; }, ""));
455
456   // For each OutputSection that needs a VA fabricate an OutputSectionCommand
457   // with an InputSectionDescription describing the InputSections
458   for (OutputSection *Sec : *OutputSections) {
459     auto *OSCmd = createOutputSectionCommand(Sec->Name, "<internal>");
460     OSCmd->Sec = Sec;
461     SecToCommand[Sec] = OSCmd;
462
463     // Prefer user supplied address over additional alignment constraint
464     auto I = Config->SectionStartMap.find(Sec->Name);
465     if (I != Config->SectionStartMap.end())
466       Commands.push_back(
467           make<SymbolAssignment>(".", [=] { return I->second; }, ""));
468     else if (Sec->PageAlign)
469       OSCmd->AddrExpr = [=] {
470         return alignTo(Script->getDot(), Config->MaxPageSize);
471       };
472
473     Commands.push_back(OSCmd);
474     if (Sec->Sections.size()) {
475       auto *ISD = make<InputSectionDescription>("");
476       OSCmd->Commands.push_back(ISD);
477       for (InputSection *ISec : Sec->Sections) {
478         ISD->Sections.push_back(ISec);
479         ISec->Assigned = true;
480       }
481     }
482   }
483   // SECTIONS commands run before other non SECTIONS commands
484   Commands.insert(Commands.end(), Opt.Commands.begin(), Opt.Commands.end());
485   Opt.Commands = std::move(Commands);
486 }
487
488 // Add sections that didn't match any sections command.
489 void LinkerScript::addOrphanSections(OutputSectionFactory &Factory) {
490   for (InputSectionBase *S : InputSections) {
491     if (!S->Live || S->Parent)
492       continue;
493     StringRef Name = getOutputSectionName(S->Name);
494     auto I = std::find_if(
495         Opt.Commands.begin(), Opt.Commands.end(), [&](BaseCommand *Base) {
496           if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base))
497             return Cmd->Name == Name;
498           return false;
499         });
500     if (I == Opt.Commands.end()) {
501       Factory.addInputSec(S, Name);
502     } else {
503       auto *Cmd = cast<OutputSectionCommand>(*I);
504       Factory.addInputSec(S, Name, Cmd->Sec);
505       if (OutputSection *Sec = Cmd->Sec) {
506         SecToCommand[Sec] = Cmd;
507         unsigned Index = std::distance(Opt.Commands.begin(), I);
508         assert(Sec->SectionIndex == INT_MAX || Sec->SectionIndex == Index);
509         Sec->SectionIndex = Index;
510       }
511       auto *ISD = make<InputSectionDescription>("");
512       ISD->Sections.push_back(cast<InputSection>(S));
513       Cmd->Commands.push_back(ISD);
514     }
515   }
516 }
517
518 uint64_t LinkerScript::advance(uint64_t Size, unsigned Align) {
519   bool IsTbss = (CurOutSec->Flags & SHF_TLS) && CurOutSec->Type == SHT_NOBITS;
520   uint64_t Start = IsTbss ? Dot + ThreadBssOffset : Dot;
521   Start = alignTo(Start, Align);
522   uint64_t End = Start + Size;
523
524   if (IsTbss)
525     ThreadBssOffset = End - Dot;
526   else
527     Dot = End;
528   return End;
529 }
530
531 void LinkerScript::output(InputSection *S) {
532   uint64_t Pos = advance(S->getSize(), S->Alignment);
533   S->OutSecOff = Pos - S->getSize() - CurOutSec->Addr;
534
535   // Update output section size after adding each section. This is so that
536   // SIZEOF works correctly in the case below:
537   // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
538   CurOutSec->Size = Pos - CurOutSec->Addr;
539
540   // If there is a memory region associated with this input section, then
541   // place the section in that region and update the region index.
542   if (CurMemRegion) {
543     CurMemRegion->Offset += CurOutSec->Size;
544     uint64_t CurSize = CurMemRegion->Offset - CurMemRegion->Origin;
545     if (CurSize > CurMemRegion->Length) {
546       uint64_t OverflowAmt = CurSize - CurMemRegion->Length;
547       error("section '" + CurOutSec->Name + "' will not fit in region '" +
548             CurMemRegion->Name + "': overflowed by " + Twine(OverflowAmt) +
549             " bytes");
550     }
551   }
552 }
553
554 void LinkerScript::switchTo(OutputSection *Sec) {
555   if (CurOutSec == Sec)
556     return;
557
558   CurOutSec = Sec;
559   CurOutSec->Addr = advance(0, CurOutSec->Alignment);
560
561   // If neither AT nor AT> is specified for an allocatable section, the linker
562   // will set the LMA such that the difference between VMA and LMA for the
563   // section is the same as the preceding output section in the same region
564   // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
565   if (LMAOffset)
566     CurOutSec->LMAOffset = LMAOffset();
567 }
568
569 void LinkerScript::process(BaseCommand &Base) {
570   // This handles the assignments to symbol or to the dot.
571   if (auto *Cmd = dyn_cast<SymbolAssignment>(&Base)) {
572     assignSymbol(Cmd, true);
573     return;
574   }
575
576   // Handle BYTE(), SHORT(), LONG(), or QUAD().
577   if (auto *Cmd = dyn_cast<BytesDataCommand>(&Base)) {
578     Cmd->Offset = Dot - CurOutSec->Addr;
579     Dot += Cmd->Size;
580     CurOutSec->Size = Dot - CurOutSec->Addr;
581     return;
582   }
583
584   // Handle ASSERT().
585   if (auto *Cmd = dyn_cast<AssertCommand>(&Base)) {
586     Cmd->Expression();
587     return;
588   }
589
590   // Handle a single input section description command.
591   // It calculates and assigns the offsets for each section and also
592   // updates the output section size.
593   auto &Cmd = cast<InputSectionDescription>(Base);
594   for (InputSection *Sec : Cmd.Sections) {
595     // We tentatively added all synthetic sections at the beginning and removed
596     // empty ones afterwards (because there is no way to know whether they were
597     // going be empty or not other than actually running linker scripts.)
598     // We need to ignore remains of empty sections.
599     if (auto *S = dyn_cast<SyntheticSection>(Sec))
600       if (S->empty())
601         continue;
602
603     if (!Sec->Live)
604       continue;
605     assert(CurOutSec == Sec->getParent());
606     output(Sec);
607   }
608 }
609
610 // This function searches for a memory region to place the given output
611 // section in. If found, a pointer to the appropriate memory region is
612 // returned. Otherwise, a nullptr is returned.
613 MemoryRegion *LinkerScript::findMemoryRegion(OutputSectionCommand *Cmd) {
614   // If a memory region name was specified in the output section command,
615   // then try to find that region first.
616   if (!Cmd->MemoryRegionName.empty()) {
617     auto It = Opt.MemoryRegions.find(Cmd->MemoryRegionName);
618     if (It != Opt.MemoryRegions.end())
619       return &It->second;
620     error("memory region '" + Cmd->MemoryRegionName + "' not declared");
621     return nullptr;
622   }
623
624   // If at least one memory region is defined, all sections must
625   // belong to some memory region. Otherwise, we don't need to do
626   // anything for memory regions.
627   if (Opt.MemoryRegions.empty())
628     return nullptr;
629
630   OutputSection *Sec = Cmd->Sec;
631   // See if a region can be found by matching section flags.
632   for (auto &Pair : Opt.MemoryRegions) {
633     MemoryRegion &M = Pair.second;
634     if ((M.Flags & Sec->Flags) && (M.NegFlags & Sec->Flags) == 0)
635       return &M;
636   }
637
638   // Otherwise, no suitable region was found.
639   if (Sec->Flags & SHF_ALLOC)
640     error("no memory region specified for section '" + Sec->Name + "'");
641   return nullptr;
642 }
643
644 // This function assigns offsets to input sections and an output section
645 // for a single sections command (e.g. ".text { *(.text); }").
646 void LinkerScript::assignOffsets(OutputSectionCommand *Cmd) {
647   OutputSection *Sec = Cmd->Sec;
648   if (!Sec)
649     return;
650
651   if (Cmd->AddrExpr && (Sec->Flags & SHF_ALLOC))
652     setDot(Cmd->AddrExpr, Cmd->Location, false);
653
654   if (Cmd->LMAExpr) {
655     uint64_t D = Dot;
656     LMAOffset = [=] { return Cmd->LMAExpr().getValue() - D; };
657   }
658
659   CurMemRegion = Cmd->MemRegion;
660   if (CurMemRegion)
661     Dot = CurMemRegion->Offset;
662   switchTo(Sec);
663
664   // We do not support custom layout for compressed debug sectons.
665   // At this point we already know their size and have compressed content.
666   if (CurOutSec->Flags & SHF_COMPRESSED)
667     return;
668
669   for (BaseCommand *C : Cmd->Commands)
670     process(*C);
671 }
672
673 void LinkerScript::removeEmptyCommands() {
674   // It is common practice to use very generic linker scripts. So for any
675   // given run some of the output sections in the script will be empty.
676   // We could create corresponding empty output sections, but that would
677   // clutter the output.
678   // We instead remove trivially empty sections. The bfd linker seems even
679   // more aggressive at removing them.
680   auto Pos = std::remove_if(
681       Opt.Commands.begin(), Opt.Commands.end(), [&](BaseCommand *Base) {
682         if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base))
683           return std::find(OutputSections->begin(), OutputSections->end(),
684                            Cmd->Sec) == OutputSections->end();
685         return false;
686       });
687   Opt.Commands.erase(Pos, Opt.Commands.end());
688 }
689
690 static bool isAllSectionDescription(const OutputSectionCommand &Cmd) {
691   for (BaseCommand *Base : Cmd.Commands)
692     if (!isa<InputSectionDescription>(*Base))
693       return false;
694   return true;
695 }
696
697 void LinkerScript::adjustSectionsBeforeSorting() {
698   // If the output section contains only symbol assignments, create a
699   // corresponding output section. The bfd linker seems to only create them if
700   // '.' is assigned to, but creating these section should not have any bad
701   // consequeces and gives us a section to put the symbol in.
702   uint64_t Flags = SHF_ALLOC;
703
704   for (int I = 0, E = Opt.Commands.size(); I != E; ++I) {
705     auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I]);
706     if (!Cmd)
707       continue;
708     if (OutputSection *Sec = Cmd->Sec) {
709       Flags = Sec->Flags;
710       continue;
711     }
712
713     if (isAllSectionDescription(*Cmd))
714       continue;
715
716     auto *OutSec = make<OutputSection>(Cmd->Name, SHT_PROGBITS, Flags);
717     OutSec->SectionIndex = I;
718     OutputSections->push_back(OutSec);
719     Cmd->Sec = OutSec;
720     SecToCommand[OutSec] = Cmd;
721   }
722 }
723
724 void LinkerScript::adjustSectionsAfterSorting() {
725   placeOrphanSections();
726
727   // Try and find an appropriate memory region to assign offsets in.
728   for (BaseCommand *Base : Opt.Commands) {
729     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base)) {
730       Cmd->MemRegion = findMemoryRegion(Cmd);
731       // Handle align (e.g. ".foo : ALIGN(16) { ... }").
732       if (Cmd->AlignExpr)
733         Cmd->Sec->updateAlignment(Cmd->AlignExpr().getValue());
734     }
735   }
736
737   // If output section command doesn't specify any segments,
738   // and we haven't previously assigned any section to segment,
739   // then we simply assign section to the very first load segment.
740   // Below is an example of such linker script:
741   // PHDRS { seg PT_LOAD; }
742   // SECTIONS { .aaa : { *(.aaa) } }
743   std::vector<StringRef> DefPhdrs;
744   auto FirstPtLoad =
745       std::find_if(Opt.PhdrsCommands.begin(), Opt.PhdrsCommands.end(),
746                    [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; });
747   if (FirstPtLoad != Opt.PhdrsCommands.end())
748     DefPhdrs.push_back(FirstPtLoad->Name);
749
750   // Walk the commands and propagate the program headers to commands that don't
751   // explicitly specify them.
752   for (BaseCommand *Base : Opt.Commands) {
753     auto *Cmd = dyn_cast<OutputSectionCommand>(Base);
754     if (!Cmd)
755       continue;
756
757     if (Cmd->Phdrs.empty())
758       Cmd->Phdrs = DefPhdrs;
759     else
760       DefPhdrs = Cmd->Phdrs;
761   }
762
763   removeEmptyCommands();
764 }
765
766 // When placing orphan sections, we want to place them after symbol assignments
767 // so that an orphan after
768 //   begin_foo = .;
769 //   foo : { *(foo) }
770 //   end_foo = .;
771 // doesn't break the intended meaning of the begin/end symbols.
772 // We don't want to go over sections since Writer<ELFT>::sortSections is the
773 // one in charge of deciding the order of the sections.
774 // We don't want to go over alignments, since doing so in
775 //  rx_sec : { *(rx_sec) }
776 //  . = ALIGN(0x1000);
777 //  /* The RW PT_LOAD starts here*/
778 //  rw_sec : { *(rw_sec) }
779 // would mean that the RW PT_LOAD would become unaligned.
780 static bool shouldSkip(BaseCommand *Cmd) {
781   if (isa<OutputSectionCommand>(Cmd))
782     return false;
783   if (auto *Assign = dyn_cast<SymbolAssignment>(Cmd))
784     return Assign->Name != ".";
785   return true;
786 }
787
788 // Orphan sections are sections present in the input files which are
789 // not explicitly placed into the output file by the linker script.
790 //
791 // When the control reaches this function, Opt.Commands contains
792 // output section commands for non-orphan sections only. This function
793 // adds new elements for orphan sections so that all sections are
794 // explicitly handled by Opt.Commands.
795 //
796 // Writer<ELFT>::sortSections has already sorted output sections.
797 // What we need to do is to scan OutputSections vector and
798 // Opt.Commands in parallel to find orphan sections. If there is an
799 // output section that doesn't have a corresponding entry in
800 // Opt.Commands, we will insert a new entry to Opt.Commands.
801 //
802 // There is some ambiguity as to where exactly a new entry should be
803 // inserted, because Opt.Commands contains not only output section
804 // commands but also other types of commands such as symbol assignment
805 // expressions. There's no correct answer here due to the lack of the
806 // formal specification of the linker script. We use heuristics to
807 // determine whether a new output command should be added before or
808 // after another commands. For the details, look at shouldSkip
809 // function.
810 void LinkerScript::placeOrphanSections() {
811   // The OutputSections are already in the correct order.
812   // This loops creates or moves commands as needed so that they are in the
813   // correct order.
814   int CmdIndex = 0;
815
816   // As a horrible special case, skip the first . assignment if it is before any
817   // section. We do this because it is common to set a load address by starting
818   // the script with ". = 0xabcd" and the expectation is that every section is
819   // after that.
820   auto FirstSectionOrDotAssignment =
821       std::find_if(Opt.Commands.begin(), Opt.Commands.end(),
822                    [](BaseCommand *Cmd) { return !shouldSkip(Cmd); });
823   if (FirstSectionOrDotAssignment != Opt.Commands.end()) {
824     CmdIndex = FirstSectionOrDotAssignment - Opt.Commands.begin();
825     if (isa<SymbolAssignment>(**FirstSectionOrDotAssignment))
826       ++CmdIndex;
827   }
828
829   for (OutputSection *Sec : *OutputSections) {
830     StringRef Name = Sec->Name;
831
832     // Find the last spot where we can insert a command and still get the
833     // correct result.
834     auto CmdIter = Opt.Commands.begin() + CmdIndex;
835     auto E = Opt.Commands.end();
836     while (CmdIter != E && shouldSkip(*CmdIter)) {
837       ++CmdIter;
838       ++CmdIndex;
839     }
840
841     // If there is no command corresponding to this output section,
842     // create one and put a InputSectionDescription in it so that both
843     // representations agree on which input sections to use.
844     OutputSectionCommand *Cmd = getCmd(Sec);
845     if (!Cmd) {
846       Cmd = createOutputSectionCommand(Name, "<internal>");
847       Opt.Commands.insert(CmdIter, Cmd);
848       ++CmdIndex;
849
850       Cmd->Sec = Sec;
851       SecToCommand[Sec] = Cmd;
852       auto *ISD = make<InputSectionDescription>("");
853       for (InputSection *IS : Sec->Sections)
854         ISD->Sections.push_back(IS);
855       Cmd->Commands.push_back(ISD);
856
857       continue;
858     }
859
860     // Continue from where we found it.
861     while (*CmdIter != Cmd) {
862       ++CmdIter;
863       ++CmdIndex;
864     }
865     ++CmdIndex;
866   }
867 }
868
869 void LinkerScript::processNonSectionCommands() {
870   for (BaseCommand *Base : Opt.Commands) {
871     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base))
872       assignSymbol(Cmd, false);
873     else if (auto *Cmd = dyn_cast<AssertCommand>(Base))
874       Cmd->Expression();
875   }
876 }
877
878 // Do a last effort at synchronizing the linker script "AST" and the section
879 // list. This is needed to account for last minute changes, like adding a
880 // .ARM.exidx terminator and sorting SHF_LINK_ORDER sections.
881 //
882 // FIXME: We should instead create the "AST" earlier and the above changes would
883 // be done directly in the "AST".
884 //
885 // This can only handle new sections being added and sections being reordered.
886 void LinkerScript::synchronize() {
887   for (BaseCommand *Base : Opt.Commands) {
888     auto *Cmd = dyn_cast<OutputSectionCommand>(Base);
889     if (!Cmd)
890       continue;
891     ArrayRef<InputSection *> Sections = Cmd->Sec->Sections;
892     std::vector<InputSection **> ScriptSections;
893     DenseSet<InputSection *> ScriptSectionsSet;
894     for (BaseCommand *Base : Cmd->Commands) {
895       auto *ISD = dyn_cast<InputSectionDescription>(Base);
896       if (!ISD)
897         continue;
898       for (InputSection *&IS : ISD->Sections) {
899         if (IS->Live) {
900           ScriptSections.push_back(&IS);
901           ScriptSectionsSet.insert(IS);
902         }
903       }
904     }
905     std::vector<InputSection *> Missing;
906     for (InputSection *IS : Sections)
907       if (!ScriptSectionsSet.count(IS))
908         Missing.push_back(IS);
909     if (!Missing.empty()) {
910       auto ISD = make<InputSectionDescription>("");
911       ISD->Sections = Missing;
912       Cmd->Commands.push_back(ISD);
913       for (InputSection *&IS : ISD->Sections)
914         if (IS->Live)
915           ScriptSections.push_back(&IS);
916     }
917     assert(ScriptSections.size() == Sections.size());
918     for (int I = 0, N = Sections.size(); I < N; ++I)
919       *ScriptSections[I] = Sections[I];
920   }
921 }
922
923 static bool
924 allocateHeaders(std::vector<PhdrEntry> &Phdrs,
925                 ArrayRef<OutputSectionCommand *> OutputSectionCommands,
926                 uint64_t Min) {
927   auto FirstPTLoad =
928       std::find_if(Phdrs.begin(), Phdrs.end(),
929                    [](const PhdrEntry &E) { return E.p_type == PT_LOAD; });
930   if (FirstPTLoad == Phdrs.end())
931     return false;
932
933   uint64_t HeaderSize = getHeaderSize();
934   if (HeaderSize <= Min || Script->hasPhdrsCommands()) {
935     Min = alignDown(Min - HeaderSize, Config->MaxPageSize);
936     Out::ElfHeader->Addr = Min;
937     Out::ProgramHeaders->Addr = Min + Out::ElfHeader->Size;
938     return true;
939   }
940
941   assert(FirstPTLoad->First == Out::ElfHeader);
942   OutputSection *ActualFirst = nullptr;
943   for (OutputSectionCommand *Cmd : OutputSectionCommands) {
944     OutputSection *Sec = Cmd->Sec;
945     if (Sec->FirstInPtLoad == Out::ElfHeader) {
946       ActualFirst = Sec;
947       break;
948     }
949   }
950   if (ActualFirst) {
951     for (OutputSectionCommand *Cmd : OutputSectionCommands) {
952       OutputSection *Sec = Cmd->Sec;
953       if (Sec->FirstInPtLoad == Out::ElfHeader)
954         Sec->FirstInPtLoad = ActualFirst;
955     }
956     FirstPTLoad->First = ActualFirst;
957   } else {
958     Phdrs.erase(FirstPTLoad);
959   }
960
961   auto PhdrI = std::find_if(Phdrs.begin(), Phdrs.end(), [](const PhdrEntry &E) {
962     return E.p_type == PT_PHDR;
963   });
964   if (PhdrI != Phdrs.end())
965     Phdrs.erase(PhdrI);
966   return false;
967 }
968
969 void LinkerScript::assignAddresses(
970     std::vector<PhdrEntry> &Phdrs,
971     ArrayRef<OutputSectionCommand *> OutputSectionCommands) {
972   // Assign addresses as instructed by linker script SECTIONS sub-commands.
973   Dot = 0;
974   ErrorOnMissingSection = true;
975   switchTo(Aether);
976
977   for (BaseCommand *Base : Opt.Commands) {
978     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base)) {
979       assignSymbol(Cmd, false);
980       continue;
981     }
982
983     if (auto *Cmd = dyn_cast<AssertCommand>(Base)) {
984       Cmd->Expression();
985       continue;
986     }
987
988     auto *Cmd = cast<OutputSectionCommand>(Base);
989     assignOffsets(Cmd);
990   }
991
992   uint64_t MinVA = std::numeric_limits<uint64_t>::max();
993   for (OutputSectionCommand *Cmd : OutputSectionCommands) {
994     OutputSection *Sec = Cmd->Sec;
995     if (Sec->Flags & SHF_ALLOC)
996       MinVA = std::min<uint64_t>(MinVA, Sec->Addr);
997     else
998       Sec->Addr = 0;
999   }
1000
1001   allocateHeaders(Phdrs, OutputSectionCommands, MinVA);
1002 }
1003
1004 // Creates program headers as instructed by PHDRS linker script command.
1005 std::vector<PhdrEntry> LinkerScript::createPhdrs() {
1006   std::vector<PhdrEntry> Ret;
1007
1008   // Process PHDRS and FILEHDR keywords because they are not
1009   // real output sections and cannot be added in the following loop.
1010   for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
1011     Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
1012     PhdrEntry &Phdr = Ret.back();
1013
1014     if (Cmd.HasFilehdr)
1015       Phdr.add(Out::ElfHeader);
1016     if (Cmd.HasPhdrs)
1017       Phdr.add(Out::ProgramHeaders);
1018
1019     if (Cmd.LMAExpr) {
1020       Phdr.p_paddr = Cmd.LMAExpr().getValue();
1021       Phdr.HasLMA = true;
1022     }
1023   }
1024
1025   // Add output sections to program headers.
1026   for (OutputSection *Sec : *OutputSections) {
1027     if (!(Sec->Flags & SHF_ALLOC))
1028       break;
1029
1030     // Assign headers specified by linker script
1031     for (size_t Id : getPhdrIndices(Sec)) {
1032       Ret[Id].add(Sec);
1033       if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
1034         Ret[Id].p_flags |= Sec->getPhdrFlags();
1035     }
1036   }
1037   return Ret;
1038 }
1039
1040 bool LinkerScript::ignoreInterpSection() {
1041   // Ignore .interp section in case we have PHDRS specification
1042   // and PT_INTERP isn't listed.
1043   if (Opt.PhdrsCommands.empty())
1044     return false;
1045   for (PhdrsCommand &Cmd : Opt.PhdrsCommands)
1046     if (Cmd.Type == PT_INTERP)
1047       return false;
1048   return true;
1049 }
1050
1051 OutputSectionCommand *LinkerScript::getCmd(OutputSection *Sec) const {
1052   auto I = SecToCommand.find(Sec);
1053   if (I == SecToCommand.end())
1054     return nullptr;
1055   return I->second;
1056 }
1057
1058 uint32_t OutputSectionCommand::getFiller() {
1059   if (Filler)
1060     return *Filler;
1061   if (Sec->Flags & SHF_EXECINSTR)
1062     return Target->TrapInstr;
1063   return 0;
1064 }
1065
1066 static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) {
1067   if (Size == 1)
1068     *Buf = Data;
1069   else if (Size == 2)
1070     write16(Buf, Data, Config->Endianness);
1071   else if (Size == 4)
1072     write32(Buf, Data, Config->Endianness);
1073   else if (Size == 8)
1074     write64(Buf, Data, Config->Endianness);
1075   else
1076     llvm_unreachable("unsupported Size argument");
1077 }
1078
1079 // Compress section contents if this section contains debug info.
1080 template <class ELFT> void OutputSectionCommand::maybeCompress() {
1081   typedef typename ELFT::Chdr Elf_Chdr;
1082
1083   // Compress only DWARF debug sections.
1084   if (!Config->CompressDebugSections || (Sec->Flags & SHF_ALLOC) ||
1085       !Name.startswith(".debug_"))
1086     return;
1087
1088   // Create a section header.
1089   Sec->ZDebugHeader.resize(sizeof(Elf_Chdr));
1090   auto *Hdr = reinterpret_cast<Elf_Chdr *>(Sec->ZDebugHeader.data());
1091   Hdr->ch_type = ELFCOMPRESS_ZLIB;
1092   Hdr->ch_size = Sec->Size;
1093   Hdr->ch_addralign = Sec->Alignment;
1094
1095   // Write section contents to a temporary buffer and compress it.
1096   std::vector<uint8_t> Buf(Sec->Size);
1097   writeTo<ELFT>(Buf.data());
1098   if (Error E = zlib::compress(toStringRef(Buf), Sec->CompressedData))
1099     fatal("compress failed: " + llvm::toString(std::move(E)));
1100
1101   // Update section headers.
1102   Sec->Size = sizeof(Elf_Chdr) + Sec->CompressedData.size();
1103   Sec->Flags |= SHF_COMPRESSED;
1104 }
1105
1106 template <class ELFT> void OutputSectionCommand::writeTo(uint8_t *Buf) {
1107   Sec->Loc = Buf;
1108
1109   // We may have already rendered compressed content when using
1110   // -compress-debug-sections option. Write it together with header.
1111   if (!Sec->CompressedData.empty()) {
1112     memcpy(Buf, Sec->ZDebugHeader.data(), Sec->ZDebugHeader.size());
1113     memcpy(Buf + Sec->ZDebugHeader.size(), Sec->CompressedData.data(),
1114            Sec->CompressedData.size());
1115     return;
1116   }
1117
1118   if (Sec->Type == SHT_NOBITS)
1119     return;
1120
1121   // Write leading padding.
1122   std::vector<InputSection *> Sections;
1123   for (BaseCommand *Cmd : Commands)
1124     if (auto *ISD = dyn_cast<InputSectionDescription>(Cmd))
1125       for (InputSection *IS : ISD->Sections)
1126         if (IS->Live)
1127           Sections.push_back(IS);
1128   uint32_t Filler = getFiller();
1129   if (Filler)
1130     fill(Buf, Sections.empty() ? Sec->Size : Sections[0]->OutSecOff, Filler);
1131
1132   parallelForEachN(0, Sections.size(), [=](size_t I) {
1133     InputSection *IS = Sections[I];
1134     IS->writeTo<ELFT>(Buf);
1135
1136     // Fill gaps between sections.
1137     if (Filler) {
1138       uint8_t *Start = Buf + IS->OutSecOff + IS->getSize();
1139       uint8_t *End;
1140       if (I + 1 == Sections.size())
1141         End = Buf + Sec->Size;
1142       else
1143         End = Buf + Sections[I + 1]->OutSecOff;
1144       fill(Start, End - Start, Filler);
1145     }
1146   });
1147
1148   // Linker scripts may have BYTE()-family commands with which you
1149   // can write arbitrary bytes to the output. Process them if any.
1150   for (BaseCommand *Base : Commands)
1151     if (auto *Data = dyn_cast<BytesDataCommand>(Base))
1152       writeInt(Buf + Data->Offset, Data->Expression().getValue(), Data->Size);
1153 }
1154
1155 bool LinkerScript::hasLMA(OutputSection *Sec) {
1156   if (OutputSectionCommand *Cmd = getCmd(Sec))
1157     if (Cmd->LMAExpr)
1158       return true;
1159   return false;
1160 }
1161
1162 ExprValue LinkerScript::getSymbolValue(const Twine &Loc, StringRef S) {
1163   if (S == ".")
1164     return {CurOutSec, Dot - CurOutSec->Addr};
1165   if (SymbolBody *B = findSymbol(S)) {
1166     if (auto *D = dyn_cast<DefinedRegular>(B))
1167       return {D->Section, D->Value};
1168     if (auto *C = dyn_cast<DefinedCommon>(B))
1169       return {InX::Common, C->Offset};
1170   }
1171   error(Loc + ": symbol not found: " + S);
1172   return 0;
1173 }
1174
1175 bool LinkerScript::isDefined(StringRef S) { return findSymbol(S) != nullptr; }
1176
1177 // Returns indices of ELF headers containing specific section. Each index is a
1178 // zero based number of ELF header listed within PHDRS {} script block.
1179 std::vector<size_t> LinkerScript::getPhdrIndices(OutputSection *Sec) {
1180   if (OutputSectionCommand *Cmd = getCmd(Sec)) {
1181     std::vector<size_t> Ret;
1182     for (StringRef PhdrName : Cmd->Phdrs)
1183       Ret.push_back(getPhdrIndex(Cmd->Location, PhdrName));
1184     return Ret;
1185   }
1186   return {};
1187 }
1188
1189 size_t LinkerScript::getPhdrIndex(const Twine &Loc, StringRef PhdrName) {
1190   size_t I = 0;
1191   for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
1192     if (Cmd.Name == PhdrName)
1193       return I;
1194     ++I;
1195   }
1196   error(Loc + ": section header '" + PhdrName + "' is not listed in PHDRS");
1197   return 0;
1198 }
1199
1200 template void OutputSectionCommand::writeTo<ELF32LE>(uint8_t *Buf);
1201 template void OutputSectionCommand::writeTo<ELF32BE>(uint8_t *Buf);
1202 template void OutputSectionCommand::writeTo<ELF64LE>(uint8_t *Buf);
1203 template void OutputSectionCommand::writeTo<ELF64BE>(uint8_t *Buf);
1204
1205 template void OutputSectionCommand::maybeCompress<ELF32LE>();
1206 template void OutputSectionCommand::maybeCompress<ELF32BE>();
1207 template void OutputSectionCommand::maybeCompress<ELF64LE>();
1208 template void OutputSectionCommand::maybeCompress<ELF64BE>();