blob: 6085b19b67890f688f15f4fe5ce28b7f3af44c2b [file] [log] [blame]
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001//===- LinkerScript.cpp ---------------------------------------------------===//
2//
3// The LLVM Linker
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains the parser/evaluator of the linker script.
Rui Ueyama629e0aa52016-07-21 19:45:22 +000011// It parses a linker script and write the result to Config or ScriptConfig
12// objects.
13//
14// If SECTIONS command is used, a ScriptConfig contains an AST
15// of the command which will later be consumed by createSections() and
16// assignAddresses().
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000017//
18//===----------------------------------------------------------------------===//
19
Rui Ueyama717677a2016-02-11 21:17:59 +000020#include "LinkerScript.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000021#include "Config.h"
22#include "Driver.h"
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +000023#include "InputSection.h"
George Rimar652852c2016-04-16 10:10:32 +000024#include "OutputSections.h"
Adhemerval Zanellae77b5bf2016-04-06 20:59:11 +000025#include "ScriptParser.h"
Rui Ueyama93c9af42016-06-29 08:01:32 +000026#include "Strings.h"
Eugene Levianteda81a12016-07-12 06:39:48 +000027#include "Symbols.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000028#include "SymbolTable.h"
Eugene Leviant467c4d52016-07-01 10:27:36 +000029#include "Target.h"
Eugene Leviantbbe38602016-07-19 09:25:43 +000030#include "Writer.h"
Rui Ueyama960504b2016-04-19 18:58:11 +000031#include "llvm/ADT/StringSwitch.h"
George Rimar652852c2016-04-16 10:10:32 +000032#include "llvm/Support/ELF.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000033#include "llvm/Support/FileSystem.h"
34#include "llvm/Support/MemoryBuffer.h"
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +000035#include "llvm/Support/Path.h"
Rui Ueyamaa47ee682015-10-11 01:53:04 +000036#include "llvm/Support/StringSaver.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000037
38using namespace llvm;
George Rimar652852c2016-04-16 10:10:32 +000039using namespace llvm::ELF;
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +000040using namespace llvm::object;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000041using namespace lld;
Rafael Espindolae0df00b2016-02-28 00:25:54 +000042using namespace lld::elf;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000043
Rui Ueyama07320e42016-04-20 20:13:41 +000044ScriptConfiguration *elf::ScriptConfig;
Rui Ueyama717677a2016-02-11 21:17:59 +000045
Eugene Leviantceabe802016-08-11 07:56:43 +000046template <class ELFT>
Rui Ueyama16024212016-08-11 23:22:52 +000047static void addRegular(SymbolAssignment *Cmd) {
48 Symbol *Sym = Symtab<ELFT>::X->addRegular(Cmd->Name, STB_GLOBAL, STV_DEFAULT);
49 Sym->Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
50 Cmd->Sym = Sym->body();
Eugene Leviantceabe802016-08-11 07:56:43 +000051}
52
Rui Ueyama0c70d3c2016-08-12 03:31:09 +000053template <class ELFT> static void addSynthetic(SymbolAssignment *Cmd) {
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
Rui Ueyama16024212016-08-11 23:22:52 +000059// If a symbol was in PROVIDE(), we need to define it only when
60// it is an undefined symbol.
61template <class ELFT> static bool shouldDefine(SymbolAssignment *Cmd) {
62 if (Cmd->Name == ".")
Eugene Leviantceabe802016-08-11 07:56:43 +000063 return false;
Rui Ueyama16024212016-08-11 23:22:52 +000064 if (!Cmd->Provide)
65 return true;
66 SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
67 return B && B->isUndefined();
Eugene Leviantceabe802016-08-11 07:56:43 +000068}
69
George Rimar076fe152016-07-21 06:43:01 +000070bool SymbolAssignment::classof(const BaseCommand *C) {
71 return C->Kind == AssignmentKind;
72}
73
74bool OutputSectionCommand::classof(const BaseCommand *C) {
75 return C->Kind == OutputSectionKind;
76}
77
George Rimareea31142016-07-21 14:26:59 +000078bool InputSectionDescription::classof(const BaseCommand *C) {
79 return C->Kind == InputSectionKind;
80}
81
George Rimareefa7582016-08-04 09:29:31 +000082bool AssertCommand::classof(const BaseCommand *C) {
83 return C->Kind == AssertKind;
84}
85
Rui Ueyama36a153c2016-07-23 14:09:58 +000086template <class ELFT> static bool isDiscarded(InputSectionBase<ELFT> *S) {
George Rimareea31142016-07-21 14:26:59 +000087 return !S || !S->Live;
Rui Ueyama717677a2016-02-11 21:17:59 +000088}
89
Rui Ueyamaf34d0e02016-08-12 01:24:53 +000090template <class ELFT> LinkerScript<ELFT>::LinkerScript() {}
91template <class ELFT> LinkerScript<ELFT>::~LinkerScript() {}
92
Rui Ueyama07320e42016-04-20 20:13:41 +000093template <class ELFT>
94bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) {
George Rimarc91930a2016-09-02 21:17:20 +000095 for (Regex *Re : Opt.KeptSections)
96 if (Re->match(S->getSectionName()))
George Rimareea31142016-07-21 14:26:59 +000097 return true;
98 return false;
99}
100
George Rimar06598002016-07-28 21:51:30 +0000101static bool fileMatches(const InputSectionDescription *Desc,
102 StringRef Filename) {
George Rimarc91930a2016-09-02 21:17:20 +0000103 return const_cast<Regex &>(Desc->FileRe).match(Filename) &&
104 !const_cast<Regex &>(Desc->ExcludedFileRe).match(Filename);
George Rimar06598002016-07-28 21:51:30 +0000105}
106
Rui Ueyama6b274812016-07-25 22:51:07 +0000107// Returns input sections filtered by given glob patterns.
108template <class ELFT>
109std::vector<InputSectionBase<ELFT> *>
Rui Ueyamaad10c3d2016-07-28 21:05:04 +0000110LinkerScript<ELFT>::getInputSections(const InputSectionDescription *I) {
George Rimarc91930a2016-09-02 21:17:20 +0000111 const Regex &Re = I->SectionRe;
Rui Ueyama6b274812016-07-25 22:51:07 +0000112 std::vector<InputSectionBase<ELFT> *> Ret;
113 for (const std::unique_ptr<ObjectFile<ELFT>> &F :
George Rimar06598002016-07-28 21:51:30 +0000114 Symtab<ELFT>::X->getObjectFiles()) {
115 if (fileMatches(I, sys::path::filename(F->getName())))
116 for (InputSectionBase<ELFT> *S : F->getSections())
117 if (!isDiscarded(S) && !S->OutSec &&
George Rimarc91930a2016-09-02 21:17:20 +0000118 const_cast<Regex &>(Re).match(S->getSectionName()))
Davide Italianoe7282792016-07-27 01:44:01 +0000119 Ret.push_back(S);
George Rimar06598002016-07-28 21:51:30 +0000120 }
Eugene Leviant3e6b0272016-07-28 19:24:13 +0000121
George Rimarc91930a2016-09-02 21:17:20 +0000122 if (const_cast<Regex &>(Re).match("COMMON"))
Rui Ueyamaad10c3d2016-07-28 21:05:04 +0000123 Ret.push_back(CommonInputSection<ELFT>::X);
Rui Ueyama6b274812016-07-25 22:51:07 +0000124 return Ret;
125}
126
Eugene Leviantceabe802016-08-11 07:56:43 +0000127template <class ELFT>
Rui Ueyama742c3832016-08-04 22:27:00 +0000128static bool compareName(InputSectionBase<ELFT> *A, InputSectionBase<ELFT> *B) {
129 return A->getSectionName() < B->getSectionName();
130}
George Rimar350ece42016-08-03 08:35:59 +0000131
Rui Ueyama742c3832016-08-04 22:27:00 +0000132template <class ELFT>
133static bool compareAlignment(InputSectionBase<ELFT> *A,
134 InputSectionBase<ELFT> *B) {
135 // ">" is not a mistake. Larger alignments are placed before smaller
136 // alignments in order to reduce the amount of padding necessary.
137 // This is compatible with GNU.
138 return A->Alignment > B->Alignment;
139}
George Rimar350ece42016-08-03 08:35:59 +0000140
Rui Ueyama742c3832016-08-04 22:27:00 +0000141template <class ELFT>
142static std::function<bool(InputSectionBase<ELFT> *, InputSectionBase<ELFT> *)>
143getComparator(SortKind K) {
144 if (K == SortByName)
145 return compareName<ELFT>;
146 return compareAlignment<ELFT>;
147}
George Rimar0702c4e2016-07-29 15:32:46 +0000148
149template <class ELFT>
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000150void LinkerScript<ELFT>::discard(OutputSectionCommand &Cmd) {
151 for (const std::unique_ptr<BaseCommand> &Base : Cmd.Commands) {
152 if (auto *Cmd = dyn_cast<InputSectionDescription>(Base.get())) {
153 for (InputSectionBase<ELFT> *S : getInputSections(Cmd)) {
154 S->Live = false;
155 reportDiscarded(S);
156 }
157 }
158 }
159}
160
George Rimar8f66df92016-08-12 20:38:20 +0000161static bool checkConstraint(uint64_t Flags, ConstraintKind Kind) {
162 bool RO = (Kind == ConstraintKind::ReadOnly);
163 bool RW = (Kind == ConstraintKind::ReadWrite);
164 bool Writable = Flags & SHF_WRITE;
165 return !((RO && Writable) || (RW && !Writable));
166}
167
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000168template <class ELFT>
George Rimar06ae6832016-08-12 09:07:57 +0000169static bool matchConstraints(ArrayRef<InputSectionBase<ELFT> *> Sections,
170 ConstraintKind Kind) {
George Rimar8f66df92016-08-12 20:38:20 +0000171 if (Kind == ConstraintKind::NoConstraint)
172 return true;
173 return llvm::all_of(Sections, [=](InputSectionBase<ELFT> *Sec) {
174 return checkConstraint(Sec->getSectionHdr()->sh_flags, Kind);
George Rimar06ae6832016-08-12 09:07:57 +0000175 });
176}
177
178template <class ELFT>
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000179std::vector<InputSectionBase<ELFT> *>
George Rimar06ae6832016-08-12 09:07:57 +0000180LinkerScript<ELFT>::createInputSectionList(OutputSectionCommand &OutCmd) {
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000181 std::vector<InputSectionBase<ELFT> *> Ret;
Eugene Leviant97403d12016-09-01 09:55:57 +0000182 DenseSet<InputSectionBase<ELFT> *> SectionIndex;
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000183
George Rimar06ae6832016-08-12 09:07:57 +0000184 for (const std::unique_ptr<BaseCommand> &Base : OutCmd.Commands) {
185 if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base.get())) {
186 if (shouldDefine<ELFT>(OutCmd))
187 addSynthetic<ELFT>(OutCmd);
Eugene Leviant97403d12016-09-01 09:55:57 +0000188 OutCmd->GoesAfter = Ret.empty() ? nullptr : Ret.back();
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000189 continue;
190 }
191
192 auto *Cmd = cast<InputSectionDescription>(Base.get());
193 std::vector<InputSectionBase<ELFT> *> V = getInputSections(Cmd);
George Rimar06ae6832016-08-12 09:07:57 +0000194 if (!matchConstraints<ELFT>(V, OutCmd.Constraint))
195 continue;
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000196 if (Cmd->SortInner)
197 std::stable_sort(V.begin(), V.end(), getComparator<ELFT>(Cmd->SortInner));
198 if (Cmd->SortOuter)
199 std::stable_sort(V.begin(), V.end(), getComparator<ELFT>(Cmd->SortOuter));
Eugene Leviant97403d12016-09-01 09:55:57 +0000200
201 // Add all input sections corresponding to rule 'Cmd' to
202 // resulting vector. We do not add duplicate input sections.
203 for (InputSectionBase<ELFT> *S : V)
204 if (SectionIndex.insert(S).second)
205 Ret.push_back(S);
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000206 }
207 return Ret;
208}
209
210template <class ELFT>
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000211void LinkerScript<ELFT>::createAssignments() {
212 for (const std::unique_ptr<SymbolAssignment> &Cmd : Opt.Assignments) {
213 if (shouldDefine<ELFT>(Cmd.get()))
214 addRegular<ELFT>(Cmd.get());
215 if (Cmd->Sym)
216 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(0);
217 }
218}
219
220template <class ELFT>
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000221void LinkerScript<ELFT>::createSections(OutputSectionFactory<ELFT> &Factory) {
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000222 for (const std::unique_ptr<BaseCommand> &Base1 : Opt.Commands) {
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000223 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base1.get())) {
224 if (shouldDefine<ELFT>(Cmd))
225 addRegular<ELFT>(Cmd);
226 continue;
227 }
228
Eugene Leviantceabe802016-08-11 07:56:43 +0000229 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000230 if (Cmd->Name == "/DISCARD/") {
231 discard(*Cmd);
232 continue;
233 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000234
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000235 std::vector<InputSectionBase<ELFT> *> V = createInputSectionList(*Cmd);
Eugene Leviant97403d12016-09-01 09:55:57 +0000236 if (V.empty())
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000237 continue;
238
239 OutputSectionBase<ELFT> *OutSec;
240 bool IsNew;
Eugene Leviant97403d12016-09-01 09:55:57 +0000241 std::tie(OutSec, IsNew) = Factory.create(V.front(), Cmd->Name);
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000242 if (IsNew)
243 OutputSections->push_back(OutSec);
George Rimardb24d9c2016-08-19 15:18:23 +0000244
245 uint32_t Subalign = Cmd->SubalignExpr ? Cmd->SubalignExpr(0) : 0;
246 for (InputSectionBase<ELFT> *Sec : V) {
247 if (Subalign)
248 Sec->Alignment = Subalign;
Eugene Leviant97403d12016-09-01 09:55:57 +0000249 OutSec->addSection(Sec);
George Rimardb24d9c2016-08-19 15:18:23 +0000250 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000251 }
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000252 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000253
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000254 // Add orphan sections.
Rui Ueyama6b274812016-07-25 22:51:07 +0000255 for (const std::unique_ptr<ObjectFile<ELFT>> &F :
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000256 Symtab<ELFT>::X->getObjectFiles()) {
257 for (InputSectionBase<ELFT> *S : F->getSections()) {
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000258 if (isDiscarded(S) || S->OutSec)
259 continue;
260 OutputSectionBase<ELFT> *OutSec;
261 bool IsNew;
262 std::tie(OutSec, IsNew) = Factory.create(S, getOutputSectionName(S));
263 if (IsNew)
264 OutputSections->push_back(OutSec);
265 OutSec->addSection(S);
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000266 }
267 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000268}
269
Eugene Leviant20889c52016-08-31 08:13:33 +0000270// Linker script may define start and end symbols for special section types,
271// like .got, .eh_frame_hdr, .eh_frame and others. Those sections are not a list
272// of regular input input sections, therefore our way of defining symbols for
273// regular sections will not work. The approach we use for special section types
274// is not perfect - it handles only start and end symbols.
275template <class ELFT>
276void addStartEndSymbols(OutputSectionCommand *Cmd,
277 OutputSectionBase<ELFT> *Sec) {
278 bool Start = true;
279 BaseCommand *PrevCmd = nullptr;
280
281 for (std::unique_ptr<BaseCommand> &Base : Cmd->Commands) {
282 if (auto *AssignCmd = dyn_cast<SymbolAssignment>(Base.get())) {
283 if (auto *Sym = cast_or_null<DefinedSynthetic<ELFT>>(AssignCmd->Sym)) {
284 Sym->Section = Sec;
285 Sym->Value =
286 AssignCmd->Expression(Sec->getVA() + (Start ? 0 : Sec->getSize())) -
287 Sec->getVA();
288 }
289 } else {
290 if (!Start && isa<SymbolAssignment>(PrevCmd))
291 error("section '" + Sec->getName() +
292 "' supports only start and end symbols");
293 Start = false;
294 }
295 PrevCmd = Base.get();
296 }
297}
298
299template <class ELFT>
300void assignOffsets(OutputSectionCommand *Cmd, OutputSectionBase<ELFT> *Sec) {
Eugene Leviantceabe802016-08-11 07:56:43 +0000301 auto *OutSec = dyn_cast<OutputSection<ELFT>>(Sec);
Rui Ueyama2de509c2016-08-12 00:55:08 +0000302 if (!OutSec) {
303 Sec->assignOffsets();
Eugene Leviant20889c52016-08-31 08:13:33 +0000304 // This section is not regular output section. However linker script may
305 // have defined start/end symbols for it. This case is handled below.
306 addStartEndSymbols(Cmd, Sec);
Eugene Leviantceabe802016-08-11 07:56:43 +0000307 return;
Rui Ueyama2de509c2016-08-12 00:55:08 +0000308 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000309 typedef typename ELFT::uint uintX_t;
310 uintX_t Off = 0;
Eugene Leviant97403d12016-09-01 09:55:57 +0000311 auto ItCmd = Cmd->Commands.begin();
Eugene Leviantceabe802016-08-11 07:56:43 +0000312
Eugene Leviant97403d12016-09-01 09:55:57 +0000313 // Assigns values to all symbols following the given
314 // input section 'D' in output section 'Sec'. When symbols
315 // are in the beginning of output section the value of 'D'
316 // is nullptr.
317 auto AssignSuccessors = [&](InputSectionData *D) {
318 for (; ItCmd != Cmd->Commands.end(); ++ItCmd) {
319 auto *AssignCmd = dyn_cast<SymbolAssignment>(ItCmd->get());
320 if (!AssignCmd)
321 continue;
322 if (D != AssignCmd->GoesAfter)
323 break;
324
325 uintX_t Value = AssignCmd->Expression(Sec->getVA() + Off) - Sec->getVA();
326 if (AssignCmd->Name == ".") {
327 // Update to location counter means update to section size.
Eugene Leviantceabe802016-08-11 07:56:43 +0000328 Off = Value;
Eugene Leviant97403d12016-09-01 09:55:57 +0000329 Sec->setSize(Off);
330 continue;
331 }
332
333 if (DefinedSynthetic<ELFT> *Sym =
334 cast_or_null<DefinedSynthetic<ELFT>>(AssignCmd->Sym)) {
Rui Ueyama0c70d3c2016-08-12 03:31:09 +0000335 Sym->Section = OutSec;
336 Sym->Value = Value;
337 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000338 }
Eugene Leviant97403d12016-09-01 09:55:57 +0000339 };
340
341 AssignSuccessors(nullptr);
342 for (InputSection<ELFT> *I : OutSec->Sections) {
343 Off = alignTo(Off, I->Alignment);
344 I->OutSecOff = Off;
345 Off += I->getSize();
Rui Ueyamaf4a30a52016-08-11 21:30:42 +0000346 // Update section size inside for-loop, so that SIZEOF
Eugene Leviantceabe802016-08-11 07:56:43 +0000347 // works correctly in the case below:
348 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
349 Sec->setSize(Off);
Eugene Leviant97403d12016-09-01 09:55:57 +0000350 // Add symbols following current input section.
351 AssignSuccessors(I);
Eugene Leviantceabe802016-08-11 07:56:43 +0000352 }
353}
354
George Rimar8f66df92016-08-12 20:38:20 +0000355template <class ELFT>
356static OutputSectionBase<ELFT> *
357findSection(OutputSectionCommand &Cmd,
358 ArrayRef<OutputSectionBase<ELFT> *> Sections) {
359 for (OutputSectionBase<ELFT> *Sec : Sections) {
360 if (Sec->getName() != Cmd.Name)
361 continue;
362 if (checkConstraint(Sec->getFlags(), Cmd.Constraint))
363 return Sec;
364 }
365 return nullptr;
366}
367
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000368template <class ELFT> void LinkerScript<ELFT>::assignAddresses() {
George Rimar652852c2016-04-16 10:10:32 +0000369 // Orphan sections are sections present in the input files which
Rui Ueyama7c18c282016-04-18 21:00:40 +0000370 // are not explicitly placed into the output file by the linker script.
371 // We place orphan sections at end of file.
372 // Other linkers places them using some heuristics as described in
George Rimar652852c2016-04-16 10:10:32 +0000373 // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
Rui Ueyamae5cc6682016-08-12 00:36:56 +0000374 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
George Rimar652852c2016-04-16 10:10:32 +0000375 StringRef Name = Sec->getName();
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000376 if (getSectionIndex(Name) == INT_MAX)
George Rimar076fe152016-07-21 06:43:01 +0000377 Opt.Commands.push_back(llvm::make_unique<OutputSectionCommand>(Name));
George Rimar652852c2016-04-16 10:10:32 +0000378 }
George Rimar652852c2016-04-16 10:10:32 +0000379
Rui Ueyama7c18c282016-04-18 21:00:40 +0000380 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rui Ueyama4f7500b2016-08-12 04:00:22 +0000381 Dot = getHeaderSize();
Eugene Leviant467c4d52016-07-01 10:27:36 +0000382 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
George Rimar652852c2016-04-16 10:10:32 +0000383 uintX_t ThreadBssOffset = 0;
George Rimar652852c2016-04-16 10:10:32 +0000384
George Rimar076fe152016-07-21 06:43:01 +0000385 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
386 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
Rui Ueyama8d083e62016-07-29 05:48:39 +0000387 if (Cmd->Name == ".") {
388 Dot = Cmd->Expression(Dot);
389 } else if (Cmd->Sym) {
390 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(Dot);
391 }
George Rimar652852c2016-04-16 10:10:32 +0000392 continue;
393 }
394
George Rimareefa7582016-08-04 09:29:31 +0000395 if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
396 Cmd->Expression(Dot);
397 continue;
398 }
399
George Rimar076fe152016-07-21 06:43:01 +0000400 auto *Cmd = cast<OutputSectionCommand>(Base.get());
George Rimar8f66df92016-08-12 20:38:20 +0000401 OutputSectionBase<ELFT> *Sec = findSection<ELFT>(*Cmd, *OutputSections);
402 if (!Sec)
George Rimarb6c52e82016-08-12 19:32:45 +0000403 continue;
George Rimar652852c2016-04-16 10:10:32 +0000404
George Rimarb6c52e82016-08-12 19:32:45 +0000405 if (Cmd->AddrExpr)
406 Dot = Cmd->AddrExpr(Dot);
George Rimar58e5c4d2016-07-25 08:29:46 +0000407
George Rimarb6c52e82016-08-12 19:32:45 +0000408 if (Cmd->AlignExpr)
409 Sec->updateAlignment(Cmd->AlignExpr(Dot));
George Rimar630c6172016-07-26 18:06:29 +0000410
George Rimarb6c52e82016-08-12 19:32:45 +0000411 if ((Sec->getFlags() & SHF_TLS) && Sec->getType() == SHT_NOBITS) {
412 uintX_t TVA = Dot + ThreadBssOffset;
413 TVA = alignTo(TVA, Sec->getAlignment());
414 Sec->setVA(TVA);
Eugene Leviant20889c52016-08-31 08:13:33 +0000415 assignOffsets(Cmd, Sec);
George Rimarb6c52e82016-08-12 19:32:45 +0000416 ThreadBssOffset = TVA - Dot + Sec->getSize();
417 continue;
George Rimar652852c2016-04-16 10:10:32 +0000418 }
George Rimarb6c52e82016-08-12 19:32:45 +0000419
420 if (!(Sec->getFlags() & SHF_ALLOC)) {
Eugene Leviant20889c52016-08-31 08:13:33 +0000421 assignOffsets(Cmd, Sec);
George Rimarb6c52e82016-08-12 19:32:45 +0000422 continue;
423 }
424
425 Dot = alignTo(Dot, Sec->getAlignment());
426 Sec->setVA(Dot);
Eugene Leviant20889c52016-08-31 08:13:33 +0000427 assignOffsets(Cmd, Sec);
George Rimarb6c52e82016-08-12 19:32:45 +0000428 MinVA = std::min(MinVA, Dot);
429 Dot += Sec->getSize();
George Rimar652852c2016-04-16 10:10:32 +0000430 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000431
Rafael Espindola64c32d62016-07-07 14:28:47 +0000432 // ELF and Program headers need to be right before the first section in
George Rimarb91e7112016-07-19 07:42:07 +0000433 // memory. Set their addresses accordingly.
Eugene Leviant467c4d52016-07-01 10:27:36 +0000434 MinVA = alignDown(MinVA - Out<ELFT>::ElfHeader->getSize() -
435 Out<ELFT>::ProgramHeaders->getSize(),
436 Target->PageSize);
437 Out<ELFT>::ElfHeader->setVA(MinVA);
438 Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
George Rimar652852c2016-04-16 10:10:32 +0000439}
440
Rui Ueyama464daad2016-08-22 04:55:20 +0000441// Creates program headers as instructed by PHDRS linker script command.
Rui Ueyama07320e42016-04-20 20:13:41 +0000442template <class ELFT>
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000443std::vector<PhdrEntry<ELFT>> LinkerScript<ELFT>::createPhdrs() {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000444 std::vector<PhdrEntry<ELFT>> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000445
Rui Ueyama464daad2016-08-22 04:55:20 +0000446 // Process PHDRS and FILEHDR keywords because they are not
447 // real output sections and cannot be added in the following loop.
Eugene Leviantbbe38602016-07-19 09:25:43 +0000448 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000449 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
450 PhdrEntry<ELFT> &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000451
452 if (Cmd.HasFilehdr)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000453 Phdr.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000454 if (Cmd.HasPhdrs)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000455 Phdr.add(Out<ELFT>::ProgramHeaders);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000456 }
457
Rui Ueyama464daad2016-08-22 04:55:20 +0000458 // Add output sections to program headers.
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000459 PhdrEntry<ELFT> *Load = nullptr;
460 uintX_t Flags = PF_R;
Rui Ueyama464daad2016-08-22 04:55:20 +0000461 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
Eugene Leviantbbe38602016-07-19 09:25:43 +0000462 if (!(Sec->getFlags() & SHF_ALLOC))
463 break;
464
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000465 std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName());
Eugene Leviantbbe38602016-07-19 09:25:43 +0000466 if (!PhdrIds.empty()) {
467 // Assign headers specified by linker script
468 for (size_t Id : PhdrIds) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000469 Ret[Id].add(Sec);
Eugene Leviant865bf862016-07-21 10:43:25 +0000470 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
Rafael Espindola0b113672016-07-27 14:10:56 +0000471 Ret[Id].H.p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000472 }
473 } else {
474 // If we have no load segment or flags've changed then we want new load
475 // segment.
Rafael Espindola0b113672016-07-27 14:10:56 +0000476 uintX_t NewFlags = Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000477 if (Load == nullptr || Flags != NewFlags) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000478 Load = &*Ret.emplace(Ret.end(), PT_LOAD, NewFlags);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000479 Flags = NewFlags;
480 }
Rui Ueyama18f084f2016-07-20 19:36:41 +0000481 Load->add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000482 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000483 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000484 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000485}
486
Eugene Leviantf9bc3bd2016-08-16 06:40:58 +0000487template <class ELFT> bool LinkerScript<ELFT>::ignoreInterpSection() {
488 // Ignore .interp section in case we have PHDRS specification
489 // and PT_INTERP isn't listed.
490 return !Opt.PhdrsCommands.empty() &&
491 llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
492 return Cmd.Type == PT_INTERP;
493 }) == Opt.PhdrsCommands.end();
494}
495
Eugene Leviantbbe38602016-07-19 09:25:43 +0000496template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000497ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000498 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
499 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
500 if (Cmd->Name == Name)
501 return Cmd->Filler;
502 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000503}
504
George Rimar206fffa2016-08-17 08:16:57 +0000505template <class ELFT> Expr LinkerScript<ELFT>::getLma(StringRef Name) {
George Rimar8ceadb32016-08-17 07:44:19 +0000506 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
507 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
508 if (Cmd->LmaExpr && Cmd->Name == Name)
509 return Cmd->LmaExpr;
510 return {};
511}
512
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000513// Returns the index of the given section name in linker script
514// SECTIONS commands. Sections are laid out as the same order as they
515// were in the script. If a given name did not appear in the script,
516// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000517template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000518 int I = 0;
519 for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
520 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
521 if (Cmd->Name == Name)
522 return I;
523 ++I;
524 }
525 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000526}
527
528// A compartor to sort output sections. Returns -1 or 1 if
529// A or B are mentioned in linker script. Otherwise, returns 0.
Rui Ueyama07320e42016-04-20 20:13:41 +0000530template <class ELFT>
531int LinkerScript<ELFT>::compareSections(StringRef A, StringRef B) {
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000532 int I = getSectionIndex(A);
533 int J = getSectionIndex(B);
534 if (I == INT_MAX && J == INT_MAX)
Rui Ueyama717677a2016-02-11 21:17:59 +0000535 return 0;
536 return I < J ? -1 : 1;
537}
538
Eugene Leviantbbe38602016-07-19 09:25:43 +0000539template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
540 return !Opt.PhdrsCommands.empty();
541}
542
George Rimar9e694502016-07-29 16:18:47 +0000543template <class ELFT>
George Rimar96659df2016-08-30 09:54:01 +0000544typename ELFT::uint
545LinkerScript<ELFT>::getOutputSectionAddress(StringRef Name) {
546 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
547 if (Sec->getName() == Name)
548 return Sec->getVA();
549 error("undefined section " + Name);
550 return 0;
551}
552
553template <class ELFT>
George Rimar9e694502016-07-29 16:18:47 +0000554typename ELFT::uint LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
555 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
556 if (Sec->getName() == Name)
557 return Sec->getSize();
558 error("undefined section " + Name);
559 return 0;
560}
561
George Rimare32a3592016-08-10 07:59:34 +0000562template <class ELFT>
Rui Ueyama4f7500b2016-08-12 04:00:22 +0000563typename ELFT::uint LinkerScript<ELFT>::getHeaderSize() {
George Rimare32a3592016-08-10 07:59:34 +0000564 return Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
565}
566
Eugene Leviantbbe38602016-07-19 09:25:43 +0000567// Returns indices of ELF headers containing specific section, identified
568// by Name. Each index is a zero based number of ELF header listed within
569// PHDRS {} script block.
570template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000571std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000572 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
573 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000574 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000575 continue;
576
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000577 std::vector<size_t> Ret;
578 for (StringRef PhdrName : Cmd->Phdrs)
579 Ret.push_back(getPhdrIndex(PhdrName));
580 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000581 }
George Rimar31d842f2016-07-20 16:43:03 +0000582 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000583}
584
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000585template <class ELFT>
586size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
587 size_t I = 0;
588 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
589 if (Cmd.Name == PhdrName)
590 return I;
591 ++I;
592 }
593 error("section header '" + PhdrName + "' is not listed in PHDRS");
594 return 0;
595}
596
Rui Ueyama07320e42016-04-20 20:13:41 +0000597class elf::ScriptParser : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000598 typedef void (ScriptParser::*Handler)();
599
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000600public:
Rui Ueyama07320e42016-04-20 20:13:41 +0000601 ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
George Rimarf23b2322016-02-19 10:45:45 +0000602
George Rimar20b65982016-08-31 09:08:26 +0000603 void readLinkerScript();
604 void readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000605
606private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000607 void addFile(StringRef Path);
608
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000609 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000610 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000611 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000612 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000613 void readInclude();
Rui Ueyamaee592822015-10-07 00:25:09 +0000614 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000615 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000616 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000617 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000618 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000619 void readSections();
Rui Ueyama95769b42016-08-31 20:03:54 +0000620 void readVersion();
621 void readVersionScriptCommand();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000622
Rui Ueyama113cdec2016-07-24 23:05:57 +0000623 SymbolAssignment *readAssignment(StringRef Name);
Rui Ueyama10416562016-08-04 02:03:27 +0000624 OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000625 std::vector<uint8_t> readOutputSectionFiller();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000626 std::vector<StringRef> readOutputSectionPhdrs();
George Rimara2496cb2016-08-30 09:46:59 +0000627 InputSectionDescription *readInputSectionDescription(StringRef Tok);
George Rimarc91930a2016-09-02 21:17:20 +0000628 Regex readFilePatterns();
George Rimara2496cb2016-08-30 09:46:59 +0000629 InputSectionDescription *readInputSectionRules(StringRef FilePattern);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000630 unsigned readPhdrType();
Rui Ueyama742c3832016-08-04 22:27:00 +0000631 SortKind readSortKind();
Petr Hoseka35e39c2016-08-16 01:11:16 +0000632 SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
Eugene Leviantceabe802016-08-11 07:56:43 +0000633 SymbolAssignment *readProvideOrAssignment(StringRef Tok);
George Rimar03fc0102016-07-28 07:18:23 +0000634 void readSort();
George Rimareefa7582016-08-04 09:29:31 +0000635 Expr readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +0000636
637 Expr readExpr();
638 Expr readExpr1(Expr Lhs, int MinPrec);
639 Expr readPrimary();
640 Expr readTernary(Expr Cond);
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +0000641 Expr readParenExpr();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000642
George Rimar20b65982016-08-31 09:08:26 +0000643 // For parsing version script.
644 void readExtern(std::vector<SymbolVersion> *Globals);
Rui Ueyama95769b42016-08-31 20:03:54 +0000645 void readVersionDeclaration(StringRef VerStr);
George Rimar20b65982016-08-31 09:08:26 +0000646 void readGlobal(StringRef VerStr);
647 void readLocal();
648
Rui Ueyama07320e42016-04-20 20:13:41 +0000649 ScriptConfiguration &Opt = *ScriptConfig;
650 StringSaver Saver = {ScriptConfig->Alloc};
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000651 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000652};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000653
George Rimar20b65982016-08-31 09:08:26 +0000654void ScriptParser::readVersionScript() {
Rui Ueyama95769b42016-08-31 20:03:54 +0000655 readVersionScriptCommand();
656 if (!atEOF())
657 setError("EOF expected, but got " + next());
658}
659
660void ScriptParser::readVersionScriptCommand() {
George Rimar20b65982016-08-31 09:08:26 +0000661 if (skip("{")) {
Rui Ueyama95769b42016-08-31 20:03:54 +0000662 readVersionDeclaration("");
George Rimar20b65982016-08-31 09:08:26 +0000663 return;
664 }
665
Rui Ueyama95769b42016-08-31 20:03:54 +0000666 while (!atEOF() && !Error && peek() != "}") {
George Rimar20b65982016-08-31 09:08:26 +0000667 StringRef VerStr = next();
668 if (VerStr == "{") {
Rui Ueyama95769b42016-08-31 20:03:54 +0000669 setError("anonymous version definition is used in "
670 "combination with other version definitions");
George Rimar20b65982016-08-31 09:08:26 +0000671 return;
672 }
673 expect("{");
Rui Ueyama95769b42016-08-31 20:03:54 +0000674 readVersionDeclaration(VerStr);
George Rimar20b65982016-08-31 09:08:26 +0000675 }
676}
677
Rui Ueyama95769b42016-08-31 20:03:54 +0000678void ScriptParser::readVersion() {
679 expect("{");
680 readVersionScriptCommand();
681 expect("}");
682}
683
George Rimar20b65982016-08-31 09:08:26 +0000684void ScriptParser::readLinkerScript() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000685 while (!atEOF()) {
686 StringRef Tok = next();
Rui Ueyamaa27eecc2016-09-02 18:52:41 +0000687 if (Tok == ";")
688 continue;
689
690 if (Tok == "ENTRY") {
691 readEntry();
692 } else if (Tok == "EXTERN") {
693 readExtern();
694 } else if (Tok == "GROUP" || Tok == "INPUT") {
695 readGroup();
696 } else if (Tok == "INCLUDE") {
697 readInclude();
698 } else if (Tok == "OUTPUT") {
699 readOutput();
700 } else if (Tok == "OUTPUT_ARCH") {
701 readOutputArch();
702 } else if (Tok == "OUTPUT_FORMAT") {
703 readOutputFormat();
704 } else if (Tok == "PHDRS") {
705 readPhdrs();
706 } else if (Tok == "SEARCH_DIR") {
707 readSearchDir();
708 } else if (Tok == "SECTIONS") {
709 readSections();
710 } else if (Tok == "VERSION") {
711 readVersion();
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000712 } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok)) {
713 if (Opt.HasContents)
714 Opt.Commands.emplace_back(Cmd);
715 else
716 Opt.Assignments.emplace_back(Cmd);
717 } else {
George Rimar57610422016-03-11 14:43:02 +0000718 setError("unknown directive: " + Tok);
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000719 }
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000720 }
721}
722
Rui Ueyama717677a2016-02-11 21:17:59 +0000723void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000724 if (IsUnderSysroot && S.startswith("/")) {
725 SmallString<128> Path;
726 (Config->Sysroot + S).toStringRef(Path);
727 if (sys::fs::exists(Path)) {
728 Driver->addFile(Saver.save(Path.str()));
729 return;
730 }
731 }
732
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +0000733 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +0000734 Driver->addFile(S);
735 } else if (S.startswith("=")) {
736 if (Config->Sysroot.empty())
737 Driver->addFile(S.substr(1));
738 else
739 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
740 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +0000741 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +0000742 } else if (sys::fs::exists(S)) {
743 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +0000744 } else {
745 std::string Path = findFromSearchPaths(S);
746 if (Path.empty())
George Rimar777f9632016-03-12 08:31:34 +0000747 setError("unable to find " + S);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000748 else
749 Driver->addFile(Saver.save(Path));
Rui Ueyama52a15092015-10-11 03:28:42 +0000750 }
751}
752
Rui Ueyama717677a2016-02-11 21:17:59 +0000753void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000754 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +0000755 bool Orig = Config->AsNeeded;
756 Config->AsNeeded = true;
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000757 while (!Error && !skip(")"))
758 addFile(next());
Rui Ueyama35da9b62015-10-11 20:59:12 +0000759 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000760}
761
Rui Ueyama717677a2016-02-11 21:17:59 +0000762void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +0000763 // -e <symbol> takes predecence over ENTRY(<symbol>).
764 expect("(");
765 StringRef Tok = next();
766 if (Config->Entry.empty())
767 Config->Entry = Tok;
768 expect(")");
769}
770
Rui Ueyama717677a2016-02-11 21:17:59 +0000771void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +0000772 expect("(");
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000773 while (!Error && !skip(")"))
774 Config->Undefined.push_back(next());
George Rimar83f406c2015-10-19 17:35:12 +0000775}
776
Rui Ueyama717677a2016-02-11 21:17:59 +0000777void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000778 expect("(");
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000779 while (!Error && !skip(")")) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000780 StringRef Tok = next();
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000781 if (Tok == "AS_NEEDED")
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000782 readAsNeeded();
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000783 else
784 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000785 }
786}
787
Rui Ueyama717677a2016-02-11 21:17:59 +0000788void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000789 StringRef Tok = next();
790 auto MBOrErr = MemoryBuffer::getFile(Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000791 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +0000792 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000793 return;
794 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000795 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Rui Ueyamaa47ee682015-10-11 01:53:04 +0000796 StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
797 std::vector<StringRef> V = tokenize(S);
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000798 Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000799}
800
Rui Ueyama717677a2016-02-11 21:17:59 +0000801void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +0000802 // -o <file> takes predecence over OUTPUT(<file>).
803 expect("(");
804 StringRef Tok = next();
805 if (Config->OutputFile.empty())
806 Config->OutputFile = Tok;
807 expect(")");
808}
809
Rui Ueyama717677a2016-02-11 21:17:59 +0000810void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +0000811 // Error checking only for now.
812 expect("(");
813 next();
814 expect(")");
815}
816
Rui Ueyama717677a2016-02-11 21:17:59 +0000817void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000818 // Error checking only for now.
819 expect("(");
820 next();
Davide Italiano6836c612015-10-12 21:08:41 +0000821 StringRef Tok = next();
822 if (Tok == ")")
823 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000824 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +0000825 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000826 return;
827 }
Davide Italiano6836c612015-10-12 21:08:41 +0000828 next();
829 expect(",");
830 next();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000831 expect(")");
832}
833
Eugene Leviantbbe38602016-07-19 09:25:43 +0000834void ScriptParser::readPhdrs() {
835 expect("{");
836 while (!Error && !skip("}")) {
837 StringRef Tok = next();
Eugene Leviant865bf862016-07-21 10:43:25 +0000838 Opt.PhdrsCommands.push_back({Tok, PT_NULL, false, false, UINT_MAX});
Eugene Leviantbbe38602016-07-19 09:25:43 +0000839 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
840
841 PhdrCmd.Type = readPhdrType();
842 do {
843 Tok = next();
844 if (Tok == ";")
845 break;
846 if (Tok == "FILEHDR")
847 PhdrCmd.HasFilehdr = true;
848 else if (Tok == "PHDRS")
849 PhdrCmd.HasPhdrs = true;
Eugene Leviant865bf862016-07-21 10:43:25 +0000850 else if (Tok == "FLAGS") {
851 expect("(");
Rafael Espindolaeb685cd2016-08-02 22:14:57 +0000852 // Passing 0 for the value of dot is a bit of a hack. It means that
853 // we accept expressions like ".|1".
854 PhdrCmd.Flags = readExpr()(0);
Eugene Leviant865bf862016-07-21 10:43:25 +0000855 expect(")");
856 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +0000857 setError("unexpected header attribute: " + Tok);
858 } while (!Error);
859 }
860}
861
Rui Ueyama717677a2016-02-11 21:17:59 +0000862void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +0000863 expect("(");
Rui Ueyama6c7ad132016-09-02 19:20:33 +0000864 if (!Config->Nostdlib)
865 Config->SearchPaths.push_back(next());
Davide Italiano68a39a62015-10-08 17:51:41 +0000866 expect(")");
867}
868
Rui Ueyama717677a2016-02-11 21:17:59 +0000869void ScriptParser::readSections() {
Rui Ueyama3de0a332016-07-29 03:31:09 +0000870 Opt.HasContents = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000871 expect("{");
George Rimar652852c2016-04-16 10:10:32 +0000872 while (!Error && !skip("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +0000873 StringRef Tok = next();
Eugene Leviantceabe802016-08-11 07:56:43 +0000874 BaseCommand *Cmd = readProvideOrAssignment(Tok);
875 if (!Cmd) {
876 if (Tok == "ASSERT")
877 Cmd = new AssertCommand(readAssert());
878 else
879 Cmd = readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +0000880 }
Rui Ueyama10416562016-08-04 02:03:27 +0000881 Opt.Commands.emplace_back(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000882 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000883}
884
Rui Ueyama708019c2016-07-24 18:19:40 +0000885static int precedence(StringRef Op) {
886 return StringSwitch<int>(Op)
887 .Case("*", 4)
888 .Case("/", 4)
889 .Case("+", 3)
890 .Case("-", 3)
891 .Case("<", 2)
892 .Case(">", 2)
893 .Case(">=", 2)
894 .Case("<=", 2)
895 .Case("==", 2)
896 .Case("!=", 2)
897 .Case("&", 1)
Rafael Espindolacc3dd622016-08-22 21:33:35 +0000898 .Case("|", 1)
Rui Ueyama708019c2016-07-24 18:19:40 +0000899 .Default(-1);
900}
901
George Rimarc91930a2016-09-02 21:17:20 +0000902Regex ScriptParser::readFilePatterns() {
Rui Ueyama10416562016-08-04 02:03:27 +0000903 std::vector<StringRef> V;
904 while (!Error && !skip(")"))
905 V.push_back(next());
George Rimarc91930a2016-09-02 21:17:20 +0000906 return compileGlobPatterns(V);
George Rimar0702c4e2016-07-29 15:32:46 +0000907}
908
Rui Ueyama742c3832016-08-04 22:27:00 +0000909SortKind ScriptParser::readSortKind() {
910 if (skip("SORT") || skip("SORT_BY_NAME"))
911 return SortByName;
912 if (skip("SORT_BY_ALIGNMENT"))
913 return SortByAlignment;
914 return SortNone;
915}
916
George Rimara2496cb2016-08-30 09:46:59 +0000917InputSectionDescription *
918ScriptParser::readInputSectionRules(StringRef FilePattern) {
George Rimarc91930a2016-09-02 21:17:20 +0000919 auto *Cmd = new InputSectionDescription(FilePattern);
Davide Italiano0ed42b02016-07-25 21:47:13 +0000920 expect("(");
Davide Italianoe7282792016-07-27 01:44:01 +0000921
Rui Ueyama742c3832016-08-04 22:27:00 +0000922 // Read EXCLUDE_FILE().
Davide Italianoe7282792016-07-27 01:44:01 +0000923 if (skip("EXCLUDE_FILE")) {
924 expect("(");
George Rimarc91930a2016-09-02 21:17:20 +0000925 Cmd->ExcludedFileRe = readFilePatterns();
Davide Italiano0ed42b02016-07-25 21:47:13 +0000926 }
George Rimar06598002016-07-28 21:51:30 +0000927
Rui Ueyama742c3832016-08-04 22:27:00 +0000928 // Read SORT().
929 if (SortKind K1 = readSortKind()) {
930 Cmd->SortOuter = K1;
George Rimar0702c4e2016-07-29 15:32:46 +0000931 expect("(");
Rui Ueyama742c3832016-08-04 22:27:00 +0000932 if (SortKind K2 = readSortKind()) {
933 Cmd->SortInner = K2;
George Rimar350ece42016-08-03 08:35:59 +0000934 expect("(");
George Rimarc91930a2016-09-02 21:17:20 +0000935 Cmd->SectionRe = readFilePatterns();
George Rimar350ece42016-08-03 08:35:59 +0000936 expect(")");
937 } else {
George Rimarc91930a2016-09-02 21:17:20 +0000938 Cmd->SectionRe = readFilePatterns();
George Rimar350ece42016-08-03 08:35:59 +0000939 }
George Rimar0702c4e2016-07-29 15:32:46 +0000940 expect(")");
Rui Ueyama10416562016-08-04 02:03:27 +0000941 return Cmd;
George Rimar06598002016-07-28 21:51:30 +0000942 }
George Rimar0702c4e2016-07-29 15:32:46 +0000943
George Rimarc91930a2016-09-02 21:17:20 +0000944 Cmd->SectionRe = readFilePatterns();
Rui Ueyama10416562016-08-04 02:03:27 +0000945 return Cmd;
Davide Italianoe7282792016-07-27 01:44:01 +0000946}
947
George Rimara2496cb2016-08-30 09:46:59 +0000948InputSectionDescription *
949ScriptParser::readInputSectionDescription(StringRef Tok) {
George Rimar06598002016-07-28 21:51:30 +0000950 // Input section wildcard can be surrounded by KEEP.
951 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
George Rimara2496cb2016-08-30 09:46:59 +0000952 if (Tok == "KEEP") {
George Rimar06598002016-07-28 21:51:30 +0000953 expect("(");
George Rimara2496cb2016-08-30 09:46:59 +0000954 StringRef FilePattern = next();
955 InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
George Rimar06598002016-07-28 21:51:30 +0000956 expect(")");
George Rimarc91930a2016-09-02 21:17:20 +0000957 Opt.KeptSections.push_back(&Cmd->SectionRe);
Rui Ueyama10416562016-08-04 02:03:27 +0000958 return Cmd;
George Rimar06598002016-07-28 21:51:30 +0000959 }
George Rimara2496cb2016-08-30 09:46:59 +0000960 return readInputSectionRules(Tok);
Davide Italiano0ed42b02016-07-25 21:47:13 +0000961}
962
George Rimar03fc0102016-07-28 07:18:23 +0000963void ScriptParser::readSort() {
964 expect("(");
965 expect("CONSTRUCTORS");
966 expect(")");
967}
968
George Rimareefa7582016-08-04 09:29:31 +0000969Expr ScriptParser::readAssert() {
970 expect("(");
971 Expr E = readExpr();
972 expect(",");
973 StringRef Msg = next();
974 expect(")");
975 return [=](uint64_t Dot) {
976 uint64_t V = E(Dot);
977 if (!V)
978 error(Msg);
979 return V;
980 };
981}
982
Rui Ueyama10416562016-08-04 02:03:27 +0000983OutputSectionCommand *
984ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +0000985 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
George Rimar58e5c4d2016-07-25 08:29:46 +0000986
987 // Read an address expression.
988 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
989 if (peek() != ":")
990 Cmd->AddrExpr = readExpr();
991
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000992 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +0000993
George Rimar8ceadb32016-08-17 07:44:19 +0000994 if (skip("AT"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +0000995 Cmd->LmaExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +0000996 if (skip("ALIGN"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +0000997 Cmd->AlignExpr = readParenExpr();
George Rimardb24d9c2016-08-19 15:18:23 +0000998 if (skip("SUBALIGN"))
999 Cmd->SubalignExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001000
Davide Italiano246f6812016-07-22 03:36:24 +00001001 // Parse constraints.
1002 if (skip("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001003 Cmd->Constraint = ConstraintKind::ReadOnly;
Davide Italiano246f6812016-07-22 03:36:24 +00001004 if (skip("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001005 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001006 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001007
Rui Ueyama025d59b2016-02-02 20:27:59 +00001008 while (!Error && !skip("}")) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001009 StringRef Tok = next();
1010 if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok))
1011 Cmd->Commands.emplace_back(Assignment);
1012 else if (Tok == "SORT")
George Rimar03fc0102016-07-28 07:18:23 +00001013 readSort();
George Rimara2496cb2016-08-30 09:46:59 +00001014 else if (peek() == "(")
1015 Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
Eugene Leviantceabe802016-08-11 07:56:43 +00001016 else
1017 setError("unknown command " + Tok);
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001018 }
George Rimar076fe152016-07-21 06:43:01 +00001019 Cmd->Phdrs = readOutputSectionPhdrs();
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001020 Cmd->Filler = readOutputSectionFiller();
Rui Ueyama10416562016-08-04 02:03:27 +00001021 return Cmd;
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001022}
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001023
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001024// Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
1025// https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
1026//
1027// ld.gold is not fully compatible with ld.bfd. ld.bfd handles
1028// hexstrings as blobs of arbitrary sizes, while ld.gold handles them
1029// as 32-bit big-endian values. We will do the same as ld.gold does
1030// because it's simpler than what ld.bfd does.
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001031std::vector<uint8_t> ScriptParser::readOutputSectionFiller() {
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001032 if (!peek().startswith("="))
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001033 return {};
Rui Ueyama965827d2016-08-03 23:25:15 +00001034
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001035 StringRef Tok = next();
Rui Ueyama965827d2016-08-03 23:25:15 +00001036 uint32_t V;
1037 if (Tok.substr(1).getAsInteger(0, V)) {
1038 setError("invalid filler expression: " + Tok);
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001039 return {};
George Rimare2ee72b2016-02-26 14:48:31 +00001040 }
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001041 return {uint8_t(V >> 24), uint8_t(V >> 16), uint8_t(V >> 8), uint8_t(V)};
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001042}
1043
Petr Hoseka35e39c2016-08-16 01:11:16 +00001044SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
Eugene Levianta31c91b2016-07-22 07:38:40 +00001045 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +00001046 SymbolAssignment *Cmd = readAssignment(next());
Petr Hoseka35e39c2016-08-16 01:11:16 +00001047 Cmd->Provide = Provide;
Rui Ueyama174e0a12016-07-29 00:29:25 +00001048 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001049 expect(")");
1050 expect(";");
Rui Ueyama10416562016-08-04 02:03:27 +00001051 return Cmd;
Eugene Levianteda81a12016-07-12 06:39:48 +00001052}
1053
Eugene Leviantceabe802016-08-11 07:56:43 +00001054SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
1055 SymbolAssignment *Cmd = nullptr;
1056 if (peek() == "=" || peek() == "+=") {
1057 Cmd = readAssignment(Tok);
1058 expect(";");
1059 } else if (Tok == "PROVIDE") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001060 Cmd = readProvideHidden(true, false);
1061 } else if (Tok == "HIDDEN") {
1062 Cmd = readProvideHidden(false, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001063 } else if (Tok == "PROVIDE_HIDDEN") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001064 Cmd = readProvideHidden(true, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001065 }
1066 return Cmd;
1067}
1068
George Rimar30835ea2016-07-28 21:08:56 +00001069static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
1070 if (S == ".")
1071 return Dot;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001072
George Rimara9c5a522016-07-26 18:18:58 +00001073 switch (Config->EKind) {
1074 case ELF32LEKind:
1075 if (SymbolBody *B = Symtab<ELF32LE>::X->find(S))
1076 return B->getVA<ELF32LE>();
1077 break;
1078 case ELF32BEKind:
1079 if (SymbolBody *B = Symtab<ELF32BE>::X->find(S))
1080 return B->getVA<ELF32BE>();
1081 break;
1082 case ELF64LEKind:
1083 if (SymbolBody *B = Symtab<ELF64LE>::X->find(S))
1084 return B->getVA<ELF64LE>();
1085 break;
1086 case ELF64BEKind:
1087 if (SymbolBody *B = Symtab<ELF64BE>::X->find(S))
1088 return B->getVA<ELF64BE>();
1089 break;
George Rimar6930a6d2016-07-26 18:41:06 +00001090 default:
George Rimarb567b622016-07-26 18:46:13 +00001091 llvm_unreachable("unsupported target");
George Rimara9c5a522016-07-26 18:18:58 +00001092 }
1093 error("symbol not found: " + S);
1094 return 0;
1095}
1096
George Rimar9e694502016-07-29 16:18:47 +00001097static uint64_t getSectionSize(StringRef Name) {
1098 switch (Config->EKind) {
1099 case ELF32LEKind:
1100 return Script<ELF32LE>::X->getOutputSectionSize(Name);
1101 case ELF32BEKind:
1102 return Script<ELF32BE>::X->getOutputSectionSize(Name);
1103 case ELF64LEKind:
1104 return Script<ELF64LE>::X->getOutputSectionSize(Name);
1105 case ELF64BEKind:
1106 return Script<ELF64BE>::X->getOutputSectionSize(Name);
1107 default:
1108 llvm_unreachable("unsupported target");
1109 }
George Rimar9e694502016-07-29 16:18:47 +00001110}
1111
George Rimar96659df2016-08-30 09:54:01 +00001112static uint64_t getSectionAddress(StringRef Name) {
1113 switch (Config->EKind) {
1114 case ELF32LEKind:
1115 return Script<ELF32LE>::X->getOutputSectionAddress(Name);
1116 case ELF32BEKind:
1117 return Script<ELF32BE>::X->getOutputSectionAddress(Name);
1118 case ELF64LEKind:
1119 return Script<ELF64LE>::X->getOutputSectionAddress(Name);
1120 case ELF64BEKind:
1121 return Script<ELF64BE>::X->getOutputSectionAddress(Name);
1122 default:
1123 llvm_unreachable("unsupported target");
1124 }
1125}
1126
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001127static uint64_t getHeaderSize() {
George Rimare32a3592016-08-10 07:59:34 +00001128 switch (Config->EKind) {
1129 case ELF32LEKind:
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001130 return Script<ELF32LE>::X->getHeaderSize();
George Rimare32a3592016-08-10 07:59:34 +00001131 case ELF32BEKind:
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001132 return Script<ELF32BE>::X->getHeaderSize();
George Rimare32a3592016-08-10 07:59:34 +00001133 case ELF64LEKind:
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001134 return Script<ELF64LE>::X->getHeaderSize();
George Rimare32a3592016-08-10 07:59:34 +00001135 case ELF64BEKind:
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001136 return Script<ELF64BE>::X->getHeaderSize();
George Rimare32a3592016-08-10 07:59:34 +00001137 default:
1138 llvm_unreachable("unsupported target");
1139 }
1140}
1141
George Rimar30835ea2016-07-28 21:08:56 +00001142SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1143 StringRef Op = next();
1144 assert(Op == "=" || Op == "+=");
1145 Expr E = readExpr();
1146 if (Op == "+=")
1147 E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
Rui Ueyama10416562016-08-04 02:03:27 +00001148 return new SymbolAssignment(Name, E);
George Rimar30835ea2016-07-28 21:08:56 +00001149}
1150
1151// This is an operator-precedence parser to parse a linker
1152// script expression.
1153Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
1154
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001155static Expr combine(StringRef Op, Expr L, Expr R) {
1156 if (Op == "*")
1157 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1158 if (Op == "/") {
1159 return [=](uint64_t Dot) -> uint64_t {
1160 uint64_t RHS = R(Dot);
1161 if (RHS == 0) {
1162 error("division by zero");
1163 return 0;
1164 }
1165 return L(Dot) / RHS;
1166 };
1167 }
1168 if (Op == "+")
1169 return [=](uint64_t Dot) { return L(Dot) + R(Dot); };
1170 if (Op == "-")
1171 return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
1172 if (Op == "<")
1173 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
1174 if (Op == ">")
1175 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
1176 if (Op == ">=")
1177 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
1178 if (Op == "<=")
1179 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
1180 if (Op == "==")
1181 return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
1182 if (Op == "!=")
1183 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
1184 if (Op == "&")
1185 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
Rafael Espindolacc3dd622016-08-22 21:33:35 +00001186 if (Op == "|")
1187 return [=](uint64_t Dot) { return L(Dot) | R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001188 llvm_unreachable("invalid operator");
1189}
1190
Rui Ueyama708019c2016-07-24 18:19:40 +00001191// This is a part of the operator-precedence parser. This function
1192// assumes that the remaining token stream starts with an operator.
1193Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1194 while (!atEOF() && !Error) {
1195 // Read an operator and an expression.
1196 StringRef Op1 = peek();
1197 if (Op1 == "?")
1198 return readTernary(Lhs);
1199 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +00001200 break;
Rui Ueyama708019c2016-07-24 18:19:40 +00001201 next();
1202 Expr Rhs = readPrimary();
1203
1204 // Evaluate the remaining part of the expression first if the
1205 // next operator has greater precedence than the previous one.
1206 // For example, if we have read "+" and "3", and if the next
1207 // operator is "*", then we'll evaluate 3 * ... part first.
1208 while (!atEOF()) {
1209 StringRef Op2 = peek();
1210 if (precedence(Op2) <= precedence(Op1))
1211 break;
1212 Rhs = readExpr1(Rhs, precedence(Op2));
1213 }
1214
1215 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +00001216 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001217 return Lhs;
1218}
1219
1220uint64_t static getConstant(StringRef S) {
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001221 if (S == "COMMONPAGESIZE")
Rui Ueyama708019c2016-07-24 18:19:40 +00001222 return Target->PageSize;
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001223 if (S == "MAXPAGESIZE")
1224 return Target->MaxPageSize;
Rui Ueyama708019c2016-07-24 18:19:40 +00001225 error("unknown constant: " + S);
1226 return 0;
1227}
1228
Rui Ueyama626e0b02016-09-02 18:19:00 +00001229// Parses Tok as an integer. Returns true if successful.
1230// It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1231// and decimal numbers. Decimal numbers may have "K" (kilo) or
1232// "M" (mega) prefixes.
George Rimar9f2f7ad2016-09-02 16:01:42 +00001233static bool readInteger(StringRef Tok, uint64_t &Result) {
1234 if (Tok.startswith_lower("0x"))
1235 return !Tok.substr(2).getAsInteger(16, Result);
1236 if (Tok.endswith_lower("H"))
1237 return !Tok.drop_back().getAsInteger(16, Result);
1238
1239 int Suffix = 1;
1240 if (Tok.endswith_lower("K")) {
1241 Suffix = 1024;
1242 Tok = Tok.drop_back();
1243 } else if (Tok.endswith_lower("M")) {
1244 Suffix = 1024 * 1024;
1245 Tok = Tok.drop_back();
1246 }
1247 if (Tok.getAsInteger(10, Result))
1248 return false;
1249 Result *= Suffix;
1250 return true;
1251}
1252
Rui Ueyama708019c2016-07-24 18:19:40 +00001253Expr ScriptParser::readPrimary() {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001254 if (peek() == "(")
1255 return readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001256
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001257 StringRef Tok = next();
Rui Ueyama708019c2016-07-24 18:19:40 +00001258
1259 // Built-in functions are parsed here.
1260 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
George Rimar96659df2016-08-30 09:54:01 +00001261 if (Tok == "ADDR") {
1262 expect("(");
1263 StringRef Name = next();
1264 expect(")");
1265 return [=](uint64_t Dot) { return getSectionAddress(Name); };
1266 }
George Rimareefa7582016-08-04 09:29:31 +00001267 if (Tok == "ASSERT")
1268 return readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001269 if (Tok == "ALIGN") {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001270 Expr E = readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001271 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1272 }
1273 if (Tok == "CONSTANT") {
1274 expect("(");
1275 StringRef Tok = next();
1276 expect(")");
1277 return [=](uint64_t Dot) { return getConstant(Tok); };
1278 }
Rafael Espindola54c145c2016-07-28 18:16:24 +00001279 if (Tok == "SEGMENT_START") {
1280 expect("(");
1281 next();
1282 expect(",");
1283 uint64_t Val;
1284 next().getAsInteger(0, Val);
1285 expect(")");
1286 return [=](uint64_t Dot) { return Val; };
1287 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001288 if (Tok == "DATA_SEGMENT_ALIGN") {
1289 expect("(");
1290 Expr E = readExpr();
1291 expect(",");
1292 readExpr();
1293 expect(")");
Rui Ueyamaf7791bb2016-07-26 19:34:10 +00001294 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001295 }
1296 if (Tok == "DATA_SEGMENT_END") {
1297 expect("(");
1298 expect(".");
1299 expect(")");
1300 return [](uint64_t Dot) { return Dot; };
1301 }
George Rimar276b4e62016-07-26 17:58:44 +00001302 // GNU linkers implements more complicated logic to handle
1303 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1304 // the next page boundary for simplicity.
1305 if (Tok == "DATA_SEGMENT_RELRO_END") {
1306 expect("(");
1307 next();
1308 expect(",");
1309 readExpr();
1310 expect(")");
1311 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1312 }
George Rimar9e694502016-07-29 16:18:47 +00001313 if (Tok == "SIZEOF") {
1314 expect("(");
1315 StringRef Name = next();
1316 expect(")");
1317 return [=](uint64_t Dot) { return getSectionSize(Name); };
1318 }
George Rimare32a3592016-08-10 07:59:34 +00001319 if (Tok == "SIZEOF_HEADERS")
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001320 return [=](uint64_t Dot) { return getHeaderSize(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001321
George Rimar9f2f7ad2016-09-02 16:01:42 +00001322 // Tok is a literal number.
1323 uint64_t V;
1324 if (readInteger(Tok, V))
1325 return [=](uint64_t Dot) { return V; };
1326
1327 // Tok is a symbol name.
1328 if (Tok != "." && !isValidCIdentifier(Tok))
1329 setError("malformed number: " + Tok);
1330 return [=](uint64_t Dot) { return getSymbolValue(Tok, Dot); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001331}
1332
1333Expr ScriptParser::readTernary(Expr Cond) {
1334 next();
1335 Expr L = readExpr();
1336 expect(":");
1337 Expr R = readExpr();
1338 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1339}
1340
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001341Expr ScriptParser::readParenExpr() {
1342 expect("(");
1343 Expr E = readExpr();
1344 expect(")");
1345 return E;
1346}
1347
Eugene Leviantbbe38602016-07-19 09:25:43 +00001348std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1349 std::vector<StringRef> Phdrs;
1350 while (!Error && peek().startswith(":")) {
1351 StringRef Tok = next();
1352 Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
1353 if (Tok.empty()) {
1354 setError("section header name is empty");
1355 break;
1356 }
Rui Ueyama047404f2016-07-20 19:36:36 +00001357 Phdrs.push_back(Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001358 }
1359 return Phdrs;
1360}
1361
1362unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001363 StringRef Tok = next();
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001364 unsigned Ret = StringSwitch<unsigned>(Tok)
1365 .Case("PT_NULL", PT_NULL)
1366 .Case("PT_LOAD", PT_LOAD)
1367 .Case("PT_DYNAMIC", PT_DYNAMIC)
1368 .Case("PT_INTERP", PT_INTERP)
1369 .Case("PT_NOTE", PT_NOTE)
1370 .Case("PT_SHLIB", PT_SHLIB)
1371 .Case("PT_PHDR", PT_PHDR)
1372 .Case("PT_TLS", PT_TLS)
1373 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1374 .Case("PT_GNU_STACK", PT_GNU_STACK)
1375 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1376 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001377
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001378 if (Ret == (unsigned)-1) {
1379 setError("invalid program header type: " + Tok);
1380 return PT_NULL;
1381 }
1382 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001383}
1384
Rui Ueyama95769b42016-08-31 20:03:54 +00001385void ScriptParser::readVersionDeclaration(StringRef VerStr) {
George Rimar20b65982016-08-31 09:08:26 +00001386 // Identifiers start at 2 because 0 and 1 are reserved
1387 // for VER_NDX_LOCAL and VER_NDX_GLOBAL constants.
1388 size_t VersionId = Config->VersionDefinitions.size() + 2;
1389 Config->VersionDefinitions.push_back({VerStr, VersionId});
1390
1391 if (skip("global:") || peek() != "local:")
1392 readGlobal(VerStr);
1393 if (skip("local:"))
1394 readLocal();
1395 expect("}");
1396
1397 // Each version may have a parent version. For example, "Ver2" defined as
1398 // "Ver2 { global: foo; local: *; } Ver1;" has "Ver1" as a parent. This
1399 // version hierarchy is, probably against your instinct, purely for human; the
1400 // runtime doesn't care about them at all. In LLD, we simply skip the token.
1401 if (!VerStr.empty() && peek() != ";")
1402 next();
1403 expect(";");
1404}
1405
1406void ScriptParser::readLocal() {
1407 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1408 expect("*");
1409 expect(";");
1410}
1411
1412void ScriptParser::readExtern(std::vector<SymbolVersion> *Globals) {
1413 expect("C++");
1414 expect("{");
1415
1416 for (;;) {
1417 if (peek() == "}" || Error)
1418 break;
1419 Globals->push_back({next(), true});
1420 expect(";");
1421 }
1422
1423 expect("}");
1424 expect(";");
1425}
1426
1427void ScriptParser::readGlobal(StringRef VerStr) {
1428 std::vector<SymbolVersion> *Globals;
1429 if (VerStr.empty())
1430 Globals = &Config->VersionScriptGlobals;
1431 else
1432 Globals = &Config->VersionDefinitions.back().Globals;
1433
1434 for (;;) {
1435 if (skip("extern"))
1436 readExtern(Globals);
1437
1438 StringRef Cur = peek();
1439 if (Cur == "}" || Cur == "local:" || Error)
1440 return;
1441 next();
1442 Globals->push_back({Cur, false});
1443 expect(";");
1444 }
1445}
1446
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001447static bool isUnderSysroot(StringRef Path) {
1448 if (Config->Sysroot == "")
1449 return false;
1450 for (; !Path.empty(); Path = sys::path::parent_path(Path))
1451 if (sys::fs::equivalent(Config->Sysroot, Path))
1452 return true;
1453 return false;
1454}
1455
Rui Ueyama07320e42016-04-20 20:13:41 +00001456void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001457 StringRef Path = MB.getBufferIdentifier();
George Rimar20b65982016-08-31 09:08:26 +00001458 ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).readLinkerScript();
1459}
1460
1461void elf::readVersionScript(MemoryBufferRef MB) {
1462 ScriptParser(MB.getBuffer(), false).readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001463}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001464
Rui Ueyama07320e42016-04-20 20:13:41 +00001465template class elf::LinkerScript<ELF32LE>;
1466template class elf::LinkerScript<ELF32BE>;
1467template class elf::LinkerScript<ELF64LE>;
1468template class elf::LinkerScript<ELF64BE>;