blob: fc56c5fcb8e0d3b7a9dc95b063bfff3b784ae1f5 [file] [log] [blame]
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001//===- LinkerScript.cpp ---------------------------------------------------===//
2//
3// The LLVM Linker
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains the parser/evaluator of the linker script.
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000011//
12//===----------------------------------------------------------------------===//
13
Rui Ueyama717677a2016-02-11 21:17:59 +000014#include "LinkerScript.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000015#include "Config.h"
16#include "Driver.h"
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +000017#include "InputSection.h"
Rui Ueyama9381eb12016-12-18 14:06:06 +000018#include "Memory.h"
George Rimar652852c2016-04-16 10:10:32 +000019#include "OutputSections.h"
Rui Ueyama794366a2017-02-14 04:47:05 +000020#include "ScriptLexer.h"
Rui Ueyama93c9af42016-06-29 08:01:32 +000021#include "Strings.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000022#include "SymbolTable.h"
Rui Ueyama55518e72016-10-28 20:57:25 +000023#include "Symbols.h"
George Rimar3fb5a6d2016-11-29 16:05:27 +000024#include "SyntheticSections.h"
Eugene Leviant467c4d52016-07-01 10:27:36 +000025#include "Target.h"
Eugene Leviantbbe38602016-07-19 09:25:43 +000026#include "Writer.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000027#include "llvm/ADT/STLExtras.h"
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +000028#include "llvm/ADT/SmallString.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000029#include "llvm/ADT/StringRef.h"
Rui Ueyama960504b2016-04-19 18:58:11 +000030#include "llvm/ADT/StringSwitch.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000031#include "llvm/Support/Casting.h"
George Rimar652852c2016-04-16 10:10:32 +000032#include "llvm/Support/ELF.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000033#include "llvm/Support/Endian.h"
34#include "llvm/Support/ErrorHandling.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000035#include "llvm/Support/FileSystem.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000036#include "llvm/Support/MathExtras.h"
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +000037#include "llvm/Support/Path.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000038#include <algorithm>
39#include <cassert>
40#include <cstddef>
41#include <cstdint>
42#include <iterator>
43#include <limits>
44#include <memory>
45#include <string>
46#include <tuple>
47#include <vector>
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000048
49using namespace llvm;
George Rimar652852c2016-04-16 10:10:32 +000050using namespace llvm::ELF;
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +000051using namespace llvm::object;
George Rimare38cbab2016-09-26 19:22:50 +000052using namespace llvm::support::endian;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000053using namespace lld;
Rafael Espindolae0df00b2016-02-28 00:25:54 +000054using namespace lld::elf;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000055
George Rimar884e7862016-09-08 08:19:13 +000056LinkerScriptBase *elf::ScriptBase;
Rui Ueyama07320e42016-04-20 20:13:41 +000057ScriptConfiguration *elf::ScriptConfig;
Rui Ueyama717677a2016-02-11 21:17:59 +000058
Meador Inge8f1f3c42017-01-09 18:36:57 +000059template <class ELFT> static SymbolBody *addRegular(SymbolAssignment *Cmd) {
Petr Hosek5e51f7d2017-02-21 22:32:51 +000060 Symbol *Sym;
Rafael Espindola3dabfc62016-10-31 13:14:53 +000061 uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
Petr Hosek5e51f7d2017-02-21 22:32:51 +000062 std::tie(Sym, std::ignore) = Symtab<ELFT>::X->insert(
63 Cmd->Name, /*Type*/ 0, Visibility, /*CanOmitFromDynSym*/ false,
64 /*File*/ nullptr);
65 Sym->Binding = STB_GLOBAL;
Rafael Espindola9bd45662017-03-10 00:47:33 +000066 SectionBase *Sec =
Rafael Espindola5616adf2017-03-08 22:36:28 +000067 Cmd->Expression.IsAbsolute() ? nullptr : Cmd->Expression.Section();
Rui Ueyama80474a22017-02-28 19:29:55 +000068 replaceBody<DefinedRegular>(Sym, Cmd->Name, /*IsLocal=*/false, Visibility,
Rafael Espindola5616adf2017-03-08 22:36:28 +000069 STT_NOTYPE, 0, 0, Sec, nullptr);
Meador Inge8f1f3c42017-01-09 18:36:57 +000070 return Sym->body();
Eugene Leviantceabe802016-08-11 07:56:43 +000071}
72
Rui Ueyama22375f22016-11-25 18:51:54 +000073static bool isUnderSysroot(StringRef Path) {
74 if (Config->Sysroot == "")
75 return false;
76 for (; !Path.empty(); Path = sys::path::parent_path(Path))
77 if (sys::fs::equivalent(Config->Sysroot, Path))
78 return true;
79 return false;
80}
81
George Rimar851dc1e2017-03-14 10:15:53 +000082OutputSection *LinkerScriptBase::getOutputSection(const Twine &Loc,
83 StringRef Name) {
84 static OutputSection FakeSec("", 0, 0);
85
86 for (OutputSection *Sec : *OutputSections)
87 if (Sec->Name == Name)
88 return Sec;
89
90 error(Loc + ": undefined section " + Name);
91 return &FakeSec;
92}
93
George Rimard83ce1b2017-03-14 10:24:47 +000094// This function is essentially the same as getOutputSection(Name)->Size,
95// but it won't print out an error message if a given section is not found.
96//
97// Linker script does not create an output section if its content is empty.
98// We want to allow SIZEOF(.foo) where .foo is a section which happened to
99// be empty. That is why this function is different from getOutputSection().
100uint64_t LinkerScriptBase::getOutputSectionSize(StringRef Name) {
101 for (OutputSection *Sec : *OutputSections)
102 if (Sec->Name == Name)
103 return Sec->Size;
104 return 0;
105}
106
George Rimara2a1ef12017-03-14 12:03:34 +0000107void LinkerScriptBase::setDot(Expr E, const Twine &Loc, bool InSec) {
George Rimar0c1c8082017-03-14 10:00:19 +0000108 uint64_t Val = E();
Rafael Espindola679828f2017-02-17 16:26:13 +0000109 if (Val < Dot) {
110 if (InSec)
George Rimar2ee2d2d2017-02-21 14:50:38 +0000111 error(Loc + ": unable to move location counter backward for: " +
112 CurOutSec->Name);
Rafael Espindola679828f2017-02-17 16:26:13 +0000113 else
George Rimar2ee2d2d2017-02-21 14:50:38 +0000114 error(Loc + ": unable to move location counter backward");
Rafael Espindola679828f2017-02-17 16:26:13 +0000115 }
116 Dot = Val;
117 // Update to location counter means update to section size.
118 if (InSec)
119 CurOutSec->Size = Dot - CurOutSec->Addr;
120}
121
George Rimarb2b70972017-02-07 10:23:28 +0000122// Sets value of a symbol. Two kinds of symbols are processed: synthetic
123// symbols, whose value is an offset from beginning of section and regular
124// symbols whose value is absolute.
George Rimara2a1ef12017-03-14 12:03:34 +0000125void LinkerScriptBase::assignSymbol(SymbolAssignment *Cmd, bool InSec) {
Rafael Espindola4cd73522017-02-17 16:01:51 +0000126 if (Cmd->Name == ".") {
George Rimar2ee2d2d2017-02-21 14:50:38 +0000127 setDot(Cmd->Expression, Cmd->Location, InSec);
Rafael Espindola4cd73522017-02-17 16:01:51 +0000128 return;
129 }
130
George Rimarb2b70972017-02-07 10:23:28 +0000131 if (!Cmd->Sym)
Meador Inge8f1f3c42017-01-09 18:36:57 +0000132 return;
133
Rafael Espindola5616adf2017-03-08 22:36:28 +0000134 auto *Sym = cast<DefinedRegular>(Cmd->Sym);
Rafael Espindola4595df92017-03-10 16:04:26 +0000135 Sym->Value = Cmd->Expression();
Rafael Espindola5616adf2017-03-08 22:36:28 +0000136 if (!Cmd->Expression.IsAbsolute()) {
137 Sym->Section = Cmd->Expression.Section();
138 if (auto *Sec = dyn_cast_or_null<OutputSection>(Sym->Section))
139 if (Sec->Flags & SHF_ALLOC)
140 Sym->Value -= Sec->Addr;
Meador Inge8f1f3c42017-01-09 18:36:57 +0000141 }
Eugene Leviantdb741e72016-09-07 07:08:43 +0000142}
Meador Inge8f1f3c42017-01-09 18:36:57 +0000143
Rafael Espindola4cd73522017-02-17 16:01:51 +0000144template <class ELFT>
145void LinkerScript<ELFT>::addSymbol(SymbolAssignment *Cmd) {
Rui Ueyama16024212016-08-11 23:22:52 +0000146 if (Cmd->Name == ".")
Meador Inge8f1f3c42017-01-09 18:36:57 +0000147 return;
148
149 // If a symbol was in PROVIDE(), we need to define it only when
150 // it is a referenced undefined symbol.
Rui Ueyama16024212016-08-11 23:22:52 +0000151 SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
Meador Inge8f1f3c42017-01-09 18:36:57 +0000152 if (Cmd->Provide && (!B || B->isDefined()))
153 return;
154
Rafael Espindola5616adf2017-03-08 22:36:28 +0000155 Cmd->Sym = addRegular<ELFT>(Cmd);
Eugene Leviantceabe802016-08-11 07:56:43 +0000156}
157
George Rimar076fe152016-07-21 06:43:01 +0000158bool SymbolAssignment::classof(const BaseCommand *C) {
159 return C->Kind == AssignmentKind;
160}
161
162bool OutputSectionCommand::classof(const BaseCommand *C) {
163 return C->Kind == OutputSectionKind;
164}
165
George Rimareea31142016-07-21 14:26:59 +0000166bool InputSectionDescription::classof(const BaseCommand *C) {
167 return C->Kind == InputSectionKind;
168}
169
George Rimareefa7582016-08-04 09:29:31 +0000170bool AssertCommand::classof(const BaseCommand *C) {
171 return C->Kind == AssertKind;
172}
173
George Rimare38cbab2016-09-26 19:22:50 +0000174bool BytesDataCommand::classof(const BaseCommand *C) {
175 return C->Kind == BytesDataKind;
176}
177
Eugene Zelenko22886a22016-11-05 01:00:56 +0000178template <class ELFT> LinkerScript<ELFT>::LinkerScript() = default;
179template <class ELFT> LinkerScript<ELFT>::~LinkerScript() = default;
Rui Ueyamaf34d0e02016-08-12 01:24:53 +0000180
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000181static StringRef basename(InputSectionBase *S) {
182 if (S->File)
183 return sys::path::filename(S->File->getName());
Rui Ueyamae0be2902016-11-21 02:10:12 +0000184 return "";
185}
186
George Rimara2a1ef12017-03-14 12:03:34 +0000187bool LinkerScriptBase::shouldKeep(InputSectionBase *S) {
Rui Ueyamae0be2902016-11-21 02:10:12 +0000188 for (InputSectionDescription *ID : Opt.KeptSections)
189 if (ID->FilePat.match(basename(S)))
190 for (SectionPattern &P : ID->SectionPatterns)
191 if (P.SectionPat.match(S->Name))
192 return true;
George Rimareea31142016-07-21 14:26:59 +0000193 return false;
194}
195
Rafael Espindolac404d502017-02-23 02:32:18 +0000196static bool comparePriority(InputSectionBase *A, InputSectionBase *B) {
George Rimar575208c2016-09-15 19:15:12 +0000197 return getPriority(A->Name) < getPriority(B->Name);
198}
199
Rafael Espindolac404d502017-02-23 02:32:18 +0000200static bool compareName(InputSectionBase *A, InputSectionBase *B) {
Rafael Espindola042a3f22016-09-08 14:06:08 +0000201 return A->Name < B->Name;
Rui Ueyama742c3832016-08-04 22:27:00 +0000202}
George Rimar350ece42016-08-03 08:35:59 +0000203
Rafael Espindolac404d502017-02-23 02:32:18 +0000204static bool compareAlignment(InputSectionBase *A, InputSectionBase *B) {
Rui Ueyama742c3832016-08-04 22:27:00 +0000205 // ">" is not a mistake. Larger alignments are placed before smaller
206 // alignments in order to reduce the amount of padding necessary.
207 // This is compatible with GNU.
208 return A->Alignment > B->Alignment;
209}
George Rimar350ece42016-08-03 08:35:59 +0000210
Rafael Espindolac404d502017-02-23 02:32:18 +0000211static std::function<bool(InputSectionBase *, InputSectionBase *)>
George Rimarbe394db2016-09-16 20:21:55 +0000212getComparator(SortSectionPolicy K) {
213 switch (K) {
214 case SortSectionPolicy::Alignment:
215 return compareAlignment;
216 case SortSectionPolicy::Name:
Rafael Espindolac0028d32016-09-08 20:47:52 +0000217 return compareName;
George Rimarbe394db2016-09-16 20:21:55 +0000218 case SortSectionPolicy::Priority:
219 return comparePriority;
220 default:
221 llvm_unreachable("unknown sort policy");
222 }
Rui Ueyama742c3832016-08-04 22:27:00 +0000223}
George Rimar0702c4e2016-07-29 15:32:46 +0000224
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000225static bool matchConstraints(ArrayRef<InputSectionBase *> Sections,
George Rimar06ae6832016-08-12 09:07:57 +0000226 ConstraintKind Kind) {
George Rimar8f66df92016-08-12 20:38:20 +0000227 if (Kind == ConstraintKind::NoConstraint)
228 return true;
Rafael Espindolac404d502017-02-23 02:32:18 +0000229 bool IsRW = llvm::any_of(Sections, [=](InputSectionBase *Sec2) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000230 auto *Sec = static_cast<InputSectionBase *>(Sec2);
Rafael Espindola1854a8e2016-10-26 12:36:56 +0000231 return Sec->Flags & SHF_WRITE;
George Rimar06ae6832016-08-12 09:07:57 +0000232 });
Rafael Espindolae746e522016-09-21 18:33:44 +0000233 return (IsRW && Kind == ConstraintKind::ReadWrite) ||
234 (!IsRW && Kind == ConstraintKind::ReadOnly);
George Rimar06ae6832016-08-12 09:07:57 +0000235}
236
Rafael Espindolac404d502017-02-23 02:32:18 +0000237static void sortSections(InputSectionBase **Begin, InputSectionBase **End,
Rui Ueyamaee924702016-09-20 19:42:41 +0000238 SortSectionPolicy K) {
239 if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
George Rimar07171f22016-09-21 15:56:44 +0000240 std::stable_sort(Begin, End, getComparator(K));
Rui Ueyamaee924702016-09-20 19:42:41 +0000241}
242
Rafael Espindolad3190792016-09-16 15:10:23 +0000243// Compute and remember which sections the InputSectionDescription matches.
George Rimara2a1ef12017-03-14 12:03:34 +0000244void LinkerScriptBase::computeInputSections(InputSectionDescription *I) {
Rui Ueyama4dc07be2016-09-17 02:23:40 +0000245 // Collects all sections that satisfy constraints of I
246 // and attach them to I.
247 for (SectionPattern &Pat : I->SectionPatterns) {
George Rimar07171f22016-09-21 15:56:44 +0000248 size_t SizeBefore = I->Sections.size();
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000249
Rui Ueyama536a2672017-02-27 02:32:08 +0000250 for (InputSectionBase *S : InputSections) {
Rafael Espindola3773bca2017-02-17 19:37:30 +0000251 if (S->Assigned)
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000252 continue;
Rafael Espindola908a3d32017-02-16 14:36:09 +0000253 // For -emit-relocs we have to ignore entries like
254 // .rela.dyn : { *(.rela.data) }
255 // which are common because they are in the default bfd script.
256 if (S->Type == SHT_REL || S->Type == SHT_RELA)
257 continue;
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000258
Rui Ueyamae0be2902016-11-21 02:10:12 +0000259 StringRef Filename = basename(S);
260 if (!I->FilePat.match(Filename) || Pat.ExcludedFilePat.match(Filename))
261 continue;
262 if (!Pat.SectionPat.match(S->Name))
263 continue;
264 I->Sections.push_back(S);
265 S->Assigned = true;
George Rimar395281c2016-09-16 17:42:10 +0000266 }
Rafael Espindolad3190792016-09-16 15:10:23 +0000267
George Rimar07171f22016-09-21 15:56:44 +0000268 // Sort sections as instructed by SORT-family commands and --sort-section
269 // option. Because SORT-family commands can be nested at most two depth
270 // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
271 // line option is respected even if a SORT command is given, the exact
272 // behavior we have here is a bit complicated. Here are the rules.
273 //
274 // 1. If two SORT commands are given, --sort-section is ignored.
275 // 2. If one SORT command is given, and if it is not SORT_NONE,
276 // --sort-section is handled as an inner SORT command.
277 // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
278 // 4. If no SORT command is given, sort according to --sort-section.
Rafael Espindolac404d502017-02-23 02:32:18 +0000279 InputSectionBase **Begin = I->Sections.data() + SizeBefore;
280 InputSectionBase **End = I->Sections.data() + I->Sections.size();
George Rimar07171f22016-09-21 15:56:44 +0000281 if (Pat.SortOuter != SortSectionPolicy::None) {
282 if (Pat.SortInner == SortSectionPolicy::Default)
283 sortSections(Begin, End, Config->SortSection);
284 else
285 sortSections(Begin, End, Pat.SortInner);
286 sortSections(Begin, End, Pat.SortOuter);
287 }
Rui Ueyamaee924702016-09-20 19:42:41 +0000288 }
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000289}
290
George Rimar503206c2017-03-15 15:42:44 +0000291void LinkerScriptBase::discard(ArrayRef<InputSectionBase *> V) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000292 for (InputSectionBase *S : V) {
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000293 S->Live = false;
George Rimar503206c2017-03-15 15:42:44 +0000294 if (S == InX::ShStrTab)
Rafael Espindolaecbfd872017-02-17 17:35:07 +0000295 error("discarding .shstrtab section is not allowed");
George Rimar647c1682017-02-17 19:34:05 +0000296 discard(S->DependentSections);
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000297 }
298}
299
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000300std::vector<InputSectionBase *>
George Rimara2a1ef12017-03-14 12:03:34 +0000301LinkerScriptBase::createInputSectionList(OutputSectionCommand &OutCmd) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000302 std::vector<InputSectionBase *> Ret;
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000303
George Rimar06ae6832016-08-12 09:07:57 +0000304 for (const std::unique_ptr<BaseCommand> &Base : OutCmd.Commands) {
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000305 auto *Cmd = dyn_cast<InputSectionDescription>(Base.get());
306 if (!Cmd)
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000307 continue;
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000308 computeInputSections(Cmd);
Rafael Espindolac404d502017-02-23 02:32:18 +0000309 for (InputSectionBase *S : Cmd->Sections)
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000310 Ret.push_back(static_cast<InputSectionBase *>(S));
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000311 }
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000312
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000313 return Ret;
314}
315
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000316template <class ELFT>
Rui Ueyama02a036f2017-02-27 02:31:48 +0000317void LinkerScript<ELFT>::processCommands(OutputSectionFactory &Factory) {
Rafael Espindola5616adf2017-03-08 22:36:28 +0000318 // A symbol can be assigned before any section is mentioned in the linker
319 // script. In an DSO, the symbol values are addresses, so the only important
320 // section values are:
321 // * SHN_UNDEF
322 // * SHN_ABS
323 // * Any value meaning a regular section.
324 // To handle that, create a dummy aether section that fills the void before
325 // the linker scripts switches to another section. It has an index of one
326 // which will map to whatever the first actual section is.
327 Aether = make<OutputSection>("", 0, SHF_ALLOC);
328 Aether->SectionIndex = 1;
329 CurOutSec = Aether;
330
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000331 for (unsigned I = 0; I < Opt.Commands.size(); ++I) {
332 auto Iter = Opt.Commands.begin() + I;
333 const std::unique_ptr<BaseCommand> &Base1 = *Iter;
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000334
335 // Handle symbol assignments outside of any output section.
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000336 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base1.get())) {
Rafael Espindola4cd73522017-02-17 16:01:51 +0000337 addSymbol(Cmd);
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000338 continue;
339 }
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000340
Eugene Leviantceabe802016-08-11 07:56:43 +0000341 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000342 std::vector<InputSectionBase *> V = createInputSectionList(*Cmd);
Rafael Espindola7bd37872016-09-12 16:05:16 +0000343
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000344 // The output section name `/DISCARD/' is special.
345 // Any input section assigned to it is discarded.
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000346 if (Cmd->Name == "/DISCARD/") {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000347 discard(V);
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000348 continue;
349 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000350
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000351 // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive
352 // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input
353 // sections satisfy a given constraint. If not, a directive is handled
354 // as if it wasn't present from the beginning.
355 //
356 // Because we'll iterate over Commands many more times, the easiest
357 // way to "make it as if it wasn't present" is to just remove it.
George Rimarf7f0d082017-03-14 11:23:33 +0000358 if (!matchConstraints(V, Cmd->Constraint)) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000359 for (InputSectionBase *S : V)
Rui Ueyamaf94efdd2016-11-20 23:15:52 +0000360 S->Assigned = false;
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000361 Opt.Commands.erase(Iter);
George Rimardfbbbc82016-09-17 09:50:10 +0000362 --I;
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000363 continue;
364 }
365
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000366 // A directive may contain symbol definitions like this:
367 // ".foo : { ...; bar = .; }". Handle them.
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000368 for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
369 if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base.get()))
Rafael Espindola4cd73522017-02-17 16:01:51 +0000370 addSymbol(OutCmd);
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000371
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000372 // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign
373 // is given, input sections are aligned to that value, whether the
374 // given value is larger or smaller than the original section alignment.
375 if (Cmd->SubalignExpr) {
Rafael Espindola4595df92017-03-10 16:04:26 +0000376 uint32_t Subalign = Cmd->SubalignExpr();
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000377 for (InputSectionBase *S : V)
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000378 S->Alignment = Subalign;
George Rimardb24d9c2016-08-19 15:18:23 +0000379 }
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000380
381 // Add input sections to an output section.
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000382 for (InputSectionBase *S : V)
George Rimare21c3af2017-03-14 09:30:25 +0000383 Factory.addInputSec(S, Cmd->Name);
Eugene Leviantceabe802016-08-11 07:56:43 +0000384 }
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000385 }
Rafael Espindola5616adf2017-03-08 22:36:28 +0000386 CurOutSec = nullptr;
Eugene Leviant20d03192016-09-16 15:30:47 +0000387}
Eugene Leviante63d81b2016-07-20 14:43:20 +0000388
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000389// Add sections that didn't match any sections command.
George Rimara2a1ef12017-03-14 12:03:34 +0000390void LinkerScriptBase::addOrphanSections(OutputSectionFactory &Factory) {
Rui Ueyama536a2672017-02-27 02:32:08 +0000391 for (InputSectionBase *S : InputSections)
Rafael Espindola8f9026b2016-11-08 18:23:02 +0000392 if (S->Live && !S->OutSec)
George Rimare21c3af2017-03-14 09:30:25 +0000393 Factory.addInputSec(S, getOutputSectionName(S->Name));
Eugene Leviante63d81b2016-07-20 14:43:20 +0000394}
395
George Rimarf7f0d082017-03-14 11:23:33 +0000396static bool isTbss(OutputSection *Sec) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000397 return (Sec->Flags & SHF_TLS) && Sec->Type == SHT_NOBITS;
Rafael Espindolaa940e532016-09-22 12:35:44 +0000398}
399
George Rimara2a1ef12017-03-14 12:03:34 +0000400void LinkerScriptBase::output(InputSection *S) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000401 if (!AlreadyOutputIS.insert(S).second)
402 return;
George Rimarf7f0d082017-03-14 11:23:33 +0000403 bool IsTbss = isTbss(CurOutSec);
Eugene Leviant20889c52016-08-31 08:13:33 +0000404
George Rimar0c1c8082017-03-14 10:00:19 +0000405 uint64_t Pos = IsTbss ? Dot + ThreadBssOffset : Dot;
Rafael Espindolad3190792016-09-16 15:10:23 +0000406 Pos = alignTo(Pos, S->Alignment);
Rafael Espindola04a2e342016-11-09 01:42:41 +0000407 S->OutSecOff = Pos - CurOutSec->Addr;
Rafael Espindola76b6bd32017-03-08 15:44:30 +0000408 Pos += S->getSize();
Rafael Espindolad3190792016-09-16 15:10:23 +0000409
410 // Update output section size after adding each section. This is so that
411 // SIZEOF works correctly in the case below:
412 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
Rafael Espindola04a2e342016-11-09 01:42:41 +0000413 CurOutSec->Size = Pos - CurOutSec->Addr;
Rafael Espindolad3190792016-09-16 15:10:23 +0000414
Meador Ingeb8897442017-01-24 02:34:00 +0000415 // If there is a memory region associated with this input section, then
416 // place the section in that region and update the region index.
417 if (CurMemRegion) {
418 CurMemRegion->Offset += CurOutSec->Size;
419 uint64_t CurSize = CurMemRegion->Offset - CurMemRegion->Origin;
420 if (CurSize > CurMemRegion->Length) {
421 uint64_t OverflowAmt = CurSize - CurMemRegion->Length;
422 error("section '" + CurOutSec->Name + "' will not fit in region '" +
423 CurMemRegion->Name + "': overflowed by " + Twine(OverflowAmt) +
424 " bytes");
425 }
426 }
427
Rafael Espindola7252ae52016-09-22 12:00:08 +0000428 if (IsTbss)
429 ThreadBssOffset = Pos - Dot;
430 else
Rafael Espindolad3190792016-09-16 15:10:23 +0000431 Dot = Pos;
432}
433
George Rimara2a1ef12017-03-14 12:03:34 +0000434void LinkerScriptBase::flush() {
Rafael Espindolabd12e2a2017-03-01 14:12:21 +0000435 assert(CurOutSec);
436 if (!AlreadyOutputOS.insert(CurOutSec).second)
Rafael Espindola65499b92016-09-23 20:10:47 +0000437 return;
Rafael Espindola24e6f362017-02-24 15:07:30 +0000438 for (InputSection *I : CurOutSec->Sections)
439 output(I);
Eugene Leviant20889c52016-08-31 08:13:33 +0000440}
441
George Rimara2a1ef12017-03-14 12:03:34 +0000442void LinkerScriptBase::switchTo(OutputSection *Sec) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000443 if (CurOutSec == Sec)
444 return;
445 if (AlreadyOutputOS.count(Sec))
446 return;
447
Rafael Espindolad3190792016-09-16 15:10:23 +0000448 CurOutSec = Sec;
449
Rafael Espindola37707632017-03-07 14:55:52 +0000450 Dot = alignTo(Dot, CurOutSec->Alignment);
George Rimarf7f0d082017-03-14 11:23:33 +0000451 CurOutSec->Addr = isTbss(CurOutSec) ? Dot + ThreadBssOffset : Dot;
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000452
453 // If neither AT nor AT> is specified for an allocatable section, the linker
454 // will set the LMA such that the difference between VMA and LMA for the
455 // section is the same as the preceding output section in the same region
456 // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
George Rimar21467872017-02-23 07:57:55 +0000457 if (LMAOffset)
Rafael Espindola29c1afb2017-02-24 14:34:12 +0000458 CurOutSec->LMAOffset = LMAOffset();
Rafael Espindolad3190792016-09-16 15:10:23 +0000459}
460
George Rimara2a1ef12017-03-14 12:03:34 +0000461void LinkerScriptBase::process(BaseCommand &Base) {
George Rimare38cbab2016-09-26 19:22:50 +0000462 // This handles the assignments to symbol or to a location counter (.)
Rafael Espindolad3190792016-09-16 15:10:23 +0000463 if (auto *AssignCmd = dyn_cast<SymbolAssignment>(&Base)) {
Rafael Espindola4cd73522017-02-17 16:01:51 +0000464 assignSymbol(AssignCmd, true);
Eugene Leviantceabe802016-08-11 07:56:43 +0000465 return;
Rui Ueyama2de509c2016-08-12 00:55:08 +0000466 }
George Rimare38cbab2016-09-26 19:22:50 +0000467
468 // Handle BYTE(), SHORT(), LONG(), or QUAD().
469 if (auto *DataCmd = dyn_cast<BytesDataCommand>(&Base)) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000470 DataCmd->Offset = Dot - CurOutSec->Addr;
George Rimare38cbab2016-09-26 19:22:50 +0000471 Dot += DataCmd->Size;
Rafael Espindola04a2e342016-11-09 01:42:41 +0000472 CurOutSec->Size = Dot - CurOutSec->Addr;
George Rimare38cbab2016-09-26 19:22:50 +0000473 return;
474 }
475
Meador Ingeb2d99d62016-11-22 18:01:50 +0000476 if (auto *AssertCmd = dyn_cast<AssertCommand>(&Base)) {
Rafael Espindola4595df92017-03-10 16:04:26 +0000477 AssertCmd->Expression();
Meador Ingeb2d99d62016-11-22 18:01:50 +0000478 return;
479 }
480
George Rimare38cbab2016-09-26 19:22:50 +0000481 // It handles single input section description command,
482 // calculates and assigns the offsets for each section and also
483 // updates the output section size.
Rafael Espindolad3190792016-09-16 15:10:23 +0000484 auto &ICmd = cast<InputSectionDescription>(Base);
Rafael Espindolabd12e2a2017-03-01 14:12:21 +0000485 for (InputSectionBase *IB : ICmd.Sections) {
George Rimar3fb5a6d2016-11-29 16:05:27 +0000486 // We tentatively added all synthetic sections at the beginning and removed
487 // empty ones afterwards (because there is no way to know whether they were
488 // going be empty or not other than actually running linker scripts.)
489 // We need to ignore remains of empty sections.
Rafael Espindolabd12e2a2017-03-01 14:12:21 +0000490 if (auto *Sec = dyn_cast<SyntheticSection>(IB))
George Rimar3fb5a6d2016-11-29 16:05:27 +0000491 if (Sec->empty())
492 continue;
493
George Rimar78ef6452017-02-21 15:46:43 +0000494 if (!IB->Live)
495 continue;
Rafael Espindolabedccb5e2017-03-01 14:21:31 +0000496 assert(CurOutSec == IB->OutSec || AlreadyOutputOS.count(IB->OutSec));
Rafael Espindolabd12e2a2017-03-01 14:12:21 +0000497 output(cast<InputSection>(IB));
Eugene Leviantceabe802016-08-11 07:56:43 +0000498 }
499}
500
Rafael Espindola24e6f362017-02-24 15:07:30 +0000501static OutputSection *
502findSection(StringRef Name, const std::vector<OutputSection *> &Sections) {
Rafael Espindola2b074552017-02-03 22:27:05 +0000503 auto End = Sections.end();
Rafael Espindola24e6f362017-02-24 15:07:30 +0000504 auto HasName = [=](OutputSection *Sec) { return Sec->Name == Name; };
Rafael Espindola2b074552017-02-03 22:27:05 +0000505 auto I = std::find_if(Sections.begin(), End, HasName);
Rafael Espindola24e6f362017-02-24 15:07:30 +0000506 std::vector<OutputSection *> Ret;
Rafael Espindola2b074552017-02-03 22:27:05 +0000507 if (I == End)
508 return nullptr;
509 assert(std::find_if(I + 1, End, HasName) == End);
510 return *I;
George Rimar8f66df92016-08-12 20:38:20 +0000511}
512
Meador Ingeb8897442017-01-24 02:34:00 +0000513// This function searches for a memory region to place the given output
514// section in. If found, a pointer to the appropriate memory region is
515// returned. Otherwise, a nullptr is returned.
George Rimara2a1ef12017-03-14 12:03:34 +0000516MemoryRegion *LinkerScriptBase::findMemoryRegion(OutputSectionCommand *Cmd,
517 OutputSection *Sec) {
Meador Ingeb8897442017-01-24 02:34:00 +0000518 // If a memory region name was specified in the output section command,
519 // then try to find that region first.
520 if (!Cmd->MemoryRegionName.empty()) {
521 auto It = Opt.MemoryRegions.find(Cmd->MemoryRegionName);
522 if (It != Opt.MemoryRegions.end())
523 return &It->second;
524 error("memory region '" + Cmd->MemoryRegionName + "' not declared");
525 return nullptr;
526 }
527
528 // The memory region name is empty, thus a suitable region must be
529 // searched for in the region map. If the region map is empty, just
530 // return. Note that this check doesn't happen at the very beginning
531 // so that uses of undeclared regions can be caught.
532 if (!Opt.MemoryRegions.size())
533 return nullptr;
534
535 // See if a region can be found by matching section flags.
536 for (auto &MRI : Opt.MemoryRegions) {
537 MemoryRegion &MR = MRI.second;
Rui Ueyama8a8a9532017-01-26 02:58:59 +0000538 if ((MR.Flags & Sec->Flags) != 0 && (MR.NegFlags & Sec->Flags) == 0)
Meador Ingeb8897442017-01-24 02:34:00 +0000539 return &MR;
540 }
541
542 // Otherwise, no suitable region was found.
543 if (Sec->Flags & SHF_ALLOC)
544 error("no memory region specified for section '" + Sec->Name + "'");
545 return nullptr;
546}
547
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000548// This function assigns offsets to input sections and an output section
549// for a single sections command (e.g. ".text { *(.text); }").
George Rimara2a1ef12017-03-14 12:03:34 +0000550void LinkerScriptBase::assignOffsets(OutputSectionCommand *Cmd) {
George Rimar23e6a022017-03-14 11:31:28 +0000551 OutputSection *Sec = findSection(Cmd->Name, *OutputSections);
Rafael Espindola2b074552017-02-03 22:27:05 +0000552 if (!Sec)
Rafael Espindolad3190792016-09-16 15:10:23 +0000553 return;
Meador Ingeb8897442017-01-24 02:34:00 +0000554
Rafael Espindola679828f2017-02-17 16:26:13 +0000555 if (Cmd->AddrExpr && Sec->Flags & SHF_ALLOC)
George Rimar2ee2d2d2017-02-21 14:50:38 +0000556 setDot(Cmd->AddrExpr, Cmd->Location);
Rafael Espindola679828f2017-02-17 16:26:13 +0000557
Eugene Leviant5784e962017-03-14 08:57:09 +0000558 if (Cmd->LMAExpr) {
George Rimar0c1c8082017-03-14 10:00:19 +0000559 uint64_t D = Dot;
Eugene Leviant5784e962017-03-14 08:57:09 +0000560 LMAOffset = [=] { return Cmd->LMAExpr() - D; };
561 }
562
Petr Hosek165088a2017-02-07 23:42:31 +0000563 // Handle align (e.g. ".foo : ALIGN(16) { ... }").
564 if (Cmd->AlignExpr)
Rafael Espindola4595df92017-03-10 16:04:26 +0000565 Sec->updateAlignment(Cmd->AlignExpr());
Petr Hosek165088a2017-02-07 23:42:31 +0000566
Meador Ingeb8897442017-01-24 02:34:00 +0000567 // Try and find an appropriate memory region to assign offsets in.
568 CurMemRegion = findMemoryRegion(Cmd, Sec);
569 if (CurMemRegion)
570 Dot = CurMemRegion->Offset;
571 switchTo(Sec);
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000572
Rafael Espindolad3190792016-09-16 15:10:23 +0000573 // Find the last section output location. We will output orphan sections
574 // there so that end symbols point to the correct location.
575 auto E = std::find_if(Cmd->Commands.rbegin(), Cmd->Commands.rend(),
576 [](const std::unique_ptr<BaseCommand> &Cmd) {
577 return !isa<SymbolAssignment>(*Cmd);
578 })
579 .base();
580 for (auto I = Cmd->Commands.begin(); I != E; ++I)
581 process(**I);
Rafael Espindola65499b92016-09-23 20:10:47 +0000582 flush();
George Rimarb31dd372016-09-19 13:27:31 +0000583 std::for_each(E, Cmd->Commands.end(),
584 [this](std::unique_ptr<BaseCommand> &B) { process(*B.get()); });
Rafael Espindolad3190792016-09-16 15:10:23 +0000585}
586
George Rimara2a1ef12017-03-14 12:03:34 +0000587void LinkerScriptBase::removeEmptyCommands() {
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000588 // It is common practice to use very generic linker scripts. So for any
589 // given run some of the output sections in the script will be empty.
590 // We could create corresponding empty output sections, but that would
591 // clutter the output.
592 // We instead remove trivially empty sections. The bfd linker seems even
593 // more aggressive at removing them.
594 auto Pos = std::remove_if(
595 Opt.Commands.begin(), Opt.Commands.end(),
596 [&](const std::unique_ptr<BaseCommand> &Base) {
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000597 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
George Rimar23e6a022017-03-14 11:31:28 +0000598 return !findSection(Cmd->Name, *OutputSections);
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000599 return false;
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000600 });
601 Opt.Commands.erase(Pos, Opt.Commands.end());
Rafael Espindola07fe6122016-11-14 14:23:35 +0000602}
603
Rafael Espindola6a537372016-11-14 14:33:49 +0000604static bool isAllSectionDescription(const OutputSectionCommand &Cmd) {
605 for (const std::unique_ptr<BaseCommand> &I : Cmd.Commands)
606 if (!isa<InputSectionDescription>(*I))
607 return false;
608 return true;
609}
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000610
George Rimara2a1ef12017-03-14 12:03:34 +0000611void LinkerScriptBase::adjustSectionsBeforeSorting() {
Rafael Espindola9546fff2016-09-22 14:40:50 +0000612 // If the output section contains only symbol assignments, create a
613 // corresponding output section. The bfd linker seems to only create them if
614 // '.' is assigned to, but creating these section should not have any bad
615 // consequeces and gives us a section to put the symbol in.
George Rimar0c1c8082017-03-14 10:00:19 +0000616 uint64_t Flags = SHF_ALLOC;
Rafael Espindolaf93b8c22016-11-26 06:55:35 +0000617 uint32_t Type = SHT_NOBITS;
Rafael Espindola9546fff2016-09-22 14:40:50 +0000618 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
619 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
620 if (!Cmd)
621 continue;
George Rimar23e6a022017-03-14 11:31:28 +0000622 if (OutputSection *Sec = findSection(Cmd->Name, *OutputSections)) {
Rafael Espindola2b074552017-02-03 22:27:05 +0000623 Flags = Sec->Flags;
624 Type = Sec->Type;
Rafael Espindola9546fff2016-09-22 14:40:50 +0000625 continue;
626 }
627
Rafael Espindola6a537372016-11-14 14:33:49 +0000628 if (isAllSectionDescription(*Cmd))
629 continue;
630
Rafael Espindola24e6f362017-02-24 15:07:30 +0000631 auto *OutSec = make<OutputSection>(Cmd->Name, Type, Flags);
Rafael Espindola9546fff2016-09-22 14:40:50 +0000632 OutputSections->push_back(OutSec);
633 }
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000634}
635
George Rimara2a1ef12017-03-14 12:03:34 +0000636void LinkerScriptBase::adjustSectionsAfterSorting() {
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000637 placeOrphanSections();
638
639 // If output section command doesn't specify any segments,
640 // and we haven't previously assigned any section to segment,
641 // then we simply assign section to the very first load segment.
642 // Below is an example of such linker script:
643 // PHDRS { seg PT_LOAD; }
644 // SECTIONS { .aaa : { *(.aaa) } }
645 std::vector<StringRef> DefPhdrs;
646 auto FirstPtLoad =
647 std::find_if(Opt.PhdrsCommands.begin(), Opt.PhdrsCommands.end(),
648 [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; });
649 if (FirstPtLoad != Opt.PhdrsCommands.end())
650 DefPhdrs.push_back(FirstPtLoad->Name);
651
652 // Walk the commands and propagate the program headers to commands that don't
653 // explicitly specify them.
654 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
655 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
656 if (!Cmd)
657 continue;
658 if (Cmd->Phdrs.empty())
659 Cmd->Phdrs = DefPhdrs;
660 else
661 DefPhdrs = Cmd->Phdrs;
662 }
Rafael Espindola6a537372016-11-14 14:33:49 +0000663
664 removeEmptyCommands();
Rafael Espindola9546fff2016-09-22 14:40:50 +0000665}
666
Rafael Espindola15c57952016-09-22 18:05:49 +0000667// When placing orphan sections, we want to place them after symbol assignments
668// so that an orphan after
669// begin_foo = .;
670// foo : { *(foo) }
671// end_foo = .;
672// doesn't break the intended meaning of the begin/end symbols.
673// We don't want to go over sections since Writer<ELFT>::sortSections is the
674// one in charge of deciding the order of the sections.
675// We don't want to go over alignments, since doing so in
676// rx_sec : { *(rx_sec) }
677// . = ALIGN(0x1000);
678// /* The RW PT_LOAD starts here*/
679// rw_sec : { *(rw_sec) }
680// would mean that the RW PT_LOAD would become unaligned.
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000681static bool shouldSkip(const BaseCommand &Cmd) {
Rafael Espindola15c57952016-09-22 18:05:49 +0000682 if (isa<OutputSectionCommand>(Cmd))
683 return false;
684 const auto *Assign = dyn_cast<SymbolAssignment>(&Cmd);
685 if (!Assign)
686 return true;
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000687 return Assign->Name != ".";
Rafael Espindola15c57952016-09-22 18:05:49 +0000688}
689
Rui Ueyama6697ec22017-02-02 23:26:12 +0000690// Orphan sections are sections present in the input files which are
691// not explicitly placed into the output file by the linker script.
692//
693// When the control reaches this function, Opt.Commands contains
694// output section commands for non-orphan sections only. This function
695// adds new elements for orphan sections to Opt.Commands so that all
696// sections are explicitly handled by Opt.Commands.
697//
698// Writer<ELFT>::sortSections has already sorted output sections.
699// What we need to do is to scan OutputSections vector and
700// Opt.Commands in parallel to find orphan sections. If there is an
701// output section that doesn't have a corresponding entry in
702// Opt.Commands, we will insert a new entry to Opt.Commands.
703//
704// There is some ambiguity as to where exactly a new entry should be
705// inserted, because Opt.Commands contains not only output section
706// commands but other types of commands such as symbol assignment
707// expressions. There's no correct answer here due to the lack of the
708// formal specification of the linker script. We use heuristics to
709// determine whether a new output command should be added before or
710// after another commands. For the details, look at shouldSkip
711// function.
George Rimara2a1ef12017-03-14 12:03:34 +0000712void LinkerScriptBase::placeOrphanSections() {
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000713 // The OutputSections are already in the correct order.
714 // This loops creates or moves commands as needed so that they are in the
715 // correct order.
716 int CmdIndex = 0;
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000717
718 // As a horrible special case, skip the first . assignment if it is before any
719 // section. We do this because it is common to set a load address by starting
720 // the script with ". = 0xabcd" and the expectation is that every section is
721 // after that.
722 auto FirstSectionOrDotAssignment =
723 std::find_if(Opt.Commands.begin(), Opt.Commands.end(),
724 [](const std::unique_ptr<BaseCommand> &Cmd) {
725 if (isa<OutputSectionCommand>(*Cmd))
726 return true;
727 const auto *Assign = dyn_cast<SymbolAssignment>(Cmd.get());
728 if (!Assign)
729 return false;
730 return Assign->Name == ".";
731 });
732 if (FirstSectionOrDotAssignment != Opt.Commands.end()) {
733 CmdIndex = FirstSectionOrDotAssignment - Opt.Commands.begin();
734 if (isa<SymbolAssignment>(**FirstSectionOrDotAssignment))
735 ++CmdIndex;
736 }
737
Rafael Espindola24e6f362017-02-24 15:07:30 +0000738 for (OutputSection *Sec : *OutputSections) {
Rafael Espindola40849412017-02-24 14:28:00 +0000739 StringRef Name = Sec->Name;
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000740
741 // Find the last spot where we can insert a command and still get the
Rafael Espindola15c57952016-09-22 18:05:49 +0000742 // correct result.
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000743 auto CmdIter = Opt.Commands.begin() + CmdIndex;
744 auto E = Opt.Commands.end();
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000745 while (CmdIter != E && shouldSkip(**CmdIter)) {
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000746 ++CmdIter;
747 ++CmdIndex;
748 }
749
750 auto Pos =
751 std::find_if(CmdIter, E, [&](const std::unique_ptr<BaseCommand> &Base) {
752 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
753 return Cmd && Cmd->Name == Name;
754 });
755 if (Pos == E) {
756 Opt.Commands.insert(CmdIter,
757 llvm::make_unique<OutputSectionCommand>(Name));
Rafael Espindola15c57952016-09-22 18:05:49 +0000758 ++CmdIndex;
759 continue;
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000760 }
Rafael Espindola15c57952016-09-22 18:05:49 +0000761
762 // Continue from where we found it.
763 CmdIndex = (Pos - Opt.Commands.begin()) + 1;
George Rimar652852c2016-04-16 10:10:32 +0000764 }
Rafael Espindola337f9032016-11-14 14:13:32 +0000765}
766
Petr Hosek02ad5162017-03-15 03:33:23 +0000767void LinkerScriptBase::processNonSectionCommands() {
768 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
769 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get()))
770 assignSymbol(Cmd);
771 else if (auto *Cmd = dyn_cast<AssertCommand>(Base.get()))
772 Cmd->Expression();
773 }
774}
775
George Rimara2a1ef12017-03-14 12:03:34 +0000776void LinkerScriptBase::assignAddresses(std::vector<PhdrEntry> &Phdrs) {
Rui Ueyama7c18c282016-04-18 21:00:40 +0000777 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rafael Espindolabe607332016-09-30 00:16:11 +0000778 Dot = 0;
Rafael Espindola06f47432017-02-06 22:21:46 +0000779 switchTo(Aether);
780
George Rimar076fe152016-07-21 06:43:01 +0000781 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
782 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
Rafael Espindola4cd73522017-02-17 16:01:51 +0000783 assignSymbol(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000784 continue;
785 }
786
George Rimareefa7582016-08-04 09:29:31 +0000787 if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
Rafael Espindola4595df92017-03-10 16:04:26 +0000788 Cmd->Expression();
George Rimareefa7582016-08-04 09:29:31 +0000789 continue;
790 }
791
George Rimar076fe152016-07-21 06:43:01 +0000792 auto *Cmd = cast<OutputSectionCommand>(Base.get());
Rafael Espindolad3190792016-09-16 15:10:23 +0000793 assignOffsets(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000794 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000795
George Rimar0c1c8082017-03-14 10:00:19 +0000796 uint64_t MinVA = std::numeric_limits<uint64_t>::max();
Rafael Espindola24e6f362017-02-24 15:07:30 +0000797 for (OutputSection *Sec : *OutputSections) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000798 if (Sec->Flags & SHF_ALLOC)
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000799 MinVA = std::min<uint64_t>(MinVA, Sec->Addr);
Rafael Espindolaea590d92017-02-08 15:19:03 +0000800 else
801 Sec->Addr = 0;
802 }
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000803
George Rimar2d262102017-03-14 09:03:53 +0000804 allocateHeaders(Phdrs, *OutputSections, MinVA);
George Rimar652852c2016-04-16 10:10:32 +0000805}
806
Rui Ueyama464daad2016-08-22 04:55:20 +0000807// Creates program headers as instructed by PHDRS linker script command.
George Rimara2a1ef12017-03-14 12:03:34 +0000808std::vector<PhdrEntry> LinkerScriptBase::createPhdrs() {
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000809 std::vector<PhdrEntry> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000810
Rui Ueyama464daad2016-08-22 04:55:20 +0000811 // Process PHDRS and FILEHDR keywords because they are not
812 // real output sections and cannot be added in the following loop.
Eugene Leviantbbe38602016-07-19 09:25:43 +0000813 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000814 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000815 PhdrEntry &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000816
817 if (Cmd.HasFilehdr)
Rui Ueyama9d1bacb12017-02-27 02:31:26 +0000818 Phdr.add(Out::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000819 if (Cmd.HasPhdrs)
Rui Ueyama9d1bacb12017-02-27 02:31:26 +0000820 Phdr.add(Out::ProgramHeaders);
Eugene Leviant56b21c82016-09-09 09:46:16 +0000821
822 if (Cmd.LMAExpr) {
Rafael Espindola4595df92017-03-10 16:04:26 +0000823 Phdr.p_paddr = Cmd.LMAExpr();
Eugene Leviant56b21c82016-09-09 09:46:16 +0000824 Phdr.HasLMA = true;
825 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000826 }
827
Rui Ueyama464daad2016-08-22 04:55:20 +0000828 // Add output sections to program headers.
Rafael Espindola24e6f362017-02-24 15:07:30 +0000829 for (OutputSection *Sec : *OutputSections) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000830 if (!(Sec->Flags & SHF_ALLOC))
Eugene Leviantbbe38602016-07-19 09:25:43 +0000831 break;
832
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000833 // Assign headers specified by linker script
Rafael Espindola40849412017-02-24 14:28:00 +0000834 for (size_t Id : getPhdrIndices(Sec->Name)) {
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000835 Ret[Id].add(Sec);
836 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000837 Ret[Id].p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000838 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000839 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000840 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000841}
842
George Rimara2a1ef12017-03-14 12:03:34 +0000843bool LinkerScriptBase::ignoreInterpSection() {
Eugene Leviantf9bc3bd2016-08-16 06:40:58 +0000844 // Ignore .interp section in case we have PHDRS specification
845 // and PT_INTERP isn't listed.
846 return !Opt.PhdrsCommands.empty() &&
847 llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
848 return Cmd.Type == PT_INTERP;
849 }) == Opt.PhdrsCommands.end();
850}
851
George Rimara2a1ef12017-03-14 12:03:34 +0000852uint32_t LinkerScriptBase::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000853 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
854 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
855 if (Cmd->Name == Name)
856 return Cmd->Filler;
Rui Ueyama16068ae2016-11-19 18:05:56 +0000857 return 0;
George Rimare2ee72b2016-02-26 14:48:31 +0000858}
859
George Rimare38cbab2016-09-26 19:22:50 +0000860template <class ELFT>
861static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) {
862 const endianness E = ELFT::TargetEndianness;
863
864 switch (Size) {
865 case 1:
866 *Buf = (uint8_t)Data;
867 break;
868 case 2:
869 write16<E>(Buf, Data);
870 break;
871 case 4:
872 write32<E>(Buf, Data);
873 break;
874 case 8:
875 write64<E>(Buf, Data);
876 break;
877 default:
878 llvm_unreachable("unsupported Size argument");
879 }
880}
881
882template <class ELFT>
883void LinkerScript<ELFT>::writeDataBytes(StringRef Name, uint8_t *Buf) {
884 int I = getSectionIndex(Name);
885 if (I == INT_MAX)
886 return;
887
Rui Ueyama6e68c5e2016-11-19 18:05:58 +0000888 auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I].get());
889 for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
890 if (auto *Data = dyn_cast<BytesDataCommand>(Base.get()))
Rafael Espindola4595df92017-03-10 16:04:26 +0000891 writeInt<ELFT>(Buf + Data->Offset, Data->Expression(), Data->Size);
George Rimare38cbab2016-09-26 19:22:50 +0000892}
893
George Rimara2a1ef12017-03-14 12:03:34 +0000894bool LinkerScriptBase::hasLMA(StringRef Name) {
George Rimar8ceadb32016-08-17 07:44:19 +0000895 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
896 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000897 if (Cmd->LMAExpr && Cmd->Name == Name)
898 return true;
899 return false;
George Rimar8ceadb32016-08-17 07:44:19 +0000900}
901
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000902// Returns the index of the given section name in linker script
903// SECTIONS commands. Sections are laid out as the same order as they
904// were in the script. If a given name did not appear in the script,
905// it returns INT_MAX, so that it will be laid out at end of file.
George Rimara2a1ef12017-03-14 12:03:34 +0000906int LinkerScriptBase::getSectionIndex(StringRef Name) {
Rui Ueyama6e68c5e2016-11-19 18:05:58 +0000907 for (int I = 0, E = Opt.Commands.size(); I != E; ++I)
908 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I].get()))
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000909 if (Cmd->Name == Name)
910 return I;
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000911 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000912}
913
Eugene Leviantf6aeed32016-12-22 13:13:12 +0000914template <class ELFT>
915uint64_t LinkerScript<ELFT>::getSymbolValue(const Twine &Loc, StringRef S) {
Rafael Espindola4595df92017-03-10 16:04:26 +0000916 if (S == ".")
917 return Dot;
George Rimar884e7862016-09-08 08:19:13 +0000918 if (SymbolBody *B = Symtab<ELFT>::X->find(S))
919 return B->getVA<ELFT>();
Eugene Leviantf6aeed32016-12-22 13:13:12 +0000920 error(Loc + ": symbol not found: " + S);
George Rimar884e7862016-09-08 08:19:13 +0000921 return 0;
922}
923
George Rimarf34f45f2016-09-23 13:17:23 +0000924template <class ELFT> bool LinkerScript<ELFT>::isDefined(StringRef S) {
925 return Symtab<ELFT>::X->find(S) != nullptr;
926}
927
Rafael Espindola2f831dc2016-10-31 19:56:37 +0000928template <class ELFT> bool LinkerScript<ELFT>::isAbsolute(StringRef S) {
Rafael Espindola4595df92017-03-10 16:04:26 +0000929 if (S == ".")
930 return false;
Rafael Espindola2f831dc2016-10-31 19:56:37 +0000931 SymbolBody *Sym = Symtab<ELFT>::X->find(S);
Rui Ueyama80474a22017-02-28 19:29:55 +0000932 auto *DR = dyn_cast_or_null<DefinedRegular>(Sym);
Rafael Espindola2f831dc2016-10-31 19:56:37 +0000933 return DR && !DR->Section;
934}
935
Eugene Leviantafaa9342016-11-16 09:49:39 +0000936// Gets section symbol belongs to. Symbol "." doesn't belong to any
937// specific section but isn't absolute at the same time, so we try
938// to find suitable section for it as well.
939template <class ELFT>
Rafael Espindola5616adf2017-03-08 22:36:28 +0000940OutputSection *LinkerScript<ELFT>::getSymbolSection(StringRef S) {
Rafael Espindola06f47432017-02-06 22:21:46 +0000941 if (SymbolBody *Sym = Symtab<ELFT>::X->find(S))
Rui Ueyama968db482017-02-28 04:02:42 +0000942 return Sym->getOutputSection<ELFT>();
Rafael Espindola06f47432017-02-06 22:21:46 +0000943 return CurOutSec;
Eugene Leviantafaa9342016-11-16 09:49:39 +0000944}
945
Eugene Leviantbbe38602016-07-19 09:25:43 +0000946// Returns indices of ELF headers containing specific section, identified
947// by Name. Each index is a zero based number of ELF header listed within
948// PHDRS {} script block.
George Rimara2a1ef12017-03-14 12:03:34 +0000949std::vector<size_t> LinkerScriptBase::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000950 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
951 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000952 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000953 continue;
954
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000955 std::vector<size_t> Ret;
956 for (StringRef PhdrName : Cmd->Phdrs)
Eugene Leviant2a942c42016-12-05 16:38:32 +0000957 Ret.push_back(getPhdrIndex(Cmd->Location, PhdrName));
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000958 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000959 }
George Rimar31d842f2016-07-20 16:43:03 +0000960 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000961}
962
George Rimara2a1ef12017-03-14 12:03:34 +0000963size_t LinkerScriptBase::getPhdrIndex(const Twine &Loc, StringRef PhdrName) {
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000964 size_t I = 0;
965 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
966 if (Cmd.Name == PhdrName)
967 return I;
968 ++I;
969 }
Eugene Leviant2a942c42016-12-05 16:38:32 +0000970 error(Loc + ": section header '" + PhdrName + "' is not listed in PHDRS");
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000971 return 0;
972}
973
Rui Ueyama794366a2017-02-14 04:47:05 +0000974class elf::ScriptParser final : public ScriptLexer {
George Rimarc3794e52016-02-24 09:21:47 +0000975 typedef void (ScriptParser::*Handler)();
976
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000977public:
Rui Ueyama22375f22016-11-25 18:51:54 +0000978 ScriptParser(MemoryBufferRef MB)
Rui Ueyama794366a2017-02-14 04:47:05 +0000979 : ScriptLexer(MB),
Rui Ueyama22375f22016-11-25 18:51:54 +0000980 IsUnderSysroot(isUnderSysroot(MB.getBufferIdentifier())) {}
George Rimarf23b2322016-02-19 10:45:45 +0000981
George Rimar20b65982016-08-31 09:08:26 +0000982 void readLinkerScript();
983 void readVersionScript();
Rafael Espindolad0ebd842016-12-08 17:54:26 +0000984 void readDynamicList();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000985
986private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000987 void addFile(StringRef Path);
988
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000989 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000990 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000991 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000992 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000993 void readInclude();
Meador Ingeb8897442017-01-24 02:34:00 +0000994 void readMemory();
Rui Ueyamaee592822015-10-07 00:25:09 +0000995 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000996 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000997 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000998 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000999 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001000 void readSections();
Rui Ueyama95769b42016-08-31 20:03:54 +00001001 void readVersion();
1002 void readVersionScriptCommand();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001003
Rui Ueyama113cdec2016-07-24 23:05:57 +00001004 SymbolAssignment *readAssignment(StringRef Name);
George Rimare38cbab2016-09-26 19:22:50 +00001005 BytesDataCommand *readBytesDataCommand(StringRef Tok);
Rui Ueyama16068ae2016-11-19 18:05:56 +00001006 uint32_t readFill();
Rui Ueyama10416562016-08-04 02:03:27 +00001007 OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
Rui Ueyama16068ae2016-11-19 18:05:56 +00001008 uint32_t readOutputSectionFiller(StringRef Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001009 std::vector<StringRef> readOutputSectionPhdrs();
George Rimara2496cb2016-08-30 09:46:59 +00001010 InputSectionDescription *readInputSectionDescription(StringRef Tok);
Eugene Leviantdb688452016-11-03 10:54:58 +00001011 StringMatcher readFilePatterns();
George Rimar07171f22016-09-21 15:56:44 +00001012 std::vector<SectionPattern> readInputSectionsList();
George Rimara2496cb2016-08-30 09:46:59 +00001013 InputSectionDescription *readInputSectionRules(StringRef FilePattern);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001014 unsigned readPhdrType();
George Rimarbe394db2016-09-16 20:21:55 +00001015 SortSectionPolicy readSortKind();
Petr Hoseka35e39c2016-08-16 01:11:16 +00001016 SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
Rafael Espindolac96da112016-11-01 11:30:45 +00001017 SymbolAssignment *readProvideOrAssignment(StringRef Tok);
George Rimar03fc0102016-07-28 07:18:23 +00001018 void readSort();
George Rimareefa7582016-08-04 09:29:31 +00001019 Expr readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001020
Rui Ueyama24e626c2017-01-26 02:58:19 +00001021 uint64_t readMemoryAssignment(StringRef, StringRef, StringRef);
1022 std::pair<uint32_t, uint32_t> readMemoryAttributes();
1023
Rui Ueyama708019c2016-07-24 18:19:40 +00001024 Expr readExpr();
1025 Expr readExpr1(Expr Lhs, int MinPrec);
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001026 StringRef readParenLiteral();
Rui Ueyama708019c2016-07-24 18:19:40 +00001027 Expr readPrimary();
1028 Expr readTernary(Expr Cond);
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001029 Expr readParenExpr();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001030
George Rimar20b65982016-08-31 09:08:26 +00001031 // For parsing version script.
Rui Ueyama12450b22016-11-18 06:30:09 +00001032 std::vector<SymbolVersion> readVersionExtern();
1033 void readAnonymousDeclaration();
Rui Ueyama95769b42016-08-31 20:03:54 +00001034 void readVersionDeclaration(StringRef VerStr);
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001035
1036 std::pair<std::vector<SymbolVersion>, std::vector<SymbolVersion>>
1037 readSymbols();
George Rimar20b65982016-08-31 09:08:26 +00001038
Rui Ueyama07320e42016-04-20 20:13:41 +00001039 ScriptConfiguration &Opt = *ScriptConfig;
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001040 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001041};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001042
Rafael Espindolad0ebd842016-12-08 17:54:26 +00001043void ScriptParser::readDynamicList() {
1044 expect("{");
1045 readAnonymousDeclaration();
1046 if (!atEOF())
1047 setError("EOF expected, but got " + next());
1048}
1049
George Rimar20b65982016-08-31 09:08:26 +00001050void ScriptParser::readVersionScript() {
Rui Ueyama95769b42016-08-31 20:03:54 +00001051 readVersionScriptCommand();
1052 if (!atEOF())
1053 setError("EOF expected, but got " + next());
1054}
1055
1056void ScriptParser::readVersionScriptCommand() {
Rui Ueyama83043f22016-10-17 16:01:53 +00001057 if (consume("{")) {
Rui Ueyama12450b22016-11-18 06:30:09 +00001058 readAnonymousDeclaration();
George Rimar20b65982016-08-31 09:08:26 +00001059 return;
1060 }
1061
Rui Ueyama95769b42016-08-31 20:03:54 +00001062 while (!atEOF() && !Error && peek() != "}") {
George Rimar20b65982016-08-31 09:08:26 +00001063 StringRef VerStr = next();
1064 if (VerStr == "{") {
Rui Ueyama95769b42016-08-31 20:03:54 +00001065 setError("anonymous version definition is used in "
1066 "combination with other version definitions");
George Rimar20b65982016-08-31 09:08:26 +00001067 return;
1068 }
1069 expect("{");
Rui Ueyama95769b42016-08-31 20:03:54 +00001070 readVersionDeclaration(VerStr);
George Rimar20b65982016-08-31 09:08:26 +00001071 }
1072}
1073
Rui Ueyama95769b42016-08-31 20:03:54 +00001074void ScriptParser::readVersion() {
1075 expect("{");
1076 readVersionScriptCommand();
1077 expect("}");
1078}
1079
George Rimar20b65982016-08-31 09:08:26 +00001080void ScriptParser::readLinkerScript() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001081 while (!atEOF()) {
1082 StringRef Tok = next();
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001083 if (Tok == ";")
1084 continue;
1085
Eugene Leviant20d03192016-09-16 15:30:47 +00001086 if (Tok == "ASSERT") {
1087 Opt.Commands.emplace_back(new AssertCommand(readAssert()));
1088 } else if (Tok == "ENTRY") {
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001089 readEntry();
1090 } else if (Tok == "EXTERN") {
1091 readExtern();
1092 } else if (Tok == "GROUP" || Tok == "INPUT") {
1093 readGroup();
1094 } else if (Tok == "INCLUDE") {
1095 readInclude();
Meador Ingeb8897442017-01-24 02:34:00 +00001096 } else if (Tok == "MEMORY") {
1097 readMemory();
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001098 } else if (Tok == "OUTPUT") {
1099 readOutput();
1100 } else if (Tok == "OUTPUT_ARCH") {
1101 readOutputArch();
1102 } else if (Tok == "OUTPUT_FORMAT") {
1103 readOutputFormat();
1104 } else if (Tok == "PHDRS") {
1105 readPhdrs();
1106 } else if (Tok == "SEARCH_DIR") {
1107 readSearchDir();
1108 } else if (Tok == "SECTIONS") {
1109 readSections();
1110 } else if (Tok == "VERSION") {
1111 readVersion();
Rafael Espindolac96da112016-11-01 11:30:45 +00001112 } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok)) {
Eugene Leviant20d03192016-09-16 15:30:47 +00001113 Opt.Commands.emplace_back(Cmd);
Petr Hoseke5d3ca52016-08-31 15:31:17 +00001114 } else {
George Rimar57610422016-03-11 14:43:02 +00001115 setError("unknown directive: " + Tok);
Petr Hoseke5d3ca52016-08-31 15:31:17 +00001116 }
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001117 }
1118}
1119
Rui Ueyama717677a2016-02-11 21:17:59 +00001120void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001121 if (IsUnderSysroot && S.startswith("/")) {
Justin Bogner5af16872016-10-17 06:08:48 +00001122 SmallString<128> PathData;
1123 StringRef Path = (Config->Sysroot + S).toStringRef(PathData);
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001124 if (sys::fs::exists(Path)) {
Justin Bogner5af16872016-10-17 06:08:48 +00001125 Driver->addFile(Saver.save(Path));
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001126 return;
1127 }
1128 }
1129
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +00001130 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +00001131 Driver->addFile(S);
1132 } else if (S.startswith("=")) {
1133 if (Config->Sysroot.empty())
1134 Driver->addFile(S.substr(1));
1135 else
1136 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
1137 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +00001138 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +00001139 } else if (sys::fs::exists(S)) {
1140 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +00001141 } else {
Rui Ueyama061f9282016-11-19 19:23:58 +00001142 if (Optional<std::string> Path = findFromSearchPaths(S))
1143 Driver->addFile(Saver.save(*Path));
Rui Ueyama025d59b2016-02-02 20:27:59 +00001144 else
Rui Ueyama061f9282016-11-19 19:23:58 +00001145 setError("unable to find " + S);
Rui Ueyama52a15092015-10-11 03:28:42 +00001146 }
1147}
1148
Rui Ueyama717677a2016-02-11 21:17:59 +00001149void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001150 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +00001151 bool Orig = Config->AsNeeded;
1152 Config->AsNeeded = true;
Rui Ueyama83043f22016-10-17 16:01:53 +00001153 while (!Error && !consume(")"))
George Rimarcd574a52016-09-09 14:35:36 +00001154 addFile(unquote(next()));
Rui Ueyama35da9b62015-10-11 20:59:12 +00001155 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001156}
1157
Rui Ueyama717677a2016-02-11 21:17:59 +00001158void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +00001159 // -e <symbol> takes predecence over ENTRY(<symbol>).
1160 expect("(");
1161 StringRef Tok = next();
1162 if (Config->Entry.empty())
1163 Config->Entry = Tok;
1164 expect(")");
1165}
1166
Rui Ueyama717677a2016-02-11 21:17:59 +00001167void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +00001168 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001169 while (!Error && !consume(")"))
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001170 Config->Undefined.push_back(next());
George Rimar83f406c2015-10-19 17:35:12 +00001171}
1172
Rui Ueyama717677a2016-02-11 21:17:59 +00001173void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001174 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001175 while (!Error && !consume(")")) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001176 StringRef Tok = next();
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001177 if (Tok == "AS_NEEDED")
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001178 readAsNeeded();
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001179 else
George Rimarcd574a52016-09-09 14:35:36 +00001180 addFile(unquote(Tok));
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001181 }
1182}
1183
Rui Ueyama717677a2016-02-11 21:17:59 +00001184void ScriptParser::readInclude() {
George Rimard4500652016-12-21 09:42:25 +00001185 StringRef Tok = unquote(next());
Rui Ueyamaec1c75e2017-01-09 01:42:02 +00001186
George Rimard4500652016-12-21 09:42:25 +00001187 // https://sourceware.org/binutils/docs/ld/File-Commands.html:
1188 // The file will be searched for in the current directory, and in any
1189 // directory specified with the -L option.
Rui Ueyamaec1c75e2017-01-09 01:42:02 +00001190 if (sys::fs::exists(Tok)) {
1191 if (Optional<MemoryBufferRef> MB = readFile(Tok))
1192 tokenize(*MB);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001193 return;
1194 }
Rui Ueyamaec1c75e2017-01-09 01:42:02 +00001195 if (Optional<std::string> Path = findFromSearchPaths(Tok)) {
1196 if (Optional<MemoryBufferRef> MB = readFile(*Path))
1197 tokenize(*MB);
1198 return;
1199 }
1200 setError("cannot open " + Tok);
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001201}
1202
Rui Ueyama717677a2016-02-11 21:17:59 +00001203void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +00001204 // -o <file> takes predecence over OUTPUT(<file>).
1205 expect("(");
1206 StringRef Tok = next();
1207 if (Config->OutputFile.empty())
George Rimarcd574a52016-09-09 14:35:36 +00001208 Config->OutputFile = unquote(Tok);
Rui Ueyamaee592822015-10-07 00:25:09 +00001209 expect(")");
1210}
1211
Rui Ueyama717677a2016-02-11 21:17:59 +00001212void ScriptParser::readOutputArch() {
George Rimar4e01c3e2017-02-08 09:59:06 +00001213 // OUTPUT_ARCH is ignored for now.
Davide Italiano9159ce92015-10-12 21:50:08 +00001214 expect("(");
George Rimar4e01c3e2017-02-08 09:59:06 +00001215 while (!Error && !consume(")"))
1216 skip();
Davide Italiano9159ce92015-10-12 21:50:08 +00001217}
1218
Rui Ueyama717677a2016-02-11 21:17:59 +00001219void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001220 // Error checking only for now.
1221 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001222 skip();
Davide Italiano6836c612015-10-12 21:08:41 +00001223 StringRef Tok = next();
1224 if (Tok == ")")
George Rimar6c55f0e2016-09-08 08:20:30 +00001225 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +00001226 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +00001227 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001228 return;
1229 }
Justin Bogner5424e7c2016-10-17 06:21:13 +00001230 skip();
Davide Italiano6836c612015-10-12 21:08:41 +00001231 expect(",");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001232 skip();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001233 expect(")");
1234}
1235
Eugene Leviantbbe38602016-07-19 09:25:43 +00001236void ScriptParser::readPhdrs() {
1237 expect("{");
Rui Ueyama83043f22016-10-17 16:01:53 +00001238 while (!Error && !consume("}")) {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001239 StringRef Tok = next();
Eugene Leviant56b21c82016-09-09 09:46:16 +00001240 Opt.PhdrsCommands.push_back(
1241 {Tok, PT_NULL, false, false, UINT_MAX, nullptr});
Eugene Leviantbbe38602016-07-19 09:25:43 +00001242 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
1243
1244 PhdrCmd.Type = readPhdrType();
1245 do {
1246 Tok = next();
1247 if (Tok == ";")
1248 break;
1249 if (Tok == "FILEHDR")
1250 PhdrCmd.HasFilehdr = true;
1251 else if (Tok == "PHDRS")
1252 PhdrCmd.HasPhdrs = true;
Eugene Leviant56b21c82016-09-09 09:46:16 +00001253 else if (Tok == "AT")
1254 PhdrCmd.LMAExpr = readParenExpr();
Eugene Leviant865bf862016-07-21 10:43:25 +00001255 else if (Tok == "FLAGS") {
1256 expect("(");
Rafael Espindolaeb685cd2016-08-02 22:14:57 +00001257 // Passing 0 for the value of dot is a bit of a hack. It means that
1258 // we accept expressions like ".|1".
Rafael Espindola4595df92017-03-10 16:04:26 +00001259 PhdrCmd.Flags = readExpr()();
Eugene Leviant865bf862016-07-21 10:43:25 +00001260 expect(")");
1261 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +00001262 setError("unexpected header attribute: " + Tok);
1263 } while (!Error);
1264 }
1265}
1266
Rui Ueyama717677a2016-02-11 21:17:59 +00001267void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +00001268 expect("(");
Rui Ueyama86c5fb82016-09-08 23:26:54 +00001269 StringRef Tok = next();
Rui Ueyama6c7ad132016-09-02 19:20:33 +00001270 if (!Config->Nostdlib)
George Rimarcd574a52016-09-09 14:35:36 +00001271 Config->SearchPaths.push_back(unquote(Tok));
Davide Italiano68a39a62015-10-08 17:51:41 +00001272 expect(")");
1273}
1274
Rui Ueyama717677a2016-02-11 21:17:59 +00001275void ScriptParser::readSections() {
Eugene Leviante05336ff2016-09-14 08:32:36 +00001276 Opt.HasSections = true;
George Rimar18a30962016-11-28 10:11:10 +00001277 // -no-rosegment is used to avoid placing read only non-executable sections in
1278 // their own segment. We do the same if SECTIONS command is present in linker
1279 // script. See comment for computeFlags().
1280 Config->SingleRoRx = true;
1281
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001282 expect("{");
Rui Ueyama83043f22016-10-17 16:01:53 +00001283 while (!Error && !consume("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +00001284 StringRef Tok = next();
Rafael Espindolac96da112016-11-01 11:30:45 +00001285 BaseCommand *Cmd = readProvideOrAssignment(Tok);
Eugene Leviantceabe802016-08-11 07:56:43 +00001286 if (!Cmd) {
1287 if (Tok == "ASSERT")
1288 Cmd = new AssertCommand(readAssert());
1289 else
1290 Cmd = readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +00001291 }
Rui Ueyama10416562016-08-04 02:03:27 +00001292 Opt.Commands.emplace_back(Cmd);
George Rimar652852c2016-04-16 10:10:32 +00001293 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001294}
1295
Rui Ueyama708019c2016-07-24 18:19:40 +00001296static int precedence(StringRef Op) {
1297 return StringSwitch<int>(Op)
Rui Ueyama0120e3f2016-09-23 18:06:51 +00001298 .Cases("*", "/", 5)
1299 .Cases("+", "-", 4)
1300 .Cases("<<", ">>", 3)
Rui Ueyama9c4ac5f2016-09-23 22:22:34 +00001301 .Cases("<", "<=", ">", ">=", "==", "!=", 2)
Rui Ueyama0120e3f2016-09-23 18:06:51 +00001302 .Cases("&", "|", 1)
Rui Ueyama708019c2016-07-24 18:19:40 +00001303 .Default(-1);
1304}
1305
Eugene Leviantdb688452016-11-03 10:54:58 +00001306StringMatcher ScriptParser::readFilePatterns() {
Rui Ueyama10416562016-08-04 02:03:27 +00001307 std::vector<StringRef> V;
Rui Ueyama83043f22016-10-17 16:01:53 +00001308 while (!Error && !consume(")"))
Rui Ueyama10416562016-08-04 02:03:27 +00001309 V.push_back(next());
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001310 return StringMatcher(V);
George Rimar0702c4e2016-07-29 15:32:46 +00001311}
1312
George Rimarbe394db2016-09-16 20:21:55 +00001313SortSectionPolicy ScriptParser::readSortKind() {
Rui Ueyama83043f22016-10-17 16:01:53 +00001314 if (consume("SORT") || consume("SORT_BY_NAME"))
George Rimarbe394db2016-09-16 20:21:55 +00001315 return SortSectionPolicy::Name;
Rui Ueyama83043f22016-10-17 16:01:53 +00001316 if (consume("SORT_BY_ALIGNMENT"))
George Rimarbe394db2016-09-16 20:21:55 +00001317 return SortSectionPolicy::Alignment;
Rui Ueyama83043f22016-10-17 16:01:53 +00001318 if (consume("SORT_BY_INIT_PRIORITY"))
George Rimarbe394db2016-09-16 20:21:55 +00001319 return SortSectionPolicy::Priority;
Rui Ueyama83043f22016-10-17 16:01:53 +00001320 if (consume("SORT_NONE"))
Rui Ueyamab2a0abd2016-09-16 21:14:55 +00001321 return SortSectionPolicy::None;
1322 return SortSectionPolicy::Default;
George Rimarbe394db2016-09-16 20:21:55 +00001323}
1324
George Rimar395281c2016-09-16 17:42:10 +00001325// Method reads a list of sequence of excluded files and section globs given in
1326// a following form: ((EXCLUDE_FILE(file_pattern+))? section_pattern+)+
1327// Example: *(.foo.1 EXCLUDE_FILE (*a.o) .foo.2 EXCLUDE_FILE (*b.o) .foo.3)
George Rimaraf03be12016-09-17 19:17:25 +00001328// The semantics of that is next:
1329// * Include .foo.1 from every file.
1330// * Include .foo.2 from every file but a.o
1331// * Include .foo.3 from every file but b.o
George Rimar07171f22016-09-21 15:56:44 +00001332std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
1333 std::vector<SectionPattern> Ret;
George Rimar601e9892016-09-21 08:53:21 +00001334 while (!Error && peek() != ")") {
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001335 StringMatcher ExcludeFilePat;
Rui Ueyama83043f22016-10-17 16:01:53 +00001336 if (consume("EXCLUDE_FILE")) {
George Rimar395281c2016-09-16 17:42:10 +00001337 expect("(");
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001338 ExcludeFilePat = readFilePatterns();
George Rimar395281c2016-09-16 17:42:10 +00001339 }
1340
George Rimar601e9892016-09-21 08:53:21 +00001341 std::vector<StringRef> V;
1342 while (!Error && peek() != ")" && peek() != "EXCLUDE_FILE")
1343 V.push_back(next());
1344
1345 if (!V.empty())
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001346 Ret.push_back({std::move(ExcludeFilePat), StringMatcher(V)});
George Rimar601e9892016-09-21 08:53:21 +00001347 else
1348 setError("section pattern is expected");
George Rimar395281c2016-09-16 17:42:10 +00001349 }
George Rimar07171f22016-09-21 15:56:44 +00001350 return Ret;
George Rimar395281c2016-09-16 17:42:10 +00001351}
1352
Rui Ueyamaf8f6f1e2016-11-18 07:03:56 +00001353// Reads contents of "SECTIONS" directive. That directive contains a
1354// list of glob patterns for input sections. The grammar is as follows.
1355//
1356// <patterns> ::= <section-list>
1357// | <sort> "(" <section-list> ")"
1358// | <sort> "(" <sort> "(" <section-list> ")" ")"
1359//
1360// <sort> ::= "SORT" | "SORT_BY_NAME" | "SORT_BY_ALIGNMENT"
1361// | "SORT_BY_INIT_PRIORITY" | "SORT_NONE"
1362//
1363// <section-list> is parsed by readInputSectionsList().
George Rimara2496cb2016-08-30 09:46:59 +00001364InputSectionDescription *
1365ScriptParser::readInputSectionRules(StringRef FilePattern) {
George Rimarc91930a2016-09-02 21:17:20 +00001366 auto *Cmd = new InputSectionDescription(FilePattern);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001367 expect("(");
Rui Ueyamaf373dd72016-11-24 01:43:21 +00001368 while (!Error && !consume(")")) {
George Rimar07171f22016-09-21 15:56:44 +00001369 SortSectionPolicy Outer = readSortKind();
1370 SortSectionPolicy Inner = SortSectionPolicy::Default;
1371 std::vector<SectionPattern> V;
1372 if (Outer != SortSectionPolicy::Default) {
George Rimar350ece42016-08-03 08:35:59 +00001373 expect("(");
George Rimar07171f22016-09-21 15:56:44 +00001374 Inner = readSortKind();
1375 if (Inner != SortSectionPolicy::Default) {
1376 expect("(");
1377 V = readInputSectionsList();
1378 expect(")");
1379 } else {
1380 V = readInputSectionsList();
1381 }
George Rimar350ece42016-08-03 08:35:59 +00001382 expect(")");
1383 } else {
George Rimar07171f22016-09-21 15:56:44 +00001384 V = readInputSectionsList();
George Rimar350ece42016-08-03 08:35:59 +00001385 }
George Rimar0702c4e2016-07-29 15:32:46 +00001386
George Rimar07171f22016-09-21 15:56:44 +00001387 for (SectionPattern &Pat : V) {
1388 Pat.SortInner = Inner;
1389 Pat.SortOuter = Outer;
1390 }
1391
1392 std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns));
1393 }
Rui Ueyama10416562016-08-04 02:03:27 +00001394 return Cmd;
Davide Italianoe7282792016-07-27 01:44:01 +00001395}
1396
George Rimara2496cb2016-08-30 09:46:59 +00001397InputSectionDescription *
1398ScriptParser::readInputSectionDescription(StringRef Tok) {
George Rimar06598002016-07-28 21:51:30 +00001399 // Input section wildcard can be surrounded by KEEP.
1400 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
George Rimara2496cb2016-08-30 09:46:59 +00001401 if (Tok == "KEEP") {
George Rimar06598002016-07-28 21:51:30 +00001402 expect("(");
George Rimara2496cb2016-08-30 09:46:59 +00001403 StringRef FilePattern = next();
1404 InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
George Rimar06598002016-07-28 21:51:30 +00001405 expect(")");
Eugene Leviantcf43f172016-10-05 09:36:59 +00001406 Opt.KeptSections.push_back(Cmd);
Rui Ueyama10416562016-08-04 02:03:27 +00001407 return Cmd;
George Rimar06598002016-07-28 21:51:30 +00001408 }
George Rimara2496cb2016-08-30 09:46:59 +00001409 return readInputSectionRules(Tok);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001410}
1411
George Rimar03fc0102016-07-28 07:18:23 +00001412void ScriptParser::readSort() {
1413 expect("(");
1414 expect("CONSTRUCTORS");
1415 expect(")");
1416}
1417
George Rimareefa7582016-08-04 09:29:31 +00001418Expr ScriptParser::readAssert() {
1419 expect("(");
1420 Expr E = readExpr();
1421 expect(",");
George Rimarcd574a52016-09-09 14:35:36 +00001422 StringRef Msg = unquote(next());
George Rimareefa7582016-08-04 09:29:31 +00001423 expect(")");
Rafael Espindola4595df92017-03-10 16:04:26 +00001424 return [=] {
1425 if (!E())
George Rimareefa7582016-08-04 09:29:31 +00001426 error(Msg);
Rafael Espindola4595df92017-03-10 16:04:26 +00001427 return ScriptBase->getDot();
George Rimareefa7582016-08-04 09:29:31 +00001428 };
1429}
1430
Rui Ueyama25150e82016-09-06 17:46:43 +00001431// Reads a FILL(expr) command. We handle the FILL command as an
1432// alias for =fillexp section attribute, which is different from
1433// what GNU linkers do.
1434// https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
Rui Ueyama16068ae2016-11-19 18:05:56 +00001435uint32_t ScriptParser::readFill() {
George Rimarff1f29e2016-09-06 13:51:57 +00001436 expect("(");
Rui Ueyama16068ae2016-11-19 18:05:56 +00001437 uint32_t V = readOutputSectionFiller(next());
George Rimarff1f29e2016-09-06 13:51:57 +00001438 expect(")");
1439 expect(";");
1440 return V;
1441}
1442
Rui Ueyama10416562016-08-04 02:03:27 +00001443OutputSectionCommand *
1444ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +00001445 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
Eugene Leviant2a942c42016-12-05 16:38:32 +00001446 Cmd->Location = getCurrentLocation();
George Rimar58e5c4d2016-07-25 08:29:46 +00001447
1448 // Read an address expression.
1449 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
1450 if (peek() != ":")
1451 Cmd->AddrExpr = readExpr();
1452
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001453 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +00001454
Rui Ueyama83043f22016-10-17 16:01:53 +00001455 if (consume("AT"))
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001456 Cmd->LMAExpr = readParenExpr();
Rui Ueyama83043f22016-10-17 16:01:53 +00001457 if (consume("ALIGN"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001458 Cmd->AlignExpr = readParenExpr();
Rui Ueyama83043f22016-10-17 16:01:53 +00001459 if (consume("SUBALIGN"))
George Rimardb24d9c2016-08-19 15:18:23 +00001460 Cmd->SubalignExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001461
Davide Italiano246f6812016-07-22 03:36:24 +00001462 // Parse constraints.
Rui Ueyama83043f22016-10-17 16:01:53 +00001463 if (consume("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001464 Cmd->Constraint = ConstraintKind::ReadOnly;
Rui Ueyama83043f22016-10-17 16:01:53 +00001465 if (consume("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001466 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001467 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001468
Rui Ueyama83043f22016-10-17 16:01:53 +00001469 while (!Error && !consume("}")) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001470 StringRef Tok = next();
George Rimar2fe07922017-01-31 08:50:11 +00001471 if (Tok == ";") {
George Rimar69750752017-02-01 09:14:22 +00001472 // Empty commands are allowed. Do nothing here.
George Rimar2fe07922017-01-31 08:50:11 +00001473 } else if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok)) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001474 Cmd->Commands.emplace_back(Assignment);
Meador Ingeb2d99d62016-11-22 18:01:50 +00001475 } else if (BytesDataCommand *Data = readBytesDataCommand(Tok)) {
George Rimare38cbab2016-09-26 19:22:50 +00001476 Cmd->Commands.emplace_back(Data);
Meador Ingeb2d99d62016-11-22 18:01:50 +00001477 } else if (Tok == "ASSERT") {
1478 Cmd->Commands.emplace_back(new AssertCommand(readAssert()));
1479 expect(";");
George Rimar8e2eca22017-01-23 09:36:19 +00001480 } else if (Tok == "CONSTRUCTORS") {
1481 // CONSTRUCTORS is a keyword to make the linker recognize C++ ctors/dtors
1482 // by name. This is for very old file formats such as ECOFF/XCOFF.
1483 // For ELF, we should ignore.
Meador Ingeb2d99d62016-11-22 18:01:50 +00001484 } else if (Tok == "FILL") {
George Rimarff1f29e2016-09-06 13:51:57 +00001485 Cmd->Filler = readFill();
Meador Ingeb2d99d62016-11-22 18:01:50 +00001486 } else if (Tok == "SORT") {
George Rimar03fc0102016-07-28 07:18:23 +00001487 readSort();
Meador Ingeb2d99d62016-11-22 18:01:50 +00001488 } else if (peek() == "(") {
George Rimara2496cb2016-08-30 09:46:59 +00001489 Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
Meador Ingeb2d99d62016-11-22 18:01:50 +00001490 } else {
Eugene Leviantceabe802016-08-11 07:56:43 +00001491 setError("unknown command " + Tok);
Meador Ingeb2d99d62016-11-22 18:01:50 +00001492 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001493 }
Meador Ingeb8897442017-01-24 02:34:00 +00001494
1495 if (consume(">"))
1496 Cmd->MemoryRegionName = next();
1497
George Rimar076fe152016-07-21 06:43:01 +00001498 Cmd->Phdrs = readOutputSectionPhdrs();
George Rimar4ebc5622016-09-23 13:29:20 +00001499
Rui Ueyama83043f22016-10-17 16:01:53 +00001500 if (consume("="))
George Rimar4ebc5622016-09-23 13:29:20 +00001501 Cmd->Filler = readOutputSectionFiller(next());
1502 else if (peek().startswith("="))
George Rimarff1f29e2016-09-06 13:51:57 +00001503 Cmd->Filler = readOutputSectionFiller(next().drop_front());
George Rimar4ebc5622016-09-23 13:29:20 +00001504
George Rimar7185a1a2017-01-17 15:32:12 +00001505 // Consume optional comma following output section command.
1506 consume(",");
1507
Rui Ueyama10416562016-08-04 02:03:27 +00001508 return Cmd;
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001509}
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001510
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001511// Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
1512// https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
1513//
1514// ld.gold is not fully compatible with ld.bfd. ld.bfd handles
1515// hexstrings as blobs of arbitrary sizes, while ld.gold handles them
1516// as 32-bit big-endian values. We will do the same as ld.gold does
1517// because it's simpler than what ld.bfd does.
Rui Ueyama16068ae2016-11-19 18:05:56 +00001518uint32_t ScriptParser::readOutputSectionFiller(StringRef Tok) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001519 uint32_t V;
Rui Ueyama16068ae2016-11-19 18:05:56 +00001520 if (!Tok.getAsInteger(0, V))
1521 return V;
1522 setError("invalid filler expression: " + Tok);
1523 return 0;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001524}
1525
Petr Hoseka35e39c2016-08-16 01:11:16 +00001526SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
Eugene Levianta31c91b2016-07-22 07:38:40 +00001527 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +00001528 SymbolAssignment *Cmd = readAssignment(next());
Petr Hoseka35e39c2016-08-16 01:11:16 +00001529 Cmd->Provide = Provide;
Rui Ueyama174e0a12016-07-29 00:29:25 +00001530 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001531 expect(")");
1532 expect(";");
Rui Ueyama10416562016-08-04 02:03:27 +00001533 return Cmd;
Eugene Levianteda81a12016-07-12 06:39:48 +00001534}
1535
Rafael Espindolac96da112016-11-01 11:30:45 +00001536SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001537 SymbolAssignment *Cmd = nullptr;
1538 if (peek() == "=" || peek() == "+=") {
1539 Cmd = readAssignment(Tok);
1540 expect(";");
1541 } else if (Tok == "PROVIDE") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001542 Cmd = readProvideHidden(true, false);
1543 } else if (Tok == "HIDDEN") {
1544 Cmd = readProvideHidden(false, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001545 } else if (Tok == "PROVIDE_HIDDEN") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001546 Cmd = readProvideHidden(true, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001547 }
1548 return Cmd;
1549}
1550
George Rimar30835ea2016-07-28 21:08:56 +00001551SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1552 StringRef Op = next();
1553 assert(Op == "=" || Op == "+=");
Petr Hosek02ad5162017-03-15 03:33:23 +00001554 Expr E = readExpr();
Eugene Leviantf6aeed32016-12-22 13:13:12 +00001555 if (Op == "+=") {
1556 std::string Loc = getCurrentLocation();
Rafael Espindola4595df92017-03-10 16:04:26 +00001557 E = [=] { return ScriptBase->getSymbolValue(Loc, Name) + E(); };
Eugene Leviantf6aeed32016-12-22 13:13:12 +00001558 }
George Rimar2ee2d2d2017-02-21 14:50:38 +00001559 return new SymbolAssignment(Name, E, getCurrentLocation());
George Rimar30835ea2016-07-28 21:08:56 +00001560}
1561
1562// This is an operator-precedence parser to parse a linker
1563// script expression.
Rui Ueyama731a66a2017-02-15 19:58:17 +00001564Expr ScriptParser::readExpr() {
1565 // Our lexer is context-aware. Set the in-expression bit so that
1566 // they apply different tokenization rules.
1567 bool Orig = InExpr;
1568 InExpr = true;
1569 Expr E = readExpr1(readPrimary(), 0);
1570 InExpr = Orig;
1571 return E;
1572}
George Rimar30835ea2016-07-28 21:08:56 +00001573
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001574static Expr combine(StringRef Op, Expr L, Expr R) {
George Rimarcc4d3e52017-02-01 09:01:16 +00001575 auto IsAbs = [=] { return L.IsAbsolute() && R.IsAbsolute(); };
1576 auto GetOutSec = [=] {
Rafael Espindola9bd45662017-03-10 00:47:33 +00001577 SectionBase *S = L.Section();
George Rimarcc4d3e52017-02-01 09:01:16 +00001578 return S ? S : R.Section();
1579 };
1580
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001581 if (Op == "*")
Rafael Espindola4595df92017-03-10 16:04:26 +00001582 return [=] { return L() * R(); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001583 if (Op == "/") {
Rafael Espindola4595df92017-03-10 16:04:26 +00001584 return [=]() -> uint64_t {
1585 uint64_t RHS = R();
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001586 if (RHS == 0) {
1587 error("division by zero");
1588 return 0;
1589 }
Rafael Espindola4595df92017-03-10 16:04:26 +00001590 return L() / RHS;
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001591 };
1592 }
1593 if (Op == "+")
Rafael Espindola4595df92017-03-10 16:04:26 +00001594 return {[=] { return L() + R(); }, IsAbs, GetOutSec};
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001595 if (Op == "-")
Rafael Espindola4595df92017-03-10 16:04:26 +00001596 return {[=] { return L() - R(); }, IsAbs, GetOutSec};
George Rimarc8ccd1f2016-09-23 13:13:55 +00001597 if (Op == "<<")
Rafael Espindola4595df92017-03-10 16:04:26 +00001598 return [=] { return L() << R(); };
George Rimarc8ccd1f2016-09-23 13:13:55 +00001599 if (Op == ">>")
Rafael Espindola4595df92017-03-10 16:04:26 +00001600 return [=] { return L() >> R(); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001601 if (Op == "<")
Rafael Espindola4595df92017-03-10 16:04:26 +00001602 return [=] { return L() < R(); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001603 if (Op == ">")
Rafael Espindola4595df92017-03-10 16:04:26 +00001604 return [=] { return L() > R(); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001605 if (Op == ">=")
Rafael Espindola4595df92017-03-10 16:04:26 +00001606 return [=] { return L() >= R(); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001607 if (Op == "<=")
Rafael Espindola4595df92017-03-10 16:04:26 +00001608 return [=] { return L() <= R(); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001609 if (Op == "==")
Rafael Espindola4595df92017-03-10 16:04:26 +00001610 return [=] { return L() == R(); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001611 if (Op == "!=")
Rafael Espindola4595df92017-03-10 16:04:26 +00001612 return [=] { return L() != R(); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001613 if (Op == "&")
Rafael Espindola4595df92017-03-10 16:04:26 +00001614 return [=] { return L() & R(); };
Rafael Espindolacc3dd622016-08-22 21:33:35 +00001615 if (Op == "|")
Rafael Espindola4595df92017-03-10 16:04:26 +00001616 return [=] { return L() | R(); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001617 llvm_unreachable("invalid operator");
1618}
1619
Rui Ueyama708019c2016-07-24 18:19:40 +00001620// This is a part of the operator-precedence parser. This function
1621// assumes that the remaining token stream starts with an operator.
1622Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1623 while (!atEOF() && !Error) {
1624 // Read an operator and an expression.
Rui Ueyama46247b82016-11-18 06:49:07 +00001625 if (consume("?"))
Rui Ueyama708019c2016-07-24 18:19:40 +00001626 return readTernary(Lhs);
Rui Ueyama46247b82016-11-18 06:49:07 +00001627 StringRef Op1 = peek();
Rui Ueyama708019c2016-07-24 18:19:40 +00001628 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +00001629 break;
Justin Bogner5424e7c2016-10-17 06:21:13 +00001630 skip();
Rui Ueyama708019c2016-07-24 18:19:40 +00001631 Expr Rhs = readPrimary();
1632
1633 // Evaluate the remaining part of the expression first if the
1634 // next operator has greater precedence than the previous one.
1635 // For example, if we have read "+" and "3", and if the next
1636 // operator is "*", then we'll evaluate 3 * ... part first.
1637 while (!atEOF()) {
1638 StringRef Op2 = peek();
1639 if (precedence(Op2) <= precedence(Op1))
1640 break;
1641 Rhs = readExpr1(Rhs, precedence(Op2));
1642 }
1643
1644 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +00001645 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001646 return Lhs;
1647}
1648
1649uint64_t static getConstant(StringRef S) {
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001650 if (S == "COMMONPAGESIZE")
Rui Ueyama708019c2016-07-24 18:19:40 +00001651 return Target->PageSize;
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001652 if (S == "MAXPAGESIZE")
Petr Hosek997f8832016-09-28 15:20:47 +00001653 return Config->MaxPageSize;
Rui Ueyama708019c2016-07-24 18:19:40 +00001654 error("unknown constant: " + S);
1655 return 0;
1656}
1657
Rui Ueyama626e0b02016-09-02 18:19:00 +00001658// Parses Tok as an integer. Returns true if successful.
1659// It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1660// and decimal numbers. Decimal numbers may have "K" (kilo) or
1661// "M" (mega) prefixes.
George Rimar9f2f7ad2016-09-02 16:01:42 +00001662static bool readInteger(StringRef Tok, uint64_t &Result) {
Rui Ueyama46247b82016-11-18 06:49:07 +00001663 // Negative number
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001664 if (Tok.startswith("-")) {
1665 if (!readInteger(Tok.substr(1), Result))
1666 return false;
1667 Result = -Result;
1668 return true;
1669 }
Rui Ueyama46247b82016-11-18 06:49:07 +00001670
1671 // Hexadecimal
George Rimar9f2f7ad2016-09-02 16:01:42 +00001672 if (Tok.startswith_lower("0x"))
1673 return !Tok.substr(2).getAsInteger(16, Result);
1674 if (Tok.endswith_lower("H"))
1675 return !Tok.drop_back().getAsInteger(16, Result);
1676
Rui Ueyama46247b82016-11-18 06:49:07 +00001677 // Decimal
George Rimar9f2f7ad2016-09-02 16:01:42 +00001678 int Suffix = 1;
1679 if (Tok.endswith_lower("K")) {
1680 Suffix = 1024;
1681 Tok = Tok.drop_back();
1682 } else if (Tok.endswith_lower("M")) {
1683 Suffix = 1024 * 1024;
1684 Tok = Tok.drop_back();
1685 }
1686 if (Tok.getAsInteger(10, Result))
1687 return false;
1688 Result *= Suffix;
1689 return true;
1690}
1691
George Rimare38cbab2016-09-26 19:22:50 +00001692BytesDataCommand *ScriptParser::readBytesDataCommand(StringRef Tok) {
1693 int Size = StringSwitch<unsigned>(Tok)
1694 .Case("BYTE", 1)
1695 .Case("SHORT", 2)
1696 .Case("LONG", 4)
1697 .Case("QUAD", 8)
1698 .Default(-1);
1699 if (Size == -1)
1700 return nullptr;
1701
Meador Inge95c7d8d2016-12-08 23:21:30 +00001702 return new BytesDataCommand(readParenExpr(), Size);
George Rimare38cbab2016-09-26 19:22:50 +00001703}
1704
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001705StringRef ScriptParser::readParenLiteral() {
1706 expect("(");
1707 StringRef Tok = next();
1708 expect(")");
1709 return Tok;
1710}
1711
Rui Ueyama708019c2016-07-24 18:19:40 +00001712Expr ScriptParser::readPrimary() {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001713 if (peek() == "(")
1714 return readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001715
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001716 StringRef Tok = next();
Rui Ueyamab5f1c3e2016-12-01 04:36:49 +00001717 std::string Location = getCurrentLocation();
Rui Ueyama708019c2016-07-24 18:19:40 +00001718
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001719 if (Tok == "~") {
1720 Expr E = readPrimary();
Rafael Espindola4595df92017-03-10 16:04:26 +00001721 return [=] { return ~E(); };
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001722 }
1723 if (Tok == "-") {
1724 Expr E = readPrimary();
Rafael Espindola4595df92017-03-10 16:04:26 +00001725 return [=] { return -E(); };
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001726 }
1727
Rui Ueyama708019c2016-07-24 18:19:40 +00001728 // Built-in functions are parsed here.
1729 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
Petr Hosek02ad5162017-03-15 03:33:23 +00001730 if (Tok == "ABSOLUTE") {
1731 Expr E = readParenExpr();
1732 E.IsAbsolute = [] { return true; };
1733 return E;
1734 }
George Rimar96659df2016-08-30 09:54:01 +00001735 if (Tok == "ADDR") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001736 StringRef Name = readParenLiteral();
Rafael Espindola4595df92017-03-10 16:04:26 +00001737 return {[=] { return ScriptBase->getOutputSection(Location, Name)->Addr; },
Eugene Levianted30ce72016-11-28 09:58:04 +00001738 [=] { return false; },
1739 [=] { return ScriptBase->getOutputSection(Location, Name); }};
George Rimar96659df2016-08-30 09:54:01 +00001740 }
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001741 if (Tok == "LOADADDR") {
1742 StringRef Name = readParenLiteral();
Rafael Espindola4595df92017-03-10 16:04:26 +00001743 return
1744 [=] { return ScriptBase->getOutputSection(Location, Name)->getLMA(); };
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001745 }
George Rimareefa7582016-08-04 09:29:31 +00001746 if (Tok == "ASSERT")
1747 return readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001748 if (Tok == "ALIGN") {
Rui Ueyama5d804dc2016-12-16 18:19:35 +00001749 expect("(");
1750 Expr E = readExpr();
1751 if (consume(",")) {
1752 Expr E2 = readExpr();
1753 expect(")");
Rafael Espindola4595df92017-03-10 16:04:26 +00001754 return [=] { return alignTo(E(), E2()); };
Rui Ueyama5d804dc2016-12-16 18:19:35 +00001755 }
1756 expect(")");
Rafael Espindola4595df92017-03-10 16:04:26 +00001757 return [=] { return alignTo(ScriptBase->getDot(), E()); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001758 }
1759 if (Tok == "CONSTANT") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001760 StringRef Name = readParenLiteral();
Rafael Espindola4595df92017-03-10 16:04:26 +00001761 return [=] { return getConstant(Name); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001762 }
George Rimarf34f45f2016-09-23 13:17:23 +00001763 if (Tok == "DEFINED") {
Rui Ueyama0ee25a62016-11-17 03:52:14 +00001764 StringRef Name = readParenLiteral();
Rafael Espindola4595df92017-03-10 16:04:26 +00001765 return [=] { return ScriptBase->isDefined(Name) ? 1 : 0; };
George Rimarf34f45f2016-09-23 13:17:23 +00001766 }
Rafael Espindola54c145c2016-07-28 18:16:24 +00001767 if (Tok == "SEGMENT_START") {
1768 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001769 skip();
Rafael Espindola54c145c2016-07-28 18:16:24 +00001770 expect(",");
George Rimar8c658bf2016-09-17 18:14:56 +00001771 Expr E = readExpr();
Rafael Espindola54c145c2016-07-28 18:16:24 +00001772 expect(")");
Rafael Espindola4595df92017-03-10 16:04:26 +00001773 return [=] { return E(); };
Rafael Espindola54c145c2016-07-28 18:16:24 +00001774 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001775 if (Tok == "DATA_SEGMENT_ALIGN") {
1776 expect("(");
1777 Expr E = readExpr();
1778 expect(",");
1779 readExpr();
1780 expect(")");
Rafael Espindola4595df92017-03-10 16:04:26 +00001781 return [=] { return alignTo(ScriptBase->getDot(), E()); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001782 }
1783 if (Tok == "DATA_SEGMENT_END") {
1784 expect("(");
1785 expect(".");
1786 expect(")");
Rafael Espindola4595df92017-03-10 16:04:26 +00001787 return []() { return ScriptBase->getDot(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001788 }
George Rimar276b4e62016-07-26 17:58:44 +00001789 // GNU linkers implements more complicated logic to handle
1790 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1791 // the next page boundary for simplicity.
1792 if (Tok == "DATA_SEGMENT_RELRO_END") {
1793 expect("(");
Rafael Espindola97bdc722016-09-14 19:14:01 +00001794 readExpr();
George Rimar276b4e62016-07-26 17:58:44 +00001795 expect(",");
1796 readExpr();
1797 expect(")");
Rafael Espindola4595df92017-03-10 16:04:26 +00001798 return []() { return alignTo(ScriptBase->getDot(), Target->PageSize); };
George Rimar276b4e62016-07-26 17:58:44 +00001799 }
George Rimar9e694502016-07-29 16:18:47 +00001800 if (Tok == "SIZEOF") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001801 StringRef Name = readParenLiteral();
Rafael Espindola4595df92017-03-10 16:04:26 +00001802 return [=] { return ScriptBase->getOutputSectionSize(Name); };
George Rimar9e694502016-07-29 16:18:47 +00001803 }
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001804 if (Tok == "ALIGNOF") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001805 StringRef Name = readParenLiteral();
Rafael Espindola4595df92017-03-10 16:04:26 +00001806 return
1807 [=] { return ScriptBase->getOutputSection(Location, Name)->Alignment; };
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001808 }
George Rimare32a3592016-08-10 07:59:34 +00001809 if (Tok == "SIZEOF_HEADERS")
George Rimar78aa2702017-03-13 14:40:58 +00001810 return [=] { return elf::getHeaderSize(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001811
George Rimar9f2f7ad2016-09-02 16:01:42 +00001812 // Tok is a literal number.
1813 uint64_t V;
1814 if (readInteger(Tok, V))
Rafael Espindola4595df92017-03-10 16:04:26 +00001815 return [=] { return V; };
George Rimar9f2f7ad2016-09-02 16:01:42 +00001816
1817 // Tok is a symbol name.
1818 if (Tok != "." && !isValidCIdentifier(Tok))
1819 setError("malformed number: " + Tok);
Rafael Espindola4595df92017-03-10 16:04:26 +00001820 return {[=] { return ScriptBase->getSymbolValue(Location, Tok); },
1821 [=] { return ScriptBase->isAbsolute(Tok); },
Rui Ueyama009d1742016-11-18 06:49:09 +00001822 [=] { return ScriptBase->getSymbolSection(Tok); }};
Rui Ueyama708019c2016-07-24 18:19:40 +00001823}
1824
1825Expr ScriptParser::readTernary(Expr Cond) {
Rui Ueyama708019c2016-07-24 18:19:40 +00001826 Expr L = readExpr();
1827 expect(":");
1828 Expr R = readExpr();
Rafael Espindola4595df92017-03-10 16:04:26 +00001829 return [=] { return Cond() ? L() : R(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001830}
1831
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001832Expr ScriptParser::readParenExpr() {
1833 expect("(");
1834 Expr E = readExpr();
1835 expect(")");
1836 return E;
1837}
1838
Eugene Leviantbbe38602016-07-19 09:25:43 +00001839std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1840 std::vector<StringRef> Phdrs;
1841 while (!Error && peek().startswith(":")) {
1842 StringRef Tok = next();
George Rimarda841c12016-11-14 10:03:54 +00001843 Phdrs.push_back((Tok.size() == 1) ? next() : Tok.substr(1));
Eugene Leviantbbe38602016-07-19 09:25:43 +00001844 }
1845 return Phdrs;
1846}
1847
George Rimar95dd7182016-10-18 10:49:50 +00001848// Read a program header type name. The next token must be a
1849// name of a program header type or a constant (e.g. "0x3").
Eugene Leviantbbe38602016-07-19 09:25:43 +00001850unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001851 StringRef Tok = next();
George Rimar95dd7182016-10-18 10:49:50 +00001852 uint64_t Val;
1853 if (readInteger(Tok, Val))
1854 return Val;
1855
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001856 unsigned Ret = StringSwitch<unsigned>(Tok)
George Rimar6c55f0e2016-09-08 08:20:30 +00001857 .Case("PT_NULL", PT_NULL)
1858 .Case("PT_LOAD", PT_LOAD)
1859 .Case("PT_DYNAMIC", PT_DYNAMIC)
1860 .Case("PT_INTERP", PT_INTERP)
1861 .Case("PT_NOTE", PT_NOTE)
1862 .Case("PT_SHLIB", PT_SHLIB)
1863 .Case("PT_PHDR", PT_PHDR)
1864 .Case("PT_TLS", PT_TLS)
1865 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1866 .Case("PT_GNU_STACK", PT_GNU_STACK)
1867 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
George Rimar270173f2016-10-14 13:02:22 +00001868 .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
George Rimarcc6e5672016-10-14 10:34:36 +00001869 .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
George Rimara2a32c22016-12-06 17:57:42 +00001870 .Case("PT_OPENBSD_BOOTDATA", PT_OPENBSD_BOOTDATA)
George Rimar6c55f0e2016-09-08 08:20:30 +00001871 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001872
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001873 if (Ret == (unsigned)-1) {
1874 setError("invalid program header type: " + Tok);
1875 return PT_NULL;
1876 }
1877 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001878}
1879
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001880// Reads an anonymous version declaration.
Rui Ueyama12450b22016-11-18 06:30:09 +00001881void ScriptParser::readAnonymousDeclaration() {
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001882 std::vector<SymbolVersion> Locals;
1883 std::vector<SymbolVersion> Globals;
1884 std::tie(Locals, Globals) = readSymbols();
1885
1886 for (SymbolVersion V : Locals) {
1887 if (V.Name == "*")
1888 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1889 else
1890 Config->VersionScriptLocals.push_back(V);
Rafael Espindola45242682017-02-03 13:24:01 +00001891 }
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001892
1893 for (SymbolVersion V : Globals)
1894 Config->VersionScriptGlobals.push_back(V);
1895
Rui Ueyama12450b22016-11-18 06:30:09 +00001896 expect(";");
1897}
1898
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001899// Reads a non-anonymous version definition,
1900// e.g. "VerStr { global: foo; bar; local: *; };".
Rui Ueyama95769b42016-08-31 20:03:54 +00001901void ScriptParser::readVersionDeclaration(StringRef VerStr) {
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001902 // Read a symbol list.
1903 std::vector<SymbolVersion> Locals;
1904 std::vector<SymbolVersion> Globals;
1905 std::tie(Locals, Globals) = readSymbols();
George Rimar20b65982016-08-31 09:08:26 +00001906
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001907 for (SymbolVersion V : Locals) {
1908 if (V.Name == "*")
1909 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1910 else
1911 Config->VersionScriptLocals.push_back(V);
Rafael Espindola45242682017-02-03 13:24:01 +00001912 }
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001913
1914 // Create a new version definition and add that to the global symbols.
1915 VersionDefinition Ver;
1916 Ver.Name = VerStr;
1917 Ver.Globals = Globals;
1918
1919 // User-defined version number starts from 2 because 0 and 1 are
1920 // reserved for VER_NDX_LOCAL and VER_NDX_GLOBAL, respectively.
1921 Ver.Id = Config->VersionDefinitions.size() + 2;
1922 Config->VersionDefinitions.push_back(Ver);
George Rimar20b65982016-08-31 09:08:26 +00001923
Rui Ueyama12450b22016-11-18 06:30:09 +00001924 // Each version may have a parent version. For example, "Ver2"
1925 // defined as "Ver2 { global: foo; local: *; } Ver1;" has "Ver1"
1926 // as a parent. This version hierarchy is, probably against your
1927 // instinct, purely for hint; the runtime doesn't care about it
1928 // at all. In LLD, we simply ignore it.
1929 if (peek() != ";")
Justin Bogner5424e7c2016-10-17 06:21:13 +00001930 skip();
George Rimar20b65982016-08-31 09:08:26 +00001931 expect(";");
1932}
1933
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001934// Reads a list of symbols, e.g. "{ global: foo; bar; local: *; };".
1935std::pair<std::vector<SymbolVersion>, std::vector<SymbolVersion>>
1936ScriptParser::readSymbols() {
1937 std::vector<SymbolVersion> Locals;
1938 std::vector<SymbolVersion> Globals;
1939 std::vector<SymbolVersion> *V = &Globals;
1940
1941 while (!Error) {
1942 if (consume("}"))
1943 break;
1944 if (consumeLabel("local")) {
1945 V = &Locals;
1946 continue;
1947 }
1948 if (consumeLabel("global")) {
1949 V = &Globals;
Rafael Espindola1ef90d22016-12-09 16:44:05 +00001950 continue;
1951 }
George Rimare0fc2422016-11-16 17:59:10 +00001952
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001953 if (consume("extern")) {
1954 std::vector<SymbolVersion> Ext = readVersionExtern();
1955 V->insert(V->end(), Ext.begin(), Ext.end());
1956 } else {
1957 StringRef Tok = next();
1958 V->push_back({unquote(Tok), false, hasWildcard(Tok)});
1959 }
George Rimare0fc2422016-11-16 17:59:10 +00001960 expect(";");
1961 }
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001962 return {Locals, Globals};
George Rimare0fc2422016-11-16 17:59:10 +00001963}
1964
Rui Ueyama12450b22016-11-18 06:30:09 +00001965// Reads an "extern C++" directive, e.g.,
1966// "extern "C++" { ns::*; "f(int, double)"; };"
1967std::vector<SymbolVersion> ScriptParser::readVersionExtern() {
Rafael Espindola7e714152016-12-08 17:26:53 +00001968 StringRef Tok = next();
1969 bool IsCXX = Tok == "\"C++\"";
1970 if (!IsCXX && Tok != "\"C\"")
Rafael Espindolad0ebd842016-12-08 17:54:26 +00001971 setError("Unknown language");
George Rimar20b65982016-08-31 09:08:26 +00001972 expect("{");
1973
Rui Ueyama12450b22016-11-18 06:30:09 +00001974 std::vector<SymbolVersion> Ret;
Rui Ueyama0ee25a62016-11-17 03:52:14 +00001975 while (!Error && peek() != "}") {
1976 StringRef Tok = next();
1977 bool HasWildcard = !Tok.startswith("\"") && hasWildcard(Tok);
Rafael Espindola7e714152016-12-08 17:26:53 +00001978 Ret.push_back({unquote(Tok), IsCXX, HasWildcard});
George Rimar20b65982016-08-31 09:08:26 +00001979 expect(";");
1980 }
1981
1982 expect("}");
Rui Ueyama12450b22016-11-18 06:30:09 +00001983 return Ret;
George Rimar20b65982016-08-31 09:08:26 +00001984}
1985
Rui Ueyama24e626c2017-01-26 02:58:19 +00001986uint64_t ScriptParser::readMemoryAssignment(
1987 StringRef S1, StringRef S2, StringRef S3) {
1988 if (!(consume(S1) || consume(S2) || consume(S3))) {
1989 setError("expected one of: " + S1 + ", " + S2 + ", or " + S3);
1990 return 0;
1991 }
1992 expect("=");
1993
1994 // TODO: Fully support constant expressions.
1995 uint64_t Val;
1996 if (!readInteger(next(), Val))
1997 setError("nonconstant expression for "+ S1);
1998 return Val;
1999}
2000
2001// Parse the MEMORY command as specified in:
2002// https://sourceware.org/binutils/docs/ld/MEMORY.html
2003//
2004// MEMORY { name [(attr)] : ORIGIN = origin, LENGTH = len ... }
Meador Ingeb8897442017-01-24 02:34:00 +00002005void ScriptParser::readMemory() {
2006 expect("{");
2007 while (!Error && !consume("}")) {
2008 StringRef Name = next();
Rui Ueyama24e626c2017-01-26 02:58:19 +00002009
Meador Ingeb8897442017-01-24 02:34:00 +00002010 uint32_t Flags = 0;
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002011 uint32_t NegFlags = 0;
Meador Ingeb8897442017-01-24 02:34:00 +00002012 if (consume("(")) {
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002013 std::tie(Flags, NegFlags) = readMemoryAttributes();
Meador Ingeb8897442017-01-24 02:34:00 +00002014 expect(")");
2015 }
2016 expect(":");
2017
Rui Ueyama24e626c2017-01-26 02:58:19 +00002018 uint64_t Origin = readMemoryAssignment("ORIGIN", "org", "o");
Meador Ingeb8897442017-01-24 02:34:00 +00002019 expect(",");
Rui Ueyama24e626c2017-01-26 02:58:19 +00002020 uint64_t Length = readMemoryAssignment("LENGTH", "len", "l");
Meador Ingeb8897442017-01-24 02:34:00 +00002021
Meador Ingeb8897442017-01-24 02:34:00 +00002022 // Add the memory region to the region map (if it doesn't already exist).
2023 auto It = Opt.MemoryRegions.find(Name);
2024 if (It != Opt.MemoryRegions.end())
2025 setError("region '" + Name + "' already defined");
2026 else
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002027 Opt.MemoryRegions[Name] = {Name, Origin, Length, Origin, Flags, NegFlags};
Meador Ingeb8897442017-01-24 02:34:00 +00002028 }
2029}
2030
2031// This function parses the attributes used to match against section
2032// flags when placing output sections in a memory region. These flags
2033// are only used when an explicit memory region name is not used.
2034std::pair<uint32_t, uint32_t> ScriptParser::readMemoryAttributes() {
2035 uint32_t Flags = 0;
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002036 uint32_t NegFlags = 0;
Meador Ingeb8897442017-01-24 02:34:00 +00002037 bool Invert = false;
Rui Ueyama481ac992017-01-26 02:58:39 +00002038
2039 for (char C : next().lower()) {
Meador Ingeb8897442017-01-24 02:34:00 +00002040 uint32_t Flag = 0;
2041 if (C == '!')
2042 Invert = !Invert;
Rui Ueyama481ac992017-01-26 02:58:39 +00002043 else if (C == 'w')
Meador Ingeb8897442017-01-24 02:34:00 +00002044 Flag = SHF_WRITE;
Rui Ueyama481ac992017-01-26 02:58:39 +00002045 else if (C == 'x')
Meador Ingeb8897442017-01-24 02:34:00 +00002046 Flag = SHF_EXECINSTR;
Rui Ueyama481ac992017-01-26 02:58:39 +00002047 else if (C == 'a')
Meador Ingeb8897442017-01-24 02:34:00 +00002048 Flag = SHF_ALLOC;
Rui Ueyama481ac992017-01-26 02:58:39 +00002049 else if (C != 'r')
Meador Ingeb8897442017-01-24 02:34:00 +00002050 setError("invalid memory region attribute");
Rui Ueyama481ac992017-01-26 02:58:39 +00002051
Meador Ingeb8897442017-01-24 02:34:00 +00002052 if (Invert)
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002053 NegFlags |= Flag;
Meador Ingeb8897442017-01-24 02:34:00 +00002054 else
2055 Flags |= Flag;
2056 }
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002057 return {Flags, NegFlags};
Meador Ingeb8897442017-01-24 02:34:00 +00002058}
2059
Rui Ueyama07320e42016-04-20 20:13:41 +00002060void elf::readLinkerScript(MemoryBufferRef MB) {
Rui Ueyama22375f22016-11-25 18:51:54 +00002061 ScriptParser(MB).readLinkerScript();
George Rimar20b65982016-08-31 09:08:26 +00002062}
2063
2064void elf::readVersionScript(MemoryBufferRef MB) {
Rui Ueyama22375f22016-11-25 18:51:54 +00002065 ScriptParser(MB).readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00002066}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00002067
Rafael Espindolad0ebd842016-12-08 17:54:26 +00002068void elf::readDynamicList(MemoryBufferRef MB) {
2069 ScriptParser(MB).readDynamicList();
2070}
2071
Rui Ueyama07320e42016-04-20 20:13:41 +00002072template class elf::LinkerScript<ELF32LE>;
2073template class elf::LinkerScript<ELF32BE>;
2074template class elf::LinkerScript<ELF64LE>;
2075template class elf::LinkerScript<ELF64BE>;