blob: 8a1c6e526ab193887d85d0619d7736edcd51225d [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"
Rui Ueyama794366a2017-02-14 04:47:05 +000020#include "ScriptLexer.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
Meador Inge8f1f3c42017-01-09 18:36:57 +000059template <class ELFT> static SymbolBody *addRegular(SymbolAssignment *Cmd) {
Petr Hosek5e51f7d2017-02-21 22:32:51 +000060 Symbol *Sym;
Rafael Espindola3dabfc62016-10-31 13:14:53 +000061 uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
Petr Hosek5e51f7d2017-02-21 22:32:51 +000062 std::tie(Sym, std::ignore) = Symtab<ELFT>::X->insert(
63 Cmd->Name, /*Type*/ 0, Visibility, /*CanOmitFromDynSym*/ false,
64 /*File*/ nullptr);
65 Sym->Binding = STB_GLOBAL;
Rafael Espindola9bd45662017-03-10 00:47:33 +000066 SectionBase *Sec =
Rafael Espindola5616adf2017-03-08 22:36:28 +000067 Cmd->Expression.IsAbsolute() ? nullptr : Cmd->Expression.Section();
Rui Ueyama80474a22017-02-28 19:29:55 +000068 replaceBody<DefinedRegular>(Sym, Cmd->Name, /*IsLocal=*/false, Visibility,
Rafael Espindola5616adf2017-03-08 22:36:28 +000069 STT_NOTYPE, 0, 0, Sec, nullptr);
Meador Inge8f1f3c42017-01-09 18:36:57 +000070 return Sym->body();
Eugene Leviantceabe802016-08-11 07:56:43 +000071}
72
Rui Ueyama22375f22016-11-25 18:51:54 +000073static bool isUnderSysroot(StringRef Path) {
74 if (Config->Sysroot == "")
75 return false;
76 for (; !Path.empty(); Path = sys::path::parent_path(Path))
77 if (sys::fs::equivalent(Config->Sysroot, Path))
78 return true;
79 return false;
80}
81
George Rimar2ee2d2d2017-02-21 14:50:38 +000082template <class ELFT>
83void LinkerScript<ELFT>::setDot(Expr E, const Twine &Loc, bool InSec) {
Rafael Espindola4595df92017-03-10 16:04:26 +000084 uintX_t Val = E();
Rafael Espindola679828f2017-02-17 16:26:13 +000085 if (Val < Dot) {
86 if (InSec)
George Rimar2ee2d2d2017-02-21 14:50:38 +000087 error(Loc + ": unable to move location counter backward for: " +
88 CurOutSec->Name);
Rafael Espindola679828f2017-02-17 16:26:13 +000089 else
George Rimar2ee2d2d2017-02-21 14:50:38 +000090 error(Loc + ": unable to move location counter backward");
Rafael Espindola679828f2017-02-17 16:26:13 +000091 }
92 Dot = Val;
93 // Update to location counter means update to section size.
94 if (InSec)
95 CurOutSec->Size = Dot - CurOutSec->Addr;
96}
97
George Rimarb2b70972017-02-07 10:23:28 +000098// Sets value of a symbol. Two kinds of symbols are processed: synthetic
99// symbols, whose value is an offset from beginning of section and regular
100// symbols whose value is absolute.
101template <class ELFT>
Rafael Espindola4cd73522017-02-17 16:01:51 +0000102void LinkerScript<ELFT>::assignSymbol(SymbolAssignment *Cmd, bool InSec) {
103 if (Cmd->Name == ".") {
George Rimar2ee2d2d2017-02-21 14:50:38 +0000104 setDot(Cmd->Expression, Cmd->Location, InSec);
Rafael Espindola4cd73522017-02-17 16:01:51 +0000105 return;
106 }
107
George Rimarb2b70972017-02-07 10:23:28 +0000108 if (!Cmd->Sym)
Meador Inge8f1f3c42017-01-09 18:36:57 +0000109 return;
110
Rafael Espindola5616adf2017-03-08 22:36:28 +0000111 auto *Sym = cast<DefinedRegular>(Cmd->Sym);
Rafael Espindola4595df92017-03-10 16:04:26 +0000112 Sym->Value = Cmd->Expression();
Rafael Espindola5616adf2017-03-08 22:36:28 +0000113 if (!Cmd->Expression.IsAbsolute()) {
114 Sym->Section = Cmd->Expression.Section();
115 if (auto *Sec = dyn_cast_or_null<OutputSection>(Sym->Section))
116 if (Sec->Flags & SHF_ALLOC)
117 Sym->Value -= Sec->Addr;
Meador Inge8f1f3c42017-01-09 18:36:57 +0000118 }
Eugene Leviantdb741e72016-09-07 07:08:43 +0000119}
Meador Inge8f1f3c42017-01-09 18:36:57 +0000120
Rafael Espindola4cd73522017-02-17 16:01:51 +0000121template <class ELFT>
122void LinkerScript<ELFT>::addSymbol(SymbolAssignment *Cmd) {
Rui Ueyama16024212016-08-11 23:22:52 +0000123 if (Cmd->Name == ".")
Meador Inge8f1f3c42017-01-09 18:36:57 +0000124 return;
125
126 // If a symbol was in PROVIDE(), we need to define it only when
127 // it is a referenced undefined symbol.
Rui Ueyama16024212016-08-11 23:22:52 +0000128 SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
Meador Inge8f1f3c42017-01-09 18:36:57 +0000129 if (Cmd->Provide && (!B || B->isDefined()))
130 return;
131
Rafael Espindola5616adf2017-03-08 22:36:28 +0000132 Cmd->Sym = addRegular<ELFT>(Cmd);
George Rimarb2b70972017-02-07 10:23:28 +0000133
134 // If there are sections, then let the value be assigned later in
135 // `assignAddresses`.
136 if (!ScriptConfig->HasSections)
Rafael Espindola4cd73522017-02-17 16:01:51 +0000137 assignSymbol(Cmd);
Eugene Leviantceabe802016-08-11 07:56:43 +0000138}
139
George Rimar076fe152016-07-21 06:43:01 +0000140bool SymbolAssignment::classof(const BaseCommand *C) {
141 return C->Kind == AssignmentKind;
142}
143
144bool OutputSectionCommand::classof(const BaseCommand *C) {
145 return C->Kind == OutputSectionKind;
146}
147
George Rimareea31142016-07-21 14:26:59 +0000148bool InputSectionDescription::classof(const BaseCommand *C) {
149 return C->Kind == InputSectionKind;
150}
151
George Rimareefa7582016-08-04 09:29:31 +0000152bool AssertCommand::classof(const BaseCommand *C) {
153 return C->Kind == AssertKind;
154}
155
George Rimare38cbab2016-09-26 19:22:50 +0000156bool BytesDataCommand::classof(const BaseCommand *C) {
157 return C->Kind == BytesDataKind;
158}
159
Eugene Zelenko22886a22016-11-05 01:00:56 +0000160template <class ELFT> LinkerScript<ELFT>::LinkerScript() = default;
161template <class ELFT> LinkerScript<ELFT>::~LinkerScript() = default;
Rui Ueyamaf34d0e02016-08-12 01:24:53 +0000162
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000163static StringRef basename(InputSectionBase *S) {
164 if (S->File)
165 return sys::path::filename(S->File->getName());
Rui Ueyamae0be2902016-11-21 02:10:12 +0000166 return "";
167}
168
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000169template <class ELFT> bool LinkerScript<ELFT>::shouldKeep(InputSectionBase *S) {
Rui Ueyamae0be2902016-11-21 02:10:12 +0000170 for (InputSectionDescription *ID : Opt.KeptSections)
171 if (ID->FilePat.match(basename(S)))
172 for (SectionPattern &P : ID->SectionPatterns)
173 if (P.SectionPat.match(S->Name))
174 return true;
George Rimareea31142016-07-21 14:26:59 +0000175 return false;
176}
177
Rafael Espindolac404d502017-02-23 02:32:18 +0000178static bool comparePriority(InputSectionBase *A, InputSectionBase *B) {
George Rimar575208c2016-09-15 19:15:12 +0000179 return getPriority(A->Name) < getPriority(B->Name);
180}
181
Rafael Espindolac404d502017-02-23 02:32:18 +0000182static bool compareName(InputSectionBase *A, InputSectionBase *B) {
Rafael Espindola042a3f22016-09-08 14:06:08 +0000183 return A->Name < B->Name;
Rui Ueyama742c3832016-08-04 22:27:00 +0000184}
George Rimar350ece42016-08-03 08:35:59 +0000185
Rafael Espindolac404d502017-02-23 02:32:18 +0000186static bool compareAlignment(InputSectionBase *A, InputSectionBase *B) {
Rui Ueyama742c3832016-08-04 22:27:00 +0000187 // ">" is not a mistake. Larger alignments are placed before smaller
188 // alignments in order to reduce the amount of padding necessary.
189 // This is compatible with GNU.
190 return A->Alignment > B->Alignment;
191}
George Rimar350ece42016-08-03 08:35:59 +0000192
Rafael Espindolac404d502017-02-23 02:32:18 +0000193static std::function<bool(InputSectionBase *, InputSectionBase *)>
George Rimarbe394db2016-09-16 20:21:55 +0000194getComparator(SortSectionPolicy K) {
195 switch (K) {
196 case SortSectionPolicy::Alignment:
197 return compareAlignment;
198 case SortSectionPolicy::Name:
Rafael Espindolac0028d32016-09-08 20:47:52 +0000199 return compareName;
George Rimarbe394db2016-09-16 20:21:55 +0000200 case SortSectionPolicy::Priority:
201 return comparePriority;
202 default:
203 llvm_unreachable("unknown sort policy");
204 }
Rui Ueyama742c3832016-08-04 22:27:00 +0000205}
George Rimar0702c4e2016-07-29 15:32:46 +0000206
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000207template <class ELFT>
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000208static bool matchConstraints(ArrayRef<InputSectionBase *> Sections,
George Rimar06ae6832016-08-12 09:07:57 +0000209 ConstraintKind Kind) {
George Rimar8f66df92016-08-12 20:38:20 +0000210 if (Kind == ConstraintKind::NoConstraint)
211 return true;
Rafael Espindolac404d502017-02-23 02:32:18 +0000212 bool IsRW = llvm::any_of(Sections, [=](InputSectionBase *Sec2) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000213 auto *Sec = static_cast<InputSectionBase *>(Sec2);
Rafael Espindola1854a8e2016-10-26 12:36:56 +0000214 return Sec->Flags & SHF_WRITE;
George Rimar06ae6832016-08-12 09:07:57 +0000215 });
Rafael Espindolae746e522016-09-21 18:33:44 +0000216 return (IsRW && Kind == ConstraintKind::ReadWrite) ||
217 (!IsRW && Kind == ConstraintKind::ReadOnly);
George Rimar06ae6832016-08-12 09:07:57 +0000218}
219
Rafael Espindolac404d502017-02-23 02:32:18 +0000220static void sortSections(InputSectionBase **Begin, InputSectionBase **End,
Rui Ueyamaee924702016-09-20 19:42:41 +0000221 SortSectionPolicy K) {
222 if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
George Rimar07171f22016-09-21 15:56:44 +0000223 std::stable_sort(Begin, End, getComparator(K));
Rui Ueyamaee924702016-09-20 19:42:41 +0000224}
225
Rafael Espindolad3190792016-09-16 15:10:23 +0000226// Compute and remember which sections the InputSectionDescription matches.
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000227template <class ELFT>
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000228void LinkerScript<ELFT>::computeInputSections(InputSectionDescription *I) {
Rui Ueyama4dc07be2016-09-17 02:23:40 +0000229 // Collects all sections that satisfy constraints of I
230 // and attach them to I.
231 for (SectionPattern &Pat : I->SectionPatterns) {
George Rimar07171f22016-09-21 15:56:44 +0000232 size_t SizeBefore = I->Sections.size();
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000233
Rui Ueyama536a2672017-02-27 02:32:08 +0000234 for (InputSectionBase *S : InputSections) {
Rafael Espindola3773bca2017-02-17 19:37:30 +0000235 if (S->Assigned)
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000236 continue;
Rafael Espindola908a3d32017-02-16 14:36:09 +0000237 // For -emit-relocs we have to ignore entries like
238 // .rela.dyn : { *(.rela.data) }
239 // which are common because they are in the default bfd script.
240 if (S->Type == SHT_REL || S->Type == SHT_RELA)
241 continue;
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000242
Rui Ueyamae0be2902016-11-21 02:10:12 +0000243 StringRef Filename = basename(S);
244 if (!I->FilePat.match(Filename) || Pat.ExcludedFilePat.match(Filename))
245 continue;
246 if (!Pat.SectionPat.match(S->Name))
247 continue;
248 I->Sections.push_back(S);
249 S->Assigned = true;
George Rimar395281c2016-09-16 17:42:10 +0000250 }
Rafael Espindolad3190792016-09-16 15:10:23 +0000251
George Rimar07171f22016-09-21 15:56:44 +0000252 // Sort sections as instructed by SORT-family commands and --sort-section
253 // option. Because SORT-family commands can be nested at most two depth
254 // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
255 // line option is respected even if a SORT command is given, the exact
256 // behavior we have here is a bit complicated. Here are the rules.
257 //
258 // 1. If two SORT commands are given, --sort-section is ignored.
259 // 2. If one SORT command is given, and if it is not SORT_NONE,
260 // --sort-section is handled as an inner SORT command.
261 // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
262 // 4. If no SORT command is given, sort according to --sort-section.
Rafael Espindolac404d502017-02-23 02:32:18 +0000263 InputSectionBase **Begin = I->Sections.data() + SizeBefore;
264 InputSectionBase **End = I->Sections.data() + I->Sections.size();
George Rimar07171f22016-09-21 15:56:44 +0000265 if (Pat.SortOuter != SortSectionPolicy::None) {
266 if (Pat.SortInner == SortSectionPolicy::Default)
267 sortSections(Begin, End, Config->SortSection);
268 else
269 sortSections(Begin, End, Pat.SortInner);
270 sortSections(Begin, End, Pat.SortOuter);
271 }
Rui Ueyamaee924702016-09-20 19:42:41 +0000272 }
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000273}
274
275template <class ELFT>
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000276void LinkerScript<ELFT>::discard(ArrayRef<InputSectionBase *> V) {
277 for (InputSectionBase *S : V) {
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000278 S->Live = false;
Rafael Espindolaecbfd872017-02-17 17:35:07 +0000279 if (S == In<ELFT>::ShStrTab)
280 error("discarding .shstrtab section is not allowed");
George Rimar647c1682017-02-17 19:34:05 +0000281 discard(S->DependentSections);
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000282 }
283}
284
George Rimar06ae6832016-08-12 09:07:57 +0000285template <class ELFT>
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000286std::vector<InputSectionBase *>
George Rimar06ae6832016-08-12 09:07:57 +0000287LinkerScript<ELFT>::createInputSectionList(OutputSectionCommand &OutCmd) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000288 std::vector<InputSectionBase *> Ret;
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000289
George Rimar06ae6832016-08-12 09:07:57 +0000290 for (const std::unique_ptr<BaseCommand> &Base : OutCmd.Commands) {
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000291 auto *Cmd = dyn_cast<InputSectionDescription>(Base.get());
292 if (!Cmd)
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000293 continue;
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000294 computeInputSections(Cmd);
Rafael Espindolac404d502017-02-23 02:32:18 +0000295 for (InputSectionBase *S : Cmd->Sections)
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000296 Ret.push_back(static_cast<InputSectionBase *>(S));
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000297 }
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000298
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000299 return Ret;
300}
301
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000302template <class ELFT>
Rui Ueyama02a036f2017-02-27 02:31:48 +0000303void LinkerScript<ELFT>::processCommands(OutputSectionFactory &Factory) {
Rafael Espindola5616adf2017-03-08 22:36:28 +0000304 // A symbol can be assigned before any section is mentioned in the linker
305 // script. In an DSO, the symbol values are addresses, so the only important
306 // section values are:
307 // * SHN_UNDEF
308 // * SHN_ABS
309 // * Any value meaning a regular section.
310 // To handle that, create a dummy aether section that fills the void before
311 // the linker scripts switches to another section. It has an index of one
312 // which will map to whatever the first actual section is.
313 Aether = make<OutputSection>("", 0, SHF_ALLOC);
314 Aether->SectionIndex = 1;
315 CurOutSec = Aether;
316
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000317 for (unsigned I = 0; I < Opt.Commands.size(); ++I) {
318 auto Iter = Opt.Commands.begin() + I;
319 const std::unique_ptr<BaseCommand> &Base1 = *Iter;
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000320
321 // Handle symbol assignments outside of any output section.
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000322 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base1.get())) {
Rafael Espindola4cd73522017-02-17 16:01:51 +0000323 addSymbol(Cmd);
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000324 continue;
325 }
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000326
Eugene Leviant20d03192016-09-16 15:30:47 +0000327 if (auto *Cmd = dyn_cast<AssertCommand>(Base1.get())) {
328 // If we don't have SECTIONS then output sections have already been
George Rimar194470cd2016-09-17 19:21:05 +0000329 // created by Writer<ELFT>. The LinkerScript<ELFT>::assignAddresses
Eugene Leviant20d03192016-09-16 15:30:47 +0000330 // will not be called, so ASSERT should be evaluated now.
331 if (!Opt.HasSections)
Rafael Espindola4595df92017-03-10 16:04:26 +0000332 Cmd->Expression();
Eugene Leviant20d03192016-09-16 15:30:47 +0000333 continue;
334 }
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000335
Eugene Leviantceabe802016-08-11 07:56:43 +0000336 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000337 std::vector<InputSectionBase *> V = createInputSectionList(*Cmd);
Rafael Espindola7bd37872016-09-12 16:05:16 +0000338
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000339 // The output section name `/DISCARD/' is special.
340 // Any input section assigned to it is discarded.
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000341 if (Cmd->Name == "/DISCARD/") {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000342 discard(V);
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000343 continue;
344 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000345
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000346 // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive
347 // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input
348 // sections satisfy a given constraint. If not, a directive is handled
349 // as if it wasn't present from the beginning.
350 //
351 // Because we'll iterate over Commands many more times, the easiest
352 // way to "make it as if it wasn't present" is to just remove it.
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000353 if (!matchConstraints<ELFT>(V, Cmd->Constraint)) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000354 for (InputSectionBase *S : V)
Rui Ueyamaf94efdd2016-11-20 23:15:52 +0000355 S->Assigned = false;
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000356 Opt.Commands.erase(Iter);
George Rimardfbbbc82016-09-17 09:50:10 +0000357 --I;
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000358 continue;
359 }
360
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000361 // A directive may contain symbol definitions like this:
362 // ".foo : { ...; bar = .; }". Handle them.
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000363 for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
364 if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base.get()))
Rafael Espindola4cd73522017-02-17 16:01:51 +0000365 addSymbol(OutCmd);
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000366
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000367 // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign
368 // is given, input sections are aligned to that value, whether the
369 // given value is larger or smaller than the original section alignment.
370 if (Cmd->SubalignExpr) {
Rafael Espindola4595df92017-03-10 16:04:26 +0000371 uint32_t Subalign = Cmd->SubalignExpr();
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000372 for (InputSectionBase *S : V)
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000373 S->Alignment = Subalign;
George Rimardb24d9c2016-08-19 15:18:23 +0000374 }
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000375
376 // Add input sections to an output section.
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000377 for (InputSectionBase *S : V)
Rui Ueyama02a036f2017-02-27 02:31:48 +0000378 Factory.addInputSec<ELFT>(S, Cmd->Name);
Eugene Leviantceabe802016-08-11 07:56:43 +0000379 }
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000380 }
Rafael Espindola5616adf2017-03-08 22:36:28 +0000381 CurOutSec = nullptr;
Eugene Leviant20d03192016-09-16 15:30:47 +0000382}
Eugene Leviante63d81b2016-07-20 14:43:20 +0000383
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000384// Add sections that didn't match any sections command.
Eugene Leviant20d03192016-09-16 15:30:47 +0000385template <class ELFT>
Rui Ueyama02a036f2017-02-27 02:31:48 +0000386void LinkerScript<ELFT>::addOrphanSections(OutputSectionFactory &Factory) {
Rui Ueyama536a2672017-02-27 02:32:08 +0000387 for (InputSectionBase *S : InputSections)
Rafael Espindola8f9026b2016-11-08 18:23:02 +0000388 if (S->Live && !S->OutSec)
Rui Ueyama02a036f2017-02-27 02:31:48 +0000389 Factory.addInputSec<ELFT>(S, getOutputSectionName(S->Name));
Eugene Leviante63d81b2016-07-20 14:43:20 +0000390}
391
Rafael Espindola24e6f362017-02-24 15:07:30 +0000392template <class ELFT> static bool isTbss(OutputSection *Sec) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000393 return (Sec->Flags & SHF_TLS) && Sec->Type == SHT_NOBITS;
Rafael Espindolaa940e532016-09-22 12:35:44 +0000394}
395
Rafael Espindola774ea7d2017-02-23 16:49:07 +0000396template <class ELFT> void LinkerScript<ELFT>::output(InputSection *S) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000397 if (!AlreadyOutputIS.insert(S).second)
398 return;
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000399 bool IsTbss = isTbss<ELFT>(CurOutSec);
Eugene Leviant20889c52016-08-31 08:13:33 +0000400
Rafael Espindolad3190792016-09-16 15:10:23 +0000401 uintX_t Pos = IsTbss ? Dot + ThreadBssOffset : Dot;
402 Pos = alignTo(Pos, S->Alignment);
Rafael Espindola04a2e342016-11-09 01:42:41 +0000403 S->OutSecOff = Pos - CurOutSec->Addr;
Rafael Espindola76b6bd32017-03-08 15:44:30 +0000404 Pos += S->getSize();
Rafael Espindolad3190792016-09-16 15:10:23 +0000405
406 // Update output section size after adding each section. This is so that
407 // SIZEOF works correctly in the case below:
408 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
Rafael Espindola04a2e342016-11-09 01:42:41 +0000409 CurOutSec->Size = Pos - CurOutSec->Addr;
Rafael Espindolad3190792016-09-16 15:10:23 +0000410
Meador Ingeb8897442017-01-24 02:34:00 +0000411 // If there is a memory region associated with this input section, then
412 // place the section in that region and update the region index.
413 if (CurMemRegion) {
414 CurMemRegion->Offset += CurOutSec->Size;
415 uint64_t CurSize = CurMemRegion->Offset - CurMemRegion->Origin;
416 if (CurSize > CurMemRegion->Length) {
417 uint64_t OverflowAmt = CurSize - CurMemRegion->Length;
418 error("section '" + CurOutSec->Name + "' will not fit in region '" +
419 CurMemRegion->Name + "': overflowed by " + Twine(OverflowAmt) +
420 " bytes");
421 }
422 }
423
Rafael Espindola7252ae52016-09-22 12:00:08 +0000424 if (IsTbss)
425 ThreadBssOffset = Pos - Dot;
426 else
Rafael Espindolad3190792016-09-16 15:10:23 +0000427 Dot = Pos;
428}
429
430template <class ELFT> void LinkerScript<ELFT>::flush() {
Rafael Espindolabd12e2a2017-03-01 14:12:21 +0000431 assert(CurOutSec);
432 if (!AlreadyOutputOS.insert(CurOutSec).second)
Rafael Espindola65499b92016-09-23 20:10:47 +0000433 return;
Rafael Espindola24e6f362017-02-24 15:07:30 +0000434 for (InputSection *I : CurOutSec->Sections)
435 output(I);
Eugene Leviant20889c52016-08-31 08:13:33 +0000436}
437
Rafael Espindola24e6f362017-02-24 15:07:30 +0000438template <class ELFT> void LinkerScript<ELFT>::switchTo(OutputSection *Sec) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000439 if (CurOutSec == Sec)
440 return;
441 if (AlreadyOutputOS.count(Sec))
442 return;
443
Rafael Espindolad3190792016-09-16 15:10:23 +0000444 CurOutSec = Sec;
445
Rafael Espindola37707632017-03-07 14:55:52 +0000446 Dot = alignTo(Dot, CurOutSec->Alignment);
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000447 CurOutSec->Addr = isTbss<ELFT>(CurOutSec) ? Dot + ThreadBssOffset : Dot;
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000448
449 // If neither AT nor AT> is specified for an allocatable section, the linker
450 // will set the LMA such that the difference between VMA and LMA for the
451 // section is the same as the preceding output section in the same region
452 // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
George Rimar21467872017-02-23 07:57:55 +0000453 if (LMAOffset)
Rafael Espindola29c1afb2017-02-24 14:34:12 +0000454 CurOutSec->LMAOffset = LMAOffset();
Rafael Espindolad3190792016-09-16 15:10:23 +0000455}
456
457template <class ELFT> void LinkerScript<ELFT>::process(BaseCommand &Base) {
George Rimare38cbab2016-09-26 19:22:50 +0000458 // This handles the assignments to symbol or to a location counter (.)
Rafael Espindolad3190792016-09-16 15:10:23 +0000459 if (auto *AssignCmd = dyn_cast<SymbolAssignment>(&Base)) {
Rafael Espindola4cd73522017-02-17 16:01:51 +0000460 assignSymbol(AssignCmd, true);
Eugene Leviantceabe802016-08-11 07:56:43 +0000461 return;
Rui Ueyama2de509c2016-08-12 00:55:08 +0000462 }
George Rimare38cbab2016-09-26 19:22:50 +0000463
464 // Handle BYTE(), SHORT(), LONG(), or QUAD().
465 if (auto *DataCmd = dyn_cast<BytesDataCommand>(&Base)) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000466 DataCmd->Offset = Dot - CurOutSec->Addr;
George Rimare38cbab2016-09-26 19:22:50 +0000467 Dot += DataCmd->Size;
Rafael Espindola04a2e342016-11-09 01:42:41 +0000468 CurOutSec->Size = Dot - CurOutSec->Addr;
George Rimare38cbab2016-09-26 19:22:50 +0000469 return;
470 }
471
Meador Ingeb2d99d62016-11-22 18:01:50 +0000472 if (auto *AssertCmd = dyn_cast<AssertCommand>(&Base)) {
Rafael Espindola4595df92017-03-10 16:04:26 +0000473 AssertCmd->Expression();
Meador Ingeb2d99d62016-11-22 18:01:50 +0000474 return;
475 }
476
George Rimare38cbab2016-09-26 19:22:50 +0000477 // It handles single input section description command,
478 // calculates and assigns the offsets for each section and also
479 // updates the output section size.
Rafael Espindolad3190792016-09-16 15:10:23 +0000480 auto &ICmd = cast<InputSectionDescription>(Base);
Rafael Espindolabd12e2a2017-03-01 14:12:21 +0000481 for (InputSectionBase *IB : ICmd.Sections) {
George Rimar3fb5a6d2016-11-29 16:05:27 +0000482 // We tentatively added all synthetic sections at the beginning and removed
483 // empty ones afterwards (because there is no way to know whether they were
484 // going be empty or not other than actually running linker scripts.)
485 // We need to ignore remains of empty sections.
Rafael Espindolabd12e2a2017-03-01 14:12:21 +0000486 if (auto *Sec = dyn_cast<SyntheticSection>(IB))
George Rimar3fb5a6d2016-11-29 16:05:27 +0000487 if (Sec->empty())
488 continue;
489
George Rimar78ef6452017-02-21 15:46:43 +0000490 if (!IB->Live)
491 continue;
Rafael Espindolabedccb5e2017-03-01 14:21:31 +0000492 assert(CurOutSec == IB->OutSec || AlreadyOutputOS.count(IB->OutSec));
Rafael Espindolabd12e2a2017-03-01 14:12:21 +0000493 output(cast<InputSection>(IB));
Eugene Leviantceabe802016-08-11 07:56:43 +0000494 }
495}
496
George Rimar8f66df92016-08-12 20:38:20 +0000497template <class ELFT>
Rafael Espindola24e6f362017-02-24 15:07:30 +0000498static OutputSection *
499findSection(StringRef Name, const std::vector<OutputSection *> &Sections) {
Rafael Espindola2b074552017-02-03 22:27:05 +0000500 auto End = Sections.end();
Rafael Espindola24e6f362017-02-24 15:07:30 +0000501 auto HasName = [=](OutputSection *Sec) { return Sec->Name == Name; };
Rafael Espindola2b074552017-02-03 22:27:05 +0000502 auto I = std::find_if(Sections.begin(), End, HasName);
Rafael Espindola24e6f362017-02-24 15:07:30 +0000503 std::vector<OutputSection *> Ret;
Rafael Espindola2b074552017-02-03 22:27:05 +0000504 if (I == End)
505 return nullptr;
506 assert(std::find_if(I + 1, End, HasName) == End);
507 return *I;
George Rimar8f66df92016-08-12 20:38:20 +0000508}
509
Meador Ingeb8897442017-01-24 02:34:00 +0000510// This function searches for a memory region to place the given output
511// section in. If found, a pointer to the appropriate memory region is
512// returned. Otherwise, a nullptr is returned.
513template <class ELFT>
514MemoryRegion *LinkerScript<ELFT>::findMemoryRegion(OutputSectionCommand *Cmd,
Rafael Espindola24e6f362017-02-24 15:07:30 +0000515 OutputSection *Sec) {
Meador Ingeb8897442017-01-24 02:34:00 +0000516 // If a memory region name was specified in the output section command,
517 // then try to find that region first.
518 if (!Cmd->MemoryRegionName.empty()) {
519 auto It = Opt.MemoryRegions.find(Cmd->MemoryRegionName);
520 if (It != Opt.MemoryRegions.end())
521 return &It->second;
522 error("memory region '" + Cmd->MemoryRegionName + "' not declared");
523 return nullptr;
524 }
525
526 // The memory region name is empty, thus a suitable region must be
527 // searched for in the region map. If the region map is empty, just
528 // return. Note that this check doesn't happen at the very beginning
529 // so that uses of undeclared regions can be caught.
530 if (!Opt.MemoryRegions.size())
531 return nullptr;
532
533 // See if a region can be found by matching section flags.
534 for (auto &MRI : Opt.MemoryRegions) {
535 MemoryRegion &MR = MRI.second;
Rui Ueyama8a8a9532017-01-26 02:58:59 +0000536 if ((MR.Flags & Sec->Flags) != 0 && (MR.NegFlags & Sec->Flags) == 0)
Meador Ingeb8897442017-01-24 02:34:00 +0000537 return &MR;
538 }
539
540 // Otherwise, no suitable region was found.
541 if (Sec->Flags & SHF_ALLOC)
542 error("no memory region specified for section '" + Sec->Name + "'");
543 return nullptr;
544}
545
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000546// This function assigns offsets to input sections and an output section
547// for a single sections command (e.g. ".text { *(.text); }").
Rafael Espindolad3190792016-09-16 15:10:23 +0000548template <class ELFT>
549void LinkerScript<ELFT>::assignOffsets(OutputSectionCommand *Cmd) {
George Rimar21467872017-02-23 07:57:55 +0000550 if (Cmd->LMAExpr) {
551 uintX_t D = Dot;
Rafael Espindola4595df92017-03-10 16:04:26 +0000552 LMAOffset = [=] { return Cmd->LMAExpr() - D; };
George Rimar21467872017-02-23 07:57:55 +0000553 }
Rafael Espindola24e6f362017-02-24 15:07:30 +0000554 OutputSection *Sec = findSection<ELFT>(Cmd->Name, *OutputSections);
Rafael Espindola2b074552017-02-03 22:27:05 +0000555 if (!Sec)
Rafael Espindolad3190792016-09-16 15:10:23 +0000556 return;
Meador Ingeb8897442017-01-24 02:34:00 +0000557
Rafael Espindola679828f2017-02-17 16:26:13 +0000558 if (Cmd->AddrExpr && Sec->Flags & SHF_ALLOC)
George Rimar2ee2d2d2017-02-21 14:50:38 +0000559 setDot(Cmd->AddrExpr, Cmd->Location);
Rafael Espindola679828f2017-02-17 16:26:13 +0000560
Petr Hosek165088a2017-02-07 23:42:31 +0000561 // Handle align (e.g. ".foo : ALIGN(16) { ... }").
562 if (Cmd->AlignExpr)
Rafael Espindola4595df92017-03-10 16:04:26 +0000563 Sec->updateAlignment(Cmd->AlignExpr());
Petr Hosek165088a2017-02-07 23:42:31 +0000564
Meador Ingeb8897442017-01-24 02:34:00 +0000565 // Try and find an appropriate memory region to assign offsets in.
566 CurMemRegion = findMemoryRegion(Cmd, Sec);
567 if (CurMemRegion)
568 Dot = CurMemRegion->Offset;
569 switchTo(Sec);
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000570
Rafael Espindolad3190792016-09-16 15:10:23 +0000571 // Find the last section output location. We will output orphan sections
572 // there so that end symbols point to the correct location.
573 auto E = std::find_if(Cmd->Commands.rbegin(), Cmd->Commands.rend(),
574 [](const std::unique_ptr<BaseCommand> &Cmd) {
575 return !isa<SymbolAssignment>(*Cmd);
576 })
577 .base();
578 for (auto I = Cmd->Commands.begin(); I != E; ++I)
579 process(**I);
Rafael Espindola65499b92016-09-23 20:10:47 +0000580 flush();
George Rimarb31dd372016-09-19 13:27:31 +0000581 std::for_each(E, Cmd->Commands.end(),
582 [this](std::unique_ptr<BaseCommand> &B) { process(*B.get()); });
Rafael Espindolad3190792016-09-16 15:10:23 +0000583}
584
Rafael Espindola07fe6122016-11-14 14:23:35 +0000585template <class ELFT> void LinkerScript<ELFT>::removeEmptyCommands() {
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000586 // It is common practice to use very generic linker scripts. So for any
587 // given run some of the output sections in the script will be empty.
588 // We could create corresponding empty output sections, but that would
589 // clutter the output.
590 // We instead remove trivially empty sections. The bfd linker seems even
591 // more aggressive at removing them.
592 auto Pos = std::remove_if(
593 Opt.Commands.begin(), Opt.Commands.end(),
594 [&](const std::unique_ptr<BaseCommand> &Base) {
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000595 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
Rafael Espindola2b074552017-02-03 22:27:05 +0000596 return !findSection<ELFT>(Cmd->Name, *OutputSections);
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000597 return false;
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000598 });
599 Opt.Commands.erase(Pos, Opt.Commands.end());
Rafael Espindola07fe6122016-11-14 14:23:35 +0000600}
601
Rafael Espindola6a537372016-11-14 14:33:49 +0000602static bool isAllSectionDescription(const OutputSectionCommand &Cmd) {
603 for (const std::unique_ptr<BaseCommand> &I : Cmd.Commands)
604 if (!isa<InputSectionDescription>(*I))
605 return false;
606 return true;
607}
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000608
Rafael Espindola6a537372016-11-14 14:33:49 +0000609template <class ELFT> void LinkerScript<ELFT>::adjustSectionsBeforeSorting() {
Rafael Espindola9546fff2016-09-22 14:40:50 +0000610 // If the output section contains only symbol assignments, create a
611 // corresponding output section. The bfd linker seems to only create them if
612 // '.' is assigned to, but creating these section should not have any bad
613 // consequeces and gives us a section to put the symbol in.
614 uintX_t Flags = SHF_ALLOC;
Rafael Espindolaf93b8c22016-11-26 06:55:35 +0000615 uint32_t Type = SHT_NOBITS;
Rafael Espindola9546fff2016-09-22 14:40:50 +0000616 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
617 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
618 if (!Cmd)
619 continue;
Rafael Espindola24e6f362017-02-24 15:07:30 +0000620 if (OutputSection *Sec = findSection<ELFT>(Cmd->Name, *OutputSections)) {
Rafael Espindola2b074552017-02-03 22:27:05 +0000621 Flags = Sec->Flags;
622 Type = Sec->Type;
Rafael Espindola9546fff2016-09-22 14:40:50 +0000623 continue;
624 }
625
Rafael Espindola6a537372016-11-14 14:33:49 +0000626 if (isAllSectionDescription(*Cmd))
627 continue;
628
Rafael Espindola24e6f362017-02-24 15:07:30 +0000629 auto *OutSec = make<OutputSection>(Cmd->Name, Type, Flags);
Rafael Espindola9546fff2016-09-22 14:40:50 +0000630 OutputSections->push_back(OutSec);
631 }
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000632}
633
634template <class ELFT> void LinkerScript<ELFT>::adjustSectionsAfterSorting() {
635 placeOrphanSections();
636
637 // If output section command doesn't specify any segments,
638 // and we haven't previously assigned any section to segment,
639 // then we simply assign section to the very first load segment.
640 // Below is an example of such linker script:
641 // PHDRS { seg PT_LOAD; }
642 // SECTIONS { .aaa : { *(.aaa) } }
643 std::vector<StringRef> DefPhdrs;
644 auto FirstPtLoad =
645 std::find_if(Opt.PhdrsCommands.begin(), Opt.PhdrsCommands.end(),
646 [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; });
647 if (FirstPtLoad != Opt.PhdrsCommands.end())
648 DefPhdrs.push_back(FirstPtLoad->Name);
649
650 // Walk the commands and propagate the program headers to commands that don't
651 // explicitly specify them.
652 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
653 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
654 if (!Cmd)
655 continue;
656 if (Cmd->Phdrs.empty())
657 Cmd->Phdrs = DefPhdrs;
658 else
659 DefPhdrs = Cmd->Phdrs;
660 }
Rafael Espindola6a537372016-11-14 14:33:49 +0000661
662 removeEmptyCommands();
Rafael Espindola9546fff2016-09-22 14:40:50 +0000663}
664
Rafael Espindola15c57952016-09-22 18:05:49 +0000665// When placing orphan sections, we want to place them after symbol assignments
666// so that an orphan after
667// begin_foo = .;
668// foo : { *(foo) }
669// end_foo = .;
670// doesn't break the intended meaning of the begin/end symbols.
671// We don't want to go over sections since Writer<ELFT>::sortSections is the
672// one in charge of deciding the order of the sections.
673// We don't want to go over alignments, since doing so in
674// rx_sec : { *(rx_sec) }
675// . = ALIGN(0x1000);
676// /* The RW PT_LOAD starts here*/
677// rw_sec : { *(rw_sec) }
678// would mean that the RW PT_LOAD would become unaligned.
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000679static bool shouldSkip(const BaseCommand &Cmd) {
Rafael Espindola15c57952016-09-22 18:05:49 +0000680 if (isa<OutputSectionCommand>(Cmd))
681 return false;
682 const auto *Assign = dyn_cast<SymbolAssignment>(&Cmd);
683 if (!Assign)
684 return true;
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000685 return Assign->Name != ".";
Rafael Espindola15c57952016-09-22 18:05:49 +0000686}
687
Rui Ueyama6697ec22017-02-02 23:26:12 +0000688// Orphan sections are sections present in the input files which are
689// not explicitly placed into the output file by the linker script.
690//
691// When the control reaches this function, Opt.Commands contains
692// output section commands for non-orphan sections only. This function
693// adds new elements for orphan sections to Opt.Commands so that all
694// sections are explicitly handled by Opt.Commands.
695//
696// Writer<ELFT>::sortSections has already sorted output sections.
697// What we need to do is to scan OutputSections vector and
698// Opt.Commands in parallel to find orphan sections. If there is an
699// output section that doesn't have a corresponding entry in
700// Opt.Commands, we will insert a new entry to Opt.Commands.
701//
702// There is some ambiguity as to where exactly a new entry should be
703// inserted, because Opt.Commands contains not only output section
704// commands but other types of commands such as symbol assignment
705// expressions. There's no correct answer here due to the lack of the
706// formal specification of the linker script. We use heuristics to
707// determine whether a new output command should be added before or
708// after another commands. For the details, look at shouldSkip
709// function.
George Rimar93c64022016-12-15 15:38:09 +0000710template <class ELFT> void LinkerScript<ELFT>::placeOrphanSections() {
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000711 // The OutputSections are already in the correct order.
712 // This loops creates or moves commands as needed so that they are in the
713 // correct order.
714 int CmdIndex = 0;
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000715
716 // As a horrible special case, skip the first . assignment if it is before any
717 // section. We do this because it is common to set a load address by starting
718 // the script with ". = 0xabcd" and the expectation is that every section is
719 // after that.
720 auto FirstSectionOrDotAssignment =
721 std::find_if(Opt.Commands.begin(), Opt.Commands.end(),
722 [](const std::unique_ptr<BaseCommand> &Cmd) {
723 if (isa<OutputSectionCommand>(*Cmd))
724 return true;
725 const auto *Assign = dyn_cast<SymbolAssignment>(Cmd.get());
726 if (!Assign)
727 return false;
728 return Assign->Name == ".";
729 });
730 if (FirstSectionOrDotAssignment != Opt.Commands.end()) {
731 CmdIndex = FirstSectionOrDotAssignment - Opt.Commands.begin();
732 if (isa<SymbolAssignment>(**FirstSectionOrDotAssignment))
733 ++CmdIndex;
734 }
735
Rafael Espindola24e6f362017-02-24 15:07:30 +0000736 for (OutputSection *Sec : *OutputSections) {
Rafael Espindola40849412017-02-24 14:28:00 +0000737 StringRef Name = Sec->Name;
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000738
739 // Find the last spot where we can insert a command and still get the
Rafael Espindola15c57952016-09-22 18:05:49 +0000740 // correct result.
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000741 auto CmdIter = Opt.Commands.begin() + CmdIndex;
742 auto E = Opt.Commands.end();
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000743 while (CmdIter != E && shouldSkip(**CmdIter)) {
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000744 ++CmdIter;
745 ++CmdIndex;
746 }
747
748 auto Pos =
749 std::find_if(CmdIter, E, [&](const std::unique_ptr<BaseCommand> &Base) {
750 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
751 return Cmd && Cmd->Name == Name;
752 });
753 if (Pos == E) {
754 Opt.Commands.insert(CmdIter,
755 llvm::make_unique<OutputSectionCommand>(Name));
Rafael Espindola15c57952016-09-22 18:05:49 +0000756 ++CmdIndex;
757 continue;
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000758 }
Rafael Espindola15c57952016-09-22 18:05:49 +0000759
760 // Continue from where we found it.
761 CmdIndex = (Pos - Opt.Commands.begin()) + 1;
George Rimar652852c2016-04-16 10:10:32 +0000762 }
Rafael Espindola337f9032016-11-14 14:13:32 +0000763}
764
765template <class ELFT>
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000766void LinkerScript<ELFT>::assignAddresses(std::vector<PhdrEntry> &Phdrs) {
Rui Ueyama7c18c282016-04-18 21:00:40 +0000767 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rafael Espindolabe607332016-09-30 00:16:11 +0000768 Dot = 0;
Rafael Espindola06f47432017-02-06 22:21:46 +0000769 switchTo(Aether);
770
George Rimar076fe152016-07-21 06:43:01 +0000771 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
772 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
Rafael Espindola4cd73522017-02-17 16:01:51 +0000773 assignSymbol(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000774 continue;
775 }
776
George Rimareefa7582016-08-04 09:29:31 +0000777 if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
Rafael Espindola4595df92017-03-10 16:04:26 +0000778 Cmd->Expression();
George Rimareefa7582016-08-04 09:29:31 +0000779 continue;
780 }
781
George Rimar076fe152016-07-21 06:43:01 +0000782 auto *Cmd = cast<OutputSectionCommand>(Base.get());
Rafael Espindolad3190792016-09-16 15:10:23 +0000783 assignOffsets(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000784 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000785
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000786 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
Rafael Espindola24e6f362017-02-24 15:07:30 +0000787 for (OutputSection *Sec : *OutputSections) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000788 if (Sec->Flags & SHF_ALLOC)
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000789 MinVA = std::min<uint64_t>(MinVA, Sec->Addr);
Rafael Espindolaea590d92017-02-08 15:19:03 +0000790 else
791 Sec->Addr = 0;
792 }
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000793
Rafael Espindola8c495e22017-01-20 20:41:18 +0000794 allocateHeaders<ELFT>(Phdrs, *OutputSections, MinVA);
George Rimar652852c2016-04-16 10:10:32 +0000795}
796
Rui Ueyama464daad2016-08-22 04:55:20 +0000797// Creates program headers as instructed by PHDRS linker script command.
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000798template <class ELFT> std::vector<PhdrEntry> LinkerScript<ELFT>::createPhdrs() {
799 std::vector<PhdrEntry> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000800
Rui Ueyama464daad2016-08-22 04:55:20 +0000801 // Process PHDRS and FILEHDR keywords because they are not
802 // real output sections and cannot be added in the following loop.
Eugene Leviantbbe38602016-07-19 09:25:43 +0000803 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000804 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000805 PhdrEntry &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000806
807 if (Cmd.HasFilehdr)
Rui Ueyama9d1bacb12017-02-27 02:31:26 +0000808 Phdr.add(Out::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000809 if (Cmd.HasPhdrs)
Rui Ueyama9d1bacb12017-02-27 02:31:26 +0000810 Phdr.add(Out::ProgramHeaders);
Eugene Leviant56b21c82016-09-09 09:46:16 +0000811
812 if (Cmd.LMAExpr) {
Rafael Espindola4595df92017-03-10 16:04:26 +0000813 Phdr.p_paddr = Cmd.LMAExpr();
Eugene Leviant56b21c82016-09-09 09:46:16 +0000814 Phdr.HasLMA = true;
815 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000816 }
817
Rui Ueyama464daad2016-08-22 04:55:20 +0000818 // Add output sections to program headers.
Rafael Espindola24e6f362017-02-24 15:07:30 +0000819 for (OutputSection *Sec : *OutputSections) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000820 if (!(Sec->Flags & SHF_ALLOC))
Eugene Leviantbbe38602016-07-19 09:25:43 +0000821 break;
822
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000823 // Assign headers specified by linker script
Rafael Espindola40849412017-02-24 14:28:00 +0000824 for (size_t Id : getPhdrIndices(Sec->Name)) {
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000825 Ret[Id].add(Sec);
826 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000827 Ret[Id].p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000828 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000829 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000830 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000831}
832
Eugene Leviantf9bc3bd2016-08-16 06:40:58 +0000833template <class ELFT> bool LinkerScript<ELFT>::ignoreInterpSection() {
834 // Ignore .interp section in case we have PHDRS specification
835 // and PT_INTERP isn't listed.
836 return !Opt.PhdrsCommands.empty() &&
837 llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
838 return Cmd.Type == PT_INTERP;
839 }) == Opt.PhdrsCommands.end();
840}
841
George Rimar93c64022016-12-15 15:38:09 +0000842template <class ELFT> uint32_t LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000843 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
844 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
845 if (Cmd->Name == Name)
846 return Cmd->Filler;
Rui Ueyama16068ae2016-11-19 18:05:56 +0000847 return 0;
George Rimare2ee72b2016-02-26 14:48:31 +0000848}
849
George Rimare38cbab2016-09-26 19:22:50 +0000850template <class ELFT>
851static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) {
852 const endianness E = ELFT::TargetEndianness;
853
854 switch (Size) {
855 case 1:
856 *Buf = (uint8_t)Data;
857 break;
858 case 2:
859 write16<E>(Buf, Data);
860 break;
861 case 4:
862 write32<E>(Buf, Data);
863 break;
864 case 8:
865 write64<E>(Buf, Data);
866 break;
867 default:
868 llvm_unreachable("unsupported Size argument");
869 }
870}
871
872template <class ELFT>
873void LinkerScript<ELFT>::writeDataBytes(StringRef Name, uint8_t *Buf) {
874 int I = getSectionIndex(Name);
875 if (I == INT_MAX)
876 return;
877
Rui Ueyama6e68c5e2016-11-19 18:05:58 +0000878 auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I].get());
879 for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
880 if (auto *Data = dyn_cast<BytesDataCommand>(Base.get()))
Rafael Espindola4595df92017-03-10 16:04:26 +0000881 writeInt<ELFT>(Buf + Data->Offset, Data->Expression(), Data->Size);
George Rimare38cbab2016-09-26 19:22:50 +0000882}
883
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000884template <class ELFT> bool LinkerScript<ELFT>::hasLMA(StringRef Name) {
George Rimar8ceadb32016-08-17 07:44:19 +0000885 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
886 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000887 if (Cmd->LMAExpr && Cmd->Name == Name)
888 return true;
889 return false;
George Rimar8ceadb32016-08-17 07:44:19 +0000890}
891
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000892// Returns the index of the given section name in linker script
893// SECTIONS commands. Sections are laid out as the same order as they
894// were in the script. If a given name did not appear in the script,
895// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000896template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
Rui Ueyama6e68c5e2016-11-19 18:05:58 +0000897 for (int I = 0, E = Opt.Commands.size(); I != E; ++I)
898 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I].get()))
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000899 if (Cmd->Name == Name)
900 return I;
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000901 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000902}
903
Eugene Leviantbbe38602016-07-19 09:25:43 +0000904template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
905 return !Opt.PhdrsCommands.empty();
906}
907
George Rimar9e694502016-07-29 16:18:47 +0000908template <class ELFT>
Rafael Espindola5616adf2017-03-08 22:36:28 +0000909OutputSection *LinkerScript<ELFT>::getOutputSection(const Twine &Loc,
910 StringRef Name) {
Rafael Espindola24e6f362017-02-24 15:07:30 +0000911 static OutputSection FakeSec("", 0, 0);
George Rimar96659df2016-08-30 09:54:01 +0000912
Rafael Espindola24e6f362017-02-24 15:07:30 +0000913 for (OutputSection *Sec : *OutputSections)
Rafael Espindola40849412017-02-24 14:28:00 +0000914 if (Sec->Name == Name)
Eugene Leviantafaa9342016-11-16 09:49:39 +0000915 return Sec;
Eugene Levianted30ce72016-11-28 09:58:04 +0000916
917 error(Loc + ": undefined section " + Name);
Eugene Leviantafaa9342016-11-16 09:49:39 +0000918 return &FakeSec;
Eugene Leviant36fac7f2016-09-08 09:08:30 +0000919}
920
Rui Ueyamaedf75e72016-11-17 20:27:10 +0000921// This function is essentially the same as getOutputSection(Name)->Size,
922// but it won't print out an error message if a given section is not found.
923//
924// Linker script does not create an output section if its content is empty.
925// We want to allow SIZEOF(.foo) where .foo is a section which happened to
926// be empty. That is why this function is different from getOutputSection().
927template <class ELFT>
928uint64_t LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
Rafael Espindola24e6f362017-02-24 15:07:30 +0000929 for (OutputSection *Sec : *OutputSections)
Rafael Espindola40849412017-02-24 14:28:00 +0000930 if (Sec->Name == Name)
Rui Ueyamaedf75e72016-11-17 20:27:10 +0000931 return Sec->Size;
932 return 0;
933}
934
George Rimar884e7862016-09-08 08:19:13 +0000935template <class ELFT> uint64_t LinkerScript<ELFT>::getHeaderSize() {
Rafael Espindola0d4b6d52016-09-22 16:47:21 +0000936 return elf::getHeaderSize<ELFT>();
George Rimare32a3592016-08-10 07:59:34 +0000937}
938
Eugene Leviantf6aeed32016-12-22 13:13:12 +0000939template <class ELFT>
940uint64_t LinkerScript<ELFT>::getSymbolValue(const Twine &Loc, StringRef S) {
Rafael Espindola4595df92017-03-10 16:04:26 +0000941 if (S == ".")
942 return Dot;
George Rimar884e7862016-09-08 08:19:13 +0000943 if (SymbolBody *B = Symtab<ELFT>::X->find(S))
944 return B->getVA<ELFT>();
Eugene Leviantf6aeed32016-12-22 13:13:12 +0000945 error(Loc + ": symbol not found: " + S);
George Rimar884e7862016-09-08 08:19:13 +0000946 return 0;
947}
948
George Rimarf34f45f2016-09-23 13:17:23 +0000949template <class ELFT> bool LinkerScript<ELFT>::isDefined(StringRef S) {
950 return Symtab<ELFT>::X->find(S) != nullptr;
951}
952
Rafael Espindola2f831dc2016-10-31 19:56:37 +0000953template <class ELFT> bool LinkerScript<ELFT>::isAbsolute(StringRef S) {
Rafael Espindola4595df92017-03-10 16:04:26 +0000954 if (S == ".")
955 return false;
Rafael Espindola2f831dc2016-10-31 19:56:37 +0000956 SymbolBody *Sym = Symtab<ELFT>::X->find(S);
Rui Ueyama80474a22017-02-28 19:29:55 +0000957 auto *DR = dyn_cast_or_null<DefinedRegular>(Sym);
Rafael Espindola2f831dc2016-10-31 19:56:37 +0000958 return DR && !DR->Section;
959}
960
Eugene Leviantafaa9342016-11-16 09:49:39 +0000961// Gets section symbol belongs to. Symbol "." doesn't belong to any
962// specific section but isn't absolute at the same time, so we try
963// to find suitable section for it as well.
964template <class ELFT>
Rafael Espindola5616adf2017-03-08 22:36:28 +0000965OutputSection *LinkerScript<ELFT>::getSymbolSection(StringRef S) {
Rafael Espindola06f47432017-02-06 22:21:46 +0000966 if (SymbolBody *Sym = Symtab<ELFT>::X->find(S))
Rui Ueyama968db482017-02-28 04:02:42 +0000967 return Sym->getOutputSection<ELFT>();
Rafael Espindola06f47432017-02-06 22:21:46 +0000968 return CurOutSec;
Eugene Leviantafaa9342016-11-16 09:49:39 +0000969}
970
Eugene Leviantbbe38602016-07-19 09:25:43 +0000971// Returns indices of ELF headers containing specific section, identified
972// by Name. Each index is a zero based number of ELF header listed within
973// PHDRS {} script block.
974template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000975std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000976 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
977 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000978 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000979 continue;
980
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000981 std::vector<size_t> Ret;
982 for (StringRef PhdrName : Cmd->Phdrs)
Eugene Leviant2a942c42016-12-05 16:38:32 +0000983 Ret.push_back(getPhdrIndex(Cmd->Location, PhdrName));
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000984 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000985 }
George Rimar31d842f2016-07-20 16:43:03 +0000986 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000987}
988
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000989template <class ELFT>
Eugene Leviant2a942c42016-12-05 16:38:32 +0000990size_t LinkerScript<ELFT>::getPhdrIndex(const Twine &Loc, StringRef PhdrName) {
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000991 size_t I = 0;
992 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
993 if (Cmd.Name == PhdrName)
994 return I;
995 ++I;
996 }
Eugene Leviant2a942c42016-12-05 16:38:32 +0000997 error(Loc + ": section header '" + PhdrName + "' is not listed in PHDRS");
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000998 return 0;
999}
1000
Rui Ueyama794366a2017-02-14 04:47:05 +00001001class elf::ScriptParser final : public ScriptLexer {
George Rimarc3794e52016-02-24 09:21:47 +00001002 typedef void (ScriptParser::*Handler)();
1003
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001004public:
Rui Ueyama22375f22016-11-25 18:51:54 +00001005 ScriptParser(MemoryBufferRef MB)
Rui Ueyama794366a2017-02-14 04:47:05 +00001006 : ScriptLexer(MB),
Rui Ueyama22375f22016-11-25 18:51:54 +00001007 IsUnderSysroot(isUnderSysroot(MB.getBufferIdentifier())) {}
George Rimarf23b2322016-02-19 10:45:45 +00001008
George Rimar20b65982016-08-31 09:08:26 +00001009 void readLinkerScript();
1010 void readVersionScript();
Rafael Espindolad0ebd842016-12-08 17:54:26 +00001011 void readDynamicList();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001012
1013private:
Rui Ueyama52a15092015-10-11 03:28:42 +00001014 void addFile(StringRef Path);
1015
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001016 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +00001017 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +00001018 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001019 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001020 void readInclude();
Meador Ingeb8897442017-01-24 02:34:00 +00001021 void readMemory();
Rui Ueyamaee592822015-10-07 00:25:09 +00001022 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +00001023 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001024 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +00001025 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +00001026 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001027 void readSections();
Rui Ueyama95769b42016-08-31 20:03:54 +00001028 void readVersion();
1029 void readVersionScriptCommand();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001030
Rui Ueyama113cdec2016-07-24 23:05:57 +00001031 SymbolAssignment *readAssignment(StringRef Name);
George Rimare38cbab2016-09-26 19:22:50 +00001032 BytesDataCommand *readBytesDataCommand(StringRef Tok);
Rui Ueyama16068ae2016-11-19 18:05:56 +00001033 uint32_t readFill();
Rui Ueyama10416562016-08-04 02:03:27 +00001034 OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
Rui Ueyama16068ae2016-11-19 18:05:56 +00001035 uint32_t readOutputSectionFiller(StringRef Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001036 std::vector<StringRef> readOutputSectionPhdrs();
George Rimara2496cb2016-08-30 09:46:59 +00001037 InputSectionDescription *readInputSectionDescription(StringRef Tok);
Eugene Leviantdb688452016-11-03 10:54:58 +00001038 StringMatcher readFilePatterns();
George Rimar07171f22016-09-21 15:56:44 +00001039 std::vector<SectionPattern> readInputSectionsList();
George Rimara2496cb2016-08-30 09:46:59 +00001040 InputSectionDescription *readInputSectionRules(StringRef FilePattern);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001041 unsigned readPhdrType();
George Rimarbe394db2016-09-16 20:21:55 +00001042 SortSectionPolicy readSortKind();
Petr Hoseka35e39c2016-08-16 01:11:16 +00001043 SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
Rafael Espindolac96da112016-11-01 11:30:45 +00001044 SymbolAssignment *readProvideOrAssignment(StringRef Tok);
George Rimar03fc0102016-07-28 07:18:23 +00001045 void readSort();
George Rimareefa7582016-08-04 09:29:31 +00001046 Expr readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001047
Rui Ueyama24e626c2017-01-26 02:58:19 +00001048 uint64_t readMemoryAssignment(StringRef, StringRef, StringRef);
1049 std::pair<uint32_t, uint32_t> readMemoryAttributes();
1050
Rui Ueyama708019c2016-07-24 18:19:40 +00001051 Expr readExpr();
1052 Expr readExpr1(Expr Lhs, int MinPrec);
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001053 StringRef readParenLiteral();
Rui Ueyama708019c2016-07-24 18:19:40 +00001054 Expr readPrimary();
1055 Expr readTernary(Expr Cond);
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001056 Expr readParenExpr();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001057
George Rimar20b65982016-08-31 09:08:26 +00001058 // For parsing version script.
Rui Ueyama12450b22016-11-18 06:30:09 +00001059 std::vector<SymbolVersion> readVersionExtern();
1060 void readAnonymousDeclaration();
Rui Ueyama95769b42016-08-31 20:03:54 +00001061 void readVersionDeclaration(StringRef VerStr);
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001062
1063 std::pair<std::vector<SymbolVersion>, std::vector<SymbolVersion>>
1064 readSymbols();
George Rimar20b65982016-08-31 09:08:26 +00001065
Rui Ueyama07320e42016-04-20 20:13:41 +00001066 ScriptConfiguration &Opt = *ScriptConfig;
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001067 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001068};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001069
Rafael Espindolad0ebd842016-12-08 17:54:26 +00001070void ScriptParser::readDynamicList() {
1071 expect("{");
1072 readAnonymousDeclaration();
1073 if (!atEOF())
1074 setError("EOF expected, but got " + next());
1075}
1076
George Rimar20b65982016-08-31 09:08:26 +00001077void ScriptParser::readVersionScript() {
Rui Ueyama95769b42016-08-31 20:03:54 +00001078 readVersionScriptCommand();
1079 if (!atEOF())
1080 setError("EOF expected, but got " + next());
1081}
1082
1083void ScriptParser::readVersionScriptCommand() {
Rui Ueyama83043f22016-10-17 16:01:53 +00001084 if (consume("{")) {
Rui Ueyama12450b22016-11-18 06:30:09 +00001085 readAnonymousDeclaration();
George Rimar20b65982016-08-31 09:08:26 +00001086 return;
1087 }
1088
Rui Ueyama95769b42016-08-31 20:03:54 +00001089 while (!atEOF() && !Error && peek() != "}") {
George Rimar20b65982016-08-31 09:08:26 +00001090 StringRef VerStr = next();
1091 if (VerStr == "{") {
Rui Ueyama95769b42016-08-31 20:03:54 +00001092 setError("anonymous version definition is used in "
1093 "combination with other version definitions");
George Rimar20b65982016-08-31 09:08:26 +00001094 return;
1095 }
1096 expect("{");
Rui Ueyama95769b42016-08-31 20:03:54 +00001097 readVersionDeclaration(VerStr);
George Rimar20b65982016-08-31 09:08:26 +00001098 }
1099}
1100
Rui Ueyama95769b42016-08-31 20:03:54 +00001101void ScriptParser::readVersion() {
1102 expect("{");
1103 readVersionScriptCommand();
1104 expect("}");
1105}
1106
George Rimar20b65982016-08-31 09:08:26 +00001107void ScriptParser::readLinkerScript() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001108 while (!atEOF()) {
1109 StringRef Tok = next();
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001110 if (Tok == ";")
1111 continue;
1112
Eugene Leviant20d03192016-09-16 15:30:47 +00001113 if (Tok == "ASSERT") {
1114 Opt.Commands.emplace_back(new AssertCommand(readAssert()));
1115 } else if (Tok == "ENTRY") {
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001116 readEntry();
1117 } else if (Tok == "EXTERN") {
1118 readExtern();
1119 } else if (Tok == "GROUP" || Tok == "INPUT") {
1120 readGroup();
1121 } else if (Tok == "INCLUDE") {
1122 readInclude();
Meador Ingeb8897442017-01-24 02:34:00 +00001123 } else if (Tok == "MEMORY") {
1124 readMemory();
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001125 } else if (Tok == "OUTPUT") {
1126 readOutput();
1127 } else if (Tok == "OUTPUT_ARCH") {
1128 readOutputArch();
1129 } else if (Tok == "OUTPUT_FORMAT") {
1130 readOutputFormat();
1131 } else if (Tok == "PHDRS") {
1132 readPhdrs();
1133 } else if (Tok == "SEARCH_DIR") {
1134 readSearchDir();
1135 } else if (Tok == "SECTIONS") {
1136 readSections();
1137 } else if (Tok == "VERSION") {
1138 readVersion();
Rafael Espindolac96da112016-11-01 11:30:45 +00001139 } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok)) {
Eugene Leviant20d03192016-09-16 15:30:47 +00001140 Opt.Commands.emplace_back(Cmd);
Petr Hoseke5d3ca52016-08-31 15:31:17 +00001141 } else {
George Rimar57610422016-03-11 14:43:02 +00001142 setError("unknown directive: " + Tok);
Petr Hoseke5d3ca52016-08-31 15:31:17 +00001143 }
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001144 }
1145}
1146
Rui Ueyama717677a2016-02-11 21:17:59 +00001147void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001148 if (IsUnderSysroot && S.startswith("/")) {
Justin Bogner5af16872016-10-17 06:08:48 +00001149 SmallString<128> PathData;
1150 StringRef Path = (Config->Sysroot + S).toStringRef(PathData);
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001151 if (sys::fs::exists(Path)) {
Justin Bogner5af16872016-10-17 06:08:48 +00001152 Driver->addFile(Saver.save(Path));
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001153 return;
1154 }
1155 }
1156
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +00001157 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +00001158 Driver->addFile(S);
1159 } else if (S.startswith("=")) {
1160 if (Config->Sysroot.empty())
1161 Driver->addFile(S.substr(1));
1162 else
1163 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
1164 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +00001165 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +00001166 } else if (sys::fs::exists(S)) {
1167 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +00001168 } else {
Rui Ueyama061f9282016-11-19 19:23:58 +00001169 if (Optional<std::string> Path = findFromSearchPaths(S))
1170 Driver->addFile(Saver.save(*Path));
Rui Ueyama025d59b2016-02-02 20:27:59 +00001171 else
Rui Ueyama061f9282016-11-19 19:23:58 +00001172 setError("unable to find " + S);
Rui Ueyama52a15092015-10-11 03:28:42 +00001173 }
1174}
1175
Rui Ueyama717677a2016-02-11 21:17:59 +00001176void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001177 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +00001178 bool Orig = Config->AsNeeded;
1179 Config->AsNeeded = true;
Rui Ueyama83043f22016-10-17 16:01:53 +00001180 while (!Error && !consume(")"))
George Rimarcd574a52016-09-09 14:35:36 +00001181 addFile(unquote(next()));
Rui Ueyama35da9b62015-10-11 20:59:12 +00001182 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001183}
1184
Rui Ueyama717677a2016-02-11 21:17:59 +00001185void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +00001186 // -e <symbol> takes predecence over ENTRY(<symbol>).
1187 expect("(");
1188 StringRef Tok = next();
1189 if (Config->Entry.empty())
1190 Config->Entry = Tok;
1191 expect(")");
1192}
1193
Rui Ueyama717677a2016-02-11 21:17:59 +00001194void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +00001195 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001196 while (!Error && !consume(")"))
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001197 Config->Undefined.push_back(next());
George Rimar83f406c2015-10-19 17:35:12 +00001198}
1199
Rui Ueyama717677a2016-02-11 21:17:59 +00001200void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001201 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001202 while (!Error && !consume(")")) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001203 StringRef Tok = next();
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001204 if (Tok == "AS_NEEDED")
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001205 readAsNeeded();
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001206 else
George Rimarcd574a52016-09-09 14:35:36 +00001207 addFile(unquote(Tok));
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001208 }
1209}
1210
Rui Ueyama717677a2016-02-11 21:17:59 +00001211void ScriptParser::readInclude() {
George Rimard4500652016-12-21 09:42:25 +00001212 StringRef Tok = unquote(next());
Rui Ueyamaec1c75e2017-01-09 01:42:02 +00001213
George Rimard4500652016-12-21 09:42:25 +00001214 // https://sourceware.org/binutils/docs/ld/File-Commands.html:
1215 // The file will be searched for in the current directory, and in any
1216 // directory specified with the -L option.
Rui Ueyamaec1c75e2017-01-09 01:42:02 +00001217 if (sys::fs::exists(Tok)) {
1218 if (Optional<MemoryBufferRef> MB = readFile(Tok))
1219 tokenize(*MB);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001220 return;
1221 }
Rui Ueyamaec1c75e2017-01-09 01:42:02 +00001222 if (Optional<std::string> Path = findFromSearchPaths(Tok)) {
1223 if (Optional<MemoryBufferRef> MB = readFile(*Path))
1224 tokenize(*MB);
1225 return;
1226 }
1227 setError("cannot open " + Tok);
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001228}
1229
Rui Ueyama717677a2016-02-11 21:17:59 +00001230void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +00001231 // -o <file> takes predecence over OUTPUT(<file>).
1232 expect("(");
1233 StringRef Tok = next();
1234 if (Config->OutputFile.empty())
George Rimarcd574a52016-09-09 14:35:36 +00001235 Config->OutputFile = unquote(Tok);
Rui Ueyamaee592822015-10-07 00:25:09 +00001236 expect(")");
1237}
1238
Rui Ueyama717677a2016-02-11 21:17:59 +00001239void ScriptParser::readOutputArch() {
George Rimar4e01c3e2017-02-08 09:59:06 +00001240 // OUTPUT_ARCH is ignored for now.
Davide Italiano9159ce92015-10-12 21:50:08 +00001241 expect("(");
George Rimar4e01c3e2017-02-08 09:59:06 +00001242 while (!Error && !consume(")"))
1243 skip();
Davide Italiano9159ce92015-10-12 21:50:08 +00001244}
1245
Rui Ueyama717677a2016-02-11 21:17:59 +00001246void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001247 // Error checking only for now.
1248 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001249 skip();
Davide Italiano6836c612015-10-12 21:08:41 +00001250 StringRef Tok = next();
1251 if (Tok == ")")
George Rimar6c55f0e2016-09-08 08:20:30 +00001252 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +00001253 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +00001254 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001255 return;
1256 }
Justin Bogner5424e7c2016-10-17 06:21:13 +00001257 skip();
Davide Italiano6836c612015-10-12 21:08:41 +00001258 expect(",");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001259 skip();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001260 expect(")");
1261}
1262
Eugene Leviantbbe38602016-07-19 09:25:43 +00001263void ScriptParser::readPhdrs() {
1264 expect("{");
Rui Ueyama83043f22016-10-17 16:01:53 +00001265 while (!Error && !consume("}")) {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001266 StringRef Tok = next();
Eugene Leviant56b21c82016-09-09 09:46:16 +00001267 Opt.PhdrsCommands.push_back(
1268 {Tok, PT_NULL, false, false, UINT_MAX, nullptr});
Eugene Leviantbbe38602016-07-19 09:25:43 +00001269 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
1270
1271 PhdrCmd.Type = readPhdrType();
1272 do {
1273 Tok = next();
1274 if (Tok == ";")
1275 break;
1276 if (Tok == "FILEHDR")
1277 PhdrCmd.HasFilehdr = true;
1278 else if (Tok == "PHDRS")
1279 PhdrCmd.HasPhdrs = true;
Eugene Leviant56b21c82016-09-09 09:46:16 +00001280 else if (Tok == "AT")
1281 PhdrCmd.LMAExpr = readParenExpr();
Eugene Leviant865bf862016-07-21 10:43:25 +00001282 else if (Tok == "FLAGS") {
1283 expect("(");
Rafael Espindolaeb685cd2016-08-02 22:14:57 +00001284 // Passing 0 for the value of dot is a bit of a hack. It means that
1285 // we accept expressions like ".|1".
Rafael Espindola4595df92017-03-10 16:04:26 +00001286 PhdrCmd.Flags = readExpr()();
Eugene Leviant865bf862016-07-21 10:43:25 +00001287 expect(")");
1288 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +00001289 setError("unexpected header attribute: " + Tok);
1290 } while (!Error);
1291 }
1292}
1293
Rui Ueyama717677a2016-02-11 21:17:59 +00001294void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +00001295 expect("(");
Rui Ueyama86c5fb82016-09-08 23:26:54 +00001296 StringRef Tok = next();
Rui Ueyama6c7ad132016-09-02 19:20:33 +00001297 if (!Config->Nostdlib)
George Rimarcd574a52016-09-09 14:35:36 +00001298 Config->SearchPaths.push_back(unquote(Tok));
Davide Italiano68a39a62015-10-08 17:51:41 +00001299 expect(")");
1300}
1301
Rui Ueyama717677a2016-02-11 21:17:59 +00001302void ScriptParser::readSections() {
Eugene Leviante05336ff2016-09-14 08:32:36 +00001303 Opt.HasSections = true;
George Rimar18a30962016-11-28 10:11:10 +00001304 // -no-rosegment is used to avoid placing read only non-executable sections in
1305 // their own segment. We do the same if SECTIONS command is present in linker
1306 // script. See comment for computeFlags().
1307 Config->SingleRoRx = true;
1308
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001309 expect("{");
Rui Ueyama83043f22016-10-17 16:01:53 +00001310 while (!Error && !consume("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +00001311 StringRef Tok = next();
Rafael Espindolac96da112016-11-01 11:30:45 +00001312 BaseCommand *Cmd = readProvideOrAssignment(Tok);
Eugene Leviantceabe802016-08-11 07:56:43 +00001313 if (!Cmd) {
1314 if (Tok == "ASSERT")
1315 Cmd = new AssertCommand(readAssert());
1316 else
1317 Cmd = readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +00001318 }
Rui Ueyama10416562016-08-04 02:03:27 +00001319 Opt.Commands.emplace_back(Cmd);
George Rimar652852c2016-04-16 10:10:32 +00001320 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001321}
1322
Rui Ueyama708019c2016-07-24 18:19:40 +00001323static int precedence(StringRef Op) {
1324 return StringSwitch<int>(Op)
Rui Ueyama0120e3f2016-09-23 18:06:51 +00001325 .Cases("*", "/", 5)
1326 .Cases("+", "-", 4)
1327 .Cases("<<", ">>", 3)
Rui Ueyama9c4ac5f2016-09-23 22:22:34 +00001328 .Cases("<", "<=", ">", ">=", "==", "!=", 2)
Rui Ueyama0120e3f2016-09-23 18:06:51 +00001329 .Cases("&", "|", 1)
Rui Ueyama708019c2016-07-24 18:19:40 +00001330 .Default(-1);
1331}
1332
Eugene Leviantdb688452016-11-03 10:54:58 +00001333StringMatcher ScriptParser::readFilePatterns() {
Rui Ueyama10416562016-08-04 02:03:27 +00001334 std::vector<StringRef> V;
Rui Ueyama83043f22016-10-17 16:01:53 +00001335 while (!Error && !consume(")"))
Rui Ueyama10416562016-08-04 02:03:27 +00001336 V.push_back(next());
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001337 return StringMatcher(V);
George Rimar0702c4e2016-07-29 15:32:46 +00001338}
1339
George Rimarbe394db2016-09-16 20:21:55 +00001340SortSectionPolicy ScriptParser::readSortKind() {
Rui Ueyama83043f22016-10-17 16:01:53 +00001341 if (consume("SORT") || consume("SORT_BY_NAME"))
George Rimarbe394db2016-09-16 20:21:55 +00001342 return SortSectionPolicy::Name;
Rui Ueyama83043f22016-10-17 16:01:53 +00001343 if (consume("SORT_BY_ALIGNMENT"))
George Rimarbe394db2016-09-16 20:21:55 +00001344 return SortSectionPolicy::Alignment;
Rui Ueyama83043f22016-10-17 16:01:53 +00001345 if (consume("SORT_BY_INIT_PRIORITY"))
George Rimarbe394db2016-09-16 20:21:55 +00001346 return SortSectionPolicy::Priority;
Rui Ueyama83043f22016-10-17 16:01:53 +00001347 if (consume("SORT_NONE"))
Rui Ueyamab2a0abd2016-09-16 21:14:55 +00001348 return SortSectionPolicy::None;
1349 return SortSectionPolicy::Default;
George Rimarbe394db2016-09-16 20:21:55 +00001350}
1351
George Rimar395281c2016-09-16 17:42:10 +00001352// Method reads a list of sequence of excluded files and section globs given in
1353// a following form: ((EXCLUDE_FILE(file_pattern+))? section_pattern+)+
1354// Example: *(.foo.1 EXCLUDE_FILE (*a.o) .foo.2 EXCLUDE_FILE (*b.o) .foo.3)
George Rimaraf03be12016-09-17 19:17:25 +00001355// The semantics of that is next:
1356// * Include .foo.1 from every file.
1357// * Include .foo.2 from every file but a.o
1358// * Include .foo.3 from every file but b.o
George Rimar07171f22016-09-21 15:56:44 +00001359std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
1360 std::vector<SectionPattern> Ret;
George Rimar601e9892016-09-21 08:53:21 +00001361 while (!Error && peek() != ")") {
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001362 StringMatcher ExcludeFilePat;
Rui Ueyama83043f22016-10-17 16:01:53 +00001363 if (consume("EXCLUDE_FILE")) {
George Rimar395281c2016-09-16 17:42:10 +00001364 expect("(");
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001365 ExcludeFilePat = readFilePatterns();
George Rimar395281c2016-09-16 17:42:10 +00001366 }
1367
George Rimar601e9892016-09-21 08:53:21 +00001368 std::vector<StringRef> V;
1369 while (!Error && peek() != ")" && peek() != "EXCLUDE_FILE")
1370 V.push_back(next());
1371
1372 if (!V.empty())
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001373 Ret.push_back({std::move(ExcludeFilePat), StringMatcher(V)});
George Rimar601e9892016-09-21 08:53:21 +00001374 else
1375 setError("section pattern is expected");
George Rimar395281c2016-09-16 17:42:10 +00001376 }
George Rimar07171f22016-09-21 15:56:44 +00001377 return Ret;
George Rimar395281c2016-09-16 17:42:10 +00001378}
1379
Rui Ueyamaf8f6f1e2016-11-18 07:03:56 +00001380// Reads contents of "SECTIONS" directive. That directive contains a
1381// list of glob patterns for input sections. The grammar is as follows.
1382//
1383// <patterns> ::= <section-list>
1384// | <sort> "(" <section-list> ")"
1385// | <sort> "(" <sort> "(" <section-list> ")" ")"
1386//
1387// <sort> ::= "SORT" | "SORT_BY_NAME" | "SORT_BY_ALIGNMENT"
1388// | "SORT_BY_INIT_PRIORITY" | "SORT_NONE"
1389//
1390// <section-list> is parsed by readInputSectionsList().
George Rimara2496cb2016-08-30 09:46:59 +00001391InputSectionDescription *
1392ScriptParser::readInputSectionRules(StringRef FilePattern) {
George Rimarc91930a2016-09-02 21:17:20 +00001393 auto *Cmd = new InputSectionDescription(FilePattern);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001394 expect("(");
Rui Ueyamaf373dd72016-11-24 01:43:21 +00001395 while (!Error && !consume(")")) {
George Rimar07171f22016-09-21 15:56:44 +00001396 SortSectionPolicy Outer = readSortKind();
1397 SortSectionPolicy Inner = SortSectionPolicy::Default;
1398 std::vector<SectionPattern> V;
1399 if (Outer != SortSectionPolicy::Default) {
George Rimar350ece42016-08-03 08:35:59 +00001400 expect("(");
George Rimar07171f22016-09-21 15:56:44 +00001401 Inner = readSortKind();
1402 if (Inner != SortSectionPolicy::Default) {
1403 expect("(");
1404 V = readInputSectionsList();
1405 expect(")");
1406 } else {
1407 V = readInputSectionsList();
1408 }
George Rimar350ece42016-08-03 08:35:59 +00001409 expect(")");
1410 } else {
George Rimar07171f22016-09-21 15:56:44 +00001411 V = readInputSectionsList();
George Rimar350ece42016-08-03 08:35:59 +00001412 }
George Rimar0702c4e2016-07-29 15:32:46 +00001413
George Rimar07171f22016-09-21 15:56:44 +00001414 for (SectionPattern &Pat : V) {
1415 Pat.SortInner = Inner;
1416 Pat.SortOuter = Outer;
1417 }
1418
1419 std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns));
1420 }
Rui Ueyama10416562016-08-04 02:03:27 +00001421 return Cmd;
Davide Italianoe7282792016-07-27 01:44:01 +00001422}
1423
George Rimara2496cb2016-08-30 09:46:59 +00001424InputSectionDescription *
1425ScriptParser::readInputSectionDescription(StringRef Tok) {
George Rimar06598002016-07-28 21:51:30 +00001426 // Input section wildcard can be surrounded by KEEP.
1427 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
George Rimara2496cb2016-08-30 09:46:59 +00001428 if (Tok == "KEEP") {
George Rimar06598002016-07-28 21:51:30 +00001429 expect("(");
George Rimara2496cb2016-08-30 09:46:59 +00001430 StringRef FilePattern = next();
1431 InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
George Rimar06598002016-07-28 21:51:30 +00001432 expect(")");
Eugene Leviantcf43f172016-10-05 09:36:59 +00001433 Opt.KeptSections.push_back(Cmd);
Rui Ueyama10416562016-08-04 02:03:27 +00001434 return Cmd;
George Rimar06598002016-07-28 21:51:30 +00001435 }
George Rimara2496cb2016-08-30 09:46:59 +00001436 return readInputSectionRules(Tok);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001437}
1438
George Rimar03fc0102016-07-28 07:18:23 +00001439void ScriptParser::readSort() {
1440 expect("(");
1441 expect("CONSTRUCTORS");
1442 expect(")");
1443}
1444
George Rimareefa7582016-08-04 09:29:31 +00001445Expr ScriptParser::readAssert() {
1446 expect("(");
1447 Expr E = readExpr();
1448 expect(",");
George Rimarcd574a52016-09-09 14:35:36 +00001449 StringRef Msg = unquote(next());
George Rimareefa7582016-08-04 09:29:31 +00001450 expect(")");
Rafael Espindola4595df92017-03-10 16:04:26 +00001451 return [=] {
1452 if (!E())
George Rimareefa7582016-08-04 09:29:31 +00001453 error(Msg);
Rafael Espindola4595df92017-03-10 16:04:26 +00001454 return ScriptBase->getDot();
George Rimareefa7582016-08-04 09:29:31 +00001455 };
1456}
1457
Rui Ueyama25150e82016-09-06 17:46:43 +00001458// Reads a FILL(expr) command. We handle the FILL command as an
1459// alias for =fillexp section attribute, which is different from
1460// what GNU linkers do.
1461// https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
Rui Ueyama16068ae2016-11-19 18:05:56 +00001462uint32_t ScriptParser::readFill() {
George Rimarff1f29e2016-09-06 13:51:57 +00001463 expect("(");
Rui Ueyama16068ae2016-11-19 18:05:56 +00001464 uint32_t V = readOutputSectionFiller(next());
George Rimarff1f29e2016-09-06 13:51:57 +00001465 expect(")");
1466 expect(";");
1467 return V;
1468}
1469
Rui Ueyama10416562016-08-04 02:03:27 +00001470OutputSectionCommand *
1471ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +00001472 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
Eugene Leviant2a942c42016-12-05 16:38:32 +00001473 Cmd->Location = getCurrentLocation();
George Rimar58e5c4d2016-07-25 08:29:46 +00001474
1475 // Read an address expression.
1476 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
1477 if (peek() != ":")
1478 Cmd->AddrExpr = readExpr();
1479
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001480 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +00001481
Rui Ueyama83043f22016-10-17 16:01:53 +00001482 if (consume("AT"))
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001483 Cmd->LMAExpr = readParenExpr();
Rui Ueyama83043f22016-10-17 16:01:53 +00001484 if (consume("ALIGN"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001485 Cmd->AlignExpr = readParenExpr();
Rui Ueyama83043f22016-10-17 16:01:53 +00001486 if (consume("SUBALIGN"))
George Rimardb24d9c2016-08-19 15:18:23 +00001487 Cmd->SubalignExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001488
Davide Italiano246f6812016-07-22 03:36:24 +00001489 // Parse constraints.
Rui Ueyama83043f22016-10-17 16:01:53 +00001490 if (consume("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001491 Cmd->Constraint = ConstraintKind::ReadOnly;
Rui Ueyama83043f22016-10-17 16:01:53 +00001492 if (consume("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001493 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001494 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001495
Rui Ueyama83043f22016-10-17 16:01:53 +00001496 while (!Error && !consume("}")) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001497 StringRef Tok = next();
George Rimar2fe07922017-01-31 08:50:11 +00001498 if (Tok == ";") {
George Rimar69750752017-02-01 09:14:22 +00001499 // Empty commands are allowed. Do nothing here.
George Rimar2fe07922017-01-31 08:50:11 +00001500 } else if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok)) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001501 Cmd->Commands.emplace_back(Assignment);
Meador Ingeb2d99d62016-11-22 18:01:50 +00001502 } else if (BytesDataCommand *Data = readBytesDataCommand(Tok)) {
George Rimare38cbab2016-09-26 19:22:50 +00001503 Cmd->Commands.emplace_back(Data);
Meador Ingeb2d99d62016-11-22 18:01:50 +00001504 } else if (Tok == "ASSERT") {
1505 Cmd->Commands.emplace_back(new AssertCommand(readAssert()));
1506 expect(";");
George Rimar8e2eca22017-01-23 09:36:19 +00001507 } else if (Tok == "CONSTRUCTORS") {
1508 // CONSTRUCTORS is a keyword to make the linker recognize C++ ctors/dtors
1509 // by name. This is for very old file formats such as ECOFF/XCOFF.
1510 // For ELF, we should ignore.
Meador Ingeb2d99d62016-11-22 18:01:50 +00001511 } else if (Tok == "FILL") {
George Rimarff1f29e2016-09-06 13:51:57 +00001512 Cmd->Filler = readFill();
Meador Ingeb2d99d62016-11-22 18:01:50 +00001513 } else if (Tok == "SORT") {
George Rimar03fc0102016-07-28 07:18:23 +00001514 readSort();
Meador Ingeb2d99d62016-11-22 18:01:50 +00001515 } else if (peek() == "(") {
George Rimara2496cb2016-08-30 09:46:59 +00001516 Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
Meador Ingeb2d99d62016-11-22 18:01:50 +00001517 } else {
Eugene Leviantceabe802016-08-11 07:56:43 +00001518 setError("unknown command " + Tok);
Meador Ingeb2d99d62016-11-22 18:01:50 +00001519 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001520 }
Meador Ingeb8897442017-01-24 02:34:00 +00001521
1522 if (consume(">"))
1523 Cmd->MemoryRegionName = next();
1524
George Rimar076fe152016-07-21 06:43:01 +00001525 Cmd->Phdrs = readOutputSectionPhdrs();
George Rimar4ebc5622016-09-23 13:29:20 +00001526
Rui Ueyama83043f22016-10-17 16:01:53 +00001527 if (consume("="))
George Rimar4ebc5622016-09-23 13:29:20 +00001528 Cmd->Filler = readOutputSectionFiller(next());
1529 else if (peek().startswith("="))
George Rimarff1f29e2016-09-06 13:51:57 +00001530 Cmd->Filler = readOutputSectionFiller(next().drop_front());
George Rimar4ebc5622016-09-23 13:29:20 +00001531
George Rimar7185a1a2017-01-17 15:32:12 +00001532 // Consume optional comma following output section command.
1533 consume(",");
1534
Rui Ueyama10416562016-08-04 02:03:27 +00001535 return Cmd;
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001536}
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001537
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001538// Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
1539// https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
1540//
1541// ld.gold is not fully compatible with ld.bfd. ld.bfd handles
1542// hexstrings as blobs of arbitrary sizes, while ld.gold handles them
1543// as 32-bit big-endian values. We will do the same as ld.gold does
1544// because it's simpler than what ld.bfd does.
Rui Ueyama16068ae2016-11-19 18:05:56 +00001545uint32_t ScriptParser::readOutputSectionFiller(StringRef Tok) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001546 uint32_t V;
Rui Ueyama16068ae2016-11-19 18:05:56 +00001547 if (!Tok.getAsInteger(0, V))
1548 return V;
1549 setError("invalid filler expression: " + Tok);
1550 return 0;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001551}
1552
Petr Hoseka35e39c2016-08-16 01:11:16 +00001553SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
Eugene Levianta31c91b2016-07-22 07:38:40 +00001554 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +00001555 SymbolAssignment *Cmd = readAssignment(next());
Petr Hoseka35e39c2016-08-16 01:11:16 +00001556 Cmd->Provide = Provide;
Rui Ueyama174e0a12016-07-29 00:29:25 +00001557 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001558 expect(")");
1559 expect(";");
Rui Ueyama10416562016-08-04 02:03:27 +00001560 return Cmd;
Eugene Levianteda81a12016-07-12 06:39:48 +00001561}
1562
Rafael Espindolac96da112016-11-01 11:30:45 +00001563SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001564 SymbolAssignment *Cmd = nullptr;
1565 if (peek() == "=" || peek() == "+=") {
1566 Cmd = readAssignment(Tok);
1567 expect(";");
1568 } else if (Tok == "PROVIDE") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001569 Cmd = readProvideHidden(true, false);
1570 } else if (Tok == "HIDDEN") {
1571 Cmd = readProvideHidden(false, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001572 } else if (Tok == "PROVIDE_HIDDEN") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001573 Cmd = readProvideHidden(true, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001574 }
1575 return Cmd;
1576}
1577
George Rimar30835ea2016-07-28 21:08:56 +00001578SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1579 StringRef Op = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +00001580 Expr E;
George Rimar30835ea2016-07-28 21:08:56 +00001581 assert(Op == "=" || Op == "+=");
Rui Ueyama83043f22016-10-17 16:01:53 +00001582 if (consume("ABSOLUTE")) {
Rui Ueyama731a66a2017-02-15 19:58:17 +00001583 E = readExpr();
Rui Ueyama009d1742016-11-18 06:49:09 +00001584 E.IsAbsolute = [] { return true; };
Eugene Leviantdb741e72016-09-07 07:08:43 +00001585 } else {
1586 E = readExpr();
1587 }
Eugene Leviantf6aeed32016-12-22 13:13:12 +00001588 if (Op == "+=") {
1589 std::string Loc = getCurrentLocation();
Rafael Espindola4595df92017-03-10 16:04:26 +00001590 E = [=] { return ScriptBase->getSymbolValue(Loc, Name) + E(); };
Eugene Leviantf6aeed32016-12-22 13:13:12 +00001591 }
George Rimar2ee2d2d2017-02-21 14:50:38 +00001592 return new SymbolAssignment(Name, E, getCurrentLocation());
George Rimar30835ea2016-07-28 21:08:56 +00001593}
1594
1595// This is an operator-precedence parser to parse a linker
1596// script expression.
Rui Ueyama731a66a2017-02-15 19:58:17 +00001597Expr ScriptParser::readExpr() {
1598 // Our lexer is context-aware. Set the in-expression bit so that
1599 // they apply different tokenization rules.
1600 bool Orig = InExpr;
1601 InExpr = true;
1602 Expr E = readExpr1(readPrimary(), 0);
1603 InExpr = Orig;
1604 return E;
1605}
George Rimar30835ea2016-07-28 21:08:56 +00001606
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001607static Expr combine(StringRef Op, Expr L, Expr R) {
George Rimarcc4d3e52017-02-01 09:01:16 +00001608 auto IsAbs = [=] { return L.IsAbsolute() && R.IsAbsolute(); };
1609 auto GetOutSec = [=] {
Rafael Espindola9bd45662017-03-10 00:47:33 +00001610 SectionBase *S = L.Section();
George Rimarcc4d3e52017-02-01 09:01:16 +00001611 return S ? S : R.Section();
1612 };
1613
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001614 if (Op == "*")
Rafael Espindola4595df92017-03-10 16:04:26 +00001615 return [=] { return L() * R(); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001616 if (Op == "/") {
Rafael Espindola4595df92017-03-10 16:04:26 +00001617 return [=]() -> uint64_t {
1618 uint64_t RHS = R();
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001619 if (RHS == 0) {
1620 error("division by zero");
1621 return 0;
1622 }
Rafael Espindola4595df92017-03-10 16:04:26 +00001623 return L() / RHS;
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001624 };
1625 }
1626 if (Op == "+")
Rafael Espindola4595df92017-03-10 16:04:26 +00001627 return {[=] { return L() + R(); }, IsAbs, GetOutSec};
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001628 if (Op == "-")
Rafael Espindola4595df92017-03-10 16:04:26 +00001629 return {[=] { return L() - R(); }, IsAbs, GetOutSec};
George Rimarc8ccd1f2016-09-23 13:13:55 +00001630 if (Op == "<<")
Rafael Espindola4595df92017-03-10 16:04:26 +00001631 return [=] { return L() << R(); };
George Rimarc8ccd1f2016-09-23 13:13:55 +00001632 if (Op == ">>")
Rafael Espindola4595df92017-03-10 16:04:26 +00001633 return [=] { return L() >> R(); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001634 if (Op == "<")
Rafael Espindola4595df92017-03-10 16:04:26 +00001635 return [=] { return L() < R(); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001636 if (Op == ">")
Rafael Espindola4595df92017-03-10 16:04:26 +00001637 return [=] { return L() > R(); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001638 if (Op == ">=")
Rafael Espindola4595df92017-03-10 16:04:26 +00001639 return [=] { return L() >= R(); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001640 if (Op == "<=")
Rafael Espindola4595df92017-03-10 16:04:26 +00001641 return [=] { return L() <= R(); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001642 if (Op == "==")
Rafael Espindola4595df92017-03-10 16:04:26 +00001643 return [=] { return L() == R(); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001644 if (Op == "!=")
Rafael Espindola4595df92017-03-10 16:04:26 +00001645 return [=] { return L() != R(); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001646 if (Op == "&")
Rafael Espindola4595df92017-03-10 16:04:26 +00001647 return [=] { return L() & R(); };
Rafael Espindolacc3dd622016-08-22 21:33:35 +00001648 if (Op == "|")
Rafael Espindola4595df92017-03-10 16:04:26 +00001649 return [=] { return L() | R(); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001650 llvm_unreachable("invalid operator");
1651}
1652
Rui Ueyama708019c2016-07-24 18:19:40 +00001653// This is a part of the operator-precedence parser. This function
1654// assumes that the remaining token stream starts with an operator.
1655Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1656 while (!atEOF() && !Error) {
1657 // Read an operator and an expression.
Rui Ueyama46247b82016-11-18 06:49:07 +00001658 if (consume("?"))
Rui Ueyama708019c2016-07-24 18:19:40 +00001659 return readTernary(Lhs);
Rui Ueyama46247b82016-11-18 06:49:07 +00001660 StringRef Op1 = peek();
Rui Ueyama708019c2016-07-24 18:19:40 +00001661 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +00001662 break;
Justin Bogner5424e7c2016-10-17 06:21:13 +00001663 skip();
Rui Ueyama708019c2016-07-24 18:19:40 +00001664 Expr Rhs = readPrimary();
1665
1666 // Evaluate the remaining part of the expression first if the
1667 // next operator has greater precedence than the previous one.
1668 // For example, if we have read "+" and "3", and if the next
1669 // operator is "*", then we'll evaluate 3 * ... part first.
1670 while (!atEOF()) {
1671 StringRef Op2 = peek();
1672 if (precedence(Op2) <= precedence(Op1))
1673 break;
1674 Rhs = readExpr1(Rhs, precedence(Op2));
1675 }
1676
1677 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +00001678 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001679 return Lhs;
1680}
1681
1682uint64_t static getConstant(StringRef S) {
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001683 if (S == "COMMONPAGESIZE")
Rui Ueyama708019c2016-07-24 18:19:40 +00001684 return Target->PageSize;
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001685 if (S == "MAXPAGESIZE")
Petr Hosek997f8832016-09-28 15:20:47 +00001686 return Config->MaxPageSize;
Rui Ueyama708019c2016-07-24 18:19:40 +00001687 error("unknown constant: " + S);
1688 return 0;
1689}
1690
Rui Ueyama626e0b02016-09-02 18:19:00 +00001691// Parses Tok as an integer. Returns true if successful.
1692// It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1693// and decimal numbers. Decimal numbers may have "K" (kilo) or
1694// "M" (mega) prefixes.
George Rimar9f2f7ad2016-09-02 16:01:42 +00001695static bool readInteger(StringRef Tok, uint64_t &Result) {
Rui Ueyama46247b82016-11-18 06:49:07 +00001696 // Negative number
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001697 if (Tok.startswith("-")) {
1698 if (!readInteger(Tok.substr(1), Result))
1699 return false;
1700 Result = -Result;
1701 return true;
1702 }
Rui Ueyama46247b82016-11-18 06:49:07 +00001703
1704 // Hexadecimal
George Rimar9f2f7ad2016-09-02 16:01:42 +00001705 if (Tok.startswith_lower("0x"))
1706 return !Tok.substr(2).getAsInteger(16, Result);
1707 if (Tok.endswith_lower("H"))
1708 return !Tok.drop_back().getAsInteger(16, Result);
1709
Rui Ueyama46247b82016-11-18 06:49:07 +00001710 // Decimal
George Rimar9f2f7ad2016-09-02 16:01:42 +00001711 int Suffix = 1;
1712 if (Tok.endswith_lower("K")) {
1713 Suffix = 1024;
1714 Tok = Tok.drop_back();
1715 } else if (Tok.endswith_lower("M")) {
1716 Suffix = 1024 * 1024;
1717 Tok = Tok.drop_back();
1718 }
1719 if (Tok.getAsInteger(10, Result))
1720 return false;
1721 Result *= Suffix;
1722 return true;
1723}
1724
George Rimare38cbab2016-09-26 19:22:50 +00001725BytesDataCommand *ScriptParser::readBytesDataCommand(StringRef Tok) {
1726 int Size = StringSwitch<unsigned>(Tok)
1727 .Case("BYTE", 1)
1728 .Case("SHORT", 2)
1729 .Case("LONG", 4)
1730 .Case("QUAD", 8)
1731 .Default(-1);
1732 if (Size == -1)
1733 return nullptr;
1734
Meador Inge95c7d8d2016-12-08 23:21:30 +00001735 return new BytesDataCommand(readParenExpr(), Size);
George Rimare38cbab2016-09-26 19:22:50 +00001736}
1737
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001738StringRef ScriptParser::readParenLiteral() {
1739 expect("(");
1740 StringRef Tok = next();
1741 expect(")");
1742 return Tok;
1743}
1744
Rui Ueyama708019c2016-07-24 18:19:40 +00001745Expr ScriptParser::readPrimary() {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001746 if (peek() == "(")
1747 return readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001748
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001749 StringRef Tok = next();
Rui Ueyamab5f1c3e2016-12-01 04:36:49 +00001750 std::string Location = getCurrentLocation();
Rui Ueyama708019c2016-07-24 18:19:40 +00001751
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001752 if (Tok == "~") {
1753 Expr E = readPrimary();
Rafael Espindola4595df92017-03-10 16:04:26 +00001754 return [=] { return ~E(); };
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001755 }
1756 if (Tok == "-") {
1757 Expr E = readPrimary();
Rafael Espindola4595df92017-03-10 16:04:26 +00001758 return [=] { return -E(); };
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001759 }
1760
Rui Ueyama708019c2016-07-24 18:19:40 +00001761 // Built-in functions are parsed here.
1762 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
George Rimar96659df2016-08-30 09:54:01 +00001763 if (Tok == "ADDR") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001764 StringRef Name = readParenLiteral();
Rafael Espindola4595df92017-03-10 16:04:26 +00001765 return {[=] { return ScriptBase->getOutputSection(Location, Name)->Addr; },
Eugene Levianted30ce72016-11-28 09:58:04 +00001766 [=] { return false; },
1767 [=] { return ScriptBase->getOutputSection(Location, Name); }};
George Rimar96659df2016-08-30 09:54:01 +00001768 }
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001769 if (Tok == "LOADADDR") {
1770 StringRef Name = readParenLiteral();
Rafael Espindola4595df92017-03-10 16:04:26 +00001771 return
1772 [=] { return ScriptBase->getOutputSection(Location, Name)->getLMA(); };
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001773 }
George Rimareefa7582016-08-04 09:29:31 +00001774 if (Tok == "ASSERT")
1775 return readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001776 if (Tok == "ALIGN") {
Rui Ueyama5d804dc2016-12-16 18:19:35 +00001777 expect("(");
1778 Expr E = readExpr();
1779 if (consume(",")) {
1780 Expr E2 = readExpr();
1781 expect(")");
Rafael Espindola4595df92017-03-10 16:04:26 +00001782 return [=] { return alignTo(E(), E2()); };
Rui Ueyama5d804dc2016-12-16 18:19:35 +00001783 }
1784 expect(")");
Rafael Espindola4595df92017-03-10 16:04:26 +00001785 return [=] { return alignTo(ScriptBase->getDot(), E()); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001786 }
1787 if (Tok == "CONSTANT") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001788 StringRef Name = readParenLiteral();
Rafael Espindola4595df92017-03-10 16:04:26 +00001789 return [=] { return getConstant(Name); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001790 }
George Rimarf34f45f2016-09-23 13:17:23 +00001791 if (Tok == "DEFINED") {
Rui Ueyama0ee25a62016-11-17 03:52:14 +00001792 StringRef Name = readParenLiteral();
Rafael Espindola4595df92017-03-10 16:04:26 +00001793 return [=] { return ScriptBase->isDefined(Name) ? 1 : 0; };
George Rimarf34f45f2016-09-23 13:17:23 +00001794 }
Rafael Espindola54c145c2016-07-28 18:16:24 +00001795 if (Tok == "SEGMENT_START") {
1796 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001797 skip();
Rafael Espindola54c145c2016-07-28 18:16:24 +00001798 expect(",");
George Rimar8c658bf2016-09-17 18:14:56 +00001799 Expr E = readExpr();
Rafael Espindola54c145c2016-07-28 18:16:24 +00001800 expect(")");
Rafael Espindola4595df92017-03-10 16:04:26 +00001801 return [=] { return E(); };
Rafael Espindola54c145c2016-07-28 18:16:24 +00001802 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001803 if (Tok == "DATA_SEGMENT_ALIGN") {
1804 expect("(");
1805 Expr E = readExpr();
1806 expect(",");
1807 readExpr();
1808 expect(")");
Rafael Espindola4595df92017-03-10 16:04:26 +00001809 return [=] { return alignTo(ScriptBase->getDot(), E()); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001810 }
1811 if (Tok == "DATA_SEGMENT_END") {
1812 expect("(");
1813 expect(".");
1814 expect(")");
Rafael Espindola4595df92017-03-10 16:04:26 +00001815 return []() { return ScriptBase->getDot(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001816 }
George Rimar276b4e62016-07-26 17:58:44 +00001817 // GNU linkers implements more complicated logic to handle
1818 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1819 // the next page boundary for simplicity.
1820 if (Tok == "DATA_SEGMENT_RELRO_END") {
1821 expect("(");
Rafael Espindola97bdc722016-09-14 19:14:01 +00001822 readExpr();
George Rimar276b4e62016-07-26 17:58:44 +00001823 expect(",");
1824 readExpr();
1825 expect(")");
Rafael Espindola4595df92017-03-10 16:04:26 +00001826 return []() { return alignTo(ScriptBase->getDot(), Target->PageSize); };
George Rimar276b4e62016-07-26 17:58:44 +00001827 }
George Rimar9e694502016-07-29 16:18:47 +00001828 if (Tok == "SIZEOF") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001829 StringRef Name = readParenLiteral();
Rafael Espindola4595df92017-03-10 16:04:26 +00001830 return [=] { return ScriptBase->getOutputSectionSize(Name); };
George Rimar9e694502016-07-29 16:18:47 +00001831 }
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001832 if (Tok == "ALIGNOF") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001833 StringRef Name = readParenLiteral();
Rafael Espindola4595df92017-03-10 16:04:26 +00001834 return
1835 [=] { return ScriptBase->getOutputSection(Location, Name)->Alignment; };
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001836 }
George Rimare32a3592016-08-10 07:59:34 +00001837 if (Tok == "SIZEOF_HEADERS")
Rafael Espindola4595df92017-03-10 16:04:26 +00001838 return [=] { return ScriptBase->getHeaderSize(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001839
George Rimar9f2f7ad2016-09-02 16:01:42 +00001840 // Tok is a literal number.
1841 uint64_t V;
1842 if (readInteger(Tok, V))
Rafael Espindola4595df92017-03-10 16:04:26 +00001843 return [=] { return V; };
George Rimar9f2f7ad2016-09-02 16:01:42 +00001844
1845 // Tok is a symbol name.
1846 if (Tok != "." && !isValidCIdentifier(Tok))
1847 setError("malformed number: " + Tok);
Rafael Espindola4595df92017-03-10 16:04:26 +00001848 return {[=] { return ScriptBase->getSymbolValue(Location, Tok); },
1849 [=] { return ScriptBase->isAbsolute(Tok); },
Rui Ueyama009d1742016-11-18 06:49:09 +00001850 [=] { return ScriptBase->getSymbolSection(Tok); }};
Rui Ueyama708019c2016-07-24 18:19:40 +00001851}
1852
1853Expr ScriptParser::readTernary(Expr Cond) {
Rui Ueyama708019c2016-07-24 18:19:40 +00001854 Expr L = readExpr();
1855 expect(":");
1856 Expr R = readExpr();
Rafael Espindola4595df92017-03-10 16:04:26 +00001857 return [=] { return Cond() ? L() : R(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001858}
1859
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001860Expr ScriptParser::readParenExpr() {
1861 expect("(");
1862 Expr E = readExpr();
1863 expect(")");
1864 return E;
1865}
1866
Eugene Leviantbbe38602016-07-19 09:25:43 +00001867std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1868 std::vector<StringRef> Phdrs;
1869 while (!Error && peek().startswith(":")) {
1870 StringRef Tok = next();
George Rimarda841c12016-11-14 10:03:54 +00001871 Phdrs.push_back((Tok.size() == 1) ? next() : Tok.substr(1));
Eugene Leviantbbe38602016-07-19 09:25:43 +00001872 }
1873 return Phdrs;
1874}
1875
George Rimar95dd7182016-10-18 10:49:50 +00001876// Read a program header type name. The next token must be a
1877// name of a program header type or a constant (e.g. "0x3").
Eugene Leviantbbe38602016-07-19 09:25:43 +00001878unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001879 StringRef Tok = next();
George Rimar95dd7182016-10-18 10:49:50 +00001880 uint64_t Val;
1881 if (readInteger(Tok, Val))
1882 return Val;
1883
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001884 unsigned Ret = StringSwitch<unsigned>(Tok)
George Rimar6c55f0e2016-09-08 08:20:30 +00001885 .Case("PT_NULL", PT_NULL)
1886 .Case("PT_LOAD", PT_LOAD)
1887 .Case("PT_DYNAMIC", PT_DYNAMIC)
1888 .Case("PT_INTERP", PT_INTERP)
1889 .Case("PT_NOTE", PT_NOTE)
1890 .Case("PT_SHLIB", PT_SHLIB)
1891 .Case("PT_PHDR", PT_PHDR)
1892 .Case("PT_TLS", PT_TLS)
1893 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1894 .Case("PT_GNU_STACK", PT_GNU_STACK)
1895 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
George Rimar270173f2016-10-14 13:02:22 +00001896 .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
George Rimarcc6e5672016-10-14 10:34:36 +00001897 .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
George Rimara2a32c22016-12-06 17:57:42 +00001898 .Case("PT_OPENBSD_BOOTDATA", PT_OPENBSD_BOOTDATA)
George Rimar6c55f0e2016-09-08 08:20:30 +00001899 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001900
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001901 if (Ret == (unsigned)-1) {
1902 setError("invalid program header type: " + Tok);
1903 return PT_NULL;
1904 }
1905 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001906}
1907
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001908// Reads an anonymous version declaration.
Rui Ueyama12450b22016-11-18 06:30:09 +00001909void ScriptParser::readAnonymousDeclaration() {
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001910 std::vector<SymbolVersion> Locals;
1911 std::vector<SymbolVersion> Globals;
1912 std::tie(Locals, Globals) = readSymbols();
1913
1914 for (SymbolVersion V : Locals) {
1915 if (V.Name == "*")
1916 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1917 else
1918 Config->VersionScriptLocals.push_back(V);
Rafael Espindola45242682017-02-03 13:24:01 +00001919 }
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001920
1921 for (SymbolVersion V : Globals)
1922 Config->VersionScriptGlobals.push_back(V);
1923
Rui Ueyama12450b22016-11-18 06:30:09 +00001924 expect(";");
1925}
1926
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001927// Reads a non-anonymous version definition,
1928// e.g. "VerStr { global: foo; bar; local: *; };".
Rui Ueyama95769b42016-08-31 20:03:54 +00001929void ScriptParser::readVersionDeclaration(StringRef VerStr) {
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001930 // Read a symbol list.
1931 std::vector<SymbolVersion> Locals;
1932 std::vector<SymbolVersion> Globals;
1933 std::tie(Locals, Globals) = readSymbols();
George Rimar20b65982016-08-31 09:08:26 +00001934
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001935 for (SymbolVersion V : Locals) {
1936 if (V.Name == "*")
1937 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1938 else
1939 Config->VersionScriptLocals.push_back(V);
Rafael Espindola45242682017-02-03 13:24:01 +00001940 }
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001941
1942 // Create a new version definition and add that to the global symbols.
1943 VersionDefinition Ver;
1944 Ver.Name = VerStr;
1945 Ver.Globals = Globals;
1946
1947 // User-defined version number starts from 2 because 0 and 1 are
1948 // reserved for VER_NDX_LOCAL and VER_NDX_GLOBAL, respectively.
1949 Ver.Id = Config->VersionDefinitions.size() + 2;
1950 Config->VersionDefinitions.push_back(Ver);
George Rimar20b65982016-08-31 09:08:26 +00001951
Rui Ueyama12450b22016-11-18 06:30:09 +00001952 // Each version may have a parent version. For example, "Ver2"
1953 // defined as "Ver2 { global: foo; local: *; } Ver1;" has "Ver1"
1954 // as a parent. This version hierarchy is, probably against your
1955 // instinct, purely for hint; the runtime doesn't care about it
1956 // at all. In LLD, we simply ignore it.
1957 if (peek() != ";")
Justin Bogner5424e7c2016-10-17 06:21:13 +00001958 skip();
George Rimar20b65982016-08-31 09:08:26 +00001959 expect(";");
1960}
1961
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001962// Reads a list of symbols, e.g. "{ global: foo; bar; local: *; };".
1963std::pair<std::vector<SymbolVersion>, std::vector<SymbolVersion>>
1964ScriptParser::readSymbols() {
1965 std::vector<SymbolVersion> Locals;
1966 std::vector<SymbolVersion> Globals;
1967 std::vector<SymbolVersion> *V = &Globals;
1968
1969 while (!Error) {
1970 if (consume("}"))
1971 break;
1972 if (consumeLabel("local")) {
1973 V = &Locals;
1974 continue;
1975 }
1976 if (consumeLabel("global")) {
1977 V = &Globals;
Rafael Espindola1ef90d22016-12-09 16:44:05 +00001978 continue;
1979 }
George Rimare0fc2422016-11-16 17:59:10 +00001980
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001981 if (consume("extern")) {
1982 std::vector<SymbolVersion> Ext = readVersionExtern();
1983 V->insert(V->end(), Ext.begin(), Ext.end());
1984 } else {
1985 StringRef Tok = next();
1986 V->push_back({unquote(Tok), false, hasWildcard(Tok)});
1987 }
George Rimare0fc2422016-11-16 17:59:10 +00001988 expect(";");
1989 }
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001990 return {Locals, Globals};
George Rimare0fc2422016-11-16 17:59:10 +00001991}
1992
Rui Ueyama12450b22016-11-18 06:30:09 +00001993// Reads an "extern C++" directive, e.g.,
1994// "extern "C++" { ns::*; "f(int, double)"; };"
1995std::vector<SymbolVersion> ScriptParser::readVersionExtern() {
Rafael Espindola7e714152016-12-08 17:26:53 +00001996 StringRef Tok = next();
1997 bool IsCXX = Tok == "\"C++\"";
1998 if (!IsCXX && Tok != "\"C\"")
Rafael Espindolad0ebd842016-12-08 17:54:26 +00001999 setError("Unknown language");
George Rimar20b65982016-08-31 09:08:26 +00002000 expect("{");
2001
Rui Ueyama12450b22016-11-18 06:30:09 +00002002 std::vector<SymbolVersion> Ret;
Rui Ueyama0ee25a62016-11-17 03:52:14 +00002003 while (!Error && peek() != "}") {
2004 StringRef Tok = next();
2005 bool HasWildcard = !Tok.startswith("\"") && hasWildcard(Tok);
Rafael Espindola7e714152016-12-08 17:26:53 +00002006 Ret.push_back({unquote(Tok), IsCXX, HasWildcard});
George Rimar20b65982016-08-31 09:08:26 +00002007 expect(";");
2008 }
2009
2010 expect("}");
Rui Ueyama12450b22016-11-18 06:30:09 +00002011 return Ret;
George Rimar20b65982016-08-31 09:08:26 +00002012}
2013
Rui Ueyama24e626c2017-01-26 02:58:19 +00002014uint64_t ScriptParser::readMemoryAssignment(
2015 StringRef S1, StringRef S2, StringRef S3) {
2016 if (!(consume(S1) || consume(S2) || consume(S3))) {
2017 setError("expected one of: " + S1 + ", " + S2 + ", or " + S3);
2018 return 0;
2019 }
2020 expect("=");
2021
2022 // TODO: Fully support constant expressions.
2023 uint64_t Val;
2024 if (!readInteger(next(), Val))
2025 setError("nonconstant expression for "+ S1);
2026 return Val;
2027}
2028
2029// Parse the MEMORY command as specified in:
2030// https://sourceware.org/binutils/docs/ld/MEMORY.html
2031//
2032// MEMORY { name [(attr)] : ORIGIN = origin, LENGTH = len ... }
Meador Ingeb8897442017-01-24 02:34:00 +00002033void ScriptParser::readMemory() {
2034 expect("{");
2035 while (!Error && !consume("}")) {
2036 StringRef Name = next();
Rui Ueyama24e626c2017-01-26 02:58:19 +00002037
Meador Ingeb8897442017-01-24 02:34:00 +00002038 uint32_t Flags = 0;
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002039 uint32_t NegFlags = 0;
Meador Ingeb8897442017-01-24 02:34:00 +00002040 if (consume("(")) {
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002041 std::tie(Flags, NegFlags) = readMemoryAttributes();
Meador Ingeb8897442017-01-24 02:34:00 +00002042 expect(")");
2043 }
2044 expect(":");
2045
Rui Ueyama24e626c2017-01-26 02:58:19 +00002046 uint64_t Origin = readMemoryAssignment("ORIGIN", "org", "o");
Meador Ingeb8897442017-01-24 02:34:00 +00002047 expect(",");
Rui Ueyama24e626c2017-01-26 02:58:19 +00002048 uint64_t Length = readMemoryAssignment("LENGTH", "len", "l");
Meador Ingeb8897442017-01-24 02:34:00 +00002049
Meador Ingeb8897442017-01-24 02:34:00 +00002050 // Add the memory region to the region map (if it doesn't already exist).
2051 auto It = Opt.MemoryRegions.find(Name);
2052 if (It != Opt.MemoryRegions.end())
2053 setError("region '" + Name + "' already defined");
2054 else
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002055 Opt.MemoryRegions[Name] = {Name, Origin, Length, Origin, Flags, NegFlags};
Meador Ingeb8897442017-01-24 02:34:00 +00002056 }
2057}
2058
2059// This function parses the attributes used to match against section
2060// flags when placing output sections in a memory region. These flags
2061// are only used when an explicit memory region name is not used.
2062std::pair<uint32_t, uint32_t> ScriptParser::readMemoryAttributes() {
2063 uint32_t Flags = 0;
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002064 uint32_t NegFlags = 0;
Meador Ingeb8897442017-01-24 02:34:00 +00002065 bool Invert = false;
Rui Ueyama481ac992017-01-26 02:58:39 +00002066
2067 for (char C : next().lower()) {
Meador Ingeb8897442017-01-24 02:34:00 +00002068 uint32_t Flag = 0;
2069 if (C == '!')
2070 Invert = !Invert;
Rui Ueyama481ac992017-01-26 02:58:39 +00002071 else if (C == 'w')
Meador Ingeb8897442017-01-24 02:34:00 +00002072 Flag = SHF_WRITE;
Rui Ueyama481ac992017-01-26 02:58:39 +00002073 else if (C == 'x')
Meador Ingeb8897442017-01-24 02:34:00 +00002074 Flag = SHF_EXECINSTR;
Rui Ueyama481ac992017-01-26 02:58:39 +00002075 else if (C == 'a')
Meador Ingeb8897442017-01-24 02:34:00 +00002076 Flag = SHF_ALLOC;
Rui Ueyama481ac992017-01-26 02:58:39 +00002077 else if (C != 'r')
Meador Ingeb8897442017-01-24 02:34:00 +00002078 setError("invalid memory region attribute");
Rui Ueyama481ac992017-01-26 02:58:39 +00002079
Meador Ingeb8897442017-01-24 02:34:00 +00002080 if (Invert)
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002081 NegFlags |= Flag;
Meador Ingeb8897442017-01-24 02:34:00 +00002082 else
2083 Flags |= Flag;
2084 }
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002085 return {Flags, NegFlags};
Meador Ingeb8897442017-01-24 02:34:00 +00002086}
2087
Rui Ueyama07320e42016-04-20 20:13:41 +00002088void elf::readLinkerScript(MemoryBufferRef MB) {
Rui Ueyama22375f22016-11-25 18:51:54 +00002089 ScriptParser(MB).readLinkerScript();
George Rimar20b65982016-08-31 09:08:26 +00002090}
2091
2092void elf::readVersionScript(MemoryBufferRef MB) {
Rui Ueyama22375f22016-11-25 18:51:54 +00002093 ScriptParser(MB).readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00002094}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00002095
Rafael Espindolad0ebd842016-12-08 17:54:26 +00002096void elf::readDynamicList(MemoryBufferRef MB) {
2097 ScriptParser(MB).readDynamicList();
2098}
2099
Rui Ueyama07320e42016-04-20 20:13:41 +00002100template class elf::LinkerScript<ELF32LE>;
2101template class elf::LinkerScript<ELF32BE>;
2102template class elf::LinkerScript<ELF64LE>;
2103template class elf::LinkerScript<ELF64BE>;