blob: 9dffb0bd3be90cfb18d3268f01a1f554f9b92410 [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"
Rui Ueyama55518e72016-10-28 20:57:25 +000024#include "Memory.h"
George Rimar652852c2016-04-16 10:10:32 +000025#include "OutputSections.h"
Adhemerval Zanellae77b5bf2016-04-06 20:59:11 +000026#include "ScriptParser.h"
Rui Ueyama93c9af42016-06-29 08:01:32 +000027#include "Strings.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000028#include "SymbolTable.h"
Rui Ueyama55518e72016-10-28 20:57:25 +000029#include "Symbols.h"
Eugene Leviant467c4d52016-07-01 10:27:36 +000030#include "Target.h"
Eugene Leviantbbe38602016-07-19 09:25:43 +000031#include "Writer.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000032#include "llvm/ADT/STLExtras.h"
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +000033#include "llvm/ADT/SmallString.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000034#include "llvm/ADT/StringRef.h"
Rui Ueyama960504b2016-04-19 18:58:11 +000035#include "llvm/ADT/StringSwitch.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000036#include "llvm/Support/Casting.h"
George Rimar652852c2016-04-16 10:10:32 +000037#include "llvm/Support/ELF.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000038#include "llvm/Support/Endian.h"
39#include "llvm/Support/ErrorHandling.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000040#include "llvm/Support/FileSystem.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000041#include "llvm/Support/MathExtras.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000042#include "llvm/Support/MemoryBuffer.h"
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +000043#include "llvm/Support/Path.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000044#include <algorithm>
45#include <cassert>
46#include <cstddef>
47#include <cstdint>
48#include <iterator>
49#include <limits>
50#include <memory>
51#include <string>
52#include <tuple>
53#include <vector>
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000054
55using namespace llvm;
George Rimar652852c2016-04-16 10:10:32 +000056using namespace llvm::ELF;
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +000057using namespace llvm::object;
George Rimare38cbab2016-09-26 19:22:50 +000058using namespace llvm::support::endian;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000059using namespace lld;
Rafael Espindolae0df00b2016-02-28 00:25:54 +000060using namespace lld::elf;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000061
George Rimar884e7862016-09-08 08:19:13 +000062LinkerScriptBase *elf::ScriptBase;
Rui Ueyama07320e42016-04-20 20:13:41 +000063ScriptConfiguration *elf::ScriptConfig;
Rui Ueyama717677a2016-02-11 21:17:59 +000064
George Rimar6c55f0e2016-09-08 08:20:30 +000065template <class ELFT> static void addRegular(SymbolAssignment *Cmd) {
Rafael Espindola3dabfc62016-10-31 13:14:53 +000066 uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
Rui Ueyama1bdaf3e2016-11-09 23:37:40 +000067 Symbol *Sym = Symtab<ELFT>::X->addRegular(Cmd->Name, Visibility, STT_NOTYPE,
68 0, 0, STB_GLOBAL, nullptr);
Rui Ueyama16024212016-08-11 23:22:52 +000069 Cmd->Sym = Sym->body();
Eugene Leviant20d03192016-09-16 15:30:47 +000070
71 // If we have no SECTIONS then we don't have '.' and don't call
72 // assignAddresses(). We calculate symbol value immediately in this case.
73 if (!ScriptConfig->HasSections)
74 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(0);
Eugene Leviantceabe802016-08-11 07:56:43 +000075}
76
Rui Ueyama0c70d3c2016-08-12 03:31:09 +000077template <class ELFT> static void addSynthetic(SymbolAssignment *Cmd) {
George Rimare1937bb2016-08-19 15:36:32 +000078 Symbol *Sym = Symtab<ELFT>::X->addSynthetic(
79 Cmd->Name, nullptr, 0, Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT);
Rui Ueyama16024212016-08-11 23:22:52 +000080 Cmd->Sym = Sym->body();
Eugene Leviantceabe802016-08-11 07:56:43 +000081}
82
Eugene Leviantdb741e72016-09-07 07:08:43 +000083template <class ELFT> static void addSymbol(SymbolAssignment *Cmd) {
Rafael Espindola2f831dc2016-10-31 19:56:37 +000084 if (Cmd->Expression.IsAbsolute())
Eugene Leviantdb741e72016-09-07 07:08:43 +000085 addRegular<ELFT>(Cmd);
86 else
87 addSynthetic<ELFT>(Cmd);
88}
Rui Ueyama16024212016-08-11 23:22:52 +000089// If a symbol was in PROVIDE(), we need to define it only when
90// it is an undefined symbol.
91template <class ELFT> static bool shouldDefine(SymbolAssignment *Cmd) {
92 if (Cmd->Name == ".")
Eugene Leviantceabe802016-08-11 07:56:43 +000093 return false;
Rui Ueyama16024212016-08-11 23:22:52 +000094 if (!Cmd->Provide)
95 return true;
96 SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
97 return B && B->isUndefined();
Eugene Leviantceabe802016-08-11 07:56:43 +000098}
99
George Rimar076fe152016-07-21 06:43:01 +0000100bool SymbolAssignment::classof(const BaseCommand *C) {
101 return C->Kind == AssignmentKind;
102}
103
104bool OutputSectionCommand::classof(const BaseCommand *C) {
105 return C->Kind == OutputSectionKind;
106}
107
George Rimareea31142016-07-21 14:26:59 +0000108bool InputSectionDescription::classof(const BaseCommand *C) {
109 return C->Kind == InputSectionKind;
110}
111
George Rimareefa7582016-08-04 09:29:31 +0000112bool AssertCommand::classof(const BaseCommand *C) {
113 return C->Kind == AssertKind;
114}
115
George Rimare38cbab2016-09-26 19:22:50 +0000116bool BytesDataCommand::classof(const BaseCommand *C) {
117 return C->Kind == BytesDataKind;
118}
119
Eugene Zelenko22886a22016-11-05 01:00:56 +0000120template <class ELFT> LinkerScript<ELFT>::LinkerScript() = default;
121template <class ELFT> LinkerScript<ELFT>::~LinkerScript() = default;
Rui Ueyamaf34d0e02016-08-12 01:24:53 +0000122
Rui Ueyama07320e42016-04-20 20:13:41 +0000123template <class ELFT>
124bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) {
Eugene Leviantcf43f172016-10-05 09:36:59 +0000125 for (InputSectionDescription *ID : Opt.KeptSections) {
126 StringRef Filename = S->getFile()->getName();
Rui Ueyamaf91282e2016-11-03 17:57:38 +0000127 if (!ID->FilePat.match(sys::path::filename(Filename)))
Eugene Leviantcf43f172016-10-05 09:36:59 +0000128 continue;
Rui Ueyamab66260a2016-10-05 20:09:50 +0000129
130 for (SectionPattern &P : ID->SectionPatterns)
Rui Ueyamaf91282e2016-11-03 17:57:38 +0000131 if (P.SectionPat.match(S->Name))
Eugene Leviantcf43f172016-10-05 09:36:59 +0000132 return true;
133 }
George Rimareea31142016-07-21 14:26:59 +0000134 return false;
135}
136
George Rimar575208c2016-09-15 19:15:12 +0000137static bool comparePriority(InputSectionData *A, InputSectionData *B) {
138 return getPriority(A->Name) < getPriority(B->Name);
139}
140
Rafael Espindolac0028d32016-09-08 20:47:52 +0000141static bool compareName(InputSectionData *A, InputSectionData *B) {
Rafael Espindola042a3f22016-09-08 14:06:08 +0000142 return A->Name < B->Name;
Rui Ueyama742c3832016-08-04 22:27:00 +0000143}
George Rimar350ece42016-08-03 08:35:59 +0000144
Rafael Espindolac0028d32016-09-08 20:47:52 +0000145static bool compareAlignment(InputSectionData *A, InputSectionData *B) {
Rui Ueyama742c3832016-08-04 22:27:00 +0000146 // ">" is not a mistake. Larger alignments are placed before smaller
147 // alignments in order to reduce the amount of padding necessary.
148 // This is compatible with GNU.
149 return A->Alignment > B->Alignment;
150}
George Rimar350ece42016-08-03 08:35:59 +0000151
Rafael Espindolac0028d32016-09-08 20:47:52 +0000152static std::function<bool(InputSectionData *, InputSectionData *)>
George Rimarbe394db2016-09-16 20:21:55 +0000153getComparator(SortSectionPolicy K) {
154 switch (K) {
155 case SortSectionPolicy::Alignment:
156 return compareAlignment;
157 case SortSectionPolicy::Name:
Rafael Espindolac0028d32016-09-08 20:47:52 +0000158 return compareName;
George Rimarbe394db2016-09-16 20:21:55 +0000159 case SortSectionPolicy::Priority:
160 return comparePriority;
161 default:
162 llvm_unreachable("unknown sort policy");
163 }
Rui Ueyama742c3832016-08-04 22:27:00 +0000164}
George Rimar0702c4e2016-07-29 15:32:46 +0000165
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000166template <class ELFT>
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000167static bool matchConstraints(ArrayRef<InputSectionBase<ELFT> *> Sections,
George Rimar06ae6832016-08-12 09:07:57 +0000168 ConstraintKind Kind) {
George Rimar8f66df92016-08-12 20:38:20 +0000169 if (Kind == ConstraintKind::NoConstraint)
170 return true;
Rafael Espindolae746e522016-09-21 18:33:44 +0000171 bool IsRW = llvm::any_of(Sections, [=](InputSectionData *Sec2) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000172 auto *Sec = static_cast<InputSectionBase<ELFT> *>(Sec2);
Rafael Espindola1854a8e2016-10-26 12:36:56 +0000173 return Sec->Flags & SHF_WRITE;
George Rimar06ae6832016-08-12 09:07:57 +0000174 });
Rafael Espindolae746e522016-09-21 18:33:44 +0000175 return (IsRW && Kind == ConstraintKind::ReadWrite) ||
176 (!IsRW && Kind == ConstraintKind::ReadOnly);
George Rimar06ae6832016-08-12 09:07:57 +0000177}
178
George Rimar07171f22016-09-21 15:56:44 +0000179static void sortSections(InputSectionData **Begin, InputSectionData **End,
Rui Ueyamaee924702016-09-20 19:42:41 +0000180 SortSectionPolicy K) {
181 if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
George Rimar07171f22016-09-21 15:56:44 +0000182 std::stable_sort(Begin, End, getComparator(K));
Rui Ueyamaee924702016-09-20 19:42:41 +0000183}
184
Rafael Espindolad3190792016-09-16 15:10:23 +0000185// Compute and remember which sections the InputSectionDescription matches.
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000186template <class ELFT>
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000187void LinkerScript<ELFT>::computeInputSections(InputSectionDescription *I) {
Rui Ueyama4dc07be2016-09-17 02:23:40 +0000188 // Collects all sections that satisfy constraints of I
189 // and attach them to I.
190 for (SectionPattern &Pat : I->SectionPatterns) {
George Rimar07171f22016-09-21 15:56:44 +0000191 size_t SizeBefore = I->Sections.size();
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000192
193 for (InputSectionBase<ELFT> *S : Symtab<ELFT>::X->Sections) {
Rafael Espindola8f9026b2016-11-08 18:23:02 +0000194 if (!S->Live || S->OutSec)
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000195 continue;
196
197 StringRef Filename;
198 if (elf::ObjectFile<ELFT> *F = S->getFile())
199 Filename = sys::path::filename(F->getName());
200
Rui Ueyamae8a61022016-11-05 23:05:47 +0000201 if (I->FilePat.match(Filename) && !Pat.ExcludedFilePat.match(Filename) &&
202 Pat.SectionPat.match(S->Name))
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000203 I->Sections.push_back(S);
George Rimar395281c2016-09-16 17:42:10 +0000204 }
Rafael Espindolad3190792016-09-16 15:10:23 +0000205
George Rimar07171f22016-09-21 15:56:44 +0000206 // Sort sections as instructed by SORT-family commands and --sort-section
207 // option. Because SORT-family commands can be nested at most two depth
208 // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
209 // line option is respected even if a SORT command is given, the exact
210 // behavior we have here is a bit complicated. Here are the rules.
211 //
212 // 1. If two SORT commands are given, --sort-section is ignored.
213 // 2. If one SORT command is given, and if it is not SORT_NONE,
214 // --sort-section is handled as an inner SORT command.
215 // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
216 // 4. If no SORT command is given, sort according to --sort-section.
217 InputSectionData **Begin = I->Sections.data() + SizeBefore;
218 InputSectionData **End = I->Sections.data() + I->Sections.size();
219 if (Pat.SortOuter != SortSectionPolicy::None) {
220 if (Pat.SortInner == SortSectionPolicy::Default)
221 sortSections(Begin, End, Config->SortSection);
222 else
223 sortSections(Begin, End, Pat.SortInner);
224 sortSections(Begin, End, Pat.SortOuter);
225 }
Rui Ueyamaee924702016-09-20 19:42:41 +0000226 }
Rafael Espindolad3190792016-09-16 15:10:23 +0000227
228 // We do not add duplicate input sections, so mark them with a dummy output
229 // section for now.
230 for (InputSectionData *S : I->Sections) {
231 auto *S2 = static_cast<InputSectionBase<ELFT> *>(S);
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000232 S2->OutSec = (OutputSectionBase *)-1;
Rafael Espindolad3190792016-09-16 15:10:23 +0000233 }
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000234}
235
236template <class ELFT>
237void LinkerScript<ELFT>::discard(ArrayRef<InputSectionBase<ELFT> *> V) {
238 for (InputSectionBase<ELFT> *S : V) {
239 S->Live = false;
240 reportDiscarded(S);
241 }
242}
243
George Rimar06ae6832016-08-12 09:07:57 +0000244template <class ELFT>
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000245std::vector<InputSectionBase<ELFT> *>
George Rimar06ae6832016-08-12 09:07:57 +0000246LinkerScript<ELFT>::createInputSectionList(OutputSectionCommand &OutCmd) {
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000247 std::vector<InputSectionBase<ELFT> *> Ret;
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000248
George Rimar06ae6832016-08-12 09:07:57 +0000249 for (const std::unique_ptr<BaseCommand> &Base : OutCmd.Commands) {
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000250 auto *Cmd = dyn_cast<InputSectionDescription>(Base.get());
251 if (!Cmd)
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000252 continue;
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000253 computeInputSections(Cmd);
Rafael Espindolad3190792016-09-16 15:10:23 +0000254 for (InputSectionData *S : Cmd->Sections)
255 Ret.push_back(static_cast<InputSectionBase<ELFT> *>(S));
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000256 }
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000257
Eugene Leviantcc1ba8c2016-10-12 12:31:34 +0000258 // After we created final list we should now set OutSec pointer to null,
George Rimara4c7e742016-10-20 08:36:42 +0000259 // instead of -1. Otherwise we may get a crash when writing relocs, in
Eugene Leviantcc1ba8c2016-10-12 12:31:34 +0000260 // case section is discarded by linker script
261 for (InputSectionBase<ELFT> *S : Ret)
262 S->OutSec = nullptr;
263
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000264 return Ret;
265}
266
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000267template <class ELFT>
Rafael Espindola10897f12016-09-13 14:23:14 +0000268static SectionKey<ELFT::Is64Bits> createKey(InputSectionBase<ELFT> *C,
269 StringRef OutsecName) {
270 // When using linker script the merge rules are different.
271 // Unfortunately, linker scripts are name based. This means that expressions
272 // like *(.foo*) can refer to multiple input sections that would normally be
273 // placed in different output sections. We cannot put them in different
274 // output sections or we would produce wrong results for
275 // start = .; *(.foo.*) end = .; *(.bar)
276 // and a mapping of .foo1 and .bar1 to one section and .foo2 and .bar2 to
277 // another. The problem is that there is no way to layout those output
278 // sections such that the .foo sections are the only thing between the
279 // start and end symbols.
280
281 // An extra annoyance is that we cannot simply disable merging of the contents
282 // of SHF_MERGE sections, but our implementation requires one output section
283 // per "kind" (string or not, which size/aligment).
284 // Fortunately, creating symbols in the middle of a merge section is not
285 // supported by bfd or gold, so we can just create multiple section in that
286 // case.
Rafael Espindola10897f12016-09-13 14:23:14 +0000287 typedef typename ELFT::uint uintX_t;
Rafael Espindola1854a8e2016-10-26 12:36:56 +0000288 uintX_t Flags = C->Flags & (SHF_MERGE | SHF_STRINGS);
Rafael Espindola10897f12016-09-13 14:23:14 +0000289
290 uintX_t Alignment = 0;
291 if (isa<MergeInputSection<ELFT>>(C))
Rafael Espindola1854a8e2016-10-26 12:36:56 +0000292 Alignment = std::max<uintX_t>(C->Alignment, C->Entsize);
Rafael Espindola10897f12016-09-13 14:23:14 +0000293
294 return SectionKey<ELFT::Is64Bits>{OutsecName, /*Type*/ 0, Flags, Alignment};
295}
296
297template <class ELFT>
Eugene Leviant20d03192016-09-16 15:30:47 +0000298void LinkerScript<ELFT>::addSection(OutputSectionFactory<ELFT> &Factory,
299 InputSectionBase<ELFT> *Sec,
300 StringRef Name) {
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000301 OutputSectionBase *OutSec;
Eugene Leviant20d03192016-09-16 15:30:47 +0000302 bool IsNew;
303 std::tie(OutSec, IsNew) = Factory.create(createKey(Sec, Name), Sec);
304 if (IsNew)
305 OutputSections->push_back(OutSec);
306 OutSec->addSection(Sec);
307}
308
309template <class ELFT>
310void LinkerScript<ELFT>::processCommands(OutputSectionFactory<ELFT> &Factory) {
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000311 for (unsigned I = 0; I < Opt.Commands.size(); ++I) {
312 auto Iter = Opt.Commands.begin() + I;
313 const std::unique_ptr<BaseCommand> &Base1 = *Iter;
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000314 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base1.get())) {
315 if (shouldDefine<ELFT>(Cmd))
Rafael Espindolab0de56b2016-10-31 21:36:23 +0000316 addSymbol<ELFT>(Cmd);
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000317 continue;
318 }
Eugene Leviant20d03192016-09-16 15:30:47 +0000319 if (auto *Cmd = dyn_cast<AssertCommand>(Base1.get())) {
320 // If we don't have SECTIONS then output sections have already been
George Rimar194470cd2016-09-17 19:21:05 +0000321 // created by Writer<ELFT>. The LinkerScript<ELFT>::assignAddresses
Eugene Leviant20d03192016-09-16 15:30:47 +0000322 // will not be called, so ASSERT should be evaluated now.
323 if (!Opt.HasSections)
324 Cmd->Expression(0);
325 continue;
326 }
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000327
Eugene Leviantceabe802016-08-11 07:56:43 +0000328 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000329 std::vector<InputSectionBase<ELFT> *> V = createInputSectionList(*Cmd);
330
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000331 if (Cmd->Name == "/DISCARD/") {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000332 discard(V);
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000333 continue;
334 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000335
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000336 if (!matchConstraints<ELFT>(V, Cmd->Constraint)) {
337 for (InputSectionBase<ELFT> *S : V)
338 S->OutSec = nullptr;
339 Opt.Commands.erase(Iter);
George Rimardfbbbc82016-09-17 09:50:10 +0000340 --I;
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000341 continue;
342 }
343
344 for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
345 if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base.get()))
346 if (shouldDefine<ELFT>(OutCmd))
347 addSymbol<ELFT>(OutCmd);
348
Eugene Leviant97403d12016-09-01 09:55:57 +0000349 if (V.empty())
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000350 continue;
351
George Rimardb24d9c2016-08-19 15:18:23 +0000352 for (InputSectionBase<ELFT> *Sec : V) {
Eugene Leviant20d03192016-09-16 15:30:47 +0000353 addSection(Factory, Sec, Cmd->Name);
354 if (uint32_t Subalign = Cmd->SubalignExpr ? Cmd->SubalignExpr(0) : 0)
George Rimardb24d9c2016-08-19 15:18:23 +0000355 Sec->Alignment = Subalign;
George Rimardb24d9c2016-08-19 15:18:23 +0000356 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000357 }
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000358 }
Eugene Leviant20d03192016-09-16 15:30:47 +0000359}
Eugene Leviante63d81b2016-07-20 14:43:20 +0000360
Eugene Leviant20d03192016-09-16 15:30:47 +0000361template <class ELFT>
362void LinkerScript<ELFT>::createSections(OutputSectionFactory<ELFT> &Factory) {
363 processCommands(Factory);
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000364
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000365 // Add orphan sections.
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000366 for (InputSectionBase<ELFT> *S : Symtab<ELFT>::X->Sections)
Rafael Espindola8f9026b2016-11-08 18:23:02 +0000367 if (S->Live && !S->OutSec)
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000368 addSection(Factory, S, getOutputSectionName(S->Name));
Eugene Leviante63d81b2016-07-20 14:43:20 +0000369}
370
Eugene Leviantdb741e72016-09-07 07:08:43 +0000371// Sets value of a section-defined symbol. Two kinds of
372// symbols are processed: synthetic symbols, whose value
373// is an offset from beginning of section and regular
374// symbols whose value is absolute.
375template <class ELFT>
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000376static void assignSectionSymbol(SymbolAssignment *Cmd, OutputSectionBase *Sec,
Rafael Espindola498ed712016-10-31 14:44:41 +0000377 typename ELFT::uint Value) {
Eugene Leviantdb741e72016-09-07 07:08:43 +0000378 if (!Cmd->Sym)
379 return;
380
381 if (auto *Body = dyn_cast<DefinedSynthetic<ELFT>>(Cmd->Sym)) {
382 Body->Section = Sec;
Rafael Espindola04a2e342016-11-09 01:42:41 +0000383 Body->Value = Cmd->Expression(Value) - Sec->Addr;
Eugene Leviantdb741e72016-09-07 07:08:43 +0000384 return;
385 }
386 auto *Body = cast<DefinedRegular<ELFT>>(Cmd->Sym);
Rafael Espindola498ed712016-10-31 14:44:41 +0000387 Body->Value = Cmd->Expression(Value);
Eugene Leviantdb741e72016-09-07 07:08:43 +0000388}
389
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000390template <class ELFT> static bool isTbss(OutputSectionBase *Sec) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000391 return (Sec->Flags & SHF_TLS) && Sec->Type == SHT_NOBITS;
Rafael Espindolaa940e532016-09-22 12:35:44 +0000392}
393
Rafael Espindolad3190792016-09-16 15:10:23 +0000394template <class ELFT> void LinkerScript<ELFT>::output(InputSection<ELFT> *S) {
395 if (!AlreadyOutputIS.insert(S).second)
396 return;
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000397 bool IsTbss = isTbss<ELFT>(CurOutSec);
Eugene Leviant20889c52016-08-31 08:13:33 +0000398
Rafael Espindolad3190792016-09-16 15:10:23 +0000399 uintX_t Pos = IsTbss ? Dot + ThreadBssOffset : Dot;
400 Pos = alignTo(Pos, S->Alignment);
Rafael Espindola04a2e342016-11-09 01:42:41 +0000401 S->OutSecOff = Pos - CurOutSec->Addr;
Rafael Espindolad3190792016-09-16 15:10:23 +0000402 Pos += S->getSize();
403
404 // Update output section size after adding each section. This is so that
405 // SIZEOF works correctly in the case below:
406 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
Rafael Espindola04a2e342016-11-09 01:42:41 +0000407 CurOutSec->Size = Pos - CurOutSec->Addr;
Rafael Espindolad3190792016-09-16 15:10:23 +0000408
Rafael Espindola7252ae52016-09-22 12:00:08 +0000409 if (IsTbss)
410 ThreadBssOffset = Pos - Dot;
411 else
Rafael Espindolad3190792016-09-16 15:10:23 +0000412 Dot = Pos;
413}
414
415template <class ELFT> void LinkerScript<ELFT>::flush() {
Rafael Espindola65499b92016-09-23 20:10:47 +0000416 if (!CurOutSec || !AlreadyOutputOS.insert(CurOutSec).second)
417 return;
418 if (auto *OutSec = dyn_cast<OutputSection<ELFT>>(CurOutSec)) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000419 for (InputSection<ELFT> *I : OutSec->Sections)
420 output(I);
Rafael Espindola65499b92016-09-23 20:10:47 +0000421 } else {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000422 Dot += CurOutSec->Size;
Eugene Leviant20889c52016-08-31 08:13:33 +0000423 }
424}
425
426template <class ELFT>
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000427void LinkerScript<ELFT>::switchTo(OutputSectionBase *Sec) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000428 if (CurOutSec == Sec)
429 return;
430 if (AlreadyOutputOS.count(Sec))
431 return;
432
433 flush();
434 CurOutSec = Sec;
435
Rafael Espindola04a2e342016-11-09 01:42:41 +0000436 Dot = alignTo(Dot, CurOutSec->Addralign);
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000437 CurOutSec->Addr = isTbss<ELFT>(CurOutSec) ? Dot + ThreadBssOffset : Dot;
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000438
439 // If neither AT nor AT> is specified for an allocatable section, the linker
440 // will set the LMA such that the difference between VMA and LMA for the
441 // section is the same as the preceding output section in the same region
442 // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
443 CurOutSec->setLMAOffset(LMAOffset);
Rafael Espindolad3190792016-09-16 15:10:23 +0000444}
445
446template <class ELFT> void LinkerScript<ELFT>::process(BaseCommand &Base) {
George Rimare38cbab2016-09-26 19:22:50 +0000447 // This handles the assignments to symbol or to a location counter (.)
Rafael Espindolad3190792016-09-16 15:10:23 +0000448 if (auto *AssignCmd = dyn_cast<SymbolAssignment>(&Base)) {
449 if (AssignCmd->Name == ".") {
450 // Update to location counter means update to section size.
451 Dot = AssignCmd->Expression(Dot);
Rafael Espindola04a2e342016-11-09 01:42:41 +0000452 CurOutSec->Size = Dot - CurOutSec->Addr;
Rafael Espindolad3190792016-09-16 15:10:23 +0000453 return;
454 }
Rafael Espindola498ed712016-10-31 14:44:41 +0000455 assignSectionSymbol<ELFT>(AssignCmd, CurOutSec, Dot);
Eugene Leviantceabe802016-08-11 07:56:43 +0000456 return;
Rui Ueyama2de509c2016-08-12 00:55:08 +0000457 }
George Rimare38cbab2016-09-26 19:22:50 +0000458
459 // Handle BYTE(), SHORT(), LONG(), or QUAD().
460 if (auto *DataCmd = dyn_cast<BytesDataCommand>(&Base)) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000461 DataCmd->Offset = Dot - CurOutSec->Addr;
George Rimare38cbab2016-09-26 19:22:50 +0000462 Dot += DataCmd->Size;
Rafael Espindola04a2e342016-11-09 01:42:41 +0000463 CurOutSec->Size = Dot - CurOutSec->Addr;
George Rimare38cbab2016-09-26 19:22:50 +0000464 return;
465 }
466
467 // It handles single input section description command,
468 // calculates and assigns the offsets for each section and also
469 // updates the output section size.
Rafael Espindolad3190792016-09-16 15:10:23 +0000470 auto &ICmd = cast<InputSectionDescription>(Base);
471 for (InputSectionData *ID : ICmd.Sections) {
472 auto *IB = static_cast<InputSectionBase<ELFT> *>(ID);
473 switchTo(IB->OutSec);
474 if (auto *I = dyn_cast<InputSection<ELFT>>(IB))
475 output(I);
Rafael Espindola65499b92016-09-23 20:10:47 +0000476 else
477 flush();
Eugene Leviantceabe802016-08-11 07:56:43 +0000478 }
479}
480
George Rimar8f66df92016-08-12 20:38:20 +0000481template <class ELFT>
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000482static std::vector<OutputSectionBase *>
483findSections(StringRef Name, const std::vector<OutputSectionBase *> &Sections) {
484 std::vector<OutputSectionBase *> Ret;
485 for (OutputSectionBase *Sec : Sections)
Eugene Leviant92577642016-10-10 11:23:12 +0000486 if (Sec->getName() == Name)
George Rimara14b13d2016-09-07 10:46:07 +0000487 Ret.push_back(Sec);
488 return Ret;
George Rimar8f66df92016-08-12 20:38:20 +0000489}
490
Rafael Espindolad3190792016-09-16 15:10:23 +0000491template <class ELFT>
492void LinkerScript<ELFT>::assignOffsets(OutputSectionCommand *Cmd) {
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000493 if (Cmd->LMAExpr)
494 LMAOffset = Cmd->LMAExpr(Dot) - Dot;
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000495 std::vector<OutputSectionBase *> Sections =
496 findSections<ELFT>(Cmd->Name, *OutputSections);
Rafael Espindolad3190792016-09-16 15:10:23 +0000497 if (Sections.empty())
498 return;
499 switchTo(Sections[0]);
Rafael Espindolad3190792016-09-16 15:10:23 +0000500 // Find the last section output location. We will output orphan sections
501 // there so that end symbols point to the correct location.
502 auto E = std::find_if(Cmd->Commands.rbegin(), Cmd->Commands.rend(),
503 [](const std::unique_ptr<BaseCommand> &Cmd) {
504 return !isa<SymbolAssignment>(*Cmd);
505 })
506 .base();
507 for (auto I = Cmd->Commands.begin(); I != E; ++I)
508 process(**I);
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000509 for (OutputSectionBase *Base : Sections)
Rafael Espindolad3190792016-09-16 15:10:23 +0000510 switchTo(Base);
Rafael Espindola65499b92016-09-23 20:10:47 +0000511 flush();
George Rimarb31dd372016-09-19 13:27:31 +0000512 std::for_each(E, Cmd->Commands.end(),
513 [this](std::unique_ptr<BaseCommand> &B) { process(*B.get()); });
Rafael Espindolad3190792016-09-16 15:10:23 +0000514}
515
Rafael Espindola07fe6122016-11-14 14:23:35 +0000516template <class ELFT> void LinkerScript<ELFT>::removeEmptyCommands() {
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000517 // It is common practice to use very generic linker scripts. So for any
518 // given run some of the output sections in the script will be empty.
519 // We could create corresponding empty output sections, but that would
520 // clutter the output.
521 // We instead remove trivially empty sections. The bfd linker seems even
522 // more aggressive at removing them.
523 auto Pos = std::remove_if(
524 Opt.Commands.begin(), Opt.Commands.end(),
525 [&](const std::unique_ptr<BaseCommand> &Base) {
526 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
527 if (!Cmd)
528 return false;
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000529 std::vector<OutputSectionBase *> Secs =
530 findSections<ELFT>(Cmd->Name, *OutputSections);
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000531 if (!Secs.empty())
532 return false;
533 for (const std::unique_ptr<BaseCommand> &I : Cmd->Commands)
534 if (!isa<InputSectionDescription>(I.get()))
535 return false;
536 return true;
537 });
538 Opt.Commands.erase(Pos, Opt.Commands.end());
Rafael Espindola07fe6122016-11-14 14:23:35 +0000539}
540
541template <class ELFT> void LinkerScript<ELFT>::adjustSectionsBeforeSorting() {
542 removeEmptyCommands();
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000543
Rafael Espindola9546fff2016-09-22 14:40:50 +0000544 // If the output section contains only symbol assignments, create a
545 // corresponding output section. The bfd linker seems to only create them if
546 // '.' is assigned to, but creating these section should not have any bad
547 // consequeces and gives us a section to put the symbol in.
548 uintX_t Flags = SHF_ALLOC;
549 uint32_t Type = 0;
550 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
551 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
552 if (!Cmd)
553 continue;
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000554 std::vector<OutputSectionBase *> Secs =
555 findSections<ELFT>(Cmd->Name, *OutputSections);
Rafael Espindola9546fff2016-09-22 14:40:50 +0000556 if (!Secs.empty()) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000557 Flags = Secs[0]->Flags;
558 Type = Secs[0]->Type;
Rafael Espindola9546fff2016-09-22 14:40:50 +0000559 continue;
560 }
561
Rui Ueyama95642b92016-11-01 23:09:07 +0000562 auto *OutSec = make<OutputSection<ELFT>>(Cmd->Name, Type, Flags);
Rafael Espindola9546fff2016-09-22 14:40:50 +0000563 OutputSections->push_back(OutSec);
564 }
565}
566
Rafael Espindola15c57952016-09-22 18:05:49 +0000567// When placing orphan sections, we want to place them after symbol assignments
568// so that an orphan after
569// begin_foo = .;
570// foo : { *(foo) }
571// end_foo = .;
572// doesn't break the intended meaning of the begin/end symbols.
573// We don't want to go over sections since Writer<ELFT>::sortSections is the
574// one in charge of deciding the order of the sections.
575// We don't want to go over alignments, since doing so in
576// rx_sec : { *(rx_sec) }
577// . = ALIGN(0x1000);
578// /* The RW PT_LOAD starts here*/
579// rw_sec : { *(rw_sec) }
580// would mean that the RW PT_LOAD would become unaligned.
581static bool shouldSkip(const BaseCommand &Cmd) {
582 if (isa<OutputSectionCommand>(Cmd))
583 return false;
584 const auto *Assign = dyn_cast<SymbolAssignment>(&Cmd);
585 if (!Assign)
586 return true;
587 return Assign->Name != ".";
588}
589
Rafael Espindola337f9032016-11-14 14:13:32 +0000590// Orphan sections are sections present in the input files which are not
591// explicitly placed into the output file by the linker script. This just
592// places them in the order already decided in OutputSections.
Rafael Espindola6d91fce2016-09-29 18:50:34 +0000593template <class ELFT>
Rafael Espindola337f9032016-11-14 14:13:32 +0000594void LinkerScript<ELFT>::placeOrphanSections() {
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000595 // The OutputSections are already in the correct order.
596 // This loops creates or moves commands as needed so that they are in the
597 // correct order.
598 int CmdIndex = 0;
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000599 for (OutputSectionBase *Sec : *OutputSections) {
George Rimar652852c2016-04-16 10:10:32 +0000600 StringRef Name = Sec->getName();
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000601
602 // Find the last spot where we can insert a command and still get the
Rafael Espindola15c57952016-09-22 18:05:49 +0000603 // correct result.
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000604 auto CmdIter = Opt.Commands.begin() + CmdIndex;
605 auto E = Opt.Commands.end();
Rafael Espindola15c57952016-09-22 18:05:49 +0000606 while (CmdIter != E && shouldSkip(**CmdIter)) {
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000607 ++CmdIter;
608 ++CmdIndex;
609 }
610
611 auto Pos =
612 std::find_if(CmdIter, E, [&](const std::unique_ptr<BaseCommand> &Base) {
613 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
614 return Cmd && Cmd->Name == Name;
615 });
616 if (Pos == E) {
617 Opt.Commands.insert(CmdIter,
618 llvm::make_unique<OutputSectionCommand>(Name));
Rafael Espindola15c57952016-09-22 18:05:49 +0000619 ++CmdIndex;
620 continue;
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000621 }
Rafael Espindola15c57952016-09-22 18:05:49 +0000622
623 // Continue from where we found it.
624 CmdIndex = (Pos - Opt.Commands.begin()) + 1;
George Rimar652852c2016-04-16 10:10:32 +0000625 }
Rafael Espindola337f9032016-11-14 14:13:32 +0000626}
627
628template <class ELFT>
629void LinkerScript<ELFT>::assignAddresses(std::vector<PhdrEntry<ELFT>> &Phdrs) {
630 placeOrphanSections();
George Rimar652852c2016-04-16 10:10:32 +0000631
Rui Ueyama7c18c282016-04-18 21:00:40 +0000632 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rafael Espindolabe607332016-09-30 00:16:11 +0000633 Dot = 0;
George Rimar652852c2016-04-16 10:10:32 +0000634
George Rimar076fe152016-07-21 06:43:01 +0000635 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
636 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
Rui Ueyama8d083e62016-07-29 05:48:39 +0000637 if (Cmd->Name == ".") {
638 Dot = Cmd->Expression(Dot);
639 } else if (Cmd->Sym) {
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000640 assignSectionSymbol<ELFT>(
641 Cmd, CurOutSec ? CurOutSec : (*OutputSections)[0], Dot);
Rui Ueyama8d083e62016-07-29 05:48:39 +0000642 }
George Rimar652852c2016-04-16 10:10:32 +0000643 continue;
644 }
645
George Rimareefa7582016-08-04 09:29:31 +0000646 if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
647 Cmd->Expression(Dot);
648 continue;
649 }
650
George Rimar076fe152016-07-21 06:43:01 +0000651 auto *Cmd = cast<OutputSectionCommand>(Base.get());
George Rimar652852c2016-04-16 10:10:32 +0000652
Rafael Espindolad3190792016-09-16 15:10:23 +0000653 if (Cmd->AddrExpr)
654 Dot = Cmd->AddrExpr(Dot);
George Rimar58e5c4d2016-07-25 08:29:46 +0000655
Rafael Espindolad3190792016-09-16 15:10:23 +0000656 assignOffsets(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000657 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000658
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000659 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000660 for (OutputSectionBase *Sec : *OutputSections) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000661 if (Sec->Flags & SHF_ALLOC)
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000662 MinVA = std::min<uint64_t>(MinVA, Sec->Addr);
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000663 else
Rafael Espindola04a2e342016-11-09 01:42:41 +0000664 Sec->Addr = 0;
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000665 }
666
Rafael Espindola0d4b6d52016-09-22 16:47:21 +0000667 uintX_t HeaderSize = getHeaderSize();
Rafael Espindola6d91fce2016-09-29 18:50:34 +0000668 auto FirstPTLoad =
669 std::find_if(Phdrs.begin(), Phdrs.end(), [](const PhdrEntry<ELFT> &E) {
670 return E.H.p_type == PT_LOAD;
671 });
Eugene Leviantdb35fdf2016-10-20 09:39:09 +0000672
Rafael Espindola6d91fce2016-09-29 18:50:34 +0000673 if (HeaderSize <= MinVA && FirstPTLoad != Phdrs.end()) {
George Rimar59d9b4b2016-11-14 10:04:45 +0000674 // If linker script specifies program headers and first PT_LOAD doesn't
Eugene Leviantdb35fdf2016-10-20 09:39:09 +0000675 // have both PHDRS and FILEHDR attributes then do nothing
676 if (!Opt.PhdrsCommands.empty()) {
677 size_t SegNum = std::distance(Phdrs.begin(), FirstPTLoad);
678 if (!Opt.PhdrsCommands[SegNum].HasPhdrs ||
679 !Opt.PhdrsCommands[SegNum].HasFilehdr)
680 return;
681 }
Rafael Espindola6d91fce2016-09-29 18:50:34 +0000682 // ELF and Program headers need to be right before the first section in
683 // memory. Set their addresses accordingly.
684 MinVA = alignDown(MinVA - HeaderSize, Target->PageSize);
Rafael Espindola04a2e342016-11-09 01:42:41 +0000685 Out<ELFT>::ElfHeader->Addr = MinVA;
686 Out<ELFT>::ProgramHeaders->Addr = Out<ELFT>::ElfHeader->Size + MinVA;
Rafael Espindola6d91fce2016-09-29 18:50:34 +0000687 FirstPTLoad->First = Out<ELFT>::ElfHeader;
688 if (!FirstPTLoad->Last)
689 FirstPTLoad->Last = Out<ELFT>::ProgramHeaders;
Eugene Leviantcd8eaf82016-10-10 15:09:44 +0000690 } else if (!FirstPTLoad->First) {
Rui Ueyamab224c0482016-10-10 18:10:01 +0000691 // Sometimes the very first PT_LOAD segment can be empty.
Eugene Leviantcd8eaf82016-10-10 15:09:44 +0000692 // This happens if (all conditions met):
693 // - Linker script is used
694 // - First section in ELF image is not RO
695 // - Not enough space for program headers.
696 // The code below removes empty PT_LOAD segment and updates
697 // program headers size.
698 Phdrs.erase(FirstPTLoad);
Rafael Espindola04a2e342016-11-09 01:42:41 +0000699 Out<ELFT>::ProgramHeaders->Size =
700 sizeof(typename ELFT::Phdr) * Phdrs.size();
Rafael Espindola6d91fce2016-09-29 18:50:34 +0000701 }
George Rimar652852c2016-04-16 10:10:32 +0000702}
703
Rui Ueyama464daad2016-08-22 04:55:20 +0000704// Creates program headers as instructed by PHDRS linker script command.
Rui Ueyama07320e42016-04-20 20:13:41 +0000705template <class ELFT>
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000706std::vector<PhdrEntry<ELFT>> LinkerScript<ELFT>::createPhdrs() {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000707 std::vector<PhdrEntry<ELFT>> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000708
Rui Ueyama464daad2016-08-22 04:55:20 +0000709 // Process PHDRS and FILEHDR keywords because they are not
710 // real output sections and cannot be added in the following loop.
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000711 std::vector<size_t> DefPhdrIds;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000712 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000713 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
714 PhdrEntry<ELFT> &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000715
716 if (Cmd.HasFilehdr)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000717 Phdr.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000718 if (Cmd.HasPhdrs)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000719 Phdr.add(Out<ELFT>::ProgramHeaders);
Eugene Leviant56b21c82016-09-09 09:46:16 +0000720
721 if (Cmd.LMAExpr) {
722 Phdr.H.p_paddr = Cmd.LMAExpr(0);
723 Phdr.HasLMA = true;
724 }
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000725
726 // If output section command doesn't specify any segments,
727 // and we haven't previously assigned any section to segment,
728 // then we simply assign section to the very first load segment.
729 // Below is an example of such linker script:
730 // PHDRS { seg PT_LOAD; }
731 // SECTIONS { .aaa : { *(.aaa) } }
732 if (DefPhdrIds.empty() && Phdr.H.p_type == PT_LOAD)
733 DefPhdrIds.push_back(Ret.size() - 1);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000734 }
735
Rui Ueyama464daad2016-08-22 04:55:20 +0000736 // Add output sections to program headers.
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000737 for (OutputSectionBase *Sec : *OutputSections) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000738 if (!(Sec->Flags & SHF_ALLOC))
Eugene Leviantbbe38602016-07-19 09:25:43 +0000739 break;
740
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000741 std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName());
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000742 if (PhdrIds.empty())
743 PhdrIds = std::move(DefPhdrIds);
744
745 // Assign headers specified by linker script
746 for (size_t Id : PhdrIds) {
747 Ret[Id].add(Sec);
748 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
749 Ret[Id].H.p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000750 }
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000751 DefPhdrIds = std::move(PhdrIds);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000752 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000753 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000754}
755
Eugene Leviantf9bc3bd2016-08-16 06:40:58 +0000756template <class ELFT> bool LinkerScript<ELFT>::ignoreInterpSection() {
757 // Ignore .interp section in case we have PHDRS specification
758 // and PT_INTERP isn't listed.
759 return !Opt.PhdrsCommands.empty() &&
760 llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
761 return Cmd.Type == PT_INTERP;
762 }) == Opt.PhdrsCommands.end();
763}
764
Eugene Leviantbbe38602016-07-19 09:25:43 +0000765template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000766ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000767 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
768 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
769 if (Cmd->Name == Name)
770 return Cmd->Filler;
771 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000772}
773
George Rimare38cbab2016-09-26 19:22:50 +0000774template <class ELFT>
775static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) {
776 const endianness E = ELFT::TargetEndianness;
777
778 switch (Size) {
779 case 1:
780 *Buf = (uint8_t)Data;
781 break;
782 case 2:
783 write16<E>(Buf, Data);
784 break;
785 case 4:
786 write32<E>(Buf, Data);
787 break;
788 case 8:
789 write64<E>(Buf, Data);
790 break;
791 default:
792 llvm_unreachable("unsupported Size argument");
793 }
794}
795
796template <class ELFT>
797void LinkerScript<ELFT>::writeDataBytes(StringRef Name, uint8_t *Buf) {
798 int I = getSectionIndex(Name);
799 if (I == INT_MAX)
800 return;
801
802 OutputSectionCommand *Cmd =
803 dyn_cast<OutputSectionCommand>(Opt.Commands[I].get());
804 for (const std::unique_ptr<BaseCommand> &Base2 : Cmd->Commands)
805 if (auto *DataCmd = dyn_cast<BytesDataCommand>(Base2.get()))
806 writeInt<ELFT>(&Buf[DataCmd->Offset], DataCmd->Data, DataCmd->Size);
807}
808
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000809template <class ELFT> bool LinkerScript<ELFT>::hasLMA(StringRef Name) {
George Rimar8ceadb32016-08-17 07:44:19 +0000810 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
811 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000812 if (Cmd->LMAExpr && Cmd->Name == Name)
813 return true;
814 return false;
George Rimar8ceadb32016-08-17 07:44:19 +0000815}
816
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000817// Returns the index of the given section name in linker script
818// SECTIONS commands. Sections are laid out as the same order as they
819// were in the script. If a given name did not appear in the script,
820// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000821template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000822 int I = 0;
823 for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
824 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
825 if (Cmd->Name == Name)
826 return I;
827 ++I;
828 }
829 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000830}
831
Eugene Leviantbbe38602016-07-19 09:25:43 +0000832template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
833 return !Opt.PhdrsCommands.empty();
834}
835
George Rimar9e694502016-07-29 16:18:47 +0000836template <class ELFT>
George Rimar884e7862016-09-08 08:19:13 +0000837uint64_t LinkerScript<ELFT>::getOutputSectionAddress(StringRef Name) {
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000838 for (OutputSectionBase *Sec : *OutputSections)
George Rimar96659df2016-08-30 09:54:01 +0000839 if (Sec->getName() == Name)
Rafael Espindola04a2e342016-11-09 01:42:41 +0000840 return Sec->Addr;
George Rimar96659df2016-08-30 09:54:01 +0000841 error("undefined section " + Name);
842 return 0;
843}
844
845template <class ELFT>
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000846uint64_t LinkerScript<ELFT>::getOutputSectionLMA(StringRef Name) {
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000847 for (OutputSectionBase *Sec : *OutputSections)
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000848 if (Sec->getName() == Name)
849 return Sec->getLMA();
850 error("undefined section " + Name);
851 return 0;
852}
853
854template <class ELFT>
George Rimar884e7862016-09-08 08:19:13 +0000855uint64_t LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000856 for (OutputSectionBase *Sec : *OutputSections)
George Rimar9e694502016-07-29 16:18:47 +0000857 if (Sec->getName() == Name)
Rafael Espindola04a2e342016-11-09 01:42:41 +0000858 return Sec->Size;
George Rimar9e694502016-07-29 16:18:47 +0000859 error("undefined section " + Name);
860 return 0;
861}
862
Eugene Leviant36fac7f2016-09-08 09:08:30 +0000863template <class ELFT>
864uint64_t LinkerScript<ELFT>::getOutputSectionAlign(StringRef Name) {
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000865 for (OutputSectionBase *Sec : *OutputSections)
Eugene Leviant36fac7f2016-09-08 09:08:30 +0000866 if (Sec->getName() == Name)
Rafael Espindola04a2e342016-11-09 01:42:41 +0000867 return Sec->Addralign;
Eugene Leviant36fac7f2016-09-08 09:08:30 +0000868 error("undefined section " + Name);
869 return 0;
870}
871
George Rimar884e7862016-09-08 08:19:13 +0000872template <class ELFT> uint64_t LinkerScript<ELFT>::getHeaderSize() {
Rafael Espindola0d4b6d52016-09-22 16:47:21 +0000873 return elf::getHeaderSize<ELFT>();
George Rimare32a3592016-08-10 07:59:34 +0000874}
875
George Rimar884e7862016-09-08 08:19:13 +0000876template <class ELFT> uint64_t LinkerScript<ELFT>::getSymbolValue(StringRef S) {
877 if (SymbolBody *B = Symtab<ELFT>::X->find(S))
878 return B->getVA<ELFT>();
879 error("symbol not found: " + S);
880 return 0;
881}
882
George Rimarf34f45f2016-09-23 13:17:23 +0000883template <class ELFT> bool LinkerScript<ELFT>::isDefined(StringRef S) {
884 return Symtab<ELFT>::X->find(S) != nullptr;
885}
886
Rafael Espindola2f831dc2016-10-31 19:56:37 +0000887template <class ELFT> bool LinkerScript<ELFT>::isAbsolute(StringRef S) {
888 SymbolBody *Sym = Symtab<ELFT>::X->find(S);
889 auto *DR = dyn_cast_or_null<DefinedRegular<ELFT>>(Sym);
890 return DR && !DR->Section;
891}
892
Eugene Leviantbbe38602016-07-19 09:25:43 +0000893// Returns indices of ELF headers containing specific section, identified
894// by Name. Each index is a zero based number of ELF header listed within
895// PHDRS {} script block.
896template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000897std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000898 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
899 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000900 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000901 continue;
902
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000903 std::vector<size_t> Ret;
904 for (StringRef PhdrName : Cmd->Phdrs)
905 Ret.push_back(getPhdrIndex(PhdrName));
906 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000907 }
George Rimar31d842f2016-07-20 16:43:03 +0000908 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000909}
910
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000911template <class ELFT>
912size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
913 size_t I = 0;
914 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
915 if (Cmd.Name == PhdrName)
916 return I;
917 ++I;
918 }
919 error("section header '" + PhdrName + "' is not listed in PHDRS");
920 return 0;
921}
922
Rui Ueyama07320e42016-04-20 20:13:41 +0000923class elf::ScriptParser : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000924 typedef void (ScriptParser::*Handler)();
925
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000926public:
Rui Ueyama07320e42016-04-20 20:13:41 +0000927 ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
George Rimarf23b2322016-02-19 10:45:45 +0000928
George Rimar20b65982016-08-31 09:08:26 +0000929 void readLinkerScript();
930 void readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000931
932private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000933 void addFile(StringRef Path);
934
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000935 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000936 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000937 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000938 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000939 void readInclude();
Rui Ueyamaee592822015-10-07 00:25:09 +0000940 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000941 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000942 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000943 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000944 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000945 void readSections();
Rui Ueyama95769b42016-08-31 20:03:54 +0000946 void readVersion();
947 void readVersionScriptCommand();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000948
Rui Ueyama113cdec2016-07-24 23:05:57 +0000949 SymbolAssignment *readAssignment(StringRef Name);
George Rimare38cbab2016-09-26 19:22:50 +0000950 BytesDataCommand *readBytesDataCommand(StringRef Tok);
George Rimarff1f29e2016-09-06 13:51:57 +0000951 std::vector<uint8_t> readFill();
Rui Ueyama10416562016-08-04 02:03:27 +0000952 OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
George Rimarff1f29e2016-09-06 13:51:57 +0000953 std::vector<uint8_t> readOutputSectionFiller(StringRef Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000954 std::vector<StringRef> readOutputSectionPhdrs();
George Rimara2496cb2016-08-30 09:46:59 +0000955 InputSectionDescription *readInputSectionDescription(StringRef Tok);
Eugene Leviantdb688452016-11-03 10:54:58 +0000956 StringMatcher readFilePatterns();
George Rimar07171f22016-09-21 15:56:44 +0000957 std::vector<SectionPattern> readInputSectionsList();
George Rimara2496cb2016-08-30 09:46:59 +0000958 InputSectionDescription *readInputSectionRules(StringRef FilePattern);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000959 unsigned readPhdrType();
George Rimarbe394db2016-09-16 20:21:55 +0000960 SortSectionPolicy readSortKind();
Petr Hoseka35e39c2016-08-16 01:11:16 +0000961 SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
Rafael Espindolac96da112016-11-01 11:30:45 +0000962 SymbolAssignment *readProvideOrAssignment(StringRef Tok);
George Rimar03fc0102016-07-28 07:18:23 +0000963 void readSort();
George Rimareefa7582016-08-04 09:29:31 +0000964 Expr readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +0000965
966 Expr readExpr();
967 Expr readExpr1(Expr Lhs, int MinPrec);
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000968 StringRef readParenLiteral();
Rui Ueyama708019c2016-07-24 18:19:40 +0000969 Expr readPrimary();
970 Expr readTernary(Expr Cond);
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +0000971 Expr readParenExpr();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000972
George Rimar20b65982016-08-31 09:08:26 +0000973 // For parsing version script.
974 void readExtern(std::vector<SymbolVersion> *Globals);
Rui Ueyama95769b42016-08-31 20:03:54 +0000975 void readVersionDeclaration(StringRef VerStr);
George Rimar20b65982016-08-31 09:08:26 +0000976 void readGlobal(StringRef VerStr);
George Rimarbb6c01e2016-11-12 07:04:15 +0000977 void readLocal(StringRef VerStr);
George Rimar20b65982016-08-31 09:08:26 +0000978
Rui Ueyama07320e42016-04-20 20:13:41 +0000979 ScriptConfiguration &Opt = *ScriptConfig;
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000980 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000981};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000982
George Rimar20b65982016-08-31 09:08:26 +0000983void ScriptParser::readVersionScript() {
Rui Ueyama95769b42016-08-31 20:03:54 +0000984 readVersionScriptCommand();
985 if (!atEOF())
986 setError("EOF expected, but got " + next());
987}
988
989void ScriptParser::readVersionScriptCommand() {
Rui Ueyama83043f22016-10-17 16:01:53 +0000990 if (consume("{")) {
Rui Ueyama95769b42016-08-31 20:03:54 +0000991 readVersionDeclaration("");
George Rimar20b65982016-08-31 09:08:26 +0000992 return;
993 }
994
Rui Ueyama95769b42016-08-31 20:03:54 +0000995 while (!atEOF() && !Error && peek() != "}") {
George Rimar20b65982016-08-31 09:08:26 +0000996 StringRef VerStr = next();
997 if (VerStr == "{") {
Rui Ueyama95769b42016-08-31 20:03:54 +0000998 setError("anonymous version definition is used in "
999 "combination with other version definitions");
George Rimar20b65982016-08-31 09:08:26 +00001000 return;
1001 }
1002 expect("{");
Rui Ueyama95769b42016-08-31 20:03:54 +00001003 readVersionDeclaration(VerStr);
George Rimar20b65982016-08-31 09:08:26 +00001004 }
1005}
1006
Rui Ueyama95769b42016-08-31 20:03:54 +00001007void ScriptParser::readVersion() {
1008 expect("{");
1009 readVersionScriptCommand();
1010 expect("}");
1011}
1012
George Rimar20b65982016-08-31 09:08:26 +00001013void ScriptParser::readLinkerScript() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001014 while (!atEOF()) {
1015 StringRef Tok = next();
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001016 if (Tok == ";")
1017 continue;
1018
Eugene Leviant20d03192016-09-16 15:30:47 +00001019 if (Tok == "ASSERT") {
1020 Opt.Commands.emplace_back(new AssertCommand(readAssert()));
1021 } else if (Tok == "ENTRY") {
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001022 readEntry();
1023 } else if (Tok == "EXTERN") {
1024 readExtern();
1025 } else if (Tok == "GROUP" || Tok == "INPUT") {
1026 readGroup();
1027 } else if (Tok == "INCLUDE") {
1028 readInclude();
1029 } else if (Tok == "OUTPUT") {
1030 readOutput();
1031 } else if (Tok == "OUTPUT_ARCH") {
1032 readOutputArch();
1033 } else if (Tok == "OUTPUT_FORMAT") {
1034 readOutputFormat();
1035 } else if (Tok == "PHDRS") {
1036 readPhdrs();
1037 } else if (Tok == "SEARCH_DIR") {
1038 readSearchDir();
1039 } else if (Tok == "SECTIONS") {
1040 readSections();
1041 } else if (Tok == "VERSION") {
1042 readVersion();
Rafael Espindolac96da112016-11-01 11:30:45 +00001043 } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok)) {
Eugene Leviant20d03192016-09-16 15:30:47 +00001044 Opt.Commands.emplace_back(Cmd);
Petr Hoseke5d3ca52016-08-31 15:31:17 +00001045 } else {
George Rimar57610422016-03-11 14:43:02 +00001046 setError("unknown directive: " + Tok);
Petr Hoseke5d3ca52016-08-31 15:31:17 +00001047 }
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001048 }
1049}
1050
Rui Ueyama717677a2016-02-11 21:17:59 +00001051void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001052 if (IsUnderSysroot && S.startswith("/")) {
Justin Bogner5af16872016-10-17 06:08:48 +00001053 SmallString<128> PathData;
1054 StringRef Path = (Config->Sysroot + S).toStringRef(PathData);
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001055 if (sys::fs::exists(Path)) {
Justin Bogner5af16872016-10-17 06:08:48 +00001056 Driver->addFile(Saver.save(Path));
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001057 return;
1058 }
1059 }
1060
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +00001061 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +00001062 Driver->addFile(S);
1063 } else if (S.startswith("=")) {
1064 if (Config->Sysroot.empty())
1065 Driver->addFile(S.substr(1));
1066 else
1067 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
1068 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +00001069 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +00001070 } else if (sys::fs::exists(S)) {
1071 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +00001072 } else {
1073 std::string Path = findFromSearchPaths(S);
1074 if (Path.empty())
George Rimar777f9632016-03-12 08:31:34 +00001075 setError("unable to find " + S);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001076 else
1077 Driver->addFile(Saver.save(Path));
Rui Ueyama52a15092015-10-11 03:28:42 +00001078 }
1079}
1080
Rui Ueyama717677a2016-02-11 21:17:59 +00001081void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001082 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +00001083 bool Orig = Config->AsNeeded;
1084 Config->AsNeeded = true;
Rui Ueyama83043f22016-10-17 16:01:53 +00001085 while (!Error && !consume(")"))
George Rimarcd574a52016-09-09 14:35:36 +00001086 addFile(unquote(next()));
Rui Ueyama35da9b62015-10-11 20:59:12 +00001087 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001088}
1089
Rui Ueyama717677a2016-02-11 21:17:59 +00001090void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +00001091 // -e <symbol> takes predecence over ENTRY(<symbol>).
1092 expect("(");
1093 StringRef Tok = next();
1094 if (Config->Entry.empty())
1095 Config->Entry = Tok;
1096 expect(")");
1097}
1098
Rui Ueyama717677a2016-02-11 21:17:59 +00001099void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +00001100 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001101 while (!Error && !consume(")"))
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001102 Config->Undefined.push_back(next());
George Rimar83f406c2015-10-19 17:35:12 +00001103}
1104
Rui Ueyama717677a2016-02-11 21:17:59 +00001105void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001106 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001107 while (!Error && !consume(")")) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001108 StringRef Tok = next();
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001109 if (Tok == "AS_NEEDED")
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001110 readAsNeeded();
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001111 else
George Rimarcd574a52016-09-09 14:35:36 +00001112 addFile(unquote(Tok));
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001113 }
1114}
1115
Rui Ueyama717677a2016-02-11 21:17:59 +00001116void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001117 StringRef Tok = next();
George Rimarcd574a52016-09-09 14:35:36 +00001118 auto MBOrErr = MemoryBuffer::getFile(unquote(Tok));
Rui Ueyama025d59b2016-02-02 20:27:59 +00001119 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +00001120 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001121 return;
1122 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001123 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Rui Ueyamaa47ee682015-10-11 01:53:04 +00001124 StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
1125 std::vector<StringRef> V = tokenize(S);
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001126 Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001127}
1128
Rui Ueyama717677a2016-02-11 21:17:59 +00001129void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +00001130 // -o <file> takes predecence over OUTPUT(<file>).
1131 expect("(");
1132 StringRef Tok = next();
1133 if (Config->OutputFile.empty())
George Rimarcd574a52016-09-09 14:35:36 +00001134 Config->OutputFile = unquote(Tok);
Rui Ueyamaee592822015-10-07 00:25:09 +00001135 expect(")");
1136}
1137
Rui Ueyama717677a2016-02-11 21:17:59 +00001138void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +00001139 // Error checking only for now.
1140 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001141 skip();
Davide Italiano9159ce92015-10-12 21:50:08 +00001142 expect(")");
1143}
1144
Rui Ueyama717677a2016-02-11 21:17:59 +00001145void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001146 // Error checking only for now.
1147 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001148 skip();
Davide Italiano6836c612015-10-12 21:08:41 +00001149 StringRef Tok = next();
1150 if (Tok == ")")
George Rimar6c55f0e2016-09-08 08:20:30 +00001151 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +00001152 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +00001153 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001154 return;
1155 }
Justin Bogner5424e7c2016-10-17 06:21:13 +00001156 skip();
Davide Italiano6836c612015-10-12 21:08:41 +00001157 expect(",");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001158 skip();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001159 expect(")");
1160}
1161
Eugene Leviantbbe38602016-07-19 09:25:43 +00001162void ScriptParser::readPhdrs() {
1163 expect("{");
Rui Ueyama83043f22016-10-17 16:01:53 +00001164 while (!Error && !consume("}")) {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001165 StringRef Tok = next();
Eugene Leviant56b21c82016-09-09 09:46:16 +00001166 Opt.PhdrsCommands.push_back(
1167 {Tok, PT_NULL, false, false, UINT_MAX, nullptr});
Eugene Leviantbbe38602016-07-19 09:25:43 +00001168 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
1169
1170 PhdrCmd.Type = readPhdrType();
1171 do {
1172 Tok = next();
1173 if (Tok == ";")
1174 break;
1175 if (Tok == "FILEHDR")
1176 PhdrCmd.HasFilehdr = true;
1177 else if (Tok == "PHDRS")
1178 PhdrCmd.HasPhdrs = true;
Eugene Leviant56b21c82016-09-09 09:46:16 +00001179 else if (Tok == "AT")
1180 PhdrCmd.LMAExpr = readParenExpr();
Eugene Leviant865bf862016-07-21 10:43:25 +00001181 else if (Tok == "FLAGS") {
1182 expect("(");
Rafael Espindolaeb685cd2016-08-02 22:14:57 +00001183 // Passing 0 for the value of dot is a bit of a hack. It means that
1184 // we accept expressions like ".|1".
1185 PhdrCmd.Flags = readExpr()(0);
Eugene Leviant865bf862016-07-21 10:43:25 +00001186 expect(")");
1187 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +00001188 setError("unexpected header attribute: " + Tok);
1189 } while (!Error);
1190 }
1191}
1192
Rui Ueyama717677a2016-02-11 21:17:59 +00001193void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +00001194 expect("(");
Rui Ueyama86c5fb82016-09-08 23:26:54 +00001195 StringRef Tok = next();
Rui Ueyama6c7ad132016-09-02 19:20:33 +00001196 if (!Config->Nostdlib)
George Rimarcd574a52016-09-09 14:35:36 +00001197 Config->SearchPaths.push_back(unquote(Tok));
Davide Italiano68a39a62015-10-08 17:51:41 +00001198 expect(")");
1199}
1200
Rui Ueyama717677a2016-02-11 21:17:59 +00001201void ScriptParser::readSections() {
Eugene Leviante05336ff2016-09-14 08:32:36 +00001202 Opt.HasSections = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001203 expect("{");
Rui Ueyama83043f22016-10-17 16:01:53 +00001204 while (!Error && !consume("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +00001205 StringRef Tok = next();
Rafael Espindolac96da112016-11-01 11:30:45 +00001206 BaseCommand *Cmd = readProvideOrAssignment(Tok);
Eugene Leviantceabe802016-08-11 07:56:43 +00001207 if (!Cmd) {
1208 if (Tok == "ASSERT")
1209 Cmd = new AssertCommand(readAssert());
1210 else
1211 Cmd = readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +00001212 }
Rui Ueyama10416562016-08-04 02:03:27 +00001213 Opt.Commands.emplace_back(Cmd);
George Rimar652852c2016-04-16 10:10:32 +00001214 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001215}
1216
Rui Ueyama708019c2016-07-24 18:19:40 +00001217static int precedence(StringRef Op) {
1218 return StringSwitch<int>(Op)
Rui Ueyama0120e3f2016-09-23 18:06:51 +00001219 .Cases("*", "/", 5)
1220 .Cases("+", "-", 4)
1221 .Cases("<<", ">>", 3)
Rui Ueyama9c4ac5f2016-09-23 22:22:34 +00001222 .Cases("<", "<=", ">", ">=", "==", "!=", 2)
Rui Ueyama0120e3f2016-09-23 18:06:51 +00001223 .Cases("&", "|", 1)
Rui Ueyama708019c2016-07-24 18:19:40 +00001224 .Default(-1);
1225}
1226
Eugene Leviantdb688452016-11-03 10:54:58 +00001227StringMatcher ScriptParser::readFilePatterns() {
Rui Ueyama10416562016-08-04 02:03:27 +00001228 std::vector<StringRef> V;
Rui Ueyama83043f22016-10-17 16:01:53 +00001229 while (!Error && !consume(")"))
Rui Ueyama10416562016-08-04 02:03:27 +00001230 V.push_back(next());
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001231 return StringMatcher(V);
George Rimar0702c4e2016-07-29 15:32:46 +00001232}
1233
George Rimarbe394db2016-09-16 20:21:55 +00001234SortSectionPolicy ScriptParser::readSortKind() {
Rui Ueyama83043f22016-10-17 16:01:53 +00001235 if (consume("SORT") || consume("SORT_BY_NAME"))
George Rimarbe394db2016-09-16 20:21:55 +00001236 return SortSectionPolicy::Name;
Rui Ueyama83043f22016-10-17 16:01:53 +00001237 if (consume("SORT_BY_ALIGNMENT"))
George Rimarbe394db2016-09-16 20:21:55 +00001238 return SortSectionPolicy::Alignment;
Rui Ueyama83043f22016-10-17 16:01:53 +00001239 if (consume("SORT_BY_INIT_PRIORITY"))
George Rimarbe394db2016-09-16 20:21:55 +00001240 return SortSectionPolicy::Priority;
Rui Ueyama83043f22016-10-17 16:01:53 +00001241 if (consume("SORT_NONE"))
Rui Ueyamab2a0abd2016-09-16 21:14:55 +00001242 return SortSectionPolicy::None;
1243 return SortSectionPolicy::Default;
George Rimarbe394db2016-09-16 20:21:55 +00001244}
1245
George Rimar395281c2016-09-16 17:42:10 +00001246// Method reads a list of sequence of excluded files and section globs given in
1247// a following form: ((EXCLUDE_FILE(file_pattern+))? section_pattern+)+
1248// Example: *(.foo.1 EXCLUDE_FILE (*a.o) .foo.2 EXCLUDE_FILE (*b.o) .foo.3)
George Rimaraf03be12016-09-17 19:17:25 +00001249// The semantics of that is next:
1250// * Include .foo.1 from every file.
1251// * Include .foo.2 from every file but a.o
1252// * Include .foo.3 from every file but b.o
George Rimar07171f22016-09-21 15:56:44 +00001253std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
1254 std::vector<SectionPattern> Ret;
George Rimar601e9892016-09-21 08:53:21 +00001255 while (!Error && peek() != ")") {
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001256 StringMatcher ExcludeFilePat;
Rui Ueyama83043f22016-10-17 16:01:53 +00001257 if (consume("EXCLUDE_FILE")) {
George Rimar395281c2016-09-16 17:42:10 +00001258 expect("(");
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001259 ExcludeFilePat = readFilePatterns();
George Rimar395281c2016-09-16 17:42:10 +00001260 }
1261
George Rimar601e9892016-09-21 08:53:21 +00001262 std::vector<StringRef> V;
1263 while (!Error && peek() != ")" && peek() != "EXCLUDE_FILE")
1264 V.push_back(next());
1265
1266 if (!V.empty())
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001267 Ret.push_back({std::move(ExcludeFilePat), StringMatcher(V)});
George Rimar601e9892016-09-21 08:53:21 +00001268 else
1269 setError("section pattern is expected");
George Rimar395281c2016-09-16 17:42:10 +00001270 }
George Rimar07171f22016-09-21 15:56:44 +00001271 return Ret;
George Rimar395281c2016-09-16 17:42:10 +00001272}
1273
George Rimar07171f22016-09-21 15:56:44 +00001274// Section pattern grammar can have complex expressions, for example:
1275// *(SORT(.foo.* EXCLUDE_FILE (*file1.o) .bar.*) .bar.* SORT(.zed.*))
1276// Generally is a sequence of globs and excludes that may be wrapped in a SORT()
1277// commands, like: SORT(glob0) glob1 glob2 SORT(glob4)
1278// This methods handles wrapping sequences of excluded files and section globs
1279// into SORT() if that needed and reads them all.
George Rimara2496cb2016-08-30 09:46:59 +00001280InputSectionDescription *
1281ScriptParser::readInputSectionRules(StringRef FilePattern) {
George Rimarc91930a2016-09-02 21:17:20 +00001282 auto *Cmd = new InputSectionDescription(FilePattern);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001283 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001284 while (!HasError && !consume(")")) {
George Rimar07171f22016-09-21 15:56:44 +00001285 SortSectionPolicy Outer = readSortKind();
1286 SortSectionPolicy Inner = SortSectionPolicy::Default;
1287 std::vector<SectionPattern> V;
1288 if (Outer != SortSectionPolicy::Default) {
George Rimar350ece42016-08-03 08:35:59 +00001289 expect("(");
George Rimar07171f22016-09-21 15:56:44 +00001290 Inner = readSortKind();
1291 if (Inner != SortSectionPolicy::Default) {
1292 expect("(");
1293 V = readInputSectionsList();
1294 expect(")");
1295 } else {
1296 V = readInputSectionsList();
1297 }
George Rimar350ece42016-08-03 08:35:59 +00001298 expect(")");
1299 } else {
George Rimar07171f22016-09-21 15:56:44 +00001300 V = readInputSectionsList();
George Rimar350ece42016-08-03 08:35:59 +00001301 }
George Rimar0702c4e2016-07-29 15:32:46 +00001302
George Rimar07171f22016-09-21 15:56:44 +00001303 for (SectionPattern &Pat : V) {
1304 Pat.SortInner = Inner;
1305 Pat.SortOuter = Outer;
1306 }
1307
1308 std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns));
1309 }
Rui Ueyama10416562016-08-04 02:03:27 +00001310 return Cmd;
Davide Italianoe7282792016-07-27 01:44:01 +00001311}
1312
George Rimara2496cb2016-08-30 09:46:59 +00001313InputSectionDescription *
1314ScriptParser::readInputSectionDescription(StringRef Tok) {
George Rimar06598002016-07-28 21:51:30 +00001315 // Input section wildcard can be surrounded by KEEP.
1316 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
George Rimara2496cb2016-08-30 09:46:59 +00001317 if (Tok == "KEEP") {
George Rimar06598002016-07-28 21:51:30 +00001318 expect("(");
George Rimara2496cb2016-08-30 09:46:59 +00001319 StringRef FilePattern = next();
1320 InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
George Rimar06598002016-07-28 21:51:30 +00001321 expect(")");
Eugene Leviantcf43f172016-10-05 09:36:59 +00001322 Opt.KeptSections.push_back(Cmd);
Rui Ueyama10416562016-08-04 02:03:27 +00001323 return Cmd;
George Rimar06598002016-07-28 21:51:30 +00001324 }
George Rimara2496cb2016-08-30 09:46:59 +00001325 return readInputSectionRules(Tok);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001326}
1327
George Rimar03fc0102016-07-28 07:18:23 +00001328void ScriptParser::readSort() {
1329 expect("(");
1330 expect("CONSTRUCTORS");
1331 expect(")");
1332}
1333
George Rimareefa7582016-08-04 09:29:31 +00001334Expr ScriptParser::readAssert() {
1335 expect("(");
1336 Expr E = readExpr();
1337 expect(",");
George Rimarcd574a52016-09-09 14:35:36 +00001338 StringRef Msg = unquote(next());
George Rimareefa7582016-08-04 09:29:31 +00001339 expect(")");
1340 return [=](uint64_t Dot) {
1341 uint64_t V = E(Dot);
1342 if (!V)
1343 error(Msg);
1344 return V;
1345 };
1346}
1347
Rui Ueyama25150e82016-09-06 17:46:43 +00001348// Reads a FILL(expr) command. We handle the FILL command as an
1349// alias for =fillexp section attribute, which is different from
1350// what GNU linkers do.
1351// https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
George Rimarff1f29e2016-09-06 13:51:57 +00001352std::vector<uint8_t> ScriptParser::readFill() {
1353 expect("(");
1354 std::vector<uint8_t> V = readOutputSectionFiller(next());
1355 expect(")");
1356 expect(";");
1357 return V;
1358}
1359
Rui Ueyama10416562016-08-04 02:03:27 +00001360OutputSectionCommand *
1361ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +00001362 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
George Rimar58e5c4d2016-07-25 08:29:46 +00001363
1364 // Read an address expression.
1365 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
1366 if (peek() != ":")
1367 Cmd->AddrExpr = readExpr();
1368
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001369 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +00001370
Rui Ueyama83043f22016-10-17 16:01:53 +00001371 if (consume("AT"))
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001372 Cmd->LMAExpr = readParenExpr();
Rui Ueyama83043f22016-10-17 16:01:53 +00001373 if (consume("ALIGN"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001374 Cmd->AlignExpr = readParenExpr();
Rui Ueyama83043f22016-10-17 16:01:53 +00001375 if (consume("SUBALIGN"))
George Rimardb24d9c2016-08-19 15:18:23 +00001376 Cmd->SubalignExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001377
Davide Italiano246f6812016-07-22 03:36:24 +00001378 // Parse constraints.
Rui Ueyama83043f22016-10-17 16:01:53 +00001379 if (consume("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001380 Cmd->Constraint = ConstraintKind::ReadOnly;
Rui Ueyama83043f22016-10-17 16:01:53 +00001381 if (consume("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001382 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001383 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001384
Rui Ueyama83043f22016-10-17 16:01:53 +00001385 while (!Error && !consume("}")) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001386 StringRef Tok = next();
Rafael Espindolac96da112016-11-01 11:30:45 +00001387 if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok))
Eugene Leviantceabe802016-08-11 07:56:43 +00001388 Cmd->Commands.emplace_back(Assignment);
George Rimare38cbab2016-09-26 19:22:50 +00001389 else if (BytesDataCommand *Data = readBytesDataCommand(Tok))
1390 Cmd->Commands.emplace_back(Data);
George Rimarff1f29e2016-09-06 13:51:57 +00001391 else if (Tok == "FILL")
1392 Cmd->Filler = readFill();
Eugene Leviantceabe802016-08-11 07:56:43 +00001393 else if (Tok == "SORT")
George Rimar03fc0102016-07-28 07:18:23 +00001394 readSort();
George Rimara2496cb2016-08-30 09:46:59 +00001395 else if (peek() == "(")
1396 Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
Eugene Leviantceabe802016-08-11 07:56:43 +00001397 else
1398 setError("unknown command " + Tok);
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001399 }
George Rimar076fe152016-07-21 06:43:01 +00001400 Cmd->Phdrs = readOutputSectionPhdrs();
George Rimar4ebc5622016-09-23 13:29:20 +00001401
Rui Ueyama83043f22016-10-17 16:01:53 +00001402 if (consume("="))
George Rimar4ebc5622016-09-23 13:29:20 +00001403 Cmd->Filler = readOutputSectionFiller(next());
1404 else if (peek().startswith("="))
George Rimarff1f29e2016-09-06 13:51:57 +00001405 Cmd->Filler = readOutputSectionFiller(next().drop_front());
George Rimar4ebc5622016-09-23 13:29:20 +00001406
Rui Ueyama10416562016-08-04 02:03:27 +00001407 return Cmd;
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001408}
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001409
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001410// Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
1411// https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
1412//
1413// ld.gold is not fully compatible with ld.bfd. ld.bfd handles
1414// hexstrings as blobs of arbitrary sizes, while ld.gold handles them
1415// as 32-bit big-endian values. We will do the same as ld.gold does
1416// because it's simpler than what ld.bfd does.
George Rimarff1f29e2016-09-06 13:51:57 +00001417std::vector<uint8_t> ScriptParser::readOutputSectionFiller(StringRef Tok) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001418 uint32_t V;
George Rimarff1f29e2016-09-06 13:51:57 +00001419 if (Tok.getAsInteger(0, V)) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001420 setError("invalid filler expression: " + Tok);
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001421 return {};
George Rimare2ee72b2016-02-26 14:48:31 +00001422 }
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001423 return {uint8_t(V >> 24), uint8_t(V >> 16), uint8_t(V >> 8), uint8_t(V)};
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001424}
1425
Petr Hoseka35e39c2016-08-16 01:11:16 +00001426SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
Eugene Levianta31c91b2016-07-22 07:38:40 +00001427 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +00001428 SymbolAssignment *Cmd = readAssignment(next());
Petr Hoseka35e39c2016-08-16 01:11:16 +00001429 Cmd->Provide = Provide;
Rui Ueyama174e0a12016-07-29 00:29:25 +00001430 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001431 expect(")");
1432 expect(";");
Rui Ueyama10416562016-08-04 02:03:27 +00001433 return Cmd;
Eugene Levianteda81a12016-07-12 06:39:48 +00001434}
1435
Rafael Espindolac96da112016-11-01 11:30:45 +00001436SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001437 SymbolAssignment *Cmd = nullptr;
1438 if (peek() == "=" || peek() == "+=") {
1439 Cmd = readAssignment(Tok);
1440 expect(";");
1441 } else if (Tok == "PROVIDE") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001442 Cmd = readProvideHidden(true, false);
1443 } else if (Tok == "HIDDEN") {
1444 Cmd = readProvideHidden(false, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001445 } else if (Tok == "PROVIDE_HIDDEN") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001446 Cmd = readProvideHidden(true, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001447 }
1448 return Cmd;
1449}
1450
George Rimar30835ea2016-07-28 21:08:56 +00001451static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
1452 if (S == ".")
1453 return Dot;
George Rimar884e7862016-09-08 08:19:13 +00001454 return ScriptBase->getSymbolValue(S);
George Rimare32a3592016-08-10 07:59:34 +00001455}
1456
Rafael Espindola2f831dc2016-10-31 19:56:37 +00001457static bool isAbsolute(StringRef S) {
1458 if (S == ".")
1459 return false;
1460 return ScriptBase->isAbsolute(S);
1461}
1462
George Rimar30835ea2016-07-28 21:08:56 +00001463SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1464 StringRef Op = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +00001465 Expr E;
George Rimar30835ea2016-07-28 21:08:56 +00001466 assert(Op == "=" || Op == "+=");
Rui Ueyama83043f22016-10-17 16:01:53 +00001467 if (consume("ABSOLUTE")) {
Rui Ueyama7c1381a2016-10-19 23:11:21 +00001468 // The RHS may be something like "ABSOLUTE(.) & 0xff".
1469 // Call readExpr1 to read the whole expression.
1470 E = readExpr1(readParenExpr(), 0);
Rafael Espindola2f831dc2016-10-31 19:56:37 +00001471 E.IsAbsolute = []() { return true; };
Eugene Leviantdb741e72016-09-07 07:08:43 +00001472 } else {
1473 E = readExpr();
1474 }
George Rimar30835ea2016-07-28 21:08:56 +00001475 if (Op == "+=")
1476 E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
Rafael Espindolaf6613932016-10-31 17:43:38 +00001477 return new SymbolAssignment(Name, E);
George Rimar30835ea2016-07-28 21:08:56 +00001478}
1479
1480// This is an operator-precedence parser to parse a linker
1481// script expression.
1482Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
1483
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001484static Expr combine(StringRef Op, Expr L, Expr R) {
1485 if (Op == "*")
1486 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1487 if (Op == "/") {
1488 return [=](uint64_t Dot) -> uint64_t {
1489 uint64_t RHS = R(Dot);
1490 if (RHS == 0) {
1491 error("division by zero");
1492 return 0;
1493 }
1494 return L(Dot) / RHS;
1495 };
1496 }
1497 if (Op == "+")
Rafael Espindola2f831dc2016-10-31 19:56:37 +00001498 return {[=](uint64_t Dot) { return L(Dot) + R(Dot); },
1499 [=]() { return L.IsAbsolute() && R.IsAbsolute(); }};
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001500 if (Op == "-")
1501 return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
George Rimarc8ccd1f2016-09-23 13:13:55 +00001502 if (Op == "<<")
1503 return [=](uint64_t Dot) { return L(Dot) << R(Dot); };
1504 if (Op == ">>")
1505 return [=](uint64_t Dot) { return L(Dot) >> R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001506 if (Op == "<")
1507 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
1508 if (Op == ">")
1509 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
1510 if (Op == ">=")
1511 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
1512 if (Op == "<=")
1513 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
1514 if (Op == "==")
1515 return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
1516 if (Op == "!=")
1517 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
1518 if (Op == "&")
1519 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
Rafael Espindolacc3dd622016-08-22 21:33:35 +00001520 if (Op == "|")
1521 return [=](uint64_t Dot) { return L(Dot) | R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001522 llvm_unreachable("invalid operator");
1523}
1524
Rui Ueyama708019c2016-07-24 18:19:40 +00001525// This is a part of the operator-precedence parser. This function
1526// assumes that the remaining token stream starts with an operator.
1527Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1528 while (!atEOF() && !Error) {
1529 // Read an operator and an expression.
1530 StringRef Op1 = peek();
1531 if (Op1 == "?")
1532 return readTernary(Lhs);
1533 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +00001534 break;
Justin Bogner5424e7c2016-10-17 06:21:13 +00001535 skip();
Rui Ueyama708019c2016-07-24 18:19:40 +00001536 Expr Rhs = readPrimary();
1537
1538 // Evaluate the remaining part of the expression first if the
1539 // next operator has greater precedence than the previous one.
1540 // For example, if we have read "+" and "3", and if the next
1541 // operator is "*", then we'll evaluate 3 * ... part first.
1542 while (!atEOF()) {
1543 StringRef Op2 = peek();
1544 if (precedence(Op2) <= precedence(Op1))
1545 break;
1546 Rhs = readExpr1(Rhs, precedence(Op2));
1547 }
1548
1549 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +00001550 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001551 return Lhs;
1552}
1553
1554uint64_t static getConstant(StringRef S) {
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001555 if (S == "COMMONPAGESIZE")
Rui Ueyama708019c2016-07-24 18:19:40 +00001556 return Target->PageSize;
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001557 if (S == "MAXPAGESIZE")
Petr Hosek997f8832016-09-28 15:20:47 +00001558 return Config->MaxPageSize;
Rui Ueyama708019c2016-07-24 18:19:40 +00001559 error("unknown constant: " + S);
1560 return 0;
1561}
1562
Rui Ueyama626e0b02016-09-02 18:19:00 +00001563// Parses Tok as an integer. Returns true if successful.
1564// It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1565// and decimal numbers. Decimal numbers may have "K" (kilo) or
1566// "M" (mega) prefixes.
George Rimar9f2f7ad2016-09-02 16:01:42 +00001567static bool readInteger(StringRef Tok, uint64_t &Result) {
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001568 if (Tok.startswith("-")) {
1569 if (!readInteger(Tok.substr(1), Result))
1570 return false;
1571 Result = -Result;
1572 return true;
1573 }
George Rimar9f2f7ad2016-09-02 16:01:42 +00001574 if (Tok.startswith_lower("0x"))
1575 return !Tok.substr(2).getAsInteger(16, Result);
1576 if (Tok.endswith_lower("H"))
1577 return !Tok.drop_back().getAsInteger(16, Result);
1578
1579 int Suffix = 1;
1580 if (Tok.endswith_lower("K")) {
1581 Suffix = 1024;
1582 Tok = Tok.drop_back();
1583 } else if (Tok.endswith_lower("M")) {
1584 Suffix = 1024 * 1024;
1585 Tok = Tok.drop_back();
1586 }
1587 if (Tok.getAsInteger(10, Result))
1588 return false;
1589 Result *= Suffix;
1590 return true;
1591}
1592
George Rimare38cbab2016-09-26 19:22:50 +00001593BytesDataCommand *ScriptParser::readBytesDataCommand(StringRef Tok) {
1594 int Size = StringSwitch<unsigned>(Tok)
1595 .Case("BYTE", 1)
1596 .Case("SHORT", 2)
1597 .Case("LONG", 4)
1598 .Case("QUAD", 8)
1599 .Default(-1);
1600 if (Size == -1)
1601 return nullptr;
1602
1603 expect("(");
1604 uint64_t Val = 0;
1605 StringRef S = next();
1606 if (!readInteger(S, Val))
1607 setError("unexpected value: " + S);
1608 expect(")");
1609 return new BytesDataCommand(Val, Size);
1610}
1611
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001612StringRef ScriptParser::readParenLiteral() {
1613 expect("(");
1614 StringRef Tok = next();
1615 expect(")");
1616 return Tok;
1617}
1618
Rui Ueyama708019c2016-07-24 18:19:40 +00001619Expr ScriptParser::readPrimary() {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001620 if (peek() == "(")
1621 return readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001622
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001623 StringRef Tok = next();
Rui Ueyama708019c2016-07-24 18:19:40 +00001624
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001625 if (Tok == "~") {
1626 Expr E = readPrimary();
1627 return [=](uint64_t Dot) { return ~E(Dot); };
1628 }
1629 if (Tok == "-") {
1630 Expr E = readPrimary();
1631 return [=](uint64_t Dot) { return -E(Dot); };
1632 }
1633
Rui Ueyama708019c2016-07-24 18:19:40 +00001634 // Built-in functions are parsed here.
1635 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
George Rimar96659df2016-08-30 09:54:01 +00001636 if (Tok == "ADDR") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001637 StringRef Name = readParenLiteral();
George Rimar884e7862016-09-08 08:19:13 +00001638 return
1639 [=](uint64_t Dot) { return ScriptBase->getOutputSectionAddress(Name); };
George Rimar96659df2016-08-30 09:54:01 +00001640 }
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001641 if (Tok == "LOADADDR") {
1642 StringRef Name = readParenLiteral();
1643 return [=](uint64_t Dot) { return ScriptBase->getOutputSectionLMA(Name); };
1644 }
George Rimareefa7582016-08-04 09:29:31 +00001645 if (Tok == "ASSERT")
1646 return readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001647 if (Tok == "ALIGN") {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001648 Expr E = readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001649 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1650 }
1651 if (Tok == "CONSTANT") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001652 StringRef Name = readParenLiteral();
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001653 return [=](uint64_t Dot) { return getConstant(Name); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001654 }
George Rimarf34f45f2016-09-23 13:17:23 +00001655 if (Tok == "DEFINED") {
1656 expect("(");
1657 StringRef Tok = next();
1658 expect(")");
George Rimarf2821022016-09-26 11:00:48 +00001659 return [=](uint64_t Dot) { return ScriptBase->isDefined(Tok) ? 1 : 0; };
George Rimarf34f45f2016-09-23 13:17:23 +00001660 }
Rafael Espindola54c145c2016-07-28 18:16:24 +00001661 if (Tok == "SEGMENT_START") {
1662 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001663 skip();
Rafael Espindola54c145c2016-07-28 18:16:24 +00001664 expect(",");
George Rimar8c658bf2016-09-17 18:14:56 +00001665 Expr E = readExpr();
Rafael Espindola54c145c2016-07-28 18:16:24 +00001666 expect(")");
George Rimar8c658bf2016-09-17 18:14:56 +00001667 return [=](uint64_t Dot) { return E(Dot); };
Rafael Espindola54c145c2016-07-28 18:16:24 +00001668 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001669 if (Tok == "DATA_SEGMENT_ALIGN") {
1670 expect("(");
1671 Expr E = readExpr();
1672 expect(",");
1673 readExpr();
1674 expect(")");
Rui Ueyamaf7791bb2016-07-26 19:34:10 +00001675 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001676 }
1677 if (Tok == "DATA_SEGMENT_END") {
1678 expect("(");
1679 expect(".");
1680 expect(")");
1681 return [](uint64_t Dot) { return Dot; };
1682 }
George Rimar276b4e62016-07-26 17:58:44 +00001683 // GNU linkers implements more complicated logic to handle
1684 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1685 // the next page boundary for simplicity.
1686 if (Tok == "DATA_SEGMENT_RELRO_END") {
1687 expect("(");
Rafael Espindola97bdc722016-09-14 19:14:01 +00001688 readExpr();
George Rimar276b4e62016-07-26 17:58:44 +00001689 expect(",");
1690 readExpr();
1691 expect(")");
1692 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1693 }
George Rimar9e694502016-07-29 16:18:47 +00001694 if (Tok == "SIZEOF") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001695 StringRef Name = readParenLiteral();
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001696 return [=](uint64_t Dot) { return ScriptBase->getOutputSectionSize(Name); };
George Rimar9e694502016-07-29 16:18:47 +00001697 }
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001698 if (Tok == "ALIGNOF") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001699 StringRef Name = readParenLiteral();
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001700 return
1701 [=](uint64_t Dot) { return ScriptBase->getOutputSectionAlign(Name); };
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001702 }
George Rimare32a3592016-08-10 07:59:34 +00001703 if (Tok == "SIZEOF_HEADERS")
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001704 return [=](uint64_t Dot) { return ScriptBase->getHeaderSize(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001705
George Rimar9f2f7ad2016-09-02 16:01:42 +00001706 // Tok is a literal number.
1707 uint64_t V;
1708 if (readInteger(Tok, V))
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001709 return [=](uint64_t Dot) { return V; };
George Rimar9f2f7ad2016-09-02 16:01:42 +00001710
1711 // Tok is a symbol name.
1712 if (Tok != "." && !isValidCIdentifier(Tok))
1713 setError("malformed number: " + Tok);
Rafael Espindola2f831dc2016-10-31 19:56:37 +00001714 return {[=](uint64_t Dot) { return getSymbolValue(Tok, Dot); },
1715 [=]() { return isAbsolute(Tok); }};
Rui Ueyama708019c2016-07-24 18:19:40 +00001716}
1717
1718Expr ScriptParser::readTernary(Expr Cond) {
Justin Bogner5424e7c2016-10-17 06:21:13 +00001719 skip();
Rui Ueyama708019c2016-07-24 18:19:40 +00001720 Expr L = readExpr();
1721 expect(":");
1722 Expr R = readExpr();
1723 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1724}
1725
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001726Expr ScriptParser::readParenExpr() {
1727 expect("(");
1728 Expr E = readExpr();
1729 expect(")");
1730 return E;
1731}
1732
Eugene Leviantbbe38602016-07-19 09:25:43 +00001733std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1734 std::vector<StringRef> Phdrs;
1735 while (!Error && peek().startswith(":")) {
1736 StringRef Tok = next();
George Rimarda841c12016-11-14 10:03:54 +00001737 Phdrs.push_back((Tok.size() == 1) ? next() : Tok.substr(1));
Eugene Leviantbbe38602016-07-19 09:25:43 +00001738 }
1739 return Phdrs;
1740}
1741
George Rimar95dd7182016-10-18 10:49:50 +00001742// Read a program header type name. The next token must be a
1743// name of a program header type or a constant (e.g. "0x3").
Eugene Leviantbbe38602016-07-19 09:25:43 +00001744unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001745 StringRef Tok = next();
George Rimar95dd7182016-10-18 10:49:50 +00001746 uint64_t Val;
1747 if (readInteger(Tok, Val))
1748 return Val;
1749
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001750 unsigned Ret = StringSwitch<unsigned>(Tok)
George Rimar6c55f0e2016-09-08 08:20:30 +00001751 .Case("PT_NULL", PT_NULL)
1752 .Case("PT_LOAD", PT_LOAD)
1753 .Case("PT_DYNAMIC", PT_DYNAMIC)
1754 .Case("PT_INTERP", PT_INTERP)
1755 .Case("PT_NOTE", PT_NOTE)
1756 .Case("PT_SHLIB", PT_SHLIB)
1757 .Case("PT_PHDR", PT_PHDR)
1758 .Case("PT_TLS", PT_TLS)
1759 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1760 .Case("PT_GNU_STACK", PT_GNU_STACK)
1761 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
George Rimar270173f2016-10-14 13:02:22 +00001762 .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
George Rimarcc6e5672016-10-14 10:34:36 +00001763 .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
George Rimar6c55f0e2016-09-08 08:20:30 +00001764 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001765
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001766 if (Ret == (unsigned)-1) {
1767 setError("invalid program header type: " + Tok);
1768 return PT_NULL;
1769 }
1770 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001771}
1772
Rui Ueyama95769b42016-08-31 20:03:54 +00001773void ScriptParser::readVersionDeclaration(StringRef VerStr) {
George Rimar20b65982016-08-31 09:08:26 +00001774 // Identifiers start at 2 because 0 and 1 are reserved
1775 // for VER_NDX_LOCAL and VER_NDX_GLOBAL constants.
1776 size_t VersionId = Config->VersionDefinitions.size() + 2;
1777 Config->VersionDefinitions.push_back({VerStr, VersionId});
1778
Rui Ueyama83043f22016-10-17 16:01:53 +00001779 if (consume("global:") || peek() != "local:")
George Rimar20b65982016-08-31 09:08:26 +00001780 readGlobal(VerStr);
Rui Ueyama83043f22016-10-17 16:01:53 +00001781 if (consume("local:"))
George Rimarbb6c01e2016-11-12 07:04:15 +00001782 readLocal(VerStr);
George Rimar20b65982016-08-31 09:08:26 +00001783 expect("}");
1784
1785 // Each version may have a parent version. For example, "Ver2" defined as
1786 // "Ver2 { global: foo; local: *; } Ver1;" has "Ver1" as a parent. This
1787 // version hierarchy is, probably against your instinct, purely for human; the
1788 // runtime doesn't care about them at all. In LLD, we simply skip the token.
1789 if (!VerStr.empty() && peek() != ";")
Justin Bogner5424e7c2016-10-17 06:21:13 +00001790 skip();
George Rimar20b65982016-08-31 09:08:26 +00001791 expect(";");
1792}
1793
George Rimarbb6c01e2016-11-12 07:04:15 +00001794void ScriptParser::readLocal(StringRef VerStr) {
1795 if (consume("*")) {
1796 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1797 expect(";");
1798 return;
1799 }
1800
1801 if (VerStr.empty())
1802 setError("locals list for anonymous version is not supported");
1803
1804 std::vector<SymbolVersion> &Locals = Config->VersionDefinitions.back().Locals;
1805 while (!Error && peek() != "}") {
1806 StringRef Tok = next();
1807 Locals.push_back({unquote(Tok), false, hasWildcard(Tok)});
1808 expect(";");
1809 }
George Rimar20b65982016-08-31 09:08:26 +00001810}
1811
1812void ScriptParser::readExtern(std::vector<SymbolVersion> *Globals) {
George Rimarcd574a52016-09-09 14:35:36 +00001813 expect("\"C++\"");
George Rimar20b65982016-08-31 09:08:26 +00001814 expect("{");
1815
1816 for (;;) {
1817 if (peek() == "}" || Error)
1818 break;
George Rimarcd574a52016-09-09 14:35:36 +00001819 bool HasWildcard = !peek().startswith("\"") && hasWildcard(peek());
1820 Globals->push_back({unquote(next()), true, HasWildcard});
George Rimar20b65982016-08-31 09:08:26 +00001821 expect(";");
1822 }
1823
1824 expect("}");
1825 expect(";");
1826}
1827
1828void ScriptParser::readGlobal(StringRef VerStr) {
1829 std::vector<SymbolVersion> *Globals;
1830 if (VerStr.empty())
1831 Globals = &Config->VersionScriptGlobals;
1832 else
1833 Globals = &Config->VersionDefinitions.back().Globals;
1834
1835 for (;;) {
Rui Ueyama83043f22016-10-17 16:01:53 +00001836 if (consume("extern"))
George Rimar20b65982016-08-31 09:08:26 +00001837 readExtern(Globals);
1838
1839 StringRef Cur = peek();
1840 if (Cur == "}" || Cur == "local:" || Error)
1841 return;
Justin Bogner5424e7c2016-10-17 06:21:13 +00001842 skip();
George Rimarcd574a52016-09-09 14:35:36 +00001843 Globals->push_back({unquote(Cur), false, hasWildcard(Cur)});
George Rimar20b65982016-08-31 09:08:26 +00001844 expect(";");
1845 }
1846}
1847
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001848static bool isUnderSysroot(StringRef Path) {
1849 if (Config->Sysroot == "")
1850 return false;
1851 for (; !Path.empty(); Path = sys::path::parent_path(Path))
1852 if (sys::fs::equivalent(Config->Sysroot, Path))
1853 return true;
1854 return false;
1855}
1856
Rui Ueyama07320e42016-04-20 20:13:41 +00001857void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001858 StringRef Path = MB.getBufferIdentifier();
George Rimar20b65982016-08-31 09:08:26 +00001859 ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).readLinkerScript();
1860}
1861
1862void elf::readVersionScript(MemoryBufferRef MB) {
1863 ScriptParser(MB.getBuffer(), false).readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001864}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001865
Rui Ueyama07320e42016-04-20 20:13:41 +00001866template class elf::LinkerScript<ELF32LE>;
1867template class elf::LinkerScript<ELF32BE>;
1868template class elf::LinkerScript<ELF64LE>;
1869template class elf::LinkerScript<ELF64BE>;