blob: 7edfacae97a8e3a662dc37c9e9ebe267f9152583 [file] [log] [blame]
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001//===- LinkerScript.cpp ---------------------------------------------------===//
2//
3// The LLVM Linker
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains the parser/evaluator of the linker script.
Rui Ueyama629e0aa52016-07-21 19:45:22 +000011// It parses a linker script and write the result to Config or ScriptConfig
12// objects.
13//
14// If SECTIONS command is used, a ScriptConfig contains an AST
15// of the command which will later be consumed by createSections() and
16// assignAddresses().
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000017//
18//===----------------------------------------------------------------------===//
19
Rui Ueyama717677a2016-02-11 21:17:59 +000020#include "LinkerScript.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000021#include "Config.h"
22#include "Driver.h"
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +000023#include "InputSection.h"
George Rimar652852c2016-04-16 10:10:32 +000024#include "OutputSections.h"
Adhemerval Zanellae77b5bf2016-04-06 20:59:11 +000025#include "ScriptParser.h"
Rui Ueyama93c9af42016-06-29 08:01:32 +000026#include "Strings.h"
Eugene Levianteda81a12016-07-12 06:39:48 +000027#include "Symbols.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000028#include "SymbolTable.h"
Eugene Leviant467c4d52016-07-01 10:27:36 +000029#include "Target.h"
Eugene Leviantbbe38602016-07-19 09:25:43 +000030#include "Writer.h"
Rui Ueyama960504b2016-04-19 18:58:11 +000031#include "llvm/ADT/StringSwitch.h"
George Rimar652852c2016-04-16 10:10:32 +000032#include "llvm/Support/ELF.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000033#include "llvm/Support/FileSystem.h"
34#include "llvm/Support/MemoryBuffer.h"
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +000035#include "llvm/Support/Path.h"
Rui Ueyamaa47ee682015-10-11 01:53:04 +000036#include "llvm/Support/StringSaver.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000037
38using namespace llvm;
George Rimar652852c2016-04-16 10:10:32 +000039using namespace llvm::ELF;
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +000040using namespace llvm::object;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000041using namespace lld;
Rafael Espindolae0df00b2016-02-28 00:25:54 +000042using namespace lld::elf;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000043
George Rimar884e7862016-09-08 08:19:13 +000044LinkerScriptBase *elf::ScriptBase;
Rui Ueyama07320e42016-04-20 20:13:41 +000045ScriptConfiguration *elf::ScriptConfig;
Rui Ueyama717677a2016-02-11 21:17:59 +000046
George Rimar6c55f0e2016-09-08 08:20:30 +000047template <class ELFT> static void addRegular(SymbolAssignment *Cmd) {
Rui Ueyama16024212016-08-11 23:22:52 +000048 Symbol *Sym = Symtab<ELFT>::X->addRegular(Cmd->Name, STB_GLOBAL, STV_DEFAULT);
49 Sym->Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
50 Cmd->Sym = Sym->body();
Eugene Leviant20d03192016-09-16 15:30:47 +000051
52 // If we have no SECTIONS then we don't have '.' and don't call
53 // assignAddresses(). We calculate symbol value immediately in this case.
54 if (!ScriptConfig->HasSections)
55 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(0);
Eugene Leviantceabe802016-08-11 07:56:43 +000056}
57
Rui Ueyama0c70d3c2016-08-12 03:31:09 +000058template <class ELFT> static void addSynthetic(SymbolAssignment *Cmd) {
George Rimare1937bb2016-08-19 15:36:32 +000059 Symbol *Sym = Symtab<ELFT>::X->addSynthetic(
60 Cmd->Name, nullptr, 0, Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT);
Rui Ueyama16024212016-08-11 23:22:52 +000061 Cmd->Sym = Sym->body();
Eugene Leviantceabe802016-08-11 07:56:43 +000062}
63
Eugene Leviantdb741e72016-09-07 07:08:43 +000064template <class ELFT> static void addSymbol(SymbolAssignment *Cmd) {
65 if (Cmd->IsAbsolute)
66 addRegular<ELFT>(Cmd);
67 else
68 addSynthetic<ELFT>(Cmd);
69}
Rui Ueyama16024212016-08-11 23:22:52 +000070// If a symbol was in PROVIDE(), we need to define it only when
71// it is an undefined symbol.
72template <class ELFT> static bool shouldDefine(SymbolAssignment *Cmd) {
73 if (Cmd->Name == ".")
Eugene Leviantceabe802016-08-11 07:56:43 +000074 return false;
Rui Ueyama16024212016-08-11 23:22:52 +000075 if (!Cmd->Provide)
76 return true;
77 SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
78 return B && B->isUndefined();
Eugene Leviantceabe802016-08-11 07:56:43 +000079}
80
George Rimar076fe152016-07-21 06:43:01 +000081bool SymbolAssignment::classof(const BaseCommand *C) {
82 return C->Kind == AssignmentKind;
83}
84
85bool OutputSectionCommand::classof(const BaseCommand *C) {
86 return C->Kind == OutputSectionKind;
87}
88
George Rimareea31142016-07-21 14:26:59 +000089bool InputSectionDescription::classof(const BaseCommand *C) {
90 return C->Kind == InputSectionKind;
91}
92
George Rimareefa7582016-08-04 09:29:31 +000093bool AssertCommand::classof(const BaseCommand *C) {
94 return C->Kind == AssertKind;
95}
96
Rui Ueyama36a153c2016-07-23 14:09:58 +000097template <class ELFT> static bool isDiscarded(InputSectionBase<ELFT> *S) {
George Rimareea31142016-07-21 14:26:59 +000098 return !S || !S->Live;
Rui Ueyama717677a2016-02-11 21:17:59 +000099}
100
Rui Ueyamaf34d0e02016-08-12 01:24:53 +0000101template <class ELFT> LinkerScript<ELFT>::LinkerScript() {}
102template <class ELFT> LinkerScript<ELFT>::~LinkerScript() {}
103
Rui Ueyama07320e42016-04-20 20:13:41 +0000104template <class ELFT>
105bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) {
George Rimarc91930a2016-09-02 21:17:20 +0000106 for (Regex *Re : Opt.KeptSections)
Rafael Espindola042a3f22016-09-08 14:06:08 +0000107 if (Re->match(S->Name))
George Rimareea31142016-07-21 14:26:59 +0000108 return true;
109 return false;
110}
111
George Rimar575208c2016-09-15 19:15:12 +0000112static bool comparePriority(InputSectionData *A, InputSectionData *B) {
113 return getPriority(A->Name) < getPriority(B->Name);
114}
115
Rafael Espindolac0028d32016-09-08 20:47:52 +0000116static bool compareName(InputSectionData *A, InputSectionData *B) {
Rafael Espindola042a3f22016-09-08 14:06:08 +0000117 return A->Name < B->Name;
Rui Ueyama742c3832016-08-04 22:27:00 +0000118}
George Rimar350ece42016-08-03 08:35:59 +0000119
Rafael Espindolac0028d32016-09-08 20:47:52 +0000120static bool compareAlignment(InputSectionData *A, InputSectionData *B) {
Rui Ueyama742c3832016-08-04 22:27:00 +0000121 // ">" is not a mistake. Larger alignments are placed before smaller
122 // alignments in order to reduce the amount of padding necessary.
123 // This is compatible with GNU.
124 return A->Alignment > B->Alignment;
125}
George Rimar350ece42016-08-03 08:35:59 +0000126
Rafael Espindolac0028d32016-09-08 20:47:52 +0000127static std::function<bool(InputSectionData *, InputSectionData *)>
George Rimarbe394db2016-09-16 20:21:55 +0000128getComparator(SortSectionPolicy K) {
129 switch (K) {
130 case SortSectionPolicy::Alignment:
131 return compareAlignment;
132 case SortSectionPolicy::Name:
Rafael Espindolac0028d32016-09-08 20:47:52 +0000133 return compareName;
George Rimarbe394db2016-09-16 20:21:55 +0000134 case SortSectionPolicy::Priority:
135 return comparePriority;
136 default:
137 llvm_unreachable("unknown sort policy");
138 }
Rui Ueyama742c3832016-08-04 22:27:00 +0000139}
George Rimar0702c4e2016-07-29 15:32:46 +0000140
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000141template <class ELFT>
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000142static bool matchConstraints(ArrayRef<InputSectionBase<ELFT> *> Sections,
George Rimar06ae6832016-08-12 09:07:57 +0000143 ConstraintKind Kind) {
George Rimar8f66df92016-08-12 20:38:20 +0000144 if (Kind == ConstraintKind::NoConstraint)
145 return true;
Rafael Espindolae746e522016-09-21 18:33:44 +0000146 bool IsRW = llvm::any_of(Sections, [=](InputSectionData *Sec2) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000147 auto *Sec = static_cast<InputSectionBase<ELFT> *>(Sec2);
Rafael Espindolae746e522016-09-21 18:33:44 +0000148 return Sec->getSectionHdr()->sh_flags & SHF_WRITE;
George Rimar06ae6832016-08-12 09:07:57 +0000149 });
Rafael Espindolae746e522016-09-21 18:33:44 +0000150 return (IsRW && Kind == ConstraintKind::ReadWrite) ||
151 (!IsRW && Kind == ConstraintKind::ReadOnly);
George Rimar06ae6832016-08-12 09:07:57 +0000152}
153
George Rimar07171f22016-09-21 15:56:44 +0000154static void sortSections(InputSectionData **Begin, InputSectionData **End,
Rui Ueyamaee924702016-09-20 19:42:41 +0000155 SortSectionPolicy K) {
156 if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
George Rimar07171f22016-09-21 15:56:44 +0000157 std::stable_sort(Begin, End, getComparator(K));
Rui Ueyamaee924702016-09-20 19:42:41 +0000158}
159
Rafael Espindolad3190792016-09-16 15:10:23 +0000160// Compute and remember which sections the InputSectionDescription matches.
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000161template <class ELFT>
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000162void LinkerScript<ELFT>::computeInputSections(InputSectionDescription *I) {
Rui Ueyama4dc07be2016-09-17 02:23:40 +0000163 // Collects all sections that satisfy constraints of I
164 // and attach them to I.
165 for (SectionPattern &Pat : I->SectionPatterns) {
George Rimar07171f22016-09-21 15:56:44 +0000166 size_t SizeBefore = I->Sections.size();
George Rimar395281c2016-09-16 17:42:10 +0000167 for (ObjectFile<ELFT> *F : Symtab<ELFT>::X->getObjectFiles()) {
Rui Ueyama3ff27f42016-09-17 02:15:28 +0000168 StringRef Filename = sys::path::filename(F->getName());
Rafael Espindolaf135f0e2016-09-19 13:33:38 +0000169 if (!I->FileRe.match(Filename) || Pat.ExcludedFileRe.match(Filename))
Rui Ueyama3ff27f42016-09-17 02:15:28 +0000170 continue;
Rui Ueyama4dc07be2016-09-17 02:23:40 +0000171
Rui Ueyama3ff27f42016-09-17 02:15:28 +0000172 for (InputSectionBase<ELFT> *S : F->getSections())
Rafael Espindolaf135f0e2016-09-19 13:33:38 +0000173 if (!isDiscarded(S) && !S->OutSec && Pat.SectionRe.match(S->Name))
Rui Ueyama3ff27f42016-09-17 02:15:28 +0000174 I->Sections.push_back(S);
Rafael Espindolaf135f0e2016-09-19 13:33:38 +0000175 if (Pat.SectionRe.match("COMMON"))
Rui Ueyama3ff27f42016-09-17 02:15:28 +0000176 I->Sections.push_back(CommonInputSection<ELFT>::X);
George Rimar395281c2016-09-16 17:42:10 +0000177 }
Rafael Espindolad3190792016-09-16 15:10:23 +0000178
George Rimar07171f22016-09-21 15:56:44 +0000179 // Sort sections as instructed by SORT-family commands and --sort-section
180 // option. Because SORT-family commands can be nested at most two depth
181 // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
182 // line option is respected even if a SORT command is given, the exact
183 // behavior we have here is a bit complicated. Here are the rules.
184 //
185 // 1. If two SORT commands are given, --sort-section is ignored.
186 // 2. If one SORT command is given, and if it is not SORT_NONE,
187 // --sort-section is handled as an inner SORT command.
188 // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
189 // 4. If no SORT command is given, sort according to --sort-section.
190 InputSectionData **Begin = I->Sections.data() + SizeBefore;
191 InputSectionData **End = I->Sections.data() + I->Sections.size();
192 if (Pat.SortOuter != SortSectionPolicy::None) {
193 if (Pat.SortInner == SortSectionPolicy::Default)
194 sortSections(Begin, End, Config->SortSection);
195 else
196 sortSections(Begin, End, Pat.SortInner);
197 sortSections(Begin, End, Pat.SortOuter);
198 }
Rui Ueyamaee924702016-09-20 19:42:41 +0000199 }
Rafael Espindolad3190792016-09-16 15:10:23 +0000200
201 // We do not add duplicate input sections, so mark them with a dummy output
202 // section for now.
203 for (InputSectionData *S : I->Sections) {
204 auto *S2 = static_cast<InputSectionBase<ELFT> *>(S);
205 S2->OutSec = (OutputSectionBase<ELFT> *)-1;
206 }
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000207}
208
209template <class ELFT>
210void LinkerScript<ELFT>::discard(ArrayRef<InputSectionBase<ELFT> *> V) {
211 for (InputSectionBase<ELFT> *S : V) {
212 S->Live = false;
213 reportDiscarded(S);
214 }
215}
216
George Rimar06ae6832016-08-12 09:07:57 +0000217template <class ELFT>
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000218std::vector<InputSectionBase<ELFT> *>
George Rimar06ae6832016-08-12 09:07:57 +0000219LinkerScript<ELFT>::createInputSectionList(OutputSectionCommand &OutCmd) {
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000220 std::vector<InputSectionBase<ELFT> *> Ret;
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000221
George Rimar06ae6832016-08-12 09:07:57 +0000222 for (const std::unique_ptr<BaseCommand> &Base : OutCmd.Commands) {
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000223 auto *Cmd = dyn_cast<InputSectionDescription>(Base.get());
224 if (!Cmd)
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000225 continue;
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000226 computeInputSections(Cmd);
Rafael Espindolad3190792016-09-16 15:10:23 +0000227 for (InputSectionData *S : Cmd->Sections)
228 Ret.push_back(static_cast<InputSectionBase<ELFT> *>(S));
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000229 }
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000230
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000231 return Ret;
232}
233
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000234template <class ELFT>
Rafael Espindola10897f12016-09-13 14:23:14 +0000235static SectionKey<ELFT::Is64Bits> createKey(InputSectionBase<ELFT> *C,
236 StringRef OutsecName) {
237 // When using linker script the merge rules are different.
238 // Unfortunately, linker scripts are name based. This means that expressions
239 // like *(.foo*) can refer to multiple input sections that would normally be
240 // placed in different output sections. We cannot put them in different
241 // output sections or we would produce wrong results for
242 // start = .; *(.foo.*) end = .; *(.bar)
243 // and a mapping of .foo1 and .bar1 to one section and .foo2 and .bar2 to
244 // another. The problem is that there is no way to layout those output
245 // sections such that the .foo sections are the only thing between the
246 // start and end symbols.
247
248 // An extra annoyance is that we cannot simply disable merging of the contents
249 // of SHF_MERGE sections, but our implementation requires one output section
250 // per "kind" (string or not, which size/aligment).
251 // Fortunately, creating symbols in the middle of a merge section is not
252 // supported by bfd or gold, so we can just create multiple section in that
253 // case.
254 const typename ELFT::Shdr *H = C->getSectionHdr();
255 typedef typename ELFT::uint uintX_t;
256 uintX_t Flags = H->sh_flags & (SHF_MERGE | SHF_STRINGS);
257
258 uintX_t Alignment = 0;
259 if (isa<MergeInputSection<ELFT>>(C))
260 Alignment = std::max(H->sh_addralign, H->sh_entsize);
261
262 return SectionKey<ELFT::Is64Bits>{OutsecName, /*Type*/ 0, Flags, Alignment};
263}
264
265template <class ELFT>
Eugene Leviant20d03192016-09-16 15:30:47 +0000266void LinkerScript<ELFT>::addSection(OutputSectionFactory<ELFT> &Factory,
267 InputSectionBase<ELFT> *Sec,
268 StringRef Name) {
269 OutputSectionBase<ELFT> *OutSec;
270 bool IsNew;
271 std::tie(OutSec, IsNew) = Factory.create(createKey(Sec, Name), Sec);
272 if (IsNew)
273 OutputSections->push_back(OutSec);
274 OutSec->addSection(Sec);
275}
276
277template <class ELFT>
278void LinkerScript<ELFT>::processCommands(OutputSectionFactory<ELFT> &Factory) {
Rafael Espindola28c15972016-09-13 13:00:06 +0000279
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000280 for (unsigned I = 0; I < Opt.Commands.size(); ++I) {
281 auto Iter = Opt.Commands.begin() + I;
282 const std::unique_ptr<BaseCommand> &Base1 = *Iter;
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000283 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base1.get())) {
284 if (shouldDefine<ELFT>(Cmd))
285 addRegular<ELFT>(Cmd);
286 continue;
287 }
Eugene Leviant20d03192016-09-16 15:30:47 +0000288 if (auto *Cmd = dyn_cast<AssertCommand>(Base1.get())) {
289 // If we don't have SECTIONS then output sections have already been
George Rimar194470cd2016-09-17 19:21:05 +0000290 // created by Writer<ELFT>. The LinkerScript<ELFT>::assignAddresses
Eugene Leviant20d03192016-09-16 15:30:47 +0000291 // will not be called, so ASSERT should be evaluated now.
292 if (!Opt.HasSections)
293 Cmd->Expression(0);
294 continue;
295 }
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000296
Eugene Leviantceabe802016-08-11 07:56:43 +0000297 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000298 std::vector<InputSectionBase<ELFT> *> V = createInputSectionList(*Cmd);
299
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000300 if (Cmd->Name == "/DISCARD/") {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000301 discard(V);
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000302 continue;
303 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000304
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000305 if (!matchConstraints<ELFT>(V, Cmd->Constraint)) {
306 for (InputSectionBase<ELFT> *S : V)
307 S->OutSec = nullptr;
308 Opt.Commands.erase(Iter);
George Rimardfbbbc82016-09-17 09:50:10 +0000309 --I;
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000310 continue;
311 }
312
313 for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
314 if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base.get()))
315 if (shouldDefine<ELFT>(OutCmd))
316 addSymbol<ELFT>(OutCmd);
317
Eugene Leviant97403d12016-09-01 09:55:57 +0000318 if (V.empty())
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000319 continue;
320
George Rimardb24d9c2016-08-19 15:18:23 +0000321 for (InputSectionBase<ELFT> *Sec : V) {
Eugene Leviant20d03192016-09-16 15:30:47 +0000322 addSection(Factory, Sec, Cmd->Name);
323 if (uint32_t Subalign = Cmd->SubalignExpr ? Cmd->SubalignExpr(0) : 0)
George Rimardb24d9c2016-08-19 15:18:23 +0000324 Sec->Alignment = Subalign;
George Rimardb24d9c2016-08-19 15:18:23 +0000325 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000326 }
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000327 }
Eugene Leviant20d03192016-09-16 15:30:47 +0000328}
Eugene Leviante63d81b2016-07-20 14:43:20 +0000329
Eugene Leviant20d03192016-09-16 15:30:47 +0000330template <class ELFT>
331void LinkerScript<ELFT>::createSections(OutputSectionFactory<ELFT> &Factory) {
332 processCommands(Factory);
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000333 // Add orphan sections.
Eugene Leviant20d03192016-09-16 15:30:47 +0000334 for (ObjectFile<ELFT> *F : Symtab<ELFT>::X->getObjectFiles())
335 for (InputSectionBase<ELFT> *S : F->getSections())
336 if (!isDiscarded(S) && !S->OutSec)
337 addSection(Factory, S, getOutputSectionName(S));
Eugene Leviante63d81b2016-07-20 14:43:20 +0000338}
339
Eugene Leviantdb741e72016-09-07 07:08:43 +0000340// Sets value of a section-defined symbol. Two kinds of
341// symbols are processed: synthetic symbols, whose value
342// is an offset from beginning of section and regular
343// symbols whose value is absolute.
344template <class ELFT>
345static void assignSectionSymbol(SymbolAssignment *Cmd,
346 OutputSectionBase<ELFT> *Sec,
347 typename ELFT::uint Off) {
348 if (!Cmd->Sym)
349 return;
350
351 if (auto *Body = dyn_cast<DefinedSynthetic<ELFT>>(Cmd->Sym)) {
352 Body->Section = Sec;
353 Body->Value = Cmd->Expression(Sec->getVA() + Off) - Sec->getVA();
354 return;
355 }
356 auto *Body = cast<DefinedRegular<ELFT>>(Cmd->Sym);
357 Body->Value = Cmd->Expression(Sec->getVA() + Off);
358}
359
Rafael Espindolad3190792016-09-16 15:10:23 +0000360template <class ELFT> void LinkerScript<ELFT>::output(InputSection<ELFT> *S) {
361 if (!AlreadyOutputIS.insert(S).second)
362 return;
363 bool IsTbss =
364 (CurOutSec->getFlags() & SHF_TLS) && CurOutSec->getType() == SHT_NOBITS;
Eugene Leviant20889c52016-08-31 08:13:33 +0000365
Rafael Espindolad3190792016-09-16 15:10:23 +0000366 uintX_t Pos = IsTbss ? Dot + ThreadBssOffset : Dot;
367 Pos = alignTo(Pos, S->Alignment);
368 S->OutSecOff = Pos - CurOutSec->getVA();
369 Pos += S->getSize();
370
371 // Update output section size after adding each section. This is so that
372 // SIZEOF works correctly in the case below:
373 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
374 CurOutSec->setSize(Pos - CurOutSec->getVA());
375
Rafael Espindola7252ae52016-09-22 12:00:08 +0000376 if (IsTbss)
377 ThreadBssOffset = Pos - Dot;
378 else
Rafael Espindolad3190792016-09-16 15:10:23 +0000379 Dot = Pos;
380}
381
382template <class ELFT> void LinkerScript<ELFT>::flush() {
383 if (auto *OutSec = dyn_cast_or_null<OutputSection<ELFT>>(CurOutSec)) {
384 for (InputSection<ELFT> *I : OutSec->Sections)
385 output(I);
386 AlreadyOutputOS.insert(CurOutSec);
Eugene Leviant20889c52016-08-31 08:13:33 +0000387 }
388}
389
390template <class ELFT>
Rafael Espindolad3190792016-09-16 15:10:23 +0000391void LinkerScript<ELFT>::switchTo(OutputSectionBase<ELFT> *Sec) {
392 if (CurOutSec == Sec)
393 return;
394 if (AlreadyOutputOS.count(Sec))
395 return;
396
397 flush();
398 CurOutSec = Sec;
399
400 Dot = alignTo(Dot, CurOutSec->getAlignment());
401 CurOutSec->setVA(Dot);
402}
403
404template <class ELFT> void LinkerScript<ELFT>::process(BaseCommand &Base) {
405 if (auto *AssignCmd = dyn_cast<SymbolAssignment>(&Base)) {
406 if (AssignCmd->Name == ".") {
407 // Update to location counter means update to section size.
408 Dot = AssignCmd->Expression(Dot);
409 CurOutSec->setSize(Dot - CurOutSec->getVA());
410 return;
411 }
412 assignSectionSymbol<ELFT>(AssignCmd, CurOutSec, Dot - CurOutSec->getVA());
Eugene Leviantceabe802016-08-11 07:56:43 +0000413 return;
Rui Ueyama2de509c2016-08-12 00:55:08 +0000414 }
Rafael Espindolad3190792016-09-16 15:10:23 +0000415 auto &ICmd = cast<InputSectionDescription>(Base);
416 for (InputSectionData *ID : ICmd.Sections) {
417 auto *IB = static_cast<InputSectionBase<ELFT> *>(ID);
418 switchTo(IB->OutSec);
419 if (auto *I = dyn_cast<InputSection<ELFT>>(IB))
420 output(I);
421 else if (AlreadyOutputOS.insert(CurOutSec).second)
422 Dot += CurOutSec->getSize();
Eugene Leviantceabe802016-08-11 07:56:43 +0000423 }
424}
425
George Rimar8f66df92016-08-12 20:38:20 +0000426template <class ELFT>
George Rimara14b13d2016-09-07 10:46:07 +0000427static std::vector<OutputSectionBase<ELFT> *>
428findSections(OutputSectionCommand &Cmd,
Rafael Espindolad3190792016-09-16 15:10:23 +0000429 const std::vector<OutputSectionBase<ELFT> *> &Sections) {
George Rimara14b13d2016-09-07 10:46:07 +0000430 std::vector<OutputSectionBase<ELFT> *> Ret;
431 for (OutputSectionBase<ELFT> *Sec : Sections)
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000432 if (Sec->getName() == Cmd.Name)
George Rimara14b13d2016-09-07 10:46:07 +0000433 Ret.push_back(Sec);
434 return Ret;
George Rimar8f66df92016-08-12 20:38:20 +0000435}
436
Rafael Espindolad3190792016-09-16 15:10:23 +0000437template <class ELFT>
438void LinkerScript<ELFT>::assignOffsets(OutputSectionCommand *Cmd) {
439 std::vector<OutputSectionBase<ELFT> *> Sections =
440 findSections(*Cmd, *OutputSections);
441 if (Sections.empty())
442 return;
443 switchTo(Sections[0]);
444
445 // Find the last section output location. We will output orphan sections
446 // there so that end symbols point to the correct location.
447 auto E = std::find_if(Cmd->Commands.rbegin(), Cmd->Commands.rend(),
448 [](const std::unique_ptr<BaseCommand> &Cmd) {
449 return !isa<SymbolAssignment>(*Cmd);
450 })
451 .base();
452 for (auto I = Cmd->Commands.begin(); I != E; ++I)
453 process(**I);
454 flush();
455 for (OutputSectionBase<ELFT> *Base : Sections) {
Eugene Leviant2506cb42016-09-21 11:29:28 +0000456 if (AlreadyOutputOS.count(Base))
Rafael Espindolad3190792016-09-16 15:10:23 +0000457 continue;
458 switchTo(Base);
459 Dot += CurOutSec->getSize();
Eugene Leviant2506cb42016-09-21 11:29:28 +0000460 flush();
Rafael Espindolad3190792016-09-16 15:10:23 +0000461 }
George Rimarb31dd372016-09-19 13:27:31 +0000462 std::for_each(E, Cmd->Commands.end(),
463 [this](std::unique_ptr<BaseCommand> &B) { process(*B.get()); });
Rafael Espindolad3190792016-09-16 15:10:23 +0000464}
465
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000466template <class ELFT> void LinkerScript<ELFT>::assignAddresses() {
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000467 // It is common practice to use very generic linker scripts. So for any
468 // given run some of the output sections in the script will be empty.
469 // We could create corresponding empty output sections, but that would
470 // clutter the output.
471 // We instead remove trivially empty sections. The bfd linker seems even
472 // more aggressive at removing them.
473 auto Pos = std::remove_if(
474 Opt.Commands.begin(), Opt.Commands.end(),
475 [&](const std::unique_ptr<BaseCommand> &Base) {
476 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
477 if (!Cmd)
478 return false;
479 std::vector<OutputSectionBase<ELFT> *> Secs =
480 findSections(*Cmd, *OutputSections);
481 if (!Secs.empty())
482 return false;
483 for (const std::unique_ptr<BaseCommand> &I : Cmd->Commands)
484 if (!isa<InputSectionDescription>(I.get()))
485 return false;
486 return true;
487 });
488 Opt.Commands.erase(Pos, Opt.Commands.end());
489
George Rimar652852c2016-04-16 10:10:32 +0000490 // Orphan sections are sections present in the input files which
Rui Ueyama7c18c282016-04-18 21:00:40 +0000491 // are not explicitly placed into the output file by the linker script.
492 // We place orphan sections at end of file.
493 // Other linkers places them using some heuristics as described in
George Rimar652852c2016-04-16 10:10:32 +0000494 // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000495
496 // The OutputSections are already in the correct order.
497 // This loops creates or moves commands as needed so that they are in the
498 // correct order.
499 int CmdIndex = 0;
Rui Ueyamae5cc6682016-08-12 00:36:56 +0000500 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
George Rimar652852c2016-04-16 10:10:32 +0000501 StringRef Name = Sec->getName();
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000502
503 // Find the last spot where we can insert a command and still get the
504 // correct order.
505 auto CmdIter = Opt.Commands.begin() + CmdIndex;
506 auto E = Opt.Commands.end();
507 while (CmdIter != E && !isa<OutputSectionCommand>(**CmdIter)) {
508 ++CmdIter;
509 ++CmdIndex;
510 }
511
512 auto Pos =
513 std::find_if(CmdIter, E, [&](const std::unique_ptr<BaseCommand> &Base) {
514 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
515 return Cmd && Cmd->Name == Name;
516 });
517 if (Pos == E) {
518 Opt.Commands.insert(CmdIter,
519 llvm::make_unique<OutputSectionCommand>(Name));
520 } else {
521 // If linker script lists alloc/non-alloc sections is the wrong order,
522 // this does a right rotate to bring the desired command in place.
Rafael Espindola373343b2016-09-16 22:47:34 +0000523 auto RPos = llvm::make_reverse_iterator(Pos + 1);
524 std::rotate(RPos, RPos + 1, llvm::make_reverse_iterator(CmdIter));
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000525 }
526 ++CmdIndex;
George Rimar652852c2016-04-16 10:10:32 +0000527 }
George Rimar652852c2016-04-16 10:10:32 +0000528
Rui Ueyama7c18c282016-04-18 21:00:40 +0000529 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rui Ueyama4f7500b2016-08-12 04:00:22 +0000530 Dot = getHeaderSize();
George Rimar652852c2016-04-16 10:10:32 +0000531
George Rimar076fe152016-07-21 06:43:01 +0000532 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
533 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
Rui Ueyama8d083e62016-07-29 05:48:39 +0000534 if (Cmd->Name == ".") {
535 Dot = Cmd->Expression(Dot);
536 } else if (Cmd->Sym) {
537 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(Dot);
538 }
George Rimar652852c2016-04-16 10:10:32 +0000539 continue;
540 }
541
George Rimareefa7582016-08-04 09:29:31 +0000542 if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
543 Cmd->Expression(Dot);
544 continue;
545 }
546
George Rimar076fe152016-07-21 06:43:01 +0000547 auto *Cmd = cast<OutputSectionCommand>(Base.get());
George Rimar652852c2016-04-16 10:10:32 +0000548
Rafael Espindolad3190792016-09-16 15:10:23 +0000549 if (Cmd->AddrExpr)
550 Dot = Cmd->AddrExpr(Dot);
George Rimar58e5c4d2016-07-25 08:29:46 +0000551
Rafael Espindolad3190792016-09-16 15:10:23 +0000552 assignOffsets(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000553 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000554
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000555 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
556 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
557 if (Sec->getFlags() & SHF_ALLOC)
558 MinVA = std::min(MinVA, Sec->getVA());
559 else
Rafael Espindolad3190792016-09-16 15:10:23 +0000560 Sec->setVA(0);
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000561 }
562
Rafael Espindola4ec013a2016-09-15 21:22:11 +0000563 uintX_t HeaderSize =
564 Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
565 if (HeaderSize > MinVA)
566 fatal("Not enough space for ELF and program headers");
567
Rafael Espindola64c32d62016-07-07 14:28:47 +0000568 // ELF and Program headers need to be right before the first section in
George Rimarb91e7112016-07-19 07:42:07 +0000569 // memory. Set their addresses accordingly.
Rafael Espindola4ec013a2016-09-15 21:22:11 +0000570 MinVA = alignDown(MinVA - HeaderSize, Target->PageSize);
Eugene Leviant467c4d52016-07-01 10:27:36 +0000571 Out<ELFT>::ElfHeader->setVA(MinVA);
572 Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
George Rimar652852c2016-04-16 10:10:32 +0000573}
574
Rui Ueyama464daad2016-08-22 04:55:20 +0000575// Creates program headers as instructed by PHDRS linker script command.
Rui Ueyama07320e42016-04-20 20:13:41 +0000576template <class ELFT>
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000577std::vector<PhdrEntry<ELFT>> LinkerScript<ELFT>::createPhdrs() {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000578 std::vector<PhdrEntry<ELFT>> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000579
Rui Ueyama464daad2016-08-22 04:55:20 +0000580 // Process PHDRS and FILEHDR keywords because they are not
581 // real output sections and cannot be added in the following loop.
Eugene Leviantbbe38602016-07-19 09:25:43 +0000582 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000583 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
584 PhdrEntry<ELFT> &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000585
586 if (Cmd.HasFilehdr)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000587 Phdr.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000588 if (Cmd.HasPhdrs)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000589 Phdr.add(Out<ELFT>::ProgramHeaders);
Eugene Leviant56b21c82016-09-09 09:46:16 +0000590
591 if (Cmd.LMAExpr) {
592 Phdr.H.p_paddr = Cmd.LMAExpr(0);
593 Phdr.HasLMA = true;
594 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000595 }
596
Rui Ueyama464daad2016-08-22 04:55:20 +0000597 // Add output sections to program headers.
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000598 PhdrEntry<ELFT> *Load = nullptr;
599 uintX_t Flags = PF_R;
Rui Ueyama464daad2016-08-22 04:55:20 +0000600 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
Eugene Leviantbbe38602016-07-19 09:25:43 +0000601 if (!(Sec->getFlags() & SHF_ALLOC))
602 break;
603
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000604 std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName());
Eugene Leviantbbe38602016-07-19 09:25:43 +0000605 if (!PhdrIds.empty()) {
606 // Assign headers specified by linker script
607 for (size_t Id : PhdrIds) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000608 Ret[Id].add(Sec);
Eugene Leviant865bf862016-07-21 10:43:25 +0000609 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
Rafael Espindola0b113672016-07-27 14:10:56 +0000610 Ret[Id].H.p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000611 }
612 } else {
613 // If we have no load segment or flags've changed then we want new load
614 // segment.
Rafael Espindola0b113672016-07-27 14:10:56 +0000615 uintX_t NewFlags = Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000616 if (Load == nullptr || Flags != NewFlags) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000617 Load = &*Ret.emplace(Ret.end(), PT_LOAD, NewFlags);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000618 Flags = NewFlags;
619 }
Rui Ueyama18f084f2016-07-20 19:36:41 +0000620 Load->add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000621 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000622 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000623 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000624}
625
Eugene Leviantf9bc3bd2016-08-16 06:40:58 +0000626template <class ELFT> bool LinkerScript<ELFT>::ignoreInterpSection() {
627 // Ignore .interp section in case we have PHDRS specification
628 // and PT_INTERP isn't listed.
629 return !Opt.PhdrsCommands.empty() &&
630 llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
631 return Cmd.Type == PT_INTERP;
632 }) == Opt.PhdrsCommands.end();
633}
634
Eugene Leviantbbe38602016-07-19 09:25:43 +0000635template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000636ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000637 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
638 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
639 if (Cmd->Name == Name)
640 return Cmd->Filler;
641 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000642}
643
George Rimar206fffa2016-08-17 08:16:57 +0000644template <class ELFT> Expr LinkerScript<ELFT>::getLma(StringRef Name) {
George Rimar8ceadb32016-08-17 07:44:19 +0000645 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
646 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
647 if (Cmd->LmaExpr && Cmd->Name == Name)
648 return Cmd->LmaExpr;
649 return {};
650}
651
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000652// Returns the index of the given section name in linker script
653// SECTIONS commands. Sections are laid out as the same order as they
654// were in the script. If a given name did not appear in the script,
655// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000656template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000657 int I = 0;
658 for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
659 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
660 if (Cmd->Name == Name)
661 return I;
662 ++I;
663 }
664 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000665}
666
Eugene Leviantbbe38602016-07-19 09:25:43 +0000667template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
668 return !Opt.PhdrsCommands.empty();
669}
670
George Rimar9e694502016-07-29 16:18:47 +0000671template <class ELFT>
George Rimar884e7862016-09-08 08:19:13 +0000672uint64_t LinkerScript<ELFT>::getOutputSectionAddress(StringRef Name) {
George Rimar96659df2016-08-30 09:54:01 +0000673 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
674 if (Sec->getName() == Name)
675 return Sec->getVA();
676 error("undefined section " + Name);
677 return 0;
678}
679
680template <class ELFT>
George Rimar884e7862016-09-08 08:19:13 +0000681uint64_t LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
George Rimar9e694502016-07-29 16:18:47 +0000682 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
683 if (Sec->getName() == Name)
684 return Sec->getSize();
685 error("undefined section " + Name);
686 return 0;
687}
688
Eugene Leviant36fac7f2016-09-08 09:08:30 +0000689template <class ELFT>
690uint64_t LinkerScript<ELFT>::getOutputSectionAlign(StringRef Name) {
691 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
692 if (Sec->getName() == Name)
693 return Sec->getAlignment();
694 error("undefined section " + Name);
695 return 0;
696}
697
George Rimar884e7862016-09-08 08:19:13 +0000698template <class ELFT> uint64_t LinkerScript<ELFT>::getHeaderSize() {
George Rimare32a3592016-08-10 07:59:34 +0000699 return Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
700}
701
George Rimar884e7862016-09-08 08:19:13 +0000702template <class ELFT> uint64_t LinkerScript<ELFT>::getSymbolValue(StringRef S) {
703 if (SymbolBody *B = Symtab<ELFT>::X->find(S))
704 return B->getVA<ELFT>();
705 error("symbol not found: " + S);
706 return 0;
707}
708
Eugene Leviantbbe38602016-07-19 09:25:43 +0000709// Returns indices of ELF headers containing specific section, identified
710// by Name. Each index is a zero based number of ELF header listed within
711// PHDRS {} script block.
712template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000713std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000714 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
715 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000716 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000717 continue;
718
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000719 std::vector<size_t> Ret;
720 for (StringRef PhdrName : Cmd->Phdrs)
721 Ret.push_back(getPhdrIndex(PhdrName));
722 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000723 }
George Rimar31d842f2016-07-20 16:43:03 +0000724 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000725}
726
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000727template <class ELFT>
728size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
729 size_t I = 0;
730 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
731 if (Cmd.Name == PhdrName)
732 return I;
733 ++I;
734 }
735 error("section header '" + PhdrName + "' is not listed in PHDRS");
736 return 0;
737}
738
Rui Ueyama07320e42016-04-20 20:13:41 +0000739class elf::ScriptParser : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000740 typedef void (ScriptParser::*Handler)();
741
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000742public:
Rui Ueyama07320e42016-04-20 20:13:41 +0000743 ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
George Rimarf23b2322016-02-19 10:45:45 +0000744
George Rimar20b65982016-08-31 09:08:26 +0000745 void readLinkerScript();
746 void readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000747
748private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000749 void addFile(StringRef Path);
750
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000751 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000752 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000753 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000754 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000755 void readInclude();
Rui Ueyamaee592822015-10-07 00:25:09 +0000756 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000757 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000758 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000759 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000760 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000761 void readSections();
Rui Ueyama95769b42016-08-31 20:03:54 +0000762 void readVersion();
763 void readVersionScriptCommand();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000764
Rui Ueyama113cdec2016-07-24 23:05:57 +0000765 SymbolAssignment *readAssignment(StringRef Name);
George Rimarff1f29e2016-09-06 13:51:57 +0000766 std::vector<uint8_t> readFill();
Rui Ueyama10416562016-08-04 02:03:27 +0000767 OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
George Rimarff1f29e2016-09-06 13:51:57 +0000768 std::vector<uint8_t> readOutputSectionFiller(StringRef Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000769 std::vector<StringRef> readOutputSectionPhdrs();
George Rimara2496cb2016-08-30 09:46:59 +0000770 InputSectionDescription *readInputSectionDescription(StringRef Tok);
George Rimarc91930a2016-09-02 21:17:20 +0000771 Regex readFilePatterns();
George Rimar07171f22016-09-21 15:56:44 +0000772 std::vector<SectionPattern> readInputSectionsList();
George Rimara2496cb2016-08-30 09:46:59 +0000773 InputSectionDescription *readInputSectionRules(StringRef FilePattern);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000774 unsigned readPhdrType();
George Rimarbe394db2016-09-16 20:21:55 +0000775 SortSectionPolicy readSortKind();
Petr Hoseka35e39c2016-08-16 01:11:16 +0000776 SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
Eugene Leviantdb741e72016-09-07 07:08:43 +0000777 SymbolAssignment *readProvideOrAssignment(StringRef Tok, bool MakeAbsolute);
George Rimar03fc0102016-07-28 07:18:23 +0000778 void readSort();
George Rimareefa7582016-08-04 09:29:31 +0000779 Expr readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +0000780
781 Expr readExpr();
782 Expr readExpr1(Expr Lhs, int MinPrec);
783 Expr readPrimary();
784 Expr readTernary(Expr Cond);
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +0000785 Expr readParenExpr();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000786
George Rimar20b65982016-08-31 09:08:26 +0000787 // For parsing version script.
788 void readExtern(std::vector<SymbolVersion> *Globals);
Rui Ueyama95769b42016-08-31 20:03:54 +0000789 void readVersionDeclaration(StringRef VerStr);
George Rimar20b65982016-08-31 09:08:26 +0000790 void readGlobal(StringRef VerStr);
791 void readLocal();
792
Rui Ueyama07320e42016-04-20 20:13:41 +0000793 ScriptConfiguration &Opt = *ScriptConfig;
794 StringSaver Saver = {ScriptConfig->Alloc};
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000795 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000796};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000797
George Rimar20b65982016-08-31 09:08:26 +0000798void ScriptParser::readVersionScript() {
Rui Ueyama95769b42016-08-31 20:03:54 +0000799 readVersionScriptCommand();
800 if (!atEOF())
801 setError("EOF expected, but got " + next());
802}
803
804void ScriptParser::readVersionScriptCommand() {
George Rimar20b65982016-08-31 09:08:26 +0000805 if (skip("{")) {
Rui Ueyama95769b42016-08-31 20:03:54 +0000806 readVersionDeclaration("");
George Rimar20b65982016-08-31 09:08:26 +0000807 return;
808 }
809
Rui Ueyama95769b42016-08-31 20:03:54 +0000810 while (!atEOF() && !Error && peek() != "}") {
George Rimar20b65982016-08-31 09:08:26 +0000811 StringRef VerStr = next();
812 if (VerStr == "{") {
Rui Ueyama95769b42016-08-31 20:03:54 +0000813 setError("anonymous version definition is used in "
814 "combination with other version definitions");
George Rimar20b65982016-08-31 09:08:26 +0000815 return;
816 }
817 expect("{");
Rui Ueyama95769b42016-08-31 20:03:54 +0000818 readVersionDeclaration(VerStr);
George Rimar20b65982016-08-31 09:08:26 +0000819 }
820}
821
Rui Ueyama95769b42016-08-31 20:03:54 +0000822void ScriptParser::readVersion() {
823 expect("{");
824 readVersionScriptCommand();
825 expect("}");
826}
827
George Rimar20b65982016-08-31 09:08:26 +0000828void ScriptParser::readLinkerScript() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000829 while (!atEOF()) {
830 StringRef Tok = next();
Rui Ueyamaa27eecc2016-09-02 18:52:41 +0000831 if (Tok == ";")
832 continue;
833
Eugene Leviant20d03192016-09-16 15:30:47 +0000834 if (Tok == "ASSERT") {
835 Opt.Commands.emplace_back(new AssertCommand(readAssert()));
836 } else if (Tok == "ENTRY") {
Rui Ueyamaa27eecc2016-09-02 18:52:41 +0000837 readEntry();
838 } else if (Tok == "EXTERN") {
839 readExtern();
840 } else if (Tok == "GROUP" || Tok == "INPUT") {
841 readGroup();
842 } else if (Tok == "INCLUDE") {
843 readInclude();
844 } else if (Tok == "OUTPUT") {
845 readOutput();
846 } else if (Tok == "OUTPUT_ARCH") {
847 readOutputArch();
848 } else if (Tok == "OUTPUT_FORMAT") {
849 readOutputFormat();
850 } else if (Tok == "PHDRS") {
851 readPhdrs();
852 } else if (Tok == "SEARCH_DIR") {
853 readSearchDir();
854 } else if (Tok == "SECTIONS") {
855 readSections();
856 } else if (Tok == "VERSION") {
857 readVersion();
Eugene Leviantdb741e72016-09-07 07:08:43 +0000858 } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok, true)) {
Eugene Leviant20d03192016-09-16 15:30:47 +0000859 Opt.Commands.emplace_back(Cmd);
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000860 } else {
George Rimar57610422016-03-11 14:43:02 +0000861 setError("unknown directive: " + Tok);
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000862 }
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000863 }
864}
865
Rui Ueyama717677a2016-02-11 21:17:59 +0000866void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000867 if (IsUnderSysroot && S.startswith("/")) {
868 SmallString<128> Path;
869 (Config->Sysroot + S).toStringRef(Path);
870 if (sys::fs::exists(Path)) {
871 Driver->addFile(Saver.save(Path.str()));
872 return;
873 }
874 }
875
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +0000876 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +0000877 Driver->addFile(S);
878 } else if (S.startswith("=")) {
879 if (Config->Sysroot.empty())
880 Driver->addFile(S.substr(1));
881 else
882 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
883 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +0000884 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +0000885 } else if (sys::fs::exists(S)) {
886 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +0000887 } else {
888 std::string Path = findFromSearchPaths(S);
889 if (Path.empty())
George Rimar777f9632016-03-12 08:31:34 +0000890 setError("unable to find " + S);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000891 else
892 Driver->addFile(Saver.save(Path));
Rui Ueyama52a15092015-10-11 03:28:42 +0000893 }
894}
895
Rui Ueyama717677a2016-02-11 21:17:59 +0000896void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000897 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +0000898 bool Orig = Config->AsNeeded;
899 Config->AsNeeded = true;
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000900 while (!Error && !skip(")"))
George Rimarcd574a52016-09-09 14:35:36 +0000901 addFile(unquote(next()));
Rui Ueyama35da9b62015-10-11 20:59:12 +0000902 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000903}
904
Rui Ueyama717677a2016-02-11 21:17:59 +0000905void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +0000906 // -e <symbol> takes predecence over ENTRY(<symbol>).
907 expect("(");
908 StringRef Tok = next();
909 if (Config->Entry.empty())
910 Config->Entry = Tok;
911 expect(")");
912}
913
Rui Ueyama717677a2016-02-11 21:17:59 +0000914void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +0000915 expect("(");
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000916 while (!Error && !skip(")"))
917 Config->Undefined.push_back(next());
George Rimar83f406c2015-10-19 17:35:12 +0000918}
919
Rui Ueyama717677a2016-02-11 21:17:59 +0000920void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000921 expect("(");
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000922 while (!Error && !skip(")")) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000923 StringRef Tok = next();
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000924 if (Tok == "AS_NEEDED")
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000925 readAsNeeded();
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000926 else
George Rimarcd574a52016-09-09 14:35:36 +0000927 addFile(unquote(Tok));
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000928 }
929}
930
Rui Ueyama717677a2016-02-11 21:17:59 +0000931void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000932 StringRef Tok = next();
George Rimarcd574a52016-09-09 14:35:36 +0000933 auto MBOrErr = MemoryBuffer::getFile(unquote(Tok));
Rui Ueyama025d59b2016-02-02 20:27:59 +0000934 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +0000935 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000936 return;
937 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000938 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Rui Ueyamaa47ee682015-10-11 01:53:04 +0000939 StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
940 std::vector<StringRef> V = tokenize(S);
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000941 Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000942}
943
Rui Ueyama717677a2016-02-11 21:17:59 +0000944void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +0000945 // -o <file> takes predecence over OUTPUT(<file>).
946 expect("(");
947 StringRef Tok = next();
948 if (Config->OutputFile.empty())
George Rimarcd574a52016-09-09 14:35:36 +0000949 Config->OutputFile = unquote(Tok);
Rui Ueyamaee592822015-10-07 00:25:09 +0000950 expect(")");
951}
952
Rui Ueyama717677a2016-02-11 21:17:59 +0000953void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +0000954 // Error checking only for now.
955 expect("(");
956 next();
957 expect(")");
958}
959
Rui Ueyama717677a2016-02-11 21:17:59 +0000960void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000961 // Error checking only for now.
962 expect("(");
963 next();
Davide Italiano6836c612015-10-12 21:08:41 +0000964 StringRef Tok = next();
965 if (Tok == ")")
George Rimar6c55f0e2016-09-08 08:20:30 +0000966 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000967 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +0000968 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000969 return;
970 }
Davide Italiano6836c612015-10-12 21:08:41 +0000971 next();
972 expect(",");
973 next();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000974 expect(")");
975}
976
Eugene Leviantbbe38602016-07-19 09:25:43 +0000977void ScriptParser::readPhdrs() {
978 expect("{");
979 while (!Error && !skip("}")) {
980 StringRef Tok = next();
Eugene Leviant56b21c82016-09-09 09:46:16 +0000981 Opt.PhdrsCommands.push_back(
982 {Tok, PT_NULL, false, false, UINT_MAX, nullptr});
Eugene Leviantbbe38602016-07-19 09:25:43 +0000983 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
984
985 PhdrCmd.Type = readPhdrType();
986 do {
987 Tok = next();
988 if (Tok == ";")
989 break;
990 if (Tok == "FILEHDR")
991 PhdrCmd.HasFilehdr = true;
992 else if (Tok == "PHDRS")
993 PhdrCmd.HasPhdrs = true;
Eugene Leviant56b21c82016-09-09 09:46:16 +0000994 else if (Tok == "AT")
995 PhdrCmd.LMAExpr = readParenExpr();
Eugene Leviant865bf862016-07-21 10:43:25 +0000996 else if (Tok == "FLAGS") {
997 expect("(");
Rafael Espindolaeb685cd2016-08-02 22:14:57 +0000998 // Passing 0 for the value of dot is a bit of a hack. It means that
999 // we accept expressions like ".|1".
1000 PhdrCmd.Flags = readExpr()(0);
Eugene Leviant865bf862016-07-21 10:43:25 +00001001 expect(")");
1002 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +00001003 setError("unexpected header attribute: " + Tok);
1004 } while (!Error);
1005 }
1006}
1007
Rui Ueyama717677a2016-02-11 21:17:59 +00001008void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +00001009 expect("(");
Rui Ueyama86c5fb82016-09-08 23:26:54 +00001010 StringRef Tok = next();
Rui Ueyama6c7ad132016-09-02 19:20:33 +00001011 if (!Config->Nostdlib)
George Rimarcd574a52016-09-09 14:35:36 +00001012 Config->SearchPaths.push_back(unquote(Tok));
Davide Italiano68a39a62015-10-08 17:51:41 +00001013 expect(")");
1014}
1015
Rui Ueyama717677a2016-02-11 21:17:59 +00001016void ScriptParser::readSections() {
Eugene Leviante05336ff2016-09-14 08:32:36 +00001017 Opt.HasSections = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001018 expect("{");
George Rimar652852c2016-04-16 10:10:32 +00001019 while (!Error && !skip("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +00001020 StringRef Tok = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +00001021 BaseCommand *Cmd = readProvideOrAssignment(Tok, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001022 if (!Cmd) {
1023 if (Tok == "ASSERT")
1024 Cmd = new AssertCommand(readAssert());
1025 else
1026 Cmd = readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +00001027 }
Rui Ueyama10416562016-08-04 02:03:27 +00001028 Opt.Commands.emplace_back(Cmd);
George Rimar652852c2016-04-16 10:10:32 +00001029 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001030}
1031
Rui Ueyama708019c2016-07-24 18:19:40 +00001032static int precedence(StringRef Op) {
1033 return StringSwitch<int>(Op)
1034 .Case("*", 4)
1035 .Case("/", 4)
1036 .Case("+", 3)
1037 .Case("-", 3)
1038 .Case("<", 2)
1039 .Case(">", 2)
1040 .Case(">=", 2)
1041 .Case("<=", 2)
1042 .Case("==", 2)
1043 .Case("!=", 2)
1044 .Case("&", 1)
Rafael Espindolacc3dd622016-08-22 21:33:35 +00001045 .Case("|", 1)
Rui Ueyama708019c2016-07-24 18:19:40 +00001046 .Default(-1);
1047}
1048
George Rimarc91930a2016-09-02 21:17:20 +00001049Regex ScriptParser::readFilePatterns() {
Rui Ueyama10416562016-08-04 02:03:27 +00001050 std::vector<StringRef> V;
1051 while (!Error && !skip(")"))
1052 V.push_back(next());
George Rimarc91930a2016-09-02 21:17:20 +00001053 return compileGlobPatterns(V);
George Rimar0702c4e2016-07-29 15:32:46 +00001054}
1055
George Rimarbe394db2016-09-16 20:21:55 +00001056SortSectionPolicy ScriptParser::readSortKind() {
Rui Ueyama742c3832016-08-04 22:27:00 +00001057 if (skip("SORT") || skip("SORT_BY_NAME"))
George Rimarbe394db2016-09-16 20:21:55 +00001058 return SortSectionPolicy::Name;
Rui Ueyama742c3832016-08-04 22:27:00 +00001059 if (skip("SORT_BY_ALIGNMENT"))
George Rimarbe394db2016-09-16 20:21:55 +00001060 return SortSectionPolicy::Alignment;
George Rimar575208c2016-09-15 19:15:12 +00001061 if (skip("SORT_BY_INIT_PRIORITY"))
George Rimarbe394db2016-09-16 20:21:55 +00001062 return SortSectionPolicy::Priority;
George Rimarbe394db2016-09-16 20:21:55 +00001063 if (skip("SORT_NONE"))
Rui Ueyamab2a0abd2016-09-16 21:14:55 +00001064 return SortSectionPolicy::None;
1065 return SortSectionPolicy::Default;
George Rimarbe394db2016-09-16 20:21:55 +00001066}
1067
George Rimar395281c2016-09-16 17:42:10 +00001068// Method reads a list of sequence of excluded files and section globs given in
1069// a following form: ((EXCLUDE_FILE(file_pattern+))? section_pattern+)+
1070// Example: *(.foo.1 EXCLUDE_FILE (*a.o) .foo.2 EXCLUDE_FILE (*b.o) .foo.3)
George Rimaraf03be12016-09-17 19:17:25 +00001071// The semantics of that is next:
1072// * Include .foo.1 from every file.
1073// * Include .foo.2 from every file but a.o
1074// * Include .foo.3 from every file but b.o
George Rimar07171f22016-09-21 15:56:44 +00001075std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
1076 std::vector<SectionPattern> Ret;
George Rimar601e9892016-09-21 08:53:21 +00001077 while (!Error && peek() != ")") {
1078 Regex ExcludeFileRe;
George Rimar395281c2016-09-16 17:42:10 +00001079 if (skip("EXCLUDE_FILE")) {
George Rimar395281c2016-09-16 17:42:10 +00001080 expect("(");
1081 ExcludeFileRe = readFilePatterns();
George Rimar395281c2016-09-16 17:42:10 +00001082 }
1083
George Rimar601e9892016-09-21 08:53:21 +00001084 std::vector<StringRef> V;
1085 while (!Error && peek() != ")" && peek() != "EXCLUDE_FILE")
1086 V.push_back(next());
1087
1088 if (!V.empty())
George Rimar07171f22016-09-21 15:56:44 +00001089 Ret.push_back({std::move(ExcludeFileRe), compileGlobPatterns(V)});
George Rimar601e9892016-09-21 08:53:21 +00001090 else
1091 setError("section pattern is expected");
George Rimar395281c2016-09-16 17:42:10 +00001092 }
George Rimar07171f22016-09-21 15:56:44 +00001093 return Ret;
George Rimar395281c2016-09-16 17:42:10 +00001094}
1095
George Rimar07171f22016-09-21 15:56:44 +00001096// Section pattern grammar can have complex expressions, for example:
1097// *(SORT(.foo.* EXCLUDE_FILE (*file1.o) .bar.*) .bar.* SORT(.zed.*))
1098// Generally is a sequence of globs and excludes that may be wrapped in a SORT()
1099// commands, like: SORT(glob0) glob1 glob2 SORT(glob4)
1100// This methods handles wrapping sequences of excluded files and section globs
1101// into SORT() if that needed and reads them all.
George Rimara2496cb2016-08-30 09:46:59 +00001102InputSectionDescription *
1103ScriptParser::readInputSectionRules(StringRef FilePattern) {
George Rimarc91930a2016-09-02 21:17:20 +00001104 auto *Cmd = new InputSectionDescription(FilePattern);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001105 expect("(");
George Rimar07171f22016-09-21 15:56:44 +00001106 while (!HasError && !skip(")")) {
1107 SortSectionPolicy Outer = readSortKind();
1108 SortSectionPolicy Inner = SortSectionPolicy::Default;
1109 std::vector<SectionPattern> V;
1110 if (Outer != SortSectionPolicy::Default) {
George Rimar350ece42016-08-03 08:35:59 +00001111 expect("(");
George Rimar07171f22016-09-21 15:56:44 +00001112 Inner = readSortKind();
1113 if (Inner != SortSectionPolicy::Default) {
1114 expect("(");
1115 V = readInputSectionsList();
1116 expect(")");
1117 } else {
1118 V = readInputSectionsList();
1119 }
George Rimar350ece42016-08-03 08:35:59 +00001120 expect(")");
1121 } else {
George Rimar07171f22016-09-21 15:56:44 +00001122 V = readInputSectionsList();
George Rimar350ece42016-08-03 08:35:59 +00001123 }
George Rimar0702c4e2016-07-29 15:32:46 +00001124
George Rimar07171f22016-09-21 15:56:44 +00001125 for (SectionPattern &Pat : V) {
1126 Pat.SortInner = Inner;
1127 Pat.SortOuter = Outer;
1128 }
1129
1130 std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns));
1131 }
Rui Ueyama10416562016-08-04 02:03:27 +00001132 return Cmd;
Davide Italianoe7282792016-07-27 01:44:01 +00001133}
1134
George Rimara2496cb2016-08-30 09:46:59 +00001135InputSectionDescription *
1136ScriptParser::readInputSectionDescription(StringRef Tok) {
George Rimar06598002016-07-28 21:51:30 +00001137 // Input section wildcard can be surrounded by KEEP.
1138 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
George Rimara2496cb2016-08-30 09:46:59 +00001139 if (Tok == "KEEP") {
George Rimar06598002016-07-28 21:51:30 +00001140 expect("(");
George Rimara2496cb2016-08-30 09:46:59 +00001141 StringRef FilePattern = next();
1142 InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
George Rimar06598002016-07-28 21:51:30 +00001143 expect(")");
Rui Ueyama4dc07be2016-09-17 02:23:40 +00001144 for (SectionPattern &Pat : Cmd->SectionPatterns)
1145 Opt.KeptSections.push_back(&Pat.SectionRe);
Rui Ueyama10416562016-08-04 02:03:27 +00001146 return Cmd;
George Rimar06598002016-07-28 21:51:30 +00001147 }
George Rimara2496cb2016-08-30 09:46:59 +00001148 return readInputSectionRules(Tok);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001149}
1150
George Rimar03fc0102016-07-28 07:18:23 +00001151void ScriptParser::readSort() {
1152 expect("(");
1153 expect("CONSTRUCTORS");
1154 expect(")");
1155}
1156
George Rimareefa7582016-08-04 09:29:31 +00001157Expr ScriptParser::readAssert() {
1158 expect("(");
1159 Expr E = readExpr();
1160 expect(",");
George Rimarcd574a52016-09-09 14:35:36 +00001161 StringRef Msg = unquote(next());
George Rimareefa7582016-08-04 09:29:31 +00001162 expect(")");
1163 return [=](uint64_t Dot) {
1164 uint64_t V = E(Dot);
1165 if (!V)
1166 error(Msg);
1167 return V;
1168 };
1169}
1170
Rui Ueyama25150e82016-09-06 17:46:43 +00001171// Reads a FILL(expr) command. We handle the FILL command as an
1172// alias for =fillexp section attribute, which is different from
1173// what GNU linkers do.
1174// https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
George Rimarff1f29e2016-09-06 13:51:57 +00001175std::vector<uint8_t> ScriptParser::readFill() {
1176 expect("(");
1177 std::vector<uint8_t> V = readOutputSectionFiller(next());
1178 expect(")");
1179 expect(";");
1180 return V;
1181}
1182
Rui Ueyama10416562016-08-04 02:03:27 +00001183OutputSectionCommand *
1184ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +00001185 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
George Rimar58e5c4d2016-07-25 08:29:46 +00001186
1187 // Read an address expression.
1188 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
1189 if (peek() != ":")
1190 Cmd->AddrExpr = readExpr();
1191
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001192 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +00001193
George Rimar8ceadb32016-08-17 07:44:19 +00001194 if (skip("AT"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001195 Cmd->LmaExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001196 if (skip("ALIGN"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001197 Cmd->AlignExpr = readParenExpr();
George Rimardb24d9c2016-08-19 15:18:23 +00001198 if (skip("SUBALIGN"))
1199 Cmd->SubalignExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001200
Davide Italiano246f6812016-07-22 03:36:24 +00001201 // Parse constraints.
1202 if (skip("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001203 Cmd->Constraint = ConstraintKind::ReadOnly;
Davide Italiano246f6812016-07-22 03:36:24 +00001204 if (skip("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001205 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001206 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001207
Rui Ueyama025d59b2016-02-02 20:27:59 +00001208 while (!Error && !skip("}")) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001209 StringRef Tok = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +00001210 if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok, false))
Eugene Leviantceabe802016-08-11 07:56:43 +00001211 Cmd->Commands.emplace_back(Assignment);
George Rimarff1f29e2016-09-06 13:51:57 +00001212 else if (Tok == "FILL")
1213 Cmd->Filler = readFill();
Eugene Leviantceabe802016-08-11 07:56:43 +00001214 else if (Tok == "SORT")
George Rimar03fc0102016-07-28 07:18:23 +00001215 readSort();
George Rimara2496cb2016-08-30 09:46:59 +00001216 else if (peek() == "(")
1217 Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
Eugene Leviantceabe802016-08-11 07:56:43 +00001218 else
1219 setError("unknown command " + Tok);
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001220 }
George Rimar076fe152016-07-21 06:43:01 +00001221 Cmd->Phdrs = readOutputSectionPhdrs();
George Rimarff1f29e2016-09-06 13:51:57 +00001222 if (peek().startswith("="))
1223 Cmd->Filler = readOutputSectionFiller(next().drop_front());
Rui Ueyama10416562016-08-04 02:03:27 +00001224 return Cmd;
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001225}
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001226
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001227// Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
1228// https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
1229//
1230// ld.gold is not fully compatible with ld.bfd. ld.bfd handles
1231// hexstrings as blobs of arbitrary sizes, while ld.gold handles them
1232// as 32-bit big-endian values. We will do the same as ld.gold does
1233// because it's simpler than what ld.bfd does.
George Rimarff1f29e2016-09-06 13:51:57 +00001234std::vector<uint8_t> ScriptParser::readOutputSectionFiller(StringRef Tok) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001235 uint32_t V;
George Rimarff1f29e2016-09-06 13:51:57 +00001236 if (Tok.getAsInteger(0, V)) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001237 setError("invalid filler expression: " + Tok);
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001238 return {};
George Rimare2ee72b2016-02-26 14:48:31 +00001239 }
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001240 return {uint8_t(V >> 24), uint8_t(V >> 16), uint8_t(V >> 8), uint8_t(V)};
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001241}
1242
Petr Hoseka35e39c2016-08-16 01:11:16 +00001243SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
Eugene Levianta31c91b2016-07-22 07:38:40 +00001244 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +00001245 SymbolAssignment *Cmd = readAssignment(next());
Petr Hoseka35e39c2016-08-16 01:11:16 +00001246 Cmd->Provide = Provide;
Rui Ueyama174e0a12016-07-29 00:29:25 +00001247 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001248 expect(")");
1249 expect(";");
Rui Ueyama10416562016-08-04 02:03:27 +00001250 return Cmd;
Eugene Levianteda81a12016-07-12 06:39:48 +00001251}
1252
Eugene Leviantdb741e72016-09-07 07:08:43 +00001253SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok,
1254 bool MakeAbsolute) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001255 SymbolAssignment *Cmd = nullptr;
1256 if (peek() == "=" || peek() == "+=") {
1257 Cmd = readAssignment(Tok);
1258 expect(";");
1259 } else if (Tok == "PROVIDE") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001260 Cmd = readProvideHidden(true, false);
1261 } else if (Tok == "HIDDEN") {
1262 Cmd = readProvideHidden(false, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001263 } else if (Tok == "PROVIDE_HIDDEN") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001264 Cmd = readProvideHidden(true, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001265 }
Eugene Leviantdb741e72016-09-07 07:08:43 +00001266 if (Cmd && MakeAbsolute)
1267 Cmd->IsAbsolute = true;
Eugene Leviantceabe802016-08-11 07:56:43 +00001268 return Cmd;
1269}
1270
George Rimar30835ea2016-07-28 21:08:56 +00001271static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
1272 if (S == ".")
1273 return Dot;
George Rimar884e7862016-09-08 08:19:13 +00001274 return ScriptBase->getSymbolValue(S);
George Rimare32a3592016-08-10 07:59:34 +00001275}
1276
George Rimar30835ea2016-07-28 21:08:56 +00001277SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1278 StringRef Op = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +00001279 bool IsAbsolute = false;
1280 Expr E;
George Rimar30835ea2016-07-28 21:08:56 +00001281 assert(Op == "=" || Op == "+=");
Eugene Leviantdb741e72016-09-07 07:08:43 +00001282 if (skip("ABSOLUTE")) {
1283 E = readParenExpr();
1284 IsAbsolute = true;
1285 } else {
1286 E = readExpr();
1287 }
George Rimar30835ea2016-07-28 21:08:56 +00001288 if (Op == "+=")
1289 E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
Eugene Leviantdb741e72016-09-07 07:08:43 +00001290 return new SymbolAssignment(Name, E, IsAbsolute);
George Rimar30835ea2016-07-28 21:08:56 +00001291}
1292
1293// This is an operator-precedence parser to parse a linker
1294// script expression.
1295Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
1296
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001297static Expr combine(StringRef Op, Expr L, Expr R) {
1298 if (Op == "*")
1299 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1300 if (Op == "/") {
1301 return [=](uint64_t Dot) -> uint64_t {
1302 uint64_t RHS = R(Dot);
1303 if (RHS == 0) {
1304 error("division by zero");
1305 return 0;
1306 }
1307 return L(Dot) / RHS;
1308 };
1309 }
1310 if (Op == "+")
1311 return [=](uint64_t Dot) { return L(Dot) + R(Dot); };
1312 if (Op == "-")
1313 return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
1314 if (Op == "<")
1315 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
1316 if (Op == ">")
1317 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
1318 if (Op == ">=")
1319 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
1320 if (Op == "<=")
1321 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
1322 if (Op == "==")
1323 return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
1324 if (Op == "!=")
1325 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
1326 if (Op == "&")
1327 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
Rafael Espindolacc3dd622016-08-22 21:33:35 +00001328 if (Op == "|")
1329 return [=](uint64_t Dot) { return L(Dot) | R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001330 llvm_unreachable("invalid operator");
1331}
1332
Rui Ueyama708019c2016-07-24 18:19:40 +00001333// This is a part of the operator-precedence parser. This function
1334// assumes that the remaining token stream starts with an operator.
1335Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1336 while (!atEOF() && !Error) {
1337 // Read an operator and an expression.
1338 StringRef Op1 = peek();
1339 if (Op1 == "?")
1340 return readTernary(Lhs);
1341 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +00001342 break;
Rui Ueyama708019c2016-07-24 18:19:40 +00001343 next();
1344 Expr Rhs = readPrimary();
1345
1346 // Evaluate the remaining part of the expression first if the
1347 // next operator has greater precedence than the previous one.
1348 // For example, if we have read "+" and "3", and if the next
1349 // operator is "*", then we'll evaluate 3 * ... part first.
1350 while (!atEOF()) {
1351 StringRef Op2 = peek();
1352 if (precedence(Op2) <= precedence(Op1))
1353 break;
1354 Rhs = readExpr1(Rhs, precedence(Op2));
1355 }
1356
1357 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +00001358 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001359 return Lhs;
1360}
1361
1362uint64_t static getConstant(StringRef S) {
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001363 if (S == "COMMONPAGESIZE")
Rui Ueyama708019c2016-07-24 18:19:40 +00001364 return Target->PageSize;
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001365 if (S == "MAXPAGESIZE")
1366 return Target->MaxPageSize;
Rui Ueyama708019c2016-07-24 18:19:40 +00001367 error("unknown constant: " + S);
1368 return 0;
1369}
1370
Rui Ueyama626e0b02016-09-02 18:19:00 +00001371// Parses Tok as an integer. Returns true if successful.
1372// It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1373// and decimal numbers. Decimal numbers may have "K" (kilo) or
1374// "M" (mega) prefixes.
George Rimar9f2f7ad2016-09-02 16:01:42 +00001375static bool readInteger(StringRef Tok, uint64_t &Result) {
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001376 if (Tok.startswith("-")) {
1377 if (!readInteger(Tok.substr(1), Result))
1378 return false;
1379 Result = -Result;
1380 return true;
1381 }
George Rimar9f2f7ad2016-09-02 16:01:42 +00001382 if (Tok.startswith_lower("0x"))
1383 return !Tok.substr(2).getAsInteger(16, Result);
1384 if (Tok.endswith_lower("H"))
1385 return !Tok.drop_back().getAsInteger(16, Result);
1386
1387 int Suffix = 1;
1388 if (Tok.endswith_lower("K")) {
1389 Suffix = 1024;
1390 Tok = Tok.drop_back();
1391 } else if (Tok.endswith_lower("M")) {
1392 Suffix = 1024 * 1024;
1393 Tok = Tok.drop_back();
1394 }
1395 if (Tok.getAsInteger(10, Result))
1396 return false;
1397 Result *= Suffix;
1398 return true;
1399}
1400
Rui Ueyama708019c2016-07-24 18:19:40 +00001401Expr ScriptParser::readPrimary() {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001402 if (peek() == "(")
1403 return readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001404
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001405 StringRef Tok = next();
Rui Ueyama708019c2016-07-24 18:19:40 +00001406
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001407 if (Tok == "~") {
1408 Expr E = readPrimary();
1409 return [=](uint64_t Dot) { return ~E(Dot); };
1410 }
1411 if (Tok == "-") {
1412 Expr E = readPrimary();
1413 return [=](uint64_t Dot) { return -E(Dot); };
1414 }
1415
Rui Ueyama708019c2016-07-24 18:19:40 +00001416 // Built-in functions are parsed here.
1417 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
George Rimar96659df2016-08-30 09:54:01 +00001418 if (Tok == "ADDR") {
1419 expect("(");
1420 StringRef Name = next();
1421 expect(")");
George Rimar884e7862016-09-08 08:19:13 +00001422 return
1423 [=](uint64_t Dot) { return ScriptBase->getOutputSectionAddress(Name); };
George Rimar96659df2016-08-30 09:54:01 +00001424 }
George Rimareefa7582016-08-04 09:29:31 +00001425 if (Tok == "ASSERT")
1426 return readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001427 if (Tok == "ALIGN") {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001428 Expr E = readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001429 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1430 }
1431 if (Tok == "CONSTANT") {
1432 expect("(");
1433 StringRef Tok = next();
1434 expect(")");
1435 return [=](uint64_t Dot) { return getConstant(Tok); };
1436 }
Rafael Espindola54c145c2016-07-28 18:16:24 +00001437 if (Tok == "SEGMENT_START") {
1438 expect("(");
1439 next();
1440 expect(",");
George Rimar8c658bf2016-09-17 18:14:56 +00001441 Expr E = readExpr();
Rafael Espindola54c145c2016-07-28 18:16:24 +00001442 expect(")");
George Rimar8c658bf2016-09-17 18:14:56 +00001443 return [=](uint64_t Dot) { return E(Dot); };
Rafael Espindola54c145c2016-07-28 18:16:24 +00001444 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001445 if (Tok == "DATA_SEGMENT_ALIGN") {
1446 expect("(");
1447 Expr E = readExpr();
1448 expect(",");
1449 readExpr();
1450 expect(")");
Rui Ueyamaf7791bb2016-07-26 19:34:10 +00001451 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001452 }
1453 if (Tok == "DATA_SEGMENT_END") {
1454 expect("(");
1455 expect(".");
1456 expect(")");
1457 return [](uint64_t Dot) { return Dot; };
1458 }
George Rimar276b4e62016-07-26 17:58:44 +00001459 // GNU linkers implements more complicated logic to handle
1460 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1461 // the next page boundary for simplicity.
1462 if (Tok == "DATA_SEGMENT_RELRO_END") {
1463 expect("(");
Rafael Espindola97bdc722016-09-14 19:14:01 +00001464 readExpr();
George Rimar276b4e62016-07-26 17:58:44 +00001465 expect(",");
1466 readExpr();
1467 expect(")");
1468 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1469 }
George Rimar9e694502016-07-29 16:18:47 +00001470 if (Tok == "SIZEOF") {
1471 expect("(");
1472 StringRef Name = next();
1473 expect(")");
George Rimar884e7862016-09-08 08:19:13 +00001474 return [=](uint64_t Dot) { return ScriptBase->getOutputSectionSize(Name); };
George Rimar9e694502016-07-29 16:18:47 +00001475 }
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001476 if (Tok == "ALIGNOF") {
1477 expect("(");
1478 StringRef Name = next();
1479 expect(")");
1480 return
1481 [=](uint64_t Dot) { return ScriptBase->getOutputSectionAlign(Name); };
1482 }
George Rimare32a3592016-08-10 07:59:34 +00001483 if (Tok == "SIZEOF_HEADERS")
George Rimar884e7862016-09-08 08:19:13 +00001484 return [=](uint64_t Dot) { return ScriptBase->getHeaderSize(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001485
George Rimar9f2f7ad2016-09-02 16:01:42 +00001486 // Tok is a literal number.
1487 uint64_t V;
1488 if (readInteger(Tok, V))
1489 return [=](uint64_t Dot) { return V; };
1490
1491 // Tok is a symbol name.
1492 if (Tok != "." && !isValidCIdentifier(Tok))
1493 setError("malformed number: " + Tok);
1494 return [=](uint64_t Dot) { return getSymbolValue(Tok, Dot); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001495}
1496
1497Expr ScriptParser::readTernary(Expr Cond) {
1498 next();
1499 Expr L = readExpr();
1500 expect(":");
1501 Expr R = readExpr();
1502 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1503}
1504
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001505Expr ScriptParser::readParenExpr() {
1506 expect("(");
1507 Expr E = readExpr();
1508 expect(")");
1509 return E;
1510}
1511
Eugene Leviantbbe38602016-07-19 09:25:43 +00001512std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1513 std::vector<StringRef> Phdrs;
1514 while (!Error && peek().startswith(":")) {
1515 StringRef Tok = next();
1516 Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
1517 if (Tok.empty()) {
1518 setError("section header name is empty");
1519 break;
1520 }
Rui Ueyama047404f2016-07-20 19:36:36 +00001521 Phdrs.push_back(Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001522 }
1523 return Phdrs;
1524}
1525
1526unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001527 StringRef Tok = next();
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001528 unsigned Ret = StringSwitch<unsigned>(Tok)
George Rimar6c55f0e2016-09-08 08:20:30 +00001529 .Case("PT_NULL", PT_NULL)
1530 .Case("PT_LOAD", PT_LOAD)
1531 .Case("PT_DYNAMIC", PT_DYNAMIC)
1532 .Case("PT_INTERP", PT_INTERP)
1533 .Case("PT_NOTE", PT_NOTE)
1534 .Case("PT_SHLIB", PT_SHLIB)
1535 .Case("PT_PHDR", PT_PHDR)
1536 .Case("PT_TLS", PT_TLS)
1537 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1538 .Case("PT_GNU_STACK", PT_GNU_STACK)
1539 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1540 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001541
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001542 if (Ret == (unsigned)-1) {
1543 setError("invalid program header type: " + Tok);
1544 return PT_NULL;
1545 }
1546 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001547}
1548
Rui Ueyama95769b42016-08-31 20:03:54 +00001549void ScriptParser::readVersionDeclaration(StringRef VerStr) {
George Rimar20b65982016-08-31 09:08:26 +00001550 // Identifiers start at 2 because 0 and 1 are reserved
1551 // for VER_NDX_LOCAL and VER_NDX_GLOBAL constants.
1552 size_t VersionId = Config->VersionDefinitions.size() + 2;
1553 Config->VersionDefinitions.push_back({VerStr, VersionId});
1554
1555 if (skip("global:") || peek() != "local:")
1556 readGlobal(VerStr);
1557 if (skip("local:"))
1558 readLocal();
1559 expect("}");
1560
1561 // Each version may have a parent version. For example, "Ver2" defined as
1562 // "Ver2 { global: foo; local: *; } Ver1;" has "Ver1" as a parent. This
1563 // version hierarchy is, probably against your instinct, purely for human; the
1564 // runtime doesn't care about them at all. In LLD, we simply skip the token.
1565 if (!VerStr.empty() && peek() != ";")
1566 next();
1567 expect(";");
1568}
1569
1570void ScriptParser::readLocal() {
1571 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1572 expect("*");
1573 expect(";");
1574}
1575
1576void ScriptParser::readExtern(std::vector<SymbolVersion> *Globals) {
George Rimarcd574a52016-09-09 14:35:36 +00001577 expect("\"C++\"");
George Rimar20b65982016-08-31 09:08:26 +00001578 expect("{");
1579
1580 for (;;) {
1581 if (peek() == "}" || Error)
1582 break;
George Rimarcd574a52016-09-09 14:35:36 +00001583 bool HasWildcard = !peek().startswith("\"") && hasWildcard(peek());
1584 Globals->push_back({unquote(next()), true, HasWildcard});
George Rimar20b65982016-08-31 09:08:26 +00001585 expect(";");
1586 }
1587
1588 expect("}");
1589 expect(";");
1590}
1591
1592void ScriptParser::readGlobal(StringRef VerStr) {
1593 std::vector<SymbolVersion> *Globals;
1594 if (VerStr.empty())
1595 Globals = &Config->VersionScriptGlobals;
1596 else
1597 Globals = &Config->VersionDefinitions.back().Globals;
1598
1599 for (;;) {
1600 if (skip("extern"))
1601 readExtern(Globals);
1602
1603 StringRef Cur = peek();
1604 if (Cur == "}" || Cur == "local:" || Error)
1605 return;
1606 next();
George Rimarcd574a52016-09-09 14:35:36 +00001607 Globals->push_back({unquote(Cur), false, hasWildcard(Cur)});
George Rimar20b65982016-08-31 09:08:26 +00001608 expect(";");
1609 }
1610}
1611
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001612static bool isUnderSysroot(StringRef Path) {
1613 if (Config->Sysroot == "")
1614 return false;
1615 for (; !Path.empty(); Path = sys::path::parent_path(Path))
1616 if (sys::fs::equivalent(Config->Sysroot, Path))
1617 return true;
1618 return false;
1619}
1620
Rui Ueyama07320e42016-04-20 20:13:41 +00001621void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001622 StringRef Path = MB.getBufferIdentifier();
George Rimar20b65982016-08-31 09:08:26 +00001623 ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).readLinkerScript();
1624}
1625
1626void elf::readVersionScript(MemoryBufferRef MB) {
1627 ScriptParser(MB.getBuffer(), false).readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001628}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001629
Rui Ueyama07320e42016-04-20 20:13:41 +00001630template class elf::LinkerScript<ELF32LE>;
1631template class elf::LinkerScript<ELF32BE>;
1632template class elf::LinkerScript<ELF64LE>;
1633template class elf::LinkerScript<ELF64BE>;