blob: 922c7da6f325173d11e3d470ea5a48997358ea49 [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 Ueyama629e0aa52016-07-21 19:45:22 +000011// It parses a linker script and write the result to Config or ScriptConfig
12// objects.
13//
14// If SECTIONS command is used, a ScriptConfig contains an AST
15// of the command which will later be consumed by createSections() and
16// assignAddresses().
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000017//
18//===----------------------------------------------------------------------===//
19
Rui Ueyama717677a2016-02-11 21:17:59 +000020#include "LinkerScript.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000021#include "Config.h"
22#include "Driver.h"
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +000023#include "InputSection.h"
George Rimar652852c2016-04-16 10:10:32 +000024#include "OutputSections.h"
Adhemerval Zanellae77b5bf2016-04-06 20:59:11 +000025#include "ScriptParser.h"
Rui Ueyama93c9af42016-06-29 08:01:32 +000026#include "Strings.h"
Eugene Levianteda81a12016-07-12 06:39:48 +000027#include "Symbols.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000028#include "SymbolTable.h"
Eugene Leviant467c4d52016-07-01 10:27:36 +000029#include "Target.h"
Eugene Leviantbbe38602016-07-19 09:25:43 +000030#include "Writer.h"
Rui Ueyama960504b2016-04-19 18:58:11 +000031#include "llvm/ADT/StringSwitch.h"
George Rimar652852c2016-04-16 10:10:32 +000032#include "llvm/Support/ELF.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000033#include "llvm/Support/FileSystem.h"
34#include "llvm/Support/MemoryBuffer.h"
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +000035#include "llvm/Support/Path.h"
Rui Ueyamaa47ee682015-10-11 01:53:04 +000036#include "llvm/Support/StringSaver.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000037
38using namespace llvm;
George Rimar652852c2016-04-16 10:10:32 +000039using namespace llvm::ELF;
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +000040using namespace llvm::object;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000041using namespace lld;
Rafael Espindolae0df00b2016-02-28 00:25:54 +000042using namespace lld::elf;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000043
Rui Ueyama07320e42016-04-20 20:13:41 +000044ScriptConfiguration *elf::ScriptConfig;
Rui Ueyama717677a2016-02-11 21:17:59 +000045
Eugene Leviantceabe802016-08-11 07:56:43 +000046template <class ELFT>
Rui Ueyama16024212016-08-11 23:22:52 +000047static void addRegular(SymbolAssignment *Cmd) {
48 Symbol *Sym = Symtab<ELFT>::X->addRegular(Cmd->Name, STB_GLOBAL, STV_DEFAULT);
49 Sym->Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
50 Cmd->Sym = Sym->body();
Eugene Leviantceabe802016-08-11 07:56:43 +000051}
52
Rui Ueyama0c70d3c2016-08-12 03:31:09 +000053template <class ELFT> static void addSynthetic(SymbolAssignment *Cmd) {
54 Symbol *Sym = Symtab<ELFT>::X->addSynthetic(Cmd->Name, nullptr, 0);
Rui Ueyama16024212016-08-11 23:22:52 +000055 Sym->Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
56 Cmd->Sym = Sym->body();
Eugene Leviantceabe802016-08-11 07:56:43 +000057}
58
Rui Ueyama16024212016-08-11 23:22:52 +000059// If a symbol was in PROVIDE(), we need to define it only when
60// it is an undefined symbol.
61template <class ELFT> static bool shouldDefine(SymbolAssignment *Cmd) {
62 if (Cmd->Name == ".")
Eugene Leviantceabe802016-08-11 07:56:43 +000063 return false;
Rui Ueyama16024212016-08-11 23:22:52 +000064 if (!Cmd->Provide)
65 return true;
66 SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
67 return B && B->isUndefined();
Eugene Leviantceabe802016-08-11 07:56:43 +000068}
69
George Rimar076fe152016-07-21 06:43:01 +000070bool SymbolAssignment::classof(const BaseCommand *C) {
71 return C->Kind == AssignmentKind;
72}
73
74bool OutputSectionCommand::classof(const BaseCommand *C) {
75 return C->Kind == OutputSectionKind;
76}
77
George Rimareea31142016-07-21 14:26:59 +000078bool InputSectionDescription::classof(const BaseCommand *C) {
79 return C->Kind == InputSectionKind;
80}
81
George Rimareefa7582016-08-04 09:29:31 +000082bool AssertCommand::classof(const BaseCommand *C) {
83 return C->Kind == AssertKind;
84}
85
Rui Ueyama36a153c2016-07-23 14:09:58 +000086template <class ELFT> static bool isDiscarded(InputSectionBase<ELFT> *S) {
George Rimareea31142016-07-21 14:26:59 +000087 return !S || !S->Live;
Rui Ueyama717677a2016-02-11 21:17:59 +000088}
89
Rui Ueyamaf34d0e02016-08-12 01:24:53 +000090template <class ELFT> LinkerScript<ELFT>::LinkerScript() {}
91template <class ELFT> LinkerScript<ELFT>::~LinkerScript() {}
92
Rui Ueyama07320e42016-04-20 20:13:41 +000093template <class ELFT>
94bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) {
Rui Ueyama8ec77e62016-04-21 22:00:51 +000095 for (StringRef Pat : Opt.KeptSections)
Rui Ueyama722830a2016-06-29 05:32:09 +000096 if (globMatch(Pat, S->getSectionName()))
Rui Ueyama8ec77e62016-04-21 22:00:51 +000097 return true;
98 return false;
George Rimar481c2ce2016-02-23 07:47:54 +000099}
100
Rui Ueyama63dc6502016-07-25 22:41:42 +0000101static bool match(ArrayRef<StringRef> Patterns, StringRef S) {
102 for (StringRef Pat : Patterns)
103 if (globMatch(Pat, S))
George Rimareea31142016-07-21 14:26:59 +0000104 return true;
105 return false;
106}
107
George Rimar06598002016-07-28 21:51:30 +0000108static bool fileMatches(const InputSectionDescription *Desc,
109 StringRef Filename) {
110 if (!globMatch(Desc->FilePattern, Filename))
111 return false;
112 return Desc->ExcludedFiles.empty() || !match(Desc->ExcludedFiles, Filename);
113}
114
Rui Ueyama6b274812016-07-25 22:51:07 +0000115// Returns input sections filtered by given glob patterns.
116template <class ELFT>
117std::vector<InputSectionBase<ELFT> *>
Rui Ueyamaad10c3d2016-07-28 21:05:04 +0000118LinkerScript<ELFT>::getInputSections(const InputSectionDescription *I) {
George Rimar06598002016-07-28 21:51:30 +0000119 ArrayRef<StringRef> Patterns = I->SectionPatterns;
Rui Ueyama6b274812016-07-25 22:51:07 +0000120 std::vector<InputSectionBase<ELFT> *> Ret;
121 for (const std::unique_ptr<ObjectFile<ELFT>> &F :
George Rimar06598002016-07-28 21:51:30 +0000122 Symtab<ELFT>::X->getObjectFiles()) {
123 if (fileMatches(I, sys::path::filename(F->getName())))
124 for (InputSectionBase<ELFT> *S : F->getSections())
125 if (!isDiscarded(S) && !S->OutSec &&
126 match(Patterns, S->getSectionName()))
Davide Italianoe7282792016-07-27 01:44:01 +0000127 Ret.push_back(S);
George Rimar06598002016-07-28 21:51:30 +0000128 }
Eugene Leviant3e6b0272016-07-28 19:24:13 +0000129
Rui Ueyama7ad9d6d2016-08-12 03:25:25 +0000130 if (llvm::find(Patterns, "COMMON") != Patterns.end())
Rui Ueyamaad10c3d2016-07-28 21:05:04 +0000131 Ret.push_back(CommonInputSection<ELFT>::X);
Eugene Leviant3e6b0272016-07-28 19:24:13 +0000132
Rui Ueyama6b274812016-07-25 22:51:07 +0000133 return Ret;
134}
135
Rui Ueyamadd81fe32016-08-11 21:00:02 +0000136// You can define new symbols using linker scripts. For example,
137// ".text { abc.o(.text); foo = .; def.o(.text); }" defines symbol
138// foo just after abc.o's text section contents. This class is to
139// handle such symbol definitions.
140//
141// In order to handle scripts like the above one, we want to
142// keep symbol definitions in output sections. Because output sections
143// can contain only input sections, we wrap symbol definitions
144// with dummy input sections. This class serves that purpose.
Rui Ueyamaf34d0e02016-08-12 01:24:53 +0000145template <class ELFT>
146class elf::LayoutInputSection : public InputSectionBase<ELFT> {
Eugene Leviantceabe802016-08-11 07:56:43 +0000147public:
Rui Ueyamaf34d0e02016-08-12 01:24:53 +0000148 explicit LayoutInputSection(SymbolAssignment *Cmd);
Eugene Leviantceabe802016-08-11 07:56:43 +0000149 static bool classof(const InputSectionBase<ELFT> *S);
150 SymbolAssignment *Cmd;
151
152private:
153 typename ELFT::Shdr Hdr;
154};
155
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000156template <class ELFT>
157static InputSectionBase<ELFT> *
158getNonLayoutSection(std::vector<InputSectionBase<ELFT> *> &Vec) {
159 for (InputSectionBase<ELFT> *S : Vec)
160 if (!isa<LayoutInputSection<ELFT>>(S))
161 return S;
162 return nullptr;
163}
Eugene Leviantceabe802016-08-11 07:56:43 +0000164
165template <class T> static T *zero(T *Val) {
166 memset(Val, 0, sizeof(*Val));
167 return Val;
168}
169
170template <class ELFT>
171LayoutInputSection<ELFT>::LayoutInputSection(SymbolAssignment *Cmd)
Rui Ueyama2c3f5012016-08-11 22:06:55 +0000172 : InputSectionBase<ELFT>(nullptr, zero(&Hdr),
173 InputSectionBase<ELFT>::Layout),
174 Cmd(Cmd) {
Eugene Leviantceabe802016-08-11 07:56:43 +0000175 this->Live = true;
Eugene Leviantceabe802016-08-11 07:56:43 +0000176 Hdr.sh_type = SHT_NOBITS;
177}
178
179template <class ELFT>
180bool LayoutInputSection<ELFT>::classof(const InputSectionBase<ELFT> *S) {
181 return S->SectionKind == InputSectionBase<ELFT>::Layout;
182}
183
184template <class ELFT>
Rui Ueyama742c3832016-08-04 22:27:00 +0000185static bool compareName(InputSectionBase<ELFT> *A, InputSectionBase<ELFT> *B) {
186 return A->getSectionName() < B->getSectionName();
187}
George Rimar350ece42016-08-03 08:35:59 +0000188
Rui Ueyama742c3832016-08-04 22:27:00 +0000189template <class ELFT>
190static bool compareAlignment(InputSectionBase<ELFT> *A,
191 InputSectionBase<ELFT> *B) {
192 // ">" is not a mistake. Larger alignments are placed before smaller
193 // alignments in order to reduce the amount of padding necessary.
194 // This is compatible with GNU.
195 return A->Alignment > B->Alignment;
196}
George Rimar350ece42016-08-03 08:35:59 +0000197
Rui Ueyama742c3832016-08-04 22:27:00 +0000198template <class ELFT>
199static std::function<bool(InputSectionBase<ELFT> *, InputSectionBase<ELFT> *)>
200getComparator(SortKind K) {
201 if (K == SortByName)
202 return compareName<ELFT>;
203 return compareAlignment<ELFT>;
204}
George Rimar0702c4e2016-07-29 15:32:46 +0000205
206template <class ELFT>
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000207void LinkerScript<ELFT>::discard(OutputSectionCommand &Cmd) {
208 for (const std::unique_ptr<BaseCommand> &Base : Cmd.Commands) {
209 if (auto *Cmd = dyn_cast<InputSectionDescription>(Base.get())) {
210 for (InputSectionBase<ELFT> *S : getInputSections(Cmd)) {
211 S->Live = false;
212 reportDiscarded(S);
213 }
214 }
215 }
216}
217
George Rimar8f66df92016-08-12 20:38:20 +0000218static bool checkConstraint(uint64_t Flags, ConstraintKind Kind) {
219 bool RO = (Kind == ConstraintKind::ReadOnly);
220 bool RW = (Kind == ConstraintKind::ReadWrite);
221 bool Writable = Flags & SHF_WRITE;
222 return !((RO && Writable) || (RW && !Writable));
223}
224
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000225template <class ELFT>
George Rimar06ae6832016-08-12 09:07:57 +0000226static bool matchConstraints(ArrayRef<InputSectionBase<ELFT> *> Sections,
227 ConstraintKind Kind) {
George Rimar8f66df92016-08-12 20:38:20 +0000228 if (Kind == ConstraintKind::NoConstraint)
229 return true;
230 return llvm::all_of(Sections, [=](InputSectionBase<ELFT> *Sec) {
231 return checkConstraint(Sec->getSectionHdr()->sh_flags, Kind);
George Rimar06ae6832016-08-12 09:07:57 +0000232 });
233}
234
235template <class ELFT>
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000236std::vector<InputSectionBase<ELFT> *>
George Rimar06ae6832016-08-12 09:07:57 +0000237LinkerScript<ELFT>::createInputSectionList(OutputSectionCommand &OutCmd) {
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000238 std::vector<InputSectionBase<ELFT> *> Ret;
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000239
George Rimar06ae6832016-08-12 09:07:57 +0000240 for (const std::unique_ptr<BaseCommand> &Base : OutCmd.Commands) {
241 if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base.get())) {
242 if (shouldDefine<ELFT>(OutCmd))
243 addSynthetic<ELFT>(OutCmd);
244 Ret.push_back(new (LAlloc.Allocate()) LayoutInputSection<ELFT>(OutCmd));
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000245 continue;
246 }
247
248 auto *Cmd = cast<InputSectionDescription>(Base.get());
249 std::vector<InputSectionBase<ELFT> *> V = getInputSections(Cmd);
George Rimar06ae6832016-08-12 09:07:57 +0000250 if (!matchConstraints<ELFT>(V, OutCmd.Constraint))
251 continue;
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000252 if (Cmd->SortInner)
253 std::stable_sort(V.begin(), V.end(), getComparator<ELFT>(Cmd->SortInner));
254 if (Cmd->SortOuter)
255 std::stable_sort(V.begin(), V.end(), getComparator<ELFT>(Cmd->SortOuter));
256 Ret.insert(Ret.end(), V.begin(), V.end());
257 }
258 return Ret;
259}
260
261template <class ELFT>
262void LinkerScript<ELFT>::createSections(OutputSectionFactory<ELFT> &Factory) {
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000263 for (const std::unique_ptr<BaseCommand> &Base1 : Opt.Commands) {
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000264 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base1.get())) {
265 if (shouldDefine<ELFT>(Cmd))
266 addRegular<ELFT>(Cmd);
267 continue;
268 }
269
Eugene Leviantceabe802016-08-11 07:56:43 +0000270 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000271 if (Cmd->Name == "/DISCARD/") {
272 discard(*Cmd);
273 continue;
274 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000275
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000276 std::vector<InputSectionBase<ELFT> *> V = createInputSectionList(*Cmd);
277 InputSectionBase<ELFT> *Head = getNonLayoutSection<ELFT>(V);
278 if (!Head)
279 continue;
280
281 OutputSectionBase<ELFT> *OutSec;
282 bool IsNew;
283 std::tie(OutSec, IsNew) = Factory.create(Head, Cmd->Name);
284 if (IsNew)
285 OutputSections->push_back(OutSec);
Rui Ueyama0c70d3c2016-08-12 03:31:09 +0000286 for (InputSectionBase<ELFT> *Sec : V)
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000287 OutSec->addSection(Sec);
Eugene Leviantceabe802016-08-11 07:56:43 +0000288 }
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000289 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000290
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000291 // Add orphan sections.
Rui Ueyama6b274812016-07-25 22:51:07 +0000292 for (const std::unique_ptr<ObjectFile<ELFT>> &F :
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000293 Symtab<ELFT>::X->getObjectFiles()) {
294 for (InputSectionBase<ELFT> *S : F->getSections()) {
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000295 if (isDiscarded(S) || S->OutSec)
296 continue;
297 OutputSectionBase<ELFT> *OutSec;
298 bool IsNew;
299 std::tie(OutSec, IsNew) = Factory.create(S, getOutputSectionName(S));
300 if (IsNew)
301 OutputSections->push_back(OutSec);
302 OutSec->addSection(S);
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000303 }
304 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000305}
306
Eugene Leviantceabe802016-08-11 07:56:43 +0000307template <class ELFT> void assignOffsets(OutputSectionBase<ELFT> *Sec) {
Eugene Leviantceabe802016-08-11 07:56:43 +0000308 auto *OutSec = dyn_cast<OutputSection<ELFT>>(Sec);
Rui Ueyama2de509c2016-08-12 00:55:08 +0000309 if (!OutSec) {
310 Sec->assignOffsets();
Eugene Leviantceabe802016-08-11 07:56:43 +0000311 return;
Rui Ueyama2de509c2016-08-12 00:55:08 +0000312 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000313
314 typedef typename ELFT::uint uintX_t;
315 uintX_t Off = 0;
316
317 for (InputSection<ELFT> *I : OutSec->Sections) {
318 if (auto *L = dyn_cast<LayoutInputSection<ELFT>>(I)) {
319 uintX_t Value = L->Cmd->Expression(Sec->getVA() + Off) - Sec->getVA();
Rui Ueyama0c70d3c2016-08-12 03:31:09 +0000320 if (L->Cmd->Name == ".") {
Eugene Leviantceabe802016-08-11 07:56:43 +0000321 Off = Value;
Eugene Leviantb6f1bb12016-08-15 09:19:51 +0000322 } else if (auto *Sym =
323 cast_or_null<DefinedSynthetic<ELFT>>(L->Cmd->Sym)) {
324 // shouldDefine could have returned false, so we need to check Sym,
325 // for non-null value.
Rui Ueyama0c70d3c2016-08-12 03:31:09 +0000326 Sym->Section = OutSec;
327 Sym->Value = Value;
328 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000329 } else {
330 Off = alignTo(Off, I->Alignment);
331 I->OutSecOff = Off;
332 Off += I->getSize();
333 }
Rui Ueyamaf4a30a52016-08-11 21:30:42 +0000334 // Update section size inside for-loop, so that SIZEOF
Eugene Leviantceabe802016-08-11 07:56:43 +0000335 // works correctly in the case below:
336 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
337 Sec->setSize(Off);
338 }
339}
340
George Rimar8f66df92016-08-12 20:38:20 +0000341template <class ELFT>
342static OutputSectionBase<ELFT> *
343findSection(OutputSectionCommand &Cmd,
344 ArrayRef<OutputSectionBase<ELFT> *> Sections) {
345 for (OutputSectionBase<ELFT> *Sec : Sections) {
346 if (Sec->getName() != Cmd.Name)
347 continue;
348 if (checkConstraint(Sec->getFlags(), Cmd.Constraint))
349 return Sec;
350 }
351 return nullptr;
352}
353
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000354template <class ELFT> void LinkerScript<ELFT>::assignAddresses() {
George Rimar652852c2016-04-16 10:10:32 +0000355 // Orphan sections are sections present in the input files which
Rui Ueyama7c18c282016-04-18 21:00:40 +0000356 // are not explicitly placed into the output file by the linker script.
357 // We place orphan sections at end of file.
358 // Other linkers places them using some heuristics as described in
George Rimar652852c2016-04-16 10:10:32 +0000359 // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
Rui Ueyamae5cc6682016-08-12 00:36:56 +0000360 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
George Rimar652852c2016-04-16 10:10:32 +0000361 StringRef Name = Sec->getName();
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000362 if (getSectionIndex(Name) == INT_MAX)
George Rimar076fe152016-07-21 06:43:01 +0000363 Opt.Commands.push_back(llvm::make_unique<OutputSectionCommand>(Name));
George Rimar652852c2016-04-16 10:10:32 +0000364 }
George Rimar652852c2016-04-16 10:10:32 +0000365
Rui Ueyama7c18c282016-04-18 21:00:40 +0000366 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rui Ueyama4f7500b2016-08-12 04:00:22 +0000367 Dot = getHeaderSize();
Eugene Leviant467c4d52016-07-01 10:27:36 +0000368 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
George Rimar652852c2016-04-16 10:10:32 +0000369 uintX_t ThreadBssOffset = 0;
George Rimar652852c2016-04-16 10:10:32 +0000370
George Rimar076fe152016-07-21 06:43:01 +0000371 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
372 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
Rui Ueyama8d083e62016-07-29 05:48:39 +0000373 if (Cmd->Name == ".") {
374 Dot = Cmd->Expression(Dot);
375 } else if (Cmd->Sym) {
376 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(Dot);
377 }
George Rimar652852c2016-04-16 10:10:32 +0000378 continue;
379 }
380
George Rimareefa7582016-08-04 09:29:31 +0000381 if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
382 Cmd->Expression(Dot);
383 continue;
384 }
385
George Rimar076fe152016-07-21 06:43:01 +0000386 auto *Cmd = cast<OutputSectionCommand>(Base.get());
George Rimar8f66df92016-08-12 20:38:20 +0000387 OutputSectionBase<ELFT> *Sec = findSection<ELFT>(*Cmd, *OutputSections);
388 if (!Sec)
George Rimarb6c52e82016-08-12 19:32:45 +0000389 continue;
George Rimar652852c2016-04-16 10:10:32 +0000390
George Rimarb6c52e82016-08-12 19:32:45 +0000391 if (Cmd->AddrExpr)
392 Dot = Cmd->AddrExpr(Dot);
George Rimar58e5c4d2016-07-25 08:29:46 +0000393
George Rimarb6c52e82016-08-12 19:32:45 +0000394 if (Cmd->AlignExpr)
395 Sec->updateAlignment(Cmd->AlignExpr(Dot));
George Rimar630c6172016-07-26 18:06:29 +0000396
George Rimarb6c52e82016-08-12 19:32:45 +0000397 if ((Sec->getFlags() & SHF_TLS) && Sec->getType() == SHT_NOBITS) {
398 uintX_t TVA = Dot + ThreadBssOffset;
399 TVA = alignTo(TVA, Sec->getAlignment());
400 Sec->setVA(TVA);
401 assignOffsets(Sec);
402 ThreadBssOffset = TVA - Dot + Sec->getSize();
403 continue;
George Rimar652852c2016-04-16 10:10:32 +0000404 }
George Rimarb6c52e82016-08-12 19:32:45 +0000405
406 if (!(Sec->getFlags() & SHF_ALLOC)) {
407 Sec->assignOffsets();
408 continue;
409 }
410
411 Dot = alignTo(Dot, Sec->getAlignment());
412 Sec->setVA(Dot);
413 assignOffsets(Sec);
414 MinVA = std::min(MinVA, Dot);
415 Dot += Sec->getSize();
George Rimar652852c2016-04-16 10:10:32 +0000416 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000417
Rafael Espindola64c32d62016-07-07 14:28:47 +0000418 // ELF and Program headers need to be right before the first section in
George Rimarb91e7112016-07-19 07:42:07 +0000419 // memory. Set their addresses accordingly.
Eugene Leviant467c4d52016-07-01 10:27:36 +0000420 MinVA = alignDown(MinVA - Out<ELFT>::ElfHeader->getSize() -
421 Out<ELFT>::ProgramHeaders->getSize(),
422 Target->PageSize);
423 Out<ELFT>::ElfHeader->setVA(MinVA);
424 Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
George Rimar652852c2016-04-16 10:10:32 +0000425}
426
Rui Ueyama07320e42016-04-20 20:13:41 +0000427template <class ELFT>
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000428std::vector<PhdrEntry<ELFT>> LinkerScript<ELFT>::createPhdrs() {
429 ArrayRef<OutputSectionBase<ELFT> *> Sections = *OutputSections;
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000430 std::vector<PhdrEntry<ELFT>> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000431
432 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000433 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
434 PhdrEntry<ELFT> &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000435
436 if (Cmd.HasFilehdr)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000437 Phdr.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000438 if (Cmd.HasPhdrs)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000439 Phdr.add(Out<ELFT>::ProgramHeaders);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000440
441 switch (Cmd.Type) {
442 case PT_INTERP:
Rui Ueyamafd03cfd2016-07-21 11:01:23 +0000443 if (Out<ELFT>::Interp)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000444 Phdr.add(Out<ELFT>::Interp);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000445 break;
446 case PT_DYNAMIC:
Rui Ueyama1034c9e2016-08-09 04:42:01 +0000447 if (Out<ELFT>::DynSymTab) {
Rafael Espindola0b113672016-07-27 14:10:56 +0000448 Phdr.H.p_flags = Out<ELFT>::Dynamic->getPhdrFlags();
Rui Ueyamaadca2452016-07-23 14:18:48 +0000449 Phdr.add(Out<ELFT>::Dynamic);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000450 }
451 break;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000452 case PT_GNU_EH_FRAME:
453 if (!Out<ELFT>::EhFrame->empty() && Out<ELFT>::EhFrameHdr) {
Rafael Espindola0b113672016-07-27 14:10:56 +0000454 Phdr.H.p_flags = Out<ELFT>::EhFrameHdr->getPhdrFlags();
Rui Ueyamaadca2452016-07-23 14:18:48 +0000455 Phdr.add(Out<ELFT>::EhFrameHdr);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000456 }
457 break;
458 }
459 }
460
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000461 PhdrEntry<ELFT> *Load = nullptr;
462 uintX_t Flags = PF_R;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000463 for (OutputSectionBase<ELFT> *Sec : Sections) {
464 if (!(Sec->getFlags() & SHF_ALLOC))
465 break;
466
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000467 std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName());
Eugene Leviantbbe38602016-07-19 09:25:43 +0000468 if (!PhdrIds.empty()) {
469 // Assign headers specified by linker script
470 for (size_t Id : PhdrIds) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000471 Ret[Id].add(Sec);
Eugene Leviant865bf862016-07-21 10:43:25 +0000472 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
Rafael Espindola0b113672016-07-27 14:10:56 +0000473 Ret[Id].H.p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000474 }
475 } else {
476 // If we have no load segment or flags've changed then we want new load
477 // segment.
Rafael Espindola0b113672016-07-27 14:10:56 +0000478 uintX_t NewFlags = Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000479 if (Load == nullptr || Flags != NewFlags) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000480 Load = &*Ret.emplace(Ret.end(), PT_LOAD, NewFlags);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000481 Flags = NewFlags;
482 }
Rui Ueyama18f084f2016-07-20 19:36:41 +0000483 Load->add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000484 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000485 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000486 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000487}
488
Eugene Leviantf9bc3bd2016-08-16 06:40:58 +0000489template <class ELFT> bool LinkerScript<ELFT>::ignoreInterpSection() {
490 // Ignore .interp section in case we have PHDRS specification
491 // and PT_INTERP isn't listed.
492 return !Opt.PhdrsCommands.empty() &&
493 llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
494 return Cmd.Type == PT_INTERP;
495 }) == Opt.PhdrsCommands.end();
496}
497
Eugene Leviantbbe38602016-07-19 09:25:43 +0000498template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000499ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000500 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
501 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
502 if (Cmd->Name == Name)
503 return Cmd->Filler;
504 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000505}
506
George Rimar206fffa2016-08-17 08:16:57 +0000507template <class ELFT> Expr LinkerScript<ELFT>::getLma(StringRef Name) {
George Rimar8ceadb32016-08-17 07:44:19 +0000508 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
509 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
510 if (Cmd->LmaExpr && Cmd->Name == Name)
511 return Cmd->LmaExpr;
512 return {};
513}
514
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000515// Returns the index of the given section name in linker script
516// SECTIONS commands. Sections are laid out as the same order as they
517// were in the script. If a given name did not appear in the script,
518// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000519template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000520 int I = 0;
521 for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
522 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
523 if (Cmd->Name == Name)
524 return I;
525 ++I;
526 }
527 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000528}
529
530// A compartor to sort output sections. Returns -1 or 1 if
531// A or B are mentioned in linker script. Otherwise, returns 0.
Rui Ueyama07320e42016-04-20 20:13:41 +0000532template <class ELFT>
533int LinkerScript<ELFT>::compareSections(StringRef A, StringRef B) {
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000534 int I = getSectionIndex(A);
535 int J = getSectionIndex(B);
536 if (I == INT_MAX && J == INT_MAX)
Rui Ueyama717677a2016-02-11 21:17:59 +0000537 return 0;
538 return I < J ? -1 : 1;
539}
540
Eugene Leviantbbe38602016-07-19 09:25:43 +0000541template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
542 return !Opt.PhdrsCommands.empty();
543}
544
George Rimar9e694502016-07-29 16:18:47 +0000545template <class ELFT>
546typename ELFT::uint LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
547 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
548 if (Sec->getName() == Name)
549 return Sec->getSize();
550 error("undefined section " + Name);
551 return 0;
552}
553
George Rimare32a3592016-08-10 07:59:34 +0000554template <class ELFT>
Rui Ueyama4f7500b2016-08-12 04:00:22 +0000555typename ELFT::uint LinkerScript<ELFT>::getHeaderSize() {
George Rimare32a3592016-08-10 07:59:34 +0000556 return Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
557}
558
Eugene Leviantbbe38602016-07-19 09:25:43 +0000559// Returns indices of ELF headers containing specific section, identified
560// by Name. Each index is a zero based number of ELF header listed within
561// PHDRS {} script block.
562template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000563std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000564 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
565 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000566 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000567 continue;
568
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000569 std::vector<size_t> Ret;
570 for (StringRef PhdrName : Cmd->Phdrs)
571 Ret.push_back(getPhdrIndex(PhdrName));
572 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000573 }
George Rimar31d842f2016-07-20 16:43:03 +0000574 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000575}
576
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000577template <class ELFT>
578size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
579 size_t I = 0;
580 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
581 if (Cmd.Name == PhdrName)
582 return I;
583 ++I;
584 }
585 error("section header '" + PhdrName + "' is not listed in PHDRS");
586 return 0;
587}
588
Rui Ueyama07320e42016-04-20 20:13:41 +0000589class elf::ScriptParser : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000590 typedef void (ScriptParser::*Handler)();
591
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000592public:
Rui Ueyama07320e42016-04-20 20:13:41 +0000593 ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
George Rimarf23b2322016-02-19 10:45:45 +0000594
Rui Ueyama4a465392016-04-22 22:59:24 +0000595 void run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000596
597private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000598 void addFile(StringRef Path);
599
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000600 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000601 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000602 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000603 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000604 void readInclude();
George Rimarc3794e52016-02-24 09:21:47 +0000605 void readNothing() {}
Rui Ueyamaee592822015-10-07 00:25:09 +0000606 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000607 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000608 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000609 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000610 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000611 void readSections();
612
Rui Ueyama113cdec2016-07-24 23:05:57 +0000613 SymbolAssignment *readAssignment(StringRef Name);
Rui Ueyama10416562016-08-04 02:03:27 +0000614 OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000615 std::vector<uint8_t> readOutputSectionFiller();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000616 std::vector<StringRef> readOutputSectionPhdrs();
Rui Ueyama10416562016-08-04 02:03:27 +0000617 InputSectionDescription *readInputSectionDescription();
618 std::vector<StringRef> readInputFilePatterns();
619 InputSectionDescription *readInputSectionRules();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000620 unsigned readPhdrType();
Rui Ueyama742c3832016-08-04 22:27:00 +0000621 SortKind readSortKind();
Petr Hoseka35e39c2016-08-16 01:11:16 +0000622 SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
Eugene Leviantceabe802016-08-11 07:56:43 +0000623 SymbolAssignment *readProvideOrAssignment(StringRef Tok);
George Rimar03fc0102016-07-28 07:18:23 +0000624 void readSort();
George Rimareefa7582016-08-04 09:29:31 +0000625 Expr readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +0000626
627 Expr readExpr();
628 Expr readExpr1(Expr Lhs, int MinPrec);
629 Expr readPrimary();
630 Expr readTernary(Expr Cond);
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +0000631 Expr readParenExpr();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000632
George Rimarc3794e52016-02-24 09:21:47 +0000633 const static StringMap<Handler> Cmd;
Rui Ueyama07320e42016-04-20 20:13:41 +0000634 ScriptConfiguration &Opt = *ScriptConfig;
635 StringSaver Saver = {ScriptConfig->Alloc};
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000636 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000637};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000638
Rafael Espindolae0df00b2016-02-28 00:25:54 +0000639const StringMap<elf::ScriptParser::Handler> elf::ScriptParser::Cmd = {
George Rimarc3794e52016-02-24 09:21:47 +0000640 {"ENTRY", &ScriptParser::readEntry},
641 {"EXTERN", &ScriptParser::readExtern},
642 {"GROUP", &ScriptParser::readGroup},
643 {"INCLUDE", &ScriptParser::readInclude},
644 {"INPUT", &ScriptParser::readGroup},
645 {"OUTPUT", &ScriptParser::readOutput},
646 {"OUTPUT_ARCH", &ScriptParser::readOutputArch},
647 {"OUTPUT_FORMAT", &ScriptParser::readOutputFormat},
Eugene Leviantbbe38602016-07-19 09:25:43 +0000648 {"PHDRS", &ScriptParser::readPhdrs},
George Rimarc3794e52016-02-24 09:21:47 +0000649 {"SEARCH_DIR", &ScriptParser::readSearchDir},
650 {"SECTIONS", &ScriptParser::readSections},
651 {";", &ScriptParser::readNothing}};
652
Rui Ueyama717677a2016-02-11 21:17:59 +0000653void ScriptParser::run() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000654 while (!atEOF()) {
655 StringRef Tok = next();
George Rimarc3794e52016-02-24 09:21:47 +0000656 if (Handler Fn = Cmd.lookup(Tok))
657 (this->*Fn)();
Petr Hosek0df80be2016-08-18 04:34:27 +0000658 else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok))
659 Opt.Commands.emplace_back(Cmd);
George Rimarc3794e52016-02-24 09:21:47 +0000660 else
George Rimar57610422016-03-11 14:43:02 +0000661 setError("unknown directive: " + Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000662 }
663}
664
Rui Ueyama717677a2016-02-11 21:17:59 +0000665void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000666 if (IsUnderSysroot && S.startswith("/")) {
667 SmallString<128> Path;
668 (Config->Sysroot + S).toStringRef(Path);
669 if (sys::fs::exists(Path)) {
670 Driver->addFile(Saver.save(Path.str()));
671 return;
672 }
673 }
674
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +0000675 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +0000676 Driver->addFile(S);
677 } else if (S.startswith("=")) {
678 if (Config->Sysroot.empty())
679 Driver->addFile(S.substr(1));
680 else
681 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
682 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +0000683 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +0000684 } else if (sys::fs::exists(S)) {
685 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +0000686 } else {
687 std::string Path = findFromSearchPaths(S);
688 if (Path.empty())
George Rimar777f9632016-03-12 08:31:34 +0000689 setError("unable to find " + S);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000690 else
691 Driver->addFile(Saver.save(Path));
Rui Ueyama52a15092015-10-11 03:28:42 +0000692 }
693}
694
Rui Ueyama717677a2016-02-11 21:17:59 +0000695void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000696 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +0000697 bool Orig = Config->AsNeeded;
698 Config->AsNeeded = true;
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000699 while (!Error && !skip(")"))
700 addFile(next());
Rui Ueyama35da9b62015-10-11 20:59:12 +0000701 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000702}
703
Rui Ueyama717677a2016-02-11 21:17:59 +0000704void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +0000705 // -e <symbol> takes predecence over ENTRY(<symbol>).
706 expect("(");
707 StringRef Tok = next();
708 if (Config->Entry.empty())
709 Config->Entry = Tok;
710 expect(")");
711}
712
Rui Ueyama717677a2016-02-11 21:17:59 +0000713void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +0000714 expect("(");
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000715 while (!Error && !skip(")"))
716 Config->Undefined.push_back(next());
George Rimar83f406c2015-10-19 17:35:12 +0000717}
718
Rui Ueyama717677a2016-02-11 21:17:59 +0000719void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000720 expect("(");
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000721 while (!Error && !skip(")")) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000722 StringRef Tok = next();
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000723 if (Tok == "AS_NEEDED")
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000724 readAsNeeded();
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000725 else
726 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000727 }
728}
729
Rui Ueyama717677a2016-02-11 21:17:59 +0000730void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000731 StringRef Tok = next();
732 auto MBOrErr = MemoryBuffer::getFile(Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000733 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +0000734 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000735 return;
736 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000737 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Rui Ueyamaa47ee682015-10-11 01:53:04 +0000738 StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
739 std::vector<StringRef> V = tokenize(S);
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000740 Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000741}
742
Rui Ueyama717677a2016-02-11 21:17:59 +0000743void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +0000744 // -o <file> takes predecence over OUTPUT(<file>).
745 expect("(");
746 StringRef Tok = next();
747 if (Config->OutputFile.empty())
748 Config->OutputFile = Tok;
749 expect(")");
750}
751
Rui Ueyama717677a2016-02-11 21:17:59 +0000752void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +0000753 // Error checking only for now.
754 expect("(");
755 next();
756 expect(")");
757}
758
Rui Ueyama717677a2016-02-11 21:17:59 +0000759void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000760 // Error checking only for now.
761 expect("(");
762 next();
Davide Italiano6836c612015-10-12 21:08:41 +0000763 StringRef Tok = next();
764 if (Tok == ")")
765 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000766 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +0000767 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000768 return;
769 }
Davide Italiano6836c612015-10-12 21:08:41 +0000770 next();
771 expect(",");
772 next();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000773 expect(")");
774}
775
Eugene Leviantbbe38602016-07-19 09:25:43 +0000776void ScriptParser::readPhdrs() {
777 expect("{");
778 while (!Error && !skip("}")) {
779 StringRef Tok = next();
Eugene Leviant865bf862016-07-21 10:43:25 +0000780 Opt.PhdrsCommands.push_back({Tok, PT_NULL, false, false, UINT_MAX});
Eugene Leviantbbe38602016-07-19 09:25:43 +0000781 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
782
783 PhdrCmd.Type = readPhdrType();
784 do {
785 Tok = next();
786 if (Tok == ";")
787 break;
788 if (Tok == "FILEHDR")
789 PhdrCmd.HasFilehdr = true;
790 else if (Tok == "PHDRS")
791 PhdrCmd.HasPhdrs = true;
Eugene Leviant865bf862016-07-21 10:43:25 +0000792 else if (Tok == "FLAGS") {
793 expect("(");
Rafael Espindolaeb685cd2016-08-02 22:14:57 +0000794 // Passing 0 for the value of dot is a bit of a hack. It means that
795 // we accept expressions like ".|1".
796 PhdrCmd.Flags = readExpr()(0);
Eugene Leviant865bf862016-07-21 10:43:25 +0000797 expect(")");
798 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +0000799 setError("unexpected header attribute: " + Tok);
800 } while (!Error);
801 }
802}
803
Rui Ueyama717677a2016-02-11 21:17:59 +0000804void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +0000805 expect("(");
Rafael Espindola06501922016-03-08 17:13:12 +0000806 Config->SearchPaths.push_back(next());
Davide Italiano68a39a62015-10-08 17:51:41 +0000807 expect(")");
808}
809
Rui Ueyama717677a2016-02-11 21:17:59 +0000810void ScriptParser::readSections() {
Rui Ueyama3de0a332016-07-29 03:31:09 +0000811 Opt.HasContents = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000812 expect("{");
George Rimar652852c2016-04-16 10:10:32 +0000813 while (!Error && !skip("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +0000814 StringRef Tok = next();
Eugene Leviantceabe802016-08-11 07:56:43 +0000815 BaseCommand *Cmd = readProvideOrAssignment(Tok);
816 if (!Cmd) {
817 if (Tok == "ASSERT")
818 Cmd = new AssertCommand(readAssert());
819 else
820 Cmd = readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +0000821 }
Rui Ueyama10416562016-08-04 02:03:27 +0000822 Opt.Commands.emplace_back(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000823 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000824}
825
Rui Ueyama708019c2016-07-24 18:19:40 +0000826static int precedence(StringRef Op) {
827 return StringSwitch<int>(Op)
828 .Case("*", 4)
829 .Case("/", 4)
830 .Case("+", 3)
831 .Case("-", 3)
832 .Case("<", 2)
833 .Case(">", 2)
834 .Case(">=", 2)
835 .Case("<=", 2)
836 .Case("==", 2)
837 .Case("!=", 2)
838 .Case("&", 1)
839 .Default(-1);
840}
841
Rui Ueyama10416562016-08-04 02:03:27 +0000842std::vector<StringRef> ScriptParser::readInputFilePatterns() {
843 std::vector<StringRef> V;
844 while (!Error && !skip(")"))
845 V.push_back(next());
846 return V;
George Rimar0702c4e2016-07-29 15:32:46 +0000847}
848
Rui Ueyama742c3832016-08-04 22:27:00 +0000849SortKind ScriptParser::readSortKind() {
850 if (skip("SORT") || skip("SORT_BY_NAME"))
851 return SortByName;
852 if (skip("SORT_BY_ALIGNMENT"))
853 return SortByAlignment;
854 return SortNone;
855}
856
Rui Ueyama10416562016-08-04 02:03:27 +0000857InputSectionDescription *ScriptParser::readInputSectionRules() {
858 auto *Cmd = new InputSectionDescription;
859 Cmd->FilePattern = next();
Davide Italiano0ed42b02016-07-25 21:47:13 +0000860 expect("(");
Davide Italianoe7282792016-07-27 01:44:01 +0000861
Rui Ueyama742c3832016-08-04 22:27:00 +0000862 // Read EXCLUDE_FILE().
Davide Italianoe7282792016-07-27 01:44:01 +0000863 if (skip("EXCLUDE_FILE")) {
864 expect("(");
865 while (!Error && !skip(")"))
Rui Ueyama10416562016-08-04 02:03:27 +0000866 Cmd->ExcludedFiles.push_back(next());
Davide Italiano0ed42b02016-07-25 21:47:13 +0000867 }
George Rimar06598002016-07-28 21:51:30 +0000868
Rui Ueyama742c3832016-08-04 22:27:00 +0000869 // Read SORT().
870 if (SortKind K1 = readSortKind()) {
871 Cmd->SortOuter = K1;
George Rimar0702c4e2016-07-29 15:32:46 +0000872 expect("(");
Rui Ueyama742c3832016-08-04 22:27:00 +0000873 if (SortKind K2 = readSortKind()) {
874 Cmd->SortInner = K2;
George Rimar350ece42016-08-03 08:35:59 +0000875 expect("(");
Rui Ueyama10416562016-08-04 02:03:27 +0000876 Cmd->SectionPatterns = readInputFilePatterns();
George Rimar350ece42016-08-03 08:35:59 +0000877 expect(")");
878 } else {
Rui Ueyama10416562016-08-04 02:03:27 +0000879 Cmd->SectionPatterns = readInputFilePatterns();
George Rimar350ece42016-08-03 08:35:59 +0000880 }
George Rimar0702c4e2016-07-29 15:32:46 +0000881 expect(")");
Rui Ueyama10416562016-08-04 02:03:27 +0000882 return Cmd;
George Rimar06598002016-07-28 21:51:30 +0000883 }
George Rimar0702c4e2016-07-29 15:32:46 +0000884
Rui Ueyama10416562016-08-04 02:03:27 +0000885 Cmd->SectionPatterns = readInputFilePatterns();
886 return Cmd;
Davide Italianoe7282792016-07-27 01:44:01 +0000887}
888
Rui Ueyama10416562016-08-04 02:03:27 +0000889InputSectionDescription *ScriptParser::readInputSectionDescription() {
George Rimar06598002016-07-28 21:51:30 +0000890 // Input section wildcard can be surrounded by KEEP.
891 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
892 if (skip("KEEP")) {
893 expect("(");
Rui Ueyama10416562016-08-04 02:03:27 +0000894 InputSectionDescription *Cmd = readInputSectionRules();
George Rimar06598002016-07-28 21:51:30 +0000895 expect(")");
Rui Ueyama10416562016-08-04 02:03:27 +0000896 Opt.KeptSections.insert(Opt.KeptSections.end(),
897 Cmd->SectionPatterns.begin(),
898 Cmd->SectionPatterns.end());
899 return Cmd;
George Rimar06598002016-07-28 21:51:30 +0000900 }
Rui Ueyama10416562016-08-04 02:03:27 +0000901 return readInputSectionRules();
Davide Italiano0ed42b02016-07-25 21:47:13 +0000902}
903
George Rimar03fc0102016-07-28 07:18:23 +0000904void ScriptParser::readSort() {
905 expect("(");
906 expect("CONSTRUCTORS");
907 expect(")");
908}
909
George Rimareefa7582016-08-04 09:29:31 +0000910Expr ScriptParser::readAssert() {
911 expect("(");
912 Expr E = readExpr();
913 expect(",");
914 StringRef Msg = next();
915 expect(")");
916 return [=](uint64_t Dot) {
917 uint64_t V = E(Dot);
918 if (!V)
919 error(Msg);
920 return V;
921 };
922}
923
Rui Ueyama10416562016-08-04 02:03:27 +0000924OutputSectionCommand *
925ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +0000926 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
George Rimar58e5c4d2016-07-25 08:29:46 +0000927
928 // Read an address expression.
929 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
930 if (peek() != ":")
931 Cmd->AddrExpr = readExpr();
932
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000933 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +0000934
George Rimar8ceadb32016-08-17 07:44:19 +0000935 if (skip("AT"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +0000936 Cmd->LmaExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +0000937 if (skip("ALIGN"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +0000938 Cmd->AlignExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +0000939
Davide Italiano246f6812016-07-22 03:36:24 +0000940 // Parse constraints.
941 if (skip("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +0000942 Cmd->Constraint = ConstraintKind::ReadOnly;
Davide Italiano246f6812016-07-22 03:36:24 +0000943 if (skip("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +0000944 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000945 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000946
Rui Ueyama025d59b2016-02-02 20:27:59 +0000947 while (!Error && !skip("}")) {
George Rimarf586ff72016-07-28 22:15:44 +0000948 if (peek().startswith("*") || peek() == "KEEP") {
Rui Ueyama10416562016-08-04 02:03:27 +0000949 Cmd->Commands.emplace_back(readInputSectionDescription());
George Rimar06598002016-07-28 21:51:30 +0000950 continue;
951 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000952
953 StringRef Tok = next();
954 if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok))
955 Cmd->Commands.emplace_back(Assignment);
956 else if (Tok == "SORT")
George Rimar03fc0102016-07-28 07:18:23 +0000957 readSort();
Eugene Leviantceabe802016-08-11 07:56:43 +0000958 else
959 setError("unknown command " + Tok);
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000960 }
George Rimar076fe152016-07-21 06:43:01 +0000961 Cmd->Phdrs = readOutputSectionPhdrs();
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000962 Cmd->Filler = readOutputSectionFiller();
Rui Ueyama10416562016-08-04 02:03:27 +0000963 return Cmd;
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000964}
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000965
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000966std::vector<uint8_t> ScriptParser::readOutputSectionFiller() {
George Rimare2ee72b2016-02-26 14:48:31 +0000967 StringRef Tok = peek();
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000968 if (!Tok.startswith("="))
969 return {};
Davide Italiano5ac0d7c2016-07-29 22:21:28 +0000970 next();
Rui Ueyama965827d2016-08-03 23:25:15 +0000971
972 // Read a hexstring of arbitrary length.
Davide Italiano5ac0d7c2016-07-29 22:21:28 +0000973 if (Tok.startswith("=0x"))
974 return parseHex(Tok.substr(3));
975
Rui Ueyama965827d2016-08-03 23:25:15 +0000976 // Read a decimal or octal value as a big-endian 32 bit value.
977 // Why do this? I don't know, but that's what gold does.
978 uint32_t V;
979 if (Tok.substr(1).getAsInteger(0, V)) {
980 setError("invalid filler expression: " + Tok);
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000981 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000982 }
Rui Ueyama965827d2016-08-03 23:25:15 +0000983 return { uint8_t(V >> 24), uint8_t(V >> 16), uint8_t(V >> 8), uint8_t(V) };
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000984}
985
Petr Hoseka35e39c2016-08-16 01:11:16 +0000986SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000987 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +0000988 SymbolAssignment *Cmd = readAssignment(next());
Petr Hoseka35e39c2016-08-16 01:11:16 +0000989 Cmd->Provide = Provide;
Rui Ueyama174e0a12016-07-29 00:29:25 +0000990 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +0000991 expect(")");
992 expect(";");
Rui Ueyama10416562016-08-04 02:03:27 +0000993 return Cmd;
Eugene Levianteda81a12016-07-12 06:39:48 +0000994}
995
Eugene Leviantceabe802016-08-11 07:56:43 +0000996SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
997 SymbolAssignment *Cmd = nullptr;
998 if (peek() == "=" || peek() == "+=") {
999 Cmd = readAssignment(Tok);
1000 expect(";");
1001 } else if (Tok == "PROVIDE") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001002 Cmd = readProvideHidden(true, false);
1003 } else if (Tok == "HIDDEN") {
1004 Cmd = readProvideHidden(false, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001005 } else if (Tok == "PROVIDE_HIDDEN") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001006 Cmd = readProvideHidden(true, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001007 }
1008 return Cmd;
1009}
1010
George Rimar30835ea2016-07-28 21:08:56 +00001011static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
1012 if (S == ".")
1013 return Dot;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001014
George Rimara9c5a522016-07-26 18:18:58 +00001015 switch (Config->EKind) {
1016 case ELF32LEKind:
1017 if (SymbolBody *B = Symtab<ELF32LE>::X->find(S))
1018 return B->getVA<ELF32LE>();
1019 break;
1020 case ELF32BEKind:
1021 if (SymbolBody *B = Symtab<ELF32BE>::X->find(S))
1022 return B->getVA<ELF32BE>();
1023 break;
1024 case ELF64LEKind:
1025 if (SymbolBody *B = Symtab<ELF64LE>::X->find(S))
1026 return B->getVA<ELF64LE>();
1027 break;
1028 case ELF64BEKind:
1029 if (SymbolBody *B = Symtab<ELF64BE>::X->find(S))
1030 return B->getVA<ELF64BE>();
1031 break;
George Rimar6930a6d2016-07-26 18:41:06 +00001032 default:
George Rimarb567b622016-07-26 18:46:13 +00001033 llvm_unreachable("unsupported target");
George Rimara9c5a522016-07-26 18:18:58 +00001034 }
1035 error("symbol not found: " + S);
1036 return 0;
1037}
1038
George Rimar9e694502016-07-29 16:18:47 +00001039static uint64_t getSectionSize(StringRef Name) {
1040 switch (Config->EKind) {
1041 case ELF32LEKind:
1042 return Script<ELF32LE>::X->getOutputSectionSize(Name);
1043 case ELF32BEKind:
1044 return Script<ELF32BE>::X->getOutputSectionSize(Name);
1045 case ELF64LEKind:
1046 return Script<ELF64LE>::X->getOutputSectionSize(Name);
1047 case ELF64BEKind:
1048 return Script<ELF64BE>::X->getOutputSectionSize(Name);
1049 default:
1050 llvm_unreachable("unsupported target");
1051 }
George Rimar9e694502016-07-29 16:18:47 +00001052}
1053
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001054static uint64_t getHeaderSize() {
George Rimare32a3592016-08-10 07:59:34 +00001055 switch (Config->EKind) {
1056 case ELF32LEKind:
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001057 return Script<ELF32LE>::X->getHeaderSize();
George Rimare32a3592016-08-10 07:59:34 +00001058 case ELF32BEKind:
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001059 return Script<ELF32BE>::X->getHeaderSize();
George Rimare32a3592016-08-10 07:59:34 +00001060 case ELF64LEKind:
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001061 return Script<ELF64LE>::X->getHeaderSize();
George Rimare32a3592016-08-10 07:59:34 +00001062 case ELF64BEKind:
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001063 return Script<ELF64BE>::X->getHeaderSize();
George Rimare32a3592016-08-10 07:59:34 +00001064 default:
1065 llvm_unreachable("unsupported target");
1066 }
1067}
1068
George Rimar30835ea2016-07-28 21:08:56 +00001069SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1070 StringRef Op = next();
1071 assert(Op == "=" || Op == "+=");
1072 Expr E = readExpr();
1073 if (Op == "+=")
1074 E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
Rui Ueyama10416562016-08-04 02:03:27 +00001075 return new SymbolAssignment(Name, E);
George Rimar30835ea2016-07-28 21:08:56 +00001076}
1077
1078// This is an operator-precedence parser to parse a linker
1079// script expression.
1080Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
1081
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001082static Expr combine(StringRef Op, Expr L, Expr R) {
1083 if (Op == "*")
1084 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1085 if (Op == "/") {
1086 return [=](uint64_t Dot) -> uint64_t {
1087 uint64_t RHS = R(Dot);
1088 if (RHS == 0) {
1089 error("division by zero");
1090 return 0;
1091 }
1092 return L(Dot) / RHS;
1093 };
1094 }
1095 if (Op == "+")
1096 return [=](uint64_t Dot) { return L(Dot) + R(Dot); };
1097 if (Op == "-")
1098 return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
1099 if (Op == "<")
1100 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
1101 if (Op == ">")
1102 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
1103 if (Op == ">=")
1104 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
1105 if (Op == "<=")
1106 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
1107 if (Op == "==")
1108 return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
1109 if (Op == "!=")
1110 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
1111 if (Op == "&")
1112 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
1113 llvm_unreachable("invalid operator");
1114}
1115
Rui Ueyama708019c2016-07-24 18:19:40 +00001116// This is a part of the operator-precedence parser. This function
1117// assumes that the remaining token stream starts with an operator.
1118Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1119 while (!atEOF() && !Error) {
1120 // Read an operator and an expression.
1121 StringRef Op1 = peek();
1122 if (Op1 == "?")
1123 return readTernary(Lhs);
1124 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +00001125 break;
Rui Ueyama708019c2016-07-24 18:19:40 +00001126 next();
1127 Expr Rhs = readPrimary();
1128
1129 // Evaluate the remaining part of the expression first if the
1130 // next operator has greater precedence than the previous one.
1131 // For example, if we have read "+" and "3", and if the next
1132 // operator is "*", then we'll evaluate 3 * ... part first.
1133 while (!atEOF()) {
1134 StringRef Op2 = peek();
1135 if (precedence(Op2) <= precedence(Op1))
1136 break;
1137 Rhs = readExpr1(Rhs, precedence(Op2));
1138 }
1139
1140 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +00001141 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001142 return Lhs;
1143}
1144
1145uint64_t static getConstant(StringRef S) {
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001146 if (S == "COMMONPAGESIZE")
Rui Ueyama708019c2016-07-24 18:19:40 +00001147 return Target->PageSize;
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001148 if (S == "MAXPAGESIZE")
1149 return Target->MaxPageSize;
Rui Ueyama708019c2016-07-24 18:19:40 +00001150 error("unknown constant: " + S);
1151 return 0;
1152}
1153
1154Expr ScriptParser::readPrimary() {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001155 if (peek() == "(")
1156 return readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001157
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001158 StringRef Tok = next();
Rui Ueyama708019c2016-07-24 18:19:40 +00001159
1160 // Built-in functions are parsed here.
1161 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
George Rimareefa7582016-08-04 09:29:31 +00001162 if (Tok == "ASSERT")
1163 return readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001164 if (Tok == "ALIGN") {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001165 Expr E = readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001166 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1167 }
1168 if (Tok == "CONSTANT") {
1169 expect("(");
1170 StringRef Tok = next();
1171 expect(")");
1172 return [=](uint64_t Dot) { return getConstant(Tok); };
1173 }
Rafael Espindola54c145c2016-07-28 18:16:24 +00001174 if (Tok == "SEGMENT_START") {
1175 expect("(");
1176 next();
1177 expect(",");
1178 uint64_t Val;
1179 next().getAsInteger(0, Val);
1180 expect(")");
1181 return [=](uint64_t Dot) { return Val; };
1182 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001183 if (Tok == "DATA_SEGMENT_ALIGN") {
1184 expect("(");
1185 Expr E = readExpr();
1186 expect(",");
1187 readExpr();
1188 expect(")");
Rui Ueyamaf7791bb2016-07-26 19:34:10 +00001189 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001190 }
1191 if (Tok == "DATA_SEGMENT_END") {
1192 expect("(");
1193 expect(".");
1194 expect(")");
1195 return [](uint64_t Dot) { return Dot; };
1196 }
George Rimar276b4e62016-07-26 17:58:44 +00001197 // GNU linkers implements more complicated logic to handle
1198 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1199 // the next page boundary for simplicity.
1200 if (Tok == "DATA_SEGMENT_RELRO_END") {
1201 expect("(");
1202 next();
1203 expect(",");
1204 readExpr();
1205 expect(")");
1206 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1207 }
George Rimar9e694502016-07-29 16:18:47 +00001208 if (Tok == "SIZEOF") {
1209 expect("(");
1210 StringRef Name = next();
1211 expect(")");
1212 return [=](uint64_t Dot) { return getSectionSize(Name); };
1213 }
George Rimare32a3592016-08-10 07:59:34 +00001214 if (Tok == "SIZEOF_HEADERS")
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001215 return [=](uint64_t Dot) { return getHeaderSize(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001216
George Rimara9c5a522016-07-26 18:18:58 +00001217 // Parse a symbol name or a number literal.
Rui Ueyama708019c2016-07-24 18:19:40 +00001218 uint64_t V = 0;
George Rimara9c5a522016-07-26 18:18:58 +00001219 if (Tok.getAsInteger(0, V)) {
George Rimar30835ea2016-07-28 21:08:56 +00001220 if (Tok != "." && !isValidCIdentifier(Tok))
George Rimara9c5a522016-07-26 18:18:58 +00001221 setError("malformed number: " + Tok);
George Rimar30835ea2016-07-28 21:08:56 +00001222 return [=](uint64_t Dot) { return getSymbolValue(Tok, Dot); };
George Rimara9c5a522016-07-26 18:18:58 +00001223 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001224 return [=](uint64_t Dot) { return V; };
1225}
1226
1227Expr ScriptParser::readTernary(Expr Cond) {
1228 next();
1229 Expr L = readExpr();
1230 expect(":");
1231 Expr R = readExpr();
1232 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1233}
1234
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001235Expr ScriptParser::readParenExpr() {
1236 expect("(");
1237 Expr E = readExpr();
1238 expect(")");
1239 return E;
1240}
1241
Eugene Leviantbbe38602016-07-19 09:25:43 +00001242std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1243 std::vector<StringRef> Phdrs;
1244 while (!Error && peek().startswith(":")) {
1245 StringRef Tok = next();
1246 Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
1247 if (Tok.empty()) {
1248 setError("section header name is empty");
1249 break;
1250 }
Rui Ueyama047404f2016-07-20 19:36:36 +00001251 Phdrs.push_back(Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001252 }
1253 return Phdrs;
1254}
1255
1256unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001257 StringRef Tok = next();
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001258 unsigned Ret = StringSwitch<unsigned>(Tok)
1259 .Case("PT_NULL", PT_NULL)
1260 .Case("PT_LOAD", PT_LOAD)
1261 .Case("PT_DYNAMIC", PT_DYNAMIC)
1262 .Case("PT_INTERP", PT_INTERP)
1263 .Case("PT_NOTE", PT_NOTE)
1264 .Case("PT_SHLIB", PT_SHLIB)
1265 .Case("PT_PHDR", PT_PHDR)
1266 .Case("PT_TLS", PT_TLS)
1267 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1268 .Case("PT_GNU_STACK", PT_GNU_STACK)
1269 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1270 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001271
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001272 if (Ret == (unsigned)-1) {
1273 setError("invalid program header type: " + Tok);
1274 return PT_NULL;
1275 }
1276 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001277}
1278
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001279static bool isUnderSysroot(StringRef Path) {
1280 if (Config->Sysroot == "")
1281 return false;
1282 for (; !Path.empty(); Path = sys::path::parent_path(Path))
1283 if (sys::fs::equivalent(Config->Sysroot, Path))
1284 return true;
1285 return false;
1286}
1287
Rui Ueyama07320e42016-04-20 20:13:41 +00001288// Entry point.
1289void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001290 StringRef Path = MB.getBufferIdentifier();
Rui Ueyama07320e42016-04-20 20:13:41 +00001291 ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001292}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001293
Rui Ueyama07320e42016-04-20 20:13:41 +00001294template class elf::LinkerScript<ELF32LE>;
1295template class elf::LinkerScript<ELF32BE>;
1296template class elf::LinkerScript<ELF64LE>;
1297template class elf::LinkerScript<ELF64BE>;