blob: ef8ccb9f315e5770daeff757ef7138103231ba4d [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
George Rimar884e7862016-09-08 08:19:13 +000044LinkerScriptBase *elf::ScriptBase;
Rui Ueyama07320e42016-04-20 20:13:41 +000045ScriptConfiguration *elf::ScriptConfig;
Rui Ueyama717677a2016-02-11 21:17:59 +000046
George Rimar6c55f0e2016-09-08 08:20:30 +000047template <class ELFT> static void addRegular(SymbolAssignment *Cmd) {
Rui Ueyama16024212016-08-11 23:22:52 +000048 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) {
George Rimare1937bb2016-08-19 15:36:32 +000054 Symbol *Sym = Symtab<ELFT>::X->addSynthetic(
55 Cmd->Name, nullptr, 0, Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT);
Rui Ueyama16024212016-08-11 23:22:52 +000056 Cmd->Sym = Sym->body();
Eugene Leviantceabe802016-08-11 07:56:43 +000057}
58
Eugene Leviantdb741e72016-09-07 07:08:43 +000059template <class ELFT> static void addSymbol(SymbolAssignment *Cmd) {
60 if (Cmd->IsAbsolute)
61 addRegular<ELFT>(Cmd);
62 else
63 addSynthetic<ELFT>(Cmd);
64}
Rui Ueyama16024212016-08-11 23:22:52 +000065// If a symbol was in PROVIDE(), we need to define it only when
66// it is an undefined symbol.
67template <class ELFT> static bool shouldDefine(SymbolAssignment *Cmd) {
68 if (Cmd->Name == ".")
Eugene Leviantceabe802016-08-11 07:56:43 +000069 return false;
Rui Ueyama16024212016-08-11 23:22:52 +000070 if (!Cmd->Provide)
71 return true;
72 SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
73 return B && B->isUndefined();
Eugene Leviantceabe802016-08-11 07:56:43 +000074}
75
George Rimar076fe152016-07-21 06:43:01 +000076bool SymbolAssignment::classof(const BaseCommand *C) {
77 return C->Kind == AssignmentKind;
78}
79
80bool OutputSectionCommand::classof(const BaseCommand *C) {
81 return C->Kind == OutputSectionKind;
82}
83
George Rimareea31142016-07-21 14:26:59 +000084bool InputSectionDescription::classof(const BaseCommand *C) {
85 return C->Kind == InputSectionKind;
86}
87
George Rimareefa7582016-08-04 09:29:31 +000088bool AssertCommand::classof(const BaseCommand *C) {
89 return C->Kind == AssertKind;
90}
91
Rui Ueyama36a153c2016-07-23 14:09:58 +000092template <class ELFT> static bool isDiscarded(InputSectionBase<ELFT> *S) {
George Rimareea31142016-07-21 14:26:59 +000093 return !S || !S->Live;
Rui Ueyama717677a2016-02-11 21:17:59 +000094}
95
Rui Ueyamaf34d0e02016-08-12 01:24:53 +000096template <class ELFT> LinkerScript<ELFT>::LinkerScript() {}
97template <class ELFT> LinkerScript<ELFT>::~LinkerScript() {}
98
Rui Ueyama07320e42016-04-20 20:13:41 +000099template <class ELFT>
100bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) {
George Rimarc91930a2016-09-02 21:17:20 +0000101 for (Regex *Re : Opt.KeptSections)
Rafael Espindola042a3f22016-09-08 14:06:08 +0000102 if (Re->match(S->Name))
George Rimareea31142016-07-21 14:26:59 +0000103 return true;
104 return false;
105}
106
George Rimar06598002016-07-28 21:51:30 +0000107static bool fileMatches(const InputSectionDescription *Desc,
108 StringRef Filename) {
George Rimarc91930a2016-09-02 21:17:20 +0000109 return const_cast<Regex &>(Desc->FileRe).match(Filename) &&
110 !const_cast<Regex &>(Desc->ExcludedFileRe).match(Filename);
George Rimar06598002016-07-28 21:51:30 +0000111}
112
Rui Ueyama6b274812016-07-25 22:51:07 +0000113// Returns input sections filtered by given glob patterns.
114template <class ELFT>
115std::vector<InputSectionBase<ELFT> *>
Rui Ueyamaad10c3d2016-07-28 21:05:04 +0000116LinkerScript<ELFT>::getInputSections(const InputSectionDescription *I) {
George Rimarc91930a2016-09-02 21:17:20 +0000117 const Regex &Re = I->SectionRe;
Rui Ueyama6b274812016-07-25 22:51:07 +0000118 std::vector<InputSectionBase<ELFT> *> Ret;
119 for (const std::unique_ptr<ObjectFile<ELFT>> &F :
George Rimar06598002016-07-28 21:51:30 +0000120 Symtab<ELFT>::X->getObjectFiles()) {
121 if (fileMatches(I, sys::path::filename(F->getName())))
122 for (InputSectionBase<ELFT> *S : F->getSections())
123 if (!isDiscarded(S) && !S->OutSec &&
Rafael Espindola042a3f22016-09-08 14:06:08 +0000124 const_cast<Regex &>(Re).match(S->Name))
Davide Italianoe7282792016-07-27 01:44:01 +0000125 Ret.push_back(S);
George Rimar06598002016-07-28 21:51:30 +0000126 }
Eugene Leviant3e6b0272016-07-28 19:24:13 +0000127
George Rimarc91930a2016-09-02 21:17:20 +0000128 if (const_cast<Regex &>(Re).match("COMMON"))
Rui Ueyamaad10c3d2016-07-28 21:05:04 +0000129 Ret.push_back(CommonInputSection<ELFT>::X);
Rui Ueyama6b274812016-07-25 22:51:07 +0000130 return Ret;
131}
132
Rafael Espindolac0028d32016-09-08 20:47:52 +0000133static bool compareName(InputSectionData *A, InputSectionData *B) {
Rafael Espindola042a3f22016-09-08 14:06:08 +0000134 return A->Name < B->Name;
Rui Ueyama742c3832016-08-04 22:27:00 +0000135}
George Rimar350ece42016-08-03 08:35:59 +0000136
Rafael Espindolac0028d32016-09-08 20:47:52 +0000137static bool compareAlignment(InputSectionData *A, InputSectionData *B) {
Rui Ueyama742c3832016-08-04 22:27:00 +0000138 // ">" is not a mistake. Larger alignments are placed before smaller
139 // alignments in order to reduce the amount of padding necessary.
140 // This is compatible with GNU.
141 return A->Alignment > B->Alignment;
142}
George Rimar350ece42016-08-03 08:35:59 +0000143
Rafael Espindolac0028d32016-09-08 20:47:52 +0000144static std::function<bool(InputSectionData *, InputSectionData *)>
Rui Ueyama742c3832016-08-04 22:27:00 +0000145getComparator(SortKind K) {
146 if (K == SortByName)
Rafael Espindolac0028d32016-09-08 20:47:52 +0000147 return compareName;
148 return compareAlignment;
Rui Ueyama742c3832016-08-04 22:27:00 +0000149}
George Rimar0702c4e2016-07-29 15:32:46 +0000150
151template <class ELFT>
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000152void LinkerScript<ELFT>::discard(OutputSectionCommand &Cmd) {
153 for (const std::unique_ptr<BaseCommand> &Base : Cmd.Commands) {
154 if (auto *Cmd = dyn_cast<InputSectionDescription>(Base.get())) {
155 for (InputSectionBase<ELFT> *S : getInputSections(Cmd)) {
156 S->Live = false;
157 reportDiscarded(S);
158 }
159 }
160 }
161}
162
George Rimar8f66df92016-08-12 20:38:20 +0000163static bool checkConstraint(uint64_t Flags, ConstraintKind Kind) {
164 bool RO = (Kind == ConstraintKind::ReadOnly);
165 bool RW = (Kind == ConstraintKind::ReadWrite);
166 bool Writable = Flags & SHF_WRITE;
Rui Ueyamaadcdb662016-09-06 22:50:48 +0000167 return !(RO && Writable) && !(RW && !Writable);
George Rimar8f66df92016-08-12 20:38:20 +0000168}
169
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000170template <class ELFT>
George Rimar06ae6832016-08-12 09:07:57 +0000171static bool matchConstraints(ArrayRef<InputSectionBase<ELFT> *> Sections,
172 ConstraintKind Kind) {
George Rimar8f66df92016-08-12 20:38:20 +0000173 if (Kind == ConstraintKind::NoConstraint)
174 return true;
175 return llvm::all_of(Sections, [=](InputSectionBase<ELFT> *Sec) {
176 return checkConstraint(Sec->getSectionHdr()->sh_flags, Kind);
George Rimar06ae6832016-08-12 09:07:57 +0000177 });
178}
179
180template <class ELFT>
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000181std::vector<InputSectionBase<ELFT> *>
George Rimar06ae6832016-08-12 09:07:57 +0000182LinkerScript<ELFT>::createInputSectionList(OutputSectionCommand &OutCmd) {
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000183 std::vector<InputSectionBase<ELFT> *> Ret;
Eugene Leviant97403d12016-09-01 09:55:57 +0000184 DenseSet<InputSectionBase<ELFT> *> SectionIndex;
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000185
George Rimar06ae6832016-08-12 09:07:57 +0000186 for (const std::unique_ptr<BaseCommand> &Base : OutCmd.Commands) {
187 if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base.get())) {
188 if (shouldDefine<ELFT>(OutCmd))
Eugene Leviantdb741e72016-09-07 07:08:43 +0000189 addSymbol<ELFT>(OutCmd);
Eugene Leviant97403d12016-09-01 09:55:57 +0000190 OutCmd->GoesAfter = Ret.empty() ? nullptr : Ret.back();
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000191 continue;
192 }
193
194 auto *Cmd = cast<InputSectionDescription>(Base.get());
195 std::vector<InputSectionBase<ELFT> *> V = getInputSections(Cmd);
George Rimar06ae6832016-08-12 09:07:57 +0000196 if (!matchConstraints<ELFT>(V, OutCmd.Constraint))
197 continue;
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000198 if (Cmd->SortInner)
Rafael Espindolac0028d32016-09-08 20:47:52 +0000199 std::stable_sort(V.begin(), V.end(), getComparator(Cmd->SortInner));
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000200 if (Cmd->SortOuter)
Rafael Espindolac0028d32016-09-08 20:47:52 +0000201 std::stable_sort(V.begin(), V.end(), getComparator(Cmd->SortOuter));
Eugene Leviant97403d12016-09-01 09:55:57 +0000202
203 // Add all input sections corresponding to rule 'Cmd' to
204 // resulting vector. We do not add duplicate input sections.
205 for (InputSectionBase<ELFT> *S : V)
206 if (SectionIndex.insert(S).second)
207 Ret.push_back(S);
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000208 }
209 return Ret;
210}
211
George Rimar6c55f0e2016-09-08 08:20:30 +0000212template <class ELFT> void LinkerScript<ELFT>::createAssignments() {
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000213 for (const std::unique_ptr<SymbolAssignment> &Cmd : Opt.Assignments) {
214 if (shouldDefine<ELFT>(Cmd.get()))
215 addRegular<ELFT>(Cmd.get());
216 if (Cmd->Sym)
217 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(0);
218 }
219}
220
221template <class ELFT>
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000222void LinkerScript<ELFT>::createSections(OutputSectionFactory<ELFT> &Factory) {
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000223 for (const std::unique_ptr<BaseCommand> &Base1 : Opt.Commands) {
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000224 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base1.get())) {
225 if (shouldDefine<ELFT>(Cmd))
226 addRegular<ELFT>(Cmd);
227 continue;
228 }
229
Eugene Leviantceabe802016-08-11 07:56:43 +0000230 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000231 if (Cmd->Name == "/DISCARD/") {
232 discard(*Cmd);
233 continue;
234 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000235
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000236 std::vector<InputSectionBase<ELFT> *> V = createInputSectionList(*Cmd);
Eugene Leviant97403d12016-09-01 09:55:57 +0000237 if (V.empty())
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000238 continue;
239
George Rimardb24d9c2016-08-19 15:18:23 +0000240 for (InputSectionBase<ELFT> *Sec : V) {
George Rimara14b13d2016-09-07 10:46:07 +0000241 OutputSectionBase<ELFT> *OutSec;
242 bool IsNew;
243 std::tie(OutSec, IsNew) = Factory.create(Sec, Cmd->Name);
244 if (IsNew)
245 OutputSections->push_back(OutSec);
246
247 uint32_t Subalign = Cmd->SubalignExpr ? Cmd->SubalignExpr(0) : 0;
248
George Rimardb24d9c2016-08-19 15:18:23 +0000249 if (Subalign)
250 Sec->Alignment = Subalign;
Eugene Leviant97403d12016-09-01 09:55:57 +0000251 OutSec->addSection(Sec);
George Rimardb24d9c2016-08-19 15:18:23 +0000252 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000253 }
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000254 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000255
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000256 // Add orphan sections.
Rui Ueyama6b274812016-07-25 22:51:07 +0000257 for (const std::unique_ptr<ObjectFile<ELFT>> &F :
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000258 Symtab<ELFT>::X->getObjectFiles()) {
259 for (InputSectionBase<ELFT> *S : F->getSections()) {
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000260 if (isDiscarded(S) || S->OutSec)
261 continue;
262 OutputSectionBase<ELFT> *OutSec;
263 bool IsNew;
264 std::tie(OutSec, IsNew) = Factory.create(S, getOutputSectionName(S));
265 if (IsNew)
266 OutputSections->push_back(OutSec);
267 OutSec->addSection(S);
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000268 }
269 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000270}
271
Eugene Leviantdb741e72016-09-07 07:08:43 +0000272// Sets value of a section-defined symbol. Two kinds of
273// symbols are processed: synthetic symbols, whose value
274// is an offset from beginning of section and regular
275// symbols whose value is absolute.
276template <class ELFT>
277static void assignSectionSymbol(SymbolAssignment *Cmd,
278 OutputSectionBase<ELFT> *Sec,
279 typename ELFT::uint Off) {
280 if (!Cmd->Sym)
281 return;
282
283 if (auto *Body = dyn_cast<DefinedSynthetic<ELFT>>(Cmd->Sym)) {
284 Body->Section = Sec;
285 Body->Value = Cmd->Expression(Sec->getVA() + Off) - Sec->getVA();
286 return;
287 }
288 auto *Body = cast<DefinedRegular<ELFT>>(Cmd->Sym);
289 Body->Value = Cmd->Expression(Sec->getVA() + Off);
290}
291
Eugene Leviant20889c52016-08-31 08:13:33 +0000292// Linker script may define start and end symbols for special section types,
293// like .got, .eh_frame_hdr, .eh_frame and others. Those sections are not a list
294// of regular input input sections, therefore our way of defining symbols for
295// regular sections will not work. The approach we use for special section types
296// is not perfect - it handles only start and end symbols.
297template <class ELFT>
298void addStartEndSymbols(OutputSectionCommand *Cmd,
299 OutputSectionBase<ELFT> *Sec) {
300 bool Start = true;
301 BaseCommand *PrevCmd = nullptr;
302
303 for (std::unique_ptr<BaseCommand> &Base : Cmd->Commands) {
304 if (auto *AssignCmd = dyn_cast<SymbolAssignment>(Base.get())) {
Eugene Leviantdb741e72016-09-07 07:08:43 +0000305 assignSectionSymbol<ELFT>(AssignCmd, Sec, Start ? 0 : Sec->getSize());
Eugene Leviant20889c52016-08-31 08:13:33 +0000306 } else {
307 if (!Start && isa<SymbolAssignment>(PrevCmd))
308 error("section '" + Sec->getName() +
309 "' supports only start and end symbols");
310 Start = false;
311 }
312 PrevCmd = Base.get();
313 }
314}
315
316template <class ELFT>
317void assignOffsets(OutputSectionCommand *Cmd, OutputSectionBase<ELFT> *Sec) {
Eugene Leviantceabe802016-08-11 07:56:43 +0000318 auto *OutSec = dyn_cast<OutputSection<ELFT>>(Sec);
Rui Ueyama2de509c2016-08-12 00:55:08 +0000319 if (!OutSec) {
320 Sec->assignOffsets();
Eugene Leviant20889c52016-08-31 08:13:33 +0000321 // This section is not regular output section. However linker script may
322 // have defined start/end symbols for it. This case is handled below.
323 addStartEndSymbols(Cmd, Sec);
Eugene Leviantceabe802016-08-11 07:56:43 +0000324 return;
Rui Ueyama2de509c2016-08-12 00:55:08 +0000325 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000326 typedef typename ELFT::uint uintX_t;
327 uintX_t Off = 0;
Eugene Leviant97403d12016-09-01 09:55:57 +0000328 auto ItCmd = Cmd->Commands.begin();
Eugene Leviantceabe802016-08-11 07:56:43 +0000329
Eugene Leviant97403d12016-09-01 09:55:57 +0000330 // Assigns values to all symbols following the given
331 // input section 'D' in output section 'Sec'. When symbols
332 // are in the beginning of output section the value of 'D'
333 // is nullptr.
334 auto AssignSuccessors = [&](InputSectionData *D) {
335 for (; ItCmd != Cmd->Commands.end(); ++ItCmd) {
336 auto *AssignCmd = dyn_cast<SymbolAssignment>(ItCmd->get());
337 if (!AssignCmd)
338 continue;
339 if (D != AssignCmd->GoesAfter)
340 break;
341
Eugene Leviant97403d12016-09-01 09:55:57 +0000342 if (AssignCmd->Name == ".") {
343 // Update to location counter means update to section size.
Eugene Leviantdb741e72016-09-07 07:08:43 +0000344 Off = AssignCmd->Expression(Sec->getVA() + Off) - Sec->getVA();
Eugene Leviant97403d12016-09-01 09:55:57 +0000345 Sec->setSize(Off);
346 continue;
347 }
Eugene Leviantdb741e72016-09-07 07:08:43 +0000348 assignSectionSymbol<ELFT>(AssignCmd, Sec, Off);
Eugene Leviantceabe802016-08-11 07:56:43 +0000349 }
Eugene Leviant97403d12016-09-01 09:55:57 +0000350 };
351
352 AssignSuccessors(nullptr);
353 for (InputSection<ELFT> *I : OutSec->Sections) {
354 Off = alignTo(Off, I->Alignment);
355 I->OutSecOff = Off;
356 Off += I->getSize();
Rui Ueyamaf4a30a52016-08-11 21:30:42 +0000357 // Update section size inside for-loop, so that SIZEOF
Eugene Leviantceabe802016-08-11 07:56:43 +0000358 // works correctly in the case below:
359 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
360 Sec->setSize(Off);
Eugene Leviant97403d12016-09-01 09:55:57 +0000361 // Add symbols following current input section.
362 AssignSuccessors(I);
Eugene Leviantceabe802016-08-11 07:56:43 +0000363 }
364}
365
George Rimar8f66df92016-08-12 20:38:20 +0000366template <class ELFT>
George Rimara14b13d2016-09-07 10:46:07 +0000367static std::vector<OutputSectionBase<ELFT> *>
368findSections(OutputSectionCommand &Cmd,
369 ArrayRef<OutputSectionBase<ELFT> *> Sections) {
370 std::vector<OutputSectionBase<ELFT> *> Ret;
371 for (OutputSectionBase<ELFT> *Sec : Sections)
372 if (Sec->getName() == Cmd.Name &&
373 checkConstraint(Sec->getFlags(), Cmd.Constraint))
374 Ret.push_back(Sec);
375 return Ret;
George Rimar8f66df92016-08-12 20:38:20 +0000376}
377
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000378template <class ELFT> void LinkerScript<ELFT>::assignAddresses() {
George Rimar652852c2016-04-16 10:10:32 +0000379 // Orphan sections are sections present in the input files which
Rui Ueyama7c18c282016-04-18 21:00:40 +0000380 // are not explicitly placed into the output file by the linker script.
381 // We place orphan sections at end of file.
382 // Other linkers places them using some heuristics as described in
George Rimar652852c2016-04-16 10:10:32 +0000383 // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
Rui Ueyamae5cc6682016-08-12 00:36:56 +0000384 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
George Rimar652852c2016-04-16 10:10:32 +0000385 StringRef Name = Sec->getName();
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000386 if (getSectionIndex(Name) == INT_MAX)
George Rimar076fe152016-07-21 06:43:01 +0000387 Opt.Commands.push_back(llvm::make_unique<OutputSectionCommand>(Name));
George Rimar652852c2016-04-16 10:10:32 +0000388 }
George Rimar652852c2016-04-16 10:10:32 +0000389
Rui Ueyama7c18c282016-04-18 21:00:40 +0000390 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rui Ueyama4f7500b2016-08-12 04:00:22 +0000391 Dot = getHeaderSize();
Eugene Leviant467c4d52016-07-01 10:27:36 +0000392 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
George Rimar652852c2016-04-16 10:10:32 +0000393 uintX_t ThreadBssOffset = 0;
George Rimar652852c2016-04-16 10:10:32 +0000394
George Rimar076fe152016-07-21 06:43:01 +0000395 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
396 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
Rui Ueyama8d083e62016-07-29 05:48:39 +0000397 if (Cmd->Name == ".") {
398 Dot = Cmd->Expression(Dot);
399 } else if (Cmd->Sym) {
400 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(Dot);
401 }
George Rimar652852c2016-04-16 10:10:32 +0000402 continue;
403 }
404
George Rimareefa7582016-08-04 09:29:31 +0000405 if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
406 Cmd->Expression(Dot);
407 continue;
408 }
409
George Rimar076fe152016-07-21 06:43:01 +0000410 auto *Cmd = cast<OutputSectionCommand>(Base.get());
George Rimara14b13d2016-09-07 10:46:07 +0000411 for (OutputSectionBase<ELFT> *Sec :
412 findSections<ELFT>(*Cmd, *OutputSections)) {
George Rimar652852c2016-04-16 10:10:32 +0000413
George Rimara14b13d2016-09-07 10:46:07 +0000414 if (Cmd->AddrExpr)
415 Dot = Cmd->AddrExpr(Dot);
George Rimar58e5c4d2016-07-25 08:29:46 +0000416
George Rimara14b13d2016-09-07 10:46:07 +0000417 if (Cmd->AlignExpr)
418 Sec->updateAlignment(Cmd->AlignExpr(Dot));
George Rimar630c6172016-07-26 18:06:29 +0000419
George Rimara14b13d2016-09-07 10:46:07 +0000420 if ((Sec->getFlags() & SHF_TLS) && Sec->getType() == SHT_NOBITS) {
421 uintX_t TVA = Dot + ThreadBssOffset;
422 TVA = alignTo(TVA, Sec->getAlignment());
423 Sec->setVA(TVA);
424 assignOffsets(Cmd, Sec);
425 ThreadBssOffset = TVA - Dot + Sec->getSize();
426 continue;
427 }
428
429 if (!(Sec->getFlags() & SHF_ALLOC)) {
430 assignOffsets(Cmd, Sec);
431 continue;
432 }
433
434 Dot = alignTo(Dot, Sec->getAlignment());
435 Sec->setVA(Dot);
Eugene Leviant20889c52016-08-31 08:13:33 +0000436 assignOffsets(Cmd, Sec);
George Rimara14b13d2016-09-07 10:46:07 +0000437 MinVA = std::min(MinVA, Dot);
438 Dot += Sec->getSize();
George Rimar652852c2016-04-16 10:10:32 +0000439 }
440 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000441
Rafael Espindola64c32d62016-07-07 14:28:47 +0000442 // ELF and Program headers need to be right before the first section in
George Rimarb91e7112016-07-19 07:42:07 +0000443 // memory. Set their addresses accordingly.
Eugene Leviant467c4d52016-07-01 10:27:36 +0000444 MinVA = alignDown(MinVA - Out<ELFT>::ElfHeader->getSize() -
445 Out<ELFT>::ProgramHeaders->getSize(),
446 Target->PageSize);
447 Out<ELFT>::ElfHeader->setVA(MinVA);
448 Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
George Rimar652852c2016-04-16 10:10:32 +0000449}
450
Rui Ueyama464daad2016-08-22 04:55:20 +0000451// Creates program headers as instructed by PHDRS linker script command.
Rui Ueyama07320e42016-04-20 20:13:41 +0000452template <class ELFT>
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000453std::vector<PhdrEntry<ELFT>> LinkerScript<ELFT>::createPhdrs() {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000454 std::vector<PhdrEntry<ELFT>> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000455
Rui Ueyama464daad2016-08-22 04:55:20 +0000456 // Process PHDRS and FILEHDR keywords because they are not
457 // real output sections and cannot be added in the following loop.
Eugene Leviantbbe38602016-07-19 09:25:43 +0000458 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000459 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
460 PhdrEntry<ELFT> &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000461
462 if (Cmd.HasFilehdr)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000463 Phdr.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000464 if (Cmd.HasPhdrs)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000465 Phdr.add(Out<ELFT>::ProgramHeaders);
Eugene Leviant56b21c82016-09-09 09:46:16 +0000466
467 if (Cmd.LMAExpr) {
468 Phdr.H.p_paddr = Cmd.LMAExpr(0);
469 Phdr.HasLMA = true;
470 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000471 }
472
Rui Ueyama464daad2016-08-22 04:55:20 +0000473 // Add output sections to program headers.
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000474 PhdrEntry<ELFT> *Load = nullptr;
475 uintX_t Flags = PF_R;
Rui Ueyama464daad2016-08-22 04:55:20 +0000476 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
Eugene Leviantbbe38602016-07-19 09:25:43 +0000477 if (!(Sec->getFlags() & SHF_ALLOC))
478 break;
479
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000480 std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName());
Eugene Leviantbbe38602016-07-19 09:25:43 +0000481 if (!PhdrIds.empty()) {
482 // Assign headers specified by linker script
483 for (size_t Id : PhdrIds) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000484 Ret[Id].add(Sec);
Eugene Leviant865bf862016-07-21 10:43:25 +0000485 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
Rafael Espindola0b113672016-07-27 14:10:56 +0000486 Ret[Id].H.p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000487 }
488 } else {
489 // If we have no load segment or flags've changed then we want new load
490 // segment.
Rafael Espindola0b113672016-07-27 14:10:56 +0000491 uintX_t NewFlags = Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000492 if (Load == nullptr || Flags != NewFlags) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000493 Load = &*Ret.emplace(Ret.end(), PT_LOAD, NewFlags);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000494 Flags = NewFlags;
495 }
Rui Ueyama18f084f2016-07-20 19:36:41 +0000496 Load->add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000497 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000498 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000499 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000500}
501
Eugene Leviantf9bc3bd2016-08-16 06:40:58 +0000502template <class ELFT> bool LinkerScript<ELFT>::ignoreInterpSection() {
503 // Ignore .interp section in case we have PHDRS specification
504 // and PT_INTERP isn't listed.
505 return !Opt.PhdrsCommands.empty() &&
506 llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
507 return Cmd.Type == PT_INTERP;
508 }) == Opt.PhdrsCommands.end();
509}
510
Eugene Leviantbbe38602016-07-19 09:25:43 +0000511template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000512ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000513 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
514 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
515 if (Cmd->Name == Name)
516 return Cmd->Filler;
517 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000518}
519
George Rimar206fffa2016-08-17 08:16:57 +0000520template <class ELFT> Expr LinkerScript<ELFT>::getLma(StringRef Name) {
George Rimar8ceadb32016-08-17 07:44:19 +0000521 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
522 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
523 if (Cmd->LmaExpr && Cmd->Name == Name)
524 return Cmd->LmaExpr;
525 return {};
526}
527
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000528// Returns the index of the given section name in linker script
529// SECTIONS commands. Sections are laid out as the same order as they
530// were in the script. If a given name did not appear in the script,
531// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000532template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000533 int I = 0;
534 for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
535 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
536 if (Cmd->Name == Name)
537 return I;
538 ++I;
539 }
540 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000541}
542
543// A compartor to sort output sections. Returns -1 or 1 if
544// A or B are mentioned in linker script. Otherwise, returns 0.
Rui Ueyama07320e42016-04-20 20:13:41 +0000545template <class ELFT>
546int LinkerScript<ELFT>::compareSections(StringRef A, StringRef B) {
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000547 int I = getSectionIndex(A);
548 int J = getSectionIndex(B);
549 if (I == INT_MAX && J == INT_MAX)
Rui Ueyama717677a2016-02-11 21:17:59 +0000550 return 0;
551 return I < J ? -1 : 1;
552}
553
Eugene Leviantbbe38602016-07-19 09:25:43 +0000554template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
555 return !Opt.PhdrsCommands.empty();
556}
557
George Rimar9e694502016-07-29 16:18:47 +0000558template <class ELFT>
George Rimar884e7862016-09-08 08:19:13 +0000559uint64_t LinkerScript<ELFT>::getOutputSectionAddress(StringRef Name) {
George Rimar96659df2016-08-30 09:54:01 +0000560 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
561 if (Sec->getName() == Name)
562 return Sec->getVA();
563 error("undefined section " + Name);
564 return 0;
565}
566
567template <class ELFT>
George Rimar884e7862016-09-08 08:19:13 +0000568uint64_t LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
George Rimar9e694502016-07-29 16:18:47 +0000569 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
570 if (Sec->getName() == Name)
571 return Sec->getSize();
572 error("undefined section " + Name);
573 return 0;
574}
575
Eugene Leviant36fac7f2016-09-08 09:08:30 +0000576template <class ELFT>
577uint64_t LinkerScript<ELFT>::getOutputSectionAlign(StringRef Name) {
578 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
579 if (Sec->getName() == Name)
580 return Sec->getAlignment();
581 error("undefined section " + Name);
582 return 0;
583}
584
George Rimar884e7862016-09-08 08:19:13 +0000585template <class ELFT> uint64_t LinkerScript<ELFT>::getHeaderSize() {
George Rimare32a3592016-08-10 07:59:34 +0000586 return Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
587}
588
George Rimar884e7862016-09-08 08:19:13 +0000589template <class ELFT> uint64_t LinkerScript<ELFT>::getSymbolValue(StringRef S) {
590 if (SymbolBody *B = Symtab<ELFT>::X->find(S))
591 return B->getVA<ELFT>();
592 error("symbol not found: " + S);
593 return 0;
594}
595
Eugene Leviantbbe38602016-07-19 09:25:43 +0000596// Returns indices of ELF headers containing specific section, identified
597// by Name. Each index is a zero based number of ELF header listed within
598// PHDRS {} script block.
599template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000600std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000601 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
602 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000603 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000604 continue;
605
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000606 std::vector<size_t> Ret;
607 for (StringRef PhdrName : Cmd->Phdrs)
608 Ret.push_back(getPhdrIndex(PhdrName));
609 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000610 }
George Rimar31d842f2016-07-20 16:43:03 +0000611 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000612}
613
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000614template <class ELFT>
615size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
616 size_t I = 0;
617 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
618 if (Cmd.Name == PhdrName)
619 return I;
620 ++I;
621 }
622 error("section header '" + PhdrName + "' is not listed in PHDRS");
623 return 0;
624}
625
Rui Ueyama07320e42016-04-20 20:13:41 +0000626class elf::ScriptParser : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000627 typedef void (ScriptParser::*Handler)();
628
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000629public:
Rui Ueyama07320e42016-04-20 20:13:41 +0000630 ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
George Rimarf23b2322016-02-19 10:45:45 +0000631
George Rimar20b65982016-08-31 09:08:26 +0000632 void readLinkerScript();
633 void readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000634
635private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000636 void addFile(StringRef Path);
637
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000638 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000639 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000640 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000641 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000642 void readInclude();
Rui Ueyamaee592822015-10-07 00:25:09 +0000643 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000644 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000645 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000646 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000647 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000648 void readSections();
Rui Ueyama95769b42016-08-31 20:03:54 +0000649 void readVersion();
650 void readVersionScriptCommand();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000651
Rui Ueyama113cdec2016-07-24 23:05:57 +0000652 SymbolAssignment *readAssignment(StringRef Name);
George Rimarff1f29e2016-09-06 13:51:57 +0000653 std::vector<uint8_t> readFill();
Rui Ueyama10416562016-08-04 02:03:27 +0000654 OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
George Rimarff1f29e2016-09-06 13:51:57 +0000655 std::vector<uint8_t> readOutputSectionFiller(StringRef Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000656 std::vector<StringRef> readOutputSectionPhdrs();
George Rimara2496cb2016-08-30 09:46:59 +0000657 InputSectionDescription *readInputSectionDescription(StringRef Tok);
George Rimarc91930a2016-09-02 21:17:20 +0000658 Regex readFilePatterns();
George Rimara2496cb2016-08-30 09:46:59 +0000659 InputSectionDescription *readInputSectionRules(StringRef FilePattern);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000660 unsigned readPhdrType();
Rui Ueyama742c3832016-08-04 22:27:00 +0000661 SortKind readSortKind();
Petr Hoseka35e39c2016-08-16 01:11:16 +0000662 SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
Eugene Leviantdb741e72016-09-07 07:08:43 +0000663 SymbolAssignment *readProvideOrAssignment(StringRef Tok, bool MakeAbsolute);
George Rimar03fc0102016-07-28 07:18:23 +0000664 void readSort();
George Rimareefa7582016-08-04 09:29:31 +0000665 Expr readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +0000666
667 Expr readExpr();
668 Expr readExpr1(Expr Lhs, int MinPrec);
669 Expr readPrimary();
670 Expr readTernary(Expr Cond);
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +0000671 Expr readParenExpr();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000672
George Rimar20b65982016-08-31 09:08:26 +0000673 // For parsing version script.
674 void readExtern(std::vector<SymbolVersion> *Globals);
Rui Ueyama95769b42016-08-31 20:03:54 +0000675 void readVersionDeclaration(StringRef VerStr);
George Rimar20b65982016-08-31 09:08:26 +0000676 void readGlobal(StringRef VerStr);
677 void readLocal();
678
Rui Ueyama07320e42016-04-20 20:13:41 +0000679 ScriptConfiguration &Opt = *ScriptConfig;
680 StringSaver Saver = {ScriptConfig->Alloc};
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000681 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000682};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000683
George Rimar20b65982016-08-31 09:08:26 +0000684void ScriptParser::readVersionScript() {
Rui Ueyama95769b42016-08-31 20:03:54 +0000685 readVersionScriptCommand();
686 if (!atEOF())
687 setError("EOF expected, but got " + next());
688}
689
690void ScriptParser::readVersionScriptCommand() {
George Rimar20b65982016-08-31 09:08:26 +0000691 if (skip("{")) {
Rui Ueyama95769b42016-08-31 20:03:54 +0000692 readVersionDeclaration("");
George Rimar20b65982016-08-31 09:08:26 +0000693 return;
694 }
695
Rui Ueyama95769b42016-08-31 20:03:54 +0000696 while (!atEOF() && !Error && peek() != "}") {
George Rimar20b65982016-08-31 09:08:26 +0000697 StringRef VerStr = next();
698 if (VerStr == "{") {
Rui Ueyama95769b42016-08-31 20:03:54 +0000699 setError("anonymous version definition is used in "
700 "combination with other version definitions");
George Rimar20b65982016-08-31 09:08:26 +0000701 return;
702 }
703 expect("{");
Rui Ueyama95769b42016-08-31 20:03:54 +0000704 readVersionDeclaration(VerStr);
George Rimar20b65982016-08-31 09:08:26 +0000705 }
706}
707
Rui Ueyama95769b42016-08-31 20:03:54 +0000708void ScriptParser::readVersion() {
709 expect("{");
710 readVersionScriptCommand();
711 expect("}");
712}
713
George Rimar20b65982016-08-31 09:08:26 +0000714void ScriptParser::readLinkerScript() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000715 while (!atEOF()) {
716 StringRef Tok = next();
Rui Ueyamaa27eecc2016-09-02 18:52:41 +0000717 if (Tok == ";")
718 continue;
719
720 if (Tok == "ENTRY") {
721 readEntry();
722 } else if (Tok == "EXTERN") {
723 readExtern();
724 } else if (Tok == "GROUP" || Tok == "INPUT") {
725 readGroup();
726 } else if (Tok == "INCLUDE") {
727 readInclude();
728 } else if (Tok == "OUTPUT") {
729 readOutput();
730 } else if (Tok == "OUTPUT_ARCH") {
731 readOutputArch();
732 } else if (Tok == "OUTPUT_FORMAT") {
733 readOutputFormat();
734 } else if (Tok == "PHDRS") {
735 readPhdrs();
736 } else if (Tok == "SEARCH_DIR") {
737 readSearchDir();
738 } else if (Tok == "SECTIONS") {
739 readSections();
740 } else if (Tok == "VERSION") {
741 readVersion();
Eugene Leviantdb741e72016-09-07 07:08:43 +0000742 } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok, true)) {
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000743 if (Opt.HasContents)
744 Opt.Commands.emplace_back(Cmd);
745 else
746 Opt.Assignments.emplace_back(Cmd);
747 } else {
George Rimar57610422016-03-11 14:43:02 +0000748 setError("unknown directive: " + Tok);
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000749 }
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000750 }
751}
752
Rui Ueyama717677a2016-02-11 21:17:59 +0000753void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000754 if (IsUnderSysroot && S.startswith("/")) {
755 SmallString<128> Path;
756 (Config->Sysroot + S).toStringRef(Path);
757 if (sys::fs::exists(Path)) {
758 Driver->addFile(Saver.save(Path.str()));
759 return;
760 }
761 }
762
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +0000763 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +0000764 Driver->addFile(S);
765 } else if (S.startswith("=")) {
766 if (Config->Sysroot.empty())
767 Driver->addFile(S.substr(1));
768 else
769 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
770 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +0000771 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +0000772 } else if (sys::fs::exists(S)) {
773 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +0000774 } else {
775 std::string Path = findFromSearchPaths(S);
776 if (Path.empty())
George Rimar777f9632016-03-12 08:31:34 +0000777 setError("unable to find " + S);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000778 else
779 Driver->addFile(Saver.save(Path));
Rui Ueyama52a15092015-10-11 03:28:42 +0000780 }
781}
782
Rui Ueyama717677a2016-02-11 21:17:59 +0000783void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000784 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +0000785 bool Orig = Config->AsNeeded;
786 Config->AsNeeded = true;
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000787 while (!Error && !skip(")"))
George Rimarcd574a52016-09-09 14:35:36 +0000788 addFile(unquote(next()));
Rui Ueyama35da9b62015-10-11 20:59:12 +0000789 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000790}
791
Rui Ueyama717677a2016-02-11 21:17:59 +0000792void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +0000793 // -e <symbol> takes predecence over ENTRY(<symbol>).
794 expect("(");
795 StringRef Tok = next();
796 if (Config->Entry.empty())
797 Config->Entry = Tok;
798 expect(")");
799}
800
Rui Ueyama717677a2016-02-11 21:17:59 +0000801void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +0000802 expect("(");
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000803 while (!Error && !skip(")"))
804 Config->Undefined.push_back(next());
George Rimar83f406c2015-10-19 17:35:12 +0000805}
806
Rui Ueyama717677a2016-02-11 21:17:59 +0000807void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000808 expect("(");
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000809 while (!Error && !skip(")")) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000810 StringRef Tok = next();
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000811 if (Tok == "AS_NEEDED")
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000812 readAsNeeded();
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000813 else
George Rimarcd574a52016-09-09 14:35:36 +0000814 addFile(unquote(Tok));
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000815 }
816}
817
Rui Ueyama717677a2016-02-11 21:17:59 +0000818void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000819 StringRef Tok = next();
George Rimarcd574a52016-09-09 14:35:36 +0000820 auto MBOrErr = MemoryBuffer::getFile(unquote(Tok));
Rui Ueyama025d59b2016-02-02 20:27:59 +0000821 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +0000822 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000823 return;
824 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000825 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Rui Ueyamaa47ee682015-10-11 01:53:04 +0000826 StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
827 std::vector<StringRef> V = tokenize(S);
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000828 Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000829}
830
Rui Ueyama717677a2016-02-11 21:17:59 +0000831void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +0000832 // -o <file> takes predecence over OUTPUT(<file>).
833 expect("(");
834 StringRef Tok = next();
835 if (Config->OutputFile.empty())
George Rimarcd574a52016-09-09 14:35:36 +0000836 Config->OutputFile = unquote(Tok);
Rui Ueyamaee592822015-10-07 00:25:09 +0000837 expect(")");
838}
839
Rui Ueyama717677a2016-02-11 21:17:59 +0000840void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +0000841 // Error checking only for now.
842 expect("(");
843 next();
844 expect(")");
845}
846
Rui Ueyama717677a2016-02-11 21:17:59 +0000847void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000848 // Error checking only for now.
849 expect("(");
850 next();
Davide Italiano6836c612015-10-12 21:08:41 +0000851 StringRef Tok = next();
852 if (Tok == ")")
George Rimar6c55f0e2016-09-08 08:20:30 +0000853 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000854 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +0000855 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000856 return;
857 }
Davide Italiano6836c612015-10-12 21:08:41 +0000858 next();
859 expect(",");
860 next();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000861 expect(")");
862}
863
Eugene Leviantbbe38602016-07-19 09:25:43 +0000864void ScriptParser::readPhdrs() {
865 expect("{");
866 while (!Error && !skip("}")) {
867 StringRef Tok = next();
Eugene Leviant56b21c82016-09-09 09:46:16 +0000868 Opt.PhdrsCommands.push_back(
869 {Tok, PT_NULL, false, false, UINT_MAX, nullptr});
Eugene Leviantbbe38602016-07-19 09:25:43 +0000870 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
871
872 PhdrCmd.Type = readPhdrType();
873 do {
874 Tok = next();
875 if (Tok == ";")
876 break;
877 if (Tok == "FILEHDR")
878 PhdrCmd.HasFilehdr = true;
879 else if (Tok == "PHDRS")
880 PhdrCmd.HasPhdrs = true;
Eugene Leviant56b21c82016-09-09 09:46:16 +0000881 else if (Tok == "AT")
882 PhdrCmd.LMAExpr = readParenExpr();
Eugene Leviant865bf862016-07-21 10:43:25 +0000883 else if (Tok == "FLAGS") {
884 expect("(");
Rafael Espindolaeb685cd2016-08-02 22:14:57 +0000885 // Passing 0 for the value of dot is a bit of a hack. It means that
886 // we accept expressions like ".|1".
887 PhdrCmd.Flags = readExpr()(0);
Eugene Leviant865bf862016-07-21 10:43:25 +0000888 expect(")");
889 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +0000890 setError("unexpected header attribute: " + Tok);
891 } while (!Error);
892 }
893}
894
Rui Ueyama717677a2016-02-11 21:17:59 +0000895void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +0000896 expect("(");
Rui Ueyama86c5fb82016-09-08 23:26:54 +0000897 StringRef Tok = next();
Rui Ueyama6c7ad132016-09-02 19:20:33 +0000898 if (!Config->Nostdlib)
George Rimarcd574a52016-09-09 14:35:36 +0000899 Config->SearchPaths.push_back(unquote(Tok));
Davide Italiano68a39a62015-10-08 17:51:41 +0000900 expect(")");
901}
902
Rui Ueyama717677a2016-02-11 21:17:59 +0000903void ScriptParser::readSections() {
Rui Ueyama3de0a332016-07-29 03:31:09 +0000904 Opt.HasContents = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000905 expect("{");
George Rimar652852c2016-04-16 10:10:32 +0000906 while (!Error && !skip("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +0000907 StringRef Tok = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +0000908 BaseCommand *Cmd = readProvideOrAssignment(Tok, true);
Eugene Leviantceabe802016-08-11 07:56:43 +0000909 if (!Cmd) {
910 if (Tok == "ASSERT")
911 Cmd = new AssertCommand(readAssert());
912 else
913 Cmd = readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +0000914 }
Rui Ueyama10416562016-08-04 02:03:27 +0000915 Opt.Commands.emplace_back(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000916 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000917}
918
Rui Ueyama708019c2016-07-24 18:19:40 +0000919static int precedence(StringRef Op) {
920 return StringSwitch<int>(Op)
921 .Case("*", 4)
922 .Case("/", 4)
923 .Case("+", 3)
924 .Case("-", 3)
925 .Case("<", 2)
926 .Case(">", 2)
927 .Case(">=", 2)
928 .Case("<=", 2)
929 .Case("==", 2)
930 .Case("!=", 2)
931 .Case("&", 1)
Rafael Espindolacc3dd622016-08-22 21:33:35 +0000932 .Case("|", 1)
Rui Ueyama708019c2016-07-24 18:19:40 +0000933 .Default(-1);
934}
935
George Rimarc91930a2016-09-02 21:17:20 +0000936Regex ScriptParser::readFilePatterns() {
Rui Ueyama10416562016-08-04 02:03:27 +0000937 std::vector<StringRef> V;
938 while (!Error && !skip(")"))
939 V.push_back(next());
George Rimarc91930a2016-09-02 21:17:20 +0000940 return compileGlobPatterns(V);
George Rimar0702c4e2016-07-29 15:32:46 +0000941}
942
Rui Ueyama742c3832016-08-04 22:27:00 +0000943SortKind ScriptParser::readSortKind() {
944 if (skip("SORT") || skip("SORT_BY_NAME"))
945 return SortByName;
946 if (skip("SORT_BY_ALIGNMENT"))
947 return SortByAlignment;
948 return SortNone;
949}
950
George Rimara2496cb2016-08-30 09:46:59 +0000951InputSectionDescription *
952ScriptParser::readInputSectionRules(StringRef FilePattern) {
George Rimarc91930a2016-09-02 21:17:20 +0000953 auto *Cmd = new InputSectionDescription(FilePattern);
Davide Italiano0ed42b02016-07-25 21:47:13 +0000954 expect("(");
Davide Italianoe7282792016-07-27 01:44:01 +0000955
Rui Ueyama742c3832016-08-04 22:27:00 +0000956 // Read EXCLUDE_FILE().
Davide Italianoe7282792016-07-27 01:44:01 +0000957 if (skip("EXCLUDE_FILE")) {
958 expect("(");
George Rimarc91930a2016-09-02 21:17:20 +0000959 Cmd->ExcludedFileRe = readFilePatterns();
Davide Italiano0ed42b02016-07-25 21:47:13 +0000960 }
George Rimar06598002016-07-28 21:51:30 +0000961
Rui Ueyama742c3832016-08-04 22:27:00 +0000962 // Read SORT().
963 if (SortKind K1 = readSortKind()) {
964 Cmd->SortOuter = K1;
George Rimar0702c4e2016-07-29 15:32:46 +0000965 expect("(");
Rui Ueyama742c3832016-08-04 22:27:00 +0000966 if (SortKind K2 = readSortKind()) {
967 Cmd->SortInner = K2;
George Rimar350ece42016-08-03 08:35:59 +0000968 expect("(");
George Rimarc91930a2016-09-02 21:17:20 +0000969 Cmd->SectionRe = readFilePatterns();
George Rimar350ece42016-08-03 08:35:59 +0000970 expect(")");
971 } else {
George Rimarc91930a2016-09-02 21:17:20 +0000972 Cmd->SectionRe = readFilePatterns();
George Rimar350ece42016-08-03 08:35:59 +0000973 }
George Rimar0702c4e2016-07-29 15:32:46 +0000974 expect(")");
Rui Ueyama10416562016-08-04 02:03:27 +0000975 return Cmd;
George Rimar06598002016-07-28 21:51:30 +0000976 }
George Rimar0702c4e2016-07-29 15:32:46 +0000977
George Rimarc91930a2016-09-02 21:17:20 +0000978 Cmd->SectionRe = readFilePatterns();
Rui Ueyama10416562016-08-04 02:03:27 +0000979 return Cmd;
Davide Italianoe7282792016-07-27 01:44:01 +0000980}
981
George Rimara2496cb2016-08-30 09:46:59 +0000982InputSectionDescription *
983ScriptParser::readInputSectionDescription(StringRef Tok) {
George Rimar06598002016-07-28 21:51:30 +0000984 // Input section wildcard can be surrounded by KEEP.
985 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
George Rimara2496cb2016-08-30 09:46:59 +0000986 if (Tok == "KEEP") {
George Rimar06598002016-07-28 21:51:30 +0000987 expect("(");
George Rimara2496cb2016-08-30 09:46:59 +0000988 StringRef FilePattern = next();
989 InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
George Rimar06598002016-07-28 21:51:30 +0000990 expect(")");
George Rimarc91930a2016-09-02 21:17:20 +0000991 Opt.KeptSections.push_back(&Cmd->SectionRe);
Rui Ueyama10416562016-08-04 02:03:27 +0000992 return Cmd;
George Rimar06598002016-07-28 21:51:30 +0000993 }
George Rimara2496cb2016-08-30 09:46:59 +0000994 return readInputSectionRules(Tok);
Davide Italiano0ed42b02016-07-25 21:47:13 +0000995}
996
George Rimar03fc0102016-07-28 07:18:23 +0000997void ScriptParser::readSort() {
998 expect("(");
999 expect("CONSTRUCTORS");
1000 expect(")");
1001}
1002
George Rimareefa7582016-08-04 09:29:31 +00001003Expr ScriptParser::readAssert() {
1004 expect("(");
1005 Expr E = readExpr();
1006 expect(",");
George Rimarcd574a52016-09-09 14:35:36 +00001007 StringRef Msg = unquote(next());
George Rimareefa7582016-08-04 09:29:31 +00001008 expect(")");
1009 return [=](uint64_t Dot) {
1010 uint64_t V = E(Dot);
1011 if (!V)
1012 error(Msg);
1013 return V;
1014 };
1015}
1016
Rui Ueyama25150e82016-09-06 17:46:43 +00001017// Reads a FILL(expr) command. We handle the FILL command as an
1018// alias for =fillexp section attribute, which is different from
1019// what GNU linkers do.
1020// https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
George Rimarff1f29e2016-09-06 13:51:57 +00001021std::vector<uint8_t> ScriptParser::readFill() {
1022 expect("(");
1023 std::vector<uint8_t> V = readOutputSectionFiller(next());
1024 expect(")");
1025 expect(";");
1026 return V;
1027}
1028
Rui Ueyama10416562016-08-04 02:03:27 +00001029OutputSectionCommand *
1030ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +00001031 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
George Rimar58e5c4d2016-07-25 08:29:46 +00001032
1033 // Read an address expression.
1034 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
1035 if (peek() != ":")
1036 Cmd->AddrExpr = readExpr();
1037
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001038 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +00001039
George Rimar8ceadb32016-08-17 07:44:19 +00001040 if (skip("AT"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001041 Cmd->LmaExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001042 if (skip("ALIGN"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001043 Cmd->AlignExpr = readParenExpr();
George Rimardb24d9c2016-08-19 15:18:23 +00001044 if (skip("SUBALIGN"))
1045 Cmd->SubalignExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001046
Davide Italiano246f6812016-07-22 03:36:24 +00001047 // Parse constraints.
1048 if (skip("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001049 Cmd->Constraint = ConstraintKind::ReadOnly;
Davide Italiano246f6812016-07-22 03:36:24 +00001050 if (skip("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001051 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001052 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001053
Rui Ueyama025d59b2016-02-02 20:27:59 +00001054 while (!Error && !skip("}")) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001055 StringRef Tok = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +00001056 if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok, false))
Eugene Leviantceabe802016-08-11 07:56:43 +00001057 Cmd->Commands.emplace_back(Assignment);
George Rimarff1f29e2016-09-06 13:51:57 +00001058 else if (Tok == "FILL")
1059 Cmd->Filler = readFill();
Eugene Leviantceabe802016-08-11 07:56:43 +00001060 else if (Tok == "SORT")
George Rimar03fc0102016-07-28 07:18:23 +00001061 readSort();
George Rimara2496cb2016-08-30 09:46:59 +00001062 else if (peek() == "(")
1063 Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
Eugene Leviantceabe802016-08-11 07:56:43 +00001064 else
1065 setError("unknown command " + Tok);
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001066 }
George Rimar076fe152016-07-21 06:43:01 +00001067 Cmd->Phdrs = readOutputSectionPhdrs();
George Rimarff1f29e2016-09-06 13:51:57 +00001068 if (peek().startswith("="))
1069 Cmd->Filler = readOutputSectionFiller(next().drop_front());
Rui Ueyama10416562016-08-04 02:03:27 +00001070 return Cmd;
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001071}
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001072
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001073// Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
1074// https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
1075//
1076// ld.gold is not fully compatible with ld.bfd. ld.bfd handles
1077// hexstrings as blobs of arbitrary sizes, while ld.gold handles them
1078// as 32-bit big-endian values. We will do the same as ld.gold does
1079// because it's simpler than what ld.bfd does.
George Rimarff1f29e2016-09-06 13:51:57 +00001080std::vector<uint8_t> ScriptParser::readOutputSectionFiller(StringRef Tok) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001081 uint32_t V;
George Rimarff1f29e2016-09-06 13:51:57 +00001082 if (Tok.getAsInteger(0, V)) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001083 setError("invalid filler expression: " + Tok);
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001084 return {};
George Rimare2ee72b2016-02-26 14:48:31 +00001085 }
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001086 return {uint8_t(V >> 24), uint8_t(V >> 16), uint8_t(V >> 8), uint8_t(V)};
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001087}
1088
Petr Hoseka35e39c2016-08-16 01:11:16 +00001089SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
Eugene Levianta31c91b2016-07-22 07:38:40 +00001090 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +00001091 SymbolAssignment *Cmd = readAssignment(next());
Petr Hoseka35e39c2016-08-16 01:11:16 +00001092 Cmd->Provide = Provide;
Rui Ueyama174e0a12016-07-29 00:29:25 +00001093 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001094 expect(")");
1095 expect(";");
Rui Ueyama10416562016-08-04 02:03:27 +00001096 return Cmd;
Eugene Levianteda81a12016-07-12 06:39:48 +00001097}
1098
Eugene Leviantdb741e72016-09-07 07:08:43 +00001099SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok,
1100 bool MakeAbsolute) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001101 SymbolAssignment *Cmd = nullptr;
1102 if (peek() == "=" || peek() == "+=") {
1103 Cmd = readAssignment(Tok);
1104 expect(";");
1105 } else if (Tok == "PROVIDE") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001106 Cmd = readProvideHidden(true, false);
1107 } else if (Tok == "HIDDEN") {
1108 Cmd = readProvideHidden(false, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001109 } else if (Tok == "PROVIDE_HIDDEN") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001110 Cmd = readProvideHidden(true, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001111 }
Eugene Leviantdb741e72016-09-07 07:08:43 +00001112 if (Cmd && MakeAbsolute)
1113 Cmd->IsAbsolute = true;
Eugene Leviantceabe802016-08-11 07:56:43 +00001114 return Cmd;
1115}
1116
George Rimar30835ea2016-07-28 21:08:56 +00001117static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
1118 if (S == ".")
1119 return Dot;
George Rimar884e7862016-09-08 08:19:13 +00001120 return ScriptBase->getSymbolValue(S);
George Rimare32a3592016-08-10 07:59:34 +00001121}
1122
George Rimar30835ea2016-07-28 21:08:56 +00001123SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1124 StringRef Op = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +00001125 bool IsAbsolute = false;
1126 Expr E;
George Rimar30835ea2016-07-28 21:08:56 +00001127 assert(Op == "=" || Op == "+=");
Eugene Leviantdb741e72016-09-07 07:08:43 +00001128 if (skip("ABSOLUTE")) {
1129 E = readParenExpr();
1130 IsAbsolute = true;
1131 } else {
1132 E = readExpr();
1133 }
George Rimar30835ea2016-07-28 21:08:56 +00001134 if (Op == "+=")
1135 E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
Eugene Leviantdb741e72016-09-07 07:08:43 +00001136 return new SymbolAssignment(Name, E, IsAbsolute);
George Rimar30835ea2016-07-28 21:08:56 +00001137}
1138
1139// This is an operator-precedence parser to parse a linker
1140// script expression.
1141Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
1142
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001143static Expr combine(StringRef Op, Expr L, Expr R) {
1144 if (Op == "*")
1145 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1146 if (Op == "/") {
1147 return [=](uint64_t Dot) -> uint64_t {
1148 uint64_t RHS = R(Dot);
1149 if (RHS == 0) {
1150 error("division by zero");
1151 return 0;
1152 }
1153 return L(Dot) / RHS;
1154 };
1155 }
1156 if (Op == "+")
1157 return [=](uint64_t Dot) { return L(Dot) + R(Dot); };
1158 if (Op == "-")
1159 return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
1160 if (Op == "<")
1161 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
1162 if (Op == ">")
1163 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
1164 if (Op == ">=")
1165 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
1166 if (Op == "<=")
1167 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
1168 if (Op == "==")
1169 return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
1170 if (Op == "!=")
1171 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
1172 if (Op == "&")
1173 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
Rafael Espindolacc3dd622016-08-22 21:33:35 +00001174 if (Op == "|")
1175 return [=](uint64_t Dot) { return L(Dot) | R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001176 llvm_unreachable("invalid operator");
1177}
1178
Rui Ueyama708019c2016-07-24 18:19:40 +00001179// This is a part of the operator-precedence parser. This function
1180// assumes that the remaining token stream starts with an operator.
1181Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1182 while (!atEOF() && !Error) {
1183 // Read an operator and an expression.
1184 StringRef Op1 = peek();
1185 if (Op1 == "?")
1186 return readTernary(Lhs);
1187 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +00001188 break;
Rui Ueyama708019c2016-07-24 18:19:40 +00001189 next();
1190 Expr Rhs = readPrimary();
1191
1192 // Evaluate the remaining part of the expression first if the
1193 // next operator has greater precedence than the previous one.
1194 // For example, if we have read "+" and "3", and if the next
1195 // operator is "*", then we'll evaluate 3 * ... part first.
1196 while (!atEOF()) {
1197 StringRef Op2 = peek();
1198 if (precedence(Op2) <= precedence(Op1))
1199 break;
1200 Rhs = readExpr1(Rhs, precedence(Op2));
1201 }
1202
1203 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +00001204 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001205 return Lhs;
1206}
1207
1208uint64_t static getConstant(StringRef S) {
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001209 if (S == "COMMONPAGESIZE")
Rui Ueyama708019c2016-07-24 18:19:40 +00001210 return Target->PageSize;
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001211 if (S == "MAXPAGESIZE")
1212 return Target->MaxPageSize;
Rui Ueyama708019c2016-07-24 18:19:40 +00001213 error("unknown constant: " + S);
1214 return 0;
1215}
1216
Rui Ueyama626e0b02016-09-02 18:19:00 +00001217// Parses Tok as an integer. Returns true if successful.
1218// It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1219// and decimal numbers. Decimal numbers may have "K" (kilo) or
1220// "M" (mega) prefixes.
George Rimar9f2f7ad2016-09-02 16:01:42 +00001221static bool readInteger(StringRef Tok, uint64_t &Result) {
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001222 if (Tok.startswith("-")) {
1223 if (!readInteger(Tok.substr(1), Result))
1224 return false;
1225 Result = -Result;
1226 return true;
1227 }
George Rimar9f2f7ad2016-09-02 16:01:42 +00001228 if (Tok.startswith_lower("0x"))
1229 return !Tok.substr(2).getAsInteger(16, Result);
1230 if (Tok.endswith_lower("H"))
1231 return !Tok.drop_back().getAsInteger(16, Result);
1232
1233 int Suffix = 1;
1234 if (Tok.endswith_lower("K")) {
1235 Suffix = 1024;
1236 Tok = Tok.drop_back();
1237 } else if (Tok.endswith_lower("M")) {
1238 Suffix = 1024 * 1024;
1239 Tok = Tok.drop_back();
1240 }
1241 if (Tok.getAsInteger(10, Result))
1242 return false;
1243 Result *= Suffix;
1244 return true;
1245}
1246
Rui Ueyama708019c2016-07-24 18:19:40 +00001247Expr ScriptParser::readPrimary() {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001248 if (peek() == "(")
1249 return readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001250
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001251 StringRef Tok = next();
Rui Ueyama708019c2016-07-24 18:19:40 +00001252
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001253 if (Tok == "~") {
1254 Expr E = readPrimary();
1255 return [=](uint64_t Dot) { return ~E(Dot); };
1256 }
1257 if (Tok == "-") {
1258 Expr E = readPrimary();
1259 return [=](uint64_t Dot) { return -E(Dot); };
1260 }
1261
Rui Ueyama708019c2016-07-24 18:19:40 +00001262 // Built-in functions are parsed here.
1263 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
George Rimar96659df2016-08-30 09:54:01 +00001264 if (Tok == "ADDR") {
1265 expect("(");
1266 StringRef Name = next();
1267 expect(")");
George Rimar884e7862016-09-08 08:19:13 +00001268 return
1269 [=](uint64_t Dot) { return ScriptBase->getOutputSectionAddress(Name); };
George Rimar96659df2016-08-30 09:54:01 +00001270 }
George Rimareefa7582016-08-04 09:29:31 +00001271 if (Tok == "ASSERT")
1272 return readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001273 if (Tok == "ALIGN") {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001274 Expr E = readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001275 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1276 }
1277 if (Tok == "CONSTANT") {
1278 expect("(");
1279 StringRef Tok = next();
1280 expect(")");
1281 return [=](uint64_t Dot) { return getConstant(Tok); };
1282 }
Rafael Espindola54c145c2016-07-28 18:16:24 +00001283 if (Tok == "SEGMENT_START") {
1284 expect("(");
1285 next();
1286 expect(",");
1287 uint64_t Val;
1288 next().getAsInteger(0, Val);
1289 expect(")");
1290 return [=](uint64_t Dot) { return Val; };
1291 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001292 if (Tok == "DATA_SEGMENT_ALIGN") {
1293 expect("(");
1294 Expr E = readExpr();
1295 expect(",");
1296 readExpr();
1297 expect(")");
Rui Ueyamaf7791bb2016-07-26 19:34:10 +00001298 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001299 }
1300 if (Tok == "DATA_SEGMENT_END") {
1301 expect("(");
1302 expect(".");
1303 expect(")");
1304 return [](uint64_t Dot) { return Dot; };
1305 }
George Rimar276b4e62016-07-26 17:58:44 +00001306 // GNU linkers implements more complicated logic to handle
1307 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1308 // the next page boundary for simplicity.
1309 if (Tok == "DATA_SEGMENT_RELRO_END") {
1310 expect("(");
1311 next();
1312 expect(",");
1313 readExpr();
1314 expect(")");
1315 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1316 }
George Rimar9e694502016-07-29 16:18:47 +00001317 if (Tok == "SIZEOF") {
1318 expect("(");
1319 StringRef Name = next();
1320 expect(")");
George Rimar884e7862016-09-08 08:19:13 +00001321 return [=](uint64_t Dot) { return ScriptBase->getOutputSectionSize(Name); };
George Rimar9e694502016-07-29 16:18:47 +00001322 }
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001323 if (Tok == "ALIGNOF") {
1324 expect("(");
1325 StringRef Name = next();
1326 expect(")");
1327 return
1328 [=](uint64_t Dot) { return ScriptBase->getOutputSectionAlign(Name); };
1329 }
George Rimare32a3592016-08-10 07:59:34 +00001330 if (Tok == "SIZEOF_HEADERS")
George Rimar884e7862016-09-08 08:19:13 +00001331 return [=](uint64_t Dot) { return ScriptBase->getHeaderSize(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001332
George Rimar9f2f7ad2016-09-02 16:01:42 +00001333 // Tok is a literal number.
1334 uint64_t V;
1335 if (readInteger(Tok, V))
1336 return [=](uint64_t Dot) { return V; };
1337
1338 // Tok is a symbol name.
1339 if (Tok != "." && !isValidCIdentifier(Tok))
1340 setError("malformed number: " + Tok);
1341 return [=](uint64_t Dot) { return getSymbolValue(Tok, Dot); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001342}
1343
1344Expr ScriptParser::readTernary(Expr Cond) {
1345 next();
1346 Expr L = readExpr();
1347 expect(":");
1348 Expr R = readExpr();
1349 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1350}
1351
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001352Expr ScriptParser::readParenExpr() {
1353 expect("(");
1354 Expr E = readExpr();
1355 expect(")");
1356 return E;
1357}
1358
Eugene Leviantbbe38602016-07-19 09:25:43 +00001359std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1360 std::vector<StringRef> Phdrs;
1361 while (!Error && peek().startswith(":")) {
1362 StringRef Tok = next();
1363 Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
1364 if (Tok.empty()) {
1365 setError("section header name is empty");
1366 break;
1367 }
Rui Ueyama047404f2016-07-20 19:36:36 +00001368 Phdrs.push_back(Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001369 }
1370 return Phdrs;
1371}
1372
1373unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001374 StringRef Tok = next();
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001375 unsigned Ret = StringSwitch<unsigned>(Tok)
George Rimar6c55f0e2016-09-08 08:20:30 +00001376 .Case("PT_NULL", PT_NULL)
1377 .Case("PT_LOAD", PT_LOAD)
1378 .Case("PT_DYNAMIC", PT_DYNAMIC)
1379 .Case("PT_INTERP", PT_INTERP)
1380 .Case("PT_NOTE", PT_NOTE)
1381 .Case("PT_SHLIB", PT_SHLIB)
1382 .Case("PT_PHDR", PT_PHDR)
1383 .Case("PT_TLS", PT_TLS)
1384 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1385 .Case("PT_GNU_STACK", PT_GNU_STACK)
1386 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1387 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001388
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001389 if (Ret == (unsigned)-1) {
1390 setError("invalid program header type: " + Tok);
1391 return PT_NULL;
1392 }
1393 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001394}
1395
Rui Ueyama95769b42016-08-31 20:03:54 +00001396void ScriptParser::readVersionDeclaration(StringRef VerStr) {
George Rimar20b65982016-08-31 09:08:26 +00001397 // Identifiers start at 2 because 0 and 1 are reserved
1398 // for VER_NDX_LOCAL and VER_NDX_GLOBAL constants.
1399 size_t VersionId = Config->VersionDefinitions.size() + 2;
1400 Config->VersionDefinitions.push_back({VerStr, VersionId});
1401
1402 if (skip("global:") || peek() != "local:")
1403 readGlobal(VerStr);
1404 if (skip("local:"))
1405 readLocal();
1406 expect("}");
1407
1408 // Each version may have a parent version. For example, "Ver2" defined as
1409 // "Ver2 { global: foo; local: *; } Ver1;" has "Ver1" as a parent. This
1410 // version hierarchy is, probably against your instinct, purely for human; the
1411 // runtime doesn't care about them at all. In LLD, we simply skip the token.
1412 if (!VerStr.empty() && peek() != ";")
1413 next();
1414 expect(";");
1415}
1416
1417void ScriptParser::readLocal() {
1418 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1419 expect("*");
1420 expect(";");
1421}
1422
1423void ScriptParser::readExtern(std::vector<SymbolVersion> *Globals) {
George Rimarcd574a52016-09-09 14:35:36 +00001424 expect("\"C++\"");
George Rimar20b65982016-08-31 09:08:26 +00001425 expect("{");
1426
1427 for (;;) {
1428 if (peek() == "}" || Error)
1429 break;
George Rimarcd574a52016-09-09 14:35:36 +00001430 bool HasWildcard = !peek().startswith("\"") && hasWildcard(peek());
1431 Globals->push_back({unquote(next()), true, HasWildcard});
George Rimar20b65982016-08-31 09:08:26 +00001432 expect(";");
1433 }
1434
1435 expect("}");
1436 expect(";");
1437}
1438
1439void ScriptParser::readGlobal(StringRef VerStr) {
1440 std::vector<SymbolVersion> *Globals;
1441 if (VerStr.empty())
1442 Globals = &Config->VersionScriptGlobals;
1443 else
1444 Globals = &Config->VersionDefinitions.back().Globals;
1445
1446 for (;;) {
1447 if (skip("extern"))
1448 readExtern(Globals);
1449
1450 StringRef Cur = peek();
1451 if (Cur == "}" || Cur == "local:" || Error)
1452 return;
1453 next();
George Rimarcd574a52016-09-09 14:35:36 +00001454 Globals->push_back({unquote(Cur), false, hasWildcard(Cur)});
George Rimar20b65982016-08-31 09:08:26 +00001455 expect(";");
1456 }
1457}
1458
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001459static bool isUnderSysroot(StringRef Path) {
1460 if (Config->Sysroot == "")
1461 return false;
1462 for (; !Path.empty(); Path = sys::path::parent_path(Path))
1463 if (sys::fs::equivalent(Config->Sysroot, Path))
1464 return true;
1465 return false;
1466}
1467
Rui Ueyama07320e42016-04-20 20:13:41 +00001468void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001469 StringRef Path = MB.getBufferIdentifier();
George Rimar20b65982016-08-31 09:08:26 +00001470 ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).readLinkerScript();
1471}
1472
1473void elf::readVersionScript(MemoryBufferRef MB) {
1474 ScriptParser(MB.getBuffer(), false).readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001475}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001476
Rui Ueyama07320e42016-04-20 20:13:41 +00001477template class elf::LinkerScript<ELF32LE>;
1478template class elf::LinkerScript<ELF32BE>;
1479template class elf::LinkerScript<ELF64LE>;
1480template class elf::LinkerScript<ELF64BE>;