blob: 9442eed35606725972aaab7293e288bd3dca20eb [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;
Rui Ueyama38dbd3e2016-09-14 00:05:51 +0000119 for (ObjectFile<ELFT> *F : Symtab<ELFT>::X->getObjectFiles())
George Rimar06598002016-07-28 21:51:30 +0000120 if (fileMatches(I, sys::path::filename(F->getName())))
121 for (InputSectionBase<ELFT> *S : F->getSections())
122 if (!isDiscarded(S) && !S->OutSec &&
Rafael Espindola042a3f22016-09-08 14:06:08 +0000123 const_cast<Regex &>(Re).match(S->Name))
Davide Italianoe7282792016-07-27 01:44:01 +0000124 Ret.push_back(S);
Eugene Leviant3e6b0272016-07-28 19:24:13 +0000125
George Rimarc91930a2016-09-02 21:17:20 +0000126 if (const_cast<Regex &>(Re).match("COMMON"))
Rui Ueyamaad10c3d2016-07-28 21:05:04 +0000127 Ret.push_back(CommonInputSection<ELFT>::X);
Rui Ueyama6b274812016-07-25 22:51:07 +0000128 return Ret;
129}
130
Rafael Espindolac0028d32016-09-08 20:47:52 +0000131static bool compareName(InputSectionData *A, InputSectionData *B) {
Rafael Espindola042a3f22016-09-08 14:06:08 +0000132 return A->Name < B->Name;
Rui Ueyama742c3832016-08-04 22:27:00 +0000133}
George Rimar350ece42016-08-03 08:35:59 +0000134
Rafael Espindolac0028d32016-09-08 20:47:52 +0000135static bool compareAlignment(InputSectionData *A, InputSectionData *B) {
Rui Ueyama742c3832016-08-04 22:27:00 +0000136 // ">" is not a mistake. Larger alignments are placed before smaller
137 // alignments in order to reduce the amount of padding necessary.
138 // This is compatible with GNU.
139 return A->Alignment > B->Alignment;
140}
George Rimar350ece42016-08-03 08:35:59 +0000141
Rafael Espindolac0028d32016-09-08 20:47:52 +0000142static std::function<bool(InputSectionData *, InputSectionData *)>
Rui Ueyama742c3832016-08-04 22:27:00 +0000143getComparator(SortKind K) {
144 if (K == SortByName)
Rafael Espindolac0028d32016-09-08 20:47:52 +0000145 return compareName;
146 return compareAlignment;
Rui Ueyama742c3832016-08-04 22:27:00 +0000147}
George Rimar0702c4e2016-07-29 15:32:46 +0000148
149template <class ELFT>
Rafael Espindola7bd37872016-09-12 16:05:16 +0000150void LinkerScript<ELFT>::discard(ArrayRef<InputSectionBase<ELFT> *> V) {
151 for (InputSectionBase<ELFT> *S : V) {
152 S->Live = false;
153 reportDiscarded(S);
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000154 }
155}
156
George Rimar8f66df92016-08-12 20:38:20 +0000157static bool checkConstraint(uint64_t Flags, ConstraintKind Kind) {
158 bool RO = (Kind == ConstraintKind::ReadOnly);
159 bool RW = (Kind == ConstraintKind::ReadWrite);
160 bool Writable = Flags & SHF_WRITE;
Rui Ueyamaadcdb662016-09-06 22:50:48 +0000161 return !(RO && Writable) && !(RW && !Writable);
George Rimar8f66df92016-08-12 20:38:20 +0000162}
163
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000164template <class ELFT>
George Rimar06ae6832016-08-12 09:07:57 +0000165static bool matchConstraints(ArrayRef<InputSectionBase<ELFT> *> Sections,
166 ConstraintKind Kind) {
George Rimar8f66df92016-08-12 20:38:20 +0000167 if (Kind == ConstraintKind::NoConstraint)
168 return true;
169 return llvm::all_of(Sections, [=](InputSectionBase<ELFT> *Sec) {
170 return checkConstraint(Sec->getSectionHdr()->sh_flags, Kind);
George Rimar06ae6832016-08-12 09:07:57 +0000171 });
172}
173
174template <class ELFT>
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000175std::vector<InputSectionBase<ELFT> *>
George Rimar06ae6832016-08-12 09:07:57 +0000176LinkerScript<ELFT>::createInputSectionList(OutputSectionCommand &OutCmd) {
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000177 std::vector<InputSectionBase<ELFT> *> Ret;
Eugene Leviant97403d12016-09-01 09:55:57 +0000178 DenseSet<InputSectionBase<ELFT> *> SectionIndex;
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000179
George Rimar06ae6832016-08-12 09:07:57 +0000180 for (const std::unique_ptr<BaseCommand> &Base : OutCmd.Commands) {
181 if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base.get())) {
182 if (shouldDefine<ELFT>(OutCmd))
Eugene Leviantdb741e72016-09-07 07:08:43 +0000183 addSymbol<ELFT>(OutCmd);
Eugene Leviant97403d12016-09-01 09:55:57 +0000184 OutCmd->GoesAfter = Ret.empty() ? nullptr : Ret.back();
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000185 continue;
186 }
187
188 auto *Cmd = cast<InputSectionDescription>(Base.get());
189 std::vector<InputSectionBase<ELFT> *> V = getInputSections(Cmd);
George Rimar06ae6832016-08-12 09:07:57 +0000190 if (!matchConstraints<ELFT>(V, OutCmd.Constraint))
191 continue;
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000192 if (Cmd->SortInner)
Rafael Espindolac0028d32016-09-08 20:47:52 +0000193 std::stable_sort(V.begin(), V.end(), getComparator(Cmd->SortInner));
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000194 if (Cmd->SortOuter)
Rafael Espindolac0028d32016-09-08 20:47:52 +0000195 std::stable_sort(V.begin(), V.end(), getComparator(Cmd->SortOuter));
Eugene Leviant97403d12016-09-01 09:55:57 +0000196
197 // Add all input sections corresponding to rule 'Cmd' to
198 // resulting vector. We do not add duplicate input sections.
199 for (InputSectionBase<ELFT> *S : V)
200 if (SectionIndex.insert(S).second)
201 Ret.push_back(S);
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000202 }
203 return Ret;
204}
205
George Rimar6c55f0e2016-09-08 08:20:30 +0000206template <class ELFT> void LinkerScript<ELFT>::createAssignments() {
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000207 for (const std::unique_ptr<SymbolAssignment> &Cmd : Opt.Assignments) {
208 if (shouldDefine<ELFT>(Cmd.get()))
209 addRegular<ELFT>(Cmd.get());
210 if (Cmd->Sym)
211 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(0);
212 }
213}
214
215template <class ELFT>
Rafael Espindola10897f12016-09-13 14:23:14 +0000216static SectionKey<ELFT::Is64Bits> createKey(InputSectionBase<ELFT> *C,
217 StringRef OutsecName) {
218 // When using linker script the merge rules are different.
219 // Unfortunately, linker scripts are name based. This means that expressions
220 // like *(.foo*) can refer to multiple input sections that would normally be
221 // placed in different output sections. We cannot put them in different
222 // output sections or we would produce wrong results for
223 // start = .; *(.foo.*) end = .; *(.bar)
224 // and a mapping of .foo1 and .bar1 to one section and .foo2 and .bar2 to
225 // another. The problem is that there is no way to layout those output
226 // sections such that the .foo sections are the only thing between the
227 // start and end symbols.
228
229 // An extra annoyance is that we cannot simply disable merging of the contents
230 // of SHF_MERGE sections, but our implementation requires one output section
231 // per "kind" (string or not, which size/aligment).
232 // Fortunately, creating symbols in the middle of a merge section is not
233 // supported by bfd or gold, so we can just create multiple section in that
234 // case.
235 const typename ELFT::Shdr *H = C->getSectionHdr();
236 typedef typename ELFT::uint uintX_t;
237 uintX_t Flags = H->sh_flags & (SHF_MERGE | SHF_STRINGS);
238
239 uintX_t Alignment = 0;
240 if (isa<MergeInputSection<ELFT>>(C))
241 Alignment = std::max(H->sh_addralign, H->sh_entsize);
242
243 return SectionKey<ELFT::Is64Bits>{OutsecName, /*Type*/ 0, Flags, Alignment};
244}
245
246template <class ELFT>
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000247void LinkerScript<ELFT>::createSections(OutputSectionFactory<ELFT> &Factory) {
Rafael Espindola28c15972016-09-13 13:00:06 +0000248 auto AddSec = [&](InputSectionBase<ELFT> *Sec, StringRef Name) {
249 OutputSectionBase<ELFT> *OutSec;
250 bool IsNew;
Rafael Espindola10897f12016-09-13 14:23:14 +0000251 std::tie(OutSec, IsNew) = Factory.create(createKey(Sec, Name), Sec);
Rafael Espindola28c15972016-09-13 13:00:06 +0000252 if (IsNew)
253 OutputSections->push_back(OutSec);
254 return OutSec;
255 };
256
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000257 for (const std::unique_ptr<BaseCommand> &Base1 : Opt.Commands) {
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000258 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base1.get())) {
259 if (shouldDefine<ELFT>(Cmd))
260 addRegular<ELFT>(Cmd);
261 continue;
262 }
263
Eugene Leviantceabe802016-08-11 07:56:43 +0000264 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000265 std::vector<InputSectionBase<ELFT> *> V = createInputSectionList(*Cmd);
266
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000267 if (Cmd->Name == "/DISCARD/") {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000268 discard(V);
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000269 continue;
270 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000271
Eugene Leviant97403d12016-09-01 09:55:57 +0000272 if (V.empty())
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000273 continue;
274
George Rimardb24d9c2016-08-19 15:18:23 +0000275 for (InputSectionBase<ELFT> *Sec : V) {
Rafael Espindola28c15972016-09-13 13:00:06 +0000276 OutputSectionBase<ELFT> *OutSec = AddSec(Sec, Cmd->Name);
George Rimara14b13d2016-09-07 10:46:07 +0000277 uint32_t Subalign = Cmd->SubalignExpr ? Cmd->SubalignExpr(0) : 0;
278
George Rimardb24d9c2016-08-19 15:18:23 +0000279 if (Subalign)
280 Sec->Alignment = Subalign;
Eugene Leviant97403d12016-09-01 09:55:57 +0000281 OutSec->addSection(Sec);
George Rimardb24d9c2016-08-19 15:18:23 +0000282 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000283 }
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000284 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000285
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000286 // Add orphan sections.
Rui Ueyama38dbd3e2016-09-14 00:05:51 +0000287 for (ObjectFile<ELFT> *F : Symtab<ELFT>::X->getObjectFiles()) {
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000288 for (InputSectionBase<ELFT> *S : F->getSections()) {
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000289 if (isDiscarded(S) || S->OutSec)
290 continue;
Rafael Espindola28c15972016-09-13 13:00:06 +0000291 OutputSectionBase<ELFT> *OutSec = AddSec(S, getOutputSectionName(S));
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000292 OutSec->addSection(S);
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000293 }
294 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000295}
296
Eugene Leviantdb741e72016-09-07 07:08:43 +0000297// Sets value of a section-defined symbol. Two kinds of
298// symbols are processed: synthetic symbols, whose value
299// is an offset from beginning of section and regular
300// symbols whose value is absolute.
301template <class ELFT>
302static void assignSectionSymbol(SymbolAssignment *Cmd,
303 OutputSectionBase<ELFT> *Sec,
304 typename ELFT::uint Off) {
305 if (!Cmd->Sym)
306 return;
307
308 if (auto *Body = dyn_cast<DefinedSynthetic<ELFT>>(Cmd->Sym)) {
309 Body->Section = Sec;
310 Body->Value = Cmd->Expression(Sec->getVA() + Off) - Sec->getVA();
311 return;
312 }
313 auto *Body = cast<DefinedRegular<ELFT>>(Cmd->Sym);
314 Body->Value = Cmd->Expression(Sec->getVA() + Off);
315}
316
Eugene Leviant20889c52016-08-31 08:13:33 +0000317// Linker script may define start and end symbols for special section types,
318// like .got, .eh_frame_hdr, .eh_frame and others. Those sections are not a list
319// of regular input input sections, therefore our way of defining symbols for
320// regular sections will not work. The approach we use for special section types
321// is not perfect - it handles only start and end symbols.
322template <class ELFT>
323void addStartEndSymbols(OutputSectionCommand *Cmd,
324 OutputSectionBase<ELFT> *Sec) {
325 bool Start = true;
326 BaseCommand *PrevCmd = nullptr;
327
328 for (std::unique_ptr<BaseCommand> &Base : Cmd->Commands) {
329 if (auto *AssignCmd = dyn_cast<SymbolAssignment>(Base.get())) {
Eugene Leviantdb741e72016-09-07 07:08:43 +0000330 assignSectionSymbol<ELFT>(AssignCmd, Sec, Start ? 0 : Sec->getSize());
Eugene Leviant20889c52016-08-31 08:13:33 +0000331 } else {
332 if (!Start && isa<SymbolAssignment>(PrevCmd))
333 error("section '" + Sec->getName() +
334 "' supports only start and end symbols");
335 Start = false;
336 }
337 PrevCmd = Base.get();
338 }
339}
340
341template <class ELFT>
342void assignOffsets(OutputSectionCommand *Cmd, OutputSectionBase<ELFT> *Sec) {
Eugene Leviantceabe802016-08-11 07:56:43 +0000343 auto *OutSec = dyn_cast<OutputSection<ELFT>>(Sec);
Rui Ueyama2de509c2016-08-12 00:55:08 +0000344 if (!OutSec) {
345 Sec->assignOffsets();
Eugene Leviant20889c52016-08-31 08:13:33 +0000346 // This section is not regular output section. However linker script may
347 // have defined start/end symbols for it. This case is handled below.
348 addStartEndSymbols(Cmd, Sec);
Eugene Leviantceabe802016-08-11 07:56:43 +0000349 return;
Rui Ueyama2de509c2016-08-12 00:55:08 +0000350 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000351 typedef typename ELFT::uint uintX_t;
352 uintX_t Off = 0;
Eugene Leviant97403d12016-09-01 09:55:57 +0000353 auto ItCmd = Cmd->Commands.begin();
Eugene Leviantceabe802016-08-11 07:56:43 +0000354
Eugene Leviant97403d12016-09-01 09:55:57 +0000355 // Assigns values to all symbols following the given
356 // input section 'D' in output section 'Sec'. When symbols
357 // are in the beginning of output section the value of 'D'
358 // is nullptr.
359 auto AssignSuccessors = [&](InputSectionData *D) {
360 for (; ItCmd != Cmd->Commands.end(); ++ItCmd) {
361 auto *AssignCmd = dyn_cast<SymbolAssignment>(ItCmd->get());
362 if (!AssignCmd)
363 continue;
364 if (D != AssignCmd->GoesAfter)
365 break;
366
Eugene Leviant97403d12016-09-01 09:55:57 +0000367 if (AssignCmd->Name == ".") {
368 // Update to location counter means update to section size.
Eugene Leviantdb741e72016-09-07 07:08:43 +0000369 Off = AssignCmd->Expression(Sec->getVA() + Off) - Sec->getVA();
Eugene Leviant97403d12016-09-01 09:55:57 +0000370 Sec->setSize(Off);
371 continue;
372 }
Eugene Leviantdb741e72016-09-07 07:08:43 +0000373 assignSectionSymbol<ELFT>(AssignCmd, Sec, Off);
Eugene Leviantceabe802016-08-11 07:56:43 +0000374 }
Eugene Leviant97403d12016-09-01 09:55:57 +0000375 };
376
377 AssignSuccessors(nullptr);
378 for (InputSection<ELFT> *I : OutSec->Sections) {
379 Off = alignTo(Off, I->Alignment);
380 I->OutSecOff = Off;
381 Off += I->getSize();
Rui Ueyamaf4a30a52016-08-11 21:30:42 +0000382 // Update section size inside for-loop, so that SIZEOF
Eugene Leviantceabe802016-08-11 07:56:43 +0000383 // works correctly in the case below:
384 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
385 Sec->setSize(Off);
Eugene Leviant97403d12016-09-01 09:55:57 +0000386 // Add symbols following current input section.
387 AssignSuccessors(I);
Eugene Leviantceabe802016-08-11 07:56:43 +0000388 }
389}
390
George Rimar8f66df92016-08-12 20:38:20 +0000391template <class ELFT>
George Rimara14b13d2016-09-07 10:46:07 +0000392static std::vector<OutputSectionBase<ELFT> *>
393findSections(OutputSectionCommand &Cmd,
394 ArrayRef<OutputSectionBase<ELFT> *> Sections) {
395 std::vector<OutputSectionBase<ELFT> *> Ret;
396 for (OutputSectionBase<ELFT> *Sec : Sections)
397 if (Sec->getName() == Cmd.Name &&
398 checkConstraint(Sec->getFlags(), Cmd.Constraint))
399 Ret.push_back(Sec);
400 return Ret;
George Rimar8f66df92016-08-12 20:38:20 +0000401}
402
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000403template <class ELFT> void LinkerScript<ELFT>::assignAddresses() {
George Rimar652852c2016-04-16 10:10:32 +0000404 // Orphan sections are sections present in the input files which
Rui Ueyama7c18c282016-04-18 21:00:40 +0000405 // are not explicitly placed into the output file by the linker script.
406 // We place orphan sections at end of file.
407 // Other linkers places them using some heuristics as described in
George Rimar652852c2016-04-16 10:10:32 +0000408 // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
Rui Ueyamae5cc6682016-08-12 00:36:56 +0000409 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
George Rimar652852c2016-04-16 10:10:32 +0000410 StringRef Name = Sec->getName();
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000411 if (getSectionIndex(Name) == INT_MAX)
George Rimar076fe152016-07-21 06:43:01 +0000412 Opt.Commands.push_back(llvm::make_unique<OutputSectionCommand>(Name));
George Rimar652852c2016-04-16 10:10:32 +0000413 }
George Rimar652852c2016-04-16 10:10:32 +0000414
Rui Ueyama7c18c282016-04-18 21:00:40 +0000415 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rui Ueyama4f7500b2016-08-12 04:00:22 +0000416 Dot = getHeaderSize();
Eugene Leviant467c4d52016-07-01 10:27:36 +0000417 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
George Rimar652852c2016-04-16 10:10:32 +0000418 uintX_t ThreadBssOffset = 0;
George Rimar652852c2016-04-16 10:10:32 +0000419
George Rimar076fe152016-07-21 06:43:01 +0000420 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
421 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
Rui Ueyama8d083e62016-07-29 05:48:39 +0000422 if (Cmd->Name == ".") {
423 Dot = Cmd->Expression(Dot);
424 } else if (Cmd->Sym) {
425 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(Dot);
426 }
George Rimar652852c2016-04-16 10:10:32 +0000427 continue;
428 }
429
George Rimareefa7582016-08-04 09:29:31 +0000430 if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
431 Cmd->Expression(Dot);
432 continue;
433 }
434
George Rimar076fe152016-07-21 06:43:01 +0000435 auto *Cmd = cast<OutputSectionCommand>(Base.get());
George Rimara14b13d2016-09-07 10:46:07 +0000436 for (OutputSectionBase<ELFT> *Sec :
437 findSections<ELFT>(*Cmd, *OutputSections)) {
George Rimar652852c2016-04-16 10:10:32 +0000438
George Rimara14b13d2016-09-07 10:46:07 +0000439 if (Cmd->AddrExpr)
440 Dot = Cmd->AddrExpr(Dot);
George Rimar58e5c4d2016-07-25 08:29:46 +0000441
George Rimara14b13d2016-09-07 10:46:07 +0000442 if ((Sec->getFlags() & SHF_TLS) && Sec->getType() == SHT_NOBITS) {
443 uintX_t TVA = Dot + ThreadBssOffset;
444 TVA = alignTo(TVA, Sec->getAlignment());
445 Sec->setVA(TVA);
446 assignOffsets(Cmd, Sec);
447 ThreadBssOffset = TVA - Dot + Sec->getSize();
448 continue;
449 }
450
451 if (!(Sec->getFlags() & SHF_ALLOC)) {
452 assignOffsets(Cmd, Sec);
453 continue;
454 }
455
456 Dot = alignTo(Dot, Sec->getAlignment());
457 Sec->setVA(Dot);
Eugene Leviant20889c52016-08-31 08:13:33 +0000458 assignOffsets(Cmd, Sec);
George Rimara14b13d2016-09-07 10:46:07 +0000459 MinVA = std::min(MinVA, Dot);
460 Dot += Sec->getSize();
George Rimar652852c2016-04-16 10:10:32 +0000461 }
462 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000463
Rafael Espindola64c32d62016-07-07 14:28:47 +0000464 // ELF and Program headers need to be right before the first section in
George Rimarb91e7112016-07-19 07:42:07 +0000465 // memory. Set their addresses accordingly.
Eugene Leviant467c4d52016-07-01 10:27:36 +0000466 MinVA = alignDown(MinVA - Out<ELFT>::ElfHeader->getSize() -
467 Out<ELFT>::ProgramHeaders->getSize(),
468 Target->PageSize);
469 Out<ELFT>::ElfHeader->setVA(MinVA);
470 Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
George Rimar652852c2016-04-16 10:10:32 +0000471}
472
Rui Ueyama464daad2016-08-22 04:55:20 +0000473// Creates program headers as instructed by PHDRS linker script command.
Rui Ueyama07320e42016-04-20 20:13:41 +0000474template <class ELFT>
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000475std::vector<PhdrEntry<ELFT>> LinkerScript<ELFT>::createPhdrs() {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000476 std::vector<PhdrEntry<ELFT>> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000477
Rui Ueyama464daad2016-08-22 04:55:20 +0000478 // Process PHDRS and FILEHDR keywords because they are not
479 // real output sections and cannot be added in the following loop.
Eugene Leviantbbe38602016-07-19 09:25:43 +0000480 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000481 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
482 PhdrEntry<ELFT> &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000483
484 if (Cmd.HasFilehdr)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000485 Phdr.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000486 if (Cmd.HasPhdrs)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000487 Phdr.add(Out<ELFT>::ProgramHeaders);
Eugene Leviant56b21c82016-09-09 09:46:16 +0000488
489 if (Cmd.LMAExpr) {
490 Phdr.H.p_paddr = Cmd.LMAExpr(0);
491 Phdr.HasLMA = true;
492 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000493 }
494
Rui Ueyama464daad2016-08-22 04:55:20 +0000495 // Add output sections to program headers.
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000496 PhdrEntry<ELFT> *Load = nullptr;
497 uintX_t Flags = PF_R;
Rui Ueyama464daad2016-08-22 04:55:20 +0000498 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
Eugene Leviantbbe38602016-07-19 09:25:43 +0000499 if (!(Sec->getFlags() & SHF_ALLOC))
500 break;
501
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000502 std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName());
Eugene Leviantbbe38602016-07-19 09:25:43 +0000503 if (!PhdrIds.empty()) {
504 // Assign headers specified by linker script
505 for (size_t Id : PhdrIds) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000506 Ret[Id].add(Sec);
Eugene Leviant865bf862016-07-21 10:43:25 +0000507 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
Rafael Espindola0b113672016-07-27 14:10:56 +0000508 Ret[Id].H.p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000509 }
510 } else {
511 // If we have no load segment or flags've changed then we want new load
512 // segment.
Rafael Espindola0b113672016-07-27 14:10:56 +0000513 uintX_t NewFlags = Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000514 if (Load == nullptr || Flags != NewFlags) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000515 Load = &*Ret.emplace(Ret.end(), PT_LOAD, NewFlags);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000516 Flags = NewFlags;
517 }
Rui Ueyama18f084f2016-07-20 19:36:41 +0000518 Load->add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000519 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000520 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000521 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000522}
523
Eugene Leviantf9bc3bd2016-08-16 06:40:58 +0000524template <class ELFT> bool LinkerScript<ELFT>::ignoreInterpSection() {
525 // Ignore .interp section in case we have PHDRS specification
526 // and PT_INTERP isn't listed.
527 return !Opt.PhdrsCommands.empty() &&
528 llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
529 return Cmd.Type == PT_INTERP;
530 }) == Opt.PhdrsCommands.end();
531}
532
Eugene Leviantbbe38602016-07-19 09:25:43 +0000533template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000534ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000535 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
536 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
537 if (Cmd->Name == Name)
538 return Cmd->Filler;
539 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000540}
541
George Rimar206fffa2016-08-17 08:16:57 +0000542template <class ELFT> Expr LinkerScript<ELFT>::getLma(StringRef Name) {
George Rimar8ceadb32016-08-17 07:44:19 +0000543 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
544 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
545 if (Cmd->LmaExpr && Cmd->Name == Name)
546 return Cmd->LmaExpr;
547 return {};
548}
549
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000550// Returns the index of the given section name in linker script
551// SECTIONS commands. Sections are laid out as the same order as they
552// were in the script. If a given name did not appear in the script,
553// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000554template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000555 int I = 0;
556 for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
557 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
558 if (Cmd->Name == Name)
559 return I;
560 ++I;
561 }
562 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000563}
564
565// A compartor to sort output sections. Returns -1 or 1 if
566// A or B are mentioned in linker script. Otherwise, returns 0.
Rui Ueyama07320e42016-04-20 20:13:41 +0000567template <class ELFT>
568int LinkerScript<ELFT>::compareSections(StringRef A, StringRef B) {
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000569 int I = getSectionIndex(A);
570 int J = getSectionIndex(B);
571 if (I == INT_MAX && J == INT_MAX)
Rui Ueyama717677a2016-02-11 21:17:59 +0000572 return 0;
573 return I < J ? -1 : 1;
574}
575
Eugene Leviantbbe38602016-07-19 09:25:43 +0000576template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
577 return !Opt.PhdrsCommands.empty();
578}
579
George Rimar9e694502016-07-29 16:18:47 +0000580template <class ELFT>
George Rimar884e7862016-09-08 08:19:13 +0000581uint64_t LinkerScript<ELFT>::getOutputSectionAddress(StringRef Name) {
George Rimar96659df2016-08-30 09:54:01 +0000582 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
583 if (Sec->getName() == Name)
584 return Sec->getVA();
585 error("undefined section " + Name);
586 return 0;
587}
588
589template <class ELFT>
George Rimar884e7862016-09-08 08:19:13 +0000590uint64_t LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
George Rimar9e694502016-07-29 16:18:47 +0000591 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
592 if (Sec->getName() == Name)
593 return Sec->getSize();
594 error("undefined section " + Name);
595 return 0;
596}
597
Eugene Leviant36fac7f2016-09-08 09:08:30 +0000598template <class ELFT>
599uint64_t LinkerScript<ELFT>::getOutputSectionAlign(StringRef Name) {
600 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
601 if (Sec->getName() == Name)
602 return Sec->getAlignment();
603 error("undefined section " + Name);
604 return 0;
605}
606
George Rimar884e7862016-09-08 08:19:13 +0000607template <class ELFT> uint64_t LinkerScript<ELFT>::getHeaderSize() {
George Rimare32a3592016-08-10 07:59:34 +0000608 return Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
609}
610
George Rimar884e7862016-09-08 08:19:13 +0000611template <class ELFT> uint64_t LinkerScript<ELFT>::getSymbolValue(StringRef S) {
612 if (SymbolBody *B = Symtab<ELFT>::X->find(S))
613 return B->getVA<ELFT>();
614 error("symbol not found: " + S);
615 return 0;
616}
617
Eugene Leviantbbe38602016-07-19 09:25:43 +0000618// Returns indices of ELF headers containing specific section, identified
619// by Name. Each index is a zero based number of ELF header listed within
620// PHDRS {} script block.
621template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000622std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000623 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
624 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000625 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000626 continue;
627
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000628 std::vector<size_t> Ret;
629 for (StringRef PhdrName : Cmd->Phdrs)
630 Ret.push_back(getPhdrIndex(PhdrName));
631 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000632 }
George Rimar31d842f2016-07-20 16:43:03 +0000633 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000634}
635
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000636template <class ELFT>
637size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
638 size_t I = 0;
639 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
640 if (Cmd.Name == PhdrName)
641 return I;
642 ++I;
643 }
644 error("section header '" + PhdrName + "' is not listed in PHDRS");
645 return 0;
646}
647
Rui Ueyama07320e42016-04-20 20:13:41 +0000648class elf::ScriptParser : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000649 typedef void (ScriptParser::*Handler)();
650
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000651public:
Rui Ueyama07320e42016-04-20 20:13:41 +0000652 ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
George Rimarf23b2322016-02-19 10:45:45 +0000653
George Rimar20b65982016-08-31 09:08:26 +0000654 void readLinkerScript();
655 void readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000656
657private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000658 void addFile(StringRef Path);
659
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000660 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000661 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000662 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000663 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000664 void readInclude();
Rui Ueyamaee592822015-10-07 00:25:09 +0000665 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000666 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000667 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000668 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000669 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000670 void readSections();
Rui Ueyama95769b42016-08-31 20:03:54 +0000671 void readVersion();
672 void readVersionScriptCommand();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000673
Rui Ueyama113cdec2016-07-24 23:05:57 +0000674 SymbolAssignment *readAssignment(StringRef Name);
George Rimarff1f29e2016-09-06 13:51:57 +0000675 std::vector<uint8_t> readFill();
Rui Ueyama10416562016-08-04 02:03:27 +0000676 OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
George Rimarff1f29e2016-09-06 13:51:57 +0000677 std::vector<uint8_t> readOutputSectionFiller(StringRef Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000678 std::vector<StringRef> readOutputSectionPhdrs();
George Rimara2496cb2016-08-30 09:46:59 +0000679 InputSectionDescription *readInputSectionDescription(StringRef Tok);
George Rimarc91930a2016-09-02 21:17:20 +0000680 Regex readFilePatterns();
George Rimara2496cb2016-08-30 09:46:59 +0000681 InputSectionDescription *readInputSectionRules(StringRef FilePattern);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000682 unsigned readPhdrType();
Rui Ueyama742c3832016-08-04 22:27:00 +0000683 SortKind readSortKind();
Petr Hoseka35e39c2016-08-16 01:11:16 +0000684 SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
Eugene Leviantdb741e72016-09-07 07:08:43 +0000685 SymbolAssignment *readProvideOrAssignment(StringRef Tok, bool MakeAbsolute);
George Rimar03fc0102016-07-28 07:18:23 +0000686 void readSort();
George Rimareefa7582016-08-04 09:29:31 +0000687 Expr readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +0000688
689 Expr readExpr();
690 Expr readExpr1(Expr Lhs, int MinPrec);
691 Expr readPrimary();
692 Expr readTernary(Expr Cond);
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +0000693 Expr readParenExpr();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000694
George Rimar20b65982016-08-31 09:08:26 +0000695 // For parsing version script.
696 void readExtern(std::vector<SymbolVersion> *Globals);
Rui Ueyama95769b42016-08-31 20:03:54 +0000697 void readVersionDeclaration(StringRef VerStr);
George Rimar20b65982016-08-31 09:08:26 +0000698 void readGlobal(StringRef VerStr);
699 void readLocal();
700
Rui Ueyama07320e42016-04-20 20:13:41 +0000701 ScriptConfiguration &Opt = *ScriptConfig;
702 StringSaver Saver = {ScriptConfig->Alloc};
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000703 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000704};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000705
George Rimar20b65982016-08-31 09:08:26 +0000706void ScriptParser::readVersionScript() {
Rui Ueyama95769b42016-08-31 20:03:54 +0000707 readVersionScriptCommand();
708 if (!atEOF())
709 setError("EOF expected, but got " + next());
710}
711
712void ScriptParser::readVersionScriptCommand() {
George Rimar20b65982016-08-31 09:08:26 +0000713 if (skip("{")) {
Rui Ueyama95769b42016-08-31 20:03:54 +0000714 readVersionDeclaration("");
George Rimar20b65982016-08-31 09:08:26 +0000715 return;
716 }
717
Rui Ueyama95769b42016-08-31 20:03:54 +0000718 while (!atEOF() && !Error && peek() != "}") {
George Rimar20b65982016-08-31 09:08:26 +0000719 StringRef VerStr = next();
720 if (VerStr == "{") {
Rui Ueyama95769b42016-08-31 20:03:54 +0000721 setError("anonymous version definition is used in "
722 "combination with other version definitions");
George Rimar20b65982016-08-31 09:08:26 +0000723 return;
724 }
725 expect("{");
Rui Ueyama95769b42016-08-31 20:03:54 +0000726 readVersionDeclaration(VerStr);
George Rimar20b65982016-08-31 09:08:26 +0000727 }
728}
729
Rui Ueyama95769b42016-08-31 20:03:54 +0000730void ScriptParser::readVersion() {
731 expect("{");
732 readVersionScriptCommand();
733 expect("}");
734}
735
George Rimar20b65982016-08-31 09:08:26 +0000736void ScriptParser::readLinkerScript() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000737 while (!atEOF()) {
738 StringRef Tok = next();
Rui Ueyamaa27eecc2016-09-02 18:52:41 +0000739 if (Tok == ";")
740 continue;
741
742 if (Tok == "ENTRY") {
743 readEntry();
744 } else if (Tok == "EXTERN") {
745 readExtern();
746 } else if (Tok == "GROUP" || Tok == "INPUT") {
747 readGroup();
748 } else if (Tok == "INCLUDE") {
749 readInclude();
750 } else if (Tok == "OUTPUT") {
751 readOutput();
752 } else if (Tok == "OUTPUT_ARCH") {
753 readOutputArch();
754 } else if (Tok == "OUTPUT_FORMAT") {
755 readOutputFormat();
756 } else if (Tok == "PHDRS") {
757 readPhdrs();
758 } else if (Tok == "SEARCH_DIR") {
759 readSearchDir();
760 } else if (Tok == "SECTIONS") {
761 readSections();
762 } else if (Tok == "VERSION") {
763 readVersion();
Eugene Leviantdb741e72016-09-07 07:08:43 +0000764 } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok, true)) {
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000765 if (Opt.HasContents)
766 Opt.Commands.emplace_back(Cmd);
767 else
768 Opt.Assignments.emplace_back(Cmd);
769 } else {
George Rimar57610422016-03-11 14:43:02 +0000770 setError("unknown directive: " + Tok);
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000771 }
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000772 }
773}
774
Rui Ueyama717677a2016-02-11 21:17:59 +0000775void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000776 if (IsUnderSysroot && S.startswith("/")) {
777 SmallString<128> Path;
778 (Config->Sysroot + S).toStringRef(Path);
779 if (sys::fs::exists(Path)) {
780 Driver->addFile(Saver.save(Path.str()));
781 return;
782 }
783 }
784
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +0000785 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +0000786 Driver->addFile(S);
787 } else if (S.startswith("=")) {
788 if (Config->Sysroot.empty())
789 Driver->addFile(S.substr(1));
790 else
791 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
792 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +0000793 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +0000794 } else if (sys::fs::exists(S)) {
795 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +0000796 } else {
797 std::string Path = findFromSearchPaths(S);
798 if (Path.empty())
George Rimar777f9632016-03-12 08:31:34 +0000799 setError("unable to find " + S);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000800 else
801 Driver->addFile(Saver.save(Path));
Rui Ueyama52a15092015-10-11 03:28:42 +0000802 }
803}
804
Rui Ueyama717677a2016-02-11 21:17:59 +0000805void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000806 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +0000807 bool Orig = Config->AsNeeded;
808 Config->AsNeeded = true;
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000809 while (!Error && !skip(")"))
George Rimarcd574a52016-09-09 14:35:36 +0000810 addFile(unquote(next()));
Rui Ueyama35da9b62015-10-11 20:59:12 +0000811 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000812}
813
Rui Ueyama717677a2016-02-11 21:17:59 +0000814void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +0000815 // -e <symbol> takes predecence over ENTRY(<symbol>).
816 expect("(");
817 StringRef Tok = next();
818 if (Config->Entry.empty())
819 Config->Entry = Tok;
820 expect(")");
821}
822
Rui Ueyama717677a2016-02-11 21:17:59 +0000823void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +0000824 expect("(");
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000825 while (!Error && !skip(")"))
826 Config->Undefined.push_back(next());
George Rimar83f406c2015-10-19 17:35:12 +0000827}
828
Rui Ueyama717677a2016-02-11 21:17:59 +0000829void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000830 expect("(");
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000831 while (!Error && !skip(")")) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000832 StringRef Tok = next();
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000833 if (Tok == "AS_NEEDED")
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000834 readAsNeeded();
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000835 else
George Rimarcd574a52016-09-09 14:35:36 +0000836 addFile(unquote(Tok));
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000837 }
838}
839
Rui Ueyama717677a2016-02-11 21:17:59 +0000840void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000841 StringRef Tok = next();
George Rimarcd574a52016-09-09 14:35:36 +0000842 auto MBOrErr = MemoryBuffer::getFile(unquote(Tok));
Rui Ueyama025d59b2016-02-02 20:27:59 +0000843 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +0000844 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000845 return;
846 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000847 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Rui Ueyamaa47ee682015-10-11 01:53:04 +0000848 StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
849 std::vector<StringRef> V = tokenize(S);
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000850 Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000851}
852
Rui Ueyama717677a2016-02-11 21:17:59 +0000853void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +0000854 // -o <file> takes predecence over OUTPUT(<file>).
855 expect("(");
856 StringRef Tok = next();
857 if (Config->OutputFile.empty())
George Rimarcd574a52016-09-09 14:35:36 +0000858 Config->OutputFile = unquote(Tok);
Rui Ueyamaee592822015-10-07 00:25:09 +0000859 expect(")");
860}
861
Rui Ueyama717677a2016-02-11 21:17:59 +0000862void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +0000863 // Error checking only for now.
864 expect("(");
865 next();
866 expect(")");
867}
868
Rui Ueyama717677a2016-02-11 21:17:59 +0000869void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000870 // Error checking only for now.
871 expect("(");
872 next();
Davide Italiano6836c612015-10-12 21:08:41 +0000873 StringRef Tok = next();
874 if (Tok == ")")
George Rimar6c55f0e2016-09-08 08:20:30 +0000875 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000876 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +0000877 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000878 return;
879 }
Davide Italiano6836c612015-10-12 21:08:41 +0000880 next();
881 expect(",");
882 next();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000883 expect(")");
884}
885
Eugene Leviantbbe38602016-07-19 09:25:43 +0000886void ScriptParser::readPhdrs() {
887 expect("{");
888 while (!Error && !skip("}")) {
889 StringRef Tok = next();
Eugene Leviant56b21c82016-09-09 09:46:16 +0000890 Opt.PhdrsCommands.push_back(
891 {Tok, PT_NULL, false, false, UINT_MAX, nullptr});
Eugene Leviantbbe38602016-07-19 09:25:43 +0000892 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
893
894 PhdrCmd.Type = readPhdrType();
895 do {
896 Tok = next();
897 if (Tok == ";")
898 break;
899 if (Tok == "FILEHDR")
900 PhdrCmd.HasFilehdr = true;
901 else if (Tok == "PHDRS")
902 PhdrCmd.HasPhdrs = true;
Eugene Leviant56b21c82016-09-09 09:46:16 +0000903 else if (Tok == "AT")
904 PhdrCmd.LMAExpr = readParenExpr();
Eugene Leviant865bf862016-07-21 10:43:25 +0000905 else if (Tok == "FLAGS") {
906 expect("(");
Rafael Espindolaeb685cd2016-08-02 22:14:57 +0000907 // Passing 0 for the value of dot is a bit of a hack. It means that
908 // we accept expressions like ".|1".
909 PhdrCmd.Flags = readExpr()(0);
Eugene Leviant865bf862016-07-21 10:43:25 +0000910 expect(")");
911 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +0000912 setError("unexpected header attribute: " + Tok);
913 } while (!Error);
914 }
915}
916
Rui Ueyama717677a2016-02-11 21:17:59 +0000917void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +0000918 expect("(");
Rui Ueyama86c5fb82016-09-08 23:26:54 +0000919 StringRef Tok = next();
Rui Ueyama6c7ad132016-09-02 19:20:33 +0000920 if (!Config->Nostdlib)
George Rimarcd574a52016-09-09 14:35:36 +0000921 Config->SearchPaths.push_back(unquote(Tok));
Davide Italiano68a39a62015-10-08 17:51:41 +0000922 expect(")");
923}
924
Rui Ueyama717677a2016-02-11 21:17:59 +0000925void ScriptParser::readSections() {
Rui Ueyama3de0a332016-07-29 03:31:09 +0000926 Opt.HasContents = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000927 expect("{");
George Rimar652852c2016-04-16 10:10:32 +0000928 while (!Error && !skip("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +0000929 StringRef Tok = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +0000930 BaseCommand *Cmd = readProvideOrAssignment(Tok, true);
Eugene Leviantceabe802016-08-11 07:56:43 +0000931 if (!Cmd) {
932 if (Tok == "ASSERT")
933 Cmd = new AssertCommand(readAssert());
934 else
935 Cmd = readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +0000936 }
Rui Ueyama10416562016-08-04 02:03:27 +0000937 Opt.Commands.emplace_back(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000938 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000939}
940
Rui Ueyama708019c2016-07-24 18:19:40 +0000941static int precedence(StringRef Op) {
942 return StringSwitch<int>(Op)
943 .Case("*", 4)
944 .Case("/", 4)
945 .Case("+", 3)
946 .Case("-", 3)
947 .Case("<", 2)
948 .Case(">", 2)
949 .Case(">=", 2)
950 .Case("<=", 2)
951 .Case("==", 2)
952 .Case("!=", 2)
953 .Case("&", 1)
Rafael Espindolacc3dd622016-08-22 21:33:35 +0000954 .Case("|", 1)
Rui Ueyama708019c2016-07-24 18:19:40 +0000955 .Default(-1);
956}
957
George Rimarc91930a2016-09-02 21:17:20 +0000958Regex ScriptParser::readFilePatterns() {
Rui Ueyama10416562016-08-04 02:03:27 +0000959 std::vector<StringRef> V;
960 while (!Error && !skip(")"))
961 V.push_back(next());
George Rimarc91930a2016-09-02 21:17:20 +0000962 return compileGlobPatterns(V);
George Rimar0702c4e2016-07-29 15:32:46 +0000963}
964
Rui Ueyama742c3832016-08-04 22:27:00 +0000965SortKind ScriptParser::readSortKind() {
966 if (skip("SORT") || skip("SORT_BY_NAME"))
967 return SortByName;
968 if (skip("SORT_BY_ALIGNMENT"))
969 return SortByAlignment;
970 return SortNone;
971}
972
George Rimara2496cb2016-08-30 09:46:59 +0000973InputSectionDescription *
974ScriptParser::readInputSectionRules(StringRef FilePattern) {
George Rimarc91930a2016-09-02 21:17:20 +0000975 auto *Cmd = new InputSectionDescription(FilePattern);
Davide Italiano0ed42b02016-07-25 21:47:13 +0000976 expect("(");
Davide Italianoe7282792016-07-27 01:44:01 +0000977
Rui Ueyama742c3832016-08-04 22:27:00 +0000978 // Read EXCLUDE_FILE().
Davide Italianoe7282792016-07-27 01:44:01 +0000979 if (skip("EXCLUDE_FILE")) {
980 expect("(");
George Rimarc91930a2016-09-02 21:17:20 +0000981 Cmd->ExcludedFileRe = readFilePatterns();
Davide Italiano0ed42b02016-07-25 21:47:13 +0000982 }
George Rimar06598002016-07-28 21:51:30 +0000983
Rui Ueyama742c3832016-08-04 22:27:00 +0000984 // Read SORT().
985 if (SortKind K1 = readSortKind()) {
986 Cmd->SortOuter = K1;
George Rimar0702c4e2016-07-29 15:32:46 +0000987 expect("(");
Rui Ueyama742c3832016-08-04 22:27:00 +0000988 if (SortKind K2 = readSortKind()) {
989 Cmd->SortInner = K2;
George Rimar350ece42016-08-03 08:35:59 +0000990 expect("(");
George Rimarc91930a2016-09-02 21:17:20 +0000991 Cmd->SectionRe = readFilePatterns();
George Rimar350ece42016-08-03 08:35:59 +0000992 expect(")");
993 } else {
George Rimarc91930a2016-09-02 21:17:20 +0000994 Cmd->SectionRe = readFilePatterns();
George Rimar350ece42016-08-03 08:35:59 +0000995 }
George Rimar0702c4e2016-07-29 15:32:46 +0000996 expect(")");
Rui Ueyama10416562016-08-04 02:03:27 +0000997 return Cmd;
George Rimar06598002016-07-28 21:51:30 +0000998 }
George Rimar0702c4e2016-07-29 15:32:46 +0000999
George Rimarc91930a2016-09-02 21:17:20 +00001000 Cmd->SectionRe = readFilePatterns();
Rui Ueyama10416562016-08-04 02:03:27 +00001001 return Cmd;
Davide Italianoe7282792016-07-27 01:44:01 +00001002}
1003
George Rimara2496cb2016-08-30 09:46:59 +00001004InputSectionDescription *
1005ScriptParser::readInputSectionDescription(StringRef Tok) {
George Rimar06598002016-07-28 21:51:30 +00001006 // Input section wildcard can be surrounded by KEEP.
1007 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
George Rimara2496cb2016-08-30 09:46:59 +00001008 if (Tok == "KEEP") {
George Rimar06598002016-07-28 21:51:30 +00001009 expect("(");
George Rimara2496cb2016-08-30 09:46:59 +00001010 StringRef FilePattern = next();
1011 InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
George Rimar06598002016-07-28 21:51:30 +00001012 expect(")");
George Rimarc91930a2016-09-02 21:17:20 +00001013 Opt.KeptSections.push_back(&Cmd->SectionRe);
Rui Ueyama10416562016-08-04 02:03:27 +00001014 return Cmd;
George Rimar06598002016-07-28 21:51:30 +00001015 }
George Rimara2496cb2016-08-30 09:46:59 +00001016 return readInputSectionRules(Tok);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001017}
1018
George Rimar03fc0102016-07-28 07:18:23 +00001019void ScriptParser::readSort() {
1020 expect("(");
1021 expect("CONSTRUCTORS");
1022 expect(")");
1023}
1024
George Rimareefa7582016-08-04 09:29:31 +00001025Expr ScriptParser::readAssert() {
1026 expect("(");
1027 Expr E = readExpr();
1028 expect(",");
George Rimarcd574a52016-09-09 14:35:36 +00001029 StringRef Msg = unquote(next());
George Rimareefa7582016-08-04 09:29:31 +00001030 expect(")");
1031 return [=](uint64_t Dot) {
1032 uint64_t V = E(Dot);
1033 if (!V)
1034 error(Msg);
1035 return V;
1036 };
1037}
1038
Rui Ueyama25150e82016-09-06 17:46:43 +00001039// Reads a FILL(expr) command. We handle the FILL command as an
1040// alias for =fillexp section attribute, which is different from
1041// what GNU linkers do.
1042// https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
George Rimarff1f29e2016-09-06 13:51:57 +00001043std::vector<uint8_t> ScriptParser::readFill() {
1044 expect("(");
1045 std::vector<uint8_t> V = readOutputSectionFiller(next());
1046 expect(")");
1047 expect(";");
1048 return V;
1049}
1050
Rui Ueyama10416562016-08-04 02:03:27 +00001051OutputSectionCommand *
1052ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +00001053 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
George Rimar58e5c4d2016-07-25 08:29:46 +00001054
1055 // Read an address expression.
1056 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
1057 if (peek() != ":")
1058 Cmd->AddrExpr = readExpr();
1059
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001060 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +00001061
George Rimar8ceadb32016-08-17 07:44:19 +00001062 if (skip("AT"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001063 Cmd->LmaExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001064 if (skip("ALIGN"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001065 Cmd->AlignExpr = readParenExpr();
George Rimardb24d9c2016-08-19 15:18:23 +00001066 if (skip("SUBALIGN"))
1067 Cmd->SubalignExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001068
Davide Italiano246f6812016-07-22 03:36:24 +00001069 // Parse constraints.
1070 if (skip("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001071 Cmd->Constraint = ConstraintKind::ReadOnly;
Davide Italiano246f6812016-07-22 03:36:24 +00001072 if (skip("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001073 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001074 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001075
Rui Ueyama025d59b2016-02-02 20:27:59 +00001076 while (!Error && !skip("}")) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001077 StringRef Tok = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +00001078 if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok, false))
Eugene Leviantceabe802016-08-11 07:56:43 +00001079 Cmd->Commands.emplace_back(Assignment);
George Rimarff1f29e2016-09-06 13:51:57 +00001080 else if (Tok == "FILL")
1081 Cmd->Filler = readFill();
Eugene Leviantceabe802016-08-11 07:56:43 +00001082 else if (Tok == "SORT")
George Rimar03fc0102016-07-28 07:18:23 +00001083 readSort();
George Rimara2496cb2016-08-30 09:46:59 +00001084 else if (peek() == "(")
1085 Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
Eugene Leviantceabe802016-08-11 07:56:43 +00001086 else
1087 setError("unknown command " + Tok);
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001088 }
George Rimar076fe152016-07-21 06:43:01 +00001089 Cmd->Phdrs = readOutputSectionPhdrs();
George Rimarff1f29e2016-09-06 13:51:57 +00001090 if (peek().startswith("="))
1091 Cmd->Filler = readOutputSectionFiller(next().drop_front());
Rui Ueyama10416562016-08-04 02:03:27 +00001092 return Cmd;
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001093}
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001094
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001095// Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
1096// https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
1097//
1098// ld.gold is not fully compatible with ld.bfd. ld.bfd handles
1099// hexstrings as blobs of arbitrary sizes, while ld.gold handles them
1100// as 32-bit big-endian values. We will do the same as ld.gold does
1101// because it's simpler than what ld.bfd does.
George Rimarff1f29e2016-09-06 13:51:57 +00001102std::vector<uint8_t> ScriptParser::readOutputSectionFiller(StringRef Tok) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001103 uint32_t V;
George Rimarff1f29e2016-09-06 13:51:57 +00001104 if (Tok.getAsInteger(0, V)) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001105 setError("invalid filler expression: " + Tok);
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001106 return {};
George Rimare2ee72b2016-02-26 14:48:31 +00001107 }
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001108 return {uint8_t(V >> 24), uint8_t(V >> 16), uint8_t(V >> 8), uint8_t(V)};
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001109}
1110
Petr Hoseka35e39c2016-08-16 01:11:16 +00001111SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
Eugene Levianta31c91b2016-07-22 07:38:40 +00001112 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +00001113 SymbolAssignment *Cmd = readAssignment(next());
Petr Hoseka35e39c2016-08-16 01:11:16 +00001114 Cmd->Provide = Provide;
Rui Ueyama174e0a12016-07-29 00:29:25 +00001115 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001116 expect(")");
1117 expect(";");
Rui Ueyama10416562016-08-04 02:03:27 +00001118 return Cmd;
Eugene Levianteda81a12016-07-12 06:39:48 +00001119}
1120
Eugene Leviantdb741e72016-09-07 07:08:43 +00001121SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok,
1122 bool MakeAbsolute) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001123 SymbolAssignment *Cmd = nullptr;
1124 if (peek() == "=" || peek() == "+=") {
1125 Cmd = readAssignment(Tok);
1126 expect(";");
1127 } else if (Tok == "PROVIDE") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001128 Cmd = readProvideHidden(true, false);
1129 } else if (Tok == "HIDDEN") {
1130 Cmd = readProvideHidden(false, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001131 } else if (Tok == "PROVIDE_HIDDEN") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001132 Cmd = readProvideHidden(true, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001133 }
Eugene Leviantdb741e72016-09-07 07:08:43 +00001134 if (Cmd && MakeAbsolute)
1135 Cmd->IsAbsolute = true;
Eugene Leviantceabe802016-08-11 07:56:43 +00001136 return Cmd;
1137}
1138
George Rimar30835ea2016-07-28 21:08:56 +00001139static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
1140 if (S == ".")
1141 return Dot;
George Rimar884e7862016-09-08 08:19:13 +00001142 return ScriptBase->getSymbolValue(S);
George Rimare32a3592016-08-10 07:59:34 +00001143}
1144
George Rimar30835ea2016-07-28 21:08:56 +00001145SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1146 StringRef Op = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +00001147 bool IsAbsolute = false;
1148 Expr E;
George Rimar30835ea2016-07-28 21:08:56 +00001149 assert(Op == "=" || Op == "+=");
Eugene Leviantdb741e72016-09-07 07:08:43 +00001150 if (skip("ABSOLUTE")) {
1151 E = readParenExpr();
1152 IsAbsolute = true;
1153 } else {
1154 E = readExpr();
1155 }
George Rimar30835ea2016-07-28 21:08:56 +00001156 if (Op == "+=")
1157 E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
Eugene Leviantdb741e72016-09-07 07:08:43 +00001158 return new SymbolAssignment(Name, E, IsAbsolute);
George Rimar30835ea2016-07-28 21:08:56 +00001159}
1160
1161// This is an operator-precedence parser to parse a linker
1162// script expression.
1163Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
1164
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001165static Expr combine(StringRef Op, Expr L, Expr R) {
1166 if (Op == "*")
1167 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1168 if (Op == "/") {
1169 return [=](uint64_t Dot) -> uint64_t {
1170 uint64_t RHS = R(Dot);
1171 if (RHS == 0) {
1172 error("division by zero");
1173 return 0;
1174 }
1175 return L(Dot) / RHS;
1176 };
1177 }
1178 if (Op == "+")
1179 return [=](uint64_t Dot) { return L(Dot) + R(Dot); };
1180 if (Op == "-")
1181 return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
1182 if (Op == "<")
1183 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
1184 if (Op == ">")
1185 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
1186 if (Op == ">=")
1187 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
1188 if (Op == "<=")
1189 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
1190 if (Op == "==")
1191 return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
1192 if (Op == "!=")
1193 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
1194 if (Op == "&")
1195 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
Rafael Espindolacc3dd622016-08-22 21:33:35 +00001196 if (Op == "|")
1197 return [=](uint64_t Dot) { return L(Dot) | R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001198 llvm_unreachable("invalid operator");
1199}
1200
Rui Ueyama708019c2016-07-24 18:19:40 +00001201// This is a part of the operator-precedence parser. This function
1202// assumes that the remaining token stream starts with an operator.
1203Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1204 while (!atEOF() && !Error) {
1205 // Read an operator and an expression.
1206 StringRef Op1 = peek();
1207 if (Op1 == "?")
1208 return readTernary(Lhs);
1209 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +00001210 break;
Rui Ueyama708019c2016-07-24 18:19:40 +00001211 next();
1212 Expr Rhs = readPrimary();
1213
1214 // Evaluate the remaining part of the expression first if the
1215 // next operator has greater precedence than the previous one.
1216 // For example, if we have read "+" and "3", and if the next
1217 // operator is "*", then we'll evaluate 3 * ... part first.
1218 while (!atEOF()) {
1219 StringRef Op2 = peek();
1220 if (precedence(Op2) <= precedence(Op1))
1221 break;
1222 Rhs = readExpr1(Rhs, precedence(Op2));
1223 }
1224
1225 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +00001226 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001227 return Lhs;
1228}
1229
1230uint64_t static getConstant(StringRef S) {
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001231 if (S == "COMMONPAGESIZE")
Rui Ueyama708019c2016-07-24 18:19:40 +00001232 return Target->PageSize;
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001233 if (S == "MAXPAGESIZE")
1234 return Target->MaxPageSize;
Rui Ueyama708019c2016-07-24 18:19:40 +00001235 error("unknown constant: " + S);
1236 return 0;
1237}
1238
Rui Ueyama626e0b02016-09-02 18:19:00 +00001239// Parses Tok as an integer. Returns true if successful.
1240// It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1241// and decimal numbers. Decimal numbers may have "K" (kilo) or
1242// "M" (mega) prefixes.
George Rimar9f2f7ad2016-09-02 16:01:42 +00001243static bool readInteger(StringRef Tok, uint64_t &Result) {
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001244 if (Tok.startswith("-")) {
1245 if (!readInteger(Tok.substr(1), Result))
1246 return false;
1247 Result = -Result;
1248 return true;
1249 }
George Rimar9f2f7ad2016-09-02 16:01:42 +00001250 if (Tok.startswith_lower("0x"))
1251 return !Tok.substr(2).getAsInteger(16, Result);
1252 if (Tok.endswith_lower("H"))
1253 return !Tok.drop_back().getAsInteger(16, Result);
1254
1255 int Suffix = 1;
1256 if (Tok.endswith_lower("K")) {
1257 Suffix = 1024;
1258 Tok = Tok.drop_back();
1259 } else if (Tok.endswith_lower("M")) {
1260 Suffix = 1024 * 1024;
1261 Tok = Tok.drop_back();
1262 }
1263 if (Tok.getAsInteger(10, Result))
1264 return false;
1265 Result *= Suffix;
1266 return true;
1267}
1268
Rui Ueyama708019c2016-07-24 18:19:40 +00001269Expr ScriptParser::readPrimary() {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001270 if (peek() == "(")
1271 return readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001272
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001273 StringRef Tok = next();
Rui Ueyama708019c2016-07-24 18:19:40 +00001274
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001275 if (Tok == "~") {
1276 Expr E = readPrimary();
1277 return [=](uint64_t Dot) { return ~E(Dot); };
1278 }
1279 if (Tok == "-") {
1280 Expr E = readPrimary();
1281 return [=](uint64_t Dot) { return -E(Dot); };
1282 }
1283
Rui Ueyama708019c2016-07-24 18:19:40 +00001284 // Built-in functions are parsed here.
1285 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
George Rimar96659df2016-08-30 09:54:01 +00001286 if (Tok == "ADDR") {
1287 expect("(");
1288 StringRef Name = next();
1289 expect(")");
George Rimar884e7862016-09-08 08:19:13 +00001290 return
1291 [=](uint64_t Dot) { return ScriptBase->getOutputSectionAddress(Name); };
George Rimar96659df2016-08-30 09:54:01 +00001292 }
George Rimareefa7582016-08-04 09:29:31 +00001293 if (Tok == "ASSERT")
1294 return readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001295 if (Tok == "ALIGN") {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001296 Expr E = readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001297 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1298 }
1299 if (Tok == "CONSTANT") {
1300 expect("(");
1301 StringRef Tok = next();
1302 expect(")");
1303 return [=](uint64_t Dot) { return getConstant(Tok); };
1304 }
Rafael Espindola54c145c2016-07-28 18:16:24 +00001305 if (Tok == "SEGMENT_START") {
1306 expect("(");
1307 next();
1308 expect(",");
1309 uint64_t Val;
1310 next().getAsInteger(0, Val);
1311 expect(")");
1312 return [=](uint64_t Dot) { return Val; };
1313 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001314 if (Tok == "DATA_SEGMENT_ALIGN") {
1315 expect("(");
1316 Expr E = readExpr();
1317 expect(",");
1318 readExpr();
1319 expect(")");
Rui Ueyamaf7791bb2016-07-26 19:34:10 +00001320 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001321 }
1322 if (Tok == "DATA_SEGMENT_END") {
1323 expect("(");
1324 expect(".");
1325 expect(")");
1326 return [](uint64_t Dot) { return Dot; };
1327 }
George Rimar276b4e62016-07-26 17:58:44 +00001328 // GNU linkers implements more complicated logic to handle
1329 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1330 // the next page boundary for simplicity.
1331 if (Tok == "DATA_SEGMENT_RELRO_END") {
1332 expect("(");
1333 next();
1334 expect(",");
1335 readExpr();
1336 expect(")");
1337 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1338 }
George Rimar9e694502016-07-29 16:18:47 +00001339 if (Tok == "SIZEOF") {
1340 expect("(");
1341 StringRef Name = next();
1342 expect(")");
George Rimar884e7862016-09-08 08:19:13 +00001343 return [=](uint64_t Dot) { return ScriptBase->getOutputSectionSize(Name); };
George Rimar9e694502016-07-29 16:18:47 +00001344 }
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001345 if (Tok == "ALIGNOF") {
1346 expect("(");
1347 StringRef Name = next();
1348 expect(")");
1349 return
1350 [=](uint64_t Dot) { return ScriptBase->getOutputSectionAlign(Name); };
1351 }
George Rimare32a3592016-08-10 07:59:34 +00001352 if (Tok == "SIZEOF_HEADERS")
George Rimar884e7862016-09-08 08:19:13 +00001353 return [=](uint64_t Dot) { return ScriptBase->getHeaderSize(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001354
George Rimar9f2f7ad2016-09-02 16:01:42 +00001355 // Tok is a literal number.
1356 uint64_t V;
1357 if (readInteger(Tok, V))
1358 return [=](uint64_t Dot) { return V; };
1359
1360 // Tok is a symbol name.
1361 if (Tok != "." && !isValidCIdentifier(Tok))
1362 setError("malformed number: " + Tok);
1363 return [=](uint64_t Dot) { return getSymbolValue(Tok, Dot); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001364}
1365
1366Expr ScriptParser::readTernary(Expr Cond) {
1367 next();
1368 Expr L = readExpr();
1369 expect(":");
1370 Expr R = readExpr();
1371 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1372}
1373
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001374Expr ScriptParser::readParenExpr() {
1375 expect("(");
1376 Expr E = readExpr();
1377 expect(")");
1378 return E;
1379}
1380
Eugene Leviantbbe38602016-07-19 09:25:43 +00001381std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1382 std::vector<StringRef> Phdrs;
1383 while (!Error && peek().startswith(":")) {
1384 StringRef Tok = next();
1385 Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
1386 if (Tok.empty()) {
1387 setError("section header name is empty");
1388 break;
1389 }
Rui Ueyama047404f2016-07-20 19:36:36 +00001390 Phdrs.push_back(Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001391 }
1392 return Phdrs;
1393}
1394
1395unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001396 StringRef Tok = next();
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001397 unsigned Ret = StringSwitch<unsigned>(Tok)
George Rimar6c55f0e2016-09-08 08:20:30 +00001398 .Case("PT_NULL", PT_NULL)
1399 .Case("PT_LOAD", PT_LOAD)
1400 .Case("PT_DYNAMIC", PT_DYNAMIC)
1401 .Case("PT_INTERP", PT_INTERP)
1402 .Case("PT_NOTE", PT_NOTE)
1403 .Case("PT_SHLIB", PT_SHLIB)
1404 .Case("PT_PHDR", PT_PHDR)
1405 .Case("PT_TLS", PT_TLS)
1406 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1407 .Case("PT_GNU_STACK", PT_GNU_STACK)
1408 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1409 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001410
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001411 if (Ret == (unsigned)-1) {
1412 setError("invalid program header type: " + Tok);
1413 return PT_NULL;
1414 }
1415 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001416}
1417
Rui Ueyama95769b42016-08-31 20:03:54 +00001418void ScriptParser::readVersionDeclaration(StringRef VerStr) {
George Rimar20b65982016-08-31 09:08:26 +00001419 // Identifiers start at 2 because 0 and 1 are reserved
1420 // for VER_NDX_LOCAL and VER_NDX_GLOBAL constants.
1421 size_t VersionId = Config->VersionDefinitions.size() + 2;
1422 Config->VersionDefinitions.push_back({VerStr, VersionId});
1423
1424 if (skip("global:") || peek() != "local:")
1425 readGlobal(VerStr);
1426 if (skip("local:"))
1427 readLocal();
1428 expect("}");
1429
1430 // Each version may have a parent version. For example, "Ver2" defined as
1431 // "Ver2 { global: foo; local: *; } Ver1;" has "Ver1" as a parent. This
1432 // version hierarchy is, probably against your instinct, purely for human; the
1433 // runtime doesn't care about them at all. In LLD, we simply skip the token.
1434 if (!VerStr.empty() && peek() != ";")
1435 next();
1436 expect(";");
1437}
1438
1439void ScriptParser::readLocal() {
1440 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1441 expect("*");
1442 expect(";");
1443}
1444
1445void ScriptParser::readExtern(std::vector<SymbolVersion> *Globals) {
George Rimarcd574a52016-09-09 14:35:36 +00001446 expect("\"C++\"");
George Rimar20b65982016-08-31 09:08:26 +00001447 expect("{");
1448
1449 for (;;) {
1450 if (peek() == "}" || Error)
1451 break;
George Rimarcd574a52016-09-09 14:35:36 +00001452 bool HasWildcard = !peek().startswith("\"") && hasWildcard(peek());
1453 Globals->push_back({unquote(next()), true, HasWildcard});
George Rimar20b65982016-08-31 09:08:26 +00001454 expect(";");
1455 }
1456
1457 expect("}");
1458 expect(";");
1459}
1460
1461void ScriptParser::readGlobal(StringRef VerStr) {
1462 std::vector<SymbolVersion> *Globals;
1463 if (VerStr.empty())
1464 Globals = &Config->VersionScriptGlobals;
1465 else
1466 Globals = &Config->VersionDefinitions.back().Globals;
1467
1468 for (;;) {
1469 if (skip("extern"))
1470 readExtern(Globals);
1471
1472 StringRef Cur = peek();
1473 if (Cur == "}" || Cur == "local:" || Error)
1474 return;
1475 next();
George Rimarcd574a52016-09-09 14:35:36 +00001476 Globals->push_back({unquote(Cur), false, hasWildcard(Cur)});
George Rimar20b65982016-08-31 09:08:26 +00001477 expect(";");
1478 }
1479}
1480
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001481static bool isUnderSysroot(StringRef Path) {
1482 if (Config->Sysroot == "")
1483 return false;
1484 for (; !Path.empty(); Path = sys::path::parent_path(Path))
1485 if (sys::fs::equivalent(Config->Sysroot, Path))
1486 return true;
1487 return false;
1488}
1489
Rui Ueyama07320e42016-04-20 20:13:41 +00001490void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001491 StringRef Path = MB.getBufferIdentifier();
George Rimar20b65982016-08-31 09:08:26 +00001492 ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).readLinkerScript();
1493}
1494
1495void elf::readVersionScript(MemoryBufferRef MB) {
1496 ScriptParser(MB.getBuffer(), false).readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001497}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001498
Rui Ueyama07320e42016-04-20 20:13:41 +00001499template class elf::LinkerScript<ELF32LE>;
1500template class elf::LinkerScript<ELF32BE>;
1501template class elf::LinkerScript<ELF64LE>;
1502template class elf::LinkerScript<ELF64BE>;