blob: 5cdee7082e1a753d89e6c995713f6826fb8b9e1a [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) {
George Rimarc91930a2016-09-02 21:17:20 +0000111 for (Regex *Re : Opt.KeptSections)
Rafael Espindola042a3f22016-09-08 14:06:08 +0000112 if (Re->match(S->Name))
George Rimareea31142016-07-21 14:26:59 +0000113 return true;
114 return false;
115}
116
George Rimar575208c2016-09-15 19:15:12 +0000117static bool comparePriority(InputSectionData *A, InputSectionData *B) {
118 return getPriority(A->Name) < getPriority(B->Name);
119}
120
Rafael Espindolac0028d32016-09-08 20:47:52 +0000121static bool compareName(InputSectionData *A, InputSectionData *B) {
Rafael Espindola042a3f22016-09-08 14:06:08 +0000122 return A->Name < B->Name;
Rui Ueyama742c3832016-08-04 22:27:00 +0000123}
George Rimar350ece42016-08-03 08:35:59 +0000124
Rafael Espindolac0028d32016-09-08 20:47:52 +0000125static bool compareAlignment(InputSectionData *A, InputSectionData *B) {
Rui Ueyama742c3832016-08-04 22:27:00 +0000126 // ">" is not a mistake. Larger alignments are placed before smaller
127 // alignments in order to reduce the amount of padding necessary.
128 // This is compatible with GNU.
129 return A->Alignment > B->Alignment;
130}
George Rimar350ece42016-08-03 08:35:59 +0000131
Rafael Espindolac0028d32016-09-08 20:47:52 +0000132static std::function<bool(InputSectionData *, InputSectionData *)>
George Rimarbe394db2016-09-16 20:21:55 +0000133getComparator(SortSectionPolicy K) {
134 switch (K) {
135 case SortSectionPolicy::Alignment:
136 return compareAlignment;
137 case SortSectionPolicy::Name:
Rafael Espindolac0028d32016-09-08 20:47:52 +0000138 return compareName;
George Rimarbe394db2016-09-16 20:21:55 +0000139 case SortSectionPolicy::Priority:
140 return comparePriority;
141 default:
142 llvm_unreachable("unknown sort policy");
143 }
Rui Ueyama742c3832016-08-04 22:27:00 +0000144}
George Rimar0702c4e2016-07-29 15:32:46 +0000145
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000146template <class ELFT>
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000147static bool matchConstraints(ArrayRef<InputSectionBase<ELFT> *> Sections,
George Rimar06ae6832016-08-12 09:07:57 +0000148 ConstraintKind Kind) {
George Rimar8f66df92016-08-12 20:38:20 +0000149 if (Kind == ConstraintKind::NoConstraint)
150 return true;
Rafael Espindolae746e522016-09-21 18:33:44 +0000151 bool IsRW = llvm::any_of(Sections, [=](InputSectionData *Sec2) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000152 auto *Sec = static_cast<InputSectionBase<ELFT> *>(Sec2);
Rafael Espindolae746e522016-09-21 18:33:44 +0000153 return Sec->getSectionHdr()->sh_flags & SHF_WRITE;
George Rimar06ae6832016-08-12 09:07:57 +0000154 });
Rafael Espindolae746e522016-09-21 18:33:44 +0000155 return (IsRW && Kind == ConstraintKind::ReadWrite) ||
156 (!IsRW && Kind == ConstraintKind::ReadOnly);
George Rimar06ae6832016-08-12 09:07:57 +0000157}
158
George Rimar07171f22016-09-21 15:56:44 +0000159static void sortSections(InputSectionData **Begin, InputSectionData **End,
Rui Ueyamaee924702016-09-20 19:42:41 +0000160 SortSectionPolicy K) {
161 if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
George Rimar07171f22016-09-21 15:56:44 +0000162 std::stable_sort(Begin, End, getComparator(K));
Rui Ueyamaee924702016-09-20 19:42:41 +0000163}
164
Rafael Espindolad3190792016-09-16 15:10:23 +0000165// Compute and remember which sections the InputSectionDescription matches.
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000166template <class ELFT>
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000167void LinkerScript<ELFT>::computeInputSections(InputSectionDescription *I) {
Rui Ueyama4dc07be2016-09-17 02:23:40 +0000168 // Collects all sections that satisfy constraints of I
169 // and attach them to I.
170 for (SectionPattern &Pat : I->SectionPatterns) {
George Rimar07171f22016-09-21 15:56:44 +0000171 size_t SizeBefore = I->Sections.size();
George Rimar395281c2016-09-16 17:42:10 +0000172 for (ObjectFile<ELFT> *F : Symtab<ELFT>::X->getObjectFiles()) {
Rui Ueyama3ff27f42016-09-17 02:15:28 +0000173 StringRef Filename = sys::path::filename(F->getName());
Rafael Espindolaf135f0e2016-09-19 13:33:38 +0000174 if (!I->FileRe.match(Filename) || Pat.ExcludedFileRe.match(Filename))
Rui Ueyama3ff27f42016-09-17 02:15:28 +0000175 continue;
Rui Ueyama4dc07be2016-09-17 02:23:40 +0000176
Rui Ueyama3ff27f42016-09-17 02:15:28 +0000177 for (InputSectionBase<ELFT> *S : F->getSections())
Rafael Espindolaf135f0e2016-09-19 13:33:38 +0000178 if (!isDiscarded(S) && !S->OutSec && Pat.SectionRe.match(S->Name))
Rui Ueyama3ff27f42016-09-17 02:15:28 +0000179 I->Sections.push_back(S);
Rafael Espindolaf135f0e2016-09-19 13:33:38 +0000180 if (Pat.SectionRe.match("COMMON"))
Rui Ueyama3ff27f42016-09-17 02:15:28 +0000181 I->Sections.push_back(CommonInputSection<ELFT>::X);
George Rimar395281c2016-09-16 17:42:10 +0000182 }
Rafael Espindolad3190792016-09-16 15:10:23 +0000183
George Rimar07171f22016-09-21 15:56:44 +0000184 // Sort sections as instructed by SORT-family commands and --sort-section
185 // option. Because SORT-family commands can be nested at most two depth
186 // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
187 // line option is respected even if a SORT command is given, the exact
188 // behavior we have here is a bit complicated. Here are the rules.
189 //
190 // 1. If two SORT commands are given, --sort-section is ignored.
191 // 2. If one SORT command is given, and if it is not SORT_NONE,
192 // --sort-section is handled as an inner SORT command.
193 // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
194 // 4. If no SORT command is given, sort according to --sort-section.
195 InputSectionData **Begin = I->Sections.data() + SizeBefore;
196 InputSectionData **End = I->Sections.data() + I->Sections.size();
197 if (Pat.SortOuter != SortSectionPolicy::None) {
198 if (Pat.SortInner == SortSectionPolicy::Default)
199 sortSections(Begin, End, Config->SortSection);
200 else
201 sortSections(Begin, End, Pat.SortInner);
202 sortSections(Begin, End, Pat.SortOuter);
203 }
Rui Ueyamaee924702016-09-20 19:42:41 +0000204 }
Rafael Espindolad3190792016-09-16 15:10:23 +0000205
206 // We do not add duplicate input sections, so mark them with a dummy output
207 // section for now.
208 for (InputSectionData *S : I->Sections) {
209 auto *S2 = static_cast<InputSectionBase<ELFT> *>(S);
210 S2->OutSec = (OutputSectionBase<ELFT> *)-1;
211 }
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000212}
213
214template <class ELFT>
215void LinkerScript<ELFT>::discard(ArrayRef<InputSectionBase<ELFT> *> V) {
216 for (InputSectionBase<ELFT> *S : V) {
217 S->Live = false;
218 reportDiscarded(S);
219 }
220}
221
George Rimar06ae6832016-08-12 09:07:57 +0000222template <class ELFT>
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000223std::vector<InputSectionBase<ELFT> *>
George Rimar06ae6832016-08-12 09:07:57 +0000224LinkerScript<ELFT>::createInputSectionList(OutputSectionCommand &OutCmd) {
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000225 std::vector<InputSectionBase<ELFT> *> Ret;
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000226
George Rimar06ae6832016-08-12 09:07:57 +0000227 for (const std::unique_ptr<BaseCommand> &Base : OutCmd.Commands) {
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000228 auto *Cmd = dyn_cast<InputSectionDescription>(Base.get());
229 if (!Cmd)
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000230 continue;
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000231 computeInputSections(Cmd);
Rafael Espindolad3190792016-09-16 15:10:23 +0000232 for (InputSectionData *S : Cmd->Sections)
233 Ret.push_back(static_cast<InputSectionBase<ELFT> *>(S));
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000234 }
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000235
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000236 return Ret;
237}
238
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000239template <class ELFT>
Rafael Espindola10897f12016-09-13 14:23:14 +0000240static SectionKey<ELFT::Is64Bits> createKey(InputSectionBase<ELFT> *C,
241 StringRef OutsecName) {
242 // When using linker script the merge rules are different.
243 // Unfortunately, linker scripts are name based. This means that expressions
244 // like *(.foo*) can refer to multiple input sections that would normally be
245 // placed in different output sections. We cannot put them in different
246 // output sections or we would produce wrong results for
247 // start = .; *(.foo.*) end = .; *(.bar)
248 // and a mapping of .foo1 and .bar1 to one section and .foo2 and .bar2 to
249 // another. The problem is that there is no way to layout those output
250 // sections such that the .foo sections are the only thing between the
251 // start and end symbols.
252
253 // An extra annoyance is that we cannot simply disable merging of the contents
254 // of SHF_MERGE sections, but our implementation requires one output section
255 // per "kind" (string or not, which size/aligment).
256 // Fortunately, creating symbols in the middle of a merge section is not
257 // supported by bfd or gold, so we can just create multiple section in that
258 // case.
259 const typename ELFT::Shdr *H = C->getSectionHdr();
260 typedef typename ELFT::uint uintX_t;
261 uintX_t Flags = H->sh_flags & (SHF_MERGE | SHF_STRINGS);
262
263 uintX_t Alignment = 0;
264 if (isa<MergeInputSection<ELFT>>(C))
265 Alignment = std::max(H->sh_addralign, H->sh_entsize);
266
267 return SectionKey<ELFT::Is64Bits>{OutsecName, /*Type*/ 0, Flags, Alignment};
268}
269
270template <class ELFT>
Eugene Leviant20d03192016-09-16 15:30:47 +0000271void LinkerScript<ELFT>::addSection(OutputSectionFactory<ELFT> &Factory,
272 InputSectionBase<ELFT> *Sec,
273 StringRef Name) {
274 OutputSectionBase<ELFT> *OutSec;
275 bool IsNew;
276 std::tie(OutSec, IsNew) = Factory.create(createKey(Sec, Name), Sec);
277 if (IsNew)
278 OutputSections->push_back(OutSec);
279 OutSec->addSection(Sec);
280}
281
282template <class ELFT>
283void LinkerScript<ELFT>::processCommands(OutputSectionFactory<ELFT> &Factory) {
Rafael Espindola28c15972016-09-13 13:00:06 +0000284
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000285 for (unsigned I = 0; I < Opt.Commands.size(); ++I) {
286 auto Iter = Opt.Commands.begin() + I;
287 const std::unique_ptr<BaseCommand> &Base1 = *Iter;
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000288 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base1.get())) {
289 if (shouldDefine<ELFT>(Cmd))
290 addRegular<ELFT>(Cmd);
291 continue;
292 }
Eugene Leviant20d03192016-09-16 15:30:47 +0000293 if (auto *Cmd = dyn_cast<AssertCommand>(Base1.get())) {
294 // If we don't have SECTIONS then output sections have already been
George Rimar194470cd2016-09-17 19:21:05 +0000295 // created by Writer<ELFT>. The LinkerScript<ELFT>::assignAddresses
Eugene Leviant20d03192016-09-16 15:30:47 +0000296 // will not be called, so ASSERT should be evaluated now.
297 if (!Opt.HasSections)
298 Cmd->Expression(0);
299 continue;
300 }
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000301
Eugene Leviantceabe802016-08-11 07:56:43 +0000302 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000303 std::vector<InputSectionBase<ELFT> *> V = createInputSectionList(*Cmd);
304
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000305 if (Cmd->Name == "/DISCARD/") {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000306 discard(V);
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000307 continue;
308 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000309
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000310 if (!matchConstraints<ELFT>(V, Cmd->Constraint)) {
311 for (InputSectionBase<ELFT> *S : V)
312 S->OutSec = nullptr;
313 Opt.Commands.erase(Iter);
George Rimardfbbbc82016-09-17 09:50:10 +0000314 --I;
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000315 continue;
316 }
317
318 for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
319 if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base.get()))
320 if (shouldDefine<ELFT>(OutCmd))
321 addSymbol<ELFT>(OutCmd);
322
Eugene Leviant97403d12016-09-01 09:55:57 +0000323 if (V.empty())
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000324 continue;
325
George Rimardb24d9c2016-08-19 15:18:23 +0000326 for (InputSectionBase<ELFT> *Sec : V) {
Eugene Leviant20d03192016-09-16 15:30:47 +0000327 addSection(Factory, Sec, Cmd->Name);
328 if (uint32_t Subalign = Cmd->SubalignExpr ? Cmd->SubalignExpr(0) : 0)
George Rimardb24d9c2016-08-19 15:18:23 +0000329 Sec->Alignment = Subalign;
George Rimardb24d9c2016-08-19 15:18:23 +0000330 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000331 }
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000332 }
Eugene Leviant20d03192016-09-16 15:30:47 +0000333}
Eugene Leviante63d81b2016-07-20 14:43:20 +0000334
Eugene Leviant20d03192016-09-16 15:30:47 +0000335template <class ELFT>
336void LinkerScript<ELFT>::createSections(OutputSectionFactory<ELFT> &Factory) {
337 processCommands(Factory);
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000338 // Add orphan sections.
Eugene Leviant20d03192016-09-16 15:30:47 +0000339 for (ObjectFile<ELFT> *F : Symtab<ELFT>::X->getObjectFiles())
340 for (InputSectionBase<ELFT> *S : F->getSections())
341 if (!isDiscarded(S) && !S->OutSec)
342 addSection(Factory, S, getOutputSectionName(S));
Eugene Leviante63d81b2016-07-20 14:43:20 +0000343}
344
Eugene Leviantdb741e72016-09-07 07:08:43 +0000345// Sets value of a section-defined symbol. Two kinds of
346// symbols are processed: synthetic symbols, whose value
347// is an offset from beginning of section and regular
348// symbols whose value is absolute.
349template <class ELFT>
350static void assignSectionSymbol(SymbolAssignment *Cmd,
351 OutputSectionBase<ELFT> *Sec,
352 typename ELFT::uint Off) {
353 if (!Cmd->Sym)
354 return;
355
356 if (auto *Body = dyn_cast<DefinedSynthetic<ELFT>>(Cmd->Sym)) {
357 Body->Section = Sec;
358 Body->Value = Cmd->Expression(Sec->getVA() + Off) - Sec->getVA();
359 return;
360 }
361 auto *Body = cast<DefinedRegular<ELFT>>(Cmd->Sym);
362 Body->Value = Cmd->Expression(Sec->getVA() + Off);
363}
364
Rafael Espindolaa940e532016-09-22 12:35:44 +0000365template <class ELFT> static bool isTbss(OutputSectionBase<ELFT> *Sec) {
366 return (Sec->getFlags() & SHF_TLS) && Sec->getType() == SHT_NOBITS;
367}
368
Rafael Espindolad3190792016-09-16 15:10:23 +0000369template <class ELFT> void LinkerScript<ELFT>::output(InputSection<ELFT> *S) {
370 if (!AlreadyOutputIS.insert(S).second)
371 return;
Rafael Espindolaa940e532016-09-22 12:35:44 +0000372 bool IsTbss = isTbss(CurOutSec);
Eugene Leviant20889c52016-08-31 08:13:33 +0000373
Rafael Espindolad3190792016-09-16 15:10:23 +0000374 uintX_t Pos = IsTbss ? Dot + ThreadBssOffset : Dot;
375 Pos = alignTo(Pos, S->Alignment);
376 S->OutSecOff = Pos - CurOutSec->getVA();
377 Pos += S->getSize();
378
379 // Update output section size after adding each section. This is so that
380 // SIZEOF works correctly in the case below:
381 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
382 CurOutSec->setSize(Pos - CurOutSec->getVA());
383
Rafael Espindola7252ae52016-09-22 12:00:08 +0000384 if (IsTbss)
385 ThreadBssOffset = Pos - Dot;
386 else
Rafael Espindolad3190792016-09-16 15:10:23 +0000387 Dot = Pos;
388}
389
390template <class ELFT> void LinkerScript<ELFT>::flush() {
Rafael Espindola65499b92016-09-23 20:10:47 +0000391 if (!CurOutSec || !AlreadyOutputOS.insert(CurOutSec).second)
392 return;
393 if (auto *OutSec = dyn_cast<OutputSection<ELFT>>(CurOutSec)) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000394 for (InputSection<ELFT> *I : OutSec->Sections)
395 output(I);
Rafael Espindola65499b92016-09-23 20:10:47 +0000396 } else {
397 Dot += CurOutSec->getSize();
Eugene Leviant20889c52016-08-31 08:13:33 +0000398 }
399}
400
401template <class ELFT>
Rafael Espindolad3190792016-09-16 15:10:23 +0000402void LinkerScript<ELFT>::switchTo(OutputSectionBase<ELFT> *Sec) {
403 if (CurOutSec == Sec)
404 return;
405 if (AlreadyOutputOS.count(Sec))
406 return;
407
408 flush();
409 CurOutSec = Sec;
410
411 Dot = alignTo(Dot, CurOutSec->getAlignment());
Rafael Espindolaa940e532016-09-22 12:35:44 +0000412 CurOutSec->setVA(isTbss(CurOutSec) ? Dot + ThreadBssOffset : Dot);
Rafael Espindolad3190792016-09-16 15:10:23 +0000413}
414
415template <class ELFT> void LinkerScript<ELFT>::process(BaseCommand &Base) {
George Rimare38cbab2016-09-26 19:22:50 +0000416 // This handles the assignments to symbol or to a location counter (.)
Rafael Espindolad3190792016-09-16 15:10:23 +0000417 if (auto *AssignCmd = dyn_cast<SymbolAssignment>(&Base)) {
418 if (AssignCmd->Name == ".") {
419 // Update to location counter means update to section size.
420 Dot = AssignCmd->Expression(Dot);
421 CurOutSec->setSize(Dot - CurOutSec->getVA());
422 return;
423 }
424 assignSectionSymbol<ELFT>(AssignCmd, CurOutSec, Dot - CurOutSec->getVA());
Eugene Leviantceabe802016-08-11 07:56:43 +0000425 return;
Rui Ueyama2de509c2016-08-12 00:55:08 +0000426 }
George Rimare38cbab2016-09-26 19:22:50 +0000427
428 // Handle BYTE(), SHORT(), LONG(), or QUAD().
429 if (auto *DataCmd = dyn_cast<BytesDataCommand>(&Base)) {
430 DataCmd->Offset = Dot - CurOutSec->getVA();
431 Dot += DataCmd->Size;
432 CurOutSec->setSize(Dot - CurOutSec->getVA());
433 return;
434 }
435
436 // It handles single input section description command,
437 // calculates and assigns the offsets for each section and also
438 // updates the output section size.
Rafael Espindolad3190792016-09-16 15:10:23 +0000439 auto &ICmd = cast<InputSectionDescription>(Base);
440 for (InputSectionData *ID : ICmd.Sections) {
441 auto *IB = static_cast<InputSectionBase<ELFT> *>(ID);
442 switchTo(IB->OutSec);
443 if (auto *I = dyn_cast<InputSection<ELFT>>(IB))
444 output(I);
Rafael Espindola65499b92016-09-23 20:10:47 +0000445 else
446 flush();
Eugene Leviantceabe802016-08-11 07:56:43 +0000447 }
448}
449
George Rimar8f66df92016-08-12 20:38:20 +0000450template <class ELFT>
George Rimara14b13d2016-09-07 10:46:07 +0000451static std::vector<OutputSectionBase<ELFT> *>
452findSections(OutputSectionCommand &Cmd,
Rafael Espindolad3190792016-09-16 15:10:23 +0000453 const std::vector<OutputSectionBase<ELFT> *> &Sections) {
George Rimara14b13d2016-09-07 10:46:07 +0000454 std::vector<OutputSectionBase<ELFT> *> Ret;
455 for (OutputSectionBase<ELFT> *Sec : Sections)
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000456 if (Sec->getName() == Cmd.Name)
George Rimara14b13d2016-09-07 10:46:07 +0000457 Ret.push_back(Sec);
458 return Ret;
George Rimar8f66df92016-08-12 20:38:20 +0000459}
460
Rafael Espindolad3190792016-09-16 15:10:23 +0000461template <class ELFT>
462void LinkerScript<ELFT>::assignOffsets(OutputSectionCommand *Cmd) {
463 std::vector<OutputSectionBase<ELFT> *> Sections =
464 findSections(*Cmd, *OutputSections);
465 if (Sections.empty())
466 return;
467 switchTo(Sections[0]);
468
469 // Find the last section output location. We will output orphan sections
470 // there so that end symbols point to the correct location.
471 auto E = std::find_if(Cmd->Commands.rbegin(), Cmd->Commands.rend(),
472 [](const std::unique_ptr<BaseCommand> &Cmd) {
473 return !isa<SymbolAssignment>(*Cmd);
474 })
475 .base();
476 for (auto I = Cmd->Commands.begin(); I != E; ++I)
477 process(**I);
Rafael Espindola65499b92016-09-23 20:10:47 +0000478 for (OutputSectionBase<ELFT> *Base : Sections)
Rafael Espindolad3190792016-09-16 15:10:23 +0000479 switchTo(Base);
Rafael Espindola65499b92016-09-23 20:10:47 +0000480 flush();
George Rimarb31dd372016-09-19 13:27:31 +0000481 std::for_each(E, Cmd->Commands.end(),
482 [this](std::unique_ptr<BaseCommand> &B) { process(*B.get()); });
Rafael Espindolad3190792016-09-16 15:10:23 +0000483}
484
Rafael Espindola9546fff2016-09-22 14:40:50 +0000485template <class ELFT> void LinkerScript<ELFT>::adjustSectionsBeforeSorting() {
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000486 // It is common practice to use very generic linker scripts. So for any
487 // given run some of the output sections in the script will be empty.
488 // We could create corresponding empty output sections, but that would
489 // clutter the output.
490 // We instead remove trivially empty sections. The bfd linker seems even
491 // more aggressive at removing them.
492 auto Pos = std::remove_if(
493 Opt.Commands.begin(), Opt.Commands.end(),
494 [&](const std::unique_ptr<BaseCommand> &Base) {
495 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
496 if (!Cmd)
497 return false;
498 std::vector<OutputSectionBase<ELFT> *> Secs =
499 findSections(*Cmd, *OutputSections);
500 if (!Secs.empty())
501 return false;
502 for (const std::unique_ptr<BaseCommand> &I : Cmd->Commands)
503 if (!isa<InputSectionDescription>(I.get()))
504 return false;
505 return true;
506 });
507 Opt.Commands.erase(Pos, Opt.Commands.end());
508
Rafael Espindola9546fff2016-09-22 14:40:50 +0000509 // If the output section contains only symbol assignments, create a
510 // corresponding output section. The bfd linker seems to only create them if
511 // '.' is assigned to, but creating these section should not have any bad
512 // consequeces and gives us a section to put the symbol in.
513 uintX_t Flags = SHF_ALLOC;
514 uint32_t Type = 0;
515 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
516 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
517 if (!Cmd)
518 continue;
519 std::vector<OutputSectionBase<ELFT> *> Secs =
520 findSections(*Cmd, *OutputSections);
521 if (!Secs.empty()) {
522 Flags = Secs[0]->getFlags();
523 Type = Secs[0]->getType();
524 continue;
525 }
526
527 auto *OutSec = new OutputSection<ELFT>(Cmd->Name, Type, Flags);
528 Out<ELFT>::Pool.emplace_back(OutSec);
529 OutputSections->push_back(OutSec);
530 }
531}
532
Rafael Espindola15c57952016-09-22 18:05:49 +0000533// When placing orphan sections, we want to place them after symbol assignments
534// so that an orphan after
535// begin_foo = .;
536// foo : { *(foo) }
537// end_foo = .;
538// doesn't break the intended meaning of the begin/end symbols.
539// We don't want to go over sections since Writer<ELFT>::sortSections is the
540// one in charge of deciding the order of the sections.
541// We don't want to go over alignments, since doing so in
542// rx_sec : { *(rx_sec) }
543// . = ALIGN(0x1000);
544// /* The RW PT_LOAD starts here*/
545// rw_sec : { *(rw_sec) }
546// would mean that the RW PT_LOAD would become unaligned.
547static bool shouldSkip(const BaseCommand &Cmd) {
548 if (isa<OutputSectionCommand>(Cmd))
549 return false;
550 const auto *Assign = dyn_cast<SymbolAssignment>(&Cmd);
551 if (!Assign)
552 return true;
553 return Assign->Name != ".";
554}
555
Rafael Espindola6d91fce2016-09-29 18:50:34 +0000556template <class ELFT>
557void LinkerScript<ELFT>::assignAddresses(std::vector<PhdrEntry<ELFT>> &Phdrs) {
George Rimar652852c2016-04-16 10:10:32 +0000558 // Orphan sections are sections present in the input files which
Rui Ueyama7c18c282016-04-18 21:00:40 +0000559 // are not explicitly placed into the output file by the linker script.
560 // We place orphan sections at end of file.
561 // Other linkers places them using some heuristics as described in
George Rimar652852c2016-04-16 10:10:32 +0000562 // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000563
564 // The OutputSections are already in the correct order.
565 // This loops creates or moves commands as needed so that they are in the
566 // correct order.
567 int CmdIndex = 0;
Rui Ueyamae5cc6682016-08-12 00:36:56 +0000568 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
George Rimar652852c2016-04-16 10:10:32 +0000569 StringRef Name = Sec->getName();
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000570
571 // Find the last spot where we can insert a command and still get the
Rafael Espindola15c57952016-09-22 18:05:49 +0000572 // correct result.
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000573 auto CmdIter = Opt.Commands.begin() + CmdIndex;
574 auto E = Opt.Commands.end();
Rafael Espindola15c57952016-09-22 18:05:49 +0000575 while (CmdIter != E && shouldSkip(**CmdIter)) {
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000576 ++CmdIter;
577 ++CmdIndex;
578 }
579
580 auto Pos =
581 std::find_if(CmdIter, E, [&](const std::unique_ptr<BaseCommand> &Base) {
582 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
583 return Cmd && Cmd->Name == Name;
584 });
585 if (Pos == E) {
586 Opt.Commands.insert(CmdIter,
587 llvm::make_unique<OutputSectionCommand>(Name));
Rafael Espindola15c57952016-09-22 18:05:49 +0000588 ++CmdIndex;
589 continue;
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000590 }
Rafael Espindola15c57952016-09-22 18:05:49 +0000591
592 // Continue from where we found it.
593 CmdIndex = (Pos - Opt.Commands.begin()) + 1;
594 continue;
George Rimar652852c2016-04-16 10:10:32 +0000595 }
George Rimar652852c2016-04-16 10:10:32 +0000596
Rui Ueyama7c18c282016-04-18 21:00:40 +0000597 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rafael Espindolabe607332016-09-30 00:16:11 +0000598 Dot = 0;
George Rimar652852c2016-04-16 10:10:32 +0000599
George Rimar076fe152016-07-21 06:43:01 +0000600 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
601 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
Rui Ueyama8d083e62016-07-29 05:48:39 +0000602 if (Cmd->Name == ".") {
603 Dot = Cmd->Expression(Dot);
604 } else if (Cmd->Sym) {
605 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(Dot);
606 }
George Rimar652852c2016-04-16 10:10:32 +0000607 continue;
608 }
609
George Rimareefa7582016-08-04 09:29:31 +0000610 if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
611 Cmd->Expression(Dot);
612 continue;
613 }
614
George Rimar076fe152016-07-21 06:43:01 +0000615 auto *Cmd = cast<OutputSectionCommand>(Base.get());
George Rimar652852c2016-04-16 10:10:32 +0000616
Rafael Espindolad3190792016-09-16 15:10:23 +0000617 if (Cmd->AddrExpr)
618 Dot = Cmd->AddrExpr(Dot);
George Rimar58e5c4d2016-07-25 08:29:46 +0000619
Rafael Espindolad3190792016-09-16 15:10:23 +0000620 assignOffsets(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000621 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000622
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000623 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
624 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
625 if (Sec->getFlags() & SHF_ALLOC)
626 MinVA = std::min(MinVA, Sec->getVA());
627 else
Rafael Espindolad3190792016-09-16 15:10:23 +0000628 Sec->setVA(0);
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000629 }
630
Rafael Espindola0d4b6d52016-09-22 16:47:21 +0000631 uintX_t HeaderSize = getHeaderSize();
Rafael Espindola6d91fce2016-09-29 18:50:34 +0000632 auto FirstPTLoad =
633 std::find_if(Phdrs.begin(), Phdrs.end(), [](const PhdrEntry<ELFT> &E) {
634 return E.H.p_type == PT_LOAD;
635 });
636 if (HeaderSize <= MinVA && FirstPTLoad != Phdrs.end()) {
637 // ELF and Program headers need to be right before the first section in
638 // memory. Set their addresses accordingly.
639 MinVA = alignDown(MinVA - HeaderSize, Target->PageSize);
640 Out<ELFT>::ElfHeader->setVA(MinVA);
641 Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
642 FirstPTLoad->First = Out<ELFT>::ElfHeader;
643 if (!FirstPTLoad->Last)
644 FirstPTLoad->Last = Out<ELFT>::ProgramHeaders;
645 }
George Rimar652852c2016-04-16 10:10:32 +0000646}
647
Rui Ueyama464daad2016-08-22 04:55:20 +0000648// Creates program headers as instructed by PHDRS linker script command.
Rui Ueyama07320e42016-04-20 20:13:41 +0000649template <class ELFT>
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000650std::vector<PhdrEntry<ELFT>> LinkerScript<ELFT>::createPhdrs() {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000651 std::vector<PhdrEntry<ELFT>> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000652
Rui Ueyama464daad2016-08-22 04:55:20 +0000653 // Process PHDRS and FILEHDR keywords because they are not
654 // real output sections and cannot be added in the following loop.
Eugene Leviantbbe38602016-07-19 09:25:43 +0000655 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000656 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
657 PhdrEntry<ELFT> &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000658
659 if (Cmd.HasFilehdr)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000660 Phdr.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000661 if (Cmd.HasPhdrs)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000662 Phdr.add(Out<ELFT>::ProgramHeaders);
Eugene Leviant56b21c82016-09-09 09:46:16 +0000663
664 if (Cmd.LMAExpr) {
665 Phdr.H.p_paddr = Cmd.LMAExpr(0);
666 Phdr.HasLMA = true;
667 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000668 }
669
Rui Ueyama464daad2016-08-22 04:55:20 +0000670 // Add output sections to program headers.
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000671 PhdrEntry<ELFT> *Load = nullptr;
672 uintX_t Flags = PF_R;
Rui Ueyama464daad2016-08-22 04:55:20 +0000673 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
Eugene Leviantbbe38602016-07-19 09:25:43 +0000674 if (!(Sec->getFlags() & SHF_ALLOC))
675 break;
676
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000677 std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName());
Eugene Leviantbbe38602016-07-19 09:25:43 +0000678 if (!PhdrIds.empty()) {
679 // Assign headers specified by linker script
680 for (size_t Id : PhdrIds) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000681 Ret[Id].add(Sec);
Eugene Leviant865bf862016-07-21 10:43:25 +0000682 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
Rafael Espindola0b113672016-07-27 14:10:56 +0000683 Ret[Id].H.p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000684 }
685 } else {
686 // If we have no load segment or flags've changed then we want new load
687 // segment.
Rafael Espindola0b113672016-07-27 14:10:56 +0000688 uintX_t NewFlags = Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000689 if (Load == nullptr || Flags != NewFlags) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000690 Load = &*Ret.emplace(Ret.end(), PT_LOAD, NewFlags);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000691 Flags = NewFlags;
692 }
Rui Ueyama18f084f2016-07-20 19:36:41 +0000693 Load->add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000694 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000695 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000696 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000697}
698
Eugene Leviantf9bc3bd2016-08-16 06:40:58 +0000699template <class ELFT> bool LinkerScript<ELFT>::ignoreInterpSection() {
700 // Ignore .interp section in case we have PHDRS specification
701 // and PT_INTERP isn't listed.
702 return !Opt.PhdrsCommands.empty() &&
703 llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
704 return Cmd.Type == PT_INTERP;
705 }) == Opt.PhdrsCommands.end();
706}
707
Eugene Leviantbbe38602016-07-19 09:25:43 +0000708template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000709ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000710 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
711 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
712 if (Cmd->Name == Name)
713 return Cmd->Filler;
714 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000715}
716
George Rimare38cbab2016-09-26 19:22:50 +0000717template <class ELFT>
718static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) {
719 const endianness E = ELFT::TargetEndianness;
720
721 switch (Size) {
722 case 1:
723 *Buf = (uint8_t)Data;
724 break;
725 case 2:
726 write16<E>(Buf, Data);
727 break;
728 case 4:
729 write32<E>(Buf, Data);
730 break;
731 case 8:
732 write64<E>(Buf, Data);
733 break;
734 default:
735 llvm_unreachable("unsupported Size argument");
736 }
737}
738
739template <class ELFT>
740void LinkerScript<ELFT>::writeDataBytes(StringRef Name, uint8_t *Buf) {
741 int I = getSectionIndex(Name);
742 if (I == INT_MAX)
743 return;
744
745 OutputSectionCommand *Cmd =
746 dyn_cast<OutputSectionCommand>(Opt.Commands[I].get());
747 for (const std::unique_ptr<BaseCommand> &Base2 : Cmd->Commands)
748 if (auto *DataCmd = dyn_cast<BytesDataCommand>(Base2.get()))
749 writeInt<ELFT>(&Buf[DataCmd->Offset], DataCmd->Data, DataCmd->Size);
750}
751
George Rimar206fffa2016-08-17 08:16:57 +0000752template <class ELFT> Expr LinkerScript<ELFT>::getLma(StringRef Name) {
George Rimar8ceadb32016-08-17 07:44:19 +0000753 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
754 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
755 if (Cmd->LmaExpr && Cmd->Name == Name)
756 return Cmd->LmaExpr;
757 return {};
758}
759
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000760// Returns the index of the given section name in linker script
761// SECTIONS commands. Sections are laid out as the same order as they
762// were in the script. If a given name did not appear in the script,
763// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000764template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000765 int I = 0;
766 for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
767 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
768 if (Cmd->Name == Name)
769 return I;
770 ++I;
771 }
772 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000773}
774
Eugene Leviantbbe38602016-07-19 09:25:43 +0000775template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
776 return !Opt.PhdrsCommands.empty();
777}
778
George Rimar9e694502016-07-29 16:18:47 +0000779template <class ELFT>
George Rimar884e7862016-09-08 08:19:13 +0000780uint64_t LinkerScript<ELFT>::getOutputSectionAddress(StringRef Name) {
George Rimar96659df2016-08-30 09:54:01 +0000781 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
782 if (Sec->getName() == Name)
783 return Sec->getVA();
784 error("undefined section " + Name);
785 return 0;
786}
787
788template <class ELFT>
George Rimar884e7862016-09-08 08:19:13 +0000789uint64_t LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
George Rimar9e694502016-07-29 16:18:47 +0000790 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
791 if (Sec->getName() == Name)
792 return Sec->getSize();
793 error("undefined section " + Name);
794 return 0;
795}
796
Eugene Leviant36fac7f2016-09-08 09:08:30 +0000797template <class ELFT>
798uint64_t LinkerScript<ELFT>::getOutputSectionAlign(StringRef Name) {
799 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
800 if (Sec->getName() == Name)
801 return Sec->getAlignment();
802 error("undefined section " + Name);
803 return 0;
804}
805
George Rimar884e7862016-09-08 08:19:13 +0000806template <class ELFT> uint64_t LinkerScript<ELFT>::getHeaderSize() {
Rafael Espindola0d4b6d52016-09-22 16:47:21 +0000807 return elf::getHeaderSize<ELFT>();
George Rimare32a3592016-08-10 07:59:34 +0000808}
809
George Rimar884e7862016-09-08 08:19:13 +0000810template <class ELFT> uint64_t LinkerScript<ELFT>::getSymbolValue(StringRef S) {
811 if (SymbolBody *B = Symtab<ELFT>::X->find(S))
812 return B->getVA<ELFT>();
813 error("symbol not found: " + S);
814 return 0;
815}
816
George Rimarf34f45f2016-09-23 13:17:23 +0000817template <class ELFT> bool LinkerScript<ELFT>::isDefined(StringRef S) {
818 return Symtab<ELFT>::X->find(S) != nullptr;
819}
820
Eugene Leviantbbe38602016-07-19 09:25:43 +0000821// Returns indices of ELF headers containing specific section, identified
822// by Name. Each index is a zero based number of ELF header listed within
823// PHDRS {} script block.
824template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000825std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000826 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
827 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000828 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000829 continue;
830
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000831 std::vector<size_t> Ret;
832 for (StringRef PhdrName : Cmd->Phdrs)
833 Ret.push_back(getPhdrIndex(PhdrName));
834 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000835 }
George Rimar31d842f2016-07-20 16:43:03 +0000836 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000837}
838
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000839template <class ELFT>
840size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
841 size_t I = 0;
842 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
843 if (Cmd.Name == PhdrName)
844 return I;
845 ++I;
846 }
847 error("section header '" + PhdrName + "' is not listed in PHDRS");
848 return 0;
849}
850
Rui Ueyama07320e42016-04-20 20:13:41 +0000851class elf::ScriptParser : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000852 typedef void (ScriptParser::*Handler)();
853
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000854public:
Rui Ueyama07320e42016-04-20 20:13:41 +0000855 ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
George Rimarf23b2322016-02-19 10:45:45 +0000856
George Rimar20b65982016-08-31 09:08:26 +0000857 void readLinkerScript();
858 void readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000859
860private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000861 void addFile(StringRef Path);
862
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000863 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000864 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000865 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000866 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000867 void readInclude();
Rui Ueyamaee592822015-10-07 00:25:09 +0000868 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000869 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000870 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000871 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000872 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000873 void readSections();
Rui Ueyama95769b42016-08-31 20:03:54 +0000874 void readVersion();
875 void readVersionScriptCommand();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000876
Rui Ueyama113cdec2016-07-24 23:05:57 +0000877 SymbolAssignment *readAssignment(StringRef Name);
George Rimare38cbab2016-09-26 19:22:50 +0000878 BytesDataCommand *readBytesDataCommand(StringRef Tok);
George Rimarff1f29e2016-09-06 13:51:57 +0000879 std::vector<uint8_t> readFill();
Rui Ueyama10416562016-08-04 02:03:27 +0000880 OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
George Rimarff1f29e2016-09-06 13:51:57 +0000881 std::vector<uint8_t> readOutputSectionFiller(StringRef Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000882 std::vector<StringRef> readOutputSectionPhdrs();
George Rimara2496cb2016-08-30 09:46:59 +0000883 InputSectionDescription *readInputSectionDescription(StringRef Tok);
George Rimarc91930a2016-09-02 21:17:20 +0000884 Regex readFilePatterns();
George Rimar07171f22016-09-21 15:56:44 +0000885 std::vector<SectionPattern> readInputSectionsList();
George Rimara2496cb2016-08-30 09:46:59 +0000886 InputSectionDescription *readInputSectionRules(StringRef FilePattern);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000887 unsigned readPhdrType();
George Rimarbe394db2016-09-16 20:21:55 +0000888 SortSectionPolicy readSortKind();
Petr Hoseka35e39c2016-08-16 01:11:16 +0000889 SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
Eugene Leviantdb741e72016-09-07 07:08:43 +0000890 SymbolAssignment *readProvideOrAssignment(StringRef Tok, bool MakeAbsolute);
George Rimar03fc0102016-07-28 07:18:23 +0000891 void readSort();
George Rimareefa7582016-08-04 09:29:31 +0000892 Expr readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +0000893
894 Expr readExpr();
895 Expr readExpr1(Expr Lhs, int MinPrec);
896 Expr readPrimary();
897 Expr readTernary(Expr Cond);
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +0000898 Expr readParenExpr();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000899
George Rimar20b65982016-08-31 09:08:26 +0000900 // For parsing version script.
901 void readExtern(std::vector<SymbolVersion> *Globals);
Rui Ueyama95769b42016-08-31 20:03:54 +0000902 void readVersionDeclaration(StringRef VerStr);
George Rimar20b65982016-08-31 09:08:26 +0000903 void readGlobal(StringRef VerStr);
904 void readLocal();
905
Rui Ueyama07320e42016-04-20 20:13:41 +0000906 ScriptConfiguration &Opt = *ScriptConfig;
907 StringSaver Saver = {ScriptConfig->Alloc};
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000908 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000909};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000910
George Rimar20b65982016-08-31 09:08:26 +0000911void ScriptParser::readVersionScript() {
Rui Ueyama95769b42016-08-31 20:03:54 +0000912 readVersionScriptCommand();
913 if (!atEOF())
914 setError("EOF expected, but got " + next());
915}
916
917void ScriptParser::readVersionScriptCommand() {
George Rimar20b65982016-08-31 09:08:26 +0000918 if (skip("{")) {
Rui Ueyama95769b42016-08-31 20:03:54 +0000919 readVersionDeclaration("");
George Rimar20b65982016-08-31 09:08:26 +0000920 return;
921 }
922
Rui Ueyama95769b42016-08-31 20:03:54 +0000923 while (!atEOF() && !Error && peek() != "}") {
George Rimar20b65982016-08-31 09:08:26 +0000924 StringRef VerStr = next();
925 if (VerStr == "{") {
Rui Ueyama95769b42016-08-31 20:03:54 +0000926 setError("anonymous version definition is used in "
927 "combination with other version definitions");
George Rimar20b65982016-08-31 09:08:26 +0000928 return;
929 }
930 expect("{");
Rui Ueyama95769b42016-08-31 20:03:54 +0000931 readVersionDeclaration(VerStr);
George Rimar20b65982016-08-31 09:08:26 +0000932 }
933}
934
Rui Ueyama95769b42016-08-31 20:03:54 +0000935void ScriptParser::readVersion() {
936 expect("{");
937 readVersionScriptCommand();
938 expect("}");
939}
940
George Rimar20b65982016-08-31 09:08:26 +0000941void ScriptParser::readLinkerScript() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000942 while (!atEOF()) {
943 StringRef Tok = next();
Rui Ueyamaa27eecc2016-09-02 18:52:41 +0000944 if (Tok == ";")
945 continue;
946
Eugene Leviant20d03192016-09-16 15:30:47 +0000947 if (Tok == "ASSERT") {
948 Opt.Commands.emplace_back(new AssertCommand(readAssert()));
949 } else if (Tok == "ENTRY") {
Rui Ueyamaa27eecc2016-09-02 18:52:41 +0000950 readEntry();
951 } else if (Tok == "EXTERN") {
952 readExtern();
953 } else if (Tok == "GROUP" || Tok == "INPUT") {
954 readGroup();
955 } else if (Tok == "INCLUDE") {
956 readInclude();
957 } else if (Tok == "OUTPUT") {
958 readOutput();
959 } else if (Tok == "OUTPUT_ARCH") {
960 readOutputArch();
961 } else if (Tok == "OUTPUT_FORMAT") {
962 readOutputFormat();
963 } else if (Tok == "PHDRS") {
964 readPhdrs();
965 } else if (Tok == "SEARCH_DIR") {
966 readSearchDir();
967 } else if (Tok == "SECTIONS") {
968 readSections();
969 } else if (Tok == "VERSION") {
970 readVersion();
Eugene Leviantdb741e72016-09-07 07:08:43 +0000971 } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok, true)) {
Eugene Leviant20d03192016-09-16 15:30:47 +0000972 Opt.Commands.emplace_back(Cmd);
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000973 } else {
George Rimar57610422016-03-11 14:43:02 +0000974 setError("unknown directive: " + Tok);
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000975 }
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000976 }
977}
978
Rui Ueyama717677a2016-02-11 21:17:59 +0000979void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000980 if (IsUnderSysroot && S.startswith("/")) {
981 SmallString<128> Path;
982 (Config->Sysroot + S).toStringRef(Path);
983 if (sys::fs::exists(Path)) {
984 Driver->addFile(Saver.save(Path.str()));
985 return;
986 }
987 }
988
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +0000989 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +0000990 Driver->addFile(S);
991 } else if (S.startswith("=")) {
992 if (Config->Sysroot.empty())
993 Driver->addFile(S.substr(1));
994 else
995 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
996 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +0000997 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +0000998 } else if (sys::fs::exists(S)) {
999 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +00001000 } else {
1001 std::string Path = findFromSearchPaths(S);
1002 if (Path.empty())
George Rimar777f9632016-03-12 08:31:34 +00001003 setError("unable to find " + S);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001004 else
1005 Driver->addFile(Saver.save(Path));
Rui Ueyama52a15092015-10-11 03:28:42 +00001006 }
1007}
1008
Rui Ueyama717677a2016-02-11 21:17:59 +00001009void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001010 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +00001011 bool Orig = Config->AsNeeded;
1012 Config->AsNeeded = true;
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001013 while (!Error && !skip(")"))
George Rimarcd574a52016-09-09 14:35:36 +00001014 addFile(unquote(next()));
Rui Ueyama35da9b62015-10-11 20:59:12 +00001015 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001016}
1017
Rui Ueyama717677a2016-02-11 21:17:59 +00001018void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +00001019 // -e <symbol> takes predecence over ENTRY(<symbol>).
1020 expect("(");
1021 StringRef Tok = next();
1022 if (Config->Entry.empty())
1023 Config->Entry = Tok;
1024 expect(")");
1025}
1026
Rui Ueyama717677a2016-02-11 21:17:59 +00001027void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +00001028 expect("(");
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001029 while (!Error && !skip(")"))
1030 Config->Undefined.push_back(next());
George Rimar83f406c2015-10-19 17:35:12 +00001031}
1032
Rui Ueyama717677a2016-02-11 21:17:59 +00001033void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001034 expect("(");
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001035 while (!Error && !skip(")")) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001036 StringRef Tok = next();
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001037 if (Tok == "AS_NEEDED")
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001038 readAsNeeded();
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001039 else
George Rimarcd574a52016-09-09 14:35:36 +00001040 addFile(unquote(Tok));
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001041 }
1042}
1043
Rui Ueyama717677a2016-02-11 21:17:59 +00001044void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001045 StringRef Tok = next();
George Rimarcd574a52016-09-09 14:35:36 +00001046 auto MBOrErr = MemoryBuffer::getFile(unquote(Tok));
Rui Ueyama025d59b2016-02-02 20:27:59 +00001047 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +00001048 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001049 return;
1050 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001051 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Rui Ueyamaa47ee682015-10-11 01:53:04 +00001052 StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
1053 std::vector<StringRef> V = tokenize(S);
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001054 Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001055}
1056
Rui Ueyama717677a2016-02-11 21:17:59 +00001057void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +00001058 // -o <file> takes predecence over OUTPUT(<file>).
1059 expect("(");
1060 StringRef Tok = next();
1061 if (Config->OutputFile.empty())
George Rimarcd574a52016-09-09 14:35:36 +00001062 Config->OutputFile = unquote(Tok);
Rui Ueyamaee592822015-10-07 00:25:09 +00001063 expect(")");
1064}
1065
Rui Ueyama717677a2016-02-11 21:17:59 +00001066void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +00001067 // Error checking only for now.
1068 expect("(");
1069 next();
1070 expect(")");
1071}
1072
Rui Ueyama717677a2016-02-11 21:17:59 +00001073void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001074 // Error checking only for now.
1075 expect("(");
1076 next();
Davide Italiano6836c612015-10-12 21:08:41 +00001077 StringRef Tok = next();
1078 if (Tok == ")")
George Rimar6c55f0e2016-09-08 08:20:30 +00001079 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +00001080 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +00001081 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001082 return;
1083 }
Davide Italiano6836c612015-10-12 21:08:41 +00001084 next();
1085 expect(",");
1086 next();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001087 expect(")");
1088}
1089
Eugene Leviantbbe38602016-07-19 09:25:43 +00001090void ScriptParser::readPhdrs() {
1091 expect("{");
1092 while (!Error && !skip("}")) {
1093 StringRef Tok = next();
Eugene Leviant56b21c82016-09-09 09:46:16 +00001094 Opt.PhdrsCommands.push_back(
1095 {Tok, PT_NULL, false, false, UINT_MAX, nullptr});
Eugene Leviantbbe38602016-07-19 09:25:43 +00001096 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
1097
1098 PhdrCmd.Type = readPhdrType();
1099 do {
1100 Tok = next();
1101 if (Tok == ";")
1102 break;
1103 if (Tok == "FILEHDR")
1104 PhdrCmd.HasFilehdr = true;
1105 else if (Tok == "PHDRS")
1106 PhdrCmd.HasPhdrs = true;
Eugene Leviant56b21c82016-09-09 09:46:16 +00001107 else if (Tok == "AT")
1108 PhdrCmd.LMAExpr = readParenExpr();
Eugene Leviant865bf862016-07-21 10:43:25 +00001109 else if (Tok == "FLAGS") {
1110 expect("(");
Rafael Espindolaeb685cd2016-08-02 22:14:57 +00001111 // Passing 0 for the value of dot is a bit of a hack. It means that
1112 // we accept expressions like ".|1".
1113 PhdrCmd.Flags = readExpr()(0);
Eugene Leviant865bf862016-07-21 10:43:25 +00001114 expect(")");
1115 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +00001116 setError("unexpected header attribute: " + Tok);
1117 } while (!Error);
1118 }
1119}
1120
Rui Ueyama717677a2016-02-11 21:17:59 +00001121void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +00001122 expect("(");
Rui Ueyama86c5fb82016-09-08 23:26:54 +00001123 StringRef Tok = next();
Rui Ueyama6c7ad132016-09-02 19:20:33 +00001124 if (!Config->Nostdlib)
George Rimarcd574a52016-09-09 14:35:36 +00001125 Config->SearchPaths.push_back(unquote(Tok));
Davide Italiano68a39a62015-10-08 17:51:41 +00001126 expect(")");
1127}
1128
Rui Ueyama717677a2016-02-11 21:17:59 +00001129void ScriptParser::readSections() {
Eugene Leviante05336ff2016-09-14 08:32:36 +00001130 Opt.HasSections = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001131 expect("{");
George Rimar652852c2016-04-16 10:10:32 +00001132 while (!Error && !skip("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +00001133 StringRef Tok = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +00001134 BaseCommand *Cmd = readProvideOrAssignment(Tok, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001135 if (!Cmd) {
1136 if (Tok == "ASSERT")
1137 Cmd = new AssertCommand(readAssert());
1138 else
1139 Cmd = readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +00001140 }
Rui Ueyama10416562016-08-04 02:03:27 +00001141 Opt.Commands.emplace_back(Cmd);
George Rimar652852c2016-04-16 10:10:32 +00001142 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001143}
1144
Rui Ueyama708019c2016-07-24 18:19:40 +00001145static int precedence(StringRef Op) {
1146 return StringSwitch<int>(Op)
Rui Ueyama0120e3f2016-09-23 18:06:51 +00001147 .Cases("*", "/", 5)
1148 .Cases("+", "-", 4)
1149 .Cases("<<", ">>", 3)
Rui Ueyama9c4ac5f2016-09-23 22:22:34 +00001150 .Cases("<", "<=", ">", ">=", "==", "!=", 2)
Rui Ueyama0120e3f2016-09-23 18:06:51 +00001151 .Cases("&", "|", 1)
Rui Ueyama708019c2016-07-24 18:19:40 +00001152 .Default(-1);
1153}
1154
George Rimarc91930a2016-09-02 21:17:20 +00001155Regex ScriptParser::readFilePatterns() {
Rui Ueyama10416562016-08-04 02:03:27 +00001156 std::vector<StringRef> V;
1157 while (!Error && !skip(")"))
1158 V.push_back(next());
George Rimarc91930a2016-09-02 21:17:20 +00001159 return compileGlobPatterns(V);
George Rimar0702c4e2016-07-29 15:32:46 +00001160}
1161
George Rimarbe394db2016-09-16 20:21:55 +00001162SortSectionPolicy ScriptParser::readSortKind() {
Rui Ueyama742c3832016-08-04 22:27:00 +00001163 if (skip("SORT") || skip("SORT_BY_NAME"))
George Rimarbe394db2016-09-16 20:21:55 +00001164 return SortSectionPolicy::Name;
Rui Ueyama742c3832016-08-04 22:27:00 +00001165 if (skip("SORT_BY_ALIGNMENT"))
George Rimarbe394db2016-09-16 20:21:55 +00001166 return SortSectionPolicy::Alignment;
George Rimar575208c2016-09-15 19:15:12 +00001167 if (skip("SORT_BY_INIT_PRIORITY"))
George Rimarbe394db2016-09-16 20:21:55 +00001168 return SortSectionPolicy::Priority;
George Rimarbe394db2016-09-16 20:21:55 +00001169 if (skip("SORT_NONE"))
Rui Ueyamab2a0abd2016-09-16 21:14:55 +00001170 return SortSectionPolicy::None;
1171 return SortSectionPolicy::Default;
George Rimarbe394db2016-09-16 20:21:55 +00001172}
1173
George Rimar395281c2016-09-16 17:42:10 +00001174// Method reads a list of sequence of excluded files and section globs given in
1175// a following form: ((EXCLUDE_FILE(file_pattern+))? section_pattern+)+
1176// Example: *(.foo.1 EXCLUDE_FILE (*a.o) .foo.2 EXCLUDE_FILE (*b.o) .foo.3)
George Rimaraf03be12016-09-17 19:17:25 +00001177// The semantics of that is next:
1178// * Include .foo.1 from every file.
1179// * Include .foo.2 from every file but a.o
1180// * Include .foo.3 from every file but b.o
George Rimar07171f22016-09-21 15:56:44 +00001181std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
1182 std::vector<SectionPattern> Ret;
George Rimar601e9892016-09-21 08:53:21 +00001183 while (!Error && peek() != ")") {
1184 Regex ExcludeFileRe;
George Rimar395281c2016-09-16 17:42:10 +00001185 if (skip("EXCLUDE_FILE")) {
George Rimar395281c2016-09-16 17:42:10 +00001186 expect("(");
1187 ExcludeFileRe = readFilePatterns();
George Rimar395281c2016-09-16 17:42:10 +00001188 }
1189
George Rimar601e9892016-09-21 08:53:21 +00001190 std::vector<StringRef> V;
1191 while (!Error && peek() != ")" && peek() != "EXCLUDE_FILE")
1192 V.push_back(next());
1193
1194 if (!V.empty())
George Rimar07171f22016-09-21 15:56:44 +00001195 Ret.push_back({std::move(ExcludeFileRe), compileGlobPatterns(V)});
George Rimar601e9892016-09-21 08:53:21 +00001196 else
1197 setError("section pattern is expected");
George Rimar395281c2016-09-16 17:42:10 +00001198 }
George Rimar07171f22016-09-21 15:56:44 +00001199 return Ret;
George Rimar395281c2016-09-16 17:42:10 +00001200}
1201
George Rimar07171f22016-09-21 15:56:44 +00001202// Section pattern grammar can have complex expressions, for example:
1203// *(SORT(.foo.* EXCLUDE_FILE (*file1.o) .bar.*) .bar.* SORT(.zed.*))
1204// Generally is a sequence of globs and excludes that may be wrapped in a SORT()
1205// commands, like: SORT(glob0) glob1 glob2 SORT(glob4)
1206// This methods handles wrapping sequences of excluded files and section globs
1207// into SORT() if that needed and reads them all.
George Rimara2496cb2016-08-30 09:46:59 +00001208InputSectionDescription *
1209ScriptParser::readInputSectionRules(StringRef FilePattern) {
George Rimarc91930a2016-09-02 21:17:20 +00001210 auto *Cmd = new InputSectionDescription(FilePattern);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001211 expect("(");
George Rimar07171f22016-09-21 15:56:44 +00001212 while (!HasError && !skip(")")) {
1213 SortSectionPolicy Outer = readSortKind();
1214 SortSectionPolicy Inner = SortSectionPolicy::Default;
1215 std::vector<SectionPattern> V;
1216 if (Outer != SortSectionPolicy::Default) {
George Rimar350ece42016-08-03 08:35:59 +00001217 expect("(");
George Rimar07171f22016-09-21 15:56:44 +00001218 Inner = readSortKind();
1219 if (Inner != SortSectionPolicy::Default) {
1220 expect("(");
1221 V = readInputSectionsList();
1222 expect(")");
1223 } else {
1224 V = readInputSectionsList();
1225 }
George Rimar350ece42016-08-03 08:35:59 +00001226 expect(")");
1227 } else {
George Rimar07171f22016-09-21 15:56:44 +00001228 V = readInputSectionsList();
George Rimar350ece42016-08-03 08:35:59 +00001229 }
George Rimar0702c4e2016-07-29 15:32:46 +00001230
George Rimar07171f22016-09-21 15:56:44 +00001231 for (SectionPattern &Pat : V) {
1232 Pat.SortInner = Inner;
1233 Pat.SortOuter = Outer;
1234 }
1235
1236 std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns));
1237 }
Rui Ueyama10416562016-08-04 02:03:27 +00001238 return Cmd;
Davide Italianoe7282792016-07-27 01:44:01 +00001239}
1240
George Rimara2496cb2016-08-30 09:46:59 +00001241InputSectionDescription *
1242ScriptParser::readInputSectionDescription(StringRef Tok) {
George Rimar06598002016-07-28 21:51:30 +00001243 // Input section wildcard can be surrounded by KEEP.
1244 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
George Rimara2496cb2016-08-30 09:46:59 +00001245 if (Tok == "KEEP") {
George Rimar06598002016-07-28 21:51:30 +00001246 expect("(");
George Rimara2496cb2016-08-30 09:46:59 +00001247 StringRef FilePattern = next();
1248 InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
George Rimar06598002016-07-28 21:51:30 +00001249 expect(")");
Rui Ueyama4dc07be2016-09-17 02:23:40 +00001250 for (SectionPattern &Pat : Cmd->SectionPatterns)
1251 Opt.KeptSections.push_back(&Pat.SectionRe);
Rui Ueyama10416562016-08-04 02:03:27 +00001252 return Cmd;
George Rimar06598002016-07-28 21:51:30 +00001253 }
George Rimara2496cb2016-08-30 09:46:59 +00001254 return readInputSectionRules(Tok);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001255}
1256
George Rimar03fc0102016-07-28 07:18:23 +00001257void ScriptParser::readSort() {
1258 expect("(");
1259 expect("CONSTRUCTORS");
1260 expect(")");
1261}
1262
George Rimareefa7582016-08-04 09:29:31 +00001263Expr ScriptParser::readAssert() {
1264 expect("(");
1265 Expr E = readExpr();
1266 expect(",");
George Rimarcd574a52016-09-09 14:35:36 +00001267 StringRef Msg = unquote(next());
George Rimareefa7582016-08-04 09:29:31 +00001268 expect(")");
1269 return [=](uint64_t Dot) {
1270 uint64_t V = E(Dot);
1271 if (!V)
1272 error(Msg);
1273 return V;
1274 };
1275}
1276
Rui Ueyama25150e82016-09-06 17:46:43 +00001277// Reads a FILL(expr) command. We handle the FILL command as an
1278// alias for =fillexp section attribute, which is different from
1279// what GNU linkers do.
1280// https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
George Rimarff1f29e2016-09-06 13:51:57 +00001281std::vector<uint8_t> ScriptParser::readFill() {
1282 expect("(");
1283 std::vector<uint8_t> V = readOutputSectionFiller(next());
1284 expect(")");
1285 expect(";");
1286 return V;
1287}
1288
Rui Ueyama10416562016-08-04 02:03:27 +00001289OutputSectionCommand *
1290ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +00001291 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
George Rimar58e5c4d2016-07-25 08:29:46 +00001292
1293 // Read an address expression.
1294 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
1295 if (peek() != ":")
1296 Cmd->AddrExpr = readExpr();
1297
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001298 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +00001299
George Rimar8ceadb32016-08-17 07:44:19 +00001300 if (skip("AT"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001301 Cmd->LmaExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001302 if (skip("ALIGN"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001303 Cmd->AlignExpr = readParenExpr();
George Rimardb24d9c2016-08-19 15:18:23 +00001304 if (skip("SUBALIGN"))
1305 Cmd->SubalignExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001306
Davide Italiano246f6812016-07-22 03:36:24 +00001307 // Parse constraints.
1308 if (skip("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001309 Cmd->Constraint = ConstraintKind::ReadOnly;
Davide Italiano246f6812016-07-22 03:36:24 +00001310 if (skip("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001311 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001312 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001313
Rui Ueyama025d59b2016-02-02 20:27:59 +00001314 while (!Error && !skip("}")) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001315 StringRef Tok = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +00001316 if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok, false))
Eugene Leviantceabe802016-08-11 07:56:43 +00001317 Cmd->Commands.emplace_back(Assignment);
George Rimare38cbab2016-09-26 19:22:50 +00001318 else if (BytesDataCommand *Data = readBytesDataCommand(Tok))
1319 Cmd->Commands.emplace_back(Data);
George Rimarff1f29e2016-09-06 13:51:57 +00001320 else if (Tok == "FILL")
1321 Cmd->Filler = readFill();
Eugene Leviantceabe802016-08-11 07:56:43 +00001322 else if (Tok == "SORT")
George Rimar03fc0102016-07-28 07:18:23 +00001323 readSort();
George Rimara2496cb2016-08-30 09:46:59 +00001324 else if (peek() == "(")
1325 Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
Eugene Leviantceabe802016-08-11 07:56:43 +00001326 else
1327 setError("unknown command " + Tok);
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001328 }
George Rimar076fe152016-07-21 06:43:01 +00001329 Cmd->Phdrs = readOutputSectionPhdrs();
George Rimar4ebc5622016-09-23 13:29:20 +00001330
1331 if (skip("="))
1332 Cmd->Filler = readOutputSectionFiller(next());
1333 else if (peek().startswith("="))
George Rimarff1f29e2016-09-06 13:51:57 +00001334 Cmd->Filler = readOutputSectionFiller(next().drop_front());
George Rimar4ebc5622016-09-23 13:29:20 +00001335
Rui Ueyama10416562016-08-04 02:03:27 +00001336 return Cmd;
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001337}
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001338
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001339// Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
1340// https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
1341//
1342// ld.gold is not fully compatible with ld.bfd. ld.bfd handles
1343// hexstrings as blobs of arbitrary sizes, while ld.gold handles them
1344// as 32-bit big-endian values. We will do the same as ld.gold does
1345// because it's simpler than what ld.bfd does.
George Rimarff1f29e2016-09-06 13:51:57 +00001346std::vector<uint8_t> ScriptParser::readOutputSectionFiller(StringRef Tok) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001347 uint32_t V;
George Rimarff1f29e2016-09-06 13:51:57 +00001348 if (Tok.getAsInteger(0, V)) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001349 setError("invalid filler expression: " + Tok);
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001350 return {};
George Rimare2ee72b2016-02-26 14:48:31 +00001351 }
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001352 return {uint8_t(V >> 24), uint8_t(V >> 16), uint8_t(V >> 8), uint8_t(V)};
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001353}
1354
Petr Hoseka35e39c2016-08-16 01:11:16 +00001355SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
Eugene Levianta31c91b2016-07-22 07:38:40 +00001356 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +00001357 SymbolAssignment *Cmd = readAssignment(next());
Petr Hoseka35e39c2016-08-16 01:11:16 +00001358 Cmd->Provide = Provide;
Rui Ueyama174e0a12016-07-29 00:29:25 +00001359 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001360 expect(")");
1361 expect(";");
Rui Ueyama10416562016-08-04 02:03:27 +00001362 return Cmd;
Eugene Levianteda81a12016-07-12 06:39:48 +00001363}
1364
Eugene Leviantdb741e72016-09-07 07:08:43 +00001365SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok,
1366 bool MakeAbsolute) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001367 SymbolAssignment *Cmd = nullptr;
1368 if (peek() == "=" || peek() == "+=") {
1369 Cmd = readAssignment(Tok);
1370 expect(";");
1371 } else if (Tok == "PROVIDE") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001372 Cmd = readProvideHidden(true, false);
1373 } else if (Tok == "HIDDEN") {
1374 Cmd = readProvideHidden(false, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001375 } else if (Tok == "PROVIDE_HIDDEN") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001376 Cmd = readProvideHidden(true, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001377 }
Eugene Leviantdb741e72016-09-07 07:08:43 +00001378 if (Cmd && MakeAbsolute)
1379 Cmd->IsAbsolute = true;
Eugene Leviantceabe802016-08-11 07:56:43 +00001380 return Cmd;
1381}
1382
George Rimar30835ea2016-07-28 21:08:56 +00001383static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
1384 if (S == ".")
1385 return Dot;
George Rimar884e7862016-09-08 08:19:13 +00001386 return ScriptBase->getSymbolValue(S);
George Rimare32a3592016-08-10 07:59:34 +00001387}
1388
George Rimar30835ea2016-07-28 21:08:56 +00001389SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1390 StringRef Op = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +00001391 bool IsAbsolute = false;
1392 Expr E;
George Rimar30835ea2016-07-28 21:08:56 +00001393 assert(Op == "=" || Op == "+=");
Eugene Leviantdb741e72016-09-07 07:08:43 +00001394 if (skip("ABSOLUTE")) {
1395 E = readParenExpr();
1396 IsAbsolute = true;
1397 } else {
1398 E = readExpr();
1399 }
George Rimar30835ea2016-07-28 21:08:56 +00001400 if (Op == "+=")
1401 E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
Eugene Leviantdb741e72016-09-07 07:08:43 +00001402 return new SymbolAssignment(Name, E, IsAbsolute);
George Rimar30835ea2016-07-28 21:08:56 +00001403}
1404
1405// This is an operator-precedence parser to parse a linker
1406// script expression.
1407Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
1408
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001409static Expr combine(StringRef Op, Expr L, Expr R) {
1410 if (Op == "*")
1411 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1412 if (Op == "/") {
1413 return [=](uint64_t Dot) -> uint64_t {
1414 uint64_t RHS = R(Dot);
1415 if (RHS == 0) {
1416 error("division by zero");
1417 return 0;
1418 }
1419 return L(Dot) / RHS;
1420 };
1421 }
1422 if (Op == "+")
1423 return [=](uint64_t Dot) { return L(Dot) + R(Dot); };
1424 if (Op == "-")
1425 return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
George Rimarc8ccd1f2016-09-23 13:13:55 +00001426 if (Op == "<<")
1427 return [=](uint64_t Dot) { return L(Dot) << R(Dot); };
1428 if (Op == ">>")
1429 return [=](uint64_t Dot) { return L(Dot) >> R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001430 if (Op == "<")
1431 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
1432 if (Op == ">")
1433 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
1434 if (Op == ">=")
1435 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
1436 if (Op == "<=")
1437 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
1438 if (Op == "==")
1439 return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
1440 if (Op == "!=")
1441 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
1442 if (Op == "&")
1443 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
Rafael Espindolacc3dd622016-08-22 21:33:35 +00001444 if (Op == "|")
1445 return [=](uint64_t Dot) { return L(Dot) | R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001446 llvm_unreachable("invalid operator");
1447}
1448
Rui Ueyama708019c2016-07-24 18:19:40 +00001449// This is a part of the operator-precedence parser. This function
1450// assumes that the remaining token stream starts with an operator.
1451Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1452 while (!atEOF() && !Error) {
1453 // Read an operator and an expression.
1454 StringRef Op1 = peek();
1455 if (Op1 == "?")
1456 return readTernary(Lhs);
1457 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +00001458 break;
Rui Ueyama708019c2016-07-24 18:19:40 +00001459 next();
1460 Expr Rhs = readPrimary();
1461
1462 // Evaluate the remaining part of the expression first if the
1463 // next operator has greater precedence than the previous one.
1464 // For example, if we have read "+" and "3", and if the next
1465 // operator is "*", then we'll evaluate 3 * ... part first.
1466 while (!atEOF()) {
1467 StringRef Op2 = peek();
1468 if (precedence(Op2) <= precedence(Op1))
1469 break;
1470 Rhs = readExpr1(Rhs, precedence(Op2));
1471 }
1472
1473 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +00001474 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001475 return Lhs;
1476}
1477
1478uint64_t static getConstant(StringRef S) {
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001479 if (S == "COMMONPAGESIZE")
Rui Ueyama708019c2016-07-24 18:19:40 +00001480 return Target->PageSize;
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001481 if (S == "MAXPAGESIZE")
Petr Hosek997f8832016-09-28 15:20:47 +00001482 return Config->MaxPageSize;
Rui Ueyama708019c2016-07-24 18:19:40 +00001483 error("unknown constant: " + S);
1484 return 0;
1485}
1486
Rui Ueyama626e0b02016-09-02 18:19:00 +00001487// Parses Tok as an integer. Returns true if successful.
1488// It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1489// and decimal numbers. Decimal numbers may have "K" (kilo) or
1490// "M" (mega) prefixes.
George Rimar9f2f7ad2016-09-02 16:01:42 +00001491static bool readInteger(StringRef Tok, uint64_t &Result) {
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001492 if (Tok.startswith("-")) {
1493 if (!readInteger(Tok.substr(1), Result))
1494 return false;
1495 Result = -Result;
1496 return true;
1497 }
George Rimar9f2f7ad2016-09-02 16:01:42 +00001498 if (Tok.startswith_lower("0x"))
1499 return !Tok.substr(2).getAsInteger(16, Result);
1500 if (Tok.endswith_lower("H"))
1501 return !Tok.drop_back().getAsInteger(16, Result);
1502
1503 int Suffix = 1;
1504 if (Tok.endswith_lower("K")) {
1505 Suffix = 1024;
1506 Tok = Tok.drop_back();
1507 } else if (Tok.endswith_lower("M")) {
1508 Suffix = 1024 * 1024;
1509 Tok = Tok.drop_back();
1510 }
1511 if (Tok.getAsInteger(10, Result))
1512 return false;
1513 Result *= Suffix;
1514 return true;
1515}
1516
George Rimare38cbab2016-09-26 19:22:50 +00001517BytesDataCommand *ScriptParser::readBytesDataCommand(StringRef Tok) {
1518 int Size = StringSwitch<unsigned>(Tok)
1519 .Case("BYTE", 1)
1520 .Case("SHORT", 2)
1521 .Case("LONG", 4)
1522 .Case("QUAD", 8)
1523 .Default(-1);
1524 if (Size == -1)
1525 return nullptr;
1526
1527 expect("(");
1528 uint64_t Val = 0;
1529 StringRef S = next();
1530 if (!readInteger(S, Val))
1531 setError("unexpected value: " + S);
1532 expect(")");
1533 return new BytesDataCommand(Val, Size);
1534}
1535
Rui Ueyama708019c2016-07-24 18:19:40 +00001536Expr ScriptParser::readPrimary() {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001537 if (peek() == "(")
1538 return readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001539
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001540 StringRef Tok = next();
Rui Ueyama708019c2016-07-24 18:19:40 +00001541
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001542 if (Tok == "~") {
1543 Expr E = readPrimary();
1544 return [=](uint64_t Dot) { return ~E(Dot); };
1545 }
1546 if (Tok == "-") {
1547 Expr E = readPrimary();
1548 return [=](uint64_t Dot) { return -E(Dot); };
1549 }
1550
Rui Ueyama708019c2016-07-24 18:19:40 +00001551 // Built-in functions are parsed here.
1552 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
George Rimar96659df2016-08-30 09:54:01 +00001553 if (Tok == "ADDR") {
1554 expect("(");
1555 StringRef Name = next();
1556 expect(")");
George Rimar884e7862016-09-08 08:19:13 +00001557 return
1558 [=](uint64_t Dot) { return ScriptBase->getOutputSectionAddress(Name); };
George Rimar96659df2016-08-30 09:54:01 +00001559 }
George Rimareefa7582016-08-04 09:29:31 +00001560 if (Tok == "ASSERT")
1561 return readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001562 if (Tok == "ALIGN") {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001563 Expr E = readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001564 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1565 }
1566 if (Tok == "CONSTANT") {
1567 expect("(");
1568 StringRef Tok = next();
1569 expect(")");
1570 return [=](uint64_t Dot) { return getConstant(Tok); };
1571 }
George Rimarf34f45f2016-09-23 13:17:23 +00001572 if (Tok == "DEFINED") {
1573 expect("(");
1574 StringRef Tok = next();
1575 expect(")");
George Rimarf2821022016-09-26 11:00:48 +00001576 return [=](uint64_t Dot) { return ScriptBase->isDefined(Tok) ? 1 : 0; };
George Rimarf34f45f2016-09-23 13:17:23 +00001577 }
Rafael Espindola54c145c2016-07-28 18:16:24 +00001578 if (Tok == "SEGMENT_START") {
1579 expect("(");
1580 next();
1581 expect(",");
George Rimar8c658bf2016-09-17 18:14:56 +00001582 Expr E = readExpr();
Rafael Espindola54c145c2016-07-28 18:16:24 +00001583 expect(")");
George Rimar8c658bf2016-09-17 18:14:56 +00001584 return [=](uint64_t Dot) { return E(Dot); };
Rafael Espindola54c145c2016-07-28 18:16:24 +00001585 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001586 if (Tok == "DATA_SEGMENT_ALIGN") {
1587 expect("(");
1588 Expr E = readExpr();
1589 expect(",");
1590 readExpr();
1591 expect(")");
Rui Ueyamaf7791bb2016-07-26 19:34:10 +00001592 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001593 }
1594 if (Tok == "DATA_SEGMENT_END") {
1595 expect("(");
1596 expect(".");
1597 expect(")");
1598 return [](uint64_t Dot) { return Dot; };
1599 }
George Rimar276b4e62016-07-26 17:58:44 +00001600 // GNU linkers implements more complicated logic to handle
1601 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1602 // the next page boundary for simplicity.
1603 if (Tok == "DATA_SEGMENT_RELRO_END") {
1604 expect("(");
Rafael Espindola97bdc722016-09-14 19:14:01 +00001605 readExpr();
George Rimar276b4e62016-07-26 17:58:44 +00001606 expect(",");
1607 readExpr();
1608 expect(")");
1609 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1610 }
George Rimar9e694502016-07-29 16:18:47 +00001611 if (Tok == "SIZEOF") {
1612 expect("(");
1613 StringRef Name = next();
1614 expect(")");
George Rimar884e7862016-09-08 08:19:13 +00001615 return [=](uint64_t Dot) { return ScriptBase->getOutputSectionSize(Name); };
George Rimar9e694502016-07-29 16:18:47 +00001616 }
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001617 if (Tok == "ALIGNOF") {
1618 expect("(");
1619 StringRef Name = next();
1620 expect(")");
1621 return
1622 [=](uint64_t Dot) { return ScriptBase->getOutputSectionAlign(Name); };
1623 }
George Rimare32a3592016-08-10 07:59:34 +00001624 if (Tok == "SIZEOF_HEADERS")
George Rimar884e7862016-09-08 08:19:13 +00001625 return [=](uint64_t Dot) { return ScriptBase->getHeaderSize(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001626
George Rimar9f2f7ad2016-09-02 16:01:42 +00001627 // Tok is a literal number.
1628 uint64_t V;
1629 if (readInteger(Tok, V))
1630 return [=](uint64_t Dot) { return V; };
1631
1632 // Tok is a symbol name.
1633 if (Tok != "." && !isValidCIdentifier(Tok))
1634 setError("malformed number: " + Tok);
1635 return [=](uint64_t Dot) { return getSymbolValue(Tok, Dot); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001636}
1637
1638Expr ScriptParser::readTernary(Expr Cond) {
1639 next();
1640 Expr L = readExpr();
1641 expect(":");
1642 Expr R = readExpr();
1643 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1644}
1645
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001646Expr ScriptParser::readParenExpr() {
1647 expect("(");
1648 Expr E = readExpr();
1649 expect(")");
1650 return E;
1651}
1652
Eugene Leviantbbe38602016-07-19 09:25:43 +00001653std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1654 std::vector<StringRef> Phdrs;
1655 while (!Error && peek().startswith(":")) {
1656 StringRef Tok = next();
1657 Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
1658 if (Tok.empty()) {
1659 setError("section header name is empty");
1660 break;
1661 }
Rui Ueyama047404f2016-07-20 19:36:36 +00001662 Phdrs.push_back(Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001663 }
1664 return Phdrs;
1665}
1666
1667unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001668 StringRef Tok = next();
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001669 unsigned Ret = StringSwitch<unsigned>(Tok)
George Rimar6c55f0e2016-09-08 08:20:30 +00001670 .Case("PT_NULL", PT_NULL)
1671 .Case("PT_LOAD", PT_LOAD)
1672 .Case("PT_DYNAMIC", PT_DYNAMIC)
1673 .Case("PT_INTERP", PT_INTERP)
1674 .Case("PT_NOTE", PT_NOTE)
1675 .Case("PT_SHLIB", PT_SHLIB)
1676 .Case("PT_PHDR", PT_PHDR)
1677 .Case("PT_TLS", PT_TLS)
1678 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1679 .Case("PT_GNU_STACK", PT_GNU_STACK)
1680 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1681 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001682
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001683 if (Ret == (unsigned)-1) {
1684 setError("invalid program header type: " + Tok);
1685 return PT_NULL;
1686 }
1687 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001688}
1689
Rui Ueyama95769b42016-08-31 20:03:54 +00001690void ScriptParser::readVersionDeclaration(StringRef VerStr) {
George Rimar20b65982016-08-31 09:08:26 +00001691 // Identifiers start at 2 because 0 and 1 are reserved
1692 // for VER_NDX_LOCAL and VER_NDX_GLOBAL constants.
1693 size_t VersionId = Config->VersionDefinitions.size() + 2;
1694 Config->VersionDefinitions.push_back({VerStr, VersionId});
1695
1696 if (skip("global:") || peek() != "local:")
1697 readGlobal(VerStr);
1698 if (skip("local:"))
1699 readLocal();
1700 expect("}");
1701
1702 // Each version may have a parent version. For example, "Ver2" defined as
1703 // "Ver2 { global: foo; local: *; } Ver1;" has "Ver1" as a parent. This
1704 // version hierarchy is, probably against your instinct, purely for human; the
1705 // runtime doesn't care about them at all. In LLD, we simply skip the token.
1706 if (!VerStr.empty() && peek() != ";")
1707 next();
1708 expect(";");
1709}
1710
1711void ScriptParser::readLocal() {
1712 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1713 expect("*");
1714 expect(";");
1715}
1716
1717void ScriptParser::readExtern(std::vector<SymbolVersion> *Globals) {
George Rimarcd574a52016-09-09 14:35:36 +00001718 expect("\"C++\"");
George Rimar20b65982016-08-31 09:08:26 +00001719 expect("{");
1720
1721 for (;;) {
1722 if (peek() == "}" || Error)
1723 break;
George Rimarcd574a52016-09-09 14:35:36 +00001724 bool HasWildcard = !peek().startswith("\"") && hasWildcard(peek());
1725 Globals->push_back({unquote(next()), true, HasWildcard});
George Rimar20b65982016-08-31 09:08:26 +00001726 expect(";");
1727 }
1728
1729 expect("}");
1730 expect(";");
1731}
1732
1733void ScriptParser::readGlobal(StringRef VerStr) {
1734 std::vector<SymbolVersion> *Globals;
1735 if (VerStr.empty())
1736 Globals = &Config->VersionScriptGlobals;
1737 else
1738 Globals = &Config->VersionDefinitions.back().Globals;
1739
1740 for (;;) {
1741 if (skip("extern"))
1742 readExtern(Globals);
1743
1744 StringRef Cur = peek();
1745 if (Cur == "}" || Cur == "local:" || Error)
1746 return;
1747 next();
George Rimarcd574a52016-09-09 14:35:36 +00001748 Globals->push_back({unquote(Cur), false, hasWildcard(Cur)});
George Rimar20b65982016-08-31 09:08:26 +00001749 expect(";");
1750 }
1751}
1752
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001753static bool isUnderSysroot(StringRef Path) {
1754 if (Config->Sysroot == "")
1755 return false;
1756 for (; !Path.empty(); Path = sys::path::parent_path(Path))
1757 if (sys::fs::equivalent(Config->Sysroot, Path))
1758 return true;
1759 return false;
1760}
1761
Rui Ueyama07320e42016-04-20 20:13:41 +00001762void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001763 StringRef Path = MB.getBufferIdentifier();
George Rimar20b65982016-08-31 09:08:26 +00001764 ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).readLinkerScript();
1765}
1766
1767void elf::readVersionScript(MemoryBufferRef MB) {
1768 ScriptParser(MB.getBuffer(), false).readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001769}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001770
Rui Ueyama07320e42016-04-20 20:13:41 +00001771template class elf::LinkerScript<ELF32LE>;
1772template class elf::LinkerScript<ELF32BE>;
1773template class elf::LinkerScript<ELF64LE>;
1774template class elf::LinkerScript<ELF64BE>;