blob: 646dbbd950086e04a743c9929a754b32aecfa9a2 [file] [log] [blame]
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001//===- LinkerScript.cpp ---------------------------------------------------===//
2//
3// The LLVM Linker
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains the parser/evaluator of the linker script.
Rui Ueyama629e0aa52016-07-21 19:45:22 +000011// It parses a linker script and write the result to Config or ScriptConfig
12// objects.
13//
14// If SECTIONS command is used, a ScriptConfig contains an AST
15// of the command which will later be consumed by createSections() and
16// assignAddresses().
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000017//
18//===----------------------------------------------------------------------===//
19
Rui Ueyama717677a2016-02-11 21:17:59 +000020#include "LinkerScript.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000021#include "Config.h"
22#include "Driver.h"
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +000023#include "InputSection.h"
George Rimar652852c2016-04-16 10:10:32 +000024#include "OutputSections.h"
Adhemerval Zanellae77b5bf2016-04-06 20:59:11 +000025#include "ScriptParser.h"
Rui Ueyama93c9af42016-06-29 08:01:32 +000026#include "Strings.h"
Eugene Levianteda81a12016-07-12 06:39:48 +000027#include "Symbols.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000028#include "SymbolTable.h"
Eugene Leviant467c4d52016-07-01 10:27:36 +000029#include "Target.h"
Eugene Leviantbbe38602016-07-19 09:25:43 +000030#include "Writer.h"
Rui Ueyama960504b2016-04-19 18:58:11 +000031#include "llvm/ADT/StringSwitch.h"
George Rimar652852c2016-04-16 10:10:32 +000032#include "llvm/Support/ELF.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000033#include "llvm/Support/FileSystem.h"
34#include "llvm/Support/MemoryBuffer.h"
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +000035#include "llvm/Support/Path.h"
Rui Ueyamaa47ee682015-10-11 01:53:04 +000036#include "llvm/Support/StringSaver.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000037
38using namespace llvm;
George Rimar652852c2016-04-16 10:10:32 +000039using namespace llvm::ELF;
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +000040using namespace llvm::object;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000041using namespace lld;
Rafael Espindolae0df00b2016-02-28 00:25:54 +000042using namespace lld::elf;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000043
George Rimar884e7862016-09-08 08:19:13 +000044LinkerScriptBase *elf::ScriptBase;
Rui Ueyama07320e42016-04-20 20:13:41 +000045ScriptConfiguration *elf::ScriptConfig;
Rui Ueyama717677a2016-02-11 21:17:59 +000046
George Rimar6c55f0e2016-09-08 08:20:30 +000047template <class ELFT> static void addRegular(SymbolAssignment *Cmd) {
Rui Ueyama16024212016-08-11 23:22:52 +000048 Symbol *Sym = Symtab<ELFT>::X->addRegular(Cmd->Name, STB_GLOBAL, STV_DEFAULT);
49 Sym->Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
50 Cmd->Sym = Sym->body();
Eugene Leviant20d03192016-09-16 15:30:47 +000051
52 // If we have no SECTIONS then we don't have '.' and don't call
53 // assignAddresses(). We calculate symbol value immediately in this case.
54 if (!ScriptConfig->HasSections)
55 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(0);
Eugene Leviantceabe802016-08-11 07:56:43 +000056}
57
Rui Ueyama0c70d3c2016-08-12 03:31:09 +000058template <class ELFT> static void addSynthetic(SymbolAssignment *Cmd) {
George Rimare1937bb2016-08-19 15:36:32 +000059 Symbol *Sym = Symtab<ELFT>::X->addSynthetic(
60 Cmd->Name, nullptr, 0, Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT);
Rui Ueyama16024212016-08-11 23:22:52 +000061 Cmd->Sym = Sym->body();
Eugene Leviantceabe802016-08-11 07:56:43 +000062}
63
Eugene Leviantdb741e72016-09-07 07:08:43 +000064template <class ELFT> static void addSymbol(SymbolAssignment *Cmd) {
65 if (Cmd->IsAbsolute)
66 addRegular<ELFT>(Cmd);
67 else
68 addSynthetic<ELFT>(Cmd);
69}
Rui Ueyama16024212016-08-11 23:22:52 +000070// If a symbol was in PROVIDE(), we need to define it only when
71// it is an undefined symbol.
72template <class ELFT> static bool shouldDefine(SymbolAssignment *Cmd) {
73 if (Cmd->Name == ".")
Eugene Leviantceabe802016-08-11 07:56:43 +000074 return false;
Rui Ueyama16024212016-08-11 23:22:52 +000075 if (!Cmd->Provide)
76 return true;
77 SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
78 return B && B->isUndefined();
Eugene Leviantceabe802016-08-11 07:56:43 +000079}
80
George Rimar076fe152016-07-21 06:43:01 +000081bool SymbolAssignment::classof(const BaseCommand *C) {
82 return C->Kind == AssignmentKind;
83}
84
85bool OutputSectionCommand::classof(const BaseCommand *C) {
86 return C->Kind == OutputSectionKind;
87}
88
George Rimareea31142016-07-21 14:26:59 +000089bool InputSectionDescription::classof(const BaseCommand *C) {
90 return C->Kind == InputSectionKind;
91}
92
George Rimareefa7582016-08-04 09:29:31 +000093bool AssertCommand::classof(const BaseCommand *C) {
94 return C->Kind == AssertKind;
95}
96
Rui Ueyama36a153c2016-07-23 14:09:58 +000097template <class ELFT> static bool isDiscarded(InputSectionBase<ELFT> *S) {
George Rimareea31142016-07-21 14:26:59 +000098 return !S || !S->Live;
Rui Ueyama717677a2016-02-11 21:17:59 +000099}
100
Rui Ueyamaf34d0e02016-08-12 01:24:53 +0000101template <class ELFT> LinkerScript<ELFT>::LinkerScript() {}
102template <class ELFT> LinkerScript<ELFT>::~LinkerScript() {}
103
Rui Ueyama07320e42016-04-20 20:13:41 +0000104template <class ELFT>
105bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) {
George Rimarc91930a2016-09-02 21:17:20 +0000106 for (Regex *Re : Opt.KeptSections)
Rafael Espindola042a3f22016-09-08 14:06:08 +0000107 if (Re->match(S->Name))
George Rimareea31142016-07-21 14:26:59 +0000108 return true;
109 return false;
110}
111
George Rimar575208c2016-09-15 19:15:12 +0000112static bool comparePriority(InputSectionData *A, InputSectionData *B) {
113 return getPriority(A->Name) < getPriority(B->Name);
114}
115
Rafael Espindolac0028d32016-09-08 20:47:52 +0000116static bool compareName(InputSectionData *A, InputSectionData *B) {
Rafael Espindola042a3f22016-09-08 14:06:08 +0000117 return A->Name < B->Name;
Rui Ueyama742c3832016-08-04 22:27:00 +0000118}
George Rimar350ece42016-08-03 08:35:59 +0000119
Rafael Espindolac0028d32016-09-08 20:47:52 +0000120static bool compareAlignment(InputSectionData *A, InputSectionData *B) {
Rui Ueyama742c3832016-08-04 22:27:00 +0000121 // ">" is not a mistake. Larger alignments are placed before smaller
122 // alignments in order to reduce the amount of padding necessary.
123 // This is compatible with GNU.
124 return A->Alignment > B->Alignment;
125}
George Rimar350ece42016-08-03 08:35:59 +0000126
Rafael Espindolac0028d32016-09-08 20:47:52 +0000127static std::function<bool(InputSectionData *, InputSectionData *)>
George Rimarbe394db2016-09-16 20:21:55 +0000128getComparator(SortSectionPolicy K) {
129 switch (K) {
130 case SortSectionPolicy::Alignment:
131 return compareAlignment;
132 case SortSectionPolicy::Name:
Rafael Espindolac0028d32016-09-08 20:47:52 +0000133 return compareName;
George Rimarbe394db2016-09-16 20:21:55 +0000134 case SortSectionPolicy::Priority:
135 return comparePriority;
136 default:
137 llvm_unreachable("unknown sort policy");
138 }
Rui Ueyama742c3832016-08-04 22:27:00 +0000139}
George Rimar0702c4e2016-07-29 15:32:46 +0000140
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000141template <class ELFT>
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000142static bool matchConstraints(ArrayRef<InputSectionBase<ELFT> *> Sections,
George Rimar06ae6832016-08-12 09:07:57 +0000143 ConstraintKind Kind) {
George Rimar8f66df92016-08-12 20:38:20 +0000144 if (Kind == ConstraintKind::NoConstraint)
145 return true;
Rafael Espindolae746e522016-09-21 18:33:44 +0000146 bool IsRW = llvm::any_of(Sections, [=](InputSectionData *Sec2) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000147 auto *Sec = static_cast<InputSectionBase<ELFT> *>(Sec2);
Rafael Espindolae746e522016-09-21 18:33:44 +0000148 return Sec->getSectionHdr()->sh_flags & SHF_WRITE;
George Rimar06ae6832016-08-12 09:07:57 +0000149 });
Rafael Espindolae746e522016-09-21 18:33:44 +0000150 return (IsRW && Kind == ConstraintKind::ReadWrite) ||
151 (!IsRW && Kind == ConstraintKind::ReadOnly);
George Rimar06ae6832016-08-12 09:07:57 +0000152}
153
George Rimar07171f22016-09-21 15:56:44 +0000154static void sortSections(InputSectionData **Begin, InputSectionData **End,
Rui Ueyamaee924702016-09-20 19:42:41 +0000155 SortSectionPolicy K) {
156 if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
George Rimar07171f22016-09-21 15:56:44 +0000157 std::stable_sort(Begin, End, getComparator(K));
Rui Ueyamaee924702016-09-20 19:42:41 +0000158}
159
Rafael Espindolad3190792016-09-16 15:10:23 +0000160// Compute and remember which sections the InputSectionDescription matches.
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000161template <class ELFT>
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000162void LinkerScript<ELFT>::computeInputSections(InputSectionDescription *I) {
Rui Ueyama4dc07be2016-09-17 02:23:40 +0000163 // Collects all sections that satisfy constraints of I
164 // and attach them to I.
165 for (SectionPattern &Pat : I->SectionPatterns) {
George Rimar07171f22016-09-21 15:56:44 +0000166 size_t SizeBefore = I->Sections.size();
George Rimar395281c2016-09-16 17:42:10 +0000167 for (ObjectFile<ELFT> *F : Symtab<ELFT>::X->getObjectFiles()) {
Rui Ueyama3ff27f42016-09-17 02:15:28 +0000168 StringRef Filename = sys::path::filename(F->getName());
Rafael Espindolaf135f0e2016-09-19 13:33:38 +0000169 if (!I->FileRe.match(Filename) || Pat.ExcludedFileRe.match(Filename))
Rui Ueyama3ff27f42016-09-17 02:15:28 +0000170 continue;
Rui Ueyama4dc07be2016-09-17 02:23:40 +0000171
Rui Ueyama3ff27f42016-09-17 02:15:28 +0000172 for (InputSectionBase<ELFT> *S : F->getSections())
Rafael Espindolaf135f0e2016-09-19 13:33:38 +0000173 if (!isDiscarded(S) && !S->OutSec && Pat.SectionRe.match(S->Name))
Rui Ueyama3ff27f42016-09-17 02:15:28 +0000174 I->Sections.push_back(S);
Rafael Espindolaf135f0e2016-09-19 13:33:38 +0000175 if (Pat.SectionRe.match("COMMON"))
Rui Ueyama3ff27f42016-09-17 02:15:28 +0000176 I->Sections.push_back(CommonInputSection<ELFT>::X);
George Rimar395281c2016-09-16 17:42:10 +0000177 }
Rafael Espindolad3190792016-09-16 15:10:23 +0000178
George Rimar07171f22016-09-21 15:56:44 +0000179 // Sort sections as instructed by SORT-family commands and --sort-section
180 // option. Because SORT-family commands can be nested at most two depth
181 // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
182 // line option is respected even if a SORT command is given, the exact
183 // behavior we have here is a bit complicated. Here are the rules.
184 //
185 // 1. If two SORT commands are given, --sort-section is ignored.
186 // 2. If one SORT command is given, and if it is not SORT_NONE,
187 // --sort-section is handled as an inner SORT command.
188 // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
189 // 4. If no SORT command is given, sort according to --sort-section.
190 InputSectionData **Begin = I->Sections.data() + SizeBefore;
191 InputSectionData **End = I->Sections.data() + I->Sections.size();
192 if (Pat.SortOuter != SortSectionPolicy::None) {
193 if (Pat.SortInner == SortSectionPolicy::Default)
194 sortSections(Begin, End, Config->SortSection);
195 else
196 sortSections(Begin, End, Pat.SortInner);
197 sortSections(Begin, End, Pat.SortOuter);
198 }
Rui Ueyamaee924702016-09-20 19:42:41 +0000199 }
Rafael Espindolad3190792016-09-16 15:10:23 +0000200
201 // We do not add duplicate input sections, so mark them with a dummy output
202 // section for now.
203 for (InputSectionData *S : I->Sections) {
204 auto *S2 = static_cast<InputSectionBase<ELFT> *>(S);
205 S2->OutSec = (OutputSectionBase<ELFT> *)-1;
206 }
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000207}
208
209template <class ELFT>
210void LinkerScript<ELFT>::discard(ArrayRef<InputSectionBase<ELFT> *> V) {
211 for (InputSectionBase<ELFT> *S : V) {
212 S->Live = false;
213 reportDiscarded(S);
214 }
215}
216
George Rimar06ae6832016-08-12 09:07:57 +0000217template <class ELFT>
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000218std::vector<InputSectionBase<ELFT> *>
George Rimar06ae6832016-08-12 09:07:57 +0000219LinkerScript<ELFT>::createInputSectionList(OutputSectionCommand &OutCmd) {
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000220 std::vector<InputSectionBase<ELFT> *> Ret;
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000221
George Rimar06ae6832016-08-12 09:07:57 +0000222 for (const std::unique_ptr<BaseCommand> &Base : OutCmd.Commands) {
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000223 auto *Cmd = dyn_cast<InputSectionDescription>(Base.get());
224 if (!Cmd)
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000225 continue;
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000226 computeInputSections(Cmd);
Rafael Espindolad3190792016-09-16 15:10:23 +0000227 for (InputSectionData *S : Cmd->Sections)
228 Ret.push_back(static_cast<InputSectionBase<ELFT> *>(S));
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000229 }
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000230
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000231 return Ret;
232}
233
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000234template <class ELFT>
Rafael Espindola10897f12016-09-13 14:23:14 +0000235static SectionKey<ELFT::Is64Bits> createKey(InputSectionBase<ELFT> *C,
236 StringRef OutsecName) {
237 // When using linker script the merge rules are different.
238 // Unfortunately, linker scripts are name based. This means that expressions
239 // like *(.foo*) can refer to multiple input sections that would normally be
240 // placed in different output sections. We cannot put them in different
241 // output sections or we would produce wrong results for
242 // start = .; *(.foo.*) end = .; *(.bar)
243 // and a mapping of .foo1 and .bar1 to one section and .foo2 and .bar2 to
244 // another. The problem is that there is no way to layout those output
245 // sections such that the .foo sections are the only thing between the
246 // start and end symbols.
247
248 // An extra annoyance is that we cannot simply disable merging of the contents
249 // of SHF_MERGE sections, but our implementation requires one output section
250 // per "kind" (string or not, which size/aligment).
251 // Fortunately, creating symbols in the middle of a merge section is not
252 // supported by bfd or gold, so we can just create multiple section in that
253 // case.
254 const typename ELFT::Shdr *H = C->getSectionHdr();
255 typedef typename ELFT::uint uintX_t;
256 uintX_t Flags = H->sh_flags & (SHF_MERGE | SHF_STRINGS);
257
258 uintX_t Alignment = 0;
259 if (isa<MergeInputSection<ELFT>>(C))
260 Alignment = std::max(H->sh_addralign, H->sh_entsize);
261
262 return SectionKey<ELFT::Is64Bits>{OutsecName, /*Type*/ 0, Flags, Alignment};
263}
264
265template <class ELFT>
Eugene Leviant20d03192016-09-16 15:30:47 +0000266void LinkerScript<ELFT>::addSection(OutputSectionFactory<ELFT> &Factory,
267 InputSectionBase<ELFT> *Sec,
268 StringRef Name) {
269 OutputSectionBase<ELFT> *OutSec;
270 bool IsNew;
271 std::tie(OutSec, IsNew) = Factory.create(createKey(Sec, Name), Sec);
272 if (IsNew)
273 OutputSections->push_back(OutSec);
274 OutSec->addSection(Sec);
275}
276
277template <class ELFT>
278void LinkerScript<ELFT>::processCommands(OutputSectionFactory<ELFT> &Factory) {
Rafael Espindola28c15972016-09-13 13:00:06 +0000279
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000280 for (unsigned I = 0; I < Opt.Commands.size(); ++I) {
281 auto Iter = Opt.Commands.begin() + I;
282 const std::unique_ptr<BaseCommand> &Base1 = *Iter;
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000283 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base1.get())) {
284 if (shouldDefine<ELFT>(Cmd))
285 addRegular<ELFT>(Cmd);
286 continue;
287 }
Eugene Leviant20d03192016-09-16 15:30:47 +0000288 if (auto *Cmd = dyn_cast<AssertCommand>(Base1.get())) {
289 // If we don't have SECTIONS then output sections have already been
George Rimar194470cd2016-09-17 19:21:05 +0000290 // created by Writer<ELFT>. The LinkerScript<ELFT>::assignAddresses
Eugene Leviant20d03192016-09-16 15:30:47 +0000291 // will not be called, so ASSERT should be evaluated now.
292 if (!Opt.HasSections)
293 Cmd->Expression(0);
294 continue;
295 }
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000296
Eugene Leviantceabe802016-08-11 07:56:43 +0000297 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000298 std::vector<InputSectionBase<ELFT> *> V = createInputSectionList(*Cmd);
299
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000300 if (Cmd->Name == "/DISCARD/") {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000301 discard(V);
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000302 continue;
303 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000304
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000305 if (!matchConstraints<ELFT>(V, Cmd->Constraint)) {
306 for (InputSectionBase<ELFT> *S : V)
307 S->OutSec = nullptr;
308 Opt.Commands.erase(Iter);
George Rimardfbbbc82016-09-17 09:50:10 +0000309 --I;
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000310 continue;
311 }
312
313 for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
314 if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base.get()))
315 if (shouldDefine<ELFT>(OutCmd))
316 addSymbol<ELFT>(OutCmd);
317
Eugene Leviant97403d12016-09-01 09:55:57 +0000318 if (V.empty())
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000319 continue;
320
George Rimardb24d9c2016-08-19 15:18:23 +0000321 for (InputSectionBase<ELFT> *Sec : V) {
Eugene Leviant20d03192016-09-16 15:30:47 +0000322 addSection(Factory, Sec, Cmd->Name);
323 if (uint32_t Subalign = Cmd->SubalignExpr ? Cmd->SubalignExpr(0) : 0)
George Rimardb24d9c2016-08-19 15:18:23 +0000324 Sec->Alignment = Subalign;
George Rimardb24d9c2016-08-19 15:18:23 +0000325 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000326 }
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000327 }
Eugene Leviant20d03192016-09-16 15:30:47 +0000328}
Eugene Leviante63d81b2016-07-20 14:43:20 +0000329
Eugene Leviant20d03192016-09-16 15:30:47 +0000330template <class ELFT>
331void LinkerScript<ELFT>::createSections(OutputSectionFactory<ELFT> &Factory) {
332 processCommands(Factory);
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000333 // Add orphan sections.
Eugene Leviant20d03192016-09-16 15:30:47 +0000334 for (ObjectFile<ELFT> *F : Symtab<ELFT>::X->getObjectFiles())
335 for (InputSectionBase<ELFT> *S : F->getSections())
336 if (!isDiscarded(S) && !S->OutSec)
337 addSection(Factory, S, getOutputSectionName(S));
Eugene Leviante63d81b2016-07-20 14:43:20 +0000338}
339
Eugene Leviantdb741e72016-09-07 07:08:43 +0000340// Sets value of a section-defined symbol. Two kinds of
341// symbols are processed: synthetic symbols, whose value
342// is an offset from beginning of section and regular
343// symbols whose value is absolute.
344template <class ELFT>
345static void assignSectionSymbol(SymbolAssignment *Cmd,
346 OutputSectionBase<ELFT> *Sec,
347 typename ELFT::uint Off) {
348 if (!Cmd->Sym)
349 return;
350
351 if (auto *Body = dyn_cast<DefinedSynthetic<ELFT>>(Cmd->Sym)) {
352 Body->Section = Sec;
353 Body->Value = Cmd->Expression(Sec->getVA() + Off) - Sec->getVA();
354 return;
355 }
356 auto *Body = cast<DefinedRegular<ELFT>>(Cmd->Sym);
357 Body->Value = Cmd->Expression(Sec->getVA() + Off);
358}
359
Rafael Espindolaa940e532016-09-22 12:35:44 +0000360template <class ELFT> static bool isTbss(OutputSectionBase<ELFT> *Sec) {
361 return (Sec->getFlags() & SHF_TLS) && Sec->getType() == SHT_NOBITS;
362}
363
Rafael Espindolad3190792016-09-16 15:10:23 +0000364template <class ELFT> void LinkerScript<ELFT>::output(InputSection<ELFT> *S) {
365 if (!AlreadyOutputIS.insert(S).second)
366 return;
Rafael Espindolaa940e532016-09-22 12:35:44 +0000367 bool IsTbss = isTbss(CurOutSec);
Eugene Leviant20889c52016-08-31 08:13:33 +0000368
Rafael Espindolad3190792016-09-16 15:10:23 +0000369 uintX_t Pos = IsTbss ? Dot + ThreadBssOffset : Dot;
370 Pos = alignTo(Pos, S->Alignment);
371 S->OutSecOff = Pos - CurOutSec->getVA();
372 Pos += S->getSize();
373
374 // Update output section size after adding each section. This is so that
375 // SIZEOF works correctly in the case below:
376 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
377 CurOutSec->setSize(Pos - CurOutSec->getVA());
378
Rafael Espindola7252ae52016-09-22 12:00:08 +0000379 if (IsTbss)
380 ThreadBssOffset = Pos - Dot;
381 else
Rafael Espindolad3190792016-09-16 15:10:23 +0000382 Dot = Pos;
383}
384
385template <class ELFT> void LinkerScript<ELFT>::flush() {
386 if (auto *OutSec = dyn_cast_or_null<OutputSection<ELFT>>(CurOutSec)) {
387 for (InputSection<ELFT> *I : OutSec->Sections)
388 output(I);
389 AlreadyOutputOS.insert(CurOutSec);
Eugene Leviant20889c52016-08-31 08:13:33 +0000390 }
391}
392
393template <class ELFT>
Rafael Espindolad3190792016-09-16 15:10:23 +0000394void LinkerScript<ELFT>::switchTo(OutputSectionBase<ELFT> *Sec) {
395 if (CurOutSec == Sec)
396 return;
397 if (AlreadyOutputOS.count(Sec))
398 return;
399
400 flush();
401 CurOutSec = Sec;
402
403 Dot = alignTo(Dot, CurOutSec->getAlignment());
Rafael Espindolaa940e532016-09-22 12:35:44 +0000404 CurOutSec->setVA(isTbss(CurOutSec) ? Dot + ThreadBssOffset : Dot);
Rafael Espindolad3190792016-09-16 15:10:23 +0000405}
406
407template <class ELFT> void LinkerScript<ELFT>::process(BaseCommand &Base) {
408 if (auto *AssignCmd = dyn_cast<SymbolAssignment>(&Base)) {
409 if (AssignCmd->Name == ".") {
410 // Update to location counter means update to section size.
411 Dot = AssignCmd->Expression(Dot);
412 CurOutSec->setSize(Dot - CurOutSec->getVA());
413 return;
414 }
415 assignSectionSymbol<ELFT>(AssignCmd, CurOutSec, Dot - CurOutSec->getVA());
Eugene Leviantceabe802016-08-11 07:56:43 +0000416 return;
Rui Ueyama2de509c2016-08-12 00:55:08 +0000417 }
Rafael Espindolad3190792016-09-16 15:10:23 +0000418 auto &ICmd = cast<InputSectionDescription>(Base);
419 for (InputSectionData *ID : ICmd.Sections) {
420 auto *IB = static_cast<InputSectionBase<ELFT> *>(ID);
421 switchTo(IB->OutSec);
422 if (auto *I = dyn_cast<InputSection<ELFT>>(IB))
423 output(I);
424 else if (AlreadyOutputOS.insert(CurOutSec).second)
425 Dot += CurOutSec->getSize();
Eugene Leviantceabe802016-08-11 07:56:43 +0000426 }
427}
428
George Rimar8f66df92016-08-12 20:38:20 +0000429template <class ELFT>
George Rimara14b13d2016-09-07 10:46:07 +0000430static std::vector<OutputSectionBase<ELFT> *>
431findSections(OutputSectionCommand &Cmd,
Rafael Espindolad3190792016-09-16 15:10:23 +0000432 const std::vector<OutputSectionBase<ELFT> *> &Sections) {
George Rimara14b13d2016-09-07 10:46:07 +0000433 std::vector<OutputSectionBase<ELFT> *> Ret;
434 for (OutputSectionBase<ELFT> *Sec : Sections)
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000435 if (Sec->getName() == Cmd.Name)
George Rimara14b13d2016-09-07 10:46:07 +0000436 Ret.push_back(Sec);
437 return Ret;
George Rimar8f66df92016-08-12 20:38:20 +0000438}
439
Rafael Espindolad3190792016-09-16 15:10:23 +0000440template <class ELFT>
441void LinkerScript<ELFT>::assignOffsets(OutputSectionCommand *Cmd) {
442 std::vector<OutputSectionBase<ELFT> *> Sections =
443 findSections(*Cmd, *OutputSections);
444 if (Sections.empty())
445 return;
446 switchTo(Sections[0]);
447
448 // Find the last section output location. We will output orphan sections
449 // there so that end symbols point to the correct location.
450 auto E = std::find_if(Cmd->Commands.rbegin(), Cmd->Commands.rend(),
451 [](const std::unique_ptr<BaseCommand> &Cmd) {
452 return !isa<SymbolAssignment>(*Cmd);
453 })
454 .base();
455 for (auto I = Cmd->Commands.begin(); I != E; ++I)
456 process(**I);
457 flush();
458 for (OutputSectionBase<ELFT> *Base : Sections) {
Eugene Leviant2506cb42016-09-21 11:29:28 +0000459 if (AlreadyOutputOS.count(Base))
Rafael Espindolad3190792016-09-16 15:10:23 +0000460 continue;
461 switchTo(Base);
462 Dot += CurOutSec->getSize();
Eugene Leviant2506cb42016-09-21 11:29:28 +0000463 flush();
Rafael Espindolad3190792016-09-16 15:10:23 +0000464 }
George Rimarb31dd372016-09-19 13:27:31 +0000465 std::for_each(E, Cmd->Commands.end(),
466 [this](std::unique_ptr<BaseCommand> &B) { process(*B.get()); });
Rafael Espindolad3190792016-09-16 15:10:23 +0000467}
468
Rafael Espindola9546fff2016-09-22 14:40:50 +0000469template <class ELFT> void LinkerScript<ELFT>::adjustSectionsBeforeSorting() {
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000470 // It is common practice to use very generic linker scripts. So for any
471 // given run some of the output sections in the script will be empty.
472 // We could create corresponding empty output sections, but that would
473 // clutter the output.
474 // We instead remove trivially empty sections. The bfd linker seems even
475 // more aggressive at removing them.
476 auto Pos = std::remove_if(
477 Opt.Commands.begin(), Opt.Commands.end(),
478 [&](const std::unique_ptr<BaseCommand> &Base) {
479 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
480 if (!Cmd)
481 return false;
482 std::vector<OutputSectionBase<ELFT> *> Secs =
483 findSections(*Cmd, *OutputSections);
484 if (!Secs.empty())
485 return false;
486 for (const std::unique_ptr<BaseCommand> &I : Cmd->Commands)
487 if (!isa<InputSectionDescription>(I.get()))
488 return false;
489 return true;
490 });
491 Opt.Commands.erase(Pos, Opt.Commands.end());
492
Rafael Espindola9546fff2016-09-22 14:40:50 +0000493 // If the output section contains only symbol assignments, create a
494 // corresponding output section. The bfd linker seems to only create them if
495 // '.' is assigned to, but creating these section should not have any bad
496 // consequeces and gives us a section to put the symbol in.
497 uintX_t Flags = SHF_ALLOC;
498 uint32_t Type = 0;
499 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
500 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
501 if (!Cmd)
502 continue;
503 std::vector<OutputSectionBase<ELFT> *> Secs =
504 findSections(*Cmd, *OutputSections);
505 if (!Secs.empty()) {
506 Flags = Secs[0]->getFlags();
507 Type = Secs[0]->getType();
508 continue;
509 }
510
511 auto *OutSec = new OutputSection<ELFT>(Cmd->Name, Type, Flags);
512 Out<ELFT>::Pool.emplace_back(OutSec);
513 OutputSections->push_back(OutSec);
514 }
515}
516
Rafael Espindola15c57952016-09-22 18:05:49 +0000517// When placing orphan sections, we want to place them after symbol assignments
518// so that an orphan after
519// begin_foo = .;
520// foo : { *(foo) }
521// end_foo = .;
522// doesn't break the intended meaning of the begin/end symbols.
523// We don't want to go over sections since Writer<ELFT>::sortSections is the
524// one in charge of deciding the order of the sections.
525// We don't want to go over alignments, since doing so in
526// rx_sec : { *(rx_sec) }
527// . = ALIGN(0x1000);
528// /* The RW PT_LOAD starts here*/
529// rw_sec : { *(rw_sec) }
530// would mean that the RW PT_LOAD would become unaligned.
531static bool shouldSkip(const BaseCommand &Cmd) {
532 if (isa<OutputSectionCommand>(Cmd))
533 return false;
534 const auto *Assign = dyn_cast<SymbolAssignment>(&Cmd);
535 if (!Assign)
536 return true;
537 return Assign->Name != ".";
538}
539
Rafael Espindola9546fff2016-09-22 14:40:50 +0000540template <class ELFT> void LinkerScript<ELFT>::assignAddresses() {
George Rimar652852c2016-04-16 10:10:32 +0000541 // Orphan sections are sections present in the input files which
Rui Ueyama7c18c282016-04-18 21:00:40 +0000542 // are not explicitly placed into the output file by the linker script.
543 // We place orphan sections at end of file.
544 // Other linkers places them using some heuristics as described in
George Rimar652852c2016-04-16 10:10:32 +0000545 // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000546
547 // The OutputSections are already in the correct order.
548 // This loops creates or moves commands as needed so that they are in the
549 // correct order.
550 int CmdIndex = 0;
Rui Ueyamae5cc6682016-08-12 00:36:56 +0000551 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
George Rimar652852c2016-04-16 10:10:32 +0000552 StringRef Name = Sec->getName();
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000553
554 // Find the last spot where we can insert a command and still get the
Rafael Espindola15c57952016-09-22 18:05:49 +0000555 // correct result.
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000556 auto CmdIter = Opt.Commands.begin() + CmdIndex;
557 auto E = Opt.Commands.end();
Rafael Espindola15c57952016-09-22 18:05:49 +0000558 while (CmdIter != E && shouldSkip(**CmdIter)) {
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000559 ++CmdIter;
560 ++CmdIndex;
561 }
562
563 auto Pos =
564 std::find_if(CmdIter, E, [&](const std::unique_ptr<BaseCommand> &Base) {
565 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
566 return Cmd && Cmd->Name == Name;
567 });
568 if (Pos == E) {
569 Opt.Commands.insert(CmdIter,
570 llvm::make_unique<OutputSectionCommand>(Name));
Rafael Espindola15c57952016-09-22 18:05:49 +0000571 ++CmdIndex;
572 continue;
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000573 }
Rafael Espindola15c57952016-09-22 18:05:49 +0000574
575 // Continue from where we found it.
576 CmdIndex = (Pos - Opt.Commands.begin()) + 1;
577 continue;
George Rimar652852c2016-04-16 10:10:32 +0000578 }
George Rimar652852c2016-04-16 10:10:32 +0000579
Rui Ueyama7c18c282016-04-18 21:00:40 +0000580 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rui Ueyama4f7500b2016-08-12 04:00:22 +0000581 Dot = getHeaderSize();
George Rimar652852c2016-04-16 10:10:32 +0000582
George Rimar076fe152016-07-21 06:43:01 +0000583 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
584 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
Rui Ueyama8d083e62016-07-29 05:48:39 +0000585 if (Cmd->Name == ".") {
586 Dot = Cmd->Expression(Dot);
587 } else if (Cmd->Sym) {
588 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(Dot);
589 }
George Rimar652852c2016-04-16 10:10:32 +0000590 continue;
591 }
592
George Rimareefa7582016-08-04 09:29:31 +0000593 if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
594 Cmd->Expression(Dot);
595 continue;
596 }
597
George Rimar076fe152016-07-21 06:43:01 +0000598 auto *Cmd = cast<OutputSectionCommand>(Base.get());
George Rimar652852c2016-04-16 10:10:32 +0000599
Rafael Espindolad3190792016-09-16 15:10:23 +0000600 if (Cmd->AddrExpr)
601 Dot = Cmd->AddrExpr(Dot);
George Rimar58e5c4d2016-07-25 08:29:46 +0000602
Rafael Espindolad3190792016-09-16 15:10:23 +0000603 assignOffsets(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000604 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000605
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000606 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
607 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
608 if (Sec->getFlags() & SHF_ALLOC)
609 MinVA = std::min(MinVA, Sec->getVA());
610 else
Rafael Espindolad3190792016-09-16 15:10:23 +0000611 Sec->setVA(0);
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000612 }
613
Rafael Espindola0d4b6d52016-09-22 16:47:21 +0000614 uintX_t HeaderSize = getHeaderSize();
Rafael Espindola4ec013a2016-09-15 21:22:11 +0000615 if (HeaderSize > MinVA)
616 fatal("Not enough space for ELF and program headers");
617
Rafael Espindola64c32d62016-07-07 14:28:47 +0000618 // ELF and Program headers need to be right before the first section in
George Rimarb91e7112016-07-19 07:42:07 +0000619 // memory. Set their addresses accordingly.
Rafael Espindola4ec013a2016-09-15 21:22:11 +0000620 MinVA = alignDown(MinVA - HeaderSize, Target->PageSize);
Eugene Leviant467c4d52016-07-01 10:27:36 +0000621 Out<ELFT>::ElfHeader->setVA(MinVA);
622 Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
George Rimar652852c2016-04-16 10:10:32 +0000623}
624
Rui Ueyama464daad2016-08-22 04:55:20 +0000625// Creates program headers as instructed by PHDRS linker script command.
Rui Ueyama07320e42016-04-20 20:13:41 +0000626template <class ELFT>
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000627std::vector<PhdrEntry<ELFT>> LinkerScript<ELFT>::createPhdrs() {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000628 std::vector<PhdrEntry<ELFT>> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000629
Rui Ueyama464daad2016-08-22 04:55:20 +0000630 // Process PHDRS and FILEHDR keywords because they are not
631 // real output sections and cannot be added in the following loop.
Eugene Leviantbbe38602016-07-19 09:25:43 +0000632 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000633 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
634 PhdrEntry<ELFT> &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000635
636 if (Cmd.HasFilehdr)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000637 Phdr.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000638 if (Cmd.HasPhdrs)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000639 Phdr.add(Out<ELFT>::ProgramHeaders);
Eugene Leviant56b21c82016-09-09 09:46:16 +0000640
641 if (Cmd.LMAExpr) {
642 Phdr.H.p_paddr = Cmd.LMAExpr(0);
643 Phdr.HasLMA = true;
644 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000645 }
646
Rui Ueyama464daad2016-08-22 04:55:20 +0000647 // Add output sections to program headers.
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000648 PhdrEntry<ELFT> *Load = nullptr;
649 uintX_t Flags = PF_R;
Rui Ueyama464daad2016-08-22 04:55:20 +0000650 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
Eugene Leviantbbe38602016-07-19 09:25:43 +0000651 if (!(Sec->getFlags() & SHF_ALLOC))
652 break;
653
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000654 std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName());
Eugene Leviantbbe38602016-07-19 09:25:43 +0000655 if (!PhdrIds.empty()) {
656 // Assign headers specified by linker script
657 for (size_t Id : PhdrIds) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000658 Ret[Id].add(Sec);
Eugene Leviant865bf862016-07-21 10:43:25 +0000659 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
Rafael Espindola0b113672016-07-27 14:10:56 +0000660 Ret[Id].H.p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000661 }
662 } else {
663 // If we have no load segment or flags've changed then we want new load
664 // segment.
Rafael Espindola0b113672016-07-27 14:10:56 +0000665 uintX_t NewFlags = Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000666 if (Load == nullptr || Flags != NewFlags) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000667 Load = &*Ret.emplace(Ret.end(), PT_LOAD, NewFlags);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000668 Flags = NewFlags;
669 }
Rui Ueyama18f084f2016-07-20 19:36:41 +0000670 Load->add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000671 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000672 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000673 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000674}
675
Eugene Leviantf9bc3bd2016-08-16 06:40:58 +0000676template <class ELFT> bool LinkerScript<ELFT>::ignoreInterpSection() {
677 // Ignore .interp section in case we have PHDRS specification
678 // and PT_INTERP isn't listed.
679 return !Opt.PhdrsCommands.empty() &&
680 llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
681 return Cmd.Type == PT_INTERP;
682 }) == Opt.PhdrsCommands.end();
683}
684
Eugene Leviantbbe38602016-07-19 09:25:43 +0000685template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000686ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000687 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
688 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
689 if (Cmd->Name == Name)
690 return Cmd->Filler;
691 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000692}
693
George Rimar206fffa2016-08-17 08:16:57 +0000694template <class ELFT> Expr LinkerScript<ELFT>::getLma(StringRef Name) {
George Rimar8ceadb32016-08-17 07:44:19 +0000695 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
696 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
697 if (Cmd->LmaExpr && Cmd->Name == Name)
698 return Cmd->LmaExpr;
699 return {};
700}
701
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000702// Returns the index of the given section name in linker script
703// SECTIONS commands. Sections are laid out as the same order as they
704// were in the script. If a given name did not appear in the script,
705// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000706template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000707 int I = 0;
708 for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
709 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
710 if (Cmd->Name == Name)
711 return I;
712 ++I;
713 }
714 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000715}
716
Eugene Leviantbbe38602016-07-19 09:25:43 +0000717template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
718 return !Opt.PhdrsCommands.empty();
719}
720
George Rimar9e694502016-07-29 16:18:47 +0000721template <class ELFT>
George Rimar884e7862016-09-08 08:19:13 +0000722uint64_t LinkerScript<ELFT>::getOutputSectionAddress(StringRef Name) {
George Rimar96659df2016-08-30 09:54:01 +0000723 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
724 if (Sec->getName() == Name)
725 return Sec->getVA();
726 error("undefined section " + Name);
727 return 0;
728}
729
730template <class ELFT>
George Rimar884e7862016-09-08 08:19:13 +0000731uint64_t LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
George Rimar9e694502016-07-29 16:18:47 +0000732 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
733 if (Sec->getName() == Name)
734 return Sec->getSize();
735 error("undefined section " + Name);
736 return 0;
737}
738
Eugene Leviant36fac7f2016-09-08 09:08:30 +0000739template <class ELFT>
740uint64_t LinkerScript<ELFT>::getOutputSectionAlign(StringRef Name) {
741 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
742 if (Sec->getName() == Name)
743 return Sec->getAlignment();
744 error("undefined section " + Name);
745 return 0;
746}
747
George Rimar884e7862016-09-08 08:19:13 +0000748template <class ELFT> uint64_t LinkerScript<ELFT>::getHeaderSize() {
Rafael Espindola0d4b6d52016-09-22 16:47:21 +0000749 return elf::getHeaderSize<ELFT>();
George Rimare32a3592016-08-10 07:59:34 +0000750}
751
George Rimar884e7862016-09-08 08:19:13 +0000752template <class ELFT> uint64_t LinkerScript<ELFT>::getSymbolValue(StringRef S) {
753 if (SymbolBody *B = Symtab<ELFT>::X->find(S))
754 return B->getVA<ELFT>();
755 error("symbol not found: " + S);
756 return 0;
757}
758
George Rimarf34f45f2016-09-23 13:17:23 +0000759template <class ELFT> bool LinkerScript<ELFT>::isDefined(StringRef S) {
760 return Symtab<ELFT>::X->find(S) != nullptr;
761}
762
Eugene Leviantbbe38602016-07-19 09:25:43 +0000763// Returns indices of ELF headers containing specific section, identified
764// by Name. Each index is a zero based number of ELF header listed within
765// PHDRS {} script block.
766template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000767std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000768 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
769 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000770 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000771 continue;
772
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000773 std::vector<size_t> Ret;
774 for (StringRef PhdrName : Cmd->Phdrs)
775 Ret.push_back(getPhdrIndex(PhdrName));
776 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000777 }
George Rimar31d842f2016-07-20 16:43:03 +0000778 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000779}
780
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000781template <class ELFT>
782size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
783 size_t I = 0;
784 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
785 if (Cmd.Name == PhdrName)
786 return I;
787 ++I;
788 }
789 error("section header '" + PhdrName + "' is not listed in PHDRS");
790 return 0;
791}
792
Rui Ueyama07320e42016-04-20 20:13:41 +0000793class elf::ScriptParser : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000794 typedef void (ScriptParser::*Handler)();
795
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000796public:
Rui Ueyama07320e42016-04-20 20:13:41 +0000797 ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
George Rimarf23b2322016-02-19 10:45:45 +0000798
George Rimar20b65982016-08-31 09:08:26 +0000799 void readLinkerScript();
800 void readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000801
802private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000803 void addFile(StringRef Path);
804
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000805 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000806 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000807 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000808 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000809 void readInclude();
Rui Ueyamaee592822015-10-07 00:25:09 +0000810 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000811 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000812 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000813 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000814 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000815 void readSections();
Rui Ueyama95769b42016-08-31 20:03:54 +0000816 void readVersion();
817 void readVersionScriptCommand();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000818
Rui Ueyama113cdec2016-07-24 23:05:57 +0000819 SymbolAssignment *readAssignment(StringRef Name);
George Rimarff1f29e2016-09-06 13:51:57 +0000820 std::vector<uint8_t> readFill();
Rui Ueyama10416562016-08-04 02:03:27 +0000821 OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
George Rimarff1f29e2016-09-06 13:51:57 +0000822 std::vector<uint8_t> readOutputSectionFiller(StringRef Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000823 std::vector<StringRef> readOutputSectionPhdrs();
George Rimara2496cb2016-08-30 09:46:59 +0000824 InputSectionDescription *readInputSectionDescription(StringRef Tok);
George Rimarc91930a2016-09-02 21:17:20 +0000825 Regex readFilePatterns();
George Rimar07171f22016-09-21 15:56:44 +0000826 std::vector<SectionPattern> readInputSectionsList();
George Rimara2496cb2016-08-30 09:46:59 +0000827 InputSectionDescription *readInputSectionRules(StringRef FilePattern);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000828 unsigned readPhdrType();
George Rimarbe394db2016-09-16 20:21:55 +0000829 SortSectionPolicy readSortKind();
Petr Hoseka35e39c2016-08-16 01:11:16 +0000830 SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
Eugene Leviantdb741e72016-09-07 07:08:43 +0000831 SymbolAssignment *readProvideOrAssignment(StringRef Tok, bool MakeAbsolute);
George Rimar03fc0102016-07-28 07:18:23 +0000832 void readSort();
George Rimareefa7582016-08-04 09:29:31 +0000833 Expr readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +0000834
835 Expr readExpr();
836 Expr readExpr1(Expr Lhs, int MinPrec);
837 Expr readPrimary();
838 Expr readTernary(Expr Cond);
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +0000839 Expr readParenExpr();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000840
George Rimar20b65982016-08-31 09:08:26 +0000841 // For parsing version script.
842 void readExtern(std::vector<SymbolVersion> *Globals);
Rui Ueyama95769b42016-08-31 20:03:54 +0000843 void readVersionDeclaration(StringRef VerStr);
George Rimar20b65982016-08-31 09:08:26 +0000844 void readGlobal(StringRef VerStr);
845 void readLocal();
846
Rui Ueyama07320e42016-04-20 20:13:41 +0000847 ScriptConfiguration &Opt = *ScriptConfig;
848 StringSaver Saver = {ScriptConfig->Alloc};
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000849 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000850};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000851
George Rimar20b65982016-08-31 09:08:26 +0000852void ScriptParser::readVersionScript() {
Rui Ueyama95769b42016-08-31 20:03:54 +0000853 readVersionScriptCommand();
854 if (!atEOF())
855 setError("EOF expected, but got " + next());
856}
857
858void ScriptParser::readVersionScriptCommand() {
George Rimar20b65982016-08-31 09:08:26 +0000859 if (skip("{")) {
Rui Ueyama95769b42016-08-31 20:03:54 +0000860 readVersionDeclaration("");
George Rimar20b65982016-08-31 09:08:26 +0000861 return;
862 }
863
Rui Ueyama95769b42016-08-31 20:03:54 +0000864 while (!atEOF() && !Error && peek() != "}") {
George Rimar20b65982016-08-31 09:08:26 +0000865 StringRef VerStr = next();
866 if (VerStr == "{") {
Rui Ueyama95769b42016-08-31 20:03:54 +0000867 setError("anonymous version definition is used in "
868 "combination with other version definitions");
George Rimar20b65982016-08-31 09:08:26 +0000869 return;
870 }
871 expect("{");
Rui Ueyama95769b42016-08-31 20:03:54 +0000872 readVersionDeclaration(VerStr);
George Rimar20b65982016-08-31 09:08:26 +0000873 }
874}
875
Rui Ueyama95769b42016-08-31 20:03:54 +0000876void ScriptParser::readVersion() {
877 expect("{");
878 readVersionScriptCommand();
879 expect("}");
880}
881
George Rimar20b65982016-08-31 09:08:26 +0000882void ScriptParser::readLinkerScript() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000883 while (!atEOF()) {
884 StringRef Tok = next();
Rui Ueyamaa27eecc2016-09-02 18:52:41 +0000885 if (Tok == ";")
886 continue;
887
Eugene Leviant20d03192016-09-16 15:30:47 +0000888 if (Tok == "ASSERT") {
889 Opt.Commands.emplace_back(new AssertCommand(readAssert()));
890 } else if (Tok == "ENTRY") {
Rui Ueyamaa27eecc2016-09-02 18:52:41 +0000891 readEntry();
892 } else if (Tok == "EXTERN") {
893 readExtern();
894 } else if (Tok == "GROUP" || Tok == "INPUT") {
895 readGroup();
896 } else if (Tok == "INCLUDE") {
897 readInclude();
898 } else if (Tok == "OUTPUT") {
899 readOutput();
900 } else if (Tok == "OUTPUT_ARCH") {
901 readOutputArch();
902 } else if (Tok == "OUTPUT_FORMAT") {
903 readOutputFormat();
904 } else if (Tok == "PHDRS") {
905 readPhdrs();
906 } else if (Tok == "SEARCH_DIR") {
907 readSearchDir();
908 } else if (Tok == "SECTIONS") {
909 readSections();
910 } else if (Tok == "VERSION") {
911 readVersion();
Eugene Leviantdb741e72016-09-07 07:08:43 +0000912 } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok, true)) {
Eugene Leviant20d03192016-09-16 15:30:47 +0000913 Opt.Commands.emplace_back(Cmd);
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000914 } else {
George Rimar57610422016-03-11 14:43:02 +0000915 setError("unknown directive: " + Tok);
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000916 }
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000917 }
918}
919
Rui Ueyama717677a2016-02-11 21:17:59 +0000920void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000921 if (IsUnderSysroot && S.startswith("/")) {
922 SmallString<128> Path;
923 (Config->Sysroot + S).toStringRef(Path);
924 if (sys::fs::exists(Path)) {
925 Driver->addFile(Saver.save(Path.str()));
926 return;
927 }
928 }
929
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +0000930 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +0000931 Driver->addFile(S);
932 } else if (S.startswith("=")) {
933 if (Config->Sysroot.empty())
934 Driver->addFile(S.substr(1));
935 else
936 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
937 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +0000938 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +0000939 } else if (sys::fs::exists(S)) {
940 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +0000941 } else {
942 std::string Path = findFromSearchPaths(S);
943 if (Path.empty())
George Rimar777f9632016-03-12 08:31:34 +0000944 setError("unable to find " + S);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000945 else
946 Driver->addFile(Saver.save(Path));
Rui Ueyama52a15092015-10-11 03:28:42 +0000947 }
948}
949
Rui Ueyama717677a2016-02-11 21:17:59 +0000950void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000951 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +0000952 bool Orig = Config->AsNeeded;
953 Config->AsNeeded = true;
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000954 while (!Error && !skip(")"))
George Rimarcd574a52016-09-09 14:35:36 +0000955 addFile(unquote(next()));
Rui Ueyama35da9b62015-10-11 20:59:12 +0000956 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000957}
958
Rui Ueyama717677a2016-02-11 21:17:59 +0000959void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +0000960 // -e <symbol> takes predecence over ENTRY(<symbol>).
961 expect("(");
962 StringRef Tok = next();
963 if (Config->Entry.empty())
964 Config->Entry = Tok;
965 expect(")");
966}
967
Rui Ueyama717677a2016-02-11 21:17:59 +0000968void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +0000969 expect("(");
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000970 while (!Error && !skip(")"))
971 Config->Undefined.push_back(next());
George Rimar83f406c2015-10-19 17:35:12 +0000972}
973
Rui Ueyama717677a2016-02-11 21:17:59 +0000974void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000975 expect("(");
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000976 while (!Error && !skip(")")) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000977 StringRef Tok = next();
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000978 if (Tok == "AS_NEEDED")
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000979 readAsNeeded();
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000980 else
George Rimarcd574a52016-09-09 14:35:36 +0000981 addFile(unquote(Tok));
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000982 }
983}
984
Rui Ueyama717677a2016-02-11 21:17:59 +0000985void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000986 StringRef Tok = next();
George Rimarcd574a52016-09-09 14:35:36 +0000987 auto MBOrErr = MemoryBuffer::getFile(unquote(Tok));
Rui Ueyama025d59b2016-02-02 20:27:59 +0000988 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +0000989 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000990 return;
991 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000992 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Rui Ueyamaa47ee682015-10-11 01:53:04 +0000993 StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
994 std::vector<StringRef> V = tokenize(S);
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000995 Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000996}
997
Rui Ueyama717677a2016-02-11 21:17:59 +0000998void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +0000999 // -o <file> takes predecence over OUTPUT(<file>).
1000 expect("(");
1001 StringRef Tok = next();
1002 if (Config->OutputFile.empty())
George Rimarcd574a52016-09-09 14:35:36 +00001003 Config->OutputFile = unquote(Tok);
Rui Ueyamaee592822015-10-07 00:25:09 +00001004 expect(")");
1005}
1006
Rui Ueyama717677a2016-02-11 21:17:59 +00001007void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +00001008 // Error checking only for now.
1009 expect("(");
1010 next();
1011 expect(")");
1012}
1013
Rui Ueyama717677a2016-02-11 21:17:59 +00001014void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001015 // Error checking only for now.
1016 expect("(");
1017 next();
Davide Italiano6836c612015-10-12 21:08:41 +00001018 StringRef Tok = next();
1019 if (Tok == ")")
George Rimar6c55f0e2016-09-08 08:20:30 +00001020 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +00001021 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +00001022 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001023 return;
1024 }
Davide Italiano6836c612015-10-12 21:08:41 +00001025 next();
1026 expect(",");
1027 next();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001028 expect(")");
1029}
1030
Eugene Leviantbbe38602016-07-19 09:25:43 +00001031void ScriptParser::readPhdrs() {
1032 expect("{");
1033 while (!Error && !skip("}")) {
1034 StringRef Tok = next();
Eugene Leviant56b21c82016-09-09 09:46:16 +00001035 Opt.PhdrsCommands.push_back(
1036 {Tok, PT_NULL, false, false, UINT_MAX, nullptr});
Eugene Leviantbbe38602016-07-19 09:25:43 +00001037 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
1038
1039 PhdrCmd.Type = readPhdrType();
1040 do {
1041 Tok = next();
1042 if (Tok == ";")
1043 break;
1044 if (Tok == "FILEHDR")
1045 PhdrCmd.HasFilehdr = true;
1046 else if (Tok == "PHDRS")
1047 PhdrCmd.HasPhdrs = true;
Eugene Leviant56b21c82016-09-09 09:46:16 +00001048 else if (Tok == "AT")
1049 PhdrCmd.LMAExpr = readParenExpr();
Eugene Leviant865bf862016-07-21 10:43:25 +00001050 else if (Tok == "FLAGS") {
1051 expect("(");
Rafael Espindolaeb685cd2016-08-02 22:14:57 +00001052 // Passing 0 for the value of dot is a bit of a hack. It means that
1053 // we accept expressions like ".|1".
1054 PhdrCmd.Flags = readExpr()(0);
Eugene Leviant865bf862016-07-21 10:43:25 +00001055 expect(")");
1056 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +00001057 setError("unexpected header attribute: " + Tok);
1058 } while (!Error);
1059 }
1060}
1061
Rui Ueyama717677a2016-02-11 21:17:59 +00001062void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +00001063 expect("(");
Rui Ueyama86c5fb82016-09-08 23:26:54 +00001064 StringRef Tok = next();
Rui Ueyama6c7ad132016-09-02 19:20:33 +00001065 if (!Config->Nostdlib)
George Rimarcd574a52016-09-09 14:35:36 +00001066 Config->SearchPaths.push_back(unquote(Tok));
Davide Italiano68a39a62015-10-08 17:51:41 +00001067 expect(")");
1068}
1069
Rui Ueyama717677a2016-02-11 21:17:59 +00001070void ScriptParser::readSections() {
Eugene Leviante05336ff2016-09-14 08:32:36 +00001071 Opt.HasSections = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001072 expect("{");
George Rimar652852c2016-04-16 10:10:32 +00001073 while (!Error && !skip("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +00001074 StringRef Tok = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +00001075 BaseCommand *Cmd = readProvideOrAssignment(Tok, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001076 if (!Cmd) {
1077 if (Tok == "ASSERT")
1078 Cmd = new AssertCommand(readAssert());
1079 else
1080 Cmd = readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +00001081 }
Rui Ueyama10416562016-08-04 02:03:27 +00001082 Opt.Commands.emplace_back(Cmd);
George Rimar652852c2016-04-16 10:10:32 +00001083 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001084}
1085
Rui Ueyama708019c2016-07-24 18:19:40 +00001086static int precedence(StringRef Op) {
1087 return StringSwitch<int>(Op)
George Rimarc8ccd1f2016-09-23 13:13:55 +00001088 .Case("*", 5)
1089 .Case("/", 5)
1090 .Case("+", 4)
1091 .Case("-", 4)
1092 .Case("<<", 3)
1093 .Case(">>", 3)
Rui Ueyama708019c2016-07-24 18:19:40 +00001094 .Case("<", 2)
1095 .Case(">", 2)
1096 .Case(">=", 2)
1097 .Case("<=", 2)
1098 .Case("==", 2)
1099 .Case("!=", 2)
1100 .Case("&", 1)
Rafael Espindolacc3dd622016-08-22 21:33:35 +00001101 .Case("|", 1)
Rui Ueyama708019c2016-07-24 18:19:40 +00001102 .Default(-1);
1103}
1104
George Rimarc91930a2016-09-02 21:17:20 +00001105Regex ScriptParser::readFilePatterns() {
Rui Ueyama10416562016-08-04 02:03:27 +00001106 std::vector<StringRef> V;
1107 while (!Error && !skip(")"))
1108 V.push_back(next());
George Rimarc91930a2016-09-02 21:17:20 +00001109 return compileGlobPatterns(V);
George Rimar0702c4e2016-07-29 15:32:46 +00001110}
1111
George Rimarbe394db2016-09-16 20:21:55 +00001112SortSectionPolicy ScriptParser::readSortKind() {
Rui Ueyama742c3832016-08-04 22:27:00 +00001113 if (skip("SORT") || skip("SORT_BY_NAME"))
George Rimarbe394db2016-09-16 20:21:55 +00001114 return SortSectionPolicy::Name;
Rui Ueyama742c3832016-08-04 22:27:00 +00001115 if (skip("SORT_BY_ALIGNMENT"))
George Rimarbe394db2016-09-16 20:21:55 +00001116 return SortSectionPolicy::Alignment;
George Rimar575208c2016-09-15 19:15:12 +00001117 if (skip("SORT_BY_INIT_PRIORITY"))
George Rimarbe394db2016-09-16 20:21:55 +00001118 return SortSectionPolicy::Priority;
George Rimarbe394db2016-09-16 20:21:55 +00001119 if (skip("SORT_NONE"))
Rui Ueyamab2a0abd2016-09-16 21:14:55 +00001120 return SortSectionPolicy::None;
1121 return SortSectionPolicy::Default;
George Rimarbe394db2016-09-16 20:21:55 +00001122}
1123
George Rimar395281c2016-09-16 17:42:10 +00001124// Method reads a list of sequence of excluded files and section globs given in
1125// a following form: ((EXCLUDE_FILE(file_pattern+))? section_pattern+)+
1126// Example: *(.foo.1 EXCLUDE_FILE (*a.o) .foo.2 EXCLUDE_FILE (*b.o) .foo.3)
George Rimaraf03be12016-09-17 19:17:25 +00001127// The semantics of that is next:
1128// * Include .foo.1 from every file.
1129// * Include .foo.2 from every file but a.o
1130// * Include .foo.3 from every file but b.o
George Rimar07171f22016-09-21 15:56:44 +00001131std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
1132 std::vector<SectionPattern> Ret;
George Rimar601e9892016-09-21 08:53:21 +00001133 while (!Error && peek() != ")") {
1134 Regex ExcludeFileRe;
George Rimar395281c2016-09-16 17:42:10 +00001135 if (skip("EXCLUDE_FILE")) {
George Rimar395281c2016-09-16 17:42:10 +00001136 expect("(");
1137 ExcludeFileRe = readFilePatterns();
George Rimar395281c2016-09-16 17:42:10 +00001138 }
1139
George Rimar601e9892016-09-21 08:53:21 +00001140 std::vector<StringRef> V;
1141 while (!Error && peek() != ")" && peek() != "EXCLUDE_FILE")
1142 V.push_back(next());
1143
1144 if (!V.empty())
George Rimar07171f22016-09-21 15:56:44 +00001145 Ret.push_back({std::move(ExcludeFileRe), compileGlobPatterns(V)});
George Rimar601e9892016-09-21 08:53:21 +00001146 else
1147 setError("section pattern is expected");
George Rimar395281c2016-09-16 17:42:10 +00001148 }
George Rimar07171f22016-09-21 15:56:44 +00001149 return Ret;
George Rimar395281c2016-09-16 17:42:10 +00001150}
1151
George Rimar07171f22016-09-21 15:56:44 +00001152// Section pattern grammar can have complex expressions, for example:
1153// *(SORT(.foo.* EXCLUDE_FILE (*file1.o) .bar.*) .bar.* SORT(.zed.*))
1154// Generally is a sequence of globs and excludes that may be wrapped in a SORT()
1155// commands, like: SORT(glob0) glob1 glob2 SORT(glob4)
1156// This methods handles wrapping sequences of excluded files and section globs
1157// into SORT() if that needed and reads them all.
George Rimara2496cb2016-08-30 09:46:59 +00001158InputSectionDescription *
1159ScriptParser::readInputSectionRules(StringRef FilePattern) {
George Rimarc91930a2016-09-02 21:17:20 +00001160 auto *Cmd = new InputSectionDescription(FilePattern);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001161 expect("(");
George Rimar07171f22016-09-21 15:56:44 +00001162 while (!HasError && !skip(")")) {
1163 SortSectionPolicy Outer = readSortKind();
1164 SortSectionPolicy Inner = SortSectionPolicy::Default;
1165 std::vector<SectionPattern> V;
1166 if (Outer != SortSectionPolicy::Default) {
George Rimar350ece42016-08-03 08:35:59 +00001167 expect("(");
George Rimar07171f22016-09-21 15:56:44 +00001168 Inner = readSortKind();
1169 if (Inner != SortSectionPolicy::Default) {
1170 expect("(");
1171 V = readInputSectionsList();
1172 expect(")");
1173 } else {
1174 V = readInputSectionsList();
1175 }
George Rimar350ece42016-08-03 08:35:59 +00001176 expect(")");
1177 } else {
George Rimar07171f22016-09-21 15:56:44 +00001178 V = readInputSectionsList();
George Rimar350ece42016-08-03 08:35:59 +00001179 }
George Rimar0702c4e2016-07-29 15:32:46 +00001180
George Rimar07171f22016-09-21 15:56:44 +00001181 for (SectionPattern &Pat : V) {
1182 Pat.SortInner = Inner;
1183 Pat.SortOuter = Outer;
1184 }
1185
1186 std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns));
1187 }
Rui Ueyama10416562016-08-04 02:03:27 +00001188 return Cmd;
Davide Italianoe7282792016-07-27 01:44:01 +00001189}
1190
George Rimara2496cb2016-08-30 09:46:59 +00001191InputSectionDescription *
1192ScriptParser::readInputSectionDescription(StringRef Tok) {
George Rimar06598002016-07-28 21:51:30 +00001193 // Input section wildcard can be surrounded by KEEP.
1194 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
George Rimara2496cb2016-08-30 09:46:59 +00001195 if (Tok == "KEEP") {
George Rimar06598002016-07-28 21:51:30 +00001196 expect("(");
George Rimara2496cb2016-08-30 09:46:59 +00001197 StringRef FilePattern = next();
1198 InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
George Rimar06598002016-07-28 21:51:30 +00001199 expect(")");
Rui Ueyama4dc07be2016-09-17 02:23:40 +00001200 for (SectionPattern &Pat : Cmd->SectionPatterns)
1201 Opt.KeptSections.push_back(&Pat.SectionRe);
Rui Ueyama10416562016-08-04 02:03:27 +00001202 return Cmd;
George Rimar06598002016-07-28 21:51:30 +00001203 }
George Rimara2496cb2016-08-30 09:46:59 +00001204 return readInputSectionRules(Tok);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001205}
1206
George Rimar03fc0102016-07-28 07:18:23 +00001207void ScriptParser::readSort() {
1208 expect("(");
1209 expect("CONSTRUCTORS");
1210 expect(")");
1211}
1212
George Rimareefa7582016-08-04 09:29:31 +00001213Expr ScriptParser::readAssert() {
1214 expect("(");
1215 Expr E = readExpr();
1216 expect(",");
George Rimarcd574a52016-09-09 14:35:36 +00001217 StringRef Msg = unquote(next());
George Rimareefa7582016-08-04 09:29:31 +00001218 expect(")");
1219 return [=](uint64_t Dot) {
1220 uint64_t V = E(Dot);
1221 if (!V)
1222 error(Msg);
1223 return V;
1224 };
1225}
1226
Rui Ueyama25150e82016-09-06 17:46:43 +00001227// Reads a FILL(expr) command. We handle the FILL command as an
1228// alias for =fillexp section attribute, which is different from
1229// what GNU linkers do.
1230// https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
George Rimarff1f29e2016-09-06 13:51:57 +00001231std::vector<uint8_t> ScriptParser::readFill() {
1232 expect("(");
1233 std::vector<uint8_t> V = readOutputSectionFiller(next());
1234 expect(")");
1235 expect(";");
1236 return V;
1237}
1238
Rui Ueyama10416562016-08-04 02:03:27 +00001239OutputSectionCommand *
1240ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +00001241 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
George Rimar58e5c4d2016-07-25 08:29:46 +00001242
1243 // Read an address expression.
1244 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
1245 if (peek() != ":")
1246 Cmd->AddrExpr = readExpr();
1247
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001248 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +00001249
George Rimar8ceadb32016-08-17 07:44:19 +00001250 if (skip("AT"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001251 Cmd->LmaExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001252 if (skip("ALIGN"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001253 Cmd->AlignExpr = readParenExpr();
George Rimardb24d9c2016-08-19 15:18:23 +00001254 if (skip("SUBALIGN"))
1255 Cmd->SubalignExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001256
Davide Italiano246f6812016-07-22 03:36:24 +00001257 // Parse constraints.
1258 if (skip("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001259 Cmd->Constraint = ConstraintKind::ReadOnly;
Davide Italiano246f6812016-07-22 03:36:24 +00001260 if (skip("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001261 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001262 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001263
Rui Ueyama025d59b2016-02-02 20:27:59 +00001264 while (!Error && !skip("}")) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001265 StringRef Tok = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +00001266 if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok, false))
Eugene Leviantceabe802016-08-11 07:56:43 +00001267 Cmd->Commands.emplace_back(Assignment);
George Rimarff1f29e2016-09-06 13:51:57 +00001268 else if (Tok == "FILL")
1269 Cmd->Filler = readFill();
Eugene Leviantceabe802016-08-11 07:56:43 +00001270 else if (Tok == "SORT")
George Rimar03fc0102016-07-28 07:18:23 +00001271 readSort();
George Rimara2496cb2016-08-30 09:46:59 +00001272 else if (peek() == "(")
1273 Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
Eugene Leviantceabe802016-08-11 07:56:43 +00001274 else
1275 setError("unknown command " + Tok);
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001276 }
George Rimar076fe152016-07-21 06:43:01 +00001277 Cmd->Phdrs = readOutputSectionPhdrs();
George Rimar4ebc5622016-09-23 13:29:20 +00001278
1279 if (skip("="))
1280 Cmd->Filler = readOutputSectionFiller(next());
1281 else if (peek().startswith("="))
George Rimarff1f29e2016-09-06 13:51:57 +00001282 Cmd->Filler = readOutputSectionFiller(next().drop_front());
George Rimar4ebc5622016-09-23 13:29:20 +00001283
Rui Ueyama10416562016-08-04 02:03:27 +00001284 return Cmd;
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001285}
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001286
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001287// Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
1288// https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
1289//
1290// ld.gold is not fully compatible with ld.bfd. ld.bfd handles
1291// hexstrings as blobs of arbitrary sizes, while ld.gold handles them
1292// as 32-bit big-endian values. We will do the same as ld.gold does
1293// because it's simpler than what ld.bfd does.
George Rimarff1f29e2016-09-06 13:51:57 +00001294std::vector<uint8_t> ScriptParser::readOutputSectionFiller(StringRef Tok) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001295 uint32_t V;
George Rimarff1f29e2016-09-06 13:51:57 +00001296 if (Tok.getAsInteger(0, V)) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001297 setError("invalid filler expression: " + Tok);
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001298 return {};
George Rimare2ee72b2016-02-26 14:48:31 +00001299 }
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001300 return {uint8_t(V >> 24), uint8_t(V >> 16), uint8_t(V >> 8), uint8_t(V)};
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001301}
1302
Petr Hoseka35e39c2016-08-16 01:11:16 +00001303SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
Eugene Levianta31c91b2016-07-22 07:38:40 +00001304 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +00001305 SymbolAssignment *Cmd = readAssignment(next());
Petr Hoseka35e39c2016-08-16 01:11:16 +00001306 Cmd->Provide = Provide;
Rui Ueyama174e0a12016-07-29 00:29:25 +00001307 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001308 expect(")");
1309 expect(";");
Rui Ueyama10416562016-08-04 02:03:27 +00001310 return Cmd;
Eugene Levianteda81a12016-07-12 06:39:48 +00001311}
1312
Eugene Leviantdb741e72016-09-07 07:08:43 +00001313SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok,
1314 bool MakeAbsolute) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001315 SymbolAssignment *Cmd = nullptr;
1316 if (peek() == "=" || peek() == "+=") {
1317 Cmd = readAssignment(Tok);
1318 expect(";");
1319 } else if (Tok == "PROVIDE") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001320 Cmd = readProvideHidden(true, false);
1321 } else if (Tok == "HIDDEN") {
1322 Cmd = readProvideHidden(false, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001323 } else if (Tok == "PROVIDE_HIDDEN") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001324 Cmd = readProvideHidden(true, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001325 }
Eugene Leviantdb741e72016-09-07 07:08:43 +00001326 if (Cmd && MakeAbsolute)
1327 Cmd->IsAbsolute = true;
Eugene Leviantceabe802016-08-11 07:56:43 +00001328 return Cmd;
1329}
1330
George Rimar30835ea2016-07-28 21:08:56 +00001331static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
1332 if (S == ".")
1333 return Dot;
George Rimar884e7862016-09-08 08:19:13 +00001334 return ScriptBase->getSymbolValue(S);
George Rimare32a3592016-08-10 07:59:34 +00001335}
1336
George Rimar30835ea2016-07-28 21:08:56 +00001337SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1338 StringRef Op = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +00001339 bool IsAbsolute = false;
1340 Expr E;
George Rimar30835ea2016-07-28 21:08:56 +00001341 assert(Op == "=" || Op == "+=");
Eugene Leviantdb741e72016-09-07 07:08:43 +00001342 if (skip("ABSOLUTE")) {
1343 E = readParenExpr();
1344 IsAbsolute = true;
1345 } else {
1346 E = readExpr();
1347 }
George Rimar30835ea2016-07-28 21:08:56 +00001348 if (Op == "+=")
1349 E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
Eugene Leviantdb741e72016-09-07 07:08:43 +00001350 return new SymbolAssignment(Name, E, IsAbsolute);
George Rimar30835ea2016-07-28 21:08:56 +00001351}
1352
1353// This is an operator-precedence parser to parse a linker
1354// script expression.
1355Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
1356
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001357static Expr combine(StringRef Op, Expr L, Expr R) {
1358 if (Op == "*")
1359 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1360 if (Op == "/") {
1361 return [=](uint64_t Dot) -> uint64_t {
1362 uint64_t RHS = R(Dot);
1363 if (RHS == 0) {
1364 error("division by zero");
1365 return 0;
1366 }
1367 return L(Dot) / RHS;
1368 };
1369 }
1370 if (Op == "+")
1371 return [=](uint64_t Dot) { return L(Dot) + R(Dot); };
1372 if (Op == "-")
1373 return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
George Rimarc8ccd1f2016-09-23 13:13:55 +00001374 if (Op == "<<")
1375 return [=](uint64_t Dot) { return L(Dot) << R(Dot); };
1376 if (Op == ">>")
1377 return [=](uint64_t Dot) { return L(Dot) >> R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001378 if (Op == "<")
1379 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
1380 if (Op == ">")
1381 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
1382 if (Op == ">=")
1383 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
1384 if (Op == "<=")
1385 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
1386 if (Op == "==")
1387 return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
1388 if (Op == "!=")
1389 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
1390 if (Op == "&")
1391 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
Rafael Espindolacc3dd622016-08-22 21:33:35 +00001392 if (Op == "|")
1393 return [=](uint64_t Dot) { return L(Dot) | R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001394 llvm_unreachable("invalid operator");
1395}
1396
Rui Ueyama708019c2016-07-24 18:19:40 +00001397// This is a part of the operator-precedence parser. This function
1398// assumes that the remaining token stream starts with an operator.
1399Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1400 while (!atEOF() && !Error) {
1401 // Read an operator and an expression.
1402 StringRef Op1 = peek();
1403 if (Op1 == "?")
1404 return readTernary(Lhs);
1405 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +00001406 break;
Rui Ueyama708019c2016-07-24 18:19:40 +00001407 next();
1408 Expr Rhs = readPrimary();
1409
1410 // Evaluate the remaining part of the expression first if the
1411 // next operator has greater precedence than the previous one.
1412 // For example, if we have read "+" and "3", and if the next
1413 // operator is "*", then we'll evaluate 3 * ... part first.
1414 while (!atEOF()) {
1415 StringRef Op2 = peek();
1416 if (precedence(Op2) <= precedence(Op1))
1417 break;
1418 Rhs = readExpr1(Rhs, precedence(Op2));
1419 }
1420
1421 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +00001422 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001423 return Lhs;
1424}
1425
1426uint64_t static getConstant(StringRef S) {
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001427 if (S == "COMMONPAGESIZE")
Rui Ueyama708019c2016-07-24 18:19:40 +00001428 return Target->PageSize;
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001429 if (S == "MAXPAGESIZE")
1430 return Target->MaxPageSize;
Rui Ueyama708019c2016-07-24 18:19:40 +00001431 error("unknown constant: " + S);
1432 return 0;
1433}
1434
Rui Ueyama626e0b02016-09-02 18:19:00 +00001435// Parses Tok as an integer. Returns true if successful.
1436// It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1437// and decimal numbers. Decimal numbers may have "K" (kilo) or
1438// "M" (mega) prefixes.
George Rimar9f2f7ad2016-09-02 16:01:42 +00001439static bool readInteger(StringRef Tok, uint64_t &Result) {
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001440 if (Tok.startswith("-")) {
1441 if (!readInteger(Tok.substr(1), Result))
1442 return false;
1443 Result = -Result;
1444 return true;
1445 }
George Rimar9f2f7ad2016-09-02 16:01:42 +00001446 if (Tok.startswith_lower("0x"))
1447 return !Tok.substr(2).getAsInteger(16, Result);
1448 if (Tok.endswith_lower("H"))
1449 return !Tok.drop_back().getAsInteger(16, Result);
1450
1451 int Suffix = 1;
1452 if (Tok.endswith_lower("K")) {
1453 Suffix = 1024;
1454 Tok = Tok.drop_back();
1455 } else if (Tok.endswith_lower("M")) {
1456 Suffix = 1024 * 1024;
1457 Tok = Tok.drop_back();
1458 }
1459 if (Tok.getAsInteger(10, Result))
1460 return false;
1461 Result *= Suffix;
1462 return true;
1463}
1464
Rui Ueyama708019c2016-07-24 18:19:40 +00001465Expr ScriptParser::readPrimary() {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001466 if (peek() == "(")
1467 return readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001468
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001469 StringRef Tok = next();
Rui Ueyama708019c2016-07-24 18:19:40 +00001470
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001471 if (Tok == "~") {
1472 Expr E = readPrimary();
1473 return [=](uint64_t Dot) { return ~E(Dot); };
1474 }
1475 if (Tok == "-") {
1476 Expr E = readPrimary();
1477 return [=](uint64_t Dot) { return -E(Dot); };
1478 }
1479
Rui Ueyama708019c2016-07-24 18:19:40 +00001480 // Built-in functions are parsed here.
1481 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
George Rimar96659df2016-08-30 09:54:01 +00001482 if (Tok == "ADDR") {
1483 expect("(");
1484 StringRef Name = next();
1485 expect(")");
George Rimar884e7862016-09-08 08:19:13 +00001486 return
1487 [=](uint64_t Dot) { return ScriptBase->getOutputSectionAddress(Name); };
George Rimar96659df2016-08-30 09:54:01 +00001488 }
George Rimareefa7582016-08-04 09:29:31 +00001489 if (Tok == "ASSERT")
1490 return readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001491 if (Tok == "ALIGN") {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001492 Expr E = readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001493 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1494 }
1495 if (Tok == "CONSTANT") {
1496 expect("(");
1497 StringRef Tok = next();
1498 expect(")");
1499 return [=](uint64_t Dot) { return getConstant(Tok); };
1500 }
George Rimarf34f45f2016-09-23 13:17:23 +00001501 if (Tok == "DEFINED") {
1502 expect("(");
1503 StringRef Tok = next();
1504 expect(")");
1505 return [=](uint64_t Dot) {
1506 return ScriptBase->isDefined(Tok) ? 1 : 0;
1507 };
1508 }
Rafael Espindola54c145c2016-07-28 18:16:24 +00001509 if (Tok == "SEGMENT_START") {
1510 expect("(");
1511 next();
1512 expect(",");
George Rimar8c658bf2016-09-17 18:14:56 +00001513 Expr E = readExpr();
Rafael Espindola54c145c2016-07-28 18:16:24 +00001514 expect(")");
George Rimar8c658bf2016-09-17 18:14:56 +00001515 return [=](uint64_t Dot) { return E(Dot); };
Rafael Espindola54c145c2016-07-28 18:16:24 +00001516 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001517 if (Tok == "DATA_SEGMENT_ALIGN") {
1518 expect("(");
1519 Expr E = readExpr();
1520 expect(",");
1521 readExpr();
1522 expect(")");
Rui Ueyamaf7791bb2016-07-26 19:34:10 +00001523 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001524 }
1525 if (Tok == "DATA_SEGMENT_END") {
1526 expect("(");
1527 expect(".");
1528 expect(")");
1529 return [](uint64_t Dot) { return Dot; };
1530 }
George Rimar276b4e62016-07-26 17:58:44 +00001531 // GNU linkers implements more complicated logic to handle
1532 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1533 // the next page boundary for simplicity.
1534 if (Tok == "DATA_SEGMENT_RELRO_END") {
1535 expect("(");
Rafael Espindola97bdc722016-09-14 19:14:01 +00001536 readExpr();
George Rimar276b4e62016-07-26 17:58:44 +00001537 expect(",");
1538 readExpr();
1539 expect(")");
1540 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1541 }
George Rimar9e694502016-07-29 16:18:47 +00001542 if (Tok == "SIZEOF") {
1543 expect("(");
1544 StringRef Name = next();
1545 expect(")");
George Rimar884e7862016-09-08 08:19:13 +00001546 return [=](uint64_t Dot) { return ScriptBase->getOutputSectionSize(Name); };
George Rimar9e694502016-07-29 16:18:47 +00001547 }
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001548 if (Tok == "ALIGNOF") {
1549 expect("(");
1550 StringRef Name = next();
1551 expect(")");
1552 return
1553 [=](uint64_t Dot) { return ScriptBase->getOutputSectionAlign(Name); };
1554 }
George Rimare32a3592016-08-10 07:59:34 +00001555 if (Tok == "SIZEOF_HEADERS")
George Rimar884e7862016-09-08 08:19:13 +00001556 return [=](uint64_t Dot) { return ScriptBase->getHeaderSize(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001557
George Rimar9f2f7ad2016-09-02 16:01:42 +00001558 // Tok is a literal number.
1559 uint64_t V;
1560 if (readInteger(Tok, V))
1561 return [=](uint64_t Dot) { return V; };
1562
1563 // Tok is a symbol name.
1564 if (Tok != "." && !isValidCIdentifier(Tok))
1565 setError("malformed number: " + Tok);
1566 return [=](uint64_t Dot) { return getSymbolValue(Tok, Dot); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001567}
1568
1569Expr ScriptParser::readTernary(Expr Cond) {
1570 next();
1571 Expr L = readExpr();
1572 expect(":");
1573 Expr R = readExpr();
1574 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1575}
1576
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001577Expr ScriptParser::readParenExpr() {
1578 expect("(");
1579 Expr E = readExpr();
1580 expect(")");
1581 return E;
1582}
1583
Eugene Leviantbbe38602016-07-19 09:25:43 +00001584std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1585 std::vector<StringRef> Phdrs;
1586 while (!Error && peek().startswith(":")) {
1587 StringRef Tok = next();
1588 Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
1589 if (Tok.empty()) {
1590 setError("section header name is empty");
1591 break;
1592 }
Rui Ueyama047404f2016-07-20 19:36:36 +00001593 Phdrs.push_back(Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001594 }
1595 return Phdrs;
1596}
1597
1598unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001599 StringRef Tok = next();
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001600 unsigned Ret = StringSwitch<unsigned>(Tok)
George Rimar6c55f0e2016-09-08 08:20:30 +00001601 .Case("PT_NULL", PT_NULL)
1602 .Case("PT_LOAD", PT_LOAD)
1603 .Case("PT_DYNAMIC", PT_DYNAMIC)
1604 .Case("PT_INTERP", PT_INTERP)
1605 .Case("PT_NOTE", PT_NOTE)
1606 .Case("PT_SHLIB", PT_SHLIB)
1607 .Case("PT_PHDR", PT_PHDR)
1608 .Case("PT_TLS", PT_TLS)
1609 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1610 .Case("PT_GNU_STACK", PT_GNU_STACK)
1611 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1612 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001613
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001614 if (Ret == (unsigned)-1) {
1615 setError("invalid program header type: " + Tok);
1616 return PT_NULL;
1617 }
1618 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001619}
1620
Rui Ueyama95769b42016-08-31 20:03:54 +00001621void ScriptParser::readVersionDeclaration(StringRef VerStr) {
George Rimar20b65982016-08-31 09:08:26 +00001622 // Identifiers start at 2 because 0 and 1 are reserved
1623 // for VER_NDX_LOCAL and VER_NDX_GLOBAL constants.
1624 size_t VersionId = Config->VersionDefinitions.size() + 2;
1625 Config->VersionDefinitions.push_back({VerStr, VersionId});
1626
1627 if (skip("global:") || peek() != "local:")
1628 readGlobal(VerStr);
1629 if (skip("local:"))
1630 readLocal();
1631 expect("}");
1632
1633 // Each version may have a parent version. For example, "Ver2" defined as
1634 // "Ver2 { global: foo; local: *; } Ver1;" has "Ver1" as a parent. This
1635 // version hierarchy is, probably against your instinct, purely for human; the
1636 // runtime doesn't care about them at all. In LLD, we simply skip the token.
1637 if (!VerStr.empty() && peek() != ";")
1638 next();
1639 expect(";");
1640}
1641
1642void ScriptParser::readLocal() {
1643 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1644 expect("*");
1645 expect(";");
1646}
1647
1648void ScriptParser::readExtern(std::vector<SymbolVersion> *Globals) {
George Rimarcd574a52016-09-09 14:35:36 +00001649 expect("\"C++\"");
George Rimar20b65982016-08-31 09:08:26 +00001650 expect("{");
1651
1652 for (;;) {
1653 if (peek() == "}" || Error)
1654 break;
George Rimarcd574a52016-09-09 14:35:36 +00001655 bool HasWildcard = !peek().startswith("\"") && hasWildcard(peek());
1656 Globals->push_back({unquote(next()), true, HasWildcard});
George Rimar20b65982016-08-31 09:08:26 +00001657 expect(";");
1658 }
1659
1660 expect("}");
1661 expect(";");
1662}
1663
1664void ScriptParser::readGlobal(StringRef VerStr) {
1665 std::vector<SymbolVersion> *Globals;
1666 if (VerStr.empty())
1667 Globals = &Config->VersionScriptGlobals;
1668 else
1669 Globals = &Config->VersionDefinitions.back().Globals;
1670
1671 for (;;) {
1672 if (skip("extern"))
1673 readExtern(Globals);
1674
1675 StringRef Cur = peek();
1676 if (Cur == "}" || Cur == "local:" || Error)
1677 return;
1678 next();
George Rimarcd574a52016-09-09 14:35:36 +00001679 Globals->push_back({unquote(Cur), false, hasWildcard(Cur)});
George Rimar20b65982016-08-31 09:08:26 +00001680 expect(";");
1681 }
1682}
1683
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001684static bool isUnderSysroot(StringRef Path) {
1685 if (Config->Sysroot == "")
1686 return false;
1687 for (; !Path.empty(); Path = sys::path::parent_path(Path))
1688 if (sys::fs::equivalent(Config->Sysroot, Path))
1689 return true;
1690 return false;
1691}
1692
Rui Ueyama07320e42016-04-20 20:13:41 +00001693void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001694 StringRef Path = MB.getBufferIdentifier();
George Rimar20b65982016-08-31 09:08:26 +00001695 ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).readLinkerScript();
1696}
1697
1698void elf::readVersionScript(MemoryBufferRef MB) {
1699 ScriptParser(MB.getBuffer(), false).readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001700}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001701
Rui Ueyama07320e42016-04-20 20:13:41 +00001702template class elf::LinkerScript<ELF32LE>;
1703template class elf::LinkerScript<ELF32BE>;
1704template class elf::LinkerScript<ELF64LE>;
1705template class elf::LinkerScript<ELF64BE>;