blob: 7e2aecccb28e309c0c40375ef7487edaa09d4c76 [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 Ueyama9381eb12016-12-18 14:06:06 +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"
George Rimar3fb5a6d2016-11-29 16:05:27 +000024#include "SyntheticSections.h"
Eugene Leviant467c4d52016-07-01 10:27:36 +000025#include "Target.h"
Eugene Leviantbbe38602016-07-19 09:25:43 +000026#include "Writer.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000027#include "llvm/ADT/STLExtras.h"
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +000028#include "llvm/ADT/SmallString.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000029#include "llvm/ADT/StringRef.h"
Rui Ueyama960504b2016-04-19 18:58:11 +000030#include "llvm/ADT/StringSwitch.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000031#include "llvm/Support/Casting.h"
George Rimar652852c2016-04-16 10:10:32 +000032#include "llvm/Support/ELF.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000033#include "llvm/Support/Endian.h"
34#include "llvm/Support/ErrorHandling.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000035#include "llvm/Support/FileSystem.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000036#include "llvm/Support/MathExtras.h"
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +000037#include "llvm/Support/Path.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000038#include <algorithm>
39#include <cassert>
40#include <cstddef>
41#include <cstdint>
42#include <iterator>
43#include <limits>
44#include <memory>
45#include <string>
46#include <tuple>
47#include <vector>
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000048
49using namespace llvm;
George Rimar652852c2016-04-16 10:10:32 +000050using namespace llvm::ELF;
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +000051using namespace llvm::object;
George Rimare38cbab2016-09-26 19:22:50 +000052using namespace llvm::support::endian;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000053using namespace lld;
Rafael Espindolae0df00b2016-02-28 00:25:54 +000054using namespace lld::elf;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000055
George Rimar884e7862016-09-08 08:19:13 +000056LinkerScriptBase *elf::ScriptBase;
Rui Ueyama07320e42016-04-20 20:13:41 +000057ScriptConfiguration *elf::ScriptConfig;
Rui Ueyama717677a2016-02-11 21:17:59 +000058
George Rimar6c55f0e2016-09-08 08:20:30 +000059template <class ELFT> static void addRegular(SymbolAssignment *Cmd) {
Rafael Espindola3dabfc62016-10-31 13:14:53 +000060 uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
Rui Ueyama1bdaf3e2016-11-09 23:37:40 +000061 Symbol *Sym = Symtab<ELFT>::X->addRegular(Cmd->Name, Visibility, STT_NOTYPE,
George Rimar463984d2016-11-15 08:07:14 +000062 0, 0, STB_GLOBAL, nullptr, nullptr);
Rui Ueyama16024212016-08-11 23:22:52 +000063 Cmd->Sym = Sym->body();
Eugene Leviant20d03192016-09-16 15:30:47 +000064
65 // If we have no SECTIONS then we don't have '.' and don't call
66 // assignAddresses(). We calculate symbol value immediately in this case.
67 if (!ScriptConfig->HasSections)
68 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(0);
Eugene Leviantceabe802016-08-11 07:56:43 +000069}
70
Rui Ueyama0c70d3c2016-08-12 03:31:09 +000071template <class ELFT> static void addSynthetic(SymbolAssignment *Cmd) {
Eugene Leviantafaa9342016-11-16 09:49:39 +000072 // If we have SECTIONS block then output sections haven't been created yet.
73 const OutputSectionBase *Sec =
74 ScriptConfig->HasSections ? nullptr : Cmd->Expression.Section();
George Rimare1937bb2016-08-19 15:36:32 +000075 Symbol *Sym = Symtab<ELFT>::X->addSynthetic(
Eugene Leviantafaa9342016-11-16 09:49:39 +000076 Cmd->Name, Sec, 0, Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT);
Rui Ueyama16024212016-08-11 23:22:52 +000077 Cmd->Sym = Sym->body();
Eugene Leviantafaa9342016-11-16 09:49:39 +000078
79 // If we already know section then we can calculate symbol value immediately.
80 if (Sec)
Rui Ueyama4f2f50d2016-12-21 08:40:09 +000081 cast<DefinedSynthetic>(Cmd->Sym)->Value = 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>
George Rimar93c64022016-12-15 15:38:09 +0000380void LinkerScript<ELFT>::addOrphanSections(
381 OutputSectionFactory<ELFT> &Factory) {
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000382 for (InputSectionBase<ELFT> *S : Symtab<ELFT>::X->Sections)
Rafael Espindola8f9026b2016-11-08 18:23:02 +0000383 if (S->Live && !S->OutSec)
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000384 addSection(Factory, S, getOutputSectionName(S->Name));
Eugene Leviante63d81b2016-07-20 14:43:20 +0000385}
386
Eugene Leviantdb741e72016-09-07 07:08:43 +0000387// Sets value of a section-defined symbol. Two kinds of
388// symbols are processed: synthetic symbols, whose value
389// is an offset from beginning of section and regular
390// symbols whose value is absolute.
391template <class ELFT>
Eugene Leviantafaa9342016-11-16 09:49:39 +0000392static void assignSectionSymbol(SymbolAssignment *Cmd,
Rafael Espindola498ed712016-10-31 14:44:41 +0000393 typename ELFT::uint Value) {
Eugene Leviantdb741e72016-09-07 07:08:43 +0000394 if (!Cmd->Sym)
395 return;
396
Rui Ueyama4f2f50d2016-12-21 08:40:09 +0000397 if (auto *Body = dyn_cast<DefinedSynthetic>(Cmd->Sym)) {
Eugene Leviantafaa9342016-11-16 09:49:39 +0000398 Body->Section = Cmd->Expression.Section();
399 Body->Value = Cmd->Expression(Value) - Body->Section->Addr;
Eugene Leviantdb741e72016-09-07 07:08:43 +0000400 return;
401 }
402 auto *Body = cast<DefinedRegular<ELFT>>(Cmd->Sym);
Rafael Espindola498ed712016-10-31 14:44:41 +0000403 Body->Value = Cmd->Expression(Value);
Eugene Leviantdb741e72016-09-07 07:08:43 +0000404}
405
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000406template <class ELFT> static bool isTbss(OutputSectionBase *Sec) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000407 return (Sec->Flags & SHF_TLS) && Sec->Type == SHT_NOBITS;
Rafael Espindolaa940e532016-09-22 12:35:44 +0000408}
409
Rafael Espindolad3190792016-09-16 15:10:23 +0000410template <class ELFT> void LinkerScript<ELFT>::output(InputSection<ELFT> *S) {
411 if (!AlreadyOutputIS.insert(S).second)
412 return;
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000413 bool IsTbss = isTbss<ELFT>(CurOutSec);
Eugene Leviant20889c52016-08-31 08:13:33 +0000414
Rafael Espindolad3190792016-09-16 15:10:23 +0000415 uintX_t Pos = IsTbss ? Dot + ThreadBssOffset : Dot;
416 Pos = alignTo(Pos, S->Alignment);
Rafael Espindola04a2e342016-11-09 01:42:41 +0000417 S->OutSecOff = Pos - CurOutSec->Addr;
Rafael Espindolad3190792016-09-16 15:10:23 +0000418 Pos += S->getSize();
419
420 // Update output section size after adding each section. This is so that
421 // SIZEOF works correctly in the case below:
422 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
Rafael Espindola04a2e342016-11-09 01:42:41 +0000423 CurOutSec->Size = Pos - CurOutSec->Addr;
Rafael Espindolad3190792016-09-16 15:10:23 +0000424
Rafael Espindola7252ae52016-09-22 12:00:08 +0000425 if (IsTbss)
426 ThreadBssOffset = Pos - Dot;
427 else
Rafael Espindolad3190792016-09-16 15:10:23 +0000428 Dot = Pos;
429}
430
431template <class ELFT> void LinkerScript<ELFT>::flush() {
Rafael Espindola65499b92016-09-23 20:10:47 +0000432 if (!CurOutSec || !AlreadyOutputOS.insert(CurOutSec).second)
433 return;
434 if (auto *OutSec = dyn_cast<OutputSection<ELFT>>(CurOutSec)) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000435 for (InputSection<ELFT> *I : OutSec->Sections)
436 output(I);
Rafael Espindola65499b92016-09-23 20:10:47 +0000437 } else {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000438 Dot += CurOutSec->Size;
Eugene Leviant20889c52016-08-31 08:13:33 +0000439 }
440}
441
442template <class ELFT>
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000443void LinkerScript<ELFT>::switchTo(OutputSectionBase *Sec) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000444 if (CurOutSec == Sec)
445 return;
446 if (AlreadyOutputOS.count(Sec))
447 return;
448
449 flush();
450 CurOutSec = Sec;
451
Rafael Espindola04a2e342016-11-09 01:42:41 +0000452 Dot = alignTo(Dot, CurOutSec->Addralign);
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000453 CurOutSec->Addr = isTbss<ELFT>(CurOutSec) ? Dot + ThreadBssOffset : Dot;
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000454
455 // If neither AT nor AT> is specified for an allocatable section, the linker
456 // will set the LMA such that the difference between VMA and LMA for the
457 // section is the same as the preceding output section in the same region
458 // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
459 CurOutSec->setLMAOffset(LMAOffset);
Rafael Espindolad3190792016-09-16 15:10:23 +0000460}
461
462template <class ELFT> void LinkerScript<ELFT>::process(BaseCommand &Base) {
George Rimare38cbab2016-09-26 19:22:50 +0000463 // This handles the assignments to symbol or to a location counter (.)
Rafael Espindolad3190792016-09-16 15:10:23 +0000464 if (auto *AssignCmd = dyn_cast<SymbolAssignment>(&Base)) {
465 if (AssignCmd->Name == ".") {
466 // Update to location counter means update to section size.
George Rimar14460e02016-12-15 07:27:28 +0000467 uintX_t Val = AssignCmd->Expression(Dot);
468 if (Val < Dot)
469 error("unable to move location counter backward for: " +
470 CurOutSec->Name);
471 Dot = Val;
Rafael Espindola04a2e342016-11-09 01:42:41 +0000472 CurOutSec->Size = Dot - CurOutSec->Addr;
Rafael Espindolad3190792016-09-16 15:10:23 +0000473 return;
474 }
Eugene Leviantafaa9342016-11-16 09:49:39 +0000475 assignSectionSymbol<ELFT>(AssignCmd, Dot);
Eugene Leviantceabe802016-08-11 07:56:43 +0000476 return;
Rui Ueyama2de509c2016-08-12 00:55:08 +0000477 }
George Rimare38cbab2016-09-26 19:22:50 +0000478
479 // Handle BYTE(), SHORT(), LONG(), or QUAD().
480 if (auto *DataCmd = dyn_cast<BytesDataCommand>(&Base)) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000481 DataCmd->Offset = Dot - CurOutSec->Addr;
George Rimare38cbab2016-09-26 19:22:50 +0000482 Dot += DataCmd->Size;
Rafael Espindola04a2e342016-11-09 01:42:41 +0000483 CurOutSec->Size = Dot - CurOutSec->Addr;
George Rimare38cbab2016-09-26 19:22:50 +0000484 return;
485 }
486
Meador Ingeb2d99d62016-11-22 18:01:50 +0000487 if (auto *AssertCmd = dyn_cast<AssertCommand>(&Base)) {
488 AssertCmd->Expression(Dot);
489 return;
490 }
491
George Rimare38cbab2016-09-26 19:22:50 +0000492 // It handles single input section description command,
493 // calculates and assigns the offsets for each section and also
494 // updates the output section size.
Rafael Espindolad3190792016-09-16 15:10:23 +0000495 auto &ICmd = cast<InputSectionDescription>(Base);
496 for (InputSectionData *ID : ICmd.Sections) {
George Rimar3fb5a6d2016-11-29 16:05:27 +0000497 // We tentatively added all synthetic sections at the beginning and removed
498 // empty ones afterwards (because there is no way to know whether they were
499 // going be empty or not other than actually running linker scripts.)
500 // We need to ignore remains of empty sections.
501 if (auto *Sec = dyn_cast<SyntheticSection<ELFT>>(ID))
502 if (Sec->empty())
503 continue;
504
Rafael Espindolad3190792016-09-16 15:10:23 +0000505 auto *IB = static_cast<InputSectionBase<ELFT> *>(ID);
506 switchTo(IB->OutSec);
507 if (auto *I = dyn_cast<InputSection<ELFT>>(IB))
508 output(I);
Rafael Espindola65499b92016-09-23 20:10:47 +0000509 else
510 flush();
Eugene Leviantceabe802016-08-11 07:56:43 +0000511 }
512}
513
George Rimar8f66df92016-08-12 20:38:20 +0000514template <class ELFT>
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000515static std::vector<OutputSectionBase *>
516findSections(StringRef Name, const std::vector<OutputSectionBase *> &Sections) {
517 std::vector<OutputSectionBase *> Ret;
518 for (OutputSectionBase *Sec : Sections)
Eugene Leviant92577642016-10-10 11:23:12 +0000519 if (Sec->getName() == Name)
George Rimara14b13d2016-09-07 10:46:07 +0000520 Ret.push_back(Sec);
521 return Ret;
George Rimar8f66df92016-08-12 20:38:20 +0000522}
523
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000524// This function assigns offsets to input sections and an output section
525// for a single sections command (e.g. ".text { *(.text); }").
Rafael Espindolad3190792016-09-16 15:10:23 +0000526template <class ELFT>
527void LinkerScript<ELFT>::assignOffsets(OutputSectionCommand *Cmd) {
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000528 if (Cmd->LMAExpr)
529 LMAOffset = Cmd->LMAExpr(Dot) - Dot;
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000530 std::vector<OutputSectionBase *> Sections =
531 findSections<ELFT>(Cmd->Name, *OutputSections);
Rafael Espindolad3190792016-09-16 15:10:23 +0000532 if (Sections.empty())
533 return;
534 switchTo(Sections[0]);
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000535
Rafael Espindolad3190792016-09-16 15:10:23 +0000536 // Find the last section output location. We will output orphan sections
537 // there so that end symbols point to the correct location.
538 auto E = std::find_if(Cmd->Commands.rbegin(), Cmd->Commands.rend(),
539 [](const std::unique_ptr<BaseCommand> &Cmd) {
540 return !isa<SymbolAssignment>(*Cmd);
541 })
542 .base();
543 for (auto I = Cmd->Commands.begin(); I != E; ++I)
544 process(**I);
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000545 for (OutputSectionBase *Base : Sections)
Rafael Espindolad3190792016-09-16 15:10:23 +0000546 switchTo(Base);
Rafael Espindola65499b92016-09-23 20:10:47 +0000547 flush();
George Rimarb31dd372016-09-19 13:27:31 +0000548 std::for_each(E, Cmd->Commands.end(),
549 [this](std::unique_ptr<BaseCommand> &B) { process(*B.get()); });
Rafael Espindolad3190792016-09-16 15:10:23 +0000550}
551
Rafael Espindola07fe6122016-11-14 14:23:35 +0000552template <class ELFT> void LinkerScript<ELFT>::removeEmptyCommands() {
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000553 // It is common practice to use very generic linker scripts. So for any
554 // given run some of the output sections in the script will be empty.
555 // We could create corresponding empty output sections, but that would
556 // clutter the output.
557 // We instead remove trivially empty sections. The bfd linker seems even
558 // more aggressive at removing them.
559 auto Pos = std::remove_if(
560 Opt.Commands.begin(), Opt.Commands.end(),
561 [&](const std::unique_ptr<BaseCommand> &Base) {
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000562 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
563 return findSections<ELFT>(Cmd->Name, *OutputSections).empty();
564 return false;
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000565 });
566 Opt.Commands.erase(Pos, Opt.Commands.end());
Rafael Espindola07fe6122016-11-14 14:23:35 +0000567}
568
Rafael Espindola6a537372016-11-14 14:33:49 +0000569static bool isAllSectionDescription(const OutputSectionCommand &Cmd) {
570 for (const std::unique_ptr<BaseCommand> &I : Cmd.Commands)
571 if (!isa<InputSectionDescription>(*I))
572 return false;
573 return true;
574}
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000575
Rafael Espindola6a537372016-11-14 14:33:49 +0000576template <class ELFT> void LinkerScript<ELFT>::adjustSectionsBeforeSorting() {
Rafael Espindola9546fff2016-09-22 14:40:50 +0000577 // If the output section contains only symbol assignments, create a
578 // corresponding output section. The bfd linker seems to only create them if
579 // '.' is assigned to, but creating these section should not have any bad
580 // consequeces and gives us a section to put the symbol in.
581 uintX_t Flags = SHF_ALLOC;
Rafael Espindolaf93b8c22016-11-26 06:55:35 +0000582 uint32_t Type = SHT_NOBITS;
Rafael Espindola9546fff2016-09-22 14:40:50 +0000583 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
584 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
585 if (!Cmd)
586 continue;
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000587 std::vector<OutputSectionBase *> Secs =
588 findSections<ELFT>(Cmd->Name, *OutputSections);
Rafael Espindola9546fff2016-09-22 14:40:50 +0000589 if (!Secs.empty()) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000590 Flags = Secs[0]->Flags;
591 Type = Secs[0]->Type;
Rafael Espindola9546fff2016-09-22 14:40:50 +0000592 continue;
593 }
594
Rafael Espindola6a537372016-11-14 14:33:49 +0000595 if (isAllSectionDescription(*Cmd))
596 continue;
597
Rui Ueyama95642b92016-11-01 23:09:07 +0000598 auto *OutSec = make<OutputSection<ELFT>>(Cmd->Name, Type, Flags);
Rafael Espindola9546fff2016-09-22 14:40:50 +0000599 OutputSections->push_back(OutSec);
600 }
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000601}
602
603template <class ELFT> void LinkerScript<ELFT>::adjustSectionsAfterSorting() {
604 placeOrphanSections();
605
606 // If output section command doesn't specify any segments,
607 // and we haven't previously assigned any section to segment,
608 // then we simply assign section to the very first load segment.
609 // Below is an example of such linker script:
610 // PHDRS { seg PT_LOAD; }
611 // SECTIONS { .aaa : { *(.aaa) } }
612 std::vector<StringRef> DefPhdrs;
613 auto FirstPtLoad =
614 std::find_if(Opt.PhdrsCommands.begin(), Opt.PhdrsCommands.end(),
615 [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; });
616 if (FirstPtLoad != Opt.PhdrsCommands.end())
617 DefPhdrs.push_back(FirstPtLoad->Name);
618
619 // Walk the commands and propagate the program headers to commands that don't
620 // explicitly specify them.
621 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
622 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
623 if (!Cmd)
624 continue;
625 if (Cmd->Phdrs.empty())
626 Cmd->Phdrs = DefPhdrs;
627 else
628 DefPhdrs = Cmd->Phdrs;
629 }
Rafael Espindola6a537372016-11-14 14:33:49 +0000630
631 removeEmptyCommands();
Rafael Espindola9546fff2016-09-22 14:40:50 +0000632}
633
Rafael Espindola15c57952016-09-22 18:05:49 +0000634// When placing orphan sections, we want to place them after symbol assignments
635// so that an orphan after
636// begin_foo = .;
637// foo : { *(foo) }
638// end_foo = .;
639// doesn't break the intended meaning of the begin/end symbols.
640// We don't want to go over sections since Writer<ELFT>::sortSections is the
641// one in charge of deciding the order of the sections.
642// We don't want to go over alignments, since doing so in
643// rx_sec : { *(rx_sec) }
644// . = ALIGN(0x1000);
645// /* The RW PT_LOAD starts here*/
646// rw_sec : { *(rw_sec) }
647// would mean that the RW PT_LOAD would become unaligned.
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000648static bool shouldSkip(const BaseCommand &Cmd) {
Rafael Espindola15c57952016-09-22 18:05:49 +0000649 if (isa<OutputSectionCommand>(Cmd))
650 return false;
651 const auto *Assign = dyn_cast<SymbolAssignment>(&Cmd);
652 if (!Assign)
653 return true;
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000654 return Assign->Name != ".";
Rafael Espindola15c57952016-09-22 18:05:49 +0000655}
656
Rafael Espindola337f9032016-11-14 14:13:32 +0000657// Orphan sections are sections present in the input files which are not
658// explicitly placed into the output file by the linker script. This just
659// places them in the order already decided in OutputSections.
George Rimar93c64022016-12-15 15:38:09 +0000660template <class ELFT> void LinkerScript<ELFT>::placeOrphanSections() {
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000661 // The OutputSections are already in the correct order.
662 // This loops creates or moves commands as needed so that they are in the
663 // correct order.
664 int CmdIndex = 0;
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000665
666 // As a horrible special case, skip the first . assignment if it is before any
667 // section. We do this because it is common to set a load address by starting
668 // the script with ". = 0xabcd" and the expectation is that every section is
669 // after that.
670 auto FirstSectionOrDotAssignment =
671 std::find_if(Opt.Commands.begin(), Opt.Commands.end(),
672 [](const std::unique_ptr<BaseCommand> &Cmd) {
673 if (isa<OutputSectionCommand>(*Cmd))
674 return true;
675 const auto *Assign = dyn_cast<SymbolAssignment>(Cmd.get());
676 if (!Assign)
677 return false;
678 return Assign->Name == ".";
679 });
680 if (FirstSectionOrDotAssignment != Opt.Commands.end()) {
681 CmdIndex = FirstSectionOrDotAssignment - Opt.Commands.begin();
682 if (isa<SymbolAssignment>(**FirstSectionOrDotAssignment))
683 ++CmdIndex;
684 }
685
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000686 for (OutputSectionBase *Sec : *OutputSections) {
George Rimar652852c2016-04-16 10:10:32 +0000687 StringRef Name = Sec->getName();
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000688
689 // Find the last spot where we can insert a command and still get the
Rafael Espindola15c57952016-09-22 18:05:49 +0000690 // correct result.
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000691 auto CmdIter = Opt.Commands.begin() + CmdIndex;
692 auto E = Opt.Commands.end();
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000693 while (CmdIter != E && shouldSkip(**CmdIter)) {
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000694 ++CmdIter;
695 ++CmdIndex;
696 }
697
698 auto Pos =
699 std::find_if(CmdIter, E, [&](const std::unique_ptr<BaseCommand> &Base) {
700 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
701 return Cmd && Cmd->Name == Name;
702 });
703 if (Pos == E) {
704 Opt.Commands.insert(CmdIter,
705 llvm::make_unique<OutputSectionCommand>(Name));
Rafael Espindola15c57952016-09-22 18:05:49 +0000706 ++CmdIndex;
707 continue;
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000708 }
Rafael Espindola15c57952016-09-22 18:05:49 +0000709
710 // Continue from where we found it.
711 CmdIndex = (Pos - Opt.Commands.begin()) + 1;
George Rimar652852c2016-04-16 10:10:32 +0000712 }
Rafael Espindola337f9032016-11-14 14:13:32 +0000713}
714
715template <class ELFT>
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000716void LinkerScript<ELFT>::assignAddresses(std::vector<PhdrEntry> &Phdrs) {
Rui Ueyama7c18c282016-04-18 21:00:40 +0000717 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rafael Espindolabe607332016-09-30 00:16:11 +0000718 Dot = 0;
George Rimar652852c2016-04-16 10:10:32 +0000719
George Rimar076fe152016-07-21 06:43:01 +0000720 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
721 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
Rui Ueyama8d083e62016-07-29 05:48:39 +0000722 if (Cmd->Name == ".") {
723 Dot = Cmd->Expression(Dot);
724 } else if (Cmd->Sym) {
Eugene Leviantafaa9342016-11-16 09:49:39 +0000725 assignSectionSymbol<ELFT>(Cmd, Dot);
Rui Ueyama8d083e62016-07-29 05:48:39 +0000726 }
George Rimar652852c2016-04-16 10:10:32 +0000727 continue;
728 }
729
George Rimareefa7582016-08-04 09:29:31 +0000730 if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
731 Cmd->Expression(Dot);
732 continue;
733 }
734
George Rimar076fe152016-07-21 06:43:01 +0000735 auto *Cmd = cast<OutputSectionCommand>(Base.get());
Rafael Espindolad3190792016-09-16 15:10:23 +0000736 if (Cmd->AddrExpr)
737 Dot = Cmd->AddrExpr(Dot);
Rafael Espindolad3190792016-09-16 15:10:23 +0000738 assignOffsets(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000739 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000740
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000741 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000742 for (OutputSectionBase *Sec : *OutputSections) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000743 if (Sec->Flags & SHF_ALLOC)
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000744 MinVA = std::min<uint64_t>(MinVA, Sec->Addr);
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000745 else
Rafael Espindola04a2e342016-11-09 01:42:41 +0000746 Sec->Addr = 0;
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000747 }
748
Rafael Espindola0d4b6d52016-09-22 16:47:21 +0000749 uintX_t HeaderSize = getHeaderSize();
Rafael Espindola1c570072016-11-21 19:59:33 +0000750 // If the linker script doesn't have PHDRS, add ElfHeader and ProgramHeaders
751 // now that we know we have space.
Rafael Espindola5967c972016-12-19 21:21:07 +0000752 if (HeaderSize <= MinVA && !hasPhdrsCommands())
753 allocateHeaders<ELFT>(Phdrs, *OutputSections);
Rafael Espindola1c570072016-11-21 19:59:33 +0000754
755 // ELF and Program headers need to be right before the first section in
756 // memory. Set their addresses accordingly.
Rafael Espindola28d5f052016-11-21 20:20:04 +0000757 MinVA = alignDown(MinVA - HeaderSize, Config->MaxPageSize);
Rafael Espindola1c570072016-11-21 19:59:33 +0000758 Out<ELFT>::ElfHeader->Addr = MinVA;
759 Out<ELFT>::ProgramHeaders->Addr = Out<ELFT>::ElfHeader->Size + MinVA;
George Rimar652852c2016-04-16 10:10:32 +0000760}
761
Rui Ueyama464daad2016-08-22 04:55:20 +0000762// Creates program headers as instructed by PHDRS linker script command.
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000763template <class ELFT> std::vector<PhdrEntry> LinkerScript<ELFT>::createPhdrs() {
764 std::vector<PhdrEntry> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000765
Rui Ueyama464daad2016-08-22 04:55:20 +0000766 // Process PHDRS and FILEHDR keywords because they are not
767 // real output sections and cannot be added in the following loop.
Eugene Leviantbbe38602016-07-19 09:25:43 +0000768 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000769 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000770 PhdrEntry &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000771
772 if (Cmd.HasFilehdr)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000773 Phdr.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000774 if (Cmd.HasPhdrs)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000775 Phdr.add(Out<ELFT>::ProgramHeaders);
Eugene Leviant56b21c82016-09-09 09:46:16 +0000776
777 if (Cmd.LMAExpr) {
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000778 Phdr.p_paddr = Cmd.LMAExpr(0);
Eugene Leviant56b21c82016-09-09 09:46:16 +0000779 Phdr.HasLMA = true;
780 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000781 }
782
Rui Ueyama464daad2016-08-22 04:55:20 +0000783 // Add output sections to program headers.
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000784 for (OutputSectionBase *Sec : *OutputSections) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000785 if (!(Sec->Flags & SHF_ALLOC))
Eugene Leviantbbe38602016-07-19 09:25:43 +0000786 break;
787
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000788 // Assign headers specified by linker script
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000789 for (size_t Id : getPhdrIndices(Sec->getName())) {
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000790 Ret[Id].add(Sec);
791 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000792 Ret[Id].p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000793 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000794 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000795 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000796}
797
Eugene Leviantf9bc3bd2016-08-16 06:40:58 +0000798template <class ELFT> bool LinkerScript<ELFT>::ignoreInterpSection() {
799 // Ignore .interp section in case we have PHDRS specification
800 // and PT_INTERP isn't listed.
801 return !Opt.PhdrsCommands.empty() &&
802 llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
803 return Cmd.Type == PT_INTERP;
804 }) == Opt.PhdrsCommands.end();
805}
806
George Rimar93c64022016-12-15 15:38:09 +0000807template <class ELFT> uint32_t LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000808 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
809 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
810 if (Cmd->Name == Name)
811 return Cmd->Filler;
Rui Ueyama16068ae2016-11-19 18:05:56 +0000812 return 0;
George Rimare2ee72b2016-02-26 14:48:31 +0000813}
814
George Rimare38cbab2016-09-26 19:22:50 +0000815template <class ELFT>
816static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) {
817 const endianness E = ELFT::TargetEndianness;
818
819 switch (Size) {
820 case 1:
821 *Buf = (uint8_t)Data;
822 break;
823 case 2:
824 write16<E>(Buf, Data);
825 break;
826 case 4:
827 write32<E>(Buf, Data);
828 break;
829 case 8:
830 write64<E>(Buf, Data);
831 break;
832 default:
833 llvm_unreachable("unsupported Size argument");
834 }
835}
836
837template <class ELFT>
838void LinkerScript<ELFT>::writeDataBytes(StringRef Name, uint8_t *Buf) {
839 int I = getSectionIndex(Name);
840 if (I == INT_MAX)
841 return;
842
Rui Ueyama6e68c5e2016-11-19 18:05:58 +0000843 auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I].get());
844 for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
845 if (auto *Data = dyn_cast<BytesDataCommand>(Base.get()))
Meador Inge95c7d8d2016-12-08 23:21:30 +0000846 writeInt<ELFT>(Buf + Data->Offset, Data->Expression(0), Data->Size);
George Rimare38cbab2016-09-26 19:22:50 +0000847}
848
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000849template <class ELFT> bool LinkerScript<ELFT>::hasLMA(StringRef Name) {
George Rimar8ceadb32016-08-17 07:44:19 +0000850 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
851 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000852 if (Cmd->LMAExpr && Cmd->Name == Name)
853 return true;
854 return false;
George Rimar8ceadb32016-08-17 07:44:19 +0000855}
856
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000857// Returns the index of the given section name in linker script
858// SECTIONS commands. Sections are laid out as the same order as they
859// were in the script. If a given name did not appear in the script,
860// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000861template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
Rui Ueyama6e68c5e2016-11-19 18:05:58 +0000862 for (int I = 0, E = Opt.Commands.size(); I != E; ++I)
863 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I].get()))
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000864 if (Cmd->Name == Name)
865 return I;
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000866 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000867}
868
Eugene Leviantbbe38602016-07-19 09:25:43 +0000869template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
870 return !Opt.PhdrsCommands.empty();
871}
872
George Rimar9e694502016-07-29 16:18:47 +0000873template <class ELFT>
Eugene Levianted30ce72016-11-28 09:58:04 +0000874const OutputSectionBase *LinkerScript<ELFT>::getOutputSection(const Twine &Loc,
875 StringRef Name) {
Eugene Leviantafaa9342016-11-16 09:49:39 +0000876 static OutputSectionBase FakeSec("", 0, 0);
George Rimar96659df2016-08-30 09:54:01 +0000877
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000878 for (OutputSectionBase *Sec : *OutputSections)
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000879 if (Sec->getName() == Name)
Eugene Leviantafaa9342016-11-16 09:49:39 +0000880 return Sec;
Eugene Levianted30ce72016-11-28 09:58:04 +0000881
882 error(Loc + ": undefined section " + Name);
Eugene Leviantafaa9342016-11-16 09:49:39 +0000883 return &FakeSec;
Eugene Leviant36fac7f2016-09-08 09:08:30 +0000884}
885
Rui Ueyamaedf75e72016-11-17 20:27:10 +0000886// This function is essentially the same as getOutputSection(Name)->Size,
887// but it won't print out an error message if a given section is not found.
888//
889// Linker script does not create an output section if its content is empty.
890// We want to allow SIZEOF(.foo) where .foo is a section which happened to
891// be empty. That is why this function is different from getOutputSection().
892template <class ELFT>
893uint64_t LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
894 for (OutputSectionBase *Sec : *OutputSections)
895 if (Sec->getName() == Name)
896 return Sec->Size;
897 return 0;
898}
899
George Rimar884e7862016-09-08 08:19:13 +0000900template <class ELFT> uint64_t LinkerScript<ELFT>::getHeaderSize() {
Rafael Espindola0d4b6d52016-09-22 16:47:21 +0000901 return elf::getHeaderSize<ELFT>();
George Rimare32a3592016-08-10 07:59:34 +0000902}
903
George Rimar884e7862016-09-08 08:19:13 +0000904template <class ELFT> uint64_t LinkerScript<ELFT>::getSymbolValue(StringRef S) {
905 if (SymbolBody *B = Symtab<ELFT>::X->find(S))
906 return B->getVA<ELFT>();
907 error("symbol not found: " + S);
908 return 0;
909}
910
George Rimarf34f45f2016-09-23 13:17:23 +0000911template <class ELFT> bool LinkerScript<ELFT>::isDefined(StringRef S) {
912 return Symtab<ELFT>::X->find(S) != nullptr;
913}
914
Rafael Espindola2f831dc2016-10-31 19:56:37 +0000915template <class ELFT> bool LinkerScript<ELFT>::isAbsolute(StringRef S) {
916 SymbolBody *Sym = Symtab<ELFT>::X->find(S);
917 auto *DR = dyn_cast_or_null<DefinedRegular<ELFT>>(Sym);
918 return DR && !DR->Section;
919}
920
Eugene Leviantafaa9342016-11-16 09:49:39 +0000921// Gets section symbol belongs to. Symbol "." doesn't belong to any
922// specific section but isn't absolute at the same time, so we try
923// to find suitable section for it as well.
924template <class ELFT>
925const OutputSectionBase *LinkerScript<ELFT>::getSymbolSection(StringRef S) {
926 SymbolBody *Sym = Symtab<ELFT>::X->find(S);
927 if (!Sym) {
928 if (OutputSections->empty())
929 return nullptr;
930 return CurOutSec ? CurOutSec : (*OutputSections)[0];
931 }
932
933 if (auto *DR = dyn_cast_or_null<DefinedRegular<ELFT>>(Sym))
934 return DR->Section ? DR->Section->OutSec : nullptr;
Rui Ueyama4f2f50d2016-12-21 08:40:09 +0000935 if (auto *DS = dyn_cast_or_null<DefinedSynthetic>(Sym))
Eugene Leviantafaa9342016-11-16 09:49:39 +0000936 return DS->Section;
937
938 return nullptr;
939}
940
Eugene Leviantbbe38602016-07-19 09:25:43 +0000941// Returns indices of ELF headers containing specific section, identified
942// by Name. Each index is a zero based number of ELF header listed within
943// PHDRS {} script block.
944template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000945std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000946 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
947 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000948 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000949 continue;
950
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000951 std::vector<size_t> Ret;
952 for (StringRef PhdrName : Cmd->Phdrs)
Eugene Leviant2a942c42016-12-05 16:38:32 +0000953 Ret.push_back(getPhdrIndex(Cmd->Location, PhdrName));
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000954 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000955 }
George Rimar31d842f2016-07-20 16:43:03 +0000956 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000957}
958
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000959template <class ELFT>
Eugene Leviant2a942c42016-12-05 16:38:32 +0000960size_t LinkerScript<ELFT>::getPhdrIndex(const Twine &Loc, StringRef PhdrName) {
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000961 size_t I = 0;
962 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
963 if (Cmd.Name == PhdrName)
964 return I;
965 ++I;
966 }
Eugene Leviant2a942c42016-12-05 16:38:32 +0000967 error(Loc + ": section header '" + PhdrName + "' is not listed in PHDRS");
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000968 return 0;
969}
970
Eugene Leviant03ff0162016-11-21 15:49:56 +0000971class elf::ScriptParser final : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000972 typedef void (ScriptParser::*Handler)();
973
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000974public:
Rui Ueyama22375f22016-11-25 18:51:54 +0000975 ScriptParser(MemoryBufferRef MB)
976 : ScriptParserBase(MB),
977 IsUnderSysroot(isUnderSysroot(MB.getBufferIdentifier())) {}
George Rimarf23b2322016-02-19 10:45:45 +0000978
George Rimar20b65982016-08-31 09:08:26 +0000979 void readLinkerScript();
980 void readVersionScript();
Rafael Espindolad0ebd842016-12-08 17:54:26 +0000981 void readDynamicList();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000982
983private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000984 void addFile(StringRef Path);
985
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000986 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000987 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000988 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000989 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000990 void readInclude();
Rui Ueyamaee592822015-10-07 00:25:09 +0000991 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000992 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000993 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000994 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000995 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000996 void readSections();
Rui Ueyama95769b42016-08-31 20:03:54 +0000997 void readVersion();
998 void readVersionScriptCommand();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000999
Rui Ueyama113cdec2016-07-24 23:05:57 +00001000 SymbolAssignment *readAssignment(StringRef Name);
George Rimare38cbab2016-09-26 19:22:50 +00001001 BytesDataCommand *readBytesDataCommand(StringRef Tok);
Rui Ueyama16068ae2016-11-19 18:05:56 +00001002 uint32_t readFill();
Rui Ueyama10416562016-08-04 02:03:27 +00001003 OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
Rui Ueyama16068ae2016-11-19 18:05:56 +00001004 uint32_t readOutputSectionFiller(StringRef Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001005 std::vector<StringRef> readOutputSectionPhdrs();
George Rimara2496cb2016-08-30 09:46:59 +00001006 InputSectionDescription *readInputSectionDescription(StringRef Tok);
Eugene Leviantdb688452016-11-03 10:54:58 +00001007 StringMatcher readFilePatterns();
George Rimar07171f22016-09-21 15:56:44 +00001008 std::vector<SectionPattern> readInputSectionsList();
George Rimara2496cb2016-08-30 09:46:59 +00001009 InputSectionDescription *readInputSectionRules(StringRef FilePattern);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001010 unsigned readPhdrType();
George Rimarbe394db2016-09-16 20:21:55 +00001011 SortSectionPolicy readSortKind();
Petr Hoseka35e39c2016-08-16 01:11:16 +00001012 SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
Rafael Espindolac96da112016-11-01 11:30:45 +00001013 SymbolAssignment *readProvideOrAssignment(StringRef Tok);
George Rimar03fc0102016-07-28 07:18:23 +00001014 void readSort();
George Rimareefa7582016-08-04 09:29:31 +00001015 Expr readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001016
1017 Expr readExpr();
1018 Expr readExpr1(Expr Lhs, int MinPrec);
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001019 StringRef readParenLiteral();
Rui Ueyama708019c2016-07-24 18:19:40 +00001020 Expr readPrimary();
1021 Expr readTernary(Expr Cond);
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001022 Expr readParenExpr();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001023
George Rimar20b65982016-08-31 09:08:26 +00001024 // For parsing version script.
Rui Ueyama12450b22016-11-18 06:30:09 +00001025 std::vector<SymbolVersion> readVersionExtern();
1026 void readAnonymousDeclaration();
Rui Ueyama95769b42016-08-31 20:03:54 +00001027 void readVersionDeclaration(StringRef VerStr);
Rui Ueyama12450b22016-11-18 06:30:09 +00001028 std::vector<SymbolVersion> readSymbols();
George Rimar20b65982016-08-31 09:08:26 +00001029
Rui Ueyama07320e42016-04-20 20:13:41 +00001030 ScriptConfiguration &Opt = *ScriptConfig;
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001031 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001032};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001033
Rafael Espindolad0ebd842016-12-08 17:54:26 +00001034void ScriptParser::readDynamicList() {
1035 expect("{");
1036 readAnonymousDeclaration();
1037 if (!atEOF())
1038 setError("EOF expected, but got " + next());
1039}
1040
George Rimar20b65982016-08-31 09:08:26 +00001041void ScriptParser::readVersionScript() {
Rui Ueyama95769b42016-08-31 20:03:54 +00001042 readVersionScriptCommand();
1043 if (!atEOF())
1044 setError("EOF expected, but got " + next());
1045}
1046
1047void ScriptParser::readVersionScriptCommand() {
Rui Ueyama83043f22016-10-17 16:01:53 +00001048 if (consume("{")) {
Rui Ueyama12450b22016-11-18 06:30:09 +00001049 readAnonymousDeclaration();
George Rimar20b65982016-08-31 09:08:26 +00001050 return;
1051 }
1052
Rui Ueyama95769b42016-08-31 20:03:54 +00001053 while (!atEOF() && !Error && peek() != "}") {
George Rimar20b65982016-08-31 09:08:26 +00001054 StringRef VerStr = next();
1055 if (VerStr == "{") {
Rui Ueyama95769b42016-08-31 20:03:54 +00001056 setError("anonymous version definition is used in "
1057 "combination with other version definitions");
George Rimar20b65982016-08-31 09:08:26 +00001058 return;
1059 }
1060 expect("{");
Rui Ueyama95769b42016-08-31 20:03:54 +00001061 readVersionDeclaration(VerStr);
George Rimar20b65982016-08-31 09:08:26 +00001062 }
1063}
1064
Rui Ueyama95769b42016-08-31 20:03:54 +00001065void ScriptParser::readVersion() {
1066 expect("{");
1067 readVersionScriptCommand();
1068 expect("}");
1069}
1070
George Rimar20b65982016-08-31 09:08:26 +00001071void ScriptParser::readLinkerScript() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001072 while (!atEOF()) {
1073 StringRef Tok = next();
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001074 if (Tok == ";")
1075 continue;
1076
Eugene Leviant20d03192016-09-16 15:30:47 +00001077 if (Tok == "ASSERT") {
1078 Opt.Commands.emplace_back(new AssertCommand(readAssert()));
1079 } else if (Tok == "ENTRY") {
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001080 readEntry();
1081 } else if (Tok == "EXTERN") {
1082 readExtern();
1083 } else if (Tok == "GROUP" || Tok == "INPUT") {
1084 readGroup();
1085 } else if (Tok == "INCLUDE") {
1086 readInclude();
1087 } else if (Tok == "OUTPUT") {
1088 readOutput();
1089 } else if (Tok == "OUTPUT_ARCH") {
1090 readOutputArch();
1091 } else if (Tok == "OUTPUT_FORMAT") {
1092 readOutputFormat();
1093 } else if (Tok == "PHDRS") {
1094 readPhdrs();
1095 } else if (Tok == "SEARCH_DIR") {
1096 readSearchDir();
1097 } else if (Tok == "SECTIONS") {
1098 readSections();
1099 } else if (Tok == "VERSION") {
1100 readVersion();
Rafael Espindolac96da112016-11-01 11:30:45 +00001101 } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok)) {
Eugene Leviant20d03192016-09-16 15:30:47 +00001102 Opt.Commands.emplace_back(Cmd);
Petr Hoseke5d3ca52016-08-31 15:31:17 +00001103 } else {
George Rimar57610422016-03-11 14:43:02 +00001104 setError("unknown directive: " + Tok);
Petr Hoseke5d3ca52016-08-31 15:31:17 +00001105 }
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001106 }
1107}
1108
Rui Ueyama717677a2016-02-11 21:17:59 +00001109void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001110 if (IsUnderSysroot && S.startswith("/")) {
Justin Bogner5af16872016-10-17 06:08:48 +00001111 SmallString<128> PathData;
1112 StringRef Path = (Config->Sysroot + S).toStringRef(PathData);
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001113 if (sys::fs::exists(Path)) {
Justin Bogner5af16872016-10-17 06:08:48 +00001114 Driver->addFile(Saver.save(Path));
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001115 return;
1116 }
1117 }
1118
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +00001119 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +00001120 Driver->addFile(S);
1121 } else if (S.startswith("=")) {
1122 if (Config->Sysroot.empty())
1123 Driver->addFile(S.substr(1));
1124 else
1125 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
1126 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +00001127 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +00001128 } else if (sys::fs::exists(S)) {
1129 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +00001130 } else {
Rui Ueyama061f9282016-11-19 19:23:58 +00001131 if (Optional<std::string> Path = findFromSearchPaths(S))
1132 Driver->addFile(Saver.save(*Path));
Rui Ueyama025d59b2016-02-02 20:27:59 +00001133 else
Rui Ueyama061f9282016-11-19 19:23:58 +00001134 setError("unable to find " + S);
Rui Ueyama52a15092015-10-11 03:28:42 +00001135 }
1136}
1137
Rui Ueyama717677a2016-02-11 21:17:59 +00001138void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001139 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +00001140 bool Orig = Config->AsNeeded;
1141 Config->AsNeeded = true;
Rui Ueyama83043f22016-10-17 16:01:53 +00001142 while (!Error && !consume(")"))
George Rimarcd574a52016-09-09 14:35:36 +00001143 addFile(unquote(next()));
Rui Ueyama35da9b62015-10-11 20:59:12 +00001144 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001145}
1146
Rui Ueyama717677a2016-02-11 21:17:59 +00001147void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +00001148 // -e <symbol> takes predecence over ENTRY(<symbol>).
1149 expect("(");
1150 StringRef Tok = next();
1151 if (Config->Entry.empty())
1152 Config->Entry = Tok;
1153 expect(")");
1154}
1155
Rui Ueyama717677a2016-02-11 21:17:59 +00001156void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +00001157 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001158 while (!Error && !consume(")"))
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001159 Config->Undefined.push_back(next());
George Rimar83f406c2015-10-19 17:35:12 +00001160}
1161
Rui Ueyama717677a2016-02-11 21:17:59 +00001162void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001163 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001164 while (!Error && !consume(")")) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001165 StringRef Tok = next();
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001166 if (Tok == "AS_NEEDED")
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001167 readAsNeeded();
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001168 else
George Rimarcd574a52016-09-09 14:35:36 +00001169 addFile(unquote(Tok));
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001170 }
1171}
1172
Rui Ueyama717677a2016-02-11 21:17:59 +00001173void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001174 StringRef Tok = next();
George Rimarcd574a52016-09-09 14:35:36 +00001175 auto MBOrErr = MemoryBuffer::getFile(unquote(Tok));
Rui Ueyama025d59b2016-02-02 20:27:59 +00001176 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +00001177 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001178 return;
1179 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001180 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
George Rimar4fb6e792016-12-21 08:11:49 +00001181 tokenize({Saver.save(MB->getBuffer()), unquote(Tok)});
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001182}
1183
Rui Ueyama717677a2016-02-11 21:17:59 +00001184void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +00001185 // -o <file> takes predecence over OUTPUT(<file>).
1186 expect("(");
1187 StringRef Tok = next();
1188 if (Config->OutputFile.empty())
George Rimarcd574a52016-09-09 14:35:36 +00001189 Config->OutputFile = unquote(Tok);
Rui Ueyamaee592822015-10-07 00:25:09 +00001190 expect(")");
1191}
1192
Rui Ueyama717677a2016-02-11 21:17:59 +00001193void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +00001194 // Error checking only for now.
1195 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001196 skip();
Davide Italiano9159ce92015-10-12 21:50:08 +00001197 expect(")");
1198}
1199
Rui Ueyama717677a2016-02-11 21:17:59 +00001200void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001201 // Error checking only for now.
1202 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001203 skip();
Davide Italiano6836c612015-10-12 21:08:41 +00001204 StringRef Tok = next();
1205 if (Tok == ")")
George Rimar6c55f0e2016-09-08 08:20:30 +00001206 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +00001207 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +00001208 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001209 return;
1210 }
Justin Bogner5424e7c2016-10-17 06:21:13 +00001211 skip();
Davide Italiano6836c612015-10-12 21:08:41 +00001212 expect(",");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001213 skip();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001214 expect(")");
1215}
1216
Eugene Leviantbbe38602016-07-19 09:25:43 +00001217void ScriptParser::readPhdrs() {
1218 expect("{");
Rui Ueyama83043f22016-10-17 16:01:53 +00001219 while (!Error && !consume("}")) {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001220 StringRef Tok = next();
Eugene Leviant56b21c82016-09-09 09:46:16 +00001221 Opt.PhdrsCommands.push_back(
1222 {Tok, PT_NULL, false, false, UINT_MAX, nullptr});
Eugene Leviantbbe38602016-07-19 09:25:43 +00001223 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
1224
1225 PhdrCmd.Type = readPhdrType();
1226 do {
1227 Tok = next();
1228 if (Tok == ";")
1229 break;
1230 if (Tok == "FILEHDR")
1231 PhdrCmd.HasFilehdr = true;
1232 else if (Tok == "PHDRS")
1233 PhdrCmd.HasPhdrs = true;
Eugene Leviant56b21c82016-09-09 09:46:16 +00001234 else if (Tok == "AT")
1235 PhdrCmd.LMAExpr = readParenExpr();
Eugene Leviant865bf862016-07-21 10:43:25 +00001236 else if (Tok == "FLAGS") {
1237 expect("(");
Rafael Espindolaeb685cd2016-08-02 22:14:57 +00001238 // Passing 0 for the value of dot is a bit of a hack. It means that
1239 // we accept expressions like ".|1".
1240 PhdrCmd.Flags = readExpr()(0);
Eugene Leviant865bf862016-07-21 10:43:25 +00001241 expect(")");
1242 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +00001243 setError("unexpected header attribute: " + Tok);
1244 } while (!Error);
1245 }
1246}
1247
Rui Ueyama717677a2016-02-11 21:17:59 +00001248void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +00001249 expect("(");
Rui Ueyama86c5fb82016-09-08 23:26:54 +00001250 StringRef Tok = next();
Rui Ueyama6c7ad132016-09-02 19:20:33 +00001251 if (!Config->Nostdlib)
George Rimarcd574a52016-09-09 14:35:36 +00001252 Config->SearchPaths.push_back(unquote(Tok));
Davide Italiano68a39a62015-10-08 17:51:41 +00001253 expect(")");
1254}
1255
Rui Ueyama717677a2016-02-11 21:17:59 +00001256void ScriptParser::readSections() {
Eugene Leviante05336ff2016-09-14 08:32:36 +00001257 Opt.HasSections = true;
George Rimar18a30962016-11-28 10:11:10 +00001258 // -no-rosegment is used to avoid placing read only non-executable sections in
1259 // their own segment. We do the same if SECTIONS command is present in linker
1260 // script. See comment for computeFlags().
1261 Config->SingleRoRx = true;
1262
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);
Eugene Leviant2a942c42016-12-05 16:38:32 +00001428 Cmd->Location = getCurrentLocation();
George Rimar58e5c4d2016-07-25 08:29:46 +00001429
1430 // Read an address expression.
1431 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
1432 if (peek() != ":")
1433 Cmd->AddrExpr = readExpr();
1434
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001435 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +00001436
Rui Ueyama83043f22016-10-17 16:01:53 +00001437 if (consume("AT"))
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001438 Cmd->LMAExpr = readParenExpr();
Rui Ueyama83043f22016-10-17 16:01:53 +00001439 if (consume("ALIGN"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001440 Cmd->AlignExpr = readParenExpr();
Rui Ueyama83043f22016-10-17 16:01:53 +00001441 if (consume("SUBALIGN"))
George Rimardb24d9c2016-08-19 15:18:23 +00001442 Cmd->SubalignExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001443
Davide Italiano246f6812016-07-22 03:36:24 +00001444 // Parse constraints.
Rui Ueyama83043f22016-10-17 16:01:53 +00001445 if (consume("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001446 Cmd->Constraint = ConstraintKind::ReadOnly;
Rui Ueyama83043f22016-10-17 16:01:53 +00001447 if (consume("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001448 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001449 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001450
Rui Ueyama83043f22016-10-17 16:01:53 +00001451 while (!Error && !consume("}")) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001452 StringRef Tok = next();
Meador Ingeb2d99d62016-11-22 18:01:50 +00001453 if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok)) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001454 Cmd->Commands.emplace_back(Assignment);
Meador Ingeb2d99d62016-11-22 18:01:50 +00001455 } else if (BytesDataCommand *Data = readBytesDataCommand(Tok)) {
George Rimare38cbab2016-09-26 19:22:50 +00001456 Cmd->Commands.emplace_back(Data);
Meador Ingeb2d99d62016-11-22 18:01:50 +00001457 } else if (Tok == "ASSERT") {
1458 Cmd->Commands.emplace_back(new AssertCommand(readAssert()));
1459 expect(";");
1460 } else if (Tok == "FILL") {
George Rimarff1f29e2016-09-06 13:51:57 +00001461 Cmd->Filler = readFill();
Meador Ingeb2d99d62016-11-22 18:01:50 +00001462 } else if (Tok == "SORT") {
George Rimar03fc0102016-07-28 07:18:23 +00001463 readSort();
Meador Ingeb2d99d62016-11-22 18:01:50 +00001464 } else if (peek() == "(") {
George Rimara2496cb2016-08-30 09:46:59 +00001465 Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
Meador Ingeb2d99d62016-11-22 18:01:50 +00001466 } else {
Eugene Leviantceabe802016-08-11 07:56:43 +00001467 setError("unknown command " + Tok);
Meador Ingeb2d99d62016-11-22 18:01:50 +00001468 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001469 }
George Rimar076fe152016-07-21 06:43:01 +00001470 Cmd->Phdrs = readOutputSectionPhdrs();
George Rimar4ebc5622016-09-23 13:29:20 +00001471
Rui Ueyama83043f22016-10-17 16:01:53 +00001472 if (consume("="))
George Rimar4ebc5622016-09-23 13:29:20 +00001473 Cmd->Filler = readOutputSectionFiller(next());
1474 else if (peek().startswith("="))
George Rimarff1f29e2016-09-06 13:51:57 +00001475 Cmd->Filler = readOutputSectionFiller(next().drop_front());
George Rimar4ebc5622016-09-23 13:29:20 +00001476
Rui Ueyama10416562016-08-04 02:03:27 +00001477 return Cmd;
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001478}
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001479
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001480// Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
1481// https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
1482//
1483// ld.gold is not fully compatible with ld.bfd. ld.bfd handles
1484// hexstrings as blobs of arbitrary sizes, while ld.gold handles them
1485// as 32-bit big-endian values. We will do the same as ld.gold does
1486// because it's simpler than what ld.bfd does.
Rui Ueyama16068ae2016-11-19 18:05:56 +00001487uint32_t ScriptParser::readOutputSectionFiller(StringRef Tok) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001488 uint32_t V;
Rui Ueyama16068ae2016-11-19 18:05:56 +00001489 if (!Tok.getAsInteger(0, V))
1490 return V;
1491 setError("invalid filler expression: " + Tok);
1492 return 0;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001493}
1494
Petr Hoseka35e39c2016-08-16 01:11:16 +00001495SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
Eugene Levianta31c91b2016-07-22 07:38:40 +00001496 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +00001497 SymbolAssignment *Cmd = readAssignment(next());
Petr Hoseka35e39c2016-08-16 01:11:16 +00001498 Cmd->Provide = Provide;
Rui Ueyama174e0a12016-07-29 00:29:25 +00001499 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001500 expect(")");
1501 expect(";");
Rui Ueyama10416562016-08-04 02:03:27 +00001502 return Cmd;
Eugene Levianteda81a12016-07-12 06:39:48 +00001503}
1504
Rafael Espindolac96da112016-11-01 11:30:45 +00001505SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001506 SymbolAssignment *Cmd = nullptr;
1507 if (peek() == "=" || peek() == "+=") {
1508 Cmd = readAssignment(Tok);
1509 expect(";");
1510 } else if (Tok == "PROVIDE") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001511 Cmd = readProvideHidden(true, false);
1512 } else if (Tok == "HIDDEN") {
1513 Cmd = readProvideHidden(false, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001514 } else if (Tok == "PROVIDE_HIDDEN") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001515 Cmd = readProvideHidden(true, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001516 }
1517 return Cmd;
1518}
1519
George Rimar30835ea2016-07-28 21:08:56 +00001520static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
1521 if (S == ".")
1522 return Dot;
George Rimar884e7862016-09-08 08:19:13 +00001523 return ScriptBase->getSymbolValue(S);
George Rimare32a3592016-08-10 07:59:34 +00001524}
1525
Rafael Espindola2f831dc2016-10-31 19:56:37 +00001526static bool isAbsolute(StringRef S) {
1527 if (S == ".")
1528 return false;
1529 return ScriptBase->isAbsolute(S);
1530}
1531
George Rimar30835ea2016-07-28 21:08:56 +00001532SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1533 StringRef Op = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +00001534 Expr E;
George Rimar30835ea2016-07-28 21:08:56 +00001535 assert(Op == "=" || Op == "+=");
Rui Ueyama83043f22016-10-17 16:01:53 +00001536 if (consume("ABSOLUTE")) {
Rui Ueyama7c1381a2016-10-19 23:11:21 +00001537 // The RHS may be something like "ABSOLUTE(.) & 0xff".
1538 // Call readExpr1 to read the whole expression.
1539 E = readExpr1(readParenExpr(), 0);
Rui Ueyama009d1742016-11-18 06:49:09 +00001540 E.IsAbsolute = [] { return true; };
Eugene Leviantdb741e72016-09-07 07:08:43 +00001541 } else {
1542 E = readExpr();
1543 }
George Rimar30835ea2016-07-28 21:08:56 +00001544 if (Op == "+=")
1545 E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
Rafael Espindolaf6613932016-10-31 17:43:38 +00001546 return new SymbolAssignment(Name, E);
George Rimar30835ea2016-07-28 21:08:56 +00001547}
1548
1549// This is an operator-precedence parser to parse a linker
1550// script expression.
1551Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
1552
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001553static Expr combine(StringRef Op, Expr L, Expr R) {
1554 if (Op == "*")
1555 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1556 if (Op == "/") {
1557 return [=](uint64_t Dot) -> uint64_t {
1558 uint64_t RHS = R(Dot);
1559 if (RHS == 0) {
1560 error("division by zero");
1561 return 0;
1562 }
1563 return L(Dot) / RHS;
1564 };
1565 }
1566 if (Op == "+")
Rafael Espindola2f831dc2016-10-31 19:56:37 +00001567 return {[=](uint64_t Dot) { return L(Dot) + R(Dot); },
Rui Ueyama009d1742016-11-18 06:49:09 +00001568 [=] { return L.IsAbsolute() && R.IsAbsolute(); },
1569 [=] {
Eugene Leviantafaa9342016-11-16 09:49:39 +00001570 const OutputSectionBase *S = L.Section();
1571 return S ? S : R.Section();
1572 }};
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001573 if (Op == "-")
1574 return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
George Rimarc8ccd1f2016-09-23 13:13:55 +00001575 if (Op == "<<")
1576 return [=](uint64_t Dot) { return L(Dot) << R(Dot); };
1577 if (Op == ">>")
1578 return [=](uint64_t Dot) { return L(Dot) >> R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001579 if (Op == "<")
1580 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
1581 if (Op == ">")
1582 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
1583 if (Op == ">=")
1584 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
1585 if (Op == "<=")
1586 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
1587 if (Op == "==")
1588 return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
1589 if (Op == "!=")
1590 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
1591 if (Op == "&")
1592 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
Rafael Espindolacc3dd622016-08-22 21:33:35 +00001593 if (Op == "|")
1594 return [=](uint64_t Dot) { return L(Dot) | R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001595 llvm_unreachable("invalid operator");
1596}
1597
Rui Ueyama708019c2016-07-24 18:19:40 +00001598// This is a part of the operator-precedence parser. This function
1599// assumes that the remaining token stream starts with an operator.
1600Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1601 while (!atEOF() && !Error) {
1602 // Read an operator and an expression.
Rui Ueyama46247b82016-11-18 06:49:07 +00001603 if (consume("?"))
Rui Ueyama708019c2016-07-24 18:19:40 +00001604 return readTernary(Lhs);
Rui Ueyama46247b82016-11-18 06:49:07 +00001605 StringRef Op1 = peek();
Rui Ueyama708019c2016-07-24 18:19:40 +00001606 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +00001607 break;
Justin Bogner5424e7c2016-10-17 06:21:13 +00001608 skip();
Rui Ueyama708019c2016-07-24 18:19:40 +00001609 Expr Rhs = readPrimary();
1610
1611 // Evaluate the remaining part of the expression first if the
1612 // next operator has greater precedence than the previous one.
1613 // For example, if we have read "+" and "3", and if the next
1614 // operator is "*", then we'll evaluate 3 * ... part first.
1615 while (!atEOF()) {
1616 StringRef Op2 = peek();
1617 if (precedence(Op2) <= precedence(Op1))
1618 break;
1619 Rhs = readExpr1(Rhs, precedence(Op2));
1620 }
1621
1622 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +00001623 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001624 return Lhs;
1625}
1626
1627uint64_t static getConstant(StringRef S) {
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001628 if (S == "COMMONPAGESIZE")
Rui Ueyama708019c2016-07-24 18:19:40 +00001629 return Target->PageSize;
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001630 if (S == "MAXPAGESIZE")
Petr Hosek997f8832016-09-28 15:20:47 +00001631 return Config->MaxPageSize;
Rui Ueyama708019c2016-07-24 18:19:40 +00001632 error("unknown constant: " + S);
1633 return 0;
1634}
1635
Rui Ueyama626e0b02016-09-02 18:19:00 +00001636// Parses Tok as an integer. Returns true if successful.
1637// It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1638// and decimal numbers. Decimal numbers may have "K" (kilo) or
1639// "M" (mega) prefixes.
George Rimar9f2f7ad2016-09-02 16:01:42 +00001640static bool readInteger(StringRef Tok, uint64_t &Result) {
Rui Ueyama46247b82016-11-18 06:49:07 +00001641 // Negative number
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001642 if (Tok.startswith("-")) {
1643 if (!readInteger(Tok.substr(1), Result))
1644 return false;
1645 Result = -Result;
1646 return true;
1647 }
Rui Ueyama46247b82016-11-18 06:49:07 +00001648
1649 // Hexadecimal
George Rimar9f2f7ad2016-09-02 16:01:42 +00001650 if (Tok.startswith_lower("0x"))
1651 return !Tok.substr(2).getAsInteger(16, Result);
1652 if (Tok.endswith_lower("H"))
1653 return !Tok.drop_back().getAsInteger(16, Result);
1654
Rui Ueyama46247b82016-11-18 06:49:07 +00001655 // Decimal
George Rimar9f2f7ad2016-09-02 16:01:42 +00001656 int Suffix = 1;
1657 if (Tok.endswith_lower("K")) {
1658 Suffix = 1024;
1659 Tok = Tok.drop_back();
1660 } else if (Tok.endswith_lower("M")) {
1661 Suffix = 1024 * 1024;
1662 Tok = Tok.drop_back();
1663 }
1664 if (Tok.getAsInteger(10, Result))
1665 return false;
1666 Result *= Suffix;
1667 return true;
1668}
1669
George Rimare38cbab2016-09-26 19:22:50 +00001670BytesDataCommand *ScriptParser::readBytesDataCommand(StringRef Tok) {
1671 int Size = StringSwitch<unsigned>(Tok)
1672 .Case("BYTE", 1)
1673 .Case("SHORT", 2)
1674 .Case("LONG", 4)
1675 .Case("QUAD", 8)
1676 .Default(-1);
1677 if (Size == -1)
1678 return nullptr;
1679
Meador Inge95c7d8d2016-12-08 23:21:30 +00001680 return new BytesDataCommand(readParenExpr(), Size);
George Rimare38cbab2016-09-26 19:22:50 +00001681}
1682
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001683StringRef ScriptParser::readParenLiteral() {
1684 expect("(");
1685 StringRef Tok = next();
1686 expect(")");
1687 return Tok;
1688}
1689
Rui Ueyama708019c2016-07-24 18:19:40 +00001690Expr ScriptParser::readPrimary() {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001691 if (peek() == "(")
1692 return readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001693
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001694 StringRef Tok = next();
Rui Ueyamab5f1c3e2016-12-01 04:36:49 +00001695 std::string Location = getCurrentLocation();
Rui Ueyama708019c2016-07-24 18:19:40 +00001696
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001697 if (Tok == "~") {
1698 Expr E = readPrimary();
1699 return [=](uint64_t Dot) { return ~E(Dot); };
1700 }
1701 if (Tok == "-") {
1702 Expr E = readPrimary();
1703 return [=](uint64_t Dot) { return -E(Dot); };
1704 }
1705
Rui Ueyama708019c2016-07-24 18:19:40 +00001706 // Built-in functions are parsed here.
1707 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
George Rimar96659df2016-08-30 09:54:01 +00001708 if (Tok == "ADDR") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001709 StringRef Name = readParenLiteral();
Eugene Levianted30ce72016-11-28 09:58:04 +00001710 return {[=](uint64_t Dot) {
1711 return ScriptBase->getOutputSection(Location, Name)->Addr;
1712 },
1713 [=] { return false; },
1714 [=] { return ScriptBase->getOutputSection(Location, Name); }};
George Rimar96659df2016-08-30 09:54:01 +00001715 }
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001716 if (Tok == "LOADADDR") {
1717 StringRef Name = readParenLiteral();
Eugene Leviantafaa9342016-11-16 09:49:39 +00001718 return [=](uint64_t Dot) {
Eugene Levianted30ce72016-11-28 09:58:04 +00001719 return ScriptBase->getOutputSection(Location, Name)->getLMA();
Eugene Leviantafaa9342016-11-16 09:49:39 +00001720 };
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001721 }
George Rimareefa7582016-08-04 09:29:31 +00001722 if (Tok == "ASSERT")
1723 return readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001724 if (Tok == "ALIGN") {
Rui Ueyama5d804dc2016-12-16 18:19:35 +00001725 expect("(");
1726 Expr E = readExpr();
1727 if (consume(",")) {
1728 Expr E2 = readExpr();
1729 expect(")");
1730 return [=](uint64_t Dot) { return alignTo(E(Dot), E2(Dot)); };
1731 }
1732 expect(")");
Rui Ueyama708019c2016-07-24 18:19:40 +00001733 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1734 }
1735 if (Tok == "CONSTANT") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001736 StringRef Name = readParenLiteral();
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001737 return [=](uint64_t Dot) { return getConstant(Name); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001738 }
George Rimarf34f45f2016-09-23 13:17:23 +00001739 if (Tok == "DEFINED") {
Rui Ueyama0ee25a62016-11-17 03:52:14 +00001740 StringRef Name = readParenLiteral();
1741 return [=](uint64_t Dot) { return ScriptBase->isDefined(Name) ? 1 : 0; };
George Rimarf34f45f2016-09-23 13:17:23 +00001742 }
Rafael Espindola54c145c2016-07-28 18:16:24 +00001743 if (Tok == "SEGMENT_START") {
1744 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001745 skip();
Rafael Espindola54c145c2016-07-28 18:16:24 +00001746 expect(",");
George Rimar8c658bf2016-09-17 18:14:56 +00001747 Expr E = readExpr();
Rafael Espindola54c145c2016-07-28 18:16:24 +00001748 expect(")");
George Rimar8c658bf2016-09-17 18:14:56 +00001749 return [=](uint64_t Dot) { return E(Dot); };
Rafael Espindola54c145c2016-07-28 18:16:24 +00001750 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001751 if (Tok == "DATA_SEGMENT_ALIGN") {
1752 expect("(");
1753 Expr E = readExpr();
1754 expect(",");
1755 readExpr();
1756 expect(")");
Rui Ueyamaf7791bb2016-07-26 19:34:10 +00001757 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001758 }
1759 if (Tok == "DATA_SEGMENT_END") {
1760 expect("(");
1761 expect(".");
1762 expect(")");
1763 return [](uint64_t Dot) { return Dot; };
1764 }
George Rimar276b4e62016-07-26 17:58:44 +00001765 // GNU linkers implements more complicated logic to handle
1766 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1767 // the next page boundary for simplicity.
1768 if (Tok == "DATA_SEGMENT_RELRO_END") {
1769 expect("(");
Rafael Espindola97bdc722016-09-14 19:14:01 +00001770 readExpr();
George Rimar276b4e62016-07-26 17:58:44 +00001771 expect(",");
1772 readExpr();
1773 expect(")");
1774 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1775 }
George Rimar9e694502016-07-29 16:18:47 +00001776 if (Tok == "SIZEOF") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001777 StringRef Name = readParenLiteral();
Rui Ueyamaedf75e72016-11-17 20:27:10 +00001778 return [=](uint64_t Dot) { return ScriptBase->getOutputSectionSize(Name); };
George Rimar9e694502016-07-29 16:18:47 +00001779 }
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001780 if (Tok == "ALIGNOF") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001781 StringRef Name = readParenLiteral();
Eugene Leviantafaa9342016-11-16 09:49:39 +00001782 return [=](uint64_t Dot) {
Eugene Levianted30ce72016-11-28 09:58:04 +00001783 return ScriptBase->getOutputSection(Location, Name)->Addralign;
Eugene Leviantafaa9342016-11-16 09:49:39 +00001784 };
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001785 }
George Rimare32a3592016-08-10 07:59:34 +00001786 if (Tok == "SIZEOF_HEADERS")
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001787 return [=](uint64_t Dot) { return ScriptBase->getHeaderSize(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001788
George Rimar9f2f7ad2016-09-02 16:01:42 +00001789 // Tok is a literal number.
1790 uint64_t V;
1791 if (readInteger(Tok, V))
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001792 return [=](uint64_t Dot) { return V; };
George Rimar9f2f7ad2016-09-02 16:01:42 +00001793
1794 // Tok is a symbol name.
1795 if (Tok != "." && !isValidCIdentifier(Tok))
1796 setError("malformed number: " + Tok);
Rafael Espindola2f831dc2016-10-31 19:56:37 +00001797 return {[=](uint64_t Dot) { return getSymbolValue(Tok, Dot); },
Rui Ueyama009d1742016-11-18 06:49:09 +00001798 [=] { return isAbsolute(Tok); },
1799 [=] { return ScriptBase->getSymbolSection(Tok); }};
Rui Ueyama708019c2016-07-24 18:19:40 +00001800}
1801
1802Expr ScriptParser::readTernary(Expr Cond) {
Rui Ueyama708019c2016-07-24 18:19:40 +00001803 Expr L = readExpr();
1804 expect(":");
1805 Expr R = readExpr();
1806 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1807}
1808
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001809Expr ScriptParser::readParenExpr() {
1810 expect("(");
1811 Expr E = readExpr();
1812 expect(")");
1813 return E;
1814}
1815
Eugene Leviantbbe38602016-07-19 09:25:43 +00001816std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1817 std::vector<StringRef> Phdrs;
1818 while (!Error && peek().startswith(":")) {
1819 StringRef Tok = next();
George Rimarda841c12016-11-14 10:03:54 +00001820 Phdrs.push_back((Tok.size() == 1) ? next() : Tok.substr(1));
Eugene Leviantbbe38602016-07-19 09:25:43 +00001821 }
1822 return Phdrs;
1823}
1824
George Rimar95dd7182016-10-18 10:49:50 +00001825// Read a program header type name. The next token must be a
1826// name of a program header type or a constant (e.g. "0x3").
Eugene Leviantbbe38602016-07-19 09:25:43 +00001827unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001828 StringRef Tok = next();
George Rimar95dd7182016-10-18 10:49:50 +00001829 uint64_t Val;
1830 if (readInteger(Tok, Val))
1831 return Val;
1832
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001833 unsigned Ret = StringSwitch<unsigned>(Tok)
George Rimar6c55f0e2016-09-08 08:20:30 +00001834 .Case("PT_NULL", PT_NULL)
1835 .Case("PT_LOAD", PT_LOAD)
1836 .Case("PT_DYNAMIC", PT_DYNAMIC)
1837 .Case("PT_INTERP", PT_INTERP)
1838 .Case("PT_NOTE", PT_NOTE)
1839 .Case("PT_SHLIB", PT_SHLIB)
1840 .Case("PT_PHDR", PT_PHDR)
1841 .Case("PT_TLS", PT_TLS)
1842 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1843 .Case("PT_GNU_STACK", PT_GNU_STACK)
1844 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
George Rimar270173f2016-10-14 13:02:22 +00001845 .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
George Rimarcc6e5672016-10-14 10:34:36 +00001846 .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
George Rimara2a32c22016-12-06 17:57:42 +00001847 .Case("PT_OPENBSD_BOOTDATA", PT_OPENBSD_BOOTDATA)
George Rimar6c55f0e2016-09-08 08:20:30 +00001848 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001849
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001850 if (Ret == (unsigned)-1) {
1851 setError("invalid program header type: " + Tok);
1852 return PT_NULL;
1853 }
1854 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001855}
1856
Rui Ueyama12450b22016-11-18 06:30:09 +00001857// Reads a list of symbols, e.g. "{ global: foo; bar; local: *; };".
1858void ScriptParser::readAnonymousDeclaration() {
1859 // Read global symbols first. "global:" is default, so if there's
1860 // no label, we assume global symbols.
1861 if (consume("global:") || peek() != "local:")
1862 Config->VersionScriptGlobals = readSymbols();
1863
1864 // Next, read local symbols.
1865 if (consume("local:")) {
1866 if (consume("*")) {
1867 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1868 expect(";");
1869 } else {
1870 setError("local symbol list for anonymous version is not supported");
1871 }
1872 }
1873 expect("}");
1874 expect(";");
1875}
1876
1877// Reads a list of symbols, e.g. "VerStr { global: foo; bar; local: *; };".
Rui Ueyama95769b42016-08-31 20:03:54 +00001878void ScriptParser::readVersionDeclaration(StringRef VerStr) {
George Rimar20b65982016-08-31 09:08:26 +00001879 // Identifiers start at 2 because 0 and 1 are reserved
1880 // for VER_NDX_LOCAL and VER_NDX_GLOBAL constants.
Rui Ueyamada805c42016-11-17 03:39:21 +00001881 uint16_t VersionId = Config->VersionDefinitions.size() + 2;
George Rimar20b65982016-08-31 09:08:26 +00001882 Config->VersionDefinitions.push_back({VerStr, VersionId});
1883
Rui Ueyama12450b22016-11-18 06:30:09 +00001884 // Read global symbols.
Rui Ueyama83043f22016-10-17 16:01:53 +00001885 if (consume("global:") || peek() != "local:")
Rui Ueyama12450b22016-11-18 06:30:09 +00001886 Config->VersionDefinitions.back().Globals = readSymbols();
1887
1888 // Read local symbols.
1889 if (consume("local:")) {
1890 if (consume("*")) {
1891 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1892 expect(";");
1893 } else {
1894 for (SymbolVersion V : readSymbols())
1895 Config->VersionScriptLocals.push_back(V);
1896 }
1897 }
George Rimar20b65982016-08-31 09:08:26 +00001898 expect("}");
1899
Rui Ueyama12450b22016-11-18 06:30:09 +00001900 // Each version may have a parent version. For example, "Ver2"
1901 // defined as "Ver2 { global: foo; local: *; } Ver1;" has "Ver1"
1902 // as a parent. This version hierarchy is, probably against your
1903 // instinct, purely for hint; the runtime doesn't care about it
1904 // at all. In LLD, we simply ignore it.
1905 if (peek() != ";")
Justin Bogner5424e7c2016-10-17 06:21:13 +00001906 skip();
George Rimar20b65982016-08-31 09:08:26 +00001907 expect(";");
1908}
1909
Rui Ueyama12450b22016-11-18 06:30:09 +00001910// Reads a list of symbols for a versions cript.
1911std::vector<SymbolVersion> ScriptParser::readSymbols() {
1912 std::vector<SymbolVersion> Ret;
George Rimare0fc2422016-11-16 17:59:10 +00001913 for (;;) {
Rafael Espindola1ef90d22016-12-09 16:44:05 +00001914 if (consume("extern")) {
Rui Ueyama12450b22016-11-18 06:30:09 +00001915 for (SymbolVersion V : readVersionExtern())
1916 Ret.push_back(V);
Rafael Espindola1ef90d22016-12-09 16:44:05 +00001917 continue;
1918 }
George Rimare0fc2422016-11-16 17:59:10 +00001919
Rui Ueyama0ee25a62016-11-17 03:52:14 +00001920 if (peek() == "}" || peek() == "local:" || Error)
Rui Ueyama12450b22016-11-18 06:30:09 +00001921 break;
Rui Ueyama0ee25a62016-11-17 03:52:14 +00001922 StringRef Tok = next();
Rui Ueyama12450b22016-11-18 06:30:09 +00001923 Ret.push_back({unquote(Tok), false, hasWildcard(Tok)});
George Rimare0fc2422016-11-16 17:59:10 +00001924 expect(";");
1925 }
Rui Ueyama12450b22016-11-18 06:30:09 +00001926 return Ret;
George Rimare0fc2422016-11-16 17:59:10 +00001927}
1928
Rui Ueyama12450b22016-11-18 06:30:09 +00001929// Reads an "extern C++" directive, e.g.,
1930// "extern "C++" { ns::*; "f(int, double)"; };"
1931std::vector<SymbolVersion> ScriptParser::readVersionExtern() {
Rafael Espindola7e714152016-12-08 17:26:53 +00001932 StringRef Tok = next();
1933 bool IsCXX = Tok == "\"C++\"";
1934 if (!IsCXX && Tok != "\"C\"")
Rafael Espindolad0ebd842016-12-08 17:54:26 +00001935 setError("Unknown language");
George Rimar20b65982016-08-31 09:08:26 +00001936 expect("{");
1937
Rui Ueyama12450b22016-11-18 06:30:09 +00001938 std::vector<SymbolVersion> Ret;
Rui Ueyama0ee25a62016-11-17 03:52:14 +00001939 while (!Error && peek() != "}") {
1940 StringRef Tok = next();
1941 bool HasWildcard = !Tok.startswith("\"") && hasWildcard(Tok);
Rafael Espindola7e714152016-12-08 17:26:53 +00001942 Ret.push_back({unquote(Tok), IsCXX, HasWildcard});
George Rimar20b65982016-08-31 09:08:26 +00001943 expect(";");
1944 }
1945
1946 expect("}");
1947 expect(";");
Rui Ueyama12450b22016-11-18 06:30:09 +00001948 return Ret;
George Rimar20b65982016-08-31 09:08:26 +00001949}
1950
Rui Ueyama07320e42016-04-20 20:13:41 +00001951void elf::readLinkerScript(MemoryBufferRef MB) {
Rui Ueyama22375f22016-11-25 18:51:54 +00001952 ScriptParser(MB).readLinkerScript();
George Rimar20b65982016-08-31 09:08:26 +00001953}
1954
1955void elf::readVersionScript(MemoryBufferRef MB) {
Rui Ueyama22375f22016-11-25 18:51:54 +00001956 ScriptParser(MB).readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001957}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001958
Rafael Espindolad0ebd842016-12-08 17:54:26 +00001959void elf::readDynamicList(MemoryBufferRef MB) {
1960 ScriptParser(MB).readDynamicList();
1961}
1962
Rui Ueyama07320e42016-04-20 20:13:41 +00001963template class elf::LinkerScript<ELF32LE>;
1964template class elf::LinkerScript<ELF32BE>;
1965template class elf::LinkerScript<ELF64LE>;
1966template class elf::LinkerScript<ELF64BE>;