blob: 644777dd0556681bf003098649e361b91eca72a4 [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}
99static ExprValue lessThan(ExprValue A, ExprValue B) {
100 return A.getValue() < B.getValue();
101}
102static ExprValue greaterThan(ExprValue A, ExprValue B) {
103 return A.getValue() > B.getValue();
104}
105static ExprValue greaterThanOrEqual(ExprValue A, ExprValue B) {
106 return A.getValue() >= B.getValue();
107}
108static ExprValue lessThanOrEqual(ExprValue A, ExprValue B) {
109 return A.getValue() <= B.getValue();
110}
111static ExprValue equal(ExprValue A, ExprValue B) {
112 return A.getValue() == B.getValue();
113}
114static ExprValue notEqual(ExprValue A, ExprValue B) {
115 return A.getValue() != B.getValue();
116}
117static ExprValue bitAnd(ExprValue A, ExprValue B) {
Rafael Espindola7ba5f472017-03-17 14:55:36 +0000118 moveAbsRight(A, B);
119 return {A.Sec, A.ForceAbsolute,
120 (A.getValue() & B.getValue()) - A.getSecAddr()};
Rafael Espindola72dc1952017-03-17 13:05:04 +0000121}
122static ExprValue bitOr(ExprValue A, ExprValue B) {
Rafael Espindola7ba5f472017-03-17 14:55:36 +0000123 moveAbsRight(A, B);
124 return {A.Sec, A.ForceAbsolute,
125 (A.getValue() | B.getValue()) - A.getSecAddr()};
Rafael Espindola72dc1952017-03-17 13:05:04 +0000126}
127static ExprValue bitNot(ExprValue A) { return ~A.getValue(); }
128static ExprValue minus(ExprValue A) { return -A.getValue(); }
129
George Rimara8dba482017-03-20 10:09:58 +0000130LinkerScriptBase *elf::Script;
Rui Ueyama07320e42016-04-20 20:13:41 +0000131ScriptConfiguration *elf::ScriptConfig;
Rui Ueyama717677a2016-02-11 21:17:59 +0000132
Meador Inge8f1f3c42017-01-09 18:36:57 +0000133template <class ELFT> static SymbolBody *addRegular(SymbolAssignment *Cmd) {
Petr Hosek5e51f7d2017-02-21 22:32:51 +0000134 Symbol *Sym;
Rafael Espindola3dabfc62016-10-31 13:14:53 +0000135 uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
Petr Hosek5e51f7d2017-02-21 22:32:51 +0000136 std::tie(Sym, std::ignore) = Symtab<ELFT>::X->insert(
137 Cmd->Name, /*Type*/ 0, Visibility, /*CanOmitFromDynSym*/ false,
138 /*File*/ nullptr);
139 Sym->Binding = STB_GLOBAL;
Rafael Espindola72dc1952017-03-17 13:05:04 +0000140 ExprValue Value = Cmd->Expression();
141 SectionBase *Sec = Value.isAbsolute() ? nullptr : Value.Sec;
Rui Ueyama80474a22017-02-28 19:29:55 +0000142 replaceBody<DefinedRegular>(Sym, Cmd->Name, /*IsLocal=*/false, Visibility,
Rafael Espindola5616adf2017-03-08 22:36:28 +0000143 STT_NOTYPE, 0, 0, Sec, nullptr);
Meador Inge8f1f3c42017-01-09 18:36:57 +0000144 return Sym->body();
Eugene Leviantceabe802016-08-11 07:56:43 +0000145}
146
Rui Ueyama22375f22016-11-25 18:51:54 +0000147static bool isUnderSysroot(StringRef Path) {
148 if (Config->Sysroot == "")
149 return false;
150 for (; !Path.empty(); Path = sys::path::parent_path(Path))
151 if (sys::fs::equivalent(Config->Sysroot, Path))
152 return true;
153 return false;
154}
155
George Rimar851dc1e2017-03-14 10:15:53 +0000156OutputSection *LinkerScriptBase::getOutputSection(const Twine &Loc,
157 StringRef Name) {
158 static OutputSection FakeSec("", 0, 0);
159
160 for (OutputSection *Sec : *OutputSections)
161 if (Sec->Name == Name)
162 return Sec;
163
Rafael Espindola72dc1952017-03-17 13:05:04 +0000164 if (ErrorOnMissingSection)
165 error(Loc + ": undefined section " + Name);
George Rimar851dc1e2017-03-14 10:15:53 +0000166 return &FakeSec;
167}
168
George Rimard83ce1b2017-03-14 10:24:47 +0000169// This function is essentially the same as getOutputSection(Name)->Size,
170// but it won't print out an error message if a given section is not found.
171//
172// Linker script does not create an output section if its content is empty.
173// We want to allow SIZEOF(.foo) where .foo is a section which happened to
174// be empty. That is why this function is different from getOutputSection().
175uint64_t LinkerScriptBase::getOutputSectionSize(StringRef Name) {
176 for (OutputSection *Sec : *OutputSections)
177 if (Sec->Name == Name)
178 return Sec->Size;
179 return 0;
180}
181
George Rimara2a1ef12017-03-14 12:03:34 +0000182void LinkerScriptBase::setDot(Expr E, const Twine &Loc, bool InSec) {
Rafael Espindola72dc1952017-03-17 13:05:04 +0000183 uint64_t Val = E().getValue();
Rafael Espindola679828f2017-02-17 16:26:13 +0000184 if (Val < Dot) {
185 if (InSec)
George Rimar2ee2d2d2017-02-21 14:50:38 +0000186 error(Loc + ": unable to move location counter backward for: " +
187 CurOutSec->Name);
Rafael Espindola679828f2017-02-17 16:26:13 +0000188 else
George Rimar2ee2d2d2017-02-21 14:50:38 +0000189 error(Loc + ": unable to move location counter backward");
Rafael Espindola679828f2017-02-17 16:26:13 +0000190 }
191 Dot = Val;
192 // Update to location counter means update to section size.
193 if (InSec)
194 CurOutSec->Size = Dot - CurOutSec->Addr;
195}
196
George Rimarb2b70972017-02-07 10:23:28 +0000197// Sets value of a symbol. Two kinds of symbols are processed: synthetic
198// symbols, whose value is an offset from beginning of section and regular
199// symbols whose value is absolute.
George Rimara2a1ef12017-03-14 12:03:34 +0000200void LinkerScriptBase::assignSymbol(SymbolAssignment *Cmd, bool InSec) {
Rafael Espindola4cd73522017-02-17 16:01:51 +0000201 if (Cmd->Name == ".") {
George Rimar2ee2d2d2017-02-21 14:50:38 +0000202 setDot(Cmd->Expression, Cmd->Location, InSec);
Rafael Espindola4cd73522017-02-17 16:01:51 +0000203 return;
204 }
205
George Rimarb2b70972017-02-07 10:23:28 +0000206 if (!Cmd->Sym)
Meador Inge8f1f3c42017-01-09 18:36:57 +0000207 return;
208
Rafael Espindola5616adf2017-03-08 22:36:28 +0000209 auto *Sym = cast<DefinedRegular>(Cmd->Sym);
Rafael Espindola72dc1952017-03-17 13:05:04 +0000210 ExprValue V = Cmd->Expression();
211 if (V.isAbsolute()) {
212 Sym->Value = V.getValue();
213 } else {
214 Sym->Section = V.Sec;
215 if (Sym->Section->Flags & SHF_ALLOC)
216 Sym->Value = V.Val;
217 else
218 Sym->Value = V.getValue();
Meador Inge8f1f3c42017-01-09 18:36:57 +0000219 }
Eugene Leviantdb741e72016-09-07 07:08:43 +0000220}
Meador Inge8f1f3c42017-01-09 18:36:57 +0000221
George Rimara8dba482017-03-20 10:09:58 +0000222static SymbolBody *findSymbol(StringRef S) {
223 switch (Config->EKind) {
224 case ELF32LEKind:
225 return Symtab<ELF32LE>::X->find(S);
226 case ELF32BEKind:
227 return Symtab<ELF32BE>::X->find(S);
228 case ELF64LEKind:
229 return Symtab<ELF64LE>::X->find(S);
230 case ELF64BEKind:
231 return Symtab<ELF64BE>::X->find(S);
232 default:
233 llvm_unreachable("unknown Config->EKind");
234 }
235}
236
237static SymbolBody *addRegularSymbol(SymbolAssignment *Cmd) {
238 switch (Config->EKind) {
239 case ELF32LEKind:
240 return addRegular<ELF32LE>(Cmd);
241 case ELF32BEKind:
242 return addRegular<ELF32BE>(Cmd);
243 case ELF64LEKind:
244 return addRegular<ELF64LE>(Cmd);
245 case ELF64BEKind:
246 return addRegular<ELF64BE>(Cmd);
247 default:
248 llvm_unreachable("unknown Config->EKind");
249 }
250}
251
252void LinkerScriptBase::addSymbol(SymbolAssignment *Cmd) {
Rui Ueyama16024212016-08-11 23:22:52 +0000253 if (Cmd->Name == ".")
Meador Inge8f1f3c42017-01-09 18:36:57 +0000254 return;
255
256 // If a symbol was in PROVIDE(), we need to define it only when
257 // it is a referenced undefined symbol.
George Rimara8dba482017-03-20 10:09:58 +0000258 SymbolBody *B = findSymbol(Cmd->Name);
Meador Inge8f1f3c42017-01-09 18:36:57 +0000259 if (Cmd->Provide && (!B || B->isDefined()))
260 return;
261
George Rimara8dba482017-03-20 10:09:58 +0000262 Cmd->Sym = addRegularSymbol(Cmd);
Eugene Leviantceabe802016-08-11 07:56:43 +0000263}
264
George Rimar076fe152016-07-21 06:43:01 +0000265bool SymbolAssignment::classof(const BaseCommand *C) {
266 return C->Kind == AssignmentKind;
267}
268
269bool OutputSectionCommand::classof(const BaseCommand *C) {
270 return C->Kind == OutputSectionKind;
271}
272
George Rimareea31142016-07-21 14:26:59 +0000273bool InputSectionDescription::classof(const BaseCommand *C) {
274 return C->Kind == InputSectionKind;
275}
276
George Rimareefa7582016-08-04 09:29:31 +0000277bool AssertCommand::classof(const BaseCommand *C) {
278 return C->Kind == AssertKind;
279}
280
George Rimare38cbab2016-09-26 19:22:50 +0000281bool BytesDataCommand::classof(const BaseCommand *C) {
282 return C->Kind == BytesDataKind;
283}
284
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000285static StringRef basename(InputSectionBase *S) {
286 if (S->File)
287 return sys::path::filename(S->File->getName());
Rui Ueyamae0be2902016-11-21 02:10:12 +0000288 return "";
289}
290
George Rimara2a1ef12017-03-14 12:03:34 +0000291bool LinkerScriptBase::shouldKeep(InputSectionBase *S) {
Rui Ueyamae0be2902016-11-21 02:10:12 +0000292 for (InputSectionDescription *ID : Opt.KeptSections)
293 if (ID->FilePat.match(basename(S)))
294 for (SectionPattern &P : ID->SectionPatterns)
295 if (P.SectionPat.match(S->Name))
296 return true;
George Rimareea31142016-07-21 14:26:59 +0000297 return false;
298}
299
Rafael Espindolac404d502017-02-23 02:32:18 +0000300static bool comparePriority(InputSectionBase *A, InputSectionBase *B) {
George Rimar575208c2016-09-15 19:15:12 +0000301 return getPriority(A->Name) < getPriority(B->Name);
302}
303
Rafael Espindolac404d502017-02-23 02:32:18 +0000304static bool compareName(InputSectionBase *A, InputSectionBase *B) {
Rafael Espindola042a3f22016-09-08 14:06:08 +0000305 return A->Name < B->Name;
Rui Ueyama742c3832016-08-04 22:27:00 +0000306}
George Rimar350ece42016-08-03 08:35:59 +0000307
Rafael Espindolac404d502017-02-23 02:32:18 +0000308static bool compareAlignment(InputSectionBase *A, InputSectionBase *B) {
Rui Ueyama742c3832016-08-04 22:27:00 +0000309 // ">" is not a mistake. Larger alignments are placed before smaller
310 // alignments in order to reduce the amount of padding necessary.
311 // This is compatible with GNU.
312 return A->Alignment > B->Alignment;
313}
George Rimar350ece42016-08-03 08:35:59 +0000314
Rafael Espindolac404d502017-02-23 02:32:18 +0000315static std::function<bool(InputSectionBase *, InputSectionBase *)>
George Rimarbe394db2016-09-16 20:21:55 +0000316getComparator(SortSectionPolicy K) {
317 switch (K) {
318 case SortSectionPolicy::Alignment:
319 return compareAlignment;
320 case SortSectionPolicy::Name:
Rafael Espindolac0028d32016-09-08 20:47:52 +0000321 return compareName;
George Rimarbe394db2016-09-16 20:21:55 +0000322 case SortSectionPolicy::Priority:
323 return comparePriority;
324 default:
325 llvm_unreachable("unknown sort policy");
326 }
Rui Ueyama742c3832016-08-04 22:27:00 +0000327}
George Rimar0702c4e2016-07-29 15:32:46 +0000328
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000329static bool matchConstraints(ArrayRef<InputSectionBase *> Sections,
George Rimar06ae6832016-08-12 09:07:57 +0000330 ConstraintKind Kind) {
George Rimar8f66df92016-08-12 20:38:20 +0000331 if (Kind == ConstraintKind::NoConstraint)
332 return true;
Rafael Espindolac404d502017-02-23 02:32:18 +0000333 bool IsRW = llvm::any_of(Sections, [=](InputSectionBase *Sec2) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000334 auto *Sec = static_cast<InputSectionBase *>(Sec2);
Rafael Espindola1854a8e2016-10-26 12:36:56 +0000335 return Sec->Flags & SHF_WRITE;
George Rimar06ae6832016-08-12 09:07:57 +0000336 });
Rafael Espindolae746e522016-09-21 18:33:44 +0000337 return (IsRW && Kind == ConstraintKind::ReadWrite) ||
338 (!IsRW && Kind == ConstraintKind::ReadOnly);
George Rimar06ae6832016-08-12 09:07:57 +0000339}
340
Rafael Espindolac404d502017-02-23 02:32:18 +0000341static void sortSections(InputSectionBase **Begin, InputSectionBase **End,
Rui Ueyamaee924702016-09-20 19:42:41 +0000342 SortSectionPolicy K) {
343 if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
George Rimar07171f22016-09-21 15:56:44 +0000344 std::stable_sort(Begin, End, getComparator(K));
Rui Ueyamaee924702016-09-20 19:42:41 +0000345}
346
Rafael Espindolad3190792016-09-16 15:10:23 +0000347// Compute and remember which sections the InputSectionDescription matches.
George Rimara2a1ef12017-03-14 12:03:34 +0000348void LinkerScriptBase::computeInputSections(InputSectionDescription *I) {
Rui Ueyama4dc07be2016-09-17 02:23:40 +0000349 // Collects all sections that satisfy constraints of I
350 // and attach them to I.
351 for (SectionPattern &Pat : I->SectionPatterns) {
George Rimar07171f22016-09-21 15:56:44 +0000352 size_t SizeBefore = I->Sections.size();
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000353
Rui Ueyama536a2672017-02-27 02:32:08 +0000354 for (InputSectionBase *S : InputSections) {
Rafael Espindola3773bca2017-02-17 19:37:30 +0000355 if (S->Assigned)
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000356 continue;
Rafael Espindola908a3d32017-02-16 14:36:09 +0000357 // For -emit-relocs we have to ignore entries like
358 // .rela.dyn : { *(.rela.data) }
359 // which are common because they are in the default bfd script.
360 if (S->Type == SHT_REL || S->Type == SHT_RELA)
361 continue;
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000362
Rui Ueyamae0be2902016-11-21 02:10:12 +0000363 StringRef Filename = basename(S);
364 if (!I->FilePat.match(Filename) || Pat.ExcludedFilePat.match(Filename))
365 continue;
366 if (!Pat.SectionPat.match(S->Name))
367 continue;
368 I->Sections.push_back(S);
369 S->Assigned = true;
George Rimar395281c2016-09-16 17:42:10 +0000370 }
Rafael Espindolad3190792016-09-16 15:10:23 +0000371
George Rimar07171f22016-09-21 15:56:44 +0000372 // Sort sections as instructed by SORT-family commands and --sort-section
373 // option. Because SORT-family commands can be nested at most two depth
374 // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
375 // line option is respected even if a SORT command is given, the exact
376 // behavior we have here is a bit complicated. Here are the rules.
377 //
378 // 1. If two SORT commands are given, --sort-section is ignored.
379 // 2. If one SORT command is given, and if it is not SORT_NONE,
380 // --sort-section is handled as an inner SORT command.
381 // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
382 // 4. If no SORT command is given, sort according to --sort-section.
Rafael Espindolac404d502017-02-23 02:32:18 +0000383 InputSectionBase **Begin = I->Sections.data() + SizeBefore;
384 InputSectionBase **End = I->Sections.data() + I->Sections.size();
George Rimar07171f22016-09-21 15:56:44 +0000385 if (Pat.SortOuter != SortSectionPolicy::None) {
386 if (Pat.SortInner == SortSectionPolicy::Default)
387 sortSections(Begin, End, Config->SortSection);
388 else
389 sortSections(Begin, End, Pat.SortInner);
390 sortSections(Begin, End, Pat.SortOuter);
391 }
Rui Ueyamaee924702016-09-20 19:42:41 +0000392 }
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000393}
394
George Rimar503206c2017-03-15 15:42:44 +0000395void LinkerScriptBase::discard(ArrayRef<InputSectionBase *> V) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000396 for (InputSectionBase *S : V) {
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000397 S->Live = false;
George Rimar503206c2017-03-15 15:42:44 +0000398 if (S == InX::ShStrTab)
Rafael Espindolaecbfd872017-02-17 17:35:07 +0000399 error("discarding .shstrtab section is not allowed");
George Rimar647c1682017-02-17 19:34:05 +0000400 discard(S->DependentSections);
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000401 }
402}
403
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000404std::vector<InputSectionBase *>
George Rimara2a1ef12017-03-14 12:03:34 +0000405LinkerScriptBase::createInputSectionList(OutputSectionCommand &OutCmd) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000406 std::vector<InputSectionBase *> Ret;
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000407
George Rimar06ae6832016-08-12 09:07:57 +0000408 for (const std::unique_ptr<BaseCommand> &Base : OutCmd.Commands) {
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000409 auto *Cmd = dyn_cast<InputSectionDescription>(Base.get());
410 if (!Cmd)
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000411 continue;
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000412 computeInputSections(Cmd);
Rafael Espindolac404d502017-02-23 02:32:18 +0000413 for (InputSectionBase *S : Cmd->Sections)
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000414 Ret.push_back(static_cast<InputSectionBase *>(S));
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000415 }
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000416
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000417 return Ret;
418}
419
George Rimara8dba482017-03-20 10:09:58 +0000420void LinkerScriptBase::processCommands(OutputSectionFactory &Factory) {
Rafael Espindola5616adf2017-03-08 22:36:28 +0000421 // A symbol can be assigned before any section is mentioned in the linker
422 // script. In an DSO, the symbol values are addresses, so the only important
423 // section values are:
424 // * SHN_UNDEF
425 // * SHN_ABS
426 // * Any value meaning a regular section.
427 // To handle that, create a dummy aether section that fills the void before
428 // the linker scripts switches to another section. It has an index of one
429 // which will map to whatever the first actual section is.
430 Aether = make<OutputSection>("", 0, SHF_ALLOC);
431 Aether->SectionIndex = 1;
432 CurOutSec = Aether;
433
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000434 for (unsigned I = 0; I < Opt.Commands.size(); ++I) {
435 auto Iter = Opt.Commands.begin() + I;
436 const std::unique_ptr<BaseCommand> &Base1 = *Iter;
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000437
438 // Handle symbol assignments outside of any output section.
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000439 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base1.get())) {
Rafael Espindola4cd73522017-02-17 16:01:51 +0000440 addSymbol(Cmd);
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000441 continue;
442 }
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000443
Eugene Leviantceabe802016-08-11 07:56:43 +0000444 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000445 std::vector<InputSectionBase *> V = createInputSectionList(*Cmd);
Rafael Espindola7bd37872016-09-12 16:05:16 +0000446
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000447 // The output section name `/DISCARD/' is special.
448 // Any input section assigned to it is discarded.
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000449 if (Cmd->Name == "/DISCARD/") {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000450 discard(V);
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000451 continue;
452 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000453
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000454 // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive
455 // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input
456 // sections satisfy a given constraint. If not, a directive is handled
457 // as if it wasn't present from the beginning.
458 //
459 // Because we'll iterate over Commands many more times, the easiest
460 // way to "make it as if it wasn't present" is to just remove it.
George Rimarf7f0d082017-03-14 11:23:33 +0000461 if (!matchConstraints(V, Cmd->Constraint)) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000462 for (InputSectionBase *S : V)
Rui Ueyamaf94efdd2016-11-20 23:15:52 +0000463 S->Assigned = false;
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000464 Opt.Commands.erase(Iter);
George Rimardfbbbc82016-09-17 09:50:10 +0000465 --I;
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000466 continue;
467 }
468
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000469 // A directive may contain symbol definitions like this:
470 // ".foo : { ...; bar = .; }". Handle them.
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000471 for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
472 if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base.get()))
Rafael Espindola4cd73522017-02-17 16:01:51 +0000473 addSymbol(OutCmd);
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000474
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000475 // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign
476 // is given, input sections are aligned to that value, whether the
477 // given value is larger or smaller than the original section alignment.
478 if (Cmd->SubalignExpr) {
Rafael Espindola72dc1952017-03-17 13:05:04 +0000479 uint32_t Subalign = Cmd->SubalignExpr().getValue();
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000480 for (InputSectionBase *S : V)
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000481 S->Alignment = Subalign;
George Rimardb24d9c2016-08-19 15:18:23 +0000482 }
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000483
484 // Add input sections to an output section.
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000485 for (InputSectionBase *S : V)
George Rimare21c3af2017-03-14 09:30:25 +0000486 Factory.addInputSec(S, Cmd->Name);
Eugene Leviantceabe802016-08-11 07:56:43 +0000487 }
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000488 }
Rafael Espindola5616adf2017-03-08 22:36:28 +0000489 CurOutSec = nullptr;
Eugene Leviant20d03192016-09-16 15:30:47 +0000490}
Eugene Leviante63d81b2016-07-20 14:43:20 +0000491
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000492// Add sections that didn't match any sections command.
George Rimara2a1ef12017-03-14 12:03:34 +0000493void LinkerScriptBase::addOrphanSections(OutputSectionFactory &Factory) {
Rui Ueyama536a2672017-02-27 02:32:08 +0000494 for (InputSectionBase *S : InputSections)
Rafael Espindola8f9026b2016-11-08 18:23:02 +0000495 if (S->Live && !S->OutSec)
George Rimare21c3af2017-03-14 09:30:25 +0000496 Factory.addInputSec(S, getOutputSectionName(S->Name));
Eugene Leviante63d81b2016-07-20 14:43:20 +0000497}
498
George Rimarf7f0d082017-03-14 11:23:33 +0000499static bool isTbss(OutputSection *Sec) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000500 return (Sec->Flags & SHF_TLS) && Sec->Type == SHT_NOBITS;
Rafael Espindolaa940e532016-09-22 12:35:44 +0000501}
502
George Rimara2a1ef12017-03-14 12:03:34 +0000503void LinkerScriptBase::output(InputSection *S) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000504 if (!AlreadyOutputIS.insert(S).second)
505 return;
George Rimarf7f0d082017-03-14 11:23:33 +0000506 bool IsTbss = isTbss(CurOutSec);
Eugene Leviant20889c52016-08-31 08:13:33 +0000507
George Rimar0c1c8082017-03-14 10:00:19 +0000508 uint64_t Pos = IsTbss ? Dot + ThreadBssOffset : Dot;
Rafael Espindolad3190792016-09-16 15:10:23 +0000509 Pos = alignTo(Pos, S->Alignment);
Rafael Espindola04a2e342016-11-09 01:42:41 +0000510 S->OutSecOff = Pos - CurOutSec->Addr;
Rafael Espindola76b6bd32017-03-08 15:44:30 +0000511 Pos += S->getSize();
Rafael Espindolad3190792016-09-16 15:10:23 +0000512
513 // Update output section size after adding each section. This is so that
514 // SIZEOF works correctly in the case below:
515 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
Rafael Espindola04a2e342016-11-09 01:42:41 +0000516 CurOutSec->Size = Pos - CurOutSec->Addr;
Rafael Espindolad3190792016-09-16 15:10:23 +0000517
Meador Ingeb8897442017-01-24 02:34:00 +0000518 // If there is a memory region associated with this input section, then
519 // place the section in that region and update the region index.
520 if (CurMemRegion) {
521 CurMemRegion->Offset += CurOutSec->Size;
522 uint64_t CurSize = CurMemRegion->Offset - CurMemRegion->Origin;
523 if (CurSize > CurMemRegion->Length) {
524 uint64_t OverflowAmt = CurSize - CurMemRegion->Length;
525 error("section '" + CurOutSec->Name + "' will not fit in region '" +
526 CurMemRegion->Name + "': overflowed by " + Twine(OverflowAmt) +
527 " bytes");
528 }
529 }
530
Rafael Espindola7252ae52016-09-22 12:00:08 +0000531 if (IsTbss)
532 ThreadBssOffset = Pos - Dot;
533 else
Rafael Espindolad3190792016-09-16 15:10:23 +0000534 Dot = Pos;
535}
536
George Rimara2a1ef12017-03-14 12:03:34 +0000537void LinkerScriptBase::flush() {
Rafael Espindolabd12e2a2017-03-01 14:12:21 +0000538 assert(CurOutSec);
539 if (!AlreadyOutputOS.insert(CurOutSec).second)
Rafael Espindola65499b92016-09-23 20:10:47 +0000540 return;
Rafael Espindola24e6f362017-02-24 15:07:30 +0000541 for (InputSection *I : CurOutSec->Sections)
542 output(I);
Eugene Leviant20889c52016-08-31 08:13:33 +0000543}
544
George Rimara2a1ef12017-03-14 12:03:34 +0000545void LinkerScriptBase::switchTo(OutputSection *Sec) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000546 if (CurOutSec == Sec)
547 return;
548 if (AlreadyOutputOS.count(Sec))
549 return;
550
Rafael Espindolad3190792016-09-16 15:10:23 +0000551 CurOutSec = Sec;
552
Rafael Espindola37707632017-03-07 14:55:52 +0000553 Dot = alignTo(Dot, CurOutSec->Alignment);
George Rimarf7f0d082017-03-14 11:23:33 +0000554 CurOutSec->Addr = isTbss(CurOutSec) ? Dot + ThreadBssOffset : Dot;
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000555
556 // If neither AT nor AT> is specified for an allocatable section, the linker
557 // will set the LMA such that the difference between VMA and LMA for the
558 // section is the same as the preceding output section in the same region
559 // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
George Rimar21467872017-02-23 07:57:55 +0000560 if (LMAOffset)
Rafael Espindola29c1afb2017-02-24 14:34:12 +0000561 CurOutSec->LMAOffset = LMAOffset();
Rafael Espindolad3190792016-09-16 15:10:23 +0000562}
563
George Rimara2a1ef12017-03-14 12:03:34 +0000564void LinkerScriptBase::process(BaseCommand &Base) {
George Rimare38cbab2016-09-26 19:22:50 +0000565 // This handles the assignments to symbol or to a location counter (.)
Rafael Espindolad3190792016-09-16 15:10:23 +0000566 if (auto *AssignCmd = dyn_cast<SymbolAssignment>(&Base)) {
Rafael Espindola4cd73522017-02-17 16:01:51 +0000567 assignSymbol(AssignCmd, true);
Eugene Leviantceabe802016-08-11 07:56:43 +0000568 return;
Rui Ueyama2de509c2016-08-12 00:55:08 +0000569 }
George Rimare38cbab2016-09-26 19:22:50 +0000570
571 // Handle BYTE(), SHORT(), LONG(), or QUAD().
572 if (auto *DataCmd = dyn_cast<BytesDataCommand>(&Base)) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000573 DataCmd->Offset = Dot - CurOutSec->Addr;
George Rimare38cbab2016-09-26 19:22:50 +0000574 Dot += DataCmd->Size;
Rafael Espindola04a2e342016-11-09 01:42:41 +0000575 CurOutSec->Size = Dot - CurOutSec->Addr;
George Rimare38cbab2016-09-26 19:22:50 +0000576 return;
577 }
578
Meador Ingeb2d99d62016-11-22 18:01:50 +0000579 if (auto *AssertCmd = dyn_cast<AssertCommand>(&Base)) {
Rafael Espindola4595df92017-03-10 16:04:26 +0000580 AssertCmd->Expression();
Meador Ingeb2d99d62016-11-22 18:01:50 +0000581 return;
582 }
583
George Rimare38cbab2016-09-26 19:22:50 +0000584 // It handles single input section description command,
585 // calculates and assigns the offsets for each section and also
586 // updates the output section size.
Rafael Espindolad3190792016-09-16 15:10:23 +0000587 auto &ICmd = cast<InputSectionDescription>(Base);
Rafael Espindolabd12e2a2017-03-01 14:12:21 +0000588 for (InputSectionBase *IB : ICmd.Sections) {
George Rimar3fb5a6d2016-11-29 16:05:27 +0000589 // We tentatively added all synthetic sections at the beginning and removed
590 // empty ones afterwards (because there is no way to know whether they were
591 // going be empty or not other than actually running linker scripts.)
592 // We need to ignore remains of empty sections.
Rafael Espindolabd12e2a2017-03-01 14:12:21 +0000593 if (auto *Sec = dyn_cast<SyntheticSection>(IB))
George Rimar3fb5a6d2016-11-29 16:05:27 +0000594 if (Sec->empty())
595 continue;
596
George Rimar78ef6452017-02-21 15:46:43 +0000597 if (!IB->Live)
598 continue;
Rafael Espindolabedccb5e2017-03-01 14:21:31 +0000599 assert(CurOutSec == IB->OutSec || AlreadyOutputOS.count(IB->OutSec));
Rafael Espindolabd12e2a2017-03-01 14:12:21 +0000600 output(cast<InputSection>(IB));
Eugene Leviantceabe802016-08-11 07:56:43 +0000601 }
602}
603
Rafael Espindola24e6f362017-02-24 15:07:30 +0000604static OutputSection *
605findSection(StringRef Name, const std::vector<OutputSection *> &Sections) {
Rafael Espindola2b074552017-02-03 22:27:05 +0000606 auto End = Sections.end();
Rafael Espindola24e6f362017-02-24 15:07:30 +0000607 auto HasName = [=](OutputSection *Sec) { return Sec->Name == Name; };
Rafael Espindola2b074552017-02-03 22:27:05 +0000608 auto I = std::find_if(Sections.begin(), End, HasName);
Rafael Espindola24e6f362017-02-24 15:07:30 +0000609 std::vector<OutputSection *> Ret;
Rafael Espindola2b074552017-02-03 22:27:05 +0000610 if (I == End)
611 return nullptr;
612 assert(std::find_if(I + 1, End, HasName) == End);
613 return *I;
George Rimar8f66df92016-08-12 20:38:20 +0000614}
615
Meador Ingeb8897442017-01-24 02:34:00 +0000616// This function searches for a memory region to place the given output
617// section in. If found, a pointer to the appropriate memory region is
618// returned. Otherwise, a nullptr is returned.
George Rimara2a1ef12017-03-14 12:03:34 +0000619MemoryRegion *LinkerScriptBase::findMemoryRegion(OutputSectionCommand *Cmd,
620 OutputSection *Sec) {
Meador Ingeb8897442017-01-24 02:34:00 +0000621 // If a memory region name was specified in the output section command,
622 // then try to find that region first.
623 if (!Cmd->MemoryRegionName.empty()) {
624 auto It = Opt.MemoryRegions.find(Cmd->MemoryRegionName);
625 if (It != Opt.MemoryRegions.end())
626 return &It->second;
627 error("memory region '" + Cmd->MemoryRegionName + "' not declared");
628 return nullptr;
629 }
630
631 // The memory region name is empty, thus a suitable region must be
632 // searched for in the region map. If the region map is empty, just
633 // return. Note that this check doesn't happen at the very beginning
634 // so that uses of undeclared regions can be caught.
635 if (!Opt.MemoryRegions.size())
636 return nullptr;
637
638 // See if a region can be found by matching section flags.
639 for (auto &MRI : Opt.MemoryRegions) {
640 MemoryRegion &MR = MRI.second;
Rui Ueyama8a8a9532017-01-26 02:58:59 +0000641 if ((MR.Flags & Sec->Flags) != 0 && (MR.NegFlags & Sec->Flags) == 0)
Meador Ingeb8897442017-01-24 02:34:00 +0000642 return &MR;
643 }
644
645 // Otherwise, no suitable region was found.
646 if (Sec->Flags & SHF_ALLOC)
647 error("no memory region specified for section '" + Sec->Name + "'");
648 return nullptr;
649}
650
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000651// This function assigns offsets to input sections and an output section
652// for a single sections command (e.g. ".text { *(.text); }").
George Rimara2a1ef12017-03-14 12:03:34 +0000653void LinkerScriptBase::assignOffsets(OutputSectionCommand *Cmd) {
George Rimar23e6a022017-03-14 11:31:28 +0000654 OutputSection *Sec = findSection(Cmd->Name, *OutputSections);
Rafael Espindola2b074552017-02-03 22:27:05 +0000655 if (!Sec)
Rafael Espindolad3190792016-09-16 15:10:23 +0000656 return;
Meador Ingeb8897442017-01-24 02:34:00 +0000657
Rafael Espindola679828f2017-02-17 16:26:13 +0000658 if (Cmd->AddrExpr && Sec->Flags & SHF_ALLOC)
George Rimar2ee2d2d2017-02-21 14:50:38 +0000659 setDot(Cmd->AddrExpr, Cmd->Location);
Rafael Espindola679828f2017-02-17 16:26:13 +0000660
Eugene Leviant5784e962017-03-14 08:57:09 +0000661 if (Cmd->LMAExpr) {
George Rimar0c1c8082017-03-14 10:00:19 +0000662 uint64_t D = Dot;
Rafael Espindola72dc1952017-03-17 13:05:04 +0000663 LMAOffset = [=] { return Cmd->LMAExpr().getValue() - D; };
Eugene Leviant5784e962017-03-14 08:57:09 +0000664 }
665
Petr Hosek165088a2017-02-07 23:42:31 +0000666 // Handle align (e.g. ".foo : ALIGN(16) { ... }").
667 if (Cmd->AlignExpr)
Rafael Espindola72dc1952017-03-17 13:05:04 +0000668 Sec->updateAlignment(Cmd->AlignExpr().getValue());
Petr Hosek165088a2017-02-07 23:42:31 +0000669
Meador Ingeb8897442017-01-24 02:34:00 +0000670 // Try and find an appropriate memory region to assign offsets in.
671 CurMemRegion = findMemoryRegion(Cmd, Sec);
672 if (CurMemRegion)
673 Dot = CurMemRegion->Offset;
674 switchTo(Sec);
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000675
Rafael Espindolad3190792016-09-16 15:10:23 +0000676 // Find the last section output location. We will output orphan sections
677 // there so that end symbols point to the correct location.
678 auto E = std::find_if(Cmd->Commands.rbegin(), Cmd->Commands.rend(),
679 [](const std::unique_ptr<BaseCommand> &Cmd) {
680 return !isa<SymbolAssignment>(*Cmd);
681 })
682 .base();
683 for (auto I = Cmd->Commands.begin(); I != E; ++I)
684 process(**I);
Rafael Espindola65499b92016-09-23 20:10:47 +0000685 flush();
George Rimarb31dd372016-09-19 13:27:31 +0000686 std::for_each(E, Cmd->Commands.end(),
687 [this](std::unique_ptr<BaseCommand> &B) { process(*B.get()); });
Rafael Espindolad3190792016-09-16 15:10:23 +0000688}
689
George Rimara2a1ef12017-03-14 12:03:34 +0000690void LinkerScriptBase::removeEmptyCommands() {
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000691 // It is common practice to use very generic linker scripts. So for any
692 // given run some of the output sections in the script will be empty.
693 // We could create corresponding empty output sections, but that would
694 // clutter the output.
695 // We instead remove trivially empty sections. The bfd linker seems even
696 // more aggressive at removing them.
697 auto Pos = std::remove_if(
698 Opt.Commands.begin(), Opt.Commands.end(),
699 [&](const std::unique_ptr<BaseCommand> &Base) {
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000700 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
George Rimar23e6a022017-03-14 11:31:28 +0000701 return !findSection(Cmd->Name, *OutputSections);
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000702 return false;
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000703 });
704 Opt.Commands.erase(Pos, Opt.Commands.end());
Rafael Espindola07fe6122016-11-14 14:23:35 +0000705}
706
Rafael Espindola6a537372016-11-14 14:33:49 +0000707static bool isAllSectionDescription(const OutputSectionCommand &Cmd) {
708 for (const std::unique_ptr<BaseCommand> &I : Cmd.Commands)
709 if (!isa<InputSectionDescription>(*I))
710 return false;
711 return true;
712}
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000713
George Rimara2a1ef12017-03-14 12:03:34 +0000714void LinkerScriptBase::adjustSectionsBeforeSorting() {
Rafael Espindola9546fff2016-09-22 14:40:50 +0000715 // If the output section contains only symbol assignments, create a
716 // corresponding output section. The bfd linker seems to only create them if
717 // '.' is assigned to, but creating these section should not have any bad
718 // consequeces and gives us a section to put the symbol in.
George Rimar0c1c8082017-03-14 10:00:19 +0000719 uint64_t Flags = SHF_ALLOC;
Rafael Espindolaf93b8c22016-11-26 06:55:35 +0000720 uint32_t Type = SHT_NOBITS;
Rafael Espindola9546fff2016-09-22 14:40:50 +0000721 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
722 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
723 if (!Cmd)
724 continue;
George Rimar23e6a022017-03-14 11:31:28 +0000725 if (OutputSection *Sec = findSection(Cmd->Name, *OutputSections)) {
Rafael Espindola2b074552017-02-03 22:27:05 +0000726 Flags = Sec->Flags;
727 Type = Sec->Type;
Rafael Espindola9546fff2016-09-22 14:40:50 +0000728 continue;
729 }
730
Rafael Espindola6a537372016-11-14 14:33:49 +0000731 if (isAllSectionDescription(*Cmd))
732 continue;
733
Rafael Espindola24e6f362017-02-24 15:07:30 +0000734 auto *OutSec = make<OutputSection>(Cmd->Name, Type, Flags);
Rafael Espindola9546fff2016-09-22 14:40:50 +0000735 OutputSections->push_back(OutSec);
736 }
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000737}
738
George Rimara2a1ef12017-03-14 12:03:34 +0000739void LinkerScriptBase::adjustSectionsAfterSorting() {
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000740 placeOrphanSections();
741
742 // If output section command doesn't specify any segments,
743 // and we haven't previously assigned any section to segment,
744 // then we simply assign section to the very first load segment.
745 // Below is an example of such linker script:
746 // PHDRS { seg PT_LOAD; }
747 // SECTIONS { .aaa : { *(.aaa) } }
748 std::vector<StringRef> DefPhdrs;
749 auto FirstPtLoad =
750 std::find_if(Opt.PhdrsCommands.begin(), Opt.PhdrsCommands.end(),
751 [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; });
752 if (FirstPtLoad != Opt.PhdrsCommands.end())
753 DefPhdrs.push_back(FirstPtLoad->Name);
754
755 // Walk the commands and propagate the program headers to commands that don't
756 // explicitly specify them.
757 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
758 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
759 if (!Cmd)
760 continue;
761 if (Cmd->Phdrs.empty())
762 Cmd->Phdrs = DefPhdrs;
763 else
764 DefPhdrs = Cmd->Phdrs;
765 }
Rafael Espindola6a537372016-11-14 14:33:49 +0000766
767 removeEmptyCommands();
Rafael Espindola9546fff2016-09-22 14:40:50 +0000768}
769
Rafael Espindola15c57952016-09-22 18:05:49 +0000770// When placing orphan sections, we want to place them after symbol assignments
771// so that an orphan after
772// begin_foo = .;
773// foo : { *(foo) }
774// end_foo = .;
775// doesn't break the intended meaning of the begin/end symbols.
776// We don't want to go over sections since Writer<ELFT>::sortSections is the
777// one in charge of deciding the order of the sections.
778// We don't want to go over alignments, since doing so in
779// rx_sec : { *(rx_sec) }
780// . = ALIGN(0x1000);
781// /* The RW PT_LOAD starts here*/
782// rw_sec : { *(rw_sec) }
783// would mean that the RW PT_LOAD would become unaligned.
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000784static bool shouldSkip(const BaseCommand &Cmd) {
Rafael Espindola15c57952016-09-22 18:05:49 +0000785 if (isa<OutputSectionCommand>(Cmd))
786 return false;
787 const auto *Assign = dyn_cast<SymbolAssignment>(&Cmd);
788 if (!Assign)
789 return true;
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000790 return Assign->Name != ".";
Rafael Espindola15c57952016-09-22 18:05:49 +0000791}
792
Rui Ueyama6697ec22017-02-02 23:26:12 +0000793// Orphan sections are sections present in the input files which are
794// not explicitly placed into the output file by the linker script.
795//
796// When the control reaches this function, Opt.Commands contains
797// output section commands for non-orphan sections only. This function
798// adds new elements for orphan sections to Opt.Commands so that all
799// sections are explicitly handled by Opt.Commands.
800//
801// Writer<ELFT>::sortSections has already sorted output sections.
802// What we need to do is to scan OutputSections vector and
803// Opt.Commands in parallel to find orphan sections. If there is an
804// output section that doesn't have a corresponding entry in
805// Opt.Commands, we will insert a new entry to Opt.Commands.
806//
807// There is some ambiguity as to where exactly a new entry should be
808// inserted, because Opt.Commands contains not only output section
809// commands but other types of commands such as symbol assignment
810// expressions. There's no correct answer here due to the lack of the
811// formal specification of the linker script. We use heuristics to
812// determine whether a new output command should be added before or
813// after another commands. For the details, look at shouldSkip
814// function.
George Rimara2a1ef12017-03-14 12:03:34 +0000815void LinkerScriptBase::placeOrphanSections() {
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000816 // The OutputSections are already in the correct order.
817 // This loops creates or moves commands as needed so that they are in the
818 // correct order.
819 int CmdIndex = 0;
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000820
821 // As a horrible special case, skip the first . assignment if it is before any
822 // section. We do this because it is common to set a load address by starting
823 // the script with ". = 0xabcd" and the expectation is that every section is
824 // after that.
825 auto FirstSectionOrDotAssignment =
826 std::find_if(Opt.Commands.begin(), Opt.Commands.end(),
827 [](const std::unique_ptr<BaseCommand> &Cmd) {
828 if (isa<OutputSectionCommand>(*Cmd))
829 return true;
830 const auto *Assign = dyn_cast<SymbolAssignment>(Cmd.get());
831 if (!Assign)
832 return false;
833 return Assign->Name == ".";
834 });
835 if (FirstSectionOrDotAssignment != Opt.Commands.end()) {
836 CmdIndex = FirstSectionOrDotAssignment - Opt.Commands.begin();
837 if (isa<SymbolAssignment>(**FirstSectionOrDotAssignment))
838 ++CmdIndex;
839 }
840
Rafael Espindola24e6f362017-02-24 15:07:30 +0000841 for (OutputSection *Sec : *OutputSections) {
Rafael Espindola40849412017-02-24 14:28:00 +0000842 StringRef Name = Sec->Name;
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000843
844 // Find the last spot where we can insert a command and still get the
Rafael Espindola15c57952016-09-22 18:05:49 +0000845 // correct result.
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000846 auto CmdIter = Opt.Commands.begin() + CmdIndex;
847 auto E = Opt.Commands.end();
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000848 while (CmdIter != E && shouldSkip(**CmdIter)) {
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000849 ++CmdIter;
850 ++CmdIndex;
851 }
852
853 auto Pos =
854 std::find_if(CmdIter, E, [&](const std::unique_ptr<BaseCommand> &Base) {
855 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
856 return Cmd && Cmd->Name == Name;
857 });
858 if (Pos == E) {
859 Opt.Commands.insert(CmdIter,
860 llvm::make_unique<OutputSectionCommand>(Name));
Rafael Espindola15c57952016-09-22 18:05:49 +0000861 ++CmdIndex;
862 continue;
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000863 }
Rafael Espindola15c57952016-09-22 18:05:49 +0000864
865 // Continue from where we found it.
866 CmdIndex = (Pos - Opt.Commands.begin()) + 1;
George Rimar652852c2016-04-16 10:10:32 +0000867 }
Rafael Espindola337f9032016-11-14 14:13:32 +0000868}
869
Petr Hosek02ad5162017-03-15 03:33:23 +0000870void LinkerScriptBase::processNonSectionCommands() {
871 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
872 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get()))
873 assignSymbol(Cmd);
874 else if (auto *Cmd = dyn_cast<AssertCommand>(Base.get()))
875 Cmd->Expression();
876 }
877}
878
George Rimara2a1ef12017-03-14 12:03:34 +0000879void LinkerScriptBase::assignAddresses(std::vector<PhdrEntry> &Phdrs) {
Rui Ueyama7c18c282016-04-18 21:00:40 +0000880 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rafael Espindolabe607332016-09-30 00:16:11 +0000881 Dot = 0;
Rafael Espindola72dc1952017-03-17 13:05:04 +0000882 ErrorOnMissingSection = true;
Rafael Espindola06f47432017-02-06 22:21:46 +0000883 switchTo(Aether);
884
George Rimar076fe152016-07-21 06:43:01 +0000885 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
886 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
Rafael Espindola4cd73522017-02-17 16:01:51 +0000887 assignSymbol(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000888 continue;
889 }
890
George Rimareefa7582016-08-04 09:29:31 +0000891 if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
Rafael Espindola4595df92017-03-10 16:04:26 +0000892 Cmd->Expression();
George Rimareefa7582016-08-04 09:29:31 +0000893 continue;
894 }
895
George Rimar076fe152016-07-21 06:43:01 +0000896 auto *Cmd = cast<OutputSectionCommand>(Base.get());
Rafael Espindolad3190792016-09-16 15:10:23 +0000897 assignOffsets(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000898 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000899
George Rimar0c1c8082017-03-14 10:00:19 +0000900 uint64_t MinVA = std::numeric_limits<uint64_t>::max();
Rafael Espindola24e6f362017-02-24 15:07:30 +0000901 for (OutputSection *Sec : *OutputSections) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000902 if (Sec->Flags & SHF_ALLOC)
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000903 MinVA = std::min<uint64_t>(MinVA, Sec->Addr);
Rafael Espindolaea590d92017-02-08 15:19:03 +0000904 else
905 Sec->Addr = 0;
906 }
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000907
George Rimar2d262102017-03-14 09:03:53 +0000908 allocateHeaders(Phdrs, *OutputSections, MinVA);
George Rimar652852c2016-04-16 10:10:32 +0000909}
910
Rui Ueyama464daad2016-08-22 04:55:20 +0000911// Creates program headers as instructed by PHDRS linker script command.
George Rimara2a1ef12017-03-14 12:03:34 +0000912std::vector<PhdrEntry> LinkerScriptBase::createPhdrs() {
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000913 std::vector<PhdrEntry> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000914
Rui Ueyama464daad2016-08-22 04:55:20 +0000915 // Process PHDRS and FILEHDR keywords because they are not
916 // real output sections and cannot be added in the following loop.
Eugene Leviantbbe38602016-07-19 09:25:43 +0000917 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000918 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000919 PhdrEntry &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000920
921 if (Cmd.HasFilehdr)
Rui Ueyama9d1bacb12017-02-27 02:31:26 +0000922 Phdr.add(Out::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000923 if (Cmd.HasPhdrs)
Rui Ueyama9d1bacb12017-02-27 02:31:26 +0000924 Phdr.add(Out::ProgramHeaders);
Eugene Leviant56b21c82016-09-09 09:46:16 +0000925
926 if (Cmd.LMAExpr) {
Rafael Espindola72dc1952017-03-17 13:05:04 +0000927 Phdr.p_paddr = Cmd.LMAExpr().getValue();
Eugene Leviant56b21c82016-09-09 09:46:16 +0000928 Phdr.HasLMA = true;
929 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000930 }
931
Rui Ueyama464daad2016-08-22 04:55:20 +0000932 // Add output sections to program headers.
Rafael Espindola24e6f362017-02-24 15:07:30 +0000933 for (OutputSection *Sec : *OutputSections) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000934 if (!(Sec->Flags & SHF_ALLOC))
Eugene Leviantbbe38602016-07-19 09:25:43 +0000935 break;
936
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000937 // Assign headers specified by linker script
Rafael Espindola40849412017-02-24 14:28:00 +0000938 for (size_t Id : getPhdrIndices(Sec->Name)) {
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000939 Ret[Id].add(Sec);
940 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000941 Ret[Id].p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000942 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000943 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000944 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000945}
946
George Rimara2a1ef12017-03-14 12:03:34 +0000947bool LinkerScriptBase::ignoreInterpSection() {
Eugene Leviantf9bc3bd2016-08-16 06:40:58 +0000948 // Ignore .interp section in case we have PHDRS specification
949 // and PT_INTERP isn't listed.
950 return !Opt.PhdrsCommands.empty() &&
951 llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
952 return Cmd.Type == PT_INTERP;
953 }) == Opt.PhdrsCommands.end();
954}
955
George Rimara2a1ef12017-03-14 12:03:34 +0000956uint32_t LinkerScriptBase::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000957 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
958 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
959 if (Cmd->Name == Name)
960 return Cmd->Filler;
Rui Ueyama16068ae2016-11-19 18:05:56 +0000961 return 0;
George Rimare2ee72b2016-02-26 14:48:31 +0000962}
963
George Rimare38cbab2016-09-26 19:22:50 +0000964static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) {
George Rimarb17d16a2017-03-20 10:16:57 +0000965 const endianness E = Config->IsLE ? endianness::little : endianness::big;
George Rimare38cbab2016-09-26 19:22:50 +0000966
967 switch (Size) {
968 case 1:
969 *Buf = (uint8_t)Data;
970 break;
971 case 2:
George Rimara8dba482017-03-20 10:09:58 +0000972 write16(Buf, Data, E);
George Rimare38cbab2016-09-26 19:22:50 +0000973 break;
974 case 4:
George Rimara8dba482017-03-20 10:09:58 +0000975 write32(Buf, Data, E);
George Rimare38cbab2016-09-26 19:22:50 +0000976 break;
977 case 8:
George Rimara8dba482017-03-20 10:09:58 +0000978 write64(Buf, Data, E);
George Rimare38cbab2016-09-26 19:22:50 +0000979 break;
980 default:
981 llvm_unreachable("unsupported Size argument");
982 }
983}
984
George Rimara8dba482017-03-20 10:09:58 +0000985void LinkerScriptBase::writeDataBytes(StringRef Name, uint8_t *Buf) {
George Rimare38cbab2016-09-26 19:22:50 +0000986 int I = getSectionIndex(Name);
987 if (I == INT_MAX)
988 return;
989
Rui Ueyama6e68c5e2016-11-19 18:05:58 +0000990 auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I].get());
991 for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
992 if (auto *Data = dyn_cast<BytesDataCommand>(Base.get()))
George Rimara8dba482017-03-20 10:09:58 +0000993 writeInt(Buf + Data->Offset, Data->Expression().getValue(), Data->Size);
George Rimare38cbab2016-09-26 19:22:50 +0000994}
995
George Rimara2a1ef12017-03-14 12:03:34 +0000996bool LinkerScriptBase::hasLMA(StringRef Name) {
George Rimar8ceadb32016-08-17 07:44:19 +0000997 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
998 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000999 if (Cmd->LMAExpr && Cmd->Name == Name)
1000 return true;
1001 return false;
George Rimar8ceadb32016-08-17 07:44:19 +00001002}
1003
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +00001004// Returns the index of the given section name in linker script
1005// SECTIONS commands. Sections are laid out as the same order as they
1006// were in the script. If a given name did not appear in the script,
1007// it returns INT_MAX, so that it will be laid out at end of file.
George Rimara2a1ef12017-03-14 12:03:34 +00001008int LinkerScriptBase::getSectionIndex(StringRef Name) {
Rui Ueyama6e68c5e2016-11-19 18:05:58 +00001009 for (int I = 0, E = Opt.Commands.size(); I != E; ++I)
1010 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I].get()))
Rui Ueyamaf510fa62016-07-26 00:21:15 +00001011 if (Cmd->Name == Name)
1012 return I;
Rui Ueyamaf510fa62016-07-26 00:21:15 +00001013 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +00001014}
1015
George Rimara8dba482017-03-20 10:09:58 +00001016ExprValue LinkerScriptBase::getSymbolValue(const Twine &Loc, StringRef S) {
Rafael Espindola4595df92017-03-10 16:04:26 +00001017 if (S == ".")
Rafael Espindola72dc1952017-03-17 13:05:04 +00001018 return {CurOutSec, Dot - CurOutSec->Addr};
George Rimara8dba482017-03-20 10:09:58 +00001019 if (SymbolBody *B = findSymbol(S)) {
Rafael Espindola72dc1952017-03-17 13:05:04 +00001020 if (auto *D = dyn_cast<DefinedRegular>(B))
1021 return {D->Section, D->Value};
1022 auto *C = cast<DefinedCommon>(B);
George Rimara8dba482017-03-20 10:09:58 +00001023 return {InX::Common, C->Offset};
Rafael Espindola72dc1952017-03-17 13:05:04 +00001024 }
Eugene Leviantf6aeed32016-12-22 13:13:12 +00001025 error(Loc + ": symbol not found: " + S);
George Rimar884e7862016-09-08 08:19:13 +00001026 return 0;
1027}
1028
George Rimara8dba482017-03-20 10:09:58 +00001029bool LinkerScriptBase::isDefined(StringRef S) {
1030 return findSymbol(S) != nullptr;
George Rimarf34f45f2016-09-23 13:17:23 +00001031}
1032
Eugene Leviantbbe38602016-07-19 09:25:43 +00001033// Returns indices of ELF headers containing specific section, identified
1034// by Name. Each index is a zero based number of ELF header listed within
1035// PHDRS {} script block.
George Rimara2a1ef12017-03-14 12:03:34 +00001036std::vector<size_t> LinkerScriptBase::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +00001037 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
1038 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +00001039 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +00001040 continue;
1041
Rui Ueyama29c5a2a2016-07-26 00:27:36 +00001042 std::vector<size_t> Ret;
1043 for (StringRef PhdrName : Cmd->Phdrs)
Eugene Leviant2a942c42016-12-05 16:38:32 +00001044 Ret.push_back(getPhdrIndex(Cmd->Location, PhdrName));
Rui Ueyama29c5a2a2016-07-26 00:27:36 +00001045 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001046 }
George Rimar31d842f2016-07-20 16:43:03 +00001047 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +00001048}
1049
George Rimara2a1ef12017-03-14 12:03:34 +00001050size_t LinkerScriptBase::getPhdrIndex(const Twine &Loc, StringRef PhdrName) {
Rui Ueyama29c5a2a2016-07-26 00:27:36 +00001051 size_t I = 0;
1052 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
1053 if (Cmd.Name == PhdrName)
1054 return I;
1055 ++I;
1056 }
Eugene Leviant2a942c42016-12-05 16:38:32 +00001057 error(Loc + ": section header '" + PhdrName + "' is not listed in PHDRS");
Rui Ueyama29c5a2a2016-07-26 00:27:36 +00001058 return 0;
1059}
1060
Rui Ueyama794366a2017-02-14 04:47:05 +00001061class elf::ScriptParser final : public ScriptLexer {
George Rimarc3794e52016-02-24 09:21:47 +00001062 typedef void (ScriptParser::*Handler)();
1063
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001064public:
Rui Ueyama22375f22016-11-25 18:51:54 +00001065 ScriptParser(MemoryBufferRef MB)
Rui Ueyama794366a2017-02-14 04:47:05 +00001066 : ScriptLexer(MB),
Rui Ueyama22375f22016-11-25 18:51:54 +00001067 IsUnderSysroot(isUnderSysroot(MB.getBufferIdentifier())) {}
George Rimarf23b2322016-02-19 10:45:45 +00001068
George Rimar20b65982016-08-31 09:08:26 +00001069 void readLinkerScript();
1070 void readVersionScript();
Rafael Espindolad0ebd842016-12-08 17:54:26 +00001071 void readDynamicList();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001072
1073private:
Rui Ueyama52a15092015-10-11 03:28:42 +00001074 void addFile(StringRef Path);
1075
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001076 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +00001077 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +00001078 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001079 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001080 void readInclude();
Meador Ingeb8897442017-01-24 02:34:00 +00001081 void readMemory();
Rui Ueyamaee592822015-10-07 00:25:09 +00001082 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +00001083 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001084 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +00001085 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +00001086 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001087 void readSections();
Rui Ueyama95769b42016-08-31 20:03:54 +00001088 void readVersion();
1089 void readVersionScriptCommand();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001090
Rui Ueyama113cdec2016-07-24 23:05:57 +00001091 SymbolAssignment *readAssignment(StringRef Name);
George Rimare38cbab2016-09-26 19:22:50 +00001092 BytesDataCommand *readBytesDataCommand(StringRef Tok);
Rui Ueyama16068ae2016-11-19 18:05:56 +00001093 uint32_t readFill();
Rui Ueyama10416562016-08-04 02:03:27 +00001094 OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
Rui Ueyama16068ae2016-11-19 18:05:56 +00001095 uint32_t readOutputSectionFiller(StringRef Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001096 std::vector<StringRef> readOutputSectionPhdrs();
George Rimara2496cb2016-08-30 09:46:59 +00001097 InputSectionDescription *readInputSectionDescription(StringRef Tok);
Eugene Leviantdb688452016-11-03 10:54:58 +00001098 StringMatcher readFilePatterns();
George Rimar07171f22016-09-21 15:56:44 +00001099 std::vector<SectionPattern> readInputSectionsList();
George Rimara2496cb2016-08-30 09:46:59 +00001100 InputSectionDescription *readInputSectionRules(StringRef FilePattern);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001101 unsigned readPhdrType();
George Rimarbe394db2016-09-16 20:21:55 +00001102 SortSectionPolicy readSortKind();
Petr Hoseka35e39c2016-08-16 01:11:16 +00001103 SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
Rafael Espindolac96da112016-11-01 11:30:45 +00001104 SymbolAssignment *readProvideOrAssignment(StringRef Tok);
George Rimar03fc0102016-07-28 07:18:23 +00001105 void readSort();
George Rimareefa7582016-08-04 09:29:31 +00001106 Expr readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001107
Rui Ueyama24e626c2017-01-26 02:58:19 +00001108 uint64_t readMemoryAssignment(StringRef, StringRef, StringRef);
1109 std::pair<uint32_t, uint32_t> readMemoryAttributes();
1110
Rui Ueyama708019c2016-07-24 18:19:40 +00001111 Expr readExpr();
1112 Expr readExpr1(Expr Lhs, int MinPrec);
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001113 StringRef readParenLiteral();
Rui Ueyama708019c2016-07-24 18:19:40 +00001114 Expr readPrimary();
1115 Expr readTernary(Expr Cond);
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001116 Expr readParenExpr();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001117
George Rimar20b65982016-08-31 09:08:26 +00001118 // For parsing version script.
Rui Ueyama12450b22016-11-18 06:30:09 +00001119 std::vector<SymbolVersion> readVersionExtern();
1120 void readAnonymousDeclaration();
Rui Ueyama95769b42016-08-31 20:03:54 +00001121 void readVersionDeclaration(StringRef VerStr);
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001122
1123 std::pair<std::vector<SymbolVersion>, std::vector<SymbolVersion>>
1124 readSymbols();
George Rimar20b65982016-08-31 09:08:26 +00001125
Rui Ueyama07320e42016-04-20 20:13:41 +00001126 ScriptConfiguration &Opt = *ScriptConfig;
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001127 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001128};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001129
Rafael Espindolad0ebd842016-12-08 17:54:26 +00001130void ScriptParser::readDynamicList() {
1131 expect("{");
1132 readAnonymousDeclaration();
1133 if (!atEOF())
1134 setError("EOF expected, but got " + next());
1135}
1136
George Rimar20b65982016-08-31 09:08:26 +00001137void ScriptParser::readVersionScript() {
Rui Ueyama95769b42016-08-31 20:03:54 +00001138 readVersionScriptCommand();
1139 if (!atEOF())
1140 setError("EOF expected, but got " + next());
1141}
1142
1143void ScriptParser::readVersionScriptCommand() {
Rui Ueyama83043f22016-10-17 16:01:53 +00001144 if (consume("{")) {
Rui Ueyama12450b22016-11-18 06:30:09 +00001145 readAnonymousDeclaration();
George Rimar20b65982016-08-31 09:08:26 +00001146 return;
1147 }
1148
Rui Ueyama95769b42016-08-31 20:03:54 +00001149 while (!atEOF() && !Error && peek() != "}") {
George Rimar20b65982016-08-31 09:08:26 +00001150 StringRef VerStr = next();
1151 if (VerStr == "{") {
Rui Ueyama95769b42016-08-31 20:03:54 +00001152 setError("anonymous version definition is used in "
1153 "combination with other version definitions");
George Rimar20b65982016-08-31 09:08:26 +00001154 return;
1155 }
1156 expect("{");
Rui Ueyama95769b42016-08-31 20:03:54 +00001157 readVersionDeclaration(VerStr);
George Rimar20b65982016-08-31 09:08:26 +00001158 }
1159}
1160
Rui Ueyama95769b42016-08-31 20:03:54 +00001161void ScriptParser::readVersion() {
1162 expect("{");
1163 readVersionScriptCommand();
1164 expect("}");
1165}
1166
George Rimar20b65982016-08-31 09:08:26 +00001167void ScriptParser::readLinkerScript() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001168 while (!atEOF()) {
1169 StringRef Tok = next();
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001170 if (Tok == ";")
1171 continue;
1172
Eugene Leviant20d03192016-09-16 15:30:47 +00001173 if (Tok == "ASSERT") {
1174 Opt.Commands.emplace_back(new AssertCommand(readAssert()));
1175 } else if (Tok == "ENTRY") {
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001176 readEntry();
1177 } else if (Tok == "EXTERN") {
1178 readExtern();
1179 } else if (Tok == "GROUP" || Tok == "INPUT") {
1180 readGroup();
1181 } else if (Tok == "INCLUDE") {
1182 readInclude();
Meador Ingeb8897442017-01-24 02:34:00 +00001183 } else if (Tok == "MEMORY") {
1184 readMemory();
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001185 } else if (Tok == "OUTPUT") {
1186 readOutput();
1187 } else if (Tok == "OUTPUT_ARCH") {
1188 readOutputArch();
1189 } else if (Tok == "OUTPUT_FORMAT") {
1190 readOutputFormat();
1191 } else if (Tok == "PHDRS") {
1192 readPhdrs();
1193 } else if (Tok == "SEARCH_DIR") {
1194 readSearchDir();
1195 } else if (Tok == "SECTIONS") {
1196 readSections();
1197 } else if (Tok == "VERSION") {
1198 readVersion();
Rafael Espindolac96da112016-11-01 11:30:45 +00001199 } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok)) {
Eugene Leviant20d03192016-09-16 15:30:47 +00001200 Opt.Commands.emplace_back(Cmd);
Petr Hoseke5d3ca52016-08-31 15:31:17 +00001201 } else {
George Rimar57610422016-03-11 14:43:02 +00001202 setError("unknown directive: " + Tok);
Petr Hoseke5d3ca52016-08-31 15:31:17 +00001203 }
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001204 }
1205}
1206
Rui Ueyama717677a2016-02-11 21:17:59 +00001207void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001208 if (IsUnderSysroot && S.startswith("/")) {
Justin Bogner5af16872016-10-17 06:08:48 +00001209 SmallString<128> PathData;
1210 StringRef Path = (Config->Sysroot + S).toStringRef(PathData);
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001211 if (sys::fs::exists(Path)) {
Justin Bogner5af16872016-10-17 06:08:48 +00001212 Driver->addFile(Saver.save(Path));
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001213 return;
1214 }
1215 }
1216
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +00001217 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +00001218 Driver->addFile(S);
1219 } else if (S.startswith("=")) {
1220 if (Config->Sysroot.empty())
1221 Driver->addFile(S.substr(1));
1222 else
1223 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
1224 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +00001225 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +00001226 } else if (sys::fs::exists(S)) {
1227 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +00001228 } else {
Rui Ueyama061f9282016-11-19 19:23:58 +00001229 if (Optional<std::string> Path = findFromSearchPaths(S))
1230 Driver->addFile(Saver.save(*Path));
Rui Ueyama025d59b2016-02-02 20:27:59 +00001231 else
Rui Ueyama061f9282016-11-19 19:23:58 +00001232 setError("unable to find " + S);
Rui Ueyama52a15092015-10-11 03:28:42 +00001233 }
1234}
1235
Rui Ueyama717677a2016-02-11 21:17:59 +00001236void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001237 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +00001238 bool Orig = Config->AsNeeded;
1239 Config->AsNeeded = true;
Rui Ueyama83043f22016-10-17 16:01:53 +00001240 while (!Error && !consume(")"))
George Rimarcd574a52016-09-09 14:35:36 +00001241 addFile(unquote(next()));
Rui Ueyama35da9b62015-10-11 20:59:12 +00001242 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001243}
1244
Rui Ueyama717677a2016-02-11 21:17:59 +00001245void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +00001246 // -e <symbol> takes predecence over ENTRY(<symbol>).
1247 expect("(");
1248 StringRef Tok = next();
1249 if (Config->Entry.empty())
1250 Config->Entry = Tok;
1251 expect(")");
1252}
1253
Rui Ueyama717677a2016-02-11 21:17:59 +00001254void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +00001255 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001256 while (!Error && !consume(")"))
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001257 Config->Undefined.push_back(next());
George Rimar83f406c2015-10-19 17:35:12 +00001258}
1259
Rui Ueyama717677a2016-02-11 21:17:59 +00001260void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001261 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001262 while (!Error && !consume(")")) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001263 StringRef Tok = next();
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001264 if (Tok == "AS_NEEDED")
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001265 readAsNeeded();
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001266 else
George Rimarcd574a52016-09-09 14:35:36 +00001267 addFile(unquote(Tok));
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001268 }
1269}
1270
Rui Ueyama717677a2016-02-11 21:17:59 +00001271void ScriptParser::readInclude() {
George Rimard4500652016-12-21 09:42:25 +00001272 StringRef Tok = unquote(next());
Rui Ueyamaec1c75e2017-01-09 01:42:02 +00001273
George Rimard4500652016-12-21 09:42:25 +00001274 // https://sourceware.org/binutils/docs/ld/File-Commands.html:
1275 // The file will be searched for in the current directory, and in any
1276 // directory specified with the -L option.
Rui Ueyamaec1c75e2017-01-09 01:42:02 +00001277 if (sys::fs::exists(Tok)) {
1278 if (Optional<MemoryBufferRef> MB = readFile(Tok))
1279 tokenize(*MB);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001280 return;
1281 }
Rui Ueyamaec1c75e2017-01-09 01:42:02 +00001282 if (Optional<std::string> Path = findFromSearchPaths(Tok)) {
1283 if (Optional<MemoryBufferRef> MB = readFile(*Path))
1284 tokenize(*MB);
1285 return;
1286 }
1287 setError("cannot open " + Tok);
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001288}
1289
Rui Ueyama717677a2016-02-11 21:17:59 +00001290void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +00001291 // -o <file> takes predecence over OUTPUT(<file>).
1292 expect("(");
1293 StringRef Tok = next();
1294 if (Config->OutputFile.empty())
George Rimarcd574a52016-09-09 14:35:36 +00001295 Config->OutputFile = unquote(Tok);
Rui Ueyamaee592822015-10-07 00:25:09 +00001296 expect(")");
1297}
1298
Rui Ueyama717677a2016-02-11 21:17:59 +00001299void ScriptParser::readOutputArch() {
George Rimar4e01c3e2017-02-08 09:59:06 +00001300 // OUTPUT_ARCH is ignored for now.
Davide Italiano9159ce92015-10-12 21:50:08 +00001301 expect("(");
George Rimar4e01c3e2017-02-08 09:59:06 +00001302 while (!Error && !consume(")"))
1303 skip();
Davide Italiano9159ce92015-10-12 21:50:08 +00001304}
1305
Rui Ueyama717677a2016-02-11 21:17:59 +00001306void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001307 // Error checking only for now.
1308 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001309 skip();
Davide Italiano6836c612015-10-12 21:08:41 +00001310 StringRef Tok = next();
1311 if (Tok == ")")
George Rimar6c55f0e2016-09-08 08:20:30 +00001312 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +00001313 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +00001314 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001315 return;
1316 }
Justin Bogner5424e7c2016-10-17 06:21:13 +00001317 skip();
Davide Italiano6836c612015-10-12 21:08:41 +00001318 expect(",");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001319 skip();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001320 expect(")");
1321}
1322
Eugene Leviantbbe38602016-07-19 09:25:43 +00001323void ScriptParser::readPhdrs() {
1324 expect("{");
Rui Ueyama83043f22016-10-17 16:01:53 +00001325 while (!Error && !consume("}")) {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001326 StringRef Tok = next();
Eugene Leviant56b21c82016-09-09 09:46:16 +00001327 Opt.PhdrsCommands.push_back(
1328 {Tok, PT_NULL, false, false, UINT_MAX, nullptr});
Eugene Leviantbbe38602016-07-19 09:25:43 +00001329 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
1330
1331 PhdrCmd.Type = readPhdrType();
1332 do {
1333 Tok = next();
1334 if (Tok == ";")
1335 break;
1336 if (Tok == "FILEHDR")
1337 PhdrCmd.HasFilehdr = true;
1338 else if (Tok == "PHDRS")
1339 PhdrCmd.HasPhdrs = true;
Eugene Leviant56b21c82016-09-09 09:46:16 +00001340 else if (Tok == "AT")
1341 PhdrCmd.LMAExpr = readParenExpr();
Eugene Leviant865bf862016-07-21 10:43:25 +00001342 else if (Tok == "FLAGS") {
1343 expect("(");
Rafael Espindolaeb685cd2016-08-02 22:14:57 +00001344 // Passing 0 for the value of dot is a bit of a hack. It means that
1345 // we accept expressions like ".|1".
Rafael Espindola72dc1952017-03-17 13:05:04 +00001346 PhdrCmd.Flags = readExpr()().getValue();
Eugene Leviant865bf862016-07-21 10:43:25 +00001347 expect(")");
1348 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +00001349 setError("unexpected header attribute: " + Tok);
1350 } while (!Error);
1351 }
1352}
1353
Rui Ueyama717677a2016-02-11 21:17:59 +00001354void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +00001355 expect("(");
Rui Ueyama86c5fb82016-09-08 23:26:54 +00001356 StringRef Tok = next();
Rui Ueyama6c7ad132016-09-02 19:20:33 +00001357 if (!Config->Nostdlib)
George Rimarcd574a52016-09-09 14:35:36 +00001358 Config->SearchPaths.push_back(unquote(Tok));
Davide Italiano68a39a62015-10-08 17:51:41 +00001359 expect(")");
1360}
1361
Rui Ueyama717677a2016-02-11 21:17:59 +00001362void ScriptParser::readSections() {
Eugene Leviante05336ff2016-09-14 08:32:36 +00001363 Opt.HasSections = true;
George Rimar18a30962016-11-28 10:11:10 +00001364 // -no-rosegment is used to avoid placing read only non-executable sections in
1365 // their own segment. We do the same if SECTIONS command is present in linker
1366 // script. See comment for computeFlags().
1367 Config->SingleRoRx = true;
1368
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001369 expect("{");
Rui Ueyama83043f22016-10-17 16:01:53 +00001370 while (!Error && !consume("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +00001371 StringRef Tok = next();
Rafael Espindolac96da112016-11-01 11:30:45 +00001372 BaseCommand *Cmd = readProvideOrAssignment(Tok);
Eugene Leviantceabe802016-08-11 07:56:43 +00001373 if (!Cmd) {
1374 if (Tok == "ASSERT")
1375 Cmd = new AssertCommand(readAssert());
1376 else
1377 Cmd = readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +00001378 }
Rui Ueyama10416562016-08-04 02:03:27 +00001379 Opt.Commands.emplace_back(Cmd);
George Rimar652852c2016-04-16 10:10:32 +00001380 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001381}
1382
Rui Ueyama708019c2016-07-24 18:19:40 +00001383static int precedence(StringRef Op) {
1384 return StringSwitch<int>(Op)
Rui Ueyama0120e3f2016-09-23 18:06:51 +00001385 .Cases("*", "/", 5)
1386 .Cases("+", "-", 4)
1387 .Cases("<<", ">>", 3)
Rui Ueyama9c4ac5f2016-09-23 22:22:34 +00001388 .Cases("<", "<=", ">", ">=", "==", "!=", 2)
Rui Ueyama0120e3f2016-09-23 18:06:51 +00001389 .Cases("&", "|", 1)
Rui Ueyama708019c2016-07-24 18:19:40 +00001390 .Default(-1);
1391}
1392
Eugene Leviantdb688452016-11-03 10:54:58 +00001393StringMatcher ScriptParser::readFilePatterns() {
Rui Ueyama10416562016-08-04 02:03:27 +00001394 std::vector<StringRef> V;
Rui Ueyama83043f22016-10-17 16:01:53 +00001395 while (!Error && !consume(")"))
Rui Ueyama10416562016-08-04 02:03:27 +00001396 V.push_back(next());
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001397 return StringMatcher(V);
George Rimar0702c4e2016-07-29 15:32:46 +00001398}
1399
George Rimarbe394db2016-09-16 20:21:55 +00001400SortSectionPolicy ScriptParser::readSortKind() {
Rui Ueyama83043f22016-10-17 16:01:53 +00001401 if (consume("SORT") || consume("SORT_BY_NAME"))
George Rimarbe394db2016-09-16 20:21:55 +00001402 return SortSectionPolicy::Name;
Rui Ueyama83043f22016-10-17 16:01:53 +00001403 if (consume("SORT_BY_ALIGNMENT"))
George Rimarbe394db2016-09-16 20:21:55 +00001404 return SortSectionPolicy::Alignment;
Rui Ueyama83043f22016-10-17 16:01:53 +00001405 if (consume("SORT_BY_INIT_PRIORITY"))
George Rimarbe394db2016-09-16 20:21:55 +00001406 return SortSectionPolicy::Priority;
Rui Ueyama83043f22016-10-17 16:01:53 +00001407 if (consume("SORT_NONE"))
Rui Ueyamab2a0abd2016-09-16 21:14:55 +00001408 return SortSectionPolicy::None;
1409 return SortSectionPolicy::Default;
George Rimarbe394db2016-09-16 20:21:55 +00001410}
1411
George Rimar395281c2016-09-16 17:42:10 +00001412// Method reads a list of sequence of excluded files and section globs given in
1413// a following form: ((EXCLUDE_FILE(file_pattern+))? section_pattern+)+
1414// Example: *(.foo.1 EXCLUDE_FILE (*a.o) .foo.2 EXCLUDE_FILE (*b.o) .foo.3)
George Rimaraf03be12016-09-17 19:17:25 +00001415// The semantics of that is next:
1416// * Include .foo.1 from every file.
1417// * Include .foo.2 from every file but a.o
1418// * Include .foo.3 from every file but b.o
George Rimar07171f22016-09-21 15:56:44 +00001419std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
1420 std::vector<SectionPattern> Ret;
George Rimar601e9892016-09-21 08:53:21 +00001421 while (!Error && peek() != ")") {
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001422 StringMatcher ExcludeFilePat;
Rui Ueyama83043f22016-10-17 16:01:53 +00001423 if (consume("EXCLUDE_FILE")) {
George Rimar395281c2016-09-16 17:42:10 +00001424 expect("(");
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001425 ExcludeFilePat = readFilePatterns();
George Rimar395281c2016-09-16 17:42:10 +00001426 }
1427
George Rimar601e9892016-09-21 08:53:21 +00001428 std::vector<StringRef> V;
1429 while (!Error && peek() != ")" && peek() != "EXCLUDE_FILE")
1430 V.push_back(next());
1431
1432 if (!V.empty())
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001433 Ret.push_back({std::move(ExcludeFilePat), StringMatcher(V)});
George Rimar601e9892016-09-21 08:53:21 +00001434 else
1435 setError("section pattern is expected");
George Rimar395281c2016-09-16 17:42:10 +00001436 }
George Rimar07171f22016-09-21 15:56:44 +00001437 return Ret;
George Rimar395281c2016-09-16 17:42:10 +00001438}
1439
Rui Ueyamaf8f6f1e2016-11-18 07:03:56 +00001440// Reads contents of "SECTIONS" directive. That directive contains a
1441// list of glob patterns for input sections. The grammar is as follows.
1442//
1443// <patterns> ::= <section-list>
1444// | <sort> "(" <section-list> ")"
1445// | <sort> "(" <sort> "(" <section-list> ")" ")"
1446//
1447// <sort> ::= "SORT" | "SORT_BY_NAME" | "SORT_BY_ALIGNMENT"
1448// | "SORT_BY_INIT_PRIORITY" | "SORT_NONE"
1449//
1450// <section-list> is parsed by readInputSectionsList().
George Rimara2496cb2016-08-30 09:46:59 +00001451InputSectionDescription *
1452ScriptParser::readInputSectionRules(StringRef FilePattern) {
George Rimarc91930a2016-09-02 21:17:20 +00001453 auto *Cmd = new InputSectionDescription(FilePattern);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001454 expect("(");
Rui Ueyamaf373dd72016-11-24 01:43:21 +00001455 while (!Error && !consume(")")) {
George Rimar07171f22016-09-21 15:56:44 +00001456 SortSectionPolicy Outer = readSortKind();
1457 SortSectionPolicy Inner = SortSectionPolicy::Default;
1458 std::vector<SectionPattern> V;
1459 if (Outer != SortSectionPolicy::Default) {
George Rimar350ece42016-08-03 08:35:59 +00001460 expect("(");
George Rimar07171f22016-09-21 15:56:44 +00001461 Inner = readSortKind();
1462 if (Inner != SortSectionPolicy::Default) {
1463 expect("(");
1464 V = readInputSectionsList();
1465 expect(")");
1466 } else {
1467 V = readInputSectionsList();
1468 }
George Rimar350ece42016-08-03 08:35:59 +00001469 expect(")");
1470 } else {
George Rimar07171f22016-09-21 15:56:44 +00001471 V = readInputSectionsList();
George Rimar350ece42016-08-03 08:35:59 +00001472 }
George Rimar0702c4e2016-07-29 15:32:46 +00001473
George Rimar07171f22016-09-21 15:56:44 +00001474 for (SectionPattern &Pat : V) {
1475 Pat.SortInner = Inner;
1476 Pat.SortOuter = Outer;
1477 }
1478
1479 std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns));
1480 }
Rui Ueyama10416562016-08-04 02:03:27 +00001481 return Cmd;
Davide Italianoe7282792016-07-27 01:44:01 +00001482}
1483
George Rimara2496cb2016-08-30 09:46:59 +00001484InputSectionDescription *
1485ScriptParser::readInputSectionDescription(StringRef Tok) {
George Rimar06598002016-07-28 21:51:30 +00001486 // Input section wildcard can be surrounded by KEEP.
1487 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
George Rimara2496cb2016-08-30 09:46:59 +00001488 if (Tok == "KEEP") {
George Rimar06598002016-07-28 21:51:30 +00001489 expect("(");
George Rimara2496cb2016-08-30 09:46:59 +00001490 StringRef FilePattern = next();
1491 InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
George Rimar06598002016-07-28 21:51:30 +00001492 expect(")");
Eugene Leviantcf43f172016-10-05 09:36:59 +00001493 Opt.KeptSections.push_back(Cmd);
Rui Ueyama10416562016-08-04 02:03:27 +00001494 return Cmd;
George Rimar06598002016-07-28 21:51:30 +00001495 }
George Rimara2496cb2016-08-30 09:46:59 +00001496 return readInputSectionRules(Tok);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001497}
1498
George Rimar03fc0102016-07-28 07:18:23 +00001499void ScriptParser::readSort() {
1500 expect("(");
1501 expect("CONSTRUCTORS");
1502 expect(")");
1503}
1504
George Rimareefa7582016-08-04 09:29:31 +00001505Expr ScriptParser::readAssert() {
1506 expect("(");
1507 Expr E = readExpr();
1508 expect(",");
George Rimarcd574a52016-09-09 14:35:36 +00001509 StringRef Msg = unquote(next());
George Rimareefa7582016-08-04 09:29:31 +00001510 expect(")");
Rafael Espindola4595df92017-03-10 16:04:26 +00001511 return [=] {
Rafael Espindola72dc1952017-03-17 13:05:04 +00001512 if (!E().getValue())
George Rimareefa7582016-08-04 09:29:31 +00001513 error(Msg);
George Rimara8dba482017-03-20 10:09:58 +00001514 return Script->getDot();
George Rimareefa7582016-08-04 09:29:31 +00001515 };
1516}
1517
Rui Ueyama25150e82016-09-06 17:46:43 +00001518// Reads a FILL(expr) command. We handle the FILL command as an
1519// alias for =fillexp section attribute, which is different from
1520// what GNU linkers do.
1521// https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
Rui Ueyama16068ae2016-11-19 18:05:56 +00001522uint32_t ScriptParser::readFill() {
George Rimarff1f29e2016-09-06 13:51:57 +00001523 expect("(");
Rui Ueyama16068ae2016-11-19 18:05:56 +00001524 uint32_t V = readOutputSectionFiller(next());
George Rimarff1f29e2016-09-06 13:51:57 +00001525 expect(")");
1526 expect(";");
1527 return V;
1528}
1529
Rui Ueyama10416562016-08-04 02:03:27 +00001530OutputSectionCommand *
1531ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +00001532 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
Eugene Leviant2a942c42016-12-05 16:38:32 +00001533 Cmd->Location = getCurrentLocation();
George Rimar58e5c4d2016-07-25 08:29:46 +00001534
1535 // Read an address expression.
1536 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
1537 if (peek() != ":")
1538 Cmd->AddrExpr = readExpr();
1539
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001540 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +00001541
Rui Ueyama83043f22016-10-17 16:01:53 +00001542 if (consume("AT"))
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001543 Cmd->LMAExpr = readParenExpr();
Rui Ueyama83043f22016-10-17 16:01:53 +00001544 if (consume("ALIGN"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001545 Cmd->AlignExpr = readParenExpr();
Rui Ueyama83043f22016-10-17 16:01:53 +00001546 if (consume("SUBALIGN"))
George Rimardb24d9c2016-08-19 15:18:23 +00001547 Cmd->SubalignExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001548
Davide Italiano246f6812016-07-22 03:36:24 +00001549 // Parse constraints.
Rui Ueyama83043f22016-10-17 16:01:53 +00001550 if (consume("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001551 Cmd->Constraint = ConstraintKind::ReadOnly;
Rui Ueyama83043f22016-10-17 16:01:53 +00001552 if (consume("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001553 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001554 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001555
Rui Ueyama83043f22016-10-17 16:01:53 +00001556 while (!Error && !consume("}")) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001557 StringRef Tok = next();
George Rimar2fe07922017-01-31 08:50:11 +00001558 if (Tok == ";") {
George Rimar69750752017-02-01 09:14:22 +00001559 // Empty commands are allowed. Do nothing here.
George Rimar2fe07922017-01-31 08:50:11 +00001560 } else if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok)) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001561 Cmd->Commands.emplace_back(Assignment);
Meador Ingeb2d99d62016-11-22 18:01:50 +00001562 } else if (BytesDataCommand *Data = readBytesDataCommand(Tok)) {
George Rimare38cbab2016-09-26 19:22:50 +00001563 Cmd->Commands.emplace_back(Data);
Meador Ingeb2d99d62016-11-22 18:01:50 +00001564 } else if (Tok == "ASSERT") {
1565 Cmd->Commands.emplace_back(new AssertCommand(readAssert()));
1566 expect(";");
George Rimar8e2eca22017-01-23 09:36:19 +00001567 } else if (Tok == "CONSTRUCTORS") {
1568 // CONSTRUCTORS is a keyword to make the linker recognize C++ ctors/dtors
1569 // by name. This is for very old file formats such as ECOFF/XCOFF.
1570 // For ELF, we should ignore.
Meador Ingeb2d99d62016-11-22 18:01:50 +00001571 } else if (Tok == "FILL") {
George Rimarff1f29e2016-09-06 13:51:57 +00001572 Cmd->Filler = readFill();
Meador Ingeb2d99d62016-11-22 18:01:50 +00001573 } else if (Tok == "SORT") {
George Rimar03fc0102016-07-28 07:18:23 +00001574 readSort();
Meador Ingeb2d99d62016-11-22 18:01:50 +00001575 } else if (peek() == "(") {
George Rimara2496cb2016-08-30 09:46:59 +00001576 Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
Meador Ingeb2d99d62016-11-22 18:01:50 +00001577 } else {
Eugene Leviantceabe802016-08-11 07:56:43 +00001578 setError("unknown command " + Tok);
Meador Ingeb2d99d62016-11-22 18:01:50 +00001579 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001580 }
Meador Ingeb8897442017-01-24 02:34:00 +00001581
1582 if (consume(">"))
1583 Cmd->MemoryRegionName = next();
1584
George Rimar076fe152016-07-21 06:43:01 +00001585 Cmd->Phdrs = readOutputSectionPhdrs();
George Rimar4ebc5622016-09-23 13:29:20 +00001586
Rui Ueyama83043f22016-10-17 16:01:53 +00001587 if (consume("="))
George Rimar4ebc5622016-09-23 13:29:20 +00001588 Cmd->Filler = readOutputSectionFiller(next());
1589 else if (peek().startswith("="))
George Rimarff1f29e2016-09-06 13:51:57 +00001590 Cmd->Filler = readOutputSectionFiller(next().drop_front());
George Rimar4ebc5622016-09-23 13:29:20 +00001591
George Rimar7185a1a2017-01-17 15:32:12 +00001592 // Consume optional comma following output section command.
1593 consume(",");
1594
Rui Ueyama10416562016-08-04 02:03:27 +00001595 return Cmd;
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001596}
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001597
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001598// Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
1599// https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
1600//
1601// ld.gold is not fully compatible with ld.bfd. ld.bfd handles
1602// hexstrings as blobs of arbitrary sizes, while ld.gold handles them
1603// as 32-bit big-endian values. We will do the same as ld.gold does
1604// because it's simpler than what ld.bfd does.
Rui Ueyama16068ae2016-11-19 18:05:56 +00001605uint32_t ScriptParser::readOutputSectionFiller(StringRef Tok) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001606 uint32_t V;
Rui Ueyama16068ae2016-11-19 18:05:56 +00001607 if (!Tok.getAsInteger(0, V))
1608 return V;
1609 setError("invalid filler expression: " + Tok);
1610 return 0;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001611}
1612
Petr Hoseka35e39c2016-08-16 01:11:16 +00001613SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
Eugene Levianta31c91b2016-07-22 07:38:40 +00001614 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +00001615 SymbolAssignment *Cmd = readAssignment(next());
Petr Hoseka35e39c2016-08-16 01:11:16 +00001616 Cmd->Provide = Provide;
Rui Ueyama174e0a12016-07-29 00:29:25 +00001617 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001618 expect(")");
1619 expect(";");
Rui Ueyama10416562016-08-04 02:03:27 +00001620 return Cmd;
Eugene Levianteda81a12016-07-12 06:39:48 +00001621}
1622
Rafael Espindolac96da112016-11-01 11:30:45 +00001623SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001624 SymbolAssignment *Cmd = nullptr;
1625 if (peek() == "=" || peek() == "+=") {
1626 Cmd = readAssignment(Tok);
1627 expect(";");
1628 } else if (Tok == "PROVIDE") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001629 Cmd = readProvideHidden(true, false);
1630 } else if (Tok == "HIDDEN") {
1631 Cmd = readProvideHidden(false, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001632 } else if (Tok == "PROVIDE_HIDDEN") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001633 Cmd = readProvideHidden(true, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001634 }
1635 return Cmd;
1636}
1637
George Rimar30835ea2016-07-28 21:08:56 +00001638SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1639 StringRef Op = next();
1640 assert(Op == "=" || Op == "+=");
Petr Hosek02ad5162017-03-15 03:33:23 +00001641 Expr E = readExpr();
Eugene Leviantf6aeed32016-12-22 13:13:12 +00001642 if (Op == "+=") {
1643 std::string Loc = getCurrentLocation();
George Rimara8dba482017-03-20 10:09:58 +00001644 E = [=] { return add(Script->getSymbolValue(Loc, Name), E()); };
Eugene Leviantf6aeed32016-12-22 13:13:12 +00001645 }
George Rimar2ee2d2d2017-02-21 14:50:38 +00001646 return new SymbolAssignment(Name, E, getCurrentLocation());
George Rimar30835ea2016-07-28 21:08:56 +00001647}
1648
1649// This is an operator-precedence parser to parse a linker
1650// script expression.
Rui Ueyama731a66a2017-02-15 19:58:17 +00001651Expr ScriptParser::readExpr() {
1652 // Our lexer is context-aware. Set the in-expression bit so that
1653 // they apply different tokenization rules.
1654 bool Orig = InExpr;
1655 InExpr = true;
1656 Expr E = readExpr1(readPrimary(), 0);
1657 InExpr = Orig;
1658 return E;
1659}
George Rimar30835ea2016-07-28 21:08:56 +00001660
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001661static Expr combine(StringRef Op, Expr L, Expr R) {
1662 if (Op == "*")
Rafael Espindola72dc1952017-03-17 13:05:04 +00001663 return [=] { return mul(L(), R()); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001664 if (Op == "/") {
Rafael Espindola72dc1952017-03-17 13:05:04 +00001665 return [=] { return div(L(), R()); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001666 }
1667 if (Op == "+")
Rafael Espindola72dc1952017-03-17 13:05:04 +00001668 return [=] { return add(L(), R()); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001669 if (Op == "-")
Rafael Espindola72dc1952017-03-17 13:05:04 +00001670 return [=] { return sub(L(), R()); };
George Rimarc8ccd1f2016-09-23 13:13:55 +00001671 if (Op == "<<")
Rafael Espindola72dc1952017-03-17 13:05:04 +00001672 return [=] { return leftShift(L(), R()); };
George Rimarc8ccd1f2016-09-23 13:13:55 +00001673 if (Op == ">>")
Rafael Espindola72dc1952017-03-17 13:05:04 +00001674 return [=] { return rightShift(L(), R()); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001675 if (Op == "<")
Rafael Espindola72dc1952017-03-17 13:05:04 +00001676 return [=] { return lessThan(L(), R()); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001677 if (Op == ">")
Rafael Espindola72dc1952017-03-17 13:05:04 +00001678 return [=] { return greaterThan(L(), R()); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001679 if (Op == ">=")
Rafael Espindola72dc1952017-03-17 13:05:04 +00001680 return [=] { return greaterThanOrEqual(L(), R()); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001681 if (Op == "<=")
Rafael Espindola72dc1952017-03-17 13:05:04 +00001682 return [=] { return lessThanOrEqual(L(), R()); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001683 if (Op == "==")
Rafael Espindola72dc1952017-03-17 13:05:04 +00001684 return [=] { return ::equal(L(), R()); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001685 if (Op == "!=")
Rafael Espindola72dc1952017-03-17 13:05:04 +00001686 return [=] { return notEqual(L(), R()); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001687 if (Op == "&")
Rafael Espindola72dc1952017-03-17 13:05:04 +00001688 return [=] { return bitAnd(L(), R()); };
Rafael Espindolacc3dd622016-08-22 21:33:35 +00001689 if (Op == "|")
Rafael Espindola72dc1952017-03-17 13:05:04 +00001690 return [=] { return bitOr(L(), R()); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001691 llvm_unreachable("invalid operator");
1692}
1693
Rui Ueyama708019c2016-07-24 18:19:40 +00001694// This is a part of the operator-precedence parser. This function
1695// assumes that the remaining token stream starts with an operator.
1696Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1697 while (!atEOF() && !Error) {
1698 // Read an operator and an expression.
Rui Ueyama46247b82016-11-18 06:49:07 +00001699 if (consume("?"))
Rui Ueyama708019c2016-07-24 18:19:40 +00001700 return readTernary(Lhs);
Rui Ueyama46247b82016-11-18 06:49:07 +00001701 StringRef Op1 = peek();
Rui Ueyama708019c2016-07-24 18:19:40 +00001702 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +00001703 break;
Justin Bogner5424e7c2016-10-17 06:21:13 +00001704 skip();
Rui Ueyama708019c2016-07-24 18:19:40 +00001705 Expr Rhs = readPrimary();
1706
1707 // Evaluate the remaining part of the expression first if the
1708 // next operator has greater precedence than the previous one.
1709 // For example, if we have read "+" and "3", and if the next
1710 // operator is "*", then we'll evaluate 3 * ... part first.
1711 while (!atEOF()) {
1712 StringRef Op2 = peek();
1713 if (precedence(Op2) <= precedence(Op1))
1714 break;
1715 Rhs = readExpr1(Rhs, precedence(Op2));
1716 }
1717
1718 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +00001719 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001720 return Lhs;
1721}
1722
1723uint64_t static getConstant(StringRef S) {
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001724 if (S == "COMMONPAGESIZE")
Rui Ueyama708019c2016-07-24 18:19:40 +00001725 return Target->PageSize;
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001726 if (S == "MAXPAGESIZE")
Petr Hosek997f8832016-09-28 15:20:47 +00001727 return Config->MaxPageSize;
Rui Ueyama708019c2016-07-24 18:19:40 +00001728 error("unknown constant: " + S);
1729 return 0;
1730}
1731
Rui Ueyama626e0b02016-09-02 18:19:00 +00001732// Parses Tok as an integer. Returns true if successful.
1733// It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1734// and decimal numbers. Decimal numbers may have "K" (kilo) or
1735// "M" (mega) prefixes.
George Rimar9f2f7ad2016-09-02 16:01:42 +00001736static bool readInteger(StringRef Tok, uint64_t &Result) {
Rui Ueyama46247b82016-11-18 06:49:07 +00001737 // Negative number
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001738 if (Tok.startswith("-")) {
1739 if (!readInteger(Tok.substr(1), Result))
1740 return false;
1741 Result = -Result;
1742 return true;
1743 }
Rui Ueyama46247b82016-11-18 06:49:07 +00001744
1745 // Hexadecimal
George Rimar9f2f7ad2016-09-02 16:01:42 +00001746 if (Tok.startswith_lower("0x"))
1747 return !Tok.substr(2).getAsInteger(16, Result);
1748 if (Tok.endswith_lower("H"))
1749 return !Tok.drop_back().getAsInteger(16, Result);
1750
Rui Ueyama46247b82016-11-18 06:49:07 +00001751 // Decimal
George Rimar9f2f7ad2016-09-02 16:01:42 +00001752 int Suffix = 1;
1753 if (Tok.endswith_lower("K")) {
1754 Suffix = 1024;
1755 Tok = Tok.drop_back();
1756 } else if (Tok.endswith_lower("M")) {
1757 Suffix = 1024 * 1024;
1758 Tok = Tok.drop_back();
1759 }
1760 if (Tok.getAsInteger(10, Result))
1761 return false;
1762 Result *= Suffix;
1763 return true;
1764}
1765
George Rimare38cbab2016-09-26 19:22:50 +00001766BytesDataCommand *ScriptParser::readBytesDataCommand(StringRef Tok) {
1767 int Size = StringSwitch<unsigned>(Tok)
1768 .Case("BYTE", 1)
1769 .Case("SHORT", 2)
1770 .Case("LONG", 4)
1771 .Case("QUAD", 8)
1772 .Default(-1);
1773 if (Size == -1)
1774 return nullptr;
1775
Meador Inge95c7d8d2016-12-08 23:21:30 +00001776 return new BytesDataCommand(readParenExpr(), Size);
George Rimare38cbab2016-09-26 19:22:50 +00001777}
1778
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001779StringRef ScriptParser::readParenLiteral() {
1780 expect("(");
1781 StringRef Tok = next();
1782 expect(")");
1783 return Tok;
1784}
1785
Rui Ueyama708019c2016-07-24 18:19:40 +00001786Expr ScriptParser::readPrimary() {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001787 if (peek() == "(")
1788 return readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001789
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001790 StringRef Tok = next();
Rui Ueyamab5f1c3e2016-12-01 04:36:49 +00001791 std::string Location = getCurrentLocation();
Rui Ueyama708019c2016-07-24 18:19:40 +00001792
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001793 if (Tok == "~") {
1794 Expr E = readPrimary();
Rafael Espindola72dc1952017-03-17 13:05:04 +00001795 return [=] { return bitNot(E()); };
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001796 }
1797 if (Tok == "-") {
1798 Expr E = readPrimary();
Rafael Espindola72dc1952017-03-17 13:05:04 +00001799 return [=] { return minus(E()); };
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001800 }
1801
Rui Ueyama708019c2016-07-24 18:19:40 +00001802 // Built-in functions are parsed here.
1803 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
Petr Hosek02ad5162017-03-15 03:33:23 +00001804 if (Tok == "ABSOLUTE") {
Rafael Espindola72dc1952017-03-17 13:05:04 +00001805 Expr Inner = readParenExpr();
1806 return [=] {
1807 ExprValue I = Inner();
1808 I.ForceAbsolute = true;
1809 return I;
1810 };
Petr Hosek02ad5162017-03-15 03:33:23 +00001811 }
George Rimar96659df2016-08-30 09:54:01 +00001812 if (Tok == "ADDR") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001813 StringRef Name = readParenLiteral();
Rafael Espindola72dc1952017-03-17 13:05:04 +00001814 return [=]() -> ExprValue {
George Rimara8dba482017-03-20 10:09:58 +00001815 return {Script->getOutputSection(Location, Name), 0};
Rafael Espindola72dc1952017-03-17 13:05:04 +00001816 };
George Rimar96659df2016-08-30 09:54:01 +00001817 }
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001818 if (Tok == "LOADADDR") {
1819 StringRef Name = readParenLiteral();
George Rimara8dba482017-03-20 10:09:58 +00001820 return [=] { return Script->getOutputSection(Location, Name)->getLMA(); };
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001821 }
George Rimareefa7582016-08-04 09:29:31 +00001822 if (Tok == "ASSERT")
1823 return readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001824 if (Tok == "ALIGN") {
Rui Ueyama5d804dc2016-12-16 18:19:35 +00001825 expect("(");
1826 Expr E = readExpr();
1827 if (consume(",")) {
1828 Expr E2 = readExpr();
1829 expect(")");
Rafael Espindola72dc1952017-03-17 13:05:04 +00001830 return [=] { return alignTo(E().getValue(), E2().getValue()); };
Rui Ueyama5d804dc2016-12-16 18:19:35 +00001831 }
1832 expect(")");
George Rimara8dba482017-03-20 10:09:58 +00001833 return [=] { return alignTo(Script->getDot(), E().getValue()); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001834 }
1835 if (Tok == "CONSTANT") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001836 StringRef Name = readParenLiteral();
Rafael Espindola4595df92017-03-10 16:04:26 +00001837 return [=] { return getConstant(Name); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001838 }
George Rimarf34f45f2016-09-23 13:17:23 +00001839 if (Tok == "DEFINED") {
Rui Ueyama0ee25a62016-11-17 03:52:14 +00001840 StringRef Name = readParenLiteral();
George Rimara8dba482017-03-20 10:09:58 +00001841 return [=] { return Script->isDefined(Name) ? 1 : 0; };
George Rimarf34f45f2016-09-23 13:17:23 +00001842 }
Rafael Espindola54c145c2016-07-28 18:16:24 +00001843 if (Tok == "SEGMENT_START") {
1844 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001845 skip();
Rafael Espindola54c145c2016-07-28 18:16:24 +00001846 expect(",");
George Rimar8c658bf2016-09-17 18:14:56 +00001847 Expr E = readExpr();
Rafael Espindola54c145c2016-07-28 18:16:24 +00001848 expect(")");
Rafael Espindola4595df92017-03-10 16:04:26 +00001849 return [=] { return E(); };
Rafael Espindola54c145c2016-07-28 18:16:24 +00001850 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001851 if (Tok == "DATA_SEGMENT_ALIGN") {
1852 expect("(");
1853 Expr E = readExpr();
1854 expect(",");
1855 readExpr();
1856 expect(")");
George Rimara8dba482017-03-20 10:09:58 +00001857 return [=] { return alignTo(Script->getDot(), E().getValue()); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001858 }
1859 if (Tok == "DATA_SEGMENT_END") {
1860 expect("(");
1861 expect(".");
1862 expect(")");
George Rimara8dba482017-03-20 10:09:58 +00001863 return [] { return Script->getDot(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001864 }
George Rimar276b4e62016-07-26 17:58:44 +00001865 // GNU linkers implements more complicated logic to handle
1866 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1867 // the next page boundary for simplicity.
1868 if (Tok == "DATA_SEGMENT_RELRO_END") {
1869 expect("(");
Rafael Espindola97bdc722016-09-14 19:14:01 +00001870 readExpr();
George Rimar276b4e62016-07-26 17:58:44 +00001871 expect(",");
1872 readExpr();
1873 expect(")");
George Rimara8dba482017-03-20 10:09:58 +00001874 return [] { return alignTo(Script->getDot(), Target->PageSize); };
George Rimar276b4e62016-07-26 17:58:44 +00001875 }
George Rimar9e694502016-07-29 16:18:47 +00001876 if (Tok == "SIZEOF") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001877 StringRef Name = readParenLiteral();
George Rimara8dba482017-03-20 10:09:58 +00001878 return [=] { return Script->getOutputSectionSize(Name); };
George Rimar9e694502016-07-29 16:18:47 +00001879 }
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001880 if (Tok == "ALIGNOF") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001881 StringRef Name = readParenLiteral();
George Rimara8dba482017-03-20 10:09:58 +00001882 return [=] { return Script->getOutputSection(Location, Name)->Alignment; };
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001883 }
George Rimare32a3592016-08-10 07:59:34 +00001884 if (Tok == "SIZEOF_HEADERS")
George Rimar78aa2702017-03-13 14:40:58 +00001885 return [=] { return elf::getHeaderSize(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001886
George Rimar9f2f7ad2016-09-02 16:01:42 +00001887 // Tok is a literal number.
1888 uint64_t V;
1889 if (readInteger(Tok, V))
Rafael Espindola4595df92017-03-10 16:04:26 +00001890 return [=] { return V; };
George Rimar9f2f7ad2016-09-02 16:01:42 +00001891
1892 // Tok is a symbol name.
1893 if (Tok != "." && !isValidCIdentifier(Tok))
1894 setError("malformed number: " + Tok);
George Rimara8dba482017-03-20 10:09:58 +00001895 return [=] { return Script->getSymbolValue(Location, Tok); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001896}
1897
1898Expr ScriptParser::readTernary(Expr Cond) {
Rui Ueyama708019c2016-07-24 18:19:40 +00001899 Expr L = readExpr();
1900 expect(":");
1901 Expr R = readExpr();
Rafael Espindola72dc1952017-03-17 13:05:04 +00001902 return [=] { return Cond().getValue() ? L() : R(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001903}
1904
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001905Expr ScriptParser::readParenExpr() {
1906 expect("(");
1907 Expr E = readExpr();
1908 expect(")");
1909 return E;
1910}
1911
Eugene Leviantbbe38602016-07-19 09:25:43 +00001912std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1913 std::vector<StringRef> Phdrs;
1914 while (!Error && peek().startswith(":")) {
1915 StringRef Tok = next();
George Rimarda841c12016-11-14 10:03:54 +00001916 Phdrs.push_back((Tok.size() == 1) ? next() : Tok.substr(1));
Eugene Leviantbbe38602016-07-19 09:25:43 +00001917 }
1918 return Phdrs;
1919}
1920
George Rimar95dd7182016-10-18 10:49:50 +00001921// Read a program header type name. The next token must be a
1922// name of a program header type or a constant (e.g. "0x3").
Eugene Leviantbbe38602016-07-19 09:25:43 +00001923unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001924 StringRef Tok = next();
George Rimar95dd7182016-10-18 10:49:50 +00001925 uint64_t Val;
1926 if (readInteger(Tok, Val))
1927 return Val;
1928
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001929 unsigned Ret = StringSwitch<unsigned>(Tok)
George Rimar6c55f0e2016-09-08 08:20:30 +00001930 .Case("PT_NULL", PT_NULL)
1931 .Case("PT_LOAD", PT_LOAD)
1932 .Case("PT_DYNAMIC", PT_DYNAMIC)
1933 .Case("PT_INTERP", PT_INTERP)
1934 .Case("PT_NOTE", PT_NOTE)
1935 .Case("PT_SHLIB", PT_SHLIB)
1936 .Case("PT_PHDR", PT_PHDR)
1937 .Case("PT_TLS", PT_TLS)
1938 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1939 .Case("PT_GNU_STACK", PT_GNU_STACK)
1940 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
George Rimar270173f2016-10-14 13:02:22 +00001941 .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
George Rimarcc6e5672016-10-14 10:34:36 +00001942 .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
George Rimara2a32c22016-12-06 17:57:42 +00001943 .Case("PT_OPENBSD_BOOTDATA", PT_OPENBSD_BOOTDATA)
George Rimar6c55f0e2016-09-08 08:20:30 +00001944 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001945
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001946 if (Ret == (unsigned)-1) {
1947 setError("invalid program header type: " + Tok);
1948 return PT_NULL;
1949 }
1950 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001951}
1952
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001953// Reads an anonymous version declaration.
Rui Ueyama12450b22016-11-18 06:30:09 +00001954void ScriptParser::readAnonymousDeclaration() {
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001955 std::vector<SymbolVersion> Locals;
1956 std::vector<SymbolVersion> Globals;
1957 std::tie(Locals, Globals) = readSymbols();
1958
1959 for (SymbolVersion V : Locals) {
1960 if (V.Name == "*")
1961 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1962 else
1963 Config->VersionScriptLocals.push_back(V);
Rafael Espindola45242682017-02-03 13:24:01 +00001964 }
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001965
1966 for (SymbolVersion V : Globals)
1967 Config->VersionScriptGlobals.push_back(V);
1968
Rui Ueyama12450b22016-11-18 06:30:09 +00001969 expect(";");
1970}
1971
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001972// Reads a non-anonymous version definition,
1973// e.g. "VerStr { global: foo; bar; local: *; };".
Rui Ueyama95769b42016-08-31 20:03:54 +00001974void ScriptParser::readVersionDeclaration(StringRef VerStr) {
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001975 // Read a symbol list.
1976 std::vector<SymbolVersion> Locals;
1977 std::vector<SymbolVersion> Globals;
1978 std::tie(Locals, Globals) = readSymbols();
George Rimar20b65982016-08-31 09:08:26 +00001979
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001980 for (SymbolVersion V : Locals) {
1981 if (V.Name == "*")
1982 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1983 else
1984 Config->VersionScriptLocals.push_back(V);
Rafael Espindola45242682017-02-03 13:24:01 +00001985 }
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001986
1987 // Create a new version definition and add that to the global symbols.
1988 VersionDefinition Ver;
1989 Ver.Name = VerStr;
1990 Ver.Globals = Globals;
1991
1992 // User-defined version number starts from 2 because 0 and 1 are
1993 // reserved for VER_NDX_LOCAL and VER_NDX_GLOBAL, respectively.
1994 Ver.Id = Config->VersionDefinitions.size() + 2;
1995 Config->VersionDefinitions.push_back(Ver);
George Rimar20b65982016-08-31 09:08:26 +00001996
Rui Ueyama12450b22016-11-18 06:30:09 +00001997 // Each version may have a parent version. For example, "Ver2"
1998 // defined as "Ver2 { global: foo; local: *; } Ver1;" has "Ver1"
1999 // as a parent. This version hierarchy is, probably against your
2000 // instinct, purely for hint; the runtime doesn't care about it
2001 // at all. In LLD, we simply ignore it.
2002 if (peek() != ";")
Justin Bogner5424e7c2016-10-17 06:21:13 +00002003 skip();
George Rimar20b65982016-08-31 09:08:26 +00002004 expect(";");
2005}
2006
Rui Ueyamaf5fce482017-03-09 19:23:00 +00002007// Reads a list of symbols, e.g. "{ global: foo; bar; local: *; };".
2008std::pair<std::vector<SymbolVersion>, std::vector<SymbolVersion>>
2009ScriptParser::readSymbols() {
2010 std::vector<SymbolVersion> Locals;
2011 std::vector<SymbolVersion> Globals;
2012 std::vector<SymbolVersion> *V = &Globals;
2013
2014 while (!Error) {
2015 if (consume("}"))
2016 break;
2017 if (consumeLabel("local")) {
2018 V = &Locals;
2019 continue;
2020 }
2021 if (consumeLabel("global")) {
2022 V = &Globals;
Rafael Espindola1ef90d22016-12-09 16:44:05 +00002023 continue;
2024 }
George Rimare0fc2422016-11-16 17:59:10 +00002025
Rui Ueyamaf5fce482017-03-09 19:23:00 +00002026 if (consume("extern")) {
2027 std::vector<SymbolVersion> Ext = readVersionExtern();
2028 V->insert(V->end(), Ext.begin(), Ext.end());
2029 } else {
2030 StringRef Tok = next();
2031 V->push_back({unquote(Tok), false, hasWildcard(Tok)});
2032 }
George Rimare0fc2422016-11-16 17:59:10 +00002033 expect(";");
2034 }
Rui Ueyamaf5fce482017-03-09 19:23:00 +00002035 return {Locals, Globals};
George Rimare0fc2422016-11-16 17:59:10 +00002036}
2037
Rui Ueyama12450b22016-11-18 06:30:09 +00002038// Reads an "extern C++" directive, e.g.,
2039// "extern "C++" { ns::*; "f(int, double)"; };"
2040std::vector<SymbolVersion> ScriptParser::readVersionExtern() {
Rafael Espindola7e714152016-12-08 17:26:53 +00002041 StringRef Tok = next();
2042 bool IsCXX = Tok == "\"C++\"";
2043 if (!IsCXX && Tok != "\"C\"")
Rafael Espindolad0ebd842016-12-08 17:54:26 +00002044 setError("Unknown language");
George Rimar20b65982016-08-31 09:08:26 +00002045 expect("{");
2046
Rui Ueyama12450b22016-11-18 06:30:09 +00002047 std::vector<SymbolVersion> Ret;
Rui Ueyama0ee25a62016-11-17 03:52:14 +00002048 while (!Error && peek() != "}") {
2049 StringRef Tok = next();
2050 bool HasWildcard = !Tok.startswith("\"") && hasWildcard(Tok);
Rafael Espindola7e714152016-12-08 17:26:53 +00002051 Ret.push_back({unquote(Tok), IsCXX, HasWildcard});
George Rimar20b65982016-08-31 09:08:26 +00002052 expect(";");
2053 }
2054
2055 expect("}");
Rui Ueyama12450b22016-11-18 06:30:09 +00002056 return Ret;
George Rimar20b65982016-08-31 09:08:26 +00002057}
2058
George Rimar009833d2017-03-20 09:51:18 +00002059uint64_t ScriptParser::readMemoryAssignment(StringRef S1, StringRef S2,
2060 StringRef S3) {
Rui Ueyama24e626c2017-01-26 02:58:19 +00002061 if (!(consume(S1) || consume(S2) || consume(S3))) {
2062 setError("expected one of: " + S1 + ", " + S2 + ", or " + S3);
2063 return 0;
2064 }
2065 expect("=");
2066
2067 // TODO: Fully support constant expressions.
2068 uint64_t Val;
2069 if (!readInteger(next(), Val))
George Rimar009833d2017-03-20 09:51:18 +00002070 setError("nonconstant expression for " + S1);
Rui Ueyama24e626c2017-01-26 02:58:19 +00002071 return Val;
2072}
2073
2074// Parse the MEMORY command as specified in:
2075// https://sourceware.org/binutils/docs/ld/MEMORY.html
2076//
2077// MEMORY { name [(attr)] : ORIGIN = origin, LENGTH = len ... }
Meador Ingeb8897442017-01-24 02:34:00 +00002078void ScriptParser::readMemory() {
2079 expect("{");
2080 while (!Error && !consume("}")) {
2081 StringRef Name = next();
Rui Ueyama24e626c2017-01-26 02:58:19 +00002082
Meador Ingeb8897442017-01-24 02:34:00 +00002083 uint32_t Flags = 0;
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002084 uint32_t NegFlags = 0;
Meador Ingeb8897442017-01-24 02:34:00 +00002085 if (consume("(")) {
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002086 std::tie(Flags, NegFlags) = readMemoryAttributes();
Meador Ingeb8897442017-01-24 02:34:00 +00002087 expect(")");
2088 }
2089 expect(":");
2090
Rui Ueyama24e626c2017-01-26 02:58:19 +00002091 uint64_t Origin = readMemoryAssignment("ORIGIN", "org", "o");
Meador Ingeb8897442017-01-24 02:34:00 +00002092 expect(",");
Rui Ueyama24e626c2017-01-26 02:58:19 +00002093 uint64_t Length = readMemoryAssignment("LENGTH", "len", "l");
Meador Ingeb8897442017-01-24 02:34:00 +00002094
Meador Ingeb8897442017-01-24 02:34:00 +00002095 // Add the memory region to the region map (if it doesn't already exist).
2096 auto It = Opt.MemoryRegions.find(Name);
2097 if (It != Opt.MemoryRegions.end())
2098 setError("region '" + Name + "' already defined");
2099 else
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002100 Opt.MemoryRegions[Name] = {Name, Origin, Length, Origin, Flags, NegFlags};
Meador Ingeb8897442017-01-24 02:34:00 +00002101 }
2102}
2103
2104// This function parses the attributes used to match against section
2105// flags when placing output sections in a memory region. These flags
2106// are only used when an explicit memory region name is not used.
2107std::pair<uint32_t, uint32_t> ScriptParser::readMemoryAttributes() {
2108 uint32_t Flags = 0;
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002109 uint32_t NegFlags = 0;
Meador Ingeb8897442017-01-24 02:34:00 +00002110 bool Invert = false;
Rui Ueyama481ac992017-01-26 02:58:39 +00002111
2112 for (char C : next().lower()) {
Meador Ingeb8897442017-01-24 02:34:00 +00002113 uint32_t Flag = 0;
2114 if (C == '!')
2115 Invert = !Invert;
Rui Ueyama481ac992017-01-26 02:58:39 +00002116 else if (C == 'w')
Meador Ingeb8897442017-01-24 02:34:00 +00002117 Flag = SHF_WRITE;
Rui Ueyama481ac992017-01-26 02:58:39 +00002118 else if (C == 'x')
Meador Ingeb8897442017-01-24 02:34:00 +00002119 Flag = SHF_EXECINSTR;
Rui Ueyama481ac992017-01-26 02:58:39 +00002120 else if (C == 'a')
Meador Ingeb8897442017-01-24 02:34:00 +00002121 Flag = SHF_ALLOC;
Rui Ueyama481ac992017-01-26 02:58:39 +00002122 else if (C != 'r')
Meador Ingeb8897442017-01-24 02:34:00 +00002123 setError("invalid memory region attribute");
Rui Ueyama481ac992017-01-26 02:58:39 +00002124
Meador Ingeb8897442017-01-24 02:34:00 +00002125 if (Invert)
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002126 NegFlags |= Flag;
Meador Ingeb8897442017-01-24 02:34:00 +00002127 else
2128 Flags |= Flag;
2129 }
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002130 return {Flags, NegFlags};
Meador Ingeb8897442017-01-24 02:34:00 +00002131}
2132
Rui Ueyama07320e42016-04-20 20:13:41 +00002133void elf::readLinkerScript(MemoryBufferRef MB) {
Rui Ueyama22375f22016-11-25 18:51:54 +00002134 ScriptParser(MB).readLinkerScript();
George Rimar20b65982016-08-31 09:08:26 +00002135}
2136
2137void elf::readVersionScript(MemoryBufferRef MB) {
Rui Ueyama22375f22016-11-25 18:51:54 +00002138 ScriptParser(MB).readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00002139}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00002140
Rafael Espindolad0ebd842016-12-08 17:54:26 +00002141void elf::readDynamicList(MemoryBufferRef MB) {
2142 ScriptParser(MB).readDynamicList();
2143}