blob: e26ab8ccbf3cc7ddff9f3cababfd3fd3eba99382 [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>
Eugene Leviant20d03192016-09-16 15:30:47 +0000267void LinkerScript<ELFT>::addSection(OutputSectionFactory<ELFT> &Factory,
268 InputSectionBase<ELFT> *Sec,
269 StringRef Name) {
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000270 OutputSectionBase *OutSec;
Eugene Leviant20d03192016-09-16 15:30:47 +0000271 bool IsNew;
Rafael Espindola33713982017-01-05 14:20:35 +0000272 std::tie(OutSec, IsNew) = Factory.create(Sec, Name);
Eugene Leviant20d03192016-09-16 15:30:47 +0000273 if (IsNew)
274 OutputSections->push_back(OutSec);
275 OutSec->addSection(Sec);
276}
277
278template <class ELFT>
279void LinkerScript<ELFT>::processCommands(OutputSectionFactory<ELFT> &Factory) {
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000280 for (unsigned I = 0; I < Opt.Commands.size(); ++I) {
281 auto Iter = Opt.Commands.begin() + I;
282 const std::unique_ptr<BaseCommand> &Base1 = *Iter;
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000283
284 // Handle symbol assignments outside of any output section.
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000285 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base1.get())) {
286 if (shouldDefine<ELFT>(Cmd))
Rafael Espindolab0de56b2016-10-31 21:36:23 +0000287 addSymbol<ELFT>(Cmd);
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000288 continue;
289 }
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000290
Eugene Leviant20d03192016-09-16 15:30:47 +0000291 if (auto *Cmd = dyn_cast<AssertCommand>(Base1.get())) {
292 // If we don't have SECTIONS then output sections have already been
George Rimar194470cd2016-09-17 19:21:05 +0000293 // created by Writer<ELFT>. The LinkerScript<ELFT>::assignAddresses
Eugene Leviant20d03192016-09-16 15:30:47 +0000294 // will not be called, so ASSERT should be evaluated now.
295 if (!Opt.HasSections)
296 Cmd->Expression(0);
297 continue;
298 }
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000299
Eugene Leviantceabe802016-08-11 07:56:43 +0000300 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000301 std::vector<InputSectionBase<ELFT> *> V = createInputSectionList(*Cmd);
302
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000303 // The output section name `/DISCARD/' is special.
304 // Any input section assigned to it is discarded.
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000305 if (Cmd->Name == "/DISCARD/") {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000306 discard(V);
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000307 continue;
308 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000309
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000310 // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive
311 // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input
312 // sections satisfy a given constraint. If not, a directive is handled
313 // as if it wasn't present from the beginning.
314 //
315 // Because we'll iterate over Commands many more times, the easiest
316 // way to "make it as if it wasn't present" is to just remove it.
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000317 if (!matchConstraints<ELFT>(V, Cmd->Constraint)) {
318 for (InputSectionBase<ELFT> *S : V)
Rui Ueyamaf94efdd2016-11-20 23:15:52 +0000319 S->Assigned = false;
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000320 Opt.Commands.erase(Iter);
George Rimardfbbbc82016-09-17 09:50:10 +0000321 --I;
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000322 continue;
323 }
324
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000325 // A directive may contain symbol definitions like this:
326 // ".foo : { ...; bar = .; }". Handle them.
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000327 for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
328 if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base.get()))
329 if (shouldDefine<ELFT>(OutCmd))
330 addSymbol<ELFT>(OutCmd);
331
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000332 // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign
333 // is given, input sections are aligned to that value, whether the
334 // given value is larger or smaller than the original section alignment.
335 if (Cmd->SubalignExpr) {
336 uint32_t Subalign = Cmd->SubalignExpr(0);
337 for (InputSectionBase<ELFT> *S : V)
338 S->Alignment = Subalign;
George Rimardb24d9c2016-08-19 15:18:23 +0000339 }
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000340
341 // Add input sections to an output section.
342 for (InputSectionBase<ELFT> *S : V)
343 addSection(Factory, S, Cmd->Name);
Eugene Leviantceabe802016-08-11 07:56:43 +0000344 }
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000345 }
Eugene Leviant20d03192016-09-16 15:30:47 +0000346}
Eugene Leviante63d81b2016-07-20 14:43:20 +0000347
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000348// Add sections that didn't match any sections command.
Eugene Leviant20d03192016-09-16 15:30:47 +0000349template <class ELFT>
George Rimar93c64022016-12-15 15:38:09 +0000350void LinkerScript<ELFT>::addOrphanSections(
351 OutputSectionFactory<ELFT> &Factory) {
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000352 for (InputSectionBase<ELFT> *S : Symtab<ELFT>::X->Sections)
Rafael Espindola8f9026b2016-11-08 18:23:02 +0000353 if (S->Live && !S->OutSec)
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000354 addSection(Factory, S, getOutputSectionName(S->Name));
Eugene Leviante63d81b2016-07-20 14:43:20 +0000355}
356
Eugene Leviantdb741e72016-09-07 07:08:43 +0000357// Sets value of a section-defined symbol. Two kinds of
358// symbols are processed: synthetic symbols, whose value
359// is an offset from beginning of section and regular
360// symbols whose value is absolute.
361template <class ELFT>
Eugene Leviantafaa9342016-11-16 09:49:39 +0000362static void assignSectionSymbol(SymbolAssignment *Cmd,
Rafael Espindola498ed712016-10-31 14:44:41 +0000363 typename ELFT::uint Value) {
Eugene Leviantdb741e72016-09-07 07:08:43 +0000364 if (!Cmd->Sym)
365 return;
366
Rui Ueyama4f2f50d2016-12-21 08:40:09 +0000367 if (auto *Body = dyn_cast<DefinedSynthetic>(Cmd->Sym)) {
Eugene Leviantafaa9342016-11-16 09:49:39 +0000368 Body->Section = Cmd->Expression.Section();
369 Body->Value = Cmd->Expression(Value) - Body->Section->Addr;
Eugene Leviantdb741e72016-09-07 07:08:43 +0000370 return;
371 }
372 auto *Body = cast<DefinedRegular<ELFT>>(Cmd->Sym);
Rafael Espindola498ed712016-10-31 14:44:41 +0000373 Body->Value = Cmd->Expression(Value);
Eugene Leviantdb741e72016-09-07 07:08:43 +0000374}
375
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000376template <class ELFT> static bool isTbss(OutputSectionBase *Sec) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000377 return (Sec->Flags & SHF_TLS) && Sec->Type == SHT_NOBITS;
Rafael Espindolaa940e532016-09-22 12:35:44 +0000378}
379
Rafael Espindolad3190792016-09-16 15:10:23 +0000380template <class ELFT> void LinkerScript<ELFT>::output(InputSection<ELFT> *S) {
381 if (!AlreadyOutputIS.insert(S).second)
382 return;
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000383 bool IsTbss = isTbss<ELFT>(CurOutSec);
Eugene Leviant20889c52016-08-31 08:13:33 +0000384
Rafael Espindolad3190792016-09-16 15:10:23 +0000385 uintX_t Pos = IsTbss ? Dot + ThreadBssOffset : Dot;
386 Pos = alignTo(Pos, S->Alignment);
Rafael Espindola04a2e342016-11-09 01:42:41 +0000387 S->OutSecOff = Pos - CurOutSec->Addr;
Rafael Espindolad3190792016-09-16 15:10:23 +0000388 Pos += S->getSize();
389
390 // Update output section size after adding each section. This is so that
391 // SIZEOF works correctly in the case below:
392 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
Rafael Espindola04a2e342016-11-09 01:42:41 +0000393 CurOutSec->Size = Pos - CurOutSec->Addr;
Rafael Espindolad3190792016-09-16 15:10:23 +0000394
Rafael Espindola7252ae52016-09-22 12:00:08 +0000395 if (IsTbss)
396 ThreadBssOffset = Pos - Dot;
397 else
Rafael Espindolad3190792016-09-16 15:10:23 +0000398 Dot = Pos;
399}
400
401template <class ELFT> void LinkerScript<ELFT>::flush() {
Rafael Espindola65499b92016-09-23 20:10:47 +0000402 if (!CurOutSec || !AlreadyOutputOS.insert(CurOutSec).second)
403 return;
404 if (auto *OutSec = dyn_cast<OutputSection<ELFT>>(CurOutSec)) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000405 for (InputSection<ELFT> *I : OutSec->Sections)
406 output(I);
Rafael Espindola65499b92016-09-23 20:10:47 +0000407 } else {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000408 Dot += CurOutSec->Size;
Eugene Leviant20889c52016-08-31 08:13:33 +0000409 }
410}
411
412template <class ELFT>
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000413void LinkerScript<ELFT>::switchTo(OutputSectionBase *Sec) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000414 if (CurOutSec == Sec)
415 return;
416 if (AlreadyOutputOS.count(Sec))
417 return;
418
419 flush();
420 CurOutSec = Sec;
421
Rafael Espindola04a2e342016-11-09 01:42:41 +0000422 Dot = alignTo(Dot, CurOutSec->Addralign);
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000423 CurOutSec->Addr = isTbss<ELFT>(CurOutSec) ? Dot + ThreadBssOffset : Dot;
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000424
425 // If neither AT nor AT> is specified for an allocatable section, the linker
426 // will set the LMA such that the difference between VMA and LMA for the
427 // section is the same as the preceding output section in the same region
428 // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
429 CurOutSec->setLMAOffset(LMAOffset);
Rafael Espindolad3190792016-09-16 15:10:23 +0000430}
431
432template <class ELFT> void LinkerScript<ELFT>::process(BaseCommand &Base) {
George Rimare38cbab2016-09-26 19:22:50 +0000433 // This handles the assignments to symbol or to a location counter (.)
Rafael Espindolad3190792016-09-16 15:10:23 +0000434 if (auto *AssignCmd = dyn_cast<SymbolAssignment>(&Base)) {
435 if (AssignCmd->Name == ".") {
436 // Update to location counter means update to section size.
George Rimar14460e02016-12-15 07:27:28 +0000437 uintX_t Val = AssignCmd->Expression(Dot);
438 if (Val < Dot)
439 error("unable to move location counter backward for: " +
440 CurOutSec->Name);
441 Dot = Val;
Rafael Espindola04a2e342016-11-09 01:42:41 +0000442 CurOutSec->Size = Dot - CurOutSec->Addr;
Rafael Espindolad3190792016-09-16 15:10:23 +0000443 return;
444 }
Eugene Leviantafaa9342016-11-16 09:49:39 +0000445 assignSectionSymbol<ELFT>(AssignCmd, Dot);
Eugene Leviantceabe802016-08-11 07:56:43 +0000446 return;
Rui Ueyama2de509c2016-08-12 00:55:08 +0000447 }
George Rimare38cbab2016-09-26 19:22:50 +0000448
449 // Handle BYTE(), SHORT(), LONG(), or QUAD().
450 if (auto *DataCmd = dyn_cast<BytesDataCommand>(&Base)) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000451 DataCmd->Offset = Dot - CurOutSec->Addr;
George Rimare38cbab2016-09-26 19:22:50 +0000452 Dot += DataCmd->Size;
Rafael Espindola04a2e342016-11-09 01:42:41 +0000453 CurOutSec->Size = Dot - CurOutSec->Addr;
George Rimare38cbab2016-09-26 19:22:50 +0000454 return;
455 }
456
Meador Ingeb2d99d62016-11-22 18:01:50 +0000457 if (auto *AssertCmd = dyn_cast<AssertCommand>(&Base)) {
458 AssertCmd->Expression(Dot);
459 return;
460 }
461
George Rimare38cbab2016-09-26 19:22:50 +0000462 // It handles single input section description command,
463 // calculates and assigns the offsets for each section and also
464 // updates the output section size.
Rafael Espindolad3190792016-09-16 15:10:23 +0000465 auto &ICmd = cast<InputSectionDescription>(Base);
466 for (InputSectionData *ID : ICmd.Sections) {
George Rimar3fb5a6d2016-11-29 16:05:27 +0000467 // We tentatively added all synthetic sections at the beginning and removed
468 // empty ones afterwards (because there is no way to know whether they were
469 // going be empty or not other than actually running linker scripts.)
470 // We need to ignore remains of empty sections.
471 if (auto *Sec = dyn_cast<SyntheticSection<ELFT>>(ID))
472 if (Sec->empty())
473 continue;
474
Rafael Espindolad3190792016-09-16 15:10:23 +0000475 auto *IB = static_cast<InputSectionBase<ELFT> *>(ID);
476 switchTo(IB->OutSec);
477 if (auto *I = dyn_cast<InputSection<ELFT>>(IB))
478 output(I);
Rafael Espindola65499b92016-09-23 20:10:47 +0000479 else
480 flush();
Eugene Leviantceabe802016-08-11 07:56:43 +0000481 }
482}
483
George Rimar8f66df92016-08-12 20:38:20 +0000484template <class ELFT>
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000485static std::vector<OutputSectionBase *>
486findSections(StringRef Name, const std::vector<OutputSectionBase *> &Sections) {
487 std::vector<OutputSectionBase *> Ret;
488 for (OutputSectionBase *Sec : Sections)
Eugene Leviant92577642016-10-10 11:23:12 +0000489 if (Sec->getName() == Name)
George Rimara14b13d2016-09-07 10:46:07 +0000490 Ret.push_back(Sec);
491 return Ret;
George Rimar8f66df92016-08-12 20:38:20 +0000492}
493
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000494// This function assigns offsets to input sections and an output section
495// for a single sections command (e.g. ".text { *(.text); }").
Rafael Espindolad3190792016-09-16 15:10:23 +0000496template <class ELFT>
497void LinkerScript<ELFT>::assignOffsets(OutputSectionCommand *Cmd) {
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000498 if (Cmd->LMAExpr)
499 LMAOffset = Cmd->LMAExpr(Dot) - Dot;
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000500 std::vector<OutputSectionBase *> Sections =
501 findSections<ELFT>(Cmd->Name, *OutputSections);
Rafael Espindolad3190792016-09-16 15:10:23 +0000502 if (Sections.empty())
503 return;
504 switchTo(Sections[0]);
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000505
Rafael Espindolad3190792016-09-16 15:10:23 +0000506 // Find the last section output location. We will output orphan sections
507 // there so that end symbols point to the correct location.
508 auto E = std::find_if(Cmd->Commands.rbegin(), Cmd->Commands.rend(),
509 [](const std::unique_ptr<BaseCommand> &Cmd) {
510 return !isa<SymbolAssignment>(*Cmd);
511 })
512 .base();
513 for (auto I = Cmd->Commands.begin(); I != E; ++I)
514 process(**I);
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000515 for (OutputSectionBase *Base : Sections)
Rafael Espindolad3190792016-09-16 15:10:23 +0000516 switchTo(Base);
Rafael Espindola65499b92016-09-23 20:10:47 +0000517 flush();
George Rimarb31dd372016-09-19 13:27:31 +0000518 std::for_each(E, Cmd->Commands.end(),
519 [this](std::unique_ptr<BaseCommand> &B) { process(*B.get()); });
Rafael Espindolad3190792016-09-16 15:10:23 +0000520}
521
Rafael Espindola07fe6122016-11-14 14:23:35 +0000522template <class ELFT> void LinkerScript<ELFT>::removeEmptyCommands() {
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000523 // It is common practice to use very generic linker scripts. So for any
524 // given run some of the output sections in the script will be empty.
525 // We could create corresponding empty output sections, but that would
526 // clutter the output.
527 // We instead remove trivially empty sections. The bfd linker seems even
528 // more aggressive at removing them.
529 auto Pos = std::remove_if(
530 Opt.Commands.begin(), Opt.Commands.end(),
531 [&](const std::unique_ptr<BaseCommand> &Base) {
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000532 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
533 return findSections<ELFT>(Cmd->Name, *OutputSections).empty();
534 return false;
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000535 });
536 Opt.Commands.erase(Pos, Opt.Commands.end());
Rafael Espindola07fe6122016-11-14 14:23:35 +0000537}
538
Rafael Espindola6a537372016-11-14 14:33:49 +0000539static bool isAllSectionDescription(const OutputSectionCommand &Cmd) {
540 for (const std::unique_ptr<BaseCommand> &I : Cmd.Commands)
541 if (!isa<InputSectionDescription>(*I))
542 return false;
543 return true;
544}
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000545
Rafael Espindola6a537372016-11-14 14:33:49 +0000546template <class ELFT> void LinkerScript<ELFT>::adjustSectionsBeforeSorting() {
Rafael Espindola9546fff2016-09-22 14:40:50 +0000547 // If the output section contains only symbol assignments, create a
548 // corresponding output section. The bfd linker seems to only create them if
549 // '.' is assigned to, but creating these section should not have any bad
550 // consequeces and gives us a section to put the symbol in.
551 uintX_t Flags = SHF_ALLOC;
Rafael Espindolaf93b8c22016-11-26 06:55:35 +0000552 uint32_t Type = SHT_NOBITS;
Rafael Espindola9546fff2016-09-22 14:40:50 +0000553 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
554 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
555 if (!Cmd)
556 continue;
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000557 std::vector<OutputSectionBase *> Secs =
558 findSections<ELFT>(Cmd->Name, *OutputSections);
Rafael Espindola9546fff2016-09-22 14:40:50 +0000559 if (!Secs.empty()) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000560 Flags = Secs[0]->Flags;
561 Type = Secs[0]->Type;
Rafael Espindola9546fff2016-09-22 14:40:50 +0000562 continue;
563 }
564
Rafael Espindola6a537372016-11-14 14:33:49 +0000565 if (isAllSectionDescription(*Cmd))
566 continue;
567
Rui Ueyama95642b92016-11-01 23:09:07 +0000568 auto *OutSec = make<OutputSection<ELFT>>(Cmd->Name, Type, Flags);
Rafael Espindola9546fff2016-09-22 14:40:50 +0000569 OutputSections->push_back(OutSec);
570 }
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000571}
572
573template <class ELFT> void LinkerScript<ELFT>::adjustSectionsAfterSorting() {
574 placeOrphanSections();
575
576 // If output section command doesn't specify any segments,
577 // and we haven't previously assigned any section to segment,
578 // then we simply assign section to the very first load segment.
579 // Below is an example of such linker script:
580 // PHDRS { seg PT_LOAD; }
581 // SECTIONS { .aaa : { *(.aaa) } }
582 std::vector<StringRef> DefPhdrs;
583 auto FirstPtLoad =
584 std::find_if(Opt.PhdrsCommands.begin(), Opt.PhdrsCommands.end(),
585 [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; });
586 if (FirstPtLoad != Opt.PhdrsCommands.end())
587 DefPhdrs.push_back(FirstPtLoad->Name);
588
589 // Walk the commands and propagate the program headers to commands that don't
590 // explicitly specify them.
591 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
592 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
593 if (!Cmd)
594 continue;
595 if (Cmd->Phdrs.empty())
596 Cmd->Phdrs = DefPhdrs;
597 else
598 DefPhdrs = Cmd->Phdrs;
599 }
Rafael Espindola6a537372016-11-14 14:33:49 +0000600
601 removeEmptyCommands();
Rafael Espindola9546fff2016-09-22 14:40:50 +0000602}
603
Rafael Espindola15c57952016-09-22 18:05:49 +0000604// When placing orphan sections, we want to place them after symbol assignments
605// so that an orphan after
606// begin_foo = .;
607// foo : { *(foo) }
608// end_foo = .;
609// doesn't break the intended meaning of the begin/end symbols.
610// We don't want to go over sections since Writer<ELFT>::sortSections is the
611// one in charge of deciding the order of the sections.
612// We don't want to go over alignments, since doing so in
613// rx_sec : { *(rx_sec) }
614// . = ALIGN(0x1000);
615// /* The RW PT_LOAD starts here*/
616// rw_sec : { *(rw_sec) }
617// would mean that the RW PT_LOAD would become unaligned.
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000618static bool shouldSkip(const BaseCommand &Cmd) {
Rafael Espindola15c57952016-09-22 18:05:49 +0000619 if (isa<OutputSectionCommand>(Cmd))
620 return false;
621 const auto *Assign = dyn_cast<SymbolAssignment>(&Cmd);
622 if (!Assign)
623 return true;
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000624 return Assign->Name != ".";
Rafael Espindola15c57952016-09-22 18:05:49 +0000625}
626
Rafael Espindola337f9032016-11-14 14:13:32 +0000627// Orphan sections are sections present in the input files which are not
628// explicitly placed into the output file by the linker script. This just
629// places them in the order already decided in OutputSections.
George Rimar93c64022016-12-15 15:38:09 +0000630template <class ELFT> void LinkerScript<ELFT>::placeOrphanSections() {
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000631 // The OutputSections are already in the correct order.
632 // This loops creates or moves commands as needed so that they are in the
633 // correct order.
634 int CmdIndex = 0;
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000635
636 // As a horrible special case, skip the first . assignment if it is before any
637 // section. We do this because it is common to set a load address by starting
638 // the script with ". = 0xabcd" and the expectation is that every section is
639 // after that.
640 auto FirstSectionOrDotAssignment =
641 std::find_if(Opt.Commands.begin(), Opt.Commands.end(),
642 [](const std::unique_ptr<BaseCommand> &Cmd) {
643 if (isa<OutputSectionCommand>(*Cmd))
644 return true;
645 const auto *Assign = dyn_cast<SymbolAssignment>(Cmd.get());
646 if (!Assign)
647 return false;
648 return Assign->Name == ".";
649 });
650 if (FirstSectionOrDotAssignment != Opt.Commands.end()) {
651 CmdIndex = FirstSectionOrDotAssignment - Opt.Commands.begin();
652 if (isa<SymbolAssignment>(**FirstSectionOrDotAssignment))
653 ++CmdIndex;
654 }
655
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000656 for (OutputSectionBase *Sec : *OutputSections) {
George Rimar652852c2016-04-16 10:10:32 +0000657 StringRef Name = Sec->getName();
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000658
659 // Find the last spot where we can insert a command and still get the
Rafael Espindola15c57952016-09-22 18:05:49 +0000660 // correct result.
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000661 auto CmdIter = Opt.Commands.begin() + CmdIndex;
662 auto E = Opt.Commands.end();
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000663 while (CmdIter != E && shouldSkip(**CmdIter)) {
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000664 ++CmdIter;
665 ++CmdIndex;
666 }
667
668 auto Pos =
669 std::find_if(CmdIter, E, [&](const std::unique_ptr<BaseCommand> &Base) {
670 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
671 return Cmd && Cmd->Name == Name;
672 });
673 if (Pos == E) {
674 Opt.Commands.insert(CmdIter,
675 llvm::make_unique<OutputSectionCommand>(Name));
Rafael Espindola15c57952016-09-22 18:05:49 +0000676 ++CmdIndex;
677 continue;
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000678 }
Rafael Espindola15c57952016-09-22 18:05:49 +0000679
680 // Continue from where we found it.
681 CmdIndex = (Pos - Opt.Commands.begin()) + 1;
George Rimar652852c2016-04-16 10:10:32 +0000682 }
Rafael Espindola337f9032016-11-14 14:13:32 +0000683}
684
685template <class ELFT>
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000686void LinkerScript<ELFT>::assignAddresses(std::vector<PhdrEntry> &Phdrs) {
Rui Ueyama7c18c282016-04-18 21:00:40 +0000687 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rafael Espindolabe607332016-09-30 00:16:11 +0000688 Dot = 0;
George Rimar652852c2016-04-16 10:10:32 +0000689
George Rimar076fe152016-07-21 06:43:01 +0000690 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
691 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
Rui Ueyama8d083e62016-07-29 05:48:39 +0000692 if (Cmd->Name == ".") {
693 Dot = Cmd->Expression(Dot);
694 } else if (Cmd->Sym) {
Eugene Leviantafaa9342016-11-16 09:49:39 +0000695 assignSectionSymbol<ELFT>(Cmd, Dot);
Rui Ueyama8d083e62016-07-29 05:48:39 +0000696 }
George Rimar652852c2016-04-16 10:10:32 +0000697 continue;
698 }
699
George Rimareefa7582016-08-04 09:29:31 +0000700 if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
701 Cmd->Expression(Dot);
702 continue;
703 }
704
George Rimar076fe152016-07-21 06:43:01 +0000705 auto *Cmd = cast<OutputSectionCommand>(Base.get());
Rafael Espindolad3190792016-09-16 15:10:23 +0000706 if (Cmd->AddrExpr)
707 Dot = Cmd->AddrExpr(Dot);
Rafael Espindolad3190792016-09-16 15:10:23 +0000708 assignOffsets(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000709 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000710
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000711 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000712 for (OutputSectionBase *Sec : *OutputSections) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000713 if (Sec->Flags & SHF_ALLOC)
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000714 MinVA = std::min<uint64_t>(MinVA, Sec->Addr);
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000715 else
Rafael Espindola04a2e342016-11-09 01:42:41 +0000716 Sec->Addr = 0;
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000717 }
718
Rafael Espindola0d4b6d52016-09-22 16:47:21 +0000719 uintX_t HeaderSize = getHeaderSize();
Rafael Espindola1c570072016-11-21 19:59:33 +0000720 // If the linker script doesn't have PHDRS, add ElfHeader and ProgramHeaders
721 // now that we know we have space.
Rafael Espindola5967c972016-12-19 21:21:07 +0000722 if (HeaderSize <= MinVA && !hasPhdrsCommands())
723 allocateHeaders<ELFT>(Phdrs, *OutputSections);
Rafael Espindola1c570072016-11-21 19:59:33 +0000724
725 // ELF and Program headers need to be right before the first section in
726 // memory. Set their addresses accordingly.
Rafael Espindola28d5f052016-11-21 20:20:04 +0000727 MinVA = alignDown(MinVA - HeaderSize, Config->MaxPageSize);
Rafael Espindola1c570072016-11-21 19:59:33 +0000728 Out<ELFT>::ElfHeader->Addr = MinVA;
729 Out<ELFT>::ProgramHeaders->Addr = Out<ELFT>::ElfHeader->Size + MinVA;
George Rimar652852c2016-04-16 10:10:32 +0000730}
731
Rui Ueyama464daad2016-08-22 04:55:20 +0000732// Creates program headers as instructed by PHDRS linker script command.
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000733template <class ELFT> std::vector<PhdrEntry> LinkerScript<ELFT>::createPhdrs() {
734 std::vector<PhdrEntry> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000735
Rui Ueyama464daad2016-08-22 04:55:20 +0000736 // Process PHDRS and FILEHDR keywords because they are not
737 // real output sections and cannot be added in the following loop.
Eugene Leviantbbe38602016-07-19 09:25:43 +0000738 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000739 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000740 PhdrEntry &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000741
742 if (Cmd.HasFilehdr)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000743 Phdr.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000744 if (Cmd.HasPhdrs)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000745 Phdr.add(Out<ELFT>::ProgramHeaders);
Eugene Leviant56b21c82016-09-09 09:46:16 +0000746
747 if (Cmd.LMAExpr) {
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000748 Phdr.p_paddr = Cmd.LMAExpr(0);
Eugene Leviant56b21c82016-09-09 09:46:16 +0000749 Phdr.HasLMA = true;
750 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000751 }
752
Rui Ueyama464daad2016-08-22 04:55:20 +0000753 // Add output sections to program headers.
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000754 for (OutputSectionBase *Sec : *OutputSections) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000755 if (!(Sec->Flags & SHF_ALLOC))
Eugene Leviantbbe38602016-07-19 09:25:43 +0000756 break;
757
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000758 // Assign headers specified by linker script
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000759 for (size_t Id : getPhdrIndices(Sec->getName())) {
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000760 Ret[Id].add(Sec);
761 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000762 Ret[Id].p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000763 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000764 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000765 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000766}
767
Eugene Leviantf9bc3bd2016-08-16 06:40:58 +0000768template <class ELFT> bool LinkerScript<ELFT>::ignoreInterpSection() {
769 // Ignore .interp section in case we have PHDRS specification
770 // and PT_INTERP isn't listed.
771 return !Opt.PhdrsCommands.empty() &&
772 llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
773 return Cmd.Type == PT_INTERP;
774 }) == Opt.PhdrsCommands.end();
775}
776
George Rimar93c64022016-12-15 15:38:09 +0000777template <class ELFT> uint32_t LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000778 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
779 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
780 if (Cmd->Name == Name)
781 return Cmd->Filler;
Rui Ueyama16068ae2016-11-19 18:05:56 +0000782 return 0;
George Rimare2ee72b2016-02-26 14:48:31 +0000783}
784
George Rimare38cbab2016-09-26 19:22:50 +0000785template <class ELFT>
786static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) {
787 const endianness E = ELFT::TargetEndianness;
788
789 switch (Size) {
790 case 1:
791 *Buf = (uint8_t)Data;
792 break;
793 case 2:
794 write16<E>(Buf, Data);
795 break;
796 case 4:
797 write32<E>(Buf, Data);
798 break;
799 case 8:
800 write64<E>(Buf, Data);
801 break;
802 default:
803 llvm_unreachable("unsupported Size argument");
804 }
805}
806
807template <class ELFT>
808void LinkerScript<ELFT>::writeDataBytes(StringRef Name, uint8_t *Buf) {
809 int I = getSectionIndex(Name);
810 if (I == INT_MAX)
811 return;
812
Rui Ueyama6e68c5e2016-11-19 18:05:58 +0000813 auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I].get());
814 for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
815 if (auto *Data = dyn_cast<BytesDataCommand>(Base.get()))
Meador Inge95c7d8d2016-12-08 23:21:30 +0000816 writeInt<ELFT>(Buf + Data->Offset, Data->Expression(0), Data->Size);
George Rimare38cbab2016-09-26 19:22:50 +0000817}
818
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000819template <class ELFT> bool LinkerScript<ELFT>::hasLMA(StringRef Name) {
George Rimar8ceadb32016-08-17 07:44:19 +0000820 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
821 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000822 if (Cmd->LMAExpr && Cmd->Name == Name)
823 return true;
824 return false;
George Rimar8ceadb32016-08-17 07:44:19 +0000825}
826
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000827// Returns the index of the given section name in linker script
828// SECTIONS commands. Sections are laid out as the same order as they
829// were in the script. If a given name did not appear in the script,
830// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000831template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
Rui Ueyama6e68c5e2016-11-19 18:05:58 +0000832 for (int I = 0, E = Opt.Commands.size(); I != E; ++I)
833 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I].get()))
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000834 if (Cmd->Name == Name)
835 return I;
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000836 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000837}
838
Eugene Leviantbbe38602016-07-19 09:25:43 +0000839template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
840 return !Opt.PhdrsCommands.empty();
841}
842
George Rimar9e694502016-07-29 16:18:47 +0000843template <class ELFT>
Eugene Levianted30ce72016-11-28 09:58:04 +0000844const OutputSectionBase *LinkerScript<ELFT>::getOutputSection(const Twine &Loc,
845 StringRef Name) {
Eugene Leviantafaa9342016-11-16 09:49:39 +0000846 static OutputSectionBase FakeSec("", 0, 0);
George Rimar96659df2016-08-30 09:54:01 +0000847
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000848 for (OutputSectionBase *Sec : *OutputSections)
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000849 if (Sec->getName() == Name)
Eugene Leviantafaa9342016-11-16 09:49:39 +0000850 return Sec;
Eugene Levianted30ce72016-11-28 09:58:04 +0000851
852 error(Loc + ": undefined section " + Name);
Eugene Leviantafaa9342016-11-16 09:49:39 +0000853 return &FakeSec;
Eugene Leviant36fac7f2016-09-08 09:08:30 +0000854}
855
Rui Ueyamaedf75e72016-11-17 20:27:10 +0000856// This function is essentially the same as getOutputSection(Name)->Size,
857// but it won't print out an error message if a given section is not found.
858//
859// Linker script does not create an output section if its content is empty.
860// We want to allow SIZEOF(.foo) where .foo is a section which happened to
861// be empty. That is why this function is different from getOutputSection().
862template <class ELFT>
863uint64_t LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
864 for (OutputSectionBase *Sec : *OutputSections)
865 if (Sec->getName() == Name)
866 return Sec->Size;
867 return 0;
868}
869
George Rimar884e7862016-09-08 08:19:13 +0000870template <class ELFT> uint64_t LinkerScript<ELFT>::getHeaderSize() {
Rafael Espindola0d4b6d52016-09-22 16:47:21 +0000871 return elf::getHeaderSize<ELFT>();
George Rimare32a3592016-08-10 07:59:34 +0000872}
873
Eugene Leviantf6aeed32016-12-22 13:13:12 +0000874template <class ELFT>
875uint64_t LinkerScript<ELFT>::getSymbolValue(const Twine &Loc, StringRef S) {
George Rimar884e7862016-09-08 08:19:13 +0000876 if (SymbolBody *B = Symtab<ELFT>::X->find(S))
877 return B->getVA<ELFT>();
Eugene Leviantf6aeed32016-12-22 13:13:12 +0000878 error(Loc + ": symbol not found: " + S);
George Rimar884e7862016-09-08 08:19:13 +0000879 return 0;
880}
881
George Rimarf34f45f2016-09-23 13:17:23 +0000882template <class ELFT> bool LinkerScript<ELFT>::isDefined(StringRef S) {
883 return Symtab<ELFT>::X->find(S) != nullptr;
884}
885
Rafael Espindola2f831dc2016-10-31 19:56:37 +0000886template <class ELFT> bool LinkerScript<ELFT>::isAbsolute(StringRef S) {
887 SymbolBody *Sym = Symtab<ELFT>::X->find(S);
888 auto *DR = dyn_cast_or_null<DefinedRegular<ELFT>>(Sym);
889 return DR && !DR->Section;
890}
891
Eugene Leviantafaa9342016-11-16 09:49:39 +0000892// Gets section symbol belongs to. Symbol "." doesn't belong to any
893// specific section but isn't absolute at the same time, so we try
894// to find suitable section for it as well.
895template <class ELFT>
896const OutputSectionBase *LinkerScript<ELFT>::getSymbolSection(StringRef S) {
897 SymbolBody *Sym = Symtab<ELFT>::X->find(S);
898 if (!Sym) {
899 if (OutputSections->empty())
900 return nullptr;
901 return CurOutSec ? CurOutSec : (*OutputSections)[0];
902 }
903
904 if (auto *DR = dyn_cast_or_null<DefinedRegular<ELFT>>(Sym))
905 return DR->Section ? DR->Section->OutSec : nullptr;
Rui Ueyama4f2f50d2016-12-21 08:40:09 +0000906 if (auto *DS = dyn_cast_or_null<DefinedSynthetic>(Sym))
Eugene Leviantafaa9342016-11-16 09:49:39 +0000907 return DS->Section;
908
909 return nullptr;
910}
911
Eugene Leviantbbe38602016-07-19 09:25:43 +0000912// Returns indices of ELF headers containing specific section, identified
913// by Name. Each index is a zero based number of ELF header listed within
914// PHDRS {} script block.
915template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000916std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000917 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
918 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000919 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000920 continue;
921
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000922 std::vector<size_t> Ret;
923 for (StringRef PhdrName : Cmd->Phdrs)
Eugene Leviant2a942c42016-12-05 16:38:32 +0000924 Ret.push_back(getPhdrIndex(Cmd->Location, PhdrName));
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000925 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000926 }
George Rimar31d842f2016-07-20 16:43:03 +0000927 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000928}
929
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000930template <class ELFT>
Eugene Leviant2a942c42016-12-05 16:38:32 +0000931size_t LinkerScript<ELFT>::getPhdrIndex(const Twine &Loc, StringRef PhdrName) {
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000932 size_t I = 0;
933 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
934 if (Cmd.Name == PhdrName)
935 return I;
936 ++I;
937 }
Eugene Leviant2a942c42016-12-05 16:38:32 +0000938 error(Loc + ": section header '" + PhdrName + "' is not listed in PHDRS");
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000939 return 0;
940}
941
Eugene Leviant03ff0162016-11-21 15:49:56 +0000942class elf::ScriptParser final : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000943 typedef void (ScriptParser::*Handler)();
944
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000945public:
Rui Ueyama22375f22016-11-25 18:51:54 +0000946 ScriptParser(MemoryBufferRef MB)
947 : ScriptParserBase(MB),
948 IsUnderSysroot(isUnderSysroot(MB.getBufferIdentifier())) {}
George Rimarf23b2322016-02-19 10:45:45 +0000949
George Rimar20b65982016-08-31 09:08:26 +0000950 void readLinkerScript();
951 void readVersionScript();
Rafael Espindolad0ebd842016-12-08 17:54:26 +0000952 void readDynamicList();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000953
954private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000955 void addFile(StringRef Path);
956
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000957 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000958 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000959 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000960 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000961 void readInclude();
Rui Ueyamaee592822015-10-07 00:25:09 +0000962 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000963 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000964 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000965 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000966 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000967 void readSections();
Rui Ueyama95769b42016-08-31 20:03:54 +0000968 void readVersion();
969 void readVersionScriptCommand();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000970
Rui Ueyama113cdec2016-07-24 23:05:57 +0000971 SymbolAssignment *readAssignment(StringRef Name);
George Rimare38cbab2016-09-26 19:22:50 +0000972 BytesDataCommand *readBytesDataCommand(StringRef Tok);
Rui Ueyama16068ae2016-11-19 18:05:56 +0000973 uint32_t readFill();
Rui Ueyama10416562016-08-04 02:03:27 +0000974 OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
Rui Ueyama16068ae2016-11-19 18:05:56 +0000975 uint32_t readOutputSectionFiller(StringRef Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000976 std::vector<StringRef> readOutputSectionPhdrs();
George Rimara2496cb2016-08-30 09:46:59 +0000977 InputSectionDescription *readInputSectionDescription(StringRef Tok);
Eugene Leviantdb688452016-11-03 10:54:58 +0000978 StringMatcher readFilePatterns();
George Rimar07171f22016-09-21 15:56:44 +0000979 std::vector<SectionPattern> readInputSectionsList();
George Rimara2496cb2016-08-30 09:46:59 +0000980 InputSectionDescription *readInputSectionRules(StringRef FilePattern);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000981 unsigned readPhdrType();
George Rimarbe394db2016-09-16 20:21:55 +0000982 SortSectionPolicy readSortKind();
Petr Hoseka35e39c2016-08-16 01:11:16 +0000983 SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
Rafael Espindolac96da112016-11-01 11:30:45 +0000984 SymbolAssignment *readProvideOrAssignment(StringRef Tok);
George Rimar03fc0102016-07-28 07:18:23 +0000985 void readSort();
George Rimareefa7582016-08-04 09:29:31 +0000986 Expr readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +0000987
988 Expr readExpr();
989 Expr readExpr1(Expr Lhs, int MinPrec);
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000990 StringRef readParenLiteral();
Rui Ueyama708019c2016-07-24 18:19:40 +0000991 Expr readPrimary();
992 Expr readTernary(Expr Cond);
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +0000993 Expr readParenExpr();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000994
George Rimar20b65982016-08-31 09:08:26 +0000995 // For parsing version script.
Rui Ueyama12450b22016-11-18 06:30:09 +0000996 std::vector<SymbolVersion> readVersionExtern();
997 void readAnonymousDeclaration();
Rui Ueyama95769b42016-08-31 20:03:54 +0000998 void readVersionDeclaration(StringRef VerStr);
Rui Ueyama12450b22016-11-18 06:30:09 +0000999 std::vector<SymbolVersion> readSymbols();
George Rimar20b65982016-08-31 09:08:26 +00001000
Rui Ueyama07320e42016-04-20 20:13:41 +00001001 ScriptConfiguration &Opt = *ScriptConfig;
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001002 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001003};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001004
Rafael Espindolad0ebd842016-12-08 17:54:26 +00001005void ScriptParser::readDynamicList() {
1006 expect("{");
1007 readAnonymousDeclaration();
1008 if (!atEOF())
1009 setError("EOF expected, but got " + next());
1010}
1011
George Rimar20b65982016-08-31 09:08:26 +00001012void ScriptParser::readVersionScript() {
Rui Ueyama95769b42016-08-31 20:03:54 +00001013 readVersionScriptCommand();
1014 if (!atEOF())
1015 setError("EOF expected, but got " + next());
1016}
1017
1018void ScriptParser::readVersionScriptCommand() {
Rui Ueyama83043f22016-10-17 16:01:53 +00001019 if (consume("{")) {
Rui Ueyama12450b22016-11-18 06:30:09 +00001020 readAnonymousDeclaration();
George Rimar20b65982016-08-31 09:08:26 +00001021 return;
1022 }
1023
Rui Ueyama95769b42016-08-31 20:03:54 +00001024 while (!atEOF() && !Error && peek() != "}") {
George Rimar20b65982016-08-31 09:08:26 +00001025 StringRef VerStr = next();
1026 if (VerStr == "{") {
Rui Ueyama95769b42016-08-31 20:03:54 +00001027 setError("anonymous version definition is used in "
1028 "combination with other version definitions");
George Rimar20b65982016-08-31 09:08:26 +00001029 return;
1030 }
1031 expect("{");
Rui Ueyama95769b42016-08-31 20:03:54 +00001032 readVersionDeclaration(VerStr);
George Rimar20b65982016-08-31 09:08:26 +00001033 }
1034}
1035
Rui Ueyama95769b42016-08-31 20:03:54 +00001036void ScriptParser::readVersion() {
1037 expect("{");
1038 readVersionScriptCommand();
1039 expect("}");
1040}
1041
George Rimar20b65982016-08-31 09:08:26 +00001042void ScriptParser::readLinkerScript() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001043 while (!atEOF()) {
1044 StringRef Tok = next();
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001045 if (Tok == ";")
1046 continue;
1047
Eugene Leviant20d03192016-09-16 15:30:47 +00001048 if (Tok == "ASSERT") {
1049 Opt.Commands.emplace_back(new AssertCommand(readAssert()));
1050 } else if (Tok == "ENTRY") {
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001051 readEntry();
1052 } else if (Tok == "EXTERN") {
1053 readExtern();
1054 } else if (Tok == "GROUP" || Tok == "INPUT") {
1055 readGroup();
1056 } else if (Tok == "INCLUDE") {
1057 readInclude();
1058 } else if (Tok == "OUTPUT") {
1059 readOutput();
1060 } else if (Tok == "OUTPUT_ARCH") {
1061 readOutputArch();
1062 } else if (Tok == "OUTPUT_FORMAT") {
1063 readOutputFormat();
1064 } else if (Tok == "PHDRS") {
1065 readPhdrs();
1066 } else if (Tok == "SEARCH_DIR") {
1067 readSearchDir();
1068 } else if (Tok == "SECTIONS") {
1069 readSections();
1070 } else if (Tok == "VERSION") {
1071 readVersion();
Rafael Espindolac96da112016-11-01 11:30:45 +00001072 } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok)) {
Eugene Leviant20d03192016-09-16 15:30:47 +00001073 Opt.Commands.emplace_back(Cmd);
Petr Hoseke5d3ca52016-08-31 15:31:17 +00001074 } else {
George Rimar57610422016-03-11 14:43:02 +00001075 setError("unknown directive: " + Tok);
Petr Hoseke5d3ca52016-08-31 15:31:17 +00001076 }
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001077 }
1078}
1079
Rui Ueyama717677a2016-02-11 21:17:59 +00001080void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001081 if (IsUnderSysroot && S.startswith("/")) {
Justin Bogner5af16872016-10-17 06:08:48 +00001082 SmallString<128> PathData;
1083 StringRef Path = (Config->Sysroot + S).toStringRef(PathData);
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001084 if (sys::fs::exists(Path)) {
Justin Bogner5af16872016-10-17 06:08:48 +00001085 Driver->addFile(Saver.save(Path));
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001086 return;
1087 }
1088 }
1089
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +00001090 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +00001091 Driver->addFile(S);
1092 } else if (S.startswith("=")) {
1093 if (Config->Sysroot.empty())
1094 Driver->addFile(S.substr(1));
1095 else
1096 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
1097 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +00001098 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +00001099 } else if (sys::fs::exists(S)) {
1100 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +00001101 } else {
Rui Ueyama061f9282016-11-19 19:23:58 +00001102 if (Optional<std::string> Path = findFromSearchPaths(S))
1103 Driver->addFile(Saver.save(*Path));
Rui Ueyama025d59b2016-02-02 20:27:59 +00001104 else
Rui Ueyama061f9282016-11-19 19:23:58 +00001105 setError("unable to find " + S);
Rui Ueyama52a15092015-10-11 03:28:42 +00001106 }
1107}
1108
Rui Ueyama717677a2016-02-11 21:17:59 +00001109void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001110 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +00001111 bool Orig = Config->AsNeeded;
1112 Config->AsNeeded = true;
Rui Ueyama83043f22016-10-17 16:01:53 +00001113 while (!Error && !consume(")"))
George Rimarcd574a52016-09-09 14:35:36 +00001114 addFile(unquote(next()));
Rui Ueyama35da9b62015-10-11 20:59:12 +00001115 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001116}
1117
Rui Ueyama717677a2016-02-11 21:17:59 +00001118void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +00001119 // -e <symbol> takes predecence over ENTRY(<symbol>).
1120 expect("(");
1121 StringRef Tok = next();
1122 if (Config->Entry.empty())
1123 Config->Entry = Tok;
1124 expect(")");
1125}
1126
Rui Ueyama717677a2016-02-11 21:17:59 +00001127void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +00001128 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001129 while (!Error && !consume(")"))
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001130 Config->Undefined.push_back(next());
George Rimar83f406c2015-10-19 17:35:12 +00001131}
1132
Rui Ueyama717677a2016-02-11 21:17:59 +00001133void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001134 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001135 while (!Error && !consume(")")) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001136 StringRef Tok = next();
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001137 if (Tok == "AS_NEEDED")
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001138 readAsNeeded();
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001139 else
George Rimarcd574a52016-09-09 14:35:36 +00001140 addFile(unquote(Tok));
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001141 }
1142}
1143
Rui Ueyama717677a2016-02-11 21:17:59 +00001144void ScriptParser::readInclude() {
George Rimard4500652016-12-21 09:42:25 +00001145 StringRef Tok = unquote(next());
Rui Ueyamaec1c75e2017-01-09 01:42:02 +00001146
George Rimard4500652016-12-21 09:42:25 +00001147 // https://sourceware.org/binutils/docs/ld/File-Commands.html:
1148 // The file will be searched for in the current directory, and in any
1149 // directory specified with the -L option.
Rui Ueyamaec1c75e2017-01-09 01:42:02 +00001150 if (sys::fs::exists(Tok)) {
1151 if (Optional<MemoryBufferRef> MB = readFile(Tok))
1152 tokenize(*MB);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001153 return;
1154 }
Rui Ueyamaec1c75e2017-01-09 01:42:02 +00001155 if (Optional<std::string> Path = findFromSearchPaths(Tok)) {
1156 if (Optional<MemoryBufferRef> MB = readFile(*Path))
1157 tokenize(*MB);
1158 return;
1159 }
1160 setError("cannot open " + Tok);
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001161}
1162
Rui Ueyama717677a2016-02-11 21:17:59 +00001163void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +00001164 // -o <file> takes predecence over OUTPUT(<file>).
1165 expect("(");
1166 StringRef Tok = next();
1167 if (Config->OutputFile.empty())
George Rimarcd574a52016-09-09 14:35:36 +00001168 Config->OutputFile = unquote(Tok);
Rui Ueyamaee592822015-10-07 00:25:09 +00001169 expect(")");
1170}
1171
Rui Ueyama717677a2016-02-11 21:17:59 +00001172void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +00001173 // Error checking only for now.
1174 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001175 skip();
Davide Italiano9159ce92015-10-12 21:50:08 +00001176 expect(")");
1177}
1178
Rui Ueyama717677a2016-02-11 21:17:59 +00001179void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001180 // Error checking only for now.
1181 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001182 skip();
Davide Italiano6836c612015-10-12 21:08:41 +00001183 StringRef Tok = next();
1184 if (Tok == ")")
George Rimar6c55f0e2016-09-08 08:20:30 +00001185 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +00001186 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +00001187 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001188 return;
1189 }
Justin Bogner5424e7c2016-10-17 06:21:13 +00001190 skip();
Davide Italiano6836c612015-10-12 21:08:41 +00001191 expect(",");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001192 skip();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001193 expect(")");
1194}
1195
Eugene Leviantbbe38602016-07-19 09:25:43 +00001196void ScriptParser::readPhdrs() {
1197 expect("{");
Rui Ueyama83043f22016-10-17 16:01:53 +00001198 while (!Error && !consume("}")) {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001199 StringRef Tok = next();
Eugene Leviant56b21c82016-09-09 09:46:16 +00001200 Opt.PhdrsCommands.push_back(
1201 {Tok, PT_NULL, false, false, UINT_MAX, nullptr});
Eugene Leviantbbe38602016-07-19 09:25:43 +00001202 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
1203
1204 PhdrCmd.Type = readPhdrType();
1205 do {
1206 Tok = next();
1207 if (Tok == ";")
1208 break;
1209 if (Tok == "FILEHDR")
1210 PhdrCmd.HasFilehdr = true;
1211 else if (Tok == "PHDRS")
1212 PhdrCmd.HasPhdrs = true;
Eugene Leviant56b21c82016-09-09 09:46:16 +00001213 else if (Tok == "AT")
1214 PhdrCmd.LMAExpr = readParenExpr();
Eugene Leviant865bf862016-07-21 10:43:25 +00001215 else if (Tok == "FLAGS") {
1216 expect("(");
Rafael Espindolaeb685cd2016-08-02 22:14:57 +00001217 // Passing 0 for the value of dot is a bit of a hack. It means that
1218 // we accept expressions like ".|1".
1219 PhdrCmd.Flags = readExpr()(0);
Eugene Leviant865bf862016-07-21 10:43:25 +00001220 expect(")");
1221 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +00001222 setError("unexpected header attribute: " + Tok);
1223 } while (!Error);
1224 }
1225}
1226
Rui Ueyama717677a2016-02-11 21:17:59 +00001227void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +00001228 expect("(");
Rui Ueyama86c5fb82016-09-08 23:26:54 +00001229 StringRef Tok = next();
Rui Ueyama6c7ad132016-09-02 19:20:33 +00001230 if (!Config->Nostdlib)
George Rimarcd574a52016-09-09 14:35:36 +00001231 Config->SearchPaths.push_back(unquote(Tok));
Davide Italiano68a39a62015-10-08 17:51:41 +00001232 expect(")");
1233}
1234
Rui Ueyama717677a2016-02-11 21:17:59 +00001235void ScriptParser::readSections() {
Eugene Leviante05336ff2016-09-14 08:32:36 +00001236 Opt.HasSections = true;
George Rimar18a30962016-11-28 10:11:10 +00001237 // -no-rosegment is used to avoid placing read only non-executable sections in
1238 // their own segment. We do the same if SECTIONS command is present in linker
1239 // script. See comment for computeFlags().
1240 Config->SingleRoRx = true;
1241
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001242 expect("{");
Rui Ueyama83043f22016-10-17 16:01:53 +00001243 while (!Error && !consume("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +00001244 StringRef Tok = next();
Rafael Espindolac96da112016-11-01 11:30:45 +00001245 BaseCommand *Cmd = readProvideOrAssignment(Tok);
Eugene Leviantceabe802016-08-11 07:56:43 +00001246 if (!Cmd) {
1247 if (Tok == "ASSERT")
1248 Cmd = new AssertCommand(readAssert());
1249 else
1250 Cmd = readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +00001251 }
Rui Ueyama10416562016-08-04 02:03:27 +00001252 Opt.Commands.emplace_back(Cmd);
George Rimar652852c2016-04-16 10:10:32 +00001253 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001254}
1255
Rui Ueyama708019c2016-07-24 18:19:40 +00001256static int precedence(StringRef Op) {
1257 return StringSwitch<int>(Op)
Rui Ueyama0120e3f2016-09-23 18:06:51 +00001258 .Cases("*", "/", 5)
1259 .Cases("+", "-", 4)
1260 .Cases("<<", ">>", 3)
Rui Ueyama9c4ac5f2016-09-23 22:22:34 +00001261 .Cases("<", "<=", ">", ">=", "==", "!=", 2)
Rui Ueyama0120e3f2016-09-23 18:06:51 +00001262 .Cases("&", "|", 1)
Rui Ueyama708019c2016-07-24 18:19:40 +00001263 .Default(-1);
1264}
1265
Eugene Leviantdb688452016-11-03 10:54:58 +00001266StringMatcher ScriptParser::readFilePatterns() {
Rui Ueyama10416562016-08-04 02:03:27 +00001267 std::vector<StringRef> V;
Rui Ueyama83043f22016-10-17 16:01:53 +00001268 while (!Error && !consume(")"))
Rui Ueyama10416562016-08-04 02:03:27 +00001269 V.push_back(next());
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001270 return StringMatcher(V);
George Rimar0702c4e2016-07-29 15:32:46 +00001271}
1272
George Rimarbe394db2016-09-16 20:21:55 +00001273SortSectionPolicy ScriptParser::readSortKind() {
Rui Ueyama83043f22016-10-17 16:01:53 +00001274 if (consume("SORT") || consume("SORT_BY_NAME"))
George Rimarbe394db2016-09-16 20:21:55 +00001275 return SortSectionPolicy::Name;
Rui Ueyama83043f22016-10-17 16:01:53 +00001276 if (consume("SORT_BY_ALIGNMENT"))
George Rimarbe394db2016-09-16 20:21:55 +00001277 return SortSectionPolicy::Alignment;
Rui Ueyama83043f22016-10-17 16:01:53 +00001278 if (consume("SORT_BY_INIT_PRIORITY"))
George Rimarbe394db2016-09-16 20:21:55 +00001279 return SortSectionPolicy::Priority;
Rui Ueyama83043f22016-10-17 16:01:53 +00001280 if (consume("SORT_NONE"))
Rui Ueyamab2a0abd2016-09-16 21:14:55 +00001281 return SortSectionPolicy::None;
1282 return SortSectionPolicy::Default;
George Rimarbe394db2016-09-16 20:21:55 +00001283}
1284
George Rimar395281c2016-09-16 17:42:10 +00001285// Method reads a list of sequence of excluded files and section globs given in
1286// a following form: ((EXCLUDE_FILE(file_pattern+))? section_pattern+)+
1287// Example: *(.foo.1 EXCLUDE_FILE (*a.o) .foo.2 EXCLUDE_FILE (*b.o) .foo.3)
George Rimaraf03be12016-09-17 19:17:25 +00001288// The semantics of that is next:
1289// * Include .foo.1 from every file.
1290// * Include .foo.2 from every file but a.o
1291// * Include .foo.3 from every file but b.o
George Rimar07171f22016-09-21 15:56:44 +00001292std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
1293 std::vector<SectionPattern> Ret;
George Rimar601e9892016-09-21 08:53:21 +00001294 while (!Error && peek() != ")") {
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001295 StringMatcher ExcludeFilePat;
Rui Ueyama83043f22016-10-17 16:01:53 +00001296 if (consume("EXCLUDE_FILE")) {
George Rimar395281c2016-09-16 17:42:10 +00001297 expect("(");
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001298 ExcludeFilePat = readFilePatterns();
George Rimar395281c2016-09-16 17:42:10 +00001299 }
1300
George Rimar601e9892016-09-21 08:53:21 +00001301 std::vector<StringRef> V;
1302 while (!Error && peek() != ")" && peek() != "EXCLUDE_FILE")
1303 V.push_back(next());
1304
1305 if (!V.empty())
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001306 Ret.push_back({std::move(ExcludeFilePat), StringMatcher(V)});
George Rimar601e9892016-09-21 08:53:21 +00001307 else
1308 setError("section pattern is expected");
George Rimar395281c2016-09-16 17:42:10 +00001309 }
George Rimar07171f22016-09-21 15:56:44 +00001310 return Ret;
George Rimar395281c2016-09-16 17:42:10 +00001311}
1312
Rui Ueyamaf8f6f1e2016-11-18 07:03:56 +00001313// Reads contents of "SECTIONS" directive. That directive contains a
1314// list of glob patterns for input sections. The grammar is as follows.
1315//
1316// <patterns> ::= <section-list>
1317// | <sort> "(" <section-list> ")"
1318// | <sort> "(" <sort> "(" <section-list> ")" ")"
1319//
1320// <sort> ::= "SORT" | "SORT_BY_NAME" | "SORT_BY_ALIGNMENT"
1321// | "SORT_BY_INIT_PRIORITY" | "SORT_NONE"
1322//
1323// <section-list> is parsed by readInputSectionsList().
George Rimara2496cb2016-08-30 09:46:59 +00001324InputSectionDescription *
1325ScriptParser::readInputSectionRules(StringRef FilePattern) {
George Rimarc91930a2016-09-02 21:17:20 +00001326 auto *Cmd = new InputSectionDescription(FilePattern);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001327 expect("(");
Rui Ueyamaf373dd72016-11-24 01:43:21 +00001328 while (!Error && !consume(")")) {
George Rimar07171f22016-09-21 15:56:44 +00001329 SortSectionPolicy Outer = readSortKind();
1330 SortSectionPolicy Inner = SortSectionPolicy::Default;
1331 std::vector<SectionPattern> V;
1332 if (Outer != SortSectionPolicy::Default) {
George Rimar350ece42016-08-03 08:35:59 +00001333 expect("(");
George Rimar07171f22016-09-21 15:56:44 +00001334 Inner = readSortKind();
1335 if (Inner != SortSectionPolicy::Default) {
1336 expect("(");
1337 V = readInputSectionsList();
1338 expect(")");
1339 } else {
1340 V = readInputSectionsList();
1341 }
George Rimar350ece42016-08-03 08:35:59 +00001342 expect(")");
1343 } else {
George Rimar07171f22016-09-21 15:56:44 +00001344 V = readInputSectionsList();
George Rimar350ece42016-08-03 08:35:59 +00001345 }
George Rimar0702c4e2016-07-29 15:32:46 +00001346
George Rimar07171f22016-09-21 15:56:44 +00001347 for (SectionPattern &Pat : V) {
1348 Pat.SortInner = Inner;
1349 Pat.SortOuter = Outer;
1350 }
1351
1352 std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns));
1353 }
Rui Ueyama10416562016-08-04 02:03:27 +00001354 return Cmd;
Davide Italianoe7282792016-07-27 01:44:01 +00001355}
1356
George Rimara2496cb2016-08-30 09:46:59 +00001357InputSectionDescription *
1358ScriptParser::readInputSectionDescription(StringRef Tok) {
George Rimar06598002016-07-28 21:51:30 +00001359 // Input section wildcard can be surrounded by KEEP.
1360 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
George Rimara2496cb2016-08-30 09:46:59 +00001361 if (Tok == "KEEP") {
George Rimar06598002016-07-28 21:51:30 +00001362 expect("(");
George Rimara2496cb2016-08-30 09:46:59 +00001363 StringRef FilePattern = next();
1364 InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
George Rimar06598002016-07-28 21:51:30 +00001365 expect(")");
Eugene Leviantcf43f172016-10-05 09:36:59 +00001366 Opt.KeptSections.push_back(Cmd);
Rui Ueyama10416562016-08-04 02:03:27 +00001367 return Cmd;
George Rimar06598002016-07-28 21:51:30 +00001368 }
George Rimara2496cb2016-08-30 09:46:59 +00001369 return readInputSectionRules(Tok);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001370}
1371
George Rimar03fc0102016-07-28 07:18:23 +00001372void ScriptParser::readSort() {
1373 expect("(");
1374 expect("CONSTRUCTORS");
1375 expect(")");
1376}
1377
George Rimareefa7582016-08-04 09:29:31 +00001378Expr ScriptParser::readAssert() {
1379 expect("(");
1380 Expr E = readExpr();
1381 expect(",");
George Rimarcd574a52016-09-09 14:35:36 +00001382 StringRef Msg = unquote(next());
George Rimareefa7582016-08-04 09:29:31 +00001383 expect(")");
1384 return [=](uint64_t Dot) {
1385 uint64_t V = E(Dot);
1386 if (!V)
1387 error(Msg);
1388 return V;
1389 };
1390}
1391
Rui Ueyama25150e82016-09-06 17:46:43 +00001392// Reads a FILL(expr) command. We handle the FILL command as an
1393// alias for =fillexp section attribute, which is different from
1394// what GNU linkers do.
1395// https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
Rui Ueyama16068ae2016-11-19 18:05:56 +00001396uint32_t ScriptParser::readFill() {
George Rimarff1f29e2016-09-06 13:51:57 +00001397 expect("(");
Rui Ueyama16068ae2016-11-19 18:05:56 +00001398 uint32_t V = readOutputSectionFiller(next());
George Rimarff1f29e2016-09-06 13:51:57 +00001399 expect(")");
1400 expect(";");
1401 return V;
1402}
1403
Rui Ueyama10416562016-08-04 02:03:27 +00001404OutputSectionCommand *
1405ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +00001406 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
Eugene Leviant2a942c42016-12-05 16:38:32 +00001407 Cmd->Location = getCurrentLocation();
George Rimar58e5c4d2016-07-25 08:29:46 +00001408
1409 // Read an address expression.
1410 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
1411 if (peek() != ":")
1412 Cmd->AddrExpr = readExpr();
1413
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001414 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +00001415
Rui Ueyama83043f22016-10-17 16:01:53 +00001416 if (consume("AT"))
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001417 Cmd->LMAExpr = readParenExpr();
Rui Ueyama83043f22016-10-17 16:01:53 +00001418 if (consume("ALIGN"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001419 Cmd->AlignExpr = readParenExpr();
Rui Ueyama83043f22016-10-17 16:01:53 +00001420 if (consume("SUBALIGN"))
George Rimardb24d9c2016-08-19 15:18:23 +00001421 Cmd->SubalignExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001422
Davide Italiano246f6812016-07-22 03:36:24 +00001423 // Parse constraints.
Rui Ueyama83043f22016-10-17 16:01:53 +00001424 if (consume("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001425 Cmd->Constraint = ConstraintKind::ReadOnly;
Rui Ueyama83043f22016-10-17 16:01:53 +00001426 if (consume("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001427 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001428 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001429
Rui Ueyama83043f22016-10-17 16:01:53 +00001430 while (!Error && !consume("}")) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001431 StringRef Tok = next();
Meador Ingeb2d99d62016-11-22 18:01:50 +00001432 if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok)) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001433 Cmd->Commands.emplace_back(Assignment);
Meador Ingeb2d99d62016-11-22 18:01:50 +00001434 } else if (BytesDataCommand *Data = readBytesDataCommand(Tok)) {
George Rimare38cbab2016-09-26 19:22:50 +00001435 Cmd->Commands.emplace_back(Data);
Meador Ingeb2d99d62016-11-22 18:01:50 +00001436 } else if (Tok == "ASSERT") {
1437 Cmd->Commands.emplace_back(new AssertCommand(readAssert()));
1438 expect(";");
1439 } else if (Tok == "FILL") {
George Rimarff1f29e2016-09-06 13:51:57 +00001440 Cmd->Filler = readFill();
Meador Ingeb2d99d62016-11-22 18:01:50 +00001441 } else if (Tok == "SORT") {
George Rimar03fc0102016-07-28 07:18:23 +00001442 readSort();
Meador Ingeb2d99d62016-11-22 18:01:50 +00001443 } else if (peek() == "(") {
George Rimara2496cb2016-08-30 09:46:59 +00001444 Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
Meador Ingeb2d99d62016-11-22 18:01:50 +00001445 } else {
Eugene Leviantceabe802016-08-11 07:56:43 +00001446 setError("unknown command " + Tok);
Meador Ingeb2d99d62016-11-22 18:01:50 +00001447 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001448 }
George Rimar076fe152016-07-21 06:43:01 +00001449 Cmd->Phdrs = readOutputSectionPhdrs();
George Rimar4ebc5622016-09-23 13:29:20 +00001450
Rui Ueyama83043f22016-10-17 16:01:53 +00001451 if (consume("="))
George Rimar4ebc5622016-09-23 13:29:20 +00001452 Cmd->Filler = readOutputSectionFiller(next());
1453 else if (peek().startswith("="))
George Rimarff1f29e2016-09-06 13:51:57 +00001454 Cmd->Filler = readOutputSectionFiller(next().drop_front());
George Rimar4ebc5622016-09-23 13:29:20 +00001455
Rui Ueyama10416562016-08-04 02:03:27 +00001456 return Cmd;
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001457}
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001458
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001459// Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
1460// https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
1461//
1462// ld.gold is not fully compatible with ld.bfd. ld.bfd handles
1463// hexstrings as blobs of arbitrary sizes, while ld.gold handles them
1464// as 32-bit big-endian values. We will do the same as ld.gold does
1465// because it's simpler than what ld.bfd does.
Rui Ueyama16068ae2016-11-19 18:05:56 +00001466uint32_t ScriptParser::readOutputSectionFiller(StringRef Tok) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001467 uint32_t V;
Rui Ueyama16068ae2016-11-19 18:05:56 +00001468 if (!Tok.getAsInteger(0, V))
1469 return V;
1470 setError("invalid filler expression: " + Tok);
1471 return 0;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001472}
1473
Petr Hoseka35e39c2016-08-16 01:11:16 +00001474SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
Eugene Levianta31c91b2016-07-22 07:38:40 +00001475 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +00001476 SymbolAssignment *Cmd = readAssignment(next());
Petr Hoseka35e39c2016-08-16 01:11:16 +00001477 Cmd->Provide = Provide;
Rui Ueyama174e0a12016-07-29 00:29:25 +00001478 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001479 expect(")");
1480 expect(";");
Rui Ueyama10416562016-08-04 02:03:27 +00001481 return Cmd;
Eugene Levianteda81a12016-07-12 06:39:48 +00001482}
1483
Rafael Espindolac96da112016-11-01 11:30:45 +00001484SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001485 SymbolAssignment *Cmd = nullptr;
1486 if (peek() == "=" || peek() == "+=") {
1487 Cmd = readAssignment(Tok);
1488 expect(";");
1489 } else if (Tok == "PROVIDE") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001490 Cmd = readProvideHidden(true, false);
1491 } else if (Tok == "HIDDEN") {
1492 Cmd = readProvideHidden(false, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001493 } else if (Tok == "PROVIDE_HIDDEN") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001494 Cmd = readProvideHidden(true, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001495 }
1496 return Cmd;
1497}
1498
Eugene Leviantf6aeed32016-12-22 13:13:12 +00001499static uint64_t getSymbolValue(const Twine &Loc, StringRef S, uint64_t Dot) {
George Rimar30835ea2016-07-28 21:08:56 +00001500 if (S == ".")
1501 return Dot;
Eugene Leviantf6aeed32016-12-22 13:13:12 +00001502 return ScriptBase->getSymbolValue(Loc, S);
George Rimare32a3592016-08-10 07:59:34 +00001503}
1504
Rafael Espindola2f831dc2016-10-31 19:56:37 +00001505static bool isAbsolute(StringRef S) {
1506 if (S == ".")
1507 return false;
1508 return ScriptBase->isAbsolute(S);
1509}
1510
George Rimar30835ea2016-07-28 21:08:56 +00001511SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1512 StringRef Op = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +00001513 Expr E;
George Rimar30835ea2016-07-28 21:08:56 +00001514 assert(Op == "=" || Op == "+=");
Rui Ueyama83043f22016-10-17 16:01:53 +00001515 if (consume("ABSOLUTE")) {
Rui Ueyama7c1381a2016-10-19 23:11:21 +00001516 // The RHS may be something like "ABSOLUTE(.) & 0xff".
1517 // Call readExpr1 to read the whole expression.
1518 E = readExpr1(readParenExpr(), 0);
Rui Ueyama009d1742016-11-18 06:49:09 +00001519 E.IsAbsolute = [] { return true; };
Eugene Leviantdb741e72016-09-07 07:08:43 +00001520 } else {
1521 E = readExpr();
1522 }
Eugene Leviantf6aeed32016-12-22 13:13:12 +00001523 if (Op == "+=") {
1524 std::string Loc = getCurrentLocation();
1525 E = [=](uint64_t Dot) {
1526 return getSymbolValue(Loc, Name, Dot) + E(Dot);
1527 };
1528 }
Rafael Espindolaf6613932016-10-31 17:43:38 +00001529 return new SymbolAssignment(Name, E);
George Rimar30835ea2016-07-28 21:08:56 +00001530}
1531
1532// This is an operator-precedence parser to parse a linker
1533// script expression.
1534Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
1535
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001536static Expr combine(StringRef Op, Expr L, Expr R) {
1537 if (Op == "*")
1538 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1539 if (Op == "/") {
1540 return [=](uint64_t Dot) -> uint64_t {
1541 uint64_t RHS = R(Dot);
1542 if (RHS == 0) {
1543 error("division by zero");
1544 return 0;
1545 }
1546 return L(Dot) / RHS;
1547 };
1548 }
1549 if (Op == "+")
Rafael Espindola2f831dc2016-10-31 19:56:37 +00001550 return {[=](uint64_t Dot) { return L(Dot) + R(Dot); },
Rui Ueyama009d1742016-11-18 06:49:09 +00001551 [=] { return L.IsAbsolute() && R.IsAbsolute(); },
1552 [=] {
Eugene Leviantafaa9342016-11-16 09:49:39 +00001553 const OutputSectionBase *S = L.Section();
1554 return S ? S : R.Section();
1555 }};
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001556 if (Op == "-")
1557 return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
George Rimarc8ccd1f2016-09-23 13:13:55 +00001558 if (Op == "<<")
1559 return [=](uint64_t Dot) { return L(Dot) << R(Dot); };
1560 if (Op == ">>")
1561 return [=](uint64_t Dot) { return L(Dot) >> R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001562 if (Op == "<")
1563 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
1564 if (Op == ">")
1565 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
1566 if (Op == ">=")
1567 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
1568 if (Op == "<=")
1569 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
1570 if (Op == "==")
1571 return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
1572 if (Op == "!=")
1573 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
1574 if (Op == "&")
1575 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
Rafael Espindolacc3dd622016-08-22 21:33:35 +00001576 if (Op == "|")
1577 return [=](uint64_t Dot) { return L(Dot) | R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001578 llvm_unreachable("invalid operator");
1579}
1580
Rui Ueyama708019c2016-07-24 18:19:40 +00001581// This is a part of the operator-precedence parser. This function
1582// assumes that the remaining token stream starts with an operator.
1583Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1584 while (!atEOF() && !Error) {
1585 // Read an operator and an expression.
Rui Ueyama46247b82016-11-18 06:49:07 +00001586 if (consume("?"))
Rui Ueyama708019c2016-07-24 18:19:40 +00001587 return readTernary(Lhs);
Rui Ueyama46247b82016-11-18 06:49:07 +00001588 StringRef Op1 = peek();
Rui Ueyama708019c2016-07-24 18:19:40 +00001589 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +00001590 break;
Justin Bogner5424e7c2016-10-17 06:21:13 +00001591 skip();
Rui Ueyama708019c2016-07-24 18:19:40 +00001592 Expr Rhs = readPrimary();
1593
1594 // Evaluate the remaining part of the expression first if the
1595 // next operator has greater precedence than the previous one.
1596 // For example, if we have read "+" and "3", and if the next
1597 // operator is "*", then we'll evaluate 3 * ... part first.
1598 while (!atEOF()) {
1599 StringRef Op2 = peek();
1600 if (precedence(Op2) <= precedence(Op1))
1601 break;
1602 Rhs = readExpr1(Rhs, precedence(Op2));
1603 }
1604
1605 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +00001606 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001607 return Lhs;
1608}
1609
1610uint64_t static getConstant(StringRef S) {
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001611 if (S == "COMMONPAGESIZE")
Rui Ueyama708019c2016-07-24 18:19:40 +00001612 return Target->PageSize;
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001613 if (S == "MAXPAGESIZE")
Petr Hosek997f8832016-09-28 15:20:47 +00001614 return Config->MaxPageSize;
Rui Ueyama708019c2016-07-24 18:19:40 +00001615 error("unknown constant: " + S);
1616 return 0;
1617}
1618
Rui Ueyama626e0b02016-09-02 18:19:00 +00001619// Parses Tok as an integer. Returns true if successful.
1620// It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1621// and decimal numbers. Decimal numbers may have "K" (kilo) or
1622// "M" (mega) prefixes.
George Rimar9f2f7ad2016-09-02 16:01:42 +00001623static bool readInteger(StringRef Tok, uint64_t &Result) {
Rui Ueyama46247b82016-11-18 06:49:07 +00001624 // Negative number
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001625 if (Tok.startswith("-")) {
1626 if (!readInteger(Tok.substr(1), Result))
1627 return false;
1628 Result = -Result;
1629 return true;
1630 }
Rui Ueyama46247b82016-11-18 06:49:07 +00001631
1632 // Hexadecimal
George Rimar9f2f7ad2016-09-02 16:01:42 +00001633 if (Tok.startswith_lower("0x"))
1634 return !Tok.substr(2).getAsInteger(16, Result);
1635 if (Tok.endswith_lower("H"))
1636 return !Tok.drop_back().getAsInteger(16, Result);
1637
Rui Ueyama46247b82016-11-18 06:49:07 +00001638 // Decimal
George Rimar9f2f7ad2016-09-02 16:01:42 +00001639 int Suffix = 1;
1640 if (Tok.endswith_lower("K")) {
1641 Suffix = 1024;
1642 Tok = Tok.drop_back();
1643 } else if (Tok.endswith_lower("M")) {
1644 Suffix = 1024 * 1024;
1645 Tok = Tok.drop_back();
1646 }
1647 if (Tok.getAsInteger(10, Result))
1648 return false;
1649 Result *= Suffix;
1650 return true;
1651}
1652
George Rimare38cbab2016-09-26 19:22:50 +00001653BytesDataCommand *ScriptParser::readBytesDataCommand(StringRef Tok) {
1654 int Size = StringSwitch<unsigned>(Tok)
1655 .Case("BYTE", 1)
1656 .Case("SHORT", 2)
1657 .Case("LONG", 4)
1658 .Case("QUAD", 8)
1659 .Default(-1);
1660 if (Size == -1)
1661 return nullptr;
1662
Meador Inge95c7d8d2016-12-08 23:21:30 +00001663 return new BytesDataCommand(readParenExpr(), Size);
George Rimare38cbab2016-09-26 19:22:50 +00001664}
1665
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001666StringRef ScriptParser::readParenLiteral() {
1667 expect("(");
1668 StringRef Tok = next();
1669 expect(")");
1670 return Tok;
1671}
1672
Rui Ueyama708019c2016-07-24 18:19:40 +00001673Expr ScriptParser::readPrimary() {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001674 if (peek() == "(")
1675 return readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001676
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001677 StringRef Tok = next();
Rui Ueyamab5f1c3e2016-12-01 04:36:49 +00001678 std::string Location = getCurrentLocation();
Rui Ueyama708019c2016-07-24 18:19:40 +00001679
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001680 if (Tok == "~") {
1681 Expr E = readPrimary();
1682 return [=](uint64_t Dot) { return ~E(Dot); };
1683 }
1684 if (Tok == "-") {
1685 Expr E = readPrimary();
1686 return [=](uint64_t Dot) { return -E(Dot); };
1687 }
1688
Rui Ueyama708019c2016-07-24 18:19:40 +00001689 // Built-in functions are parsed here.
1690 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
George Rimar96659df2016-08-30 09:54:01 +00001691 if (Tok == "ADDR") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001692 StringRef Name = readParenLiteral();
Eugene Levianted30ce72016-11-28 09:58:04 +00001693 return {[=](uint64_t Dot) {
1694 return ScriptBase->getOutputSection(Location, Name)->Addr;
1695 },
1696 [=] { return false; },
1697 [=] { return ScriptBase->getOutputSection(Location, Name); }};
George Rimar96659df2016-08-30 09:54:01 +00001698 }
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001699 if (Tok == "LOADADDR") {
1700 StringRef Name = readParenLiteral();
Eugene Leviantafaa9342016-11-16 09:49:39 +00001701 return [=](uint64_t Dot) {
Eugene Levianted30ce72016-11-28 09:58:04 +00001702 return ScriptBase->getOutputSection(Location, Name)->getLMA();
Eugene Leviantafaa9342016-11-16 09:49:39 +00001703 };
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001704 }
George Rimareefa7582016-08-04 09:29:31 +00001705 if (Tok == "ASSERT")
1706 return readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001707 if (Tok == "ALIGN") {
Rui Ueyama5d804dc2016-12-16 18:19:35 +00001708 expect("(");
1709 Expr E = readExpr();
1710 if (consume(",")) {
1711 Expr E2 = readExpr();
1712 expect(")");
1713 return [=](uint64_t Dot) { return alignTo(E(Dot), E2(Dot)); };
1714 }
1715 expect(")");
Rui Ueyama708019c2016-07-24 18:19:40 +00001716 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1717 }
1718 if (Tok == "CONSTANT") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001719 StringRef Name = readParenLiteral();
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001720 return [=](uint64_t Dot) { return getConstant(Name); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001721 }
George Rimarf34f45f2016-09-23 13:17:23 +00001722 if (Tok == "DEFINED") {
Rui Ueyama0ee25a62016-11-17 03:52:14 +00001723 StringRef Name = readParenLiteral();
1724 return [=](uint64_t Dot) { return ScriptBase->isDefined(Name) ? 1 : 0; };
George Rimarf34f45f2016-09-23 13:17:23 +00001725 }
Rafael Espindola54c145c2016-07-28 18:16:24 +00001726 if (Tok == "SEGMENT_START") {
1727 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001728 skip();
Rafael Espindola54c145c2016-07-28 18:16:24 +00001729 expect(",");
George Rimar8c658bf2016-09-17 18:14:56 +00001730 Expr E = readExpr();
Rafael Espindola54c145c2016-07-28 18:16:24 +00001731 expect(")");
George Rimar8c658bf2016-09-17 18:14:56 +00001732 return [=](uint64_t Dot) { return E(Dot); };
Rafael Espindola54c145c2016-07-28 18:16:24 +00001733 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001734 if (Tok == "DATA_SEGMENT_ALIGN") {
1735 expect("(");
1736 Expr E = readExpr();
1737 expect(",");
1738 readExpr();
1739 expect(")");
Rui Ueyamaf7791bb2016-07-26 19:34:10 +00001740 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001741 }
1742 if (Tok == "DATA_SEGMENT_END") {
1743 expect("(");
1744 expect(".");
1745 expect(")");
1746 return [](uint64_t Dot) { return Dot; };
1747 }
George Rimar276b4e62016-07-26 17:58:44 +00001748 // GNU linkers implements more complicated logic to handle
1749 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1750 // the next page boundary for simplicity.
1751 if (Tok == "DATA_SEGMENT_RELRO_END") {
1752 expect("(");
Rafael Espindola97bdc722016-09-14 19:14:01 +00001753 readExpr();
George Rimar276b4e62016-07-26 17:58:44 +00001754 expect(",");
1755 readExpr();
1756 expect(")");
1757 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1758 }
George Rimar9e694502016-07-29 16:18:47 +00001759 if (Tok == "SIZEOF") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001760 StringRef Name = readParenLiteral();
Rui Ueyamaedf75e72016-11-17 20:27:10 +00001761 return [=](uint64_t Dot) { return ScriptBase->getOutputSectionSize(Name); };
George Rimar9e694502016-07-29 16:18:47 +00001762 }
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001763 if (Tok == "ALIGNOF") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001764 StringRef Name = readParenLiteral();
Eugene Leviantafaa9342016-11-16 09:49:39 +00001765 return [=](uint64_t Dot) {
Eugene Levianted30ce72016-11-28 09:58:04 +00001766 return ScriptBase->getOutputSection(Location, Name)->Addralign;
Eugene Leviantafaa9342016-11-16 09:49:39 +00001767 };
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001768 }
George Rimare32a3592016-08-10 07:59:34 +00001769 if (Tok == "SIZEOF_HEADERS")
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001770 return [=](uint64_t Dot) { return ScriptBase->getHeaderSize(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001771
George Rimar9f2f7ad2016-09-02 16:01:42 +00001772 // Tok is a literal number.
1773 uint64_t V;
1774 if (readInteger(Tok, V))
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001775 return [=](uint64_t Dot) { return V; };
George Rimar9f2f7ad2016-09-02 16:01:42 +00001776
1777 // Tok is a symbol name.
1778 if (Tok != "." && !isValidCIdentifier(Tok))
1779 setError("malformed number: " + Tok);
Eugene Leviantf6aeed32016-12-22 13:13:12 +00001780 return {[=](uint64_t Dot) { return getSymbolValue(Location, Tok, Dot); },
Rui Ueyama009d1742016-11-18 06:49:09 +00001781 [=] { return isAbsolute(Tok); },
1782 [=] { return ScriptBase->getSymbolSection(Tok); }};
Rui Ueyama708019c2016-07-24 18:19:40 +00001783}
1784
1785Expr ScriptParser::readTernary(Expr Cond) {
Rui Ueyama708019c2016-07-24 18:19:40 +00001786 Expr L = readExpr();
1787 expect(":");
1788 Expr R = readExpr();
1789 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1790}
1791
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001792Expr ScriptParser::readParenExpr() {
1793 expect("(");
1794 Expr E = readExpr();
1795 expect(")");
1796 return E;
1797}
1798
Eugene Leviantbbe38602016-07-19 09:25:43 +00001799std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1800 std::vector<StringRef> Phdrs;
1801 while (!Error && peek().startswith(":")) {
1802 StringRef Tok = next();
George Rimarda841c12016-11-14 10:03:54 +00001803 Phdrs.push_back((Tok.size() == 1) ? next() : Tok.substr(1));
Eugene Leviantbbe38602016-07-19 09:25:43 +00001804 }
1805 return Phdrs;
1806}
1807
George Rimar95dd7182016-10-18 10:49:50 +00001808// Read a program header type name. The next token must be a
1809// name of a program header type or a constant (e.g. "0x3").
Eugene Leviantbbe38602016-07-19 09:25:43 +00001810unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001811 StringRef Tok = next();
George Rimar95dd7182016-10-18 10:49:50 +00001812 uint64_t Val;
1813 if (readInteger(Tok, Val))
1814 return Val;
1815
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001816 unsigned Ret = StringSwitch<unsigned>(Tok)
George Rimar6c55f0e2016-09-08 08:20:30 +00001817 .Case("PT_NULL", PT_NULL)
1818 .Case("PT_LOAD", PT_LOAD)
1819 .Case("PT_DYNAMIC", PT_DYNAMIC)
1820 .Case("PT_INTERP", PT_INTERP)
1821 .Case("PT_NOTE", PT_NOTE)
1822 .Case("PT_SHLIB", PT_SHLIB)
1823 .Case("PT_PHDR", PT_PHDR)
1824 .Case("PT_TLS", PT_TLS)
1825 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1826 .Case("PT_GNU_STACK", PT_GNU_STACK)
1827 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
George Rimar270173f2016-10-14 13:02:22 +00001828 .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
George Rimarcc6e5672016-10-14 10:34:36 +00001829 .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
George Rimara2a32c22016-12-06 17:57:42 +00001830 .Case("PT_OPENBSD_BOOTDATA", PT_OPENBSD_BOOTDATA)
George Rimar6c55f0e2016-09-08 08:20:30 +00001831 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001832
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001833 if (Ret == (unsigned)-1) {
1834 setError("invalid program header type: " + Tok);
1835 return PT_NULL;
1836 }
1837 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001838}
1839
Rui Ueyama12450b22016-11-18 06:30:09 +00001840// Reads a list of symbols, e.g. "{ global: foo; bar; local: *; };".
1841void ScriptParser::readAnonymousDeclaration() {
1842 // Read global symbols first. "global:" is default, so if there's
1843 // no label, we assume global symbols.
1844 if (consume("global:") || peek() != "local:")
1845 Config->VersionScriptGlobals = readSymbols();
1846
1847 // Next, read local symbols.
1848 if (consume("local:")) {
1849 if (consume("*")) {
1850 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1851 expect(";");
1852 } else {
1853 setError("local symbol list for anonymous version is not supported");
1854 }
1855 }
1856 expect("}");
1857 expect(";");
1858}
1859
1860// Reads a list of symbols, e.g. "VerStr { global: foo; bar; local: *; };".
Rui Ueyama95769b42016-08-31 20:03:54 +00001861void ScriptParser::readVersionDeclaration(StringRef VerStr) {
George Rimar20b65982016-08-31 09:08:26 +00001862 // Identifiers start at 2 because 0 and 1 are reserved
1863 // for VER_NDX_LOCAL and VER_NDX_GLOBAL constants.
Rui Ueyamada805c42016-11-17 03:39:21 +00001864 uint16_t VersionId = Config->VersionDefinitions.size() + 2;
George Rimar20b65982016-08-31 09:08:26 +00001865 Config->VersionDefinitions.push_back({VerStr, VersionId});
1866
Rui Ueyama12450b22016-11-18 06:30:09 +00001867 // Read global symbols.
Rui Ueyama83043f22016-10-17 16:01:53 +00001868 if (consume("global:") || peek() != "local:")
Rui Ueyama12450b22016-11-18 06:30:09 +00001869 Config->VersionDefinitions.back().Globals = readSymbols();
1870
1871 // Read local symbols.
1872 if (consume("local:")) {
1873 if (consume("*")) {
1874 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1875 expect(";");
1876 } else {
1877 for (SymbolVersion V : readSymbols())
1878 Config->VersionScriptLocals.push_back(V);
1879 }
1880 }
George Rimar20b65982016-08-31 09:08:26 +00001881 expect("}");
1882
Rui Ueyama12450b22016-11-18 06:30:09 +00001883 // Each version may have a parent version. For example, "Ver2"
1884 // defined as "Ver2 { global: foo; local: *; } Ver1;" has "Ver1"
1885 // as a parent. This version hierarchy is, probably against your
1886 // instinct, purely for hint; the runtime doesn't care about it
1887 // at all. In LLD, we simply ignore it.
1888 if (peek() != ";")
Justin Bogner5424e7c2016-10-17 06:21:13 +00001889 skip();
George Rimar20b65982016-08-31 09:08:26 +00001890 expect(";");
1891}
1892
Rui Ueyama12450b22016-11-18 06:30:09 +00001893// Reads a list of symbols for a versions cript.
1894std::vector<SymbolVersion> ScriptParser::readSymbols() {
1895 std::vector<SymbolVersion> Ret;
George Rimare0fc2422016-11-16 17:59:10 +00001896 for (;;) {
Rafael Espindola1ef90d22016-12-09 16:44:05 +00001897 if (consume("extern")) {
Rui Ueyama12450b22016-11-18 06:30:09 +00001898 for (SymbolVersion V : readVersionExtern())
1899 Ret.push_back(V);
Rafael Espindola1ef90d22016-12-09 16:44:05 +00001900 continue;
1901 }
George Rimare0fc2422016-11-16 17:59:10 +00001902
Rui Ueyama0ee25a62016-11-17 03:52:14 +00001903 if (peek() == "}" || peek() == "local:" || Error)
Rui Ueyama12450b22016-11-18 06:30:09 +00001904 break;
Rui Ueyama0ee25a62016-11-17 03:52:14 +00001905 StringRef Tok = next();
Rui Ueyama12450b22016-11-18 06:30:09 +00001906 Ret.push_back({unquote(Tok), false, hasWildcard(Tok)});
George Rimare0fc2422016-11-16 17:59:10 +00001907 expect(";");
1908 }
Rui Ueyama12450b22016-11-18 06:30:09 +00001909 return Ret;
George Rimare0fc2422016-11-16 17:59:10 +00001910}
1911
Rui Ueyama12450b22016-11-18 06:30:09 +00001912// Reads an "extern C++" directive, e.g.,
1913// "extern "C++" { ns::*; "f(int, double)"; };"
1914std::vector<SymbolVersion> ScriptParser::readVersionExtern() {
Rafael Espindola7e714152016-12-08 17:26:53 +00001915 StringRef Tok = next();
1916 bool IsCXX = Tok == "\"C++\"";
1917 if (!IsCXX && Tok != "\"C\"")
Rafael Espindolad0ebd842016-12-08 17:54:26 +00001918 setError("Unknown language");
George Rimar20b65982016-08-31 09:08:26 +00001919 expect("{");
1920
Rui Ueyama12450b22016-11-18 06:30:09 +00001921 std::vector<SymbolVersion> Ret;
Rui Ueyama0ee25a62016-11-17 03:52:14 +00001922 while (!Error && peek() != "}") {
1923 StringRef Tok = next();
1924 bool HasWildcard = !Tok.startswith("\"") && hasWildcard(Tok);
Rafael Espindola7e714152016-12-08 17:26:53 +00001925 Ret.push_back({unquote(Tok), IsCXX, HasWildcard});
George Rimar20b65982016-08-31 09:08:26 +00001926 expect(";");
1927 }
1928
1929 expect("}");
1930 expect(";");
Rui Ueyama12450b22016-11-18 06:30:09 +00001931 return Ret;
George Rimar20b65982016-08-31 09:08:26 +00001932}
1933
Rui Ueyama07320e42016-04-20 20:13:41 +00001934void elf::readLinkerScript(MemoryBufferRef MB) {
Rui Ueyama22375f22016-11-25 18:51:54 +00001935 ScriptParser(MB).readLinkerScript();
George Rimar20b65982016-08-31 09:08:26 +00001936}
1937
1938void elf::readVersionScript(MemoryBufferRef MB) {
Rui Ueyama22375f22016-11-25 18:51:54 +00001939 ScriptParser(MB).readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001940}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001941
Rafael Espindolad0ebd842016-12-08 17:54:26 +00001942void elf::readDynamicList(MemoryBufferRef MB) {
1943 ScriptParser(MB).readDynamicList();
1944}
1945
Rui Ueyama07320e42016-04-20 20:13:41 +00001946template class elf::LinkerScript<ELF32LE>;
1947template class elf::LinkerScript<ELF32BE>;
1948template class elf::LinkerScript<ELF64LE>;
1949template class elf::LinkerScript<ELF64BE>;