blob: 35a1a6143a2325351337940290e3544018e43c80 [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)
Eugene Leviant3f675e32016-08-18 07:27:37 +0000287 if (!Sec->OutSec)
288 OutSec->addSection(Sec);
Eugene Leviantceabe802016-08-11 07:56:43 +0000289 }
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000290 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000291
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000292 // Add orphan sections.
Rui Ueyama6b274812016-07-25 22:51:07 +0000293 for (const std::unique_ptr<ObjectFile<ELFT>> &F :
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000294 Symtab<ELFT>::X->getObjectFiles()) {
295 for (InputSectionBase<ELFT> *S : F->getSections()) {
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000296 if (isDiscarded(S) || S->OutSec)
297 continue;
298 OutputSectionBase<ELFT> *OutSec;
299 bool IsNew;
300 std::tie(OutSec, IsNew) = Factory.create(S, getOutputSectionName(S));
301 if (IsNew)
302 OutputSections->push_back(OutSec);
303 OutSec->addSection(S);
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000304 }
305 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000306}
307
Eugene Leviantceabe802016-08-11 07:56:43 +0000308template <class ELFT> void assignOffsets(OutputSectionBase<ELFT> *Sec) {
Eugene Leviantceabe802016-08-11 07:56:43 +0000309 auto *OutSec = dyn_cast<OutputSection<ELFT>>(Sec);
Rui Ueyama2de509c2016-08-12 00:55:08 +0000310 if (!OutSec) {
311 Sec->assignOffsets();
Eugene Leviantceabe802016-08-11 07:56:43 +0000312 return;
Rui Ueyama2de509c2016-08-12 00:55:08 +0000313 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000314
315 typedef typename ELFT::uint uintX_t;
316 uintX_t Off = 0;
317
318 for (InputSection<ELFT> *I : OutSec->Sections) {
319 if (auto *L = dyn_cast<LayoutInputSection<ELFT>>(I)) {
320 uintX_t Value = L->Cmd->Expression(Sec->getVA() + Off) - Sec->getVA();
Rui Ueyama0c70d3c2016-08-12 03:31:09 +0000321 if (L->Cmd->Name == ".") {
Eugene Leviantceabe802016-08-11 07:56:43 +0000322 Off = Value;
Eugene Leviantb6f1bb12016-08-15 09:19:51 +0000323 } else if (auto *Sym =
324 cast_or_null<DefinedSynthetic<ELFT>>(L->Cmd->Sym)) {
325 // shouldDefine could have returned false, so we need to check Sym,
326 // for non-null value.
Rui Ueyama0c70d3c2016-08-12 03:31:09 +0000327 Sym->Section = OutSec;
328 Sym->Value = Value;
329 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000330 } else {
331 Off = alignTo(Off, I->Alignment);
332 I->OutSecOff = Off;
333 Off += I->getSize();
334 }
Rui Ueyamaf4a30a52016-08-11 21:30:42 +0000335 // Update section size inside for-loop, so that SIZEOF
Eugene Leviantceabe802016-08-11 07:56:43 +0000336 // works correctly in the case below:
337 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
338 Sec->setSize(Off);
339 }
340}
341
George Rimar8f66df92016-08-12 20:38:20 +0000342template <class ELFT>
343static OutputSectionBase<ELFT> *
344findSection(OutputSectionCommand &Cmd,
345 ArrayRef<OutputSectionBase<ELFT> *> Sections) {
346 for (OutputSectionBase<ELFT> *Sec : Sections) {
347 if (Sec->getName() != Cmd.Name)
348 continue;
349 if (checkConstraint(Sec->getFlags(), Cmd.Constraint))
350 return Sec;
351 }
352 return nullptr;
353}
354
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000355template <class ELFT> void LinkerScript<ELFT>::assignAddresses() {
George Rimar652852c2016-04-16 10:10:32 +0000356 // Orphan sections are sections present in the input files which
Rui Ueyama7c18c282016-04-18 21:00:40 +0000357 // are not explicitly placed into the output file by the linker script.
358 // We place orphan sections at end of file.
359 // Other linkers places them using some heuristics as described in
George Rimar652852c2016-04-16 10:10:32 +0000360 // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
Rui Ueyamae5cc6682016-08-12 00:36:56 +0000361 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
George Rimar652852c2016-04-16 10:10:32 +0000362 StringRef Name = Sec->getName();
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000363 if (getSectionIndex(Name) == INT_MAX)
George Rimar076fe152016-07-21 06:43:01 +0000364 Opt.Commands.push_back(llvm::make_unique<OutputSectionCommand>(Name));
George Rimar652852c2016-04-16 10:10:32 +0000365 }
George Rimar652852c2016-04-16 10:10:32 +0000366
Rui Ueyama7c18c282016-04-18 21:00:40 +0000367 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rui Ueyama4f7500b2016-08-12 04:00:22 +0000368 Dot = getHeaderSize();
Eugene Leviant467c4d52016-07-01 10:27:36 +0000369 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
George Rimar652852c2016-04-16 10:10:32 +0000370 uintX_t ThreadBssOffset = 0;
George Rimar652852c2016-04-16 10:10:32 +0000371
George Rimar076fe152016-07-21 06:43:01 +0000372 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
373 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
Rui Ueyama8d083e62016-07-29 05:48:39 +0000374 if (Cmd->Name == ".") {
375 Dot = Cmd->Expression(Dot);
376 } else if (Cmd->Sym) {
377 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(Dot);
378 }
George Rimar652852c2016-04-16 10:10:32 +0000379 continue;
380 }
381
George Rimareefa7582016-08-04 09:29:31 +0000382 if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
383 Cmd->Expression(Dot);
384 continue;
385 }
386
George Rimar076fe152016-07-21 06:43:01 +0000387 auto *Cmd = cast<OutputSectionCommand>(Base.get());
George Rimar8f66df92016-08-12 20:38:20 +0000388 OutputSectionBase<ELFT> *Sec = findSection<ELFT>(*Cmd, *OutputSections);
389 if (!Sec)
George Rimarb6c52e82016-08-12 19:32:45 +0000390 continue;
George Rimar652852c2016-04-16 10:10:32 +0000391
George Rimarb6c52e82016-08-12 19:32:45 +0000392 if (Cmd->AddrExpr)
393 Dot = Cmd->AddrExpr(Dot);
George Rimar58e5c4d2016-07-25 08:29:46 +0000394
George Rimarb6c52e82016-08-12 19:32:45 +0000395 if (Cmd->AlignExpr)
396 Sec->updateAlignment(Cmd->AlignExpr(Dot));
George Rimar630c6172016-07-26 18:06:29 +0000397
George Rimarb6c52e82016-08-12 19:32:45 +0000398 if ((Sec->getFlags() & SHF_TLS) && Sec->getType() == SHT_NOBITS) {
399 uintX_t TVA = Dot + ThreadBssOffset;
400 TVA = alignTo(TVA, Sec->getAlignment());
401 Sec->setVA(TVA);
402 assignOffsets(Sec);
403 ThreadBssOffset = TVA - Dot + Sec->getSize();
404 continue;
George Rimar652852c2016-04-16 10:10:32 +0000405 }
George Rimarb6c52e82016-08-12 19:32:45 +0000406
407 if (!(Sec->getFlags() & SHF_ALLOC)) {
408 Sec->assignOffsets();
409 continue;
410 }
411
412 Dot = alignTo(Dot, Sec->getAlignment());
413 Sec->setVA(Dot);
414 assignOffsets(Sec);
415 MinVA = std::min(MinVA, Dot);
416 Dot += Sec->getSize();
George Rimar652852c2016-04-16 10:10:32 +0000417 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000418
Rafael Espindola64c32d62016-07-07 14:28:47 +0000419 // ELF and Program headers need to be right before the first section in
George Rimarb91e7112016-07-19 07:42:07 +0000420 // memory. Set their addresses accordingly.
Eugene Leviant467c4d52016-07-01 10:27:36 +0000421 MinVA = alignDown(MinVA - Out<ELFT>::ElfHeader->getSize() -
422 Out<ELFT>::ProgramHeaders->getSize(),
423 Target->PageSize);
424 Out<ELFT>::ElfHeader->setVA(MinVA);
425 Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
George Rimar652852c2016-04-16 10:10:32 +0000426}
427
Rui Ueyama07320e42016-04-20 20:13:41 +0000428template <class ELFT>
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000429std::vector<PhdrEntry<ELFT>> LinkerScript<ELFT>::createPhdrs() {
430 ArrayRef<OutputSectionBase<ELFT> *> Sections = *OutputSections;
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000431 std::vector<PhdrEntry<ELFT>> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000432
433 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000434 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
435 PhdrEntry<ELFT> &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000436
437 if (Cmd.HasFilehdr)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000438 Phdr.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000439 if (Cmd.HasPhdrs)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000440 Phdr.add(Out<ELFT>::ProgramHeaders);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000441
442 switch (Cmd.Type) {
443 case PT_INTERP:
Rui Ueyamafd03cfd2016-07-21 11:01:23 +0000444 if (Out<ELFT>::Interp)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000445 Phdr.add(Out<ELFT>::Interp);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000446 break;
447 case PT_DYNAMIC:
Rui Ueyama1034c9e2016-08-09 04:42:01 +0000448 if (Out<ELFT>::DynSymTab) {
Rafael Espindola0b113672016-07-27 14:10:56 +0000449 Phdr.H.p_flags = Out<ELFT>::Dynamic->getPhdrFlags();
Rui Ueyamaadca2452016-07-23 14:18:48 +0000450 Phdr.add(Out<ELFT>::Dynamic);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000451 }
452 break;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000453 case PT_GNU_EH_FRAME:
454 if (!Out<ELFT>::EhFrame->empty() && Out<ELFT>::EhFrameHdr) {
Rafael Espindola0b113672016-07-27 14:10:56 +0000455 Phdr.H.p_flags = Out<ELFT>::EhFrameHdr->getPhdrFlags();
Rui Ueyamaadca2452016-07-23 14:18:48 +0000456 Phdr.add(Out<ELFT>::EhFrameHdr);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000457 }
458 break;
459 }
460 }
461
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000462 PhdrEntry<ELFT> *Load = nullptr;
463 uintX_t Flags = PF_R;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000464 for (OutputSectionBase<ELFT> *Sec : Sections) {
465 if (!(Sec->getFlags() & SHF_ALLOC))
466 break;
467
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000468 std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName());
Eugene Leviantbbe38602016-07-19 09:25:43 +0000469 if (!PhdrIds.empty()) {
470 // Assign headers specified by linker script
471 for (size_t Id : PhdrIds) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000472 Ret[Id].add(Sec);
Eugene Leviant865bf862016-07-21 10:43:25 +0000473 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
Rafael Espindola0b113672016-07-27 14:10:56 +0000474 Ret[Id].H.p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000475 }
476 } else {
477 // If we have no load segment or flags've changed then we want new load
478 // segment.
Rafael Espindola0b113672016-07-27 14:10:56 +0000479 uintX_t NewFlags = Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000480 if (Load == nullptr || Flags != NewFlags) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000481 Load = &*Ret.emplace(Ret.end(), PT_LOAD, NewFlags);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000482 Flags = NewFlags;
483 }
Rui Ueyama18f084f2016-07-20 19:36:41 +0000484 Load->add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000485 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000486 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000487 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000488}
489
Eugene Leviantf9bc3bd2016-08-16 06:40:58 +0000490template <class ELFT> bool LinkerScript<ELFT>::ignoreInterpSection() {
491 // Ignore .interp section in case we have PHDRS specification
492 // and PT_INTERP isn't listed.
493 return !Opt.PhdrsCommands.empty() &&
494 llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
495 return Cmd.Type == PT_INTERP;
496 }) == Opt.PhdrsCommands.end();
497}
498
Eugene Leviantbbe38602016-07-19 09:25:43 +0000499template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000500ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000501 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
502 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
503 if (Cmd->Name == Name)
504 return Cmd->Filler;
505 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000506}
507
George Rimar206fffa2016-08-17 08:16:57 +0000508template <class ELFT> Expr LinkerScript<ELFT>::getLma(StringRef Name) {
George Rimar8ceadb32016-08-17 07:44:19 +0000509 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
510 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
511 if (Cmd->LmaExpr && Cmd->Name == Name)
512 return Cmd->LmaExpr;
513 return {};
514}
515
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000516// Returns the index of the given section name in linker script
517// SECTIONS commands. Sections are laid out as the same order as they
518// were in the script. If a given name did not appear in the script,
519// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000520template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000521 int I = 0;
522 for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
523 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
524 if (Cmd->Name == Name)
525 return I;
526 ++I;
527 }
528 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000529}
530
531// A compartor to sort output sections. Returns -1 or 1 if
532// A or B are mentioned in linker script. Otherwise, returns 0.
Rui Ueyama07320e42016-04-20 20:13:41 +0000533template <class ELFT>
534int LinkerScript<ELFT>::compareSections(StringRef A, StringRef B) {
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000535 int I = getSectionIndex(A);
536 int J = getSectionIndex(B);
537 if (I == INT_MAX && J == INT_MAX)
Rui Ueyama717677a2016-02-11 21:17:59 +0000538 return 0;
539 return I < J ? -1 : 1;
540}
541
Eugene Leviantbbe38602016-07-19 09:25:43 +0000542template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
543 return !Opt.PhdrsCommands.empty();
544}
545
George Rimar9e694502016-07-29 16:18:47 +0000546template <class ELFT>
547typename ELFT::uint LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
548 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
549 if (Sec->getName() == Name)
550 return Sec->getSize();
551 error("undefined section " + Name);
552 return 0;
553}
554
George Rimare32a3592016-08-10 07:59:34 +0000555template <class ELFT>
Rui Ueyama4f7500b2016-08-12 04:00:22 +0000556typename ELFT::uint LinkerScript<ELFT>::getHeaderSize() {
George Rimare32a3592016-08-10 07:59:34 +0000557 return Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
558}
559
Eugene Leviantbbe38602016-07-19 09:25:43 +0000560// Returns indices of ELF headers containing specific section, identified
561// by Name. Each index is a zero based number of ELF header listed within
562// PHDRS {} script block.
563template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000564std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000565 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
566 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000567 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000568 continue;
569
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000570 std::vector<size_t> Ret;
571 for (StringRef PhdrName : Cmd->Phdrs)
572 Ret.push_back(getPhdrIndex(PhdrName));
573 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000574 }
George Rimar31d842f2016-07-20 16:43:03 +0000575 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000576}
577
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000578template <class ELFT>
579size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
580 size_t I = 0;
581 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
582 if (Cmd.Name == PhdrName)
583 return I;
584 ++I;
585 }
586 error("section header '" + PhdrName + "' is not listed in PHDRS");
587 return 0;
588}
589
Rui Ueyama07320e42016-04-20 20:13:41 +0000590class elf::ScriptParser : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000591 typedef void (ScriptParser::*Handler)();
592
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000593public:
Rui Ueyama07320e42016-04-20 20:13:41 +0000594 ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
George Rimarf23b2322016-02-19 10:45:45 +0000595
Rui Ueyama4a465392016-04-22 22:59:24 +0000596 void run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000597
598private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000599 void addFile(StringRef Path);
600
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000601 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000602 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000603 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000604 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000605 void readInclude();
George Rimarc3794e52016-02-24 09:21:47 +0000606 void readNothing() {}
Rui Ueyamaee592822015-10-07 00:25:09 +0000607 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000608 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000609 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000610 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000611 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000612 void readSections();
613
Rui Ueyama113cdec2016-07-24 23:05:57 +0000614 SymbolAssignment *readAssignment(StringRef Name);
Rui Ueyama10416562016-08-04 02:03:27 +0000615 OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000616 std::vector<uint8_t> readOutputSectionFiller();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000617 std::vector<StringRef> readOutputSectionPhdrs();
Rui Ueyama10416562016-08-04 02:03:27 +0000618 InputSectionDescription *readInputSectionDescription();
619 std::vector<StringRef> readInputFilePatterns();
620 InputSectionDescription *readInputSectionRules();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000621 unsigned readPhdrType();
Rui Ueyama742c3832016-08-04 22:27:00 +0000622 SortKind readSortKind();
Petr Hoseka35e39c2016-08-16 01:11:16 +0000623 SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
Eugene Leviantceabe802016-08-11 07:56:43 +0000624 SymbolAssignment *readProvideOrAssignment(StringRef Tok);
George Rimar03fc0102016-07-28 07:18:23 +0000625 void readSort();
George Rimareefa7582016-08-04 09:29:31 +0000626 Expr readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +0000627
628 Expr readExpr();
629 Expr readExpr1(Expr Lhs, int MinPrec);
630 Expr readPrimary();
631 Expr readTernary(Expr Cond);
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +0000632 Expr readParenExpr();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000633
George Rimarc3794e52016-02-24 09:21:47 +0000634 const static StringMap<Handler> Cmd;
Rui Ueyama07320e42016-04-20 20:13:41 +0000635 ScriptConfiguration &Opt = *ScriptConfig;
636 StringSaver Saver = {ScriptConfig->Alloc};
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000637 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000638};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000639
Rafael Espindolae0df00b2016-02-28 00:25:54 +0000640const StringMap<elf::ScriptParser::Handler> elf::ScriptParser::Cmd = {
George Rimarc3794e52016-02-24 09:21:47 +0000641 {"ENTRY", &ScriptParser::readEntry},
642 {"EXTERN", &ScriptParser::readExtern},
643 {"GROUP", &ScriptParser::readGroup},
644 {"INCLUDE", &ScriptParser::readInclude},
645 {"INPUT", &ScriptParser::readGroup},
646 {"OUTPUT", &ScriptParser::readOutput},
647 {"OUTPUT_ARCH", &ScriptParser::readOutputArch},
648 {"OUTPUT_FORMAT", &ScriptParser::readOutputFormat},
Eugene Leviantbbe38602016-07-19 09:25:43 +0000649 {"PHDRS", &ScriptParser::readPhdrs},
George Rimarc3794e52016-02-24 09:21:47 +0000650 {"SEARCH_DIR", &ScriptParser::readSearchDir},
651 {"SECTIONS", &ScriptParser::readSections},
652 {";", &ScriptParser::readNothing}};
653
Rui Ueyama717677a2016-02-11 21:17:59 +0000654void ScriptParser::run() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000655 while (!atEOF()) {
656 StringRef Tok = next();
George Rimarc3794e52016-02-24 09:21:47 +0000657 if (Handler Fn = Cmd.lookup(Tok))
658 (this->*Fn)();
Petr Hosek0df80be2016-08-18 04:34:27 +0000659 else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok))
660 Opt.Commands.emplace_back(Cmd);
George Rimarc3794e52016-02-24 09:21:47 +0000661 else
George Rimar57610422016-03-11 14:43:02 +0000662 setError("unknown directive: " + Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000663 }
664}
665
Rui Ueyama717677a2016-02-11 21:17:59 +0000666void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000667 if (IsUnderSysroot && S.startswith("/")) {
668 SmallString<128> Path;
669 (Config->Sysroot + S).toStringRef(Path);
670 if (sys::fs::exists(Path)) {
671 Driver->addFile(Saver.save(Path.str()));
672 return;
673 }
674 }
675
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +0000676 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +0000677 Driver->addFile(S);
678 } else if (S.startswith("=")) {
679 if (Config->Sysroot.empty())
680 Driver->addFile(S.substr(1));
681 else
682 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
683 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +0000684 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +0000685 } else if (sys::fs::exists(S)) {
686 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +0000687 } else {
688 std::string Path = findFromSearchPaths(S);
689 if (Path.empty())
George Rimar777f9632016-03-12 08:31:34 +0000690 setError("unable to find " + S);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000691 else
692 Driver->addFile(Saver.save(Path));
Rui Ueyama52a15092015-10-11 03:28:42 +0000693 }
694}
695
Rui Ueyama717677a2016-02-11 21:17:59 +0000696void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000697 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +0000698 bool Orig = Config->AsNeeded;
699 Config->AsNeeded = true;
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000700 while (!Error && !skip(")"))
701 addFile(next());
Rui Ueyama35da9b62015-10-11 20:59:12 +0000702 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000703}
704
Rui Ueyama717677a2016-02-11 21:17:59 +0000705void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +0000706 // -e <symbol> takes predecence over ENTRY(<symbol>).
707 expect("(");
708 StringRef Tok = next();
709 if (Config->Entry.empty())
710 Config->Entry = Tok;
711 expect(")");
712}
713
Rui Ueyama717677a2016-02-11 21:17:59 +0000714void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +0000715 expect("(");
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000716 while (!Error && !skip(")"))
717 Config->Undefined.push_back(next());
George Rimar83f406c2015-10-19 17:35:12 +0000718}
719
Rui Ueyama717677a2016-02-11 21:17:59 +0000720void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000721 expect("(");
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000722 while (!Error && !skip(")")) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000723 StringRef Tok = next();
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000724 if (Tok == "AS_NEEDED")
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000725 readAsNeeded();
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000726 else
727 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000728 }
729}
730
Rui Ueyama717677a2016-02-11 21:17:59 +0000731void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000732 StringRef Tok = next();
733 auto MBOrErr = MemoryBuffer::getFile(Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000734 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +0000735 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000736 return;
737 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000738 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Rui Ueyamaa47ee682015-10-11 01:53:04 +0000739 StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
740 std::vector<StringRef> V = tokenize(S);
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000741 Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000742}
743
Rui Ueyama717677a2016-02-11 21:17:59 +0000744void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +0000745 // -o <file> takes predecence over OUTPUT(<file>).
746 expect("(");
747 StringRef Tok = next();
748 if (Config->OutputFile.empty())
749 Config->OutputFile = Tok;
750 expect(")");
751}
752
Rui Ueyama717677a2016-02-11 21:17:59 +0000753void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +0000754 // Error checking only for now.
755 expect("(");
756 next();
757 expect(")");
758}
759
Rui Ueyama717677a2016-02-11 21:17:59 +0000760void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000761 // Error checking only for now.
762 expect("(");
763 next();
Davide Italiano6836c612015-10-12 21:08:41 +0000764 StringRef Tok = next();
765 if (Tok == ")")
766 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000767 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +0000768 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000769 return;
770 }
Davide Italiano6836c612015-10-12 21:08:41 +0000771 next();
772 expect(",");
773 next();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000774 expect(")");
775}
776
Eugene Leviantbbe38602016-07-19 09:25:43 +0000777void ScriptParser::readPhdrs() {
778 expect("{");
779 while (!Error && !skip("}")) {
780 StringRef Tok = next();
Eugene Leviant865bf862016-07-21 10:43:25 +0000781 Opt.PhdrsCommands.push_back({Tok, PT_NULL, false, false, UINT_MAX});
Eugene Leviantbbe38602016-07-19 09:25:43 +0000782 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
783
784 PhdrCmd.Type = readPhdrType();
785 do {
786 Tok = next();
787 if (Tok == ";")
788 break;
789 if (Tok == "FILEHDR")
790 PhdrCmd.HasFilehdr = true;
791 else if (Tok == "PHDRS")
792 PhdrCmd.HasPhdrs = true;
Eugene Leviant865bf862016-07-21 10:43:25 +0000793 else if (Tok == "FLAGS") {
794 expect("(");
Rafael Espindolaeb685cd2016-08-02 22:14:57 +0000795 // Passing 0 for the value of dot is a bit of a hack. It means that
796 // we accept expressions like ".|1".
797 PhdrCmd.Flags = readExpr()(0);
Eugene Leviant865bf862016-07-21 10:43:25 +0000798 expect(")");
799 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +0000800 setError("unexpected header attribute: " + Tok);
801 } while (!Error);
802 }
803}
804
Rui Ueyama717677a2016-02-11 21:17:59 +0000805void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +0000806 expect("(");
Rafael Espindola06501922016-03-08 17:13:12 +0000807 Config->SearchPaths.push_back(next());
Davide Italiano68a39a62015-10-08 17:51:41 +0000808 expect(")");
809}
810
Rui Ueyama717677a2016-02-11 21:17:59 +0000811void ScriptParser::readSections() {
Rui Ueyama3de0a332016-07-29 03:31:09 +0000812 Opt.HasContents = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000813 expect("{");
George Rimar652852c2016-04-16 10:10:32 +0000814 while (!Error && !skip("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +0000815 StringRef Tok = next();
Eugene Leviantceabe802016-08-11 07:56:43 +0000816 BaseCommand *Cmd = readProvideOrAssignment(Tok);
817 if (!Cmd) {
818 if (Tok == "ASSERT")
819 Cmd = new AssertCommand(readAssert());
820 else
821 Cmd = readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +0000822 }
Rui Ueyama10416562016-08-04 02:03:27 +0000823 Opt.Commands.emplace_back(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000824 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000825}
826
Rui Ueyama708019c2016-07-24 18:19:40 +0000827static int precedence(StringRef Op) {
828 return StringSwitch<int>(Op)
829 .Case("*", 4)
830 .Case("/", 4)
831 .Case("+", 3)
832 .Case("-", 3)
833 .Case("<", 2)
834 .Case(">", 2)
835 .Case(">=", 2)
836 .Case("<=", 2)
837 .Case("==", 2)
838 .Case("!=", 2)
839 .Case("&", 1)
840 .Default(-1);
841}
842
Rui Ueyama10416562016-08-04 02:03:27 +0000843std::vector<StringRef> ScriptParser::readInputFilePatterns() {
844 std::vector<StringRef> V;
845 while (!Error && !skip(")"))
846 V.push_back(next());
847 return V;
George Rimar0702c4e2016-07-29 15:32:46 +0000848}
849
Rui Ueyama742c3832016-08-04 22:27:00 +0000850SortKind ScriptParser::readSortKind() {
851 if (skip("SORT") || skip("SORT_BY_NAME"))
852 return SortByName;
853 if (skip("SORT_BY_ALIGNMENT"))
854 return SortByAlignment;
855 return SortNone;
856}
857
Rui Ueyama10416562016-08-04 02:03:27 +0000858InputSectionDescription *ScriptParser::readInputSectionRules() {
859 auto *Cmd = new InputSectionDescription;
860 Cmd->FilePattern = next();
Davide Italiano0ed42b02016-07-25 21:47:13 +0000861 expect("(");
Davide Italianoe7282792016-07-27 01:44:01 +0000862
Rui Ueyama742c3832016-08-04 22:27:00 +0000863 // Read EXCLUDE_FILE().
Davide Italianoe7282792016-07-27 01:44:01 +0000864 if (skip("EXCLUDE_FILE")) {
865 expect("(");
866 while (!Error && !skip(")"))
Rui Ueyama10416562016-08-04 02:03:27 +0000867 Cmd->ExcludedFiles.push_back(next());
Davide Italiano0ed42b02016-07-25 21:47:13 +0000868 }
George Rimar06598002016-07-28 21:51:30 +0000869
Rui Ueyama742c3832016-08-04 22:27:00 +0000870 // Read SORT().
871 if (SortKind K1 = readSortKind()) {
872 Cmd->SortOuter = K1;
George Rimar0702c4e2016-07-29 15:32:46 +0000873 expect("(");
Rui Ueyama742c3832016-08-04 22:27:00 +0000874 if (SortKind K2 = readSortKind()) {
875 Cmd->SortInner = K2;
George Rimar350ece42016-08-03 08:35:59 +0000876 expect("(");
Rui Ueyama10416562016-08-04 02:03:27 +0000877 Cmd->SectionPatterns = readInputFilePatterns();
George Rimar350ece42016-08-03 08:35:59 +0000878 expect(")");
879 } else {
Rui Ueyama10416562016-08-04 02:03:27 +0000880 Cmd->SectionPatterns = readInputFilePatterns();
George Rimar350ece42016-08-03 08:35:59 +0000881 }
George Rimar0702c4e2016-07-29 15:32:46 +0000882 expect(")");
Rui Ueyama10416562016-08-04 02:03:27 +0000883 return Cmd;
George Rimar06598002016-07-28 21:51:30 +0000884 }
George Rimar0702c4e2016-07-29 15:32:46 +0000885
Rui Ueyama10416562016-08-04 02:03:27 +0000886 Cmd->SectionPatterns = readInputFilePatterns();
887 return Cmd;
Davide Italianoe7282792016-07-27 01:44:01 +0000888}
889
Rui Ueyama10416562016-08-04 02:03:27 +0000890InputSectionDescription *ScriptParser::readInputSectionDescription() {
George Rimar06598002016-07-28 21:51:30 +0000891 // Input section wildcard can be surrounded by KEEP.
892 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
893 if (skip("KEEP")) {
894 expect("(");
Rui Ueyama10416562016-08-04 02:03:27 +0000895 InputSectionDescription *Cmd = readInputSectionRules();
George Rimar06598002016-07-28 21:51:30 +0000896 expect(")");
Rui Ueyama10416562016-08-04 02:03:27 +0000897 Opt.KeptSections.insert(Opt.KeptSections.end(),
898 Cmd->SectionPatterns.begin(),
899 Cmd->SectionPatterns.end());
900 return Cmd;
George Rimar06598002016-07-28 21:51:30 +0000901 }
Rui Ueyama10416562016-08-04 02:03:27 +0000902 return readInputSectionRules();
Davide Italiano0ed42b02016-07-25 21:47:13 +0000903}
904
George Rimar03fc0102016-07-28 07:18:23 +0000905void ScriptParser::readSort() {
906 expect("(");
907 expect("CONSTRUCTORS");
908 expect(")");
909}
910
George Rimareefa7582016-08-04 09:29:31 +0000911Expr ScriptParser::readAssert() {
912 expect("(");
913 Expr E = readExpr();
914 expect(",");
915 StringRef Msg = next();
916 expect(")");
917 return [=](uint64_t Dot) {
918 uint64_t V = E(Dot);
919 if (!V)
920 error(Msg);
921 return V;
922 };
923}
924
Rui Ueyama10416562016-08-04 02:03:27 +0000925OutputSectionCommand *
926ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +0000927 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
George Rimar58e5c4d2016-07-25 08:29:46 +0000928
929 // Read an address expression.
930 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
931 if (peek() != ":")
932 Cmd->AddrExpr = readExpr();
933
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000934 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +0000935
George Rimar8ceadb32016-08-17 07:44:19 +0000936 if (skip("AT"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +0000937 Cmd->LmaExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +0000938 if (skip("ALIGN"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +0000939 Cmd->AlignExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +0000940
Davide Italiano246f6812016-07-22 03:36:24 +0000941 // Parse constraints.
942 if (skip("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +0000943 Cmd->Constraint = ConstraintKind::ReadOnly;
Davide Italiano246f6812016-07-22 03:36:24 +0000944 if (skip("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +0000945 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000946 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000947
Rui Ueyama025d59b2016-02-02 20:27:59 +0000948 while (!Error && !skip("}")) {
George Rimarf586ff72016-07-28 22:15:44 +0000949 if (peek().startswith("*") || peek() == "KEEP") {
Rui Ueyama10416562016-08-04 02:03:27 +0000950 Cmd->Commands.emplace_back(readInputSectionDescription());
George Rimar06598002016-07-28 21:51:30 +0000951 continue;
952 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000953
954 StringRef Tok = next();
955 if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok))
956 Cmd->Commands.emplace_back(Assignment);
957 else if (Tok == "SORT")
George Rimar03fc0102016-07-28 07:18:23 +0000958 readSort();
Eugene Leviantceabe802016-08-11 07:56:43 +0000959 else
960 setError("unknown command " + Tok);
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000961 }
George Rimar076fe152016-07-21 06:43:01 +0000962 Cmd->Phdrs = readOutputSectionPhdrs();
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000963 Cmd->Filler = readOutputSectionFiller();
Rui Ueyama10416562016-08-04 02:03:27 +0000964 return Cmd;
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000965}
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000966
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000967std::vector<uint8_t> ScriptParser::readOutputSectionFiller() {
George Rimare2ee72b2016-02-26 14:48:31 +0000968 StringRef Tok = peek();
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000969 if (!Tok.startswith("="))
970 return {};
Davide Italiano5ac0d7c2016-07-29 22:21:28 +0000971 next();
Rui Ueyama965827d2016-08-03 23:25:15 +0000972
973 // Read a hexstring of arbitrary length.
Davide Italiano5ac0d7c2016-07-29 22:21:28 +0000974 if (Tok.startswith("=0x"))
975 return parseHex(Tok.substr(3));
976
Rui Ueyama965827d2016-08-03 23:25:15 +0000977 // Read a decimal or octal value as a big-endian 32 bit value.
978 // Why do this? I don't know, but that's what gold does.
979 uint32_t V;
980 if (Tok.substr(1).getAsInteger(0, V)) {
981 setError("invalid filler expression: " + Tok);
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000982 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000983 }
Rui Ueyama965827d2016-08-03 23:25:15 +0000984 return { uint8_t(V >> 24), uint8_t(V >> 16), uint8_t(V >> 8), uint8_t(V) };
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000985}
986
Petr Hoseka35e39c2016-08-16 01:11:16 +0000987SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000988 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +0000989 SymbolAssignment *Cmd = readAssignment(next());
Petr Hoseka35e39c2016-08-16 01:11:16 +0000990 Cmd->Provide = Provide;
Rui Ueyama174e0a12016-07-29 00:29:25 +0000991 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +0000992 expect(")");
993 expect(";");
Rui Ueyama10416562016-08-04 02:03:27 +0000994 return Cmd;
Eugene Levianteda81a12016-07-12 06:39:48 +0000995}
996
Eugene Leviantceabe802016-08-11 07:56:43 +0000997SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
998 SymbolAssignment *Cmd = nullptr;
999 if (peek() == "=" || peek() == "+=") {
1000 Cmd = readAssignment(Tok);
1001 expect(";");
1002 } else if (Tok == "PROVIDE") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001003 Cmd = readProvideHidden(true, false);
1004 } else if (Tok == "HIDDEN") {
1005 Cmd = readProvideHidden(false, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001006 } else if (Tok == "PROVIDE_HIDDEN") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001007 Cmd = readProvideHidden(true, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001008 }
1009 return Cmd;
1010}
1011
George Rimar30835ea2016-07-28 21:08:56 +00001012static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
1013 if (S == ".")
1014 return Dot;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001015
George Rimara9c5a522016-07-26 18:18:58 +00001016 switch (Config->EKind) {
1017 case ELF32LEKind:
1018 if (SymbolBody *B = Symtab<ELF32LE>::X->find(S))
1019 return B->getVA<ELF32LE>();
1020 break;
1021 case ELF32BEKind:
1022 if (SymbolBody *B = Symtab<ELF32BE>::X->find(S))
1023 return B->getVA<ELF32BE>();
1024 break;
1025 case ELF64LEKind:
1026 if (SymbolBody *B = Symtab<ELF64LE>::X->find(S))
1027 return B->getVA<ELF64LE>();
1028 break;
1029 case ELF64BEKind:
1030 if (SymbolBody *B = Symtab<ELF64BE>::X->find(S))
1031 return B->getVA<ELF64BE>();
1032 break;
George Rimar6930a6d2016-07-26 18:41:06 +00001033 default:
George Rimarb567b622016-07-26 18:46:13 +00001034 llvm_unreachable("unsupported target");
George Rimara9c5a522016-07-26 18:18:58 +00001035 }
1036 error("symbol not found: " + S);
1037 return 0;
1038}
1039
George Rimar9e694502016-07-29 16:18:47 +00001040static uint64_t getSectionSize(StringRef Name) {
1041 switch (Config->EKind) {
1042 case ELF32LEKind:
1043 return Script<ELF32LE>::X->getOutputSectionSize(Name);
1044 case ELF32BEKind:
1045 return Script<ELF32BE>::X->getOutputSectionSize(Name);
1046 case ELF64LEKind:
1047 return Script<ELF64LE>::X->getOutputSectionSize(Name);
1048 case ELF64BEKind:
1049 return Script<ELF64BE>::X->getOutputSectionSize(Name);
1050 default:
1051 llvm_unreachable("unsupported target");
1052 }
George Rimar9e694502016-07-29 16:18:47 +00001053}
1054
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001055static uint64_t getHeaderSize() {
George Rimare32a3592016-08-10 07:59:34 +00001056 switch (Config->EKind) {
1057 case ELF32LEKind:
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001058 return Script<ELF32LE>::X->getHeaderSize();
George Rimare32a3592016-08-10 07:59:34 +00001059 case ELF32BEKind:
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001060 return Script<ELF32BE>::X->getHeaderSize();
George Rimare32a3592016-08-10 07:59:34 +00001061 case ELF64LEKind:
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001062 return Script<ELF64LE>::X->getHeaderSize();
George Rimare32a3592016-08-10 07:59:34 +00001063 case ELF64BEKind:
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001064 return Script<ELF64BE>::X->getHeaderSize();
George Rimare32a3592016-08-10 07:59:34 +00001065 default:
1066 llvm_unreachable("unsupported target");
1067 }
1068}
1069
George Rimar30835ea2016-07-28 21:08:56 +00001070SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1071 StringRef Op = next();
1072 assert(Op == "=" || Op == "+=");
1073 Expr E = readExpr();
1074 if (Op == "+=")
1075 E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
Rui Ueyama10416562016-08-04 02:03:27 +00001076 return new SymbolAssignment(Name, E);
George Rimar30835ea2016-07-28 21:08:56 +00001077}
1078
1079// This is an operator-precedence parser to parse a linker
1080// script expression.
1081Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
1082
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001083static Expr combine(StringRef Op, Expr L, Expr R) {
1084 if (Op == "*")
1085 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1086 if (Op == "/") {
1087 return [=](uint64_t Dot) -> uint64_t {
1088 uint64_t RHS = R(Dot);
1089 if (RHS == 0) {
1090 error("division by zero");
1091 return 0;
1092 }
1093 return L(Dot) / RHS;
1094 };
1095 }
1096 if (Op == "+")
1097 return [=](uint64_t Dot) { return L(Dot) + R(Dot); };
1098 if (Op == "-")
1099 return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
1100 if (Op == "<")
1101 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
1102 if (Op == ">")
1103 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
1104 if (Op == ">=")
1105 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
1106 if (Op == "<=")
1107 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
1108 if (Op == "==")
1109 return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
1110 if (Op == "!=")
1111 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
1112 if (Op == "&")
1113 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
1114 llvm_unreachable("invalid operator");
1115}
1116
Rui Ueyama708019c2016-07-24 18:19:40 +00001117// This is a part of the operator-precedence parser. This function
1118// assumes that the remaining token stream starts with an operator.
1119Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1120 while (!atEOF() && !Error) {
1121 // Read an operator and an expression.
1122 StringRef Op1 = peek();
1123 if (Op1 == "?")
1124 return readTernary(Lhs);
1125 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +00001126 break;
Rui Ueyama708019c2016-07-24 18:19:40 +00001127 next();
1128 Expr Rhs = readPrimary();
1129
1130 // Evaluate the remaining part of the expression first if the
1131 // next operator has greater precedence than the previous one.
1132 // For example, if we have read "+" and "3", and if the next
1133 // operator is "*", then we'll evaluate 3 * ... part first.
1134 while (!atEOF()) {
1135 StringRef Op2 = peek();
1136 if (precedence(Op2) <= precedence(Op1))
1137 break;
1138 Rhs = readExpr1(Rhs, precedence(Op2));
1139 }
1140
1141 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +00001142 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001143 return Lhs;
1144}
1145
1146uint64_t static getConstant(StringRef S) {
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001147 if (S == "COMMONPAGESIZE")
Rui Ueyama708019c2016-07-24 18:19:40 +00001148 return Target->PageSize;
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001149 if (S == "MAXPAGESIZE")
1150 return Target->MaxPageSize;
Rui Ueyama708019c2016-07-24 18:19:40 +00001151 error("unknown constant: " + S);
1152 return 0;
1153}
1154
1155Expr ScriptParser::readPrimary() {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001156 if (peek() == "(")
1157 return readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001158
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001159 StringRef Tok = next();
Rui Ueyama708019c2016-07-24 18:19:40 +00001160
1161 // Built-in functions are parsed here.
1162 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
George Rimareefa7582016-08-04 09:29:31 +00001163 if (Tok == "ASSERT")
1164 return readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001165 if (Tok == "ALIGN") {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001166 Expr E = readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001167 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1168 }
1169 if (Tok == "CONSTANT") {
1170 expect("(");
1171 StringRef Tok = next();
1172 expect(")");
1173 return [=](uint64_t Dot) { return getConstant(Tok); };
1174 }
Rafael Espindola54c145c2016-07-28 18:16:24 +00001175 if (Tok == "SEGMENT_START") {
1176 expect("(");
1177 next();
1178 expect(",");
1179 uint64_t Val;
1180 next().getAsInteger(0, Val);
1181 expect(")");
1182 return [=](uint64_t Dot) { return Val; };
1183 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001184 if (Tok == "DATA_SEGMENT_ALIGN") {
1185 expect("(");
1186 Expr E = readExpr();
1187 expect(",");
1188 readExpr();
1189 expect(")");
Rui Ueyamaf7791bb2016-07-26 19:34:10 +00001190 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001191 }
1192 if (Tok == "DATA_SEGMENT_END") {
1193 expect("(");
1194 expect(".");
1195 expect(")");
1196 return [](uint64_t Dot) { return Dot; };
1197 }
George Rimar276b4e62016-07-26 17:58:44 +00001198 // GNU linkers implements more complicated logic to handle
1199 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1200 // the next page boundary for simplicity.
1201 if (Tok == "DATA_SEGMENT_RELRO_END") {
1202 expect("(");
1203 next();
1204 expect(",");
1205 readExpr();
1206 expect(")");
1207 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1208 }
George Rimar9e694502016-07-29 16:18:47 +00001209 if (Tok == "SIZEOF") {
1210 expect("(");
1211 StringRef Name = next();
1212 expect(")");
1213 return [=](uint64_t Dot) { return getSectionSize(Name); };
1214 }
George Rimare32a3592016-08-10 07:59:34 +00001215 if (Tok == "SIZEOF_HEADERS")
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001216 return [=](uint64_t Dot) { return getHeaderSize(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001217
George Rimara9c5a522016-07-26 18:18:58 +00001218 // Parse a symbol name or a number literal.
Rui Ueyama708019c2016-07-24 18:19:40 +00001219 uint64_t V = 0;
George Rimara9c5a522016-07-26 18:18:58 +00001220 if (Tok.getAsInteger(0, V)) {
George Rimar30835ea2016-07-28 21:08:56 +00001221 if (Tok != "." && !isValidCIdentifier(Tok))
George Rimara9c5a522016-07-26 18:18:58 +00001222 setError("malformed number: " + Tok);
George Rimar30835ea2016-07-28 21:08:56 +00001223 return [=](uint64_t Dot) { return getSymbolValue(Tok, Dot); };
George Rimara9c5a522016-07-26 18:18:58 +00001224 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001225 return [=](uint64_t Dot) { return V; };
1226}
1227
1228Expr ScriptParser::readTernary(Expr Cond) {
1229 next();
1230 Expr L = readExpr();
1231 expect(":");
1232 Expr R = readExpr();
1233 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1234}
1235
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001236Expr ScriptParser::readParenExpr() {
1237 expect("(");
1238 Expr E = readExpr();
1239 expect(")");
1240 return E;
1241}
1242
Eugene Leviantbbe38602016-07-19 09:25:43 +00001243std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1244 std::vector<StringRef> Phdrs;
1245 while (!Error && peek().startswith(":")) {
1246 StringRef Tok = next();
1247 Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
1248 if (Tok.empty()) {
1249 setError("section header name is empty");
1250 break;
1251 }
Rui Ueyama047404f2016-07-20 19:36:36 +00001252 Phdrs.push_back(Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001253 }
1254 return Phdrs;
1255}
1256
1257unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001258 StringRef Tok = next();
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001259 unsigned Ret = StringSwitch<unsigned>(Tok)
1260 .Case("PT_NULL", PT_NULL)
1261 .Case("PT_LOAD", PT_LOAD)
1262 .Case("PT_DYNAMIC", PT_DYNAMIC)
1263 .Case("PT_INTERP", PT_INTERP)
1264 .Case("PT_NOTE", PT_NOTE)
1265 .Case("PT_SHLIB", PT_SHLIB)
1266 .Case("PT_PHDR", PT_PHDR)
1267 .Case("PT_TLS", PT_TLS)
1268 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1269 .Case("PT_GNU_STACK", PT_GNU_STACK)
1270 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1271 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001272
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001273 if (Ret == (unsigned)-1) {
1274 setError("invalid program header type: " + Tok);
1275 return PT_NULL;
1276 }
1277 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001278}
1279
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001280static bool isUnderSysroot(StringRef Path) {
1281 if (Config->Sysroot == "")
1282 return false;
1283 for (; !Path.empty(); Path = sys::path::parent_path(Path))
1284 if (sys::fs::equivalent(Config->Sysroot, Path))
1285 return true;
1286 return false;
1287}
1288
Rui Ueyama07320e42016-04-20 20:13:41 +00001289// Entry point.
1290void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001291 StringRef Path = MB.getBufferIdentifier();
Rui Ueyama07320e42016-04-20 20:13:41 +00001292 ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001293}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001294
Rui Ueyama07320e42016-04-20 20:13:41 +00001295template class elf::LinkerScript<ELF32LE>;
1296template class elf::LinkerScript<ELF32BE>;
1297template class elf::LinkerScript<ELF64LE>;
1298template class elf::LinkerScript<ELF64BE>;