blob: feafd370fd84de873e448cee079b815a40916afd [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 Ueyamaf7c5fbb2015-09-30 17:23:26 +000011//
12//===----------------------------------------------------------------------===//
13
Rui Ueyama717677a2016-02-11 21:17:59 +000014#include "LinkerScript.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000015#include "Config.h"
16#include "Driver.h"
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +000017#include "InputSection.h"
Rui Ueyama55518e72016-10-28 20:57:25 +000018#include "Memory.h"
George Rimar652852c2016-04-16 10:10:32 +000019#include "OutputSections.h"
Adhemerval Zanellae77b5bf2016-04-06 20:59:11 +000020#include "ScriptParser.h"
Rui Ueyama93c9af42016-06-29 08:01:32 +000021#include "Strings.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000022#include "SymbolTable.h"
Rui Ueyama55518e72016-10-28 20:57:25 +000023#include "Symbols.h"
Eugene Leviant467c4d52016-07-01 10:27:36 +000024#include "Target.h"
Eugene Leviantbbe38602016-07-19 09:25:43 +000025#include "Writer.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000026#include "llvm/ADT/STLExtras.h"
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +000027#include "llvm/ADT/SmallString.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000028#include "llvm/ADT/StringRef.h"
Rui Ueyama960504b2016-04-19 18:58:11 +000029#include "llvm/ADT/StringSwitch.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000030#include "llvm/Support/Casting.h"
George Rimar652852c2016-04-16 10:10:32 +000031#include "llvm/Support/ELF.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000032#include "llvm/Support/Endian.h"
33#include "llvm/Support/ErrorHandling.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000034#include "llvm/Support/FileSystem.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000035#include "llvm/Support/MathExtras.h"
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +000036#include "llvm/Support/Path.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000037#include <algorithm>
38#include <cassert>
39#include <cstddef>
40#include <cstdint>
41#include <iterator>
42#include <limits>
43#include <memory>
44#include <string>
45#include <tuple>
46#include <vector>
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000047
48using namespace llvm;
George Rimar652852c2016-04-16 10:10:32 +000049using namespace llvm::ELF;
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +000050using namespace llvm::object;
George Rimare38cbab2016-09-26 19:22:50 +000051using namespace llvm::support::endian;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000052using namespace lld;
Rafael Espindolae0df00b2016-02-28 00:25:54 +000053using namespace lld::elf;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000054
George Rimar884e7862016-09-08 08:19:13 +000055LinkerScriptBase *elf::ScriptBase;
Rui Ueyama07320e42016-04-20 20:13:41 +000056ScriptConfiguration *elf::ScriptConfig;
Rui Ueyama717677a2016-02-11 21:17:59 +000057
George Rimar6c55f0e2016-09-08 08:20:30 +000058template <class ELFT> static void addRegular(SymbolAssignment *Cmd) {
Rafael Espindola3dabfc62016-10-31 13:14:53 +000059 uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
Rui Ueyama1bdaf3e2016-11-09 23:37:40 +000060 Symbol *Sym = Symtab<ELFT>::X->addRegular(Cmd->Name, Visibility, STT_NOTYPE,
George Rimar463984d2016-11-15 08:07:14 +000061 0, 0, STB_GLOBAL, nullptr, nullptr);
Rui Ueyama16024212016-08-11 23:22:52 +000062 Cmd->Sym = Sym->body();
Eugene Leviant20d03192016-09-16 15:30:47 +000063
64 // If we have no SECTIONS then we don't have '.' and don't call
65 // assignAddresses(). We calculate symbol value immediately in this case.
66 if (!ScriptConfig->HasSections)
67 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(0);
Eugene Leviantceabe802016-08-11 07:56:43 +000068}
69
Rui Ueyama0c70d3c2016-08-12 03:31:09 +000070template <class ELFT> static void addSynthetic(SymbolAssignment *Cmd) {
Eugene Leviantafaa9342016-11-16 09:49:39 +000071 // If we have SECTIONS block then output sections haven't been created yet.
72 const OutputSectionBase *Sec =
73 ScriptConfig->HasSections ? nullptr : Cmd->Expression.Section();
George Rimare1937bb2016-08-19 15:36:32 +000074 Symbol *Sym = Symtab<ELFT>::X->addSynthetic(
Eugene Leviantafaa9342016-11-16 09:49:39 +000075 Cmd->Name, Sec, 0, Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT);
Rui Ueyama16024212016-08-11 23:22:52 +000076 Cmd->Sym = Sym->body();
Eugene Leviantafaa9342016-11-16 09:49:39 +000077
78 // If we already know section then we can calculate symbol value immediately.
79 if (Sec)
80 cast<DefinedSynthetic<ELFT>>(Cmd->Sym)->Value =
81 Cmd->Expression(0) - Sec->Addr;
Eugene Leviantceabe802016-08-11 07:56:43 +000082}
83
Rui Ueyama22375f22016-11-25 18:51:54 +000084static bool isUnderSysroot(StringRef Path) {
85 if (Config->Sysroot == "")
86 return false;
87 for (; !Path.empty(); Path = sys::path::parent_path(Path))
88 if (sys::fs::equivalent(Config->Sysroot, Path))
89 return true;
90 return false;
91}
92
Eugene Leviantdb741e72016-09-07 07:08:43 +000093template <class ELFT> static void addSymbol(SymbolAssignment *Cmd) {
Rafael Espindola2f831dc2016-10-31 19:56:37 +000094 if (Cmd->Expression.IsAbsolute())
Eugene Leviantdb741e72016-09-07 07:08:43 +000095 addRegular<ELFT>(Cmd);
96 else
97 addSynthetic<ELFT>(Cmd);
98}
Rui Ueyama16024212016-08-11 23:22:52 +000099// If a symbol was in PROVIDE(), we need to define it only when
100// it is an undefined symbol.
101template <class ELFT> static bool shouldDefine(SymbolAssignment *Cmd) {
102 if (Cmd->Name == ".")
Eugene Leviantceabe802016-08-11 07:56:43 +0000103 return false;
Rui Ueyama16024212016-08-11 23:22:52 +0000104 if (!Cmd->Provide)
105 return true;
106 SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
107 return B && B->isUndefined();
Eugene Leviantceabe802016-08-11 07:56:43 +0000108}
109
George Rimar076fe152016-07-21 06:43:01 +0000110bool SymbolAssignment::classof(const BaseCommand *C) {
111 return C->Kind == AssignmentKind;
112}
113
114bool OutputSectionCommand::classof(const BaseCommand *C) {
115 return C->Kind == OutputSectionKind;
116}
117
George Rimareea31142016-07-21 14:26:59 +0000118bool InputSectionDescription::classof(const BaseCommand *C) {
119 return C->Kind == InputSectionKind;
120}
121
George Rimareefa7582016-08-04 09:29:31 +0000122bool AssertCommand::classof(const BaseCommand *C) {
123 return C->Kind == AssertKind;
124}
125
George Rimare38cbab2016-09-26 19:22:50 +0000126bool BytesDataCommand::classof(const BaseCommand *C) {
127 return C->Kind == BytesDataKind;
128}
129
Eugene Zelenko22886a22016-11-05 01:00:56 +0000130template <class ELFT> LinkerScript<ELFT>::LinkerScript() = default;
131template <class ELFT> LinkerScript<ELFT>::~LinkerScript() = default;
Rui Ueyamaf34d0e02016-08-12 01:24:53 +0000132
Rui Ueyamae0be2902016-11-21 02:10:12 +0000133template <class ELFT> static StringRef basename(InputSectionBase<ELFT> *S) {
134 if (S->getFile())
135 return sys::path::filename(S->getFile()->getName());
136 return "";
137}
138
Rui Ueyama07320e42016-04-20 20:13:41 +0000139template <class ELFT>
140bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) {
Rui Ueyamae0be2902016-11-21 02:10:12 +0000141 for (InputSectionDescription *ID : Opt.KeptSections)
142 if (ID->FilePat.match(basename(S)))
143 for (SectionPattern &P : ID->SectionPatterns)
144 if (P.SectionPat.match(S->Name))
145 return true;
George Rimareea31142016-07-21 14:26:59 +0000146 return false;
147}
148
George Rimar575208c2016-09-15 19:15:12 +0000149static bool comparePriority(InputSectionData *A, InputSectionData *B) {
150 return getPriority(A->Name) < getPriority(B->Name);
151}
152
Rafael Espindolac0028d32016-09-08 20:47:52 +0000153static bool compareName(InputSectionData *A, InputSectionData *B) {
Rafael Espindola042a3f22016-09-08 14:06:08 +0000154 return A->Name < B->Name;
Rui Ueyama742c3832016-08-04 22:27:00 +0000155}
George Rimar350ece42016-08-03 08:35:59 +0000156
Rafael Espindolac0028d32016-09-08 20:47:52 +0000157static bool compareAlignment(InputSectionData *A, InputSectionData *B) {
Rui Ueyama742c3832016-08-04 22:27:00 +0000158 // ">" is not a mistake. Larger alignments are placed before smaller
159 // alignments in order to reduce the amount of padding necessary.
160 // This is compatible with GNU.
161 return A->Alignment > B->Alignment;
162}
George Rimar350ece42016-08-03 08:35:59 +0000163
Rafael Espindolac0028d32016-09-08 20:47:52 +0000164static std::function<bool(InputSectionData *, InputSectionData *)>
George Rimarbe394db2016-09-16 20:21:55 +0000165getComparator(SortSectionPolicy K) {
166 switch (K) {
167 case SortSectionPolicy::Alignment:
168 return compareAlignment;
169 case SortSectionPolicy::Name:
Rafael Espindolac0028d32016-09-08 20:47:52 +0000170 return compareName;
George Rimarbe394db2016-09-16 20:21:55 +0000171 case SortSectionPolicy::Priority:
172 return comparePriority;
173 default:
174 llvm_unreachable("unknown sort policy");
175 }
Rui Ueyama742c3832016-08-04 22:27:00 +0000176}
George Rimar0702c4e2016-07-29 15:32:46 +0000177
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000178template <class ELFT>
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000179static bool matchConstraints(ArrayRef<InputSectionBase<ELFT> *> Sections,
George Rimar06ae6832016-08-12 09:07:57 +0000180 ConstraintKind Kind) {
George Rimar8f66df92016-08-12 20:38:20 +0000181 if (Kind == ConstraintKind::NoConstraint)
182 return true;
Rafael Espindolae746e522016-09-21 18:33:44 +0000183 bool IsRW = llvm::any_of(Sections, [=](InputSectionData *Sec2) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000184 auto *Sec = static_cast<InputSectionBase<ELFT> *>(Sec2);
Rafael Espindola1854a8e2016-10-26 12:36:56 +0000185 return Sec->Flags & SHF_WRITE;
George Rimar06ae6832016-08-12 09:07:57 +0000186 });
Rafael Espindolae746e522016-09-21 18:33:44 +0000187 return (IsRW && Kind == ConstraintKind::ReadWrite) ||
188 (!IsRW && Kind == ConstraintKind::ReadOnly);
George Rimar06ae6832016-08-12 09:07:57 +0000189}
190
George Rimar07171f22016-09-21 15:56:44 +0000191static void sortSections(InputSectionData **Begin, InputSectionData **End,
Rui Ueyamaee924702016-09-20 19:42:41 +0000192 SortSectionPolicy K) {
193 if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
George Rimar07171f22016-09-21 15:56:44 +0000194 std::stable_sort(Begin, End, getComparator(K));
Rui Ueyamaee924702016-09-20 19:42:41 +0000195}
196
Rafael Espindolad3190792016-09-16 15:10:23 +0000197// Compute and remember which sections the InputSectionDescription matches.
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000198template <class ELFT>
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000199void LinkerScript<ELFT>::computeInputSections(InputSectionDescription *I) {
Rui Ueyama4dc07be2016-09-17 02:23:40 +0000200 // Collects all sections that satisfy constraints of I
201 // and attach them to I.
202 for (SectionPattern &Pat : I->SectionPatterns) {
George Rimar07171f22016-09-21 15:56:44 +0000203 size_t SizeBefore = I->Sections.size();
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000204
205 for (InputSectionBase<ELFT> *S : Symtab<ELFT>::X->Sections) {
Rui Ueyamaf94efdd2016-11-20 23:15:52 +0000206 if (!S->Live || S->Assigned)
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000207 continue;
208
Rui Ueyamae0be2902016-11-21 02:10:12 +0000209 StringRef Filename = basename(S);
210 if (!I->FilePat.match(Filename) || Pat.ExcludedFilePat.match(Filename))
211 continue;
212 if (!Pat.SectionPat.match(S->Name))
213 continue;
214 I->Sections.push_back(S);
215 S->Assigned = true;
George Rimar395281c2016-09-16 17:42:10 +0000216 }
Rafael Espindolad3190792016-09-16 15:10:23 +0000217
George Rimar07171f22016-09-21 15:56:44 +0000218 // Sort sections as instructed by SORT-family commands and --sort-section
219 // option. Because SORT-family commands can be nested at most two depth
220 // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
221 // line option is respected even if a SORT command is given, the exact
222 // behavior we have here is a bit complicated. Here are the rules.
223 //
224 // 1. If two SORT commands are given, --sort-section is ignored.
225 // 2. If one SORT command is given, and if it is not SORT_NONE,
226 // --sort-section is handled as an inner SORT command.
227 // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
228 // 4. If no SORT command is given, sort according to --sort-section.
229 InputSectionData **Begin = I->Sections.data() + SizeBefore;
230 InputSectionData **End = I->Sections.data() + I->Sections.size();
231 if (Pat.SortOuter != SortSectionPolicy::None) {
232 if (Pat.SortInner == SortSectionPolicy::Default)
233 sortSections(Begin, End, Config->SortSection);
234 else
235 sortSections(Begin, End, Pat.SortInner);
236 sortSections(Begin, End, Pat.SortOuter);
237 }
Rui Ueyamaee924702016-09-20 19:42:41 +0000238 }
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000239}
240
241template <class ELFT>
242void LinkerScript<ELFT>::discard(ArrayRef<InputSectionBase<ELFT> *> V) {
243 for (InputSectionBase<ELFT> *S : V) {
244 S->Live = false;
245 reportDiscarded(S);
246 }
247}
248
George Rimar06ae6832016-08-12 09:07:57 +0000249template <class ELFT>
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000250std::vector<InputSectionBase<ELFT> *>
George Rimar06ae6832016-08-12 09:07:57 +0000251LinkerScript<ELFT>::createInputSectionList(OutputSectionCommand &OutCmd) {
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000252 std::vector<InputSectionBase<ELFT> *> Ret;
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000253
George Rimar06ae6832016-08-12 09:07:57 +0000254 for (const std::unique_ptr<BaseCommand> &Base : OutCmd.Commands) {
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000255 auto *Cmd = dyn_cast<InputSectionDescription>(Base.get());
256 if (!Cmd)
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000257 continue;
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000258 computeInputSections(Cmd);
Rafael Espindolad3190792016-09-16 15:10:23 +0000259 for (InputSectionData *S : Cmd->Sections)
260 Ret.push_back(static_cast<InputSectionBase<ELFT> *>(S));
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000261 }
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000262
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000263 return Ret;
264}
265
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000266template <class ELFT>
Rafael Espindola10897f12016-09-13 14:23:14 +0000267static SectionKey<ELFT::Is64Bits> createKey(InputSectionBase<ELFT> *C,
268 StringRef OutsecName) {
269 // When using linker script the merge rules are different.
270 // Unfortunately, linker scripts are name based. This means that expressions
271 // like *(.foo*) can refer to multiple input sections that would normally be
272 // placed in different output sections. We cannot put them in different
273 // output sections or we would produce wrong results for
274 // start = .; *(.foo.*) end = .; *(.bar)
275 // and a mapping of .foo1 and .bar1 to one section and .foo2 and .bar2 to
276 // another. The problem is that there is no way to layout those output
277 // sections such that the .foo sections are the only thing between the
278 // start and end symbols.
279
280 // An extra annoyance is that we cannot simply disable merging of the contents
281 // of SHF_MERGE sections, but our implementation requires one output section
282 // per "kind" (string or not, which size/aligment).
283 // Fortunately, creating symbols in the middle of a merge section is not
284 // supported by bfd or gold, so we can just create multiple section in that
285 // case.
Rafael Espindola10897f12016-09-13 14:23:14 +0000286 typedef typename ELFT::uint uintX_t;
Rafael Espindola1854a8e2016-10-26 12:36:56 +0000287 uintX_t Flags = C->Flags & (SHF_MERGE | SHF_STRINGS);
Rafael Espindola10897f12016-09-13 14:23:14 +0000288
289 uintX_t Alignment = 0;
290 if (isa<MergeInputSection<ELFT>>(C))
Rafael Espindola1854a8e2016-10-26 12:36:56 +0000291 Alignment = std::max<uintX_t>(C->Alignment, C->Entsize);
Rafael Espindola10897f12016-09-13 14:23:14 +0000292
293 return SectionKey<ELFT::Is64Bits>{OutsecName, /*Type*/ 0, Flags, Alignment};
294}
295
296template <class ELFT>
Eugene Leviant20d03192016-09-16 15:30:47 +0000297void LinkerScript<ELFT>::addSection(OutputSectionFactory<ELFT> &Factory,
298 InputSectionBase<ELFT> *Sec,
299 StringRef Name) {
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000300 OutputSectionBase *OutSec;
Eugene Leviant20d03192016-09-16 15:30:47 +0000301 bool IsNew;
302 std::tie(OutSec, IsNew) = Factory.create(createKey(Sec, Name), Sec);
303 if (IsNew)
304 OutputSections->push_back(OutSec);
305 OutSec->addSection(Sec);
306}
307
308template <class ELFT>
309void LinkerScript<ELFT>::processCommands(OutputSectionFactory<ELFT> &Factory) {
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000310 for (unsigned I = 0; I < Opt.Commands.size(); ++I) {
311 auto Iter = Opt.Commands.begin() + I;
312 const std::unique_ptr<BaseCommand> &Base1 = *Iter;
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000313
314 // Handle symbol assignments outside of any output section.
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000315 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base1.get())) {
316 if (shouldDefine<ELFT>(Cmd))
Rafael Espindolab0de56b2016-10-31 21:36:23 +0000317 addSymbol<ELFT>(Cmd);
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000318 continue;
319 }
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000320
Eugene Leviant20d03192016-09-16 15:30:47 +0000321 if (auto *Cmd = dyn_cast<AssertCommand>(Base1.get())) {
322 // If we don't have SECTIONS then output sections have already been
George Rimar194470cd2016-09-17 19:21:05 +0000323 // created by Writer<ELFT>. The LinkerScript<ELFT>::assignAddresses
Eugene Leviant20d03192016-09-16 15:30:47 +0000324 // will not be called, so ASSERT should be evaluated now.
325 if (!Opt.HasSections)
326 Cmd->Expression(0);
327 continue;
328 }
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000329
Eugene Leviantceabe802016-08-11 07:56:43 +0000330 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000331 std::vector<InputSectionBase<ELFT> *> V = createInputSectionList(*Cmd);
332
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000333 // The output section name `/DISCARD/' is special.
334 // Any input section assigned to it is discarded.
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000335 if (Cmd->Name == "/DISCARD/") {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000336 discard(V);
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000337 continue;
338 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000339
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000340 // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive
341 // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input
342 // sections satisfy a given constraint. If not, a directive is handled
343 // as if it wasn't present from the beginning.
344 //
345 // Because we'll iterate over Commands many more times, the easiest
346 // way to "make it as if it wasn't present" is to just remove it.
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000347 if (!matchConstraints<ELFT>(V, Cmd->Constraint)) {
348 for (InputSectionBase<ELFT> *S : V)
Rui Ueyamaf94efdd2016-11-20 23:15:52 +0000349 S->Assigned = false;
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000350 Opt.Commands.erase(Iter);
George Rimardfbbbc82016-09-17 09:50:10 +0000351 --I;
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000352 continue;
353 }
354
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000355 // A directive may contain symbol definitions like this:
356 // ".foo : { ...; bar = .; }". Handle them.
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000357 for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
358 if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base.get()))
359 if (shouldDefine<ELFT>(OutCmd))
360 addSymbol<ELFT>(OutCmd);
361
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000362 // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign
363 // is given, input sections are aligned to that value, whether the
364 // given value is larger or smaller than the original section alignment.
365 if (Cmd->SubalignExpr) {
366 uint32_t Subalign = Cmd->SubalignExpr(0);
367 for (InputSectionBase<ELFT> *S : V)
368 S->Alignment = Subalign;
George Rimardb24d9c2016-08-19 15:18:23 +0000369 }
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000370
371 // Add input sections to an output section.
372 for (InputSectionBase<ELFT> *S : V)
373 addSection(Factory, S, Cmd->Name);
Eugene Leviantceabe802016-08-11 07:56:43 +0000374 }
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000375 }
Eugene Leviant20d03192016-09-16 15:30:47 +0000376}
Eugene Leviante63d81b2016-07-20 14:43:20 +0000377
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000378// Add sections that didn't match any sections command.
Eugene Leviant20d03192016-09-16 15:30:47 +0000379template <class ELFT>
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000380void LinkerScript<ELFT>::addOrphanSections(OutputSectionFactory<ELFT> &Factory) {
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000381 for (InputSectionBase<ELFT> *S : Symtab<ELFT>::X->Sections)
Rafael Espindola8f9026b2016-11-08 18:23:02 +0000382 if (S->Live && !S->OutSec)
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000383 addSection(Factory, S, getOutputSectionName(S->Name));
Eugene Leviante63d81b2016-07-20 14:43:20 +0000384}
385
Eugene Leviantdb741e72016-09-07 07:08:43 +0000386// Sets value of a section-defined symbol. Two kinds of
387// symbols are processed: synthetic symbols, whose value
388// is an offset from beginning of section and regular
389// symbols whose value is absolute.
390template <class ELFT>
Eugene Leviantafaa9342016-11-16 09:49:39 +0000391static void assignSectionSymbol(SymbolAssignment *Cmd,
Rafael Espindola498ed712016-10-31 14:44:41 +0000392 typename ELFT::uint Value) {
Eugene Leviantdb741e72016-09-07 07:08:43 +0000393 if (!Cmd->Sym)
394 return;
395
396 if (auto *Body = dyn_cast<DefinedSynthetic<ELFT>>(Cmd->Sym)) {
Eugene Leviantafaa9342016-11-16 09:49:39 +0000397 Body->Section = Cmd->Expression.Section();
398 Body->Value = Cmd->Expression(Value) - Body->Section->Addr;
Eugene Leviantdb741e72016-09-07 07:08:43 +0000399 return;
400 }
401 auto *Body = cast<DefinedRegular<ELFT>>(Cmd->Sym);
Rafael Espindola498ed712016-10-31 14:44:41 +0000402 Body->Value = Cmd->Expression(Value);
Eugene Leviantdb741e72016-09-07 07:08:43 +0000403}
404
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000405template <class ELFT> static bool isTbss(OutputSectionBase *Sec) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000406 return (Sec->Flags & SHF_TLS) && Sec->Type == SHT_NOBITS;
Rafael Espindolaa940e532016-09-22 12:35:44 +0000407}
408
Rafael Espindolad3190792016-09-16 15:10:23 +0000409template <class ELFT> void LinkerScript<ELFT>::output(InputSection<ELFT> *S) {
410 if (!AlreadyOutputIS.insert(S).second)
411 return;
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000412 bool IsTbss = isTbss<ELFT>(CurOutSec);
Eugene Leviant20889c52016-08-31 08:13:33 +0000413
Rafael Espindolad3190792016-09-16 15:10:23 +0000414 uintX_t Pos = IsTbss ? Dot + ThreadBssOffset : Dot;
415 Pos = alignTo(Pos, S->Alignment);
Rafael Espindola04a2e342016-11-09 01:42:41 +0000416 S->OutSecOff = Pos - CurOutSec->Addr;
Rafael Espindolad3190792016-09-16 15:10:23 +0000417 Pos += S->getSize();
418
419 // Update output section size after adding each section. This is so that
420 // SIZEOF works correctly in the case below:
421 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
Rafael Espindola04a2e342016-11-09 01:42:41 +0000422 CurOutSec->Size = Pos - CurOutSec->Addr;
Rafael Espindolad3190792016-09-16 15:10:23 +0000423
Rafael Espindola7252ae52016-09-22 12:00:08 +0000424 if (IsTbss)
425 ThreadBssOffset = Pos - Dot;
426 else
Rafael Espindolad3190792016-09-16 15:10:23 +0000427 Dot = Pos;
428}
429
430template <class ELFT> void LinkerScript<ELFT>::flush() {
Rafael Espindola65499b92016-09-23 20:10:47 +0000431 if (!CurOutSec || !AlreadyOutputOS.insert(CurOutSec).second)
432 return;
433 if (auto *OutSec = dyn_cast<OutputSection<ELFT>>(CurOutSec)) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000434 for (InputSection<ELFT> *I : OutSec->Sections)
435 output(I);
Rafael Espindola65499b92016-09-23 20:10:47 +0000436 } else {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000437 Dot += CurOutSec->Size;
Eugene Leviant20889c52016-08-31 08:13:33 +0000438 }
439}
440
441template <class ELFT>
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000442void LinkerScript<ELFT>::switchTo(OutputSectionBase *Sec) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000443 if (CurOutSec == Sec)
444 return;
445 if (AlreadyOutputOS.count(Sec))
446 return;
447
448 flush();
449 CurOutSec = Sec;
450
Rafael Espindola04a2e342016-11-09 01:42:41 +0000451 Dot = alignTo(Dot, CurOutSec->Addralign);
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000452 CurOutSec->Addr = isTbss<ELFT>(CurOutSec) ? Dot + ThreadBssOffset : Dot;
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000453
454 // If neither AT nor AT> is specified for an allocatable section, the linker
455 // will set the LMA such that the difference between VMA and LMA for the
456 // section is the same as the preceding output section in the same region
457 // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
458 CurOutSec->setLMAOffset(LMAOffset);
Rafael Espindolad3190792016-09-16 15:10:23 +0000459}
460
461template <class ELFT> void LinkerScript<ELFT>::process(BaseCommand &Base) {
George Rimare38cbab2016-09-26 19:22:50 +0000462 // This handles the assignments to symbol or to a location counter (.)
Rafael Espindolad3190792016-09-16 15:10:23 +0000463 if (auto *AssignCmd = dyn_cast<SymbolAssignment>(&Base)) {
464 if (AssignCmd->Name == ".") {
465 // Update to location counter means update to section size.
466 Dot = AssignCmd->Expression(Dot);
Rafael Espindola04a2e342016-11-09 01:42:41 +0000467 CurOutSec->Size = Dot - CurOutSec->Addr;
Rafael Espindolad3190792016-09-16 15:10:23 +0000468 return;
469 }
Eugene Leviantafaa9342016-11-16 09:49:39 +0000470 assignSectionSymbol<ELFT>(AssignCmd, Dot);
Eugene Leviantceabe802016-08-11 07:56:43 +0000471 return;
Rui Ueyama2de509c2016-08-12 00:55:08 +0000472 }
George Rimare38cbab2016-09-26 19:22:50 +0000473
474 // Handle BYTE(), SHORT(), LONG(), or QUAD().
475 if (auto *DataCmd = dyn_cast<BytesDataCommand>(&Base)) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000476 DataCmd->Offset = Dot - CurOutSec->Addr;
George Rimare38cbab2016-09-26 19:22:50 +0000477 Dot += DataCmd->Size;
Rafael Espindola04a2e342016-11-09 01:42:41 +0000478 CurOutSec->Size = Dot - CurOutSec->Addr;
George Rimare38cbab2016-09-26 19:22:50 +0000479 return;
480 }
481
Meador Ingeb2d99d62016-11-22 18:01:50 +0000482 if (auto *AssertCmd = dyn_cast<AssertCommand>(&Base)) {
483 AssertCmd->Expression(Dot);
484 return;
485 }
486
George Rimare38cbab2016-09-26 19:22:50 +0000487 // It handles single input section description command,
488 // calculates and assigns the offsets for each section and also
489 // updates the output section size.
Rafael Espindolad3190792016-09-16 15:10:23 +0000490 auto &ICmd = cast<InputSectionDescription>(Base);
491 for (InputSectionData *ID : ICmd.Sections) {
492 auto *IB = static_cast<InputSectionBase<ELFT> *>(ID);
493 switchTo(IB->OutSec);
494 if (auto *I = dyn_cast<InputSection<ELFT>>(IB))
495 output(I);
Rafael Espindola65499b92016-09-23 20:10:47 +0000496 else
497 flush();
Eugene Leviantceabe802016-08-11 07:56:43 +0000498 }
499}
500
George Rimar8f66df92016-08-12 20:38:20 +0000501template <class ELFT>
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000502static std::vector<OutputSectionBase *>
503findSections(StringRef Name, const std::vector<OutputSectionBase *> &Sections) {
504 std::vector<OutputSectionBase *> Ret;
505 for (OutputSectionBase *Sec : Sections)
Eugene Leviant92577642016-10-10 11:23:12 +0000506 if (Sec->getName() == Name)
George Rimara14b13d2016-09-07 10:46:07 +0000507 Ret.push_back(Sec);
508 return Ret;
George Rimar8f66df92016-08-12 20:38:20 +0000509}
510
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000511// This function assigns offsets to input sections and an output section
512// for a single sections command (e.g. ".text { *(.text); }").
Rafael Espindolad3190792016-09-16 15:10:23 +0000513template <class ELFT>
514void LinkerScript<ELFT>::assignOffsets(OutputSectionCommand *Cmd) {
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000515 if (Cmd->LMAExpr)
516 LMAOffset = Cmd->LMAExpr(Dot) - Dot;
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000517 std::vector<OutputSectionBase *> Sections =
518 findSections<ELFT>(Cmd->Name, *OutputSections);
Rafael Espindolad3190792016-09-16 15:10:23 +0000519 if (Sections.empty())
520 return;
521 switchTo(Sections[0]);
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000522
Rafael Espindolad3190792016-09-16 15:10:23 +0000523 // Find the last section output location. We will output orphan sections
524 // there so that end symbols point to the correct location.
525 auto E = std::find_if(Cmd->Commands.rbegin(), Cmd->Commands.rend(),
526 [](const std::unique_ptr<BaseCommand> &Cmd) {
527 return !isa<SymbolAssignment>(*Cmd);
528 })
529 .base();
530 for (auto I = Cmd->Commands.begin(); I != E; ++I)
531 process(**I);
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000532 for (OutputSectionBase *Base : Sections)
Rafael Espindolad3190792016-09-16 15:10:23 +0000533 switchTo(Base);
Rafael Espindola65499b92016-09-23 20:10:47 +0000534 flush();
George Rimarb31dd372016-09-19 13:27:31 +0000535 std::for_each(E, Cmd->Commands.end(),
536 [this](std::unique_ptr<BaseCommand> &B) { process(*B.get()); });
Rafael Espindolad3190792016-09-16 15:10:23 +0000537}
538
Rafael Espindola07fe6122016-11-14 14:23:35 +0000539template <class ELFT> void LinkerScript<ELFT>::removeEmptyCommands() {
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000540 // It is common practice to use very generic linker scripts. So for any
541 // given run some of the output sections in the script will be empty.
542 // We could create corresponding empty output sections, but that would
543 // clutter the output.
544 // We instead remove trivially empty sections. The bfd linker seems even
545 // more aggressive at removing them.
546 auto Pos = std::remove_if(
547 Opt.Commands.begin(), Opt.Commands.end(),
548 [&](const std::unique_ptr<BaseCommand> &Base) {
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000549 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
550 return findSections<ELFT>(Cmd->Name, *OutputSections).empty();
551 return false;
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000552 });
553 Opt.Commands.erase(Pos, Opt.Commands.end());
Rafael Espindola07fe6122016-11-14 14:23:35 +0000554}
555
Rafael Espindola6a537372016-11-14 14:33:49 +0000556static bool isAllSectionDescription(const OutputSectionCommand &Cmd) {
557 for (const std::unique_ptr<BaseCommand> &I : Cmd.Commands)
558 if (!isa<InputSectionDescription>(*I))
559 return false;
560 return true;
561}
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000562
Rafael Espindola6a537372016-11-14 14:33:49 +0000563template <class ELFT> void LinkerScript<ELFT>::adjustSectionsBeforeSorting() {
Rafael Espindola9546fff2016-09-22 14:40:50 +0000564 // If the output section contains only symbol assignments, create a
565 // corresponding output section. The bfd linker seems to only create them if
566 // '.' is assigned to, but creating these section should not have any bad
567 // consequeces and gives us a section to put the symbol in.
568 uintX_t Flags = SHF_ALLOC;
Rafael Espindolaf93b8c22016-11-26 06:55:35 +0000569 uint32_t Type = SHT_NOBITS;
Rafael Espindola9546fff2016-09-22 14:40:50 +0000570 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
571 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
572 if (!Cmd)
573 continue;
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000574 std::vector<OutputSectionBase *> Secs =
575 findSections<ELFT>(Cmd->Name, *OutputSections);
Rafael Espindola9546fff2016-09-22 14:40:50 +0000576 if (!Secs.empty()) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000577 Flags = Secs[0]->Flags;
578 Type = Secs[0]->Type;
Rafael Espindola9546fff2016-09-22 14:40:50 +0000579 continue;
580 }
581
Rafael Espindola6a537372016-11-14 14:33:49 +0000582 if (isAllSectionDescription(*Cmd))
583 continue;
584
Rui Ueyama95642b92016-11-01 23:09:07 +0000585 auto *OutSec = make<OutputSection<ELFT>>(Cmd->Name, Type, Flags);
Rafael Espindola9546fff2016-09-22 14:40:50 +0000586 OutputSections->push_back(OutSec);
587 }
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000588}
589
590template <class ELFT> void LinkerScript<ELFT>::adjustSectionsAfterSorting() {
591 placeOrphanSections();
592
593 // If output section command doesn't specify any segments,
594 // and we haven't previously assigned any section to segment,
595 // then we simply assign section to the very first load segment.
596 // Below is an example of such linker script:
597 // PHDRS { seg PT_LOAD; }
598 // SECTIONS { .aaa : { *(.aaa) } }
599 std::vector<StringRef> DefPhdrs;
600 auto FirstPtLoad =
601 std::find_if(Opt.PhdrsCommands.begin(), Opt.PhdrsCommands.end(),
602 [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; });
603 if (FirstPtLoad != Opt.PhdrsCommands.end())
604 DefPhdrs.push_back(FirstPtLoad->Name);
605
606 // Walk the commands and propagate the program headers to commands that don't
607 // explicitly specify them.
608 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
609 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
610 if (!Cmd)
611 continue;
612 if (Cmd->Phdrs.empty())
613 Cmd->Phdrs = DefPhdrs;
614 else
615 DefPhdrs = Cmd->Phdrs;
616 }
Rafael Espindola6a537372016-11-14 14:33:49 +0000617
618 removeEmptyCommands();
Rafael Espindola9546fff2016-09-22 14:40:50 +0000619}
620
Rafael Espindola15c57952016-09-22 18:05:49 +0000621// When placing orphan sections, we want to place them after symbol assignments
622// so that an orphan after
623// begin_foo = .;
624// foo : { *(foo) }
625// end_foo = .;
626// doesn't break the intended meaning of the begin/end symbols.
627// We don't want to go over sections since Writer<ELFT>::sortSections is the
628// one in charge of deciding the order of the sections.
629// We don't want to go over alignments, since doing so in
630// rx_sec : { *(rx_sec) }
631// . = ALIGN(0x1000);
632// /* The RW PT_LOAD starts here*/
633// rw_sec : { *(rw_sec) }
634// would mean that the RW PT_LOAD would become unaligned.
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000635static bool shouldSkip(const BaseCommand &Cmd) {
Rafael Espindola15c57952016-09-22 18:05:49 +0000636 if (isa<OutputSectionCommand>(Cmd))
637 return false;
638 const auto *Assign = dyn_cast<SymbolAssignment>(&Cmd);
639 if (!Assign)
640 return true;
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000641 return Assign->Name != ".";
Rafael Espindola15c57952016-09-22 18:05:49 +0000642}
643
Rafael Espindola337f9032016-11-14 14:13:32 +0000644// Orphan sections are sections present in the input files which are not
645// explicitly placed into the output file by the linker script. This just
646// places them in the order already decided in OutputSections.
Rafael Espindola6d91fce2016-09-29 18:50:34 +0000647template <class ELFT>
Rafael Espindola337f9032016-11-14 14:13:32 +0000648void LinkerScript<ELFT>::placeOrphanSections() {
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000649 // The OutputSections are already in the correct order.
650 // This loops creates or moves commands as needed so that they are in the
651 // correct order.
652 int CmdIndex = 0;
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000653
654 // As a horrible special case, skip the first . assignment if it is before any
655 // section. We do this because it is common to set a load address by starting
656 // the script with ". = 0xabcd" and the expectation is that every section is
657 // after that.
658 auto FirstSectionOrDotAssignment =
659 std::find_if(Opt.Commands.begin(), Opt.Commands.end(),
660 [](const std::unique_ptr<BaseCommand> &Cmd) {
661 if (isa<OutputSectionCommand>(*Cmd))
662 return true;
663 const auto *Assign = dyn_cast<SymbolAssignment>(Cmd.get());
664 if (!Assign)
665 return false;
666 return Assign->Name == ".";
667 });
668 if (FirstSectionOrDotAssignment != Opt.Commands.end()) {
669 CmdIndex = FirstSectionOrDotAssignment - Opt.Commands.begin();
670 if (isa<SymbolAssignment>(**FirstSectionOrDotAssignment))
671 ++CmdIndex;
672 }
673
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000674 for (OutputSectionBase *Sec : *OutputSections) {
George Rimar652852c2016-04-16 10:10:32 +0000675 StringRef Name = Sec->getName();
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000676
677 // Find the last spot where we can insert a command and still get the
Rafael Espindola15c57952016-09-22 18:05:49 +0000678 // correct result.
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000679 auto CmdIter = Opt.Commands.begin() + CmdIndex;
680 auto E = Opt.Commands.end();
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000681 while (CmdIter != E && shouldSkip(**CmdIter)) {
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000682 ++CmdIter;
683 ++CmdIndex;
684 }
685
686 auto Pos =
687 std::find_if(CmdIter, E, [&](const std::unique_ptr<BaseCommand> &Base) {
688 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
689 return Cmd && Cmd->Name == Name;
690 });
691 if (Pos == E) {
692 Opt.Commands.insert(CmdIter,
693 llvm::make_unique<OutputSectionCommand>(Name));
Rafael Espindola15c57952016-09-22 18:05:49 +0000694 ++CmdIndex;
695 continue;
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000696 }
Rafael Espindola15c57952016-09-22 18:05:49 +0000697
698 // Continue from where we found it.
699 CmdIndex = (Pos - Opt.Commands.begin()) + 1;
George Rimar652852c2016-04-16 10:10:32 +0000700 }
Rafael Espindola337f9032016-11-14 14:13:32 +0000701}
702
703template <class ELFT>
704void LinkerScript<ELFT>::assignAddresses(std::vector<PhdrEntry<ELFT>> &Phdrs) {
Rui Ueyama7c18c282016-04-18 21:00:40 +0000705 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rafael Espindolabe607332016-09-30 00:16:11 +0000706 Dot = 0;
George Rimar652852c2016-04-16 10:10:32 +0000707
George Rimar076fe152016-07-21 06:43:01 +0000708 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
709 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
Rui Ueyama8d083e62016-07-29 05:48:39 +0000710 if (Cmd->Name == ".") {
711 Dot = Cmd->Expression(Dot);
712 } else if (Cmd->Sym) {
Eugene Leviantafaa9342016-11-16 09:49:39 +0000713 assignSectionSymbol<ELFT>(Cmd, Dot);
Rui Ueyama8d083e62016-07-29 05:48:39 +0000714 }
George Rimar652852c2016-04-16 10:10:32 +0000715 continue;
716 }
717
George Rimareefa7582016-08-04 09:29:31 +0000718 if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
719 Cmd->Expression(Dot);
720 continue;
721 }
722
George Rimar076fe152016-07-21 06:43:01 +0000723 auto *Cmd = cast<OutputSectionCommand>(Base.get());
Rafael Espindolad3190792016-09-16 15:10:23 +0000724 if (Cmd->AddrExpr)
725 Dot = Cmd->AddrExpr(Dot);
Rafael Espindolad3190792016-09-16 15:10:23 +0000726 assignOffsets(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000727 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000728
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000729 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000730 for (OutputSectionBase *Sec : *OutputSections) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000731 if (Sec->Flags & SHF_ALLOC)
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000732 MinVA = std::min<uint64_t>(MinVA, Sec->Addr);
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000733 else
Rafael Espindola04a2e342016-11-09 01:42:41 +0000734 Sec->Addr = 0;
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000735 }
736
Rafael Espindola0d4b6d52016-09-22 16:47:21 +0000737 uintX_t HeaderSize = getHeaderSize();
Rafael Espindola6d91fce2016-09-29 18:50:34 +0000738 auto FirstPTLoad =
739 std::find_if(Phdrs.begin(), Phdrs.end(), [](const PhdrEntry<ELFT> &E) {
740 return E.H.p_type == PT_LOAD;
741 });
Rafael Espindolad8b81d62016-11-17 14:18:08 +0000742 if (FirstPTLoad == Phdrs.end())
743 return;
Eugene Leviantdb35fdf2016-10-20 09:39:09 +0000744
Rafael Espindola1c570072016-11-21 19:59:33 +0000745 // If the linker script doesn't have PHDRS, add ElfHeader and ProgramHeaders
746 // now that we know we have space.
747 if (HeaderSize <= MinVA && !hasPhdrsCommands()) {
Rafael Espindola6d91fce2016-09-29 18:50:34 +0000748 FirstPTLoad->First = Out<ELFT>::ElfHeader;
749 if (!FirstPTLoad->Last)
750 FirstPTLoad->Last = Out<ELFT>::ProgramHeaders;
Rafael Espindola1c570072016-11-21 19:59:33 +0000751 }
752
753 // ELF and Program headers need to be right before the first section in
754 // memory. Set their addresses accordingly.
Rafael Espindola28d5f052016-11-21 20:20:04 +0000755 MinVA = alignDown(MinVA - HeaderSize, Config->MaxPageSize);
Rafael Espindola1c570072016-11-21 19:59:33 +0000756 Out<ELFT>::ElfHeader->Addr = MinVA;
757 Out<ELFT>::ProgramHeaders->Addr = Out<ELFT>::ElfHeader->Size + MinVA;
758
759 if (!FirstPTLoad->First) {
Rui Ueyamab224c0482016-10-10 18:10:01 +0000760 // Sometimes the very first PT_LOAD segment can be empty.
Eugene Leviantcd8eaf82016-10-10 15:09:44 +0000761 // This happens if (all conditions met):
762 // - Linker script is used
763 // - First section in ELF image is not RO
764 // - Not enough space for program headers.
765 // The code below removes empty PT_LOAD segment and updates
766 // program headers size.
767 Phdrs.erase(FirstPTLoad);
Rafael Espindola04a2e342016-11-09 01:42:41 +0000768 Out<ELFT>::ProgramHeaders->Size =
769 sizeof(typename ELFT::Phdr) * Phdrs.size();
Rafael Espindola6d91fce2016-09-29 18:50:34 +0000770 }
George Rimar652852c2016-04-16 10:10:32 +0000771}
772
Rui Ueyama464daad2016-08-22 04:55:20 +0000773// Creates program headers as instructed by PHDRS linker script command.
Rui Ueyama07320e42016-04-20 20:13:41 +0000774template <class ELFT>
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000775std::vector<PhdrEntry<ELFT>> LinkerScript<ELFT>::createPhdrs() {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000776 std::vector<PhdrEntry<ELFT>> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000777
Rui Ueyama464daad2016-08-22 04:55:20 +0000778 // Process PHDRS and FILEHDR keywords because they are not
779 // real output sections and cannot be added in the following loop.
Eugene Leviantbbe38602016-07-19 09:25:43 +0000780 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000781 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
782 PhdrEntry<ELFT> &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000783
784 if (Cmd.HasFilehdr)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000785 Phdr.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000786 if (Cmd.HasPhdrs)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000787 Phdr.add(Out<ELFT>::ProgramHeaders);
Eugene Leviant56b21c82016-09-09 09:46:16 +0000788
789 if (Cmd.LMAExpr) {
790 Phdr.H.p_paddr = Cmd.LMAExpr(0);
791 Phdr.HasLMA = true;
792 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000793 }
794
Rui Ueyama464daad2016-08-22 04:55:20 +0000795 // Add output sections to program headers.
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000796 for (OutputSectionBase *Sec : *OutputSections) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000797 if (!(Sec->Flags & SHF_ALLOC))
Eugene Leviantbbe38602016-07-19 09:25:43 +0000798 break;
799
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000800 // Assign headers specified by linker script
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000801 for (size_t Id : getPhdrIndices(Sec->getName())) {
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000802 Ret[Id].add(Sec);
803 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
804 Ret[Id].H.p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000805 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000806 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000807 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000808}
809
Eugene Leviantf9bc3bd2016-08-16 06:40:58 +0000810template <class ELFT> bool LinkerScript<ELFT>::ignoreInterpSection() {
811 // Ignore .interp section in case we have PHDRS specification
812 // and PT_INTERP isn't listed.
813 return !Opt.PhdrsCommands.empty() &&
814 llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
815 return Cmd.Type == PT_INTERP;
816 }) == Opt.PhdrsCommands.end();
817}
818
Eugene Leviantbbe38602016-07-19 09:25:43 +0000819template <class ELFT>
Rui Ueyama16068ae2016-11-19 18:05:56 +0000820uint32_t LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000821 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
822 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
823 if (Cmd->Name == Name)
824 return Cmd->Filler;
Rui Ueyama16068ae2016-11-19 18:05:56 +0000825 return 0;
George Rimare2ee72b2016-02-26 14:48:31 +0000826}
827
George Rimare38cbab2016-09-26 19:22:50 +0000828template <class ELFT>
829static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) {
830 const endianness E = ELFT::TargetEndianness;
831
832 switch (Size) {
833 case 1:
834 *Buf = (uint8_t)Data;
835 break;
836 case 2:
837 write16<E>(Buf, Data);
838 break;
839 case 4:
840 write32<E>(Buf, Data);
841 break;
842 case 8:
843 write64<E>(Buf, Data);
844 break;
845 default:
846 llvm_unreachable("unsupported Size argument");
847 }
848}
849
850template <class ELFT>
851void LinkerScript<ELFT>::writeDataBytes(StringRef Name, uint8_t *Buf) {
852 int I = getSectionIndex(Name);
853 if (I == INT_MAX)
854 return;
855
Rui Ueyama6e68c5e2016-11-19 18:05:58 +0000856 auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I].get());
857 for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
858 if (auto *Data = dyn_cast<BytesDataCommand>(Base.get()))
859 writeInt<ELFT>(Buf + Data->Offset, Data->Data, Data->Size);
George Rimare38cbab2016-09-26 19:22:50 +0000860}
861
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000862template <class ELFT> bool LinkerScript<ELFT>::hasLMA(StringRef Name) {
George Rimar8ceadb32016-08-17 07:44:19 +0000863 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
864 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000865 if (Cmd->LMAExpr && Cmd->Name == Name)
866 return true;
867 return false;
George Rimar8ceadb32016-08-17 07:44:19 +0000868}
869
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000870// Returns the index of the given section name in linker script
871// SECTIONS commands. Sections are laid out as the same order as they
872// were in the script. If a given name did not appear in the script,
873// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000874template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
Rui Ueyama6e68c5e2016-11-19 18:05:58 +0000875 for (int I = 0, E = Opt.Commands.size(); I != E; ++I)
876 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I].get()))
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000877 if (Cmd->Name == Name)
878 return I;
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000879 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000880}
881
Eugene Leviantbbe38602016-07-19 09:25:43 +0000882template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
883 return !Opt.PhdrsCommands.empty();
884}
885
George Rimar9e694502016-07-29 16:18:47 +0000886template <class ELFT>
Eugene Leviantafaa9342016-11-16 09:49:39 +0000887const OutputSectionBase *LinkerScript<ELFT>::getOutputSection(StringRef Name) {
888 static OutputSectionBase FakeSec("", 0, 0);
George Rimar96659df2016-08-30 09:54:01 +0000889
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000890 for (OutputSectionBase *Sec : *OutputSections)
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000891 if (Sec->getName() == Name)
Eugene Leviantafaa9342016-11-16 09:49:39 +0000892 return Sec;
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000893 error("undefined section " + Name);
Eugene Leviantafaa9342016-11-16 09:49:39 +0000894 return &FakeSec;
Eugene Leviant36fac7f2016-09-08 09:08:30 +0000895}
896
Rui Ueyamaedf75e72016-11-17 20:27:10 +0000897// This function is essentially the same as getOutputSection(Name)->Size,
898// but it won't print out an error message if a given section is not found.
899//
900// Linker script does not create an output section if its content is empty.
901// We want to allow SIZEOF(.foo) where .foo is a section which happened to
902// be empty. That is why this function is different from getOutputSection().
903template <class ELFT>
904uint64_t LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
905 for (OutputSectionBase *Sec : *OutputSections)
906 if (Sec->getName() == Name)
907 return Sec->Size;
908 return 0;
909}
910
George Rimar884e7862016-09-08 08:19:13 +0000911template <class ELFT> uint64_t LinkerScript<ELFT>::getHeaderSize() {
Rafael Espindola0d4b6d52016-09-22 16:47:21 +0000912 return elf::getHeaderSize<ELFT>();
George Rimare32a3592016-08-10 07:59:34 +0000913}
914
George Rimar884e7862016-09-08 08:19:13 +0000915template <class ELFT> uint64_t LinkerScript<ELFT>::getSymbolValue(StringRef S) {
916 if (SymbolBody *B = Symtab<ELFT>::X->find(S))
917 return B->getVA<ELFT>();
918 error("symbol not found: " + S);
919 return 0;
920}
921
George Rimarf34f45f2016-09-23 13:17:23 +0000922template <class ELFT> bool LinkerScript<ELFT>::isDefined(StringRef S) {
923 return Symtab<ELFT>::X->find(S) != nullptr;
924}
925
Rafael Espindola2f831dc2016-10-31 19:56:37 +0000926template <class ELFT> bool LinkerScript<ELFT>::isAbsolute(StringRef S) {
927 SymbolBody *Sym = Symtab<ELFT>::X->find(S);
928 auto *DR = dyn_cast_or_null<DefinedRegular<ELFT>>(Sym);
929 return DR && !DR->Section;
930}
931
Eugene Leviantafaa9342016-11-16 09:49:39 +0000932// Gets section symbol belongs to. Symbol "." doesn't belong to any
933// specific section but isn't absolute at the same time, so we try
934// to find suitable section for it as well.
935template <class ELFT>
936const OutputSectionBase *LinkerScript<ELFT>::getSymbolSection(StringRef S) {
937 SymbolBody *Sym = Symtab<ELFT>::X->find(S);
938 if (!Sym) {
939 if (OutputSections->empty())
940 return nullptr;
941 return CurOutSec ? CurOutSec : (*OutputSections)[0];
942 }
943
944 if (auto *DR = dyn_cast_or_null<DefinedRegular<ELFT>>(Sym))
945 return DR->Section ? DR->Section->OutSec : nullptr;
946 if (auto *DS = dyn_cast_or_null<DefinedSynthetic<ELFT>>(Sym))
947 return DS->Section;
948
949 return nullptr;
950}
951
Eugene Leviantbbe38602016-07-19 09:25:43 +0000952// Returns indices of ELF headers containing specific section, identified
953// by Name. Each index is a zero based number of ELF header listed within
954// PHDRS {} script block.
955template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000956std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000957 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
958 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000959 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000960 continue;
961
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000962 std::vector<size_t> Ret;
963 for (StringRef PhdrName : Cmd->Phdrs)
964 Ret.push_back(getPhdrIndex(PhdrName));
965 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000966 }
George Rimar31d842f2016-07-20 16:43:03 +0000967 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000968}
969
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000970template <class ELFT>
971size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
972 size_t I = 0;
973 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
974 if (Cmd.Name == PhdrName)
975 return I;
976 ++I;
977 }
978 error("section header '" + PhdrName + "' is not listed in PHDRS");
979 return 0;
980}
981
Eugene Leviant03ff0162016-11-21 15:49:56 +0000982class elf::ScriptParser final : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000983 typedef void (ScriptParser::*Handler)();
984
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000985public:
Rui Ueyama22375f22016-11-25 18:51:54 +0000986 ScriptParser(MemoryBufferRef MB)
987 : ScriptParserBase(MB),
988 IsUnderSysroot(isUnderSysroot(MB.getBufferIdentifier())) {}
George Rimarf23b2322016-02-19 10:45:45 +0000989
George Rimar20b65982016-08-31 09:08:26 +0000990 void readLinkerScript();
991 void readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000992
993private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000994 void addFile(StringRef Path);
995
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000996 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000997 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000998 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000999 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001000 void readInclude();
Rui Ueyamaee592822015-10-07 00:25:09 +00001001 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +00001002 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001003 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +00001004 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +00001005 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001006 void readSections();
Rui Ueyama95769b42016-08-31 20:03:54 +00001007 void readVersion();
1008 void readVersionScriptCommand();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001009
Rui Ueyama113cdec2016-07-24 23:05:57 +00001010 SymbolAssignment *readAssignment(StringRef Name);
George Rimare38cbab2016-09-26 19:22:50 +00001011 BytesDataCommand *readBytesDataCommand(StringRef Tok);
Rui Ueyama16068ae2016-11-19 18:05:56 +00001012 uint32_t readFill();
Rui Ueyama10416562016-08-04 02:03:27 +00001013 OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
Rui Ueyama16068ae2016-11-19 18:05:56 +00001014 uint32_t readOutputSectionFiller(StringRef Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001015 std::vector<StringRef> readOutputSectionPhdrs();
George Rimara2496cb2016-08-30 09:46:59 +00001016 InputSectionDescription *readInputSectionDescription(StringRef Tok);
Eugene Leviantdb688452016-11-03 10:54:58 +00001017 StringMatcher readFilePatterns();
George Rimar07171f22016-09-21 15:56:44 +00001018 std::vector<SectionPattern> readInputSectionsList();
George Rimara2496cb2016-08-30 09:46:59 +00001019 InputSectionDescription *readInputSectionRules(StringRef FilePattern);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001020 unsigned readPhdrType();
George Rimarbe394db2016-09-16 20:21:55 +00001021 SortSectionPolicy readSortKind();
Petr Hoseka35e39c2016-08-16 01:11:16 +00001022 SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
Rafael Espindolac96da112016-11-01 11:30:45 +00001023 SymbolAssignment *readProvideOrAssignment(StringRef Tok);
George Rimar03fc0102016-07-28 07:18:23 +00001024 void readSort();
George Rimareefa7582016-08-04 09:29:31 +00001025 Expr readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001026
1027 Expr readExpr();
1028 Expr readExpr1(Expr Lhs, int MinPrec);
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001029 StringRef readParenLiteral();
Rui Ueyama708019c2016-07-24 18:19:40 +00001030 Expr readPrimary();
1031 Expr readTernary(Expr Cond);
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001032 Expr readParenExpr();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001033
George Rimar20b65982016-08-31 09:08:26 +00001034 // For parsing version script.
Rui Ueyama12450b22016-11-18 06:30:09 +00001035 std::vector<SymbolVersion> readVersionExtern();
1036 void readAnonymousDeclaration();
Rui Ueyama95769b42016-08-31 20:03:54 +00001037 void readVersionDeclaration(StringRef VerStr);
Rui Ueyama12450b22016-11-18 06:30:09 +00001038 std::vector<SymbolVersion> readSymbols();
George Rimar20b65982016-08-31 09:08:26 +00001039
Rui Ueyama07320e42016-04-20 20:13:41 +00001040 ScriptConfiguration &Opt = *ScriptConfig;
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001041 bool IsUnderSysroot;
Eugene Leviant03ff0162016-11-21 15:49:56 +00001042 std::vector<std::unique_ptr<MemoryBuffer>> OwningMBs;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001043};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001044
George Rimar20b65982016-08-31 09:08:26 +00001045void ScriptParser::readVersionScript() {
Rui Ueyama95769b42016-08-31 20:03:54 +00001046 readVersionScriptCommand();
1047 if (!atEOF())
1048 setError("EOF expected, but got " + next());
1049}
1050
1051void ScriptParser::readVersionScriptCommand() {
Rui Ueyama83043f22016-10-17 16:01:53 +00001052 if (consume("{")) {
Rui Ueyama12450b22016-11-18 06:30:09 +00001053 readAnonymousDeclaration();
George Rimar20b65982016-08-31 09:08:26 +00001054 return;
1055 }
1056
Rui Ueyama95769b42016-08-31 20:03:54 +00001057 while (!atEOF() && !Error && peek() != "}") {
George Rimar20b65982016-08-31 09:08:26 +00001058 StringRef VerStr = next();
1059 if (VerStr == "{") {
Rui Ueyama95769b42016-08-31 20:03:54 +00001060 setError("anonymous version definition is used in "
1061 "combination with other version definitions");
George Rimar20b65982016-08-31 09:08:26 +00001062 return;
1063 }
1064 expect("{");
Rui Ueyama95769b42016-08-31 20:03:54 +00001065 readVersionDeclaration(VerStr);
George Rimar20b65982016-08-31 09:08:26 +00001066 }
1067}
1068
Rui Ueyama95769b42016-08-31 20:03:54 +00001069void ScriptParser::readVersion() {
1070 expect("{");
1071 readVersionScriptCommand();
1072 expect("}");
1073}
1074
George Rimar20b65982016-08-31 09:08:26 +00001075void ScriptParser::readLinkerScript() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001076 while (!atEOF()) {
1077 StringRef Tok = next();
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001078 if (Tok == ";")
1079 continue;
1080
Eugene Leviant20d03192016-09-16 15:30:47 +00001081 if (Tok == "ASSERT") {
1082 Opt.Commands.emplace_back(new AssertCommand(readAssert()));
1083 } else if (Tok == "ENTRY") {
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001084 readEntry();
1085 } else if (Tok == "EXTERN") {
1086 readExtern();
1087 } else if (Tok == "GROUP" || Tok == "INPUT") {
1088 readGroup();
1089 } else if (Tok == "INCLUDE") {
1090 readInclude();
1091 } else if (Tok == "OUTPUT") {
1092 readOutput();
1093 } else if (Tok == "OUTPUT_ARCH") {
1094 readOutputArch();
1095 } else if (Tok == "OUTPUT_FORMAT") {
1096 readOutputFormat();
1097 } else if (Tok == "PHDRS") {
1098 readPhdrs();
1099 } else if (Tok == "SEARCH_DIR") {
1100 readSearchDir();
1101 } else if (Tok == "SECTIONS") {
1102 readSections();
1103 } else if (Tok == "VERSION") {
1104 readVersion();
Rafael Espindolac96da112016-11-01 11:30:45 +00001105 } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok)) {
Eugene Leviant20d03192016-09-16 15:30:47 +00001106 Opt.Commands.emplace_back(Cmd);
Petr Hoseke5d3ca52016-08-31 15:31:17 +00001107 } else {
George Rimar57610422016-03-11 14:43:02 +00001108 setError("unknown directive: " + Tok);
Petr Hoseke5d3ca52016-08-31 15:31:17 +00001109 }
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001110 }
1111}
1112
Rui Ueyama717677a2016-02-11 21:17:59 +00001113void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001114 if (IsUnderSysroot && S.startswith("/")) {
Justin Bogner5af16872016-10-17 06:08:48 +00001115 SmallString<128> PathData;
1116 StringRef Path = (Config->Sysroot + S).toStringRef(PathData);
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001117 if (sys::fs::exists(Path)) {
Justin Bogner5af16872016-10-17 06:08:48 +00001118 Driver->addFile(Saver.save(Path));
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001119 return;
1120 }
1121 }
1122
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +00001123 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +00001124 Driver->addFile(S);
1125 } else if (S.startswith("=")) {
1126 if (Config->Sysroot.empty())
1127 Driver->addFile(S.substr(1));
1128 else
1129 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
1130 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +00001131 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +00001132 } else if (sys::fs::exists(S)) {
1133 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +00001134 } else {
Rui Ueyama061f9282016-11-19 19:23:58 +00001135 if (Optional<std::string> Path = findFromSearchPaths(S))
1136 Driver->addFile(Saver.save(*Path));
Rui Ueyama025d59b2016-02-02 20:27:59 +00001137 else
Rui Ueyama061f9282016-11-19 19:23:58 +00001138 setError("unable to find " + S);
Rui Ueyama52a15092015-10-11 03:28:42 +00001139 }
1140}
1141
Rui Ueyama717677a2016-02-11 21:17:59 +00001142void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001143 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +00001144 bool Orig = Config->AsNeeded;
1145 Config->AsNeeded = true;
Rui Ueyama83043f22016-10-17 16:01:53 +00001146 while (!Error && !consume(")"))
George Rimarcd574a52016-09-09 14:35:36 +00001147 addFile(unquote(next()));
Rui Ueyama35da9b62015-10-11 20:59:12 +00001148 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001149}
1150
Rui Ueyama717677a2016-02-11 21:17:59 +00001151void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +00001152 // -e <symbol> takes predecence over ENTRY(<symbol>).
1153 expect("(");
1154 StringRef Tok = next();
1155 if (Config->Entry.empty())
1156 Config->Entry = Tok;
1157 expect(")");
1158}
1159
Rui Ueyama717677a2016-02-11 21:17:59 +00001160void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +00001161 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001162 while (!Error && !consume(")"))
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001163 Config->Undefined.push_back(next());
George Rimar83f406c2015-10-19 17:35:12 +00001164}
1165
Rui Ueyama717677a2016-02-11 21:17:59 +00001166void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001167 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001168 while (!Error && !consume(")")) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001169 StringRef Tok = next();
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001170 if (Tok == "AS_NEEDED")
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001171 readAsNeeded();
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001172 else
George Rimarcd574a52016-09-09 14:35:36 +00001173 addFile(unquote(Tok));
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001174 }
1175}
1176
Rui Ueyama717677a2016-02-11 21:17:59 +00001177void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001178 StringRef Tok = next();
George Rimarcd574a52016-09-09 14:35:36 +00001179 auto MBOrErr = MemoryBuffer::getFile(unquote(Tok));
Rui Ueyama025d59b2016-02-02 20:27:59 +00001180 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +00001181 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001182 return;
1183 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001184 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Eugene Leviant03ff0162016-11-21 15:49:56 +00001185 tokenize(MB->getMemBufferRef());
1186 OwningMBs.push_back(std::move(MB));
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001187}
1188
Rui Ueyama717677a2016-02-11 21:17:59 +00001189void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +00001190 // -o <file> takes predecence over OUTPUT(<file>).
1191 expect("(");
1192 StringRef Tok = next();
1193 if (Config->OutputFile.empty())
George Rimarcd574a52016-09-09 14:35:36 +00001194 Config->OutputFile = unquote(Tok);
Rui Ueyamaee592822015-10-07 00:25:09 +00001195 expect(")");
1196}
1197
Rui Ueyama717677a2016-02-11 21:17:59 +00001198void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +00001199 // Error checking only for now.
1200 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001201 skip();
Davide Italiano9159ce92015-10-12 21:50:08 +00001202 expect(")");
1203}
1204
Rui Ueyama717677a2016-02-11 21:17:59 +00001205void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001206 // Error checking only for now.
1207 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001208 skip();
Davide Italiano6836c612015-10-12 21:08:41 +00001209 StringRef Tok = next();
1210 if (Tok == ")")
George Rimar6c55f0e2016-09-08 08:20:30 +00001211 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +00001212 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +00001213 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001214 return;
1215 }
Justin Bogner5424e7c2016-10-17 06:21:13 +00001216 skip();
Davide Italiano6836c612015-10-12 21:08:41 +00001217 expect(",");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001218 skip();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001219 expect(")");
1220}
1221
Eugene Leviantbbe38602016-07-19 09:25:43 +00001222void ScriptParser::readPhdrs() {
1223 expect("{");
Rui Ueyama83043f22016-10-17 16:01:53 +00001224 while (!Error && !consume("}")) {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001225 StringRef Tok = next();
Eugene Leviant56b21c82016-09-09 09:46:16 +00001226 Opt.PhdrsCommands.push_back(
1227 {Tok, PT_NULL, false, false, UINT_MAX, nullptr});
Eugene Leviantbbe38602016-07-19 09:25:43 +00001228 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
1229
1230 PhdrCmd.Type = readPhdrType();
1231 do {
1232 Tok = next();
1233 if (Tok == ";")
1234 break;
1235 if (Tok == "FILEHDR")
1236 PhdrCmd.HasFilehdr = true;
1237 else if (Tok == "PHDRS")
1238 PhdrCmd.HasPhdrs = true;
Eugene Leviant56b21c82016-09-09 09:46:16 +00001239 else if (Tok == "AT")
1240 PhdrCmd.LMAExpr = readParenExpr();
Eugene Leviant865bf862016-07-21 10:43:25 +00001241 else if (Tok == "FLAGS") {
1242 expect("(");
Rafael Espindolaeb685cd2016-08-02 22:14:57 +00001243 // Passing 0 for the value of dot is a bit of a hack. It means that
1244 // we accept expressions like ".|1".
1245 PhdrCmd.Flags = readExpr()(0);
Eugene Leviant865bf862016-07-21 10:43:25 +00001246 expect(")");
1247 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +00001248 setError("unexpected header attribute: " + Tok);
1249 } while (!Error);
1250 }
1251}
1252
Rui Ueyama717677a2016-02-11 21:17:59 +00001253void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +00001254 expect("(");
Rui Ueyama86c5fb82016-09-08 23:26:54 +00001255 StringRef Tok = next();
Rui Ueyama6c7ad132016-09-02 19:20:33 +00001256 if (!Config->Nostdlib)
George Rimarcd574a52016-09-09 14:35:36 +00001257 Config->SearchPaths.push_back(unquote(Tok));
Davide Italiano68a39a62015-10-08 17:51:41 +00001258 expect(")");
1259}
1260
Rui Ueyama717677a2016-02-11 21:17:59 +00001261void ScriptParser::readSections() {
Eugene Leviante05336ff2016-09-14 08:32:36 +00001262 Opt.HasSections = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001263 expect("{");
Rui Ueyama83043f22016-10-17 16:01:53 +00001264 while (!Error && !consume("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +00001265 StringRef Tok = next();
Rafael Espindolac96da112016-11-01 11:30:45 +00001266 BaseCommand *Cmd = readProvideOrAssignment(Tok);
Eugene Leviantceabe802016-08-11 07:56:43 +00001267 if (!Cmd) {
1268 if (Tok == "ASSERT")
1269 Cmd = new AssertCommand(readAssert());
1270 else
1271 Cmd = readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +00001272 }
Rui Ueyama10416562016-08-04 02:03:27 +00001273 Opt.Commands.emplace_back(Cmd);
George Rimar652852c2016-04-16 10:10:32 +00001274 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001275}
1276
Rui Ueyama708019c2016-07-24 18:19:40 +00001277static int precedence(StringRef Op) {
1278 return StringSwitch<int>(Op)
Rui Ueyama0120e3f2016-09-23 18:06:51 +00001279 .Cases("*", "/", 5)
1280 .Cases("+", "-", 4)
1281 .Cases("<<", ">>", 3)
Rui Ueyama9c4ac5f2016-09-23 22:22:34 +00001282 .Cases("<", "<=", ">", ">=", "==", "!=", 2)
Rui Ueyama0120e3f2016-09-23 18:06:51 +00001283 .Cases("&", "|", 1)
Rui Ueyama708019c2016-07-24 18:19:40 +00001284 .Default(-1);
1285}
1286
Eugene Leviantdb688452016-11-03 10:54:58 +00001287StringMatcher ScriptParser::readFilePatterns() {
Rui Ueyama10416562016-08-04 02:03:27 +00001288 std::vector<StringRef> V;
Rui Ueyama83043f22016-10-17 16:01:53 +00001289 while (!Error && !consume(")"))
Rui Ueyama10416562016-08-04 02:03:27 +00001290 V.push_back(next());
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001291 return StringMatcher(V);
George Rimar0702c4e2016-07-29 15:32:46 +00001292}
1293
George Rimarbe394db2016-09-16 20:21:55 +00001294SortSectionPolicy ScriptParser::readSortKind() {
Rui Ueyama83043f22016-10-17 16:01:53 +00001295 if (consume("SORT") || consume("SORT_BY_NAME"))
George Rimarbe394db2016-09-16 20:21:55 +00001296 return SortSectionPolicy::Name;
Rui Ueyama83043f22016-10-17 16:01:53 +00001297 if (consume("SORT_BY_ALIGNMENT"))
George Rimarbe394db2016-09-16 20:21:55 +00001298 return SortSectionPolicy::Alignment;
Rui Ueyama83043f22016-10-17 16:01:53 +00001299 if (consume("SORT_BY_INIT_PRIORITY"))
George Rimarbe394db2016-09-16 20:21:55 +00001300 return SortSectionPolicy::Priority;
Rui Ueyama83043f22016-10-17 16:01:53 +00001301 if (consume("SORT_NONE"))
Rui Ueyamab2a0abd2016-09-16 21:14:55 +00001302 return SortSectionPolicy::None;
1303 return SortSectionPolicy::Default;
George Rimarbe394db2016-09-16 20:21:55 +00001304}
1305
George Rimar395281c2016-09-16 17:42:10 +00001306// Method reads a list of sequence of excluded files and section globs given in
1307// a following form: ((EXCLUDE_FILE(file_pattern+))? section_pattern+)+
1308// Example: *(.foo.1 EXCLUDE_FILE (*a.o) .foo.2 EXCLUDE_FILE (*b.o) .foo.3)
George Rimaraf03be12016-09-17 19:17:25 +00001309// The semantics of that is next:
1310// * Include .foo.1 from every file.
1311// * Include .foo.2 from every file but a.o
1312// * Include .foo.3 from every file but b.o
George Rimar07171f22016-09-21 15:56:44 +00001313std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
1314 std::vector<SectionPattern> Ret;
George Rimar601e9892016-09-21 08:53:21 +00001315 while (!Error && peek() != ")") {
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001316 StringMatcher ExcludeFilePat;
Rui Ueyama83043f22016-10-17 16:01:53 +00001317 if (consume("EXCLUDE_FILE")) {
George Rimar395281c2016-09-16 17:42:10 +00001318 expect("(");
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001319 ExcludeFilePat = readFilePatterns();
George Rimar395281c2016-09-16 17:42:10 +00001320 }
1321
George Rimar601e9892016-09-21 08:53:21 +00001322 std::vector<StringRef> V;
1323 while (!Error && peek() != ")" && peek() != "EXCLUDE_FILE")
1324 V.push_back(next());
1325
1326 if (!V.empty())
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001327 Ret.push_back({std::move(ExcludeFilePat), StringMatcher(V)});
George Rimar601e9892016-09-21 08:53:21 +00001328 else
1329 setError("section pattern is expected");
George Rimar395281c2016-09-16 17:42:10 +00001330 }
George Rimar07171f22016-09-21 15:56:44 +00001331 return Ret;
George Rimar395281c2016-09-16 17:42:10 +00001332}
1333
Rui Ueyamaf8f6f1e2016-11-18 07:03:56 +00001334// Reads contents of "SECTIONS" directive. That directive contains a
1335// list of glob patterns for input sections. The grammar is as follows.
1336//
1337// <patterns> ::= <section-list>
1338// | <sort> "(" <section-list> ")"
1339// | <sort> "(" <sort> "(" <section-list> ")" ")"
1340//
1341// <sort> ::= "SORT" | "SORT_BY_NAME" | "SORT_BY_ALIGNMENT"
1342// | "SORT_BY_INIT_PRIORITY" | "SORT_NONE"
1343//
1344// <section-list> is parsed by readInputSectionsList().
George Rimara2496cb2016-08-30 09:46:59 +00001345InputSectionDescription *
1346ScriptParser::readInputSectionRules(StringRef FilePattern) {
George Rimarc91930a2016-09-02 21:17:20 +00001347 auto *Cmd = new InputSectionDescription(FilePattern);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001348 expect("(");
Rui Ueyamaf373dd72016-11-24 01:43:21 +00001349 while (!Error && !consume(")")) {
George Rimar07171f22016-09-21 15:56:44 +00001350 SortSectionPolicy Outer = readSortKind();
1351 SortSectionPolicy Inner = SortSectionPolicy::Default;
1352 std::vector<SectionPattern> V;
1353 if (Outer != SortSectionPolicy::Default) {
George Rimar350ece42016-08-03 08:35:59 +00001354 expect("(");
George Rimar07171f22016-09-21 15:56:44 +00001355 Inner = readSortKind();
1356 if (Inner != SortSectionPolicy::Default) {
1357 expect("(");
1358 V = readInputSectionsList();
1359 expect(")");
1360 } else {
1361 V = readInputSectionsList();
1362 }
George Rimar350ece42016-08-03 08:35:59 +00001363 expect(")");
1364 } else {
George Rimar07171f22016-09-21 15:56:44 +00001365 V = readInputSectionsList();
George Rimar350ece42016-08-03 08:35:59 +00001366 }
George Rimar0702c4e2016-07-29 15:32:46 +00001367
George Rimar07171f22016-09-21 15:56:44 +00001368 for (SectionPattern &Pat : V) {
1369 Pat.SortInner = Inner;
1370 Pat.SortOuter = Outer;
1371 }
1372
1373 std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns));
1374 }
Rui Ueyama10416562016-08-04 02:03:27 +00001375 return Cmd;
Davide Italianoe7282792016-07-27 01:44:01 +00001376}
1377
George Rimara2496cb2016-08-30 09:46:59 +00001378InputSectionDescription *
1379ScriptParser::readInputSectionDescription(StringRef Tok) {
George Rimar06598002016-07-28 21:51:30 +00001380 // Input section wildcard can be surrounded by KEEP.
1381 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
George Rimara2496cb2016-08-30 09:46:59 +00001382 if (Tok == "KEEP") {
George Rimar06598002016-07-28 21:51:30 +00001383 expect("(");
George Rimara2496cb2016-08-30 09:46:59 +00001384 StringRef FilePattern = next();
1385 InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
George Rimar06598002016-07-28 21:51:30 +00001386 expect(")");
Eugene Leviantcf43f172016-10-05 09:36:59 +00001387 Opt.KeptSections.push_back(Cmd);
Rui Ueyama10416562016-08-04 02:03:27 +00001388 return Cmd;
George Rimar06598002016-07-28 21:51:30 +00001389 }
George Rimara2496cb2016-08-30 09:46:59 +00001390 return readInputSectionRules(Tok);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001391}
1392
George Rimar03fc0102016-07-28 07:18:23 +00001393void ScriptParser::readSort() {
1394 expect("(");
1395 expect("CONSTRUCTORS");
1396 expect(")");
1397}
1398
George Rimareefa7582016-08-04 09:29:31 +00001399Expr ScriptParser::readAssert() {
1400 expect("(");
1401 Expr E = readExpr();
1402 expect(",");
George Rimarcd574a52016-09-09 14:35:36 +00001403 StringRef Msg = unquote(next());
George Rimareefa7582016-08-04 09:29:31 +00001404 expect(")");
1405 return [=](uint64_t Dot) {
1406 uint64_t V = E(Dot);
1407 if (!V)
1408 error(Msg);
1409 return V;
1410 };
1411}
1412
Rui Ueyama25150e82016-09-06 17:46:43 +00001413// Reads a FILL(expr) command. We handle the FILL command as an
1414// alias for =fillexp section attribute, which is different from
1415// what GNU linkers do.
1416// https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
Rui Ueyama16068ae2016-11-19 18:05:56 +00001417uint32_t ScriptParser::readFill() {
George Rimarff1f29e2016-09-06 13:51:57 +00001418 expect("(");
Rui Ueyama16068ae2016-11-19 18:05:56 +00001419 uint32_t V = readOutputSectionFiller(next());
George Rimarff1f29e2016-09-06 13:51:57 +00001420 expect(")");
1421 expect(";");
1422 return V;
1423}
1424
Rui Ueyama10416562016-08-04 02:03:27 +00001425OutputSectionCommand *
1426ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +00001427 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
George Rimar58e5c4d2016-07-25 08:29:46 +00001428
1429 // Read an address expression.
1430 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
1431 if (peek() != ":")
1432 Cmd->AddrExpr = readExpr();
1433
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001434 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +00001435
Rui Ueyama83043f22016-10-17 16:01:53 +00001436 if (consume("AT"))
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001437 Cmd->LMAExpr = readParenExpr();
Rui Ueyama83043f22016-10-17 16:01:53 +00001438 if (consume("ALIGN"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001439 Cmd->AlignExpr = readParenExpr();
Rui Ueyama83043f22016-10-17 16:01:53 +00001440 if (consume("SUBALIGN"))
George Rimardb24d9c2016-08-19 15:18:23 +00001441 Cmd->SubalignExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001442
Davide Italiano246f6812016-07-22 03:36:24 +00001443 // Parse constraints.
Rui Ueyama83043f22016-10-17 16:01:53 +00001444 if (consume("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001445 Cmd->Constraint = ConstraintKind::ReadOnly;
Rui Ueyama83043f22016-10-17 16:01:53 +00001446 if (consume("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001447 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001448 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001449
Rui Ueyama83043f22016-10-17 16:01:53 +00001450 while (!Error && !consume("}")) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001451 StringRef Tok = next();
Meador Ingeb2d99d62016-11-22 18:01:50 +00001452 if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok)) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001453 Cmd->Commands.emplace_back(Assignment);
Meador Ingeb2d99d62016-11-22 18:01:50 +00001454 } else if (BytesDataCommand *Data = readBytesDataCommand(Tok)) {
George Rimare38cbab2016-09-26 19:22:50 +00001455 Cmd->Commands.emplace_back(Data);
Meador Ingeb2d99d62016-11-22 18:01:50 +00001456 } else if (Tok == "ASSERT") {
1457 Cmd->Commands.emplace_back(new AssertCommand(readAssert()));
1458 expect(";");
1459 } else if (Tok == "FILL") {
George Rimarff1f29e2016-09-06 13:51:57 +00001460 Cmd->Filler = readFill();
Meador Ingeb2d99d62016-11-22 18:01:50 +00001461 } else if (Tok == "SORT") {
George Rimar03fc0102016-07-28 07:18:23 +00001462 readSort();
Meador Ingeb2d99d62016-11-22 18:01:50 +00001463 } else if (peek() == "(") {
George Rimara2496cb2016-08-30 09:46:59 +00001464 Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
Meador Ingeb2d99d62016-11-22 18:01:50 +00001465 } else {
Eugene Leviantceabe802016-08-11 07:56:43 +00001466 setError("unknown command " + Tok);
Meador Ingeb2d99d62016-11-22 18:01:50 +00001467 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001468 }
George Rimar076fe152016-07-21 06:43:01 +00001469 Cmd->Phdrs = readOutputSectionPhdrs();
George Rimar4ebc5622016-09-23 13:29:20 +00001470
Rui Ueyama83043f22016-10-17 16:01:53 +00001471 if (consume("="))
George Rimar4ebc5622016-09-23 13:29:20 +00001472 Cmd->Filler = readOutputSectionFiller(next());
1473 else if (peek().startswith("="))
George Rimarff1f29e2016-09-06 13:51:57 +00001474 Cmd->Filler = readOutputSectionFiller(next().drop_front());
George Rimar4ebc5622016-09-23 13:29:20 +00001475
Rui Ueyama10416562016-08-04 02:03:27 +00001476 return Cmd;
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001477}
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001478
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001479// Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
1480// https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
1481//
1482// ld.gold is not fully compatible with ld.bfd. ld.bfd handles
1483// hexstrings as blobs of arbitrary sizes, while ld.gold handles them
1484// as 32-bit big-endian values. We will do the same as ld.gold does
1485// because it's simpler than what ld.bfd does.
Rui Ueyama16068ae2016-11-19 18:05:56 +00001486uint32_t ScriptParser::readOutputSectionFiller(StringRef Tok) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001487 uint32_t V;
Rui Ueyama16068ae2016-11-19 18:05:56 +00001488 if (!Tok.getAsInteger(0, V))
1489 return V;
1490 setError("invalid filler expression: " + Tok);
1491 return 0;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001492}
1493
Petr Hoseka35e39c2016-08-16 01:11:16 +00001494SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
Eugene Levianta31c91b2016-07-22 07:38:40 +00001495 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +00001496 SymbolAssignment *Cmd = readAssignment(next());
Petr Hoseka35e39c2016-08-16 01:11:16 +00001497 Cmd->Provide = Provide;
Rui Ueyama174e0a12016-07-29 00:29:25 +00001498 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001499 expect(")");
1500 expect(";");
Rui Ueyama10416562016-08-04 02:03:27 +00001501 return Cmd;
Eugene Levianteda81a12016-07-12 06:39:48 +00001502}
1503
Rafael Espindolac96da112016-11-01 11:30:45 +00001504SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001505 SymbolAssignment *Cmd = nullptr;
1506 if (peek() == "=" || peek() == "+=") {
1507 Cmd = readAssignment(Tok);
1508 expect(";");
1509 } else if (Tok == "PROVIDE") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001510 Cmd = readProvideHidden(true, false);
1511 } else if (Tok == "HIDDEN") {
1512 Cmd = readProvideHidden(false, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001513 } else if (Tok == "PROVIDE_HIDDEN") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001514 Cmd = readProvideHidden(true, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001515 }
1516 return Cmd;
1517}
1518
George Rimar30835ea2016-07-28 21:08:56 +00001519static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
1520 if (S == ".")
1521 return Dot;
George Rimar884e7862016-09-08 08:19:13 +00001522 return ScriptBase->getSymbolValue(S);
George Rimare32a3592016-08-10 07:59:34 +00001523}
1524
Rafael Espindola2f831dc2016-10-31 19:56:37 +00001525static bool isAbsolute(StringRef S) {
1526 if (S == ".")
1527 return false;
1528 return ScriptBase->isAbsolute(S);
1529}
1530
George Rimar30835ea2016-07-28 21:08:56 +00001531SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1532 StringRef Op = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +00001533 Expr E;
George Rimar30835ea2016-07-28 21:08:56 +00001534 assert(Op == "=" || Op == "+=");
Rui Ueyama83043f22016-10-17 16:01:53 +00001535 if (consume("ABSOLUTE")) {
Rui Ueyama7c1381a2016-10-19 23:11:21 +00001536 // The RHS may be something like "ABSOLUTE(.) & 0xff".
1537 // Call readExpr1 to read the whole expression.
1538 E = readExpr1(readParenExpr(), 0);
Rui Ueyama009d1742016-11-18 06:49:09 +00001539 E.IsAbsolute = [] { return true; };
Eugene Leviantdb741e72016-09-07 07:08:43 +00001540 } else {
1541 E = readExpr();
1542 }
George Rimar30835ea2016-07-28 21:08:56 +00001543 if (Op == "+=")
1544 E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
Rafael Espindolaf6613932016-10-31 17:43:38 +00001545 return new SymbolAssignment(Name, E);
George Rimar30835ea2016-07-28 21:08:56 +00001546}
1547
1548// This is an operator-precedence parser to parse a linker
1549// script expression.
1550Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
1551
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001552static Expr combine(StringRef Op, Expr L, Expr R) {
1553 if (Op == "*")
1554 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1555 if (Op == "/") {
1556 return [=](uint64_t Dot) -> uint64_t {
1557 uint64_t RHS = R(Dot);
1558 if (RHS == 0) {
1559 error("division by zero");
1560 return 0;
1561 }
1562 return L(Dot) / RHS;
1563 };
1564 }
1565 if (Op == "+")
Rafael Espindola2f831dc2016-10-31 19:56:37 +00001566 return {[=](uint64_t Dot) { return L(Dot) + R(Dot); },
Rui Ueyama009d1742016-11-18 06:49:09 +00001567 [=] { return L.IsAbsolute() && R.IsAbsolute(); },
1568 [=] {
Eugene Leviantafaa9342016-11-16 09:49:39 +00001569 const OutputSectionBase *S = L.Section();
1570 return S ? S : R.Section();
1571 }};
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001572 if (Op == "-")
1573 return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
George Rimarc8ccd1f2016-09-23 13:13:55 +00001574 if (Op == "<<")
1575 return [=](uint64_t Dot) { return L(Dot) << R(Dot); };
1576 if (Op == ">>")
1577 return [=](uint64_t Dot) { return L(Dot) >> R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001578 if (Op == "<")
1579 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
1580 if (Op == ">")
1581 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
1582 if (Op == ">=")
1583 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
1584 if (Op == "<=")
1585 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
1586 if (Op == "==")
1587 return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
1588 if (Op == "!=")
1589 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
1590 if (Op == "&")
1591 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
Rafael Espindolacc3dd622016-08-22 21:33:35 +00001592 if (Op == "|")
1593 return [=](uint64_t Dot) { return L(Dot) | R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001594 llvm_unreachable("invalid operator");
1595}
1596
Rui Ueyama708019c2016-07-24 18:19:40 +00001597// This is a part of the operator-precedence parser. This function
1598// assumes that the remaining token stream starts with an operator.
1599Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1600 while (!atEOF() && !Error) {
1601 // Read an operator and an expression.
Rui Ueyama46247b82016-11-18 06:49:07 +00001602 if (consume("?"))
Rui Ueyama708019c2016-07-24 18:19:40 +00001603 return readTernary(Lhs);
Rui Ueyama46247b82016-11-18 06:49:07 +00001604 StringRef Op1 = peek();
Rui Ueyama708019c2016-07-24 18:19:40 +00001605 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +00001606 break;
Justin Bogner5424e7c2016-10-17 06:21:13 +00001607 skip();
Rui Ueyama708019c2016-07-24 18:19:40 +00001608 Expr Rhs = readPrimary();
1609
1610 // Evaluate the remaining part of the expression first if the
1611 // next operator has greater precedence than the previous one.
1612 // For example, if we have read "+" and "3", and if the next
1613 // operator is "*", then we'll evaluate 3 * ... part first.
1614 while (!atEOF()) {
1615 StringRef Op2 = peek();
1616 if (precedence(Op2) <= precedence(Op1))
1617 break;
1618 Rhs = readExpr1(Rhs, precedence(Op2));
1619 }
1620
1621 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +00001622 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001623 return Lhs;
1624}
1625
1626uint64_t static getConstant(StringRef S) {
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001627 if (S == "COMMONPAGESIZE")
Rui Ueyama708019c2016-07-24 18:19:40 +00001628 return Target->PageSize;
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001629 if (S == "MAXPAGESIZE")
Petr Hosek997f8832016-09-28 15:20:47 +00001630 return Config->MaxPageSize;
Rui Ueyama708019c2016-07-24 18:19:40 +00001631 error("unknown constant: " + S);
1632 return 0;
1633}
1634
Rui Ueyama626e0b02016-09-02 18:19:00 +00001635// Parses Tok as an integer. Returns true if successful.
1636// It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1637// and decimal numbers. Decimal numbers may have "K" (kilo) or
1638// "M" (mega) prefixes.
George Rimar9f2f7ad2016-09-02 16:01:42 +00001639static bool readInteger(StringRef Tok, uint64_t &Result) {
Rui Ueyama46247b82016-11-18 06:49:07 +00001640 // Negative number
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001641 if (Tok.startswith("-")) {
1642 if (!readInteger(Tok.substr(1), Result))
1643 return false;
1644 Result = -Result;
1645 return true;
1646 }
Rui Ueyama46247b82016-11-18 06:49:07 +00001647
1648 // Hexadecimal
George Rimar9f2f7ad2016-09-02 16:01:42 +00001649 if (Tok.startswith_lower("0x"))
1650 return !Tok.substr(2).getAsInteger(16, Result);
1651 if (Tok.endswith_lower("H"))
1652 return !Tok.drop_back().getAsInteger(16, Result);
1653
Rui Ueyama46247b82016-11-18 06:49:07 +00001654 // Decimal
George Rimar9f2f7ad2016-09-02 16:01:42 +00001655 int Suffix = 1;
1656 if (Tok.endswith_lower("K")) {
1657 Suffix = 1024;
1658 Tok = Tok.drop_back();
1659 } else if (Tok.endswith_lower("M")) {
1660 Suffix = 1024 * 1024;
1661 Tok = Tok.drop_back();
1662 }
1663 if (Tok.getAsInteger(10, Result))
1664 return false;
1665 Result *= Suffix;
1666 return true;
1667}
1668
George Rimare38cbab2016-09-26 19:22:50 +00001669BytesDataCommand *ScriptParser::readBytesDataCommand(StringRef Tok) {
1670 int Size = StringSwitch<unsigned>(Tok)
1671 .Case("BYTE", 1)
1672 .Case("SHORT", 2)
1673 .Case("LONG", 4)
1674 .Case("QUAD", 8)
1675 .Default(-1);
1676 if (Size == -1)
1677 return nullptr;
1678
1679 expect("(");
1680 uint64_t Val = 0;
1681 StringRef S = next();
1682 if (!readInteger(S, Val))
1683 setError("unexpected value: " + S);
1684 expect(")");
1685 return new BytesDataCommand(Val, Size);
1686}
1687
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001688StringRef ScriptParser::readParenLiteral() {
1689 expect("(");
1690 StringRef Tok = next();
1691 expect(")");
1692 return Tok;
1693}
1694
Rui Ueyama708019c2016-07-24 18:19:40 +00001695Expr ScriptParser::readPrimary() {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001696 if (peek() == "(")
1697 return readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001698
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001699 StringRef Tok = next();
Rui Ueyama708019c2016-07-24 18:19:40 +00001700
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001701 if (Tok == "~") {
1702 Expr E = readPrimary();
1703 return [=](uint64_t Dot) { return ~E(Dot); };
1704 }
1705 if (Tok == "-") {
1706 Expr E = readPrimary();
1707 return [=](uint64_t Dot) { return -E(Dot); };
1708 }
1709
Rui Ueyama708019c2016-07-24 18:19:40 +00001710 // Built-in functions are parsed here.
1711 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
George Rimar96659df2016-08-30 09:54:01 +00001712 if (Tok == "ADDR") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001713 StringRef Name = readParenLiteral();
Eugene Leviantafaa9342016-11-16 09:49:39 +00001714 return {
1715 [=](uint64_t Dot) { return ScriptBase->getOutputSection(Name)->Addr; },
Rui Ueyama009d1742016-11-18 06:49:09 +00001716 [=] { return false; },
1717 [=] { return ScriptBase->getOutputSection(Name); }};
George Rimar96659df2016-08-30 09:54:01 +00001718 }
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001719 if (Tok == "LOADADDR") {
1720 StringRef Name = readParenLiteral();
Eugene Leviantafaa9342016-11-16 09:49:39 +00001721 return [=](uint64_t Dot) {
1722 return ScriptBase->getOutputSection(Name)->getLMA();
1723 };
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001724 }
George Rimareefa7582016-08-04 09:29:31 +00001725 if (Tok == "ASSERT")
1726 return readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001727 if (Tok == "ALIGN") {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001728 Expr E = readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001729 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1730 }
1731 if (Tok == "CONSTANT") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001732 StringRef Name = readParenLiteral();
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001733 return [=](uint64_t Dot) { return getConstant(Name); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001734 }
George Rimarf34f45f2016-09-23 13:17:23 +00001735 if (Tok == "DEFINED") {
Rui Ueyama0ee25a62016-11-17 03:52:14 +00001736 StringRef Name = readParenLiteral();
1737 return [=](uint64_t Dot) { return ScriptBase->isDefined(Name) ? 1 : 0; };
George Rimarf34f45f2016-09-23 13:17:23 +00001738 }
Rafael Espindola54c145c2016-07-28 18:16:24 +00001739 if (Tok == "SEGMENT_START") {
1740 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001741 skip();
Rafael Espindola54c145c2016-07-28 18:16:24 +00001742 expect(",");
George Rimar8c658bf2016-09-17 18:14:56 +00001743 Expr E = readExpr();
Rafael Espindola54c145c2016-07-28 18:16:24 +00001744 expect(")");
George Rimar8c658bf2016-09-17 18:14:56 +00001745 return [=](uint64_t Dot) { return E(Dot); };
Rafael Espindola54c145c2016-07-28 18:16:24 +00001746 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001747 if (Tok == "DATA_SEGMENT_ALIGN") {
1748 expect("(");
1749 Expr E = readExpr();
1750 expect(",");
1751 readExpr();
1752 expect(")");
Rui Ueyamaf7791bb2016-07-26 19:34:10 +00001753 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001754 }
1755 if (Tok == "DATA_SEGMENT_END") {
1756 expect("(");
1757 expect(".");
1758 expect(")");
1759 return [](uint64_t Dot) { return Dot; };
1760 }
George Rimar276b4e62016-07-26 17:58:44 +00001761 // GNU linkers implements more complicated logic to handle
1762 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1763 // the next page boundary for simplicity.
1764 if (Tok == "DATA_SEGMENT_RELRO_END") {
1765 expect("(");
Rafael Espindola97bdc722016-09-14 19:14:01 +00001766 readExpr();
George Rimar276b4e62016-07-26 17:58:44 +00001767 expect(",");
1768 readExpr();
1769 expect(")");
1770 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1771 }
George Rimar9e694502016-07-29 16:18:47 +00001772 if (Tok == "SIZEOF") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001773 StringRef Name = readParenLiteral();
Rui Ueyamaedf75e72016-11-17 20:27:10 +00001774 return [=](uint64_t Dot) { return ScriptBase->getOutputSectionSize(Name); };
George Rimar9e694502016-07-29 16:18:47 +00001775 }
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001776 if (Tok == "ALIGNOF") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001777 StringRef Name = readParenLiteral();
Eugene Leviantafaa9342016-11-16 09:49:39 +00001778 return [=](uint64_t Dot) {
1779 return ScriptBase->getOutputSection(Name)->Addralign;
1780 };
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001781 }
George Rimare32a3592016-08-10 07:59:34 +00001782 if (Tok == "SIZEOF_HEADERS")
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001783 return [=](uint64_t Dot) { return ScriptBase->getHeaderSize(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001784
George Rimar9f2f7ad2016-09-02 16:01:42 +00001785 // Tok is a literal number.
1786 uint64_t V;
1787 if (readInteger(Tok, V))
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001788 return [=](uint64_t Dot) { return V; };
George Rimar9f2f7ad2016-09-02 16:01:42 +00001789
1790 // Tok is a symbol name.
1791 if (Tok != "." && !isValidCIdentifier(Tok))
1792 setError("malformed number: " + Tok);
Rafael Espindola2f831dc2016-10-31 19:56:37 +00001793 return {[=](uint64_t Dot) { return getSymbolValue(Tok, Dot); },
Rui Ueyama009d1742016-11-18 06:49:09 +00001794 [=] { return isAbsolute(Tok); },
1795 [=] { return ScriptBase->getSymbolSection(Tok); }};
Rui Ueyama708019c2016-07-24 18:19:40 +00001796}
1797
1798Expr ScriptParser::readTernary(Expr Cond) {
Rui Ueyama708019c2016-07-24 18:19:40 +00001799 Expr L = readExpr();
1800 expect(":");
1801 Expr R = readExpr();
1802 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1803}
1804
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001805Expr ScriptParser::readParenExpr() {
1806 expect("(");
1807 Expr E = readExpr();
1808 expect(")");
1809 return E;
1810}
1811
Eugene Leviantbbe38602016-07-19 09:25:43 +00001812std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1813 std::vector<StringRef> Phdrs;
1814 while (!Error && peek().startswith(":")) {
1815 StringRef Tok = next();
George Rimarda841c12016-11-14 10:03:54 +00001816 Phdrs.push_back((Tok.size() == 1) ? next() : Tok.substr(1));
Eugene Leviantbbe38602016-07-19 09:25:43 +00001817 }
1818 return Phdrs;
1819}
1820
George Rimar95dd7182016-10-18 10:49:50 +00001821// Read a program header type name. The next token must be a
1822// name of a program header type or a constant (e.g. "0x3").
Eugene Leviantbbe38602016-07-19 09:25:43 +00001823unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001824 StringRef Tok = next();
George Rimar95dd7182016-10-18 10:49:50 +00001825 uint64_t Val;
1826 if (readInteger(Tok, Val))
1827 return Val;
1828
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001829 unsigned Ret = StringSwitch<unsigned>(Tok)
George Rimar6c55f0e2016-09-08 08:20:30 +00001830 .Case("PT_NULL", PT_NULL)
1831 .Case("PT_LOAD", PT_LOAD)
1832 .Case("PT_DYNAMIC", PT_DYNAMIC)
1833 .Case("PT_INTERP", PT_INTERP)
1834 .Case("PT_NOTE", PT_NOTE)
1835 .Case("PT_SHLIB", PT_SHLIB)
1836 .Case("PT_PHDR", PT_PHDR)
1837 .Case("PT_TLS", PT_TLS)
1838 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1839 .Case("PT_GNU_STACK", PT_GNU_STACK)
1840 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
George Rimar270173f2016-10-14 13:02:22 +00001841 .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
George Rimarcc6e5672016-10-14 10:34:36 +00001842 .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
George Rimar6c55f0e2016-09-08 08:20:30 +00001843 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001844
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001845 if (Ret == (unsigned)-1) {
1846 setError("invalid program header type: " + Tok);
1847 return PT_NULL;
1848 }
1849 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001850}
1851
Rui Ueyama12450b22016-11-18 06:30:09 +00001852// Reads a list of symbols, e.g. "{ global: foo; bar; local: *; };".
1853void ScriptParser::readAnonymousDeclaration() {
1854 // Read global symbols first. "global:" is default, so if there's
1855 // no label, we assume global symbols.
1856 if (consume("global:") || peek() != "local:")
1857 Config->VersionScriptGlobals = readSymbols();
1858
1859 // Next, read local symbols.
1860 if (consume("local:")) {
1861 if (consume("*")) {
1862 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1863 expect(";");
1864 } else {
1865 setError("local symbol list for anonymous version is not supported");
1866 }
1867 }
1868 expect("}");
1869 expect(";");
1870}
1871
1872// Reads a list of symbols, e.g. "VerStr { global: foo; bar; local: *; };".
Rui Ueyama95769b42016-08-31 20:03:54 +00001873void ScriptParser::readVersionDeclaration(StringRef VerStr) {
George Rimar20b65982016-08-31 09:08:26 +00001874 // Identifiers start at 2 because 0 and 1 are reserved
1875 // for VER_NDX_LOCAL and VER_NDX_GLOBAL constants.
Rui Ueyamada805c42016-11-17 03:39:21 +00001876 uint16_t VersionId = Config->VersionDefinitions.size() + 2;
George Rimar20b65982016-08-31 09:08:26 +00001877 Config->VersionDefinitions.push_back({VerStr, VersionId});
1878
Rui Ueyama12450b22016-11-18 06:30:09 +00001879 // Read global symbols.
Rui Ueyama83043f22016-10-17 16:01:53 +00001880 if (consume("global:") || peek() != "local:")
Rui Ueyama12450b22016-11-18 06:30:09 +00001881 Config->VersionDefinitions.back().Globals = readSymbols();
1882
1883 // Read local symbols.
1884 if (consume("local:")) {
1885 if (consume("*")) {
1886 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1887 expect(";");
1888 } else {
1889 for (SymbolVersion V : readSymbols())
1890 Config->VersionScriptLocals.push_back(V);
1891 }
1892 }
George Rimar20b65982016-08-31 09:08:26 +00001893 expect("}");
1894
Rui Ueyama12450b22016-11-18 06:30:09 +00001895 // Each version may have a parent version. For example, "Ver2"
1896 // defined as "Ver2 { global: foo; local: *; } Ver1;" has "Ver1"
1897 // as a parent. This version hierarchy is, probably against your
1898 // instinct, purely for hint; the runtime doesn't care about it
1899 // at all. In LLD, we simply ignore it.
1900 if (peek() != ";")
Justin Bogner5424e7c2016-10-17 06:21:13 +00001901 skip();
George Rimar20b65982016-08-31 09:08:26 +00001902 expect(";");
1903}
1904
Rui Ueyama12450b22016-11-18 06:30:09 +00001905// Reads a list of symbols for a versions cript.
1906std::vector<SymbolVersion> ScriptParser::readSymbols() {
1907 std::vector<SymbolVersion> Ret;
George Rimare0fc2422016-11-16 17:59:10 +00001908 for (;;) {
1909 if (consume("extern"))
Rui Ueyama12450b22016-11-18 06:30:09 +00001910 for (SymbolVersion V : readVersionExtern())
1911 Ret.push_back(V);
George Rimare0fc2422016-11-16 17:59:10 +00001912
Rui Ueyama0ee25a62016-11-17 03:52:14 +00001913 if (peek() == "}" || peek() == "local:" || Error)
Rui Ueyama12450b22016-11-18 06:30:09 +00001914 break;
Rui Ueyama0ee25a62016-11-17 03:52:14 +00001915 StringRef Tok = next();
Rui Ueyama12450b22016-11-18 06:30:09 +00001916 Ret.push_back({unquote(Tok), false, hasWildcard(Tok)});
George Rimare0fc2422016-11-16 17:59:10 +00001917 expect(";");
1918 }
Rui Ueyama12450b22016-11-18 06:30:09 +00001919 return Ret;
George Rimare0fc2422016-11-16 17:59:10 +00001920}
1921
Rui Ueyama12450b22016-11-18 06:30:09 +00001922// Reads an "extern C++" directive, e.g.,
1923// "extern "C++" { ns::*; "f(int, double)"; };"
1924std::vector<SymbolVersion> ScriptParser::readVersionExtern() {
George Rimarcd574a52016-09-09 14:35:36 +00001925 expect("\"C++\"");
George Rimar20b65982016-08-31 09:08:26 +00001926 expect("{");
1927
Rui Ueyama12450b22016-11-18 06:30:09 +00001928 std::vector<SymbolVersion> Ret;
Rui Ueyama0ee25a62016-11-17 03:52:14 +00001929 while (!Error && peek() != "}") {
1930 StringRef Tok = next();
1931 bool HasWildcard = !Tok.startswith("\"") && hasWildcard(Tok);
Rui Ueyama12450b22016-11-18 06:30:09 +00001932 Ret.push_back({unquote(Tok), true, HasWildcard});
George Rimar20b65982016-08-31 09:08:26 +00001933 expect(";");
1934 }
1935
1936 expect("}");
1937 expect(";");
Rui Ueyama12450b22016-11-18 06:30:09 +00001938 return Ret;
George Rimar20b65982016-08-31 09:08:26 +00001939}
1940
Rui Ueyama07320e42016-04-20 20:13:41 +00001941void elf::readLinkerScript(MemoryBufferRef MB) {
Rui Ueyama22375f22016-11-25 18:51:54 +00001942 ScriptParser(MB).readLinkerScript();
George Rimar20b65982016-08-31 09:08:26 +00001943}
1944
1945void elf::readVersionScript(MemoryBufferRef MB) {
Rui Ueyama22375f22016-11-25 18:51:54 +00001946 ScriptParser(MB).readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001947}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001948
Rui Ueyama07320e42016-04-20 20:13:41 +00001949template class elf::LinkerScript<ELF32LE>;
1950template class elf::LinkerScript<ELF32BE>;
1951template class elf::LinkerScript<ELF64LE>;
1952template class elf::LinkerScript<ELF64BE>;