blob: b7f71944a2a335584f0d77db2b9dfacc3bb0539a [file] [log] [blame]
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001//===- LinkerScript.cpp ---------------------------------------------------===//
2//
3// The LLVM Linker
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains the parser/evaluator of the linker script.
Rui Ueyama629e0aa52016-07-21 19:45:22 +000011// It parses a linker script and write the result to Config or ScriptConfig
12// objects.
13//
14// If SECTIONS command is used, a ScriptConfig contains an AST
15// of the command which will later be consumed by createSections() and
16// assignAddresses().
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000017//
18//===----------------------------------------------------------------------===//
19
Rui Ueyama717677a2016-02-11 21:17:59 +000020#include "LinkerScript.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000021#include "Config.h"
22#include "Driver.h"
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +000023#include "InputSection.h"
George Rimar652852c2016-04-16 10:10:32 +000024#include "OutputSections.h"
Adhemerval Zanellae77b5bf2016-04-06 20:59:11 +000025#include "ScriptParser.h"
Rui Ueyama93c9af42016-06-29 08:01:32 +000026#include "Strings.h"
Eugene Levianteda81a12016-07-12 06:39:48 +000027#include "Symbols.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000028#include "SymbolTable.h"
Eugene Leviant467c4d52016-07-01 10:27:36 +000029#include "Target.h"
Eugene Leviantbbe38602016-07-19 09:25:43 +000030#include "Writer.h"
Rui Ueyama960504b2016-04-19 18:58:11 +000031#include "llvm/ADT/StringSwitch.h"
George Rimar652852c2016-04-16 10:10:32 +000032#include "llvm/Support/ELF.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000033#include "llvm/Support/FileSystem.h"
34#include "llvm/Support/MemoryBuffer.h"
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +000035#include "llvm/Support/Path.h"
Rui Ueyamaa47ee682015-10-11 01:53:04 +000036#include "llvm/Support/StringSaver.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000037
38using namespace llvm;
George Rimar652852c2016-04-16 10:10:32 +000039using namespace llvm::ELF;
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +000040using namespace llvm::object;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000041using namespace lld;
Rafael Espindolae0df00b2016-02-28 00:25:54 +000042using namespace lld::elf;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000043
George Rimar884e7862016-09-08 08:19:13 +000044LinkerScriptBase *elf::ScriptBase;
Rui Ueyama07320e42016-04-20 20:13:41 +000045ScriptConfiguration *elf::ScriptConfig;
Rui Ueyama717677a2016-02-11 21:17:59 +000046
George Rimar6c55f0e2016-09-08 08:20:30 +000047template <class ELFT> static void addRegular(SymbolAssignment *Cmd) {
Rui Ueyama16024212016-08-11 23:22:52 +000048 Symbol *Sym = Symtab<ELFT>::X->addRegular(Cmd->Name, STB_GLOBAL, STV_DEFAULT);
49 Sym->Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
50 Cmd->Sym = Sym->body();
Eugene Leviantceabe802016-08-11 07:56:43 +000051}
52
Rui Ueyama0c70d3c2016-08-12 03:31:09 +000053template <class ELFT> static void addSynthetic(SymbolAssignment *Cmd) {
George Rimare1937bb2016-08-19 15:36:32 +000054 Symbol *Sym = Symtab<ELFT>::X->addSynthetic(
55 Cmd->Name, nullptr, 0, Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT);
Rui Ueyama16024212016-08-11 23:22:52 +000056 Cmd->Sym = Sym->body();
Eugene Leviantceabe802016-08-11 07:56:43 +000057}
58
Eugene Leviantdb741e72016-09-07 07:08:43 +000059template <class ELFT> static void addSymbol(SymbolAssignment *Cmd) {
60 if (Cmd->IsAbsolute)
61 addRegular<ELFT>(Cmd);
62 else
63 addSynthetic<ELFT>(Cmd);
64}
Rui Ueyama16024212016-08-11 23:22:52 +000065// If a symbol was in PROVIDE(), we need to define it only when
66// it is an undefined symbol.
67template <class ELFT> static bool shouldDefine(SymbolAssignment *Cmd) {
68 if (Cmd->Name == ".")
Eugene Leviantceabe802016-08-11 07:56:43 +000069 return false;
Rui Ueyama16024212016-08-11 23:22:52 +000070 if (!Cmd->Provide)
71 return true;
72 SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
73 return B && B->isUndefined();
Eugene Leviantceabe802016-08-11 07:56:43 +000074}
75
George Rimar076fe152016-07-21 06:43:01 +000076bool SymbolAssignment::classof(const BaseCommand *C) {
77 return C->Kind == AssignmentKind;
78}
79
80bool OutputSectionCommand::classof(const BaseCommand *C) {
81 return C->Kind == OutputSectionKind;
82}
83
George Rimareea31142016-07-21 14:26:59 +000084bool InputSectionDescription::classof(const BaseCommand *C) {
85 return C->Kind == InputSectionKind;
86}
87
George Rimareefa7582016-08-04 09:29:31 +000088bool AssertCommand::classof(const BaseCommand *C) {
89 return C->Kind == AssertKind;
90}
91
Rui Ueyama36a153c2016-07-23 14:09:58 +000092template <class ELFT> static bool isDiscarded(InputSectionBase<ELFT> *S) {
George Rimareea31142016-07-21 14:26:59 +000093 return !S || !S->Live;
Rui Ueyama717677a2016-02-11 21:17:59 +000094}
95
Rui Ueyamaf34d0e02016-08-12 01:24:53 +000096template <class ELFT> LinkerScript<ELFT>::LinkerScript() {}
97template <class ELFT> LinkerScript<ELFT>::~LinkerScript() {}
98
Rui Ueyama07320e42016-04-20 20:13:41 +000099template <class ELFT>
100bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) {
George Rimarc91930a2016-09-02 21:17:20 +0000101 for (Regex *Re : Opt.KeptSections)
Rafael Espindola042a3f22016-09-08 14:06:08 +0000102 if (Re->match(S->Name))
George Rimareea31142016-07-21 14:26:59 +0000103 return true;
104 return false;
105}
106
George Rimar06598002016-07-28 21:51:30 +0000107static bool fileMatches(const InputSectionDescription *Desc,
108 StringRef Filename) {
George Rimarc91930a2016-09-02 21:17:20 +0000109 return const_cast<Regex &>(Desc->FileRe).match(Filename) &&
110 !const_cast<Regex &>(Desc->ExcludedFileRe).match(Filename);
George Rimar06598002016-07-28 21:51:30 +0000111}
112
Rui Ueyama6b274812016-07-25 22:51:07 +0000113// Returns input sections filtered by given glob patterns.
114template <class ELFT>
115std::vector<InputSectionBase<ELFT> *>
Rui Ueyamaad10c3d2016-07-28 21:05:04 +0000116LinkerScript<ELFT>::getInputSections(const InputSectionDescription *I) {
George Rimarc91930a2016-09-02 21:17:20 +0000117 const Regex &Re = I->SectionRe;
Rui Ueyama6b274812016-07-25 22:51:07 +0000118 std::vector<InputSectionBase<ELFT> *> Ret;
119 for (const std::unique_ptr<ObjectFile<ELFT>> &F :
George Rimar06598002016-07-28 21:51:30 +0000120 Symtab<ELFT>::X->getObjectFiles()) {
121 if (fileMatches(I, sys::path::filename(F->getName())))
122 for (InputSectionBase<ELFT> *S : F->getSections())
123 if (!isDiscarded(S) && !S->OutSec &&
Rafael Espindola042a3f22016-09-08 14:06:08 +0000124 const_cast<Regex &>(Re).match(S->Name))
Davide Italianoe7282792016-07-27 01:44:01 +0000125 Ret.push_back(S);
George Rimar06598002016-07-28 21:51:30 +0000126 }
Eugene Leviant3e6b0272016-07-28 19:24:13 +0000127
George Rimarc91930a2016-09-02 21:17:20 +0000128 if (const_cast<Regex &>(Re).match("COMMON"))
Rui Ueyamaad10c3d2016-07-28 21:05:04 +0000129 Ret.push_back(CommonInputSection<ELFT>::X);
Rui Ueyama6b274812016-07-25 22:51:07 +0000130 return Ret;
131}
132
Rafael Espindolac0028d32016-09-08 20:47:52 +0000133static bool compareName(InputSectionData *A, InputSectionData *B) {
Rafael Espindola042a3f22016-09-08 14:06:08 +0000134 return A->Name < B->Name;
Rui Ueyama742c3832016-08-04 22:27:00 +0000135}
George Rimar350ece42016-08-03 08:35:59 +0000136
Rafael Espindolac0028d32016-09-08 20:47:52 +0000137static bool compareAlignment(InputSectionData *A, InputSectionData *B) {
Rui Ueyama742c3832016-08-04 22:27:00 +0000138 // ">" is not a mistake. Larger alignments are placed before smaller
139 // alignments in order to reduce the amount of padding necessary.
140 // This is compatible with GNU.
141 return A->Alignment > B->Alignment;
142}
George Rimar350ece42016-08-03 08:35:59 +0000143
Rafael Espindolac0028d32016-09-08 20:47:52 +0000144static std::function<bool(InputSectionData *, InputSectionData *)>
Rui Ueyama742c3832016-08-04 22:27:00 +0000145getComparator(SortKind K) {
146 if (K == SortByName)
Rafael Espindolac0028d32016-09-08 20:47:52 +0000147 return compareName;
148 return compareAlignment;
Rui Ueyama742c3832016-08-04 22:27:00 +0000149}
George Rimar0702c4e2016-07-29 15:32:46 +0000150
151template <class ELFT>
Rafael Espindola7bd37872016-09-12 16:05:16 +0000152void LinkerScript<ELFT>::discard(ArrayRef<InputSectionBase<ELFT> *> V) {
153 for (InputSectionBase<ELFT> *S : V) {
154 S->Live = false;
155 reportDiscarded(S);
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000156 }
157}
158
George Rimar8f66df92016-08-12 20:38:20 +0000159static bool checkConstraint(uint64_t Flags, ConstraintKind Kind) {
160 bool RO = (Kind == ConstraintKind::ReadOnly);
161 bool RW = (Kind == ConstraintKind::ReadWrite);
162 bool Writable = Flags & SHF_WRITE;
Rui Ueyamaadcdb662016-09-06 22:50:48 +0000163 return !(RO && Writable) && !(RW && !Writable);
George Rimar8f66df92016-08-12 20:38:20 +0000164}
165
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000166template <class ELFT>
George Rimar06ae6832016-08-12 09:07:57 +0000167static bool matchConstraints(ArrayRef<InputSectionBase<ELFT> *> Sections,
168 ConstraintKind Kind) {
George Rimar8f66df92016-08-12 20:38:20 +0000169 if (Kind == ConstraintKind::NoConstraint)
170 return true;
171 return llvm::all_of(Sections, [=](InputSectionBase<ELFT> *Sec) {
172 return checkConstraint(Sec->getSectionHdr()->sh_flags, Kind);
George Rimar06ae6832016-08-12 09:07:57 +0000173 });
174}
175
176template <class ELFT>
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000177std::vector<InputSectionBase<ELFT> *>
George Rimar06ae6832016-08-12 09:07:57 +0000178LinkerScript<ELFT>::createInputSectionList(OutputSectionCommand &OutCmd) {
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000179 std::vector<InputSectionBase<ELFT> *> Ret;
Eugene Leviant97403d12016-09-01 09:55:57 +0000180 DenseSet<InputSectionBase<ELFT> *> SectionIndex;
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000181
George Rimar06ae6832016-08-12 09:07:57 +0000182 for (const std::unique_ptr<BaseCommand> &Base : OutCmd.Commands) {
183 if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base.get())) {
184 if (shouldDefine<ELFT>(OutCmd))
Eugene Leviantdb741e72016-09-07 07:08:43 +0000185 addSymbol<ELFT>(OutCmd);
Eugene Leviant97403d12016-09-01 09:55:57 +0000186 OutCmd->GoesAfter = Ret.empty() ? nullptr : Ret.back();
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000187 continue;
188 }
189
190 auto *Cmd = cast<InputSectionDescription>(Base.get());
191 std::vector<InputSectionBase<ELFT> *> V = getInputSections(Cmd);
George Rimar06ae6832016-08-12 09:07:57 +0000192 if (!matchConstraints<ELFT>(V, OutCmd.Constraint))
193 continue;
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000194 if (Cmd->SortInner)
Rafael Espindolac0028d32016-09-08 20:47:52 +0000195 std::stable_sort(V.begin(), V.end(), getComparator(Cmd->SortInner));
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000196 if (Cmd->SortOuter)
Rafael Espindolac0028d32016-09-08 20:47:52 +0000197 std::stable_sort(V.begin(), V.end(), getComparator(Cmd->SortOuter));
Eugene Leviant97403d12016-09-01 09:55:57 +0000198
199 // Add all input sections corresponding to rule 'Cmd' to
200 // resulting vector. We do not add duplicate input sections.
201 for (InputSectionBase<ELFT> *S : V)
202 if (SectionIndex.insert(S).second)
203 Ret.push_back(S);
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000204 }
205 return Ret;
206}
207
George Rimar6c55f0e2016-09-08 08:20:30 +0000208template <class ELFT> void LinkerScript<ELFT>::createAssignments() {
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000209 for (const std::unique_ptr<SymbolAssignment> &Cmd : Opt.Assignments) {
210 if (shouldDefine<ELFT>(Cmd.get()))
211 addRegular<ELFT>(Cmd.get());
212 if (Cmd->Sym)
213 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(0);
214 }
215}
216
217template <class ELFT>
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000218void LinkerScript<ELFT>::createSections(OutputSectionFactory<ELFT> &Factory) {
Rafael Espindola28c15972016-09-13 13:00:06 +0000219 auto AddSec = [&](InputSectionBase<ELFT> *Sec, StringRef Name) {
220 OutputSectionBase<ELFT> *OutSec;
221 bool IsNew;
222 std::tie(OutSec, IsNew) = Factory.create(Sec, Name);
223 if (IsNew)
224 OutputSections->push_back(OutSec);
225 return OutSec;
226 };
227
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000228 for (const std::unique_ptr<BaseCommand> &Base1 : Opt.Commands) {
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000229 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base1.get())) {
230 if (shouldDefine<ELFT>(Cmd))
231 addRegular<ELFT>(Cmd);
232 continue;
233 }
234
Eugene Leviantceabe802016-08-11 07:56:43 +0000235 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000236 std::vector<InputSectionBase<ELFT> *> V = createInputSectionList(*Cmd);
237
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000238 if (Cmd->Name == "/DISCARD/") {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000239 discard(V);
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000240 continue;
241 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000242
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) {
Rafael Espindola28c15972016-09-13 13:00:06 +0000247 OutputSectionBase<ELFT> *OutSec = AddSec(Sec, Cmd->Name);
George Rimara14b13d2016-09-07 10:46:07 +0000248 uint32_t Subalign = Cmd->SubalignExpr ? Cmd->SubalignExpr(0) : 0;
249
George Rimardb24d9c2016-08-19 15:18:23 +0000250 if (Subalign)
251 Sec->Alignment = Subalign;
Eugene Leviant97403d12016-09-01 09:55:57 +0000252 OutSec->addSection(Sec);
George Rimardb24d9c2016-08-19 15:18:23 +0000253 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000254 }
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000255 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000256
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000257 // Add orphan sections.
Rui Ueyama6b274812016-07-25 22:51:07 +0000258 for (const std::unique_ptr<ObjectFile<ELFT>> &F :
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000259 Symtab<ELFT>::X->getObjectFiles()) {
260 for (InputSectionBase<ELFT> *S : F->getSections()) {
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000261 if (isDiscarded(S) || S->OutSec)
262 continue;
Rafael Espindola28c15972016-09-13 13:00:06 +0000263 OutputSectionBase<ELFT> *OutSec = AddSec(S, getOutputSectionName(S));
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000264 OutSec->addSection(S);
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000265 }
266 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000267}
268
Eugene Leviantdb741e72016-09-07 07:08:43 +0000269// Sets value of a section-defined symbol. Two kinds of
270// symbols are processed: synthetic symbols, whose value
271// is an offset from beginning of section and regular
272// symbols whose value is absolute.
273template <class ELFT>
274static void assignSectionSymbol(SymbolAssignment *Cmd,
275 OutputSectionBase<ELFT> *Sec,
276 typename ELFT::uint Off) {
277 if (!Cmd->Sym)
278 return;
279
280 if (auto *Body = dyn_cast<DefinedSynthetic<ELFT>>(Cmd->Sym)) {
281 Body->Section = Sec;
282 Body->Value = Cmd->Expression(Sec->getVA() + Off) - Sec->getVA();
283 return;
284 }
285 auto *Body = cast<DefinedRegular<ELFT>>(Cmd->Sym);
286 Body->Value = Cmd->Expression(Sec->getVA() + Off);
287}
288
Eugene Leviant20889c52016-08-31 08:13:33 +0000289// Linker script may define start and end symbols for special section types,
290// like .got, .eh_frame_hdr, .eh_frame and others. Those sections are not a list
291// of regular input input sections, therefore our way of defining symbols for
292// regular sections will not work. The approach we use for special section types
293// is not perfect - it handles only start and end symbols.
294template <class ELFT>
295void addStartEndSymbols(OutputSectionCommand *Cmd,
296 OutputSectionBase<ELFT> *Sec) {
297 bool Start = true;
298 BaseCommand *PrevCmd = nullptr;
299
300 for (std::unique_ptr<BaseCommand> &Base : Cmd->Commands) {
301 if (auto *AssignCmd = dyn_cast<SymbolAssignment>(Base.get())) {
Eugene Leviantdb741e72016-09-07 07:08:43 +0000302 assignSectionSymbol<ELFT>(AssignCmd, Sec, Start ? 0 : Sec->getSize());
Eugene Leviant20889c52016-08-31 08:13:33 +0000303 } else {
304 if (!Start && isa<SymbolAssignment>(PrevCmd))
305 error("section '" + Sec->getName() +
306 "' supports only start and end symbols");
307 Start = false;
308 }
309 PrevCmd = Base.get();
310 }
311}
312
313template <class ELFT>
314void assignOffsets(OutputSectionCommand *Cmd, OutputSectionBase<ELFT> *Sec) {
Eugene Leviantceabe802016-08-11 07:56:43 +0000315 auto *OutSec = dyn_cast<OutputSection<ELFT>>(Sec);
Rui Ueyama2de509c2016-08-12 00:55:08 +0000316 if (!OutSec) {
317 Sec->assignOffsets();
Eugene Leviant20889c52016-08-31 08:13:33 +0000318 // This section is not regular output section. However linker script may
319 // have defined start/end symbols for it. This case is handled below.
320 addStartEndSymbols(Cmd, Sec);
Eugene Leviantceabe802016-08-11 07:56:43 +0000321 return;
Rui Ueyama2de509c2016-08-12 00:55:08 +0000322 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000323 typedef typename ELFT::uint uintX_t;
324 uintX_t Off = 0;
Eugene Leviant97403d12016-09-01 09:55:57 +0000325 auto ItCmd = Cmd->Commands.begin();
Eugene Leviantceabe802016-08-11 07:56:43 +0000326
Eugene Leviant97403d12016-09-01 09:55:57 +0000327 // Assigns values to all symbols following the given
328 // input section 'D' in output section 'Sec'. When symbols
329 // are in the beginning of output section the value of 'D'
330 // is nullptr.
331 auto AssignSuccessors = [&](InputSectionData *D) {
332 for (; ItCmd != Cmd->Commands.end(); ++ItCmd) {
333 auto *AssignCmd = dyn_cast<SymbolAssignment>(ItCmd->get());
334 if (!AssignCmd)
335 continue;
336 if (D != AssignCmd->GoesAfter)
337 break;
338
Eugene Leviant97403d12016-09-01 09:55:57 +0000339 if (AssignCmd->Name == ".") {
340 // Update to location counter means update to section size.
Eugene Leviantdb741e72016-09-07 07:08:43 +0000341 Off = AssignCmd->Expression(Sec->getVA() + Off) - Sec->getVA();
Eugene Leviant97403d12016-09-01 09:55:57 +0000342 Sec->setSize(Off);
343 continue;
344 }
Eugene Leviantdb741e72016-09-07 07:08:43 +0000345 assignSectionSymbol<ELFT>(AssignCmd, Sec, Off);
Eugene Leviantceabe802016-08-11 07:56:43 +0000346 }
Eugene Leviant97403d12016-09-01 09:55:57 +0000347 };
348
349 AssignSuccessors(nullptr);
350 for (InputSection<ELFT> *I : OutSec->Sections) {
351 Off = alignTo(Off, I->Alignment);
352 I->OutSecOff = Off;
353 Off += I->getSize();
Rui Ueyamaf4a30a52016-08-11 21:30:42 +0000354 // Update section size inside for-loop, so that SIZEOF
Eugene Leviantceabe802016-08-11 07:56:43 +0000355 // works correctly in the case below:
356 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
357 Sec->setSize(Off);
Eugene Leviant97403d12016-09-01 09:55:57 +0000358 // Add symbols following current input section.
359 AssignSuccessors(I);
Eugene Leviantceabe802016-08-11 07:56:43 +0000360 }
361}
362
George Rimar8f66df92016-08-12 20:38:20 +0000363template <class ELFT>
George Rimara14b13d2016-09-07 10:46:07 +0000364static std::vector<OutputSectionBase<ELFT> *>
365findSections(OutputSectionCommand &Cmd,
366 ArrayRef<OutputSectionBase<ELFT> *> Sections) {
367 std::vector<OutputSectionBase<ELFT> *> Ret;
368 for (OutputSectionBase<ELFT> *Sec : Sections)
369 if (Sec->getName() == Cmd.Name &&
370 checkConstraint(Sec->getFlags(), Cmd.Constraint))
371 Ret.push_back(Sec);
372 return Ret;
George Rimar8f66df92016-08-12 20:38:20 +0000373}
374
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000375template <class ELFT> void LinkerScript<ELFT>::assignAddresses() {
George Rimar652852c2016-04-16 10:10:32 +0000376 // Orphan sections are sections present in the input files which
Rui Ueyama7c18c282016-04-18 21:00:40 +0000377 // are not explicitly placed into the output file by the linker script.
378 // We place orphan sections at end of file.
379 // Other linkers places them using some heuristics as described in
George Rimar652852c2016-04-16 10:10:32 +0000380 // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
Rui Ueyamae5cc6682016-08-12 00:36:56 +0000381 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
George Rimar652852c2016-04-16 10:10:32 +0000382 StringRef Name = Sec->getName();
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000383 if (getSectionIndex(Name) == INT_MAX)
George Rimar076fe152016-07-21 06:43:01 +0000384 Opt.Commands.push_back(llvm::make_unique<OutputSectionCommand>(Name));
George Rimar652852c2016-04-16 10:10:32 +0000385 }
George Rimar652852c2016-04-16 10:10:32 +0000386
Rui Ueyama7c18c282016-04-18 21:00:40 +0000387 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rui Ueyama4f7500b2016-08-12 04:00:22 +0000388 Dot = getHeaderSize();
Eugene Leviant467c4d52016-07-01 10:27:36 +0000389 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
George Rimar652852c2016-04-16 10:10:32 +0000390 uintX_t ThreadBssOffset = 0;
George Rimar652852c2016-04-16 10:10:32 +0000391
George Rimar076fe152016-07-21 06:43:01 +0000392 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
393 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
Rui Ueyama8d083e62016-07-29 05:48:39 +0000394 if (Cmd->Name == ".") {
395 Dot = Cmd->Expression(Dot);
396 } else if (Cmd->Sym) {
397 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(Dot);
398 }
George Rimar652852c2016-04-16 10:10:32 +0000399 continue;
400 }
401
George Rimareefa7582016-08-04 09:29:31 +0000402 if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
403 Cmd->Expression(Dot);
404 continue;
405 }
406
George Rimar076fe152016-07-21 06:43:01 +0000407 auto *Cmd = cast<OutputSectionCommand>(Base.get());
George Rimara14b13d2016-09-07 10:46:07 +0000408 for (OutputSectionBase<ELFT> *Sec :
409 findSections<ELFT>(*Cmd, *OutputSections)) {
George Rimar652852c2016-04-16 10:10:32 +0000410
George Rimara14b13d2016-09-07 10:46:07 +0000411 if (Cmd->AddrExpr)
412 Dot = Cmd->AddrExpr(Dot);
George Rimar58e5c4d2016-07-25 08:29:46 +0000413
George Rimara14b13d2016-09-07 10:46:07 +0000414 if ((Sec->getFlags() & SHF_TLS) && Sec->getType() == SHT_NOBITS) {
415 uintX_t TVA = Dot + ThreadBssOffset;
416 TVA = alignTo(TVA, Sec->getAlignment());
417 Sec->setVA(TVA);
418 assignOffsets(Cmd, Sec);
419 ThreadBssOffset = TVA - Dot + Sec->getSize();
420 continue;
421 }
422
423 if (!(Sec->getFlags() & SHF_ALLOC)) {
424 assignOffsets(Cmd, Sec);
425 continue;
426 }
427
428 Dot = alignTo(Dot, Sec->getAlignment());
429 Sec->setVA(Dot);
Eugene Leviant20889c52016-08-31 08:13:33 +0000430 assignOffsets(Cmd, Sec);
George Rimara14b13d2016-09-07 10:46:07 +0000431 MinVA = std::min(MinVA, Dot);
432 Dot += Sec->getSize();
George Rimar652852c2016-04-16 10:10:32 +0000433 }
434 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000435
Rafael Espindola64c32d62016-07-07 14:28:47 +0000436 // ELF and Program headers need to be right before the first section in
George Rimarb91e7112016-07-19 07:42:07 +0000437 // memory. Set their addresses accordingly.
Eugene Leviant467c4d52016-07-01 10:27:36 +0000438 MinVA = alignDown(MinVA - Out<ELFT>::ElfHeader->getSize() -
439 Out<ELFT>::ProgramHeaders->getSize(),
440 Target->PageSize);
441 Out<ELFT>::ElfHeader->setVA(MinVA);
442 Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
George Rimar652852c2016-04-16 10:10:32 +0000443}
444
Rui Ueyama464daad2016-08-22 04:55:20 +0000445// Creates program headers as instructed by PHDRS linker script command.
Rui Ueyama07320e42016-04-20 20:13:41 +0000446template <class ELFT>
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000447std::vector<PhdrEntry<ELFT>> LinkerScript<ELFT>::createPhdrs() {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000448 std::vector<PhdrEntry<ELFT>> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000449
Rui Ueyama464daad2016-08-22 04:55:20 +0000450 // Process PHDRS and FILEHDR keywords because they are not
451 // real output sections and cannot be added in the following loop.
Eugene Leviantbbe38602016-07-19 09:25:43 +0000452 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000453 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
454 PhdrEntry<ELFT> &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000455
456 if (Cmd.HasFilehdr)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000457 Phdr.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000458 if (Cmd.HasPhdrs)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000459 Phdr.add(Out<ELFT>::ProgramHeaders);
Eugene Leviant56b21c82016-09-09 09:46:16 +0000460
461 if (Cmd.LMAExpr) {
462 Phdr.H.p_paddr = Cmd.LMAExpr(0);
463 Phdr.HasLMA = true;
464 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000465 }
466
Rui Ueyama464daad2016-08-22 04:55:20 +0000467 // Add output sections to program headers.
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000468 PhdrEntry<ELFT> *Load = nullptr;
469 uintX_t Flags = PF_R;
Rui Ueyama464daad2016-08-22 04:55:20 +0000470 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
Eugene Leviantbbe38602016-07-19 09:25:43 +0000471 if (!(Sec->getFlags() & SHF_ALLOC))
472 break;
473
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000474 std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName());
Eugene Leviantbbe38602016-07-19 09:25:43 +0000475 if (!PhdrIds.empty()) {
476 // Assign headers specified by linker script
477 for (size_t Id : PhdrIds) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000478 Ret[Id].add(Sec);
Eugene Leviant865bf862016-07-21 10:43:25 +0000479 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
Rafael Espindola0b113672016-07-27 14:10:56 +0000480 Ret[Id].H.p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000481 }
482 } else {
483 // If we have no load segment or flags've changed then we want new load
484 // segment.
Rafael Espindola0b113672016-07-27 14:10:56 +0000485 uintX_t NewFlags = Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000486 if (Load == nullptr || Flags != NewFlags) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000487 Load = &*Ret.emplace(Ret.end(), PT_LOAD, NewFlags);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000488 Flags = NewFlags;
489 }
Rui Ueyama18f084f2016-07-20 19:36:41 +0000490 Load->add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000491 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000492 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000493 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000494}
495
Eugene Leviantf9bc3bd2016-08-16 06:40:58 +0000496template <class ELFT> bool LinkerScript<ELFT>::ignoreInterpSection() {
497 // Ignore .interp section in case we have PHDRS specification
498 // and PT_INTERP isn't listed.
499 return !Opt.PhdrsCommands.empty() &&
500 llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
501 return Cmd.Type == PT_INTERP;
502 }) == Opt.PhdrsCommands.end();
503}
504
Eugene Leviantbbe38602016-07-19 09:25:43 +0000505template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000506ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000507 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
508 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
509 if (Cmd->Name == Name)
510 return Cmd->Filler;
511 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000512}
513
George Rimar206fffa2016-08-17 08:16:57 +0000514template <class ELFT> Expr LinkerScript<ELFT>::getLma(StringRef Name) {
George Rimar8ceadb32016-08-17 07:44:19 +0000515 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
516 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
517 if (Cmd->LmaExpr && Cmd->Name == Name)
518 return Cmd->LmaExpr;
519 return {};
520}
521
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000522// Returns the index of the given section name in linker script
523// SECTIONS commands. Sections are laid out as the same order as they
524// were in the script. If a given name did not appear in the script,
525// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000526template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000527 int I = 0;
528 for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
529 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
530 if (Cmd->Name == Name)
531 return I;
532 ++I;
533 }
534 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000535}
536
537// A compartor to sort output sections. Returns -1 or 1 if
538// A or B are mentioned in linker script. Otherwise, returns 0.
Rui Ueyama07320e42016-04-20 20:13:41 +0000539template <class ELFT>
540int LinkerScript<ELFT>::compareSections(StringRef A, StringRef B) {
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000541 int I = getSectionIndex(A);
542 int J = getSectionIndex(B);
543 if (I == INT_MAX && J == INT_MAX)
Rui Ueyama717677a2016-02-11 21:17:59 +0000544 return 0;
545 return I < J ? -1 : 1;
546}
547
Eugene Leviantbbe38602016-07-19 09:25:43 +0000548template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
549 return !Opt.PhdrsCommands.empty();
550}
551
George Rimar9e694502016-07-29 16:18:47 +0000552template <class ELFT>
George Rimar884e7862016-09-08 08:19:13 +0000553uint64_t LinkerScript<ELFT>::getOutputSectionAddress(StringRef Name) {
George Rimar96659df2016-08-30 09:54:01 +0000554 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
555 if (Sec->getName() == Name)
556 return Sec->getVA();
557 error("undefined section " + Name);
558 return 0;
559}
560
561template <class ELFT>
George Rimar884e7862016-09-08 08:19:13 +0000562uint64_t LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
George Rimar9e694502016-07-29 16:18:47 +0000563 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
564 if (Sec->getName() == Name)
565 return Sec->getSize();
566 error("undefined section " + Name);
567 return 0;
568}
569
Eugene Leviant36fac7f2016-09-08 09:08:30 +0000570template <class ELFT>
571uint64_t LinkerScript<ELFT>::getOutputSectionAlign(StringRef Name) {
572 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
573 if (Sec->getName() == Name)
574 return Sec->getAlignment();
575 error("undefined section " + Name);
576 return 0;
577}
578
George Rimar884e7862016-09-08 08:19:13 +0000579template <class ELFT> uint64_t LinkerScript<ELFT>::getHeaderSize() {
George Rimare32a3592016-08-10 07:59:34 +0000580 return Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
581}
582
George Rimar884e7862016-09-08 08:19:13 +0000583template <class ELFT> uint64_t LinkerScript<ELFT>::getSymbolValue(StringRef S) {
584 if (SymbolBody *B = Symtab<ELFT>::X->find(S))
585 return B->getVA<ELFT>();
586 error("symbol not found: " + S);
587 return 0;
588}
589
Eugene Leviantbbe38602016-07-19 09:25:43 +0000590// Returns indices of ELF headers containing specific section, identified
591// by Name. Each index is a zero based number of ELF header listed within
592// PHDRS {} script block.
593template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000594std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000595 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
596 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000597 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000598 continue;
599
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000600 std::vector<size_t> Ret;
601 for (StringRef PhdrName : Cmd->Phdrs)
602 Ret.push_back(getPhdrIndex(PhdrName));
603 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000604 }
George Rimar31d842f2016-07-20 16:43:03 +0000605 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000606}
607
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000608template <class ELFT>
609size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
610 size_t I = 0;
611 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
612 if (Cmd.Name == PhdrName)
613 return I;
614 ++I;
615 }
616 error("section header '" + PhdrName + "' is not listed in PHDRS");
617 return 0;
618}
619
Rui Ueyama07320e42016-04-20 20:13:41 +0000620class elf::ScriptParser : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000621 typedef void (ScriptParser::*Handler)();
622
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000623public:
Rui Ueyama07320e42016-04-20 20:13:41 +0000624 ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
George Rimarf23b2322016-02-19 10:45:45 +0000625
George Rimar20b65982016-08-31 09:08:26 +0000626 void readLinkerScript();
627 void readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000628
629private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000630 void addFile(StringRef Path);
631
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000632 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000633 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000634 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000635 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000636 void readInclude();
Rui Ueyamaee592822015-10-07 00:25:09 +0000637 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000638 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000639 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000640 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000641 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000642 void readSections();
Rui Ueyama95769b42016-08-31 20:03:54 +0000643 void readVersion();
644 void readVersionScriptCommand();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000645
Rui Ueyama113cdec2016-07-24 23:05:57 +0000646 SymbolAssignment *readAssignment(StringRef Name);
George Rimarff1f29e2016-09-06 13:51:57 +0000647 std::vector<uint8_t> readFill();
Rui Ueyama10416562016-08-04 02:03:27 +0000648 OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
George Rimarff1f29e2016-09-06 13:51:57 +0000649 std::vector<uint8_t> readOutputSectionFiller(StringRef Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000650 std::vector<StringRef> readOutputSectionPhdrs();
George Rimara2496cb2016-08-30 09:46:59 +0000651 InputSectionDescription *readInputSectionDescription(StringRef Tok);
George Rimarc91930a2016-09-02 21:17:20 +0000652 Regex readFilePatterns();
George Rimara2496cb2016-08-30 09:46:59 +0000653 InputSectionDescription *readInputSectionRules(StringRef FilePattern);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000654 unsigned readPhdrType();
Rui Ueyama742c3832016-08-04 22:27:00 +0000655 SortKind readSortKind();
Petr Hoseka35e39c2016-08-16 01:11:16 +0000656 SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
Eugene Leviantdb741e72016-09-07 07:08:43 +0000657 SymbolAssignment *readProvideOrAssignment(StringRef Tok, bool MakeAbsolute);
George Rimar03fc0102016-07-28 07:18:23 +0000658 void readSort();
George Rimareefa7582016-08-04 09:29:31 +0000659 Expr readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +0000660
661 Expr readExpr();
662 Expr readExpr1(Expr Lhs, int MinPrec);
663 Expr readPrimary();
664 Expr readTernary(Expr Cond);
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +0000665 Expr readParenExpr();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000666
George Rimar20b65982016-08-31 09:08:26 +0000667 // For parsing version script.
668 void readExtern(std::vector<SymbolVersion> *Globals);
Rui Ueyama95769b42016-08-31 20:03:54 +0000669 void readVersionDeclaration(StringRef VerStr);
George Rimar20b65982016-08-31 09:08:26 +0000670 void readGlobal(StringRef VerStr);
671 void readLocal();
672
Rui Ueyama07320e42016-04-20 20:13:41 +0000673 ScriptConfiguration &Opt = *ScriptConfig;
674 StringSaver Saver = {ScriptConfig->Alloc};
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000675 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000676};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000677
George Rimar20b65982016-08-31 09:08:26 +0000678void ScriptParser::readVersionScript() {
Rui Ueyama95769b42016-08-31 20:03:54 +0000679 readVersionScriptCommand();
680 if (!atEOF())
681 setError("EOF expected, but got " + next());
682}
683
684void ScriptParser::readVersionScriptCommand() {
George Rimar20b65982016-08-31 09:08:26 +0000685 if (skip("{")) {
Rui Ueyama95769b42016-08-31 20:03:54 +0000686 readVersionDeclaration("");
George Rimar20b65982016-08-31 09:08:26 +0000687 return;
688 }
689
Rui Ueyama95769b42016-08-31 20:03:54 +0000690 while (!atEOF() && !Error && peek() != "}") {
George Rimar20b65982016-08-31 09:08:26 +0000691 StringRef VerStr = next();
692 if (VerStr == "{") {
Rui Ueyama95769b42016-08-31 20:03:54 +0000693 setError("anonymous version definition is used in "
694 "combination with other version definitions");
George Rimar20b65982016-08-31 09:08:26 +0000695 return;
696 }
697 expect("{");
Rui Ueyama95769b42016-08-31 20:03:54 +0000698 readVersionDeclaration(VerStr);
George Rimar20b65982016-08-31 09:08:26 +0000699 }
700}
701
Rui Ueyama95769b42016-08-31 20:03:54 +0000702void ScriptParser::readVersion() {
703 expect("{");
704 readVersionScriptCommand();
705 expect("}");
706}
707
George Rimar20b65982016-08-31 09:08:26 +0000708void ScriptParser::readLinkerScript() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000709 while (!atEOF()) {
710 StringRef Tok = next();
Rui Ueyamaa27eecc2016-09-02 18:52:41 +0000711 if (Tok == ";")
712 continue;
713
714 if (Tok == "ENTRY") {
715 readEntry();
716 } else if (Tok == "EXTERN") {
717 readExtern();
718 } else if (Tok == "GROUP" || Tok == "INPUT") {
719 readGroup();
720 } else if (Tok == "INCLUDE") {
721 readInclude();
722 } else if (Tok == "OUTPUT") {
723 readOutput();
724 } else if (Tok == "OUTPUT_ARCH") {
725 readOutputArch();
726 } else if (Tok == "OUTPUT_FORMAT") {
727 readOutputFormat();
728 } else if (Tok == "PHDRS") {
729 readPhdrs();
730 } else if (Tok == "SEARCH_DIR") {
731 readSearchDir();
732 } else if (Tok == "SECTIONS") {
733 readSections();
734 } else if (Tok == "VERSION") {
735 readVersion();
Eugene Leviantdb741e72016-09-07 07:08:43 +0000736 } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok, true)) {
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000737 if (Opt.HasContents)
738 Opt.Commands.emplace_back(Cmd);
739 else
740 Opt.Assignments.emplace_back(Cmd);
741 } else {
George Rimar57610422016-03-11 14:43:02 +0000742 setError("unknown directive: " + Tok);
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000743 }
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000744 }
745}
746
Rui Ueyama717677a2016-02-11 21:17:59 +0000747void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000748 if (IsUnderSysroot && S.startswith("/")) {
749 SmallString<128> Path;
750 (Config->Sysroot + S).toStringRef(Path);
751 if (sys::fs::exists(Path)) {
752 Driver->addFile(Saver.save(Path.str()));
753 return;
754 }
755 }
756
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +0000757 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +0000758 Driver->addFile(S);
759 } else if (S.startswith("=")) {
760 if (Config->Sysroot.empty())
761 Driver->addFile(S.substr(1));
762 else
763 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
764 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +0000765 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +0000766 } else if (sys::fs::exists(S)) {
767 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +0000768 } else {
769 std::string Path = findFromSearchPaths(S);
770 if (Path.empty())
George Rimar777f9632016-03-12 08:31:34 +0000771 setError("unable to find " + S);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000772 else
773 Driver->addFile(Saver.save(Path));
Rui Ueyama52a15092015-10-11 03:28:42 +0000774 }
775}
776
Rui Ueyama717677a2016-02-11 21:17:59 +0000777void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000778 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +0000779 bool Orig = Config->AsNeeded;
780 Config->AsNeeded = true;
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000781 while (!Error && !skip(")"))
George Rimarcd574a52016-09-09 14:35:36 +0000782 addFile(unquote(next()));
Rui Ueyama35da9b62015-10-11 20:59:12 +0000783 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000784}
785
Rui Ueyama717677a2016-02-11 21:17:59 +0000786void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +0000787 // -e <symbol> takes predecence over ENTRY(<symbol>).
788 expect("(");
789 StringRef Tok = next();
790 if (Config->Entry.empty())
791 Config->Entry = Tok;
792 expect(")");
793}
794
Rui Ueyama717677a2016-02-11 21:17:59 +0000795void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +0000796 expect("(");
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000797 while (!Error && !skip(")"))
798 Config->Undefined.push_back(next());
George Rimar83f406c2015-10-19 17:35:12 +0000799}
800
Rui Ueyama717677a2016-02-11 21:17:59 +0000801void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000802 expect("(");
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000803 while (!Error && !skip(")")) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000804 StringRef Tok = next();
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000805 if (Tok == "AS_NEEDED")
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000806 readAsNeeded();
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000807 else
George Rimarcd574a52016-09-09 14:35:36 +0000808 addFile(unquote(Tok));
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000809 }
810}
811
Rui Ueyama717677a2016-02-11 21:17:59 +0000812void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000813 StringRef Tok = next();
George Rimarcd574a52016-09-09 14:35:36 +0000814 auto MBOrErr = MemoryBuffer::getFile(unquote(Tok));
Rui Ueyama025d59b2016-02-02 20:27:59 +0000815 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +0000816 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000817 return;
818 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000819 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Rui Ueyamaa47ee682015-10-11 01:53:04 +0000820 StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
821 std::vector<StringRef> V = tokenize(S);
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000822 Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000823}
824
Rui Ueyama717677a2016-02-11 21:17:59 +0000825void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +0000826 // -o <file> takes predecence over OUTPUT(<file>).
827 expect("(");
828 StringRef Tok = next();
829 if (Config->OutputFile.empty())
George Rimarcd574a52016-09-09 14:35:36 +0000830 Config->OutputFile = unquote(Tok);
Rui Ueyamaee592822015-10-07 00:25:09 +0000831 expect(")");
832}
833
Rui Ueyama717677a2016-02-11 21:17:59 +0000834void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +0000835 // Error checking only for now.
836 expect("(");
837 next();
838 expect(")");
839}
840
Rui Ueyama717677a2016-02-11 21:17:59 +0000841void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000842 // Error checking only for now.
843 expect("(");
844 next();
Davide Italiano6836c612015-10-12 21:08:41 +0000845 StringRef Tok = next();
846 if (Tok == ")")
George Rimar6c55f0e2016-09-08 08:20:30 +0000847 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000848 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +0000849 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000850 return;
851 }
Davide Italiano6836c612015-10-12 21:08:41 +0000852 next();
853 expect(",");
854 next();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000855 expect(")");
856}
857
Eugene Leviantbbe38602016-07-19 09:25:43 +0000858void ScriptParser::readPhdrs() {
859 expect("{");
860 while (!Error && !skip("}")) {
861 StringRef Tok = next();
Eugene Leviant56b21c82016-09-09 09:46:16 +0000862 Opt.PhdrsCommands.push_back(
863 {Tok, PT_NULL, false, false, UINT_MAX, nullptr});
Eugene Leviantbbe38602016-07-19 09:25:43 +0000864 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
865
866 PhdrCmd.Type = readPhdrType();
867 do {
868 Tok = next();
869 if (Tok == ";")
870 break;
871 if (Tok == "FILEHDR")
872 PhdrCmd.HasFilehdr = true;
873 else if (Tok == "PHDRS")
874 PhdrCmd.HasPhdrs = true;
Eugene Leviant56b21c82016-09-09 09:46:16 +0000875 else if (Tok == "AT")
876 PhdrCmd.LMAExpr = readParenExpr();
Eugene Leviant865bf862016-07-21 10:43:25 +0000877 else if (Tok == "FLAGS") {
878 expect("(");
Rafael Espindolaeb685cd2016-08-02 22:14:57 +0000879 // Passing 0 for the value of dot is a bit of a hack. It means that
880 // we accept expressions like ".|1".
881 PhdrCmd.Flags = readExpr()(0);
Eugene Leviant865bf862016-07-21 10:43:25 +0000882 expect(")");
883 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +0000884 setError("unexpected header attribute: " + Tok);
885 } while (!Error);
886 }
887}
888
Rui Ueyama717677a2016-02-11 21:17:59 +0000889void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +0000890 expect("(");
Rui Ueyama86c5fb82016-09-08 23:26:54 +0000891 StringRef Tok = next();
Rui Ueyama6c7ad132016-09-02 19:20:33 +0000892 if (!Config->Nostdlib)
George Rimarcd574a52016-09-09 14:35:36 +0000893 Config->SearchPaths.push_back(unquote(Tok));
Davide Italiano68a39a62015-10-08 17:51:41 +0000894 expect(")");
895}
896
Rui Ueyama717677a2016-02-11 21:17:59 +0000897void ScriptParser::readSections() {
Rui Ueyama3de0a332016-07-29 03:31:09 +0000898 Opt.HasContents = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000899 expect("{");
George Rimar652852c2016-04-16 10:10:32 +0000900 while (!Error && !skip("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +0000901 StringRef Tok = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +0000902 BaseCommand *Cmd = readProvideOrAssignment(Tok, true);
Eugene Leviantceabe802016-08-11 07:56:43 +0000903 if (!Cmd) {
904 if (Tok == "ASSERT")
905 Cmd = new AssertCommand(readAssert());
906 else
907 Cmd = readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +0000908 }
Rui Ueyama10416562016-08-04 02:03:27 +0000909 Opt.Commands.emplace_back(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000910 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000911}
912
Rui Ueyama708019c2016-07-24 18:19:40 +0000913static int precedence(StringRef Op) {
914 return StringSwitch<int>(Op)
915 .Case("*", 4)
916 .Case("/", 4)
917 .Case("+", 3)
918 .Case("-", 3)
919 .Case("<", 2)
920 .Case(">", 2)
921 .Case(">=", 2)
922 .Case("<=", 2)
923 .Case("==", 2)
924 .Case("!=", 2)
925 .Case("&", 1)
Rafael Espindolacc3dd622016-08-22 21:33:35 +0000926 .Case("|", 1)
Rui Ueyama708019c2016-07-24 18:19:40 +0000927 .Default(-1);
928}
929
George Rimarc91930a2016-09-02 21:17:20 +0000930Regex ScriptParser::readFilePatterns() {
Rui Ueyama10416562016-08-04 02:03:27 +0000931 std::vector<StringRef> V;
932 while (!Error && !skip(")"))
933 V.push_back(next());
George Rimarc91930a2016-09-02 21:17:20 +0000934 return compileGlobPatterns(V);
George Rimar0702c4e2016-07-29 15:32:46 +0000935}
936
Rui Ueyama742c3832016-08-04 22:27:00 +0000937SortKind ScriptParser::readSortKind() {
938 if (skip("SORT") || skip("SORT_BY_NAME"))
939 return SortByName;
940 if (skip("SORT_BY_ALIGNMENT"))
941 return SortByAlignment;
942 return SortNone;
943}
944
George Rimara2496cb2016-08-30 09:46:59 +0000945InputSectionDescription *
946ScriptParser::readInputSectionRules(StringRef FilePattern) {
George Rimarc91930a2016-09-02 21:17:20 +0000947 auto *Cmd = new InputSectionDescription(FilePattern);
Davide Italiano0ed42b02016-07-25 21:47:13 +0000948 expect("(");
Davide Italianoe7282792016-07-27 01:44:01 +0000949
Rui Ueyama742c3832016-08-04 22:27:00 +0000950 // Read EXCLUDE_FILE().
Davide Italianoe7282792016-07-27 01:44:01 +0000951 if (skip("EXCLUDE_FILE")) {
952 expect("(");
George Rimarc91930a2016-09-02 21:17:20 +0000953 Cmd->ExcludedFileRe = readFilePatterns();
Davide Italiano0ed42b02016-07-25 21:47:13 +0000954 }
George Rimar06598002016-07-28 21:51:30 +0000955
Rui Ueyama742c3832016-08-04 22:27:00 +0000956 // Read SORT().
957 if (SortKind K1 = readSortKind()) {
958 Cmd->SortOuter = K1;
George Rimar0702c4e2016-07-29 15:32:46 +0000959 expect("(");
Rui Ueyama742c3832016-08-04 22:27:00 +0000960 if (SortKind K2 = readSortKind()) {
961 Cmd->SortInner = K2;
George Rimar350ece42016-08-03 08:35:59 +0000962 expect("(");
George Rimarc91930a2016-09-02 21:17:20 +0000963 Cmd->SectionRe = readFilePatterns();
George Rimar350ece42016-08-03 08:35:59 +0000964 expect(")");
965 } else {
George Rimarc91930a2016-09-02 21:17:20 +0000966 Cmd->SectionRe = readFilePatterns();
George Rimar350ece42016-08-03 08:35:59 +0000967 }
George Rimar0702c4e2016-07-29 15:32:46 +0000968 expect(")");
Rui Ueyama10416562016-08-04 02:03:27 +0000969 return Cmd;
George Rimar06598002016-07-28 21:51:30 +0000970 }
George Rimar0702c4e2016-07-29 15:32:46 +0000971
George Rimarc91930a2016-09-02 21:17:20 +0000972 Cmd->SectionRe = readFilePatterns();
Rui Ueyama10416562016-08-04 02:03:27 +0000973 return Cmd;
Davide Italianoe7282792016-07-27 01:44:01 +0000974}
975
George Rimara2496cb2016-08-30 09:46:59 +0000976InputSectionDescription *
977ScriptParser::readInputSectionDescription(StringRef Tok) {
George Rimar06598002016-07-28 21:51:30 +0000978 // Input section wildcard can be surrounded by KEEP.
979 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
George Rimara2496cb2016-08-30 09:46:59 +0000980 if (Tok == "KEEP") {
George Rimar06598002016-07-28 21:51:30 +0000981 expect("(");
George Rimara2496cb2016-08-30 09:46:59 +0000982 StringRef FilePattern = next();
983 InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
George Rimar06598002016-07-28 21:51:30 +0000984 expect(")");
George Rimarc91930a2016-09-02 21:17:20 +0000985 Opt.KeptSections.push_back(&Cmd->SectionRe);
Rui Ueyama10416562016-08-04 02:03:27 +0000986 return Cmd;
George Rimar06598002016-07-28 21:51:30 +0000987 }
George Rimara2496cb2016-08-30 09:46:59 +0000988 return readInputSectionRules(Tok);
Davide Italiano0ed42b02016-07-25 21:47:13 +0000989}
990
George Rimar03fc0102016-07-28 07:18:23 +0000991void ScriptParser::readSort() {
992 expect("(");
993 expect("CONSTRUCTORS");
994 expect(")");
995}
996
George Rimareefa7582016-08-04 09:29:31 +0000997Expr ScriptParser::readAssert() {
998 expect("(");
999 Expr E = readExpr();
1000 expect(",");
George Rimarcd574a52016-09-09 14:35:36 +00001001 StringRef Msg = unquote(next());
George Rimareefa7582016-08-04 09:29:31 +00001002 expect(")");
1003 return [=](uint64_t Dot) {
1004 uint64_t V = E(Dot);
1005 if (!V)
1006 error(Msg);
1007 return V;
1008 };
1009}
1010
Rui Ueyama25150e82016-09-06 17:46:43 +00001011// Reads a FILL(expr) command. We handle the FILL command as an
1012// alias for =fillexp section attribute, which is different from
1013// what GNU linkers do.
1014// https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
George Rimarff1f29e2016-09-06 13:51:57 +00001015std::vector<uint8_t> ScriptParser::readFill() {
1016 expect("(");
1017 std::vector<uint8_t> V = readOutputSectionFiller(next());
1018 expect(")");
1019 expect(";");
1020 return V;
1021}
1022
Rui Ueyama10416562016-08-04 02:03:27 +00001023OutputSectionCommand *
1024ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +00001025 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
George Rimar58e5c4d2016-07-25 08:29:46 +00001026
1027 // Read an address expression.
1028 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
1029 if (peek() != ":")
1030 Cmd->AddrExpr = readExpr();
1031
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001032 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +00001033
George Rimar8ceadb32016-08-17 07:44:19 +00001034 if (skip("AT"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001035 Cmd->LmaExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001036 if (skip("ALIGN"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001037 Cmd->AlignExpr = readParenExpr();
George Rimardb24d9c2016-08-19 15:18:23 +00001038 if (skip("SUBALIGN"))
1039 Cmd->SubalignExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001040
Davide Italiano246f6812016-07-22 03:36:24 +00001041 // Parse constraints.
1042 if (skip("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001043 Cmd->Constraint = ConstraintKind::ReadOnly;
Davide Italiano246f6812016-07-22 03:36:24 +00001044 if (skip("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001045 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001046 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001047
Rui Ueyama025d59b2016-02-02 20:27:59 +00001048 while (!Error && !skip("}")) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001049 StringRef Tok = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +00001050 if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok, false))
Eugene Leviantceabe802016-08-11 07:56:43 +00001051 Cmd->Commands.emplace_back(Assignment);
George Rimarff1f29e2016-09-06 13:51:57 +00001052 else if (Tok == "FILL")
1053 Cmd->Filler = readFill();
Eugene Leviantceabe802016-08-11 07:56:43 +00001054 else if (Tok == "SORT")
George Rimar03fc0102016-07-28 07:18:23 +00001055 readSort();
George Rimara2496cb2016-08-30 09:46:59 +00001056 else if (peek() == "(")
1057 Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
Eugene Leviantceabe802016-08-11 07:56:43 +00001058 else
1059 setError("unknown command " + Tok);
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001060 }
George Rimar076fe152016-07-21 06:43:01 +00001061 Cmd->Phdrs = readOutputSectionPhdrs();
George Rimarff1f29e2016-09-06 13:51:57 +00001062 if (peek().startswith("="))
1063 Cmd->Filler = readOutputSectionFiller(next().drop_front());
Rui Ueyama10416562016-08-04 02:03:27 +00001064 return Cmd;
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001065}
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001066
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001067// Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
1068// https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
1069//
1070// ld.gold is not fully compatible with ld.bfd. ld.bfd handles
1071// hexstrings as blobs of arbitrary sizes, while ld.gold handles them
1072// as 32-bit big-endian values. We will do the same as ld.gold does
1073// because it's simpler than what ld.bfd does.
George Rimarff1f29e2016-09-06 13:51:57 +00001074std::vector<uint8_t> ScriptParser::readOutputSectionFiller(StringRef Tok) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001075 uint32_t V;
George Rimarff1f29e2016-09-06 13:51:57 +00001076 if (Tok.getAsInteger(0, V)) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001077 setError("invalid filler expression: " + Tok);
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001078 return {};
George Rimare2ee72b2016-02-26 14:48:31 +00001079 }
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001080 return {uint8_t(V >> 24), uint8_t(V >> 16), uint8_t(V >> 8), uint8_t(V)};
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001081}
1082
Petr Hoseka35e39c2016-08-16 01:11:16 +00001083SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
Eugene Levianta31c91b2016-07-22 07:38:40 +00001084 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +00001085 SymbolAssignment *Cmd = readAssignment(next());
Petr Hoseka35e39c2016-08-16 01:11:16 +00001086 Cmd->Provide = Provide;
Rui Ueyama174e0a12016-07-29 00:29:25 +00001087 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001088 expect(")");
1089 expect(";");
Rui Ueyama10416562016-08-04 02:03:27 +00001090 return Cmd;
Eugene Levianteda81a12016-07-12 06:39:48 +00001091}
1092
Eugene Leviantdb741e72016-09-07 07:08:43 +00001093SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok,
1094 bool MakeAbsolute) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001095 SymbolAssignment *Cmd = nullptr;
1096 if (peek() == "=" || peek() == "+=") {
1097 Cmd = readAssignment(Tok);
1098 expect(";");
1099 } else if (Tok == "PROVIDE") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001100 Cmd = readProvideHidden(true, false);
1101 } else if (Tok == "HIDDEN") {
1102 Cmd = readProvideHidden(false, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001103 } else if (Tok == "PROVIDE_HIDDEN") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001104 Cmd = readProvideHidden(true, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001105 }
Eugene Leviantdb741e72016-09-07 07:08:43 +00001106 if (Cmd && MakeAbsolute)
1107 Cmd->IsAbsolute = true;
Eugene Leviantceabe802016-08-11 07:56:43 +00001108 return Cmd;
1109}
1110
George Rimar30835ea2016-07-28 21:08:56 +00001111static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
1112 if (S == ".")
1113 return Dot;
George Rimar884e7862016-09-08 08:19:13 +00001114 return ScriptBase->getSymbolValue(S);
George Rimare32a3592016-08-10 07:59:34 +00001115}
1116
George Rimar30835ea2016-07-28 21:08:56 +00001117SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1118 StringRef Op = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +00001119 bool IsAbsolute = false;
1120 Expr E;
George Rimar30835ea2016-07-28 21:08:56 +00001121 assert(Op == "=" || Op == "+=");
Eugene Leviantdb741e72016-09-07 07:08:43 +00001122 if (skip("ABSOLUTE")) {
1123 E = readParenExpr();
1124 IsAbsolute = true;
1125 } else {
1126 E = readExpr();
1127 }
George Rimar30835ea2016-07-28 21:08:56 +00001128 if (Op == "+=")
1129 E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
Eugene Leviantdb741e72016-09-07 07:08:43 +00001130 return new SymbolAssignment(Name, E, IsAbsolute);
George Rimar30835ea2016-07-28 21:08:56 +00001131}
1132
1133// This is an operator-precedence parser to parse a linker
1134// script expression.
1135Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
1136
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001137static Expr combine(StringRef Op, Expr L, Expr R) {
1138 if (Op == "*")
1139 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1140 if (Op == "/") {
1141 return [=](uint64_t Dot) -> uint64_t {
1142 uint64_t RHS = R(Dot);
1143 if (RHS == 0) {
1144 error("division by zero");
1145 return 0;
1146 }
1147 return L(Dot) / RHS;
1148 };
1149 }
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); };
1162 if (Op == "==")
1163 return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
1164 if (Op == "!=")
1165 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
1166 if (Op == "&")
1167 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
Rafael Espindolacc3dd622016-08-22 21:33:35 +00001168 if (Op == "|")
1169 return [=](uint64_t Dot) { return L(Dot) | R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001170 llvm_unreachable("invalid operator");
1171}
1172
Rui Ueyama708019c2016-07-24 18:19:40 +00001173// This is a part of the operator-precedence parser. This function
1174// assumes that the remaining token stream starts with an operator.
1175Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1176 while (!atEOF() && !Error) {
1177 // Read an operator and an expression.
1178 StringRef Op1 = peek();
1179 if (Op1 == "?")
1180 return readTernary(Lhs);
1181 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +00001182 break;
Rui Ueyama708019c2016-07-24 18:19:40 +00001183 next();
1184 Expr Rhs = readPrimary();
1185
1186 // Evaluate the remaining part of the expression first if the
1187 // next operator has greater precedence than the previous one.
1188 // For example, if we have read "+" and "3", and if the next
1189 // operator is "*", then we'll evaluate 3 * ... part first.
1190 while (!atEOF()) {
1191 StringRef Op2 = peek();
1192 if (precedence(Op2) <= precedence(Op1))
1193 break;
1194 Rhs = readExpr1(Rhs, precedence(Op2));
1195 }
1196
1197 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +00001198 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001199 return Lhs;
1200}
1201
1202uint64_t static getConstant(StringRef S) {
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001203 if (S == "COMMONPAGESIZE")
Rui Ueyama708019c2016-07-24 18:19:40 +00001204 return Target->PageSize;
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001205 if (S == "MAXPAGESIZE")
1206 return Target->MaxPageSize;
Rui Ueyama708019c2016-07-24 18:19:40 +00001207 error("unknown constant: " + S);
1208 return 0;
1209}
1210
Rui Ueyama626e0b02016-09-02 18:19:00 +00001211// Parses Tok as an integer. Returns true if successful.
1212// It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1213// and decimal numbers. Decimal numbers may have "K" (kilo) or
1214// "M" (mega) prefixes.
George Rimar9f2f7ad2016-09-02 16:01:42 +00001215static bool readInteger(StringRef Tok, uint64_t &Result) {
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001216 if (Tok.startswith("-")) {
1217 if (!readInteger(Tok.substr(1), Result))
1218 return false;
1219 Result = -Result;
1220 return true;
1221 }
George Rimar9f2f7ad2016-09-02 16:01:42 +00001222 if (Tok.startswith_lower("0x"))
1223 return !Tok.substr(2).getAsInteger(16, Result);
1224 if (Tok.endswith_lower("H"))
1225 return !Tok.drop_back().getAsInteger(16, Result);
1226
1227 int Suffix = 1;
1228 if (Tok.endswith_lower("K")) {
1229 Suffix = 1024;
1230 Tok = Tok.drop_back();
1231 } else if (Tok.endswith_lower("M")) {
1232 Suffix = 1024 * 1024;
1233 Tok = Tok.drop_back();
1234 }
1235 if (Tok.getAsInteger(10, Result))
1236 return false;
1237 Result *= Suffix;
1238 return true;
1239}
1240
Rui Ueyama708019c2016-07-24 18:19:40 +00001241Expr ScriptParser::readPrimary() {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001242 if (peek() == "(")
1243 return readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001244
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001245 StringRef Tok = next();
Rui Ueyama708019c2016-07-24 18:19:40 +00001246
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001247 if (Tok == "~") {
1248 Expr E = readPrimary();
1249 return [=](uint64_t Dot) { return ~E(Dot); };
1250 }
1251 if (Tok == "-") {
1252 Expr E = readPrimary();
1253 return [=](uint64_t Dot) { return -E(Dot); };
1254 }
1255
Rui Ueyama708019c2016-07-24 18:19:40 +00001256 // Built-in functions are parsed here.
1257 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
George Rimar96659df2016-08-30 09:54:01 +00001258 if (Tok == "ADDR") {
1259 expect("(");
1260 StringRef Name = next();
1261 expect(")");
George Rimar884e7862016-09-08 08:19:13 +00001262 return
1263 [=](uint64_t Dot) { return ScriptBase->getOutputSectionAddress(Name); };
George Rimar96659df2016-08-30 09:54:01 +00001264 }
George Rimareefa7582016-08-04 09:29:31 +00001265 if (Tok == "ASSERT")
1266 return readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001267 if (Tok == "ALIGN") {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001268 Expr E = readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001269 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1270 }
1271 if (Tok == "CONSTANT") {
1272 expect("(");
1273 StringRef Tok = next();
1274 expect(")");
1275 return [=](uint64_t Dot) { return getConstant(Tok); };
1276 }
Rafael Espindola54c145c2016-07-28 18:16:24 +00001277 if (Tok == "SEGMENT_START") {
1278 expect("(");
1279 next();
1280 expect(",");
1281 uint64_t Val;
1282 next().getAsInteger(0, Val);
1283 expect(")");
1284 return [=](uint64_t Dot) { return Val; };
1285 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001286 if (Tok == "DATA_SEGMENT_ALIGN") {
1287 expect("(");
1288 Expr E = readExpr();
1289 expect(",");
1290 readExpr();
1291 expect(")");
Rui Ueyamaf7791bb2016-07-26 19:34:10 +00001292 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001293 }
1294 if (Tok == "DATA_SEGMENT_END") {
1295 expect("(");
1296 expect(".");
1297 expect(")");
1298 return [](uint64_t Dot) { return Dot; };
1299 }
George Rimar276b4e62016-07-26 17:58:44 +00001300 // GNU linkers implements more complicated logic to handle
1301 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1302 // the next page boundary for simplicity.
1303 if (Tok == "DATA_SEGMENT_RELRO_END") {
1304 expect("(");
1305 next();
1306 expect(",");
1307 readExpr();
1308 expect(")");
1309 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1310 }
George Rimar9e694502016-07-29 16:18:47 +00001311 if (Tok == "SIZEOF") {
1312 expect("(");
1313 StringRef Name = next();
1314 expect(")");
George Rimar884e7862016-09-08 08:19:13 +00001315 return [=](uint64_t Dot) { return ScriptBase->getOutputSectionSize(Name); };
George Rimar9e694502016-07-29 16:18:47 +00001316 }
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001317 if (Tok == "ALIGNOF") {
1318 expect("(");
1319 StringRef Name = next();
1320 expect(")");
1321 return
1322 [=](uint64_t Dot) { return ScriptBase->getOutputSectionAlign(Name); };
1323 }
George Rimare32a3592016-08-10 07:59:34 +00001324 if (Tok == "SIZEOF_HEADERS")
George Rimar884e7862016-09-08 08:19:13 +00001325 return [=](uint64_t Dot) { return ScriptBase->getHeaderSize(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001326
George Rimar9f2f7ad2016-09-02 16:01:42 +00001327 // Tok is a literal number.
1328 uint64_t V;
1329 if (readInteger(Tok, V))
1330 return [=](uint64_t Dot) { return V; };
1331
1332 // Tok is a symbol name.
1333 if (Tok != "." && !isValidCIdentifier(Tok))
1334 setError("malformed number: " + Tok);
1335 return [=](uint64_t Dot) { return getSymbolValue(Tok, Dot); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001336}
1337
1338Expr ScriptParser::readTernary(Expr Cond) {
1339 next();
1340 Expr L = readExpr();
1341 expect(":");
1342 Expr R = readExpr();
1343 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1344}
1345
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001346Expr ScriptParser::readParenExpr() {
1347 expect("(");
1348 Expr E = readExpr();
1349 expect(")");
1350 return E;
1351}
1352
Eugene Leviantbbe38602016-07-19 09:25:43 +00001353std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1354 std::vector<StringRef> Phdrs;
1355 while (!Error && peek().startswith(":")) {
1356 StringRef Tok = next();
1357 Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
1358 if (Tok.empty()) {
1359 setError("section header name is empty");
1360 break;
1361 }
Rui Ueyama047404f2016-07-20 19:36:36 +00001362 Phdrs.push_back(Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001363 }
1364 return Phdrs;
1365}
1366
1367unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001368 StringRef Tok = next();
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001369 unsigned Ret = StringSwitch<unsigned>(Tok)
George Rimar6c55f0e2016-09-08 08:20:30 +00001370 .Case("PT_NULL", PT_NULL)
1371 .Case("PT_LOAD", PT_LOAD)
1372 .Case("PT_DYNAMIC", PT_DYNAMIC)
1373 .Case("PT_INTERP", PT_INTERP)
1374 .Case("PT_NOTE", PT_NOTE)
1375 .Case("PT_SHLIB", PT_SHLIB)
1376 .Case("PT_PHDR", PT_PHDR)
1377 .Case("PT_TLS", PT_TLS)
1378 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1379 .Case("PT_GNU_STACK", PT_GNU_STACK)
1380 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1381 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001382
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001383 if (Ret == (unsigned)-1) {
1384 setError("invalid program header type: " + Tok);
1385 return PT_NULL;
1386 }
1387 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001388}
1389
Rui Ueyama95769b42016-08-31 20:03:54 +00001390void ScriptParser::readVersionDeclaration(StringRef VerStr) {
George Rimar20b65982016-08-31 09:08:26 +00001391 // Identifiers start at 2 because 0 and 1 are reserved
1392 // for VER_NDX_LOCAL and VER_NDX_GLOBAL constants.
1393 size_t VersionId = Config->VersionDefinitions.size() + 2;
1394 Config->VersionDefinitions.push_back({VerStr, VersionId});
1395
1396 if (skip("global:") || peek() != "local:")
1397 readGlobal(VerStr);
1398 if (skip("local:"))
1399 readLocal();
1400 expect("}");
1401
1402 // Each version may have a parent version. For example, "Ver2" defined as
1403 // "Ver2 { global: foo; local: *; } Ver1;" has "Ver1" as a parent. This
1404 // version hierarchy is, probably against your instinct, purely for human; the
1405 // runtime doesn't care about them at all. In LLD, we simply skip the token.
1406 if (!VerStr.empty() && peek() != ";")
1407 next();
1408 expect(";");
1409}
1410
1411void ScriptParser::readLocal() {
1412 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1413 expect("*");
1414 expect(";");
1415}
1416
1417void ScriptParser::readExtern(std::vector<SymbolVersion> *Globals) {
George Rimarcd574a52016-09-09 14:35:36 +00001418 expect("\"C++\"");
George Rimar20b65982016-08-31 09:08:26 +00001419 expect("{");
1420
1421 for (;;) {
1422 if (peek() == "}" || Error)
1423 break;
George Rimarcd574a52016-09-09 14:35:36 +00001424 bool HasWildcard = !peek().startswith("\"") && hasWildcard(peek());
1425 Globals->push_back({unquote(next()), true, HasWildcard});
George Rimar20b65982016-08-31 09:08:26 +00001426 expect(";");
1427 }
1428
1429 expect("}");
1430 expect(";");
1431}
1432
1433void ScriptParser::readGlobal(StringRef VerStr) {
1434 std::vector<SymbolVersion> *Globals;
1435 if (VerStr.empty())
1436 Globals = &Config->VersionScriptGlobals;
1437 else
1438 Globals = &Config->VersionDefinitions.back().Globals;
1439
1440 for (;;) {
1441 if (skip("extern"))
1442 readExtern(Globals);
1443
1444 StringRef Cur = peek();
1445 if (Cur == "}" || Cur == "local:" || Error)
1446 return;
1447 next();
George Rimarcd574a52016-09-09 14:35:36 +00001448 Globals->push_back({unquote(Cur), false, hasWildcard(Cur)});
George Rimar20b65982016-08-31 09:08:26 +00001449 expect(";");
1450 }
1451}
1452
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001453static bool isUnderSysroot(StringRef Path) {
1454 if (Config->Sysroot == "")
1455 return false;
1456 for (; !Path.empty(); Path = sys::path::parent_path(Path))
1457 if (sys::fs::equivalent(Config->Sysroot, Path))
1458 return true;
1459 return false;
1460}
1461
Rui Ueyama07320e42016-04-20 20:13:41 +00001462void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001463 StringRef Path = MB.getBufferIdentifier();
George Rimar20b65982016-08-31 09:08:26 +00001464 ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).readLinkerScript();
1465}
1466
1467void elf::readVersionScript(MemoryBufferRef MB) {
1468 ScriptParser(MB.getBuffer(), false).readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001469}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001470
Rui Ueyama07320e42016-04-20 20:13:41 +00001471template class elf::LinkerScript<ELF32LE>;
1472template class elf::LinkerScript<ELF32BE>;
1473template class elf::LinkerScript<ELF64LE>;
1474template class elf::LinkerScript<ELF64BE>;