blob: 5f04382a64b45c2f4253e5282f1c2dc848827c3b [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;
Rui Ueyamaadcdb662016-09-06 22:50:48 +0000165 return !(RO && Writable) && !(RW && !Writable);
George Rimar8f66df92016-08-12 20:38:20 +0000166}
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);
George Rimarff1f29e2016-09-06 13:51:57 +0000624 std::vector<uint8_t> readFill();
Rui Ueyama10416562016-08-04 02:03:27 +0000625 OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
George Rimarff1f29e2016-09-06 13:51:57 +0000626 std::vector<uint8_t> readOutputSectionFiller(StringRef Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000627 std::vector<StringRef> readOutputSectionPhdrs();
George Rimara2496cb2016-08-30 09:46:59 +0000628 InputSectionDescription *readInputSectionDescription(StringRef Tok);
George Rimarc91930a2016-09-02 21:17:20 +0000629 Regex readFilePatterns();
George Rimara2496cb2016-08-30 09:46:59 +0000630 InputSectionDescription *readInputSectionRules(StringRef FilePattern);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000631 unsigned readPhdrType();
Rui Ueyama742c3832016-08-04 22:27:00 +0000632 SortKind readSortKind();
Petr Hoseka35e39c2016-08-16 01:11:16 +0000633 SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
Eugene Leviantceabe802016-08-11 07:56:43 +0000634 SymbolAssignment *readProvideOrAssignment(StringRef Tok);
George Rimar03fc0102016-07-28 07:18:23 +0000635 void readSort();
George Rimareefa7582016-08-04 09:29:31 +0000636 Expr readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +0000637
638 Expr readExpr();
639 Expr readExpr1(Expr Lhs, int MinPrec);
640 Expr readPrimary();
641 Expr readTernary(Expr Cond);
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +0000642 Expr readParenExpr();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000643
George Rimar20b65982016-08-31 09:08:26 +0000644 // For parsing version script.
645 void readExtern(std::vector<SymbolVersion> *Globals);
Rui Ueyama95769b42016-08-31 20:03:54 +0000646 void readVersionDeclaration(StringRef VerStr);
George Rimar20b65982016-08-31 09:08:26 +0000647 void readGlobal(StringRef VerStr);
648 void readLocal();
649
Rui Ueyama07320e42016-04-20 20:13:41 +0000650 ScriptConfiguration &Opt = *ScriptConfig;
651 StringSaver Saver = {ScriptConfig->Alloc};
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000652 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000653};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000654
George Rimar20b65982016-08-31 09:08:26 +0000655void ScriptParser::readVersionScript() {
Rui Ueyama95769b42016-08-31 20:03:54 +0000656 readVersionScriptCommand();
657 if (!atEOF())
658 setError("EOF expected, but got " + next());
659}
660
661void ScriptParser::readVersionScriptCommand() {
George Rimar20b65982016-08-31 09:08:26 +0000662 if (skip("{")) {
Rui Ueyama95769b42016-08-31 20:03:54 +0000663 readVersionDeclaration("");
George Rimar20b65982016-08-31 09:08:26 +0000664 return;
665 }
666
Rui Ueyama95769b42016-08-31 20:03:54 +0000667 while (!atEOF() && !Error && peek() != "}") {
George Rimar20b65982016-08-31 09:08:26 +0000668 StringRef VerStr = next();
669 if (VerStr == "{") {
Rui Ueyama95769b42016-08-31 20:03:54 +0000670 setError("anonymous version definition is used in "
671 "combination with other version definitions");
George Rimar20b65982016-08-31 09:08:26 +0000672 return;
673 }
674 expect("{");
Rui Ueyama95769b42016-08-31 20:03:54 +0000675 readVersionDeclaration(VerStr);
George Rimar20b65982016-08-31 09:08:26 +0000676 }
677}
678
Rui Ueyama95769b42016-08-31 20:03:54 +0000679void ScriptParser::readVersion() {
680 expect("{");
681 readVersionScriptCommand();
682 expect("}");
683}
684
George Rimar20b65982016-08-31 09:08:26 +0000685void ScriptParser::readLinkerScript() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000686 while (!atEOF()) {
687 StringRef Tok = next();
Rui Ueyamaa27eecc2016-09-02 18:52:41 +0000688 if (Tok == ";")
689 continue;
690
691 if (Tok == "ENTRY") {
692 readEntry();
693 } else if (Tok == "EXTERN") {
694 readExtern();
695 } else if (Tok == "GROUP" || Tok == "INPUT") {
696 readGroup();
697 } else if (Tok == "INCLUDE") {
698 readInclude();
699 } else if (Tok == "OUTPUT") {
700 readOutput();
701 } else if (Tok == "OUTPUT_ARCH") {
702 readOutputArch();
703 } else if (Tok == "OUTPUT_FORMAT") {
704 readOutputFormat();
705 } else if (Tok == "PHDRS") {
706 readPhdrs();
707 } else if (Tok == "SEARCH_DIR") {
708 readSearchDir();
709 } else if (Tok == "SECTIONS") {
710 readSections();
711 } else if (Tok == "VERSION") {
712 readVersion();
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000713 } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok)) {
714 if (Opt.HasContents)
715 Opt.Commands.emplace_back(Cmd);
716 else
717 Opt.Assignments.emplace_back(Cmd);
718 } else {
George Rimar57610422016-03-11 14:43:02 +0000719 setError("unknown directive: " + Tok);
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000720 }
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000721 }
722}
723
Rui Ueyama717677a2016-02-11 21:17:59 +0000724void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000725 if (IsUnderSysroot && S.startswith("/")) {
726 SmallString<128> Path;
727 (Config->Sysroot + S).toStringRef(Path);
728 if (sys::fs::exists(Path)) {
729 Driver->addFile(Saver.save(Path.str()));
730 return;
731 }
732 }
733
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +0000734 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +0000735 Driver->addFile(S);
736 } else if (S.startswith("=")) {
737 if (Config->Sysroot.empty())
738 Driver->addFile(S.substr(1));
739 else
740 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
741 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +0000742 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +0000743 } else if (sys::fs::exists(S)) {
744 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +0000745 } else {
746 std::string Path = findFromSearchPaths(S);
747 if (Path.empty())
George Rimar777f9632016-03-12 08:31:34 +0000748 setError("unable to find " + S);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000749 else
750 Driver->addFile(Saver.save(Path));
Rui Ueyama52a15092015-10-11 03:28:42 +0000751 }
752}
753
Rui Ueyama717677a2016-02-11 21:17:59 +0000754void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000755 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +0000756 bool Orig = Config->AsNeeded;
757 Config->AsNeeded = true;
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000758 while (!Error && !skip(")"))
759 addFile(next());
Rui Ueyama35da9b62015-10-11 20:59:12 +0000760 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000761}
762
Rui Ueyama717677a2016-02-11 21:17:59 +0000763void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +0000764 // -e <symbol> takes predecence over ENTRY(<symbol>).
765 expect("(");
766 StringRef Tok = next();
767 if (Config->Entry.empty())
768 Config->Entry = Tok;
769 expect(")");
770}
771
Rui Ueyama717677a2016-02-11 21:17:59 +0000772void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +0000773 expect("(");
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000774 while (!Error && !skip(")"))
775 Config->Undefined.push_back(next());
George Rimar83f406c2015-10-19 17:35:12 +0000776}
777
Rui Ueyama717677a2016-02-11 21:17:59 +0000778void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000779 expect("(");
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000780 while (!Error && !skip(")")) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000781 StringRef Tok = next();
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000782 if (Tok == "AS_NEEDED")
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000783 readAsNeeded();
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000784 else
785 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000786 }
787}
788
Rui Ueyama717677a2016-02-11 21:17:59 +0000789void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000790 StringRef Tok = next();
791 auto MBOrErr = MemoryBuffer::getFile(Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000792 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +0000793 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000794 return;
795 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000796 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Rui Ueyamaa47ee682015-10-11 01:53:04 +0000797 StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
798 std::vector<StringRef> V = tokenize(S);
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000799 Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000800}
801
Rui Ueyama717677a2016-02-11 21:17:59 +0000802void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +0000803 // -o <file> takes predecence over OUTPUT(<file>).
804 expect("(");
805 StringRef Tok = next();
806 if (Config->OutputFile.empty())
807 Config->OutputFile = Tok;
808 expect(")");
809}
810
Rui Ueyama717677a2016-02-11 21:17:59 +0000811void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +0000812 // Error checking only for now.
813 expect("(");
814 next();
815 expect(")");
816}
817
Rui Ueyama717677a2016-02-11 21:17:59 +0000818void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000819 // Error checking only for now.
820 expect("(");
821 next();
Davide Italiano6836c612015-10-12 21:08:41 +0000822 StringRef Tok = next();
823 if (Tok == ")")
824 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000825 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +0000826 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000827 return;
828 }
Davide Italiano6836c612015-10-12 21:08:41 +0000829 next();
830 expect(",");
831 next();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000832 expect(")");
833}
834
Eugene Leviantbbe38602016-07-19 09:25:43 +0000835void ScriptParser::readPhdrs() {
836 expect("{");
837 while (!Error && !skip("}")) {
838 StringRef Tok = next();
Eugene Leviant865bf862016-07-21 10:43:25 +0000839 Opt.PhdrsCommands.push_back({Tok, PT_NULL, false, false, UINT_MAX});
Eugene Leviantbbe38602016-07-19 09:25:43 +0000840 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
841
842 PhdrCmd.Type = readPhdrType();
843 do {
844 Tok = next();
845 if (Tok == ";")
846 break;
847 if (Tok == "FILEHDR")
848 PhdrCmd.HasFilehdr = true;
849 else if (Tok == "PHDRS")
850 PhdrCmd.HasPhdrs = true;
Eugene Leviant865bf862016-07-21 10:43:25 +0000851 else if (Tok == "FLAGS") {
852 expect("(");
Rafael Espindolaeb685cd2016-08-02 22:14:57 +0000853 // Passing 0 for the value of dot is a bit of a hack. It means that
854 // we accept expressions like ".|1".
855 PhdrCmd.Flags = readExpr()(0);
Eugene Leviant865bf862016-07-21 10:43:25 +0000856 expect(")");
857 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +0000858 setError("unexpected header attribute: " + Tok);
859 } while (!Error);
860 }
861}
862
Rui Ueyama717677a2016-02-11 21:17:59 +0000863void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +0000864 expect("(");
Rui Ueyama6c7ad132016-09-02 19:20:33 +0000865 if (!Config->Nostdlib)
866 Config->SearchPaths.push_back(next());
Davide Italiano68a39a62015-10-08 17:51:41 +0000867 expect(")");
868}
869
Rui Ueyama717677a2016-02-11 21:17:59 +0000870void ScriptParser::readSections() {
Rui Ueyama3de0a332016-07-29 03:31:09 +0000871 Opt.HasContents = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000872 expect("{");
George Rimar652852c2016-04-16 10:10:32 +0000873 while (!Error && !skip("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +0000874 StringRef Tok = next();
Eugene Leviantceabe802016-08-11 07:56:43 +0000875 BaseCommand *Cmd = readProvideOrAssignment(Tok);
876 if (!Cmd) {
877 if (Tok == "ASSERT")
878 Cmd = new AssertCommand(readAssert());
879 else
880 Cmd = readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +0000881 }
Rui Ueyama10416562016-08-04 02:03:27 +0000882 Opt.Commands.emplace_back(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000883 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000884}
885
Rui Ueyama708019c2016-07-24 18:19:40 +0000886static int precedence(StringRef Op) {
887 return StringSwitch<int>(Op)
888 .Case("*", 4)
889 .Case("/", 4)
890 .Case("+", 3)
891 .Case("-", 3)
892 .Case("<", 2)
893 .Case(">", 2)
894 .Case(">=", 2)
895 .Case("<=", 2)
896 .Case("==", 2)
897 .Case("!=", 2)
898 .Case("&", 1)
Rafael Espindolacc3dd622016-08-22 21:33:35 +0000899 .Case("|", 1)
Rui Ueyama708019c2016-07-24 18:19:40 +0000900 .Default(-1);
901}
902
George Rimarc91930a2016-09-02 21:17:20 +0000903Regex ScriptParser::readFilePatterns() {
Rui Ueyama10416562016-08-04 02:03:27 +0000904 std::vector<StringRef> V;
905 while (!Error && !skip(")"))
906 V.push_back(next());
George Rimarc91930a2016-09-02 21:17:20 +0000907 return compileGlobPatterns(V);
George Rimar0702c4e2016-07-29 15:32:46 +0000908}
909
Rui Ueyama742c3832016-08-04 22:27:00 +0000910SortKind ScriptParser::readSortKind() {
911 if (skip("SORT") || skip("SORT_BY_NAME"))
912 return SortByName;
913 if (skip("SORT_BY_ALIGNMENT"))
914 return SortByAlignment;
915 return SortNone;
916}
917
George Rimara2496cb2016-08-30 09:46:59 +0000918InputSectionDescription *
919ScriptParser::readInputSectionRules(StringRef FilePattern) {
George Rimarc91930a2016-09-02 21:17:20 +0000920 auto *Cmd = new InputSectionDescription(FilePattern);
Davide Italiano0ed42b02016-07-25 21:47:13 +0000921 expect("(");
Davide Italianoe7282792016-07-27 01:44:01 +0000922
Rui Ueyama742c3832016-08-04 22:27:00 +0000923 // Read EXCLUDE_FILE().
Davide Italianoe7282792016-07-27 01:44:01 +0000924 if (skip("EXCLUDE_FILE")) {
925 expect("(");
George Rimarc91930a2016-09-02 21:17:20 +0000926 Cmd->ExcludedFileRe = readFilePatterns();
Davide Italiano0ed42b02016-07-25 21:47:13 +0000927 }
George Rimar06598002016-07-28 21:51:30 +0000928
Rui Ueyama742c3832016-08-04 22:27:00 +0000929 // Read SORT().
930 if (SortKind K1 = readSortKind()) {
931 Cmd->SortOuter = K1;
George Rimar0702c4e2016-07-29 15:32:46 +0000932 expect("(");
Rui Ueyama742c3832016-08-04 22:27:00 +0000933 if (SortKind K2 = readSortKind()) {
934 Cmd->SortInner = K2;
George Rimar350ece42016-08-03 08:35:59 +0000935 expect("(");
George Rimarc91930a2016-09-02 21:17:20 +0000936 Cmd->SectionRe = readFilePatterns();
George Rimar350ece42016-08-03 08:35:59 +0000937 expect(")");
938 } else {
George Rimarc91930a2016-09-02 21:17:20 +0000939 Cmd->SectionRe = readFilePatterns();
George Rimar350ece42016-08-03 08:35:59 +0000940 }
George Rimar0702c4e2016-07-29 15:32:46 +0000941 expect(")");
Rui Ueyama10416562016-08-04 02:03:27 +0000942 return Cmd;
George Rimar06598002016-07-28 21:51:30 +0000943 }
George Rimar0702c4e2016-07-29 15:32:46 +0000944
George Rimarc91930a2016-09-02 21:17:20 +0000945 Cmd->SectionRe = readFilePatterns();
Rui Ueyama10416562016-08-04 02:03:27 +0000946 return Cmd;
Davide Italianoe7282792016-07-27 01:44:01 +0000947}
948
George Rimara2496cb2016-08-30 09:46:59 +0000949InputSectionDescription *
950ScriptParser::readInputSectionDescription(StringRef Tok) {
George Rimar06598002016-07-28 21:51:30 +0000951 // Input section wildcard can be surrounded by KEEP.
952 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
George Rimara2496cb2016-08-30 09:46:59 +0000953 if (Tok == "KEEP") {
George Rimar06598002016-07-28 21:51:30 +0000954 expect("(");
George Rimara2496cb2016-08-30 09:46:59 +0000955 StringRef FilePattern = next();
956 InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
George Rimar06598002016-07-28 21:51:30 +0000957 expect(")");
George Rimarc91930a2016-09-02 21:17:20 +0000958 Opt.KeptSections.push_back(&Cmd->SectionRe);
Rui Ueyama10416562016-08-04 02:03:27 +0000959 return Cmd;
George Rimar06598002016-07-28 21:51:30 +0000960 }
George Rimara2496cb2016-08-30 09:46:59 +0000961 return readInputSectionRules(Tok);
Davide Italiano0ed42b02016-07-25 21:47:13 +0000962}
963
George Rimar03fc0102016-07-28 07:18:23 +0000964void ScriptParser::readSort() {
965 expect("(");
966 expect("CONSTRUCTORS");
967 expect(")");
968}
969
George Rimareefa7582016-08-04 09:29:31 +0000970Expr ScriptParser::readAssert() {
971 expect("(");
972 Expr E = readExpr();
973 expect(",");
974 StringRef Msg = next();
975 expect(")");
976 return [=](uint64_t Dot) {
977 uint64_t V = E(Dot);
978 if (!V)
979 error(Msg);
980 return V;
981 };
982}
983
Rui Ueyama25150e82016-09-06 17:46:43 +0000984// Reads a FILL(expr) command. We handle the FILL command as an
985// alias for =fillexp section attribute, which is different from
986// what GNU linkers do.
987// https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
George Rimarff1f29e2016-09-06 13:51:57 +0000988std::vector<uint8_t> ScriptParser::readFill() {
989 expect("(");
990 std::vector<uint8_t> V = readOutputSectionFiller(next());
991 expect(")");
992 expect(";");
993 return V;
994}
995
Rui Ueyama10416562016-08-04 02:03:27 +0000996OutputSectionCommand *
997ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +0000998 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
George Rimar58e5c4d2016-07-25 08:29:46 +0000999
1000 // Read an address expression.
1001 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
1002 if (peek() != ":")
1003 Cmd->AddrExpr = readExpr();
1004
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001005 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +00001006
George Rimar8ceadb32016-08-17 07:44:19 +00001007 if (skip("AT"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001008 Cmd->LmaExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001009 if (skip("ALIGN"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001010 Cmd->AlignExpr = readParenExpr();
George Rimardb24d9c2016-08-19 15:18:23 +00001011 if (skip("SUBALIGN"))
1012 Cmd->SubalignExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001013
Davide Italiano246f6812016-07-22 03:36:24 +00001014 // Parse constraints.
1015 if (skip("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001016 Cmd->Constraint = ConstraintKind::ReadOnly;
Davide Italiano246f6812016-07-22 03:36:24 +00001017 if (skip("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001018 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001019 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001020
Rui Ueyama025d59b2016-02-02 20:27:59 +00001021 while (!Error && !skip("}")) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001022 StringRef Tok = next();
1023 if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok))
1024 Cmd->Commands.emplace_back(Assignment);
George Rimarff1f29e2016-09-06 13:51:57 +00001025 else if (Tok == "FILL")
1026 Cmd->Filler = readFill();
Eugene Leviantceabe802016-08-11 07:56:43 +00001027 else if (Tok == "SORT")
George Rimar03fc0102016-07-28 07:18:23 +00001028 readSort();
George Rimara2496cb2016-08-30 09:46:59 +00001029 else if (peek() == "(")
1030 Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
Eugene Leviantceabe802016-08-11 07:56:43 +00001031 else
1032 setError("unknown command " + Tok);
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001033 }
George Rimar076fe152016-07-21 06:43:01 +00001034 Cmd->Phdrs = readOutputSectionPhdrs();
George Rimarff1f29e2016-09-06 13:51:57 +00001035 if (peek().startswith("="))
1036 Cmd->Filler = readOutputSectionFiller(next().drop_front());
Rui Ueyama10416562016-08-04 02:03:27 +00001037 return Cmd;
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001038}
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001039
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001040// Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
1041// https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
1042//
1043// ld.gold is not fully compatible with ld.bfd. ld.bfd handles
1044// hexstrings as blobs of arbitrary sizes, while ld.gold handles them
1045// as 32-bit big-endian values. We will do the same as ld.gold does
1046// because it's simpler than what ld.bfd does.
George Rimarff1f29e2016-09-06 13:51:57 +00001047std::vector<uint8_t> ScriptParser::readOutputSectionFiller(StringRef Tok) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001048 uint32_t V;
George Rimarff1f29e2016-09-06 13:51:57 +00001049 if (Tok.getAsInteger(0, V)) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001050 setError("invalid filler expression: " + Tok);
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001051 return {};
George Rimare2ee72b2016-02-26 14:48:31 +00001052 }
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001053 return {uint8_t(V >> 24), uint8_t(V >> 16), uint8_t(V >> 8), uint8_t(V)};
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001054}
1055
Petr Hoseka35e39c2016-08-16 01:11:16 +00001056SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
Eugene Levianta31c91b2016-07-22 07:38:40 +00001057 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +00001058 SymbolAssignment *Cmd = readAssignment(next());
Petr Hoseka35e39c2016-08-16 01:11:16 +00001059 Cmd->Provide = Provide;
Rui Ueyama174e0a12016-07-29 00:29:25 +00001060 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001061 expect(")");
1062 expect(";");
Rui Ueyama10416562016-08-04 02:03:27 +00001063 return Cmd;
Eugene Levianteda81a12016-07-12 06:39:48 +00001064}
1065
Eugene Leviantceabe802016-08-11 07:56:43 +00001066SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
1067 SymbolAssignment *Cmd = nullptr;
1068 if (peek() == "=" || peek() == "+=") {
1069 Cmd = readAssignment(Tok);
1070 expect(";");
1071 } else if (Tok == "PROVIDE") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001072 Cmd = readProvideHidden(true, false);
1073 } else if (Tok == "HIDDEN") {
1074 Cmd = readProvideHidden(false, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001075 } else if (Tok == "PROVIDE_HIDDEN") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001076 Cmd = readProvideHidden(true, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001077 }
1078 return Cmd;
1079}
1080
George Rimar30835ea2016-07-28 21:08:56 +00001081static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
1082 if (S == ".")
1083 return Dot;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001084
George Rimara9c5a522016-07-26 18:18:58 +00001085 switch (Config->EKind) {
1086 case ELF32LEKind:
1087 if (SymbolBody *B = Symtab<ELF32LE>::X->find(S))
1088 return B->getVA<ELF32LE>();
1089 break;
1090 case ELF32BEKind:
1091 if (SymbolBody *B = Symtab<ELF32BE>::X->find(S))
1092 return B->getVA<ELF32BE>();
1093 break;
1094 case ELF64LEKind:
1095 if (SymbolBody *B = Symtab<ELF64LE>::X->find(S))
1096 return B->getVA<ELF64LE>();
1097 break;
1098 case ELF64BEKind:
1099 if (SymbolBody *B = Symtab<ELF64BE>::X->find(S))
1100 return B->getVA<ELF64BE>();
1101 break;
George Rimar6930a6d2016-07-26 18:41:06 +00001102 default:
George Rimarb567b622016-07-26 18:46:13 +00001103 llvm_unreachable("unsupported target");
George Rimara9c5a522016-07-26 18:18:58 +00001104 }
1105 error("symbol not found: " + S);
1106 return 0;
1107}
1108
George Rimar9e694502016-07-29 16:18:47 +00001109static uint64_t getSectionSize(StringRef Name) {
1110 switch (Config->EKind) {
1111 case ELF32LEKind:
1112 return Script<ELF32LE>::X->getOutputSectionSize(Name);
1113 case ELF32BEKind:
1114 return Script<ELF32BE>::X->getOutputSectionSize(Name);
1115 case ELF64LEKind:
1116 return Script<ELF64LE>::X->getOutputSectionSize(Name);
1117 case ELF64BEKind:
1118 return Script<ELF64BE>::X->getOutputSectionSize(Name);
1119 default:
1120 llvm_unreachable("unsupported target");
1121 }
George Rimar9e694502016-07-29 16:18:47 +00001122}
1123
George Rimar96659df2016-08-30 09:54:01 +00001124static uint64_t getSectionAddress(StringRef Name) {
1125 switch (Config->EKind) {
1126 case ELF32LEKind:
1127 return Script<ELF32LE>::X->getOutputSectionAddress(Name);
1128 case ELF32BEKind:
1129 return Script<ELF32BE>::X->getOutputSectionAddress(Name);
1130 case ELF64LEKind:
1131 return Script<ELF64LE>::X->getOutputSectionAddress(Name);
1132 case ELF64BEKind:
1133 return Script<ELF64BE>::X->getOutputSectionAddress(Name);
1134 default:
1135 llvm_unreachable("unsupported target");
1136 }
1137}
1138
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001139static uint64_t getHeaderSize() {
George Rimare32a3592016-08-10 07:59:34 +00001140 switch (Config->EKind) {
1141 case ELF32LEKind:
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001142 return Script<ELF32LE>::X->getHeaderSize();
George Rimare32a3592016-08-10 07:59:34 +00001143 case ELF32BEKind:
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001144 return Script<ELF32BE>::X->getHeaderSize();
George Rimare32a3592016-08-10 07:59:34 +00001145 case ELF64LEKind:
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001146 return Script<ELF64LE>::X->getHeaderSize();
George Rimare32a3592016-08-10 07:59:34 +00001147 case ELF64BEKind:
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001148 return Script<ELF64BE>::X->getHeaderSize();
George Rimare32a3592016-08-10 07:59:34 +00001149 default:
1150 llvm_unreachable("unsupported target");
1151 }
1152}
1153
George Rimar30835ea2016-07-28 21:08:56 +00001154SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1155 StringRef Op = next();
1156 assert(Op == "=" || Op == "+=");
1157 Expr E = readExpr();
1158 if (Op == "+=")
1159 E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
Rui Ueyama10416562016-08-04 02:03:27 +00001160 return new SymbolAssignment(Name, E);
George Rimar30835ea2016-07-28 21:08:56 +00001161}
1162
1163// This is an operator-precedence parser to parse a linker
1164// script expression.
1165Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
1166
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001167static Expr combine(StringRef Op, Expr L, Expr R) {
1168 if (Op == "*")
1169 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1170 if (Op == "/") {
1171 return [=](uint64_t Dot) -> uint64_t {
1172 uint64_t RHS = R(Dot);
1173 if (RHS == 0) {
1174 error("division by zero");
1175 return 0;
1176 }
1177 return L(Dot) / RHS;
1178 };
1179 }
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); };
1186 if (Op == ">")
1187 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
1188 if (Op == ">=")
1189 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
1190 if (Op == "<=")
1191 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
1192 if (Op == "==")
1193 return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
1194 if (Op == "!=")
1195 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
1196 if (Op == "&")
1197 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
Rafael Espindolacc3dd622016-08-22 21:33:35 +00001198 if (Op == "|")
1199 return [=](uint64_t Dot) { return L(Dot) | R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001200 llvm_unreachable("invalid operator");
1201}
1202
Rui Ueyama708019c2016-07-24 18:19:40 +00001203// This is a part of the operator-precedence parser. This function
1204// assumes that the remaining token stream starts with an operator.
1205Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1206 while (!atEOF() && !Error) {
1207 // Read an operator and an expression.
1208 StringRef Op1 = peek();
1209 if (Op1 == "?")
1210 return readTernary(Lhs);
1211 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +00001212 break;
Rui Ueyama708019c2016-07-24 18:19:40 +00001213 next();
1214 Expr Rhs = readPrimary();
1215
1216 // Evaluate the remaining part of the expression first if the
1217 // next operator has greater precedence than the previous one.
1218 // For example, if we have read "+" and "3", and if the next
1219 // operator is "*", then we'll evaluate 3 * ... part first.
1220 while (!atEOF()) {
1221 StringRef Op2 = peek();
1222 if (precedence(Op2) <= precedence(Op1))
1223 break;
1224 Rhs = readExpr1(Rhs, precedence(Op2));
1225 }
1226
1227 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +00001228 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001229 return Lhs;
1230}
1231
1232uint64_t static getConstant(StringRef S) {
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001233 if (S == "COMMONPAGESIZE")
Rui Ueyama708019c2016-07-24 18:19:40 +00001234 return Target->PageSize;
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001235 if (S == "MAXPAGESIZE")
1236 return Target->MaxPageSize;
Rui Ueyama708019c2016-07-24 18:19:40 +00001237 error("unknown constant: " + S);
1238 return 0;
1239}
1240
Rui Ueyama626e0b02016-09-02 18:19:00 +00001241// Parses Tok as an integer. Returns true if successful.
1242// It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1243// and decimal numbers. Decimal numbers may have "K" (kilo) or
1244// "M" (mega) prefixes.
George Rimar9f2f7ad2016-09-02 16:01:42 +00001245static bool readInteger(StringRef Tok, uint64_t &Result) {
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001246 if (Tok.startswith("-")) {
1247 if (!readInteger(Tok.substr(1), Result))
1248 return false;
1249 Result = -Result;
1250 return true;
1251 }
George Rimar9f2f7ad2016-09-02 16:01:42 +00001252 if (Tok.startswith_lower("0x"))
1253 return !Tok.substr(2).getAsInteger(16, Result);
1254 if (Tok.endswith_lower("H"))
1255 return !Tok.drop_back().getAsInteger(16, Result);
1256
1257 int Suffix = 1;
1258 if (Tok.endswith_lower("K")) {
1259 Suffix = 1024;
1260 Tok = Tok.drop_back();
1261 } else if (Tok.endswith_lower("M")) {
1262 Suffix = 1024 * 1024;
1263 Tok = Tok.drop_back();
1264 }
1265 if (Tok.getAsInteger(10, Result))
1266 return false;
1267 Result *= Suffix;
1268 return true;
1269}
1270
Rui Ueyama708019c2016-07-24 18:19:40 +00001271Expr ScriptParser::readPrimary() {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001272 if (peek() == "(")
1273 return readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001274
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001275 StringRef Tok = next();
Rui Ueyama708019c2016-07-24 18:19:40 +00001276
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001277 if (Tok == "~") {
1278 Expr E = readPrimary();
1279 return [=](uint64_t Dot) { return ~E(Dot); };
1280 }
1281 if (Tok == "-") {
1282 Expr E = readPrimary();
1283 return [=](uint64_t Dot) { return -E(Dot); };
1284 }
1285
Rui Ueyama708019c2016-07-24 18:19:40 +00001286 // Built-in functions are parsed here.
1287 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
George Rimar96659df2016-08-30 09:54:01 +00001288 if (Tok == "ADDR") {
1289 expect("(");
1290 StringRef Name = next();
1291 expect(")");
1292 return [=](uint64_t Dot) { return getSectionAddress(Name); };
1293 }
George Rimareefa7582016-08-04 09:29:31 +00001294 if (Tok == "ASSERT")
1295 return readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001296 if (Tok == "ALIGN") {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001297 Expr E = readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001298 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1299 }
1300 if (Tok == "CONSTANT") {
1301 expect("(");
1302 StringRef Tok = next();
1303 expect(")");
1304 return [=](uint64_t Dot) { return getConstant(Tok); };
1305 }
Rafael Espindola54c145c2016-07-28 18:16:24 +00001306 if (Tok == "SEGMENT_START") {
1307 expect("(");
1308 next();
1309 expect(",");
1310 uint64_t Val;
1311 next().getAsInteger(0, Val);
1312 expect(")");
1313 return [=](uint64_t Dot) { return Val; };
1314 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001315 if (Tok == "DATA_SEGMENT_ALIGN") {
1316 expect("(");
1317 Expr E = readExpr();
1318 expect(",");
1319 readExpr();
1320 expect(")");
Rui Ueyamaf7791bb2016-07-26 19:34:10 +00001321 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001322 }
1323 if (Tok == "DATA_SEGMENT_END") {
1324 expect("(");
1325 expect(".");
1326 expect(")");
1327 return [](uint64_t Dot) { return Dot; };
1328 }
George Rimar276b4e62016-07-26 17:58:44 +00001329 // GNU linkers implements more complicated logic to handle
1330 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1331 // the next page boundary for simplicity.
1332 if (Tok == "DATA_SEGMENT_RELRO_END") {
1333 expect("(");
1334 next();
1335 expect(",");
1336 readExpr();
1337 expect(")");
1338 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1339 }
George Rimar9e694502016-07-29 16:18:47 +00001340 if (Tok == "SIZEOF") {
1341 expect("(");
1342 StringRef Name = next();
1343 expect(")");
1344 return [=](uint64_t Dot) { return getSectionSize(Name); };
1345 }
George Rimare32a3592016-08-10 07:59:34 +00001346 if (Tok == "SIZEOF_HEADERS")
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001347 return [=](uint64_t Dot) { return getHeaderSize(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001348
George Rimar9f2f7ad2016-09-02 16:01:42 +00001349 // Tok is a literal number.
1350 uint64_t V;
1351 if (readInteger(Tok, V))
1352 return [=](uint64_t Dot) { return V; };
1353
1354 // Tok is a symbol name.
1355 if (Tok != "." && !isValidCIdentifier(Tok))
1356 setError("malformed number: " + Tok);
1357 return [=](uint64_t Dot) { return getSymbolValue(Tok, Dot); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001358}
1359
1360Expr ScriptParser::readTernary(Expr Cond) {
1361 next();
1362 Expr L = readExpr();
1363 expect(":");
1364 Expr R = readExpr();
1365 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1366}
1367
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001368Expr ScriptParser::readParenExpr() {
1369 expect("(");
1370 Expr E = readExpr();
1371 expect(")");
1372 return E;
1373}
1374
Eugene Leviantbbe38602016-07-19 09:25:43 +00001375std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1376 std::vector<StringRef> Phdrs;
1377 while (!Error && peek().startswith(":")) {
1378 StringRef Tok = next();
1379 Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
1380 if (Tok.empty()) {
1381 setError("section header name is empty");
1382 break;
1383 }
Rui Ueyama047404f2016-07-20 19:36:36 +00001384 Phdrs.push_back(Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001385 }
1386 return Phdrs;
1387}
1388
1389unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001390 StringRef Tok = next();
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001391 unsigned Ret = StringSwitch<unsigned>(Tok)
1392 .Case("PT_NULL", PT_NULL)
1393 .Case("PT_LOAD", PT_LOAD)
1394 .Case("PT_DYNAMIC", PT_DYNAMIC)
1395 .Case("PT_INTERP", PT_INTERP)
1396 .Case("PT_NOTE", PT_NOTE)
1397 .Case("PT_SHLIB", PT_SHLIB)
1398 .Case("PT_PHDR", PT_PHDR)
1399 .Case("PT_TLS", PT_TLS)
1400 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1401 .Case("PT_GNU_STACK", PT_GNU_STACK)
1402 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1403 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001404
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001405 if (Ret == (unsigned)-1) {
1406 setError("invalid program header type: " + Tok);
1407 return PT_NULL;
1408 }
1409 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001410}
1411
Rui Ueyama95769b42016-08-31 20:03:54 +00001412void ScriptParser::readVersionDeclaration(StringRef VerStr) {
George Rimar20b65982016-08-31 09:08:26 +00001413 // Identifiers start at 2 because 0 and 1 are reserved
1414 // for VER_NDX_LOCAL and VER_NDX_GLOBAL constants.
1415 size_t VersionId = Config->VersionDefinitions.size() + 2;
1416 Config->VersionDefinitions.push_back({VerStr, VersionId});
1417
1418 if (skip("global:") || peek() != "local:")
1419 readGlobal(VerStr);
1420 if (skip("local:"))
1421 readLocal();
1422 expect("}");
1423
1424 // Each version may have a parent version. For example, "Ver2" defined as
1425 // "Ver2 { global: foo; local: *; } Ver1;" has "Ver1" as a parent. This
1426 // version hierarchy is, probably against your instinct, purely for human; the
1427 // runtime doesn't care about them at all. In LLD, we simply skip the token.
1428 if (!VerStr.empty() && peek() != ";")
1429 next();
1430 expect(";");
1431}
1432
1433void ScriptParser::readLocal() {
1434 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1435 expect("*");
1436 expect(";");
1437}
1438
1439void ScriptParser::readExtern(std::vector<SymbolVersion> *Globals) {
1440 expect("C++");
1441 expect("{");
1442
1443 for (;;) {
1444 if (peek() == "}" || Error)
1445 break;
1446 Globals->push_back({next(), true});
1447 expect(";");
1448 }
1449
1450 expect("}");
1451 expect(";");
1452}
1453
1454void ScriptParser::readGlobal(StringRef VerStr) {
1455 std::vector<SymbolVersion> *Globals;
1456 if (VerStr.empty())
1457 Globals = &Config->VersionScriptGlobals;
1458 else
1459 Globals = &Config->VersionDefinitions.back().Globals;
1460
1461 for (;;) {
1462 if (skip("extern"))
1463 readExtern(Globals);
1464
1465 StringRef Cur = peek();
1466 if (Cur == "}" || Cur == "local:" || Error)
1467 return;
1468 next();
1469 Globals->push_back({Cur, false});
1470 expect(";");
1471 }
1472}
1473
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001474static bool isUnderSysroot(StringRef Path) {
1475 if (Config->Sysroot == "")
1476 return false;
1477 for (; !Path.empty(); Path = sys::path::parent_path(Path))
1478 if (sys::fs::equivalent(Config->Sysroot, Path))
1479 return true;
1480 return false;
1481}
1482
Rui Ueyama07320e42016-04-20 20:13:41 +00001483void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001484 StringRef Path = MB.getBufferIdentifier();
George Rimar20b65982016-08-31 09:08:26 +00001485 ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).readLinkerScript();
1486}
1487
1488void elf::readVersionScript(MemoryBufferRef MB) {
1489 ScriptParser(MB.getBuffer(), false).readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001490}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001491
Rui Ueyama07320e42016-04-20 20:13:41 +00001492template class elf::LinkerScript<ELF32LE>;
1493template class elf::LinkerScript<ELF32BE>;
1494template class elf::LinkerScript<ELF64LE>;
1495template class elf::LinkerScript<ELF64BE>;