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 
828c022ca7SRafael Espindola OutputSection *LinkerScript::createOutputSection(StringRef Name,
838c022ca7SRafael Espindola                                                  StringRef Location) {
848c022ca7SRafael Espindola   OutputSection *&SecRef = NameToOutputSection[Name];
858c022ca7SRafael Espindola   OutputSection *Sec;
868c022ca7SRafael Espindola   if (SecRef && SecRef->Location.empty()) {
8705c4f67cSRafael Espindola     // There was a forward reference.
888c022ca7SRafael Espindola     Sec = SecRef;
8905c4f67cSRafael Espindola   } else {
908c022ca7SRafael Espindola     Sec = make<OutputSection>(Name, SHT_PROGBITS, 0);
918c022ca7SRafael Espindola     if (!SecRef)
928c022ca7SRafael Espindola       SecRef = Sec;
9305c4f67cSRafael Espindola   }
948c022ca7SRafael Espindola   Sec->Location = Location;
958c022ca7SRafael Espindola   return Sec;
96851dc1e8SGeorge Rimar }
97851dc1e8SGeorge Rimar 
988c022ca7SRafael Espindola OutputSection *LinkerScript::getOrCreateOutputSection(StringRef Name) {
998c022ca7SRafael Espindola   OutputSection *&CmdRef = NameToOutputSection[Name];
10005c4f67cSRafael Espindola   if (!CmdRef)
1018c022ca7SRafael Espindola     CmdRef = make<OutputSection>(Name, SHT_PROGBITS, 0);
10205c4f67cSRafael Espindola   return CmdRef;
103d83ce1b4SGeorge Rimar }
104d83ce1b4SGeorge Rimar 
105b8dd23f5SRui Ueyama void LinkerScript::setDot(Expr E, const Twine &Loc, bool InSec) {
10672dc195dSRafael Espindola   uint64_t Val = E().getValue();
1078c804d97SGeorge Rimar   if (Val < Dot && InSec)
1082ee2d2dcSGeorge Rimar     error(Loc + ": unable to move location counter backward for: " +
10929b240c6SRui Ueyama           Ctx->OutSec->Name);
1104cd7352cSRafael Espindola   Dot = Val;
11118d19687SRui Ueyama 
1124cd7352cSRafael Espindola   // Update to location counter means update to section size.
1134cd7352cSRafael Espindola   if (InSec)
11429b240c6SRui Ueyama     Ctx->OutSec->Size = Dot - Ctx->OutSec->Addr;
115679828ffSRafael Espindola }
116679828ffSRafael Espindola 
1175908c2f8SRui Ueyama // This function is called from processSectionCommands,
1185908c2f8SRui Ueyama // while we are fixing the output section layout.
119b8dd23f5SRui Ueyama void LinkerScript::addSymbol(SymbolAssignment *Cmd) {
1201602421cSRui Ueyama   if (Cmd->Name == ".")
1218f1f3c40SMeador Inge     return;
1228f1f3c40SMeador Inge 
1238f1f3c40SMeador Inge   // If a symbol was in PROVIDE(), we need to define it only when
1248f1f3c40SMeador Inge   // it is a referenced undefined symbol.
125244ef981SRafael Espindola   SymbolBody *B = Symtab->find(Cmd->Name);
1268f1f3c40SMeador Inge   if (Cmd->Provide && (!B || B->isDefined()))
1278f1f3c40SMeador Inge     return;
1288f1f3c40SMeador Inge 
12918d19687SRui Ueyama   // Define a symbol.
13018d19687SRui Ueyama   Symbol *Sym;
13118d19687SRui Ueyama   uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
13218d19687SRui Ueyama   std::tie(Sym, std::ignore) = Symtab->insert(Cmd->Name, /*Type*/ 0, Visibility,
13318d19687SRui Ueyama                                               /*CanOmitFromDynSym*/ false,
13418d19687SRui Ueyama                                               /*File*/ nullptr);
13518d19687SRui Ueyama   Sym->Binding = STB_GLOBAL;
13618d19687SRui Ueyama   ExprValue Value = Cmd->Expression();
13718d19687SRui Ueyama   SectionBase *Sec = Value.isAbsolute() ? nullptr : Value.Sec;
13818d19687SRui Ueyama 
13918d19687SRui Ueyama   // When this function is called, section addresses have not been
14018d19687SRui Ueyama   // fixed yet. So, we may or may not know the value of the RHS
14118d19687SRui Ueyama   // expression.
14218d19687SRui Ueyama   //
14318d19687SRui Ueyama   // For example, if an expression is `x = 42`, we know x is always 42.
14418d19687SRui Ueyama   // However, if an expression is `x = .`, there's no way to know its
14518d19687SRui Ueyama   // value at the moment.
14618d19687SRui Ueyama   //
14718d19687SRui Ueyama   // We want to set symbol values early if we can. This allows us to
14818d19687SRui Ueyama   // use symbols as variables in linker scripts. Doing so allows us to
14918d19687SRui Ueyama   // write expressions like this: `alignment = 16; . = ALIGN(., alignment)`.
15018d19687SRui Ueyama   uint64_t SymValue = Value.Sec ? 0 : Value.getValue();
15118d19687SRui Ueyama 
15218d19687SRui Ueyama   replaceBody<DefinedRegular>(Sym, nullptr, Cmd->Name, /*IsLocal=*/false,
15318d19687SRui Ueyama                               Visibility, STT_NOTYPE, SymValue, 0, Sec);
15418d19687SRui Ueyama   Cmd->Sym = cast<DefinedRegular>(Sym->body());
15518d19687SRui Ueyama }
15618d19687SRui Ueyama 
15718d19687SRui Ueyama // This function is called from assignAddresses, while we are
15818d19687SRui Ueyama // fixing the output section addresses. This function is supposed
15918d19687SRui Ueyama // to set the final value for a given symbol assignment.
16018d19687SRui Ueyama void LinkerScript::assignSymbol(SymbolAssignment *Cmd, bool InSec) {
16118d19687SRui Ueyama   if (Cmd->Name == ".") {
16218d19687SRui Ueyama     setDot(Cmd->Expression, Cmd->Location, InSec);
16318d19687SRui Ueyama     return;
16418d19687SRui Ueyama   }
16518d19687SRui Ueyama 
16618d19687SRui Ueyama   if (!Cmd->Sym)
16718d19687SRui Ueyama     return;
16818d19687SRui Ueyama 
16918d19687SRui Ueyama   ExprValue V = Cmd->Expression();
17018d19687SRui Ueyama   if (V.isAbsolute()) {
17118d19687SRui Ueyama     Cmd->Sym->Section = nullptr;
17218d19687SRui Ueyama     Cmd->Sym->Value = V.getValue();
17318d19687SRui Ueyama   } else {
17418d19687SRui Ueyama     Cmd->Sym->Section = V.Sec;
17518d19687SRui Ueyama     Cmd->Sym->Value = V.getSectionOffset();
17618d19687SRui Ueyama   }
177ceabe80eSEugene Leviant }
178ceabe80eSEugene Leviant 
17904c9ca74SRui Ueyama static std::string getFilename(InputFile *File) {
1801e30f07cSDmitry Mikulin   if (!File)
181e0be2901SRui Ueyama     return "";
1821e30f07cSDmitry Mikulin   if (File->ArchiveName.empty())
1831e30f07cSDmitry Mikulin     return File->getName();
1841e30f07cSDmitry Mikulin   return (File->ArchiveName + "(" + File->getName() + ")").str();
185e0be2901SRui Ueyama }
186e0be2901SRui Ueyama 
187b8dd23f5SRui Ueyama bool LinkerScript::shouldKeep(InputSectionBase *S) {
18804c9ca74SRui Ueyama   std::string Filename = getFilename(S->File);
1897f1c266eSRui Ueyama   for (InputSectionDescription *ID : KeptSections)
190f300ca21SDmitry Mikulin     if (ID->FilePat.match(Filename))
191cf43f179SEugene Leviant       for (SectionPattern &P : ID->SectionPatterns)
192f91282e1SRui Ueyama         if (P.SectionPat.match(S->Name))
193eea3114fSGeorge Rimar           return true;
194eea3114fSGeorge Rimar   return false;
195eea3114fSGeorge Rimar }
196eea3114fSGeorge Rimar 
197ea93fe00SRui Ueyama // A helper function for the SORT() command.
198c404d50dSRafael Espindola static std::function<bool(InputSectionBase *, InputSectionBase *)>
199be394db3SGeorge Rimar getComparator(SortSectionPolicy K) {
200be394db3SGeorge Rimar   switch (K) {
201be394db3SGeorge Rimar   case SortSectionPolicy::Alignment:
202ea93fe00SRui Ueyama     return [](InputSectionBase *A, InputSectionBase *B) {
203ea93fe00SRui Ueyama       // ">" is not a mistake. Sections with larger alignments are placed
204ea93fe00SRui Ueyama       // before sections with smaller alignments in order to reduce the
205ea93fe00SRui Ueyama       // amount of padding necessary. This is compatible with GNU.
206ea93fe00SRui Ueyama       return A->Alignment > B->Alignment;
207ea93fe00SRui Ueyama     };
208be394db3SGeorge Rimar   case SortSectionPolicy::Name:
209ea93fe00SRui Ueyama     return [](InputSectionBase *A, InputSectionBase *B) {
210ea93fe00SRui Ueyama       return A->Name < B->Name;
211ea93fe00SRui Ueyama     };
212be394db3SGeorge Rimar   case SortSectionPolicy::Priority:
213ea93fe00SRui Ueyama     return [](InputSectionBase *A, InputSectionBase *B) {
214ea93fe00SRui Ueyama       return getPriority(A->Name) < getPriority(B->Name);
215ea93fe00SRui Ueyama     };
216be394db3SGeorge Rimar   default:
217be394db3SGeorge Rimar     llvm_unreachable("unknown sort policy");
218be394db3SGeorge Rimar   }
219742c3836SRui Ueyama }
2200702c4e8SGeorge Rimar 
221ea93fe00SRui Ueyama // A helper function for the SORT() command.
22205433431SRui Ueyama static bool matchConstraints(ArrayRef<InputSection *> Sections,
22306ae6836SGeorge Rimar                              ConstraintKind Kind) {
2248f66df92SGeorge Rimar   if (Kind == ConstraintKind::NoConstraint)
2258f66df92SGeorge Rimar     return true;
2262c7171bfSRui Ueyama 
227b801441eSRui Ueyama   bool IsRW = llvm::any_of(
22805433431SRui Ueyama       Sections, [](InputSection *Sec) { return Sec->Flags & SHF_WRITE; });
2292c7171bfSRui Ueyama 
230e746e52cSRafael Espindola   return (IsRW && Kind == ConstraintKind::ReadWrite) ||
231e746e52cSRafael Espindola          (!IsRW && Kind == ConstraintKind::ReadOnly);
23206ae6836SGeorge Rimar }
23306ae6836SGeorge Rimar 
2341f4d7b56SRui Ueyama static void sortSections(MutableArrayRef<InputSection *> Vec,
235ee924709SRui Ueyama                          SortSectionPolicy K) {
236ee924709SRui Ueyama   if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
2371f4d7b56SRui Ueyama     std::stable_sort(Vec.begin(), Vec.end(), getComparator(K));
238ee924709SRui Ueyama }
239ee924709SRui Ueyama 
240d3190795SRafael Espindola // Compute and remember which sections the InputSectionDescription matches.
2416a1aa8d9SRafael Espindola std::vector<InputSection *>
24272e107f3SRui Ueyama LinkerScript::computeInputSections(const InputSectionDescription *Cmd) {
2436a1aa8d9SRafael Espindola   std::vector<InputSection *> Ret;
244187b67a5SRui Ueyama   DenseMap<SectionBase *, int> Order = buildSectionOrder();
2458c6a5aafSRui Ueyama 
24672e107f3SRui Ueyama   // Collects all sections that satisfy constraints of Cmd.
24772e107f3SRui Ueyama   for (const SectionPattern &Pat : Cmd->SectionPatterns) {
24872e107f3SRui Ueyama     size_t SizeBefore = Ret.size();
24972e107f3SRui Ueyama 
25072e107f3SRui Ueyama     for (InputSectionBase *Sec : InputSections) {
25172e107f3SRui Ueyama       if (Sec->Assigned)
2528c6a5aafSRui Ueyama         continue;
25372e107f3SRui Ueyama 
254e39709b2SRafael Espindola       if (!Sec->Live) {
255e39709b2SRafael Espindola         reportDiscarded(Sec);
256e39709b2SRafael Espindola         continue;
257e39709b2SRafael Espindola       }
258e39709b2SRafael Espindola 
259908a3d34SRafael Espindola       // For -emit-relocs we have to ignore entries like
260908a3d34SRafael Espindola       //   .rela.dyn : { *(.rela.data) }
261908a3d34SRafael Espindola       // which are common because they are in the default bfd script.
26272e107f3SRui Ueyama       if (Sec->Type == SHT_REL || Sec->Type == SHT_RELA)
263908a3d34SRafael Espindola         continue;
2648c6a5aafSRui Ueyama 
26504c9ca74SRui Ueyama       std::string Filename = getFilename(Sec->File);
26672e107f3SRui Ueyama       if (!Cmd->FilePat.match(Filename) ||
26772e107f3SRui Ueyama           Pat.ExcludedFilePat.match(Filename) ||
26872e107f3SRui Ueyama           !Pat.SectionPat.match(Sec->Name))
269e0be2901SRui Ueyama         continue;
27072e107f3SRui Ueyama 
271ec5c4adbSRui Ueyama       // It is safe to assume that Sec is an InputSection
272ec5c4adbSRui Ueyama       // because mergeable or EH input sections have already been
273ec5c4adbSRui Ueyama       // handled and eliminated.
2746a1aa8d9SRafael Espindola       Ret.push_back(cast<InputSection>(Sec));
27572e107f3SRui Ueyama       Sec->Assigned = true;
276f94efdddSRui Ueyama     }
277d3190795SRafael Espindola 
278ee924709SRui Ueyama     // Sort sections as instructed by SORT-family commands and --sort-section
279ee924709SRui Ueyama     // option. Because SORT-family commands can be nested at most two depth
280ee924709SRui Ueyama     // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
281ee924709SRui Ueyama     // line option is respected even if a SORT command is given, the exact
282ee924709SRui Ueyama     // behavior we have here is a bit complicated. Here are the rules.
283ee924709SRui Ueyama     //
284ee924709SRui Ueyama     // 1. If two SORT commands are given, --sort-section is ignored.
285ee924709SRui Ueyama     // 2. If one SORT command is given, and if it is not SORT_NONE,
286ee924709SRui Ueyama     //    --sort-section is handled as an inner SORT command.
287ee924709SRui Ueyama     // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
288ee924709SRui Ueyama     // 4. If no SORT command is given, sort according to --sort-section.
289d6bcde38SGeorge Rimar     // 5. If no SORT commands are given and --sort-section is not specified,
290d6bcde38SGeorge Rimar     //    apply sorting provided by --symbol-ordering-file if any exist.
2911f4d7b56SRui Ueyama     auto Vec = MutableArrayRef<InputSection *>(Ret).slice(SizeBefore);
2921f4d7b56SRui Ueyama 
293d6bcde38SGeorge Rimar     if (Pat.SortOuter == SortSectionPolicy::Default &&
294d6bcde38SGeorge Rimar         Config->SortSection == SortSectionPolicy::Default) {
295187b67a5SRui Ueyama 
296187b67a5SRui Ueyama       // If -symbol-ordering-file was given, sort accordingly.
297187b67a5SRui Ueyama       // Usually, Order is empty.
298187b67a5SRui Ueyama       if (!Order.empty())
299187b67a5SRui Ueyama         sortByOrder(Vec, [&](InputSectionBase *S) { return Order.lookup(S); });
300d6bcde38SGeorge Rimar       continue;
301d6bcde38SGeorge Rimar     }
3021f4d7b56SRui Ueyama 
30307171f21SGeorge Rimar     if (Pat.SortOuter != SortSectionPolicy::None) {
30407171f21SGeorge Rimar       if (Pat.SortInner == SortSectionPolicy::Default)
3051f4d7b56SRui Ueyama         sortSections(Vec, Config->SortSection);
306ee924709SRui Ueyama       else
3071f4d7b56SRui Ueyama         sortSections(Vec, Pat.SortInner);
3081f4d7b56SRui Ueyama       sortSections(Vec, Pat.SortOuter);
30907171f21SGeorge Rimar     }
310ee924709SRui Ueyama   }
31172e107f3SRui Ueyama   return Ret;
312be94e1b6SRafael Espindola }
313be94e1b6SRafael Espindola 
31405433431SRui Ueyama void LinkerScript::discard(ArrayRef<InputSection *> V) {
31505433431SRui Ueyama   for (InputSection *S : V) {
316be94e1b6SRafael Espindola     S->Live = false;
3171e30f07cSDmitry Mikulin     if (S == InX::ShStrTab || S == InX::Dynamic || S == InX::DynSymTab ||
3181e30f07cSDmitry Mikulin         S == InX::DynStrTab)
3192af64b0bSRafael Espindola       error("discarding " + S->Name + " section is not allowed");
320647c1685SGeorge Rimar     discard(S->DependentSections);
321be94e1b6SRafael Espindola   }
322be94e1b6SRafael Espindola }
323be94e1b6SRafael Espindola 
32405433431SRui Ueyama std::vector<InputSection *>
3258c022ca7SRafael Espindola LinkerScript::createInputSectionList(OutputSection &OutCmd) {
32605433431SRui Ueyama   std::vector<InputSection *> Ret;
327e7f912cdSRui Ueyama 
3286b394caaSRui Ueyama   for (BaseCommand *Base : OutCmd.SectionCommands) {
32905433431SRui Ueyama     if (auto *Cmd = dyn_cast<InputSectionDescription>(Base)) {
33072e107f3SRui Ueyama       Cmd->Sections = computeInputSections(Cmd);
331e4c8b9b7SRafael Espindola       Ret.insert(Ret.end(), Cmd->Sections.begin(), Cmd->Sections.end());
3320b9ce6a4SRui Ueyama     }
33305433431SRui Ueyama   }
3340b9ce6a4SRui Ueyama   return Ret;
3350b9ce6a4SRui Ueyama }
3360b9ce6a4SRui Ueyama 
3375908c2f8SRui Ueyama void LinkerScript::processSectionCommands(OutputSectionFactory &Factory) {
3385616adf6SRafael Espindola   // A symbol can be assigned before any section is mentioned in the linker
3395616adf6SRafael Espindola   // script. In an DSO, the symbol values are addresses, so the only important
3405616adf6SRafael Espindola   // section values are:
3415616adf6SRafael Espindola   // * SHN_UNDEF
3425616adf6SRafael Espindola   // * SHN_ABS
3435616adf6SRafael Espindola   // * Any value meaning a regular section.
3445616adf6SRafael Espindola   // To handle that, create a dummy aether section that fills the void before
3455616adf6SRafael Espindola   // the linker scripts switches to another section. It has an index of one
3465616adf6SRafael Espindola   // which will map to whatever the first actual section is.
3475616adf6SRafael Espindola   Aether = make<OutputSection>("", 0, SHF_ALLOC);
3485616adf6SRafael Espindola   Aether->SectionIndex = 1;
34918d19687SRui Ueyama 
35029b240c6SRui Ueyama   // Ctx captures the local AddressState and makes it accessible deliberately.
35129b240c6SRui Ueyama   // This is needed as there are some cases where we cannot just
352c1ace40bSPeter Smith   // thread the current state through to a lambda function created by the
353c1ace40bSPeter Smith   // script parser.
35429b240c6SRui Ueyama   Ctx = make_unique<AddressState>();
35529b240c6SRui Ueyama   Ctx->OutSec = Aether;
3565616adf6SRafael Espindola 
357355a8dd6SRui Ueyama   // Add input sections to output sections.
3586b394caaSRui Ueyama   for (size_t I = 0; I < SectionCommands.size(); ++I) {
3590b1b695aSRui Ueyama     // Handle symbol assignments outside of any output section.
3606b394caaSRui Ueyama     if (auto *Cmd = dyn_cast<SymbolAssignment>(SectionCommands[I])) {
3614cd7352cSRafael Espindola       addSymbol(Cmd);
3622ab5f73dSRui Ueyama       continue;
3632ab5f73dSRui Ueyama     }
3640b1b695aSRui Ueyama 
3656b394caaSRui Ueyama     if (auto *Sec = dyn_cast<OutputSection>(SectionCommands[I])) {
36605433431SRui Ueyama       std::vector<InputSection *> V = createInputSectionList(*Sec);
3677bd37870SRafael Espindola 
3680b1b695aSRui Ueyama       // The output section name `/DISCARD/' is special.
3690b1b695aSRui Ueyama       // Any input section assigned to it is discarded.
3708c022ca7SRafael Espindola       if (Sec->Name == "/DISCARD/") {
3717bd37870SRafael Espindola         discard(V);
37248c3f1ceSRui Ueyama         continue;
37348c3f1ceSRui Ueyama       }
3740b9ce6a4SRui Ueyama 
3750b1b695aSRui Ueyama       // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive
3760b1b695aSRui Ueyama       // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input
3770b1b695aSRui Ueyama       // sections satisfy a given constraint. If not, a directive is handled
37807d7c42cSGeorge Rimar       // as if it wasn't present from the beginning.
3790b1b695aSRui Ueyama       //
3806b394caaSRui Ueyama       // Because we'll iterate over SectionCommands many more times, the easiest
38107d7c42cSGeorge Rimar       // way to "make it as if it wasn't present" is to just remove it.
3828c022ca7SRafael Espindola       if (!matchConstraints(V, Sec->Constraint)) {
383b4c9b81aSRafael Espindola         for (InputSectionBase *S : V)
384f94efdddSRui Ueyama           S->Assigned = false;
3856b394caaSRui Ueyama         SectionCommands.erase(SectionCommands.begin() + I);
38607d7c42cSGeorge Rimar         --I;
3877c3ff2ebSRafael Espindola         continue;
3887c3ff2ebSRafael Espindola       }
3897c3ff2ebSRafael Espindola 
3900b1b695aSRui Ueyama       // A directive may contain symbol definitions like this:
3910b1b695aSRui Ueyama       // ".foo : { ...; bar = .; }". Handle them.
3926b394caaSRui Ueyama       for (BaseCommand *Base : Sec->SectionCommands)
3938f99f73cSRui Ueyama         if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base))
3944cd7352cSRafael Espindola           addSymbol(OutCmd);
3957c3ff2ebSRafael Espindola 
3960b1b695aSRui Ueyama       // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign
3970b1b695aSRui Ueyama       // is given, input sections are aligned to that value, whether the
3980b1b695aSRui Ueyama       // given value is larger or smaller than the original section alignment.
3998c022ca7SRafael Espindola       if (Sec->SubalignExpr) {
4008c022ca7SRafael Espindola         uint32_t Subalign = Sec->SubalignExpr().getValue();
401b4c9b81aSRafael Espindola         for (InputSectionBase *S : V)
4020b1b695aSRui Ueyama           S->Alignment = Subalign;
40320d03194SEugene Leviant       }
4040b1b695aSRui Ueyama 
4050b1b695aSRui Ueyama       // Add input sections to an output section.
40605433431SRui Ueyama       for (InputSection *S : V)
40705433431SRui Ueyama         Sec->addSection(S);
408355a8dd6SRui Ueyama     }
409355a8dd6SRui Ueyama   }
410355a8dd6SRui Ueyama   Ctx = nullptr;
411c54d5b16SRui Ueyama 
412355a8dd6SRui Ueyama   // Output sections are emitted in the exact same order as
413355a8dd6SRui Ueyama   // appeared in SECTIONS command, so we know their section indices.
414355a8dd6SRui Ueyama   for (size_t I = 0; I < SectionCommands.size(); ++I) {
415355a8dd6SRui Ueyama     auto *Sec = dyn_cast<OutputSection>(SectionCommands[I]);
416355a8dd6SRui Ueyama     if (!Sec)
417355a8dd6SRui Ueyama       continue;
418660c9ab9SRafael Espindola     assert(Sec->SectionIndex == INT_MAX);
419660c9ab9SRafael Espindola     Sec->SectionIndex = I;
4208c022ca7SRafael Espindola     if (Sec->Noload)
421fbb0463fSGeorge Rimar       Sec->Type = SHT_NOBITS;
42248c3f1ceSRui Ueyama   }
4234aa2ef5bSRafael Espindola }
424e63d81bdSEugene Leviant 
4252f4c121dSRui Ueyama // If no SECTIONS command was given, we create simple SectionCommands
4262f4c121dSRui Ueyama // as if a minimum SECTIONS command were given. This function does that.
42702ed7575SRafael Espindola void LinkerScript::fabricateDefaultCommands() {
428cbfe9e94SPeter Smith   // Define start address
429761f0b66SRui Ueyama   uint64_t StartAddr = UINT64_MAX;
430cbfe9e94SPeter Smith 
431c60b4510SPeter Smith   // The Sections with -T<section> have been sorted in order of ascending
432c60b4510SPeter Smith   // address. We must lower StartAddr if the lowest -T<section address> as
433c60b4510SPeter Smith   // calls to setDot() must be monotonically increasing.
434c60b4510SPeter Smith   for (auto &KV : Config->SectionStartMap)
435c60b4510SPeter Smith     StartAddr = std::min(StartAddr, KV.second);
436c60b4510SPeter Smith 
437f5db0b36SRui Ueyama   auto Expr = [=] {
438b5ca92efSJames Henderson     return std::min(StartAddr, Target->getImageBase() + elf::getHeaderSize());
439f5db0b36SRui Ueyama   };
4406b394caaSRui Ueyama   SectionCommands.insert(SectionCommands.begin(),
4416b394caaSRui Ueyama                          make<SymbolAssignment>(".", Expr, ""));
442cbfe9e94SPeter Smith }
443cbfe9e94SPeter Smith 
444d2f225fdSRui Ueyama static OutputSection *findByName(ArrayRef<BaseCommand *> Vec,
445d2f225fdSRui Ueyama                                  StringRef Name) {
446d2f225fdSRui Ueyama   for (BaseCommand *Base : Vec)
447d2f225fdSRui Ueyama     if (auto *Sec = dyn_cast<OutputSection>(Base))
448d2f225fdSRui Ueyama       if (Sec->Name == Name)
449d2f225fdSRui Ueyama         return Sec;
450d2f225fdSRui Ueyama   return nullptr;
451d2f225fdSRui Ueyama }
452d2f225fdSRui Ueyama 
4530b1b695aSRui Ueyama // Add sections that didn't match any sections command.
454b8dd23f5SRui Ueyama void LinkerScript::addOrphanSections(OutputSectionFactory &Factory) {
4556b394caaSRui Ueyama   unsigned End = SectionCommands.size();
456d2f225fdSRui Ueyama 
4574f013bb3SRafael Espindola   for (InputSectionBase *S : InputSections) {
458db5e56f7SRafael Espindola     if (!S->Live || S->Parent)
4594f013bb3SRafael Espindola       continue;
460d2f225fdSRui Ueyama 
4614f013bb3SRafael Espindola     StringRef Name = getOutputSectionName(S->Name);
462347c70d7SGeorge Rimar     log(toString(S) + " is being placed in '" + Name + "'");
463d2f225fdSRui Ueyama 
464ac27de9dSRui Ueyama     if (OutputSection *Sec =
4656b394caaSRui Ueyama             findByName(makeArrayRef(SectionCommands).slice(0, End), Name)) {
4660e2bfb1eSRui Ueyama       Sec->addSection(cast<InputSection>(S));
467c54d5b16SRui Ueyama       continue;
468660c9ab9SRafael Espindola     }
469c54d5b16SRui Ueyama 
470c54d5b16SRui Ueyama     if (OutputSection *OS = Factory.addInputSec(S, Name))
4716b394caaSRui Ueyama       SectionCommands.push_back(OS);
472c54d5b16SRui Ueyama     assert(S->getOutputSection()->SectionIndex == INT_MAX);
473d7faa916SRafael Espindola   }
4744f013bb3SRafael Espindola }
475e63d81bdSEugene Leviant 
47671f84067SRui Ueyama uint64_t LinkerScript::advance(uint64_t Size, unsigned Alignment) {
47729b240c6SRui Ueyama   bool IsTbss =
47829b240c6SRui Ueyama       (Ctx->OutSec->Flags & SHF_TLS) && Ctx->OutSec->Type == SHT_NOBITS;
47929b240c6SRui Ueyama   uint64_t Start = IsTbss ? Dot + Ctx->ThreadBssOffset : Dot;
48071f84067SRui Ueyama   Start = alignTo(Start, Alignment);
4817c4eafa3SRafael Espindola   uint64_t End = Start + Size;
4827c4eafa3SRafael Espindola 
4837c4eafa3SRafael Espindola   if (IsTbss)
48429b240c6SRui Ueyama     Ctx->ThreadBssOffset = End - Dot;
4857c4eafa3SRafael Espindola   else
4867c4eafa3SRafael Espindola     Dot = End;
4877c4eafa3SRafael Espindola   return End;
488a940e539SRafael Espindola }
489a940e539SRafael Espindola 
490b8dd23f5SRui Ueyama void LinkerScript::output(InputSection *S) {
491f694d33fSGeorge Rimar   uint64_t Before = advance(0, 1);
4927c4eafa3SRafael Espindola   uint64_t Pos = advance(S->getSize(), S->Alignment);
49329b240c6SRui Ueyama   S->OutSecOff = Pos - S->getSize() - Ctx->OutSec->Addr;
494d3190795SRafael Espindola 
495d3190795SRafael Espindola   // Update output section size after adding each section. This is so that
496d3190795SRafael Espindola   // SIZEOF works correctly in the case below:
497d3190795SRafael Espindola   // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
49829b240c6SRui Ueyama   Ctx->OutSec->Size = Pos - Ctx->OutSec->Addr;
499d3190795SRafael Espindola 
500b889744eSMeador Inge   // If there is a memory region associated with this input section, then
501b889744eSMeador Inge   // place the section in that region and update the region index.
50229b240c6SRui Ueyama   if (Ctx->MemRegion) {
50329b240c6SRui Ueyama     uint64_t &CurOffset = Ctx->MemRegionOffset[Ctx->MemRegion];
504f694d33fSGeorge Rimar     CurOffset += Pos - Before;
50529b240c6SRui Ueyama     uint64_t CurSize = CurOffset - Ctx->MemRegion->Origin;
50629b240c6SRui Ueyama     if (CurSize > Ctx->MemRegion->Length) {
50729b240c6SRui Ueyama       uint64_t OverflowAmt = CurSize - Ctx->MemRegion->Length;
50829b240c6SRui Ueyama       error("section '" + Ctx->OutSec->Name + "' will not fit in region '" +
50929b240c6SRui Ueyama             Ctx->MemRegion->Name + "': overflowed by " + Twine(OverflowAmt) +
51029b240c6SRui Ueyama             " bytes");
511b889744eSMeador Inge     }
512b889744eSMeador Inge   }
5132de509c3SRui Ueyama }
514ceabe80eSEugene Leviant 
515b8dd23f5SRui Ueyama void LinkerScript::switchTo(OutputSection *Sec) {
51629b240c6SRui Ueyama   if (Ctx->OutSec == Sec)
517d3190795SRafael Espindola     return;
518d3190795SRafael Espindola 
51929b240c6SRui Ueyama   Ctx->OutSec = Sec;
52029b240c6SRui Ueyama   Ctx->OutSec->Addr = advance(0, Ctx->OutSec->Alignment);
521b71d6f7aSEugene Leviant 
522b71d6f7aSEugene Leviant   // If neither AT nor AT> is specified for an allocatable section, the linker
523b71d6f7aSEugene Leviant   // will set the LMA such that the difference between VMA and LMA for the
524b71d6f7aSEugene Leviant   // section is the same as the preceding output section in the same region
525b71d6f7aSEugene Leviant   // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
52629b240c6SRui Ueyama   if (Ctx->LMAOffset)
52729b240c6SRui Ueyama     Ctx->OutSec->LMAOffset = Ctx->LMAOffset();
528d3190795SRafael Espindola }
529d3190795SRafael Espindola 
530b889744eSMeador Inge // This function searches for a memory region to place the given output
531b889744eSMeador Inge // section in. If found, a pointer to the appropriate memory region is
532b889744eSMeador Inge // returned. Otherwise, a nullptr is returned.
5338c022ca7SRafael Espindola MemoryRegion *LinkerScript::findMemoryRegion(OutputSection *Sec) {
534b889744eSMeador Inge   // If a memory region name was specified in the output section command,
535b889744eSMeador Inge   // then try to find that region first.
5368c022ca7SRafael Espindola   if (!Sec->MemoryRegionName.empty()) {
537ac27de9dSRui Ueyama     auto It = MemoryRegions.find(Sec->MemoryRegionName);
538ac27de9dSRui Ueyama     if (It != MemoryRegions.end())
5395f37541cSGeorge Rimar       return It->second;
5408c022ca7SRafael Espindola     error("memory region '" + Sec->MemoryRegionName + "' not declared");
541b889744eSMeador Inge     return nullptr;
542b889744eSMeador Inge   }
543b889744eSMeador Inge 
544d7c5400fSRui Ueyama   // If at least one memory region is defined, all sections must
545d7c5400fSRui Ueyama   // belong to some memory region. Otherwise, we don't need to do
546d7c5400fSRui Ueyama   // anything for memory regions.
547ac27de9dSRui Ueyama   if (MemoryRegions.empty())
548b889744eSMeador Inge     return nullptr;
549b889744eSMeador Inge 
550b889744eSMeador Inge   // See if a region can be found by matching section flags.
551ac27de9dSRui Ueyama   for (auto &Pair : MemoryRegions) {
5525f37541cSGeorge Rimar     MemoryRegion *M = Pair.second;
5535f37541cSGeorge Rimar     if ((M->Flags & Sec->Flags) && (M->NegFlags & Sec->Flags) == 0)
5545f37541cSGeorge Rimar       return M;
555b889744eSMeador Inge   }
556b889744eSMeador Inge 
557b889744eSMeador Inge   // Otherwise, no suitable region was found.
558b889744eSMeador Inge   if (Sec->Flags & SHF_ALLOC)
559b889744eSMeador Inge     error("no memory region specified for section '" + Sec->Name + "'");
560b889744eSMeador Inge   return nullptr;
561b889744eSMeador Inge }
562b889744eSMeador Inge 
5630b1b695aSRui Ueyama // This function assigns offsets to input sections and an output section
5640b1b695aSRui Ueyama // for a single sections command (e.g. ".text { *(.text); }").
5658c022ca7SRafael Espindola void LinkerScript::assignOffsets(OutputSection *Sec) {
566dece2808SRafael Espindola   if (!(Sec->Flags & SHF_ALLOC))
567dece2808SRafael Espindola     Dot = 0;
5688c022ca7SRafael Espindola   else if (Sec->AddrExpr)
5698c022ca7SRafael Espindola     setDot(Sec->AddrExpr, Sec->Location, false);
570679828ffSRafael Espindola 
57129b240c6SRui Ueyama   Ctx->MemRegion = Sec->MemRegion;
57229b240c6SRui Ueyama   if (Ctx->MemRegion)
57329b240c6SRui Ueyama     Dot = Ctx->MemRegionOffset[Ctx->MemRegion];
574c2dffe3aSGeorge Rimar 
5758c022ca7SRafael Espindola   if (Sec->LMAExpr) {
5760c1c8085SGeorge Rimar     uint64_t D = Dot;
57729b240c6SRui Ueyama     Ctx->LMAOffset = [=] { return Sec->LMAExpr().getValue() - D; };
5785784e96fSEugene Leviant   }
5795784e96fSEugene Leviant 
580b889744eSMeador Inge   switchTo(Sec);
5810b1b695aSRui Ueyama 
582d86a4e50SGeorge Rimar   // We do not support custom layout for compressed debug sectons.
583d86a4e50SGeorge Rimar   // At this point we already know their size and have compressed content.
58429b240c6SRui Ueyama   if (Ctx->OutSec->Flags & SHF_COMPRESSED)
585d86a4e50SGeorge Rimar     return;
586d86a4e50SGeorge Rimar 
5872f4c121dSRui Ueyama   // We visited SectionsCommands from processSectionCommands to
5882f4c121dSRui Ueyama   // layout sections. Now, we visit SectionsCommands again to fix
5892f4c121dSRui Ueyama   // section offsets.
5902f4c121dSRui Ueyama   for (BaseCommand *Base : Sec->SectionCommands) {
5912f4c121dSRui Ueyama     // This handles the assignments to symbol or to the dot.
5922f4c121dSRui Ueyama     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base)) {
5932f4c121dSRui Ueyama       assignSymbol(Cmd, true);
5942f4c121dSRui Ueyama       continue;
5952f4c121dSRui Ueyama     }
5962f4c121dSRui Ueyama 
5972f4c121dSRui Ueyama     // Handle BYTE(), SHORT(), LONG(), or QUAD().
598*f0403c60SRui Ueyama     if (auto *Cmd = dyn_cast<ByteCommand>(Base)) {
5992f4c121dSRui Ueyama       Cmd->Offset = Dot - Ctx->OutSec->Addr;
6002f4c121dSRui Ueyama       Dot += Cmd->Size;
6012f4c121dSRui Ueyama       Ctx->OutSec->Size = Dot - Ctx->OutSec->Addr;
6022f4c121dSRui Ueyama       continue;
6032f4c121dSRui Ueyama     }
6042f4c121dSRui Ueyama 
6052f4c121dSRui Ueyama     // Handle ASSERT().
6062f4c121dSRui Ueyama     if (auto *Cmd = dyn_cast<AssertCommand>(Base)) {
6072f4c121dSRui Ueyama       Cmd->Expression();
6082f4c121dSRui Ueyama       continue;
6092f4c121dSRui Ueyama     }
6102f4c121dSRui Ueyama 
6112f4c121dSRui Ueyama     // Handle a single input section description command.
6122f4c121dSRui Ueyama     // It calculates and assigns the offsets for each section and also
6132f4c121dSRui Ueyama     // updates the output section size.
6142f4c121dSRui Ueyama     auto *Cmd = cast<InputSectionDescription>(Base);
6152f4c121dSRui Ueyama     for (InputSection *Sec : Cmd->Sections) {
6162f4c121dSRui Ueyama       // We tentatively added all synthetic sections at the beginning and
6172f4c121dSRui Ueyama       // removed empty ones afterwards (because there is no way to know
6182f4c121dSRui Ueyama       // whether they were going be empty or not other than actually running
6192f4c121dSRui Ueyama       // linker scripts.) We need to ignore remains of empty sections.
6202f4c121dSRui Ueyama       if (auto *S = dyn_cast<SyntheticSection>(Sec))
6212f4c121dSRui Ueyama         if (S->empty())
6222f4c121dSRui Ueyama           continue;
6232f4c121dSRui Ueyama 
6242f4c121dSRui Ueyama       if (!Sec->Live)
6252f4c121dSRui Ueyama         continue;
6262f4c121dSRui Ueyama       assert(Ctx->OutSec == Sec->getParent());
6272f4c121dSRui Ueyama       output(Sec);
6282f4c121dSRui Ueyama     }
6292f4c121dSRui Ueyama   }
630d3190795SRafael Espindola }
631d3190795SRafael Espindola 
632b8dd23f5SRui Ueyama void LinkerScript::removeEmptyCommands() {
6336d38e4dbSRafael Espindola   // It is common practice to use very generic linker scripts. So for any
6346d38e4dbSRafael Espindola   // given run some of the output sections in the script will be empty.
6356d38e4dbSRafael Espindola   // We could create corresponding empty output sections, but that would
6366d38e4dbSRafael Espindola   // clutter the output.
6376d38e4dbSRafael Espindola   // We instead remove trivially empty sections. The bfd linker seems even
6386d38e4dbSRafael Espindola   // more aggressive at removing them.
6396b394caaSRui Ueyama   llvm::erase_if(SectionCommands, [&](BaseCommand *Base) {
6408c022ca7SRafael Espindola     if (auto *Sec = dyn_cast<OutputSection>(Base))
6418c022ca7SRafael Espindola       return !Sec->Live;
6420b1b695aSRui Ueyama     return false;
6436d38e4dbSRafael Espindola   });
64407fe6129SRafael Espindola }
64507fe6129SRafael Espindola 
6468c022ca7SRafael Espindola static bool isAllSectionDescription(const OutputSection &Cmd) {
6476b394caaSRui Ueyama   for (BaseCommand *Base : Cmd.SectionCommands)
6488f99f73cSRui Ueyama     if (!isa<InputSectionDescription>(*Base))
6496a53737cSRafael Espindola       return false;
6506a53737cSRafael Espindola   return true;
6516a53737cSRafael Espindola }
6526d38e4dbSRafael Espindola 
653b8dd23f5SRui Ueyama void LinkerScript::adjustSectionsBeforeSorting() {
6549546fffbSRafael Espindola   // If the output section contains only symbol assignments, create a
6559546fffbSRafael Espindola   // corresponding output section. The bfd linker seems to only create them if
6569546fffbSRafael Espindola   // '.' is assigned to, but creating these section should not have any bad
6579546fffbSRafael Espindola   // consequeces and gives us a section to put the symbol in.
6580c1c8085SGeorge Rimar   uint64_t Flags = SHF_ALLOC;
659660c9ab9SRafael Espindola 
6606b394caaSRui Ueyama   for (BaseCommand *Cmd : SectionCommands) {
6618962db91SGeorge Rimar     auto *Sec = dyn_cast<OutputSection>(Cmd);
6628c022ca7SRafael Espindola     if (!Sec)
6639546fffbSRafael Espindola       continue;
6648c022ca7SRafael Espindola     if (Sec->Live) {
6652b074553SRafael Espindola       Flags = Sec->Flags;
6669546fffbSRafael Espindola       continue;
6679546fffbSRafael Espindola     }
6689546fffbSRafael Espindola 
6698c022ca7SRafael Espindola     if (isAllSectionDescription(*Sec))
6706a53737cSRafael Espindola       continue;
6716a53737cSRafael Espindola 
6728c022ca7SRafael Espindola     Sec->Live = true;
6738c022ca7SRafael Espindola     Sec->Flags = Flags;
6749546fffbSRafael Espindola   }
675f7a17448SRafael Espindola }
676f7a17448SRafael Espindola 
677b8dd23f5SRui Ueyama void LinkerScript::adjustSectionsAfterSorting() {
678feed7506SRafael Espindola   // Try and find an appropriate memory region to assign offsets in.
6796b394caaSRui Ueyama   for (BaseCommand *Base : SectionCommands) {
6808c022ca7SRafael Espindola     if (auto *Sec = dyn_cast<OutputSection>(Base)) {
681ba45584cSGeorge Rimar       if (!Sec->Live)
682ba45584cSGeorge Rimar         continue;
6838c022ca7SRafael Espindola       Sec->MemRegion = findMemoryRegion(Sec);
684d1960dc0SRafael Espindola       // Handle align (e.g. ".foo : ALIGN(16) { ... }").
6858c022ca7SRafael Espindola       if (Sec->AlignExpr)
6868befefb2SRui Ueyama         Sec->Alignment =
6878befefb2SRui Ueyama             std::max<uint32_t>(Sec->Alignment, Sec->AlignExpr().getValue());
688d1960dc0SRafael Espindola     }
689d1960dc0SRafael Espindola   }
690feed7506SRafael Espindola 
691f7a17448SRafael Espindola   // If output section command doesn't specify any segments,
692f7a17448SRafael Espindola   // and we haven't previously assigned any section to segment,
693f7a17448SRafael Espindola   // then we simply assign section to the very first load segment.
694f7a17448SRafael Espindola   // Below is an example of such linker script:
695f7a17448SRafael Espindola   // PHDRS { seg PT_LOAD; }
696f7a17448SRafael Espindola   // SECTIONS { .aaa : { *(.aaa) } }
697f7a17448SRafael Espindola   std::vector<StringRef> DefPhdrs;
698f7a17448SRafael Espindola   auto FirstPtLoad =
699ac27de9dSRui Ueyama       std::find_if(PhdrsCommands.begin(), PhdrsCommands.end(),
700f7a17448SRafael Espindola                    [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; });
701ac27de9dSRui Ueyama   if (FirstPtLoad != PhdrsCommands.end())
702f7a17448SRafael Espindola     DefPhdrs.push_back(FirstPtLoad->Name);
703f7a17448SRafael Espindola 
704f7a17448SRafael Espindola   // Walk the commands and propagate the program headers to commands that don't
705f7a17448SRafael Espindola   // explicitly specify them.
7066b394caaSRui Ueyama   for (BaseCommand *Base : SectionCommands) {
7078c022ca7SRafael Espindola     auto *Sec = dyn_cast<OutputSection>(Base);
7088c022ca7SRafael Espindola     if (!Sec)
709f7a17448SRafael Espindola       continue;
7108f99f73cSRui Ueyama 
7118c022ca7SRafael Espindola     if (Sec->Phdrs.empty()) {
712a020d348SAndrew Ng       // To match the bfd linker script behaviour, only propagate program
713a020d348SAndrew Ng       // headers to sections that are allocated.
7148c022ca7SRafael Espindola       if (Sec->Flags & SHF_ALLOC)
7158c022ca7SRafael Espindola         Sec->Phdrs = DefPhdrs;
716a020d348SAndrew Ng     } else {
7178c022ca7SRafael Espindola       DefPhdrs = Sec->Phdrs;
718f7a17448SRafael Espindola     }
719a020d348SAndrew Ng   }
7209546fffbSRafael Espindola }
7219546fffbSRafael Espindola 
722582ede89SGeorge Rimar static OutputSection *findFirstSection(PhdrEntry *Load) {
723582ede89SGeorge Rimar   for (OutputSection *Sec : OutputSections)
724582ede89SGeorge Rimar     if (Sec->PtLoad == Load)
725582ede89SGeorge Rimar       return Sec;
726582ede89SGeorge Rimar   return nullptr;
727582ede89SGeorge Rimar }
728582ede89SGeorge Rimar 
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.
755a323e2a7SRui Ueyama   uint64_t Base = HasSectionsCommand ? alignDown(Min, Config->MaxPageSize) : 0;
756b93c5b9fSPetr Hosek   if (HeaderSize <= Min - Base || Script->hasPhdrsCommands()) {
7571f0fe88aSRafael Espindola     Min = alignDown(Min - HeaderSize, Config->MaxPageSize);
75802ed7575SRafael Espindola     Out::ElfHeader->Addr = Min;
75902ed7575SRafael Espindola     Out::ProgramHeaders->Addr = Min + Out::ElfHeader->Size;
760d971e703SGeorge Rimar     return;
76102ed7575SRafael Espindola   }
76202ed7575SRafael Espindola 
763582ede89SGeorge Rimar   Out::ElfHeader->PtLoad = nullptr;
764582ede89SGeorge Rimar   Out::ProgramHeaders->PtLoad = nullptr;
7656823c5f0SGeorge Rimar   FirstPTLoad->FirstSec = findFirstSection(FirstPTLoad);
76602ed7575SRafael Espindola 
76760608a8aSGeorge Rimar   llvm::erase_if(Phdrs,
76860608a8aSGeorge Rimar                  [](const PhdrEntry *E) { return E->p_type == PT_PHDR; });
76902ed7575SRafael Espindola }
77002ed7575SRafael Espindola 
771ac27de9dSRui Ueyama LinkerScript::AddressState::AddressState() {
772ac27de9dSRui Ueyama   for (auto &MRI : Script->MemoryRegions) {
7735f37541cSGeorge Rimar     const MemoryRegion *MR = MRI.second;
774906e9a18SPeter Smith     MemRegionOffset[MR] = MR->Origin;
775906e9a18SPeter Smith   }
776906e9a18SPeter Smith }
777906e9a18SPeter Smith 
7787c18c28cSRui Ueyama // Assign addresses as instructed by linker script SECTIONS sub-commands.
779b5ca92efSJames Henderson void LinkerScript::assignAddresses() {
780b5ca92efSJames Henderson   // By default linker scripts use an initial value of 0 for '.', but prefer
781b5ca92efSJames Henderson   // -image-base if set.
782b5ca92efSJames Henderson   Dot = Config->ImageBase ? *Config->ImageBase : 0;
78318d19687SRui Ueyama 
78429b240c6SRui Ueyama   // Ctx captures the local AddressState and makes it accessible
785c1ace40bSPeter Smith   // deliberately. This is needed as there are some cases where we cannot just
786c1ace40bSPeter Smith   // thread the current state through to a lambda function created by the
787c1ace40bSPeter Smith   // script parser.
78829b240c6SRui Ueyama   Ctx = make_unique<AddressState>();
78972dc195dSRafael Espindola   ErrorOnMissingSection = true;
79006f4743aSRafael Espindola   switchTo(Aether);
79106f4743aSRafael Espindola 
7926b394caaSRui Ueyama   for (BaseCommand *Base : SectionCommands) {
7938f99f73cSRui Ueyama     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base)) {
794d379f735SRui Ueyama       assignSymbol(Cmd, false);
79505ef4cffSRui Ueyama       continue;
796652852c5SGeorge Rimar     }
797652852c5SGeorge Rimar 
7988f99f73cSRui Ueyama     if (auto *Cmd = dyn_cast<AssertCommand>(Base)) {
7994595df94SRafael Espindola       Cmd->Expression();
800eefa758eSGeorge Rimar       continue;
801eefa758eSGeorge Rimar     }
802eefa758eSGeorge Rimar 
8038c022ca7SRafael Espindola     assignOffsets(cast<OutputSection>(Base));
804a14b13d8SGeorge Rimar   }
80529b240c6SRui Ueyama   Ctx = nullptr;
806fb8978fcSDima Stepanov }
807652852c5SGeorge Rimar 
808464daadcSRui Ueyama // Creates program headers as instructed by PHDRS linker script command.
809aa354187SGeorge Rimar std::vector<PhdrEntry *> LinkerScript::createPhdrs() {
810aa354187SGeorge Rimar   std::vector<PhdrEntry *> Ret;
811bbe38602SEugene Leviant 
812464daadcSRui Ueyama   // Process PHDRS and FILEHDR keywords because they are not
813464daadcSRui Ueyama   // real output sections and cannot be added in the following loop.
814ac27de9dSRui Ueyama   for (const PhdrsCommand &Cmd : PhdrsCommands) {
8150ae2c24cSRui Ueyama     PhdrEntry *Phdr = make<PhdrEntry>(Cmd.Type, Cmd.Flags ? *Cmd.Flags : PF_R);
816bbe38602SEugene Leviant 
817bbe38602SEugene Leviant     if (Cmd.HasFilehdr)
818aa354187SGeorge Rimar       Phdr->add(Out::ElfHeader);
819bbe38602SEugene Leviant     if (Cmd.HasPhdrs)
820aa354187SGeorge Rimar       Phdr->add(Out::ProgramHeaders);
82156b21c86SEugene Leviant 
82256b21c86SEugene Leviant     if (Cmd.LMAExpr) {
823aa354187SGeorge Rimar       Phdr->p_paddr = Cmd.LMAExpr().getValue();
824aa354187SGeorge Rimar       Phdr->HasLMA = true;
82556b21c86SEugene Leviant     }
826aa354187SGeorge Rimar     Ret.push_back(Phdr);
827bbe38602SEugene Leviant   }
828bbe38602SEugene Leviant 
829464daadcSRui Ueyama   // Add output sections to program headers.
8308c022ca7SRafael Espindola   for (OutputSection *Sec : OutputSections) {
831bbe38602SEugene Leviant     // Assign headers specified by linker script
8328c022ca7SRafael Espindola     for (size_t Id : getPhdrIndices(Sec)) {
833aa354187SGeorge Rimar       Ret[Id]->add(Sec);
834ac27de9dSRui Ueyama       if (!PhdrsCommands[Id].Flags.hasValue())
835aa354187SGeorge Rimar         Ret[Id]->p_flags |= Sec->getPhdrFlags();
836bbe38602SEugene Leviant     }
837bbe38602SEugene Leviant   }
838edebbdf1SRui Ueyama   return Ret;
839bbe38602SEugene Leviant }
840bbe38602SEugene Leviant 
841e03ba023SRui Ueyama // Returns true if we should emit an .interp section.
842e03ba023SRui Ueyama //
843e03ba023SRui Ueyama // We usually do. But if PHDRS commands are given, and
844e03ba023SRui Ueyama // no PT_INTERP is there, there's no place to emit an
845e03ba023SRui Ueyama // .interp, so we don't do that in that case.
846e03ba023SRui Ueyama bool LinkerScript::needsInterpSection() {
847ac27de9dSRui Ueyama   if (PhdrsCommands.empty())
848e03ba023SRui Ueyama     return true;
849ac27de9dSRui Ueyama   for (PhdrsCommand &Cmd : PhdrsCommands)
850e31d9886SRui Ueyama     if (Cmd.Type == PT_INTERP)
851e31d9886SRui Ueyama       return true;
852e03ba023SRui Ueyama   return false;
853f9bc3bd2SEugene Leviant }
854f9bc3bd2SEugene Leviant 
855b8dd23f5SRui Ueyama ExprValue LinkerScript::getSymbolValue(const Twine &Loc, StringRef S) {
8567e5b0a59SGeorge Rimar   if (S == ".") {
85729b240c6SRui Ueyama     if (Ctx)
85829b240c6SRui Ueyama       return {Ctx->OutSec, false, Dot - Ctx->OutSec->Addr, Loc};
8597e5b0a59SGeorge Rimar     error(Loc + ": unable to get location counter value");
8607e5b0a59SGeorge Rimar     return 0;
8617e5b0a59SGeorge Rimar   }
862244ef981SRafael Espindola   if (SymbolBody *B = Symtab->find(S)) {
86372dc195dSRafael Espindola     if (auto *D = dyn_cast<DefinedRegular>(B))
8644fbe3518SRui Ueyama       return {D->Section, false, D->Value, Loc};
86530f16b23SPetr Hosek     if (auto *C = dyn_cast<DefinedCommon>(B))
8664fbe3518SRui Ueyama       return {C->Section, false, 0, Loc};
86772dc195dSRafael Espindola   }
868f6aeed36SEugene Leviant   error(Loc + ": symbol not found: " + S);
869884e786dSGeorge Rimar   return 0;
870884e786dSGeorge Rimar }
871884e786dSGeorge Rimar 
872656be311SRui Ueyama // Returns the index of the segment named Name.
873656be311SRui Ueyama static Optional<size_t> getPhdrIndex(ArrayRef<PhdrsCommand> Vec,
874656be311SRui Ueyama                                      StringRef Name) {
875656be311SRui Ueyama   for (size_t I = 0; I < Vec.size(); ++I)
876656be311SRui Ueyama     if (Vec[I].Name == Name)
877656be311SRui Ueyama       return I;
878656be311SRui Ueyama   return None;
879656be311SRui Ueyama }
880656be311SRui Ueyama 
8812c923c2cSRafael Espindola // Returns indices of ELF headers containing specific section. Each index is a
8822c923c2cSRafael Espindola // zero based number of ELF header listed within PHDRS {} script block.
8838c022ca7SRafael Espindola std::vector<size_t> LinkerScript::getPhdrIndices(OutputSection *Cmd) {
88429c5a2a9SRui Ueyama   std::vector<size_t> Ret;
885656be311SRui Ueyama 
886656be311SRui Ueyama   for (StringRef S : Cmd->Phdrs) {
887ac27de9dSRui Ueyama     if (Optional<size_t> Idx = getPhdrIndex(PhdrsCommands, S))
88887223574SRui Ueyama       Ret.push_back(*Idx);
889656be311SRui Ueyama     else if (S != "NONE")
890656be311SRui Ueyama       error(Cmd->Location + ": section header '" + S +
891656be311SRui Ueyama             "' is not listed in PHDRS");
892bbe38602SEugene Leviant   }
893656be311SRui Ueyama   return Ret;
89429c5a2a9SRui Ueyama }
895