blob: c36d55236ff2a3be42349dbb376a308850987efb [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
Rafael Espindola72dc1952017-03-17 13:05:04 +000056uint64_t ExprValue::getValue() const {
57 if (Sec)
58 return Sec->getOffset(Val) + Sec->getOutputSection()->Addr;
59 return Val;
60}
61
Rafael Espindola7ba5f472017-03-17 14:55:36 +000062uint64_t ExprValue::getSecAddr() const {
63 if (Sec)
64 return Sec->getOffset(0) + Sec->getOutputSection()->Addr;
65 return 0;
66}
67
68// Some operations only support one non absolute value. Move the
69// absolute one to the right hand side for convenience.
70static void moveAbsRight(ExprValue &A, ExprValue &B) {
Rafael Espindolaf2115f02017-03-17 13:45:36 +000071 if (A.isAbsolute())
72 std::swap(A, B);
Rafael Espindola5f08a1d2017-03-17 14:51:07 +000073 if (!B.isAbsolute())
74 error("At least one side of the expression must be absolute");
Rafael Espindola7ba5f472017-03-17 14:55:36 +000075}
76
77static ExprValue add(ExprValue A, ExprValue B) {
78 moveAbsRight(A, B);
Rafael Espindola72dc1952017-03-17 13:05:04 +000079 return {A.Sec, A.ForceAbsolute, A.Val + B.getValue()};
80}
81static ExprValue sub(ExprValue A, ExprValue B) {
82 return {A.Sec, A.Val - B.getValue()};
83}
84static ExprValue mul(ExprValue A, ExprValue B) {
85 return A.getValue() * B.getValue();
86}
87static ExprValue div(ExprValue A, ExprValue B) {
88 if (uint64_t BV = B.getValue())
89 return A.getValue() / BV;
90 error("division by zero");
91 return 0;
92}
93static ExprValue leftShift(ExprValue A, ExprValue B) {
94 return A.getValue() << B.getValue();
95}
96static ExprValue rightShift(ExprValue A, ExprValue B) {
97 return A.getValue() >> B.getValue();
98}
Rafael Espindola72dc1952017-03-17 13:05:04 +000099static ExprValue bitAnd(ExprValue A, ExprValue B) {
Rafael Espindola7ba5f472017-03-17 14:55:36 +0000100 moveAbsRight(A, B);
101 return {A.Sec, A.ForceAbsolute,
102 (A.getValue() & B.getValue()) - A.getSecAddr()};
Rafael Espindola72dc1952017-03-17 13:05:04 +0000103}
104static ExprValue bitOr(ExprValue A, ExprValue B) {
Rafael Espindola7ba5f472017-03-17 14:55:36 +0000105 moveAbsRight(A, B);
106 return {A.Sec, A.ForceAbsolute,
107 (A.getValue() | B.getValue()) - A.getSecAddr()};
Rafael Espindola72dc1952017-03-17 13:05:04 +0000108}
109static ExprValue bitNot(ExprValue A) { return ~A.getValue(); }
110static ExprValue minus(ExprValue A) { return -A.getValue(); }
111
George Rimara8dba482017-03-20 10:09:58 +0000112LinkerScriptBase *elf::Script;
Rui Ueyama07320e42016-04-20 20:13:41 +0000113ScriptConfiguration *elf::ScriptConfig;
Rui Ueyama717677a2016-02-11 21:17:59 +0000114
Meador Inge8f1f3c42017-01-09 18:36:57 +0000115template <class ELFT> static SymbolBody *addRegular(SymbolAssignment *Cmd) {
Petr Hosek5e51f7d2017-02-21 22:32:51 +0000116 Symbol *Sym;
Rafael Espindola3dabfc62016-10-31 13:14:53 +0000117 uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
Petr Hosek5e51f7d2017-02-21 22:32:51 +0000118 std::tie(Sym, std::ignore) = Symtab<ELFT>::X->insert(
119 Cmd->Name, /*Type*/ 0, Visibility, /*CanOmitFromDynSym*/ false,
120 /*File*/ nullptr);
121 Sym->Binding = STB_GLOBAL;
Rafael Espindola72dc1952017-03-17 13:05:04 +0000122 ExprValue Value = Cmd->Expression();
123 SectionBase *Sec = Value.isAbsolute() ? nullptr : Value.Sec;
Rui Ueyama80474a22017-02-28 19:29:55 +0000124 replaceBody<DefinedRegular>(Sym, Cmd->Name, /*IsLocal=*/false, Visibility,
Rafael Espindola5616adf2017-03-08 22:36:28 +0000125 STT_NOTYPE, 0, 0, Sec, nullptr);
Meador Inge8f1f3c42017-01-09 18:36:57 +0000126 return Sym->body();
Eugene Leviantceabe802016-08-11 07:56:43 +0000127}
128
Rui Ueyama22375f22016-11-25 18:51:54 +0000129static bool isUnderSysroot(StringRef Path) {
130 if (Config->Sysroot == "")
131 return false;
132 for (; !Path.empty(); Path = sys::path::parent_path(Path))
133 if (sys::fs::equivalent(Config->Sysroot, Path))
134 return true;
135 return false;
136}
137
George Rimar851dc1e2017-03-14 10:15:53 +0000138OutputSection *LinkerScriptBase::getOutputSection(const Twine &Loc,
139 StringRef Name) {
140 static OutputSection FakeSec("", 0, 0);
141
142 for (OutputSection *Sec : *OutputSections)
143 if (Sec->Name == Name)
144 return Sec;
145
Rafael Espindola72dc1952017-03-17 13:05:04 +0000146 if (ErrorOnMissingSection)
147 error(Loc + ": undefined section " + Name);
George Rimar851dc1e2017-03-14 10:15:53 +0000148 return &FakeSec;
149}
150
George Rimard83ce1b2017-03-14 10:24:47 +0000151// This function is essentially the same as getOutputSection(Name)->Size,
152// but it won't print out an error message if a given section is not found.
153//
154// Linker script does not create an output section if its content is empty.
155// We want to allow SIZEOF(.foo) where .foo is a section which happened to
156// be empty. That is why this function is different from getOutputSection().
157uint64_t LinkerScriptBase::getOutputSectionSize(StringRef Name) {
158 for (OutputSection *Sec : *OutputSections)
159 if (Sec->Name == Name)
160 return Sec->Size;
161 return 0;
162}
163
George Rimara2a1ef12017-03-14 12:03:34 +0000164void LinkerScriptBase::setDot(Expr E, const Twine &Loc, bool InSec) {
Rafael Espindola72dc1952017-03-17 13:05:04 +0000165 uint64_t Val = E().getValue();
Rafael Espindola679828f2017-02-17 16:26:13 +0000166 if (Val < Dot) {
167 if (InSec)
George Rimar2ee2d2d2017-02-21 14:50:38 +0000168 error(Loc + ": unable to move location counter backward for: " +
169 CurOutSec->Name);
Rafael Espindola679828f2017-02-17 16:26:13 +0000170 else
George Rimar2ee2d2d2017-02-21 14:50:38 +0000171 error(Loc + ": unable to move location counter backward");
Rafael Espindola679828f2017-02-17 16:26:13 +0000172 }
173 Dot = Val;
174 // Update to location counter means update to section size.
175 if (InSec)
176 CurOutSec->Size = Dot - CurOutSec->Addr;
177}
178
George Rimarb2b70972017-02-07 10:23:28 +0000179// Sets value of a symbol. Two kinds of symbols are processed: synthetic
180// symbols, whose value is an offset from beginning of section and regular
181// symbols whose value is absolute.
George Rimara2a1ef12017-03-14 12:03:34 +0000182void LinkerScriptBase::assignSymbol(SymbolAssignment *Cmd, bool InSec) {
Rafael Espindola4cd73522017-02-17 16:01:51 +0000183 if (Cmd->Name == ".") {
George Rimar2ee2d2d2017-02-21 14:50:38 +0000184 setDot(Cmd->Expression, Cmd->Location, InSec);
Rafael Espindola4cd73522017-02-17 16:01:51 +0000185 return;
186 }
187
George Rimarb2b70972017-02-07 10:23:28 +0000188 if (!Cmd->Sym)
Meador Inge8f1f3c42017-01-09 18:36:57 +0000189 return;
190
Rafael Espindola5616adf2017-03-08 22:36:28 +0000191 auto *Sym = cast<DefinedRegular>(Cmd->Sym);
Rafael Espindola72dc1952017-03-17 13:05:04 +0000192 ExprValue V = Cmd->Expression();
193 if (V.isAbsolute()) {
194 Sym->Value = V.getValue();
195 } else {
196 Sym->Section = V.Sec;
197 if (Sym->Section->Flags & SHF_ALLOC)
198 Sym->Value = V.Val;
199 else
200 Sym->Value = V.getValue();
Meador Inge8f1f3c42017-01-09 18:36:57 +0000201 }
Eugene Leviantdb741e72016-09-07 07:08:43 +0000202}
Meador Inge8f1f3c42017-01-09 18:36:57 +0000203
George Rimara8dba482017-03-20 10:09:58 +0000204static SymbolBody *findSymbol(StringRef S) {
205 switch (Config->EKind) {
206 case ELF32LEKind:
207 return Symtab<ELF32LE>::X->find(S);
208 case ELF32BEKind:
209 return Symtab<ELF32BE>::X->find(S);
210 case ELF64LEKind:
211 return Symtab<ELF64LE>::X->find(S);
212 case ELF64BEKind:
213 return Symtab<ELF64BE>::X->find(S);
214 default:
215 llvm_unreachable("unknown Config->EKind");
216 }
217}
218
219static SymbolBody *addRegularSymbol(SymbolAssignment *Cmd) {
220 switch (Config->EKind) {
221 case ELF32LEKind:
222 return addRegular<ELF32LE>(Cmd);
223 case ELF32BEKind:
224 return addRegular<ELF32BE>(Cmd);
225 case ELF64LEKind:
226 return addRegular<ELF64LE>(Cmd);
227 case ELF64BEKind:
228 return addRegular<ELF64BE>(Cmd);
229 default:
230 llvm_unreachable("unknown Config->EKind");
231 }
232}
233
234void LinkerScriptBase::addSymbol(SymbolAssignment *Cmd) {
Rui Ueyama16024212016-08-11 23:22:52 +0000235 if (Cmd->Name == ".")
Meador Inge8f1f3c42017-01-09 18:36:57 +0000236 return;
237
238 // If a symbol was in PROVIDE(), we need to define it only when
239 // it is a referenced undefined symbol.
George Rimara8dba482017-03-20 10:09:58 +0000240 SymbolBody *B = findSymbol(Cmd->Name);
Meador Inge8f1f3c42017-01-09 18:36:57 +0000241 if (Cmd->Provide && (!B || B->isDefined()))
242 return;
243
George Rimara8dba482017-03-20 10:09:58 +0000244 Cmd->Sym = addRegularSymbol(Cmd);
Eugene Leviantceabe802016-08-11 07:56:43 +0000245}
246
George Rimar076fe152016-07-21 06:43:01 +0000247bool SymbolAssignment::classof(const BaseCommand *C) {
248 return C->Kind == AssignmentKind;
249}
250
251bool OutputSectionCommand::classof(const BaseCommand *C) {
252 return C->Kind == OutputSectionKind;
253}
254
George Rimareea31142016-07-21 14:26:59 +0000255bool InputSectionDescription::classof(const BaseCommand *C) {
256 return C->Kind == InputSectionKind;
257}
258
George Rimareefa7582016-08-04 09:29:31 +0000259bool AssertCommand::classof(const BaseCommand *C) {
260 return C->Kind == AssertKind;
261}
262
George Rimare38cbab2016-09-26 19:22:50 +0000263bool BytesDataCommand::classof(const BaseCommand *C) {
264 return C->Kind == BytesDataKind;
265}
266
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000267static StringRef basename(InputSectionBase *S) {
268 if (S->File)
269 return sys::path::filename(S->File->getName());
Rui Ueyamae0be2902016-11-21 02:10:12 +0000270 return "";
271}
272
George Rimara2a1ef12017-03-14 12:03:34 +0000273bool LinkerScriptBase::shouldKeep(InputSectionBase *S) {
Rui Ueyamae0be2902016-11-21 02:10:12 +0000274 for (InputSectionDescription *ID : Opt.KeptSections)
275 if (ID->FilePat.match(basename(S)))
276 for (SectionPattern &P : ID->SectionPatterns)
277 if (P.SectionPat.match(S->Name))
278 return true;
George Rimareea31142016-07-21 14:26:59 +0000279 return false;
280}
281
Rafael Espindolac404d502017-02-23 02:32:18 +0000282static bool comparePriority(InputSectionBase *A, InputSectionBase *B) {
George Rimar575208c2016-09-15 19:15:12 +0000283 return getPriority(A->Name) < getPriority(B->Name);
284}
285
Rafael Espindolac404d502017-02-23 02:32:18 +0000286static bool compareName(InputSectionBase *A, InputSectionBase *B) {
Rafael Espindola042a3f22016-09-08 14:06:08 +0000287 return A->Name < B->Name;
Rui Ueyama742c3832016-08-04 22:27:00 +0000288}
George Rimar350ece42016-08-03 08:35:59 +0000289
Rafael Espindolac404d502017-02-23 02:32:18 +0000290static bool compareAlignment(InputSectionBase *A, InputSectionBase *B) {
Rui Ueyama742c3832016-08-04 22:27:00 +0000291 // ">" is not a mistake. Larger alignments are placed before smaller
292 // alignments in order to reduce the amount of padding necessary.
293 // This is compatible with GNU.
294 return A->Alignment > B->Alignment;
295}
George Rimar350ece42016-08-03 08:35:59 +0000296
Rafael Espindolac404d502017-02-23 02:32:18 +0000297static std::function<bool(InputSectionBase *, InputSectionBase *)>
George Rimarbe394db2016-09-16 20:21:55 +0000298getComparator(SortSectionPolicy K) {
299 switch (K) {
300 case SortSectionPolicy::Alignment:
301 return compareAlignment;
302 case SortSectionPolicy::Name:
Rafael Espindolac0028d32016-09-08 20:47:52 +0000303 return compareName;
George Rimarbe394db2016-09-16 20:21:55 +0000304 case SortSectionPolicy::Priority:
305 return comparePriority;
306 default:
307 llvm_unreachable("unknown sort policy");
308 }
Rui Ueyama742c3832016-08-04 22:27:00 +0000309}
George Rimar0702c4e2016-07-29 15:32:46 +0000310
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000311static bool matchConstraints(ArrayRef<InputSectionBase *> Sections,
George Rimar06ae6832016-08-12 09:07:57 +0000312 ConstraintKind Kind) {
George Rimar8f66df92016-08-12 20:38:20 +0000313 if (Kind == ConstraintKind::NoConstraint)
314 return true;
Rafael Espindolac404d502017-02-23 02:32:18 +0000315 bool IsRW = llvm::any_of(Sections, [=](InputSectionBase *Sec2) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000316 auto *Sec = static_cast<InputSectionBase *>(Sec2);
Rafael Espindola1854a8e2016-10-26 12:36:56 +0000317 return Sec->Flags & SHF_WRITE;
George Rimar06ae6832016-08-12 09:07:57 +0000318 });
Rafael Espindolae746e522016-09-21 18:33:44 +0000319 return (IsRW && Kind == ConstraintKind::ReadWrite) ||
320 (!IsRW && Kind == ConstraintKind::ReadOnly);
George Rimar06ae6832016-08-12 09:07:57 +0000321}
322
Rafael Espindolac404d502017-02-23 02:32:18 +0000323static void sortSections(InputSectionBase **Begin, InputSectionBase **End,
Rui Ueyamaee924702016-09-20 19:42:41 +0000324 SortSectionPolicy K) {
325 if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
George Rimar07171f22016-09-21 15:56:44 +0000326 std::stable_sort(Begin, End, getComparator(K));
Rui Ueyamaee924702016-09-20 19:42:41 +0000327}
328
Rafael Espindolad3190792016-09-16 15:10:23 +0000329// Compute and remember which sections the InputSectionDescription matches.
George Rimara2a1ef12017-03-14 12:03:34 +0000330void LinkerScriptBase::computeInputSections(InputSectionDescription *I) {
Rui Ueyama4dc07be2016-09-17 02:23:40 +0000331 // Collects all sections that satisfy constraints of I
332 // and attach them to I.
333 for (SectionPattern &Pat : I->SectionPatterns) {
George Rimar07171f22016-09-21 15:56:44 +0000334 size_t SizeBefore = I->Sections.size();
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000335
Rui Ueyama536a2672017-02-27 02:32:08 +0000336 for (InputSectionBase *S : InputSections) {
Rafael Espindola3773bca2017-02-17 19:37:30 +0000337 if (S->Assigned)
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000338 continue;
Rafael Espindola908a3d32017-02-16 14:36:09 +0000339 // For -emit-relocs we have to ignore entries like
340 // .rela.dyn : { *(.rela.data) }
341 // which are common because they are in the default bfd script.
342 if (S->Type == SHT_REL || S->Type == SHT_RELA)
343 continue;
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000344
Rui Ueyamae0be2902016-11-21 02:10:12 +0000345 StringRef Filename = basename(S);
346 if (!I->FilePat.match(Filename) || Pat.ExcludedFilePat.match(Filename))
347 continue;
348 if (!Pat.SectionPat.match(S->Name))
349 continue;
350 I->Sections.push_back(S);
351 S->Assigned = true;
George Rimar395281c2016-09-16 17:42:10 +0000352 }
Rafael Espindolad3190792016-09-16 15:10:23 +0000353
George Rimar07171f22016-09-21 15:56:44 +0000354 // Sort sections as instructed by SORT-family commands and --sort-section
355 // option. Because SORT-family commands can be nested at most two depth
356 // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
357 // line option is respected even if a SORT command is given, the exact
358 // behavior we have here is a bit complicated. Here are the rules.
359 //
360 // 1. If two SORT commands are given, --sort-section is ignored.
361 // 2. If one SORT command is given, and if it is not SORT_NONE,
362 // --sort-section is handled as an inner SORT command.
363 // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
364 // 4. If no SORT command is given, sort according to --sort-section.
Rafael Espindolac404d502017-02-23 02:32:18 +0000365 InputSectionBase **Begin = I->Sections.data() + SizeBefore;
366 InputSectionBase **End = I->Sections.data() + I->Sections.size();
George Rimar07171f22016-09-21 15:56:44 +0000367 if (Pat.SortOuter != SortSectionPolicy::None) {
368 if (Pat.SortInner == SortSectionPolicy::Default)
369 sortSections(Begin, End, Config->SortSection);
370 else
371 sortSections(Begin, End, Pat.SortInner);
372 sortSections(Begin, End, Pat.SortOuter);
373 }
Rui Ueyamaee924702016-09-20 19:42:41 +0000374 }
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000375}
376
George Rimar503206c2017-03-15 15:42:44 +0000377void LinkerScriptBase::discard(ArrayRef<InputSectionBase *> V) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000378 for (InputSectionBase *S : V) {
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000379 S->Live = false;
George Rimar503206c2017-03-15 15:42:44 +0000380 if (S == InX::ShStrTab)
Rafael Espindolaecbfd872017-02-17 17:35:07 +0000381 error("discarding .shstrtab section is not allowed");
George Rimar647c1682017-02-17 19:34:05 +0000382 discard(S->DependentSections);
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000383 }
384}
385
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000386std::vector<InputSectionBase *>
George Rimara2a1ef12017-03-14 12:03:34 +0000387LinkerScriptBase::createInputSectionList(OutputSectionCommand &OutCmd) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000388 std::vector<InputSectionBase *> Ret;
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000389
George Rimar06ae6832016-08-12 09:07:57 +0000390 for (const std::unique_ptr<BaseCommand> &Base : OutCmd.Commands) {
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000391 auto *Cmd = dyn_cast<InputSectionDescription>(Base.get());
392 if (!Cmd)
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000393 continue;
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000394 computeInputSections(Cmd);
Rafael Espindolac404d502017-02-23 02:32:18 +0000395 for (InputSectionBase *S : Cmd->Sections)
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000396 Ret.push_back(static_cast<InputSectionBase *>(S));
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000397 }
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000398
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000399 return Ret;
400}
401
George Rimara8dba482017-03-20 10:09:58 +0000402void LinkerScriptBase::processCommands(OutputSectionFactory &Factory) {
Rafael Espindola5616adf2017-03-08 22:36:28 +0000403 // A symbol can be assigned before any section is mentioned in the linker
404 // script. In an DSO, the symbol values are addresses, so the only important
405 // section values are:
406 // * SHN_UNDEF
407 // * SHN_ABS
408 // * Any value meaning a regular section.
409 // To handle that, create a dummy aether section that fills the void before
410 // the linker scripts switches to another section. It has an index of one
411 // which will map to whatever the first actual section is.
412 Aether = make<OutputSection>("", 0, SHF_ALLOC);
413 Aether->SectionIndex = 1;
414 CurOutSec = Aether;
Rafael Espindola49592cf2017-03-20 14:33:33 +0000415 Dot = 0;
Rafael Espindola5616adf2017-03-08 22:36:28 +0000416
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000417 for (unsigned I = 0; I < Opt.Commands.size(); ++I) {
418 auto Iter = Opt.Commands.begin() + I;
419 const std::unique_ptr<BaseCommand> &Base1 = *Iter;
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000420
421 // Handle symbol assignments outside of any output section.
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000422 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base1.get())) {
Rafael Espindola4cd73522017-02-17 16:01:51 +0000423 addSymbol(Cmd);
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000424 continue;
425 }
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000426
Eugene Leviantceabe802016-08-11 07:56:43 +0000427 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000428 std::vector<InputSectionBase *> V = createInputSectionList(*Cmd);
Rafael Espindola7bd37872016-09-12 16:05:16 +0000429
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000430 // The output section name `/DISCARD/' is special.
431 // Any input section assigned to it is discarded.
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000432 if (Cmd->Name == "/DISCARD/") {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000433 discard(V);
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000434 continue;
435 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000436
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000437 // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive
438 // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input
439 // sections satisfy a given constraint. If not, a directive is handled
440 // as if it wasn't present from the beginning.
441 //
442 // Because we'll iterate over Commands many more times, the easiest
443 // way to "make it as if it wasn't present" is to just remove it.
George Rimarf7f0d082017-03-14 11:23:33 +0000444 if (!matchConstraints(V, Cmd->Constraint)) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000445 for (InputSectionBase *S : V)
Rui Ueyamaf94efdd2016-11-20 23:15:52 +0000446 S->Assigned = false;
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000447 Opt.Commands.erase(Iter);
George Rimardfbbbc82016-09-17 09:50:10 +0000448 --I;
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000449 continue;
450 }
451
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000452 // A directive may contain symbol definitions like this:
453 // ".foo : { ...; bar = .; }". Handle them.
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000454 for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
455 if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base.get()))
Rafael Espindola4cd73522017-02-17 16:01:51 +0000456 addSymbol(OutCmd);
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000457
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000458 // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign
459 // is given, input sections are aligned to that value, whether the
460 // given value is larger or smaller than the original section alignment.
461 if (Cmd->SubalignExpr) {
Rafael Espindola72dc1952017-03-17 13:05:04 +0000462 uint32_t Subalign = Cmd->SubalignExpr().getValue();
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000463 for (InputSectionBase *S : V)
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000464 S->Alignment = Subalign;
George Rimardb24d9c2016-08-19 15:18:23 +0000465 }
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000466
467 // Add input sections to an output section.
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000468 for (InputSectionBase *S : V)
George Rimare21c3af2017-03-14 09:30:25 +0000469 Factory.addInputSec(S, Cmd->Name);
Eugene Leviantceabe802016-08-11 07:56:43 +0000470 }
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000471 }
Rafael Espindola5616adf2017-03-08 22:36:28 +0000472 CurOutSec = nullptr;
Eugene Leviant20d03192016-09-16 15:30:47 +0000473}
Eugene Leviante63d81b2016-07-20 14:43:20 +0000474
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000475// Add sections that didn't match any sections command.
George Rimara2a1ef12017-03-14 12:03:34 +0000476void LinkerScriptBase::addOrphanSections(OutputSectionFactory &Factory) {
Rui Ueyama536a2672017-02-27 02:32:08 +0000477 for (InputSectionBase *S : InputSections)
Rafael Espindola8f9026b2016-11-08 18:23:02 +0000478 if (S->Live && !S->OutSec)
George Rimare21c3af2017-03-14 09:30:25 +0000479 Factory.addInputSec(S, getOutputSectionName(S->Name));
Eugene Leviante63d81b2016-07-20 14:43:20 +0000480}
481
George Rimarf7f0d082017-03-14 11:23:33 +0000482static bool isTbss(OutputSection *Sec) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000483 return (Sec->Flags & SHF_TLS) && Sec->Type == SHT_NOBITS;
Rafael Espindolaa940e532016-09-22 12:35:44 +0000484}
485
George Rimara2a1ef12017-03-14 12:03:34 +0000486void LinkerScriptBase::output(InputSection *S) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000487 if (!AlreadyOutputIS.insert(S).second)
488 return;
George Rimarf7f0d082017-03-14 11:23:33 +0000489 bool IsTbss = isTbss(CurOutSec);
Eugene Leviant20889c52016-08-31 08:13:33 +0000490
George Rimar0c1c8082017-03-14 10:00:19 +0000491 uint64_t Pos = IsTbss ? Dot + ThreadBssOffset : Dot;
Rafael Espindolad3190792016-09-16 15:10:23 +0000492 Pos = alignTo(Pos, S->Alignment);
Rafael Espindola04a2e342016-11-09 01:42:41 +0000493 S->OutSecOff = Pos - CurOutSec->Addr;
Rafael Espindola76b6bd32017-03-08 15:44:30 +0000494 Pos += S->getSize();
Rafael Espindolad3190792016-09-16 15:10:23 +0000495
496 // Update output section size after adding each section. This is so that
497 // SIZEOF works correctly in the case below:
498 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
Rafael Espindola04a2e342016-11-09 01:42:41 +0000499 CurOutSec->Size = Pos - CurOutSec->Addr;
Rafael Espindolad3190792016-09-16 15:10:23 +0000500
Meador Ingeb8897442017-01-24 02:34:00 +0000501 // If there is a memory region associated with this input section, then
502 // place the section in that region and update the region index.
503 if (CurMemRegion) {
504 CurMemRegion->Offset += CurOutSec->Size;
505 uint64_t CurSize = CurMemRegion->Offset - CurMemRegion->Origin;
506 if (CurSize > CurMemRegion->Length) {
507 uint64_t OverflowAmt = CurSize - CurMemRegion->Length;
508 error("section '" + CurOutSec->Name + "' will not fit in region '" +
509 CurMemRegion->Name + "': overflowed by " + Twine(OverflowAmt) +
510 " bytes");
511 }
512 }
513
Rafael Espindola7252ae52016-09-22 12:00:08 +0000514 if (IsTbss)
515 ThreadBssOffset = Pos - Dot;
516 else
Rafael Espindolad3190792016-09-16 15:10:23 +0000517 Dot = Pos;
518}
519
George Rimara2a1ef12017-03-14 12:03:34 +0000520void LinkerScriptBase::flush() {
Rafael Espindolabd12e2a2017-03-01 14:12:21 +0000521 assert(CurOutSec);
522 if (!AlreadyOutputOS.insert(CurOutSec).second)
Rafael Espindola65499b92016-09-23 20:10:47 +0000523 return;
Rafael Espindola24e6f362017-02-24 15:07:30 +0000524 for (InputSection *I : CurOutSec->Sections)
525 output(I);
Eugene Leviant20889c52016-08-31 08:13:33 +0000526}
527
George Rimara2a1ef12017-03-14 12:03:34 +0000528void LinkerScriptBase::switchTo(OutputSection *Sec) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000529 if (CurOutSec == Sec)
530 return;
531 if (AlreadyOutputOS.count(Sec))
532 return;
533
Rafael Espindolad3190792016-09-16 15:10:23 +0000534 CurOutSec = Sec;
535
Rafael Espindola37707632017-03-07 14:55:52 +0000536 Dot = alignTo(Dot, CurOutSec->Alignment);
George Rimarf7f0d082017-03-14 11:23:33 +0000537 CurOutSec->Addr = isTbss(CurOutSec) ? Dot + ThreadBssOffset : Dot;
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000538
539 // If neither AT nor AT> is specified for an allocatable section, the linker
540 // will set the LMA such that the difference between VMA and LMA for the
541 // section is the same as the preceding output section in the same region
542 // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
George Rimar21467872017-02-23 07:57:55 +0000543 if (LMAOffset)
Rafael Espindola29c1afb2017-02-24 14:34:12 +0000544 CurOutSec->LMAOffset = LMAOffset();
Rafael Espindolad3190792016-09-16 15:10:23 +0000545}
546
George Rimara2a1ef12017-03-14 12:03:34 +0000547void LinkerScriptBase::process(BaseCommand &Base) {
George Rimare38cbab2016-09-26 19:22:50 +0000548 // This handles the assignments to symbol or to a location counter (.)
Rafael Espindolad3190792016-09-16 15:10:23 +0000549 if (auto *AssignCmd = dyn_cast<SymbolAssignment>(&Base)) {
Rafael Espindola4cd73522017-02-17 16:01:51 +0000550 assignSymbol(AssignCmd, true);
Eugene Leviantceabe802016-08-11 07:56:43 +0000551 return;
Rui Ueyama2de509c2016-08-12 00:55:08 +0000552 }
George Rimare38cbab2016-09-26 19:22:50 +0000553
554 // Handle BYTE(), SHORT(), LONG(), or QUAD().
555 if (auto *DataCmd = dyn_cast<BytesDataCommand>(&Base)) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000556 DataCmd->Offset = Dot - CurOutSec->Addr;
George Rimare38cbab2016-09-26 19:22:50 +0000557 Dot += DataCmd->Size;
Rafael Espindola04a2e342016-11-09 01:42:41 +0000558 CurOutSec->Size = Dot - CurOutSec->Addr;
George Rimare38cbab2016-09-26 19:22:50 +0000559 return;
560 }
561
Meador Ingeb2d99d62016-11-22 18:01:50 +0000562 if (auto *AssertCmd = dyn_cast<AssertCommand>(&Base)) {
Rafael Espindola4595df92017-03-10 16:04:26 +0000563 AssertCmd->Expression();
Meador Ingeb2d99d62016-11-22 18:01:50 +0000564 return;
565 }
566
George Rimare38cbab2016-09-26 19:22:50 +0000567 // It handles single input section description command,
568 // calculates and assigns the offsets for each section and also
569 // updates the output section size.
Rafael Espindolad3190792016-09-16 15:10:23 +0000570 auto &ICmd = cast<InputSectionDescription>(Base);
Rafael Espindolabd12e2a2017-03-01 14:12:21 +0000571 for (InputSectionBase *IB : ICmd.Sections) {
George Rimar3fb5a6d2016-11-29 16:05:27 +0000572 // We tentatively added all synthetic sections at the beginning and removed
573 // empty ones afterwards (because there is no way to know whether they were
574 // going be empty or not other than actually running linker scripts.)
575 // We need to ignore remains of empty sections.
Rafael Espindolabd12e2a2017-03-01 14:12:21 +0000576 if (auto *Sec = dyn_cast<SyntheticSection>(IB))
George Rimar3fb5a6d2016-11-29 16:05:27 +0000577 if (Sec->empty())
578 continue;
579
George Rimar78ef6452017-02-21 15:46:43 +0000580 if (!IB->Live)
581 continue;
Rafael Espindolabedccb5e2017-03-01 14:21:31 +0000582 assert(CurOutSec == IB->OutSec || AlreadyOutputOS.count(IB->OutSec));
Rafael Espindolabd12e2a2017-03-01 14:12:21 +0000583 output(cast<InputSection>(IB));
Eugene Leviantceabe802016-08-11 07:56:43 +0000584 }
585}
586
Rafael Espindola24e6f362017-02-24 15:07:30 +0000587static OutputSection *
588findSection(StringRef Name, const std::vector<OutputSection *> &Sections) {
Rafael Espindola2b074552017-02-03 22:27:05 +0000589 auto End = Sections.end();
Rafael Espindola24e6f362017-02-24 15:07:30 +0000590 auto HasName = [=](OutputSection *Sec) { return Sec->Name == Name; };
Rafael Espindola2b074552017-02-03 22:27:05 +0000591 auto I = std::find_if(Sections.begin(), End, HasName);
Rafael Espindola24e6f362017-02-24 15:07:30 +0000592 std::vector<OutputSection *> Ret;
Rafael Espindola2b074552017-02-03 22:27:05 +0000593 if (I == End)
594 return nullptr;
595 assert(std::find_if(I + 1, End, HasName) == End);
596 return *I;
George Rimar8f66df92016-08-12 20:38:20 +0000597}
598
Meador Ingeb8897442017-01-24 02:34:00 +0000599// This function searches for a memory region to place the given output
600// section in. If found, a pointer to the appropriate memory region is
601// returned. Otherwise, a nullptr is returned.
George Rimara2a1ef12017-03-14 12:03:34 +0000602MemoryRegion *LinkerScriptBase::findMemoryRegion(OutputSectionCommand *Cmd,
603 OutputSection *Sec) {
Meador Ingeb8897442017-01-24 02:34:00 +0000604 // If a memory region name was specified in the output section command,
605 // then try to find that region first.
606 if (!Cmd->MemoryRegionName.empty()) {
607 auto It = Opt.MemoryRegions.find(Cmd->MemoryRegionName);
608 if (It != Opt.MemoryRegions.end())
609 return &It->second;
610 error("memory region '" + Cmd->MemoryRegionName + "' not declared");
611 return nullptr;
612 }
613
614 // The memory region name is empty, thus a suitable region must be
615 // searched for in the region map. If the region map is empty, just
616 // return. Note that this check doesn't happen at the very beginning
617 // so that uses of undeclared regions can be caught.
618 if (!Opt.MemoryRegions.size())
619 return nullptr;
620
621 // See if a region can be found by matching section flags.
622 for (auto &MRI : Opt.MemoryRegions) {
623 MemoryRegion &MR = MRI.second;
Rui Ueyama8a8a9532017-01-26 02:58:59 +0000624 if ((MR.Flags & Sec->Flags) != 0 && (MR.NegFlags & Sec->Flags) == 0)
Meador Ingeb8897442017-01-24 02:34:00 +0000625 return &MR;
626 }
627
628 // Otherwise, no suitable region was found.
629 if (Sec->Flags & SHF_ALLOC)
630 error("no memory region specified for section '" + Sec->Name + "'");
631 return nullptr;
632}
633
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000634// This function assigns offsets to input sections and an output section
635// for a single sections command (e.g. ".text { *(.text); }").
George Rimara2a1ef12017-03-14 12:03:34 +0000636void LinkerScriptBase::assignOffsets(OutputSectionCommand *Cmd) {
George Rimar23e6a022017-03-14 11:31:28 +0000637 OutputSection *Sec = findSection(Cmd->Name, *OutputSections);
Rafael Espindola2b074552017-02-03 22:27:05 +0000638 if (!Sec)
Rafael Espindolad3190792016-09-16 15:10:23 +0000639 return;
Meador Ingeb8897442017-01-24 02:34:00 +0000640
Rafael Espindola679828f2017-02-17 16:26:13 +0000641 if (Cmd->AddrExpr && Sec->Flags & SHF_ALLOC)
George Rimar2ee2d2d2017-02-21 14:50:38 +0000642 setDot(Cmd->AddrExpr, Cmd->Location);
Rafael Espindola679828f2017-02-17 16:26:13 +0000643
Eugene Leviant5784e962017-03-14 08:57:09 +0000644 if (Cmd->LMAExpr) {
George Rimar0c1c8082017-03-14 10:00:19 +0000645 uint64_t D = Dot;
Rafael Espindola72dc1952017-03-17 13:05:04 +0000646 LMAOffset = [=] { return Cmd->LMAExpr().getValue() - D; };
Eugene Leviant5784e962017-03-14 08:57:09 +0000647 }
648
Petr Hosek165088a2017-02-07 23:42:31 +0000649 // Handle align (e.g. ".foo : ALIGN(16) { ... }").
650 if (Cmd->AlignExpr)
Rafael Espindola72dc1952017-03-17 13:05:04 +0000651 Sec->updateAlignment(Cmd->AlignExpr().getValue());
Petr Hosek165088a2017-02-07 23:42:31 +0000652
Meador Ingeb8897442017-01-24 02:34:00 +0000653 // Try and find an appropriate memory region to assign offsets in.
654 CurMemRegion = findMemoryRegion(Cmd, Sec);
655 if (CurMemRegion)
656 Dot = CurMemRegion->Offset;
657 switchTo(Sec);
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000658
Rafael Espindolad3190792016-09-16 15:10:23 +0000659 // Find the last section output location. We will output orphan sections
660 // there so that end symbols point to the correct location.
661 auto E = std::find_if(Cmd->Commands.rbegin(), Cmd->Commands.rend(),
662 [](const std::unique_ptr<BaseCommand> &Cmd) {
663 return !isa<SymbolAssignment>(*Cmd);
664 })
665 .base();
666 for (auto I = Cmd->Commands.begin(); I != E; ++I)
667 process(**I);
Rafael Espindola65499b92016-09-23 20:10:47 +0000668 flush();
George Rimarb31dd372016-09-19 13:27:31 +0000669 std::for_each(E, Cmd->Commands.end(),
670 [this](std::unique_ptr<BaseCommand> &B) { process(*B.get()); });
Rafael Espindolad3190792016-09-16 15:10:23 +0000671}
672
George Rimara2a1ef12017-03-14 12:03:34 +0000673void LinkerScriptBase::removeEmptyCommands() {
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000674 // It is common practice to use very generic linker scripts. So for any
675 // given run some of the output sections in the script will be empty.
676 // We could create corresponding empty output sections, but that would
677 // clutter the output.
678 // We instead remove trivially empty sections. The bfd linker seems even
679 // more aggressive at removing them.
680 auto Pos = std::remove_if(
681 Opt.Commands.begin(), Opt.Commands.end(),
682 [&](const std::unique_ptr<BaseCommand> &Base) {
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000683 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
George Rimar23e6a022017-03-14 11:31:28 +0000684 return !findSection(Cmd->Name, *OutputSections);
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000685 return false;
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000686 });
687 Opt.Commands.erase(Pos, Opt.Commands.end());
Rafael Espindola07fe6122016-11-14 14:23:35 +0000688}
689
Rafael Espindola6a537372016-11-14 14:33:49 +0000690static bool isAllSectionDescription(const OutputSectionCommand &Cmd) {
691 for (const std::unique_ptr<BaseCommand> &I : Cmd.Commands)
692 if (!isa<InputSectionDescription>(*I))
693 return false;
694 return true;
695}
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000696
George Rimara2a1ef12017-03-14 12:03:34 +0000697void LinkerScriptBase::adjustSectionsBeforeSorting() {
Rafael Espindola9546fff2016-09-22 14:40:50 +0000698 // If the output section contains only symbol assignments, create a
699 // corresponding output section. The bfd linker seems to only create them if
700 // '.' is assigned to, but creating these section should not have any bad
701 // consequeces and gives us a section to put the symbol in.
George Rimar0c1c8082017-03-14 10:00:19 +0000702 uint64_t Flags = SHF_ALLOC;
Rafael Espindolaf93b8c22016-11-26 06:55:35 +0000703 uint32_t Type = SHT_NOBITS;
Rafael Espindola9546fff2016-09-22 14:40:50 +0000704 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
705 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
706 if (!Cmd)
707 continue;
George Rimar23e6a022017-03-14 11:31:28 +0000708 if (OutputSection *Sec = findSection(Cmd->Name, *OutputSections)) {
Rafael Espindola2b074552017-02-03 22:27:05 +0000709 Flags = Sec->Flags;
710 Type = Sec->Type;
Rafael Espindola9546fff2016-09-22 14:40:50 +0000711 continue;
712 }
713
Rafael Espindola6a537372016-11-14 14:33:49 +0000714 if (isAllSectionDescription(*Cmd))
715 continue;
716
Rafael Espindola24e6f362017-02-24 15:07:30 +0000717 auto *OutSec = make<OutputSection>(Cmd->Name, Type, Flags);
Rafael Espindola9546fff2016-09-22 14:40:50 +0000718 OutputSections->push_back(OutSec);
719 }
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000720}
721
George Rimara2a1ef12017-03-14 12:03:34 +0000722void LinkerScriptBase::adjustSectionsAfterSorting() {
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000723 placeOrphanSections();
724
725 // If output section command doesn't specify any segments,
726 // and we haven't previously assigned any section to segment,
727 // then we simply assign section to the very first load segment.
728 // Below is an example of such linker script:
729 // PHDRS { seg PT_LOAD; }
730 // SECTIONS { .aaa : { *(.aaa) } }
731 std::vector<StringRef> DefPhdrs;
732 auto FirstPtLoad =
733 std::find_if(Opt.PhdrsCommands.begin(), Opt.PhdrsCommands.end(),
734 [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; });
735 if (FirstPtLoad != Opt.PhdrsCommands.end())
736 DefPhdrs.push_back(FirstPtLoad->Name);
737
738 // Walk the commands and propagate the program headers to commands that don't
739 // explicitly specify them.
740 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
741 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
742 if (!Cmd)
743 continue;
744 if (Cmd->Phdrs.empty())
745 Cmd->Phdrs = DefPhdrs;
746 else
747 DefPhdrs = Cmd->Phdrs;
748 }
Rafael Espindola6a537372016-11-14 14:33:49 +0000749
750 removeEmptyCommands();
Rafael Espindola9546fff2016-09-22 14:40:50 +0000751}
752
Rafael Espindola15c57952016-09-22 18:05:49 +0000753// When placing orphan sections, we want to place them after symbol assignments
754// so that an orphan after
755// begin_foo = .;
756// foo : { *(foo) }
757// end_foo = .;
758// doesn't break the intended meaning of the begin/end symbols.
759// We don't want to go over sections since Writer<ELFT>::sortSections is the
760// one in charge of deciding the order of the sections.
761// We don't want to go over alignments, since doing so in
762// rx_sec : { *(rx_sec) }
763// . = ALIGN(0x1000);
764// /* The RW PT_LOAD starts here*/
765// rw_sec : { *(rw_sec) }
766// would mean that the RW PT_LOAD would become unaligned.
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000767static bool shouldSkip(const BaseCommand &Cmd) {
Rafael Espindola15c57952016-09-22 18:05:49 +0000768 if (isa<OutputSectionCommand>(Cmd))
769 return false;
770 const auto *Assign = dyn_cast<SymbolAssignment>(&Cmd);
771 if (!Assign)
772 return true;
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000773 return Assign->Name != ".";
Rafael Espindola15c57952016-09-22 18:05:49 +0000774}
775
Rui Ueyama6697ec22017-02-02 23:26:12 +0000776// Orphan sections are sections present in the input files which are
777// not explicitly placed into the output file by the linker script.
778//
779// When the control reaches this function, Opt.Commands contains
780// output section commands for non-orphan sections only. This function
781// adds new elements for orphan sections to Opt.Commands so that all
782// sections are explicitly handled by Opt.Commands.
783//
784// Writer<ELFT>::sortSections has already sorted output sections.
785// What we need to do is to scan OutputSections vector and
786// Opt.Commands in parallel to find orphan sections. If there is an
787// output section that doesn't have a corresponding entry in
788// Opt.Commands, we will insert a new entry to Opt.Commands.
789//
790// There is some ambiguity as to where exactly a new entry should be
791// inserted, because Opt.Commands contains not only output section
792// commands but other types of commands such as symbol assignment
793// expressions. There's no correct answer here due to the lack of the
794// formal specification of the linker script. We use heuristics to
795// determine whether a new output command should be added before or
796// after another commands. For the details, look at shouldSkip
797// function.
George Rimara2a1ef12017-03-14 12:03:34 +0000798void LinkerScriptBase::placeOrphanSections() {
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000799 // The OutputSections are already in the correct order.
800 // This loops creates or moves commands as needed so that they are in the
801 // correct order.
802 int CmdIndex = 0;
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000803
804 // As a horrible special case, skip the first . assignment if it is before any
805 // section. We do this because it is common to set a load address by starting
806 // the script with ". = 0xabcd" and the expectation is that every section is
807 // after that.
808 auto FirstSectionOrDotAssignment =
809 std::find_if(Opt.Commands.begin(), Opt.Commands.end(),
810 [](const std::unique_ptr<BaseCommand> &Cmd) {
811 if (isa<OutputSectionCommand>(*Cmd))
812 return true;
813 const auto *Assign = dyn_cast<SymbolAssignment>(Cmd.get());
814 if (!Assign)
815 return false;
816 return Assign->Name == ".";
817 });
818 if (FirstSectionOrDotAssignment != Opt.Commands.end()) {
819 CmdIndex = FirstSectionOrDotAssignment - Opt.Commands.begin();
820 if (isa<SymbolAssignment>(**FirstSectionOrDotAssignment))
821 ++CmdIndex;
822 }
823
Rafael Espindola24e6f362017-02-24 15:07:30 +0000824 for (OutputSection *Sec : *OutputSections) {
Rafael Espindola40849412017-02-24 14:28:00 +0000825 StringRef Name = Sec->Name;
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000826
827 // Find the last spot where we can insert a command and still get the
Rafael Espindola15c57952016-09-22 18:05:49 +0000828 // correct result.
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000829 auto CmdIter = Opt.Commands.begin() + CmdIndex;
830 auto E = Opt.Commands.end();
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000831 while (CmdIter != E && shouldSkip(**CmdIter)) {
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000832 ++CmdIter;
833 ++CmdIndex;
834 }
835
836 auto Pos =
837 std::find_if(CmdIter, E, [&](const std::unique_ptr<BaseCommand> &Base) {
838 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
839 return Cmd && Cmd->Name == Name;
840 });
841 if (Pos == E) {
842 Opt.Commands.insert(CmdIter,
843 llvm::make_unique<OutputSectionCommand>(Name));
Rafael Espindola15c57952016-09-22 18:05:49 +0000844 ++CmdIndex;
845 continue;
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000846 }
Rafael Espindola15c57952016-09-22 18:05:49 +0000847
848 // Continue from where we found it.
849 CmdIndex = (Pos - Opt.Commands.begin()) + 1;
George Rimar652852c2016-04-16 10:10:32 +0000850 }
Rafael Espindola337f9032016-11-14 14:13:32 +0000851}
852
Petr Hosek02ad5162017-03-15 03:33:23 +0000853void LinkerScriptBase::processNonSectionCommands() {
854 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
855 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get()))
856 assignSymbol(Cmd);
857 else if (auto *Cmd = dyn_cast<AssertCommand>(Base.get()))
858 Cmd->Expression();
859 }
860}
861
George Rimara2a1ef12017-03-14 12:03:34 +0000862void LinkerScriptBase::assignAddresses(std::vector<PhdrEntry> &Phdrs) {
Rui Ueyama7c18c282016-04-18 21:00:40 +0000863 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rafael Espindolabe607332016-09-30 00:16:11 +0000864 Dot = 0;
Rafael Espindola72dc1952017-03-17 13:05:04 +0000865 ErrorOnMissingSection = true;
Rafael Espindola06f47432017-02-06 22:21:46 +0000866 switchTo(Aether);
867
George Rimar076fe152016-07-21 06:43:01 +0000868 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
869 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
Rafael Espindola4cd73522017-02-17 16:01:51 +0000870 assignSymbol(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000871 continue;
872 }
873
George Rimareefa7582016-08-04 09:29:31 +0000874 if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
Rafael Espindola4595df92017-03-10 16:04:26 +0000875 Cmd->Expression();
George Rimareefa7582016-08-04 09:29:31 +0000876 continue;
877 }
878
George Rimar076fe152016-07-21 06:43:01 +0000879 auto *Cmd = cast<OutputSectionCommand>(Base.get());
Rafael Espindolad3190792016-09-16 15:10:23 +0000880 assignOffsets(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000881 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000882
George Rimar0c1c8082017-03-14 10:00:19 +0000883 uint64_t MinVA = std::numeric_limits<uint64_t>::max();
Rafael Espindola24e6f362017-02-24 15:07:30 +0000884 for (OutputSection *Sec : *OutputSections) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000885 if (Sec->Flags & SHF_ALLOC)
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000886 MinVA = std::min<uint64_t>(MinVA, Sec->Addr);
Rafael Espindolaea590d92017-02-08 15:19:03 +0000887 else
888 Sec->Addr = 0;
889 }
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000890
George Rimar2d262102017-03-14 09:03:53 +0000891 allocateHeaders(Phdrs, *OutputSections, MinVA);
George Rimar652852c2016-04-16 10:10:32 +0000892}
893
Rui Ueyama464daad2016-08-22 04:55:20 +0000894// Creates program headers as instructed by PHDRS linker script command.
George Rimara2a1ef12017-03-14 12:03:34 +0000895std::vector<PhdrEntry> LinkerScriptBase::createPhdrs() {
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000896 std::vector<PhdrEntry> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000897
Rui Ueyama464daad2016-08-22 04:55:20 +0000898 // Process PHDRS and FILEHDR keywords because they are not
899 // real output sections and cannot be added in the following loop.
Eugene Leviantbbe38602016-07-19 09:25:43 +0000900 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000901 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000902 PhdrEntry &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000903
904 if (Cmd.HasFilehdr)
Rui Ueyama9d1bacb12017-02-27 02:31:26 +0000905 Phdr.add(Out::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000906 if (Cmd.HasPhdrs)
Rui Ueyama9d1bacb12017-02-27 02:31:26 +0000907 Phdr.add(Out::ProgramHeaders);
Eugene Leviant56b21c82016-09-09 09:46:16 +0000908
909 if (Cmd.LMAExpr) {
Rafael Espindola72dc1952017-03-17 13:05:04 +0000910 Phdr.p_paddr = Cmd.LMAExpr().getValue();
Eugene Leviant56b21c82016-09-09 09:46:16 +0000911 Phdr.HasLMA = true;
912 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000913 }
914
Rui Ueyama464daad2016-08-22 04:55:20 +0000915 // Add output sections to program headers.
Rafael Espindola24e6f362017-02-24 15:07:30 +0000916 for (OutputSection *Sec : *OutputSections) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000917 if (!(Sec->Flags & SHF_ALLOC))
Eugene Leviantbbe38602016-07-19 09:25:43 +0000918 break;
919
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000920 // Assign headers specified by linker script
Rafael Espindola40849412017-02-24 14:28:00 +0000921 for (size_t Id : getPhdrIndices(Sec->Name)) {
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000922 Ret[Id].add(Sec);
923 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000924 Ret[Id].p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000925 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000926 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000927 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000928}
929
George Rimara2a1ef12017-03-14 12:03:34 +0000930bool LinkerScriptBase::ignoreInterpSection() {
Eugene Leviantf9bc3bd2016-08-16 06:40:58 +0000931 // Ignore .interp section in case we have PHDRS specification
932 // and PT_INTERP isn't listed.
933 return !Opt.PhdrsCommands.empty() &&
934 llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
935 return Cmd.Type == PT_INTERP;
936 }) == Opt.PhdrsCommands.end();
937}
938
George Rimara2a1ef12017-03-14 12:03:34 +0000939uint32_t LinkerScriptBase::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000940 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
941 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
942 if (Cmd->Name == Name)
943 return Cmd->Filler;
Rui Ueyama16068ae2016-11-19 18:05:56 +0000944 return 0;
George Rimare2ee72b2016-02-26 14:48:31 +0000945}
946
George Rimare38cbab2016-09-26 19:22:50 +0000947static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) {
George Rimarb17d16a2017-03-20 10:16:57 +0000948 const endianness E = Config->IsLE ? endianness::little : endianness::big;
George Rimare38cbab2016-09-26 19:22:50 +0000949
950 switch (Size) {
951 case 1:
952 *Buf = (uint8_t)Data;
953 break;
954 case 2:
George Rimara8dba482017-03-20 10:09:58 +0000955 write16(Buf, Data, E);
George Rimare38cbab2016-09-26 19:22:50 +0000956 break;
957 case 4:
George Rimara8dba482017-03-20 10:09:58 +0000958 write32(Buf, Data, E);
George Rimare38cbab2016-09-26 19:22:50 +0000959 break;
960 case 8:
George Rimara8dba482017-03-20 10:09:58 +0000961 write64(Buf, Data, E);
George Rimare38cbab2016-09-26 19:22:50 +0000962 break;
963 default:
964 llvm_unreachable("unsupported Size argument");
965 }
966}
967
George Rimara8dba482017-03-20 10:09:58 +0000968void LinkerScriptBase::writeDataBytes(StringRef Name, uint8_t *Buf) {
George Rimare38cbab2016-09-26 19:22:50 +0000969 int I = getSectionIndex(Name);
970 if (I == INT_MAX)
971 return;
972
Rui Ueyama6e68c5e2016-11-19 18:05:58 +0000973 auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I].get());
974 for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
975 if (auto *Data = dyn_cast<BytesDataCommand>(Base.get()))
George Rimara8dba482017-03-20 10:09:58 +0000976 writeInt(Buf + Data->Offset, Data->Expression().getValue(), Data->Size);
George Rimare38cbab2016-09-26 19:22:50 +0000977}
978
George Rimara2a1ef12017-03-14 12:03:34 +0000979bool LinkerScriptBase::hasLMA(StringRef Name) {
George Rimar8ceadb32016-08-17 07:44:19 +0000980 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
981 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000982 if (Cmd->LMAExpr && Cmd->Name == Name)
983 return true;
984 return false;
George Rimar8ceadb32016-08-17 07:44:19 +0000985}
986
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000987// Returns the index of the given section name in linker script
988// SECTIONS commands. Sections are laid out as the same order as they
989// were in the script. If a given name did not appear in the script,
990// it returns INT_MAX, so that it will be laid out at end of file.
George Rimara2a1ef12017-03-14 12:03:34 +0000991int LinkerScriptBase::getSectionIndex(StringRef Name) {
Rui Ueyama6e68c5e2016-11-19 18:05:58 +0000992 for (int I = 0, E = Opt.Commands.size(); I != E; ++I)
993 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I].get()))
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000994 if (Cmd->Name == Name)
995 return I;
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000996 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000997}
998
George Rimara8dba482017-03-20 10:09:58 +0000999ExprValue LinkerScriptBase::getSymbolValue(const Twine &Loc, StringRef S) {
Rafael Espindola4595df92017-03-10 16:04:26 +00001000 if (S == ".")
Rafael Espindola72dc1952017-03-17 13:05:04 +00001001 return {CurOutSec, Dot - CurOutSec->Addr};
George Rimara8dba482017-03-20 10:09:58 +00001002 if (SymbolBody *B = findSymbol(S)) {
Rafael Espindola72dc1952017-03-17 13:05:04 +00001003 if (auto *D = dyn_cast<DefinedRegular>(B))
1004 return {D->Section, D->Value};
1005 auto *C = cast<DefinedCommon>(B);
George Rimara8dba482017-03-20 10:09:58 +00001006 return {InX::Common, C->Offset};
Rafael Espindola72dc1952017-03-17 13:05:04 +00001007 }
Eugene Leviantf6aeed32016-12-22 13:13:12 +00001008 error(Loc + ": symbol not found: " + S);
George Rimar884e7862016-09-08 08:19:13 +00001009 return 0;
1010}
1011
George Rimara8dba482017-03-20 10:09:58 +00001012bool LinkerScriptBase::isDefined(StringRef S) {
1013 return findSymbol(S) != nullptr;
George Rimarf34f45f2016-09-23 13:17:23 +00001014}
1015
Eugene Leviantbbe38602016-07-19 09:25:43 +00001016// Returns indices of ELF headers containing specific section, identified
1017// by Name. Each index is a zero based number of ELF header listed within
1018// PHDRS {} script block.
George Rimara2a1ef12017-03-14 12:03:34 +00001019std::vector<size_t> LinkerScriptBase::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +00001020 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
1021 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +00001022 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +00001023 continue;
1024
Rui Ueyama29c5a2a2016-07-26 00:27:36 +00001025 std::vector<size_t> Ret;
1026 for (StringRef PhdrName : Cmd->Phdrs)
Eugene Leviant2a942c42016-12-05 16:38:32 +00001027 Ret.push_back(getPhdrIndex(Cmd->Location, PhdrName));
Rui Ueyama29c5a2a2016-07-26 00:27:36 +00001028 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001029 }
George Rimar31d842f2016-07-20 16:43:03 +00001030 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +00001031}
1032
George Rimara2a1ef12017-03-14 12:03:34 +00001033size_t LinkerScriptBase::getPhdrIndex(const Twine &Loc, StringRef PhdrName) {
Rui Ueyama29c5a2a2016-07-26 00:27:36 +00001034 size_t I = 0;
1035 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
1036 if (Cmd.Name == PhdrName)
1037 return I;
1038 ++I;
1039 }
Eugene Leviant2a942c42016-12-05 16:38:32 +00001040 error(Loc + ": section header '" + PhdrName + "' is not listed in PHDRS");
Rui Ueyama29c5a2a2016-07-26 00:27:36 +00001041 return 0;
1042}
1043
Rui Ueyama794366a2017-02-14 04:47:05 +00001044class elf::ScriptParser final : public ScriptLexer {
George Rimarc3794e52016-02-24 09:21:47 +00001045 typedef void (ScriptParser::*Handler)();
1046
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001047public:
Rui Ueyama22375f22016-11-25 18:51:54 +00001048 ScriptParser(MemoryBufferRef MB)
Rui Ueyama794366a2017-02-14 04:47:05 +00001049 : ScriptLexer(MB),
Rui Ueyama22375f22016-11-25 18:51:54 +00001050 IsUnderSysroot(isUnderSysroot(MB.getBufferIdentifier())) {}
George Rimarf23b2322016-02-19 10:45:45 +00001051
George Rimar20b65982016-08-31 09:08:26 +00001052 void readLinkerScript();
1053 void readVersionScript();
Rafael Espindolad0ebd842016-12-08 17:54:26 +00001054 void readDynamicList();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001055
1056private:
Rui Ueyama52a15092015-10-11 03:28:42 +00001057 void addFile(StringRef Path);
1058
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001059 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +00001060 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +00001061 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001062 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001063 void readInclude();
Meador Ingeb8897442017-01-24 02:34:00 +00001064 void readMemory();
Rui Ueyamaee592822015-10-07 00:25:09 +00001065 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +00001066 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001067 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +00001068 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +00001069 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001070 void readSections();
Rui Ueyama95769b42016-08-31 20:03:54 +00001071 void readVersion();
1072 void readVersionScriptCommand();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001073
Rui Ueyama113cdec2016-07-24 23:05:57 +00001074 SymbolAssignment *readAssignment(StringRef Name);
George Rimare38cbab2016-09-26 19:22:50 +00001075 BytesDataCommand *readBytesDataCommand(StringRef Tok);
Rui Ueyama16068ae2016-11-19 18:05:56 +00001076 uint32_t readFill();
Rui Ueyama10416562016-08-04 02:03:27 +00001077 OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
Rui Ueyama16068ae2016-11-19 18:05:56 +00001078 uint32_t readOutputSectionFiller(StringRef Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001079 std::vector<StringRef> readOutputSectionPhdrs();
George Rimara2496cb2016-08-30 09:46:59 +00001080 InputSectionDescription *readInputSectionDescription(StringRef Tok);
Eugene Leviantdb688452016-11-03 10:54:58 +00001081 StringMatcher readFilePatterns();
George Rimar07171f22016-09-21 15:56:44 +00001082 std::vector<SectionPattern> readInputSectionsList();
George Rimara2496cb2016-08-30 09:46:59 +00001083 InputSectionDescription *readInputSectionRules(StringRef FilePattern);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001084 unsigned readPhdrType();
George Rimarbe394db2016-09-16 20:21:55 +00001085 SortSectionPolicy readSortKind();
Petr Hoseka35e39c2016-08-16 01:11:16 +00001086 SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
Rafael Espindolac96da112016-11-01 11:30:45 +00001087 SymbolAssignment *readProvideOrAssignment(StringRef Tok);
George Rimar03fc0102016-07-28 07:18:23 +00001088 void readSort();
George Rimareefa7582016-08-04 09:29:31 +00001089 Expr readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001090
Rui Ueyama24e626c2017-01-26 02:58:19 +00001091 uint64_t readMemoryAssignment(StringRef, StringRef, StringRef);
1092 std::pair<uint32_t, uint32_t> readMemoryAttributes();
1093
Rui Ueyama708019c2016-07-24 18:19:40 +00001094 Expr readExpr();
1095 Expr readExpr1(Expr Lhs, int MinPrec);
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001096 StringRef readParenLiteral();
Rui Ueyama708019c2016-07-24 18:19:40 +00001097 Expr readPrimary();
1098 Expr readTernary(Expr Cond);
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001099 Expr readParenExpr();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001100
George Rimar20b65982016-08-31 09:08:26 +00001101 // For parsing version script.
Rui Ueyama12450b22016-11-18 06:30:09 +00001102 std::vector<SymbolVersion> readVersionExtern();
1103 void readAnonymousDeclaration();
Rui Ueyama95769b42016-08-31 20:03:54 +00001104 void readVersionDeclaration(StringRef VerStr);
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001105
1106 std::pair<std::vector<SymbolVersion>, std::vector<SymbolVersion>>
1107 readSymbols();
George Rimar20b65982016-08-31 09:08:26 +00001108
Rui Ueyama07320e42016-04-20 20:13:41 +00001109 ScriptConfiguration &Opt = *ScriptConfig;
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001110 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001111};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001112
Rafael Espindolad0ebd842016-12-08 17:54:26 +00001113void ScriptParser::readDynamicList() {
1114 expect("{");
1115 readAnonymousDeclaration();
1116 if (!atEOF())
1117 setError("EOF expected, but got " + next());
1118}
1119
George Rimar20b65982016-08-31 09:08:26 +00001120void ScriptParser::readVersionScript() {
Rui Ueyama95769b42016-08-31 20:03:54 +00001121 readVersionScriptCommand();
1122 if (!atEOF())
1123 setError("EOF expected, but got " + next());
1124}
1125
1126void ScriptParser::readVersionScriptCommand() {
Rui Ueyama83043f22016-10-17 16:01:53 +00001127 if (consume("{")) {
Rui Ueyama12450b22016-11-18 06:30:09 +00001128 readAnonymousDeclaration();
George Rimar20b65982016-08-31 09:08:26 +00001129 return;
1130 }
1131
Rui Ueyama95769b42016-08-31 20:03:54 +00001132 while (!atEOF() && !Error && peek() != "}") {
George Rimar20b65982016-08-31 09:08:26 +00001133 StringRef VerStr = next();
1134 if (VerStr == "{") {
Rui Ueyama95769b42016-08-31 20:03:54 +00001135 setError("anonymous version definition is used in "
1136 "combination with other version definitions");
George Rimar20b65982016-08-31 09:08:26 +00001137 return;
1138 }
1139 expect("{");
Rui Ueyama95769b42016-08-31 20:03:54 +00001140 readVersionDeclaration(VerStr);
George Rimar20b65982016-08-31 09:08:26 +00001141 }
1142}
1143
Rui Ueyama95769b42016-08-31 20:03:54 +00001144void ScriptParser::readVersion() {
1145 expect("{");
1146 readVersionScriptCommand();
1147 expect("}");
1148}
1149
George Rimar20b65982016-08-31 09:08:26 +00001150void ScriptParser::readLinkerScript() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001151 while (!atEOF()) {
1152 StringRef Tok = next();
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001153 if (Tok == ";")
1154 continue;
1155
Eugene Leviant20d03192016-09-16 15:30:47 +00001156 if (Tok == "ASSERT") {
1157 Opt.Commands.emplace_back(new AssertCommand(readAssert()));
1158 } else if (Tok == "ENTRY") {
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001159 readEntry();
1160 } else if (Tok == "EXTERN") {
1161 readExtern();
1162 } else if (Tok == "GROUP" || Tok == "INPUT") {
1163 readGroup();
1164 } else if (Tok == "INCLUDE") {
1165 readInclude();
Meador Ingeb8897442017-01-24 02:34:00 +00001166 } else if (Tok == "MEMORY") {
1167 readMemory();
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001168 } else if (Tok == "OUTPUT") {
1169 readOutput();
1170 } else if (Tok == "OUTPUT_ARCH") {
1171 readOutputArch();
1172 } else if (Tok == "OUTPUT_FORMAT") {
1173 readOutputFormat();
1174 } else if (Tok == "PHDRS") {
1175 readPhdrs();
1176 } else if (Tok == "SEARCH_DIR") {
1177 readSearchDir();
1178 } else if (Tok == "SECTIONS") {
1179 readSections();
1180 } else if (Tok == "VERSION") {
1181 readVersion();
Rafael Espindolac96da112016-11-01 11:30:45 +00001182 } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok)) {
Eugene Leviant20d03192016-09-16 15:30:47 +00001183 Opt.Commands.emplace_back(Cmd);
Petr Hoseke5d3ca52016-08-31 15:31:17 +00001184 } else {
George Rimar57610422016-03-11 14:43:02 +00001185 setError("unknown directive: " + Tok);
Petr Hoseke5d3ca52016-08-31 15:31:17 +00001186 }
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001187 }
1188}
1189
Rui Ueyama717677a2016-02-11 21:17:59 +00001190void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001191 if (IsUnderSysroot && S.startswith("/")) {
Justin Bogner5af16872016-10-17 06:08:48 +00001192 SmallString<128> PathData;
1193 StringRef Path = (Config->Sysroot + S).toStringRef(PathData);
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001194 if (sys::fs::exists(Path)) {
Justin Bogner5af16872016-10-17 06:08:48 +00001195 Driver->addFile(Saver.save(Path));
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001196 return;
1197 }
1198 }
1199
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +00001200 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +00001201 Driver->addFile(S);
1202 } else if (S.startswith("=")) {
1203 if (Config->Sysroot.empty())
1204 Driver->addFile(S.substr(1));
1205 else
1206 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
1207 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +00001208 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +00001209 } else if (sys::fs::exists(S)) {
1210 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +00001211 } else {
Rui Ueyama061f9282016-11-19 19:23:58 +00001212 if (Optional<std::string> Path = findFromSearchPaths(S))
1213 Driver->addFile(Saver.save(*Path));
Rui Ueyama025d59b2016-02-02 20:27:59 +00001214 else
Rui Ueyama061f9282016-11-19 19:23:58 +00001215 setError("unable to find " + S);
Rui Ueyama52a15092015-10-11 03:28:42 +00001216 }
1217}
1218
Rui Ueyama717677a2016-02-11 21:17:59 +00001219void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001220 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +00001221 bool Orig = Config->AsNeeded;
1222 Config->AsNeeded = true;
Rui Ueyama83043f22016-10-17 16:01:53 +00001223 while (!Error && !consume(")"))
George Rimarcd574a52016-09-09 14:35:36 +00001224 addFile(unquote(next()));
Rui Ueyama35da9b62015-10-11 20:59:12 +00001225 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001226}
1227
Rui Ueyama717677a2016-02-11 21:17:59 +00001228void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +00001229 // -e <symbol> takes predecence over ENTRY(<symbol>).
1230 expect("(");
1231 StringRef Tok = next();
1232 if (Config->Entry.empty())
1233 Config->Entry = Tok;
1234 expect(")");
1235}
1236
Rui Ueyama717677a2016-02-11 21:17:59 +00001237void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +00001238 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001239 while (!Error && !consume(")"))
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001240 Config->Undefined.push_back(next());
George Rimar83f406c2015-10-19 17:35:12 +00001241}
1242
Rui Ueyama717677a2016-02-11 21:17:59 +00001243void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001244 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001245 while (!Error && !consume(")")) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001246 StringRef Tok = next();
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001247 if (Tok == "AS_NEEDED")
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001248 readAsNeeded();
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001249 else
George Rimarcd574a52016-09-09 14:35:36 +00001250 addFile(unquote(Tok));
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001251 }
1252}
1253
Rui Ueyama717677a2016-02-11 21:17:59 +00001254void ScriptParser::readInclude() {
George Rimard4500652016-12-21 09:42:25 +00001255 StringRef Tok = unquote(next());
Rui Ueyamaec1c75e2017-01-09 01:42:02 +00001256
George Rimard4500652016-12-21 09:42:25 +00001257 // https://sourceware.org/binutils/docs/ld/File-Commands.html:
1258 // The file will be searched for in the current directory, and in any
1259 // directory specified with the -L option.
Rui Ueyamaec1c75e2017-01-09 01:42:02 +00001260 if (sys::fs::exists(Tok)) {
1261 if (Optional<MemoryBufferRef> MB = readFile(Tok))
1262 tokenize(*MB);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001263 return;
1264 }
Rui Ueyamaec1c75e2017-01-09 01:42:02 +00001265 if (Optional<std::string> Path = findFromSearchPaths(Tok)) {
1266 if (Optional<MemoryBufferRef> MB = readFile(*Path))
1267 tokenize(*MB);
1268 return;
1269 }
1270 setError("cannot open " + Tok);
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001271}
1272
Rui Ueyama717677a2016-02-11 21:17:59 +00001273void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +00001274 // -o <file> takes predecence over OUTPUT(<file>).
1275 expect("(");
1276 StringRef Tok = next();
1277 if (Config->OutputFile.empty())
George Rimarcd574a52016-09-09 14:35:36 +00001278 Config->OutputFile = unquote(Tok);
Rui Ueyamaee592822015-10-07 00:25:09 +00001279 expect(")");
1280}
1281
Rui Ueyama717677a2016-02-11 21:17:59 +00001282void ScriptParser::readOutputArch() {
George Rimar4e01c3e2017-02-08 09:59:06 +00001283 // OUTPUT_ARCH is ignored for now.
Davide Italiano9159ce92015-10-12 21:50:08 +00001284 expect("(");
George Rimar4e01c3e2017-02-08 09:59:06 +00001285 while (!Error && !consume(")"))
1286 skip();
Davide Italiano9159ce92015-10-12 21:50:08 +00001287}
1288
Rui Ueyama717677a2016-02-11 21:17:59 +00001289void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001290 // Error checking only for now.
1291 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001292 skip();
Davide Italiano6836c612015-10-12 21:08:41 +00001293 StringRef Tok = next();
1294 if (Tok == ")")
George Rimar6c55f0e2016-09-08 08:20:30 +00001295 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +00001296 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +00001297 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001298 return;
1299 }
Justin Bogner5424e7c2016-10-17 06:21:13 +00001300 skip();
Davide Italiano6836c612015-10-12 21:08:41 +00001301 expect(",");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001302 skip();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001303 expect(")");
1304}
1305
Eugene Leviantbbe38602016-07-19 09:25:43 +00001306void ScriptParser::readPhdrs() {
1307 expect("{");
Rui Ueyama83043f22016-10-17 16:01:53 +00001308 while (!Error && !consume("}")) {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001309 StringRef Tok = next();
Eugene Leviant56b21c82016-09-09 09:46:16 +00001310 Opt.PhdrsCommands.push_back(
1311 {Tok, PT_NULL, false, false, UINT_MAX, nullptr});
Eugene Leviantbbe38602016-07-19 09:25:43 +00001312 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
1313
1314 PhdrCmd.Type = readPhdrType();
1315 do {
1316 Tok = next();
1317 if (Tok == ";")
1318 break;
1319 if (Tok == "FILEHDR")
1320 PhdrCmd.HasFilehdr = true;
1321 else if (Tok == "PHDRS")
1322 PhdrCmd.HasPhdrs = true;
Eugene Leviant56b21c82016-09-09 09:46:16 +00001323 else if (Tok == "AT")
1324 PhdrCmd.LMAExpr = readParenExpr();
Eugene Leviant865bf862016-07-21 10:43:25 +00001325 else if (Tok == "FLAGS") {
1326 expect("(");
Rafael Espindolaeb685cd2016-08-02 22:14:57 +00001327 // Passing 0 for the value of dot is a bit of a hack. It means that
1328 // we accept expressions like ".|1".
Rafael Espindola72dc1952017-03-17 13:05:04 +00001329 PhdrCmd.Flags = readExpr()().getValue();
Eugene Leviant865bf862016-07-21 10:43:25 +00001330 expect(")");
1331 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +00001332 setError("unexpected header attribute: " + Tok);
1333 } while (!Error);
1334 }
1335}
1336
Rui Ueyama717677a2016-02-11 21:17:59 +00001337void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +00001338 expect("(");
Rui Ueyama86c5fb82016-09-08 23:26:54 +00001339 StringRef Tok = next();
Rui Ueyama6c7ad132016-09-02 19:20:33 +00001340 if (!Config->Nostdlib)
George Rimarcd574a52016-09-09 14:35:36 +00001341 Config->SearchPaths.push_back(unquote(Tok));
Davide Italiano68a39a62015-10-08 17:51:41 +00001342 expect(")");
1343}
1344
Rui Ueyama717677a2016-02-11 21:17:59 +00001345void ScriptParser::readSections() {
Eugene Leviante05336ff2016-09-14 08:32:36 +00001346 Opt.HasSections = true;
George Rimar18a30962016-11-28 10:11:10 +00001347 // -no-rosegment is used to avoid placing read only non-executable sections in
1348 // their own segment. We do the same if SECTIONS command is present in linker
1349 // script. See comment for computeFlags().
1350 Config->SingleRoRx = true;
1351
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001352 expect("{");
Rui Ueyama83043f22016-10-17 16:01:53 +00001353 while (!Error && !consume("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +00001354 StringRef Tok = next();
Rafael Espindolac96da112016-11-01 11:30:45 +00001355 BaseCommand *Cmd = readProvideOrAssignment(Tok);
Eugene Leviantceabe802016-08-11 07:56:43 +00001356 if (!Cmd) {
1357 if (Tok == "ASSERT")
1358 Cmd = new AssertCommand(readAssert());
1359 else
1360 Cmd = readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +00001361 }
Rui Ueyama10416562016-08-04 02:03:27 +00001362 Opt.Commands.emplace_back(Cmd);
George Rimar652852c2016-04-16 10:10:32 +00001363 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001364}
1365
Rui Ueyama708019c2016-07-24 18:19:40 +00001366static int precedence(StringRef Op) {
1367 return StringSwitch<int>(Op)
Rui Ueyama0120e3f2016-09-23 18:06:51 +00001368 .Cases("*", "/", 5)
1369 .Cases("+", "-", 4)
1370 .Cases("<<", ">>", 3)
Rui Ueyama9c4ac5f2016-09-23 22:22:34 +00001371 .Cases("<", "<=", ">", ">=", "==", "!=", 2)
Rui Ueyama0120e3f2016-09-23 18:06:51 +00001372 .Cases("&", "|", 1)
Rui Ueyama708019c2016-07-24 18:19:40 +00001373 .Default(-1);
1374}
1375
Eugene Leviantdb688452016-11-03 10:54:58 +00001376StringMatcher ScriptParser::readFilePatterns() {
Rui Ueyama10416562016-08-04 02:03:27 +00001377 std::vector<StringRef> V;
Rui Ueyama83043f22016-10-17 16:01:53 +00001378 while (!Error && !consume(")"))
Rui Ueyama10416562016-08-04 02:03:27 +00001379 V.push_back(next());
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001380 return StringMatcher(V);
George Rimar0702c4e2016-07-29 15:32:46 +00001381}
1382
George Rimarbe394db2016-09-16 20:21:55 +00001383SortSectionPolicy ScriptParser::readSortKind() {
Rui Ueyama83043f22016-10-17 16:01:53 +00001384 if (consume("SORT") || consume("SORT_BY_NAME"))
George Rimarbe394db2016-09-16 20:21:55 +00001385 return SortSectionPolicy::Name;
Rui Ueyama83043f22016-10-17 16:01:53 +00001386 if (consume("SORT_BY_ALIGNMENT"))
George Rimarbe394db2016-09-16 20:21:55 +00001387 return SortSectionPolicy::Alignment;
Rui Ueyama83043f22016-10-17 16:01:53 +00001388 if (consume("SORT_BY_INIT_PRIORITY"))
George Rimarbe394db2016-09-16 20:21:55 +00001389 return SortSectionPolicy::Priority;
Rui Ueyama83043f22016-10-17 16:01:53 +00001390 if (consume("SORT_NONE"))
Rui Ueyamab2a0abd2016-09-16 21:14:55 +00001391 return SortSectionPolicy::None;
1392 return SortSectionPolicy::Default;
George Rimarbe394db2016-09-16 20:21:55 +00001393}
1394
George Rimar395281c2016-09-16 17:42:10 +00001395// Method reads a list of sequence of excluded files and section globs given in
1396// a following form: ((EXCLUDE_FILE(file_pattern+))? section_pattern+)+
1397// Example: *(.foo.1 EXCLUDE_FILE (*a.o) .foo.2 EXCLUDE_FILE (*b.o) .foo.3)
George Rimaraf03be12016-09-17 19:17:25 +00001398// The semantics of that is next:
1399// * Include .foo.1 from every file.
1400// * Include .foo.2 from every file but a.o
1401// * Include .foo.3 from every file but b.o
George Rimar07171f22016-09-21 15:56:44 +00001402std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
1403 std::vector<SectionPattern> Ret;
George Rimar601e9892016-09-21 08:53:21 +00001404 while (!Error && peek() != ")") {
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001405 StringMatcher ExcludeFilePat;
Rui Ueyama83043f22016-10-17 16:01:53 +00001406 if (consume("EXCLUDE_FILE")) {
George Rimar395281c2016-09-16 17:42:10 +00001407 expect("(");
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001408 ExcludeFilePat = readFilePatterns();
George Rimar395281c2016-09-16 17:42:10 +00001409 }
1410
George Rimar601e9892016-09-21 08:53:21 +00001411 std::vector<StringRef> V;
1412 while (!Error && peek() != ")" && peek() != "EXCLUDE_FILE")
1413 V.push_back(next());
1414
1415 if (!V.empty())
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001416 Ret.push_back({std::move(ExcludeFilePat), StringMatcher(V)});
George Rimar601e9892016-09-21 08:53:21 +00001417 else
1418 setError("section pattern is expected");
George Rimar395281c2016-09-16 17:42:10 +00001419 }
George Rimar07171f22016-09-21 15:56:44 +00001420 return Ret;
George Rimar395281c2016-09-16 17:42:10 +00001421}
1422
Rui Ueyamaf8f6f1e2016-11-18 07:03:56 +00001423// Reads contents of "SECTIONS" directive. That directive contains a
1424// list of glob patterns for input sections. The grammar is as follows.
1425//
1426// <patterns> ::= <section-list>
1427// | <sort> "(" <section-list> ")"
1428// | <sort> "(" <sort> "(" <section-list> ")" ")"
1429//
1430// <sort> ::= "SORT" | "SORT_BY_NAME" | "SORT_BY_ALIGNMENT"
1431// | "SORT_BY_INIT_PRIORITY" | "SORT_NONE"
1432//
1433// <section-list> is parsed by readInputSectionsList().
George Rimara2496cb2016-08-30 09:46:59 +00001434InputSectionDescription *
1435ScriptParser::readInputSectionRules(StringRef FilePattern) {
George Rimarc91930a2016-09-02 21:17:20 +00001436 auto *Cmd = new InputSectionDescription(FilePattern);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001437 expect("(");
Rui Ueyamaf373dd72016-11-24 01:43:21 +00001438 while (!Error && !consume(")")) {
George Rimar07171f22016-09-21 15:56:44 +00001439 SortSectionPolicy Outer = readSortKind();
1440 SortSectionPolicy Inner = SortSectionPolicy::Default;
1441 std::vector<SectionPattern> V;
1442 if (Outer != SortSectionPolicy::Default) {
George Rimar350ece42016-08-03 08:35:59 +00001443 expect("(");
George Rimar07171f22016-09-21 15:56:44 +00001444 Inner = readSortKind();
1445 if (Inner != SortSectionPolicy::Default) {
1446 expect("(");
1447 V = readInputSectionsList();
1448 expect(")");
1449 } else {
1450 V = readInputSectionsList();
1451 }
George Rimar350ece42016-08-03 08:35:59 +00001452 expect(")");
1453 } else {
George Rimar07171f22016-09-21 15:56:44 +00001454 V = readInputSectionsList();
George Rimar350ece42016-08-03 08:35:59 +00001455 }
George Rimar0702c4e2016-07-29 15:32:46 +00001456
George Rimar07171f22016-09-21 15:56:44 +00001457 for (SectionPattern &Pat : V) {
1458 Pat.SortInner = Inner;
1459 Pat.SortOuter = Outer;
1460 }
1461
1462 std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns));
1463 }
Rui Ueyama10416562016-08-04 02:03:27 +00001464 return Cmd;
Davide Italianoe7282792016-07-27 01:44:01 +00001465}
1466
George Rimara2496cb2016-08-30 09:46:59 +00001467InputSectionDescription *
1468ScriptParser::readInputSectionDescription(StringRef Tok) {
George Rimar06598002016-07-28 21:51:30 +00001469 // Input section wildcard can be surrounded by KEEP.
1470 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
George Rimara2496cb2016-08-30 09:46:59 +00001471 if (Tok == "KEEP") {
George Rimar06598002016-07-28 21:51:30 +00001472 expect("(");
George Rimara2496cb2016-08-30 09:46:59 +00001473 StringRef FilePattern = next();
1474 InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
George Rimar06598002016-07-28 21:51:30 +00001475 expect(")");
Eugene Leviantcf43f172016-10-05 09:36:59 +00001476 Opt.KeptSections.push_back(Cmd);
Rui Ueyama10416562016-08-04 02:03:27 +00001477 return Cmd;
George Rimar06598002016-07-28 21:51:30 +00001478 }
George Rimara2496cb2016-08-30 09:46:59 +00001479 return readInputSectionRules(Tok);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001480}
1481
George Rimar03fc0102016-07-28 07:18:23 +00001482void ScriptParser::readSort() {
1483 expect("(");
1484 expect("CONSTRUCTORS");
1485 expect(")");
1486}
1487
George Rimareefa7582016-08-04 09:29:31 +00001488Expr ScriptParser::readAssert() {
1489 expect("(");
1490 Expr E = readExpr();
1491 expect(",");
George Rimarcd574a52016-09-09 14:35:36 +00001492 StringRef Msg = unquote(next());
George Rimareefa7582016-08-04 09:29:31 +00001493 expect(")");
Rafael Espindola4595df92017-03-10 16:04:26 +00001494 return [=] {
Rafael Espindola72dc1952017-03-17 13:05:04 +00001495 if (!E().getValue())
George Rimareefa7582016-08-04 09:29:31 +00001496 error(Msg);
George Rimara8dba482017-03-20 10:09:58 +00001497 return Script->getDot();
George Rimareefa7582016-08-04 09:29:31 +00001498 };
1499}
1500
Rui Ueyama25150e82016-09-06 17:46:43 +00001501// Reads a FILL(expr) command. We handle the FILL command as an
1502// alias for =fillexp section attribute, which is different from
1503// what GNU linkers do.
1504// https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
Rui Ueyama16068ae2016-11-19 18:05:56 +00001505uint32_t ScriptParser::readFill() {
George Rimarff1f29e2016-09-06 13:51:57 +00001506 expect("(");
Rui Ueyama16068ae2016-11-19 18:05:56 +00001507 uint32_t V = readOutputSectionFiller(next());
George Rimarff1f29e2016-09-06 13:51:57 +00001508 expect(")");
1509 expect(";");
1510 return V;
1511}
1512
Rui Ueyama10416562016-08-04 02:03:27 +00001513OutputSectionCommand *
1514ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +00001515 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
Eugene Leviant2a942c42016-12-05 16:38:32 +00001516 Cmd->Location = getCurrentLocation();
George Rimar58e5c4d2016-07-25 08:29:46 +00001517
1518 // Read an address expression.
1519 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
1520 if (peek() != ":")
1521 Cmd->AddrExpr = readExpr();
1522
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001523 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +00001524
Rui Ueyama83043f22016-10-17 16:01:53 +00001525 if (consume("AT"))
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001526 Cmd->LMAExpr = readParenExpr();
Rui Ueyama83043f22016-10-17 16:01:53 +00001527 if (consume("ALIGN"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001528 Cmd->AlignExpr = readParenExpr();
Rui Ueyama83043f22016-10-17 16:01:53 +00001529 if (consume("SUBALIGN"))
George Rimardb24d9c2016-08-19 15:18:23 +00001530 Cmd->SubalignExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001531
Davide Italiano246f6812016-07-22 03:36:24 +00001532 // Parse constraints.
Rui Ueyama83043f22016-10-17 16:01:53 +00001533 if (consume("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001534 Cmd->Constraint = ConstraintKind::ReadOnly;
Rui Ueyama83043f22016-10-17 16:01:53 +00001535 if (consume("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001536 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001537 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001538
Rui Ueyama83043f22016-10-17 16:01:53 +00001539 while (!Error && !consume("}")) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001540 StringRef Tok = next();
George Rimar2fe07922017-01-31 08:50:11 +00001541 if (Tok == ";") {
George Rimar69750752017-02-01 09:14:22 +00001542 // Empty commands are allowed. Do nothing here.
George Rimar2fe07922017-01-31 08:50:11 +00001543 } else if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok)) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001544 Cmd->Commands.emplace_back(Assignment);
Meador Ingeb2d99d62016-11-22 18:01:50 +00001545 } else if (BytesDataCommand *Data = readBytesDataCommand(Tok)) {
George Rimare38cbab2016-09-26 19:22:50 +00001546 Cmd->Commands.emplace_back(Data);
Meador Ingeb2d99d62016-11-22 18:01:50 +00001547 } else if (Tok == "ASSERT") {
1548 Cmd->Commands.emplace_back(new AssertCommand(readAssert()));
1549 expect(";");
George Rimar8e2eca22017-01-23 09:36:19 +00001550 } else if (Tok == "CONSTRUCTORS") {
1551 // CONSTRUCTORS is a keyword to make the linker recognize C++ ctors/dtors
1552 // by name. This is for very old file formats such as ECOFF/XCOFF.
1553 // For ELF, we should ignore.
Meador Ingeb2d99d62016-11-22 18:01:50 +00001554 } else if (Tok == "FILL") {
George Rimarff1f29e2016-09-06 13:51:57 +00001555 Cmd->Filler = readFill();
Meador Ingeb2d99d62016-11-22 18:01:50 +00001556 } else if (Tok == "SORT") {
George Rimar03fc0102016-07-28 07:18:23 +00001557 readSort();
Meador Ingeb2d99d62016-11-22 18:01:50 +00001558 } else if (peek() == "(") {
George Rimara2496cb2016-08-30 09:46:59 +00001559 Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
Meador Ingeb2d99d62016-11-22 18:01:50 +00001560 } else {
Eugene Leviantceabe802016-08-11 07:56:43 +00001561 setError("unknown command " + Tok);
Meador Ingeb2d99d62016-11-22 18:01:50 +00001562 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001563 }
Meador Ingeb8897442017-01-24 02:34:00 +00001564
1565 if (consume(">"))
1566 Cmd->MemoryRegionName = next();
1567
George Rimar076fe152016-07-21 06:43:01 +00001568 Cmd->Phdrs = readOutputSectionPhdrs();
George Rimar4ebc5622016-09-23 13:29:20 +00001569
Rui Ueyama83043f22016-10-17 16:01:53 +00001570 if (consume("="))
George Rimar4ebc5622016-09-23 13:29:20 +00001571 Cmd->Filler = readOutputSectionFiller(next());
1572 else if (peek().startswith("="))
George Rimarff1f29e2016-09-06 13:51:57 +00001573 Cmd->Filler = readOutputSectionFiller(next().drop_front());
George Rimar4ebc5622016-09-23 13:29:20 +00001574
George Rimar7185a1a2017-01-17 15:32:12 +00001575 // Consume optional comma following output section command.
1576 consume(",");
1577
Rui Ueyama10416562016-08-04 02:03:27 +00001578 return Cmd;
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001579}
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001580
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001581// Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
1582// https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
1583//
1584// ld.gold is not fully compatible with ld.bfd. ld.bfd handles
1585// hexstrings as blobs of arbitrary sizes, while ld.gold handles them
1586// as 32-bit big-endian values. We will do the same as ld.gold does
1587// because it's simpler than what ld.bfd does.
Rui Ueyama16068ae2016-11-19 18:05:56 +00001588uint32_t ScriptParser::readOutputSectionFiller(StringRef Tok) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001589 uint32_t V;
Rui Ueyama16068ae2016-11-19 18:05:56 +00001590 if (!Tok.getAsInteger(0, V))
1591 return V;
1592 setError("invalid filler expression: " + Tok);
1593 return 0;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001594}
1595
Petr Hoseka35e39c2016-08-16 01:11:16 +00001596SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
Eugene Levianta31c91b2016-07-22 07:38:40 +00001597 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +00001598 SymbolAssignment *Cmd = readAssignment(next());
Petr Hoseka35e39c2016-08-16 01:11:16 +00001599 Cmd->Provide = Provide;
Rui Ueyama174e0a12016-07-29 00:29:25 +00001600 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001601 expect(")");
1602 expect(";");
Rui Ueyama10416562016-08-04 02:03:27 +00001603 return Cmd;
Eugene Levianteda81a12016-07-12 06:39:48 +00001604}
1605
Rafael Espindolac96da112016-11-01 11:30:45 +00001606SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001607 SymbolAssignment *Cmd = nullptr;
1608 if (peek() == "=" || peek() == "+=") {
1609 Cmd = readAssignment(Tok);
1610 expect(";");
1611 } else if (Tok == "PROVIDE") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001612 Cmd = readProvideHidden(true, false);
1613 } else if (Tok == "HIDDEN") {
1614 Cmd = readProvideHidden(false, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001615 } else if (Tok == "PROVIDE_HIDDEN") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001616 Cmd = readProvideHidden(true, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001617 }
1618 return Cmd;
1619}
1620
George Rimar30835ea2016-07-28 21:08:56 +00001621SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1622 StringRef Op = next();
1623 assert(Op == "=" || Op == "+=");
Petr Hosek02ad5162017-03-15 03:33:23 +00001624 Expr E = readExpr();
Eugene Leviantf6aeed32016-12-22 13:13:12 +00001625 if (Op == "+=") {
1626 std::string Loc = getCurrentLocation();
George Rimara8dba482017-03-20 10:09:58 +00001627 E = [=] { return add(Script->getSymbolValue(Loc, Name), E()); };
Eugene Leviantf6aeed32016-12-22 13:13:12 +00001628 }
George Rimar2ee2d2d2017-02-21 14:50:38 +00001629 return new SymbolAssignment(Name, E, getCurrentLocation());
George Rimar30835ea2016-07-28 21:08:56 +00001630}
1631
1632// This is an operator-precedence parser to parse a linker
1633// script expression.
Rui Ueyama731a66a2017-02-15 19:58:17 +00001634Expr ScriptParser::readExpr() {
1635 // Our lexer is context-aware. Set the in-expression bit so that
1636 // they apply different tokenization rules.
1637 bool Orig = InExpr;
1638 InExpr = true;
1639 Expr E = readExpr1(readPrimary(), 0);
1640 InExpr = Orig;
1641 return E;
1642}
George Rimar30835ea2016-07-28 21:08:56 +00001643
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001644static Expr combine(StringRef Op, Expr L, Expr R) {
1645 if (Op == "*")
Rafael Espindola72dc1952017-03-17 13:05:04 +00001646 return [=] { return mul(L(), R()); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001647 if (Op == "/") {
Rafael Espindola72dc1952017-03-17 13:05:04 +00001648 return [=] { return div(L(), R()); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001649 }
1650 if (Op == "+")
Rafael Espindola72dc1952017-03-17 13:05:04 +00001651 return [=] { return add(L(), R()); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001652 if (Op == "-")
Rafael Espindola72dc1952017-03-17 13:05:04 +00001653 return [=] { return sub(L(), R()); };
George Rimarc8ccd1f2016-09-23 13:13:55 +00001654 if (Op == "<<")
Rafael Espindola72dc1952017-03-17 13:05:04 +00001655 return [=] { return leftShift(L(), R()); };
George Rimarc8ccd1f2016-09-23 13:13:55 +00001656 if (Op == ">>")
Rafael Espindola72dc1952017-03-17 13:05:04 +00001657 return [=] { return rightShift(L(), R()); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001658 if (Op == "<")
Rafael Espindola195f23c2017-03-20 14:35:41 +00001659 return [=] { return L().getValue() < R().getValue(); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001660 if (Op == ">")
Rafael Espindola195f23c2017-03-20 14:35:41 +00001661 return [=] { return L().getValue() > R().getValue(); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001662 if (Op == ">=")
Rafael Espindola195f23c2017-03-20 14:35:41 +00001663 return [=] { return L().getValue() >= R().getValue(); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001664 if (Op == "<=")
Rafael Espindola195f23c2017-03-20 14:35:41 +00001665 return [=] { return L().getValue() <= R().getValue(); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001666 if (Op == "==")
Rafael Espindola195f23c2017-03-20 14:35:41 +00001667 return [=] { return L().getValue() == R().getValue(); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001668 if (Op == "!=")
Rafael Espindola195f23c2017-03-20 14:35:41 +00001669 return [=] { return L().getValue() != R().getValue(); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001670 if (Op == "&")
Rafael Espindola72dc1952017-03-17 13:05:04 +00001671 return [=] { return bitAnd(L(), R()); };
Rafael Espindolacc3dd622016-08-22 21:33:35 +00001672 if (Op == "|")
Rafael Espindola72dc1952017-03-17 13:05:04 +00001673 return [=] { return bitOr(L(), R()); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001674 llvm_unreachable("invalid operator");
1675}
1676
Rui Ueyama708019c2016-07-24 18:19:40 +00001677// This is a part of the operator-precedence parser. This function
1678// assumes that the remaining token stream starts with an operator.
1679Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1680 while (!atEOF() && !Error) {
1681 // Read an operator and an expression.
Rui Ueyama46247b82016-11-18 06:49:07 +00001682 if (consume("?"))
Rui Ueyama708019c2016-07-24 18:19:40 +00001683 return readTernary(Lhs);
Rui Ueyama46247b82016-11-18 06:49:07 +00001684 StringRef Op1 = peek();
Rui Ueyama708019c2016-07-24 18:19:40 +00001685 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +00001686 break;
Justin Bogner5424e7c2016-10-17 06:21:13 +00001687 skip();
Rui Ueyama708019c2016-07-24 18:19:40 +00001688 Expr Rhs = readPrimary();
1689
1690 // Evaluate the remaining part of the expression first if the
1691 // next operator has greater precedence than the previous one.
1692 // For example, if we have read "+" and "3", and if the next
1693 // operator is "*", then we'll evaluate 3 * ... part first.
1694 while (!atEOF()) {
1695 StringRef Op2 = peek();
1696 if (precedence(Op2) <= precedence(Op1))
1697 break;
1698 Rhs = readExpr1(Rhs, precedence(Op2));
1699 }
1700
1701 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +00001702 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001703 return Lhs;
1704}
1705
1706uint64_t static getConstant(StringRef S) {
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001707 if (S == "COMMONPAGESIZE")
Rui Ueyama708019c2016-07-24 18:19:40 +00001708 return Target->PageSize;
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001709 if (S == "MAXPAGESIZE")
Petr Hosek997f8832016-09-28 15:20:47 +00001710 return Config->MaxPageSize;
Rui Ueyama708019c2016-07-24 18:19:40 +00001711 error("unknown constant: " + S);
1712 return 0;
1713}
1714
Rui Ueyama626e0b02016-09-02 18:19:00 +00001715// Parses Tok as an integer. Returns true if successful.
1716// It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1717// and decimal numbers. Decimal numbers may have "K" (kilo) or
1718// "M" (mega) prefixes.
George Rimar9f2f7ad2016-09-02 16:01:42 +00001719static bool readInteger(StringRef Tok, uint64_t &Result) {
Rui Ueyama46247b82016-11-18 06:49:07 +00001720 // Negative number
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001721 if (Tok.startswith("-")) {
1722 if (!readInteger(Tok.substr(1), Result))
1723 return false;
1724 Result = -Result;
1725 return true;
1726 }
Rui Ueyama46247b82016-11-18 06:49:07 +00001727
1728 // Hexadecimal
George Rimar9f2f7ad2016-09-02 16:01:42 +00001729 if (Tok.startswith_lower("0x"))
1730 return !Tok.substr(2).getAsInteger(16, Result);
1731 if (Tok.endswith_lower("H"))
1732 return !Tok.drop_back().getAsInteger(16, Result);
1733
Rui Ueyama46247b82016-11-18 06:49:07 +00001734 // Decimal
George Rimar9f2f7ad2016-09-02 16:01:42 +00001735 int Suffix = 1;
1736 if (Tok.endswith_lower("K")) {
1737 Suffix = 1024;
1738 Tok = Tok.drop_back();
1739 } else if (Tok.endswith_lower("M")) {
1740 Suffix = 1024 * 1024;
1741 Tok = Tok.drop_back();
1742 }
1743 if (Tok.getAsInteger(10, Result))
1744 return false;
1745 Result *= Suffix;
1746 return true;
1747}
1748
George Rimare38cbab2016-09-26 19:22:50 +00001749BytesDataCommand *ScriptParser::readBytesDataCommand(StringRef Tok) {
1750 int Size = StringSwitch<unsigned>(Tok)
1751 .Case("BYTE", 1)
1752 .Case("SHORT", 2)
1753 .Case("LONG", 4)
1754 .Case("QUAD", 8)
1755 .Default(-1);
1756 if (Size == -1)
1757 return nullptr;
1758
Meador Inge95c7d8d2016-12-08 23:21:30 +00001759 return new BytesDataCommand(readParenExpr(), Size);
George Rimare38cbab2016-09-26 19:22:50 +00001760}
1761
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001762StringRef ScriptParser::readParenLiteral() {
1763 expect("(");
1764 StringRef Tok = next();
1765 expect(")");
1766 return Tok;
1767}
1768
Rui Ueyama708019c2016-07-24 18:19:40 +00001769Expr ScriptParser::readPrimary() {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001770 if (peek() == "(")
1771 return readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001772
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001773 StringRef Tok = next();
Rui Ueyamab5f1c3e2016-12-01 04:36:49 +00001774 std::string Location = getCurrentLocation();
Rui Ueyama708019c2016-07-24 18:19:40 +00001775
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001776 if (Tok == "~") {
1777 Expr E = readPrimary();
Rafael Espindola72dc1952017-03-17 13:05:04 +00001778 return [=] { return bitNot(E()); };
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001779 }
1780 if (Tok == "-") {
1781 Expr E = readPrimary();
Rafael Espindola72dc1952017-03-17 13:05:04 +00001782 return [=] { return minus(E()); };
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001783 }
1784
Rui Ueyama708019c2016-07-24 18:19:40 +00001785 // Built-in functions are parsed here.
1786 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
Petr Hosek02ad5162017-03-15 03:33:23 +00001787 if (Tok == "ABSOLUTE") {
Rafael Espindola72dc1952017-03-17 13:05:04 +00001788 Expr Inner = readParenExpr();
1789 return [=] {
1790 ExprValue I = Inner();
1791 I.ForceAbsolute = true;
1792 return I;
1793 };
Petr Hosek02ad5162017-03-15 03:33:23 +00001794 }
George Rimar96659df2016-08-30 09:54:01 +00001795 if (Tok == "ADDR") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001796 StringRef Name = readParenLiteral();
Rafael Espindola72dc1952017-03-17 13:05:04 +00001797 return [=]() -> ExprValue {
George Rimara8dba482017-03-20 10:09:58 +00001798 return {Script->getOutputSection(Location, Name), 0};
Rafael Espindola72dc1952017-03-17 13:05:04 +00001799 };
George Rimar96659df2016-08-30 09:54:01 +00001800 }
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001801 if (Tok == "LOADADDR") {
1802 StringRef Name = readParenLiteral();
George Rimara8dba482017-03-20 10:09:58 +00001803 return [=] { return Script->getOutputSection(Location, Name)->getLMA(); };
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001804 }
George Rimareefa7582016-08-04 09:29:31 +00001805 if (Tok == "ASSERT")
1806 return readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001807 if (Tok == "ALIGN") {
Rui Ueyama5d804dc2016-12-16 18:19:35 +00001808 expect("(");
1809 Expr E = readExpr();
1810 if (consume(",")) {
1811 Expr E2 = readExpr();
1812 expect(")");
Rafael Espindola72dc1952017-03-17 13:05:04 +00001813 return [=] { return alignTo(E().getValue(), E2().getValue()); };
Rui Ueyama5d804dc2016-12-16 18:19:35 +00001814 }
1815 expect(")");
George Rimara8dba482017-03-20 10:09:58 +00001816 return [=] { return alignTo(Script->getDot(), E().getValue()); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001817 }
1818 if (Tok == "CONSTANT") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001819 StringRef Name = readParenLiteral();
Rafael Espindola4595df92017-03-10 16:04:26 +00001820 return [=] { return getConstant(Name); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001821 }
George Rimarf34f45f2016-09-23 13:17:23 +00001822 if (Tok == "DEFINED") {
Rui Ueyama0ee25a62016-11-17 03:52:14 +00001823 StringRef Name = readParenLiteral();
George Rimara8dba482017-03-20 10:09:58 +00001824 return [=] { return Script->isDefined(Name) ? 1 : 0; };
George Rimarf34f45f2016-09-23 13:17:23 +00001825 }
Rafael Espindola54c145c2016-07-28 18:16:24 +00001826 if (Tok == "SEGMENT_START") {
1827 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001828 skip();
Rafael Espindola54c145c2016-07-28 18:16:24 +00001829 expect(",");
George Rimar8c658bf2016-09-17 18:14:56 +00001830 Expr E = readExpr();
Rafael Espindola54c145c2016-07-28 18:16:24 +00001831 expect(")");
Rafael Espindola4595df92017-03-10 16:04:26 +00001832 return [=] { return E(); };
Rafael Espindola54c145c2016-07-28 18:16:24 +00001833 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001834 if (Tok == "DATA_SEGMENT_ALIGN") {
1835 expect("(");
1836 Expr E = readExpr();
1837 expect(",");
1838 readExpr();
1839 expect(")");
George Rimara8dba482017-03-20 10:09:58 +00001840 return [=] { return alignTo(Script->getDot(), E().getValue()); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001841 }
1842 if (Tok == "DATA_SEGMENT_END") {
1843 expect("(");
1844 expect(".");
1845 expect(")");
George Rimara8dba482017-03-20 10:09:58 +00001846 return [] { return Script->getDot(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001847 }
George Rimar276b4e62016-07-26 17:58:44 +00001848 // GNU linkers implements more complicated logic to handle
1849 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1850 // the next page boundary for simplicity.
1851 if (Tok == "DATA_SEGMENT_RELRO_END") {
1852 expect("(");
Rafael Espindola97bdc722016-09-14 19:14:01 +00001853 readExpr();
George Rimar276b4e62016-07-26 17:58:44 +00001854 expect(",");
1855 readExpr();
1856 expect(")");
George Rimara8dba482017-03-20 10:09:58 +00001857 return [] { return alignTo(Script->getDot(), Target->PageSize); };
George Rimar276b4e62016-07-26 17:58:44 +00001858 }
George Rimar9e694502016-07-29 16:18:47 +00001859 if (Tok == "SIZEOF") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001860 StringRef Name = readParenLiteral();
George Rimara8dba482017-03-20 10:09:58 +00001861 return [=] { return Script->getOutputSectionSize(Name); };
George Rimar9e694502016-07-29 16:18:47 +00001862 }
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001863 if (Tok == "ALIGNOF") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001864 StringRef Name = readParenLiteral();
George Rimara8dba482017-03-20 10:09:58 +00001865 return [=] { return Script->getOutputSection(Location, Name)->Alignment; };
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001866 }
George Rimare32a3592016-08-10 07:59:34 +00001867 if (Tok == "SIZEOF_HEADERS")
George Rimar78aa2702017-03-13 14:40:58 +00001868 return [=] { return elf::getHeaderSize(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001869
George Rimar9f2f7ad2016-09-02 16:01:42 +00001870 // Tok is a literal number.
1871 uint64_t V;
1872 if (readInteger(Tok, V))
Rafael Espindola4595df92017-03-10 16:04:26 +00001873 return [=] { return V; };
George Rimar9f2f7ad2016-09-02 16:01:42 +00001874
1875 // Tok is a symbol name.
1876 if (Tok != "." && !isValidCIdentifier(Tok))
1877 setError("malformed number: " + Tok);
George Rimara8dba482017-03-20 10:09:58 +00001878 return [=] { return Script->getSymbolValue(Location, Tok); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001879}
1880
1881Expr ScriptParser::readTernary(Expr Cond) {
Rui Ueyama708019c2016-07-24 18:19:40 +00001882 Expr L = readExpr();
1883 expect(":");
1884 Expr R = readExpr();
Rafael Espindola72dc1952017-03-17 13:05:04 +00001885 return [=] { return Cond().getValue() ? L() : R(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001886}
1887
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001888Expr ScriptParser::readParenExpr() {
1889 expect("(");
1890 Expr E = readExpr();
1891 expect(")");
1892 return E;
1893}
1894
Eugene Leviantbbe38602016-07-19 09:25:43 +00001895std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1896 std::vector<StringRef> Phdrs;
1897 while (!Error && peek().startswith(":")) {
1898 StringRef Tok = next();
George Rimarda841c12016-11-14 10:03:54 +00001899 Phdrs.push_back((Tok.size() == 1) ? next() : Tok.substr(1));
Eugene Leviantbbe38602016-07-19 09:25:43 +00001900 }
1901 return Phdrs;
1902}
1903
George Rimar95dd7182016-10-18 10:49:50 +00001904// Read a program header type name. The next token must be a
1905// name of a program header type or a constant (e.g. "0x3").
Eugene Leviantbbe38602016-07-19 09:25:43 +00001906unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001907 StringRef Tok = next();
George Rimar95dd7182016-10-18 10:49:50 +00001908 uint64_t Val;
1909 if (readInteger(Tok, Val))
1910 return Val;
1911
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001912 unsigned Ret = StringSwitch<unsigned>(Tok)
George Rimar6c55f0e2016-09-08 08:20:30 +00001913 .Case("PT_NULL", PT_NULL)
1914 .Case("PT_LOAD", PT_LOAD)
1915 .Case("PT_DYNAMIC", PT_DYNAMIC)
1916 .Case("PT_INTERP", PT_INTERP)
1917 .Case("PT_NOTE", PT_NOTE)
1918 .Case("PT_SHLIB", PT_SHLIB)
1919 .Case("PT_PHDR", PT_PHDR)
1920 .Case("PT_TLS", PT_TLS)
1921 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1922 .Case("PT_GNU_STACK", PT_GNU_STACK)
1923 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
George Rimar270173f2016-10-14 13:02:22 +00001924 .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
George Rimarcc6e5672016-10-14 10:34:36 +00001925 .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
George Rimara2a32c22016-12-06 17:57:42 +00001926 .Case("PT_OPENBSD_BOOTDATA", PT_OPENBSD_BOOTDATA)
George Rimar6c55f0e2016-09-08 08:20:30 +00001927 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001928
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001929 if (Ret == (unsigned)-1) {
1930 setError("invalid program header type: " + Tok);
1931 return PT_NULL;
1932 }
1933 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001934}
1935
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001936// Reads an anonymous version declaration.
Rui Ueyama12450b22016-11-18 06:30:09 +00001937void ScriptParser::readAnonymousDeclaration() {
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001938 std::vector<SymbolVersion> Locals;
1939 std::vector<SymbolVersion> Globals;
1940 std::tie(Locals, Globals) = readSymbols();
1941
1942 for (SymbolVersion V : Locals) {
1943 if (V.Name == "*")
1944 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1945 else
1946 Config->VersionScriptLocals.push_back(V);
Rafael Espindola45242682017-02-03 13:24:01 +00001947 }
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001948
1949 for (SymbolVersion V : Globals)
1950 Config->VersionScriptGlobals.push_back(V);
1951
Rui Ueyama12450b22016-11-18 06:30:09 +00001952 expect(";");
1953}
1954
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001955// Reads a non-anonymous version definition,
1956// e.g. "VerStr { global: foo; bar; local: *; };".
Rui Ueyama95769b42016-08-31 20:03:54 +00001957void ScriptParser::readVersionDeclaration(StringRef VerStr) {
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001958 // Read a symbol list.
1959 std::vector<SymbolVersion> Locals;
1960 std::vector<SymbolVersion> Globals;
1961 std::tie(Locals, Globals) = readSymbols();
George Rimar20b65982016-08-31 09:08:26 +00001962
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001963 for (SymbolVersion V : Locals) {
1964 if (V.Name == "*")
1965 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1966 else
1967 Config->VersionScriptLocals.push_back(V);
Rafael Espindola45242682017-02-03 13:24:01 +00001968 }
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001969
1970 // Create a new version definition and add that to the global symbols.
1971 VersionDefinition Ver;
1972 Ver.Name = VerStr;
1973 Ver.Globals = Globals;
1974
1975 // User-defined version number starts from 2 because 0 and 1 are
1976 // reserved for VER_NDX_LOCAL and VER_NDX_GLOBAL, respectively.
1977 Ver.Id = Config->VersionDefinitions.size() + 2;
1978 Config->VersionDefinitions.push_back(Ver);
George Rimar20b65982016-08-31 09:08:26 +00001979
Rui Ueyama12450b22016-11-18 06:30:09 +00001980 // Each version may have a parent version. For example, "Ver2"
1981 // defined as "Ver2 { global: foo; local: *; } Ver1;" has "Ver1"
1982 // as a parent. This version hierarchy is, probably against your
1983 // instinct, purely for hint; the runtime doesn't care about it
1984 // at all. In LLD, we simply ignore it.
1985 if (peek() != ";")
Justin Bogner5424e7c2016-10-17 06:21:13 +00001986 skip();
George Rimar20b65982016-08-31 09:08:26 +00001987 expect(";");
1988}
1989
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001990// Reads a list of symbols, e.g. "{ global: foo; bar; local: *; };".
1991std::pair<std::vector<SymbolVersion>, std::vector<SymbolVersion>>
1992ScriptParser::readSymbols() {
1993 std::vector<SymbolVersion> Locals;
1994 std::vector<SymbolVersion> Globals;
1995 std::vector<SymbolVersion> *V = &Globals;
1996
1997 while (!Error) {
1998 if (consume("}"))
1999 break;
2000 if (consumeLabel("local")) {
2001 V = &Locals;
2002 continue;
2003 }
2004 if (consumeLabel("global")) {
2005 V = &Globals;
Rafael Espindola1ef90d22016-12-09 16:44:05 +00002006 continue;
2007 }
George Rimare0fc2422016-11-16 17:59:10 +00002008
Rui Ueyamaf5fce482017-03-09 19:23:00 +00002009 if (consume("extern")) {
2010 std::vector<SymbolVersion> Ext = readVersionExtern();
2011 V->insert(V->end(), Ext.begin(), Ext.end());
2012 } else {
2013 StringRef Tok = next();
2014 V->push_back({unquote(Tok), false, hasWildcard(Tok)});
2015 }
George Rimare0fc2422016-11-16 17:59:10 +00002016 expect(";");
2017 }
Rui Ueyamaf5fce482017-03-09 19:23:00 +00002018 return {Locals, Globals};
George Rimare0fc2422016-11-16 17:59:10 +00002019}
2020
Rui Ueyama12450b22016-11-18 06:30:09 +00002021// Reads an "extern C++" directive, e.g.,
2022// "extern "C++" { ns::*; "f(int, double)"; };"
2023std::vector<SymbolVersion> ScriptParser::readVersionExtern() {
Rafael Espindola7e714152016-12-08 17:26:53 +00002024 StringRef Tok = next();
2025 bool IsCXX = Tok == "\"C++\"";
2026 if (!IsCXX && Tok != "\"C\"")
Rafael Espindolad0ebd842016-12-08 17:54:26 +00002027 setError("Unknown language");
George Rimar20b65982016-08-31 09:08:26 +00002028 expect("{");
2029
Rui Ueyama12450b22016-11-18 06:30:09 +00002030 std::vector<SymbolVersion> Ret;
Rui Ueyama0ee25a62016-11-17 03:52:14 +00002031 while (!Error && peek() != "}") {
2032 StringRef Tok = next();
2033 bool HasWildcard = !Tok.startswith("\"") && hasWildcard(Tok);
Rafael Espindola7e714152016-12-08 17:26:53 +00002034 Ret.push_back({unquote(Tok), IsCXX, HasWildcard});
George Rimar20b65982016-08-31 09:08:26 +00002035 expect(";");
2036 }
2037
2038 expect("}");
Rui Ueyama12450b22016-11-18 06:30:09 +00002039 return Ret;
George Rimar20b65982016-08-31 09:08:26 +00002040}
2041
George Rimar009833d2017-03-20 09:51:18 +00002042uint64_t ScriptParser::readMemoryAssignment(StringRef S1, StringRef S2,
2043 StringRef S3) {
Rui Ueyama24e626c2017-01-26 02:58:19 +00002044 if (!(consume(S1) || consume(S2) || consume(S3))) {
2045 setError("expected one of: " + S1 + ", " + S2 + ", or " + S3);
2046 return 0;
2047 }
2048 expect("=");
2049
2050 // TODO: Fully support constant expressions.
2051 uint64_t Val;
2052 if (!readInteger(next(), Val))
George Rimar009833d2017-03-20 09:51:18 +00002053 setError("nonconstant expression for " + S1);
Rui Ueyama24e626c2017-01-26 02:58:19 +00002054 return Val;
2055}
2056
2057// Parse the MEMORY command as specified in:
2058// https://sourceware.org/binutils/docs/ld/MEMORY.html
2059//
2060// MEMORY { name [(attr)] : ORIGIN = origin, LENGTH = len ... }
Meador Ingeb8897442017-01-24 02:34:00 +00002061void ScriptParser::readMemory() {
2062 expect("{");
2063 while (!Error && !consume("}")) {
2064 StringRef Name = next();
Rui Ueyama24e626c2017-01-26 02:58:19 +00002065
Meador Ingeb8897442017-01-24 02:34:00 +00002066 uint32_t Flags = 0;
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002067 uint32_t NegFlags = 0;
Meador Ingeb8897442017-01-24 02:34:00 +00002068 if (consume("(")) {
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002069 std::tie(Flags, NegFlags) = readMemoryAttributes();
Meador Ingeb8897442017-01-24 02:34:00 +00002070 expect(")");
2071 }
2072 expect(":");
2073
Rui Ueyama24e626c2017-01-26 02:58:19 +00002074 uint64_t Origin = readMemoryAssignment("ORIGIN", "org", "o");
Meador Ingeb8897442017-01-24 02:34:00 +00002075 expect(",");
Rui Ueyama24e626c2017-01-26 02:58:19 +00002076 uint64_t Length = readMemoryAssignment("LENGTH", "len", "l");
Meador Ingeb8897442017-01-24 02:34:00 +00002077
Meador Ingeb8897442017-01-24 02:34:00 +00002078 // Add the memory region to the region map (if it doesn't already exist).
2079 auto It = Opt.MemoryRegions.find(Name);
2080 if (It != Opt.MemoryRegions.end())
2081 setError("region '" + Name + "' already defined");
2082 else
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002083 Opt.MemoryRegions[Name] = {Name, Origin, Length, Origin, Flags, NegFlags};
Meador Ingeb8897442017-01-24 02:34:00 +00002084 }
2085}
2086
2087// This function parses the attributes used to match against section
2088// flags when placing output sections in a memory region. These flags
2089// are only used when an explicit memory region name is not used.
2090std::pair<uint32_t, uint32_t> ScriptParser::readMemoryAttributes() {
2091 uint32_t Flags = 0;
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002092 uint32_t NegFlags = 0;
Meador Ingeb8897442017-01-24 02:34:00 +00002093 bool Invert = false;
Rui Ueyama481ac992017-01-26 02:58:39 +00002094
2095 for (char C : next().lower()) {
Meador Ingeb8897442017-01-24 02:34:00 +00002096 uint32_t Flag = 0;
2097 if (C == '!')
2098 Invert = !Invert;
Rui Ueyama481ac992017-01-26 02:58:39 +00002099 else if (C == 'w')
Meador Ingeb8897442017-01-24 02:34:00 +00002100 Flag = SHF_WRITE;
Rui Ueyama481ac992017-01-26 02:58:39 +00002101 else if (C == 'x')
Meador Ingeb8897442017-01-24 02:34:00 +00002102 Flag = SHF_EXECINSTR;
Rui Ueyama481ac992017-01-26 02:58:39 +00002103 else if (C == 'a')
Meador Ingeb8897442017-01-24 02:34:00 +00002104 Flag = SHF_ALLOC;
Rui Ueyama481ac992017-01-26 02:58:39 +00002105 else if (C != 'r')
Meador Ingeb8897442017-01-24 02:34:00 +00002106 setError("invalid memory region attribute");
Rui Ueyama481ac992017-01-26 02:58:39 +00002107
Meador Ingeb8897442017-01-24 02:34:00 +00002108 if (Invert)
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002109 NegFlags |= Flag;
Meador Ingeb8897442017-01-24 02:34:00 +00002110 else
2111 Flags |= Flag;
2112 }
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002113 return {Flags, NegFlags};
Meador Ingeb8897442017-01-24 02:34:00 +00002114}
2115
Rui Ueyama07320e42016-04-20 20:13:41 +00002116void elf::readLinkerScript(MemoryBufferRef MB) {
Rui Ueyama22375f22016-11-25 18:51:54 +00002117 ScriptParser(MB).readLinkerScript();
George Rimar20b65982016-08-31 09:08:26 +00002118}
2119
2120void elf::readVersionScript(MemoryBufferRef MB) {
Rui Ueyama22375f22016-11-25 18:51:54 +00002121 ScriptParser(MB).readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00002122}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00002123
Rafael Espindolad0ebd842016-12-08 17:54:26 +00002124void elf::readDynamicList(MemoryBufferRef MB) {
2125 ScriptParser(MB).readDynamicList();
2126}