blob: 943a4abaff044eecf0cdb4937c9a951301d93e46 [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)
102 if (Re->match(S->getSectionName()))
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 &&
George Rimarc91930a2016-09-02 21:17:20 +0000124 const_cast<Regex &>(Re).match(S->getSectionName()))
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
Eugene Leviantceabe802016-08-11 07:56:43 +0000133template <class ELFT>
Rui Ueyama742c3832016-08-04 22:27:00 +0000134static bool compareName(InputSectionBase<ELFT> *A, InputSectionBase<ELFT> *B) {
135 return A->getSectionName() < B->getSectionName();
136}
George Rimar350ece42016-08-03 08:35:59 +0000137
Rui Ueyama742c3832016-08-04 22:27:00 +0000138template <class ELFT>
139static bool compareAlignment(InputSectionBase<ELFT> *A,
140 InputSectionBase<ELFT> *B) {
141 // ">" is not a mistake. Larger alignments are placed before smaller
142 // alignments in order to reduce the amount of padding necessary.
143 // This is compatible with GNU.
144 return A->Alignment > B->Alignment;
145}
George Rimar350ece42016-08-03 08:35:59 +0000146
Rui Ueyama742c3832016-08-04 22:27:00 +0000147template <class ELFT>
148static std::function<bool(InputSectionBase<ELFT> *, InputSectionBase<ELFT> *)>
149getComparator(SortKind K) {
150 if (K == SortByName)
151 return compareName<ELFT>;
152 return compareAlignment<ELFT>;
153}
George Rimar0702c4e2016-07-29 15:32:46 +0000154
155template <class ELFT>
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000156void LinkerScript<ELFT>::discard(OutputSectionCommand &Cmd) {
157 for (const std::unique_ptr<BaseCommand> &Base : Cmd.Commands) {
158 if (auto *Cmd = dyn_cast<InputSectionDescription>(Base.get())) {
159 for (InputSectionBase<ELFT> *S : getInputSections(Cmd)) {
160 S->Live = false;
161 reportDiscarded(S);
162 }
163 }
164 }
165}
166
George Rimar8f66df92016-08-12 20:38:20 +0000167static bool checkConstraint(uint64_t Flags, ConstraintKind Kind) {
168 bool RO = (Kind == ConstraintKind::ReadOnly);
169 bool RW = (Kind == ConstraintKind::ReadWrite);
170 bool Writable = Flags & SHF_WRITE;
Rui Ueyamaadcdb662016-09-06 22:50:48 +0000171 return !(RO && Writable) && !(RW && !Writable);
George Rimar8f66df92016-08-12 20:38:20 +0000172}
173
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000174template <class ELFT>
George Rimar06ae6832016-08-12 09:07:57 +0000175static bool matchConstraints(ArrayRef<InputSectionBase<ELFT> *> Sections,
176 ConstraintKind Kind) {
George Rimar8f66df92016-08-12 20:38:20 +0000177 if (Kind == ConstraintKind::NoConstraint)
178 return true;
179 return llvm::all_of(Sections, [=](InputSectionBase<ELFT> *Sec) {
180 return checkConstraint(Sec->getSectionHdr()->sh_flags, Kind);
George Rimar06ae6832016-08-12 09:07:57 +0000181 });
182}
183
184template <class ELFT>
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000185std::vector<InputSectionBase<ELFT> *>
George Rimar06ae6832016-08-12 09:07:57 +0000186LinkerScript<ELFT>::createInputSectionList(OutputSectionCommand &OutCmd) {
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000187 std::vector<InputSectionBase<ELFT> *> Ret;
Eugene Leviant97403d12016-09-01 09:55:57 +0000188 DenseSet<InputSectionBase<ELFT> *> SectionIndex;
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000189
George Rimar06ae6832016-08-12 09:07:57 +0000190 for (const std::unique_ptr<BaseCommand> &Base : OutCmd.Commands) {
191 if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base.get())) {
192 if (shouldDefine<ELFT>(OutCmd))
Eugene Leviantdb741e72016-09-07 07:08:43 +0000193 addSymbol<ELFT>(OutCmd);
Eugene Leviant97403d12016-09-01 09:55:57 +0000194 OutCmd->GoesAfter = Ret.empty() ? nullptr : Ret.back();
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000195 continue;
196 }
197
198 auto *Cmd = cast<InputSectionDescription>(Base.get());
199 std::vector<InputSectionBase<ELFT> *> V = getInputSections(Cmd);
George Rimar06ae6832016-08-12 09:07:57 +0000200 if (!matchConstraints<ELFT>(V, OutCmd.Constraint))
201 continue;
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000202 if (Cmd->SortInner)
203 std::stable_sort(V.begin(), V.end(), getComparator<ELFT>(Cmd->SortInner));
204 if (Cmd->SortOuter)
205 std::stable_sort(V.begin(), V.end(), getComparator<ELFT>(Cmd->SortOuter));
Eugene Leviant97403d12016-09-01 09:55:57 +0000206
207 // Add all input sections corresponding to rule 'Cmd' to
208 // resulting vector. We do not add duplicate input sections.
209 for (InputSectionBase<ELFT> *S : V)
210 if (SectionIndex.insert(S).second)
211 Ret.push_back(S);
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000212 }
213 return Ret;
214}
215
George Rimar6c55f0e2016-09-08 08:20:30 +0000216template <class ELFT> void LinkerScript<ELFT>::createAssignments() {
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000217 for (const std::unique_ptr<SymbolAssignment> &Cmd : Opt.Assignments) {
218 if (shouldDefine<ELFT>(Cmd.get()))
219 addRegular<ELFT>(Cmd.get());
220 if (Cmd->Sym)
221 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(0);
222 }
223}
224
225template <class ELFT>
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000226void LinkerScript<ELFT>::createSections(OutputSectionFactory<ELFT> &Factory) {
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000227 for (const std::unique_ptr<BaseCommand> &Base1 : Opt.Commands) {
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000228 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base1.get())) {
229 if (shouldDefine<ELFT>(Cmd))
230 addRegular<ELFT>(Cmd);
231 continue;
232 }
233
Eugene Leviantceabe802016-08-11 07:56:43 +0000234 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000235 if (Cmd->Name == "/DISCARD/") {
236 discard(*Cmd);
237 continue;
238 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000239
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000240 std::vector<InputSectionBase<ELFT> *> V = createInputSectionList(*Cmd);
Eugene Leviant97403d12016-09-01 09:55:57 +0000241 if (V.empty())
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000242 continue;
243
George Rimardb24d9c2016-08-19 15:18:23 +0000244 for (InputSectionBase<ELFT> *Sec : V) {
George Rimara14b13d2016-09-07 10:46:07 +0000245 OutputSectionBase<ELFT> *OutSec;
246 bool IsNew;
247 std::tie(OutSec, IsNew) = Factory.create(Sec, Cmd->Name);
248 if (IsNew)
249 OutputSections->push_back(OutSec);
250
251 uint32_t Subalign = Cmd->SubalignExpr ? Cmd->SubalignExpr(0) : 0;
252
George Rimardb24d9c2016-08-19 15:18:23 +0000253 if (Subalign)
254 Sec->Alignment = Subalign;
Eugene Leviant97403d12016-09-01 09:55:57 +0000255 OutSec->addSection(Sec);
George Rimardb24d9c2016-08-19 15:18:23 +0000256 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000257 }
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000258 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000259
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000260 // Add orphan sections.
Rui Ueyama6b274812016-07-25 22:51:07 +0000261 for (const std::unique_ptr<ObjectFile<ELFT>> &F :
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000262 Symtab<ELFT>::X->getObjectFiles()) {
263 for (InputSectionBase<ELFT> *S : F->getSections()) {
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000264 if (isDiscarded(S) || S->OutSec)
265 continue;
266 OutputSectionBase<ELFT> *OutSec;
267 bool IsNew;
268 std::tie(OutSec, IsNew) = Factory.create(S, getOutputSectionName(S));
269 if (IsNew)
270 OutputSections->push_back(OutSec);
271 OutSec->addSection(S);
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000272 }
273 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000274}
275
Eugene Leviantdb741e72016-09-07 07:08:43 +0000276// Sets value of a section-defined symbol. Two kinds of
277// symbols are processed: synthetic symbols, whose value
278// is an offset from beginning of section and regular
279// symbols whose value is absolute.
280template <class ELFT>
281static void assignSectionSymbol(SymbolAssignment *Cmd,
282 OutputSectionBase<ELFT> *Sec,
283 typename ELFT::uint Off) {
284 if (!Cmd->Sym)
285 return;
286
287 if (auto *Body = dyn_cast<DefinedSynthetic<ELFT>>(Cmd->Sym)) {
288 Body->Section = Sec;
289 Body->Value = Cmd->Expression(Sec->getVA() + Off) - Sec->getVA();
290 return;
291 }
292 auto *Body = cast<DefinedRegular<ELFT>>(Cmd->Sym);
293 Body->Value = Cmd->Expression(Sec->getVA() + Off);
294}
295
Eugene Leviant20889c52016-08-31 08:13:33 +0000296// Linker script may define start and end symbols for special section types,
297// like .got, .eh_frame_hdr, .eh_frame and others. Those sections are not a list
298// of regular input input sections, therefore our way of defining symbols for
299// regular sections will not work. The approach we use for special section types
300// is not perfect - it handles only start and end symbols.
301template <class ELFT>
302void addStartEndSymbols(OutputSectionCommand *Cmd,
303 OutputSectionBase<ELFT> *Sec) {
304 bool Start = true;
305 BaseCommand *PrevCmd = nullptr;
306
307 for (std::unique_ptr<BaseCommand> &Base : Cmd->Commands) {
308 if (auto *AssignCmd = dyn_cast<SymbolAssignment>(Base.get())) {
Eugene Leviantdb741e72016-09-07 07:08:43 +0000309 assignSectionSymbol<ELFT>(AssignCmd, Sec, Start ? 0 : Sec->getSize());
Eugene Leviant20889c52016-08-31 08:13:33 +0000310 } else {
311 if (!Start && isa<SymbolAssignment>(PrevCmd))
312 error("section '" + Sec->getName() +
313 "' supports only start and end symbols");
314 Start = false;
315 }
316 PrevCmd = Base.get();
317 }
318}
319
320template <class ELFT>
321void assignOffsets(OutputSectionCommand *Cmd, OutputSectionBase<ELFT> *Sec) {
Eugene Leviantceabe802016-08-11 07:56:43 +0000322 auto *OutSec = dyn_cast<OutputSection<ELFT>>(Sec);
Rui Ueyama2de509c2016-08-12 00:55:08 +0000323 if (!OutSec) {
324 Sec->assignOffsets();
Eugene Leviant20889c52016-08-31 08:13:33 +0000325 // This section is not regular output section. However linker script may
326 // have defined start/end symbols for it. This case is handled below.
327 addStartEndSymbols(Cmd, Sec);
Eugene Leviantceabe802016-08-11 07:56:43 +0000328 return;
Rui Ueyama2de509c2016-08-12 00:55:08 +0000329 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000330 typedef typename ELFT::uint uintX_t;
331 uintX_t Off = 0;
Eugene Leviant97403d12016-09-01 09:55:57 +0000332 auto ItCmd = Cmd->Commands.begin();
Eugene Leviantceabe802016-08-11 07:56:43 +0000333
Eugene Leviant97403d12016-09-01 09:55:57 +0000334 // Assigns values to all symbols following the given
335 // input section 'D' in output section 'Sec'. When symbols
336 // are in the beginning of output section the value of 'D'
337 // is nullptr.
338 auto AssignSuccessors = [&](InputSectionData *D) {
339 for (; ItCmd != Cmd->Commands.end(); ++ItCmd) {
340 auto *AssignCmd = dyn_cast<SymbolAssignment>(ItCmd->get());
341 if (!AssignCmd)
342 continue;
343 if (D != AssignCmd->GoesAfter)
344 break;
345
Eugene Leviant97403d12016-09-01 09:55:57 +0000346 if (AssignCmd->Name == ".") {
347 // Update to location counter means update to section size.
Eugene Leviantdb741e72016-09-07 07:08:43 +0000348 Off = AssignCmd->Expression(Sec->getVA() + Off) - Sec->getVA();
Eugene Leviant97403d12016-09-01 09:55:57 +0000349 Sec->setSize(Off);
350 continue;
351 }
Eugene Leviantdb741e72016-09-07 07:08:43 +0000352 assignSectionSymbol<ELFT>(AssignCmd, Sec, Off);
Eugene Leviantceabe802016-08-11 07:56:43 +0000353 }
Eugene Leviant97403d12016-09-01 09:55:57 +0000354 };
355
356 AssignSuccessors(nullptr);
357 for (InputSection<ELFT> *I : OutSec->Sections) {
358 Off = alignTo(Off, I->Alignment);
359 I->OutSecOff = Off;
360 Off += I->getSize();
Rui Ueyamaf4a30a52016-08-11 21:30:42 +0000361 // Update section size inside for-loop, so that SIZEOF
Eugene Leviantceabe802016-08-11 07:56:43 +0000362 // works correctly in the case below:
363 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
364 Sec->setSize(Off);
Eugene Leviant97403d12016-09-01 09:55:57 +0000365 // Add symbols following current input section.
366 AssignSuccessors(I);
Eugene Leviantceabe802016-08-11 07:56:43 +0000367 }
368}
369
George Rimar8f66df92016-08-12 20:38:20 +0000370template <class ELFT>
George Rimara14b13d2016-09-07 10:46:07 +0000371static std::vector<OutputSectionBase<ELFT> *>
372findSections(OutputSectionCommand &Cmd,
373 ArrayRef<OutputSectionBase<ELFT> *> Sections) {
374 std::vector<OutputSectionBase<ELFT> *> Ret;
375 for (OutputSectionBase<ELFT> *Sec : Sections)
376 if (Sec->getName() == Cmd.Name &&
377 checkConstraint(Sec->getFlags(), Cmd.Constraint))
378 Ret.push_back(Sec);
379 return Ret;
George Rimar8f66df92016-08-12 20:38:20 +0000380}
381
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000382template <class ELFT> void LinkerScript<ELFT>::assignAddresses() {
George Rimar652852c2016-04-16 10:10:32 +0000383 // Orphan sections are sections present in the input files which
Rui Ueyama7c18c282016-04-18 21:00:40 +0000384 // are not explicitly placed into the output file by the linker script.
385 // We place orphan sections at end of file.
386 // Other linkers places them using some heuristics as described in
George Rimar652852c2016-04-16 10:10:32 +0000387 // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
Rui Ueyamae5cc6682016-08-12 00:36:56 +0000388 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
George Rimar652852c2016-04-16 10:10:32 +0000389 StringRef Name = Sec->getName();
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000390 if (getSectionIndex(Name) == INT_MAX)
George Rimar076fe152016-07-21 06:43:01 +0000391 Opt.Commands.push_back(llvm::make_unique<OutputSectionCommand>(Name));
George Rimar652852c2016-04-16 10:10:32 +0000392 }
George Rimar652852c2016-04-16 10:10:32 +0000393
Rui Ueyama7c18c282016-04-18 21:00:40 +0000394 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rui Ueyama4f7500b2016-08-12 04:00:22 +0000395 Dot = getHeaderSize();
Eugene Leviant467c4d52016-07-01 10:27:36 +0000396 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
George Rimar652852c2016-04-16 10:10:32 +0000397 uintX_t ThreadBssOffset = 0;
George Rimar652852c2016-04-16 10:10:32 +0000398
George Rimar076fe152016-07-21 06:43:01 +0000399 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
400 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
Rui Ueyama8d083e62016-07-29 05:48:39 +0000401 if (Cmd->Name == ".") {
402 Dot = Cmd->Expression(Dot);
403 } else if (Cmd->Sym) {
404 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(Dot);
405 }
George Rimar652852c2016-04-16 10:10:32 +0000406 continue;
407 }
408
George Rimareefa7582016-08-04 09:29:31 +0000409 if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
410 Cmd->Expression(Dot);
411 continue;
412 }
413
George Rimar076fe152016-07-21 06:43:01 +0000414 auto *Cmd = cast<OutputSectionCommand>(Base.get());
George Rimara14b13d2016-09-07 10:46:07 +0000415 for (OutputSectionBase<ELFT> *Sec :
416 findSections<ELFT>(*Cmd, *OutputSections)) {
George Rimar652852c2016-04-16 10:10:32 +0000417
George Rimara14b13d2016-09-07 10:46:07 +0000418 if (Cmd->AddrExpr)
419 Dot = Cmd->AddrExpr(Dot);
George Rimar58e5c4d2016-07-25 08:29:46 +0000420
George Rimara14b13d2016-09-07 10:46:07 +0000421 if (Cmd->AlignExpr)
422 Sec->updateAlignment(Cmd->AlignExpr(Dot));
George Rimar630c6172016-07-26 18:06:29 +0000423
George Rimara14b13d2016-09-07 10:46:07 +0000424 if ((Sec->getFlags() & SHF_TLS) && Sec->getType() == SHT_NOBITS) {
425 uintX_t TVA = Dot + ThreadBssOffset;
426 TVA = alignTo(TVA, Sec->getAlignment());
427 Sec->setVA(TVA);
428 assignOffsets(Cmd, Sec);
429 ThreadBssOffset = TVA - Dot + Sec->getSize();
430 continue;
431 }
432
433 if (!(Sec->getFlags() & SHF_ALLOC)) {
434 assignOffsets(Cmd, Sec);
435 continue;
436 }
437
438 Dot = alignTo(Dot, Sec->getAlignment());
439 Sec->setVA(Dot);
Eugene Leviant20889c52016-08-31 08:13:33 +0000440 assignOffsets(Cmd, Sec);
George Rimara14b13d2016-09-07 10:46:07 +0000441 MinVA = std::min(MinVA, Dot);
442 Dot += Sec->getSize();
George Rimar652852c2016-04-16 10:10:32 +0000443 }
444 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000445
Rafael Espindola64c32d62016-07-07 14:28:47 +0000446 // ELF and Program headers need to be right before the first section in
George Rimarb91e7112016-07-19 07:42:07 +0000447 // memory. Set their addresses accordingly.
Eugene Leviant467c4d52016-07-01 10:27:36 +0000448 MinVA = alignDown(MinVA - Out<ELFT>::ElfHeader->getSize() -
449 Out<ELFT>::ProgramHeaders->getSize(),
450 Target->PageSize);
451 Out<ELFT>::ElfHeader->setVA(MinVA);
452 Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
George Rimar652852c2016-04-16 10:10:32 +0000453}
454
Rui Ueyama464daad2016-08-22 04:55:20 +0000455// Creates program headers as instructed by PHDRS linker script command.
Rui Ueyama07320e42016-04-20 20:13:41 +0000456template <class ELFT>
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000457std::vector<PhdrEntry<ELFT>> LinkerScript<ELFT>::createPhdrs() {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000458 std::vector<PhdrEntry<ELFT>> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000459
Rui Ueyama464daad2016-08-22 04:55:20 +0000460 // Process PHDRS and FILEHDR keywords because they are not
461 // real output sections and cannot be added in the following loop.
Eugene Leviantbbe38602016-07-19 09:25:43 +0000462 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000463 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
464 PhdrEntry<ELFT> &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000465
466 if (Cmd.HasFilehdr)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000467 Phdr.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000468 if (Cmd.HasPhdrs)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000469 Phdr.add(Out<ELFT>::ProgramHeaders);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000470 }
471
Rui Ueyama464daad2016-08-22 04:55:20 +0000472 // Add output sections to program headers.
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000473 PhdrEntry<ELFT> *Load = nullptr;
474 uintX_t Flags = PF_R;
Rui Ueyama464daad2016-08-22 04:55:20 +0000475 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
Eugene Leviantbbe38602016-07-19 09:25:43 +0000476 if (!(Sec->getFlags() & SHF_ALLOC))
477 break;
478
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000479 std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName());
Eugene Leviantbbe38602016-07-19 09:25:43 +0000480 if (!PhdrIds.empty()) {
481 // Assign headers specified by linker script
482 for (size_t Id : PhdrIds) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000483 Ret[Id].add(Sec);
Eugene Leviant865bf862016-07-21 10:43:25 +0000484 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
Rafael Espindola0b113672016-07-27 14:10:56 +0000485 Ret[Id].H.p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000486 }
487 } else {
488 // If we have no load segment or flags've changed then we want new load
489 // segment.
Rafael Espindola0b113672016-07-27 14:10:56 +0000490 uintX_t NewFlags = Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000491 if (Load == nullptr || Flags != NewFlags) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000492 Load = &*Ret.emplace(Ret.end(), PT_LOAD, NewFlags);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000493 Flags = NewFlags;
494 }
Rui Ueyama18f084f2016-07-20 19:36:41 +0000495 Load->add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000496 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000497 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000498 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000499}
500
Eugene Leviantf9bc3bd2016-08-16 06:40:58 +0000501template <class ELFT> bool LinkerScript<ELFT>::ignoreInterpSection() {
502 // Ignore .interp section in case we have PHDRS specification
503 // and PT_INTERP isn't listed.
504 return !Opt.PhdrsCommands.empty() &&
505 llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
506 return Cmd.Type == PT_INTERP;
507 }) == Opt.PhdrsCommands.end();
508}
509
Eugene Leviantbbe38602016-07-19 09:25:43 +0000510template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000511ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000512 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
513 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
514 if (Cmd->Name == Name)
515 return Cmd->Filler;
516 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000517}
518
George Rimar206fffa2016-08-17 08:16:57 +0000519template <class ELFT> Expr LinkerScript<ELFT>::getLma(StringRef Name) {
George Rimar8ceadb32016-08-17 07:44:19 +0000520 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
521 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
522 if (Cmd->LmaExpr && Cmd->Name == Name)
523 return Cmd->LmaExpr;
524 return {};
525}
526
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000527// Returns the index of the given section name in linker script
528// SECTIONS commands. Sections are laid out as the same order as they
529// were in the script. If a given name did not appear in the script,
530// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000531template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000532 int I = 0;
533 for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
534 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
535 if (Cmd->Name == Name)
536 return I;
537 ++I;
538 }
539 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000540}
541
542// A compartor to sort output sections. Returns -1 or 1 if
543// A or B are mentioned in linker script. Otherwise, returns 0.
Rui Ueyama07320e42016-04-20 20:13:41 +0000544template <class ELFT>
545int LinkerScript<ELFT>::compareSections(StringRef A, StringRef B) {
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000546 int I = getSectionIndex(A);
547 int J = getSectionIndex(B);
548 if (I == INT_MAX && J == INT_MAX)
Rui Ueyama717677a2016-02-11 21:17:59 +0000549 return 0;
550 return I < J ? -1 : 1;
551}
552
Eugene Leviantbbe38602016-07-19 09:25:43 +0000553template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
554 return !Opt.PhdrsCommands.empty();
555}
556
George Rimar9e694502016-07-29 16:18:47 +0000557template <class ELFT>
George Rimar884e7862016-09-08 08:19:13 +0000558uint64_t LinkerScript<ELFT>::getOutputSectionAddress(StringRef Name) {
George Rimar96659df2016-08-30 09:54:01 +0000559 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
560 if (Sec->getName() == Name)
561 return Sec->getVA();
562 error("undefined section " + Name);
563 return 0;
564}
565
566template <class ELFT>
George Rimar884e7862016-09-08 08:19:13 +0000567uint64_t LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
George Rimar9e694502016-07-29 16:18:47 +0000568 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
569 if (Sec->getName() == Name)
570 return Sec->getSize();
571 error("undefined section " + Name);
572 return 0;
573}
574
Eugene Leviant36fac7f2016-09-08 09:08:30 +0000575template <class ELFT>
576uint64_t LinkerScript<ELFT>::getOutputSectionAlign(StringRef Name) {
577 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
578 if (Sec->getName() == Name)
579 return Sec->getAlignment();
580 error("undefined section " + Name);
581 return 0;
582}
583
George Rimar884e7862016-09-08 08:19:13 +0000584template <class ELFT> uint64_t LinkerScript<ELFT>::getHeaderSize() {
George Rimare32a3592016-08-10 07:59:34 +0000585 return Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
586}
587
George Rimar884e7862016-09-08 08:19:13 +0000588template <class ELFT> uint64_t LinkerScript<ELFT>::getSymbolValue(StringRef S) {
589 if (SymbolBody *B = Symtab<ELFT>::X->find(S))
590 return B->getVA<ELFT>();
591 error("symbol not found: " + S);
592 return 0;
593}
594
Eugene Leviantbbe38602016-07-19 09:25:43 +0000595// Returns indices of ELF headers containing specific section, identified
596// by Name. Each index is a zero based number of ELF header listed within
597// PHDRS {} script block.
598template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000599std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000600 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
601 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000602 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000603 continue;
604
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000605 std::vector<size_t> Ret;
606 for (StringRef PhdrName : Cmd->Phdrs)
607 Ret.push_back(getPhdrIndex(PhdrName));
608 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000609 }
George Rimar31d842f2016-07-20 16:43:03 +0000610 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000611}
612
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000613template <class ELFT>
614size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
615 size_t I = 0;
616 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
617 if (Cmd.Name == PhdrName)
618 return I;
619 ++I;
620 }
621 error("section header '" + PhdrName + "' is not listed in PHDRS");
622 return 0;
623}
624
Rui Ueyama07320e42016-04-20 20:13:41 +0000625class elf::ScriptParser : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000626 typedef void (ScriptParser::*Handler)();
627
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000628public:
Rui Ueyama07320e42016-04-20 20:13:41 +0000629 ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
George Rimarf23b2322016-02-19 10:45:45 +0000630
George Rimar20b65982016-08-31 09:08:26 +0000631 void readLinkerScript();
632 void readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000633
634private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000635 void addFile(StringRef Path);
636
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000637 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000638 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000639 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000640 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000641 void readInclude();
Rui Ueyamaee592822015-10-07 00:25:09 +0000642 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000643 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000644 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000645 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000646 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000647 void readSections();
Rui Ueyama95769b42016-08-31 20:03:54 +0000648 void readVersion();
649 void readVersionScriptCommand();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000650
Rui Ueyama113cdec2016-07-24 23:05:57 +0000651 SymbolAssignment *readAssignment(StringRef Name);
George Rimarff1f29e2016-09-06 13:51:57 +0000652 std::vector<uint8_t> readFill();
Rui Ueyama10416562016-08-04 02:03:27 +0000653 OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
George Rimarff1f29e2016-09-06 13:51:57 +0000654 std::vector<uint8_t> readOutputSectionFiller(StringRef Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000655 std::vector<StringRef> readOutputSectionPhdrs();
George Rimara2496cb2016-08-30 09:46:59 +0000656 InputSectionDescription *readInputSectionDescription(StringRef Tok);
George Rimarc91930a2016-09-02 21:17:20 +0000657 Regex readFilePatterns();
George Rimara2496cb2016-08-30 09:46:59 +0000658 InputSectionDescription *readInputSectionRules(StringRef FilePattern);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000659 unsigned readPhdrType();
Rui Ueyama742c3832016-08-04 22:27:00 +0000660 SortKind readSortKind();
Petr Hoseka35e39c2016-08-16 01:11:16 +0000661 SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
Eugene Leviantdb741e72016-09-07 07:08:43 +0000662 SymbolAssignment *readProvideOrAssignment(StringRef Tok, bool MakeAbsolute);
George Rimar03fc0102016-07-28 07:18:23 +0000663 void readSort();
George Rimareefa7582016-08-04 09:29:31 +0000664 Expr readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +0000665
666 Expr readExpr();
667 Expr readExpr1(Expr Lhs, int MinPrec);
668 Expr readPrimary();
669 Expr readTernary(Expr Cond);
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +0000670 Expr readParenExpr();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000671
George Rimar20b65982016-08-31 09:08:26 +0000672 // For parsing version script.
673 void readExtern(std::vector<SymbolVersion> *Globals);
Rui Ueyama95769b42016-08-31 20:03:54 +0000674 void readVersionDeclaration(StringRef VerStr);
George Rimar20b65982016-08-31 09:08:26 +0000675 void readGlobal(StringRef VerStr);
676 void readLocal();
677
Rui Ueyama07320e42016-04-20 20:13:41 +0000678 ScriptConfiguration &Opt = *ScriptConfig;
679 StringSaver Saver = {ScriptConfig->Alloc};
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000680 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000681};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000682
George Rimar20b65982016-08-31 09:08:26 +0000683void ScriptParser::readVersionScript() {
Rui Ueyama95769b42016-08-31 20:03:54 +0000684 readVersionScriptCommand();
685 if (!atEOF())
686 setError("EOF expected, but got " + next());
687}
688
689void ScriptParser::readVersionScriptCommand() {
George Rimar20b65982016-08-31 09:08:26 +0000690 if (skip("{")) {
Rui Ueyama95769b42016-08-31 20:03:54 +0000691 readVersionDeclaration("");
George Rimar20b65982016-08-31 09:08:26 +0000692 return;
693 }
694
Rui Ueyama95769b42016-08-31 20:03:54 +0000695 while (!atEOF() && !Error && peek() != "}") {
George Rimar20b65982016-08-31 09:08:26 +0000696 StringRef VerStr = next();
697 if (VerStr == "{") {
Rui Ueyama95769b42016-08-31 20:03:54 +0000698 setError("anonymous version definition is used in "
699 "combination with other version definitions");
George Rimar20b65982016-08-31 09:08:26 +0000700 return;
701 }
702 expect("{");
Rui Ueyama95769b42016-08-31 20:03:54 +0000703 readVersionDeclaration(VerStr);
George Rimar20b65982016-08-31 09:08:26 +0000704 }
705}
706
Rui Ueyama95769b42016-08-31 20:03:54 +0000707void ScriptParser::readVersion() {
708 expect("{");
709 readVersionScriptCommand();
710 expect("}");
711}
712
George Rimar20b65982016-08-31 09:08:26 +0000713void ScriptParser::readLinkerScript() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000714 while (!atEOF()) {
715 StringRef Tok = next();
Rui Ueyamaa27eecc2016-09-02 18:52:41 +0000716 if (Tok == ";")
717 continue;
718
719 if (Tok == "ENTRY") {
720 readEntry();
721 } else if (Tok == "EXTERN") {
722 readExtern();
723 } else if (Tok == "GROUP" || Tok == "INPUT") {
724 readGroup();
725 } else if (Tok == "INCLUDE") {
726 readInclude();
727 } else if (Tok == "OUTPUT") {
728 readOutput();
729 } else if (Tok == "OUTPUT_ARCH") {
730 readOutputArch();
731 } else if (Tok == "OUTPUT_FORMAT") {
732 readOutputFormat();
733 } else if (Tok == "PHDRS") {
734 readPhdrs();
735 } else if (Tok == "SEARCH_DIR") {
736 readSearchDir();
737 } else if (Tok == "SECTIONS") {
738 readSections();
739 } else if (Tok == "VERSION") {
740 readVersion();
Eugene Leviantdb741e72016-09-07 07:08:43 +0000741 } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok, true)) {
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000742 if (Opt.HasContents)
743 Opt.Commands.emplace_back(Cmd);
744 else
745 Opt.Assignments.emplace_back(Cmd);
746 } else {
George Rimar57610422016-03-11 14:43:02 +0000747 setError("unknown directive: " + Tok);
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000748 }
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000749 }
750}
751
Rui Ueyama717677a2016-02-11 21:17:59 +0000752void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000753 if (IsUnderSysroot && S.startswith("/")) {
754 SmallString<128> Path;
755 (Config->Sysroot + S).toStringRef(Path);
756 if (sys::fs::exists(Path)) {
757 Driver->addFile(Saver.save(Path.str()));
758 return;
759 }
760 }
761
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +0000762 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +0000763 Driver->addFile(S);
764 } else if (S.startswith("=")) {
765 if (Config->Sysroot.empty())
766 Driver->addFile(S.substr(1));
767 else
768 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
769 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +0000770 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +0000771 } else if (sys::fs::exists(S)) {
772 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +0000773 } else {
774 std::string Path = findFromSearchPaths(S);
775 if (Path.empty())
George Rimar777f9632016-03-12 08:31:34 +0000776 setError("unable to find " + S);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000777 else
778 Driver->addFile(Saver.save(Path));
Rui Ueyama52a15092015-10-11 03:28:42 +0000779 }
780}
781
Rui Ueyama717677a2016-02-11 21:17:59 +0000782void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000783 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +0000784 bool Orig = Config->AsNeeded;
785 Config->AsNeeded = true;
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000786 while (!Error && !skip(")"))
787 addFile(next());
Rui Ueyama35da9b62015-10-11 20:59:12 +0000788 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000789}
790
Rui Ueyama717677a2016-02-11 21:17:59 +0000791void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +0000792 // -e <symbol> takes predecence over ENTRY(<symbol>).
793 expect("(");
794 StringRef Tok = next();
795 if (Config->Entry.empty())
796 Config->Entry = Tok;
797 expect(")");
798}
799
Rui Ueyama717677a2016-02-11 21:17:59 +0000800void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +0000801 expect("(");
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000802 while (!Error && !skip(")"))
803 Config->Undefined.push_back(next());
George Rimar83f406c2015-10-19 17:35:12 +0000804}
805
Rui Ueyama717677a2016-02-11 21:17:59 +0000806void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000807 expect("(");
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000808 while (!Error && !skip(")")) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000809 StringRef Tok = next();
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000810 if (Tok == "AS_NEEDED")
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000811 readAsNeeded();
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000812 else
813 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000814 }
815}
816
Rui Ueyama717677a2016-02-11 21:17:59 +0000817void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000818 StringRef Tok = next();
819 auto MBOrErr = MemoryBuffer::getFile(Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000820 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +0000821 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000822 return;
823 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000824 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Rui Ueyamaa47ee682015-10-11 01:53:04 +0000825 StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
826 std::vector<StringRef> V = tokenize(S);
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000827 Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000828}
829
Rui Ueyama717677a2016-02-11 21:17:59 +0000830void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +0000831 // -o <file> takes predecence over OUTPUT(<file>).
832 expect("(");
833 StringRef Tok = next();
834 if (Config->OutputFile.empty())
835 Config->OutputFile = Tok;
836 expect(")");
837}
838
Rui Ueyama717677a2016-02-11 21:17:59 +0000839void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +0000840 // Error checking only for now.
841 expect("(");
842 next();
843 expect(")");
844}
845
Rui Ueyama717677a2016-02-11 21:17:59 +0000846void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000847 // Error checking only for now.
848 expect("(");
849 next();
Davide Italiano6836c612015-10-12 21:08:41 +0000850 StringRef Tok = next();
851 if (Tok == ")")
George Rimar6c55f0e2016-09-08 08:20:30 +0000852 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000853 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +0000854 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000855 return;
856 }
Davide Italiano6836c612015-10-12 21:08:41 +0000857 next();
858 expect(",");
859 next();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000860 expect(")");
861}
862
Eugene Leviantbbe38602016-07-19 09:25:43 +0000863void ScriptParser::readPhdrs() {
864 expect("{");
865 while (!Error && !skip("}")) {
866 StringRef Tok = next();
Eugene Leviant865bf862016-07-21 10:43:25 +0000867 Opt.PhdrsCommands.push_back({Tok, PT_NULL, false, false, UINT_MAX});
Eugene Leviantbbe38602016-07-19 09:25:43 +0000868 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
869
870 PhdrCmd.Type = readPhdrType();
871 do {
872 Tok = next();
873 if (Tok == ";")
874 break;
875 if (Tok == "FILEHDR")
876 PhdrCmd.HasFilehdr = true;
877 else if (Tok == "PHDRS")
878 PhdrCmd.HasPhdrs = true;
Eugene Leviant865bf862016-07-21 10:43:25 +0000879 else if (Tok == "FLAGS") {
880 expect("(");
Rafael Espindolaeb685cd2016-08-02 22:14:57 +0000881 // Passing 0 for the value of dot is a bit of a hack. It means that
882 // we accept expressions like ".|1".
883 PhdrCmd.Flags = readExpr()(0);
Eugene Leviant865bf862016-07-21 10:43:25 +0000884 expect(")");
885 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +0000886 setError("unexpected header attribute: " + Tok);
887 } while (!Error);
888 }
889}
890
Rui Ueyama717677a2016-02-11 21:17:59 +0000891void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +0000892 expect("(");
Rui Ueyama6c7ad132016-09-02 19:20:33 +0000893 if (!Config->Nostdlib)
894 Config->SearchPaths.push_back(next());
Davide Italiano68a39a62015-10-08 17:51:41 +0000895 expect(")");
896}
897
Rui Ueyama717677a2016-02-11 21:17:59 +0000898void ScriptParser::readSections() {
Rui Ueyama3de0a332016-07-29 03:31:09 +0000899 Opt.HasContents = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000900 expect("{");
George Rimar652852c2016-04-16 10:10:32 +0000901 while (!Error && !skip("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +0000902 StringRef Tok = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +0000903 BaseCommand *Cmd = readProvideOrAssignment(Tok, true);
Eugene Leviantceabe802016-08-11 07:56:43 +0000904 if (!Cmd) {
905 if (Tok == "ASSERT")
906 Cmd = new AssertCommand(readAssert());
907 else
908 Cmd = readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +0000909 }
Rui Ueyama10416562016-08-04 02:03:27 +0000910 Opt.Commands.emplace_back(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000911 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000912}
913
Rui Ueyama708019c2016-07-24 18:19:40 +0000914static int precedence(StringRef Op) {
915 return StringSwitch<int>(Op)
916 .Case("*", 4)
917 .Case("/", 4)
918 .Case("+", 3)
919 .Case("-", 3)
920 .Case("<", 2)
921 .Case(">", 2)
922 .Case(">=", 2)
923 .Case("<=", 2)
924 .Case("==", 2)
925 .Case("!=", 2)
926 .Case("&", 1)
Rafael Espindolacc3dd622016-08-22 21:33:35 +0000927 .Case("|", 1)
Rui Ueyama708019c2016-07-24 18:19:40 +0000928 .Default(-1);
929}
930
George Rimarc91930a2016-09-02 21:17:20 +0000931Regex ScriptParser::readFilePatterns() {
Rui Ueyama10416562016-08-04 02:03:27 +0000932 std::vector<StringRef> V;
933 while (!Error && !skip(")"))
934 V.push_back(next());
George Rimarc91930a2016-09-02 21:17:20 +0000935 return compileGlobPatterns(V);
George Rimar0702c4e2016-07-29 15:32:46 +0000936}
937
Rui Ueyama742c3832016-08-04 22:27:00 +0000938SortKind ScriptParser::readSortKind() {
939 if (skip("SORT") || skip("SORT_BY_NAME"))
940 return SortByName;
941 if (skip("SORT_BY_ALIGNMENT"))
942 return SortByAlignment;
943 return SortNone;
944}
945
George Rimara2496cb2016-08-30 09:46:59 +0000946InputSectionDescription *
947ScriptParser::readInputSectionRules(StringRef FilePattern) {
George Rimarc91930a2016-09-02 21:17:20 +0000948 auto *Cmd = new InputSectionDescription(FilePattern);
Davide Italiano0ed42b02016-07-25 21:47:13 +0000949 expect("(");
Davide Italianoe7282792016-07-27 01:44:01 +0000950
Rui Ueyama742c3832016-08-04 22:27:00 +0000951 // Read EXCLUDE_FILE().
Davide Italianoe7282792016-07-27 01:44:01 +0000952 if (skip("EXCLUDE_FILE")) {
953 expect("(");
George Rimarc91930a2016-09-02 21:17:20 +0000954 Cmd->ExcludedFileRe = readFilePatterns();
Davide Italiano0ed42b02016-07-25 21:47:13 +0000955 }
George Rimar06598002016-07-28 21:51:30 +0000956
Rui Ueyama742c3832016-08-04 22:27:00 +0000957 // Read SORT().
958 if (SortKind K1 = readSortKind()) {
959 Cmd->SortOuter = K1;
George Rimar0702c4e2016-07-29 15:32:46 +0000960 expect("(");
Rui Ueyama742c3832016-08-04 22:27:00 +0000961 if (SortKind K2 = readSortKind()) {
962 Cmd->SortInner = K2;
George Rimar350ece42016-08-03 08:35:59 +0000963 expect("(");
George Rimarc91930a2016-09-02 21:17:20 +0000964 Cmd->SectionRe = readFilePatterns();
George Rimar350ece42016-08-03 08:35:59 +0000965 expect(")");
966 } else {
George Rimarc91930a2016-09-02 21:17:20 +0000967 Cmd->SectionRe = readFilePatterns();
George Rimar350ece42016-08-03 08:35:59 +0000968 }
George Rimar0702c4e2016-07-29 15:32:46 +0000969 expect(")");
Rui Ueyama10416562016-08-04 02:03:27 +0000970 return Cmd;
George Rimar06598002016-07-28 21:51:30 +0000971 }
George Rimar0702c4e2016-07-29 15:32:46 +0000972
George Rimarc91930a2016-09-02 21:17:20 +0000973 Cmd->SectionRe = readFilePatterns();
Rui Ueyama10416562016-08-04 02:03:27 +0000974 return Cmd;
Davide Italianoe7282792016-07-27 01:44:01 +0000975}
976
George Rimara2496cb2016-08-30 09:46:59 +0000977InputSectionDescription *
978ScriptParser::readInputSectionDescription(StringRef Tok) {
George Rimar06598002016-07-28 21:51:30 +0000979 // Input section wildcard can be surrounded by KEEP.
980 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
George Rimara2496cb2016-08-30 09:46:59 +0000981 if (Tok == "KEEP") {
George Rimar06598002016-07-28 21:51:30 +0000982 expect("(");
George Rimara2496cb2016-08-30 09:46:59 +0000983 StringRef FilePattern = next();
984 InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
George Rimar06598002016-07-28 21:51:30 +0000985 expect(")");
George Rimarc91930a2016-09-02 21:17:20 +0000986 Opt.KeptSections.push_back(&Cmd->SectionRe);
Rui Ueyama10416562016-08-04 02:03:27 +0000987 return Cmd;
George Rimar06598002016-07-28 21:51:30 +0000988 }
George Rimara2496cb2016-08-30 09:46:59 +0000989 return readInputSectionRules(Tok);
Davide Italiano0ed42b02016-07-25 21:47:13 +0000990}
991
George Rimar03fc0102016-07-28 07:18:23 +0000992void ScriptParser::readSort() {
993 expect("(");
994 expect("CONSTRUCTORS");
995 expect(")");
996}
997
George Rimareefa7582016-08-04 09:29:31 +0000998Expr ScriptParser::readAssert() {
999 expect("(");
1000 Expr E = readExpr();
1001 expect(",");
1002 StringRef Msg = next();
1003 expect(")");
1004 return [=](uint64_t Dot) {
1005 uint64_t V = E(Dot);
1006 if (!V)
1007 error(Msg);
1008 return V;
1009 };
1010}
1011
Rui Ueyama25150e82016-09-06 17:46:43 +00001012// Reads a FILL(expr) command. We handle the FILL command as an
1013// alias for =fillexp section attribute, which is different from
1014// what GNU linkers do.
1015// https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
George Rimarff1f29e2016-09-06 13:51:57 +00001016std::vector<uint8_t> ScriptParser::readFill() {
1017 expect("(");
1018 std::vector<uint8_t> V = readOutputSectionFiller(next());
1019 expect(")");
1020 expect(";");
1021 return V;
1022}
1023
Rui Ueyama10416562016-08-04 02:03:27 +00001024OutputSectionCommand *
1025ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +00001026 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
George Rimar58e5c4d2016-07-25 08:29:46 +00001027
1028 // Read an address expression.
1029 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
1030 if (peek() != ":")
1031 Cmd->AddrExpr = readExpr();
1032
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001033 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +00001034
George Rimar8ceadb32016-08-17 07:44:19 +00001035 if (skip("AT"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001036 Cmd->LmaExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001037 if (skip("ALIGN"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001038 Cmd->AlignExpr = readParenExpr();
George Rimardb24d9c2016-08-19 15:18:23 +00001039 if (skip("SUBALIGN"))
1040 Cmd->SubalignExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001041
Davide Italiano246f6812016-07-22 03:36:24 +00001042 // Parse constraints.
1043 if (skip("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001044 Cmd->Constraint = ConstraintKind::ReadOnly;
Davide Italiano246f6812016-07-22 03:36:24 +00001045 if (skip("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001046 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001047 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001048
Rui Ueyama025d59b2016-02-02 20:27:59 +00001049 while (!Error && !skip("}")) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001050 StringRef Tok = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +00001051 if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok, false))
Eugene Leviantceabe802016-08-11 07:56:43 +00001052 Cmd->Commands.emplace_back(Assignment);
George Rimarff1f29e2016-09-06 13:51:57 +00001053 else if (Tok == "FILL")
1054 Cmd->Filler = readFill();
Eugene Leviantceabe802016-08-11 07:56:43 +00001055 else if (Tok == "SORT")
George Rimar03fc0102016-07-28 07:18:23 +00001056 readSort();
George Rimara2496cb2016-08-30 09:46:59 +00001057 else if (peek() == "(")
1058 Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
Eugene Leviantceabe802016-08-11 07:56:43 +00001059 else
1060 setError("unknown command " + Tok);
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001061 }
George Rimar076fe152016-07-21 06:43:01 +00001062 Cmd->Phdrs = readOutputSectionPhdrs();
George Rimarff1f29e2016-09-06 13:51:57 +00001063 if (peek().startswith("="))
1064 Cmd->Filler = readOutputSectionFiller(next().drop_front());
Rui Ueyama10416562016-08-04 02:03:27 +00001065 return Cmd;
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001066}
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001067
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001068// Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
1069// https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
1070//
1071// ld.gold is not fully compatible with ld.bfd. ld.bfd handles
1072// hexstrings as blobs of arbitrary sizes, while ld.gold handles them
1073// as 32-bit big-endian values. We will do the same as ld.gold does
1074// because it's simpler than what ld.bfd does.
George Rimarff1f29e2016-09-06 13:51:57 +00001075std::vector<uint8_t> ScriptParser::readOutputSectionFiller(StringRef Tok) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001076 uint32_t V;
George Rimarff1f29e2016-09-06 13:51:57 +00001077 if (Tok.getAsInteger(0, V)) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001078 setError("invalid filler expression: " + Tok);
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001079 return {};
George Rimare2ee72b2016-02-26 14:48:31 +00001080 }
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001081 return {uint8_t(V >> 24), uint8_t(V >> 16), uint8_t(V >> 8), uint8_t(V)};
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001082}
1083
Petr Hoseka35e39c2016-08-16 01:11:16 +00001084SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
Eugene Levianta31c91b2016-07-22 07:38:40 +00001085 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +00001086 SymbolAssignment *Cmd = readAssignment(next());
Petr Hoseka35e39c2016-08-16 01:11:16 +00001087 Cmd->Provide = Provide;
Rui Ueyama174e0a12016-07-29 00:29:25 +00001088 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001089 expect(")");
1090 expect(";");
Rui Ueyama10416562016-08-04 02:03:27 +00001091 return Cmd;
Eugene Levianteda81a12016-07-12 06:39:48 +00001092}
1093
Eugene Leviantdb741e72016-09-07 07:08:43 +00001094SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok,
1095 bool MakeAbsolute) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001096 SymbolAssignment *Cmd = nullptr;
1097 if (peek() == "=" || peek() == "+=") {
1098 Cmd = readAssignment(Tok);
1099 expect(";");
1100 } else if (Tok == "PROVIDE") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001101 Cmd = readProvideHidden(true, false);
1102 } else if (Tok == "HIDDEN") {
1103 Cmd = readProvideHidden(false, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001104 } else if (Tok == "PROVIDE_HIDDEN") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001105 Cmd = readProvideHidden(true, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001106 }
Eugene Leviantdb741e72016-09-07 07:08:43 +00001107 if (Cmd && MakeAbsolute)
1108 Cmd->IsAbsolute = true;
Eugene Leviantceabe802016-08-11 07:56:43 +00001109 return Cmd;
1110}
1111
George Rimar30835ea2016-07-28 21:08:56 +00001112static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
1113 if (S == ".")
1114 return Dot;
George Rimar884e7862016-09-08 08:19:13 +00001115 return ScriptBase->getSymbolValue(S);
George Rimare32a3592016-08-10 07:59:34 +00001116}
1117
George Rimar30835ea2016-07-28 21:08:56 +00001118SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1119 StringRef Op = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +00001120 bool IsAbsolute = false;
1121 Expr E;
George Rimar30835ea2016-07-28 21:08:56 +00001122 assert(Op == "=" || Op == "+=");
Eugene Leviantdb741e72016-09-07 07:08:43 +00001123 if (skip("ABSOLUTE")) {
1124 E = readParenExpr();
1125 IsAbsolute = true;
1126 } else {
1127 E = readExpr();
1128 }
George Rimar30835ea2016-07-28 21:08:56 +00001129 if (Op == "+=")
1130 E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
Eugene Leviantdb741e72016-09-07 07:08:43 +00001131 return new SymbolAssignment(Name, E, IsAbsolute);
George Rimar30835ea2016-07-28 21:08:56 +00001132}
1133
1134// This is an operator-precedence parser to parse a linker
1135// script expression.
1136Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
1137
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001138static Expr combine(StringRef Op, Expr L, Expr R) {
1139 if (Op == "*")
1140 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1141 if (Op == "/") {
1142 return [=](uint64_t Dot) -> uint64_t {
1143 uint64_t RHS = R(Dot);
1144 if (RHS == 0) {
1145 error("division by zero");
1146 return 0;
1147 }
1148 return L(Dot) / RHS;
1149 };
1150 }
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); };
1165 if (Op == "!=")
1166 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
1167 if (Op == "&")
1168 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
Rafael Espindolacc3dd622016-08-22 21:33:35 +00001169 if (Op == "|")
1170 return [=](uint64_t Dot) { return L(Dot) | R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001171 llvm_unreachable("invalid operator");
1172}
1173
Rui Ueyama708019c2016-07-24 18:19:40 +00001174// This is a part of the operator-precedence parser. This function
1175// assumes that the remaining token stream starts with an operator.
1176Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1177 while (!atEOF() && !Error) {
1178 // Read an operator and an expression.
1179 StringRef Op1 = peek();
1180 if (Op1 == "?")
1181 return readTernary(Lhs);
1182 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +00001183 break;
Rui Ueyama708019c2016-07-24 18:19:40 +00001184 next();
1185 Expr Rhs = readPrimary();
1186
1187 // Evaluate the remaining part of the expression first if the
1188 // next operator has greater precedence than the previous one.
1189 // For example, if we have read "+" and "3", and if the next
1190 // operator is "*", then we'll evaluate 3 * ... part first.
1191 while (!atEOF()) {
1192 StringRef Op2 = peek();
1193 if (precedence(Op2) <= precedence(Op1))
1194 break;
1195 Rhs = readExpr1(Rhs, precedence(Op2));
1196 }
1197
1198 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +00001199 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001200 return Lhs;
1201}
1202
1203uint64_t static getConstant(StringRef S) {
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001204 if (S == "COMMONPAGESIZE")
Rui Ueyama708019c2016-07-24 18:19:40 +00001205 return Target->PageSize;
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001206 if (S == "MAXPAGESIZE")
1207 return Target->MaxPageSize;
Rui Ueyama708019c2016-07-24 18:19:40 +00001208 error("unknown constant: " + S);
1209 return 0;
1210}
1211
Rui Ueyama626e0b02016-09-02 18:19:00 +00001212// Parses Tok as an integer. Returns true if successful.
1213// It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1214// and decimal numbers. Decimal numbers may have "K" (kilo) or
1215// "M" (mega) prefixes.
George Rimar9f2f7ad2016-09-02 16:01:42 +00001216static bool readInteger(StringRef Tok, uint64_t &Result) {
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001217 if (Tok.startswith("-")) {
1218 if (!readInteger(Tok.substr(1), Result))
1219 return false;
1220 Result = -Result;
1221 return true;
1222 }
George Rimar9f2f7ad2016-09-02 16:01:42 +00001223 if (Tok.startswith_lower("0x"))
1224 return !Tok.substr(2).getAsInteger(16, Result);
1225 if (Tok.endswith_lower("H"))
1226 return !Tok.drop_back().getAsInteger(16, Result);
1227
1228 int Suffix = 1;
1229 if (Tok.endswith_lower("K")) {
1230 Suffix = 1024;
1231 Tok = Tok.drop_back();
1232 } else if (Tok.endswith_lower("M")) {
1233 Suffix = 1024 * 1024;
1234 Tok = Tok.drop_back();
1235 }
1236 if (Tok.getAsInteger(10, Result))
1237 return false;
1238 Result *= Suffix;
1239 return true;
1240}
1241
Rui Ueyama708019c2016-07-24 18:19:40 +00001242Expr ScriptParser::readPrimary() {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001243 if (peek() == "(")
1244 return readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001245
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001246 StringRef Tok = next();
Rui Ueyama708019c2016-07-24 18:19:40 +00001247
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001248 if (Tok == "~") {
1249 Expr E = readPrimary();
1250 return [=](uint64_t Dot) { return ~E(Dot); };
1251 }
1252 if (Tok == "-") {
1253 Expr E = readPrimary();
1254 return [=](uint64_t Dot) { return -E(Dot); };
1255 }
1256
Rui Ueyama708019c2016-07-24 18:19:40 +00001257 // Built-in functions are parsed here.
1258 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
George Rimar96659df2016-08-30 09:54:01 +00001259 if (Tok == "ADDR") {
1260 expect("(");
1261 StringRef Name = next();
1262 expect(")");
George Rimar884e7862016-09-08 08:19:13 +00001263 return
1264 [=](uint64_t Dot) { return ScriptBase->getOutputSectionAddress(Name); };
George Rimar96659df2016-08-30 09:54:01 +00001265 }
George Rimareefa7582016-08-04 09:29:31 +00001266 if (Tok == "ASSERT")
1267 return readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001268 if (Tok == "ALIGN") {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001269 Expr E = readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001270 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1271 }
1272 if (Tok == "CONSTANT") {
1273 expect("(");
1274 StringRef Tok = next();
1275 expect(")");
1276 return [=](uint64_t Dot) { return getConstant(Tok); };
1277 }
Rafael Espindola54c145c2016-07-28 18:16:24 +00001278 if (Tok == "SEGMENT_START") {
1279 expect("(");
1280 next();
1281 expect(",");
1282 uint64_t Val;
1283 next().getAsInteger(0, Val);
1284 expect(")");
1285 return [=](uint64_t Dot) { return Val; };
1286 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001287 if (Tok == "DATA_SEGMENT_ALIGN") {
1288 expect("(");
1289 Expr E = readExpr();
1290 expect(",");
1291 readExpr();
1292 expect(")");
Rui Ueyamaf7791bb2016-07-26 19:34:10 +00001293 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001294 }
1295 if (Tok == "DATA_SEGMENT_END") {
1296 expect("(");
1297 expect(".");
1298 expect(")");
1299 return [](uint64_t Dot) { return Dot; };
1300 }
George Rimar276b4e62016-07-26 17:58:44 +00001301 // GNU linkers implements more complicated logic to handle
1302 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1303 // the next page boundary for simplicity.
1304 if (Tok == "DATA_SEGMENT_RELRO_END") {
1305 expect("(");
1306 next();
1307 expect(",");
1308 readExpr();
1309 expect(")");
1310 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1311 }
George Rimar9e694502016-07-29 16:18:47 +00001312 if (Tok == "SIZEOF") {
1313 expect("(");
1314 StringRef Name = next();
1315 expect(")");
George Rimar884e7862016-09-08 08:19:13 +00001316 return [=](uint64_t Dot) { return ScriptBase->getOutputSectionSize(Name); };
George Rimar9e694502016-07-29 16:18:47 +00001317 }
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001318 if (Tok == "ALIGNOF") {
1319 expect("(");
1320 StringRef Name = next();
1321 expect(")");
1322 return
1323 [=](uint64_t Dot) { return ScriptBase->getOutputSectionAlign(Name); };
1324 }
George Rimare32a3592016-08-10 07:59:34 +00001325 if (Tok == "SIZEOF_HEADERS")
George Rimar884e7862016-09-08 08:19:13 +00001326 return [=](uint64_t Dot) { return ScriptBase->getHeaderSize(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001327
George Rimar9f2f7ad2016-09-02 16:01:42 +00001328 // Tok is a literal number.
1329 uint64_t V;
1330 if (readInteger(Tok, V))
1331 return [=](uint64_t Dot) { return V; };
1332
1333 // Tok is a symbol name.
1334 if (Tok != "." && !isValidCIdentifier(Tok))
1335 setError("malformed number: " + Tok);
1336 return [=](uint64_t Dot) { return getSymbolValue(Tok, Dot); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001337}
1338
1339Expr ScriptParser::readTernary(Expr Cond) {
1340 next();
1341 Expr L = readExpr();
1342 expect(":");
1343 Expr R = readExpr();
1344 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1345}
1346
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001347Expr ScriptParser::readParenExpr() {
1348 expect("(");
1349 Expr E = readExpr();
1350 expect(")");
1351 return E;
1352}
1353
Eugene Leviantbbe38602016-07-19 09:25:43 +00001354std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1355 std::vector<StringRef> Phdrs;
1356 while (!Error && peek().startswith(":")) {
1357 StringRef Tok = next();
1358 Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
1359 if (Tok.empty()) {
1360 setError("section header name is empty");
1361 break;
1362 }
Rui Ueyama047404f2016-07-20 19:36:36 +00001363 Phdrs.push_back(Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001364 }
1365 return Phdrs;
1366}
1367
1368unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001369 StringRef Tok = next();
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001370 unsigned Ret = StringSwitch<unsigned>(Tok)
George Rimar6c55f0e2016-09-08 08:20:30 +00001371 .Case("PT_NULL", PT_NULL)
1372 .Case("PT_LOAD", PT_LOAD)
1373 .Case("PT_DYNAMIC", PT_DYNAMIC)
1374 .Case("PT_INTERP", PT_INTERP)
1375 .Case("PT_NOTE", PT_NOTE)
1376 .Case("PT_SHLIB", PT_SHLIB)
1377 .Case("PT_PHDR", PT_PHDR)
1378 .Case("PT_TLS", PT_TLS)
1379 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1380 .Case("PT_GNU_STACK", PT_GNU_STACK)
1381 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1382 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001383
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001384 if (Ret == (unsigned)-1) {
1385 setError("invalid program header type: " + Tok);
1386 return PT_NULL;
1387 }
1388 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001389}
1390
Rui Ueyama95769b42016-08-31 20:03:54 +00001391void ScriptParser::readVersionDeclaration(StringRef VerStr) {
George Rimar20b65982016-08-31 09:08:26 +00001392 // Identifiers start at 2 because 0 and 1 are reserved
1393 // for VER_NDX_LOCAL and VER_NDX_GLOBAL constants.
1394 size_t VersionId = Config->VersionDefinitions.size() + 2;
1395 Config->VersionDefinitions.push_back({VerStr, VersionId});
1396
1397 if (skip("global:") || peek() != "local:")
1398 readGlobal(VerStr);
1399 if (skip("local:"))
1400 readLocal();
1401 expect("}");
1402
1403 // Each version may have a parent version. For example, "Ver2" defined as
1404 // "Ver2 { global: foo; local: *; } Ver1;" has "Ver1" as a parent. This
1405 // version hierarchy is, probably against your instinct, purely for human; the
1406 // runtime doesn't care about them at all. In LLD, we simply skip the token.
1407 if (!VerStr.empty() && peek() != ";")
1408 next();
1409 expect(";");
1410}
1411
1412void ScriptParser::readLocal() {
1413 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1414 expect("*");
1415 expect(";");
1416}
1417
1418void ScriptParser::readExtern(std::vector<SymbolVersion> *Globals) {
1419 expect("C++");
1420 expect("{");
1421
1422 for (;;) {
1423 if (peek() == "}" || Error)
1424 break;
1425 Globals->push_back({next(), true});
1426 expect(";");
1427 }
1428
1429 expect("}");
1430 expect(";");
1431}
1432
1433void ScriptParser::readGlobal(StringRef VerStr) {
1434 std::vector<SymbolVersion> *Globals;
1435 if (VerStr.empty())
1436 Globals = &Config->VersionScriptGlobals;
1437 else
1438 Globals = &Config->VersionDefinitions.back().Globals;
1439
1440 for (;;) {
1441 if (skip("extern"))
1442 readExtern(Globals);
1443
1444 StringRef Cur = peek();
1445 if (Cur == "}" || Cur == "local:" || Error)
1446 return;
1447 next();
1448 Globals->push_back({Cur, false});
1449 expect(";");
1450 }
1451}
1452
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001453static bool isUnderSysroot(StringRef Path) {
1454 if (Config->Sysroot == "")
1455 return false;
1456 for (; !Path.empty(); Path = sys::path::parent_path(Path))
1457 if (sys::fs::equivalent(Config->Sysroot, Path))
1458 return true;
1459 return false;
1460}
1461
Rui Ueyama07320e42016-04-20 20:13:41 +00001462void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001463 StringRef Path = MB.getBufferIdentifier();
George Rimar20b65982016-08-31 09:08:26 +00001464 ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).readLinkerScript();
1465}
1466
1467void elf::readVersionScript(MemoryBufferRef MB) {
1468 ScriptParser(MB.getBuffer(), false).readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001469}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001470
Rui Ueyama07320e42016-04-20 20:13:41 +00001471template class elf::LinkerScript<ELF32LE>;
1472template class elf::LinkerScript<ELF32BE>;
1473template class elf::LinkerScript<ELF64LE>;
1474template class elf::LinkerScript<ELF64BE>;