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 
73a5e8dd35SRafael Espindola static SymbolBody *addRegular(SymbolAssignment *Cmd) {
745e51f7d2SPetr Hosek   Symbol *Sym;
753dabfc6bSRafael Espindola   uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
76244ef981SRafael Espindola   std::tie(Sym, std::ignore) = Symtab->insert(Cmd->Name, /*Type*/ 0, Visibility,
77244ef981SRafael Espindola                                               /*CanOmitFromDynSym*/ false,
785e51f7d2SPetr Hosek                                               /*File*/ nullptr);
795e51f7d2SPetr Hosek   Sym->Binding = STB_GLOBAL;
8072dc195dSRafael Espindola   ExprValue Value = Cmd->Expression();
8172dc195dSRafael Espindola   SectionBase *Sec = Value.isAbsolute() ? nullptr : Value.Sec;
8201aa795fSGeorge Rimar 
8301aa795fSGeorge Rimar   // We want to set symbol values early if we can. This allows us to use symbols
8401aa795fSGeorge Rimar   // as variables in linker scripts. Doing so allows us to write expressions
8501aa795fSGeorge Rimar   // like this: `alignment = 16; . = ALIGN(., alignment)`
8601aa795fSGeorge Rimar   uint64_t SymValue = Value.isAbsolute() ? Value.getValue() : 0;
876e93d054SRafael Espindola   replaceBody<DefinedRegular>(Sym, nullptr, Cmd->Name, /*IsLocal=*/false,
886e93d054SRafael Espindola                               Visibility, STT_NOTYPE, SymValue, 0, Sec);
898f1f3c40SMeador Inge   return Sym->body();
90ceabe80eSEugene Leviant }
91ceabe80eSEugene Leviant 
928c022ca7SRafael Espindola OutputSection *LinkerScript::createOutputSection(StringRef Name,
938c022ca7SRafael Espindola                                                  StringRef Location) {
948c022ca7SRafael Espindola   OutputSection *&SecRef = NameToOutputSection[Name];
958c022ca7SRafael Espindola   OutputSection *Sec;
968c022ca7SRafael Espindola   if (SecRef && SecRef->Location.empty()) {
9705c4f67cSRafael Espindola     // There was a forward reference.
988c022ca7SRafael Espindola     Sec = SecRef;
9905c4f67cSRafael Espindola   } else {
1008c022ca7SRafael Espindola     Sec = make<OutputSection>(Name, SHT_PROGBITS, 0);
1018c022ca7SRafael Espindola     if (!SecRef)
1028c022ca7SRafael Espindola       SecRef = Sec;
10305c4f67cSRafael Espindola   }
1048c022ca7SRafael Espindola   Sec->Location = Location;
1058c022ca7SRafael Espindola   return Sec;
106851dc1e8SGeorge Rimar }
107851dc1e8SGeorge Rimar 
1088c022ca7SRafael Espindola OutputSection *LinkerScript::getOrCreateOutputSection(StringRef Name) {
1098c022ca7SRafael Espindola   OutputSection *&CmdRef = NameToOutputSection[Name];
11005c4f67cSRafael Espindola   if (!CmdRef)
1118c022ca7SRafael Espindola     CmdRef = make<OutputSection>(Name, SHT_PROGBITS, 0);
11205c4f67cSRafael Espindola   return CmdRef;
113d83ce1b4SGeorge Rimar }
114d83ce1b4SGeorge Rimar 
115b8dd23f5SRui Ueyama void LinkerScript::setDot(Expr E, const Twine &Loc, bool InSec) {
11672dc195dSRafael Espindola   uint64_t Val = E().getValue();
1178c804d97SGeorge Rimar   if (Val < Dot && InSec)
1182ee2d2dcSGeorge Rimar     error(Loc + ": unable to move location counter backward for: " +
119906e9a18SPeter Smith           CurAddressState->OutSec->Name);
1204cd7352cSRafael Espindola   Dot = Val;
1214cd7352cSRafael Espindola   // Update to location counter means update to section size.
1224cd7352cSRafael Espindola   if (InSec)
123906e9a18SPeter Smith     CurAddressState->OutSec->Size = Dot - CurAddressState->OutSec->Addr;
124679828ffSRafael Espindola }
125679828ffSRafael Espindola 
126679828ffSRafael Espindola // Sets value of a symbol. Two kinds of symbols are processed: synthetic
127679828ffSRafael Espindola // symbols, whose value is an offset from beginning of section and regular
128679828ffSRafael Espindola // symbols whose value is absolute.
129b8dd23f5SRui Ueyama void LinkerScript::assignSymbol(SymbolAssignment *Cmd, bool InSec) {
130679828ffSRafael Espindola   if (Cmd->Name == ".") {
1312ee2d2dcSGeorge Rimar     setDot(Cmd->Expression, Cmd->Location, InSec);
1324cd7352cSRafael Espindola     return;
1334cd7352cSRafael Espindola   }
1344cd7352cSRafael Espindola 
135b2b70975SGeorge Rimar   if (!Cmd->Sym)
1368f1f3c40SMeador Inge     return;
1378f1f3c40SMeador Inge 
1385616adf6SRafael Espindola   auto *Sym = cast<DefinedRegular>(Cmd->Sym);
13972dc195dSRafael Espindola   ExprValue V = Cmd->Expression();
14072dc195dSRafael Espindola   if (V.isAbsolute()) {
14172dc195dSRafael Espindola     Sym->Value = V.getValue();
14272dc195dSRafael Espindola   } else {
14372dc195dSRafael Espindola     Sym->Section = V.Sec;
1443c6de1a6SPetr Hosek     Sym->Value = alignTo(V.Val, V.Alignment);
145ea590d91SRafael Espindola   }
1468f1f3c40SMeador Inge }
1478f1f3c40SMeador Inge 
148b8dd23f5SRui Ueyama void LinkerScript::addSymbol(SymbolAssignment *Cmd) {
1491602421cSRui Ueyama   if (Cmd->Name == ".")
1508f1f3c40SMeador Inge     return;
1518f1f3c40SMeador Inge 
1528f1f3c40SMeador Inge   // If a symbol was in PROVIDE(), we need to define it only when
1538f1f3c40SMeador Inge   // it is a referenced undefined symbol.
154244ef981SRafael Espindola   SymbolBody *B = Symtab->find(Cmd->Name);
1558f1f3c40SMeador Inge   if (Cmd->Provide && (!B || B->isDefined()))
1568f1f3c40SMeador Inge     return;
1578f1f3c40SMeador Inge 
158a5e8dd35SRafael Espindola   Cmd->Sym = addRegular(Cmd);
159ceabe80eSEugene Leviant }
160ceabe80eSEugene Leviant 
161076fe157SGeorge Rimar bool SymbolAssignment::classof(const BaseCommand *C) {
162076fe157SGeorge Rimar   return C->Kind == AssignmentKind;
163076fe157SGeorge Rimar }
164076fe157SGeorge Rimar 
165eea3114fSGeorge Rimar bool InputSectionDescription::classof(const BaseCommand *C) {
166eea3114fSGeorge Rimar   return C->Kind == InputSectionKind;
167eea3114fSGeorge Rimar }
168eea3114fSGeorge Rimar 
169eefa758eSGeorge Rimar bool AssertCommand::classof(const BaseCommand *C) {
170eefa758eSGeorge Rimar   return C->Kind == AssertKind;
171eefa758eSGeorge Rimar }
172eefa758eSGeorge Rimar 
173e38cbab5SGeorge Rimar bool BytesDataCommand::classof(const BaseCommand *C) {
174e38cbab5SGeorge Rimar   return C->Kind == BytesDataKind;
175e38cbab5SGeorge Rimar }
176e38cbab5SGeorge Rimar 
177f300ca21SDmitry Mikulin static std::string filename(InputSectionBase *S) {
178f300ca21SDmitry Mikulin   if (!S->File)
179e0be2901SRui Ueyama     return "";
180f300ca21SDmitry Mikulin   if (S->File->ArchiveName.empty())
181f300ca21SDmitry Mikulin     return S->File->getName();
182f300ca21SDmitry Mikulin   return (S->File->ArchiveName + "(" + S->File->getName() + ")").str();
183e0be2901SRui Ueyama }
184e0be2901SRui Ueyama 
185b8dd23f5SRui Ueyama bool LinkerScript::shouldKeep(InputSectionBase *S) {
186f300ca21SDmitry Mikulin   for (InputSectionDescription *ID : Opt.KeptSections) {
187f300ca21SDmitry Mikulin     std::string Filename = filename(S);
188f300ca21SDmitry Mikulin     if (ID->FilePat.match(Filename))
189cf43f179SEugene Leviant       for (SectionPattern &P : ID->SectionPatterns)
190f91282e1SRui Ueyama         if (P.SectionPat.match(S->Name))
191eea3114fSGeorge Rimar           return true;
192f300ca21SDmitry Mikulin   }
193eea3114fSGeorge Rimar   return false;
194eea3114fSGeorge Rimar }
195eea3114fSGeorge Rimar 
196ea93fe00SRui Ueyama // A helper function for the SORT() command.
197c404d50dSRafael Espindola static std::function<bool(InputSectionBase *, InputSectionBase *)>
198be394db3SGeorge Rimar getComparator(SortSectionPolicy K) {
199be394db3SGeorge Rimar   switch (K) {
200be394db3SGeorge Rimar   case SortSectionPolicy::Alignment:
201ea93fe00SRui Ueyama     return [](InputSectionBase *A, InputSectionBase *B) {
202ea93fe00SRui Ueyama       // ">" is not a mistake. Sections with larger alignments are placed
203ea93fe00SRui Ueyama       // before sections with smaller alignments in order to reduce the
204ea93fe00SRui Ueyama       // amount of padding necessary. This is compatible with GNU.
205ea93fe00SRui Ueyama       return A->Alignment > B->Alignment;
206ea93fe00SRui Ueyama     };
207be394db3SGeorge Rimar   case SortSectionPolicy::Name:
208ea93fe00SRui Ueyama     return [](InputSectionBase *A, InputSectionBase *B) {
209ea93fe00SRui Ueyama       return A->Name < B->Name;
210ea93fe00SRui Ueyama     };
211be394db3SGeorge Rimar   case SortSectionPolicy::Priority:
212ea93fe00SRui Ueyama     return [](InputSectionBase *A, InputSectionBase *B) {
213ea93fe00SRui Ueyama       return getPriority(A->Name) < getPriority(B->Name);
214ea93fe00SRui Ueyama     };
215be394db3SGeorge Rimar   default:
216be394db3SGeorge Rimar     llvm_unreachable("unknown sort policy");
217be394db3SGeorge Rimar   }
218742c3836SRui Ueyama }
2190702c4e8SGeorge Rimar 
220ea93fe00SRui Ueyama // A helper function for the SORT() command.
221b4c9b81aSRafael Espindola static bool matchConstraints(ArrayRef<InputSectionBase *> Sections,
22206ae6836SGeorge Rimar                              ConstraintKind Kind) {
2238f66df92SGeorge Rimar   if (Kind == ConstraintKind::NoConstraint)
2248f66df92SGeorge Rimar     return true;
2252c7171bfSRui Ueyama 
2262c7171bfSRui Ueyama   bool IsRW = llvm::any_of(Sections, [](InputSectionBase *Sec) {
2272c7171bfSRui Ueyama     return static_cast<InputSectionBase *>(Sec)->Flags & SHF_WRITE;
22806ae6836SGeorge Rimar   });
2292c7171bfSRui Ueyama 
230e746e52cSRafael Espindola   return (IsRW && Kind == ConstraintKind::ReadWrite) ||
231e746e52cSRafael Espindola          (!IsRW && Kind == ConstraintKind::ReadOnly);
23206ae6836SGeorge Rimar }
23306ae6836SGeorge Rimar 
2346a1aa8d9SRafael Espindola static void sortSections(InputSection **Begin, InputSection **End,
235ee924709SRui Ueyama                          SortSectionPolicy K) {
236ee924709SRui Ueyama   if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
23707171f21SGeorge Rimar     std::stable_sort(Begin, End, getComparator(K));
238ee924709SRui Ueyama }
239ee924709SRui Ueyama 
240d6bcde38SGeorge Rimar static llvm::DenseMap<SectionBase *, int> getSectionOrder() {
241d6bcde38SGeorge Rimar   switch (Config->EKind) {
242d6bcde38SGeorge Rimar   case ELF32LEKind:
243d6bcde38SGeorge Rimar     return buildSectionOrder<ELF32LE>();
244d6bcde38SGeorge Rimar   case ELF32BEKind:
245d6bcde38SGeorge Rimar     return buildSectionOrder<ELF32BE>();
246d6bcde38SGeorge Rimar   case ELF64LEKind:
247d6bcde38SGeorge Rimar     return buildSectionOrder<ELF64LE>();
248d6bcde38SGeorge Rimar   case ELF64BEKind:
249d6bcde38SGeorge Rimar     return buildSectionOrder<ELF64BE>();
250d6bcde38SGeorge Rimar   default:
251d6bcde38SGeorge Rimar     llvm_unreachable("unknown ELF type");
252d6bcde38SGeorge Rimar   }
253d6bcde38SGeorge Rimar }
254d6bcde38SGeorge Rimar 
255d6bcde38SGeorge Rimar static void sortBySymbolOrder(InputSection **Begin, InputSection **End) {
256d6bcde38SGeorge Rimar   if (Config->SymbolOrderingFile.empty())
257d6bcde38SGeorge Rimar     return;
258d6bcde38SGeorge Rimar   static llvm::DenseMap<SectionBase *, int> Order = getSectionOrder();
259d6bcde38SGeorge Rimar   MutableArrayRef<InputSection *> In(Begin, End - Begin);
260d6bcde38SGeorge Rimar   sortByOrder(In, [&](InputSectionBase *S) { return Order.lookup(S); });
261d6bcde38SGeorge Rimar }
262d6bcde38SGeorge Rimar 
263d3190795SRafael Espindola // Compute and remember which sections the InputSectionDescription matches.
2646a1aa8d9SRafael Espindola std::vector<InputSection *>
26572e107f3SRui Ueyama LinkerScript::computeInputSections(const InputSectionDescription *Cmd) {
2666a1aa8d9SRafael Espindola   std::vector<InputSection *> Ret;
2678c6a5aafSRui Ueyama 
26872e107f3SRui Ueyama   // Collects all sections that satisfy constraints of Cmd.
26972e107f3SRui Ueyama   for (const SectionPattern &Pat : Cmd->SectionPatterns) {
27072e107f3SRui Ueyama     size_t SizeBefore = Ret.size();
27172e107f3SRui Ueyama 
27272e107f3SRui Ueyama     for (InputSectionBase *Sec : InputSections) {
27372e107f3SRui Ueyama       if (Sec->Assigned)
2748c6a5aafSRui Ueyama         continue;
27572e107f3SRui Ueyama 
276e39709b2SRafael Espindola       if (!Sec->Live) {
277e39709b2SRafael Espindola         reportDiscarded(Sec);
278e39709b2SRafael Espindola         continue;
279e39709b2SRafael Espindola       }
280e39709b2SRafael Espindola 
281908a3d34SRafael Espindola       // For -emit-relocs we have to ignore entries like
282908a3d34SRafael Espindola       //   .rela.dyn : { *(.rela.data) }
283908a3d34SRafael Espindola       // which are common because they are in the default bfd script.
28472e107f3SRui Ueyama       if (Sec->Type == SHT_REL || Sec->Type == SHT_RELA)
285908a3d34SRafael Espindola         continue;
2868c6a5aafSRui Ueyama 
287f300ca21SDmitry Mikulin       std::string Filename = filename(Sec);
28872e107f3SRui Ueyama       if (!Cmd->FilePat.match(Filename) ||
28972e107f3SRui Ueyama           Pat.ExcludedFilePat.match(Filename) ||
29072e107f3SRui Ueyama           !Pat.SectionPat.match(Sec->Name))
291e0be2901SRui Ueyama         continue;
29272e107f3SRui Ueyama 
2936a1aa8d9SRafael Espindola       Ret.push_back(cast<InputSection>(Sec));
29472e107f3SRui Ueyama       Sec->Assigned = true;
295f94efdddSRui Ueyama     }
296d3190795SRafael Espindola 
297ee924709SRui Ueyama     // Sort sections as instructed by SORT-family commands and --sort-section
298ee924709SRui Ueyama     // option. Because SORT-family commands can be nested at most two depth
299ee924709SRui Ueyama     // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
300ee924709SRui Ueyama     // line option is respected even if a SORT command is given, the exact
301ee924709SRui Ueyama     // behavior we have here is a bit complicated. Here are the rules.
302ee924709SRui Ueyama     //
303ee924709SRui Ueyama     // 1. If two SORT commands are given, --sort-section is ignored.
304ee924709SRui Ueyama     // 2. If one SORT command is given, and if it is not SORT_NONE,
305ee924709SRui Ueyama     //    --sort-section is handled as an inner SORT command.
306ee924709SRui Ueyama     // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
307ee924709SRui Ueyama     // 4. If no SORT command is given, sort according to --sort-section.
308d6bcde38SGeorge Rimar     // 5. If no SORT commands are given and --sort-section is not specified,
309d6bcde38SGeorge Rimar     //    apply sorting provided by --symbol-ordering-file if any exist.
3106a1aa8d9SRafael Espindola     InputSection **Begin = Ret.data() + SizeBefore;
3116a1aa8d9SRafael Espindola     InputSection **End = Ret.data() + Ret.size();
312d6bcde38SGeorge Rimar     if (Pat.SortOuter == SortSectionPolicy::Default &&
313d6bcde38SGeorge Rimar         Config->SortSection == SortSectionPolicy::Default) {
314d6bcde38SGeorge Rimar       sortBySymbolOrder(Begin, End);
315d6bcde38SGeorge Rimar       continue;
316d6bcde38SGeorge Rimar     }
31707171f21SGeorge Rimar     if (Pat.SortOuter != SortSectionPolicy::None) {
31807171f21SGeorge Rimar       if (Pat.SortInner == SortSectionPolicy::Default)
31907171f21SGeorge Rimar         sortSections(Begin, End, Config->SortSection);
320ee924709SRui Ueyama       else
32107171f21SGeorge Rimar         sortSections(Begin, End, Pat.SortInner);
32207171f21SGeorge Rimar       sortSections(Begin, End, Pat.SortOuter);
32307171f21SGeorge Rimar     }
324ee924709SRui Ueyama   }
32572e107f3SRui Ueyama   return Ret;
326be94e1b6SRafael Espindola }
327be94e1b6SRafael Espindola 
328b8dd23f5SRui Ueyama void LinkerScript::discard(ArrayRef<InputSectionBase *> V) {
329b4c9b81aSRafael Espindola   for (InputSectionBase *S : V) {
330be94e1b6SRafael Espindola     S->Live = false;
331945cd31cSGeorge Rimar     if (S == InX::ShStrTab || S == InX::Common || S == InX::Dynamic ||
332945cd31cSGeorge Rimar         S == InX::DynSymTab || S == InX::DynStrTab)
3332af64b0bSRafael Espindola       error("discarding " + S->Name + " section is not allowed");
334647c1685SGeorge Rimar     discard(S->DependentSections);
335be94e1b6SRafael Espindola   }
336be94e1b6SRafael Espindola }
337be94e1b6SRafael Espindola 
338b4c9b81aSRafael Espindola std::vector<InputSectionBase *>
3398c022ca7SRafael Espindola LinkerScript::createInputSectionList(OutputSection &OutCmd) {
340b4c9b81aSRafael Espindola   std::vector<InputSectionBase *> Ret;
341e7f912cdSRui Ueyama 
3428f99f73cSRui Ueyama   for (BaseCommand *Base : OutCmd.Commands) {
3438f99f73cSRui Ueyama     auto *Cmd = dyn_cast<InputSectionDescription>(Base);
3447c3ff2ebSRafael Espindola     if (!Cmd)
3450b9ce6a4SRui Ueyama       continue;
34672e107f3SRui Ueyama 
34772e107f3SRui Ueyama     Cmd->Sections = computeInputSections(Cmd);
348e4c8b9b7SRafael Espindola     Ret.insert(Ret.end(), Cmd->Sections.begin(), Cmd->Sections.end());
3490b9ce6a4SRui Ueyama   }
350e71a3f8aSRafael Espindola 
3510b9ce6a4SRui Ueyama   return Ret;
3520b9ce6a4SRui Ueyama }
3530b9ce6a4SRui Ueyama 
354b8dd23f5SRui Ueyama void LinkerScript::processCommands(OutputSectionFactory &Factory) {
3555616adf6SRafael Espindola   // A symbol can be assigned before any section is mentioned in the linker
3565616adf6SRafael Espindola   // script. In an DSO, the symbol values are addresses, so the only important
3575616adf6SRafael Espindola   // section values are:
3585616adf6SRafael Espindola   // * SHN_UNDEF
3595616adf6SRafael Espindola   // * SHN_ABS
3605616adf6SRafael Espindola   // * Any value meaning a regular section.
3615616adf6SRafael Espindola   // To handle that, create a dummy aether section that fills the void before
3625616adf6SRafael Espindola   // the linker scripts switches to another section. It has an index of one
3635616adf6SRafael Espindola   // which will map to whatever the first actual section is.
3645616adf6SRafael Espindola   Aether = make<OutputSection>("", 0, SHF_ALLOC);
3655616adf6SRafael Espindola   Aether->SectionIndex = 1;
366906e9a18SPeter Smith   auto State = make_unique<AddressState>(Opt);
367c1ace40bSPeter Smith   // CurAddressState captures the local AddressState and makes it accessible
368c1ace40bSPeter Smith   // deliberately. This is needed as there are some cases where we cannot just
369c1ace40bSPeter Smith   // thread the current state through to a lambda function created by the
370c1ace40bSPeter Smith   // script parser.
371906e9a18SPeter Smith   CurAddressState = State.get();
372906e9a18SPeter Smith   CurAddressState->OutSec = Aether;
37349592cf6SRafael Espindola   Dot = 0;
3745616adf6SRafael Espindola 
37592a5ba6dSRui Ueyama   for (size_t I = 0; I < Opt.Commands.size(); ++I) {
3760b1b695aSRui Ueyama     // Handle symbol assignments outside of any output section.
37792a5ba6dSRui Ueyama     if (auto *Cmd = dyn_cast<SymbolAssignment>(Opt.Commands[I])) {
3784cd7352cSRafael Espindola       addSymbol(Cmd);
3792ab5f73dSRui Ueyama       continue;
3802ab5f73dSRui Ueyama     }
3810b1b695aSRui Ueyama 
3828c022ca7SRafael Espindola     if (auto *Sec = dyn_cast<OutputSection>(Opt.Commands[I])) {
3838c022ca7SRafael Espindola       std::vector<InputSectionBase *> V = createInputSectionList(*Sec);
3847bd37870SRafael Espindola 
3850b1b695aSRui Ueyama       // The output section name `/DISCARD/' is special.
3860b1b695aSRui Ueyama       // Any input section assigned to it is discarded.
3878c022ca7SRafael Espindola       if (Sec->Name == "/DISCARD/") {
3887bd37870SRafael Espindola         discard(V);
38948c3f1ceSRui Ueyama         continue;
39048c3f1ceSRui Ueyama       }
3910b9ce6a4SRui Ueyama 
3920b1b695aSRui Ueyama       // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive
3930b1b695aSRui Ueyama       // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input
3940b1b695aSRui Ueyama       // sections satisfy a given constraint. If not, a directive is handled
39507d7c42cSGeorge Rimar       // as if it wasn't present from the beginning.
3960b1b695aSRui Ueyama       //
3970b1b695aSRui Ueyama       // Because we'll iterate over Commands many more times, the easiest
39807d7c42cSGeorge Rimar       // way to "make it as if it wasn't present" is to just remove it.
3998c022ca7SRafael Espindola       if (!matchConstraints(V, Sec->Constraint)) {
400b4c9b81aSRafael Espindola         for (InputSectionBase *S : V)
401f94efdddSRui Ueyama           S->Assigned = false;
40292a5ba6dSRui Ueyama         Opt.Commands.erase(Opt.Commands.begin() + I);
40307d7c42cSGeorge Rimar         --I;
4047c3ff2ebSRafael Espindola         continue;
4057c3ff2ebSRafael Espindola       }
4067c3ff2ebSRafael Espindola 
4070b1b695aSRui Ueyama       // A directive may contain symbol definitions like this:
4080b1b695aSRui Ueyama       // ".foo : { ...; bar = .; }". Handle them.
4098c022ca7SRafael Espindola       for (BaseCommand *Base : Sec->Commands)
4108f99f73cSRui Ueyama         if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base))
4114cd7352cSRafael Espindola           addSymbol(OutCmd);
4127c3ff2ebSRafael Espindola 
4130b1b695aSRui Ueyama       // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign
4140b1b695aSRui Ueyama       // is given, input sections are aligned to that value, whether the
4150b1b695aSRui Ueyama       // given value is larger or smaller than the original section alignment.
4168c022ca7SRafael Espindola       if (Sec->SubalignExpr) {
4178c022ca7SRafael Espindola         uint32_t Subalign = Sec->SubalignExpr().getValue();
418b4c9b81aSRafael Espindola         for (InputSectionBase *S : V)
4190b1b695aSRui Ueyama           S->Alignment = Subalign;
42020d03194SEugene Leviant       }
4210b1b695aSRui Ueyama 
4220b1b695aSRui Ueyama       // Add input sections to an output section.
423d86a4e50SGeorge Rimar       for (InputSectionBase *S : V)
4248c022ca7SRafael Espindola         Factory.addInputSec(S, Sec->Name, Sec);
425660c9ab9SRafael Espindola       assert(Sec->SectionIndex == INT_MAX);
426660c9ab9SRafael Espindola       Sec->SectionIndex = I;
4278c022ca7SRafael Espindola       if (Sec->Noload)
428fbb0463fSGeorge Rimar         Sec->Type = SHT_NOBITS;
42948c3f1ceSRui Ueyama     }
4304aa2ef5bSRafael Espindola   }
431c1ace40bSPeter Smith   CurAddressState = nullptr;
432db24d9c3SGeorge Rimar }
433e63d81bdSEugene Leviant 
43402ed7575SRafael Espindola void LinkerScript::fabricateDefaultCommands() {
435cbfe9e94SPeter Smith   // Define start address
436e76231b6SRafael Espindola   uint64_t StartAddr = -1;
437cbfe9e94SPeter Smith 
438c60b4510SPeter Smith   // The Sections with -T<section> have been sorted in order of ascending
439c60b4510SPeter Smith   // address. We must lower StartAddr if the lowest -T<section address> as
440c60b4510SPeter Smith   // calls to setDot() must be monotonically increasing.
441c60b4510SPeter Smith   for (auto &KV : Config->SectionStartMap)
442c60b4510SPeter Smith     StartAddr = std::min(StartAddr, KV.second);
443c60b4510SPeter Smith 
4448c022ca7SRafael Espindola   Opt.Commands.insert(Opt.Commands.begin(),
4458c022ca7SRafael Espindola                       make<SymbolAssignment>(".",
446e76231b6SRafael Espindola                                              [=] {
4478c022ca7SRafael Espindola                                                return std::min(
4488c022ca7SRafael Espindola                                                    StartAddr,
4498c022ca7SRafael Espindola                                                    Config->ImageBase +
4508c022ca7SRafael Espindola                                                        elf::getHeaderSize());
451e76231b6SRafael Espindola                                              },
452e76231b6SRafael Espindola                                              ""));
453cbfe9e94SPeter Smith }
454cbfe9e94SPeter Smith 
4550b1b695aSRui Ueyama // Add sections that didn't match any sections command.
456b8dd23f5SRui Ueyama void LinkerScript::addOrphanSections(OutputSectionFactory &Factory) {
457d7faa916SRafael Espindola   unsigned NumCommands = Opt.Commands.size();
4584f013bb3SRafael Espindola   for (InputSectionBase *S : InputSections) {
459db5e56f7SRafael Espindola     if (!S->Live || S->Parent)
4604f013bb3SRafael Espindola       continue;
4614f013bb3SRafael Espindola     StringRef Name = getOutputSectionName(S->Name);
462d7faa916SRafael Espindola     auto End = Opt.Commands.begin() + NumCommands;
463d7faa916SRafael Espindola     auto I = std::find_if(Opt.Commands.begin(), End, [&](BaseCommand *Base) {
4648c022ca7SRafael Espindola       if (auto *Sec = dyn_cast<OutputSection>(Base))
4658c022ca7SRafael Espindola         return Sec->Name == Name;
4664f013bb3SRafael Espindola       return false;
4674f013bb3SRafael Espindola     });
468d7faa916SRafael Espindola     if (I == End) {
4694f013bb3SRafael Espindola       Factory.addInputSec(S, Name);
470a2df2f09SRafael Espindola       assert(S->getOutputSection()->SectionIndex == INT_MAX);
471de8d9897SRafael Espindola     } else {
4728c022ca7SRafael Espindola       OutputSection *Sec = cast<OutputSection>(*I);
4738c022ca7SRafael Espindola       Factory.addInputSec(S, Name, Sec);
474660c9ab9SRafael Espindola       unsigned Index = std::distance(Opt.Commands.begin(), I);
475660c9ab9SRafael Espindola       assert(Sec->SectionIndex == INT_MAX || Sec->SectionIndex == Index);
476660c9ab9SRafael Espindola       Sec->SectionIndex = Index;
477660c9ab9SRafael Espindola     }
478d7faa916SRafael Espindola   }
4794f013bb3SRafael Espindola }
480e63d81bdSEugene Leviant 
4817c4eafa3SRafael Espindola uint64_t LinkerScript::advance(uint64_t Size, unsigned Align) {
482906e9a18SPeter Smith   bool IsTbss = (CurAddressState->OutSec->Flags & SHF_TLS) &&
483906e9a18SPeter Smith                 CurAddressState->OutSec->Type == SHT_NOBITS;
484906e9a18SPeter Smith   uint64_t Start = IsTbss ? Dot + CurAddressState->ThreadBssOffset : Dot;
4857c4eafa3SRafael Espindola   Start = alignTo(Start, Align);
4867c4eafa3SRafael Espindola   uint64_t End = Start + Size;
4877c4eafa3SRafael Espindola 
4887c4eafa3SRafael Espindola   if (IsTbss)
489906e9a18SPeter Smith     CurAddressState->ThreadBssOffset = End - Dot;
4907c4eafa3SRafael Espindola   else
4917c4eafa3SRafael Espindola     Dot = End;
4927c4eafa3SRafael Espindola   return End;
493a940e539SRafael Espindola }
494a940e539SRafael Espindola 
495b8dd23f5SRui Ueyama void LinkerScript::output(InputSection *S) {
496f694d33fSGeorge Rimar   uint64_t Before = advance(0, 1);
4977c4eafa3SRafael Espindola   uint64_t Pos = advance(S->getSize(), S->Alignment);
498906e9a18SPeter Smith   S->OutSecOff = Pos - S->getSize() - CurAddressState->OutSec->Addr;
499d3190795SRafael Espindola 
500d3190795SRafael Espindola   // Update output section size after adding each section. This is so that
501d3190795SRafael Espindola   // SIZEOF works correctly in the case below:
502d3190795SRafael Espindola   // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
503906e9a18SPeter Smith   CurAddressState->OutSec->Size = Pos - CurAddressState->OutSec->Addr;
504d3190795SRafael Espindola 
505b889744eSMeador Inge   // If there is a memory region associated with this input section, then
506b889744eSMeador Inge   // place the section in that region and update the region index.
507906e9a18SPeter Smith   if (CurAddressState->MemRegion) {
508906e9a18SPeter Smith     uint64_t &CurOffset =
509906e9a18SPeter Smith         CurAddressState->MemRegionOffset[CurAddressState->MemRegion];
510f694d33fSGeorge Rimar     CurOffset += Pos - Before;
511906e9a18SPeter Smith     uint64_t CurSize = CurOffset - CurAddressState->MemRegion->Origin;
512906e9a18SPeter Smith     if (CurSize > CurAddressState->MemRegion->Length) {
513906e9a18SPeter Smith       uint64_t OverflowAmt = CurSize - CurAddressState->MemRegion->Length;
514906e9a18SPeter Smith       error("section '" + CurAddressState->OutSec->Name +
515906e9a18SPeter Smith             "' will not fit in region '" + CurAddressState->MemRegion->Name +
516906e9a18SPeter Smith             "': overflowed by " + Twine(OverflowAmt) + " bytes");
517b889744eSMeador Inge     }
518b889744eSMeador Inge   }
5192de509c3SRui Ueyama }
520ceabe80eSEugene Leviant 
521b8dd23f5SRui Ueyama void LinkerScript::switchTo(OutputSection *Sec) {
522906e9a18SPeter Smith   if (CurAddressState->OutSec == Sec)
523d3190795SRafael Espindola     return;
524d3190795SRafael Espindola 
525906e9a18SPeter Smith   CurAddressState->OutSec = Sec;
526906e9a18SPeter Smith   CurAddressState->OutSec->Addr =
527906e9a18SPeter Smith       advance(0, CurAddressState->OutSec->Alignment);
528b71d6f7aSEugene Leviant 
529b71d6f7aSEugene Leviant   // If neither AT nor AT> is specified for an allocatable section, the linker
530b71d6f7aSEugene Leviant   // will set the LMA such that the difference between VMA and LMA for the
531b71d6f7aSEugene Leviant   // section is the same as the preceding output section in the same region
532b71d6f7aSEugene Leviant   // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
533906e9a18SPeter Smith   if (CurAddressState->LMAOffset)
534906e9a18SPeter Smith     CurAddressState->OutSec->LMAOffset = CurAddressState->LMAOffset();
535d3190795SRafael Espindola }
536d3190795SRafael Espindola 
537b8dd23f5SRui Ueyama void LinkerScript::process(BaseCommand &Base) {
5382e081a4fSRui Ueyama   // This handles the assignments to symbol or to the dot.
5392e081a4fSRui Ueyama   if (auto *Cmd = dyn_cast<SymbolAssignment>(&Base)) {
5402e081a4fSRui Ueyama     assignSymbol(Cmd, true);
541d3190795SRafael Espindola     return;
54297403d15SEugene Leviant   }
543e38cbab5SGeorge Rimar 
544e38cbab5SGeorge Rimar   // Handle BYTE(), SHORT(), LONG(), or QUAD().
5452e081a4fSRui Ueyama   if (auto *Cmd = dyn_cast<BytesDataCommand>(&Base)) {
546906e9a18SPeter Smith     Cmd->Offset = Dot - CurAddressState->OutSec->Addr;
5472e081a4fSRui Ueyama     Dot += Cmd->Size;
548906e9a18SPeter Smith     CurAddressState->OutSec->Size = Dot - CurAddressState->OutSec->Addr;
549e38cbab5SGeorge Rimar     return;
550e38cbab5SGeorge Rimar   }
551e38cbab5SGeorge Rimar 
5522e081a4fSRui Ueyama   // Handle ASSERT().
5532e081a4fSRui Ueyama   if (auto *Cmd = dyn_cast<AssertCommand>(&Base)) {
5542e081a4fSRui Ueyama     Cmd->Expression();
555b2d99d6aSMeador Inge     return;
556b2d99d6aSMeador Inge   }
557b2d99d6aSMeador Inge 
5582e081a4fSRui Ueyama   // Handle a single input section description command.
5592e081a4fSRui Ueyama   // It calculates and assigns the offsets for each section and also
560e38cbab5SGeorge Rimar   // updates the output section size.
5612e081a4fSRui Ueyama   auto &Cmd = cast<InputSectionDescription>(Base);
562a85e8ddaSRafael Espindola   for (InputSection *Sec : Cmd.Sections) {
5633fb5a6dcSGeorge Rimar     // We tentatively added all synthetic sections at the beginning and removed
5643fb5a6dcSGeorge Rimar     // empty ones afterwards (because there is no way to know whether they were
5653fb5a6dcSGeorge Rimar     // going be empty or not other than actually running linker scripts.)
5663fb5a6dcSGeorge Rimar     // We need to ignore remains of empty sections.
5672e081a4fSRui Ueyama     if (auto *S = dyn_cast<SyntheticSection>(Sec))
5682e081a4fSRui Ueyama       if (S->empty())
5693fb5a6dcSGeorge Rimar         continue;
5703fb5a6dcSGeorge Rimar 
5712e081a4fSRui Ueyama     if (!Sec->Live)
57278ef645fSGeorge Rimar       continue;
573906e9a18SPeter Smith     assert(CurAddressState->OutSec == Sec->getParent());
574a85e8ddaSRafael Espindola     output(Sec);
575ceabe80eSEugene Leviant   }
576ceabe80eSEugene Leviant }
577ceabe80eSEugene Leviant 
578b889744eSMeador Inge // This function searches for a memory region to place the given output
579b889744eSMeador Inge // section in. If found, a pointer to the appropriate memory region is
580b889744eSMeador Inge // returned. Otherwise, a nullptr is returned.
5818c022ca7SRafael Espindola MemoryRegion *LinkerScript::findMemoryRegion(OutputSection *Sec) {
582b889744eSMeador Inge   // If a memory region name was specified in the output section command,
583b889744eSMeador Inge   // then try to find that region first.
5848c022ca7SRafael Espindola   if (!Sec->MemoryRegionName.empty()) {
5858c022ca7SRafael Espindola     auto It = Opt.MemoryRegions.find(Sec->MemoryRegionName);
586b889744eSMeador Inge     if (It != Opt.MemoryRegions.end())
587b889744eSMeador Inge       return &It->second;
5888c022ca7SRafael Espindola     error("memory region '" + Sec->MemoryRegionName + "' not declared");
589b889744eSMeador Inge     return nullptr;
590b889744eSMeador Inge   }
591b889744eSMeador Inge 
592d7c5400fSRui Ueyama   // If at least one memory region is defined, all sections must
593d7c5400fSRui Ueyama   // belong to some memory region. Otherwise, we don't need to do
594d7c5400fSRui Ueyama   // anything for memory regions.
595cc400cc8SRui Ueyama   if (Opt.MemoryRegions.empty())
596b889744eSMeador Inge     return nullptr;
597b889744eSMeador Inge 
598b889744eSMeador Inge   // See if a region can be found by matching section flags.
5992e081a4fSRui Ueyama   for (auto &Pair : Opt.MemoryRegions) {
6002e081a4fSRui Ueyama     MemoryRegion &M = Pair.second;
6012e081a4fSRui Ueyama     if ((M.Flags & Sec->Flags) && (M.NegFlags & Sec->Flags) == 0)
6022e081a4fSRui Ueyama       return &M;
603b889744eSMeador Inge   }
604b889744eSMeador Inge 
605b889744eSMeador Inge   // Otherwise, no suitable region was found.
606b889744eSMeador Inge   if (Sec->Flags & SHF_ALLOC)
607b889744eSMeador Inge     error("no memory region specified for section '" + Sec->Name + "'");
608b889744eSMeador Inge   return nullptr;
609b889744eSMeador Inge }
610b889744eSMeador Inge 
6110b1b695aSRui Ueyama // This function assigns offsets to input sections and an output section
6120b1b695aSRui Ueyama // for a single sections command (e.g. ".text { *(.text); }").
6138c022ca7SRafael Espindola void LinkerScript::assignOffsets(OutputSection *Sec) {
614dece2808SRafael Espindola   if (!(Sec->Flags & SHF_ALLOC))
615dece2808SRafael Espindola     Dot = 0;
6168c022ca7SRafael Espindola   else if (Sec->AddrExpr)
6178c022ca7SRafael Espindola     setDot(Sec->AddrExpr, Sec->Location, false);
618679828ffSRafael Espindola 
619*c2dffe3aSGeorge Rimar   CurAddressState->MemRegion = Sec->MemRegion;
620*c2dffe3aSGeorge Rimar   if (CurAddressState->MemRegion)
621*c2dffe3aSGeorge Rimar     Dot = CurAddressState->MemRegionOffset[CurAddressState->MemRegion];
622*c2dffe3aSGeorge Rimar 
6238c022ca7SRafael Espindola   if (Sec->LMAExpr) {
6240c1c8085SGeorge Rimar     uint64_t D = Dot;
6258c022ca7SRafael Espindola     CurAddressState->LMAOffset = [=] { return Sec->LMAExpr().getValue() - D; };
6265784e96fSEugene Leviant   }
6275784e96fSEugene Leviant 
628b889744eSMeador Inge   switchTo(Sec);
6290b1b695aSRui Ueyama 
630d86a4e50SGeorge Rimar   // We do not support custom layout for compressed debug sectons.
631d86a4e50SGeorge Rimar   // At this point we already know their size and have compressed content.
632906e9a18SPeter Smith   if (CurAddressState->OutSec->Flags & SHF_COMPRESSED)
633d86a4e50SGeorge Rimar     return;
634d86a4e50SGeorge Rimar 
6358c022ca7SRafael Espindola   for (BaseCommand *C : Sec->Commands)
636de8d9897SRafael Espindola     process(*C);
637d3190795SRafael Espindola }
638d3190795SRafael Espindola 
639b8dd23f5SRui Ueyama void LinkerScript::removeEmptyCommands() {
6406d38e4dbSRafael Espindola   // It is common practice to use very generic linker scripts. So for any
6416d38e4dbSRafael Espindola   // given run some of the output sections in the script will be empty.
6426d38e4dbSRafael Espindola   // We could create corresponding empty output sections, but that would
6436d38e4dbSRafael Espindola   // clutter the output.
6446d38e4dbSRafael Espindola   // We instead remove trivially empty sections. The bfd linker seems even
6456d38e4dbSRafael Espindola   // more aggressive at removing them.
64660608a8aSGeorge Rimar   llvm::erase_if(Opt.Commands, [&](BaseCommand *Base) {
6478c022ca7SRafael Espindola     if (auto *Sec = dyn_cast<OutputSection>(Base))
6488c022ca7SRafael Espindola       return !Sec->Live;
6490b1b695aSRui Ueyama     return false;
6506d38e4dbSRafael Espindola   });
65107fe6129SRafael Espindola }
65207fe6129SRafael Espindola 
6538c022ca7SRafael Espindola static bool isAllSectionDescription(const OutputSection &Cmd) {
6548f99f73cSRui Ueyama   for (BaseCommand *Base : Cmd.Commands)
6558f99f73cSRui Ueyama     if (!isa<InputSectionDescription>(*Base))
6566a53737cSRafael Espindola       return false;
6576a53737cSRafael Espindola   return true;
6586a53737cSRafael Espindola }
6596d38e4dbSRafael Espindola 
660b8dd23f5SRui Ueyama void LinkerScript::adjustSectionsBeforeSorting() {
6619546fffbSRafael Espindola   // If the output section contains only symbol assignments, create a
6629546fffbSRafael Espindola   // corresponding output section. The bfd linker seems to only create them if
6639546fffbSRafael Espindola   // '.' is assigned to, but creating these section should not have any bad
6649546fffbSRafael Espindola   // consequeces and gives us a section to put the symbol in.
6650c1c8085SGeorge Rimar   uint64_t Flags = SHF_ALLOC;
666660c9ab9SRafael Espindola 
667660c9ab9SRafael Espindola   for (int I = 0, E = Opt.Commands.size(); I != E; ++I) {
6688c022ca7SRafael Espindola     auto *Sec = dyn_cast<OutputSection>(Opt.Commands[I]);
6698c022ca7SRafael Espindola     if (!Sec)
6709546fffbSRafael Espindola       continue;
6718c022ca7SRafael Espindola     if (Sec->Live) {
6722b074553SRafael Espindola       Flags = Sec->Flags;
6739546fffbSRafael Espindola       continue;
6749546fffbSRafael Espindola     }
6759546fffbSRafael Espindola 
6768c022ca7SRafael Espindola     if (isAllSectionDescription(*Sec))
6776a53737cSRafael Espindola       continue;
6786a53737cSRafael Espindola 
6798c022ca7SRafael Espindola     Sec->Live = true;
6808c022ca7SRafael Espindola     Sec->SectionIndex = I;
6818c022ca7SRafael Espindola     Sec->Flags = Flags;
6829546fffbSRafael Espindola   }
683f7a17448SRafael Espindola }
684f7a17448SRafael Espindola 
685b8dd23f5SRui Ueyama void LinkerScript::adjustSectionsAfterSorting() {
686feed7506SRafael Espindola   // Try and find an appropriate memory region to assign offsets in.
687d1960dc0SRafael Espindola   for (BaseCommand *Base : Opt.Commands) {
6888c022ca7SRafael Espindola     if (auto *Sec = dyn_cast<OutputSection>(Base)) {
6898c022ca7SRafael Espindola       Sec->MemRegion = findMemoryRegion(Sec);
690d1960dc0SRafael Espindola       // Handle align (e.g. ".foo : ALIGN(16) { ... }").
6918c022ca7SRafael Espindola       if (Sec->AlignExpr)
6928c022ca7SRafael Espindola         Sec->updateAlignment(Sec->AlignExpr().getValue());
693d1960dc0SRafael Espindola     }
694d1960dc0SRafael Espindola   }
695feed7506SRafael Espindola 
696f7a17448SRafael Espindola   // If output section command doesn't specify any segments,
697f7a17448SRafael Espindola   // and we haven't previously assigned any section to segment,
698f7a17448SRafael Espindola   // then we simply assign section to the very first load segment.
699f7a17448SRafael Espindola   // Below is an example of such linker script:
700f7a17448SRafael Espindola   // PHDRS { seg PT_LOAD; }
701f7a17448SRafael Espindola   // SECTIONS { .aaa : { *(.aaa) } }
702f7a17448SRafael Espindola   std::vector<StringRef> DefPhdrs;
703f7a17448SRafael Espindola   auto FirstPtLoad =
704f7a17448SRafael Espindola       std::find_if(Opt.PhdrsCommands.begin(), Opt.PhdrsCommands.end(),
705f7a17448SRafael Espindola                    [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; });
706f7a17448SRafael Espindola   if (FirstPtLoad != Opt.PhdrsCommands.end())
707f7a17448SRafael Espindola     DefPhdrs.push_back(FirstPtLoad->Name);
708f7a17448SRafael Espindola 
709f7a17448SRafael Espindola   // Walk the commands and propagate the program headers to commands that don't
710f7a17448SRafael Espindola   // explicitly specify them.
7118f99f73cSRui Ueyama   for (BaseCommand *Base : Opt.Commands) {
7128c022ca7SRafael Espindola     auto *Sec = dyn_cast<OutputSection>(Base);
7138c022ca7SRafael Espindola     if (!Sec)
714f7a17448SRafael Espindola       continue;
7158f99f73cSRui Ueyama 
7168c022ca7SRafael Espindola     if (Sec->Phdrs.empty()) {
717a020d348SAndrew Ng       // To match the bfd linker script behaviour, only propagate program
718a020d348SAndrew Ng       // headers to sections that are allocated.
7198c022ca7SRafael Espindola       if (Sec->Flags & SHF_ALLOC)
7208c022ca7SRafael Espindola         Sec->Phdrs = DefPhdrs;
721a020d348SAndrew Ng     } else {
7228c022ca7SRafael Espindola       DefPhdrs = Sec->Phdrs;
723f7a17448SRafael Espindola     }
724a020d348SAndrew Ng   }
7256a53737cSRafael Espindola 
7266a53737cSRafael Espindola   removeEmptyCommands();
7279546fffbSRafael Espindola }
7289546fffbSRafael Espindola 
729b93c5b9fSPetr Hosek // Try to find an address for the file and program headers output sections,
730b93c5b9fSPetr Hosek // which were unconditionally added to the first PT_LOAD segment earlier.
731b93c5b9fSPetr Hosek //
732b93c5b9fSPetr Hosek // When using the default layout, we check if the headers fit below the first
733b93c5b9fSPetr Hosek // allocated section. When using a linker script, we also check if the headers
734b93c5b9fSPetr Hosek // are covered by the output section. This allows omitting the headers by not
735b93c5b9fSPetr Hosek // leaving enough space for them in the linker script; this pattern is common
736b93c5b9fSPetr Hosek // in embedded systems.
737b93c5b9fSPetr Hosek //
738b93c5b9fSPetr Hosek // If there isn't enough space for these sections, we'll remove them from the
739b93c5b9fSPetr Hosek // PT_LOAD segment, and we'll also remove the PT_PHDR segment.
740aa354187SGeorge Rimar void LinkerScript::allocateHeaders(std::vector<PhdrEntry *> &Phdrs) {
7415aedebffSPeter Smith   uint64_t Min = std::numeric_limits<uint64_t>::max();
7428c022ca7SRafael Espindola   for (OutputSection *Sec : OutputSections)
7435aedebffSPeter Smith     if (Sec->Flags & SHF_ALLOC)
7445aedebffSPeter Smith       Min = std::min<uint64_t>(Min, Sec->Addr);
7455aedebffSPeter Smith 
746aa354187SGeorge Rimar   auto It = llvm::find_if(
747aa354187SGeorge Rimar       Phdrs, [](const PhdrEntry *E) { return E->p_type == PT_LOAD; });
748aa354187SGeorge Rimar   if (It == Phdrs.end())
749d971e703SGeorge Rimar     return;
750aa354187SGeorge Rimar   PhdrEntry *FirstPTLoad = *It;
75102ed7575SRafael Espindola 
75202ed7575SRafael Espindola   uint64_t HeaderSize = getHeaderSize();
753b93c5b9fSPetr Hosek   // When linker script with SECTIONS is being used, don't output headers
754b93c5b9fSPetr Hosek   // unless there's a space for them.
755b93c5b9fSPetr Hosek   uint64_t Base = Opt.HasSections ? alignDown(Min, Config->MaxPageSize) : 0;
756b93c5b9fSPetr Hosek   if (HeaderSize <= Min - Base || Script->hasPhdrsCommands()) {
757b93c5b9fSPetr Hosek     Min = Opt.HasSections ? Base
758b93c5b9fSPetr Hosek                           : alignDown(Min - HeaderSize, Config->MaxPageSize);
75902ed7575SRafael Espindola     Out::ElfHeader->Addr = Min;
76002ed7575SRafael Espindola     Out::ProgramHeaders->Addr = Min + Out::ElfHeader->Size;
761d971e703SGeorge Rimar     return;
76202ed7575SRafael Espindola   }
76302ed7575SRafael Espindola 
76402ed7575SRafael Espindola   OutputSection *ActualFirst = nullptr;
7658c022ca7SRafael Espindola   for (OutputSection *Sec : OutputSections) {
76602ed7575SRafael Espindola     if (Sec->FirstInPtLoad == Out::ElfHeader) {
76702ed7575SRafael Espindola       ActualFirst = Sec;
76802ed7575SRafael Espindola       break;
76902ed7575SRafael Espindola     }
77002ed7575SRafael Espindola   }
77102ed7575SRafael Espindola   if (ActualFirst) {
7728c022ca7SRafael Espindola     for (OutputSection *Sec : OutputSections)
77302ed7575SRafael Espindola       if (Sec->FirstInPtLoad == Out::ElfHeader)
77402ed7575SRafael Espindola         Sec->FirstInPtLoad = ActualFirst;
77502ed7575SRafael Espindola     FirstPTLoad->First = ActualFirst;
77602ed7575SRafael Espindola   } else {
777aa354187SGeorge Rimar     Phdrs.erase(It);
77802ed7575SRafael Espindola   }
77902ed7575SRafael Espindola 
78060608a8aSGeorge Rimar   llvm::erase_if(Phdrs,
78160608a8aSGeorge Rimar                  [](const PhdrEntry *E) { return E->p_type == PT_PHDR; });
78202ed7575SRafael Espindola }
78302ed7575SRafael Espindola 
784906e9a18SPeter Smith LinkerScript::AddressState::AddressState(const ScriptConfiguration &Opt) {
785906e9a18SPeter Smith   for (auto &MRI : Opt.MemoryRegions) {
786906e9a18SPeter Smith     const MemoryRegion *MR = &MRI.second;
787906e9a18SPeter Smith     MemRegionOffset[MR] = MR->Origin;
788906e9a18SPeter Smith   }
789906e9a18SPeter Smith }
790906e9a18SPeter Smith 
7915aedebffSPeter Smith void LinkerScript::assignAddresses() {
7927c18c28cSRui Ueyama   // Assign addresses as instructed by linker script SECTIONS sub-commands.
793be607334SRafael Espindola   Dot = 0;
794906e9a18SPeter Smith   auto State = make_unique<AddressState>(Opt);
795c1ace40bSPeter Smith   // CurAddressState captures the local AddressState and makes it accessible
796c1ace40bSPeter Smith   // deliberately. This is needed as there are some cases where we cannot just
797c1ace40bSPeter Smith   // thread the current state through to a lambda function created by the
798c1ace40bSPeter Smith   // script parser.
799906e9a18SPeter Smith   CurAddressState = State.get();
80072dc195dSRafael Espindola   ErrorOnMissingSection = true;
80106f4743aSRafael Espindola   switchTo(Aether);
80206f4743aSRafael Espindola 
8038f99f73cSRui Ueyama   for (BaseCommand *Base : Opt.Commands) {
8048f99f73cSRui Ueyama     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base)) {
805d379f735SRui Ueyama       assignSymbol(Cmd, false);
80605ef4cffSRui Ueyama       continue;
807652852c5SGeorge Rimar     }
808652852c5SGeorge Rimar 
8098f99f73cSRui Ueyama     if (auto *Cmd = dyn_cast<AssertCommand>(Base)) {
8104595df94SRafael Espindola       Cmd->Expression();
811eefa758eSGeorge Rimar       continue;
812eefa758eSGeorge Rimar     }
813eefa758eSGeorge Rimar 
8148c022ca7SRafael Espindola     assignOffsets(cast<OutputSection>(Base));
815a14b13d8SGeorge Rimar   }
816c1ace40bSPeter Smith   CurAddressState = nullptr;
817fb8978fcSDima Stepanov }
818652852c5SGeorge Rimar 
819464daadcSRui Ueyama // Creates program headers as instructed by PHDRS linker script command.
820aa354187SGeorge Rimar std::vector<PhdrEntry *> LinkerScript::createPhdrs() {
821aa354187SGeorge Rimar   std::vector<PhdrEntry *> Ret;
822bbe38602SEugene Leviant 
823464daadcSRui Ueyama   // Process PHDRS and FILEHDR keywords because they are not
824464daadcSRui Ueyama   // real output sections and cannot be added in the following loop.
825bbe38602SEugene Leviant   for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
826aa354187SGeorge Rimar     PhdrEntry *Phdr =
827aa354187SGeorge Rimar         make<PhdrEntry>(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
828bbe38602SEugene Leviant 
829bbe38602SEugene Leviant     if (Cmd.HasFilehdr)
830aa354187SGeorge Rimar       Phdr->add(Out::ElfHeader);
831bbe38602SEugene Leviant     if (Cmd.HasPhdrs)
832aa354187SGeorge Rimar       Phdr->add(Out::ProgramHeaders);
83356b21c86SEugene Leviant 
83456b21c86SEugene Leviant     if (Cmd.LMAExpr) {
835aa354187SGeorge Rimar       Phdr->p_paddr = Cmd.LMAExpr().getValue();
836aa354187SGeorge Rimar       Phdr->HasLMA = true;
83756b21c86SEugene Leviant     }
838aa354187SGeorge Rimar     Ret.push_back(Phdr);
839bbe38602SEugene Leviant   }
840bbe38602SEugene Leviant 
841464daadcSRui Ueyama   // Add output sections to program headers.
8428c022ca7SRafael Espindola   for (OutputSection *Sec : OutputSections) {
843bbe38602SEugene Leviant     // Assign headers specified by linker script
8448c022ca7SRafael Espindola     for (size_t Id : getPhdrIndices(Sec)) {
845aa354187SGeorge Rimar       Ret[Id]->add(Sec);
846865bf863SEugene Leviant       if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
847aa354187SGeorge Rimar         Ret[Id]->p_flags |= Sec->getPhdrFlags();
848bbe38602SEugene Leviant     }
849bbe38602SEugene Leviant   }
850edebbdf1SRui Ueyama   return Ret;
851bbe38602SEugene Leviant }
852bbe38602SEugene Leviant 
853b8dd23f5SRui Ueyama bool LinkerScript::ignoreInterpSection() {
854f9bc3bd2SEugene Leviant   // Ignore .interp section in case we have PHDRS specification
855f9bc3bd2SEugene Leviant   // and PT_INTERP isn't listed.
856e31d9886SRui Ueyama   if (Opt.PhdrsCommands.empty())
857e31d9886SRui Ueyama     return false;
858e31d9886SRui Ueyama   for (PhdrsCommand &Cmd : Opt.PhdrsCommands)
859e31d9886SRui Ueyama     if (Cmd.Type == PT_INTERP)
860e31d9886SRui Ueyama       return false;
861e31d9886SRui Ueyama   return true;
862f9bc3bd2SEugene Leviant }
863f9bc3bd2SEugene Leviant 
864b8dd23f5SRui Ueyama ExprValue LinkerScript::getSymbolValue(const Twine &Loc, StringRef S) {
8657e5b0a59SGeorge Rimar   if (S == ".") {
8667e5b0a59SGeorge Rimar     if (CurAddressState)
8677e5b0a59SGeorge Rimar       return {CurAddressState->OutSec, Dot - CurAddressState->OutSec->Addr,
8687e5b0a59SGeorge Rimar               Loc};
8697e5b0a59SGeorge Rimar     error(Loc + ": unable to get location counter value");
8707e5b0a59SGeorge Rimar     return 0;
8717e5b0a59SGeorge Rimar   }
872244ef981SRafael Espindola   if (SymbolBody *B = Symtab->find(S)) {
87372dc195dSRafael Espindola     if (auto *D = dyn_cast<DefinedRegular>(B))
87441c7ab4aSGeorge Rimar       return {D->Section, D->Value, Loc};
87530f16b23SPetr Hosek     if (auto *C = dyn_cast<DefinedCommon>(B))
87641c7ab4aSGeorge Rimar       return {InX::Common, C->Offset, Loc};
87772dc195dSRafael Espindola   }
878f6aeed36SEugene Leviant   error(Loc + ": symbol not found: " + S);
879884e786dSGeorge Rimar   return 0;
880884e786dSGeorge Rimar }
881884e786dSGeorge Rimar 
882244ef981SRafael Espindola bool LinkerScript::isDefined(StringRef S) { return Symtab->find(S) != nullptr; }
883f34f45fdSGeorge Rimar 
8846e9f98c1SAndrew Ng static const size_t NoPhdr = -1;
8856e9f98c1SAndrew Ng 
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;
8906e9f98c1SAndrew Ng   for (StringRef PhdrName : Cmd->Phdrs) {
8916e9f98c1SAndrew Ng     size_t Index = getPhdrIndex(Cmd->Location, PhdrName);
8926e9f98c1SAndrew Ng     if (Index != NoPhdr)
8936e9f98c1SAndrew Ng       Ret.push_back(Index);
8946e9f98c1SAndrew Ng   }
89529c5a2a9SRui Ueyama   return Ret;
896bbe38602SEugene Leviant }
897bbe38602SEugene Leviant 
8986e9f98c1SAndrew Ng // Returns the index of the segment named PhdrName if found otherwise
8996e9f98c1SAndrew Ng // NoPhdr. When not found, if PhdrName is not the special case value 'NONE'
9006e9f98c1SAndrew Ng // (which can be used to explicitly specify that a section isn't assigned to a
9016e9f98c1SAndrew Ng // segment) then error.
902b8dd23f5SRui Ueyama size_t LinkerScript::getPhdrIndex(const Twine &Loc, StringRef PhdrName) {
90329c5a2a9SRui Ueyama   size_t I = 0;
90429c5a2a9SRui Ueyama   for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
90529c5a2a9SRui Ueyama     if (Cmd.Name == PhdrName)
90629c5a2a9SRui Ueyama       return I;
90729c5a2a9SRui Ueyama     ++I;
90829c5a2a9SRui Ueyama   }
9096e9f98c1SAndrew Ng   if (PhdrName != "NONE")
9102a942c4bSEugene Leviant     error(Loc + ": section header '" + PhdrName + "' is not listed in PHDRS");
9116e9f98c1SAndrew Ng   return NoPhdr;
91229c5a2a9SRui Ueyama }
913