blob: eeb6dc278be08c0b1e43113d09faef30c5229a46 [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 Leviantbbe38602016-07-19 09:25:43 +0000466 }
467
Rui Ueyama464daad2016-08-22 04:55:20 +0000468 // Add output sections to program headers.
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000469 PhdrEntry<ELFT> *Load = nullptr;
470 uintX_t Flags = PF_R;
Rui Ueyama464daad2016-08-22 04:55:20 +0000471 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
Eugene Leviantbbe38602016-07-19 09:25:43 +0000472 if (!(Sec->getFlags() & SHF_ALLOC))
473 break;
474
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000475 std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName());
Eugene Leviantbbe38602016-07-19 09:25:43 +0000476 if (!PhdrIds.empty()) {
477 // Assign headers specified by linker script
478 for (size_t Id : PhdrIds) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000479 Ret[Id].add(Sec);
Eugene Leviant865bf862016-07-21 10:43:25 +0000480 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
Rafael Espindola0b113672016-07-27 14:10:56 +0000481 Ret[Id].H.p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000482 }
483 } else {
484 // If we have no load segment or flags've changed then we want new load
485 // segment.
Rafael Espindola0b113672016-07-27 14:10:56 +0000486 uintX_t NewFlags = Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000487 if (Load == nullptr || Flags != NewFlags) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000488 Load = &*Ret.emplace(Ret.end(), PT_LOAD, NewFlags);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000489 Flags = NewFlags;
490 }
Rui Ueyama18f084f2016-07-20 19:36:41 +0000491 Load->add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000492 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000493 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000494 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000495}
496
Eugene Leviantf9bc3bd2016-08-16 06:40:58 +0000497template <class ELFT> bool LinkerScript<ELFT>::ignoreInterpSection() {
498 // Ignore .interp section in case we have PHDRS specification
499 // and PT_INTERP isn't listed.
500 return !Opt.PhdrsCommands.empty() &&
501 llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
502 return Cmd.Type == PT_INTERP;
503 }) == Opt.PhdrsCommands.end();
504}
505
Eugene Leviantbbe38602016-07-19 09:25:43 +0000506template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000507ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000508 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
509 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
510 if (Cmd->Name == Name)
511 return Cmd->Filler;
512 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000513}
514
George Rimar206fffa2016-08-17 08:16:57 +0000515template <class ELFT> Expr LinkerScript<ELFT>::getLma(StringRef Name) {
George Rimar8ceadb32016-08-17 07:44:19 +0000516 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
517 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
518 if (Cmd->LmaExpr && Cmd->Name == Name)
519 return Cmd->LmaExpr;
520 return {};
521}
522
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000523// Returns the index of the given section name in linker script
524// SECTIONS commands. Sections are laid out as the same order as they
525// were in the script. If a given name did not appear in the script,
526// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000527template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000528 int I = 0;
529 for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
530 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
531 if (Cmd->Name == Name)
532 return I;
533 ++I;
534 }
535 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000536}
537
538// A compartor to sort output sections. Returns -1 or 1 if
539// A or B are mentioned in linker script. Otherwise, returns 0.
Rui Ueyama07320e42016-04-20 20:13:41 +0000540template <class ELFT>
541int LinkerScript<ELFT>::compareSections(StringRef A, StringRef B) {
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000542 int I = getSectionIndex(A);
543 int J = getSectionIndex(B);
544 if (I == INT_MAX && J == INT_MAX)
Rui Ueyama717677a2016-02-11 21:17:59 +0000545 return 0;
546 return I < J ? -1 : 1;
547}
548
Eugene Leviantbbe38602016-07-19 09:25:43 +0000549template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
550 return !Opt.PhdrsCommands.empty();
551}
552
George Rimar9e694502016-07-29 16:18:47 +0000553template <class ELFT>
George Rimar884e7862016-09-08 08:19:13 +0000554uint64_t LinkerScript<ELFT>::getOutputSectionAddress(StringRef Name) {
George Rimar96659df2016-08-30 09:54:01 +0000555 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
556 if (Sec->getName() == Name)
557 return Sec->getVA();
558 error("undefined section " + Name);
559 return 0;
560}
561
562template <class ELFT>
George Rimar884e7862016-09-08 08:19:13 +0000563uint64_t LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
George Rimar9e694502016-07-29 16:18:47 +0000564 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
565 if (Sec->getName() == Name)
566 return Sec->getSize();
567 error("undefined section " + Name);
568 return 0;
569}
570
Eugene Leviant36fac7f2016-09-08 09:08:30 +0000571template <class ELFT>
572uint64_t LinkerScript<ELFT>::getOutputSectionAlign(StringRef Name) {
573 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
574 if (Sec->getName() == Name)
575 return Sec->getAlignment();
576 error("undefined section " + Name);
577 return 0;
578}
579
George Rimar884e7862016-09-08 08:19:13 +0000580template <class ELFT> uint64_t LinkerScript<ELFT>::getHeaderSize() {
George Rimare32a3592016-08-10 07:59:34 +0000581 return Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
582}
583
George Rimar884e7862016-09-08 08:19:13 +0000584template <class ELFT> uint64_t LinkerScript<ELFT>::getSymbolValue(StringRef S) {
585 if (SymbolBody *B = Symtab<ELFT>::X->find(S))
586 return B->getVA<ELFT>();
587 error("symbol not found: " + S);
588 return 0;
589}
590
Eugene Leviantbbe38602016-07-19 09:25:43 +0000591// Returns indices of ELF headers containing specific section, identified
592// by Name. Each index is a zero based number of ELF header listed within
593// PHDRS {} script block.
594template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000595std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000596 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
597 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000598 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000599 continue;
600
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000601 std::vector<size_t> Ret;
602 for (StringRef PhdrName : Cmd->Phdrs)
603 Ret.push_back(getPhdrIndex(PhdrName));
604 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000605 }
George Rimar31d842f2016-07-20 16:43:03 +0000606 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000607}
608
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000609template <class ELFT>
610size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
611 size_t I = 0;
612 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
613 if (Cmd.Name == PhdrName)
614 return I;
615 ++I;
616 }
617 error("section header '" + PhdrName + "' is not listed in PHDRS");
618 return 0;
619}
620
Rui Ueyama07320e42016-04-20 20:13:41 +0000621class elf::ScriptParser : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000622 typedef void (ScriptParser::*Handler)();
623
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000624public:
Rui Ueyama07320e42016-04-20 20:13:41 +0000625 ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
George Rimarf23b2322016-02-19 10:45:45 +0000626
George Rimar20b65982016-08-31 09:08:26 +0000627 void readLinkerScript();
628 void readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000629
630private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000631 void addFile(StringRef Path);
632
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000633 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000634 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000635 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000636 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000637 void readInclude();
Rui Ueyamaee592822015-10-07 00:25:09 +0000638 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000639 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000640 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000641 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000642 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000643 void readSections();
Rui Ueyama95769b42016-08-31 20:03:54 +0000644 void readVersion();
645 void readVersionScriptCommand();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000646
Rui Ueyama113cdec2016-07-24 23:05:57 +0000647 SymbolAssignment *readAssignment(StringRef Name);
George Rimarff1f29e2016-09-06 13:51:57 +0000648 std::vector<uint8_t> readFill();
Rui Ueyama10416562016-08-04 02:03:27 +0000649 OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
George Rimarff1f29e2016-09-06 13:51:57 +0000650 std::vector<uint8_t> readOutputSectionFiller(StringRef Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000651 std::vector<StringRef> readOutputSectionPhdrs();
George Rimara2496cb2016-08-30 09:46:59 +0000652 InputSectionDescription *readInputSectionDescription(StringRef Tok);
George Rimarc91930a2016-09-02 21:17:20 +0000653 Regex readFilePatterns();
George Rimara2496cb2016-08-30 09:46:59 +0000654 InputSectionDescription *readInputSectionRules(StringRef FilePattern);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000655 unsigned readPhdrType();
Rui Ueyama742c3832016-08-04 22:27:00 +0000656 SortKind readSortKind();
Petr Hoseka35e39c2016-08-16 01:11:16 +0000657 SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
Eugene Leviantdb741e72016-09-07 07:08:43 +0000658 SymbolAssignment *readProvideOrAssignment(StringRef Tok, bool MakeAbsolute);
George Rimar03fc0102016-07-28 07:18:23 +0000659 void readSort();
George Rimareefa7582016-08-04 09:29:31 +0000660 Expr readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +0000661
662 Expr readExpr();
663 Expr readExpr1(Expr Lhs, int MinPrec);
664 Expr readPrimary();
665 Expr readTernary(Expr Cond);
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +0000666 Expr readParenExpr();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000667
George Rimar20b65982016-08-31 09:08:26 +0000668 // For parsing version script.
669 void readExtern(std::vector<SymbolVersion> *Globals);
Rui Ueyama95769b42016-08-31 20:03:54 +0000670 void readVersionDeclaration(StringRef VerStr);
George Rimar20b65982016-08-31 09:08:26 +0000671 void readGlobal(StringRef VerStr);
672 void readLocal();
673
Rui Ueyama07320e42016-04-20 20:13:41 +0000674 ScriptConfiguration &Opt = *ScriptConfig;
675 StringSaver Saver = {ScriptConfig->Alloc};
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000676 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000677};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000678
George Rimar20b65982016-08-31 09:08:26 +0000679void ScriptParser::readVersionScript() {
Rui Ueyama95769b42016-08-31 20:03:54 +0000680 readVersionScriptCommand();
681 if (!atEOF())
682 setError("EOF expected, but got " + next());
683}
684
685void ScriptParser::readVersionScriptCommand() {
George Rimar20b65982016-08-31 09:08:26 +0000686 if (skip("{")) {
Rui Ueyama95769b42016-08-31 20:03:54 +0000687 readVersionDeclaration("");
George Rimar20b65982016-08-31 09:08:26 +0000688 return;
689 }
690
Rui Ueyama95769b42016-08-31 20:03:54 +0000691 while (!atEOF() && !Error && peek() != "}") {
George Rimar20b65982016-08-31 09:08:26 +0000692 StringRef VerStr = next();
693 if (VerStr == "{") {
Rui Ueyama95769b42016-08-31 20:03:54 +0000694 setError("anonymous version definition is used in "
695 "combination with other version definitions");
George Rimar20b65982016-08-31 09:08:26 +0000696 return;
697 }
698 expect("{");
Rui Ueyama95769b42016-08-31 20:03:54 +0000699 readVersionDeclaration(VerStr);
George Rimar20b65982016-08-31 09:08:26 +0000700 }
701}
702
Rui Ueyama95769b42016-08-31 20:03:54 +0000703void ScriptParser::readVersion() {
704 expect("{");
705 readVersionScriptCommand();
706 expect("}");
707}
708
George Rimar20b65982016-08-31 09:08:26 +0000709void ScriptParser::readLinkerScript() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000710 while (!atEOF()) {
711 StringRef Tok = next();
Rui Ueyamaa27eecc2016-09-02 18:52:41 +0000712 if (Tok == ";")
713 continue;
714
715 if (Tok == "ENTRY") {
716 readEntry();
717 } else if (Tok == "EXTERN") {
718 readExtern();
719 } else if (Tok == "GROUP" || Tok == "INPUT") {
720 readGroup();
721 } else if (Tok == "INCLUDE") {
722 readInclude();
723 } else if (Tok == "OUTPUT") {
724 readOutput();
725 } else if (Tok == "OUTPUT_ARCH") {
726 readOutputArch();
727 } else if (Tok == "OUTPUT_FORMAT") {
728 readOutputFormat();
729 } else if (Tok == "PHDRS") {
730 readPhdrs();
731 } else if (Tok == "SEARCH_DIR") {
732 readSearchDir();
733 } else if (Tok == "SECTIONS") {
734 readSections();
735 } else if (Tok == "VERSION") {
736 readVersion();
Eugene Leviantdb741e72016-09-07 07:08:43 +0000737 } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok, true)) {
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000738 if (Opt.HasContents)
739 Opt.Commands.emplace_back(Cmd);
740 else
741 Opt.Assignments.emplace_back(Cmd);
742 } else {
George Rimar57610422016-03-11 14:43:02 +0000743 setError("unknown directive: " + Tok);
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000744 }
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000745 }
746}
747
Rui Ueyama717677a2016-02-11 21:17:59 +0000748void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000749 if (IsUnderSysroot && S.startswith("/")) {
750 SmallString<128> Path;
751 (Config->Sysroot + S).toStringRef(Path);
752 if (sys::fs::exists(Path)) {
753 Driver->addFile(Saver.save(Path.str()));
754 return;
755 }
756 }
757
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +0000758 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +0000759 Driver->addFile(S);
760 } else if (S.startswith("=")) {
761 if (Config->Sysroot.empty())
762 Driver->addFile(S.substr(1));
763 else
764 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
765 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +0000766 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +0000767 } else if (sys::fs::exists(S)) {
768 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +0000769 } else {
770 std::string Path = findFromSearchPaths(S);
771 if (Path.empty())
George Rimar777f9632016-03-12 08:31:34 +0000772 setError("unable to find " + S);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000773 else
774 Driver->addFile(Saver.save(Path));
Rui Ueyama52a15092015-10-11 03:28:42 +0000775 }
776}
777
Rui Ueyama717677a2016-02-11 21:17:59 +0000778void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000779 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +0000780 bool Orig = Config->AsNeeded;
781 Config->AsNeeded = true;
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000782 while (!Error && !skip(")"))
783 addFile(next());
Rui Ueyama35da9b62015-10-11 20:59:12 +0000784 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000785}
786
Rui Ueyama717677a2016-02-11 21:17:59 +0000787void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +0000788 // -e <symbol> takes predecence over ENTRY(<symbol>).
789 expect("(");
790 StringRef Tok = next();
791 if (Config->Entry.empty())
792 Config->Entry = Tok;
793 expect(")");
794}
795
Rui Ueyama717677a2016-02-11 21:17:59 +0000796void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +0000797 expect("(");
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000798 while (!Error && !skip(")"))
799 Config->Undefined.push_back(next());
George Rimar83f406c2015-10-19 17:35:12 +0000800}
801
Rui Ueyama717677a2016-02-11 21:17:59 +0000802void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000803 expect("(");
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000804 while (!Error && !skip(")")) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000805 StringRef Tok = next();
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000806 if (Tok == "AS_NEEDED")
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000807 readAsNeeded();
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000808 else
809 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000810 }
811}
812
Rui Ueyama717677a2016-02-11 21:17:59 +0000813void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000814 StringRef Tok = next();
815 auto MBOrErr = MemoryBuffer::getFile(Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000816 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +0000817 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000818 return;
819 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000820 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Rui Ueyamaa47ee682015-10-11 01:53:04 +0000821 StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
822 std::vector<StringRef> V = tokenize(S);
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000823 Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000824}
825
Rui Ueyama717677a2016-02-11 21:17:59 +0000826void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +0000827 // -o <file> takes predecence over OUTPUT(<file>).
828 expect("(");
829 StringRef Tok = next();
830 if (Config->OutputFile.empty())
831 Config->OutputFile = Tok;
832 expect(")");
833}
834
Rui Ueyama717677a2016-02-11 21:17:59 +0000835void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +0000836 // Error checking only for now.
837 expect("(");
838 next();
839 expect(")");
840}
841
Rui Ueyama717677a2016-02-11 21:17:59 +0000842void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000843 // Error checking only for now.
844 expect("(");
845 next();
Davide Italiano6836c612015-10-12 21:08:41 +0000846 StringRef Tok = next();
847 if (Tok == ")")
George Rimar6c55f0e2016-09-08 08:20:30 +0000848 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000849 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +0000850 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000851 return;
852 }
Davide Italiano6836c612015-10-12 21:08:41 +0000853 next();
854 expect(",");
855 next();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000856 expect(")");
857}
858
Eugene Leviantbbe38602016-07-19 09:25:43 +0000859void ScriptParser::readPhdrs() {
860 expect("{");
861 while (!Error && !skip("}")) {
862 StringRef Tok = next();
Eugene Leviant865bf862016-07-21 10:43:25 +0000863 Opt.PhdrsCommands.push_back({Tok, PT_NULL, false, false, UINT_MAX});
Eugene Leviantbbe38602016-07-19 09:25:43 +0000864 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
865
866 PhdrCmd.Type = readPhdrType();
867 do {
868 Tok = next();
869 if (Tok == ";")
870 break;
871 if (Tok == "FILEHDR")
872 PhdrCmd.HasFilehdr = true;
873 else if (Tok == "PHDRS")
874 PhdrCmd.HasPhdrs = true;
Eugene Leviant865bf862016-07-21 10:43:25 +0000875 else if (Tok == "FLAGS") {
876 expect("(");
Rafael Espindolaeb685cd2016-08-02 22:14:57 +0000877 // Passing 0 for the value of dot is a bit of a hack. It means that
878 // we accept expressions like ".|1".
879 PhdrCmd.Flags = readExpr()(0);
Eugene Leviant865bf862016-07-21 10:43:25 +0000880 expect(")");
881 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +0000882 setError("unexpected header attribute: " + Tok);
883 } while (!Error);
884 }
885}
886
Rui Ueyama717677a2016-02-11 21:17:59 +0000887void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +0000888 expect("(");
Rui Ueyama6c7ad132016-09-02 19:20:33 +0000889 if (!Config->Nostdlib)
890 Config->SearchPaths.push_back(next());
Davide Italiano68a39a62015-10-08 17:51:41 +0000891 expect(")");
892}
893
Rui Ueyama717677a2016-02-11 21:17:59 +0000894void ScriptParser::readSections() {
Rui Ueyama3de0a332016-07-29 03:31:09 +0000895 Opt.HasContents = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000896 expect("{");
George Rimar652852c2016-04-16 10:10:32 +0000897 while (!Error && !skip("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +0000898 StringRef Tok = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +0000899 BaseCommand *Cmd = readProvideOrAssignment(Tok, true);
Eugene Leviantceabe802016-08-11 07:56:43 +0000900 if (!Cmd) {
901 if (Tok == "ASSERT")
902 Cmd = new AssertCommand(readAssert());
903 else
904 Cmd = readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +0000905 }
Rui Ueyama10416562016-08-04 02:03:27 +0000906 Opt.Commands.emplace_back(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000907 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000908}
909
Rui Ueyama708019c2016-07-24 18:19:40 +0000910static int precedence(StringRef Op) {
911 return StringSwitch<int>(Op)
912 .Case("*", 4)
913 .Case("/", 4)
914 .Case("+", 3)
915 .Case("-", 3)
916 .Case("<", 2)
917 .Case(">", 2)
918 .Case(">=", 2)
919 .Case("<=", 2)
920 .Case("==", 2)
921 .Case("!=", 2)
922 .Case("&", 1)
Rafael Espindolacc3dd622016-08-22 21:33:35 +0000923 .Case("|", 1)
Rui Ueyama708019c2016-07-24 18:19:40 +0000924 .Default(-1);
925}
926
George Rimarc91930a2016-09-02 21:17:20 +0000927Regex ScriptParser::readFilePatterns() {
Rui Ueyama10416562016-08-04 02:03:27 +0000928 std::vector<StringRef> V;
929 while (!Error && !skip(")"))
930 V.push_back(next());
George Rimarc91930a2016-09-02 21:17:20 +0000931 return compileGlobPatterns(V);
George Rimar0702c4e2016-07-29 15:32:46 +0000932}
933
Rui Ueyama742c3832016-08-04 22:27:00 +0000934SortKind ScriptParser::readSortKind() {
935 if (skip("SORT") || skip("SORT_BY_NAME"))
936 return SortByName;
937 if (skip("SORT_BY_ALIGNMENT"))
938 return SortByAlignment;
939 return SortNone;
940}
941
George Rimara2496cb2016-08-30 09:46:59 +0000942InputSectionDescription *
943ScriptParser::readInputSectionRules(StringRef FilePattern) {
George Rimarc91930a2016-09-02 21:17:20 +0000944 auto *Cmd = new InputSectionDescription(FilePattern);
Davide Italiano0ed42b02016-07-25 21:47:13 +0000945 expect("(");
Davide Italianoe7282792016-07-27 01:44:01 +0000946
Rui Ueyama742c3832016-08-04 22:27:00 +0000947 // Read EXCLUDE_FILE().
Davide Italianoe7282792016-07-27 01:44:01 +0000948 if (skip("EXCLUDE_FILE")) {
949 expect("(");
George Rimarc91930a2016-09-02 21:17:20 +0000950 Cmd->ExcludedFileRe = readFilePatterns();
Davide Italiano0ed42b02016-07-25 21:47:13 +0000951 }
George Rimar06598002016-07-28 21:51:30 +0000952
Rui Ueyama742c3832016-08-04 22:27:00 +0000953 // Read SORT().
954 if (SortKind K1 = readSortKind()) {
955 Cmd->SortOuter = K1;
George Rimar0702c4e2016-07-29 15:32:46 +0000956 expect("(");
Rui Ueyama742c3832016-08-04 22:27:00 +0000957 if (SortKind K2 = readSortKind()) {
958 Cmd->SortInner = K2;
George Rimar350ece42016-08-03 08:35:59 +0000959 expect("(");
George Rimarc91930a2016-09-02 21:17:20 +0000960 Cmd->SectionRe = readFilePatterns();
George Rimar350ece42016-08-03 08:35:59 +0000961 expect(")");
962 } else {
George Rimarc91930a2016-09-02 21:17:20 +0000963 Cmd->SectionRe = readFilePatterns();
George Rimar350ece42016-08-03 08:35:59 +0000964 }
George Rimar0702c4e2016-07-29 15:32:46 +0000965 expect(")");
Rui Ueyama10416562016-08-04 02:03:27 +0000966 return Cmd;
George Rimar06598002016-07-28 21:51:30 +0000967 }
George Rimar0702c4e2016-07-29 15:32:46 +0000968
George Rimarc91930a2016-09-02 21:17:20 +0000969 Cmd->SectionRe = readFilePatterns();
Rui Ueyama10416562016-08-04 02:03:27 +0000970 return Cmd;
Davide Italianoe7282792016-07-27 01:44:01 +0000971}
972
George Rimara2496cb2016-08-30 09:46:59 +0000973InputSectionDescription *
974ScriptParser::readInputSectionDescription(StringRef Tok) {
George Rimar06598002016-07-28 21:51:30 +0000975 // Input section wildcard can be surrounded by KEEP.
976 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
George Rimara2496cb2016-08-30 09:46:59 +0000977 if (Tok == "KEEP") {
George Rimar06598002016-07-28 21:51:30 +0000978 expect("(");
George Rimara2496cb2016-08-30 09:46:59 +0000979 StringRef FilePattern = next();
980 InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
George Rimar06598002016-07-28 21:51:30 +0000981 expect(")");
George Rimarc91930a2016-09-02 21:17:20 +0000982 Opt.KeptSections.push_back(&Cmd->SectionRe);
Rui Ueyama10416562016-08-04 02:03:27 +0000983 return Cmd;
George Rimar06598002016-07-28 21:51:30 +0000984 }
George Rimara2496cb2016-08-30 09:46:59 +0000985 return readInputSectionRules(Tok);
Davide Italiano0ed42b02016-07-25 21:47:13 +0000986}
987
George Rimar03fc0102016-07-28 07:18:23 +0000988void ScriptParser::readSort() {
989 expect("(");
990 expect("CONSTRUCTORS");
991 expect(")");
992}
993
George Rimareefa7582016-08-04 09:29:31 +0000994Expr ScriptParser::readAssert() {
995 expect("(");
996 Expr E = readExpr();
997 expect(",");
998 StringRef Msg = next();
999 expect(")");
1000 return [=](uint64_t Dot) {
1001 uint64_t V = E(Dot);
1002 if (!V)
1003 error(Msg);
1004 return V;
1005 };
1006}
1007
Rui Ueyama25150e82016-09-06 17:46:43 +00001008// Reads a FILL(expr) command. We handle the FILL command as an
1009// alias for =fillexp section attribute, which is different from
1010// what GNU linkers do.
1011// https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
George Rimarff1f29e2016-09-06 13:51:57 +00001012std::vector<uint8_t> ScriptParser::readFill() {
1013 expect("(");
1014 std::vector<uint8_t> V = readOutputSectionFiller(next());
1015 expect(")");
1016 expect(";");
1017 return V;
1018}
1019
Rui Ueyama10416562016-08-04 02:03:27 +00001020OutputSectionCommand *
1021ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +00001022 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
George Rimar58e5c4d2016-07-25 08:29:46 +00001023
1024 // Read an address expression.
1025 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
1026 if (peek() != ":")
1027 Cmd->AddrExpr = readExpr();
1028
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001029 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +00001030
George Rimar8ceadb32016-08-17 07:44:19 +00001031 if (skip("AT"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001032 Cmd->LmaExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001033 if (skip("ALIGN"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001034 Cmd->AlignExpr = readParenExpr();
George Rimardb24d9c2016-08-19 15:18:23 +00001035 if (skip("SUBALIGN"))
1036 Cmd->SubalignExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001037
Davide Italiano246f6812016-07-22 03:36:24 +00001038 // Parse constraints.
1039 if (skip("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001040 Cmd->Constraint = ConstraintKind::ReadOnly;
Davide Italiano246f6812016-07-22 03:36:24 +00001041 if (skip("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001042 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001043 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001044
Rui Ueyama025d59b2016-02-02 20:27:59 +00001045 while (!Error && !skip("}")) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001046 StringRef Tok = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +00001047 if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok, false))
Eugene Leviantceabe802016-08-11 07:56:43 +00001048 Cmd->Commands.emplace_back(Assignment);
George Rimarff1f29e2016-09-06 13:51:57 +00001049 else if (Tok == "FILL")
1050 Cmd->Filler = readFill();
Eugene Leviantceabe802016-08-11 07:56:43 +00001051 else if (Tok == "SORT")
George Rimar03fc0102016-07-28 07:18:23 +00001052 readSort();
George Rimara2496cb2016-08-30 09:46:59 +00001053 else if (peek() == "(")
1054 Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
Eugene Leviantceabe802016-08-11 07:56:43 +00001055 else
1056 setError("unknown command " + Tok);
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001057 }
George Rimar076fe152016-07-21 06:43:01 +00001058 Cmd->Phdrs = readOutputSectionPhdrs();
George Rimarff1f29e2016-09-06 13:51:57 +00001059 if (peek().startswith("="))
1060 Cmd->Filler = readOutputSectionFiller(next().drop_front());
Rui Ueyama10416562016-08-04 02:03:27 +00001061 return Cmd;
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001062}
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001063
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001064// Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
1065// https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
1066//
1067// ld.gold is not fully compatible with ld.bfd. ld.bfd handles
1068// hexstrings as blobs of arbitrary sizes, while ld.gold handles them
1069// as 32-bit big-endian values. We will do the same as ld.gold does
1070// because it's simpler than what ld.bfd does.
George Rimarff1f29e2016-09-06 13:51:57 +00001071std::vector<uint8_t> ScriptParser::readOutputSectionFiller(StringRef Tok) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001072 uint32_t V;
George Rimarff1f29e2016-09-06 13:51:57 +00001073 if (Tok.getAsInteger(0, V)) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001074 setError("invalid filler expression: " + Tok);
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001075 return {};
George Rimare2ee72b2016-02-26 14:48:31 +00001076 }
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001077 return {uint8_t(V >> 24), uint8_t(V >> 16), uint8_t(V >> 8), uint8_t(V)};
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001078}
1079
Petr Hoseka35e39c2016-08-16 01:11:16 +00001080SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
Eugene Levianta31c91b2016-07-22 07:38:40 +00001081 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +00001082 SymbolAssignment *Cmd = readAssignment(next());
Petr Hoseka35e39c2016-08-16 01:11:16 +00001083 Cmd->Provide = Provide;
Rui Ueyama174e0a12016-07-29 00:29:25 +00001084 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001085 expect(")");
1086 expect(";");
Rui Ueyama10416562016-08-04 02:03:27 +00001087 return Cmd;
Eugene Levianteda81a12016-07-12 06:39:48 +00001088}
1089
Eugene Leviantdb741e72016-09-07 07:08:43 +00001090SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok,
1091 bool MakeAbsolute) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001092 SymbolAssignment *Cmd = nullptr;
1093 if (peek() == "=" || peek() == "+=") {
1094 Cmd = readAssignment(Tok);
1095 expect(";");
1096 } else if (Tok == "PROVIDE") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001097 Cmd = readProvideHidden(true, false);
1098 } else if (Tok == "HIDDEN") {
1099 Cmd = readProvideHidden(false, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001100 } else if (Tok == "PROVIDE_HIDDEN") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001101 Cmd = readProvideHidden(true, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001102 }
Eugene Leviantdb741e72016-09-07 07:08:43 +00001103 if (Cmd && MakeAbsolute)
1104 Cmd->IsAbsolute = true;
Eugene Leviantceabe802016-08-11 07:56:43 +00001105 return Cmd;
1106}
1107
George Rimar30835ea2016-07-28 21:08:56 +00001108static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
1109 if (S == ".")
1110 return Dot;
George Rimar884e7862016-09-08 08:19:13 +00001111 return ScriptBase->getSymbolValue(S);
George Rimare32a3592016-08-10 07:59:34 +00001112}
1113
George Rimar30835ea2016-07-28 21:08:56 +00001114SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1115 StringRef Op = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +00001116 bool IsAbsolute = false;
1117 Expr E;
George Rimar30835ea2016-07-28 21:08:56 +00001118 assert(Op == "=" || Op == "+=");
Eugene Leviantdb741e72016-09-07 07:08:43 +00001119 if (skip("ABSOLUTE")) {
1120 E = readParenExpr();
1121 IsAbsolute = true;
1122 } else {
1123 E = readExpr();
1124 }
George Rimar30835ea2016-07-28 21:08:56 +00001125 if (Op == "+=")
1126 E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
Eugene Leviantdb741e72016-09-07 07:08:43 +00001127 return new SymbolAssignment(Name, E, IsAbsolute);
George Rimar30835ea2016-07-28 21:08:56 +00001128}
1129
1130// This is an operator-precedence parser to parse a linker
1131// script expression.
1132Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
1133
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001134static Expr combine(StringRef Op, Expr L, Expr R) {
1135 if (Op == "*")
1136 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1137 if (Op == "/") {
1138 return [=](uint64_t Dot) -> uint64_t {
1139 uint64_t RHS = R(Dot);
1140 if (RHS == 0) {
1141 error("division by zero");
1142 return 0;
1143 }
1144 return L(Dot) / RHS;
1145 };
1146 }
1147 if (Op == "+")
1148 return [=](uint64_t Dot) { return L(Dot) + R(Dot); };
1149 if (Op == "-")
1150 return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
1151 if (Op == "<")
1152 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
1153 if (Op == ">")
1154 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
1155 if (Op == ">=")
1156 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
1157 if (Op == "<=")
1158 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
1159 if (Op == "==")
1160 return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
1161 if (Op == "!=")
1162 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
1163 if (Op == "&")
1164 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
Rafael Espindolacc3dd622016-08-22 21:33:35 +00001165 if (Op == "|")
1166 return [=](uint64_t Dot) { return L(Dot) | R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001167 llvm_unreachable("invalid operator");
1168}
1169
Rui Ueyama708019c2016-07-24 18:19:40 +00001170// This is a part of the operator-precedence parser. This function
1171// assumes that the remaining token stream starts with an operator.
1172Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1173 while (!atEOF() && !Error) {
1174 // Read an operator and an expression.
1175 StringRef Op1 = peek();
1176 if (Op1 == "?")
1177 return readTernary(Lhs);
1178 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +00001179 break;
Rui Ueyama708019c2016-07-24 18:19:40 +00001180 next();
1181 Expr Rhs = readPrimary();
1182
1183 // Evaluate the remaining part of the expression first if the
1184 // next operator has greater precedence than the previous one.
1185 // For example, if we have read "+" and "3", and if the next
1186 // operator is "*", then we'll evaluate 3 * ... part first.
1187 while (!atEOF()) {
1188 StringRef Op2 = peek();
1189 if (precedence(Op2) <= precedence(Op1))
1190 break;
1191 Rhs = readExpr1(Rhs, precedence(Op2));
1192 }
1193
1194 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +00001195 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001196 return Lhs;
1197}
1198
1199uint64_t static getConstant(StringRef S) {
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001200 if (S == "COMMONPAGESIZE")
Rui Ueyama708019c2016-07-24 18:19:40 +00001201 return Target->PageSize;
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001202 if (S == "MAXPAGESIZE")
1203 return Target->MaxPageSize;
Rui Ueyama708019c2016-07-24 18:19:40 +00001204 error("unknown constant: " + S);
1205 return 0;
1206}
1207
Rui Ueyama626e0b02016-09-02 18:19:00 +00001208// Parses Tok as an integer. Returns true if successful.
1209// It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1210// and decimal numbers. Decimal numbers may have "K" (kilo) or
1211// "M" (mega) prefixes.
George Rimar9f2f7ad2016-09-02 16:01:42 +00001212static bool readInteger(StringRef Tok, uint64_t &Result) {
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001213 if (Tok.startswith("-")) {
1214 if (!readInteger(Tok.substr(1), Result))
1215 return false;
1216 Result = -Result;
1217 return true;
1218 }
George Rimar9f2f7ad2016-09-02 16:01:42 +00001219 if (Tok.startswith_lower("0x"))
1220 return !Tok.substr(2).getAsInteger(16, Result);
1221 if (Tok.endswith_lower("H"))
1222 return !Tok.drop_back().getAsInteger(16, Result);
1223
1224 int Suffix = 1;
1225 if (Tok.endswith_lower("K")) {
1226 Suffix = 1024;
1227 Tok = Tok.drop_back();
1228 } else if (Tok.endswith_lower("M")) {
1229 Suffix = 1024 * 1024;
1230 Tok = Tok.drop_back();
1231 }
1232 if (Tok.getAsInteger(10, Result))
1233 return false;
1234 Result *= Suffix;
1235 return true;
1236}
1237
Rui Ueyama708019c2016-07-24 18:19:40 +00001238Expr ScriptParser::readPrimary() {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001239 if (peek() == "(")
1240 return readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001241
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001242 StringRef Tok = next();
Rui Ueyama708019c2016-07-24 18:19:40 +00001243
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001244 if (Tok == "~") {
1245 Expr E = readPrimary();
1246 return [=](uint64_t Dot) { return ~E(Dot); };
1247 }
1248 if (Tok == "-") {
1249 Expr E = readPrimary();
1250 return [=](uint64_t Dot) { return -E(Dot); };
1251 }
1252
Rui Ueyama708019c2016-07-24 18:19:40 +00001253 // Built-in functions are parsed here.
1254 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
George Rimar96659df2016-08-30 09:54:01 +00001255 if (Tok == "ADDR") {
1256 expect("(");
1257 StringRef Name = next();
1258 expect(")");
George Rimar884e7862016-09-08 08:19:13 +00001259 return
1260 [=](uint64_t Dot) { return ScriptBase->getOutputSectionAddress(Name); };
George Rimar96659df2016-08-30 09:54:01 +00001261 }
George Rimareefa7582016-08-04 09:29:31 +00001262 if (Tok == "ASSERT")
1263 return readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001264 if (Tok == "ALIGN") {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001265 Expr E = readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001266 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1267 }
1268 if (Tok == "CONSTANT") {
1269 expect("(");
1270 StringRef Tok = next();
1271 expect(")");
1272 return [=](uint64_t Dot) { return getConstant(Tok); };
1273 }
Rafael Espindola54c145c2016-07-28 18:16:24 +00001274 if (Tok == "SEGMENT_START") {
1275 expect("(");
1276 next();
1277 expect(",");
1278 uint64_t Val;
1279 next().getAsInteger(0, Val);
1280 expect(")");
1281 return [=](uint64_t Dot) { return Val; };
1282 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001283 if (Tok == "DATA_SEGMENT_ALIGN") {
1284 expect("(");
1285 Expr E = readExpr();
1286 expect(",");
1287 readExpr();
1288 expect(")");
Rui Ueyamaf7791bb2016-07-26 19:34:10 +00001289 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001290 }
1291 if (Tok == "DATA_SEGMENT_END") {
1292 expect("(");
1293 expect(".");
1294 expect(")");
1295 return [](uint64_t Dot) { return Dot; };
1296 }
George Rimar276b4e62016-07-26 17:58:44 +00001297 // GNU linkers implements more complicated logic to handle
1298 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1299 // the next page boundary for simplicity.
1300 if (Tok == "DATA_SEGMENT_RELRO_END") {
1301 expect("(");
1302 next();
1303 expect(",");
1304 readExpr();
1305 expect(")");
1306 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1307 }
George Rimar9e694502016-07-29 16:18:47 +00001308 if (Tok == "SIZEOF") {
1309 expect("(");
1310 StringRef Name = next();
1311 expect(")");
George Rimar884e7862016-09-08 08:19:13 +00001312 return [=](uint64_t Dot) { return ScriptBase->getOutputSectionSize(Name); };
George Rimar9e694502016-07-29 16:18:47 +00001313 }
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001314 if (Tok == "ALIGNOF") {
1315 expect("(");
1316 StringRef Name = next();
1317 expect(")");
1318 return
1319 [=](uint64_t Dot) { return ScriptBase->getOutputSectionAlign(Name); };
1320 }
George Rimare32a3592016-08-10 07:59:34 +00001321 if (Tok == "SIZEOF_HEADERS")
George Rimar884e7862016-09-08 08:19:13 +00001322 return [=](uint64_t Dot) { return ScriptBase->getHeaderSize(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001323
George Rimar9f2f7ad2016-09-02 16:01:42 +00001324 // Tok is a literal number.
1325 uint64_t V;
1326 if (readInteger(Tok, V))
1327 return [=](uint64_t Dot) { return V; };
1328
1329 // Tok is a symbol name.
1330 if (Tok != "." && !isValidCIdentifier(Tok))
1331 setError("malformed number: " + Tok);
1332 return [=](uint64_t Dot) { return getSymbolValue(Tok, Dot); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001333}
1334
1335Expr ScriptParser::readTernary(Expr Cond) {
1336 next();
1337 Expr L = readExpr();
1338 expect(":");
1339 Expr R = readExpr();
1340 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1341}
1342
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001343Expr ScriptParser::readParenExpr() {
1344 expect("(");
1345 Expr E = readExpr();
1346 expect(")");
1347 return E;
1348}
1349
Eugene Leviantbbe38602016-07-19 09:25:43 +00001350std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1351 std::vector<StringRef> Phdrs;
1352 while (!Error && peek().startswith(":")) {
1353 StringRef Tok = next();
1354 Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
1355 if (Tok.empty()) {
1356 setError("section header name is empty");
1357 break;
1358 }
Rui Ueyama047404f2016-07-20 19:36:36 +00001359 Phdrs.push_back(Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001360 }
1361 return Phdrs;
1362}
1363
1364unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001365 StringRef Tok = next();
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001366 unsigned Ret = StringSwitch<unsigned>(Tok)
George Rimar6c55f0e2016-09-08 08:20:30 +00001367 .Case("PT_NULL", PT_NULL)
1368 .Case("PT_LOAD", PT_LOAD)
1369 .Case("PT_DYNAMIC", PT_DYNAMIC)
1370 .Case("PT_INTERP", PT_INTERP)
1371 .Case("PT_NOTE", PT_NOTE)
1372 .Case("PT_SHLIB", PT_SHLIB)
1373 .Case("PT_PHDR", PT_PHDR)
1374 .Case("PT_TLS", PT_TLS)
1375 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1376 .Case("PT_GNU_STACK", PT_GNU_STACK)
1377 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1378 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001379
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001380 if (Ret == (unsigned)-1) {
1381 setError("invalid program header type: " + Tok);
1382 return PT_NULL;
1383 }
1384 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001385}
1386
Rui Ueyama95769b42016-08-31 20:03:54 +00001387void ScriptParser::readVersionDeclaration(StringRef VerStr) {
George Rimar20b65982016-08-31 09:08:26 +00001388 // Identifiers start at 2 because 0 and 1 are reserved
1389 // for VER_NDX_LOCAL and VER_NDX_GLOBAL constants.
1390 size_t VersionId = Config->VersionDefinitions.size() + 2;
1391 Config->VersionDefinitions.push_back({VerStr, VersionId});
1392
1393 if (skip("global:") || peek() != "local:")
1394 readGlobal(VerStr);
1395 if (skip("local:"))
1396 readLocal();
1397 expect("}");
1398
1399 // Each version may have a parent version. For example, "Ver2" defined as
1400 // "Ver2 { global: foo; local: *; } Ver1;" has "Ver1" as a parent. This
1401 // version hierarchy is, probably against your instinct, purely for human; the
1402 // runtime doesn't care about them at all. In LLD, we simply skip the token.
1403 if (!VerStr.empty() && peek() != ";")
1404 next();
1405 expect(";");
1406}
1407
1408void ScriptParser::readLocal() {
1409 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1410 expect("*");
1411 expect(";");
1412}
1413
1414void ScriptParser::readExtern(std::vector<SymbolVersion> *Globals) {
1415 expect("C++");
1416 expect("{");
1417
1418 for (;;) {
1419 if (peek() == "}" || Error)
1420 break;
1421 Globals->push_back({next(), true});
1422 expect(";");
1423 }
1424
1425 expect("}");
1426 expect(";");
1427}
1428
1429void ScriptParser::readGlobal(StringRef VerStr) {
1430 std::vector<SymbolVersion> *Globals;
1431 if (VerStr.empty())
1432 Globals = &Config->VersionScriptGlobals;
1433 else
1434 Globals = &Config->VersionDefinitions.back().Globals;
1435
1436 for (;;) {
1437 if (skip("extern"))
1438 readExtern(Globals);
1439
1440 StringRef Cur = peek();
1441 if (Cur == "}" || Cur == "local:" || Error)
1442 return;
1443 next();
1444 Globals->push_back({Cur, false});
1445 expect(";");
1446 }
1447}
1448
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001449static bool isUnderSysroot(StringRef Path) {
1450 if (Config->Sysroot == "")
1451 return false;
1452 for (; !Path.empty(); Path = sys::path::parent_path(Path))
1453 if (sys::fs::equivalent(Config->Sysroot, Path))
1454 return true;
1455 return false;
1456}
1457
Rui Ueyama07320e42016-04-20 20:13:41 +00001458void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001459 StringRef Path = MB.getBufferIdentifier();
George Rimar20b65982016-08-31 09:08:26 +00001460 ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).readLinkerScript();
1461}
1462
1463void elf::readVersionScript(MemoryBufferRef MB) {
1464 ScriptParser(MB.getBuffer(), false).readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001465}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001466
Rui Ueyama07320e42016-04-20 20:13:41 +00001467template class elf::LinkerScript<ELF32LE>;
1468template class elf::LinkerScript<ELF32BE>;
1469template class elf::LinkerScript<ELF64LE>;
1470template class elf::LinkerScript<ELF64BE>;