blob: d1cfd569ada840228279e35faeaa9346eaddbeb6 [file] [log] [blame]
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001//===- LinkerScript.cpp ---------------------------------------------------===//
2//
3// The LLVM Linker
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains the parser/evaluator of the linker script.
Rui Ueyama629e0aa52016-07-21 19:45:22 +000011// It parses a linker script and write the result to Config or ScriptConfig
12// objects.
13//
14// If SECTIONS command is used, a ScriptConfig contains an AST
15// of the command which will later be consumed by createSections() and
16// assignAddresses().
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000017//
18//===----------------------------------------------------------------------===//
19
Rui Ueyama717677a2016-02-11 21:17:59 +000020#include "LinkerScript.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000021#include "Config.h"
22#include "Driver.h"
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +000023#include "InputSection.h"
George Rimar652852c2016-04-16 10:10:32 +000024#include "OutputSections.h"
Adhemerval Zanellae77b5bf2016-04-06 20:59:11 +000025#include "ScriptParser.h"
Rui Ueyama93c9af42016-06-29 08:01:32 +000026#include "Strings.h"
Eugene Levianteda81a12016-07-12 06:39:48 +000027#include "Symbols.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000028#include "SymbolTable.h"
Eugene Leviant467c4d52016-07-01 10:27:36 +000029#include "Target.h"
Eugene Leviantbbe38602016-07-19 09:25:43 +000030#include "Writer.h"
Rui Ueyama960504b2016-04-19 18:58:11 +000031#include "llvm/ADT/StringSwitch.h"
George Rimar652852c2016-04-16 10:10:32 +000032#include "llvm/Support/ELF.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000033#include "llvm/Support/FileSystem.h"
34#include "llvm/Support/MemoryBuffer.h"
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +000035#include "llvm/Support/Path.h"
Rui Ueyamaa47ee682015-10-11 01:53:04 +000036#include "llvm/Support/StringSaver.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000037
38using namespace llvm;
George Rimar652852c2016-04-16 10:10:32 +000039using namespace llvm::ELF;
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +000040using namespace llvm::object;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000041using namespace lld;
Rafael Espindolae0df00b2016-02-28 00:25:54 +000042using namespace lld::elf;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000043
George Rimar884e7862016-09-08 08:19:13 +000044LinkerScriptBase *elf::ScriptBase;
Rui Ueyama07320e42016-04-20 20:13:41 +000045ScriptConfiguration *elf::ScriptConfig;
Rui Ueyama717677a2016-02-11 21:17:59 +000046
Eugene Leviantceabe802016-08-11 07:56:43 +000047template <class ELFT>
Rui Ueyama16024212016-08-11 23:22:52 +000048static void addRegular(SymbolAssignment *Cmd) {
49 Symbol *Sym = Symtab<ELFT>::X->addRegular(Cmd->Name, STB_GLOBAL, STV_DEFAULT);
50 Sym->Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
51 Cmd->Sym = Sym->body();
Eugene Leviantceabe802016-08-11 07:56:43 +000052}
53
Rui Ueyama0c70d3c2016-08-12 03:31:09 +000054template <class ELFT> static void addSynthetic(SymbolAssignment *Cmd) {
George Rimare1937bb2016-08-19 15:36:32 +000055 Symbol *Sym = Symtab<ELFT>::X->addSynthetic(
56 Cmd->Name, nullptr, 0, Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT);
Rui Ueyama16024212016-08-11 23:22:52 +000057 Cmd->Sym = Sym->body();
Eugene Leviantceabe802016-08-11 07:56:43 +000058}
59
Eugene Leviantdb741e72016-09-07 07:08:43 +000060template <class ELFT> static void addSymbol(SymbolAssignment *Cmd) {
61 if (Cmd->IsAbsolute)
62 addRegular<ELFT>(Cmd);
63 else
64 addSynthetic<ELFT>(Cmd);
65}
Rui Ueyama16024212016-08-11 23:22:52 +000066// If a symbol was in PROVIDE(), we need to define it only when
67// it is an undefined symbol.
68template <class ELFT> static bool shouldDefine(SymbolAssignment *Cmd) {
69 if (Cmd->Name == ".")
Eugene Leviantceabe802016-08-11 07:56:43 +000070 return false;
Rui Ueyama16024212016-08-11 23:22:52 +000071 if (!Cmd->Provide)
72 return true;
73 SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
74 return B && B->isUndefined();
Eugene Leviantceabe802016-08-11 07:56:43 +000075}
76
George Rimar076fe152016-07-21 06:43:01 +000077bool SymbolAssignment::classof(const BaseCommand *C) {
78 return C->Kind == AssignmentKind;
79}
80
81bool OutputSectionCommand::classof(const BaseCommand *C) {
82 return C->Kind == OutputSectionKind;
83}
84
George Rimareea31142016-07-21 14:26:59 +000085bool InputSectionDescription::classof(const BaseCommand *C) {
86 return C->Kind == InputSectionKind;
87}
88
George Rimareefa7582016-08-04 09:29:31 +000089bool AssertCommand::classof(const BaseCommand *C) {
90 return C->Kind == AssertKind;
91}
92
Rui Ueyama36a153c2016-07-23 14:09:58 +000093template <class ELFT> static bool isDiscarded(InputSectionBase<ELFT> *S) {
George Rimareea31142016-07-21 14:26:59 +000094 return !S || !S->Live;
Rui Ueyama717677a2016-02-11 21:17:59 +000095}
96
Rui Ueyamaf34d0e02016-08-12 01:24:53 +000097template <class ELFT> LinkerScript<ELFT>::LinkerScript() {}
98template <class ELFT> LinkerScript<ELFT>::~LinkerScript() {}
99
Rui Ueyama07320e42016-04-20 20:13:41 +0000100template <class ELFT>
101bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) {
George Rimarc91930a2016-09-02 21:17:20 +0000102 for (Regex *Re : Opt.KeptSections)
103 if (Re->match(S->getSectionName()))
George Rimareea31142016-07-21 14:26:59 +0000104 return true;
105 return false;
106}
107
George Rimar06598002016-07-28 21:51:30 +0000108static bool fileMatches(const InputSectionDescription *Desc,
109 StringRef Filename) {
George Rimarc91930a2016-09-02 21:17:20 +0000110 return const_cast<Regex &>(Desc->FileRe).match(Filename) &&
111 !const_cast<Regex &>(Desc->ExcludedFileRe).match(Filename);
George Rimar06598002016-07-28 21:51:30 +0000112}
113
Rui Ueyama6b274812016-07-25 22:51:07 +0000114// Returns input sections filtered by given glob patterns.
115template <class ELFT>
116std::vector<InputSectionBase<ELFT> *>
Rui Ueyamaad10c3d2016-07-28 21:05:04 +0000117LinkerScript<ELFT>::getInputSections(const InputSectionDescription *I) {
George Rimarc91930a2016-09-02 21:17:20 +0000118 const Regex &Re = I->SectionRe;
Rui Ueyama6b274812016-07-25 22:51:07 +0000119 std::vector<InputSectionBase<ELFT> *> Ret;
120 for (const std::unique_ptr<ObjectFile<ELFT>> &F :
George Rimar06598002016-07-28 21:51:30 +0000121 Symtab<ELFT>::X->getObjectFiles()) {
122 if (fileMatches(I, sys::path::filename(F->getName())))
123 for (InputSectionBase<ELFT> *S : F->getSections())
124 if (!isDiscarded(S) && !S->OutSec &&
George Rimarc91930a2016-09-02 21:17:20 +0000125 const_cast<Regex &>(Re).match(S->getSectionName()))
Davide Italianoe7282792016-07-27 01:44:01 +0000126 Ret.push_back(S);
George Rimar06598002016-07-28 21:51:30 +0000127 }
Eugene Leviant3e6b0272016-07-28 19:24:13 +0000128
George Rimarc91930a2016-09-02 21:17:20 +0000129 if (const_cast<Regex &>(Re).match("COMMON"))
Rui Ueyamaad10c3d2016-07-28 21:05:04 +0000130 Ret.push_back(CommonInputSection<ELFT>::X);
Rui Ueyama6b274812016-07-25 22:51:07 +0000131 return Ret;
132}
133
Eugene Leviantceabe802016-08-11 07:56:43 +0000134template <class ELFT>
Rui Ueyama742c3832016-08-04 22:27:00 +0000135static bool compareName(InputSectionBase<ELFT> *A, InputSectionBase<ELFT> *B) {
136 return A->getSectionName() < B->getSectionName();
137}
George Rimar350ece42016-08-03 08:35:59 +0000138
Rui Ueyama742c3832016-08-04 22:27:00 +0000139template <class ELFT>
140static bool compareAlignment(InputSectionBase<ELFT> *A,
141 InputSectionBase<ELFT> *B) {
142 // ">" is not a mistake. Larger alignments are placed before smaller
143 // alignments in order to reduce the amount of padding necessary.
144 // This is compatible with GNU.
145 return A->Alignment > B->Alignment;
146}
George Rimar350ece42016-08-03 08:35:59 +0000147
Rui Ueyama742c3832016-08-04 22:27:00 +0000148template <class ELFT>
149static std::function<bool(InputSectionBase<ELFT> *, InputSectionBase<ELFT> *)>
150getComparator(SortKind K) {
151 if (K == SortByName)
152 return compareName<ELFT>;
153 return compareAlignment<ELFT>;
154}
George Rimar0702c4e2016-07-29 15:32:46 +0000155
156template <class ELFT>
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000157void LinkerScript<ELFT>::discard(OutputSectionCommand &Cmd) {
158 for (const std::unique_ptr<BaseCommand> &Base : Cmd.Commands) {
159 if (auto *Cmd = dyn_cast<InputSectionDescription>(Base.get())) {
160 for (InputSectionBase<ELFT> *S : getInputSections(Cmd)) {
161 S->Live = false;
162 reportDiscarded(S);
163 }
164 }
165 }
166}
167
George Rimar8f66df92016-08-12 20:38:20 +0000168static bool checkConstraint(uint64_t Flags, ConstraintKind Kind) {
169 bool RO = (Kind == ConstraintKind::ReadOnly);
170 bool RW = (Kind == ConstraintKind::ReadWrite);
171 bool Writable = Flags & SHF_WRITE;
Rui Ueyamaadcdb662016-09-06 22:50:48 +0000172 return !(RO && Writable) && !(RW && !Writable);
George Rimar8f66df92016-08-12 20:38:20 +0000173}
174
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000175template <class ELFT>
George Rimar06ae6832016-08-12 09:07:57 +0000176static bool matchConstraints(ArrayRef<InputSectionBase<ELFT> *> Sections,
177 ConstraintKind Kind) {
George Rimar8f66df92016-08-12 20:38:20 +0000178 if (Kind == ConstraintKind::NoConstraint)
179 return true;
180 return llvm::all_of(Sections, [=](InputSectionBase<ELFT> *Sec) {
181 return checkConstraint(Sec->getSectionHdr()->sh_flags, Kind);
George Rimar06ae6832016-08-12 09:07:57 +0000182 });
183}
184
185template <class ELFT>
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000186std::vector<InputSectionBase<ELFT> *>
George Rimar06ae6832016-08-12 09:07:57 +0000187LinkerScript<ELFT>::createInputSectionList(OutputSectionCommand &OutCmd) {
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000188 std::vector<InputSectionBase<ELFT> *> Ret;
Eugene Leviant97403d12016-09-01 09:55:57 +0000189 DenseSet<InputSectionBase<ELFT> *> SectionIndex;
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000190
George Rimar06ae6832016-08-12 09:07:57 +0000191 for (const std::unique_ptr<BaseCommand> &Base : OutCmd.Commands) {
192 if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base.get())) {
193 if (shouldDefine<ELFT>(OutCmd))
Eugene Leviantdb741e72016-09-07 07:08:43 +0000194 addSymbol<ELFT>(OutCmd);
Eugene Leviant97403d12016-09-01 09:55:57 +0000195 OutCmd->GoesAfter = Ret.empty() ? nullptr : Ret.back();
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000196 continue;
197 }
198
199 auto *Cmd = cast<InputSectionDescription>(Base.get());
200 std::vector<InputSectionBase<ELFT> *> V = getInputSections(Cmd);
George Rimar06ae6832016-08-12 09:07:57 +0000201 if (!matchConstraints<ELFT>(V, OutCmd.Constraint))
202 continue;
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000203 if (Cmd->SortInner)
204 std::stable_sort(V.begin(), V.end(), getComparator<ELFT>(Cmd->SortInner));
205 if (Cmd->SortOuter)
206 std::stable_sort(V.begin(), V.end(), getComparator<ELFT>(Cmd->SortOuter));
Eugene Leviant97403d12016-09-01 09:55:57 +0000207
208 // Add all input sections corresponding to rule 'Cmd' to
209 // resulting vector. We do not add duplicate input sections.
210 for (InputSectionBase<ELFT> *S : V)
211 if (SectionIndex.insert(S).second)
212 Ret.push_back(S);
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000213 }
214 return Ret;
215}
216
217template <class ELFT>
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000218void LinkerScript<ELFT>::createAssignments() {
219 for (const std::unique_ptr<SymbolAssignment> &Cmd : Opt.Assignments) {
220 if (shouldDefine<ELFT>(Cmd.get()))
221 addRegular<ELFT>(Cmd.get());
222 if (Cmd->Sym)
223 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(0);
224 }
225}
226
227template <class ELFT>
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000228void LinkerScript<ELFT>::createSections(OutputSectionFactory<ELFT> &Factory) {
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000229 for (const std::unique_ptr<BaseCommand> &Base1 : Opt.Commands) {
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000230 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base1.get())) {
231 if (shouldDefine<ELFT>(Cmd))
232 addRegular<ELFT>(Cmd);
233 continue;
234 }
235
Eugene Leviantceabe802016-08-11 07:56:43 +0000236 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000237 if (Cmd->Name == "/DISCARD/") {
238 discard(*Cmd);
239 continue;
240 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000241
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000242 std::vector<InputSectionBase<ELFT> *> V = createInputSectionList(*Cmd);
Eugene Leviant97403d12016-09-01 09:55:57 +0000243 if (V.empty())
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000244 continue;
245
George Rimardb24d9c2016-08-19 15:18:23 +0000246 for (InputSectionBase<ELFT> *Sec : V) {
George Rimara14b13d2016-09-07 10:46:07 +0000247 OutputSectionBase<ELFT> *OutSec;
248 bool IsNew;
249 std::tie(OutSec, IsNew) = Factory.create(Sec, Cmd->Name);
250 if (IsNew)
251 OutputSections->push_back(OutSec);
252
253 uint32_t Subalign = Cmd->SubalignExpr ? Cmd->SubalignExpr(0) : 0;
254
George Rimardb24d9c2016-08-19 15:18:23 +0000255 if (Subalign)
256 Sec->Alignment = Subalign;
Eugene Leviant97403d12016-09-01 09:55:57 +0000257 OutSec->addSection(Sec);
George Rimardb24d9c2016-08-19 15:18:23 +0000258 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000259 }
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000260 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000261
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000262 // Add orphan sections.
Rui Ueyama6b274812016-07-25 22:51:07 +0000263 for (const std::unique_ptr<ObjectFile<ELFT>> &F :
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000264 Symtab<ELFT>::X->getObjectFiles()) {
265 for (InputSectionBase<ELFT> *S : F->getSections()) {
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000266 if (isDiscarded(S) || S->OutSec)
267 continue;
268 OutputSectionBase<ELFT> *OutSec;
269 bool IsNew;
270 std::tie(OutSec, IsNew) = Factory.create(S, getOutputSectionName(S));
271 if (IsNew)
272 OutputSections->push_back(OutSec);
273 OutSec->addSection(S);
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000274 }
275 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000276}
277
Eugene Leviantdb741e72016-09-07 07:08:43 +0000278// Sets value of a section-defined symbol. Two kinds of
279// symbols are processed: synthetic symbols, whose value
280// is an offset from beginning of section and regular
281// symbols whose value is absolute.
282template <class ELFT>
283static void assignSectionSymbol(SymbolAssignment *Cmd,
284 OutputSectionBase<ELFT> *Sec,
285 typename ELFT::uint Off) {
286 if (!Cmd->Sym)
287 return;
288
289 if (auto *Body = dyn_cast<DefinedSynthetic<ELFT>>(Cmd->Sym)) {
290 Body->Section = Sec;
291 Body->Value = Cmd->Expression(Sec->getVA() + Off) - Sec->getVA();
292 return;
293 }
294 auto *Body = cast<DefinedRegular<ELFT>>(Cmd->Sym);
295 Body->Value = Cmd->Expression(Sec->getVA() + Off);
296}
297
Eugene Leviant20889c52016-08-31 08:13:33 +0000298// Linker script may define start and end symbols for special section types,
299// like .got, .eh_frame_hdr, .eh_frame and others. Those sections are not a list
300// of regular input input sections, therefore our way of defining symbols for
301// regular sections will not work. The approach we use for special section types
302// is not perfect - it handles only start and end symbols.
303template <class ELFT>
304void addStartEndSymbols(OutputSectionCommand *Cmd,
305 OutputSectionBase<ELFT> *Sec) {
306 bool Start = true;
307 BaseCommand *PrevCmd = nullptr;
308
309 for (std::unique_ptr<BaseCommand> &Base : Cmd->Commands) {
310 if (auto *AssignCmd = dyn_cast<SymbolAssignment>(Base.get())) {
Eugene Leviantdb741e72016-09-07 07:08:43 +0000311 assignSectionSymbol<ELFT>(AssignCmd, Sec, Start ? 0 : Sec->getSize());
Eugene Leviant20889c52016-08-31 08:13:33 +0000312 } else {
313 if (!Start && isa<SymbolAssignment>(PrevCmd))
314 error("section '" + Sec->getName() +
315 "' supports only start and end symbols");
316 Start = false;
317 }
318 PrevCmd = Base.get();
319 }
320}
321
322template <class ELFT>
323void assignOffsets(OutputSectionCommand *Cmd, OutputSectionBase<ELFT> *Sec) {
Eugene Leviantceabe802016-08-11 07:56:43 +0000324 auto *OutSec = dyn_cast<OutputSection<ELFT>>(Sec);
Rui Ueyama2de509c2016-08-12 00:55:08 +0000325 if (!OutSec) {
326 Sec->assignOffsets();
Eugene Leviant20889c52016-08-31 08:13:33 +0000327 // This section is not regular output section. However linker script may
328 // have defined start/end symbols for it. This case is handled below.
329 addStartEndSymbols(Cmd, Sec);
Eugene Leviantceabe802016-08-11 07:56:43 +0000330 return;
Rui Ueyama2de509c2016-08-12 00:55:08 +0000331 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000332 typedef typename ELFT::uint uintX_t;
333 uintX_t Off = 0;
Eugene Leviant97403d12016-09-01 09:55:57 +0000334 auto ItCmd = Cmd->Commands.begin();
Eugene Leviantceabe802016-08-11 07:56:43 +0000335
Eugene Leviant97403d12016-09-01 09:55:57 +0000336 // Assigns values to all symbols following the given
337 // input section 'D' in output section 'Sec'. When symbols
338 // are in the beginning of output section the value of 'D'
339 // is nullptr.
340 auto AssignSuccessors = [&](InputSectionData *D) {
341 for (; ItCmd != Cmd->Commands.end(); ++ItCmd) {
342 auto *AssignCmd = dyn_cast<SymbolAssignment>(ItCmd->get());
343 if (!AssignCmd)
344 continue;
345 if (D != AssignCmd->GoesAfter)
346 break;
347
Eugene Leviant97403d12016-09-01 09:55:57 +0000348 if (AssignCmd->Name == ".") {
349 // Update to location counter means update to section size.
Eugene Leviantdb741e72016-09-07 07:08:43 +0000350 Off = AssignCmd->Expression(Sec->getVA() + Off) - Sec->getVA();
Eugene Leviant97403d12016-09-01 09:55:57 +0000351 Sec->setSize(Off);
352 continue;
353 }
Eugene Leviantdb741e72016-09-07 07:08:43 +0000354 assignSectionSymbol<ELFT>(AssignCmd, Sec, Off);
Eugene Leviantceabe802016-08-11 07:56:43 +0000355 }
Eugene Leviant97403d12016-09-01 09:55:57 +0000356 };
357
358 AssignSuccessors(nullptr);
359 for (InputSection<ELFT> *I : OutSec->Sections) {
360 Off = alignTo(Off, I->Alignment);
361 I->OutSecOff = Off;
362 Off += I->getSize();
Rui Ueyamaf4a30a52016-08-11 21:30:42 +0000363 // Update section size inside for-loop, so that SIZEOF
Eugene Leviantceabe802016-08-11 07:56:43 +0000364 // works correctly in the case below:
365 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
366 Sec->setSize(Off);
Eugene Leviant97403d12016-09-01 09:55:57 +0000367 // Add symbols following current input section.
368 AssignSuccessors(I);
Eugene Leviantceabe802016-08-11 07:56:43 +0000369 }
370}
371
George Rimar8f66df92016-08-12 20:38:20 +0000372template <class ELFT>
George Rimara14b13d2016-09-07 10:46:07 +0000373static std::vector<OutputSectionBase<ELFT> *>
374findSections(OutputSectionCommand &Cmd,
375 ArrayRef<OutputSectionBase<ELFT> *> Sections) {
376 std::vector<OutputSectionBase<ELFT> *> Ret;
377 for (OutputSectionBase<ELFT> *Sec : Sections)
378 if (Sec->getName() == Cmd.Name &&
379 checkConstraint(Sec->getFlags(), Cmd.Constraint))
380 Ret.push_back(Sec);
381 return Ret;
George Rimar8f66df92016-08-12 20:38:20 +0000382}
383
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000384template <class ELFT> void LinkerScript<ELFT>::assignAddresses() {
George Rimar652852c2016-04-16 10:10:32 +0000385 // Orphan sections are sections present in the input files which
Rui Ueyama7c18c282016-04-18 21:00:40 +0000386 // are not explicitly placed into the output file by the linker script.
387 // We place orphan sections at end of file.
388 // Other linkers places them using some heuristics as described in
George Rimar652852c2016-04-16 10:10:32 +0000389 // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
Rui Ueyamae5cc6682016-08-12 00:36:56 +0000390 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
George Rimar652852c2016-04-16 10:10:32 +0000391 StringRef Name = Sec->getName();
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000392 if (getSectionIndex(Name) == INT_MAX)
George Rimar076fe152016-07-21 06:43:01 +0000393 Opt.Commands.push_back(llvm::make_unique<OutputSectionCommand>(Name));
George Rimar652852c2016-04-16 10:10:32 +0000394 }
George Rimar652852c2016-04-16 10:10:32 +0000395
Rui Ueyama7c18c282016-04-18 21:00:40 +0000396 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rui Ueyama4f7500b2016-08-12 04:00:22 +0000397 Dot = getHeaderSize();
Eugene Leviant467c4d52016-07-01 10:27:36 +0000398 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
George Rimar652852c2016-04-16 10:10:32 +0000399 uintX_t ThreadBssOffset = 0;
George Rimar652852c2016-04-16 10:10:32 +0000400
George Rimar076fe152016-07-21 06:43:01 +0000401 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
402 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
Rui Ueyama8d083e62016-07-29 05:48:39 +0000403 if (Cmd->Name == ".") {
404 Dot = Cmd->Expression(Dot);
405 } else if (Cmd->Sym) {
406 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(Dot);
407 }
George Rimar652852c2016-04-16 10:10:32 +0000408 continue;
409 }
410
George Rimareefa7582016-08-04 09:29:31 +0000411 if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
412 Cmd->Expression(Dot);
413 continue;
414 }
415
George Rimar076fe152016-07-21 06:43:01 +0000416 auto *Cmd = cast<OutputSectionCommand>(Base.get());
George Rimara14b13d2016-09-07 10:46:07 +0000417 for (OutputSectionBase<ELFT> *Sec :
418 findSections<ELFT>(*Cmd, *OutputSections)) {
George Rimar652852c2016-04-16 10:10:32 +0000419
George Rimara14b13d2016-09-07 10:46:07 +0000420 if (Cmd->AddrExpr)
421 Dot = Cmd->AddrExpr(Dot);
George Rimar58e5c4d2016-07-25 08:29:46 +0000422
George Rimara14b13d2016-09-07 10:46:07 +0000423 if (Cmd->AlignExpr)
424 Sec->updateAlignment(Cmd->AlignExpr(Dot));
George Rimar630c6172016-07-26 18:06:29 +0000425
George Rimara14b13d2016-09-07 10:46:07 +0000426 if ((Sec->getFlags() & SHF_TLS) && Sec->getType() == SHT_NOBITS) {
427 uintX_t TVA = Dot + ThreadBssOffset;
428 TVA = alignTo(TVA, Sec->getAlignment());
429 Sec->setVA(TVA);
430 assignOffsets(Cmd, Sec);
431 ThreadBssOffset = TVA - Dot + Sec->getSize();
432 continue;
433 }
434
435 if (!(Sec->getFlags() & SHF_ALLOC)) {
436 assignOffsets(Cmd, Sec);
437 continue;
438 }
439
440 Dot = alignTo(Dot, Sec->getAlignment());
441 Sec->setVA(Dot);
Eugene Leviant20889c52016-08-31 08:13:33 +0000442 assignOffsets(Cmd, Sec);
George Rimara14b13d2016-09-07 10:46:07 +0000443 MinVA = std::min(MinVA, Dot);
444 Dot += Sec->getSize();
George Rimar652852c2016-04-16 10:10:32 +0000445 }
446 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000447
Rafael Espindola64c32d62016-07-07 14:28:47 +0000448 // ELF and Program headers need to be right before the first section in
George Rimarb91e7112016-07-19 07:42:07 +0000449 // memory. Set their addresses accordingly.
Eugene Leviant467c4d52016-07-01 10:27:36 +0000450 MinVA = alignDown(MinVA - Out<ELFT>::ElfHeader->getSize() -
451 Out<ELFT>::ProgramHeaders->getSize(),
452 Target->PageSize);
453 Out<ELFT>::ElfHeader->setVA(MinVA);
454 Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
George Rimar652852c2016-04-16 10:10:32 +0000455}
456
Rui Ueyama464daad2016-08-22 04:55:20 +0000457// Creates program headers as instructed by PHDRS linker script command.
Rui Ueyama07320e42016-04-20 20:13:41 +0000458template <class ELFT>
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000459std::vector<PhdrEntry<ELFT>> LinkerScript<ELFT>::createPhdrs() {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000460 std::vector<PhdrEntry<ELFT>> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000461
Rui Ueyama464daad2016-08-22 04:55:20 +0000462 // Process PHDRS and FILEHDR keywords because they are not
463 // real output sections and cannot be added in the following loop.
Eugene Leviantbbe38602016-07-19 09:25:43 +0000464 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000465 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
466 PhdrEntry<ELFT> &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000467
468 if (Cmd.HasFilehdr)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000469 Phdr.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000470 if (Cmd.HasPhdrs)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000471 Phdr.add(Out<ELFT>::ProgramHeaders);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000472 }
473
Rui Ueyama464daad2016-08-22 04:55:20 +0000474 // Add output sections to program headers.
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000475 PhdrEntry<ELFT> *Load = nullptr;
476 uintX_t Flags = PF_R;
Rui Ueyama464daad2016-08-22 04:55:20 +0000477 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
Eugene Leviantbbe38602016-07-19 09:25:43 +0000478 if (!(Sec->getFlags() & SHF_ALLOC))
479 break;
480
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000481 std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName());
Eugene Leviantbbe38602016-07-19 09:25:43 +0000482 if (!PhdrIds.empty()) {
483 // Assign headers specified by linker script
484 for (size_t Id : PhdrIds) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000485 Ret[Id].add(Sec);
Eugene Leviant865bf862016-07-21 10:43:25 +0000486 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
Rafael Espindola0b113672016-07-27 14:10:56 +0000487 Ret[Id].H.p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000488 }
489 } else {
490 // If we have no load segment or flags've changed then we want new load
491 // segment.
Rafael Espindola0b113672016-07-27 14:10:56 +0000492 uintX_t NewFlags = Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000493 if (Load == nullptr || Flags != NewFlags) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000494 Load = &*Ret.emplace(Ret.end(), PT_LOAD, NewFlags);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000495 Flags = NewFlags;
496 }
Rui Ueyama18f084f2016-07-20 19:36:41 +0000497 Load->add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000498 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000499 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000500 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000501}
502
Eugene Leviantf9bc3bd2016-08-16 06:40:58 +0000503template <class ELFT> bool LinkerScript<ELFT>::ignoreInterpSection() {
504 // Ignore .interp section in case we have PHDRS specification
505 // and PT_INTERP isn't listed.
506 return !Opt.PhdrsCommands.empty() &&
507 llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
508 return Cmd.Type == PT_INTERP;
509 }) == Opt.PhdrsCommands.end();
510}
511
Eugene Leviantbbe38602016-07-19 09:25:43 +0000512template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000513ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000514 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
515 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
516 if (Cmd->Name == Name)
517 return Cmd->Filler;
518 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000519}
520
George Rimar206fffa2016-08-17 08:16:57 +0000521template <class ELFT> Expr LinkerScript<ELFT>::getLma(StringRef Name) {
George Rimar8ceadb32016-08-17 07:44:19 +0000522 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
523 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
524 if (Cmd->LmaExpr && Cmd->Name == Name)
525 return Cmd->LmaExpr;
526 return {};
527}
528
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000529// Returns the index of the given section name in linker script
530// SECTIONS commands. Sections are laid out as the same order as they
531// were in the script. If a given name did not appear in the script,
532// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000533template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000534 int I = 0;
535 for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
536 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
537 if (Cmd->Name == Name)
538 return I;
539 ++I;
540 }
541 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000542}
543
544// A compartor to sort output sections. Returns -1 or 1 if
545// A or B are mentioned in linker script. Otherwise, returns 0.
Rui Ueyama07320e42016-04-20 20:13:41 +0000546template <class ELFT>
547int LinkerScript<ELFT>::compareSections(StringRef A, StringRef B) {
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000548 int I = getSectionIndex(A);
549 int J = getSectionIndex(B);
550 if (I == INT_MAX && J == INT_MAX)
Rui Ueyama717677a2016-02-11 21:17:59 +0000551 return 0;
552 return I < J ? -1 : 1;
553}
554
Eugene Leviantbbe38602016-07-19 09:25:43 +0000555template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
556 return !Opt.PhdrsCommands.empty();
557}
558
George Rimar9e694502016-07-29 16:18:47 +0000559template <class ELFT>
George Rimar884e7862016-09-08 08:19:13 +0000560uint64_t LinkerScript<ELFT>::getOutputSectionAddress(StringRef Name) {
George Rimar96659df2016-08-30 09:54:01 +0000561 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
562 if (Sec->getName() == Name)
563 return Sec->getVA();
564 error("undefined section " + Name);
565 return 0;
566}
567
568template <class ELFT>
George Rimar884e7862016-09-08 08:19:13 +0000569uint64_t LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
George Rimar9e694502016-07-29 16:18:47 +0000570 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
571 if (Sec->getName() == Name)
572 return Sec->getSize();
573 error("undefined section " + Name);
574 return 0;
575}
576
George Rimar884e7862016-09-08 08:19:13 +0000577template <class ELFT> uint64_t LinkerScript<ELFT>::getHeaderSize() {
George Rimare32a3592016-08-10 07:59:34 +0000578 return Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
579}
580
George Rimar884e7862016-09-08 08:19:13 +0000581template <class ELFT> uint64_t LinkerScript<ELFT>::getSymbolValue(StringRef S) {
582 if (SymbolBody *B = Symtab<ELFT>::X->find(S))
583 return B->getVA<ELFT>();
584 error("symbol not found: " + S);
585 return 0;
586}
587
Eugene Leviantbbe38602016-07-19 09:25:43 +0000588// Returns indices of ELF headers containing specific section, identified
589// by Name. Each index is a zero based number of ELF header listed within
590// PHDRS {} script block.
591template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000592std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000593 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
594 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000595 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000596 continue;
597
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000598 std::vector<size_t> Ret;
599 for (StringRef PhdrName : Cmd->Phdrs)
600 Ret.push_back(getPhdrIndex(PhdrName));
601 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000602 }
George Rimar31d842f2016-07-20 16:43:03 +0000603 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000604}
605
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000606template <class ELFT>
607size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
608 size_t I = 0;
609 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
610 if (Cmd.Name == PhdrName)
611 return I;
612 ++I;
613 }
614 error("section header '" + PhdrName + "' is not listed in PHDRS");
615 return 0;
616}
617
Rui Ueyama07320e42016-04-20 20:13:41 +0000618class elf::ScriptParser : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000619 typedef void (ScriptParser::*Handler)();
620
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000621public:
Rui Ueyama07320e42016-04-20 20:13:41 +0000622 ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
George Rimarf23b2322016-02-19 10:45:45 +0000623
George Rimar20b65982016-08-31 09:08:26 +0000624 void readLinkerScript();
625 void readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000626
627private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000628 void addFile(StringRef Path);
629
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000630 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000631 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000632 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000633 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000634 void readInclude();
Rui Ueyamaee592822015-10-07 00:25:09 +0000635 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000636 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000637 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000638 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000639 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000640 void readSections();
Rui Ueyama95769b42016-08-31 20:03:54 +0000641 void readVersion();
642 void readVersionScriptCommand();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000643
Rui Ueyama113cdec2016-07-24 23:05:57 +0000644 SymbolAssignment *readAssignment(StringRef Name);
George Rimarff1f29e2016-09-06 13:51:57 +0000645 std::vector<uint8_t> readFill();
Rui Ueyama10416562016-08-04 02:03:27 +0000646 OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
George Rimarff1f29e2016-09-06 13:51:57 +0000647 std::vector<uint8_t> readOutputSectionFiller(StringRef Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000648 std::vector<StringRef> readOutputSectionPhdrs();
George Rimara2496cb2016-08-30 09:46:59 +0000649 InputSectionDescription *readInputSectionDescription(StringRef Tok);
George Rimarc91930a2016-09-02 21:17:20 +0000650 Regex readFilePatterns();
George Rimara2496cb2016-08-30 09:46:59 +0000651 InputSectionDescription *readInputSectionRules(StringRef FilePattern);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000652 unsigned readPhdrType();
Rui Ueyama742c3832016-08-04 22:27:00 +0000653 SortKind readSortKind();
Petr Hoseka35e39c2016-08-16 01:11:16 +0000654 SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
Eugene Leviantdb741e72016-09-07 07:08:43 +0000655 SymbolAssignment *readProvideOrAssignment(StringRef Tok, bool MakeAbsolute);
George Rimar03fc0102016-07-28 07:18:23 +0000656 void readSort();
George Rimareefa7582016-08-04 09:29:31 +0000657 Expr readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +0000658
659 Expr readExpr();
660 Expr readExpr1(Expr Lhs, int MinPrec);
661 Expr readPrimary();
662 Expr readTernary(Expr Cond);
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +0000663 Expr readParenExpr();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000664
George Rimar20b65982016-08-31 09:08:26 +0000665 // For parsing version script.
666 void readExtern(std::vector<SymbolVersion> *Globals);
Rui Ueyama95769b42016-08-31 20:03:54 +0000667 void readVersionDeclaration(StringRef VerStr);
George Rimar20b65982016-08-31 09:08:26 +0000668 void readGlobal(StringRef VerStr);
669 void readLocal();
670
Rui Ueyama07320e42016-04-20 20:13:41 +0000671 ScriptConfiguration &Opt = *ScriptConfig;
672 StringSaver Saver = {ScriptConfig->Alloc};
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000673 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000674};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000675
George Rimar20b65982016-08-31 09:08:26 +0000676void ScriptParser::readVersionScript() {
Rui Ueyama95769b42016-08-31 20:03:54 +0000677 readVersionScriptCommand();
678 if (!atEOF())
679 setError("EOF expected, but got " + next());
680}
681
682void ScriptParser::readVersionScriptCommand() {
George Rimar20b65982016-08-31 09:08:26 +0000683 if (skip("{")) {
Rui Ueyama95769b42016-08-31 20:03:54 +0000684 readVersionDeclaration("");
George Rimar20b65982016-08-31 09:08:26 +0000685 return;
686 }
687
Rui Ueyama95769b42016-08-31 20:03:54 +0000688 while (!atEOF() && !Error && peek() != "}") {
George Rimar20b65982016-08-31 09:08:26 +0000689 StringRef VerStr = next();
690 if (VerStr == "{") {
Rui Ueyama95769b42016-08-31 20:03:54 +0000691 setError("anonymous version definition is used in "
692 "combination with other version definitions");
George Rimar20b65982016-08-31 09:08:26 +0000693 return;
694 }
695 expect("{");
Rui Ueyama95769b42016-08-31 20:03:54 +0000696 readVersionDeclaration(VerStr);
George Rimar20b65982016-08-31 09:08:26 +0000697 }
698}
699
Rui Ueyama95769b42016-08-31 20:03:54 +0000700void ScriptParser::readVersion() {
701 expect("{");
702 readVersionScriptCommand();
703 expect("}");
704}
705
George Rimar20b65982016-08-31 09:08:26 +0000706void ScriptParser::readLinkerScript() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000707 while (!atEOF()) {
708 StringRef Tok = next();
Rui Ueyamaa27eecc2016-09-02 18:52:41 +0000709 if (Tok == ";")
710 continue;
711
712 if (Tok == "ENTRY") {
713 readEntry();
714 } else if (Tok == "EXTERN") {
715 readExtern();
716 } else if (Tok == "GROUP" || Tok == "INPUT") {
717 readGroup();
718 } else if (Tok == "INCLUDE") {
719 readInclude();
720 } else if (Tok == "OUTPUT") {
721 readOutput();
722 } else if (Tok == "OUTPUT_ARCH") {
723 readOutputArch();
724 } else if (Tok == "OUTPUT_FORMAT") {
725 readOutputFormat();
726 } else if (Tok == "PHDRS") {
727 readPhdrs();
728 } else if (Tok == "SEARCH_DIR") {
729 readSearchDir();
730 } else if (Tok == "SECTIONS") {
731 readSections();
732 } else if (Tok == "VERSION") {
733 readVersion();
Eugene Leviantdb741e72016-09-07 07:08:43 +0000734 } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok, true)) {
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000735 if (Opt.HasContents)
736 Opt.Commands.emplace_back(Cmd);
737 else
738 Opt.Assignments.emplace_back(Cmd);
739 } else {
George Rimar57610422016-03-11 14:43:02 +0000740 setError("unknown directive: " + Tok);
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000741 }
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000742 }
743}
744
Rui Ueyama717677a2016-02-11 21:17:59 +0000745void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000746 if (IsUnderSysroot && S.startswith("/")) {
747 SmallString<128> Path;
748 (Config->Sysroot + S).toStringRef(Path);
749 if (sys::fs::exists(Path)) {
750 Driver->addFile(Saver.save(Path.str()));
751 return;
752 }
753 }
754
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +0000755 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +0000756 Driver->addFile(S);
757 } else if (S.startswith("=")) {
758 if (Config->Sysroot.empty())
759 Driver->addFile(S.substr(1));
760 else
761 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
762 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +0000763 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +0000764 } else if (sys::fs::exists(S)) {
765 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +0000766 } else {
767 std::string Path = findFromSearchPaths(S);
768 if (Path.empty())
George Rimar777f9632016-03-12 08:31:34 +0000769 setError("unable to find " + S);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000770 else
771 Driver->addFile(Saver.save(Path));
Rui Ueyama52a15092015-10-11 03:28:42 +0000772 }
773}
774
Rui Ueyama717677a2016-02-11 21:17:59 +0000775void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000776 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +0000777 bool Orig = Config->AsNeeded;
778 Config->AsNeeded = true;
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000779 while (!Error && !skip(")"))
780 addFile(next());
Rui Ueyama35da9b62015-10-11 20:59:12 +0000781 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000782}
783
Rui Ueyama717677a2016-02-11 21:17:59 +0000784void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +0000785 // -e <symbol> takes predecence over ENTRY(<symbol>).
786 expect("(");
787 StringRef Tok = next();
788 if (Config->Entry.empty())
789 Config->Entry = Tok;
790 expect(")");
791}
792
Rui Ueyama717677a2016-02-11 21:17:59 +0000793void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +0000794 expect("(");
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000795 while (!Error && !skip(")"))
796 Config->Undefined.push_back(next());
George Rimar83f406c2015-10-19 17:35:12 +0000797}
798
Rui Ueyama717677a2016-02-11 21:17:59 +0000799void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000800 expect("(");
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000801 while (!Error && !skip(")")) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000802 StringRef Tok = next();
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000803 if (Tok == "AS_NEEDED")
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000804 readAsNeeded();
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000805 else
806 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000807 }
808}
809
Rui Ueyama717677a2016-02-11 21:17:59 +0000810void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000811 StringRef Tok = next();
812 auto MBOrErr = MemoryBuffer::getFile(Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000813 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +0000814 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000815 return;
816 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000817 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Rui Ueyamaa47ee682015-10-11 01:53:04 +0000818 StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
819 std::vector<StringRef> V = tokenize(S);
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000820 Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000821}
822
Rui Ueyama717677a2016-02-11 21:17:59 +0000823void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +0000824 // -o <file> takes predecence over OUTPUT(<file>).
825 expect("(");
826 StringRef Tok = next();
827 if (Config->OutputFile.empty())
828 Config->OutputFile = Tok;
829 expect(")");
830}
831
Rui Ueyama717677a2016-02-11 21:17:59 +0000832void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +0000833 // Error checking only for now.
834 expect("(");
835 next();
836 expect(")");
837}
838
Rui Ueyama717677a2016-02-11 21:17:59 +0000839void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000840 // Error checking only for now.
841 expect("(");
842 next();
Davide Italiano6836c612015-10-12 21:08:41 +0000843 StringRef Tok = next();
844 if (Tok == ")")
845 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000846 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +0000847 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000848 return;
849 }
Davide Italiano6836c612015-10-12 21:08:41 +0000850 next();
851 expect(",");
852 next();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000853 expect(")");
854}
855
Eugene Leviantbbe38602016-07-19 09:25:43 +0000856void ScriptParser::readPhdrs() {
857 expect("{");
858 while (!Error && !skip("}")) {
859 StringRef Tok = next();
Eugene Leviant865bf862016-07-21 10:43:25 +0000860 Opt.PhdrsCommands.push_back({Tok, PT_NULL, false, false, UINT_MAX});
Eugene Leviantbbe38602016-07-19 09:25:43 +0000861 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
862
863 PhdrCmd.Type = readPhdrType();
864 do {
865 Tok = next();
866 if (Tok == ";")
867 break;
868 if (Tok == "FILEHDR")
869 PhdrCmd.HasFilehdr = true;
870 else if (Tok == "PHDRS")
871 PhdrCmd.HasPhdrs = true;
Eugene Leviant865bf862016-07-21 10:43:25 +0000872 else if (Tok == "FLAGS") {
873 expect("(");
Rafael Espindolaeb685cd2016-08-02 22:14:57 +0000874 // Passing 0 for the value of dot is a bit of a hack. It means that
875 // we accept expressions like ".|1".
876 PhdrCmd.Flags = readExpr()(0);
Eugene Leviant865bf862016-07-21 10:43:25 +0000877 expect(")");
878 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +0000879 setError("unexpected header attribute: " + Tok);
880 } while (!Error);
881 }
882}
883
Rui Ueyama717677a2016-02-11 21:17:59 +0000884void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +0000885 expect("(");
Rui Ueyama6c7ad132016-09-02 19:20:33 +0000886 if (!Config->Nostdlib)
887 Config->SearchPaths.push_back(next());
Davide Italiano68a39a62015-10-08 17:51:41 +0000888 expect(")");
889}
890
Rui Ueyama717677a2016-02-11 21:17:59 +0000891void ScriptParser::readSections() {
Rui Ueyama3de0a332016-07-29 03:31:09 +0000892 Opt.HasContents = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000893 expect("{");
George Rimar652852c2016-04-16 10:10:32 +0000894 while (!Error && !skip("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +0000895 StringRef Tok = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +0000896 BaseCommand *Cmd = readProvideOrAssignment(Tok, true);
Eugene Leviantceabe802016-08-11 07:56:43 +0000897 if (!Cmd) {
898 if (Tok == "ASSERT")
899 Cmd = new AssertCommand(readAssert());
900 else
901 Cmd = readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +0000902 }
Rui Ueyama10416562016-08-04 02:03:27 +0000903 Opt.Commands.emplace_back(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000904 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000905}
906
Rui Ueyama708019c2016-07-24 18:19:40 +0000907static int precedence(StringRef Op) {
908 return StringSwitch<int>(Op)
909 .Case("*", 4)
910 .Case("/", 4)
911 .Case("+", 3)
912 .Case("-", 3)
913 .Case("<", 2)
914 .Case(">", 2)
915 .Case(">=", 2)
916 .Case("<=", 2)
917 .Case("==", 2)
918 .Case("!=", 2)
919 .Case("&", 1)
Rafael Espindolacc3dd622016-08-22 21:33:35 +0000920 .Case("|", 1)
Rui Ueyama708019c2016-07-24 18:19:40 +0000921 .Default(-1);
922}
923
George Rimarc91930a2016-09-02 21:17:20 +0000924Regex ScriptParser::readFilePatterns() {
Rui Ueyama10416562016-08-04 02:03:27 +0000925 std::vector<StringRef> V;
926 while (!Error && !skip(")"))
927 V.push_back(next());
George Rimarc91930a2016-09-02 21:17:20 +0000928 return compileGlobPatterns(V);
George Rimar0702c4e2016-07-29 15:32:46 +0000929}
930
Rui Ueyama742c3832016-08-04 22:27:00 +0000931SortKind ScriptParser::readSortKind() {
932 if (skip("SORT") || skip("SORT_BY_NAME"))
933 return SortByName;
934 if (skip("SORT_BY_ALIGNMENT"))
935 return SortByAlignment;
936 return SortNone;
937}
938
George Rimara2496cb2016-08-30 09:46:59 +0000939InputSectionDescription *
940ScriptParser::readInputSectionRules(StringRef FilePattern) {
George Rimarc91930a2016-09-02 21:17:20 +0000941 auto *Cmd = new InputSectionDescription(FilePattern);
Davide Italiano0ed42b02016-07-25 21:47:13 +0000942 expect("(");
Davide Italianoe7282792016-07-27 01:44:01 +0000943
Rui Ueyama742c3832016-08-04 22:27:00 +0000944 // Read EXCLUDE_FILE().
Davide Italianoe7282792016-07-27 01:44:01 +0000945 if (skip("EXCLUDE_FILE")) {
946 expect("(");
George Rimarc91930a2016-09-02 21:17:20 +0000947 Cmd->ExcludedFileRe = readFilePatterns();
Davide Italiano0ed42b02016-07-25 21:47:13 +0000948 }
George Rimar06598002016-07-28 21:51:30 +0000949
Rui Ueyama742c3832016-08-04 22:27:00 +0000950 // Read SORT().
951 if (SortKind K1 = readSortKind()) {
952 Cmd->SortOuter = K1;
George Rimar0702c4e2016-07-29 15:32:46 +0000953 expect("(");
Rui Ueyama742c3832016-08-04 22:27:00 +0000954 if (SortKind K2 = readSortKind()) {
955 Cmd->SortInner = K2;
George Rimar350ece42016-08-03 08:35:59 +0000956 expect("(");
George Rimarc91930a2016-09-02 21:17:20 +0000957 Cmd->SectionRe = readFilePatterns();
George Rimar350ece42016-08-03 08:35:59 +0000958 expect(")");
959 } else {
George Rimarc91930a2016-09-02 21:17:20 +0000960 Cmd->SectionRe = readFilePatterns();
George Rimar350ece42016-08-03 08:35:59 +0000961 }
George Rimar0702c4e2016-07-29 15:32:46 +0000962 expect(")");
Rui Ueyama10416562016-08-04 02:03:27 +0000963 return Cmd;
George Rimar06598002016-07-28 21:51:30 +0000964 }
George Rimar0702c4e2016-07-29 15:32:46 +0000965
George Rimarc91930a2016-09-02 21:17:20 +0000966 Cmd->SectionRe = readFilePatterns();
Rui Ueyama10416562016-08-04 02:03:27 +0000967 return Cmd;
Davide Italianoe7282792016-07-27 01:44:01 +0000968}
969
George Rimara2496cb2016-08-30 09:46:59 +0000970InputSectionDescription *
971ScriptParser::readInputSectionDescription(StringRef Tok) {
George Rimar06598002016-07-28 21:51:30 +0000972 // Input section wildcard can be surrounded by KEEP.
973 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
George Rimara2496cb2016-08-30 09:46:59 +0000974 if (Tok == "KEEP") {
George Rimar06598002016-07-28 21:51:30 +0000975 expect("(");
George Rimara2496cb2016-08-30 09:46:59 +0000976 StringRef FilePattern = next();
977 InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
George Rimar06598002016-07-28 21:51:30 +0000978 expect(")");
George Rimarc91930a2016-09-02 21:17:20 +0000979 Opt.KeptSections.push_back(&Cmd->SectionRe);
Rui Ueyama10416562016-08-04 02:03:27 +0000980 return Cmd;
George Rimar06598002016-07-28 21:51:30 +0000981 }
George Rimara2496cb2016-08-30 09:46:59 +0000982 return readInputSectionRules(Tok);
Davide Italiano0ed42b02016-07-25 21:47:13 +0000983}
984
George Rimar03fc0102016-07-28 07:18:23 +0000985void ScriptParser::readSort() {
986 expect("(");
987 expect("CONSTRUCTORS");
988 expect(")");
989}
990
George Rimareefa7582016-08-04 09:29:31 +0000991Expr ScriptParser::readAssert() {
992 expect("(");
993 Expr E = readExpr();
994 expect(",");
995 StringRef Msg = next();
996 expect(")");
997 return [=](uint64_t Dot) {
998 uint64_t V = E(Dot);
999 if (!V)
1000 error(Msg);
1001 return V;
1002 };
1003}
1004
Rui Ueyama25150e82016-09-06 17:46:43 +00001005// Reads a FILL(expr) command. We handle the FILL command as an
1006// alias for =fillexp section attribute, which is different from
1007// what GNU linkers do.
1008// https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
George Rimarff1f29e2016-09-06 13:51:57 +00001009std::vector<uint8_t> ScriptParser::readFill() {
1010 expect("(");
1011 std::vector<uint8_t> V = readOutputSectionFiller(next());
1012 expect(")");
1013 expect(";");
1014 return V;
1015}
1016
Rui Ueyama10416562016-08-04 02:03:27 +00001017OutputSectionCommand *
1018ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +00001019 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
George Rimar58e5c4d2016-07-25 08:29:46 +00001020
1021 // Read an address expression.
1022 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
1023 if (peek() != ":")
1024 Cmd->AddrExpr = readExpr();
1025
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001026 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +00001027
George Rimar8ceadb32016-08-17 07:44:19 +00001028 if (skip("AT"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001029 Cmd->LmaExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001030 if (skip("ALIGN"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001031 Cmd->AlignExpr = readParenExpr();
George Rimardb24d9c2016-08-19 15:18:23 +00001032 if (skip("SUBALIGN"))
1033 Cmd->SubalignExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001034
Davide Italiano246f6812016-07-22 03:36:24 +00001035 // Parse constraints.
1036 if (skip("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001037 Cmd->Constraint = ConstraintKind::ReadOnly;
Davide Italiano246f6812016-07-22 03:36:24 +00001038 if (skip("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001039 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001040 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001041
Rui Ueyama025d59b2016-02-02 20:27:59 +00001042 while (!Error && !skip("}")) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001043 StringRef Tok = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +00001044 if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok, false))
Eugene Leviantceabe802016-08-11 07:56:43 +00001045 Cmd->Commands.emplace_back(Assignment);
George Rimarff1f29e2016-09-06 13:51:57 +00001046 else if (Tok == "FILL")
1047 Cmd->Filler = readFill();
Eugene Leviantceabe802016-08-11 07:56:43 +00001048 else if (Tok == "SORT")
George Rimar03fc0102016-07-28 07:18:23 +00001049 readSort();
George Rimara2496cb2016-08-30 09:46:59 +00001050 else if (peek() == "(")
1051 Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
Eugene Leviantceabe802016-08-11 07:56:43 +00001052 else
1053 setError("unknown command " + Tok);
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001054 }
George Rimar076fe152016-07-21 06:43:01 +00001055 Cmd->Phdrs = readOutputSectionPhdrs();
George Rimarff1f29e2016-09-06 13:51:57 +00001056 if (peek().startswith("="))
1057 Cmd->Filler = readOutputSectionFiller(next().drop_front());
Rui Ueyama10416562016-08-04 02:03:27 +00001058 return Cmd;
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001059}
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001060
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001061// Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
1062// https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
1063//
1064// ld.gold is not fully compatible with ld.bfd. ld.bfd handles
1065// hexstrings as blobs of arbitrary sizes, while ld.gold handles them
1066// as 32-bit big-endian values. We will do the same as ld.gold does
1067// because it's simpler than what ld.bfd does.
George Rimarff1f29e2016-09-06 13:51:57 +00001068std::vector<uint8_t> ScriptParser::readOutputSectionFiller(StringRef Tok) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001069 uint32_t V;
George Rimarff1f29e2016-09-06 13:51:57 +00001070 if (Tok.getAsInteger(0, V)) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001071 setError("invalid filler expression: " + Tok);
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001072 return {};
George Rimare2ee72b2016-02-26 14:48:31 +00001073 }
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001074 return {uint8_t(V >> 24), uint8_t(V >> 16), uint8_t(V >> 8), uint8_t(V)};
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001075}
1076
Petr Hoseka35e39c2016-08-16 01:11:16 +00001077SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
Eugene Levianta31c91b2016-07-22 07:38:40 +00001078 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +00001079 SymbolAssignment *Cmd = readAssignment(next());
Petr Hoseka35e39c2016-08-16 01:11:16 +00001080 Cmd->Provide = Provide;
Rui Ueyama174e0a12016-07-29 00:29:25 +00001081 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001082 expect(")");
1083 expect(";");
Rui Ueyama10416562016-08-04 02:03:27 +00001084 return Cmd;
Eugene Levianteda81a12016-07-12 06:39:48 +00001085}
1086
Eugene Leviantdb741e72016-09-07 07:08:43 +00001087SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok,
1088 bool MakeAbsolute) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001089 SymbolAssignment *Cmd = nullptr;
1090 if (peek() == "=" || peek() == "+=") {
1091 Cmd = readAssignment(Tok);
1092 expect(";");
1093 } else if (Tok == "PROVIDE") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001094 Cmd = readProvideHidden(true, false);
1095 } else if (Tok == "HIDDEN") {
1096 Cmd = readProvideHidden(false, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001097 } else if (Tok == "PROVIDE_HIDDEN") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001098 Cmd = readProvideHidden(true, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001099 }
Eugene Leviantdb741e72016-09-07 07:08:43 +00001100 if (Cmd && MakeAbsolute)
1101 Cmd->IsAbsolute = true;
Eugene Leviantceabe802016-08-11 07:56:43 +00001102 return Cmd;
1103}
1104
George Rimar30835ea2016-07-28 21:08:56 +00001105static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
1106 if (S == ".")
1107 return Dot;
George Rimar884e7862016-09-08 08:19:13 +00001108 return ScriptBase->getSymbolValue(S);
George Rimare32a3592016-08-10 07:59:34 +00001109}
1110
George Rimar30835ea2016-07-28 21:08:56 +00001111SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1112 StringRef Op = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +00001113 bool IsAbsolute = false;
1114 Expr E;
George Rimar30835ea2016-07-28 21:08:56 +00001115 assert(Op == "=" || Op == "+=");
Eugene Leviantdb741e72016-09-07 07:08:43 +00001116 if (skip("ABSOLUTE")) {
1117 E = readParenExpr();
1118 IsAbsolute = true;
1119 } else {
1120 E = readExpr();
1121 }
George Rimar30835ea2016-07-28 21:08:56 +00001122 if (Op == "+=")
1123 E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
Eugene Leviantdb741e72016-09-07 07:08:43 +00001124 return new SymbolAssignment(Name, E, IsAbsolute);
George Rimar30835ea2016-07-28 21:08:56 +00001125}
1126
1127// This is an operator-precedence parser to parse a linker
1128// script expression.
1129Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
1130
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001131static Expr combine(StringRef Op, Expr L, Expr R) {
1132 if (Op == "*")
1133 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1134 if (Op == "/") {
1135 return [=](uint64_t Dot) -> uint64_t {
1136 uint64_t RHS = R(Dot);
1137 if (RHS == 0) {
1138 error("division by zero");
1139 return 0;
1140 }
1141 return L(Dot) / RHS;
1142 };
1143 }
1144 if (Op == "+")
1145 return [=](uint64_t Dot) { return L(Dot) + R(Dot); };
1146 if (Op == "-")
1147 return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
1148 if (Op == "<")
1149 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
1150 if (Op == ">")
1151 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
1152 if (Op == ">=")
1153 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
1154 if (Op == "<=")
1155 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
1156 if (Op == "==")
1157 return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
1158 if (Op == "!=")
1159 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
1160 if (Op == "&")
1161 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
Rafael Espindolacc3dd622016-08-22 21:33:35 +00001162 if (Op == "|")
1163 return [=](uint64_t Dot) { return L(Dot) | R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001164 llvm_unreachable("invalid operator");
1165}
1166
Rui Ueyama708019c2016-07-24 18:19:40 +00001167// This is a part of the operator-precedence parser. This function
1168// assumes that the remaining token stream starts with an operator.
1169Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1170 while (!atEOF() && !Error) {
1171 // Read an operator and an expression.
1172 StringRef Op1 = peek();
1173 if (Op1 == "?")
1174 return readTernary(Lhs);
1175 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +00001176 break;
Rui Ueyama708019c2016-07-24 18:19:40 +00001177 next();
1178 Expr Rhs = readPrimary();
1179
1180 // Evaluate the remaining part of the expression first if the
1181 // next operator has greater precedence than the previous one.
1182 // For example, if we have read "+" and "3", and if the next
1183 // operator is "*", then we'll evaluate 3 * ... part first.
1184 while (!atEOF()) {
1185 StringRef Op2 = peek();
1186 if (precedence(Op2) <= precedence(Op1))
1187 break;
1188 Rhs = readExpr1(Rhs, precedence(Op2));
1189 }
1190
1191 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +00001192 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001193 return Lhs;
1194}
1195
1196uint64_t static getConstant(StringRef S) {
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001197 if (S == "COMMONPAGESIZE")
Rui Ueyama708019c2016-07-24 18:19:40 +00001198 return Target->PageSize;
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001199 if (S == "MAXPAGESIZE")
1200 return Target->MaxPageSize;
Rui Ueyama708019c2016-07-24 18:19:40 +00001201 error("unknown constant: " + S);
1202 return 0;
1203}
1204
Rui Ueyama626e0b02016-09-02 18:19:00 +00001205// Parses Tok as an integer. Returns true if successful.
1206// It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1207// and decimal numbers. Decimal numbers may have "K" (kilo) or
1208// "M" (mega) prefixes.
George Rimar9f2f7ad2016-09-02 16:01:42 +00001209static bool readInteger(StringRef Tok, uint64_t &Result) {
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001210 if (Tok.startswith("-")) {
1211 if (!readInteger(Tok.substr(1), Result))
1212 return false;
1213 Result = -Result;
1214 return true;
1215 }
George Rimar9f2f7ad2016-09-02 16:01:42 +00001216 if (Tok.startswith_lower("0x"))
1217 return !Tok.substr(2).getAsInteger(16, Result);
1218 if (Tok.endswith_lower("H"))
1219 return !Tok.drop_back().getAsInteger(16, Result);
1220
1221 int Suffix = 1;
1222 if (Tok.endswith_lower("K")) {
1223 Suffix = 1024;
1224 Tok = Tok.drop_back();
1225 } else if (Tok.endswith_lower("M")) {
1226 Suffix = 1024 * 1024;
1227 Tok = Tok.drop_back();
1228 }
1229 if (Tok.getAsInteger(10, Result))
1230 return false;
1231 Result *= Suffix;
1232 return true;
1233}
1234
Rui Ueyama708019c2016-07-24 18:19:40 +00001235Expr ScriptParser::readPrimary() {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001236 if (peek() == "(")
1237 return readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001238
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001239 StringRef Tok = next();
Rui Ueyama708019c2016-07-24 18:19:40 +00001240
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001241 if (Tok == "~") {
1242 Expr E = readPrimary();
1243 return [=](uint64_t Dot) { return ~E(Dot); };
1244 }
1245 if (Tok == "-") {
1246 Expr E = readPrimary();
1247 return [=](uint64_t Dot) { return -E(Dot); };
1248 }
1249
Rui Ueyama708019c2016-07-24 18:19:40 +00001250 // Built-in functions are parsed here.
1251 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
George Rimar96659df2016-08-30 09:54:01 +00001252 if (Tok == "ADDR") {
1253 expect("(");
1254 StringRef Name = next();
1255 expect(")");
George Rimar884e7862016-09-08 08:19:13 +00001256 return
1257 [=](uint64_t Dot) { return ScriptBase->getOutputSectionAddress(Name); };
George Rimar96659df2016-08-30 09:54:01 +00001258 }
George Rimareefa7582016-08-04 09:29:31 +00001259 if (Tok == "ASSERT")
1260 return readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001261 if (Tok == "ALIGN") {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001262 Expr E = readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001263 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1264 }
1265 if (Tok == "CONSTANT") {
1266 expect("(");
1267 StringRef Tok = next();
1268 expect(")");
1269 return [=](uint64_t Dot) { return getConstant(Tok); };
1270 }
Rafael Espindola54c145c2016-07-28 18:16:24 +00001271 if (Tok == "SEGMENT_START") {
1272 expect("(");
1273 next();
1274 expect(",");
1275 uint64_t Val;
1276 next().getAsInteger(0, Val);
1277 expect(")");
1278 return [=](uint64_t Dot) { return Val; };
1279 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001280 if (Tok == "DATA_SEGMENT_ALIGN") {
1281 expect("(");
1282 Expr E = readExpr();
1283 expect(",");
1284 readExpr();
1285 expect(")");
Rui Ueyamaf7791bb2016-07-26 19:34:10 +00001286 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001287 }
1288 if (Tok == "DATA_SEGMENT_END") {
1289 expect("(");
1290 expect(".");
1291 expect(")");
1292 return [](uint64_t Dot) { return Dot; };
1293 }
George Rimar276b4e62016-07-26 17:58:44 +00001294 // GNU linkers implements more complicated logic to handle
1295 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1296 // the next page boundary for simplicity.
1297 if (Tok == "DATA_SEGMENT_RELRO_END") {
1298 expect("(");
1299 next();
1300 expect(",");
1301 readExpr();
1302 expect(")");
1303 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1304 }
George Rimar9e694502016-07-29 16:18:47 +00001305 if (Tok == "SIZEOF") {
1306 expect("(");
1307 StringRef Name = next();
1308 expect(")");
George Rimar884e7862016-09-08 08:19:13 +00001309 return [=](uint64_t Dot) { return ScriptBase->getOutputSectionSize(Name); };
George Rimar9e694502016-07-29 16:18:47 +00001310 }
George Rimare32a3592016-08-10 07:59:34 +00001311 if (Tok == "SIZEOF_HEADERS")
George Rimar884e7862016-09-08 08:19:13 +00001312 return [=](uint64_t Dot) { return ScriptBase->getHeaderSize(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001313
George Rimar9f2f7ad2016-09-02 16:01:42 +00001314 // Tok is a literal number.
1315 uint64_t V;
1316 if (readInteger(Tok, V))
1317 return [=](uint64_t Dot) { return V; };
1318
1319 // Tok is a symbol name.
1320 if (Tok != "." && !isValidCIdentifier(Tok))
1321 setError("malformed number: " + Tok);
1322 return [=](uint64_t Dot) { return getSymbolValue(Tok, Dot); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001323}
1324
1325Expr ScriptParser::readTernary(Expr Cond) {
1326 next();
1327 Expr L = readExpr();
1328 expect(":");
1329 Expr R = readExpr();
1330 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1331}
1332
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001333Expr ScriptParser::readParenExpr() {
1334 expect("(");
1335 Expr E = readExpr();
1336 expect(")");
1337 return E;
1338}
1339
Eugene Leviantbbe38602016-07-19 09:25:43 +00001340std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1341 std::vector<StringRef> Phdrs;
1342 while (!Error && peek().startswith(":")) {
1343 StringRef Tok = next();
1344 Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
1345 if (Tok.empty()) {
1346 setError("section header name is empty");
1347 break;
1348 }
Rui Ueyama047404f2016-07-20 19:36:36 +00001349 Phdrs.push_back(Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001350 }
1351 return Phdrs;
1352}
1353
1354unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001355 StringRef Tok = next();
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001356 unsigned Ret = StringSwitch<unsigned>(Tok)
1357 .Case("PT_NULL", PT_NULL)
1358 .Case("PT_LOAD", PT_LOAD)
1359 .Case("PT_DYNAMIC", PT_DYNAMIC)
1360 .Case("PT_INTERP", PT_INTERP)
1361 .Case("PT_NOTE", PT_NOTE)
1362 .Case("PT_SHLIB", PT_SHLIB)
1363 .Case("PT_PHDR", PT_PHDR)
1364 .Case("PT_TLS", PT_TLS)
1365 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1366 .Case("PT_GNU_STACK", PT_GNU_STACK)
1367 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1368 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001369
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001370 if (Ret == (unsigned)-1) {
1371 setError("invalid program header type: " + Tok);
1372 return PT_NULL;
1373 }
1374 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001375}
1376
Rui Ueyama95769b42016-08-31 20:03:54 +00001377void ScriptParser::readVersionDeclaration(StringRef VerStr) {
George Rimar20b65982016-08-31 09:08:26 +00001378 // Identifiers start at 2 because 0 and 1 are reserved
1379 // for VER_NDX_LOCAL and VER_NDX_GLOBAL constants.
1380 size_t VersionId = Config->VersionDefinitions.size() + 2;
1381 Config->VersionDefinitions.push_back({VerStr, VersionId});
1382
1383 if (skip("global:") || peek() != "local:")
1384 readGlobal(VerStr);
1385 if (skip("local:"))
1386 readLocal();
1387 expect("}");
1388
1389 // Each version may have a parent version. For example, "Ver2" defined as
1390 // "Ver2 { global: foo; local: *; } Ver1;" has "Ver1" as a parent. This
1391 // version hierarchy is, probably against your instinct, purely for human; the
1392 // runtime doesn't care about them at all. In LLD, we simply skip the token.
1393 if (!VerStr.empty() && peek() != ";")
1394 next();
1395 expect(";");
1396}
1397
1398void ScriptParser::readLocal() {
1399 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1400 expect("*");
1401 expect(";");
1402}
1403
1404void ScriptParser::readExtern(std::vector<SymbolVersion> *Globals) {
1405 expect("C++");
1406 expect("{");
1407
1408 for (;;) {
1409 if (peek() == "}" || Error)
1410 break;
1411 Globals->push_back({next(), true});
1412 expect(";");
1413 }
1414
1415 expect("}");
1416 expect(";");
1417}
1418
1419void ScriptParser::readGlobal(StringRef VerStr) {
1420 std::vector<SymbolVersion> *Globals;
1421 if (VerStr.empty())
1422 Globals = &Config->VersionScriptGlobals;
1423 else
1424 Globals = &Config->VersionDefinitions.back().Globals;
1425
1426 for (;;) {
1427 if (skip("extern"))
1428 readExtern(Globals);
1429
1430 StringRef Cur = peek();
1431 if (Cur == "}" || Cur == "local:" || Error)
1432 return;
1433 next();
1434 Globals->push_back({Cur, false});
1435 expect(";");
1436 }
1437}
1438
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001439static bool isUnderSysroot(StringRef Path) {
1440 if (Config->Sysroot == "")
1441 return false;
1442 for (; !Path.empty(); Path = sys::path::parent_path(Path))
1443 if (sys::fs::equivalent(Config->Sysroot, Path))
1444 return true;
1445 return false;
1446}
1447
Rui Ueyama07320e42016-04-20 20:13:41 +00001448void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001449 StringRef Path = MB.getBufferIdentifier();
George Rimar20b65982016-08-31 09:08:26 +00001450 ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).readLinkerScript();
1451}
1452
1453void elf::readVersionScript(MemoryBufferRef MB) {
1454 ScriptParser(MB.getBuffer(), false).readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001455}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001456
Rui Ueyama07320e42016-04-20 20:13:41 +00001457template class elf::LinkerScript<ELF32LE>;
1458template class elf::LinkerScript<ELF32BE>;
1459template class elf::LinkerScript<ELF64LE>;
1460template class elf::LinkerScript<ELF64BE>;