1f7c5fbb1SRui Ueyama //===- LinkerScript.cpp ---------------------------------------------------===//
2f7c5fbb1SRui Ueyama //
3f7c5fbb1SRui Ueyama //                             The LLVM Linker
4f7c5fbb1SRui Ueyama //
5f7c5fbb1SRui Ueyama // This file is distributed under the University of Illinois Open Source
6f7c5fbb1SRui Ueyama // License. See LICENSE.TXT for details.
7f7c5fbb1SRui Ueyama //
8f7c5fbb1SRui Ueyama //===----------------------------------------------------------------------===//
9f7c5fbb1SRui Ueyama //
10f7c5fbb1SRui Ueyama // This file contains the parser/evaluator of the linker script.
11f7c5fbb1SRui Ueyama //
12f7c5fbb1SRui Ueyama //===----------------------------------------------------------------------===//
13f7c5fbb1SRui Ueyama 
14717677afSRui Ueyama #include "LinkerScript.h"
15f7c5fbb1SRui Ueyama #include "Config.h"
161ebc8ed7SRui Ueyama #include "InputSection.h"
179381eb10SRui Ueyama #include "Memory.h"
18652852c5SGeorge Rimar #include "OutputSections.h"
1993c9af42SRui Ueyama #include "Strings.h"
20f7c5fbb1SRui Ueyama #include "SymbolTable.h"
2155518e7dSRui Ueyama #include "Symbols.h"
223fb5a6dcSGeorge Rimar #include "SyntheticSections.h"
2355b169bfSRafael Espindola #include "Target.h"
2455b169bfSRafael Espindola #include "Threads.h"
25bbe38602SEugene Leviant #include "Writer.h"
2622886a28SEugene Zelenko #include "llvm/ADT/STLExtras.h"
2722886a28SEugene Zelenko #include "llvm/ADT/StringRef.h"
28264b5d9eSZachary Turner #include "llvm/BinaryFormat/ELF.h"
2922886a28SEugene Zelenko #include "llvm/Support/Casting.h"
3022886a28SEugene Zelenko #include "llvm/Support/Endian.h"
3122886a28SEugene Zelenko #include "llvm/Support/ErrorHandling.h"
32f7c5fbb1SRui Ueyama #include "llvm/Support/FileSystem.h"
33f03f3cc1SRui Ueyama #include "llvm/Support/Path.h"
3422886a28SEugene Zelenko #include <algorithm>
3522886a28SEugene Zelenko #include <cassert>
3622886a28SEugene Zelenko #include <cstddef>
3722886a28SEugene Zelenko #include <cstdint>
3822886a28SEugene Zelenko #include <iterator>
3922886a28SEugene Zelenko #include <limits>
4022886a28SEugene Zelenko #include <string>
4122886a28SEugene Zelenko #include <vector>
42f7c5fbb1SRui Ueyama 
43f7c5fbb1SRui Ueyama using namespace llvm;
44652852c5SGeorge Rimar using namespace llvm::ELF;
451ebc8ed7SRui Ueyama using namespace llvm::object;
46e38cbab5SGeorge Rimar using namespace llvm::support::endian;
47f7c5fbb1SRui Ueyama using namespace lld;
48e0df00b9SRafael Espindola using namespace lld::elf;
49f7c5fbb1SRui Ueyama 
50a34da938SRui Ueyama LinkerScript *elf::Script;
51a34da938SRui Ueyama 
525d0ea70aSGeorge Rimar static uint64_t getOutputSectionVA(SectionBase *InputSec, StringRef Loc) {
535d0ea70aSGeorge Rimar   if (OutputSection *OS = InputSec->getOutputSection())
545d0ea70aSGeorge Rimar     return OS->Addr;
555d0ea70aSGeorge Rimar   error(Loc + ": unable to evaluate expression: input section " +
565d0ea70aSGeorge Rimar         InputSec->Name + " has no output section assigned");
575d0ea70aSGeorge Rimar   return 0;
58608cf670SGeorge Rimar }
595d0ea70aSGeorge Rimar 
605d0ea70aSGeorge Rimar uint64_t ExprValue::getValue() const {
615d0ea70aSGeorge Rimar   if (Sec)
625d0ea70aSGeorge Rimar     return alignTo(Sec->getOffset(Val) + getOutputSectionVA(Sec, Loc),
635d0ea70aSGeorge Rimar                    Alignment);
643c6de1a6SPetr Hosek   return alignTo(Val, Alignment);
6572dc195dSRafael Espindola }
6672dc195dSRafael Espindola 
677ba5f47eSRafael Espindola uint64_t ExprValue::getSecAddr() const {
687ba5f47eSRafael Espindola   if (Sec)
695d0ea70aSGeorge Rimar     return Sec->getOffset(0) + getOutputSectionVA(Sec, Loc);
707ba5f47eSRafael Espindola   return 0;
717ba5f47eSRafael Espindola }
727ba5f47eSRafael Espindola 
73a6acd23cSRafael Espindola uint64_t ExprValue::getSectionOffset() const {
748b250344SRafael Espindola   // If the alignment is trivial, we don't have to compute the full
758b250344SRafael Espindola   // value to know the offset. This allows this function to succeed in
768b250344SRafael Espindola   // cases where the output section is not yet known.
778b250344SRafael Espindola   if (Alignment == 1)
788b250344SRafael Espindola     return Val;
79a6acd23cSRafael Espindola   return getValue() - getSecAddr();
80a6acd23cSRafael Espindola }
81a6acd23cSRafael Espindola 
82a5e8dd35SRafael Espindola static SymbolBody *addRegular(SymbolAssignment *Cmd) {
835e51f7d2SPetr Hosek   Symbol *Sym;
843dabfc6bSRafael Espindola   uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
85244ef981SRafael Espindola   std::tie(Sym, std::ignore) = Symtab->insert(Cmd->Name, /*Type*/ 0, Visibility,
86244ef981SRafael Espindola                                               /*CanOmitFromDynSym*/ false,
875e51f7d2SPetr Hosek                                               /*File*/ nullptr);
885e51f7d2SPetr Hosek   Sym->Binding = STB_GLOBAL;
8972dc195dSRafael Espindola   ExprValue Value = Cmd->Expression();
9072dc195dSRafael Espindola   SectionBase *Sec = Value.isAbsolute() ? nullptr : Value.Sec;
9101aa795fSGeorge Rimar 
9201aa795fSGeorge Rimar   // We want to set symbol values early if we can. This allows us to use symbols
9301aa795fSGeorge Rimar   // as variables in linker scripts. Doing so allows us to write expressions
9401aa795fSGeorge Rimar   // like this: `alignment = 16; . = ALIGN(., alignment)`
95e4bad83eSRafael Espindola   uint64_t SymValue = Value.Sec ? 0 : Value.getValue();
966e93d054SRafael Espindola   replaceBody<DefinedRegular>(Sym, nullptr, Cmd->Name, /*IsLocal=*/false,
976e93d054SRafael Espindola                               Visibility, STT_NOTYPE, SymValue, 0, Sec);
988f1f3c40SMeador Inge   return Sym->body();
99ceabe80eSEugene Leviant }
100ceabe80eSEugene Leviant 
1018c022ca7SRafael Espindola OutputSection *LinkerScript::createOutputSection(StringRef Name,
1028c022ca7SRafael Espindola                                                  StringRef Location) {
1038c022ca7SRafael Espindola   OutputSection *&SecRef = NameToOutputSection[Name];
1048c022ca7SRafael Espindola   OutputSection *Sec;
1058c022ca7SRafael Espindola   if (SecRef && SecRef->Location.empty()) {
10605c4f67cSRafael Espindola     // There was a forward reference.
1078c022ca7SRafael Espindola     Sec = SecRef;
10805c4f67cSRafael Espindola   } else {
1098c022ca7SRafael Espindola     Sec = make<OutputSection>(Name, SHT_PROGBITS, 0);
1108c022ca7SRafael Espindola     if (!SecRef)
1118c022ca7SRafael Espindola       SecRef = Sec;
11205c4f67cSRafael Espindola   }
1138c022ca7SRafael Espindola   Sec->Location = Location;
1148c022ca7SRafael Espindola   return Sec;
115851dc1e8SGeorge Rimar }
116851dc1e8SGeorge Rimar 
1178c022ca7SRafael Espindola OutputSection *LinkerScript::getOrCreateOutputSection(StringRef Name) {
1188c022ca7SRafael Espindola   OutputSection *&CmdRef = NameToOutputSection[Name];
11905c4f67cSRafael Espindola   if (!CmdRef)
1208c022ca7SRafael Espindola     CmdRef = make<OutputSection>(Name, SHT_PROGBITS, 0);
12105c4f67cSRafael Espindola   return CmdRef;
122d83ce1b4SGeorge Rimar }
123d83ce1b4SGeorge Rimar 
124b8dd23f5SRui Ueyama void LinkerScript::setDot(Expr E, const Twine &Loc, bool InSec) {
12572dc195dSRafael Espindola   uint64_t Val = E().getValue();
1268c804d97SGeorge Rimar   if (Val < Dot && InSec)
1272ee2d2dcSGeorge Rimar     error(Loc + ": unable to move location counter backward for: " +
128906e9a18SPeter Smith           CurAddressState->OutSec->Name);
1294cd7352cSRafael Espindola   Dot = Val;
1304cd7352cSRafael Espindola   // Update to location counter means update to section size.
1314cd7352cSRafael Espindola   if (InSec)
132906e9a18SPeter Smith     CurAddressState->OutSec->Size = Dot - CurAddressState->OutSec->Addr;
133679828ffSRafael Espindola }
134679828ffSRafael Espindola 
135679828ffSRafael Espindola // Sets value of a symbol. Two kinds of symbols are processed: synthetic
136679828ffSRafael Espindola // symbols, whose value is an offset from beginning of section and regular
137679828ffSRafael Espindola // symbols whose value is absolute.
138b8dd23f5SRui Ueyama void LinkerScript::assignSymbol(SymbolAssignment *Cmd, bool InSec) {
139679828ffSRafael Espindola   if (Cmd->Name == ".") {
1402ee2d2dcSGeorge Rimar     setDot(Cmd->Expression, Cmd->Location, InSec);
1414cd7352cSRafael Espindola     return;
1424cd7352cSRafael Espindola   }
1434cd7352cSRafael Espindola 
144b2b70975SGeorge Rimar   if (!Cmd->Sym)
1458f1f3c40SMeador Inge     return;
1468f1f3c40SMeador Inge 
1475616adf6SRafael Espindola   auto *Sym = cast<DefinedRegular>(Cmd->Sym);
14872dc195dSRafael Espindola   ExprValue V = Cmd->Expression();
14972dc195dSRafael Espindola   if (V.isAbsolute()) {
15072dc195dSRafael Espindola     Sym->Value = V.getValue();
1519be24cf5SRafael Espindola     Sym->Section = nullptr;
15272dc195dSRafael Espindola   } else {
15372dc195dSRafael Espindola     Sym->Section = V.Sec;
154a6acd23cSRafael Espindola     Sym->Value = V.getSectionOffset();
155ea590d91SRafael Espindola   }
1568f1f3c40SMeador Inge }
1578f1f3c40SMeador Inge 
158b8dd23f5SRui Ueyama void LinkerScript::addSymbol(SymbolAssignment *Cmd) {
1591602421cSRui Ueyama   if (Cmd->Name == ".")
1608f1f3c40SMeador Inge     return;
1618f1f3c40SMeador Inge 
1628f1f3c40SMeador Inge   // If a symbol was in PROVIDE(), we need to define it only when
1638f1f3c40SMeador Inge   // it is a referenced undefined symbol.
164244ef981SRafael Espindola   SymbolBody *B = Symtab->find(Cmd->Name);
1658f1f3c40SMeador Inge   if (Cmd->Provide && (!B || B->isDefined()))
1668f1f3c40SMeador Inge     return;
1678f1f3c40SMeador Inge 
168a5e8dd35SRafael Espindola   Cmd->Sym = addRegular(Cmd);
169ceabe80eSEugene Leviant }
170ceabe80eSEugene Leviant 
171076fe157SGeorge Rimar bool SymbolAssignment::classof(const BaseCommand *C) {
172076fe157SGeorge Rimar   return C->Kind == AssignmentKind;
173076fe157SGeorge Rimar }
174076fe157SGeorge Rimar 
175eea3114fSGeorge Rimar bool InputSectionDescription::classof(const BaseCommand *C) {
176eea3114fSGeorge Rimar   return C->Kind == InputSectionKind;
177eea3114fSGeorge Rimar }
178eea3114fSGeorge Rimar 
179eefa758eSGeorge Rimar bool AssertCommand::classof(const BaseCommand *C) {
180eefa758eSGeorge Rimar   return C->Kind == AssertKind;
181eefa758eSGeorge Rimar }
182eefa758eSGeorge Rimar 
183e38cbab5SGeorge Rimar bool BytesDataCommand::classof(const BaseCommand *C) {
184e38cbab5SGeorge Rimar   return C->Kind == BytesDataKind;
185e38cbab5SGeorge Rimar }
186e38cbab5SGeorge Rimar 
1871e30f07cSDmitry Mikulin static std::string filename(InputFile *File) {
1881e30f07cSDmitry Mikulin   if (!File)
189e0be2901SRui Ueyama     return "";
1901e30f07cSDmitry Mikulin   if (File->ArchiveName.empty())
1911e30f07cSDmitry Mikulin     return File->getName();
1921e30f07cSDmitry Mikulin   return (File->ArchiveName + "(" + File->getName() + ")").str();
193e0be2901SRui Ueyama }
194e0be2901SRui Ueyama 
195b8dd23f5SRui Ueyama bool LinkerScript::shouldKeep(InputSectionBase *S) {
196f300ca21SDmitry Mikulin   for (InputSectionDescription *ID : Opt.KeptSections) {
1971e30f07cSDmitry Mikulin     std::string Filename = filename(S->File);
198f300ca21SDmitry Mikulin     if (ID->FilePat.match(Filename))
199cf43f179SEugene Leviant       for (SectionPattern &P : ID->SectionPatterns)
200f91282e1SRui Ueyama         if (P.SectionPat.match(S->Name))
201eea3114fSGeorge Rimar           return true;
202f300ca21SDmitry Mikulin   }
203eea3114fSGeorge Rimar   return false;
204eea3114fSGeorge Rimar }
205eea3114fSGeorge Rimar 
206ea93fe00SRui Ueyama // A helper function for the SORT() command.
207c404d50dSRafael Espindola static std::function<bool(InputSectionBase *, InputSectionBase *)>
208be394db3SGeorge Rimar getComparator(SortSectionPolicy K) {
209be394db3SGeorge Rimar   switch (K) {
210be394db3SGeorge Rimar   case SortSectionPolicy::Alignment:
211ea93fe00SRui Ueyama     return [](InputSectionBase *A, InputSectionBase *B) {
212ea93fe00SRui Ueyama       // ">" is not a mistake. Sections with larger alignments are placed
213ea93fe00SRui Ueyama       // before sections with smaller alignments in order to reduce the
214ea93fe00SRui Ueyama       // amount of padding necessary. This is compatible with GNU.
215ea93fe00SRui Ueyama       return A->Alignment > B->Alignment;
216ea93fe00SRui Ueyama     };
217be394db3SGeorge Rimar   case SortSectionPolicy::Name:
218ea93fe00SRui Ueyama     return [](InputSectionBase *A, InputSectionBase *B) {
219ea93fe00SRui Ueyama       return A->Name < B->Name;
220ea93fe00SRui Ueyama     };
221be394db3SGeorge Rimar   case SortSectionPolicy::Priority:
222ea93fe00SRui Ueyama     return [](InputSectionBase *A, InputSectionBase *B) {
223ea93fe00SRui Ueyama       return getPriority(A->Name) < getPriority(B->Name);
224ea93fe00SRui Ueyama     };
225be394db3SGeorge Rimar   default:
226be394db3SGeorge Rimar     llvm_unreachable("unknown sort policy");
227be394db3SGeorge Rimar   }
228742c3836SRui Ueyama }
2290702c4e8SGeorge Rimar 
230ea93fe00SRui Ueyama // A helper function for the SORT() command.
231b4c9b81aSRafael Espindola static bool matchConstraints(ArrayRef<InputSectionBase *> Sections,
23206ae6836SGeorge Rimar                              ConstraintKind Kind) {
2338f66df92SGeorge Rimar   if (Kind == ConstraintKind::NoConstraint)
2348f66df92SGeorge Rimar     return true;
2352c7171bfSRui Ueyama 
2362c7171bfSRui Ueyama   bool IsRW = llvm::any_of(Sections, [](InputSectionBase *Sec) {
2372c7171bfSRui Ueyama     return static_cast<InputSectionBase *>(Sec)->Flags & SHF_WRITE;
23806ae6836SGeorge Rimar   });
2392c7171bfSRui Ueyama 
240e746e52cSRafael Espindola   return (IsRW && Kind == ConstraintKind::ReadWrite) ||
241e746e52cSRafael Espindola          (!IsRW && Kind == ConstraintKind::ReadOnly);
24206ae6836SGeorge Rimar }
24306ae6836SGeorge Rimar 
2446a1aa8d9SRafael Espindola static void sortSections(InputSection **Begin, InputSection **End,
245ee924709SRui Ueyama                          SortSectionPolicy K) {
246ee924709SRui Ueyama   if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
24707171f21SGeorge Rimar     std::stable_sort(Begin, End, getComparator(K));
248ee924709SRui Ueyama }
249ee924709SRui Ueyama 
250d6bcde38SGeorge Rimar static void sortBySymbolOrder(InputSection **Begin, InputSection **End) {
251d6bcde38SGeorge Rimar   if (Config->SymbolOrderingFile.empty())
252d6bcde38SGeorge Rimar     return;
253696a7f9aSGeorge Rimar   static llvm::DenseMap<SectionBase *, int> Order = buildSectionOrder();
254d6bcde38SGeorge Rimar   MutableArrayRef<InputSection *> In(Begin, End - Begin);
255d6bcde38SGeorge Rimar   sortByOrder(In, [&](InputSectionBase *S) { return Order.lookup(S); });
256d6bcde38SGeorge Rimar }
257d6bcde38SGeorge Rimar 
258d3190795SRafael Espindola // Compute and remember which sections the InputSectionDescription matches.
2596a1aa8d9SRafael Espindola std::vector<InputSection *>
26072e107f3SRui Ueyama LinkerScript::computeInputSections(const InputSectionDescription *Cmd) {
2616a1aa8d9SRafael Espindola   std::vector<InputSection *> Ret;
2628c6a5aafSRui Ueyama 
26372e107f3SRui Ueyama   // Collects all sections that satisfy constraints of Cmd.
26472e107f3SRui Ueyama   for (const SectionPattern &Pat : Cmd->SectionPatterns) {
26572e107f3SRui Ueyama     size_t SizeBefore = Ret.size();
26672e107f3SRui Ueyama 
26772e107f3SRui Ueyama     for (InputSectionBase *Sec : InputSections) {
26872e107f3SRui Ueyama       if (Sec->Assigned)
2698c6a5aafSRui Ueyama         continue;
27072e107f3SRui Ueyama 
271e39709b2SRafael Espindola       if (!Sec->Live) {
272e39709b2SRafael Espindola         reportDiscarded(Sec);
273e39709b2SRafael Espindola         continue;
274e39709b2SRafael Espindola       }
275e39709b2SRafael Espindola 
276908a3d34SRafael Espindola       // For -emit-relocs we have to ignore entries like
277908a3d34SRafael Espindola       //   .rela.dyn : { *(.rela.data) }
278908a3d34SRafael Espindola       // which are common because they are in the default bfd script.
27972e107f3SRui Ueyama       if (Sec->Type == SHT_REL || Sec->Type == SHT_RELA)
280908a3d34SRafael Espindola         continue;
2818c6a5aafSRui Ueyama 
2821e30f07cSDmitry Mikulin       std::string Filename = filename(Sec->File);
28372e107f3SRui Ueyama       if (!Cmd->FilePat.match(Filename) ||
28472e107f3SRui Ueyama           Pat.ExcludedFilePat.match(Filename) ||
28572e107f3SRui Ueyama           !Pat.SectionPat.match(Sec->Name))
286e0be2901SRui Ueyama         continue;
28772e107f3SRui Ueyama 
2886a1aa8d9SRafael Espindola       Ret.push_back(cast<InputSection>(Sec));
28972e107f3SRui Ueyama       Sec->Assigned = true;
290f94efdddSRui Ueyama     }
291d3190795SRafael Espindola 
292ee924709SRui Ueyama     // Sort sections as instructed by SORT-family commands and --sort-section
293ee924709SRui Ueyama     // option. Because SORT-family commands can be nested at most two depth
294ee924709SRui Ueyama     // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
295ee924709SRui Ueyama     // line option is respected even if a SORT command is given, the exact
296ee924709SRui Ueyama     // behavior we have here is a bit complicated. Here are the rules.
297ee924709SRui Ueyama     //
298ee924709SRui Ueyama     // 1. If two SORT commands are given, --sort-section is ignored.
299ee924709SRui Ueyama     // 2. If one SORT command is given, and if it is not SORT_NONE,
300ee924709SRui Ueyama     //    --sort-section is handled as an inner SORT command.
301ee924709SRui Ueyama     // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
302ee924709SRui Ueyama     // 4. If no SORT command is given, sort according to --sort-section.
303d6bcde38SGeorge Rimar     // 5. If no SORT commands are given and --sort-section is not specified,
304d6bcde38SGeorge Rimar     //    apply sorting provided by --symbol-ordering-file if any exist.
3056a1aa8d9SRafael Espindola     InputSection **Begin = Ret.data() + SizeBefore;
3066a1aa8d9SRafael Espindola     InputSection **End = Ret.data() + Ret.size();
307d6bcde38SGeorge Rimar     if (Pat.SortOuter == SortSectionPolicy::Default &&
308d6bcde38SGeorge Rimar         Config->SortSection == SortSectionPolicy::Default) {
309d6bcde38SGeorge Rimar       sortBySymbolOrder(Begin, End);
310d6bcde38SGeorge Rimar       continue;
311d6bcde38SGeorge Rimar     }
31207171f21SGeorge Rimar     if (Pat.SortOuter != SortSectionPolicy::None) {
31307171f21SGeorge Rimar       if (Pat.SortInner == SortSectionPolicy::Default)
31407171f21SGeorge Rimar         sortSections(Begin, End, Config->SortSection);
315ee924709SRui Ueyama       else
31607171f21SGeorge Rimar         sortSections(Begin, End, Pat.SortInner);
31707171f21SGeorge Rimar       sortSections(Begin, End, Pat.SortOuter);
31807171f21SGeorge Rimar     }
319ee924709SRui Ueyama   }
32072e107f3SRui Ueyama   return Ret;
321be94e1b6SRafael Espindola }
322be94e1b6SRafael Espindola 
323b8dd23f5SRui Ueyama void LinkerScript::discard(ArrayRef<InputSectionBase *> V) {
324b4c9b81aSRafael Espindola   for (InputSectionBase *S : V) {
325be94e1b6SRafael Espindola     S->Live = false;
3261e30f07cSDmitry Mikulin     if (S == InX::ShStrTab || S == InX::Dynamic || S == InX::DynSymTab ||
3271e30f07cSDmitry Mikulin         S == InX::DynStrTab)
3282af64b0bSRafael Espindola       error("discarding " + S->Name + " section is not allowed");
329647c1685SGeorge Rimar     discard(S->DependentSections);
330be94e1b6SRafael Espindola   }
331be94e1b6SRafael Espindola }
332be94e1b6SRafael Espindola 
333b4c9b81aSRafael Espindola std::vector<InputSectionBase *>
3348c022ca7SRafael Espindola LinkerScript::createInputSectionList(OutputSection &OutCmd) {
335b4c9b81aSRafael Espindola   std::vector<InputSectionBase *> Ret;
336e7f912cdSRui Ueyama 
3378f99f73cSRui Ueyama   for (BaseCommand *Base : OutCmd.Commands) {
3388f99f73cSRui Ueyama     auto *Cmd = dyn_cast<InputSectionDescription>(Base);
3397c3ff2ebSRafael Espindola     if (!Cmd)
3400b9ce6a4SRui Ueyama       continue;
34172e107f3SRui Ueyama 
34272e107f3SRui Ueyama     Cmd->Sections = computeInputSections(Cmd);
343e4c8b9b7SRafael Espindola     Ret.insert(Ret.end(), Cmd->Sections.begin(), Cmd->Sections.end());
3440b9ce6a4SRui Ueyama   }
345e71a3f8aSRafael Espindola 
3460b9ce6a4SRui Ueyama   return Ret;
3470b9ce6a4SRui Ueyama }
3480b9ce6a4SRui Ueyama 
349b8dd23f5SRui Ueyama void LinkerScript::processCommands(OutputSectionFactory &Factory) {
3505616adf6SRafael Espindola   // A symbol can be assigned before any section is mentioned in the linker
3515616adf6SRafael Espindola   // script. In an DSO, the symbol values are addresses, so the only important
3525616adf6SRafael Espindola   // section values are:
3535616adf6SRafael Espindola   // * SHN_UNDEF
3545616adf6SRafael Espindola   // * SHN_ABS
3555616adf6SRafael Espindola   // * Any value meaning a regular section.
3565616adf6SRafael Espindola   // To handle that, create a dummy aether section that fills the void before
3575616adf6SRafael Espindola   // the linker scripts switches to another section. It has an index of one
3585616adf6SRafael Espindola   // which will map to whatever the first actual section is.
3595616adf6SRafael Espindola   Aether = make<OutputSection>("", 0, SHF_ALLOC);
3605616adf6SRafael Espindola   Aether->SectionIndex = 1;
361906e9a18SPeter Smith   auto State = make_unique<AddressState>(Opt);
362c1ace40bSPeter Smith   // CurAddressState captures the local AddressState and makes it accessible
363c1ace40bSPeter Smith   // deliberately. This is needed as there are some cases where we cannot just
364c1ace40bSPeter Smith   // thread the current state through to a lambda function created by the
365c1ace40bSPeter Smith   // script parser.
366906e9a18SPeter Smith   CurAddressState = State.get();
367906e9a18SPeter Smith   CurAddressState->OutSec = Aether;
3685616adf6SRafael Espindola 
36992a5ba6dSRui Ueyama   for (size_t I = 0; I < Opt.Commands.size(); ++I) {
3700b1b695aSRui Ueyama     // Handle symbol assignments outside of any output section.
37192a5ba6dSRui Ueyama     if (auto *Cmd = dyn_cast<SymbolAssignment>(Opt.Commands[I])) {
3724cd7352cSRafael Espindola       addSymbol(Cmd);
3732ab5f73dSRui Ueyama       continue;
3742ab5f73dSRui Ueyama     }
3750b1b695aSRui Ueyama 
3768c022ca7SRafael Espindola     if (auto *Sec = dyn_cast<OutputSection>(Opt.Commands[I])) {
3778c022ca7SRafael Espindola       std::vector<InputSectionBase *> V = createInputSectionList(*Sec);
3787bd37870SRafael Espindola 
3790b1b695aSRui Ueyama       // The output section name `/DISCARD/' is special.
3800b1b695aSRui Ueyama       // Any input section assigned to it is discarded.
3818c022ca7SRafael Espindola       if (Sec->Name == "/DISCARD/") {
3827bd37870SRafael Espindola         discard(V);
38348c3f1ceSRui Ueyama         continue;
38448c3f1ceSRui Ueyama       }
3850b9ce6a4SRui Ueyama 
3860b1b695aSRui Ueyama       // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive
3870b1b695aSRui Ueyama       // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input
3880b1b695aSRui Ueyama       // sections satisfy a given constraint. If not, a directive is handled
38907d7c42cSGeorge Rimar       // as if it wasn't present from the beginning.
3900b1b695aSRui Ueyama       //
3910b1b695aSRui Ueyama       // Because we'll iterate over Commands many more times, the easiest
39207d7c42cSGeorge Rimar       // way to "make it as if it wasn't present" is to just remove it.
3938c022ca7SRafael Espindola       if (!matchConstraints(V, Sec->Constraint)) {
394b4c9b81aSRafael Espindola         for (InputSectionBase *S : V)
395f94efdddSRui Ueyama           S->Assigned = false;
39692a5ba6dSRui Ueyama         Opt.Commands.erase(Opt.Commands.begin() + I);
39707d7c42cSGeorge Rimar         --I;
3987c3ff2ebSRafael Espindola         continue;
3997c3ff2ebSRafael Espindola       }
4007c3ff2ebSRafael Espindola 
4010b1b695aSRui Ueyama       // A directive may contain symbol definitions like this:
4020b1b695aSRui Ueyama       // ".foo : { ...; bar = .; }". Handle them.
4038c022ca7SRafael Espindola       for (BaseCommand *Base : Sec->Commands)
4048f99f73cSRui Ueyama         if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base))
4054cd7352cSRafael Espindola           addSymbol(OutCmd);
4067c3ff2ebSRafael Espindola 
4070b1b695aSRui Ueyama       // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign
4080b1b695aSRui Ueyama       // is given, input sections are aligned to that value, whether the
4090b1b695aSRui Ueyama       // given value is larger or smaller than the original section alignment.
4108c022ca7SRafael Espindola       if (Sec->SubalignExpr) {
4118c022ca7SRafael Espindola         uint32_t Subalign = Sec->SubalignExpr().getValue();
412b4c9b81aSRafael Espindola         for (InputSectionBase *S : V)
4130b1b695aSRui Ueyama           S->Alignment = Subalign;
41420d03194SEugene Leviant       }
4150b1b695aSRui Ueyama 
4160b1b695aSRui Ueyama       // Add input sections to an output section.
417d86a4e50SGeorge Rimar       for (InputSectionBase *S : V)
4180e2bfb1eSRui Ueyama         Sec->addSection(cast<InputSection>(S));
419c54d5b16SRui Ueyama 
420660c9ab9SRafael Espindola       assert(Sec->SectionIndex == INT_MAX);
421660c9ab9SRafael Espindola       Sec->SectionIndex = I;
4228c022ca7SRafael Espindola       if (Sec->Noload)
423fbb0463fSGeorge Rimar         Sec->Type = SHT_NOBITS;
42448c3f1ceSRui Ueyama     }
4254aa2ef5bSRafael Espindola   }
426c1ace40bSPeter Smith   CurAddressState = nullptr;
427db24d9c3SGeorge Rimar }
428e63d81bdSEugene Leviant 
42902ed7575SRafael Espindola void LinkerScript::fabricateDefaultCommands() {
430cbfe9e94SPeter Smith   // Define start address
431761f0b66SRui Ueyama   uint64_t StartAddr = UINT64_MAX;
432cbfe9e94SPeter Smith 
433c60b4510SPeter Smith   // The Sections with -T<section> have been sorted in order of ascending
434c60b4510SPeter Smith   // address. We must lower StartAddr if the lowest -T<section address> as
435c60b4510SPeter Smith   // calls to setDot() must be monotonically increasing.
436c60b4510SPeter Smith   for (auto &KV : Config->SectionStartMap)
437c60b4510SPeter Smith     StartAddr = std::min(StartAddr, KV.second);
438c60b4510SPeter Smith 
439f5db0b36SRui Ueyama   auto Expr = [=] {
440*b5ca92efSJames Henderson     return std::min(StartAddr, Target->getImageBase() + elf::getHeaderSize());
441f5db0b36SRui Ueyama   };
4428c022ca7SRafael Espindola   Opt.Commands.insert(Opt.Commands.begin(),
443f5db0b36SRui Ueyama                       make<SymbolAssignment>(".", Expr, ""));
444cbfe9e94SPeter Smith }
445cbfe9e94SPeter Smith 
446d2f225fdSRui Ueyama static OutputSection *findByName(ArrayRef<BaseCommand *> Vec,
447d2f225fdSRui Ueyama                                  StringRef Name) {
448d2f225fdSRui Ueyama   for (BaseCommand *Base : Vec)
449d2f225fdSRui Ueyama     if (auto *Sec = dyn_cast<OutputSection>(Base))
450d2f225fdSRui Ueyama       if (Sec->Name == Name)
451d2f225fdSRui Ueyama         return Sec;
452d2f225fdSRui Ueyama   return nullptr;
453d2f225fdSRui Ueyama }
454d2f225fdSRui Ueyama 
4550b1b695aSRui Ueyama // Add sections that didn't match any sections command.
456b8dd23f5SRui Ueyama void LinkerScript::addOrphanSections(OutputSectionFactory &Factory) {
457d2f225fdSRui Ueyama   unsigned End = Opt.Commands.size();
458d2f225fdSRui Ueyama 
4594f013bb3SRafael Espindola   for (InputSectionBase *S : InputSections) {
460db5e56f7SRafael Espindola     if (!S->Live || S->Parent)
4614f013bb3SRafael Espindola       continue;
462d2f225fdSRui Ueyama 
4634f013bb3SRafael Espindola     StringRef Name = getOutputSectionName(S->Name);
464347c70d7SGeorge Rimar     log(toString(S) + " is being placed in '" + Name + "'");
465d2f225fdSRui Ueyama 
466d2f225fdSRui Ueyama     if (OutputSection *Sec = findByName(
467d2f225fdSRui Ueyama             makeArrayRef(Opt.Commands).slice(0, End), Name)) {
4680e2bfb1eSRui Ueyama       Sec->addSection(cast<InputSection>(S));
469c54d5b16SRui Ueyama       continue;
470660c9ab9SRafael Espindola     }
471c54d5b16SRui Ueyama 
472c54d5b16SRui Ueyama     if (OutputSection *OS = Factory.addInputSec(S, Name))
473c54d5b16SRui Ueyama       Script->Opt.Commands.push_back(OS);
474c54d5b16SRui Ueyama     assert(S->getOutputSection()->SectionIndex == INT_MAX);
475d7faa916SRafael Espindola   }
4764f013bb3SRafael Espindola }
477e63d81bdSEugene Leviant 
4787c4eafa3SRafael Espindola uint64_t LinkerScript::advance(uint64_t Size, unsigned Align) {
479906e9a18SPeter Smith   bool IsTbss = (CurAddressState->OutSec->Flags & SHF_TLS) &&
480906e9a18SPeter Smith                 CurAddressState->OutSec->Type == SHT_NOBITS;
481906e9a18SPeter Smith   uint64_t Start = IsTbss ? Dot + CurAddressState->ThreadBssOffset : Dot;
4827c4eafa3SRafael Espindola   Start = alignTo(Start, Align);
4837c4eafa3SRafael Espindola   uint64_t End = Start + Size;
4847c4eafa3SRafael Espindola 
4857c4eafa3SRafael Espindola   if (IsTbss)
486906e9a18SPeter Smith     CurAddressState->ThreadBssOffset = End - Dot;
4877c4eafa3SRafael Espindola   else
4887c4eafa3SRafael Espindola     Dot = End;
4897c4eafa3SRafael Espindola   return End;
490a940e539SRafael Espindola }
491a940e539SRafael Espindola 
492b8dd23f5SRui Ueyama void LinkerScript::output(InputSection *S) {
493f694d33fSGeorge Rimar   uint64_t Before = advance(0, 1);
4947c4eafa3SRafael Espindola   uint64_t Pos = advance(S->getSize(), S->Alignment);
495906e9a18SPeter Smith   S->OutSecOff = Pos - S->getSize() - CurAddressState->OutSec->Addr;
496d3190795SRafael Espindola 
497d3190795SRafael Espindola   // Update output section size after adding each section. This is so that
498d3190795SRafael Espindola   // SIZEOF works correctly in the case below:
499d3190795SRafael Espindola   // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
500906e9a18SPeter Smith   CurAddressState->OutSec->Size = Pos - CurAddressState->OutSec->Addr;
501d3190795SRafael Espindola 
502b889744eSMeador Inge   // If there is a memory region associated with this input section, then
503b889744eSMeador Inge   // place the section in that region and update the region index.
504906e9a18SPeter Smith   if (CurAddressState->MemRegion) {
505906e9a18SPeter Smith     uint64_t &CurOffset =
506906e9a18SPeter Smith         CurAddressState->MemRegionOffset[CurAddressState->MemRegion];
507f694d33fSGeorge Rimar     CurOffset += Pos - Before;
508906e9a18SPeter Smith     uint64_t CurSize = CurOffset - CurAddressState->MemRegion->Origin;
509906e9a18SPeter Smith     if (CurSize > CurAddressState->MemRegion->Length) {
510906e9a18SPeter Smith       uint64_t OverflowAmt = CurSize - CurAddressState->MemRegion->Length;
511906e9a18SPeter Smith       error("section '" + CurAddressState->OutSec->Name +
512906e9a18SPeter Smith             "' will not fit in region '" + CurAddressState->MemRegion->Name +
513906e9a18SPeter Smith             "': overflowed by " + Twine(OverflowAmt) + " bytes");
514b889744eSMeador Inge     }
515b889744eSMeador Inge   }
5162de509c3SRui Ueyama }
517ceabe80eSEugene Leviant 
518b8dd23f5SRui Ueyama void LinkerScript::switchTo(OutputSection *Sec) {
519906e9a18SPeter Smith   if (CurAddressState->OutSec == Sec)
520d3190795SRafael Espindola     return;
521d3190795SRafael Espindola 
522906e9a18SPeter Smith   CurAddressState->OutSec = Sec;
523906e9a18SPeter Smith   CurAddressState->OutSec->Addr =
524906e9a18SPeter Smith       advance(0, CurAddressState->OutSec->Alignment);
525b71d6f7aSEugene Leviant 
526b71d6f7aSEugene Leviant   // If neither AT nor AT> is specified for an allocatable section, the linker
527b71d6f7aSEugene Leviant   // will set the LMA such that the difference between VMA and LMA for the
528b71d6f7aSEugene Leviant   // section is the same as the preceding output section in the same region
529b71d6f7aSEugene Leviant   // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
530906e9a18SPeter Smith   if (CurAddressState->LMAOffset)
531906e9a18SPeter Smith     CurAddressState->OutSec->LMAOffset = CurAddressState->LMAOffset();
532d3190795SRafael Espindola }
533d3190795SRafael Espindola 
534b8dd23f5SRui Ueyama void LinkerScript::process(BaseCommand &Base) {
5352e081a4fSRui Ueyama   // This handles the assignments to symbol or to the dot.
5362e081a4fSRui Ueyama   if (auto *Cmd = dyn_cast<SymbolAssignment>(&Base)) {
5372e081a4fSRui Ueyama     assignSymbol(Cmd, true);
538d3190795SRafael Espindola     return;
53997403d15SEugene Leviant   }
540e38cbab5SGeorge Rimar 
541e38cbab5SGeorge Rimar   // Handle BYTE(), SHORT(), LONG(), or QUAD().
5422e081a4fSRui Ueyama   if (auto *Cmd = dyn_cast<BytesDataCommand>(&Base)) {
543906e9a18SPeter Smith     Cmd->Offset = Dot - CurAddressState->OutSec->Addr;
5442e081a4fSRui Ueyama     Dot += Cmd->Size;
545906e9a18SPeter Smith     CurAddressState->OutSec->Size = Dot - CurAddressState->OutSec->Addr;
546e38cbab5SGeorge Rimar     return;
547e38cbab5SGeorge Rimar   }
548e38cbab5SGeorge Rimar 
5492e081a4fSRui Ueyama   // Handle ASSERT().
5502e081a4fSRui Ueyama   if (auto *Cmd = dyn_cast<AssertCommand>(&Base)) {
5512e081a4fSRui Ueyama     Cmd->Expression();
552b2d99d6aSMeador Inge     return;
553b2d99d6aSMeador Inge   }
554b2d99d6aSMeador Inge 
5552e081a4fSRui Ueyama   // Handle a single input section description command.
5562e081a4fSRui Ueyama   // It calculates and assigns the offsets for each section and also
557e38cbab5SGeorge Rimar   // updates the output section size.
5582e081a4fSRui Ueyama   auto &Cmd = cast<InputSectionDescription>(Base);
559a85e8ddaSRafael Espindola   for (InputSection *Sec : Cmd.Sections) {
5603fb5a6dcSGeorge Rimar     // We tentatively added all synthetic sections at the beginning and removed
5613fb5a6dcSGeorge Rimar     // empty ones afterwards (because there is no way to know whether they were
5623fb5a6dcSGeorge Rimar     // going be empty or not other than actually running linker scripts.)
5633fb5a6dcSGeorge Rimar     // We need to ignore remains of empty sections.
5642e081a4fSRui Ueyama     if (auto *S = dyn_cast<SyntheticSection>(Sec))
5652e081a4fSRui Ueyama       if (S->empty())
5663fb5a6dcSGeorge Rimar         continue;
5673fb5a6dcSGeorge Rimar 
5682e081a4fSRui Ueyama     if (!Sec->Live)
56978ef645fSGeorge Rimar       continue;
570906e9a18SPeter Smith     assert(CurAddressState->OutSec == Sec->getParent());
571a85e8ddaSRafael Espindola     output(Sec);
572ceabe80eSEugene Leviant   }
573ceabe80eSEugene Leviant }
574ceabe80eSEugene Leviant 
575b889744eSMeador Inge // This function searches for a memory region to place the given output
576b889744eSMeador Inge // section in. If found, a pointer to the appropriate memory region is
577b889744eSMeador Inge // returned. Otherwise, a nullptr is returned.
5788c022ca7SRafael Espindola MemoryRegion *LinkerScript::findMemoryRegion(OutputSection *Sec) {
579b889744eSMeador Inge   // If a memory region name was specified in the output section command,
580b889744eSMeador Inge   // then try to find that region first.
5818c022ca7SRafael Espindola   if (!Sec->MemoryRegionName.empty()) {
5828c022ca7SRafael Espindola     auto It = Opt.MemoryRegions.find(Sec->MemoryRegionName);
583b889744eSMeador Inge     if (It != Opt.MemoryRegions.end())
5845f37541cSGeorge Rimar       return It->second;
5858c022ca7SRafael Espindola     error("memory region '" + Sec->MemoryRegionName + "' not declared");
586b889744eSMeador Inge     return nullptr;
587b889744eSMeador Inge   }
588b889744eSMeador Inge 
589d7c5400fSRui Ueyama   // If at least one memory region is defined, all sections must
590d7c5400fSRui Ueyama   // belong to some memory region. Otherwise, we don't need to do
591d7c5400fSRui Ueyama   // anything for memory regions.
592cc400cc8SRui Ueyama   if (Opt.MemoryRegions.empty())
593b889744eSMeador Inge     return nullptr;
594b889744eSMeador Inge 
595b889744eSMeador Inge   // See if a region can be found by matching section flags.
5962e081a4fSRui Ueyama   for (auto &Pair : Opt.MemoryRegions) {
5975f37541cSGeorge Rimar     MemoryRegion *M = Pair.second;
5985f37541cSGeorge Rimar     if ((M->Flags & Sec->Flags) && (M->NegFlags & Sec->Flags) == 0)
5995f37541cSGeorge Rimar       return M;
600b889744eSMeador Inge   }
601b889744eSMeador Inge 
602b889744eSMeador Inge   // Otherwise, no suitable region was found.
603b889744eSMeador Inge   if (Sec->Flags & SHF_ALLOC)
604b889744eSMeador Inge     error("no memory region specified for section '" + Sec->Name + "'");
605b889744eSMeador Inge   return nullptr;
606b889744eSMeador Inge }
607b889744eSMeador Inge 
6080b1b695aSRui Ueyama // This function assigns offsets to input sections and an output section
6090b1b695aSRui Ueyama // for a single sections command (e.g. ".text { *(.text); }").
6108c022ca7SRafael Espindola void LinkerScript::assignOffsets(OutputSection *Sec) {
611dece2808SRafael Espindola   if (!(Sec->Flags & SHF_ALLOC))
612dece2808SRafael Espindola     Dot = 0;
6138c022ca7SRafael Espindola   else if (Sec->AddrExpr)
6148c022ca7SRafael Espindola     setDot(Sec->AddrExpr, Sec->Location, false);
615679828ffSRafael Espindola 
616c2dffe3aSGeorge Rimar   CurAddressState->MemRegion = Sec->MemRegion;
617c2dffe3aSGeorge Rimar   if (CurAddressState->MemRegion)
618c2dffe3aSGeorge Rimar     Dot = CurAddressState->MemRegionOffset[CurAddressState->MemRegion];
619c2dffe3aSGeorge Rimar 
6208c022ca7SRafael Espindola   if (Sec->LMAExpr) {
6210c1c8085SGeorge Rimar     uint64_t D = Dot;
6228c022ca7SRafael Espindola     CurAddressState->LMAOffset = [=] { return Sec->LMAExpr().getValue() - D; };
6235784e96fSEugene Leviant   }
6245784e96fSEugene Leviant 
625b889744eSMeador Inge   switchTo(Sec);
6260b1b695aSRui Ueyama 
627d86a4e50SGeorge Rimar   // We do not support custom layout for compressed debug sectons.
628d86a4e50SGeorge Rimar   // At this point we already know their size and have compressed content.
629906e9a18SPeter Smith   if (CurAddressState->OutSec->Flags & SHF_COMPRESSED)
630d86a4e50SGeorge Rimar     return;
631d86a4e50SGeorge Rimar 
6328c022ca7SRafael Espindola   for (BaseCommand *C : Sec->Commands)
633de8d9897SRafael Espindola     process(*C);
634d3190795SRafael Espindola }
635d3190795SRafael Espindola 
636b8dd23f5SRui Ueyama void LinkerScript::removeEmptyCommands() {
6376d38e4dbSRafael Espindola   // It is common practice to use very generic linker scripts. So for any
6386d38e4dbSRafael Espindola   // given run some of the output sections in the script will be empty.
6396d38e4dbSRafael Espindola   // We could create corresponding empty output sections, but that would
6406d38e4dbSRafael Espindola   // clutter the output.
6416d38e4dbSRafael Espindola   // We instead remove trivially empty sections. The bfd linker seems even
6426d38e4dbSRafael Espindola   // more aggressive at removing them.
64360608a8aSGeorge Rimar   llvm::erase_if(Opt.Commands, [&](BaseCommand *Base) {
6448c022ca7SRafael Espindola     if (auto *Sec = dyn_cast<OutputSection>(Base))
6458c022ca7SRafael Espindola       return !Sec->Live;
6460b1b695aSRui Ueyama     return false;
6476d38e4dbSRafael Espindola   });
64807fe6129SRafael Espindola }
64907fe6129SRafael Espindola 
6508c022ca7SRafael Espindola static bool isAllSectionDescription(const OutputSection &Cmd) {
6518f99f73cSRui Ueyama   for (BaseCommand *Base : Cmd.Commands)
6528f99f73cSRui Ueyama     if (!isa<InputSectionDescription>(*Base))
6536a53737cSRafael Espindola       return false;
6546a53737cSRafael Espindola   return true;
6556a53737cSRafael Espindola }
6566d38e4dbSRafael Espindola 
657b8dd23f5SRui Ueyama void LinkerScript::adjustSectionsBeforeSorting() {
6589546fffbSRafael Espindola   // If the output section contains only symbol assignments, create a
6599546fffbSRafael Espindola   // corresponding output section. The bfd linker seems to only create them if
6609546fffbSRafael Espindola   // '.' is assigned to, but creating these section should not have any bad
6619546fffbSRafael Espindola   // consequeces and gives us a section to put the symbol in.
6620c1c8085SGeorge Rimar   uint64_t Flags = SHF_ALLOC;
663660c9ab9SRafael Espindola 
6648962db91SGeorge Rimar   for (BaseCommand * Cmd : Opt.Commands) {
6658962db91SGeorge Rimar     auto *Sec = dyn_cast<OutputSection>(Cmd);
6668c022ca7SRafael Espindola     if (!Sec)
6679546fffbSRafael Espindola       continue;
6688c022ca7SRafael Espindola     if (Sec->Live) {
6692b074553SRafael Espindola       Flags = Sec->Flags;
6709546fffbSRafael Espindola       continue;
6719546fffbSRafael Espindola     }
6729546fffbSRafael Espindola 
6738c022ca7SRafael Espindola     if (isAllSectionDescription(*Sec))
6746a53737cSRafael Espindola       continue;
6756a53737cSRafael Espindola 
6768c022ca7SRafael Espindola     Sec->Live = true;
6778c022ca7SRafael Espindola     Sec->Flags = Flags;
6789546fffbSRafael Espindola   }
679f7a17448SRafael Espindola }
680f7a17448SRafael Espindola 
681b8dd23f5SRui Ueyama void LinkerScript::adjustSectionsAfterSorting() {
682feed7506SRafael Espindola   // Try and find an appropriate memory region to assign offsets in.
683d1960dc0SRafael Espindola   for (BaseCommand *Base : Opt.Commands) {
6848c022ca7SRafael Espindola     if (auto *Sec = dyn_cast<OutputSection>(Base)) {
685ba45584cSGeorge Rimar       if (!Sec->Live)
686ba45584cSGeorge Rimar         continue;
6878c022ca7SRafael Espindola       Sec->MemRegion = findMemoryRegion(Sec);
688d1960dc0SRafael Espindola       // Handle align (e.g. ".foo : ALIGN(16) { ... }").
6898c022ca7SRafael Espindola       if (Sec->AlignExpr)
6908befefb2SRui Ueyama         Sec->Alignment =
6918befefb2SRui Ueyama             std::max<uint32_t>(Sec->Alignment, Sec->AlignExpr().getValue());
692d1960dc0SRafael Espindola     }
693d1960dc0SRafael Espindola   }
694feed7506SRafael Espindola 
695f7a17448SRafael Espindola   // If output section command doesn't specify any segments,
696f7a17448SRafael Espindola   // and we haven't previously assigned any section to segment,
697f7a17448SRafael Espindola   // then we simply assign section to the very first load segment.
698f7a17448SRafael Espindola   // Below is an example of such linker script:
699f7a17448SRafael Espindola   // PHDRS { seg PT_LOAD; }
700f7a17448SRafael Espindola   // SECTIONS { .aaa : { *(.aaa) } }
701f7a17448SRafael Espindola   std::vector<StringRef> DefPhdrs;
702f7a17448SRafael Espindola   auto FirstPtLoad =
703f7a17448SRafael Espindola       std::find_if(Opt.PhdrsCommands.begin(), Opt.PhdrsCommands.end(),
704f7a17448SRafael Espindola                    [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; });
705f7a17448SRafael Espindola   if (FirstPtLoad != Opt.PhdrsCommands.end())
706f7a17448SRafael Espindola     DefPhdrs.push_back(FirstPtLoad->Name);
707f7a17448SRafael Espindola 
708f7a17448SRafael Espindola   // Walk the commands and propagate the program headers to commands that don't
709f7a17448SRafael Espindola   // explicitly specify them.
7108f99f73cSRui Ueyama   for (BaseCommand *Base : Opt.Commands) {
7118c022ca7SRafael Espindola     auto *Sec = dyn_cast<OutputSection>(Base);
7128c022ca7SRafael Espindola     if (!Sec)
713f7a17448SRafael Espindola       continue;
7148f99f73cSRui Ueyama 
7158c022ca7SRafael Espindola     if (Sec->Phdrs.empty()) {
716a020d348SAndrew Ng       // To match the bfd linker script behaviour, only propagate program
717a020d348SAndrew Ng       // headers to sections that are allocated.
7188c022ca7SRafael Espindola       if (Sec->Flags & SHF_ALLOC)
7198c022ca7SRafael Espindola         Sec->Phdrs = DefPhdrs;
720a020d348SAndrew Ng     } else {
7218c022ca7SRafael Espindola       DefPhdrs = Sec->Phdrs;
722f7a17448SRafael Espindola     }
723a020d348SAndrew Ng   }
7249546fffbSRafael Espindola }
7259546fffbSRafael Espindola 
726582ede89SGeorge Rimar static OutputSection *findFirstSection(PhdrEntry *Load) {
727582ede89SGeorge Rimar   for (OutputSection *Sec : OutputSections)
728582ede89SGeorge Rimar     if (Sec->PtLoad == Load)
729582ede89SGeorge Rimar       return Sec;
730582ede89SGeorge Rimar   return nullptr;
731582ede89SGeorge Rimar }
732582ede89SGeorge Rimar 
733b93c5b9fSPetr Hosek // Try to find an address for the file and program headers output sections,
734b93c5b9fSPetr Hosek // which were unconditionally added to the first PT_LOAD segment earlier.
735b93c5b9fSPetr Hosek //
736b93c5b9fSPetr Hosek // When using the default layout, we check if the headers fit below the first
737b93c5b9fSPetr Hosek // allocated section. When using a linker script, we also check if the headers
738b93c5b9fSPetr Hosek // are covered by the output section. This allows omitting the headers by not
739b93c5b9fSPetr Hosek // leaving enough space for them in the linker script; this pattern is common
740b93c5b9fSPetr Hosek // in embedded systems.
741b93c5b9fSPetr Hosek //
742b93c5b9fSPetr Hosek // If there isn't enough space for these sections, we'll remove them from the
743b93c5b9fSPetr Hosek // PT_LOAD segment, and we'll also remove the PT_PHDR segment.
744aa354187SGeorge Rimar void LinkerScript::allocateHeaders(std::vector<PhdrEntry *> &Phdrs) {
7455aedebffSPeter Smith   uint64_t Min = std::numeric_limits<uint64_t>::max();
7468c022ca7SRafael Espindola   for (OutputSection *Sec : OutputSections)
7475aedebffSPeter Smith     if (Sec->Flags & SHF_ALLOC)
7485aedebffSPeter Smith       Min = std::min<uint64_t>(Min, Sec->Addr);
7495aedebffSPeter Smith 
750aa354187SGeorge Rimar   auto It = llvm::find_if(
751aa354187SGeorge Rimar       Phdrs, [](const PhdrEntry *E) { return E->p_type == PT_LOAD; });
752aa354187SGeorge Rimar   if (It == Phdrs.end())
753d971e703SGeorge Rimar     return;
754aa354187SGeorge Rimar   PhdrEntry *FirstPTLoad = *It;
75502ed7575SRafael Espindola 
75602ed7575SRafael Espindola   uint64_t HeaderSize = getHeaderSize();
757b93c5b9fSPetr Hosek   // When linker script with SECTIONS is being used, don't output headers
758b93c5b9fSPetr Hosek   // unless there's a space for them.
759b93c5b9fSPetr Hosek   uint64_t Base = Opt.HasSections ? alignDown(Min, Config->MaxPageSize) : 0;
760b93c5b9fSPetr Hosek   if (HeaderSize <= Min - Base || Script->hasPhdrsCommands()) {
7611f0fe88aSRafael Espindola     Min = alignDown(Min - HeaderSize, Config->MaxPageSize);
76202ed7575SRafael Espindola     Out::ElfHeader->Addr = Min;
76302ed7575SRafael Espindola     Out::ProgramHeaders->Addr = Min + Out::ElfHeader->Size;
764d971e703SGeorge Rimar     return;
76502ed7575SRafael Espindola   }
76602ed7575SRafael Espindola 
767582ede89SGeorge Rimar   Out::ElfHeader->PtLoad = nullptr;
768582ede89SGeorge Rimar   Out::ProgramHeaders->PtLoad = nullptr;
7696823c5f0SGeorge Rimar   FirstPTLoad->FirstSec = findFirstSection(FirstPTLoad);
77002ed7575SRafael Espindola 
77160608a8aSGeorge Rimar   llvm::erase_if(Phdrs,
77260608a8aSGeorge Rimar                  [](const PhdrEntry *E) { return E->p_type == PT_PHDR; });
77302ed7575SRafael Espindola }
77402ed7575SRafael Espindola 
775906e9a18SPeter Smith LinkerScript::AddressState::AddressState(const ScriptConfiguration &Opt) {
776906e9a18SPeter Smith   for (auto &MRI : Opt.MemoryRegions) {
7775f37541cSGeorge Rimar     const MemoryRegion *MR = MRI.second;
778906e9a18SPeter Smith     MemRegionOffset[MR] = MR->Origin;
779906e9a18SPeter Smith   }
780906e9a18SPeter Smith }
781906e9a18SPeter Smith 
7827c18c28cSRui Ueyama // Assign addresses as instructed by linker script SECTIONS sub-commands.
783*b5ca92efSJames Henderson void LinkerScript::assignAddresses() {
784*b5ca92efSJames Henderson   // By default linker scripts use an initial value of 0 for '.', but prefer
785*b5ca92efSJames Henderson   // -image-base if set.
786*b5ca92efSJames Henderson   Dot = Config->ImageBase ? *Config->ImageBase : 0;
787906e9a18SPeter Smith   auto State = make_unique<AddressState>(Opt);
788c1ace40bSPeter Smith   // CurAddressState captures the local AddressState and makes it accessible
789c1ace40bSPeter Smith   // deliberately. This is needed as there are some cases where we cannot just
790c1ace40bSPeter Smith   // thread the current state through to a lambda function created by the
791c1ace40bSPeter Smith   // script parser.
792906e9a18SPeter Smith   CurAddressState = State.get();
79372dc195dSRafael Espindola   ErrorOnMissingSection = true;
79406f4743aSRafael Espindola   switchTo(Aether);
79506f4743aSRafael Espindola 
7968f99f73cSRui Ueyama   for (BaseCommand *Base : Opt.Commands) {
7978f99f73cSRui Ueyama     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base)) {
798d379f735SRui Ueyama       assignSymbol(Cmd, false);
79905ef4cffSRui Ueyama       continue;
800652852c5SGeorge Rimar     }
801652852c5SGeorge Rimar 
8028f99f73cSRui Ueyama     if (auto *Cmd = dyn_cast<AssertCommand>(Base)) {
8034595df94SRafael Espindola       Cmd->Expression();
804eefa758eSGeorge Rimar       continue;
805eefa758eSGeorge Rimar     }
806eefa758eSGeorge Rimar 
8078c022ca7SRafael Espindola     assignOffsets(cast<OutputSection>(Base));
808a14b13d8SGeorge Rimar   }
809c1ace40bSPeter Smith   CurAddressState = nullptr;
810fb8978fcSDima Stepanov }
811652852c5SGeorge Rimar 
812464daadcSRui Ueyama // Creates program headers as instructed by PHDRS linker script command.
813aa354187SGeorge Rimar std::vector<PhdrEntry *> LinkerScript::createPhdrs() {
814aa354187SGeorge Rimar   std::vector<PhdrEntry *> Ret;
815bbe38602SEugene Leviant 
816464daadcSRui Ueyama   // Process PHDRS and FILEHDR keywords because they are not
817464daadcSRui Ueyama   // real output sections and cannot be added in the following loop.
818bbe38602SEugene Leviant   for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
8190ae2c24cSRui Ueyama     PhdrEntry *Phdr = make<PhdrEntry>(Cmd.Type, Cmd.Flags ? *Cmd.Flags : PF_R);
820bbe38602SEugene Leviant 
821bbe38602SEugene Leviant     if (Cmd.HasFilehdr)
822aa354187SGeorge Rimar       Phdr->add(Out::ElfHeader);
823bbe38602SEugene Leviant     if (Cmd.HasPhdrs)
824aa354187SGeorge Rimar       Phdr->add(Out::ProgramHeaders);
82556b21c86SEugene Leviant 
82656b21c86SEugene Leviant     if (Cmd.LMAExpr) {
827aa354187SGeorge Rimar       Phdr->p_paddr = Cmd.LMAExpr().getValue();
828aa354187SGeorge Rimar       Phdr->HasLMA = true;
82956b21c86SEugene Leviant     }
830aa354187SGeorge Rimar     Ret.push_back(Phdr);
831bbe38602SEugene Leviant   }
832bbe38602SEugene Leviant 
833464daadcSRui Ueyama   // Add output sections to program headers.
8348c022ca7SRafael Espindola   for (OutputSection *Sec : OutputSections) {
835bbe38602SEugene Leviant     // Assign headers specified by linker script
8368c022ca7SRafael Espindola     for (size_t Id : getPhdrIndices(Sec)) {
837aa354187SGeorge Rimar       Ret[Id]->add(Sec);
8380ae2c24cSRui Ueyama       if (!Opt.PhdrsCommands[Id].Flags.hasValue())
839aa354187SGeorge Rimar         Ret[Id]->p_flags |= Sec->getPhdrFlags();
840bbe38602SEugene Leviant     }
841bbe38602SEugene Leviant   }
842edebbdf1SRui Ueyama   return Ret;
843bbe38602SEugene Leviant }
844bbe38602SEugene Leviant 
845e03ba023SRui Ueyama // Returns true if we should emit an .interp section.
846e03ba023SRui Ueyama //
847e03ba023SRui Ueyama // We usually do. But if PHDRS commands are given, and
848e03ba023SRui Ueyama // no PT_INTERP is there, there's no place to emit an
849e03ba023SRui Ueyama // .interp, so we don't do that in that case.
850e03ba023SRui Ueyama bool LinkerScript::needsInterpSection() {
851e31d9886SRui Ueyama   if (Opt.PhdrsCommands.empty())
852e03ba023SRui Ueyama     return true;
853e31d9886SRui Ueyama   for (PhdrsCommand &Cmd : Opt.PhdrsCommands)
854e31d9886SRui Ueyama     if (Cmd.Type == PT_INTERP)
855e31d9886SRui Ueyama       return true;
856e03ba023SRui Ueyama   return false;
857f9bc3bd2SEugene Leviant }
858f9bc3bd2SEugene Leviant 
859b8dd23f5SRui Ueyama ExprValue LinkerScript::getSymbolValue(const Twine &Loc, StringRef S) {
8607e5b0a59SGeorge Rimar   if (S == ".") {
8617e5b0a59SGeorge Rimar     if (CurAddressState)
8627e5b0a59SGeorge Rimar       return {CurAddressState->OutSec, Dot - CurAddressState->OutSec->Addr,
8637e5b0a59SGeorge Rimar               Loc};
8647e5b0a59SGeorge Rimar     error(Loc + ": unable to get location counter value");
8657e5b0a59SGeorge Rimar     return 0;
8667e5b0a59SGeorge Rimar   }
867244ef981SRafael Espindola   if (SymbolBody *B = Symtab->find(S)) {
86872dc195dSRafael Espindola     if (auto *D = dyn_cast<DefinedRegular>(B))
86941c7ab4aSGeorge Rimar       return {D->Section, D->Value, Loc};
87030f16b23SPetr Hosek     if (auto *C = dyn_cast<DefinedCommon>(B))
87167df57a2SRafael Espindola       return {C->Section, 0, Loc};
87272dc195dSRafael Espindola   }
873f6aeed36SEugene Leviant   error(Loc + ": symbol not found: " + S);
874884e786dSGeorge Rimar   return 0;
875884e786dSGeorge Rimar }
876884e786dSGeorge Rimar 
877656be311SRui Ueyama // Returns the index of the segment named Name.
878656be311SRui Ueyama static Optional<size_t> getPhdrIndex(ArrayRef<PhdrsCommand> Vec,
879656be311SRui Ueyama                                      StringRef Name) {
880656be311SRui Ueyama   for (size_t I = 0; I < Vec.size(); ++I)
881656be311SRui Ueyama     if (Vec[I].Name == Name)
882656be311SRui Ueyama       return I;
883656be311SRui Ueyama   return None;
884656be311SRui Ueyama }
885656be311SRui Ueyama 
8862c923c2cSRafael Espindola // Returns indices of ELF headers containing specific section. Each index is a
8872c923c2cSRafael Espindola // zero based number of ELF header listed within PHDRS {} script block.
8888c022ca7SRafael Espindola std::vector<size_t> LinkerScript::getPhdrIndices(OutputSection *Cmd) {
88929c5a2a9SRui Ueyama   std::vector<size_t> Ret;
890656be311SRui Ueyama 
891656be311SRui Ueyama   for (StringRef S : Cmd->Phdrs) {
892656be311SRui Ueyama     if (Optional<size_t> Idx = getPhdrIndex(Opt.PhdrsCommands, S))
89387223574SRui Ueyama       Ret.push_back(*Idx);
894656be311SRui Ueyama     else if (S != "NONE")
895656be311SRui Ueyama       error(Cmd->Location + ": section header '" + S +
896656be311SRui Ueyama             "' is not listed in PHDRS");
897bbe38602SEugene Leviant   }
898656be311SRui Ueyama   return Ret;
89929c5a2a9SRui Ueyama }
900