blob: b1462e05cfb4a85ddb6d06c136852b322d0e6fc1 [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;
George Rimare38cbab2016-09-26 19:22:50 +000041using namespace llvm::support::endian;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000042using namespace lld;
Rafael Espindolae0df00b2016-02-28 00:25:54 +000043using namespace lld::elf;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000044
George Rimar884e7862016-09-08 08:19:13 +000045LinkerScriptBase *elf::ScriptBase;
Rui Ueyama07320e42016-04-20 20:13:41 +000046ScriptConfiguration *elf::ScriptConfig;
Rui Ueyama717677a2016-02-11 21:17:59 +000047
George Rimar6c55f0e2016-09-08 08:20:30 +000048template <class ELFT> static void addRegular(SymbolAssignment *Cmd) {
Rui Ueyama16024212016-08-11 23:22:52 +000049 Symbol *Sym = Symtab<ELFT>::X->addRegular(Cmd->Name, STB_GLOBAL, STV_DEFAULT);
50 Sym->Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
51 Cmd->Sym = Sym->body();
Eugene Leviant20d03192016-09-16 15:30:47 +000052
53 // If we have no SECTIONS then we don't have '.' and don't call
54 // assignAddresses(). We calculate symbol value immediately in this case.
55 if (!ScriptConfig->HasSections)
56 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(0);
Eugene Leviantceabe802016-08-11 07:56:43 +000057}
58
Rui Ueyama0c70d3c2016-08-12 03:31:09 +000059template <class ELFT> static void addSynthetic(SymbolAssignment *Cmd) {
George Rimare1937bb2016-08-19 15:36:32 +000060 Symbol *Sym = Symtab<ELFT>::X->addSynthetic(
61 Cmd->Name, nullptr, 0, Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT);
Rui Ueyama16024212016-08-11 23:22:52 +000062 Cmd->Sym = Sym->body();
Eugene Leviantceabe802016-08-11 07:56:43 +000063}
64
Eugene Leviantdb741e72016-09-07 07:08:43 +000065template <class ELFT> static void addSymbol(SymbolAssignment *Cmd) {
66 if (Cmd->IsAbsolute)
67 addRegular<ELFT>(Cmd);
68 else
69 addSynthetic<ELFT>(Cmd);
70}
Rui Ueyama16024212016-08-11 23:22:52 +000071// If a symbol was in PROVIDE(), we need to define it only when
72// it is an undefined symbol.
73template <class ELFT> static bool shouldDefine(SymbolAssignment *Cmd) {
74 if (Cmd->Name == ".")
Eugene Leviantceabe802016-08-11 07:56:43 +000075 return false;
Rui Ueyama16024212016-08-11 23:22:52 +000076 if (!Cmd->Provide)
77 return true;
78 SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
79 return B && B->isUndefined();
Eugene Leviantceabe802016-08-11 07:56:43 +000080}
81
George Rimar076fe152016-07-21 06:43:01 +000082bool SymbolAssignment::classof(const BaseCommand *C) {
83 return C->Kind == AssignmentKind;
84}
85
86bool OutputSectionCommand::classof(const BaseCommand *C) {
87 return C->Kind == OutputSectionKind;
88}
89
George Rimareea31142016-07-21 14:26:59 +000090bool InputSectionDescription::classof(const BaseCommand *C) {
91 return C->Kind == InputSectionKind;
92}
93
George Rimareefa7582016-08-04 09:29:31 +000094bool AssertCommand::classof(const BaseCommand *C) {
95 return C->Kind == AssertKind;
96}
97
George Rimare38cbab2016-09-26 19:22:50 +000098bool BytesDataCommand::classof(const BaseCommand *C) {
99 return C->Kind == BytesDataKind;
100}
101
Rui Ueyama36a153c2016-07-23 14:09:58 +0000102template <class ELFT> static bool isDiscarded(InputSectionBase<ELFT> *S) {
George Rimareea31142016-07-21 14:26:59 +0000103 return !S || !S->Live;
Rui Ueyama717677a2016-02-11 21:17:59 +0000104}
105
Rui Ueyamaf34d0e02016-08-12 01:24:53 +0000106template <class ELFT> LinkerScript<ELFT>::LinkerScript() {}
107template <class ELFT> LinkerScript<ELFT>::~LinkerScript() {}
108
Rui Ueyama07320e42016-04-20 20:13:41 +0000109template <class ELFT>
110bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) {
Eugene Leviantcf43f172016-10-05 09:36:59 +0000111 for (InputSectionDescription *ID : Opt.KeptSections) {
112 StringRef Filename = S->getFile()->getName();
113 if (!ID->FileRe.match(sys::path::filename(Filename)))
114 continue;
Rui Ueyamab66260a2016-10-05 20:09:50 +0000115
116 for (SectionPattern &P : ID->SectionPatterns)
Eugene Leviantcf43f172016-10-05 09:36:59 +0000117 if (P.SectionRe.match(S->Name))
118 return true;
119 }
George Rimareea31142016-07-21 14:26:59 +0000120 return false;
121}
122
George Rimar575208c2016-09-15 19:15:12 +0000123static bool comparePriority(InputSectionData *A, InputSectionData *B) {
124 return getPriority(A->Name) < getPriority(B->Name);
125}
126
Rafael Espindolac0028d32016-09-08 20:47:52 +0000127static bool compareName(InputSectionData *A, InputSectionData *B) {
Rafael Espindola042a3f22016-09-08 14:06:08 +0000128 return A->Name < B->Name;
Rui Ueyama742c3832016-08-04 22:27:00 +0000129}
George Rimar350ece42016-08-03 08:35:59 +0000130
Rafael Espindolac0028d32016-09-08 20:47:52 +0000131static bool compareAlignment(InputSectionData *A, InputSectionData *B) {
Rui Ueyama742c3832016-08-04 22:27:00 +0000132 // ">" is not a mistake. Larger alignments are placed before smaller
133 // alignments in order to reduce the amount of padding necessary.
134 // This is compatible with GNU.
135 return A->Alignment > B->Alignment;
136}
George Rimar350ece42016-08-03 08:35:59 +0000137
Rafael Espindolac0028d32016-09-08 20:47:52 +0000138static std::function<bool(InputSectionData *, InputSectionData *)>
George Rimarbe394db2016-09-16 20:21:55 +0000139getComparator(SortSectionPolicy K) {
140 switch (K) {
141 case SortSectionPolicy::Alignment:
142 return compareAlignment;
143 case SortSectionPolicy::Name:
Rafael Espindolac0028d32016-09-08 20:47:52 +0000144 return compareName;
George Rimarbe394db2016-09-16 20:21:55 +0000145 case SortSectionPolicy::Priority:
146 return comparePriority;
147 default:
148 llvm_unreachable("unknown sort policy");
149 }
Rui Ueyama742c3832016-08-04 22:27:00 +0000150}
George Rimar0702c4e2016-07-29 15:32:46 +0000151
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000152template <class ELFT>
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000153static bool matchConstraints(ArrayRef<InputSectionBase<ELFT> *> Sections,
George Rimar06ae6832016-08-12 09:07:57 +0000154 ConstraintKind Kind) {
George Rimar8f66df92016-08-12 20:38:20 +0000155 if (Kind == ConstraintKind::NoConstraint)
156 return true;
Rafael Espindolae746e522016-09-21 18:33:44 +0000157 bool IsRW = llvm::any_of(Sections, [=](InputSectionData *Sec2) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000158 auto *Sec = static_cast<InputSectionBase<ELFT> *>(Sec2);
Rafael Espindolae746e522016-09-21 18:33:44 +0000159 return Sec->getSectionHdr()->sh_flags & SHF_WRITE;
George Rimar06ae6832016-08-12 09:07:57 +0000160 });
Rafael Espindolae746e522016-09-21 18:33:44 +0000161 return (IsRW && Kind == ConstraintKind::ReadWrite) ||
162 (!IsRW && Kind == ConstraintKind::ReadOnly);
George Rimar06ae6832016-08-12 09:07:57 +0000163}
164
George Rimar07171f22016-09-21 15:56:44 +0000165static void sortSections(InputSectionData **Begin, InputSectionData **End,
Rui Ueyamaee924702016-09-20 19:42:41 +0000166 SortSectionPolicy K) {
167 if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
George Rimar07171f22016-09-21 15:56:44 +0000168 std::stable_sort(Begin, End, getComparator(K));
Rui Ueyamaee924702016-09-20 19:42:41 +0000169}
170
Rafael Espindolad3190792016-09-16 15:10:23 +0000171// Compute and remember which sections the InputSectionDescription matches.
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000172template <class ELFT>
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000173void LinkerScript<ELFT>::computeInputSections(InputSectionDescription *I) {
Rui Ueyama4dc07be2016-09-17 02:23:40 +0000174 // Collects all sections that satisfy constraints of I
175 // and attach them to I.
176 for (SectionPattern &Pat : I->SectionPatterns) {
George Rimar07171f22016-09-21 15:56:44 +0000177 size_t SizeBefore = I->Sections.size();
George Rimar395281c2016-09-16 17:42:10 +0000178 for (ObjectFile<ELFT> *F : Symtab<ELFT>::X->getObjectFiles()) {
Rui Ueyama3ff27f42016-09-17 02:15:28 +0000179 StringRef Filename = sys::path::filename(F->getName());
Rafael Espindolaf135f0e2016-09-19 13:33:38 +0000180 if (!I->FileRe.match(Filename) || Pat.ExcludedFileRe.match(Filename))
Rui Ueyama3ff27f42016-09-17 02:15:28 +0000181 continue;
Rui Ueyama4dc07be2016-09-17 02:23:40 +0000182
Rui Ueyama3ff27f42016-09-17 02:15:28 +0000183 for (InputSectionBase<ELFT> *S : F->getSections())
Rafael Espindolaf135f0e2016-09-19 13:33:38 +0000184 if (!isDiscarded(S) && !S->OutSec && Pat.SectionRe.match(S->Name))
Rui Ueyama3ff27f42016-09-17 02:15:28 +0000185 I->Sections.push_back(S);
Rafael Espindolaf135f0e2016-09-19 13:33:38 +0000186 if (Pat.SectionRe.match("COMMON"))
Rui Ueyama3ff27f42016-09-17 02:15:28 +0000187 I->Sections.push_back(CommonInputSection<ELFT>::X);
George Rimar395281c2016-09-16 17:42:10 +0000188 }
Rafael Espindolad3190792016-09-16 15:10:23 +0000189
George Rimar07171f22016-09-21 15:56:44 +0000190 // Sort sections as instructed by SORT-family commands and --sort-section
191 // option. Because SORT-family commands can be nested at most two depth
192 // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
193 // line option is respected even if a SORT command is given, the exact
194 // behavior we have here is a bit complicated. Here are the rules.
195 //
196 // 1. If two SORT commands are given, --sort-section is ignored.
197 // 2. If one SORT command is given, and if it is not SORT_NONE,
198 // --sort-section is handled as an inner SORT command.
199 // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
200 // 4. If no SORT command is given, sort according to --sort-section.
201 InputSectionData **Begin = I->Sections.data() + SizeBefore;
202 InputSectionData **End = I->Sections.data() + I->Sections.size();
203 if (Pat.SortOuter != SortSectionPolicy::None) {
204 if (Pat.SortInner == SortSectionPolicy::Default)
205 sortSections(Begin, End, Config->SortSection);
206 else
207 sortSections(Begin, End, Pat.SortInner);
208 sortSections(Begin, End, Pat.SortOuter);
209 }
Rui Ueyamaee924702016-09-20 19:42:41 +0000210 }
Rafael Espindolad3190792016-09-16 15:10:23 +0000211
212 // We do not add duplicate input sections, so mark them with a dummy output
213 // section for now.
214 for (InputSectionData *S : I->Sections) {
215 auto *S2 = static_cast<InputSectionBase<ELFT> *>(S);
216 S2->OutSec = (OutputSectionBase<ELFT> *)-1;
217 }
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000218}
219
220template <class ELFT>
221void LinkerScript<ELFT>::discard(ArrayRef<InputSectionBase<ELFT> *> V) {
222 for (InputSectionBase<ELFT> *S : V) {
223 S->Live = false;
224 reportDiscarded(S);
225 }
226}
227
George Rimar06ae6832016-08-12 09:07:57 +0000228template <class ELFT>
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000229std::vector<InputSectionBase<ELFT> *>
George Rimar06ae6832016-08-12 09:07:57 +0000230LinkerScript<ELFT>::createInputSectionList(OutputSectionCommand &OutCmd) {
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000231 std::vector<InputSectionBase<ELFT> *> Ret;
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000232
George Rimar06ae6832016-08-12 09:07:57 +0000233 for (const std::unique_ptr<BaseCommand> &Base : OutCmd.Commands) {
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000234 auto *Cmd = dyn_cast<InputSectionDescription>(Base.get());
235 if (!Cmd)
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000236 continue;
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000237 computeInputSections(Cmd);
Rafael Espindolad3190792016-09-16 15:10:23 +0000238 for (InputSectionData *S : Cmd->Sections)
239 Ret.push_back(static_cast<InputSectionBase<ELFT> *>(S));
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000240 }
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000241
Eugene Leviantcc1ba8c2016-10-12 12:31:34 +0000242 // After we created final list we should now set OutSec pointer to null,
George Rimara4c7e742016-10-20 08:36:42 +0000243 // instead of -1. Otherwise we may get a crash when writing relocs, in
Eugene Leviantcc1ba8c2016-10-12 12:31:34 +0000244 // case section is discarded by linker script
245 for (InputSectionBase<ELFT> *S : Ret)
246 S->OutSec = nullptr;
247
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000248 return Ret;
249}
250
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000251template <class ELFT>
Rafael Espindola10897f12016-09-13 14:23:14 +0000252static SectionKey<ELFT::Is64Bits> createKey(InputSectionBase<ELFT> *C,
253 StringRef OutsecName) {
254 // When using linker script the merge rules are different.
255 // Unfortunately, linker scripts are name based. This means that expressions
256 // like *(.foo*) can refer to multiple input sections that would normally be
257 // placed in different output sections. We cannot put them in different
258 // output sections or we would produce wrong results for
259 // start = .; *(.foo.*) end = .; *(.bar)
260 // and a mapping of .foo1 and .bar1 to one section and .foo2 and .bar2 to
261 // another. The problem is that there is no way to layout those output
262 // sections such that the .foo sections are the only thing between the
263 // start and end symbols.
264
265 // An extra annoyance is that we cannot simply disable merging of the contents
266 // of SHF_MERGE sections, but our implementation requires one output section
267 // per "kind" (string or not, which size/aligment).
268 // Fortunately, creating symbols in the middle of a merge section is not
269 // supported by bfd or gold, so we can just create multiple section in that
270 // case.
271 const typename ELFT::Shdr *H = C->getSectionHdr();
272 typedef typename ELFT::uint uintX_t;
273 uintX_t Flags = H->sh_flags & (SHF_MERGE | SHF_STRINGS);
274
275 uintX_t Alignment = 0;
276 if (isa<MergeInputSection<ELFT>>(C))
277 Alignment = std::max(H->sh_addralign, H->sh_entsize);
278
279 return SectionKey<ELFT::Is64Bits>{OutsecName, /*Type*/ 0, Flags, Alignment};
280}
281
282template <class ELFT>
Eugene Leviant20d03192016-09-16 15:30:47 +0000283void LinkerScript<ELFT>::addSection(OutputSectionFactory<ELFT> &Factory,
284 InputSectionBase<ELFT> *Sec,
285 StringRef Name) {
286 OutputSectionBase<ELFT> *OutSec;
287 bool IsNew;
288 std::tie(OutSec, IsNew) = Factory.create(createKey(Sec, Name), Sec);
289 if (IsNew)
290 OutputSections->push_back(OutSec);
291 OutSec->addSection(Sec);
292}
293
294template <class ELFT>
295void LinkerScript<ELFT>::processCommands(OutputSectionFactory<ELFT> &Factory) {
Rafael Espindola28c15972016-09-13 13:00:06 +0000296
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000297 for (unsigned I = 0; I < Opt.Commands.size(); ++I) {
298 auto Iter = Opt.Commands.begin() + I;
299 const std::unique_ptr<BaseCommand> &Base1 = *Iter;
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000300 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base1.get())) {
301 if (shouldDefine<ELFT>(Cmd))
302 addRegular<ELFT>(Cmd);
303 continue;
304 }
Eugene Leviant20d03192016-09-16 15:30:47 +0000305 if (auto *Cmd = dyn_cast<AssertCommand>(Base1.get())) {
306 // If we don't have SECTIONS then output sections have already been
George Rimar194470cd2016-09-17 19:21:05 +0000307 // created by Writer<ELFT>. The LinkerScript<ELFT>::assignAddresses
Eugene Leviant20d03192016-09-16 15:30:47 +0000308 // will not be called, so ASSERT should be evaluated now.
309 if (!Opt.HasSections)
310 Cmd->Expression(0);
311 continue;
312 }
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000313
Eugene Leviantceabe802016-08-11 07:56:43 +0000314 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000315 std::vector<InputSectionBase<ELFT> *> V = createInputSectionList(*Cmd);
316
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000317 if (Cmd->Name == "/DISCARD/") {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000318 discard(V);
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000319 continue;
320 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000321
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000322 if (!matchConstraints<ELFT>(V, Cmd->Constraint)) {
323 for (InputSectionBase<ELFT> *S : V)
324 S->OutSec = nullptr;
325 Opt.Commands.erase(Iter);
George Rimardfbbbc82016-09-17 09:50:10 +0000326 --I;
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000327 continue;
328 }
329
330 for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
331 if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base.get()))
332 if (shouldDefine<ELFT>(OutCmd))
333 addSymbol<ELFT>(OutCmd);
334
Eugene Leviant97403d12016-09-01 09:55:57 +0000335 if (V.empty())
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000336 continue;
337
George Rimardb24d9c2016-08-19 15:18:23 +0000338 for (InputSectionBase<ELFT> *Sec : V) {
Eugene Leviant20d03192016-09-16 15:30:47 +0000339 addSection(Factory, Sec, Cmd->Name);
340 if (uint32_t Subalign = Cmd->SubalignExpr ? Cmd->SubalignExpr(0) : 0)
George Rimardb24d9c2016-08-19 15:18:23 +0000341 Sec->Alignment = Subalign;
George Rimardb24d9c2016-08-19 15:18:23 +0000342 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000343 }
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000344 }
Eugene Leviant20d03192016-09-16 15:30:47 +0000345}
Eugene Leviante63d81b2016-07-20 14:43:20 +0000346
Eugene Leviant20d03192016-09-16 15:30:47 +0000347template <class ELFT>
348void LinkerScript<ELFT>::createSections(OutputSectionFactory<ELFT> &Factory) {
349 processCommands(Factory);
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000350 // Add orphan sections.
Eugene Leviant20d03192016-09-16 15:30:47 +0000351 for (ObjectFile<ELFT> *F : Symtab<ELFT>::X->getObjectFiles())
352 for (InputSectionBase<ELFT> *S : F->getSections())
353 if (!isDiscarded(S) && !S->OutSec)
Rui Ueyama05384082016-10-12 22:36:31 +0000354 addSection(Factory, S, getOutputSectionName(S->Name, Opt.Alloc));
Eugene Leviante63d81b2016-07-20 14:43:20 +0000355}
356
Eugene Leviantdb741e72016-09-07 07:08:43 +0000357// Sets value of a section-defined symbol. Two kinds of
358// symbols are processed: synthetic symbols, whose value
359// is an offset from beginning of section and regular
360// symbols whose value is absolute.
361template <class ELFT>
362static void assignSectionSymbol(SymbolAssignment *Cmd,
363 OutputSectionBase<ELFT> *Sec,
364 typename ELFT::uint Off) {
365 if (!Cmd->Sym)
366 return;
367
368 if (auto *Body = dyn_cast<DefinedSynthetic<ELFT>>(Cmd->Sym)) {
369 Body->Section = Sec;
370 Body->Value = Cmd->Expression(Sec->getVA() + Off) - Sec->getVA();
371 return;
372 }
373 auto *Body = cast<DefinedRegular<ELFT>>(Cmd->Sym);
374 Body->Value = Cmd->Expression(Sec->getVA() + Off);
375}
376
Rafael Espindolaa940e532016-09-22 12:35:44 +0000377template <class ELFT> static bool isTbss(OutputSectionBase<ELFT> *Sec) {
378 return (Sec->getFlags() & SHF_TLS) && Sec->getType() == SHT_NOBITS;
379}
380
Rafael Espindolad3190792016-09-16 15:10:23 +0000381template <class ELFT> void LinkerScript<ELFT>::output(InputSection<ELFT> *S) {
382 if (!AlreadyOutputIS.insert(S).second)
383 return;
Rafael Espindolaa940e532016-09-22 12:35:44 +0000384 bool IsTbss = isTbss(CurOutSec);
Eugene Leviant20889c52016-08-31 08:13:33 +0000385
Rafael Espindolad3190792016-09-16 15:10:23 +0000386 uintX_t Pos = IsTbss ? Dot + ThreadBssOffset : Dot;
387 Pos = alignTo(Pos, S->Alignment);
388 S->OutSecOff = Pos - CurOutSec->getVA();
389 Pos += S->getSize();
390
391 // Update output section size after adding each section. This is so that
392 // SIZEOF works correctly in the case below:
393 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
394 CurOutSec->setSize(Pos - CurOutSec->getVA());
395
Rafael Espindola7252ae52016-09-22 12:00:08 +0000396 if (IsTbss)
397 ThreadBssOffset = Pos - Dot;
398 else
Rafael Espindolad3190792016-09-16 15:10:23 +0000399 Dot = Pos;
400}
401
402template <class ELFT> void LinkerScript<ELFT>::flush() {
Rafael Espindola65499b92016-09-23 20:10:47 +0000403 if (!CurOutSec || !AlreadyOutputOS.insert(CurOutSec).second)
404 return;
405 if (auto *OutSec = dyn_cast<OutputSection<ELFT>>(CurOutSec)) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000406 for (InputSection<ELFT> *I : OutSec->Sections)
407 output(I);
Rafael Espindola65499b92016-09-23 20:10:47 +0000408 } else {
409 Dot += CurOutSec->getSize();
Eugene Leviant20889c52016-08-31 08:13:33 +0000410 }
411}
412
413template <class ELFT>
Rafael Espindolad3190792016-09-16 15:10:23 +0000414void LinkerScript<ELFT>::switchTo(OutputSectionBase<ELFT> *Sec) {
415 if (CurOutSec == Sec)
416 return;
417 if (AlreadyOutputOS.count(Sec))
418 return;
419
420 flush();
421 CurOutSec = Sec;
422
423 Dot = alignTo(Dot, CurOutSec->getAlignment());
Rafael Espindolaa940e532016-09-22 12:35:44 +0000424 CurOutSec->setVA(isTbss(CurOutSec) ? Dot + ThreadBssOffset : Dot);
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000425
426 // If neither AT nor AT> is specified for an allocatable section, the linker
427 // will set the LMA such that the difference between VMA and LMA for the
428 // section is the same as the preceding output section in the same region
429 // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
430 CurOutSec->setLMAOffset(LMAOffset);
Rafael Espindolad3190792016-09-16 15:10:23 +0000431}
432
433template <class ELFT> void LinkerScript<ELFT>::process(BaseCommand &Base) {
George Rimare38cbab2016-09-26 19:22:50 +0000434 // This handles the assignments to symbol or to a location counter (.)
Rafael Espindolad3190792016-09-16 15:10:23 +0000435 if (auto *AssignCmd = dyn_cast<SymbolAssignment>(&Base)) {
436 if (AssignCmd->Name == ".") {
437 // Update to location counter means update to section size.
438 Dot = AssignCmd->Expression(Dot);
439 CurOutSec->setSize(Dot - CurOutSec->getVA());
440 return;
441 }
442 assignSectionSymbol<ELFT>(AssignCmd, CurOutSec, Dot - CurOutSec->getVA());
Eugene Leviantceabe802016-08-11 07:56:43 +0000443 return;
Rui Ueyama2de509c2016-08-12 00:55:08 +0000444 }
George Rimare38cbab2016-09-26 19:22:50 +0000445
446 // Handle BYTE(), SHORT(), LONG(), or QUAD().
447 if (auto *DataCmd = dyn_cast<BytesDataCommand>(&Base)) {
448 DataCmd->Offset = Dot - CurOutSec->getVA();
449 Dot += DataCmd->Size;
450 CurOutSec->setSize(Dot - CurOutSec->getVA());
451 return;
452 }
453
454 // It handles single input section description command,
455 // calculates and assigns the offsets for each section and also
456 // updates the output section size.
Rafael Espindolad3190792016-09-16 15:10:23 +0000457 auto &ICmd = cast<InputSectionDescription>(Base);
458 for (InputSectionData *ID : ICmd.Sections) {
459 auto *IB = static_cast<InputSectionBase<ELFT> *>(ID);
460 switchTo(IB->OutSec);
461 if (auto *I = dyn_cast<InputSection<ELFT>>(IB))
462 output(I);
Rafael Espindola65499b92016-09-23 20:10:47 +0000463 else
464 flush();
Eugene Leviantceabe802016-08-11 07:56:43 +0000465 }
466}
467
George Rimar8f66df92016-08-12 20:38:20 +0000468template <class ELFT>
George Rimara14b13d2016-09-07 10:46:07 +0000469static std::vector<OutputSectionBase<ELFT> *>
Eugene Leviant92577642016-10-10 11:23:12 +0000470findSections(StringRef Name,
Rafael Espindolad3190792016-09-16 15:10:23 +0000471 const std::vector<OutputSectionBase<ELFT> *> &Sections) {
George Rimara14b13d2016-09-07 10:46:07 +0000472 std::vector<OutputSectionBase<ELFT> *> Ret;
473 for (OutputSectionBase<ELFT> *Sec : Sections)
Eugene Leviant92577642016-10-10 11:23:12 +0000474 if (Sec->getName() == Name)
George Rimara14b13d2016-09-07 10:46:07 +0000475 Ret.push_back(Sec);
476 return Ret;
George Rimar8f66df92016-08-12 20:38:20 +0000477}
478
Rafael Espindolad3190792016-09-16 15:10:23 +0000479template <class ELFT>
480void LinkerScript<ELFT>::assignOffsets(OutputSectionCommand *Cmd) {
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000481 if (Cmd->LMAExpr)
482 LMAOffset = Cmd->LMAExpr(Dot) - Dot;
Rafael Espindolad3190792016-09-16 15:10:23 +0000483 std::vector<OutputSectionBase<ELFT> *> Sections =
Eugene Leviant92577642016-10-10 11:23:12 +0000484 findSections(Cmd->Name, *OutputSections);
Rafael Espindolad3190792016-09-16 15:10:23 +0000485 if (Sections.empty())
486 return;
487 switchTo(Sections[0]);
Rafael Espindolad3190792016-09-16 15:10:23 +0000488 // Find the last section output location. We will output orphan sections
489 // there so that end symbols point to the correct location.
490 auto E = std::find_if(Cmd->Commands.rbegin(), Cmd->Commands.rend(),
491 [](const std::unique_ptr<BaseCommand> &Cmd) {
492 return !isa<SymbolAssignment>(*Cmd);
493 })
494 .base();
495 for (auto I = Cmd->Commands.begin(); I != E; ++I)
496 process(**I);
Rafael Espindola65499b92016-09-23 20:10:47 +0000497 for (OutputSectionBase<ELFT> *Base : Sections)
Rafael Espindolad3190792016-09-16 15:10:23 +0000498 switchTo(Base);
Rafael Espindola65499b92016-09-23 20:10:47 +0000499 flush();
George Rimarb31dd372016-09-19 13:27:31 +0000500 std::for_each(E, Cmd->Commands.end(),
501 [this](std::unique_ptr<BaseCommand> &B) { process(*B.get()); });
Rafael Espindolad3190792016-09-16 15:10:23 +0000502}
503
Rafael Espindola9546fff2016-09-22 14:40:50 +0000504template <class ELFT> void LinkerScript<ELFT>::adjustSectionsBeforeSorting() {
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000505 // It is common practice to use very generic linker scripts. So for any
506 // given run some of the output sections in the script will be empty.
507 // We could create corresponding empty output sections, but that would
508 // clutter the output.
509 // We instead remove trivially empty sections. The bfd linker seems even
510 // more aggressive at removing them.
511 auto Pos = std::remove_if(
512 Opt.Commands.begin(), Opt.Commands.end(),
513 [&](const std::unique_ptr<BaseCommand> &Base) {
514 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
515 if (!Cmd)
516 return false;
517 std::vector<OutputSectionBase<ELFT> *> Secs =
Eugene Leviant92577642016-10-10 11:23:12 +0000518 findSections(Cmd->Name, *OutputSections);
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000519 if (!Secs.empty())
520 return false;
521 for (const std::unique_ptr<BaseCommand> &I : Cmd->Commands)
522 if (!isa<InputSectionDescription>(I.get()))
523 return false;
524 return true;
525 });
526 Opt.Commands.erase(Pos, Opt.Commands.end());
527
Rafael Espindola9546fff2016-09-22 14:40:50 +0000528 // If the output section contains only symbol assignments, create a
529 // corresponding output section. The bfd linker seems to only create them if
530 // '.' is assigned to, but creating these section should not have any bad
531 // consequeces and gives us a section to put the symbol in.
532 uintX_t Flags = SHF_ALLOC;
533 uint32_t Type = 0;
534 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
535 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
536 if (!Cmd)
537 continue;
538 std::vector<OutputSectionBase<ELFT> *> Secs =
Eugene Leviant92577642016-10-10 11:23:12 +0000539 findSections(Cmd->Name, *OutputSections);
Rafael Espindola9546fff2016-09-22 14:40:50 +0000540 if (!Secs.empty()) {
541 Flags = Secs[0]->getFlags();
542 Type = Secs[0]->getType();
543 continue;
544 }
545
546 auto *OutSec = new OutputSection<ELFT>(Cmd->Name, Type, Flags);
547 Out<ELFT>::Pool.emplace_back(OutSec);
548 OutputSections->push_back(OutSec);
549 }
550}
551
Rafael Espindola15c57952016-09-22 18:05:49 +0000552// When placing orphan sections, we want to place them after symbol assignments
553// so that an orphan after
554// begin_foo = .;
555// foo : { *(foo) }
556// end_foo = .;
557// doesn't break the intended meaning of the begin/end symbols.
558// We don't want to go over sections since Writer<ELFT>::sortSections is the
559// one in charge of deciding the order of the sections.
560// We don't want to go over alignments, since doing so in
561// rx_sec : { *(rx_sec) }
562// . = ALIGN(0x1000);
563// /* The RW PT_LOAD starts here*/
564// rw_sec : { *(rw_sec) }
565// would mean that the RW PT_LOAD would become unaligned.
566static bool shouldSkip(const BaseCommand &Cmd) {
567 if (isa<OutputSectionCommand>(Cmd))
568 return false;
569 const auto *Assign = dyn_cast<SymbolAssignment>(&Cmd);
570 if (!Assign)
571 return true;
572 return Assign->Name != ".";
573}
574
Rafael Espindola6d91fce2016-09-29 18:50:34 +0000575template <class ELFT>
576void LinkerScript<ELFT>::assignAddresses(std::vector<PhdrEntry<ELFT>> &Phdrs) {
George Rimar652852c2016-04-16 10:10:32 +0000577 // Orphan sections are sections present in the input files which
Rui Ueyama7c18c282016-04-18 21:00:40 +0000578 // are not explicitly placed into the output file by the linker script.
579 // We place orphan sections at end of file.
580 // Other linkers places them using some heuristics as described in
George Rimar652852c2016-04-16 10:10:32 +0000581 // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000582
583 // The OutputSections are already in the correct order.
584 // This loops creates or moves commands as needed so that they are in the
585 // correct order.
586 int CmdIndex = 0;
Rui Ueyamae5cc6682016-08-12 00:36:56 +0000587 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
George Rimar652852c2016-04-16 10:10:32 +0000588 StringRef Name = Sec->getName();
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000589
590 // Find the last spot where we can insert a command and still get the
Rafael Espindola15c57952016-09-22 18:05:49 +0000591 // correct result.
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000592 auto CmdIter = Opt.Commands.begin() + CmdIndex;
593 auto E = Opt.Commands.end();
Rafael Espindola15c57952016-09-22 18:05:49 +0000594 while (CmdIter != E && shouldSkip(**CmdIter)) {
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000595 ++CmdIter;
596 ++CmdIndex;
597 }
598
599 auto Pos =
600 std::find_if(CmdIter, E, [&](const std::unique_ptr<BaseCommand> &Base) {
601 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
602 return Cmd && Cmd->Name == Name;
603 });
604 if (Pos == E) {
605 Opt.Commands.insert(CmdIter,
606 llvm::make_unique<OutputSectionCommand>(Name));
Rafael Espindola15c57952016-09-22 18:05:49 +0000607 ++CmdIndex;
608 continue;
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000609 }
Rafael Espindola15c57952016-09-22 18:05:49 +0000610
611 // Continue from where we found it.
612 CmdIndex = (Pos - Opt.Commands.begin()) + 1;
613 continue;
George Rimar652852c2016-04-16 10:10:32 +0000614 }
George Rimar652852c2016-04-16 10:10:32 +0000615
Rui Ueyama7c18c282016-04-18 21:00:40 +0000616 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rafael Espindolabe607332016-09-30 00:16:11 +0000617 Dot = 0;
George Rimar652852c2016-04-16 10:10:32 +0000618
George Rimar076fe152016-07-21 06:43:01 +0000619 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
620 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
Rui Ueyama8d083e62016-07-29 05:48:39 +0000621 if (Cmd->Name == ".") {
622 Dot = Cmd->Expression(Dot);
623 } else if (Cmd->Sym) {
624 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(Dot);
625 }
George Rimar652852c2016-04-16 10:10:32 +0000626 continue;
627 }
628
George Rimareefa7582016-08-04 09:29:31 +0000629 if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
630 Cmd->Expression(Dot);
631 continue;
632 }
633
George Rimar076fe152016-07-21 06:43:01 +0000634 auto *Cmd = cast<OutputSectionCommand>(Base.get());
George Rimar652852c2016-04-16 10:10:32 +0000635
Rafael Espindolad3190792016-09-16 15:10:23 +0000636 if (Cmd->AddrExpr)
637 Dot = Cmd->AddrExpr(Dot);
George Rimar58e5c4d2016-07-25 08:29:46 +0000638
Rafael Espindolad3190792016-09-16 15:10:23 +0000639 assignOffsets(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000640 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000641
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000642 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
643 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
644 if (Sec->getFlags() & SHF_ALLOC)
645 MinVA = std::min(MinVA, Sec->getVA());
646 else
Rafael Espindolad3190792016-09-16 15:10:23 +0000647 Sec->setVA(0);
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000648 }
649
Rafael Espindola0d4b6d52016-09-22 16:47:21 +0000650 uintX_t HeaderSize = getHeaderSize();
Rafael Espindola6d91fce2016-09-29 18:50:34 +0000651 auto FirstPTLoad =
652 std::find_if(Phdrs.begin(), Phdrs.end(), [](const PhdrEntry<ELFT> &E) {
653 return E.H.p_type == PT_LOAD;
654 });
655 if (HeaderSize <= MinVA && FirstPTLoad != Phdrs.end()) {
656 // ELF and Program headers need to be right before the first section in
657 // memory. Set their addresses accordingly.
658 MinVA = alignDown(MinVA - HeaderSize, Target->PageSize);
659 Out<ELFT>::ElfHeader->setVA(MinVA);
660 Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
661 FirstPTLoad->First = Out<ELFT>::ElfHeader;
662 if (!FirstPTLoad->Last)
663 FirstPTLoad->Last = Out<ELFT>::ProgramHeaders;
Eugene Leviantcd8eaf82016-10-10 15:09:44 +0000664 } else if (!FirstPTLoad->First) {
Rui Ueyamab224c0482016-10-10 18:10:01 +0000665 // Sometimes the very first PT_LOAD segment can be empty.
Eugene Leviantcd8eaf82016-10-10 15:09:44 +0000666 // This happens if (all conditions met):
667 // - Linker script is used
668 // - First section in ELF image is not RO
669 // - Not enough space for program headers.
670 // The code below removes empty PT_LOAD segment and updates
671 // program headers size.
672 Phdrs.erase(FirstPTLoad);
673 Out<ELFT>::ProgramHeaders->setSize(sizeof(typename ELFT::Phdr) *
674 Phdrs.size());
Rafael Espindola6d91fce2016-09-29 18:50:34 +0000675 }
George Rimar652852c2016-04-16 10:10:32 +0000676}
677
Rui Ueyama464daad2016-08-22 04:55:20 +0000678// Creates program headers as instructed by PHDRS linker script command.
Rui Ueyama07320e42016-04-20 20:13:41 +0000679template <class ELFT>
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000680std::vector<PhdrEntry<ELFT>> LinkerScript<ELFT>::createPhdrs() {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000681 std::vector<PhdrEntry<ELFT>> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000682
Rui Ueyama464daad2016-08-22 04:55:20 +0000683 // Process PHDRS and FILEHDR keywords because they are not
684 // real output sections and cannot be added in the following loop.
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000685 std::vector<size_t> DefPhdrIds;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000686 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000687 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
688 PhdrEntry<ELFT> &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000689
690 if (Cmd.HasFilehdr)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000691 Phdr.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000692 if (Cmd.HasPhdrs)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000693 Phdr.add(Out<ELFT>::ProgramHeaders);
Eugene Leviant56b21c82016-09-09 09:46:16 +0000694
695 if (Cmd.LMAExpr) {
696 Phdr.H.p_paddr = Cmd.LMAExpr(0);
697 Phdr.HasLMA = true;
698 }
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000699
700 // If output section command doesn't specify any segments,
701 // and we haven't previously assigned any section to segment,
702 // then we simply assign section to the very first load segment.
703 // Below is an example of such linker script:
704 // PHDRS { seg PT_LOAD; }
705 // SECTIONS { .aaa : { *(.aaa) } }
706 if (DefPhdrIds.empty() && Phdr.H.p_type == PT_LOAD)
707 DefPhdrIds.push_back(Ret.size() - 1);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000708 }
709
Rui Ueyama464daad2016-08-22 04:55:20 +0000710 // Add output sections to program headers.
Rui Ueyama464daad2016-08-22 04:55:20 +0000711 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
Eugene Leviantbbe38602016-07-19 09:25:43 +0000712 if (!(Sec->getFlags() & SHF_ALLOC))
713 break;
714
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000715 std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName());
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000716 if (PhdrIds.empty())
717 PhdrIds = std::move(DefPhdrIds);
718
719 // Assign headers specified by linker script
720 for (size_t Id : PhdrIds) {
721 Ret[Id].add(Sec);
722 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
723 Ret[Id].H.p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000724 }
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000725 DefPhdrIds = std::move(PhdrIds);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000726 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000727 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000728}
729
Eugene Leviantf9bc3bd2016-08-16 06:40:58 +0000730template <class ELFT> bool LinkerScript<ELFT>::ignoreInterpSection() {
731 // Ignore .interp section in case we have PHDRS specification
732 // and PT_INTERP isn't listed.
733 return !Opt.PhdrsCommands.empty() &&
734 llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
735 return Cmd.Type == PT_INTERP;
736 }) == Opt.PhdrsCommands.end();
737}
738
Eugene Leviantbbe38602016-07-19 09:25:43 +0000739template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000740ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000741 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
742 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
743 if (Cmd->Name == Name)
744 return Cmd->Filler;
745 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000746}
747
George Rimare38cbab2016-09-26 19:22:50 +0000748template <class ELFT>
749static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) {
750 const endianness E = ELFT::TargetEndianness;
751
752 switch (Size) {
753 case 1:
754 *Buf = (uint8_t)Data;
755 break;
756 case 2:
757 write16<E>(Buf, Data);
758 break;
759 case 4:
760 write32<E>(Buf, Data);
761 break;
762 case 8:
763 write64<E>(Buf, Data);
764 break;
765 default:
766 llvm_unreachable("unsupported Size argument");
767 }
768}
769
770template <class ELFT>
771void LinkerScript<ELFT>::writeDataBytes(StringRef Name, uint8_t *Buf) {
772 int I = getSectionIndex(Name);
773 if (I == INT_MAX)
774 return;
775
776 OutputSectionCommand *Cmd =
777 dyn_cast<OutputSectionCommand>(Opt.Commands[I].get());
778 for (const std::unique_ptr<BaseCommand> &Base2 : Cmd->Commands)
779 if (auto *DataCmd = dyn_cast<BytesDataCommand>(Base2.get()))
780 writeInt<ELFT>(&Buf[DataCmd->Offset], DataCmd->Data, DataCmd->Size);
781}
782
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000783template <class ELFT> bool LinkerScript<ELFT>::hasLMA(StringRef Name) {
George Rimar8ceadb32016-08-17 07:44:19 +0000784 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
785 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000786 if (Cmd->LMAExpr && Cmd->Name == Name)
787 return true;
788 return false;
George Rimar8ceadb32016-08-17 07:44:19 +0000789}
790
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000791// Returns the index of the given section name in linker script
792// SECTIONS commands. Sections are laid out as the same order as they
793// were in the script. If a given name did not appear in the script,
794// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000795template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000796 int I = 0;
797 for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
798 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
799 if (Cmd->Name == Name)
800 return I;
801 ++I;
802 }
803 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000804}
805
Eugene Leviantbbe38602016-07-19 09:25:43 +0000806template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
807 return !Opt.PhdrsCommands.empty();
808}
809
George Rimar9e694502016-07-29 16:18:47 +0000810template <class ELFT>
George Rimar884e7862016-09-08 08:19:13 +0000811uint64_t LinkerScript<ELFT>::getOutputSectionAddress(StringRef Name) {
George Rimar96659df2016-08-30 09:54:01 +0000812 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
813 if (Sec->getName() == Name)
814 return Sec->getVA();
815 error("undefined section " + Name);
816 return 0;
817}
818
819template <class ELFT>
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000820uint64_t LinkerScript<ELFT>::getOutputSectionLMA(StringRef Name) {
821 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
822 if (Sec->getName() == Name)
823 return Sec->getLMA();
824 error("undefined section " + Name);
825 return 0;
826}
827
828template <class ELFT>
George Rimar884e7862016-09-08 08:19:13 +0000829uint64_t LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
George Rimar9e694502016-07-29 16:18:47 +0000830 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
831 if (Sec->getName() == Name)
832 return Sec->getSize();
833 error("undefined section " + Name);
834 return 0;
835}
836
Eugene Leviant36fac7f2016-09-08 09:08:30 +0000837template <class ELFT>
838uint64_t LinkerScript<ELFT>::getOutputSectionAlign(StringRef Name) {
839 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
840 if (Sec->getName() == Name)
841 return Sec->getAlignment();
842 error("undefined section " + Name);
843 return 0;
844}
845
George Rimar884e7862016-09-08 08:19:13 +0000846template <class ELFT> uint64_t LinkerScript<ELFT>::getHeaderSize() {
Rafael Espindola0d4b6d52016-09-22 16:47:21 +0000847 return elf::getHeaderSize<ELFT>();
George Rimare32a3592016-08-10 07:59:34 +0000848}
849
George Rimar884e7862016-09-08 08:19:13 +0000850template <class ELFT> uint64_t LinkerScript<ELFT>::getSymbolValue(StringRef S) {
851 if (SymbolBody *B = Symtab<ELFT>::X->find(S))
852 return B->getVA<ELFT>();
853 error("symbol not found: " + S);
854 return 0;
855}
856
George Rimarf34f45f2016-09-23 13:17:23 +0000857template <class ELFT> bool LinkerScript<ELFT>::isDefined(StringRef S) {
858 return Symtab<ELFT>::X->find(S) != nullptr;
859}
860
Eugene Leviantbbe38602016-07-19 09:25:43 +0000861// Returns indices of ELF headers containing specific section, identified
862// by Name. Each index is a zero based number of ELF header listed within
863// PHDRS {} script block.
864template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000865std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000866 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
867 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000868 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000869 continue;
870
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000871 std::vector<size_t> Ret;
872 for (StringRef PhdrName : Cmd->Phdrs)
873 Ret.push_back(getPhdrIndex(PhdrName));
874 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000875 }
George Rimar31d842f2016-07-20 16:43:03 +0000876 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000877}
878
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000879template <class ELFT>
880size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
881 size_t I = 0;
882 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
883 if (Cmd.Name == PhdrName)
884 return I;
885 ++I;
886 }
887 error("section header '" + PhdrName + "' is not listed in PHDRS");
888 return 0;
889}
890
Rui Ueyama07320e42016-04-20 20:13:41 +0000891class elf::ScriptParser : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000892 typedef void (ScriptParser::*Handler)();
893
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000894public:
Rui Ueyama07320e42016-04-20 20:13:41 +0000895 ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
George Rimarf23b2322016-02-19 10:45:45 +0000896
George Rimar20b65982016-08-31 09:08:26 +0000897 void readLinkerScript();
898 void readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000899
900private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000901 void addFile(StringRef Path);
902
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000903 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000904 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000905 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000906 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000907 void readInclude();
Rui Ueyamaee592822015-10-07 00:25:09 +0000908 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000909 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000910 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000911 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000912 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000913 void readSections();
Rui Ueyama95769b42016-08-31 20:03:54 +0000914 void readVersion();
915 void readVersionScriptCommand();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000916
Rui Ueyama113cdec2016-07-24 23:05:57 +0000917 SymbolAssignment *readAssignment(StringRef Name);
George Rimare38cbab2016-09-26 19:22:50 +0000918 BytesDataCommand *readBytesDataCommand(StringRef Tok);
George Rimarff1f29e2016-09-06 13:51:57 +0000919 std::vector<uint8_t> readFill();
Rui Ueyama10416562016-08-04 02:03:27 +0000920 OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
George Rimarff1f29e2016-09-06 13:51:57 +0000921 std::vector<uint8_t> readOutputSectionFiller(StringRef Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000922 std::vector<StringRef> readOutputSectionPhdrs();
George Rimara2496cb2016-08-30 09:46:59 +0000923 InputSectionDescription *readInputSectionDescription(StringRef Tok);
George Rimarc91930a2016-09-02 21:17:20 +0000924 Regex readFilePatterns();
George Rimar07171f22016-09-21 15:56:44 +0000925 std::vector<SectionPattern> readInputSectionsList();
George Rimara2496cb2016-08-30 09:46:59 +0000926 InputSectionDescription *readInputSectionRules(StringRef FilePattern);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000927 unsigned readPhdrType();
George Rimarbe394db2016-09-16 20:21:55 +0000928 SortSectionPolicy readSortKind();
Petr Hoseka35e39c2016-08-16 01:11:16 +0000929 SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
Eugene Leviantdb741e72016-09-07 07:08:43 +0000930 SymbolAssignment *readProvideOrAssignment(StringRef Tok, bool MakeAbsolute);
George Rimar03fc0102016-07-28 07:18:23 +0000931 void readSort();
George Rimareefa7582016-08-04 09:29:31 +0000932 Expr readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +0000933
934 Expr readExpr();
935 Expr readExpr1(Expr Lhs, int MinPrec);
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000936 StringRef readParenLiteral();
Rui Ueyama708019c2016-07-24 18:19:40 +0000937 Expr readPrimary();
938 Expr readTernary(Expr Cond);
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +0000939 Expr readParenExpr();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000940
George Rimar20b65982016-08-31 09:08:26 +0000941 // For parsing version script.
942 void readExtern(std::vector<SymbolVersion> *Globals);
Rui Ueyama95769b42016-08-31 20:03:54 +0000943 void readVersionDeclaration(StringRef VerStr);
George Rimar20b65982016-08-31 09:08:26 +0000944 void readGlobal(StringRef VerStr);
945 void readLocal();
946
Rui Ueyama07320e42016-04-20 20:13:41 +0000947 ScriptConfiguration &Opt = *ScriptConfig;
948 StringSaver Saver = {ScriptConfig->Alloc};
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000949 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000950};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000951
George Rimar20b65982016-08-31 09:08:26 +0000952void ScriptParser::readVersionScript() {
Rui Ueyama95769b42016-08-31 20:03:54 +0000953 readVersionScriptCommand();
954 if (!atEOF())
955 setError("EOF expected, but got " + next());
956}
957
958void ScriptParser::readVersionScriptCommand() {
Rui Ueyama83043f22016-10-17 16:01:53 +0000959 if (consume("{")) {
Rui Ueyama95769b42016-08-31 20:03:54 +0000960 readVersionDeclaration("");
George Rimar20b65982016-08-31 09:08:26 +0000961 return;
962 }
963
Rui Ueyama95769b42016-08-31 20:03:54 +0000964 while (!atEOF() && !Error && peek() != "}") {
George Rimar20b65982016-08-31 09:08:26 +0000965 StringRef VerStr = next();
966 if (VerStr == "{") {
Rui Ueyama95769b42016-08-31 20:03:54 +0000967 setError("anonymous version definition is used in "
968 "combination with other version definitions");
George Rimar20b65982016-08-31 09:08:26 +0000969 return;
970 }
971 expect("{");
Rui Ueyama95769b42016-08-31 20:03:54 +0000972 readVersionDeclaration(VerStr);
George Rimar20b65982016-08-31 09:08:26 +0000973 }
974}
975
Rui Ueyama95769b42016-08-31 20:03:54 +0000976void ScriptParser::readVersion() {
977 expect("{");
978 readVersionScriptCommand();
979 expect("}");
980}
981
George Rimar20b65982016-08-31 09:08:26 +0000982void ScriptParser::readLinkerScript() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000983 while (!atEOF()) {
984 StringRef Tok = next();
Rui Ueyamaa27eecc2016-09-02 18:52:41 +0000985 if (Tok == ";")
986 continue;
987
Eugene Leviant20d03192016-09-16 15:30:47 +0000988 if (Tok == "ASSERT") {
989 Opt.Commands.emplace_back(new AssertCommand(readAssert()));
990 } else if (Tok == "ENTRY") {
Rui Ueyamaa27eecc2016-09-02 18:52:41 +0000991 readEntry();
992 } else if (Tok == "EXTERN") {
993 readExtern();
994 } else if (Tok == "GROUP" || Tok == "INPUT") {
995 readGroup();
996 } else if (Tok == "INCLUDE") {
997 readInclude();
998 } else if (Tok == "OUTPUT") {
999 readOutput();
1000 } else if (Tok == "OUTPUT_ARCH") {
1001 readOutputArch();
1002 } else if (Tok == "OUTPUT_FORMAT") {
1003 readOutputFormat();
1004 } else if (Tok == "PHDRS") {
1005 readPhdrs();
1006 } else if (Tok == "SEARCH_DIR") {
1007 readSearchDir();
1008 } else if (Tok == "SECTIONS") {
1009 readSections();
1010 } else if (Tok == "VERSION") {
1011 readVersion();
Eugene Leviantdb741e72016-09-07 07:08:43 +00001012 } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok, true)) {
Eugene Leviant20d03192016-09-16 15:30:47 +00001013 Opt.Commands.emplace_back(Cmd);
Petr Hoseke5d3ca52016-08-31 15:31:17 +00001014 } else {
George Rimar57610422016-03-11 14:43:02 +00001015 setError("unknown directive: " + Tok);
Petr Hoseke5d3ca52016-08-31 15:31:17 +00001016 }
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001017 }
1018}
1019
Rui Ueyama717677a2016-02-11 21:17:59 +00001020void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001021 if (IsUnderSysroot && S.startswith("/")) {
Justin Bogner5af16872016-10-17 06:08:48 +00001022 SmallString<128> PathData;
1023 StringRef Path = (Config->Sysroot + S).toStringRef(PathData);
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001024 if (sys::fs::exists(Path)) {
Justin Bogner5af16872016-10-17 06:08:48 +00001025 Driver->addFile(Saver.save(Path));
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001026 return;
1027 }
1028 }
1029
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +00001030 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +00001031 Driver->addFile(S);
1032 } else if (S.startswith("=")) {
1033 if (Config->Sysroot.empty())
1034 Driver->addFile(S.substr(1));
1035 else
1036 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
1037 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +00001038 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +00001039 } else if (sys::fs::exists(S)) {
1040 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +00001041 } else {
1042 std::string Path = findFromSearchPaths(S);
1043 if (Path.empty())
George Rimar777f9632016-03-12 08:31:34 +00001044 setError("unable to find " + S);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001045 else
1046 Driver->addFile(Saver.save(Path));
Rui Ueyama52a15092015-10-11 03:28:42 +00001047 }
1048}
1049
Rui Ueyama717677a2016-02-11 21:17:59 +00001050void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001051 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +00001052 bool Orig = Config->AsNeeded;
1053 Config->AsNeeded = true;
Rui Ueyama83043f22016-10-17 16:01:53 +00001054 while (!Error && !consume(")"))
George Rimarcd574a52016-09-09 14:35:36 +00001055 addFile(unquote(next()));
Rui Ueyama35da9b62015-10-11 20:59:12 +00001056 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001057}
1058
Rui Ueyama717677a2016-02-11 21:17:59 +00001059void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +00001060 // -e <symbol> takes predecence over ENTRY(<symbol>).
1061 expect("(");
1062 StringRef Tok = next();
1063 if (Config->Entry.empty())
1064 Config->Entry = Tok;
1065 expect(")");
1066}
1067
Rui Ueyama717677a2016-02-11 21:17:59 +00001068void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +00001069 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001070 while (!Error && !consume(")"))
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001071 Config->Undefined.push_back(next());
George Rimar83f406c2015-10-19 17:35:12 +00001072}
1073
Rui Ueyama717677a2016-02-11 21:17:59 +00001074void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001075 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001076 while (!Error && !consume(")")) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001077 StringRef Tok = next();
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001078 if (Tok == "AS_NEEDED")
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001079 readAsNeeded();
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001080 else
George Rimarcd574a52016-09-09 14:35:36 +00001081 addFile(unquote(Tok));
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001082 }
1083}
1084
Rui Ueyama717677a2016-02-11 21:17:59 +00001085void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001086 StringRef Tok = next();
George Rimarcd574a52016-09-09 14:35:36 +00001087 auto MBOrErr = MemoryBuffer::getFile(unquote(Tok));
Rui Ueyama025d59b2016-02-02 20:27:59 +00001088 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +00001089 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001090 return;
1091 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001092 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Rui Ueyamaa47ee682015-10-11 01:53:04 +00001093 StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
1094 std::vector<StringRef> V = tokenize(S);
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001095 Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001096}
1097
Rui Ueyama717677a2016-02-11 21:17:59 +00001098void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +00001099 // -o <file> takes predecence over OUTPUT(<file>).
1100 expect("(");
1101 StringRef Tok = next();
1102 if (Config->OutputFile.empty())
George Rimarcd574a52016-09-09 14:35:36 +00001103 Config->OutputFile = unquote(Tok);
Rui Ueyamaee592822015-10-07 00:25:09 +00001104 expect(")");
1105}
1106
Rui Ueyama717677a2016-02-11 21:17:59 +00001107void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +00001108 // Error checking only for now.
1109 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001110 skip();
Davide Italiano9159ce92015-10-12 21:50:08 +00001111 expect(")");
1112}
1113
Rui Ueyama717677a2016-02-11 21:17:59 +00001114void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001115 // Error checking only for now.
1116 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001117 skip();
Davide Italiano6836c612015-10-12 21:08:41 +00001118 StringRef Tok = next();
1119 if (Tok == ")")
George Rimar6c55f0e2016-09-08 08:20:30 +00001120 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +00001121 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +00001122 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001123 return;
1124 }
Justin Bogner5424e7c2016-10-17 06:21:13 +00001125 skip();
Davide Italiano6836c612015-10-12 21:08:41 +00001126 expect(",");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001127 skip();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001128 expect(")");
1129}
1130
Eugene Leviantbbe38602016-07-19 09:25:43 +00001131void ScriptParser::readPhdrs() {
1132 expect("{");
Rui Ueyama83043f22016-10-17 16:01:53 +00001133 while (!Error && !consume("}")) {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001134 StringRef Tok = next();
Eugene Leviant56b21c82016-09-09 09:46:16 +00001135 Opt.PhdrsCommands.push_back(
1136 {Tok, PT_NULL, false, false, UINT_MAX, nullptr});
Eugene Leviantbbe38602016-07-19 09:25:43 +00001137 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
1138
1139 PhdrCmd.Type = readPhdrType();
1140 do {
1141 Tok = next();
1142 if (Tok == ";")
1143 break;
1144 if (Tok == "FILEHDR")
1145 PhdrCmd.HasFilehdr = true;
1146 else if (Tok == "PHDRS")
1147 PhdrCmd.HasPhdrs = true;
Eugene Leviant56b21c82016-09-09 09:46:16 +00001148 else if (Tok == "AT")
1149 PhdrCmd.LMAExpr = readParenExpr();
Eugene Leviant865bf862016-07-21 10:43:25 +00001150 else if (Tok == "FLAGS") {
1151 expect("(");
Rafael Espindolaeb685cd2016-08-02 22:14:57 +00001152 // Passing 0 for the value of dot is a bit of a hack. It means that
1153 // we accept expressions like ".|1".
1154 PhdrCmd.Flags = readExpr()(0);
Eugene Leviant865bf862016-07-21 10:43:25 +00001155 expect(")");
1156 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +00001157 setError("unexpected header attribute: " + Tok);
1158 } while (!Error);
1159 }
1160}
1161
Rui Ueyama717677a2016-02-11 21:17:59 +00001162void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +00001163 expect("(");
Rui Ueyama86c5fb82016-09-08 23:26:54 +00001164 StringRef Tok = next();
Rui Ueyama6c7ad132016-09-02 19:20:33 +00001165 if (!Config->Nostdlib)
George Rimarcd574a52016-09-09 14:35:36 +00001166 Config->SearchPaths.push_back(unquote(Tok));
Davide Italiano68a39a62015-10-08 17:51:41 +00001167 expect(")");
1168}
1169
Rui Ueyama717677a2016-02-11 21:17:59 +00001170void ScriptParser::readSections() {
Eugene Leviante05336ff2016-09-14 08:32:36 +00001171 Opt.HasSections = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001172 expect("{");
Rui Ueyama83043f22016-10-17 16:01:53 +00001173 while (!Error && !consume("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +00001174 StringRef Tok = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +00001175 BaseCommand *Cmd = readProvideOrAssignment(Tok, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001176 if (!Cmd) {
1177 if (Tok == "ASSERT")
1178 Cmd = new AssertCommand(readAssert());
1179 else
1180 Cmd = readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +00001181 }
Rui Ueyama10416562016-08-04 02:03:27 +00001182 Opt.Commands.emplace_back(Cmd);
George Rimar652852c2016-04-16 10:10:32 +00001183 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001184}
1185
Rui Ueyama708019c2016-07-24 18:19:40 +00001186static int precedence(StringRef Op) {
1187 return StringSwitch<int>(Op)
Rui Ueyama0120e3f2016-09-23 18:06:51 +00001188 .Cases("*", "/", 5)
1189 .Cases("+", "-", 4)
1190 .Cases("<<", ">>", 3)
Rui Ueyama9c4ac5f2016-09-23 22:22:34 +00001191 .Cases("<", "<=", ">", ">=", "==", "!=", 2)
Rui Ueyama0120e3f2016-09-23 18:06:51 +00001192 .Cases("&", "|", 1)
Rui Ueyama708019c2016-07-24 18:19:40 +00001193 .Default(-1);
1194}
1195
George Rimarc91930a2016-09-02 21:17:20 +00001196Regex ScriptParser::readFilePatterns() {
Rui Ueyama10416562016-08-04 02:03:27 +00001197 std::vector<StringRef> V;
Rui Ueyama83043f22016-10-17 16:01:53 +00001198 while (!Error && !consume(")"))
Rui Ueyama10416562016-08-04 02:03:27 +00001199 V.push_back(next());
George Rimarc91930a2016-09-02 21:17:20 +00001200 return compileGlobPatterns(V);
George Rimar0702c4e2016-07-29 15:32:46 +00001201}
1202
George Rimarbe394db2016-09-16 20:21:55 +00001203SortSectionPolicy ScriptParser::readSortKind() {
Rui Ueyama83043f22016-10-17 16:01:53 +00001204 if (consume("SORT") || consume("SORT_BY_NAME"))
George Rimarbe394db2016-09-16 20:21:55 +00001205 return SortSectionPolicy::Name;
Rui Ueyama83043f22016-10-17 16:01:53 +00001206 if (consume("SORT_BY_ALIGNMENT"))
George Rimarbe394db2016-09-16 20:21:55 +00001207 return SortSectionPolicy::Alignment;
Rui Ueyama83043f22016-10-17 16:01:53 +00001208 if (consume("SORT_BY_INIT_PRIORITY"))
George Rimarbe394db2016-09-16 20:21:55 +00001209 return SortSectionPolicy::Priority;
Rui Ueyama83043f22016-10-17 16:01:53 +00001210 if (consume("SORT_NONE"))
Rui Ueyamab2a0abd2016-09-16 21:14:55 +00001211 return SortSectionPolicy::None;
1212 return SortSectionPolicy::Default;
George Rimarbe394db2016-09-16 20:21:55 +00001213}
1214
George Rimar395281c2016-09-16 17:42:10 +00001215// Method reads a list of sequence of excluded files and section globs given in
1216// a following form: ((EXCLUDE_FILE(file_pattern+))? section_pattern+)+
1217// Example: *(.foo.1 EXCLUDE_FILE (*a.o) .foo.2 EXCLUDE_FILE (*b.o) .foo.3)
George Rimaraf03be12016-09-17 19:17:25 +00001218// The semantics of that is next:
1219// * Include .foo.1 from every file.
1220// * Include .foo.2 from every file but a.o
1221// * Include .foo.3 from every file but b.o
George Rimar07171f22016-09-21 15:56:44 +00001222std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
1223 std::vector<SectionPattern> Ret;
George Rimar601e9892016-09-21 08:53:21 +00001224 while (!Error && peek() != ")") {
1225 Regex ExcludeFileRe;
Rui Ueyama83043f22016-10-17 16:01:53 +00001226 if (consume("EXCLUDE_FILE")) {
George Rimar395281c2016-09-16 17:42:10 +00001227 expect("(");
1228 ExcludeFileRe = readFilePatterns();
George Rimar395281c2016-09-16 17:42:10 +00001229 }
1230
George Rimar601e9892016-09-21 08:53:21 +00001231 std::vector<StringRef> V;
1232 while (!Error && peek() != ")" && peek() != "EXCLUDE_FILE")
1233 V.push_back(next());
1234
1235 if (!V.empty())
George Rimar07171f22016-09-21 15:56:44 +00001236 Ret.push_back({std::move(ExcludeFileRe), compileGlobPatterns(V)});
George Rimar601e9892016-09-21 08:53:21 +00001237 else
1238 setError("section pattern is expected");
George Rimar395281c2016-09-16 17:42:10 +00001239 }
George Rimar07171f22016-09-21 15:56:44 +00001240 return Ret;
George Rimar395281c2016-09-16 17:42:10 +00001241}
1242
George Rimar07171f22016-09-21 15:56:44 +00001243// Section pattern grammar can have complex expressions, for example:
1244// *(SORT(.foo.* EXCLUDE_FILE (*file1.o) .bar.*) .bar.* SORT(.zed.*))
1245// Generally is a sequence of globs and excludes that may be wrapped in a SORT()
1246// commands, like: SORT(glob0) glob1 glob2 SORT(glob4)
1247// This methods handles wrapping sequences of excluded files and section globs
1248// into SORT() if that needed and reads them all.
George Rimara2496cb2016-08-30 09:46:59 +00001249InputSectionDescription *
1250ScriptParser::readInputSectionRules(StringRef FilePattern) {
George Rimarc91930a2016-09-02 21:17:20 +00001251 auto *Cmd = new InputSectionDescription(FilePattern);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001252 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001253 while (!HasError && !consume(")")) {
George Rimar07171f22016-09-21 15:56:44 +00001254 SortSectionPolicy Outer = readSortKind();
1255 SortSectionPolicy Inner = SortSectionPolicy::Default;
1256 std::vector<SectionPattern> V;
1257 if (Outer != SortSectionPolicy::Default) {
George Rimar350ece42016-08-03 08:35:59 +00001258 expect("(");
George Rimar07171f22016-09-21 15:56:44 +00001259 Inner = readSortKind();
1260 if (Inner != SortSectionPolicy::Default) {
1261 expect("(");
1262 V = readInputSectionsList();
1263 expect(")");
1264 } else {
1265 V = readInputSectionsList();
1266 }
George Rimar350ece42016-08-03 08:35:59 +00001267 expect(")");
1268 } else {
George Rimar07171f22016-09-21 15:56:44 +00001269 V = readInputSectionsList();
George Rimar350ece42016-08-03 08:35:59 +00001270 }
George Rimar0702c4e2016-07-29 15:32:46 +00001271
George Rimar07171f22016-09-21 15:56:44 +00001272 for (SectionPattern &Pat : V) {
1273 Pat.SortInner = Inner;
1274 Pat.SortOuter = Outer;
1275 }
1276
1277 std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns));
1278 }
Rui Ueyama10416562016-08-04 02:03:27 +00001279 return Cmd;
Davide Italianoe7282792016-07-27 01:44:01 +00001280}
1281
George Rimara2496cb2016-08-30 09:46:59 +00001282InputSectionDescription *
1283ScriptParser::readInputSectionDescription(StringRef Tok) {
George Rimar06598002016-07-28 21:51:30 +00001284 // Input section wildcard can be surrounded by KEEP.
1285 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
George Rimara2496cb2016-08-30 09:46:59 +00001286 if (Tok == "KEEP") {
George Rimar06598002016-07-28 21:51:30 +00001287 expect("(");
George Rimara2496cb2016-08-30 09:46:59 +00001288 StringRef FilePattern = next();
1289 InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
George Rimar06598002016-07-28 21:51:30 +00001290 expect(")");
Eugene Leviantcf43f172016-10-05 09:36:59 +00001291 Opt.KeptSections.push_back(Cmd);
Rui Ueyama10416562016-08-04 02:03:27 +00001292 return Cmd;
George Rimar06598002016-07-28 21:51:30 +00001293 }
George Rimara2496cb2016-08-30 09:46:59 +00001294 return readInputSectionRules(Tok);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001295}
1296
George Rimar03fc0102016-07-28 07:18:23 +00001297void ScriptParser::readSort() {
1298 expect("(");
1299 expect("CONSTRUCTORS");
1300 expect(")");
1301}
1302
George Rimareefa7582016-08-04 09:29:31 +00001303Expr ScriptParser::readAssert() {
1304 expect("(");
1305 Expr E = readExpr();
1306 expect(",");
George Rimarcd574a52016-09-09 14:35:36 +00001307 StringRef Msg = unquote(next());
George Rimareefa7582016-08-04 09:29:31 +00001308 expect(")");
1309 return [=](uint64_t Dot) {
1310 uint64_t V = E(Dot);
1311 if (!V)
1312 error(Msg);
1313 return V;
1314 };
1315}
1316
Rui Ueyama25150e82016-09-06 17:46:43 +00001317// Reads a FILL(expr) command. We handle the FILL command as an
1318// alias for =fillexp section attribute, which is different from
1319// what GNU linkers do.
1320// https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
George Rimarff1f29e2016-09-06 13:51:57 +00001321std::vector<uint8_t> ScriptParser::readFill() {
1322 expect("(");
1323 std::vector<uint8_t> V = readOutputSectionFiller(next());
1324 expect(")");
1325 expect(";");
1326 return V;
1327}
1328
Rui Ueyama10416562016-08-04 02:03:27 +00001329OutputSectionCommand *
1330ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +00001331 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
George Rimar58e5c4d2016-07-25 08:29:46 +00001332
1333 // Read an address expression.
1334 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
1335 if (peek() != ":")
1336 Cmd->AddrExpr = readExpr();
1337
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001338 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +00001339
Rui Ueyama83043f22016-10-17 16:01:53 +00001340 if (consume("AT"))
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001341 Cmd->LMAExpr = readParenExpr();
Rui Ueyama83043f22016-10-17 16:01:53 +00001342 if (consume("ALIGN"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001343 Cmd->AlignExpr = readParenExpr();
Rui Ueyama83043f22016-10-17 16:01:53 +00001344 if (consume("SUBALIGN"))
George Rimardb24d9c2016-08-19 15:18:23 +00001345 Cmd->SubalignExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001346
Davide Italiano246f6812016-07-22 03:36:24 +00001347 // Parse constraints.
Rui Ueyama83043f22016-10-17 16:01:53 +00001348 if (consume("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001349 Cmd->Constraint = ConstraintKind::ReadOnly;
Rui Ueyama83043f22016-10-17 16:01:53 +00001350 if (consume("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001351 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001352 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001353
Rui Ueyama83043f22016-10-17 16:01:53 +00001354 while (!Error && !consume("}")) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001355 StringRef Tok = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +00001356 if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok, false))
Eugene Leviantceabe802016-08-11 07:56:43 +00001357 Cmd->Commands.emplace_back(Assignment);
George Rimare38cbab2016-09-26 19:22:50 +00001358 else if (BytesDataCommand *Data = readBytesDataCommand(Tok))
1359 Cmd->Commands.emplace_back(Data);
George Rimarff1f29e2016-09-06 13:51:57 +00001360 else if (Tok == "FILL")
1361 Cmd->Filler = readFill();
Eugene Leviantceabe802016-08-11 07:56:43 +00001362 else if (Tok == "SORT")
George Rimar03fc0102016-07-28 07:18:23 +00001363 readSort();
George Rimara2496cb2016-08-30 09:46:59 +00001364 else if (peek() == "(")
1365 Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
Eugene Leviantceabe802016-08-11 07:56:43 +00001366 else
1367 setError("unknown command " + Tok);
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001368 }
George Rimar076fe152016-07-21 06:43:01 +00001369 Cmd->Phdrs = readOutputSectionPhdrs();
George Rimar4ebc5622016-09-23 13:29:20 +00001370
Rui Ueyama83043f22016-10-17 16:01:53 +00001371 if (consume("="))
George Rimar4ebc5622016-09-23 13:29:20 +00001372 Cmd->Filler = readOutputSectionFiller(next());
1373 else if (peek().startswith("="))
George Rimarff1f29e2016-09-06 13:51:57 +00001374 Cmd->Filler = readOutputSectionFiller(next().drop_front());
George Rimar4ebc5622016-09-23 13:29:20 +00001375
Rui Ueyama10416562016-08-04 02:03:27 +00001376 return Cmd;
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001377}
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001378
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001379// Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
1380// https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
1381//
1382// ld.gold is not fully compatible with ld.bfd. ld.bfd handles
1383// hexstrings as blobs of arbitrary sizes, while ld.gold handles them
1384// as 32-bit big-endian values. We will do the same as ld.gold does
1385// because it's simpler than what ld.bfd does.
George Rimarff1f29e2016-09-06 13:51:57 +00001386std::vector<uint8_t> ScriptParser::readOutputSectionFiller(StringRef Tok) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001387 uint32_t V;
George Rimarff1f29e2016-09-06 13:51:57 +00001388 if (Tok.getAsInteger(0, V)) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001389 setError("invalid filler expression: " + Tok);
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001390 return {};
George Rimare2ee72b2016-02-26 14:48:31 +00001391 }
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001392 return {uint8_t(V >> 24), uint8_t(V >> 16), uint8_t(V >> 8), uint8_t(V)};
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001393}
1394
Petr Hoseka35e39c2016-08-16 01:11:16 +00001395SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
Eugene Levianta31c91b2016-07-22 07:38:40 +00001396 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +00001397 SymbolAssignment *Cmd = readAssignment(next());
Petr Hoseka35e39c2016-08-16 01:11:16 +00001398 Cmd->Provide = Provide;
Rui Ueyama174e0a12016-07-29 00:29:25 +00001399 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001400 expect(")");
1401 expect(";");
Rui Ueyama10416562016-08-04 02:03:27 +00001402 return Cmd;
Eugene Levianteda81a12016-07-12 06:39:48 +00001403}
1404
Eugene Leviantdb741e72016-09-07 07:08:43 +00001405SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok,
1406 bool MakeAbsolute) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001407 SymbolAssignment *Cmd = nullptr;
1408 if (peek() == "=" || peek() == "+=") {
1409 Cmd = readAssignment(Tok);
1410 expect(";");
1411 } else if (Tok == "PROVIDE") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001412 Cmd = readProvideHidden(true, false);
1413 } else if (Tok == "HIDDEN") {
1414 Cmd = readProvideHidden(false, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001415 } else if (Tok == "PROVIDE_HIDDEN") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001416 Cmd = readProvideHidden(true, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001417 }
Eugene Leviantdb741e72016-09-07 07:08:43 +00001418 if (Cmd && MakeAbsolute)
1419 Cmd->IsAbsolute = true;
Eugene Leviantceabe802016-08-11 07:56:43 +00001420 return Cmd;
1421}
1422
George Rimar30835ea2016-07-28 21:08:56 +00001423static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
1424 if (S == ".")
1425 return Dot;
George Rimar884e7862016-09-08 08:19:13 +00001426 return ScriptBase->getSymbolValue(S);
George Rimare32a3592016-08-10 07:59:34 +00001427}
1428
George Rimar30835ea2016-07-28 21:08:56 +00001429SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1430 StringRef Op = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +00001431 bool IsAbsolute = false;
1432 Expr E;
George Rimar30835ea2016-07-28 21:08:56 +00001433 assert(Op == "=" || Op == "+=");
Rui Ueyama83043f22016-10-17 16:01:53 +00001434 if (consume("ABSOLUTE")) {
Rui Ueyama7c1381a2016-10-19 23:11:21 +00001435 // The RHS may be something like "ABSOLUTE(.) & 0xff".
1436 // Call readExpr1 to read the whole expression.
1437 E = readExpr1(readParenExpr(), 0);
Eugene Leviantdb741e72016-09-07 07:08:43 +00001438 IsAbsolute = true;
1439 } else {
1440 E = readExpr();
1441 }
George Rimar30835ea2016-07-28 21:08:56 +00001442 if (Op == "+=")
1443 E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
Eugene Leviantdb741e72016-09-07 07:08:43 +00001444 return new SymbolAssignment(Name, E, IsAbsolute);
George Rimar30835ea2016-07-28 21:08:56 +00001445}
1446
1447// This is an operator-precedence parser to parse a linker
1448// script expression.
1449Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
1450
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001451static Expr combine(StringRef Op, Expr L, Expr R) {
1452 if (Op == "*")
1453 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1454 if (Op == "/") {
1455 return [=](uint64_t Dot) -> uint64_t {
1456 uint64_t RHS = R(Dot);
1457 if (RHS == 0) {
1458 error("division by zero");
1459 return 0;
1460 }
1461 return L(Dot) / RHS;
1462 };
1463 }
1464 if (Op == "+")
1465 return [=](uint64_t Dot) { return L(Dot) + R(Dot); };
1466 if (Op == "-")
1467 return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
George Rimarc8ccd1f2016-09-23 13:13:55 +00001468 if (Op == "<<")
1469 return [=](uint64_t Dot) { return L(Dot) << R(Dot); };
1470 if (Op == ">>")
1471 return [=](uint64_t Dot) { return L(Dot) >> R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001472 if (Op == "<")
1473 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
1474 if (Op == ">")
1475 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
1476 if (Op == ">=")
1477 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
1478 if (Op == "<=")
1479 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
1480 if (Op == "==")
1481 return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
1482 if (Op == "!=")
1483 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
1484 if (Op == "&")
1485 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
Rafael Espindolacc3dd622016-08-22 21:33:35 +00001486 if (Op == "|")
1487 return [=](uint64_t Dot) { return L(Dot) | R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001488 llvm_unreachable("invalid operator");
1489}
1490
Rui Ueyama708019c2016-07-24 18:19:40 +00001491// This is a part of the operator-precedence parser. This function
1492// assumes that the remaining token stream starts with an operator.
1493Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1494 while (!atEOF() && !Error) {
1495 // Read an operator and an expression.
1496 StringRef Op1 = peek();
1497 if (Op1 == "?")
1498 return readTernary(Lhs);
1499 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +00001500 break;
Justin Bogner5424e7c2016-10-17 06:21:13 +00001501 skip();
Rui Ueyama708019c2016-07-24 18:19:40 +00001502 Expr Rhs = readPrimary();
1503
1504 // Evaluate the remaining part of the expression first if the
1505 // next operator has greater precedence than the previous one.
1506 // For example, if we have read "+" and "3", and if the next
1507 // operator is "*", then we'll evaluate 3 * ... part first.
1508 while (!atEOF()) {
1509 StringRef Op2 = peek();
1510 if (precedence(Op2) <= precedence(Op1))
1511 break;
1512 Rhs = readExpr1(Rhs, precedence(Op2));
1513 }
1514
1515 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +00001516 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001517 return Lhs;
1518}
1519
1520uint64_t static getConstant(StringRef S) {
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001521 if (S == "COMMONPAGESIZE")
Rui Ueyama708019c2016-07-24 18:19:40 +00001522 return Target->PageSize;
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001523 if (S == "MAXPAGESIZE")
Petr Hosek997f8832016-09-28 15:20:47 +00001524 return Config->MaxPageSize;
Rui Ueyama708019c2016-07-24 18:19:40 +00001525 error("unknown constant: " + S);
1526 return 0;
1527}
1528
Rui Ueyama626e0b02016-09-02 18:19:00 +00001529// Parses Tok as an integer. Returns true if successful.
1530// It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1531// and decimal numbers. Decimal numbers may have "K" (kilo) or
1532// "M" (mega) prefixes.
George Rimar9f2f7ad2016-09-02 16:01:42 +00001533static bool readInteger(StringRef Tok, uint64_t &Result) {
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001534 if (Tok.startswith("-")) {
1535 if (!readInteger(Tok.substr(1), Result))
1536 return false;
1537 Result = -Result;
1538 return true;
1539 }
George Rimar9f2f7ad2016-09-02 16:01:42 +00001540 if (Tok.startswith_lower("0x"))
1541 return !Tok.substr(2).getAsInteger(16, Result);
1542 if (Tok.endswith_lower("H"))
1543 return !Tok.drop_back().getAsInteger(16, Result);
1544
1545 int Suffix = 1;
1546 if (Tok.endswith_lower("K")) {
1547 Suffix = 1024;
1548 Tok = Tok.drop_back();
1549 } else if (Tok.endswith_lower("M")) {
1550 Suffix = 1024 * 1024;
1551 Tok = Tok.drop_back();
1552 }
1553 if (Tok.getAsInteger(10, Result))
1554 return false;
1555 Result *= Suffix;
1556 return true;
1557}
1558
George Rimare38cbab2016-09-26 19:22:50 +00001559BytesDataCommand *ScriptParser::readBytesDataCommand(StringRef Tok) {
1560 int Size = StringSwitch<unsigned>(Tok)
1561 .Case("BYTE", 1)
1562 .Case("SHORT", 2)
1563 .Case("LONG", 4)
1564 .Case("QUAD", 8)
1565 .Default(-1);
1566 if (Size == -1)
1567 return nullptr;
1568
1569 expect("(");
1570 uint64_t Val = 0;
1571 StringRef S = next();
1572 if (!readInteger(S, Val))
1573 setError("unexpected value: " + S);
1574 expect(")");
1575 return new BytesDataCommand(Val, Size);
1576}
1577
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001578StringRef ScriptParser::readParenLiteral() {
1579 expect("(");
1580 StringRef Tok = next();
1581 expect(")");
1582 return Tok;
1583}
1584
Rui Ueyama708019c2016-07-24 18:19:40 +00001585Expr ScriptParser::readPrimary() {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001586 if (peek() == "(")
1587 return readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001588
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001589 StringRef Tok = next();
Rui Ueyama708019c2016-07-24 18:19:40 +00001590
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001591 if (Tok == "~") {
1592 Expr E = readPrimary();
1593 return [=](uint64_t Dot) { return ~E(Dot); };
1594 }
1595 if (Tok == "-") {
1596 Expr E = readPrimary();
1597 return [=](uint64_t Dot) { return -E(Dot); };
1598 }
1599
Rui Ueyama708019c2016-07-24 18:19:40 +00001600 // Built-in functions are parsed here.
1601 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
George Rimar96659df2016-08-30 09:54:01 +00001602 if (Tok == "ADDR") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001603 StringRef Name = readParenLiteral();
George Rimar884e7862016-09-08 08:19:13 +00001604 return
1605 [=](uint64_t Dot) { return ScriptBase->getOutputSectionAddress(Name); };
George Rimar96659df2016-08-30 09:54:01 +00001606 }
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001607 if (Tok == "LOADADDR") {
1608 StringRef Name = readParenLiteral();
1609 return [=](uint64_t Dot) { return ScriptBase->getOutputSectionLMA(Name); };
1610 }
George Rimareefa7582016-08-04 09:29:31 +00001611 if (Tok == "ASSERT")
1612 return readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001613 if (Tok == "ALIGN") {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001614 Expr E = readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001615 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1616 }
1617 if (Tok == "CONSTANT") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001618 StringRef Name = readParenLiteral();
1619 return [=](uint64_t Dot) { return getConstant(Name); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001620 }
George Rimarf34f45f2016-09-23 13:17:23 +00001621 if (Tok == "DEFINED") {
1622 expect("(");
1623 StringRef Tok = next();
1624 expect(")");
George Rimarf2821022016-09-26 11:00:48 +00001625 return [=](uint64_t Dot) { return ScriptBase->isDefined(Tok) ? 1 : 0; };
George Rimarf34f45f2016-09-23 13:17:23 +00001626 }
Rafael Espindola54c145c2016-07-28 18:16:24 +00001627 if (Tok == "SEGMENT_START") {
1628 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001629 skip();
Rafael Espindola54c145c2016-07-28 18:16:24 +00001630 expect(",");
George Rimar8c658bf2016-09-17 18:14:56 +00001631 Expr E = readExpr();
Rafael Espindola54c145c2016-07-28 18:16:24 +00001632 expect(")");
George Rimar8c658bf2016-09-17 18:14:56 +00001633 return [=](uint64_t Dot) { return E(Dot); };
Rafael Espindola54c145c2016-07-28 18:16:24 +00001634 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001635 if (Tok == "DATA_SEGMENT_ALIGN") {
1636 expect("(");
1637 Expr E = readExpr();
1638 expect(",");
1639 readExpr();
1640 expect(")");
Rui Ueyamaf7791bb2016-07-26 19:34:10 +00001641 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001642 }
1643 if (Tok == "DATA_SEGMENT_END") {
1644 expect("(");
1645 expect(".");
1646 expect(")");
1647 return [](uint64_t Dot) { return Dot; };
1648 }
George Rimar276b4e62016-07-26 17:58:44 +00001649 // GNU linkers implements more complicated logic to handle
1650 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1651 // the next page boundary for simplicity.
1652 if (Tok == "DATA_SEGMENT_RELRO_END") {
1653 expect("(");
Rafael Espindola97bdc722016-09-14 19:14:01 +00001654 readExpr();
George Rimar276b4e62016-07-26 17:58:44 +00001655 expect(",");
1656 readExpr();
1657 expect(")");
1658 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1659 }
George Rimar9e694502016-07-29 16:18:47 +00001660 if (Tok == "SIZEOF") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001661 StringRef Name = readParenLiteral();
George Rimar884e7862016-09-08 08:19:13 +00001662 return [=](uint64_t Dot) { return ScriptBase->getOutputSectionSize(Name); };
George Rimar9e694502016-07-29 16:18:47 +00001663 }
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001664 if (Tok == "ALIGNOF") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001665 StringRef Name = readParenLiteral();
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001666 return
1667 [=](uint64_t Dot) { return ScriptBase->getOutputSectionAlign(Name); };
1668 }
George Rimare32a3592016-08-10 07:59:34 +00001669 if (Tok == "SIZEOF_HEADERS")
George Rimar884e7862016-09-08 08:19:13 +00001670 return [=](uint64_t Dot) { return ScriptBase->getHeaderSize(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001671
George Rimar9f2f7ad2016-09-02 16:01:42 +00001672 // Tok is a literal number.
1673 uint64_t V;
1674 if (readInteger(Tok, V))
1675 return [=](uint64_t Dot) { return V; };
1676
1677 // Tok is a symbol name.
1678 if (Tok != "." && !isValidCIdentifier(Tok))
1679 setError("malformed number: " + Tok);
1680 return [=](uint64_t Dot) { return getSymbolValue(Tok, Dot); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001681}
1682
1683Expr ScriptParser::readTernary(Expr Cond) {
Justin Bogner5424e7c2016-10-17 06:21:13 +00001684 skip();
Rui Ueyama708019c2016-07-24 18:19:40 +00001685 Expr L = readExpr();
1686 expect(":");
1687 Expr R = readExpr();
1688 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1689}
1690
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001691Expr ScriptParser::readParenExpr() {
1692 expect("(");
1693 Expr E = readExpr();
1694 expect(")");
1695 return E;
1696}
1697
Eugene Leviantbbe38602016-07-19 09:25:43 +00001698std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1699 std::vector<StringRef> Phdrs;
1700 while (!Error && peek().startswith(":")) {
1701 StringRef Tok = next();
1702 Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
1703 if (Tok.empty()) {
1704 setError("section header name is empty");
1705 break;
1706 }
Rui Ueyama047404f2016-07-20 19:36:36 +00001707 Phdrs.push_back(Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001708 }
1709 return Phdrs;
1710}
1711
George Rimar95dd7182016-10-18 10:49:50 +00001712// Read a program header type name. The next token must be a
1713// name of a program header type or a constant (e.g. "0x3").
Eugene Leviantbbe38602016-07-19 09:25:43 +00001714unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001715 StringRef Tok = next();
George Rimar95dd7182016-10-18 10:49:50 +00001716 uint64_t Val;
1717 if (readInteger(Tok, Val))
1718 return Val;
1719
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001720 unsigned Ret = StringSwitch<unsigned>(Tok)
George Rimar6c55f0e2016-09-08 08:20:30 +00001721 .Case("PT_NULL", PT_NULL)
1722 .Case("PT_LOAD", PT_LOAD)
1723 .Case("PT_DYNAMIC", PT_DYNAMIC)
1724 .Case("PT_INTERP", PT_INTERP)
1725 .Case("PT_NOTE", PT_NOTE)
1726 .Case("PT_SHLIB", PT_SHLIB)
1727 .Case("PT_PHDR", PT_PHDR)
1728 .Case("PT_TLS", PT_TLS)
1729 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1730 .Case("PT_GNU_STACK", PT_GNU_STACK)
1731 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
George Rimar270173f2016-10-14 13:02:22 +00001732 .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
George Rimarcc6e5672016-10-14 10:34:36 +00001733 .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
George Rimar6c55f0e2016-09-08 08:20:30 +00001734 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001735
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001736 if (Ret == (unsigned)-1) {
1737 setError("invalid program header type: " + Tok);
1738 return PT_NULL;
1739 }
1740 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001741}
1742
Rui Ueyama95769b42016-08-31 20:03:54 +00001743void ScriptParser::readVersionDeclaration(StringRef VerStr) {
George Rimar20b65982016-08-31 09:08:26 +00001744 // Identifiers start at 2 because 0 and 1 are reserved
1745 // for VER_NDX_LOCAL and VER_NDX_GLOBAL constants.
1746 size_t VersionId = Config->VersionDefinitions.size() + 2;
1747 Config->VersionDefinitions.push_back({VerStr, VersionId});
1748
Rui Ueyama83043f22016-10-17 16:01:53 +00001749 if (consume("global:") || peek() != "local:")
George Rimar20b65982016-08-31 09:08:26 +00001750 readGlobal(VerStr);
Rui Ueyama83043f22016-10-17 16:01:53 +00001751 if (consume("local:"))
George Rimar20b65982016-08-31 09:08:26 +00001752 readLocal();
1753 expect("}");
1754
1755 // Each version may have a parent version. For example, "Ver2" defined as
1756 // "Ver2 { global: foo; local: *; } Ver1;" has "Ver1" as a parent. This
1757 // version hierarchy is, probably against your instinct, purely for human; the
1758 // runtime doesn't care about them at all. In LLD, we simply skip the token.
1759 if (!VerStr.empty() && peek() != ";")
Justin Bogner5424e7c2016-10-17 06:21:13 +00001760 skip();
George Rimar20b65982016-08-31 09:08:26 +00001761 expect(";");
1762}
1763
1764void ScriptParser::readLocal() {
1765 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1766 expect("*");
1767 expect(";");
1768}
1769
1770void ScriptParser::readExtern(std::vector<SymbolVersion> *Globals) {
George Rimarcd574a52016-09-09 14:35:36 +00001771 expect("\"C++\"");
George Rimar20b65982016-08-31 09:08:26 +00001772 expect("{");
1773
1774 for (;;) {
1775 if (peek() == "}" || Error)
1776 break;
George Rimarcd574a52016-09-09 14:35:36 +00001777 bool HasWildcard = !peek().startswith("\"") && hasWildcard(peek());
1778 Globals->push_back({unquote(next()), true, HasWildcard});
George Rimar20b65982016-08-31 09:08:26 +00001779 expect(";");
1780 }
1781
1782 expect("}");
1783 expect(";");
1784}
1785
1786void ScriptParser::readGlobal(StringRef VerStr) {
1787 std::vector<SymbolVersion> *Globals;
1788 if (VerStr.empty())
1789 Globals = &Config->VersionScriptGlobals;
1790 else
1791 Globals = &Config->VersionDefinitions.back().Globals;
1792
1793 for (;;) {
Rui Ueyama83043f22016-10-17 16:01:53 +00001794 if (consume("extern"))
George Rimar20b65982016-08-31 09:08:26 +00001795 readExtern(Globals);
1796
1797 StringRef Cur = peek();
1798 if (Cur == "}" || Cur == "local:" || Error)
1799 return;
Justin Bogner5424e7c2016-10-17 06:21:13 +00001800 skip();
George Rimarcd574a52016-09-09 14:35:36 +00001801 Globals->push_back({unquote(Cur), false, hasWildcard(Cur)});
George Rimar20b65982016-08-31 09:08:26 +00001802 expect(";");
1803 }
1804}
1805
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001806static bool isUnderSysroot(StringRef Path) {
1807 if (Config->Sysroot == "")
1808 return false;
1809 for (; !Path.empty(); Path = sys::path::parent_path(Path))
1810 if (sys::fs::equivalent(Config->Sysroot, Path))
1811 return true;
1812 return false;
1813}
1814
Rui Ueyama07320e42016-04-20 20:13:41 +00001815void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001816 StringRef Path = MB.getBufferIdentifier();
George Rimar20b65982016-08-31 09:08:26 +00001817 ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).readLinkerScript();
1818}
1819
1820void elf::readVersionScript(MemoryBufferRef MB) {
1821 ScriptParser(MB.getBuffer(), false).readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001822}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001823
Rui Ueyama07320e42016-04-20 20:13:41 +00001824template class elf::LinkerScript<ELF32LE>;
1825template class elf::LinkerScript<ELF32BE>;
1826template class elf::LinkerScript<ELF64LE>;
1827template class elf::LinkerScript<ELF64BE>;