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;
36849592cf6SRafael Espindola   Dot = 0;
3695616adf6SRafael Espindola 
37092a5ba6dSRui Ueyama   for (size_t I = 0; I < Opt.Commands.size(); ++I) {
3710b1b695aSRui Ueyama     // Handle symbol assignments outside of any output section.
37292a5ba6dSRui Ueyama     if (auto *Cmd = dyn_cast<SymbolAssignment>(Opt.Commands[I])) {
3734cd7352cSRafael Espindola       addSymbol(Cmd);
3742ab5f73dSRui Ueyama       continue;
3752ab5f73dSRui Ueyama     }
3760b1b695aSRui Ueyama 
3778c022ca7SRafael Espindola     if (auto *Sec = dyn_cast<OutputSection>(Opt.Commands[I])) {
3788c022ca7SRafael Espindola       std::vector<InputSectionBase *> V = createInputSectionList(*Sec);
3797bd37870SRafael Espindola 
3800b1b695aSRui Ueyama       // The output section name `/DISCARD/' is special.
3810b1b695aSRui Ueyama       // Any input section assigned to it is discarded.
3828c022ca7SRafael Espindola       if (Sec->Name == "/DISCARD/") {
3837bd37870SRafael Espindola         discard(V);
38448c3f1ceSRui Ueyama         continue;
38548c3f1ceSRui Ueyama       }
3860b9ce6a4SRui Ueyama 
3870b1b695aSRui Ueyama       // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive
3880b1b695aSRui Ueyama       // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input
3890b1b695aSRui Ueyama       // sections satisfy a given constraint. If not, a directive is handled
39007d7c42cSGeorge Rimar       // as if it wasn't present from the beginning.
3910b1b695aSRui Ueyama       //
3920b1b695aSRui Ueyama       // Because we'll iterate over Commands many more times, the easiest
39307d7c42cSGeorge Rimar       // way to "make it as if it wasn't present" is to just remove it.
3948c022ca7SRafael Espindola       if (!matchConstraints(V, Sec->Constraint)) {
395b4c9b81aSRafael Espindola         for (InputSectionBase *S : V)
396f94efdddSRui Ueyama           S->Assigned = false;
39792a5ba6dSRui Ueyama         Opt.Commands.erase(Opt.Commands.begin() + I);
39807d7c42cSGeorge Rimar         --I;
3997c3ff2ebSRafael Espindola         continue;
4007c3ff2ebSRafael Espindola       }
4017c3ff2ebSRafael Espindola 
4020b1b695aSRui Ueyama       // A directive may contain symbol definitions like this:
4030b1b695aSRui Ueyama       // ".foo : { ...; bar = .; }". Handle them.
4048c022ca7SRafael Espindola       for (BaseCommand *Base : Sec->Commands)
4058f99f73cSRui Ueyama         if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base))
4064cd7352cSRafael Espindola           addSymbol(OutCmd);
4077c3ff2ebSRafael Espindola 
4080b1b695aSRui Ueyama       // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign
4090b1b695aSRui Ueyama       // is given, input sections are aligned to that value, whether the
4100b1b695aSRui Ueyama       // given value is larger or smaller than the original section alignment.
4118c022ca7SRafael Espindola       if (Sec->SubalignExpr) {
4128c022ca7SRafael Espindola         uint32_t Subalign = Sec->SubalignExpr().getValue();
413b4c9b81aSRafael Espindola         for (InputSectionBase *S : V)
4140b1b695aSRui Ueyama           S->Alignment = Subalign;
41520d03194SEugene Leviant       }
4160b1b695aSRui Ueyama 
4170b1b695aSRui Ueyama       // Add input sections to an output section.
418d86a4e50SGeorge Rimar       for (InputSectionBase *S : V)
4198c022ca7SRafael Espindola         Factory.addInputSec(S, Sec->Name, Sec);
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
431e76231b6SRafael Espindola   uint64_t StartAddr = -1;
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 
439*f5db0b36SRui Ueyama   auto Expr = [=] {
440*f5db0b36SRui Ueyama     return std::min(StartAddr, Config->ImageBase + elf::getHeaderSize());
441*f5db0b36SRui Ueyama   };
4428c022ca7SRafael Espindola   Opt.Commands.insert(Opt.Commands.begin(),
443*f5db0b36SRui Ueyama                       make<SymbolAssignment>(".", Expr, ""));
444cbfe9e94SPeter Smith }
445cbfe9e94SPeter Smith 
4460b1b695aSRui Ueyama // Add sections that didn't match any sections command.
447b8dd23f5SRui Ueyama void LinkerScript::addOrphanSections(OutputSectionFactory &Factory) {
448d7faa916SRafael Espindola   unsigned NumCommands = Opt.Commands.size();
4494f013bb3SRafael Espindola   for (InputSectionBase *S : InputSections) {
450db5e56f7SRafael Espindola     if (!S->Live || S->Parent)
4514f013bb3SRafael Espindola       continue;
4524f013bb3SRafael Espindola     StringRef Name = getOutputSectionName(S->Name);
453d7faa916SRafael Espindola     auto End = Opt.Commands.begin() + NumCommands;
454d7faa916SRafael Espindola     auto I = std::find_if(Opt.Commands.begin(), End, [&](BaseCommand *Base) {
4558c022ca7SRafael Espindola       if (auto *Sec = dyn_cast<OutputSection>(Base))
4568c022ca7SRafael Espindola         return Sec->Name == Name;
4574f013bb3SRafael Espindola       return false;
4584f013bb3SRafael Espindola     });
459347c70d7SGeorge Rimar     log(toString(S) + " is being placed in '" + Name + "'");
460d7faa916SRafael Espindola     if (I == End) {
4614f013bb3SRafael Espindola       Factory.addInputSec(S, Name);
462a2df2f09SRafael Espindola       assert(S->getOutputSection()->SectionIndex == INT_MAX);
463de8d9897SRafael Espindola     } else {
4648c022ca7SRafael Espindola       OutputSection *Sec = cast<OutputSection>(*I);
4658c022ca7SRafael Espindola       Factory.addInputSec(S, Name, Sec);
466660c9ab9SRafael Espindola       unsigned Index = std::distance(Opt.Commands.begin(), I);
467660c9ab9SRafael Espindola       assert(Sec->SectionIndex == INT_MAX || Sec->SectionIndex == Index);
468660c9ab9SRafael Espindola       Sec->SectionIndex = Index;
469660c9ab9SRafael Espindola     }
470d7faa916SRafael Espindola   }
4714f013bb3SRafael Espindola }
472e63d81bdSEugene Leviant 
4737c4eafa3SRafael Espindola uint64_t LinkerScript::advance(uint64_t Size, unsigned Align) {
474906e9a18SPeter Smith   bool IsTbss = (CurAddressState->OutSec->Flags & SHF_TLS) &&
475906e9a18SPeter Smith                 CurAddressState->OutSec->Type == SHT_NOBITS;
476906e9a18SPeter Smith   uint64_t Start = IsTbss ? Dot + CurAddressState->ThreadBssOffset : Dot;
4777c4eafa3SRafael Espindola   Start = alignTo(Start, Align);
4787c4eafa3SRafael Espindola   uint64_t End = Start + Size;
4797c4eafa3SRafael Espindola 
4807c4eafa3SRafael Espindola   if (IsTbss)
481906e9a18SPeter Smith     CurAddressState->ThreadBssOffset = End - Dot;
4827c4eafa3SRafael Espindola   else
4837c4eafa3SRafael Espindola     Dot = End;
4847c4eafa3SRafael Espindola   return End;
485a940e539SRafael Espindola }
486a940e539SRafael Espindola 
487b8dd23f5SRui Ueyama void LinkerScript::output(InputSection *S) {
488f694d33fSGeorge Rimar   uint64_t Before = advance(0, 1);
4897c4eafa3SRafael Espindola   uint64_t Pos = advance(S->getSize(), S->Alignment);
490906e9a18SPeter Smith   S->OutSecOff = Pos - S->getSize() - CurAddressState->OutSec->Addr;
491d3190795SRafael Espindola 
492d3190795SRafael Espindola   // Update output section size after adding each section. This is so that
493d3190795SRafael Espindola   // SIZEOF works correctly in the case below:
494d3190795SRafael Espindola   // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
495906e9a18SPeter Smith   CurAddressState->OutSec->Size = Pos - CurAddressState->OutSec->Addr;
496d3190795SRafael Espindola 
497b889744eSMeador Inge   // If there is a memory region associated with this input section, then
498b889744eSMeador Inge   // place the section in that region and update the region index.
499906e9a18SPeter Smith   if (CurAddressState->MemRegion) {
500906e9a18SPeter Smith     uint64_t &CurOffset =
501906e9a18SPeter Smith         CurAddressState->MemRegionOffset[CurAddressState->MemRegion];
502f694d33fSGeorge Rimar     CurOffset += Pos - Before;
503906e9a18SPeter Smith     uint64_t CurSize = CurOffset - CurAddressState->MemRegion->Origin;
504906e9a18SPeter Smith     if (CurSize > CurAddressState->MemRegion->Length) {
505906e9a18SPeter Smith       uint64_t OverflowAmt = CurSize - CurAddressState->MemRegion->Length;
506906e9a18SPeter Smith       error("section '" + CurAddressState->OutSec->Name +
507906e9a18SPeter Smith             "' will not fit in region '" + CurAddressState->MemRegion->Name +
508906e9a18SPeter Smith             "': overflowed by " + Twine(OverflowAmt) + " bytes");
509b889744eSMeador Inge     }
510b889744eSMeador Inge   }
5112de509c3SRui Ueyama }
512ceabe80eSEugene Leviant 
513b8dd23f5SRui Ueyama void LinkerScript::switchTo(OutputSection *Sec) {
514906e9a18SPeter Smith   if (CurAddressState->OutSec == Sec)
515d3190795SRafael Espindola     return;
516d3190795SRafael Espindola 
517906e9a18SPeter Smith   CurAddressState->OutSec = Sec;
518906e9a18SPeter Smith   CurAddressState->OutSec->Addr =
519906e9a18SPeter Smith       advance(0, CurAddressState->OutSec->Alignment);
520b71d6f7aSEugene Leviant 
521b71d6f7aSEugene Leviant   // If neither AT nor AT> is specified for an allocatable section, the linker
522b71d6f7aSEugene Leviant   // will set the LMA such that the difference between VMA and LMA for the
523b71d6f7aSEugene Leviant   // section is the same as the preceding output section in the same region
524b71d6f7aSEugene Leviant   // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
525906e9a18SPeter Smith   if (CurAddressState->LMAOffset)
526906e9a18SPeter Smith     CurAddressState->OutSec->LMAOffset = CurAddressState->LMAOffset();
527d3190795SRafael Espindola }
528d3190795SRafael Espindola 
529b8dd23f5SRui Ueyama void LinkerScript::process(BaseCommand &Base) {
5302e081a4fSRui Ueyama   // This handles the assignments to symbol or to the dot.
5312e081a4fSRui Ueyama   if (auto *Cmd = dyn_cast<SymbolAssignment>(&Base)) {
5322e081a4fSRui Ueyama     assignSymbol(Cmd, true);
533d3190795SRafael Espindola     return;
53497403d15SEugene Leviant   }
535e38cbab5SGeorge Rimar 
536e38cbab5SGeorge Rimar   // Handle BYTE(), SHORT(), LONG(), or QUAD().
5372e081a4fSRui Ueyama   if (auto *Cmd = dyn_cast<BytesDataCommand>(&Base)) {
538906e9a18SPeter Smith     Cmd->Offset = Dot - CurAddressState->OutSec->Addr;
5392e081a4fSRui Ueyama     Dot += Cmd->Size;
540906e9a18SPeter Smith     CurAddressState->OutSec->Size = Dot - CurAddressState->OutSec->Addr;
541e38cbab5SGeorge Rimar     return;
542e38cbab5SGeorge Rimar   }
543e38cbab5SGeorge Rimar 
5442e081a4fSRui Ueyama   // Handle ASSERT().
5452e081a4fSRui Ueyama   if (auto *Cmd = dyn_cast<AssertCommand>(&Base)) {
5462e081a4fSRui Ueyama     Cmd->Expression();
547b2d99d6aSMeador Inge     return;
548b2d99d6aSMeador Inge   }
549b2d99d6aSMeador Inge 
5502e081a4fSRui Ueyama   // Handle a single input section description command.
5512e081a4fSRui Ueyama   // It calculates and assigns the offsets for each section and also
552e38cbab5SGeorge Rimar   // updates the output section size.
5532e081a4fSRui Ueyama   auto &Cmd = cast<InputSectionDescription>(Base);
554a85e8ddaSRafael Espindola   for (InputSection *Sec : Cmd.Sections) {
5553fb5a6dcSGeorge Rimar     // We tentatively added all synthetic sections at the beginning and removed
5563fb5a6dcSGeorge Rimar     // empty ones afterwards (because there is no way to know whether they were
5573fb5a6dcSGeorge Rimar     // going be empty or not other than actually running linker scripts.)
5583fb5a6dcSGeorge Rimar     // We need to ignore remains of empty sections.
5592e081a4fSRui Ueyama     if (auto *S = dyn_cast<SyntheticSection>(Sec))
5602e081a4fSRui Ueyama       if (S->empty())
5613fb5a6dcSGeorge Rimar         continue;
5623fb5a6dcSGeorge Rimar 
5632e081a4fSRui Ueyama     if (!Sec->Live)
56478ef645fSGeorge Rimar       continue;
565906e9a18SPeter Smith     assert(CurAddressState->OutSec == Sec->getParent());
566a85e8ddaSRafael Espindola     output(Sec);
567ceabe80eSEugene Leviant   }
568ceabe80eSEugene Leviant }
569ceabe80eSEugene Leviant 
570b889744eSMeador Inge // This function searches for a memory region to place the given output
571b889744eSMeador Inge // section in. If found, a pointer to the appropriate memory region is
572b889744eSMeador Inge // returned. Otherwise, a nullptr is returned.
5738c022ca7SRafael Espindola MemoryRegion *LinkerScript::findMemoryRegion(OutputSection *Sec) {
574b889744eSMeador Inge   // If a memory region name was specified in the output section command,
575b889744eSMeador Inge   // then try to find that region first.
5768c022ca7SRafael Espindola   if (!Sec->MemoryRegionName.empty()) {
5778c022ca7SRafael Espindola     auto It = Opt.MemoryRegions.find(Sec->MemoryRegionName);
578b889744eSMeador Inge     if (It != Opt.MemoryRegions.end())
5795f37541cSGeorge Rimar       return It->second;
5808c022ca7SRafael Espindola     error("memory region '" + Sec->MemoryRegionName + "' not declared");
581b889744eSMeador Inge     return nullptr;
582b889744eSMeador Inge   }
583b889744eSMeador Inge 
584d7c5400fSRui Ueyama   // If at least one memory region is defined, all sections must
585d7c5400fSRui Ueyama   // belong to some memory region. Otherwise, we don't need to do
586d7c5400fSRui Ueyama   // anything for memory regions.
587cc400cc8SRui Ueyama   if (Opt.MemoryRegions.empty())
588b889744eSMeador Inge     return nullptr;
589b889744eSMeador Inge 
590b889744eSMeador Inge   // See if a region can be found by matching section flags.
5912e081a4fSRui Ueyama   for (auto &Pair : Opt.MemoryRegions) {
5925f37541cSGeorge Rimar     MemoryRegion *M = Pair.second;
5935f37541cSGeorge Rimar     if ((M->Flags & Sec->Flags) && (M->NegFlags & Sec->Flags) == 0)
5945f37541cSGeorge Rimar       return M;
595b889744eSMeador Inge   }
596b889744eSMeador Inge 
597b889744eSMeador Inge   // Otherwise, no suitable region was found.
598b889744eSMeador Inge   if (Sec->Flags & SHF_ALLOC)
599b889744eSMeador Inge     error("no memory region specified for section '" + Sec->Name + "'");
600b889744eSMeador Inge   return nullptr;
601b889744eSMeador Inge }
602b889744eSMeador Inge 
6030b1b695aSRui Ueyama // This function assigns offsets to input sections and an output section
6040b1b695aSRui Ueyama // for a single sections command (e.g. ".text { *(.text); }").
6058c022ca7SRafael Espindola void LinkerScript::assignOffsets(OutputSection *Sec) {
606dece2808SRafael Espindola   if (!(Sec->Flags & SHF_ALLOC))
607dece2808SRafael Espindola     Dot = 0;
6088c022ca7SRafael Espindola   else if (Sec->AddrExpr)
6098c022ca7SRafael Espindola     setDot(Sec->AddrExpr, Sec->Location, false);
610679828ffSRafael Espindola 
611c2dffe3aSGeorge Rimar   CurAddressState->MemRegion = Sec->MemRegion;
612c2dffe3aSGeorge Rimar   if (CurAddressState->MemRegion)
613c2dffe3aSGeorge Rimar     Dot = CurAddressState->MemRegionOffset[CurAddressState->MemRegion];
614c2dffe3aSGeorge Rimar 
6158c022ca7SRafael Espindola   if (Sec->LMAExpr) {
6160c1c8085SGeorge Rimar     uint64_t D = Dot;
6178c022ca7SRafael Espindola     CurAddressState->LMAOffset = [=] { return Sec->LMAExpr().getValue() - D; };
6185784e96fSEugene Leviant   }
6195784e96fSEugene Leviant 
620b889744eSMeador Inge   switchTo(Sec);
6210b1b695aSRui Ueyama 
622d86a4e50SGeorge Rimar   // We do not support custom layout for compressed debug sectons.
623d86a4e50SGeorge Rimar   // At this point we already know their size and have compressed content.
624906e9a18SPeter Smith   if (CurAddressState->OutSec->Flags & SHF_COMPRESSED)
625d86a4e50SGeorge Rimar     return;
626d86a4e50SGeorge Rimar 
6278c022ca7SRafael Espindola   for (BaseCommand *C : Sec->Commands)
628de8d9897SRafael Espindola     process(*C);
629d3190795SRafael Espindola }
630d3190795SRafael Espindola 
631b8dd23f5SRui Ueyama void LinkerScript::removeEmptyCommands() {
6326d38e4dbSRafael Espindola   // It is common practice to use very generic linker scripts. So for any
6336d38e4dbSRafael Espindola   // given run some of the output sections in the script will be empty.
6346d38e4dbSRafael Espindola   // We could create corresponding empty output sections, but that would
6356d38e4dbSRafael Espindola   // clutter the output.
6366d38e4dbSRafael Espindola   // We instead remove trivially empty sections. The bfd linker seems even
6376d38e4dbSRafael Espindola   // more aggressive at removing them.
63860608a8aSGeorge Rimar   llvm::erase_if(Opt.Commands, [&](BaseCommand *Base) {
6398c022ca7SRafael Espindola     if (auto *Sec = dyn_cast<OutputSection>(Base))
6408c022ca7SRafael Espindola       return !Sec->Live;
6410b1b695aSRui Ueyama     return false;
6426d38e4dbSRafael Espindola   });
64307fe6129SRafael Espindola }
64407fe6129SRafael Espindola 
6458c022ca7SRafael Espindola static bool isAllSectionDescription(const OutputSection &Cmd) {
6468f99f73cSRui Ueyama   for (BaseCommand *Base : Cmd.Commands)
6478f99f73cSRui Ueyama     if (!isa<InputSectionDescription>(*Base))
6486a53737cSRafael Espindola       return false;
6496a53737cSRafael Espindola   return true;
6506a53737cSRafael Espindola }
6516d38e4dbSRafael Espindola 
652b8dd23f5SRui Ueyama void LinkerScript::adjustSectionsBeforeSorting() {
6539546fffbSRafael Espindola   // If the output section contains only symbol assignments, create a
6549546fffbSRafael Espindola   // corresponding output section. The bfd linker seems to only create them if
6559546fffbSRafael Espindola   // '.' is assigned to, but creating these section should not have any bad
6569546fffbSRafael Espindola   // consequeces and gives us a section to put the symbol in.
6570c1c8085SGeorge Rimar   uint64_t Flags = SHF_ALLOC;
658660c9ab9SRafael Espindola 
6598962db91SGeorge Rimar   for (BaseCommand * Cmd : Opt.Commands) {
6608962db91SGeorge Rimar     auto *Sec = dyn_cast<OutputSection>(Cmd);
6618c022ca7SRafael Espindola     if (!Sec)
6629546fffbSRafael Espindola       continue;
6638c022ca7SRafael Espindola     if (Sec->Live) {
6642b074553SRafael Espindola       Flags = Sec->Flags;
6659546fffbSRafael Espindola       continue;
6669546fffbSRafael Espindola     }
6679546fffbSRafael Espindola 
6688c022ca7SRafael Espindola     if (isAllSectionDescription(*Sec))
6696a53737cSRafael Espindola       continue;
6706a53737cSRafael Espindola 
6718c022ca7SRafael Espindola     Sec->Live = true;
6728c022ca7SRafael Espindola     Sec->Flags = Flags;
6739546fffbSRafael Espindola   }
674f7a17448SRafael Espindola }
675f7a17448SRafael Espindola 
676b8dd23f5SRui Ueyama void LinkerScript::adjustSectionsAfterSorting() {
677feed7506SRafael Espindola   // Try and find an appropriate memory region to assign offsets in.
678d1960dc0SRafael Espindola   for (BaseCommand *Base : Opt.Commands) {
6798c022ca7SRafael Espindola     if (auto *Sec = dyn_cast<OutputSection>(Base)) {
6808c022ca7SRafael Espindola       Sec->MemRegion = findMemoryRegion(Sec);
681d1960dc0SRafael Espindola       // Handle align (e.g. ".foo : ALIGN(16) { ... }").
6828c022ca7SRafael Espindola       if (Sec->AlignExpr)
6838c022ca7SRafael Espindola         Sec->updateAlignment(Sec->AlignExpr().getValue());
684d1960dc0SRafael Espindola     }
685d1960dc0SRafael Espindola   }
686feed7506SRafael Espindola 
687f7a17448SRafael Espindola   // If output section command doesn't specify any segments,
688f7a17448SRafael Espindola   // and we haven't previously assigned any section to segment,
689f7a17448SRafael Espindola   // then we simply assign section to the very first load segment.
690f7a17448SRafael Espindola   // Below is an example of such linker script:
691f7a17448SRafael Espindola   // PHDRS { seg PT_LOAD; }
692f7a17448SRafael Espindola   // SECTIONS { .aaa : { *(.aaa) } }
693f7a17448SRafael Espindola   std::vector<StringRef> DefPhdrs;
694f7a17448SRafael Espindola   auto FirstPtLoad =
695f7a17448SRafael Espindola       std::find_if(Opt.PhdrsCommands.begin(), Opt.PhdrsCommands.end(),
696f7a17448SRafael Espindola                    [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; });
697f7a17448SRafael Espindola   if (FirstPtLoad != Opt.PhdrsCommands.end())
698f7a17448SRafael Espindola     DefPhdrs.push_back(FirstPtLoad->Name);
699f7a17448SRafael Espindola 
700f7a17448SRafael Espindola   // Walk the commands and propagate the program headers to commands that don't
701f7a17448SRafael Espindola   // explicitly specify them.
7028f99f73cSRui Ueyama   for (BaseCommand *Base : Opt.Commands) {
7038c022ca7SRafael Espindola     auto *Sec = dyn_cast<OutputSection>(Base);
7048c022ca7SRafael Espindola     if (!Sec)
705f7a17448SRafael Espindola       continue;
7068f99f73cSRui Ueyama 
7078c022ca7SRafael Espindola     if (Sec->Phdrs.empty()) {
708a020d348SAndrew Ng       // To match the bfd linker script behaviour, only propagate program
709a020d348SAndrew Ng       // headers to sections that are allocated.
7108c022ca7SRafael Espindola       if (Sec->Flags & SHF_ALLOC)
7118c022ca7SRafael Espindola         Sec->Phdrs = DefPhdrs;
712a020d348SAndrew Ng     } else {
7138c022ca7SRafael Espindola       DefPhdrs = Sec->Phdrs;
714f7a17448SRafael Espindola     }
715a020d348SAndrew Ng   }
7166a53737cSRafael Espindola 
7176a53737cSRafael Espindola   removeEmptyCommands();
7189546fffbSRafael Espindola }
7199546fffbSRafael Espindola 
720582ede89SGeorge Rimar static OutputSection *findFirstSection(PhdrEntry *Load) {
721582ede89SGeorge Rimar   for (OutputSection *Sec : OutputSections)
722582ede89SGeorge Rimar     if (Sec->PtLoad == Load)
723582ede89SGeorge Rimar       return Sec;
724582ede89SGeorge Rimar   return nullptr;
725582ede89SGeorge Rimar }
726582ede89SGeorge Rimar 
727b93c5b9fSPetr Hosek // Try to find an address for the file and program headers output sections,
728b93c5b9fSPetr Hosek // which were unconditionally added to the first PT_LOAD segment earlier.
729b93c5b9fSPetr Hosek //
730b93c5b9fSPetr Hosek // When using the default layout, we check if the headers fit below the first
731b93c5b9fSPetr Hosek // allocated section. When using a linker script, we also check if the headers
732b93c5b9fSPetr Hosek // are covered by the output section. This allows omitting the headers by not
733b93c5b9fSPetr Hosek // leaving enough space for them in the linker script; this pattern is common
734b93c5b9fSPetr Hosek // in embedded systems.
735b93c5b9fSPetr Hosek //
736b93c5b9fSPetr Hosek // If there isn't enough space for these sections, we'll remove them from the
737b93c5b9fSPetr Hosek // PT_LOAD segment, and we'll also remove the PT_PHDR segment.
738aa354187SGeorge Rimar void LinkerScript::allocateHeaders(std::vector<PhdrEntry *> &Phdrs) {
7395aedebffSPeter Smith   uint64_t Min = std::numeric_limits<uint64_t>::max();
7408c022ca7SRafael Espindola   for (OutputSection *Sec : OutputSections)
7415aedebffSPeter Smith     if (Sec->Flags & SHF_ALLOC)
7425aedebffSPeter Smith       Min = std::min<uint64_t>(Min, Sec->Addr);
7435aedebffSPeter Smith 
744aa354187SGeorge Rimar   auto It = llvm::find_if(
745aa354187SGeorge Rimar       Phdrs, [](const PhdrEntry *E) { return E->p_type == PT_LOAD; });
746aa354187SGeorge Rimar   if (It == Phdrs.end())
747d971e703SGeorge Rimar     return;
748aa354187SGeorge Rimar   PhdrEntry *FirstPTLoad = *It;
74902ed7575SRafael Espindola 
75002ed7575SRafael Espindola   uint64_t HeaderSize = getHeaderSize();
751b93c5b9fSPetr Hosek   // When linker script with SECTIONS is being used, don't output headers
752b93c5b9fSPetr Hosek   // unless there's a space for them.
753b93c5b9fSPetr Hosek   uint64_t Base = Opt.HasSections ? alignDown(Min, Config->MaxPageSize) : 0;
754b93c5b9fSPetr Hosek   if (HeaderSize <= Min - Base || Script->hasPhdrsCommands()) {
755b93c5b9fSPetr Hosek     Min = Opt.HasSections ? Base
756b93c5b9fSPetr Hosek                           : alignDown(Min - HeaderSize, Config->MaxPageSize);
75702ed7575SRafael Espindola     Out::ElfHeader->Addr = Min;
75802ed7575SRafael Espindola     Out::ProgramHeaders->Addr = Min + Out::ElfHeader->Size;
759d971e703SGeorge Rimar     return;
76002ed7575SRafael Espindola   }
76102ed7575SRafael Espindola 
762582ede89SGeorge Rimar   Out::ElfHeader->PtLoad = nullptr;
763582ede89SGeorge Rimar   Out::ProgramHeaders->PtLoad = nullptr;
7646823c5f0SGeorge Rimar   FirstPTLoad->FirstSec = findFirstSection(FirstPTLoad);
76502ed7575SRafael Espindola 
76660608a8aSGeorge Rimar   llvm::erase_if(Phdrs,
76760608a8aSGeorge Rimar                  [](const PhdrEntry *E) { return E->p_type == PT_PHDR; });
76802ed7575SRafael Espindola }
76902ed7575SRafael Espindola 
770906e9a18SPeter Smith LinkerScript::AddressState::AddressState(const ScriptConfiguration &Opt) {
771906e9a18SPeter Smith   for (auto &MRI : Opt.MemoryRegions) {
7725f37541cSGeorge Rimar     const MemoryRegion *MR = MRI.second;
773906e9a18SPeter Smith     MemRegionOffset[MR] = MR->Origin;
774906e9a18SPeter Smith   }
775906e9a18SPeter Smith }
776906e9a18SPeter Smith 
7775aedebffSPeter Smith void LinkerScript::assignAddresses() {
7787c18c28cSRui Ueyama   // Assign addresses as instructed by linker script SECTIONS sub-commands.
779be607334SRafael Espindola   Dot = 0;
780906e9a18SPeter Smith   auto State = make_unique<AddressState>(Opt);
781c1ace40bSPeter Smith   // CurAddressState captures the local AddressState and makes it accessible
782c1ace40bSPeter Smith   // deliberately. This is needed as there are some cases where we cannot just
783c1ace40bSPeter Smith   // thread the current state through to a lambda function created by the
784c1ace40bSPeter Smith   // script parser.
785906e9a18SPeter Smith   CurAddressState = State.get();
78672dc195dSRafael Espindola   ErrorOnMissingSection = true;
78706f4743aSRafael Espindola   switchTo(Aether);
78806f4743aSRafael Espindola 
7898f99f73cSRui Ueyama   for (BaseCommand *Base : Opt.Commands) {
7908f99f73cSRui Ueyama     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base)) {
791d379f735SRui Ueyama       assignSymbol(Cmd, false);
79205ef4cffSRui Ueyama       continue;
793652852c5SGeorge Rimar     }
794652852c5SGeorge Rimar 
7958f99f73cSRui Ueyama     if (auto *Cmd = dyn_cast<AssertCommand>(Base)) {
7964595df94SRafael Espindola       Cmd->Expression();
797eefa758eSGeorge Rimar       continue;
798eefa758eSGeorge Rimar     }
799eefa758eSGeorge Rimar 
8008c022ca7SRafael Espindola     assignOffsets(cast<OutputSection>(Base));
801a14b13d8SGeorge Rimar   }
802c1ace40bSPeter Smith   CurAddressState = nullptr;
803fb8978fcSDima Stepanov }
804652852c5SGeorge Rimar 
805464daadcSRui Ueyama // Creates program headers as instructed by PHDRS linker script command.
806aa354187SGeorge Rimar std::vector<PhdrEntry *> LinkerScript::createPhdrs() {
807aa354187SGeorge Rimar   std::vector<PhdrEntry *> Ret;
808bbe38602SEugene Leviant 
809464daadcSRui Ueyama   // Process PHDRS and FILEHDR keywords because they are not
810464daadcSRui Ueyama   // real output sections and cannot be added in the following loop.
811bbe38602SEugene Leviant   for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
812aa354187SGeorge Rimar     PhdrEntry *Phdr =
813aa354187SGeorge Rimar         make<PhdrEntry>(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
814bbe38602SEugene Leviant 
815bbe38602SEugene Leviant     if (Cmd.HasFilehdr)
816aa354187SGeorge Rimar       Phdr->add(Out::ElfHeader);
817bbe38602SEugene Leviant     if (Cmd.HasPhdrs)
818aa354187SGeorge Rimar       Phdr->add(Out::ProgramHeaders);
81956b21c86SEugene Leviant 
82056b21c86SEugene Leviant     if (Cmd.LMAExpr) {
821aa354187SGeorge Rimar       Phdr->p_paddr = Cmd.LMAExpr().getValue();
822aa354187SGeorge Rimar       Phdr->HasLMA = true;
82356b21c86SEugene Leviant     }
824aa354187SGeorge Rimar     Ret.push_back(Phdr);
825bbe38602SEugene Leviant   }
826bbe38602SEugene Leviant 
827464daadcSRui Ueyama   // Add output sections to program headers.
8288c022ca7SRafael Espindola   for (OutputSection *Sec : OutputSections) {
829bbe38602SEugene Leviant     // Assign headers specified by linker script
8308c022ca7SRafael Espindola     for (size_t Id : getPhdrIndices(Sec)) {
831aa354187SGeorge Rimar       Ret[Id]->add(Sec);
832865bf863SEugene Leviant       if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
833aa354187SGeorge Rimar         Ret[Id]->p_flags |= Sec->getPhdrFlags();
834bbe38602SEugene Leviant     }
835bbe38602SEugene Leviant   }
836edebbdf1SRui Ueyama   return Ret;
837bbe38602SEugene Leviant }
838bbe38602SEugene Leviant 
839b8dd23f5SRui Ueyama bool LinkerScript::ignoreInterpSection() {
840f9bc3bd2SEugene Leviant   // Ignore .interp section in case we have PHDRS specification
841f9bc3bd2SEugene Leviant   // and PT_INTERP isn't listed.
842e31d9886SRui Ueyama   if (Opt.PhdrsCommands.empty())
843e31d9886SRui Ueyama     return false;
844e31d9886SRui Ueyama   for (PhdrsCommand &Cmd : Opt.PhdrsCommands)
845e31d9886SRui Ueyama     if (Cmd.Type == PT_INTERP)
846e31d9886SRui Ueyama       return false;
847e31d9886SRui Ueyama   return true;
848f9bc3bd2SEugene Leviant }
849f9bc3bd2SEugene Leviant 
850b8dd23f5SRui Ueyama ExprValue LinkerScript::getSymbolValue(const Twine &Loc, StringRef S) {
8517e5b0a59SGeorge Rimar   if (S == ".") {
8527e5b0a59SGeorge Rimar     if (CurAddressState)
8537e5b0a59SGeorge Rimar       return {CurAddressState->OutSec, Dot - CurAddressState->OutSec->Addr,
8547e5b0a59SGeorge Rimar               Loc};
8557e5b0a59SGeorge Rimar     error(Loc + ": unable to get location counter value");
8567e5b0a59SGeorge Rimar     return 0;
8577e5b0a59SGeorge Rimar   }
858244ef981SRafael Espindola   if (SymbolBody *B = Symtab->find(S)) {
85972dc195dSRafael Espindola     if (auto *D = dyn_cast<DefinedRegular>(B))
86041c7ab4aSGeorge Rimar       return {D->Section, D->Value, Loc};
86130f16b23SPetr Hosek     if (auto *C = dyn_cast<DefinedCommon>(B))
86267df57a2SRafael Espindola       return {C->Section, 0, Loc};
86372dc195dSRafael Espindola   }
864f6aeed36SEugene Leviant   error(Loc + ": symbol not found: " + S);
865884e786dSGeorge Rimar   return 0;
866884e786dSGeorge Rimar }
867884e786dSGeorge Rimar 
868244ef981SRafael Espindola bool LinkerScript::isDefined(StringRef S) { return Symtab->find(S) != nullptr; }
869f34f45fdSGeorge Rimar 
8706e9f98c1SAndrew Ng static const size_t NoPhdr = -1;
8716e9f98c1SAndrew Ng 
8722c923c2cSRafael Espindola // Returns indices of ELF headers containing specific section. Each index is a
8732c923c2cSRafael Espindola // zero based number of ELF header listed within PHDRS {} script block.
8748c022ca7SRafael Espindola std::vector<size_t> LinkerScript::getPhdrIndices(OutputSection *Cmd) {
87529c5a2a9SRui Ueyama   std::vector<size_t> Ret;
8766e9f98c1SAndrew Ng   for (StringRef PhdrName : Cmd->Phdrs) {
8776e9f98c1SAndrew Ng     size_t Index = getPhdrIndex(Cmd->Location, PhdrName);
8786e9f98c1SAndrew Ng     if (Index != NoPhdr)
8796e9f98c1SAndrew Ng       Ret.push_back(Index);
8806e9f98c1SAndrew Ng   }
88129c5a2a9SRui Ueyama   return Ret;
882bbe38602SEugene Leviant }
883bbe38602SEugene Leviant 
8846e9f98c1SAndrew Ng // Returns the index of the segment named PhdrName if found otherwise
8856e9f98c1SAndrew Ng // NoPhdr. When not found, if PhdrName is not the special case value 'NONE'
8866e9f98c1SAndrew Ng // (which can be used to explicitly specify that a section isn't assigned to a
8876e9f98c1SAndrew Ng // segment) then error.
888b8dd23f5SRui Ueyama size_t LinkerScript::getPhdrIndex(const Twine &Loc, StringRef PhdrName) {
88929c5a2a9SRui Ueyama   size_t I = 0;
89029c5a2a9SRui Ueyama   for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
89129c5a2a9SRui Ueyama     if (Cmd.Name == PhdrName)
89229c5a2a9SRui Ueyama       return I;
89329c5a2a9SRui Ueyama     ++I;
89429c5a2a9SRui Ueyama   }
8956e9f98c1SAndrew Ng   if (PhdrName != "NONE")
8962a942c4bSEugene Leviant     error(Loc + ": section header '" + PhdrName + "' is not listed in PHDRS");
8976e9f98c1SAndrew Ng   return NoPhdr;
89829c5a2a9SRui Ueyama }
899