blob: db7bb03568b1f1064b55f8a81532fb95074d7452 [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) {
Rafael Espindola3dabfc62016-10-31 13:14:53 +000060 uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
Meador Inge8f1f3c42017-01-09 18:36:57 +000061 Symbol *Sym = Symtab<ELFT>::X->addUndefined(
62 Cmd->Name, /*IsLocal=*/false, STB_GLOBAL, Visibility,
63 /*Type*/ 0,
64 /*CanOmitFromDynSym*/ false, /*File*/ nullptr);
Eugene Leviant20d03192016-09-16 15:30:47 +000065
Meador Inge8f1f3c42017-01-09 18:36:57 +000066 replaceBody<DefinedRegular<ELFT>>(Sym, Cmd->Name, /*IsLocal=*/false,
67 Visibility, STT_NOTYPE, 0, 0, nullptr,
68 nullptr);
69 return Sym->body();
Eugene Leviantceabe802016-08-11 07:56:43 +000070}
71
Meador Inge8f1f3c42017-01-09 18:36:57 +000072template <class ELFT> static SymbolBody *addSynthetic(SymbolAssignment *Cmd) {
73 uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
Eugene Leviantafaa9342016-11-16 09:49:39 +000074 const OutputSectionBase *Sec =
75 ScriptConfig->HasSections ? nullptr : Cmd->Expression.Section();
Meador Inge8f1f3c42017-01-09 18:36:57 +000076 Symbol *Sym = Symtab<ELFT>::X->addUndefined(
77 Cmd->Name, /*IsLocal=*/false, STB_GLOBAL, Visibility,
78 /*Type*/ 0,
79 /*CanOmitFromDynSym*/ false, /*File*/ nullptr);
Eugene Leviantafaa9342016-11-16 09:49:39 +000080
Meador Inge8f1f3c42017-01-09 18:36:57 +000081 replaceBody<DefinedSynthetic>(Sym, Cmd->Name, 0, Sec);
82 return Sym->body();
Eugene Leviantceabe802016-08-11 07:56:43 +000083}
84
Rui Ueyama22375f22016-11-25 18:51:54 +000085static bool isUnderSysroot(StringRef Path) {
86 if (Config->Sysroot == "")
87 return false;
88 for (; !Path.empty(); Path = sys::path::parent_path(Path))
89 if (sys::fs::equivalent(Config->Sysroot, Path))
90 return true;
91 return false;
92}
93
George Rimar2ee2d2d2017-02-21 14:50:38 +000094template <class ELFT>
95void LinkerScript<ELFT>::setDot(Expr E, const Twine &Loc, bool InSec) {
Rafael Espindola679828f2017-02-17 16:26:13 +000096 uintX_t Val = E(Dot);
97 if (Val < Dot) {
98 if (InSec)
George Rimar2ee2d2d2017-02-21 14:50:38 +000099 error(Loc + ": unable to move location counter backward for: " +
100 CurOutSec->Name);
Rafael Espindola679828f2017-02-17 16:26:13 +0000101 else
George Rimar2ee2d2d2017-02-21 14:50:38 +0000102 error(Loc + ": unable to move location counter backward");
Rafael Espindola679828f2017-02-17 16:26:13 +0000103 }
104 Dot = Val;
105 // Update to location counter means update to section size.
106 if (InSec)
107 CurOutSec->Size = Dot - CurOutSec->Addr;
108}
109
George Rimarb2b70972017-02-07 10:23:28 +0000110// Sets value of a symbol. Two kinds of symbols are processed: synthetic
111// symbols, whose value is an offset from beginning of section and regular
112// symbols whose value is absolute.
113template <class ELFT>
Rafael Espindola4cd73522017-02-17 16:01:51 +0000114void LinkerScript<ELFT>::assignSymbol(SymbolAssignment *Cmd, bool InSec) {
115 if (Cmd->Name == ".") {
George Rimar2ee2d2d2017-02-21 14:50:38 +0000116 setDot(Cmd->Expression, Cmd->Location, InSec);
Rafael Espindola4cd73522017-02-17 16:01:51 +0000117 return;
118 }
119
George Rimarb2b70972017-02-07 10:23:28 +0000120 if (!Cmd->Sym)
Meador Inge8f1f3c42017-01-09 18:36:57 +0000121 return;
122
George Rimarb2b70972017-02-07 10:23:28 +0000123 if (auto *Body = dyn_cast<DefinedSynthetic>(Cmd->Sym)) {
124 Body->Section = Cmd->Expression.Section();
Rafael Espindolaea590d92017-02-08 15:19:03 +0000125 if (Body->Section) {
126 uint64_t VA = 0;
127 if (Body->Section->Flags & SHF_ALLOC)
128 VA = Body->Section->Addr;
129 Body->Value = Cmd->Expression(Dot) - VA;
130 }
George Rimarb2b70972017-02-07 10:23:28 +0000131 return;
Meador Inge8f1f3c42017-01-09 18:36:57 +0000132 }
George Rimarb2b70972017-02-07 10:23:28 +0000133
134 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(Dot);
Eugene Leviantdb741e72016-09-07 07:08:43 +0000135}
Meador Inge8f1f3c42017-01-09 18:36:57 +0000136
Rafael Espindola4cd73522017-02-17 16:01:51 +0000137template <class ELFT>
138void LinkerScript<ELFT>::addSymbol(SymbolAssignment *Cmd) {
Rui Ueyama16024212016-08-11 23:22:52 +0000139 if (Cmd->Name == ".")
Meador Inge8f1f3c42017-01-09 18:36:57 +0000140 return;
141
142 // If a symbol was in PROVIDE(), we need to define it only when
143 // it is a referenced undefined symbol.
Rui Ueyama16024212016-08-11 23:22:52 +0000144 SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
Meador Inge8f1f3c42017-01-09 18:36:57 +0000145 if (Cmd->Provide && (!B || B->isDefined()))
146 return;
147
148 // Otherwise, create a new symbol if one does not exist or an
149 // undefined one does exist.
150 if (Cmd->Expression.IsAbsolute())
151 Cmd->Sym = addRegular<ELFT>(Cmd);
152 else
153 Cmd->Sym = addSynthetic<ELFT>(Cmd);
George Rimarb2b70972017-02-07 10:23:28 +0000154
155 // If there are sections, then let the value be assigned later in
156 // `assignAddresses`.
157 if (!ScriptConfig->HasSections)
Rafael Espindola4cd73522017-02-17 16:01:51 +0000158 assignSymbol(Cmd);
Eugene Leviantceabe802016-08-11 07:56:43 +0000159}
160
George Rimar076fe152016-07-21 06:43:01 +0000161bool SymbolAssignment::classof(const BaseCommand *C) {
162 return C->Kind == AssignmentKind;
163}
164
165bool OutputSectionCommand::classof(const BaseCommand *C) {
166 return C->Kind == OutputSectionKind;
167}
168
George Rimareea31142016-07-21 14:26:59 +0000169bool InputSectionDescription::classof(const BaseCommand *C) {
170 return C->Kind == InputSectionKind;
171}
172
George Rimareefa7582016-08-04 09:29:31 +0000173bool AssertCommand::classof(const BaseCommand *C) {
174 return C->Kind == AssertKind;
175}
176
George Rimare38cbab2016-09-26 19:22:50 +0000177bool BytesDataCommand::classof(const BaseCommand *C) {
178 return C->Kind == BytesDataKind;
179}
180
Eugene Zelenko22886a22016-11-05 01:00:56 +0000181template <class ELFT> LinkerScript<ELFT>::LinkerScript() = default;
182template <class ELFT> LinkerScript<ELFT>::~LinkerScript() = default;
Rui Ueyamaf34d0e02016-08-12 01:24:53 +0000183
Rui Ueyamae0be2902016-11-21 02:10:12 +0000184template <class ELFT> static StringRef basename(InputSectionBase<ELFT> *S) {
185 if (S->getFile())
186 return sys::path::filename(S->getFile()->getName());
187 return "";
188}
189
Rui Ueyama07320e42016-04-20 20:13:41 +0000190template <class ELFT>
191bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) {
Rui Ueyamae0be2902016-11-21 02:10:12 +0000192 for (InputSectionDescription *ID : Opt.KeptSections)
193 if (ID->FilePat.match(basename(S)))
194 for (SectionPattern &P : ID->SectionPatterns)
195 if (P.SectionPat.match(S->Name))
196 return true;
George Rimareea31142016-07-21 14:26:59 +0000197 return false;
198}
199
George Rimar575208c2016-09-15 19:15:12 +0000200static bool comparePriority(InputSectionData *A, InputSectionData *B) {
201 return getPriority(A->Name) < getPriority(B->Name);
202}
203
Rafael Espindolac0028d32016-09-08 20:47:52 +0000204static bool compareName(InputSectionData *A, InputSectionData *B) {
Rafael Espindola042a3f22016-09-08 14:06:08 +0000205 return A->Name < B->Name;
Rui Ueyama742c3832016-08-04 22:27:00 +0000206}
George Rimar350ece42016-08-03 08:35:59 +0000207
Rafael Espindolac0028d32016-09-08 20:47:52 +0000208static bool compareAlignment(InputSectionData *A, InputSectionData *B) {
Rui Ueyama742c3832016-08-04 22:27:00 +0000209 // ">" is not a mistake. Larger alignments are placed before smaller
210 // alignments in order to reduce the amount of padding necessary.
211 // This is compatible with GNU.
212 return A->Alignment > B->Alignment;
213}
George Rimar350ece42016-08-03 08:35:59 +0000214
Rafael Espindolac0028d32016-09-08 20:47:52 +0000215static std::function<bool(InputSectionData *, InputSectionData *)>
George Rimarbe394db2016-09-16 20:21:55 +0000216getComparator(SortSectionPolicy K) {
217 switch (K) {
218 case SortSectionPolicy::Alignment:
219 return compareAlignment;
220 case SortSectionPolicy::Name:
Rafael Espindolac0028d32016-09-08 20:47:52 +0000221 return compareName;
George Rimarbe394db2016-09-16 20:21:55 +0000222 case SortSectionPolicy::Priority:
223 return comparePriority;
224 default:
225 llvm_unreachable("unknown sort policy");
226 }
Rui Ueyama742c3832016-08-04 22:27:00 +0000227}
George Rimar0702c4e2016-07-29 15:32:46 +0000228
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000229template <class ELFT>
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000230static bool matchConstraints(ArrayRef<InputSectionBase<ELFT> *> Sections,
George Rimar06ae6832016-08-12 09:07:57 +0000231 ConstraintKind Kind) {
George Rimar8f66df92016-08-12 20:38:20 +0000232 if (Kind == ConstraintKind::NoConstraint)
233 return true;
Rafael Espindolae746e522016-09-21 18:33:44 +0000234 bool IsRW = llvm::any_of(Sections, [=](InputSectionData *Sec2) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000235 auto *Sec = static_cast<InputSectionBase<ELFT> *>(Sec2);
Rafael Espindola1854a8e2016-10-26 12:36:56 +0000236 return Sec->Flags & SHF_WRITE;
George Rimar06ae6832016-08-12 09:07:57 +0000237 });
Rafael Espindolae746e522016-09-21 18:33:44 +0000238 return (IsRW && Kind == ConstraintKind::ReadWrite) ||
239 (!IsRW && Kind == ConstraintKind::ReadOnly);
George Rimar06ae6832016-08-12 09:07:57 +0000240}
241
George Rimar07171f22016-09-21 15:56:44 +0000242static void sortSections(InputSectionData **Begin, InputSectionData **End,
Rui Ueyamaee924702016-09-20 19:42:41 +0000243 SortSectionPolicy K) {
244 if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
George Rimar07171f22016-09-21 15:56:44 +0000245 std::stable_sort(Begin, End, getComparator(K));
Rui Ueyamaee924702016-09-20 19:42:41 +0000246}
247
Rafael Espindolad3190792016-09-16 15:10:23 +0000248// Compute and remember which sections the InputSectionDescription matches.
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000249template <class ELFT>
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000250void LinkerScript<ELFT>::computeInputSections(InputSectionDescription *I) {
Rui Ueyama4dc07be2016-09-17 02:23:40 +0000251 // Collects all sections that satisfy constraints of I
252 // and attach them to I.
253 for (SectionPattern &Pat : I->SectionPatterns) {
George Rimar07171f22016-09-21 15:56:44 +0000254 size_t SizeBefore = I->Sections.size();
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000255
256 for (InputSectionBase<ELFT> *S : Symtab<ELFT>::X->Sections) {
Rafael Espindola3773bca2017-02-17 19:37:30 +0000257 if (S->Assigned)
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000258 continue;
Rafael Espindola908a3d32017-02-16 14:36:09 +0000259 // For -emit-relocs we have to ignore entries like
260 // .rela.dyn : { *(.rela.data) }
261 // which are common because they are in the default bfd script.
262 if (S->Type == SHT_REL || S->Type == SHT_RELA)
263 continue;
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000264
Rui Ueyamae0be2902016-11-21 02:10:12 +0000265 StringRef Filename = basename(S);
266 if (!I->FilePat.match(Filename) || Pat.ExcludedFilePat.match(Filename))
267 continue;
268 if (!Pat.SectionPat.match(S->Name))
269 continue;
270 I->Sections.push_back(S);
271 S->Assigned = true;
George Rimar395281c2016-09-16 17:42:10 +0000272 }
Rafael Espindolad3190792016-09-16 15:10:23 +0000273
George Rimar07171f22016-09-21 15:56:44 +0000274 // Sort sections as instructed by SORT-family commands and --sort-section
275 // option. Because SORT-family commands can be nested at most two depth
276 // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
277 // line option is respected even if a SORT command is given, the exact
278 // behavior we have here is a bit complicated. Here are the rules.
279 //
280 // 1. If two SORT commands are given, --sort-section is ignored.
281 // 2. If one SORT command is given, and if it is not SORT_NONE,
282 // --sort-section is handled as an inner SORT command.
283 // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
284 // 4. If no SORT command is given, sort according to --sort-section.
285 InputSectionData **Begin = I->Sections.data() + SizeBefore;
286 InputSectionData **End = I->Sections.data() + I->Sections.size();
287 if (Pat.SortOuter != SortSectionPolicy::None) {
288 if (Pat.SortInner == SortSectionPolicy::Default)
289 sortSections(Begin, End, Config->SortSection);
290 else
291 sortSections(Begin, End, Pat.SortInner);
292 sortSections(Begin, End, Pat.SortOuter);
293 }
Rui Ueyamaee924702016-09-20 19:42:41 +0000294 }
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000295}
296
297template <class ELFT>
298void LinkerScript<ELFT>::discard(ArrayRef<InputSectionBase<ELFT> *> V) {
299 for (InputSectionBase<ELFT> *S : V) {
300 S->Live = false;
Rafael Espindolaecbfd872017-02-17 17:35:07 +0000301 if (S == In<ELFT>::ShStrTab)
302 error("discarding .shstrtab section is not allowed");
George Rimar647c1682017-02-17 19:34:05 +0000303 discard(S->DependentSections);
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000304 }
305}
306
George Rimar06ae6832016-08-12 09:07:57 +0000307template <class ELFT>
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000308std::vector<InputSectionBase<ELFT> *>
George Rimar06ae6832016-08-12 09:07:57 +0000309LinkerScript<ELFT>::createInputSectionList(OutputSectionCommand &OutCmd) {
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000310 std::vector<InputSectionBase<ELFT> *> Ret;
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000311
George Rimar06ae6832016-08-12 09:07:57 +0000312 for (const std::unique_ptr<BaseCommand> &Base : OutCmd.Commands) {
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000313 auto *Cmd = dyn_cast<InputSectionDescription>(Base.get());
314 if (!Cmd)
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000315 continue;
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000316 computeInputSections(Cmd);
Rafael Espindolad3190792016-09-16 15:10:23 +0000317 for (InputSectionData *S : Cmd->Sections)
318 Ret.push_back(static_cast<InputSectionBase<ELFT> *>(S));
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000319 }
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000320
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000321 return Ret;
322}
323
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000324template <class ELFT>
Eugene Leviant20d03192016-09-16 15:30:47 +0000325void LinkerScript<ELFT>::processCommands(OutputSectionFactory<ELFT> &Factory) {
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000326 for (unsigned I = 0; I < Opt.Commands.size(); ++I) {
327 auto Iter = Opt.Commands.begin() + I;
328 const std::unique_ptr<BaseCommand> &Base1 = *Iter;
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000329
330 // Handle symbol assignments outside of any output section.
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000331 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base1.get())) {
Rafael Espindola4cd73522017-02-17 16:01:51 +0000332 addSymbol(Cmd);
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000333 continue;
334 }
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000335
Eugene Leviant20d03192016-09-16 15:30:47 +0000336 if (auto *Cmd = dyn_cast<AssertCommand>(Base1.get())) {
337 // If we don't have SECTIONS then output sections have already been
George Rimar194470cd2016-09-17 19:21:05 +0000338 // created by Writer<ELFT>. The LinkerScript<ELFT>::assignAddresses
Eugene Leviant20d03192016-09-16 15:30:47 +0000339 // will not be called, so ASSERT should be evaluated now.
340 if (!Opt.HasSections)
341 Cmd->Expression(0);
342 continue;
343 }
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000344
Eugene Leviantceabe802016-08-11 07:56:43 +0000345 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000346 std::vector<InputSectionBase<ELFT> *> V = createInputSectionList(*Cmd);
347
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000348 // The output section name `/DISCARD/' is special.
349 // Any input section assigned to it is discarded.
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000350 if (Cmd->Name == "/DISCARD/") {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000351 discard(V);
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000352 continue;
353 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000354
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000355 // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive
356 // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input
357 // sections satisfy a given constraint. If not, a directive is handled
358 // as if it wasn't present from the beginning.
359 //
360 // Because we'll iterate over Commands many more times, the easiest
361 // way to "make it as if it wasn't present" is to just remove it.
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000362 if (!matchConstraints<ELFT>(V, Cmd->Constraint)) {
363 for (InputSectionBase<ELFT> *S : V)
Rui Ueyamaf94efdd2016-11-20 23:15:52 +0000364 S->Assigned = false;
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000365 Opt.Commands.erase(Iter);
George Rimardfbbbc82016-09-17 09:50:10 +0000366 --I;
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000367 continue;
368 }
369
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000370 // A directive may contain symbol definitions like this:
371 // ".foo : { ...; bar = .; }". Handle them.
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000372 for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
373 if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base.get()))
Rafael Espindola4cd73522017-02-17 16:01:51 +0000374 addSymbol(OutCmd);
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000375
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000376 // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign
377 // is given, input sections are aligned to that value, whether the
378 // given value is larger or smaller than the original section alignment.
379 if (Cmd->SubalignExpr) {
380 uint32_t Subalign = Cmd->SubalignExpr(0);
381 for (InputSectionBase<ELFT> *S : V)
382 S->Alignment = Subalign;
George Rimardb24d9c2016-08-19 15:18:23 +0000383 }
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000384
385 // Add input sections to an output section.
386 for (InputSectionBase<ELFT> *S : V)
Rafael Espindola82902742017-02-16 17:32:26 +0000387 Factory.addInputSec(S, Cmd->Name);
Eugene Leviantceabe802016-08-11 07:56:43 +0000388 }
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000389 }
Eugene Leviant20d03192016-09-16 15:30:47 +0000390}
Eugene Leviante63d81b2016-07-20 14:43:20 +0000391
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000392// Add sections that didn't match any sections command.
Eugene Leviant20d03192016-09-16 15:30:47 +0000393template <class ELFT>
George Rimar93c64022016-12-15 15:38:09 +0000394void LinkerScript<ELFT>::addOrphanSections(
395 OutputSectionFactory<ELFT> &Factory) {
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000396 for (InputSectionBase<ELFT> *S : Symtab<ELFT>::X->Sections)
Rafael Espindola8f9026b2016-11-08 18:23:02 +0000397 if (S->Live && !S->OutSec)
Rafael Espindola82902742017-02-16 17:32:26 +0000398 Factory.addInputSec(S, getOutputSectionName(S->Name));
Eugene Leviante63d81b2016-07-20 14:43:20 +0000399}
400
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000401template <class ELFT> static bool isTbss(OutputSectionBase *Sec) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000402 return (Sec->Flags & SHF_TLS) && Sec->Type == SHT_NOBITS;
Rafael Espindolaa940e532016-09-22 12:35:44 +0000403}
404
Rafael Espindolad3190792016-09-16 15:10:23 +0000405template <class ELFT> void LinkerScript<ELFT>::output(InputSection<ELFT> *S) {
406 if (!AlreadyOutputIS.insert(S).second)
407 return;
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000408 bool IsTbss = isTbss<ELFT>(CurOutSec);
Eugene Leviant20889c52016-08-31 08:13:33 +0000409
Rafael Espindolad3190792016-09-16 15:10:23 +0000410 uintX_t Pos = IsTbss ? Dot + ThreadBssOffset : Dot;
411 Pos = alignTo(Pos, S->Alignment);
Rafael Espindola04a2e342016-11-09 01:42:41 +0000412 S->OutSecOff = Pos - CurOutSec->Addr;
Rafael Espindolad3190792016-09-16 15:10:23 +0000413 Pos += S->getSize();
414
415 // Update output section size after adding each section. This is so that
416 // SIZEOF works correctly in the case below:
417 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
Rafael Espindola04a2e342016-11-09 01:42:41 +0000418 CurOutSec->Size = Pos - CurOutSec->Addr;
Rafael Espindolad3190792016-09-16 15:10:23 +0000419
Meador Ingeb8897442017-01-24 02:34:00 +0000420 // If there is a memory region associated with this input section, then
421 // place the section in that region and update the region index.
422 if (CurMemRegion) {
423 CurMemRegion->Offset += CurOutSec->Size;
424 uint64_t CurSize = CurMemRegion->Offset - CurMemRegion->Origin;
425 if (CurSize > CurMemRegion->Length) {
426 uint64_t OverflowAmt = CurSize - CurMemRegion->Length;
427 error("section '" + CurOutSec->Name + "' will not fit in region '" +
428 CurMemRegion->Name + "': overflowed by " + Twine(OverflowAmt) +
429 " bytes");
430 }
431 }
432
Rafael Espindola7252ae52016-09-22 12:00:08 +0000433 if (IsTbss)
434 ThreadBssOffset = Pos - Dot;
435 else
Rafael Espindolad3190792016-09-16 15:10:23 +0000436 Dot = Pos;
437}
438
439template <class ELFT> void LinkerScript<ELFT>::flush() {
Rafael Espindola65499b92016-09-23 20:10:47 +0000440 if (!CurOutSec || !AlreadyOutputOS.insert(CurOutSec).second)
441 return;
442 if (auto *OutSec = dyn_cast<OutputSection<ELFT>>(CurOutSec)) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000443 for (InputSection<ELFT> *I : OutSec->Sections)
444 output(I);
Rafael Espindola65499b92016-09-23 20:10:47 +0000445 } else {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000446 Dot += CurOutSec->Size;
Eugene Leviant20889c52016-08-31 08:13:33 +0000447 }
448}
449
450template <class ELFT>
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000451void LinkerScript<ELFT>::switchTo(OutputSectionBase *Sec) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000452 if (CurOutSec == Sec)
453 return;
454 if (AlreadyOutputOS.count(Sec))
455 return;
456
457 flush();
458 CurOutSec = Sec;
459
Rafael Espindola04a2e342016-11-09 01:42:41 +0000460 Dot = alignTo(Dot, CurOutSec->Addralign);
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000461 CurOutSec->Addr = isTbss<ELFT>(CurOutSec) ? Dot + ThreadBssOffset : Dot;
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000462
463 // If neither AT nor AT> is specified for an allocatable section, the linker
464 // will set the LMA such that the difference between VMA and LMA for the
465 // section is the same as the preceding output section in the same region
466 // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
George Rimarae4761c2017-02-21 15:08:18 +0000467 Expr LMAExpr = CurLMA.first;
468 if (LMAExpr)
469 CurOutSec->setLMAOffset(LMAExpr(CurLMA.second) - CurLMA.second);
Rafael Espindolad3190792016-09-16 15:10:23 +0000470}
471
472template <class ELFT> void LinkerScript<ELFT>::process(BaseCommand &Base) {
George Rimare38cbab2016-09-26 19:22:50 +0000473 // This handles the assignments to symbol or to a location counter (.)
Rafael Espindolad3190792016-09-16 15:10:23 +0000474 if (auto *AssignCmd = dyn_cast<SymbolAssignment>(&Base)) {
Rafael Espindola4cd73522017-02-17 16:01:51 +0000475 assignSymbol(AssignCmd, true);
Eugene Leviantceabe802016-08-11 07:56:43 +0000476 return;
Rui Ueyama2de509c2016-08-12 00:55:08 +0000477 }
George Rimare38cbab2016-09-26 19:22:50 +0000478
479 // Handle BYTE(), SHORT(), LONG(), or QUAD().
480 if (auto *DataCmd = dyn_cast<BytesDataCommand>(&Base)) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000481 DataCmd->Offset = Dot - CurOutSec->Addr;
George Rimare38cbab2016-09-26 19:22:50 +0000482 Dot += DataCmd->Size;
Rafael Espindola04a2e342016-11-09 01:42:41 +0000483 CurOutSec->Size = Dot - CurOutSec->Addr;
George Rimare38cbab2016-09-26 19:22:50 +0000484 return;
485 }
486
Meador Ingeb2d99d62016-11-22 18:01:50 +0000487 if (auto *AssertCmd = dyn_cast<AssertCommand>(&Base)) {
488 AssertCmd->Expression(Dot);
489 return;
490 }
491
George Rimare38cbab2016-09-26 19:22:50 +0000492 // It handles single input section description command,
493 // calculates and assigns the offsets for each section and also
494 // updates the output section size.
Rafael Espindolad3190792016-09-16 15:10:23 +0000495 auto &ICmd = cast<InputSectionDescription>(Base);
496 for (InputSectionData *ID : ICmd.Sections) {
George Rimar3fb5a6d2016-11-29 16:05:27 +0000497 // We tentatively added all synthetic sections at the beginning and removed
498 // empty ones afterwards (because there is no way to know whether they were
499 // going be empty or not other than actually running linker scripts.)
500 // We need to ignore remains of empty sections.
501 if (auto *Sec = dyn_cast<SyntheticSection<ELFT>>(ID))
502 if (Sec->empty())
503 continue;
504
Rafael Espindolad3190792016-09-16 15:10:23 +0000505 auto *IB = static_cast<InputSectionBase<ELFT> *>(ID);
506 switchTo(IB->OutSec);
507 if (auto *I = dyn_cast<InputSection<ELFT>>(IB))
508 output(I);
Rafael Espindola65499b92016-09-23 20:10:47 +0000509 else
510 flush();
Eugene Leviantceabe802016-08-11 07:56:43 +0000511 }
512}
513
George Rimar8f66df92016-08-12 20:38:20 +0000514template <class ELFT>
Rafael Espindola2b074552017-02-03 22:27:05 +0000515static OutputSectionBase *
516findSection(StringRef Name, const std::vector<OutputSectionBase *> &Sections) {
517 auto End = Sections.end();
518 auto HasName = [=](OutputSectionBase *Sec) { return Sec->getName() == Name; };
519 auto I = std::find_if(Sections.begin(), End, HasName);
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000520 std::vector<OutputSectionBase *> Ret;
Rafael Espindola2b074552017-02-03 22:27:05 +0000521 if (I == End)
522 return nullptr;
523 assert(std::find_if(I + 1, End, HasName) == End);
524 return *I;
George Rimar8f66df92016-08-12 20:38:20 +0000525}
526
Meador Ingeb8897442017-01-24 02:34:00 +0000527// This function searches for a memory region to place the given output
528// section in. If found, a pointer to the appropriate memory region is
529// returned. Otherwise, a nullptr is returned.
530template <class ELFT>
531MemoryRegion *LinkerScript<ELFT>::findMemoryRegion(OutputSectionCommand *Cmd,
532 OutputSectionBase *Sec) {
533 // If a memory region name was specified in the output section command,
534 // then try to find that region first.
535 if (!Cmd->MemoryRegionName.empty()) {
536 auto It = Opt.MemoryRegions.find(Cmd->MemoryRegionName);
537 if (It != Opt.MemoryRegions.end())
538 return &It->second;
539 error("memory region '" + Cmd->MemoryRegionName + "' not declared");
540 return nullptr;
541 }
542
543 // The memory region name is empty, thus a suitable region must be
544 // searched for in the region map. If the region map is empty, just
545 // return. Note that this check doesn't happen at the very beginning
546 // so that uses of undeclared regions can be caught.
547 if (!Opt.MemoryRegions.size())
548 return nullptr;
549
550 // See if a region can be found by matching section flags.
551 for (auto &MRI : Opt.MemoryRegions) {
552 MemoryRegion &MR = MRI.second;
Rui Ueyama8a8a9532017-01-26 02:58:59 +0000553 if ((MR.Flags & Sec->Flags) != 0 && (MR.NegFlags & Sec->Flags) == 0)
Meador Ingeb8897442017-01-24 02:34:00 +0000554 return &MR;
555 }
556
557 // Otherwise, no suitable region was found.
558 if (Sec->Flags & SHF_ALLOC)
559 error("no memory region specified for section '" + Sec->Name + "'");
560 return nullptr;
561}
562
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000563// This function assigns offsets to input sections and an output section
564// for a single sections command (e.g. ".text { *(.text); }").
Rafael Espindolad3190792016-09-16 15:10:23 +0000565template <class ELFT>
566void LinkerScript<ELFT>::assignOffsets(OutputSectionCommand *Cmd) {
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000567 if (Cmd->LMAExpr)
George Rimarae4761c2017-02-21 15:08:18 +0000568 CurLMA = {Cmd->LMAExpr, Dot};
Rafael Espindola2b074552017-02-03 22:27:05 +0000569 OutputSectionBase *Sec = findSection<ELFT>(Cmd->Name, *OutputSections);
570 if (!Sec)
Rafael Espindolad3190792016-09-16 15:10:23 +0000571 return;
Meador Ingeb8897442017-01-24 02:34:00 +0000572
Rafael Espindola679828f2017-02-17 16:26:13 +0000573 if (Cmd->AddrExpr && Sec->Flags & SHF_ALLOC)
George Rimar2ee2d2d2017-02-21 14:50:38 +0000574 setDot(Cmd->AddrExpr, Cmd->Location);
Rafael Espindola679828f2017-02-17 16:26:13 +0000575
Petr Hosek165088a2017-02-07 23:42:31 +0000576 // Handle align (e.g. ".foo : ALIGN(16) { ... }").
577 if (Cmd->AlignExpr)
578 Sec->updateAlignment(Cmd->AlignExpr(0));
579
Meador Ingeb8897442017-01-24 02:34:00 +0000580 // Try and find an appropriate memory region to assign offsets in.
581 CurMemRegion = findMemoryRegion(Cmd, Sec);
582 if (CurMemRegion)
583 Dot = CurMemRegion->Offset;
584 switchTo(Sec);
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000585
Rafael Espindolad3190792016-09-16 15:10:23 +0000586 // Find the last section output location. We will output orphan sections
587 // there so that end symbols point to the correct location.
588 auto E = std::find_if(Cmd->Commands.rbegin(), Cmd->Commands.rend(),
589 [](const std::unique_ptr<BaseCommand> &Cmd) {
590 return !isa<SymbolAssignment>(*Cmd);
591 })
592 .base();
593 for (auto I = Cmd->Commands.begin(); I != E; ++I)
594 process(**I);
Rafael Espindola65499b92016-09-23 20:10:47 +0000595 flush();
George Rimarb31dd372016-09-19 13:27:31 +0000596 std::for_each(E, Cmd->Commands.end(),
597 [this](std::unique_ptr<BaseCommand> &B) { process(*B.get()); });
Rafael Espindolad3190792016-09-16 15:10:23 +0000598}
599
Rafael Espindola07fe6122016-11-14 14:23:35 +0000600template <class ELFT> void LinkerScript<ELFT>::removeEmptyCommands() {
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000601 // It is common practice to use very generic linker scripts. So for any
602 // given run some of the output sections in the script will be empty.
603 // We could create corresponding empty output sections, but that would
604 // clutter the output.
605 // We instead remove trivially empty sections. The bfd linker seems even
606 // more aggressive at removing them.
607 auto Pos = std::remove_if(
608 Opt.Commands.begin(), Opt.Commands.end(),
609 [&](const std::unique_ptr<BaseCommand> &Base) {
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000610 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
Rafael Espindola2b074552017-02-03 22:27:05 +0000611 return !findSection<ELFT>(Cmd->Name, *OutputSections);
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000612 return false;
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000613 });
614 Opt.Commands.erase(Pos, Opt.Commands.end());
Rafael Espindola07fe6122016-11-14 14:23:35 +0000615}
616
Rafael Espindola6a537372016-11-14 14:33:49 +0000617static bool isAllSectionDescription(const OutputSectionCommand &Cmd) {
618 for (const std::unique_ptr<BaseCommand> &I : Cmd.Commands)
619 if (!isa<InputSectionDescription>(*I))
620 return false;
621 return true;
622}
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000623
Rafael Espindola6a537372016-11-14 14:33:49 +0000624template <class ELFT> void LinkerScript<ELFT>::adjustSectionsBeforeSorting() {
Rafael Espindola9546fff2016-09-22 14:40:50 +0000625 // If the output section contains only symbol assignments, create a
626 // corresponding output section. The bfd linker seems to only create them if
627 // '.' is assigned to, but creating these section should not have any bad
628 // consequeces and gives us a section to put the symbol in.
629 uintX_t Flags = SHF_ALLOC;
Rafael Espindolaf93b8c22016-11-26 06:55:35 +0000630 uint32_t Type = SHT_NOBITS;
Rafael Espindola9546fff2016-09-22 14:40:50 +0000631 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
632 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
633 if (!Cmd)
634 continue;
Rafael Espindola2b074552017-02-03 22:27:05 +0000635 if (OutputSectionBase *Sec =
636 findSection<ELFT>(Cmd->Name, *OutputSections)) {
637 Flags = Sec->Flags;
638 Type = Sec->Type;
Rafael Espindola9546fff2016-09-22 14:40:50 +0000639 continue;
640 }
641
Rafael Espindola6a537372016-11-14 14:33:49 +0000642 if (isAllSectionDescription(*Cmd))
643 continue;
644
Rui Ueyama95642b92016-11-01 23:09:07 +0000645 auto *OutSec = make<OutputSection<ELFT>>(Cmd->Name, Type, Flags);
Rafael Espindola9546fff2016-09-22 14:40:50 +0000646 OutputSections->push_back(OutSec);
647 }
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000648}
649
650template <class ELFT> void LinkerScript<ELFT>::adjustSectionsAfterSorting() {
651 placeOrphanSections();
652
653 // If output section command doesn't specify any segments,
654 // and we haven't previously assigned any section to segment,
655 // then we simply assign section to the very first load segment.
656 // Below is an example of such linker script:
657 // PHDRS { seg PT_LOAD; }
658 // SECTIONS { .aaa : { *(.aaa) } }
659 std::vector<StringRef> DefPhdrs;
660 auto FirstPtLoad =
661 std::find_if(Opt.PhdrsCommands.begin(), Opt.PhdrsCommands.end(),
662 [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; });
663 if (FirstPtLoad != Opt.PhdrsCommands.end())
664 DefPhdrs.push_back(FirstPtLoad->Name);
665
666 // Walk the commands and propagate the program headers to commands that don't
667 // explicitly specify them.
668 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
669 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
670 if (!Cmd)
671 continue;
672 if (Cmd->Phdrs.empty())
673 Cmd->Phdrs = DefPhdrs;
674 else
675 DefPhdrs = Cmd->Phdrs;
676 }
Rafael Espindola6a537372016-11-14 14:33:49 +0000677
678 removeEmptyCommands();
Rafael Espindola9546fff2016-09-22 14:40:50 +0000679}
680
Rafael Espindola15c57952016-09-22 18:05:49 +0000681// When placing orphan sections, we want to place them after symbol assignments
682// so that an orphan after
683// begin_foo = .;
684// foo : { *(foo) }
685// end_foo = .;
686// doesn't break the intended meaning of the begin/end symbols.
687// We don't want to go over sections since Writer<ELFT>::sortSections is the
688// one in charge of deciding the order of the sections.
689// We don't want to go over alignments, since doing so in
690// rx_sec : { *(rx_sec) }
691// . = ALIGN(0x1000);
692// /* The RW PT_LOAD starts here*/
693// rw_sec : { *(rw_sec) }
694// would mean that the RW PT_LOAD would become unaligned.
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000695static bool shouldSkip(const BaseCommand &Cmd) {
Rafael Espindola15c57952016-09-22 18:05:49 +0000696 if (isa<OutputSectionCommand>(Cmd))
697 return false;
698 const auto *Assign = dyn_cast<SymbolAssignment>(&Cmd);
699 if (!Assign)
700 return true;
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000701 return Assign->Name != ".";
Rafael Espindola15c57952016-09-22 18:05:49 +0000702}
703
Rui Ueyama6697ec22017-02-02 23:26:12 +0000704// Orphan sections are sections present in the input files which are
705// not explicitly placed into the output file by the linker script.
706//
707// When the control reaches this function, Opt.Commands contains
708// output section commands for non-orphan sections only. This function
709// adds new elements for orphan sections to Opt.Commands so that all
710// sections are explicitly handled by Opt.Commands.
711//
712// Writer<ELFT>::sortSections has already sorted output sections.
713// What we need to do is to scan OutputSections vector and
714// Opt.Commands in parallel to find orphan sections. If there is an
715// output section that doesn't have a corresponding entry in
716// Opt.Commands, we will insert a new entry to Opt.Commands.
717//
718// There is some ambiguity as to where exactly a new entry should be
719// inserted, because Opt.Commands contains not only output section
720// commands but other types of commands such as symbol assignment
721// expressions. There's no correct answer here due to the lack of the
722// formal specification of the linker script. We use heuristics to
723// determine whether a new output command should be added before or
724// after another commands. For the details, look at shouldSkip
725// function.
George Rimar93c64022016-12-15 15:38:09 +0000726template <class ELFT> void LinkerScript<ELFT>::placeOrphanSections() {
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000727 // The OutputSections are already in the correct order.
728 // This loops creates or moves commands as needed so that they are in the
729 // correct order.
730 int CmdIndex = 0;
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000731
732 // As a horrible special case, skip the first . assignment if it is before any
733 // section. We do this because it is common to set a load address by starting
734 // the script with ". = 0xabcd" and the expectation is that every section is
735 // after that.
736 auto FirstSectionOrDotAssignment =
737 std::find_if(Opt.Commands.begin(), Opt.Commands.end(),
738 [](const std::unique_ptr<BaseCommand> &Cmd) {
739 if (isa<OutputSectionCommand>(*Cmd))
740 return true;
741 const auto *Assign = dyn_cast<SymbolAssignment>(Cmd.get());
742 if (!Assign)
743 return false;
744 return Assign->Name == ".";
745 });
746 if (FirstSectionOrDotAssignment != Opt.Commands.end()) {
747 CmdIndex = FirstSectionOrDotAssignment - Opt.Commands.begin();
748 if (isa<SymbolAssignment>(**FirstSectionOrDotAssignment))
749 ++CmdIndex;
750 }
751
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000752 for (OutputSectionBase *Sec : *OutputSections) {
George Rimar652852c2016-04-16 10:10:32 +0000753 StringRef Name = Sec->getName();
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000754
755 // Find the last spot where we can insert a command and still get the
Rafael Espindola15c57952016-09-22 18:05:49 +0000756 // correct result.
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000757 auto CmdIter = Opt.Commands.begin() + CmdIndex;
758 auto E = Opt.Commands.end();
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000759 while (CmdIter != E && shouldSkip(**CmdIter)) {
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000760 ++CmdIter;
761 ++CmdIndex;
762 }
763
764 auto Pos =
765 std::find_if(CmdIter, E, [&](const std::unique_ptr<BaseCommand> &Base) {
766 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
767 return Cmd && Cmd->Name == Name;
768 });
769 if (Pos == E) {
770 Opt.Commands.insert(CmdIter,
771 llvm::make_unique<OutputSectionCommand>(Name));
Rafael Espindola15c57952016-09-22 18:05:49 +0000772 ++CmdIndex;
773 continue;
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000774 }
Rafael Espindola15c57952016-09-22 18:05:49 +0000775
776 // Continue from where we found it.
777 CmdIndex = (Pos - Opt.Commands.begin()) + 1;
George Rimar652852c2016-04-16 10:10:32 +0000778 }
Rafael Espindola337f9032016-11-14 14:13:32 +0000779}
780
781template <class ELFT>
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000782void LinkerScript<ELFT>::assignAddresses(std::vector<PhdrEntry> &Phdrs) {
Rui Ueyama7c18c282016-04-18 21:00:40 +0000783 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rafael Espindolabe607332016-09-30 00:16:11 +0000784 Dot = 0;
George Rimar652852c2016-04-16 10:10:32 +0000785
Rafael Espindola06f47432017-02-06 22:21:46 +0000786 // A symbol can be assigned before any section is mentioned in the linker
787 // script. In an DSO, the symbol values are addresses, so the only important
788 // section values are:
789 // * SHN_UNDEF
790 // * SHN_ABS
791 // * Any value meaning a regular section.
792 // To handle that, create a dummy aether section that fills the void before
793 // the linker scripts switches to another section. It has an index of one
794 // which will map to whatever the first actual section is.
795 auto *Aether = make<OutputSectionBase>("", 0, SHF_ALLOC);
796 Aether->SectionIndex = 1;
797 switchTo(Aether);
798
George Rimar076fe152016-07-21 06:43:01 +0000799 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
800 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
Rafael Espindola4cd73522017-02-17 16:01:51 +0000801 assignSymbol(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000802 continue;
803 }
804
George Rimareefa7582016-08-04 09:29:31 +0000805 if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
806 Cmd->Expression(Dot);
807 continue;
808 }
809
George Rimar076fe152016-07-21 06:43:01 +0000810 auto *Cmd = cast<OutputSectionCommand>(Base.get());
Rafael Espindolad3190792016-09-16 15:10:23 +0000811 assignOffsets(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000812 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000813
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000814 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
Rafael Espindolaea590d92017-02-08 15:19:03 +0000815 for (OutputSectionBase *Sec : *OutputSections) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000816 if (Sec->Flags & SHF_ALLOC)
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000817 MinVA = std::min<uint64_t>(MinVA, Sec->Addr);
Rafael Espindolaea590d92017-02-08 15:19:03 +0000818 else
819 Sec->Addr = 0;
820 }
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000821
Rafael Espindola8c495e22017-01-20 20:41:18 +0000822 allocateHeaders<ELFT>(Phdrs, *OutputSections, MinVA);
George Rimar652852c2016-04-16 10:10:32 +0000823}
824
Rui Ueyama464daad2016-08-22 04:55:20 +0000825// Creates program headers as instructed by PHDRS linker script command.
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000826template <class ELFT> std::vector<PhdrEntry> LinkerScript<ELFT>::createPhdrs() {
827 std::vector<PhdrEntry> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000828
Rui Ueyama464daad2016-08-22 04:55:20 +0000829 // Process PHDRS and FILEHDR keywords because they are not
830 // real output sections and cannot be added in the following loop.
Eugene Leviantbbe38602016-07-19 09:25:43 +0000831 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000832 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000833 PhdrEntry &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000834
835 if (Cmd.HasFilehdr)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000836 Phdr.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000837 if (Cmd.HasPhdrs)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000838 Phdr.add(Out<ELFT>::ProgramHeaders);
Eugene Leviant56b21c82016-09-09 09:46:16 +0000839
840 if (Cmd.LMAExpr) {
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000841 Phdr.p_paddr = Cmd.LMAExpr(0);
Eugene Leviant56b21c82016-09-09 09:46:16 +0000842 Phdr.HasLMA = true;
843 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000844 }
845
Rui Ueyama464daad2016-08-22 04:55:20 +0000846 // Add output sections to program headers.
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000847 for (OutputSectionBase *Sec : *OutputSections) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000848 if (!(Sec->Flags & SHF_ALLOC))
Eugene Leviantbbe38602016-07-19 09:25:43 +0000849 break;
850
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000851 // Assign headers specified by linker script
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000852 for (size_t Id : getPhdrIndices(Sec->getName())) {
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000853 Ret[Id].add(Sec);
854 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000855 Ret[Id].p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000856 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000857 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000858 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000859}
860
Eugene Leviantf9bc3bd2016-08-16 06:40:58 +0000861template <class ELFT> bool LinkerScript<ELFT>::ignoreInterpSection() {
862 // Ignore .interp section in case we have PHDRS specification
863 // and PT_INTERP isn't listed.
864 return !Opt.PhdrsCommands.empty() &&
865 llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
866 return Cmd.Type == PT_INTERP;
867 }) == Opt.PhdrsCommands.end();
868}
869
George Rimar93c64022016-12-15 15:38:09 +0000870template <class ELFT> uint32_t LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000871 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
872 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
873 if (Cmd->Name == Name)
874 return Cmd->Filler;
Rui Ueyama16068ae2016-11-19 18:05:56 +0000875 return 0;
George Rimare2ee72b2016-02-26 14:48:31 +0000876}
877
George Rimare38cbab2016-09-26 19:22:50 +0000878template <class ELFT>
879static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) {
880 const endianness E = ELFT::TargetEndianness;
881
882 switch (Size) {
883 case 1:
884 *Buf = (uint8_t)Data;
885 break;
886 case 2:
887 write16<E>(Buf, Data);
888 break;
889 case 4:
890 write32<E>(Buf, Data);
891 break;
892 case 8:
893 write64<E>(Buf, Data);
894 break;
895 default:
896 llvm_unreachable("unsupported Size argument");
897 }
898}
899
900template <class ELFT>
901void LinkerScript<ELFT>::writeDataBytes(StringRef Name, uint8_t *Buf) {
902 int I = getSectionIndex(Name);
903 if (I == INT_MAX)
904 return;
905
Rui Ueyama6e68c5e2016-11-19 18:05:58 +0000906 auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I].get());
907 for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
908 if (auto *Data = dyn_cast<BytesDataCommand>(Base.get()))
Meador Inge95c7d8d2016-12-08 23:21:30 +0000909 writeInt<ELFT>(Buf + Data->Offset, Data->Expression(0), Data->Size);
George Rimare38cbab2016-09-26 19:22:50 +0000910}
911
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000912template <class ELFT> bool LinkerScript<ELFT>::hasLMA(StringRef Name) {
George Rimar8ceadb32016-08-17 07:44:19 +0000913 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
914 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000915 if (Cmd->LMAExpr && Cmd->Name == Name)
916 return true;
917 return false;
George Rimar8ceadb32016-08-17 07:44:19 +0000918}
919
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000920// Returns the index of the given section name in linker script
921// SECTIONS commands. Sections are laid out as the same order as they
922// were in the script. If a given name did not appear in the script,
923// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000924template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
Rui Ueyama6e68c5e2016-11-19 18:05:58 +0000925 for (int I = 0, E = Opt.Commands.size(); I != E; ++I)
926 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I].get()))
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000927 if (Cmd->Name == Name)
928 return I;
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000929 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000930}
931
Eugene Leviantbbe38602016-07-19 09:25:43 +0000932template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
933 return !Opt.PhdrsCommands.empty();
934}
935
George Rimar9e694502016-07-29 16:18:47 +0000936template <class ELFT>
Eugene Levianted30ce72016-11-28 09:58:04 +0000937const OutputSectionBase *LinkerScript<ELFT>::getOutputSection(const Twine &Loc,
938 StringRef Name) {
Eugene Leviantafaa9342016-11-16 09:49:39 +0000939 static OutputSectionBase FakeSec("", 0, 0);
George Rimar96659df2016-08-30 09:54:01 +0000940
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000941 for (OutputSectionBase *Sec : *OutputSections)
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000942 if (Sec->getName() == Name)
Eugene Leviantafaa9342016-11-16 09:49:39 +0000943 return Sec;
Eugene Levianted30ce72016-11-28 09:58:04 +0000944
945 error(Loc + ": undefined section " + Name);
Eugene Leviantafaa9342016-11-16 09:49:39 +0000946 return &FakeSec;
Eugene Leviant36fac7f2016-09-08 09:08:30 +0000947}
948
Rui Ueyamaedf75e72016-11-17 20:27:10 +0000949// This function is essentially the same as getOutputSection(Name)->Size,
950// but it won't print out an error message if a given section is not found.
951//
952// Linker script does not create an output section if its content is empty.
953// We want to allow SIZEOF(.foo) where .foo is a section which happened to
954// be empty. That is why this function is different from getOutputSection().
955template <class ELFT>
956uint64_t LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
957 for (OutputSectionBase *Sec : *OutputSections)
958 if (Sec->getName() == Name)
959 return Sec->Size;
960 return 0;
961}
962
George Rimar884e7862016-09-08 08:19:13 +0000963template <class ELFT> uint64_t LinkerScript<ELFT>::getHeaderSize() {
Rafael Espindola0d4b6d52016-09-22 16:47:21 +0000964 return elf::getHeaderSize<ELFT>();
George Rimare32a3592016-08-10 07:59:34 +0000965}
966
Eugene Leviantf6aeed32016-12-22 13:13:12 +0000967template <class ELFT>
968uint64_t LinkerScript<ELFT>::getSymbolValue(const Twine &Loc, StringRef S) {
George Rimar884e7862016-09-08 08:19:13 +0000969 if (SymbolBody *B = Symtab<ELFT>::X->find(S))
970 return B->getVA<ELFT>();
Eugene Leviantf6aeed32016-12-22 13:13:12 +0000971 error(Loc + ": symbol not found: " + S);
George Rimar884e7862016-09-08 08:19:13 +0000972 return 0;
973}
974
George Rimarf34f45f2016-09-23 13:17:23 +0000975template <class ELFT> bool LinkerScript<ELFT>::isDefined(StringRef S) {
976 return Symtab<ELFT>::X->find(S) != nullptr;
977}
978
Rafael Espindola2f831dc2016-10-31 19:56:37 +0000979template <class ELFT> bool LinkerScript<ELFT>::isAbsolute(StringRef S) {
980 SymbolBody *Sym = Symtab<ELFT>::X->find(S);
981 auto *DR = dyn_cast_or_null<DefinedRegular<ELFT>>(Sym);
982 return DR && !DR->Section;
983}
984
Eugene Leviantafaa9342016-11-16 09:49:39 +0000985// Gets section symbol belongs to. Symbol "." doesn't belong to any
986// specific section but isn't absolute at the same time, so we try
987// to find suitable section for it as well.
988template <class ELFT>
989const OutputSectionBase *LinkerScript<ELFT>::getSymbolSection(StringRef S) {
Rafael Espindola06f47432017-02-06 22:21:46 +0000990 if (SymbolBody *Sym = Symtab<ELFT>::X->find(S))
991 return SymbolTableSection<ELFT>::getOutputSection(Sym);
992 return CurOutSec;
Eugene Leviantafaa9342016-11-16 09:49:39 +0000993}
994
Eugene Leviantbbe38602016-07-19 09:25:43 +0000995// Returns indices of ELF headers containing specific section, identified
996// by Name. Each index is a zero based number of ELF header listed within
997// PHDRS {} script block.
998template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000999std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +00001000 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
1001 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +00001002 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +00001003 continue;
1004
Rui Ueyama29c5a2a2016-07-26 00:27:36 +00001005 std::vector<size_t> Ret;
1006 for (StringRef PhdrName : Cmd->Phdrs)
Eugene Leviant2a942c42016-12-05 16:38:32 +00001007 Ret.push_back(getPhdrIndex(Cmd->Location, PhdrName));
Rui Ueyama29c5a2a2016-07-26 00:27:36 +00001008 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001009 }
George Rimar31d842f2016-07-20 16:43:03 +00001010 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +00001011}
1012
Rui Ueyama29c5a2a2016-07-26 00:27:36 +00001013template <class ELFT>
Eugene Leviant2a942c42016-12-05 16:38:32 +00001014size_t LinkerScript<ELFT>::getPhdrIndex(const Twine &Loc, StringRef PhdrName) {
Rui Ueyama29c5a2a2016-07-26 00:27:36 +00001015 size_t I = 0;
1016 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
1017 if (Cmd.Name == PhdrName)
1018 return I;
1019 ++I;
1020 }
Eugene Leviant2a942c42016-12-05 16:38:32 +00001021 error(Loc + ": section header '" + PhdrName + "' is not listed in PHDRS");
Rui Ueyama29c5a2a2016-07-26 00:27:36 +00001022 return 0;
1023}
1024
Rui Ueyama794366a2017-02-14 04:47:05 +00001025class elf::ScriptParser final : public ScriptLexer {
George Rimarc3794e52016-02-24 09:21:47 +00001026 typedef void (ScriptParser::*Handler)();
1027
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001028public:
Rui Ueyama22375f22016-11-25 18:51:54 +00001029 ScriptParser(MemoryBufferRef MB)
Rui Ueyama794366a2017-02-14 04:47:05 +00001030 : ScriptLexer(MB),
Rui Ueyama22375f22016-11-25 18:51:54 +00001031 IsUnderSysroot(isUnderSysroot(MB.getBufferIdentifier())) {}
George Rimarf23b2322016-02-19 10:45:45 +00001032
George Rimar20b65982016-08-31 09:08:26 +00001033 void readLinkerScript();
1034 void readVersionScript();
Rafael Espindolad0ebd842016-12-08 17:54:26 +00001035 void readDynamicList();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001036
1037private:
Rui Ueyama52a15092015-10-11 03:28:42 +00001038 void addFile(StringRef Path);
1039
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001040 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +00001041 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +00001042 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001043 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001044 void readInclude();
Meador Ingeb8897442017-01-24 02:34:00 +00001045 void readMemory();
Rui Ueyamaee592822015-10-07 00:25:09 +00001046 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +00001047 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001048 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +00001049 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +00001050 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001051 void readSections();
Rui Ueyama95769b42016-08-31 20:03:54 +00001052 void readVersion();
1053 void readVersionScriptCommand();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001054
Rui Ueyama113cdec2016-07-24 23:05:57 +00001055 SymbolAssignment *readAssignment(StringRef Name);
George Rimare38cbab2016-09-26 19:22:50 +00001056 BytesDataCommand *readBytesDataCommand(StringRef Tok);
Rui Ueyama16068ae2016-11-19 18:05:56 +00001057 uint32_t readFill();
Rui Ueyama10416562016-08-04 02:03:27 +00001058 OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
Rui Ueyama16068ae2016-11-19 18:05:56 +00001059 uint32_t readOutputSectionFiller(StringRef Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001060 std::vector<StringRef> readOutputSectionPhdrs();
George Rimara2496cb2016-08-30 09:46:59 +00001061 InputSectionDescription *readInputSectionDescription(StringRef Tok);
Eugene Leviantdb688452016-11-03 10:54:58 +00001062 StringMatcher readFilePatterns();
George Rimar07171f22016-09-21 15:56:44 +00001063 std::vector<SectionPattern> readInputSectionsList();
George Rimara2496cb2016-08-30 09:46:59 +00001064 InputSectionDescription *readInputSectionRules(StringRef FilePattern);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001065 unsigned readPhdrType();
George Rimarbe394db2016-09-16 20:21:55 +00001066 SortSectionPolicy readSortKind();
Petr Hoseka35e39c2016-08-16 01:11:16 +00001067 SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
Rafael Espindolac96da112016-11-01 11:30:45 +00001068 SymbolAssignment *readProvideOrAssignment(StringRef Tok);
George Rimar03fc0102016-07-28 07:18:23 +00001069 void readSort();
George Rimareefa7582016-08-04 09:29:31 +00001070 Expr readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001071
Rui Ueyama24e626c2017-01-26 02:58:19 +00001072 uint64_t readMemoryAssignment(StringRef, StringRef, StringRef);
1073 std::pair<uint32_t, uint32_t> readMemoryAttributes();
1074
Rui Ueyama708019c2016-07-24 18:19:40 +00001075 Expr readExpr();
1076 Expr readExpr1(Expr Lhs, int MinPrec);
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001077 StringRef readParenLiteral();
Rui Ueyama708019c2016-07-24 18:19:40 +00001078 Expr readPrimary();
1079 Expr readTernary(Expr Cond);
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001080 Expr readParenExpr();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001081
George Rimar20b65982016-08-31 09:08:26 +00001082 // For parsing version script.
Rui Ueyama12450b22016-11-18 06:30:09 +00001083 std::vector<SymbolVersion> readVersionExtern();
1084 void readAnonymousDeclaration();
Rui Ueyama95769b42016-08-31 20:03:54 +00001085 void readVersionDeclaration(StringRef VerStr);
Rui Ueyama12450b22016-11-18 06:30:09 +00001086 std::vector<SymbolVersion> readSymbols();
Rafael Espindolae999ddb2017-01-10 16:37:24 +00001087 void readLocals();
George Rimar20b65982016-08-31 09:08:26 +00001088
Rui Ueyama07320e42016-04-20 20:13:41 +00001089 ScriptConfiguration &Opt = *ScriptConfig;
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001090 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001091};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001092
Rafael Espindolad0ebd842016-12-08 17:54:26 +00001093void ScriptParser::readDynamicList() {
1094 expect("{");
1095 readAnonymousDeclaration();
1096 if (!atEOF())
1097 setError("EOF expected, but got " + next());
1098}
1099
George Rimar20b65982016-08-31 09:08:26 +00001100void ScriptParser::readVersionScript() {
Rui Ueyama95769b42016-08-31 20:03:54 +00001101 readVersionScriptCommand();
1102 if (!atEOF())
1103 setError("EOF expected, but got " + next());
1104}
1105
1106void ScriptParser::readVersionScriptCommand() {
Rui Ueyama83043f22016-10-17 16:01:53 +00001107 if (consume("{")) {
Rui Ueyama12450b22016-11-18 06:30:09 +00001108 readAnonymousDeclaration();
George Rimar20b65982016-08-31 09:08:26 +00001109 return;
1110 }
1111
Rui Ueyama95769b42016-08-31 20:03:54 +00001112 while (!atEOF() && !Error && peek() != "}") {
George Rimar20b65982016-08-31 09:08:26 +00001113 StringRef VerStr = next();
1114 if (VerStr == "{") {
Rui Ueyama95769b42016-08-31 20:03:54 +00001115 setError("anonymous version definition is used in "
1116 "combination with other version definitions");
George Rimar20b65982016-08-31 09:08:26 +00001117 return;
1118 }
1119 expect("{");
Rui Ueyama95769b42016-08-31 20:03:54 +00001120 readVersionDeclaration(VerStr);
George Rimar20b65982016-08-31 09:08:26 +00001121 }
1122}
1123
Rui Ueyama95769b42016-08-31 20:03:54 +00001124void ScriptParser::readVersion() {
1125 expect("{");
1126 readVersionScriptCommand();
1127 expect("}");
1128}
1129
George Rimar20b65982016-08-31 09:08:26 +00001130void ScriptParser::readLinkerScript() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001131 while (!atEOF()) {
1132 StringRef Tok = next();
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001133 if (Tok == ";")
1134 continue;
1135
Eugene Leviant20d03192016-09-16 15:30:47 +00001136 if (Tok == "ASSERT") {
1137 Opt.Commands.emplace_back(new AssertCommand(readAssert()));
1138 } else if (Tok == "ENTRY") {
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001139 readEntry();
1140 } else if (Tok == "EXTERN") {
1141 readExtern();
1142 } else if (Tok == "GROUP" || Tok == "INPUT") {
1143 readGroup();
1144 } else if (Tok == "INCLUDE") {
1145 readInclude();
Meador Ingeb8897442017-01-24 02:34:00 +00001146 } else if (Tok == "MEMORY") {
1147 readMemory();
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001148 } else if (Tok == "OUTPUT") {
1149 readOutput();
1150 } else if (Tok == "OUTPUT_ARCH") {
1151 readOutputArch();
1152 } else if (Tok == "OUTPUT_FORMAT") {
1153 readOutputFormat();
1154 } else if (Tok == "PHDRS") {
1155 readPhdrs();
1156 } else if (Tok == "SEARCH_DIR") {
1157 readSearchDir();
1158 } else if (Tok == "SECTIONS") {
1159 readSections();
1160 } else if (Tok == "VERSION") {
1161 readVersion();
Rafael Espindolac96da112016-11-01 11:30:45 +00001162 } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok)) {
Eugene Leviant20d03192016-09-16 15:30:47 +00001163 Opt.Commands.emplace_back(Cmd);
Petr Hoseke5d3ca52016-08-31 15:31:17 +00001164 } else {
George Rimar57610422016-03-11 14:43:02 +00001165 setError("unknown directive: " + Tok);
Petr Hoseke5d3ca52016-08-31 15:31:17 +00001166 }
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001167 }
1168}
1169
Rui Ueyama717677a2016-02-11 21:17:59 +00001170void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001171 if (IsUnderSysroot && S.startswith("/")) {
Justin Bogner5af16872016-10-17 06:08:48 +00001172 SmallString<128> PathData;
1173 StringRef Path = (Config->Sysroot + S).toStringRef(PathData);
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001174 if (sys::fs::exists(Path)) {
Justin Bogner5af16872016-10-17 06:08:48 +00001175 Driver->addFile(Saver.save(Path));
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001176 return;
1177 }
1178 }
1179
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +00001180 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +00001181 Driver->addFile(S);
1182 } else if (S.startswith("=")) {
1183 if (Config->Sysroot.empty())
1184 Driver->addFile(S.substr(1));
1185 else
1186 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
1187 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +00001188 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +00001189 } else if (sys::fs::exists(S)) {
1190 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +00001191 } else {
Rui Ueyama061f9282016-11-19 19:23:58 +00001192 if (Optional<std::string> Path = findFromSearchPaths(S))
1193 Driver->addFile(Saver.save(*Path));
Rui Ueyama025d59b2016-02-02 20:27:59 +00001194 else
Rui Ueyama061f9282016-11-19 19:23:58 +00001195 setError("unable to find " + S);
Rui Ueyama52a15092015-10-11 03:28:42 +00001196 }
1197}
1198
Rui Ueyama717677a2016-02-11 21:17:59 +00001199void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001200 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +00001201 bool Orig = Config->AsNeeded;
1202 Config->AsNeeded = true;
Rui Ueyama83043f22016-10-17 16:01:53 +00001203 while (!Error && !consume(")"))
George Rimarcd574a52016-09-09 14:35:36 +00001204 addFile(unquote(next()));
Rui Ueyama35da9b62015-10-11 20:59:12 +00001205 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001206}
1207
Rui Ueyama717677a2016-02-11 21:17:59 +00001208void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +00001209 // -e <symbol> takes predecence over ENTRY(<symbol>).
1210 expect("(");
1211 StringRef Tok = next();
1212 if (Config->Entry.empty())
1213 Config->Entry = Tok;
1214 expect(")");
1215}
1216
Rui Ueyama717677a2016-02-11 21:17:59 +00001217void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +00001218 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001219 while (!Error && !consume(")"))
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001220 Config->Undefined.push_back(next());
George Rimar83f406c2015-10-19 17:35:12 +00001221}
1222
Rui Ueyama717677a2016-02-11 21:17:59 +00001223void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001224 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001225 while (!Error && !consume(")")) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001226 StringRef Tok = next();
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001227 if (Tok == "AS_NEEDED")
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001228 readAsNeeded();
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001229 else
George Rimarcd574a52016-09-09 14:35:36 +00001230 addFile(unquote(Tok));
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001231 }
1232}
1233
Rui Ueyama717677a2016-02-11 21:17:59 +00001234void ScriptParser::readInclude() {
George Rimard4500652016-12-21 09:42:25 +00001235 StringRef Tok = unquote(next());
Rui Ueyamaec1c75e2017-01-09 01:42:02 +00001236
George Rimard4500652016-12-21 09:42:25 +00001237 // https://sourceware.org/binutils/docs/ld/File-Commands.html:
1238 // The file will be searched for in the current directory, and in any
1239 // directory specified with the -L option.
Rui Ueyamaec1c75e2017-01-09 01:42:02 +00001240 if (sys::fs::exists(Tok)) {
1241 if (Optional<MemoryBufferRef> MB = readFile(Tok))
1242 tokenize(*MB);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001243 return;
1244 }
Rui Ueyamaec1c75e2017-01-09 01:42:02 +00001245 if (Optional<std::string> Path = findFromSearchPaths(Tok)) {
1246 if (Optional<MemoryBufferRef> MB = readFile(*Path))
1247 tokenize(*MB);
1248 return;
1249 }
1250 setError("cannot open " + Tok);
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001251}
1252
Rui Ueyama717677a2016-02-11 21:17:59 +00001253void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +00001254 // -o <file> takes predecence over OUTPUT(<file>).
1255 expect("(");
1256 StringRef Tok = next();
1257 if (Config->OutputFile.empty())
George Rimarcd574a52016-09-09 14:35:36 +00001258 Config->OutputFile = unquote(Tok);
Rui Ueyamaee592822015-10-07 00:25:09 +00001259 expect(")");
1260}
1261
Rui Ueyama717677a2016-02-11 21:17:59 +00001262void ScriptParser::readOutputArch() {
George Rimar4e01c3e2017-02-08 09:59:06 +00001263 // OUTPUT_ARCH is ignored for now.
Davide Italiano9159ce92015-10-12 21:50:08 +00001264 expect("(");
George Rimar4e01c3e2017-02-08 09:59:06 +00001265 while (!Error && !consume(")"))
1266 skip();
Davide Italiano9159ce92015-10-12 21:50:08 +00001267}
1268
Rui Ueyama717677a2016-02-11 21:17:59 +00001269void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001270 // Error checking only for now.
1271 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001272 skip();
Davide Italiano6836c612015-10-12 21:08:41 +00001273 StringRef Tok = next();
1274 if (Tok == ")")
George Rimar6c55f0e2016-09-08 08:20:30 +00001275 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +00001276 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +00001277 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001278 return;
1279 }
Justin Bogner5424e7c2016-10-17 06:21:13 +00001280 skip();
Davide Italiano6836c612015-10-12 21:08:41 +00001281 expect(",");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001282 skip();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001283 expect(")");
1284}
1285
Eugene Leviantbbe38602016-07-19 09:25:43 +00001286void ScriptParser::readPhdrs() {
1287 expect("{");
Rui Ueyama83043f22016-10-17 16:01:53 +00001288 while (!Error && !consume("}")) {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001289 StringRef Tok = next();
Eugene Leviant56b21c82016-09-09 09:46:16 +00001290 Opt.PhdrsCommands.push_back(
1291 {Tok, PT_NULL, false, false, UINT_MAX, nullptr});
Eugene Leviantbbe38602016-07-19 09:25:43 +00001292 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
1293
1294 PhdrCmd.Type = readPhdrType();
1295 do {
1296 Tok = next();
1297 if (Tok == ";")
1298 break;
1299 if (Tok == "FILEHDR")
1300 PhdrCmd.HasFilehdr = true;
1301 else if (Tok == "PHDRS")
1302 PhdrCmd.HasPhdrs = true;
Eugene Leviant56b21c82016-09-09 09:46:16 +00001303 else if (Tok == "AT")
1304 PhdrCmd.LMAExpr = readParenExpr();
Eugene Leviant865bf862016-07-21 10:43:25 +00001305 else if (Tok == "FLAGS") {
1306 expect("(");
Rafael Espindolaeb685cd2016-08-02 22:14:57 +00001307 // Passing 0 for the value of dot is a bit of a hack. It means that
1308 // we accept expressions like ".|1".
1309 PhdrCmd.Flags = readExpr()(0);
Eugene Leviant865bf862016-07-21 10:43:25 +00001310 expect(")");
1311 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +00001312 setError("unexpected header attribute: " + Tok);
1313 } while (!Error);
1314 }
1315}
1316
Rui Ueyama717677a2016-02-11 21:17:59 +00001317void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +00001318 expect("(");
Rui Ueyama86c5fb82016-09-08 23:26:54 +00001319 StringRef Tok = next();
Rui Ueyama6c7ad132016-09-02 19:20:33 +00001320 if (!Config->Nostdlib)
George Rimarcd574a52016-09-09 14:35:36 +00001321 Config->SearchPaths.push_back(unquote(Tok));
Davide Italiano68a39a62015-10-08 17:51:41 +00001322 expect(")");
1323}
1324
Rui Ueyama717677a2016-02-11 21:17:59 +00001325void ScriptParser::readSections() {
Eugene Leviante05336ff2016-09-14 08:32:36 +00001326 Opt.HasSections = true;
George Rimar18a30962016-11-28 10:11:10 +00001327 // -no-rosegment is used to avoid placing read only non-executable sections in
1328 // their own segment. We do the same if SECTIONS command is present in linker
1329 // script. See comment for computeFlags().
1330 Config->SingleRoRx = true;
1331
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001332 expect("{");
Rui Ueyama83043f22016-10-17 16:01:53 +00001333 while (!Error && !consume("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +00001334 StringRef Tok = next();
Rafael Espindolac96da112016-11-01 11:30:45 +00001335 BaseCommand *Cmd = readProvideOrAssignment(Tok);
Eugene Leviantceabe802016-08-11 07:56:43 +00001336 if (!Cmd) {
1337 if (Tok == "ASSERT")
1338 Cmd = new AssertCommand(readAssert());
1339 else
1340 Cmd = readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +00001341 }
Rui Ueyama10416562016-08-04 02:03:27 +00001342 Opt.Commands.emplace_back(Cmd);
George Rimar652852c2016-04-16 10:10:32 +00001343 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001344}
1345
Rui Ueyama708019c2016-07-24 18:19:40 +00001346static int precedence(StringRef Op) {
1347 return StringSwitch<int>(Op)
Rui Ueyama0120e3f2016-09-23 18:06:51 +00001348 .Cases("*", "/", 5)
1349 .Cases("+", "-", 4)
1350 .Cases("<<", ">>", 3)
Rui Ueyama9c4ac5f2016-09-23 22:22:34 +00001351 .Cases("<", "<=", ">", ">=", "==", "!=", 2)
Rui Ueyama0120e3f2016-09-23 18:06:51 +00001352 .Cases("&", "|", 1)
Rui Ueyama708019c2016-07-24 18:19:40 +00001353 .Default(-1);
1354}
1355
Eugene Leviantdb688452016-11-03 10:54:58 +00001356StringMatcher ScriptParser::readFilePatterns() {
Rui Ueyama10416562016-08-04 02:03:27 +00001357 std::vector<StringRef> V;
Rui Ueyama83043f22016-10-17 16:01:53 +00001358 while (!Error && !consume(")"))
Rui Ueyama10416562016-08-04 02:03:27 +00001359 V.push_back(next());
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001360 return StringMatcher(V);
George Rimar0702c4e2016-07-29 15:32:46 +00001361}
1362
George Rimarbe394db2016-09-16 20:21:55 +00001363SortSectionPolicy ScriptParser::readSortKind() {
Rui Ueyama83043f22016-10-17 16:01:53 +00001364 if (consume("SORT") || consume("SORT_BY_NAME"))
George Rimarbe394db2016-09-16 20:21:55 +00001365 return SortSectionPolicy::Name;
Rui Ueyama83043f22016-10-17 16:01:53 +00001366 if (consume("SORT_BY_ALIGNMENT"))
George Rimarbe394db2016-09-16 20:21:55 +00001367 return SortSectionPolicy::Alignment;
Rui Ueyama83043f22016-10-17 16:01:53 +00001368 if (consume("SORT_BY_INIT_PRIORITY"))
George Rimarbe394db2016-09-16 20:21:55 +00001369 return SortSectionPolicy::Priority;
Rui Ueyama83043f22016-10-17 16:01:53 +00001370 if (consume("SORT_NONE"))
Rui Ueyamab2a0abd2016-09-16 21:14:55 +00001371 return SortSectionPolicy::None;
1372 return SortSectionPolicy::Default;
George Rimarbe394db2016-09-16 20:21:55 +00001373}
1374
George Rimar395281c2016-09-16 17:42:10 +00001375// Method reads a list of sequence of excluded files and section globs given in
1376// a following form: ((EXCLUDE_FILE(file_pattern+))? section_pattern+)+
1377// Example: *(.foo.1 EXCLUDE_FILE (*a.o) .foo.2 EXCLUDE_FILE (*b.o) .foo.3)
George Rimaraf03be12016-09-17 19:17:25 +00001378// The semantics of that is next:
1379// * Include .foo.1 from every file.
1380// * Include .foo.2 from every file but a.o
1381// * Include .foo.3 from every file but b.o
George Rimar07171f22016-09-21 15:56:44 +00001382std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
1383 std::vector<SectionPattern> Ret;
George Rimar601e9892016-09-21 08:53:21 +00001384 while (!Error && peek() != ")") {
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001385 StringMatcher ExcludeFilePat;
Rui Ueyama83043f22016-10-17 16:01:53 +00001386 if (consume("EXCLUDE_FILE")) {
George Rimar395281c2016-09-16 17:42:10 +00001387 expect("(");
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001388 ExcludeFilePat = readFilePatterns();
George Rimar395281c2016-09-16 17:42:10 +00001389 }
1390
George Rimar601e9892016-09-21 08:53:21 +00001391 std::vector<StringRef> V;
1392 while (!Error && peek() != ")" && peek() != "EXCLUDE_FILE")
1393 V.push_back(next());
1394
1395 if (!V.empty())
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001396 Ret.push_back({std::move(ExcludeFilePat), StringMatcher(V)});
George Rimar601e9892016-09-21 08:53:21 +00001397 else
1398 setError("section pattern is expected");
George Rimar395281c2016-09-16 17:42:10 +00001399 }
George Rimar07171f22016-09-21 15:56:44 +00001400 return Ret;
George Rimar395281c2016-09-16 17:42:10 +00001401}
1402
Rui Ueyamaf8f6f1e2016-11-18 07:03:56 +00001403// Reads contents of "SECTIONS" directive. That directive contains a
1404// list of glob patterns for input sections. The grammar is as follows.
1405//
1406// <patterns> ::= <section-list>
1407// | <sort> "(" <section-list> ")"
1408// | <sort> "(" <sort> "(" <section-list> ")" ")"
1409//
1410// <sort> ::= "SORT" | "SORT_BY_NAME" | "SORT_BY_ALIGNMENT"
1411// | "SORT_BY_INIT_PRIORITY" | "SORT_NONE"
1412//
1413// <section-list> is parsed by readInputSectionsList().
George Rimara2496cb2016-08-30 09:46:59 +00001414InputSectionDescription *
1415ScriptParser::readInputSectionRules(StringRef FilePattern) {
George Rimarc91930a2016-09-02 21:17:20 +00001416 auto *Cmd = new InputSectionDescription(FilePattern);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001417 expect("(");
Rui Ueyamaf373dd72016-11-24 01:43:21 +00001418 while (!Error && !consume(")")) {
George Rimar07171f22016-09-21 15:56:44 +00001419 SortSectionPolicy Outer = readSortKind();
1420 SortSectionPolicy Inner = SortSectionPolicy::Default;
1421 std::vector<SectionPattern> V;
1422 if (Outer != SortSectionPolicy::Default) {
George Rimar350ece42016-08-03 08:35:59 +00001423 expect("(");
George Rimar07171f22016-09-21 15:56:44 +00001424 Inner = readSortKind();
1425 if (Inner != SortSectionPolicy::Default) {
1426 expect("(");
1427 V = readInputSectionsList();
1428 expect(")");
1429 } else {
1430 V = readInputSectionsList();
1431 }
George Rimar350ece42016-08-03 08:35:59 +00001432 expect(")");
1433 } else {
George Rimar07171f22016-09-21 15:56:44 +00001434 V = readInputSectionsList();
George Rimar350ece42016-08-03 08:35:59 +00001435 }
George Rimar0702c4e2016-07-29 15:32:46 +00001436
George Rimar07171f22016-09-21 15:56:44 +00001437 for (SectionPattern &Pat : V) {
1438 Pat.SortInner = Inner;
1439 Pat.SortOuter = Outer;
1440 }
1441
1442 std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns));
1443 }
Rui Ueyama10416562016-08-04 02:03:27 +00001444 return Cmd;
Davide Italianoe7282792016-07-27 01:44:01 +00001445}
1446
George Rimara2496cb2016-08-30 09:46:59 +00001447InputSectionDescription *
1448ScriptParser::readInputSectionDescription(StringRef Tok) {
George Rimar06598002016-07-28 21:51:30 +00001449 // Input section wildcard can be surrounded by KEEP.
1450 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
George Rimara2496cb2016-08-30 09:46:59 +00001451 if (Tok == "KEEP") {
George Rimar06598002016-07-28 21:51:30 +00001452 expect("(");
George Rimara2496cb2016-08-30 09:46:59 +00001453 StringRef FilePattern = next();
1454 InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
George Rimar06598002016-07-28 21:51:30 +00001455 expect(")");
Eugene Leviantcf43f172016-10-05 09:36:59 +00001456 Opt.KeptSections.push_back(Cmd);
Rui Ueyama10416562016-08-04 02:03:27 +00001457 return Cmd;
George Rimar06598002016-07-28 21:51:30 +00001458 }
George Rimara2496cb2016-08-30 09:46:59 +00001459 return readInputSectionRules(Tok);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001460}
1461
George Rimar03fc0102016-07-28 07:18:23 +00001462void ScriptParser::readSort() {
1463 expect("(");
1464 expect("CONSTRUCTORS");
1465 expect(")");
1466}
1467
George Rimareefa7582016-08-04 09:29:31 +00001468Expr ScriptParser::readAssert() {
1469 expect("(");
1470 Expr E = readExpr();
1471 expect(",");
George Rimarcd574a52016-09-09 14:35:36 +00001472 StringRef Msg = unquote(next());
George Rimareefa7582016-08-04 09:29:31 +00001473 expect(")");
1474 return [=](uint64_t Dot) {
George Rimar60f1fe82017-02-21 07:33:38 +00001475 if (!E(Dot))
George Rimareefa7582016-08-04 09:29:31 +00001476 error(Msg);
George Rimar60f1fe82017-02-21 07:33:38 +00001477 return Dot;
George Rimareefa7582016-08-04 09:29:31 +00001478 };
1479}
1480
Rui Ueyama25150e82016-09-06 17:46:43 +00001481// Reads a FILL(expr) command. We handle the FILL command as an
1482// alias for =fillexp section attribute, which is different from
1483// what GNU linkers do.
1484// https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
Rui Ueyama16068ae2016-11-19 18:05:56 +00001485uint32_t ScriptParser::readFill() {
George Rimarff1f29e2016-09-06 13:51:57 +00001486 expect("(");
Rui Ueyama16068ae2016-11-19 18:05:56 +00001487 uint32_t V = readOutputSectionFiller(next());
George Rimarff1f29e2016-09-06 13:51:57 +00001488 expect(")");
1489 expect(";");
1490 return V;
1491}
1492
Rui Ueyama10416562016-08-04 02:03:27 +00001493OutputSectionCommand *
1494ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +00001495 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
Eugene Leviant2a942c42016-12-05 16:38:32 +00001496 Cmd->Location = getCurrentLocation();
George Rimar58e5c4d2016-07-25 08:29:46 +00001497
1498 // Read an address expression.
1499 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
1500 if (peek() != ":")
1501 Cmd->AddrExpr = readExpr();
1502
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001503 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +00001504
Rui Ueyama83043f22016-10-17 16:01:53 +00001505 if (consume("AT"))
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001506 Cmd->LMAExpr = readParenExpr();
Rui Ueyama83043f22016-10-17 16:01:53 +00001507 if (consume("ALIGN"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001508 Cmd->AlignExpr = readParenExpr();
Rui Ueyama83043f22016-10-17 16:01:53 +00001509 if (consume("SUBALIGN"))
George Rimardb24d9c2016-08-19 15:18:23 +00001510 Cmd->SubalignExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001511
Davide Italiano246f6812016-07-22 03:36:24 +00001512 // Parse constraints.
Rui Ueyama83043f22016-10-17 16:01:53 +00001513 if (consume("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001514 Cmd->Constraint = ConstraintKind::ReadOnly;
Rui Ueyama83043f22016-10-17 16:01:53 +00001515 if (consume("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001516 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001517 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001518
Rui Ueyama83043f22016-10-17 16:01:53 +00001519 while (!Error && !consume("}")) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001520 StringRef Tok = next();
George Rimar2fe07922017-01-31 08:50:11 +00001521 if (Tok == ";") {
George Rimar69750752017-02-01 09:14:22 +00001522 // Empty commands are allowed. Do nothing here.
George Rimar2fe07922017-01-31 08:50:11 +00001523 } else if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok)) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001524 Cmd->Commands.emplace_back(Assignment);
Meador Ingeb2d99d62016-11-22 18:01:50 +00001525 } else if (BytesDataCommand *Data = readBytesDataCommand(Tok)) {
George Rimare38cbab2016-09-26 19:22:50 +00001526 Cmd->Commands.emplace_back(Data);
Meador Ingeb2d99d62016-11-22 18:01:50 +00001527 } else if (Tok == "ASSERT") {
1528 Cmd->Commands.emplace_back(new AssertCommand(readAssert()));
1529 expect(";");
George Rimar8e2eca22017-01-23 09:36:19 +00001530 } else if (Tok == "CONSTRUCTORS") {
1531 // CONSTRUCTORS is a keyword to make the linker recognize C++ ctors/dtors
1532 // by name. This is for very old file formats such as ECOFF/XCOFF.
1533 // For ELF, we should ignore.
Meador Ingeb2d99d62016-11-22 18:01:50 +00001534 } else if (Tok == "FILL") {
George Rimarff1f29e2016-09-06 13:51:57 +00001535 Cmd->Filler = readFill();
Meador Ingeb2d99d62016-11-22 18:01:50 +00001536 } else if (Tok == "SORT") {
George Rimar03fc0102016-07-28 07:18:23 +00001537 readSort();
Meador Ingeb2d99d62016-11-22 18:01:50 +00001538 } else if (peek() == "(") {
George Rimara2496cb2016-08-30 09:46:59 +00001539 Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
Meador Ingeb2d99d62016-11-22 18:01:50 +00001540 } else {
Eugene Leviantceabe802016-08-11 07:56:43 +00001541 setError("unknown command " + Tok);
Meador Ingeb2d99d62016-11-22 18:01:50 +00001542 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001543 }
Meador Ingeb8897442017-01-24 02:34:00 +00001544
1545 if (consume(">"))
1546 Cmd->MemoryRegionName = next();
1547
George Rimar076fe152016-07-21 06:43:01 +00001548 Cmd->Phdrs = readOutputSectionPhdrs();
George Rimar4ebc5622016-09-23 13:29:20 +00001549
Rui Ueyama83043f22016-10-17 16:01:53 +00001550 if (consume("="))
George Rimar4ebc5622016-09-23 13:29:20 +00001551 Cmd->Filler = readOutputSectionFiller(next());
1552 else if (peek().startswith("="))
George Rimarff1f29e2016-09-06 13:51:57 +00001553 Cmd->Filler = readOutputSectionFiller(next().drop_front());
George Rimar4ebc5622016-09-23 13:29:20 +00001554
George Rimar7185a1a2017-01-17 15:32:12 +00001555 // Consume optional comma following output section command.
1556 consume(",");
1557
Rui Ueyama10416562016-08-04 02:03:27 +00001558 return Cmd;
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001559}
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001560
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001561// Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
1562// https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
1563//
1564// ld.gold is not fully compatible with ld.bfd. ld.bfd handles
1565// hexstrings as blobs of arbitrary sizes, while ld.gold handles them
1566// as 32-bit big-endian values. We will do the same as ld.gold does
1567// because it's simpler than what ld.bfd does.
Rui Ueyama16068ae2016-11-19 18:05:56 +00001568uint32_t ScriptParser::readOutputSectionFiller(StringRef Tok) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001569 uint32_t V;
Rui Ueyama16068ae2016-11-19 18:05:56 +00001570 if (!Tok.getAsInteger(0, V))
1571 return V;
1572 setError("invalid filler expression: " + Tok);
1573 return 0;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001574}
1575
Petr Hoseka35e39c2016-08-16 01:11:16 +00001576SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
Eugene Levianta31c91b2016-07-22 07:38:40 +00001577 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +00001578 SymbolAssignment *Cmd = readAssignment(next());
Petr Hoseka35e39c2016-08-16 01:11:16 +00001579 Cmd->Provide = Provide;
Rui Ueyama174e0a12016-07-29 00:29:25 +00001580 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001581 expect(")");
1582 expect(";");
Rui Ueyama10416562016-08-04 02:03:27 +00001583 return Cmd;
Eugene Levianteda81a12016-07-12 06:39:48 +00001584}
1585
Rafael Espindolac96da112016-11-01 11:30:45 +00001586SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001587 SymbolAssignment *Cmd = nullptr;
1588 if (peek() == "=" || peek() == "+=") {
1589 Cmd = readAssignment(Tok);
1590 expect(";");
1591 } else if (Tok == "PROVIDE") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001592 Cmd = readProvideHidden(true, false);
1593 } else if (Tok == "HIDDEN") {
1594 Cmd = readProvideHidden(false, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001595 } else if (Tok == "PROVIDE_HIDDEN") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001596 Cmd = readProvideHidden(true, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001597 }
1598 return Cmd;
1599}
1600
Eugene Leviantf6aeed32016-12-22 13:13:12 +00001601static uint64_t getSymbolValue(const Twine &Loc, StringRef S, uint64_t Dot) {
George Rimar30835ea2016-07-28 21:08:56 +00001602 if (S == ".")
1603 return Dot;
Eugene Leviantf6aeed32016-12-22 13:13:12 +00001604 return ScriptBase->getSymbolValue(Loc, S);
George Rimare32a3592016-08-10 07:59:34 +00001605}
1606
Rafael Espindola2f831dc2016-10-31 19:56:37 +00001607static bool isAbsolute(StringRef S) {
1608 if (S == ".")
1609 return false;
1610 return ScriptBase->isAbsolute(S);
1611}
1612
George Rimar30835ea2016-07-28 21:08:56 +00001613SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1614 StringRef Op = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +00001615 Expr E;
George Rimar30835ea2016-07-28 21:08:56 +00001616 assert(Op == "=" || Op == "+=");
Rui Ueyama83043f22016-10-17 16:01:53 +00001617 if (consume("ABSOLUTE")) {
Rui Ueyama731a66a2017-02-15 19:58:17 +00001618 E = readExpr();
Rui Ueyama009d1742016-11-18 06:49:09 +00001619 E.IsAbsolute = [] { return true; };
Eugene Leviantdb741e72016-09-07 07:08:43 +00001620 } else {
1621 E = readExpr();
1622 }
Eugene Leviantf6aeed32016-12-22 13:13:12 +00001623 if (Op == "+=") {
1624 std::string Loc = getCurrentLocation();
1625 E = [=](uint64_t Dot) {
1626 return getSymbolValue(Loc, Name, Dot) + E(Dot);
1627 };
1628 }
George Rimar2ee2d2d2017-02-21 14:50:38 +00001629 return new SymbolAssignment(Name, E, getCurrentLocation());
George Rimar30835ea2016-07-28 21:08:56 +00001630}
1631
1632// This is an operator-precedence parser to parse a linker
1633// script expression.
Rui Ueyama731a66a2017-02-15 19:58:17 +00001634Expr ScriptParser::readExpr() {
1635 // Our lexer is context-aware. Set the in-expression bit so that
1636 // they apply different tokenization rules.
1637 bool Orig = InExpr;
1638 InExpr = true;
1639 Expr E = readExpr1(readPrimary(), 0);
1640 InExpr = Orig;
1641 return E;
1642}
George Rimar30835ea2016-07-28 21:08:56 +00001643
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001644static Expr combine(StringRef Op, Expr L, Expr R) {
George Rimarcc4d3e52017-02-01 09:01:16 +00001645 auto IsAbs = [=] { return L.IsAbsolute() && R.IsAbsolute(); };
1646 auto GetOutSec = [=] {
1647 const OutputSectionBase *S = L.Section();
1648 return S ? S : R.Section();
1649 };
1650
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001651 if (Op == "*")
1652 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1653 if (Op == "/") {
1654 return [=](uint64_t Dot) -> uint64_t {
1655 uint64_t RHS = R(Dot);
1656 if (RHS == 0) {
1657 error("division by zero");
1658 return 0;
1659 }
1660 return L(Dot) / RHS;
1661 };
1662 }
1663 if (Op == "+")
George Rimarcc4d3e52017-02-01 09:01:16 +00001664 return {[=](uint64_t Dot) { return L(Dot) + R(Dot); }, IsAbs, GetOutSec};
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001665 if (Op == "-")
George Rimarcc4d3e52017-02-01 09:01:16 +00001666 return {[=](uint64_t Dot) { return L(Dot) - R(Dot); }, IsAbs, GetOutSec};
George Rimarc8ccd1f2016-09-23 13:13:55 +00001667 if (Op == "<<")
1668 return [=](uint64_t Dot) { return L(Dot) << R(Dot); };
1669 if (Op == ">>")
1670 return [=](uint64_t Dot) { return L(Dot) >> R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001671 if (Op == "<")
1672 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
1673 if (Op == ">")
1674 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
1675 if (Op == ">=")
1676 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
1677 if (Op == "<=")
1678 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
1679 if (Op == "==")
1680 return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
1681 if (Op == "!=")
1682 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
1683 if (Op == "&")
1684 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
Rafael Espindolacc3dd622016-08-22 21:33:35 +00001685 if (Op == "|")
1686 return [=](uint64_t Dot) { return L(Dot) | R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001687 llvm_unreachable("invalid operator");
1688}
1689
Rui Ueyama708019c2016-07-24 18:19:40 +00001690// This is a part of the operator-precedence parser. This function
1691// assumes that the remaining token stream starts with an operator.
1692Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1693 while (!atEOF() && !Error) {
1694 // Read an operator and an expression.
Rui Ueyama46247b82016-11-18 06:49:07 +00001695 if (consume("?"))
Rui Ueyama708019c2016-07-24 18:19:40 +00001696 return readTernary(Lhs);
Rui Ueyama46247b82016-11-18 06:49:07 +00001697 StringRef Op1 = peek();
Rui Ueyama708019c2016-07-24 18:19:40 +00001698 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +00001699 break;
Justin Bogner5424e7c2016-10-17 06:21:13 +00001700 skip();
Rui Ueyama708019c2016-07-24 18:19:40 +00001701 Expr Rhs = readPrimary();
1702
1703 // Evaluate the remaining part of the expression first if the
1704 // next operator has greater precedence than the previous one.
1705 // For example, if we have read "+" and "3", and if the next
1706 // operator is "*", then we'll evaluate 3 * ... part first.
1707 while (!atEOF()) {
1708 StringRef Op2 = peek();
1709 if (precedence(Op2) <= precedence(Op1))
1710 break;
1711 Rhs = readExpr1(Rhs, precedence(Op2));
1712 }
1713
1714 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +00001715 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001716 return Lhs;
1717}
1718
1719uint64_t static getConstant(StringRef S) {
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001720 if (S == "COMMONPAGESIZE")
Rui Ueyama708019c2016-07-24 18:19:40 +00001721 return Target->PageSize;
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001722 if (S == "MAXPAGESIZE")
Petr Hosek997f8832016-09-28 15:20:47 +00001723 return Config->MaxPageSize;
Rui Ueyama708019c2016-07-24 18:19:40 +00001724 error("unknown constant: " + S);
1725 return 0;
1726}
1727
Rui Ueyama626e0b02016-09-02 18:19:00 +00001728// Parses Tok as an integer. Returns true if successful.
1729// It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1730// and decimal numbers. Decimal numbers may have "K" (kilo) or
1731// "M" (mega) prefixes.
George Rimar9f2f7ad2016-09-02 16:01:42 +00001732static bool readInteger(StringRef Tok, uint64_t &Result) {
Rui Ueyama46247b82016-11-18 06:49:07 +00001733 // Negative number
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001734 if (Tok.startswith("-")) {
1735 if (!readInteger(Tok.substr(1), Result))
1736 return false;
1737 Result = -Result;
1738 return true;
1739 }
Rui Ueyama46247b82016-11-18 06:49:07 +00001740
1741 // Hexadecimal
George Rimar9f2f7ad2016-09-02 16:01:42 +00001742 if (Tok.startswith_lower("0x"))
1743 return !Tok.substr(2).getAsInteger(16, Result);
1744 if (Tok.endswith_lower("H"))
1745 return !Tok.drop_back().getAsInteger(16, Result);
1746
Rui Ueyama46247b82016-11-18 06:49:07 +00001747 // Decimal
George Rimar9f2f7ad2016-09-02 16:01:42 +00001748 int Suffix = 1;
1749 if (Tok.endswith_lower("K")) {
1750 Suffix = 1024;
1751 Tok = Tok.drop_back();
1752 } else if (Tok.endswith_lower("M")) {
1753 Suffix = 1024 * 1024;
1754 Tok = Tok.drop_back();
1755 }
1756 if (Tok.getAsInteger(10, Result))
1757 return false;
1758 Result *= Suffix;
1759 return true;
1760}
1761
George Rimare38cbab2016-09-26 19:22:50 +00001762BytesDataCommand *ScriptParser::readBytesDataCommand(StringRef Tok) {
1763 int Size = StringSwitch<unsigned>(Tok)
1764 .Case("BYTE", 1)
1765 .Case("SHORT", 2)
1766 .Case("LONG", 4)
1767 .Case("QUAD", 8)
1768 .Default(-1);
1769 if (Size == -1)
1770 return nullptr;
1771
Meador Inge95c7d8d2016-12-08 23:21:30 +00001772 return new BytesDataCommand(readParenExpr(), Size);
George Rimare38cbab2016-09-26 19:22:50 +00001773}
1774
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001775StringRef ScriptParser::readParenLiteral() {
1776 expect("(");
1777 StringRef Tok = next();
1778 expect(")");
1779 return Tok;
1780}
1781
Rui Ueyama708019c2016-07-24 18:19:40 +00001782Expr ScriptParser::readPrimary() {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001783 if (peek() == "(")
1784 return readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001785
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001786 StringRef Tok = next();
Rui Ueyamab5f1c3e2016-12-01 04:36:49 +00001787 std::string Location = getCurrentLocation();
Rui Ueyama708019c2016-07-24 18:19:40 +00001788
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001789 if (Tok == "~") {
1790 Expr E = readPrimary();
1791 return [=](uint64_t Dot) { return ~E(Dot); };
1792 }
1793 if (Tok == "-") {
1794 Expr E = readPrimary();
1795 return [=](uint64_t Dot) { return -E(Dot); };
1796 }
1797
Rui Ueyama708019c2016-07-24 18:19:40 +00001798 // Built-in functions are parsed here.
1799 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
George Rimar96659df2016-08-30 09:54:01 +00001800 if (Tok == "ADDR") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001801 StringRef Name = readParenLiteral();
Eugene Levianted30ce72016-11-28 09:58:04 +00001802 return {[=](uint64_t Dot) {
1803 return ScriptBase->getOutputSection(Location, Name)->Addr;
1804 },
1805 [=] { return false; },
1806 [=] { return ScriptBase->getOutputSection(Location, Name); }};
George Rimar96659df2016-08-30 09:54:01 +00001807 }
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001808 if (Tok == "LOADADDR") {
1809 StringRef Name = readParenLiteral();
Eugene Leviantafaa9342016-11-16 09:49:39 +00001810 return [=](uint64_t Dot) {
Eugene Levianted30ce72016-11-28 09:58:04 +00001811 return ScriptBase->getOutputSection(Location, Name)->getLMA();
Eugene Leviantafaa9342016-11-16 09:49:39 +00001812 };
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001813 }
George Rimareefa7582016-08-04 09:29:31 +00001814 if (Tok == "ASSERT")
1815 return readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001816 if (Tok == "ALIGN") {
Rui Ueyama5d804dc2016-12-16 18:19:35 +00001817 expect("(");
1818 Expr E = readExpr();
1819 if (consume(",")) {
1820 Expr E2 = readExpr();
1821 expect(")");
1822 return [=](uint64_t Dot) { return alignTo(E(Dot), E2(Dot)); };
1823 }
1824 expect(")");
Rui Ueyama708019c2016-07-24 18:19:40 +00001825 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1826 }
1827 if (Tok == "CONSTANT") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001828 StringRef Name = readParenLiteral();
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001829 return [=](uint64_t Dot) { return getConstant(Name); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001830 }
George Rimarf34f45f2016-09-23 13:17:23 +00001831 if (Tok == "DEFINED") {
Rui Ueyama0ee25a62016-11-17 03:52:14 +00001832 StringRef Name = readParenLiteral();
1833 return [=](uint64_t Dot) { return ScriptBase->isDefined(Name) ? 1 : 0; };
George Rimarf34f45f2016-09-23 13:17:23 +00001834 }
Rafael Espindola54c145c2016-07-28 18:16:24 +00001835 if (Tok == "SEGMENT_START") {
1836 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001837 skip();
Rafael Espindola54c145c2016-07-28 18:16:24 +00001838 expect(",");
George Rimar8c658bf2016-09-17 18:14:56 +00001839 Expr E = readExpr();
Rafael Espindola54c145c2016-07-28 18:16:24 +00001840 expect(")");
George Rimar8c658bf2016-09-17 18:14:56 +00001841 return [=](uint64_t Dot) { return E(Dot); };
Rafael Espindola54c145c2016-07-28 18:16:24 +00001842 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001843 if (Tok == "DATA_SEGMENT_ALIGN") {
1844 expect("(");
1845 Expr E = readExpr();
1846 expect(",");
1847 readExpr();
1848 expect(")");
Rui Ueyamaf7791bb2016-07-26 19:34:10 +00001849 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001850 }
1851 if (Tok == "DATA_SEGMENT_END") {
1852 expect("(");
1853 expect(".");
1854 expect(")");
1855 return [](uint64_t Dot) { return Dot; };
1856 }
George Rimar276b4e62016-07-26 17:58:44 +00001857 // GNU linkers implements more complicated logic to handle
1858 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1859 // the next page boundary for simplicity.
1860 if (Tok == "DATA_SEGMENT_RELRO_END") {
1861 expect("(");
Rafael Espindola97bdc722016-09-14 19:14:01 +00001862 readExpr();
George Rimar276b4e62016-07-26 17:58:44 +00001863 expect(",");
1864 readExpr();
1865 expect(")");
1866 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1867 }
George Rimar9e694502016-07-29 16:18:47 +00001868 if (Tok == "SIZEOF") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001869 StringRef Name = readParenLiteral();
Rui Ueyamaedf75e72016-11-17 20:27:10 +00001870 return [=](uint64_t Dot) { return ScriptBase->getOutputSectionSize(Name); };
George Rimar9e694502016-07-29 16:18:47 +00001871 }
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001872 if (Tok == "ALIGNOF") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001873 StringRef Name = readParenLiteral();
Eugene Leviantafaa9342016-11-16 09:49:39 +00001874 return [=](uint64_t Dot) {
Eugene Levianted30ce72016-11-28 09:58:04 +00001875 return ScriptBase->getOutputSection(Location, Name)->Addralign;
Eugene Leviantafaa9342016-11-16 09:49:39 +00001876 };
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001877 }
George Rimare32a3592016-08-10 07:59:34 +00001878 if (Tok == "SIZEOF_HEADERS")
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001879 return [=](uint64_t Dot) { return ScriptBase->getHeaderSize(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001880
George Rimar9f2f7ad2016-09-02 16:01:42 +00001881 // Tok is a literal number.
1882 uint64_t V;
1883 if (readInteger(Tok, V))
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001884 return [=](uint64_t Dot) { return V; };
George Rimar9f2f7ad2016-09-02 16:01:42 +00001885
1886 // Tok is a symbol name.
1887 if (Tok != "." && !isValidCIdentifier(Tok))
1888 setError("malformed number: " + Tok);
Eugene Leviantf6aeed32016-12-22 13:13:12 +00001889 return {[=](uint64_t Dot) { return getSymbolValue(Location, Tok, Dot); },
Rui Ueyama009d1742016-11-18 06:49:09 +00001890 [=] { return isAbsolute(Tok); },
1891 [=] { return ScriptBase->getSymbolSection(Tok); }};
Rui Ueyama708019c2016-07-24 18:19:40 +00001892}
1893
1894Expr ScriptParser::readTernary(Expr Cond) {
Rui Ueyama708019c2016-07-24 18:19:40 +00001895 Expr L = readExpr();
1896 expect(":");
1897 Expr R = readExpr();
1898 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1899}
1900
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001901Expr ScriptParser::readParenExpr() {
1902 expect("(");
1903 Expr E = readExpr();
1904 expect(")");
1905 return E;
1906}
1907
Eugene Leviantbbe38602016-07-19 09:25:43 +00001908std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1909 std::vector<StringRef> Phdrs;
1910 while (!Error && peek().startswith(":")) {
1911 StringRef Tok = next();
George Rimarda841c12016-11-14 10:03:54 +00001912 Phdrs.push_back((Tok.size() == 1) ? next() : Tok.substr(1));
Eugene Leviantbbe38602016-07-19 09:25:43 +00001913 }
1914 return Phdrs;
1915}
1916
George Rimar95dd7182016-10-18 10:49:50 +00001917// Read a program header type name. The next token must be a
1918// name of a program header type or a constant (e.g. "0x3").
Eugene Leviantbbe38602016-07-19 09:25:43 +00001919unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001920 StringRef Tok = next();
George Rimar95dd7182016-10-18 10:49:50 +00001921 uint64_t Val;
1922 if (readInteger(Tok, Val))
1923 return Val;
1924
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001925 unsigned Ret = StringSwitch<unsigned>(Tok)
George Rimar6c55f0e2016-09-08 08:20:30 +00001926 .Case("PT_NULL", PT_NULL)
1927 .Case("PT_LOAD", PT_LOAD)
1928 .Case("PT_DYNAMIC", PT_DYNAMIC)
1929 .Case("PT_INTERP", PT_INTERP)
1930 .Case("PT_NOTE", PT_NOTE)
1931 .Case("PT_SHLIB", PT_SHLIB)
1932 .Case("PT_PHDR", PT_PHDR)
1933 .Case("PT_TLS", PT_TLS)
1934 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1935 .Case("PT_GNU_STACK", PT_GNU_STACK)
1936 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
George Rimar270173f2016-10-14 13:02:22 +00001937 .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
George Rimarcc6e5672016-10-14 10:34:36 +00001938 .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
George Rimara2a32c22016-12-06 17:57:42 +00001939 .Case("PT_OPENBSD_BOOTDATA", PT_OPENBSD_BOOTDATA)
George Rimar6c55f0e2016-09-08 08:20:30 +00001940 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001941
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001942 if (Ret == (unsigned)-1) {
1943 setError("invalid program header type: " + Tok);
1944 return PT_NULL;
1945 }
1946 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001947}
1948
Rui Ueyama12450b22016-11-18 06:30:09 +00001949// Reads a list of symbols, e.g. "{ global: foo; bar; local: *; };".
1950void ScriptParser::readAnonymousDeclaration() {
1951 // Read global symbols first. "global:" is default, so if there's
1952 // no label, we assume global symbols.
Rafael Espindola45242682017-02-03 13:24:01 +00001953 if (peek() != "local") {
1954 if (consume("global"))
1955 expect(":");
Peter Collingbourne904c5ed2017-02-13 18:31:12 +00001956 for (SymbolVersion V : readSymbols())
1957 Config->VersionScriptGlobals.push_back(V);
Rafael Espindola45242682017-02-03 13:24:01 +00001958 }
Rafael Espindolae999ddb2017-01-10 16:37:24 +00001959 readLocals();
Rui Ueyama12450b22016-11-18 06:30:09 +00001960 expect("}");
1961 expect(";");
1962}
1963
Rafael Espindolae999ddb2017-01-10 16:37:24 +00001964void ScriptParser::readLocals() {
Rafael Espindola45242682017-02-03 13:24:01 +00001965 if (!consume("local"))
Rafael Espindolae999ddb2017-01-10 16:37:24 +00001966 return;
Rafael Espindola45242682017-02-03 13:24:01 +00001967 expect(":");
Rafael Espindolae999ddb2017-01-10 16:37:24 +00001968 std::vector<SymbolVersion> Locals = readSymbols();
1969 for (SymbolVersion V : Locals) {
1970 if (V.Name == "*") {
1971 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1972 continue;
1973 }
1974 Config->VersionScriptLocals.push_back(V);
1975 }
1976}
1977
Rui Ueyama12450b22016-11-18 06:30:09 +00001978// Reads a list of symbols, e.g. "VerStr { global: foo; bar; local: *; };".
Rui Ueyama95769b42016-08-31 20:03:54 +00001979void ScriptParser::readVersionDeclaration(StringRef VerStr) {
George Rimar20b65982016-08-31 09:08:26 +00001980 // Identifiers start at 2 because 0 and 1 are reserved
1981 // for VER_NDX_LOCAL and VER_NDX_GLOBAL constants.
Rui Ueyamada805c42016-11-17 03:39:21 +00001982 uint16_t VersionId = Config->VersionDefinitions.size() + 2;
George Rimar20b65982016-08-31 09:08:26 +00001983 Config->VersionDefinitions.push_back({VerStr, VersionId});
1984
Rui Ueyama12450b22016-11-18 06:30:09 +00001985 // Read global symbols.
Rafael Espindola45242682017-02-03 13:24:01 +00001986 if (peek() != "local") {
1987 if (consume("global"))
1988 expect(":");
Rui Ueyama12450b22016-11-18 06:30:09 +00001989 Config->VersionDefinitions.back().Globals = readSymbols();
Rafael Espindola45242682017-02-03 13:24:01 +00001990 }
Rafael Espindolae999ddb2017-01-10 16:37:24 +00001991 readLocals();
George Rimar20b65982016-08-31 09:08:26 +00001992 expect("}");
1993
Rui Ueyama12450b22016-11-18 06:30:09 +00001994 // Each version may have a parent version. For example, "Ver2"
1995 // defined as "Ver2 { global: foo; local: *; } Ver1;" has "Ver1"
1996 // as a parent. This version hierarchy is, probably against your
1997 // instinct, purely for hint; the runtime doesn't care about it
1998 // at all. In LLD, we simply ignore it.
1999 if (peek() != ";")
Justin Bogner5424e7c2016-10-17 06:21:13 +00002000 skip();
George Rimar20b65982016-08-31 09:08:26 +00002001 expect(";");
2002}
2003
Rui Ueyama12450b22016-11-18 06:30:09 +00002004// Reads a list of symbols for a versions cript.
2005std::vector<SymbolVersion> ScriptParser::readSymbols() {
2006 std::vector<SymbolVersion> Ret;
George Rimare0fc2422016-11-16 17:59:10 +00002007 for (;;) {
Rafael Espindola1ef90d22016-12-09 16:44:05 +00002008 if (consume("extern")) {
Rui Ueyama12450b22016-11-18 06:30:09 +00002009 for (SymbolVersion V : readVersionExtern())
2010 Ret.push_back(V);
Rafael Espindola1ef90d22016-12-09 16:44:05 +00002011 continue;
2012 }
George Rimare0fc2422016-11-16 17:59:10 +00002013
Dmitry Mikulinf3965c02017-02-07 19:50:47 +00002014 if (peek() == "}" || (peek() == "local" && peek(1) == ":") || Error)
Rui Ueyama12450b22016-11-18 06:30:09 +00002015 break;
Rui Ueyama0ee25a62016-11-17 03:52:14 +00002016 StringRef Tok = next();
Rui Ueyama12450b22016-11-18 06:30:09 +00002017 Ret.push_back({unquote(Tok), false, hasWildcard(Tok)});
George Rimare0fc2422016-11-16 17:59:10 +00002018 expect(";");
2019 }
Rui Ueyama12450b22016-11-18 06:30:09 +00002020 return Ret;
George Rimare0fc2422016-11-16 17:59:10 +00002021}
2022
Rui Ueyama12450b22016-11-18 06:30:09 +00002023// Reads an "extern C++" directive, e.g.,
2024// "extern "C++" { ns::*; "f(int, double)"; };"
2025std::vector<SymbolVersion> ScriptParser::readVersionExtern() {
Rafael Espindola7e714152016-12-08 17:26:53 +00002026 StringRef Tok = next();
2027 bool IsCXX = Tok == "\"C++\"";
2028 if (!IsCXX && Tok != "\"C\"")
Rafael Espindolad0ebd842016-12-08 17:54:26 +00002029 setError("Unknown language");
George Rimar20b65982016-08-31 09:08:26 +00002030 expect("{");
2031
Rui Ueyama12450b22016-11-18 06:30:09 +00002032 std::vector<SymbolVersion> Ret;
Rui Ueyama0ee25a62016-11-17 03:52:14 +00002033 while (!Error && peek() != "}") {
2034 StringRef Tok = next();
2035 bool HasWildcard = !Tok.startswith("\"") && hasWildcard(Tok);
Rafael Espindola7e714152016-12-08 17:26:53 +00002036 Ret.push_back({unquote(Tok), IsCXX, HasWildcard});
George Rimar20b65982016-08-31 09:08:26 +00002037 expect(";");
2038 }
2039
2040 expect("}");
2041 expect(";");
Rui Ueyama12450b22016-11-18 06:30:09 +00002042 return Ret;
George Rimar20b65982016-08-31 09:08:26 +00002043}
2044
Rui Ueyama24e626c2017-01-26 02:58:19 +00002045uint64_t ScriptParser::readMemoryAssignment(
2046 StringRef S1, StringRef S2, StringRef S3) {
2047 if (!(consume(S1) || consume(S2) || consume(S3))) {
2048 setError("expected one of: " + S1 + ", " + S2 + ", or " + S3);
2049 return 0;
2050 }
2051 expect("=");
2052
2053 // TODO: Fully support constant expressions.
2054 uint64_t Val;
2055 if (!readInteger(next(), Val))
2056 setError("nonconstant expression for "+ S1);
2057 return Val;
2058}
2059
2060// Parse the MEMORY command as specified in:
2061// https://sourceware.org/binutils/docs/ld/MEMORY.html
2062//
2063// MEMORY { name [(attr)] : ORIGIN = origin, LENGTH = len ... }
Meador Ingeb8897442017-01-24 02:34:00 +00002064void ScriptParser::readMemory() {
2065 expect("{");
2066 while (!Error && !consume("}")) {
2067 StringRef Name = next();
Rui Ueyama24e626c2017-01-26 02:58:19 +00002068
Meador Ingeb8897442017-01-24 02:34:00 +00002069 uint32_t Flags = 0;
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002070 uint32_t NegFlags = 0;
Meador Ingeb8897442017-01-24 02:34:00 +00002071 if (consume("(")) {
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002072 std::tie(Flags, NegFlags) = readMemoryAttributes();
Meador Ingeb8897442017-01-24 02:34:00 +00002073 expect(")");
2074 }
2075 expect(":");
2076
Rui Ueyama24e626c2017-01-26 02:58:19 +00002077 uint64_t Origin = readMemoryAssignment("ORIGIN", "org", "o");
Meador Ingeb8897442017-01-24 02:34:00 +00002078 expect(",");
Rui Ueyama24e626c2017-01-26 02:58:19 +00002079 uint64_t Length = readMemoryAssignment("LENGTH", "len", "l");
Meador Ingeb8897442017-01-24 02:34:00 +00002080
Meador Ingeb8897442017-01-24 02:34:00 +00002081 // Add the memory region to the region map (if it doesn't already exist).
2082 auto It = Opt.MemoryRegions.find(Name);
2083 if (It != Opt.MemoryRegions.end())
2084 setError("region '" + Name + "' already defined");
2085 else
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002086 Opt.MemoryRegions[Name] = {Name, Origin, Length, Origin, Flags, NegFlags};
Meador Ingeb8897442017-01-24 02:34:00 +00002087 }
2088}
2089
2090// This function parses the attributes used to match against section
2091// flags when placing output sections in a memory region. These flags
2092// are only used when an explicit memory region name is not used.
2093std::pair<uint32_t, uint32_t> ScriptParser::readMemoryAttributes() {
2094 uint32_t Flags = 0;
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002095 uint32_t NegFlags = 0;
Meador Ingeb8897442017-01-24 02:34:00 +00002096 bool Invert = false;
Rui Ueyama481ac992017-01-26 02:58:39 +00002097
2098 for (char C : next().lower()) {
Meador Ingeb8897442017-01-24 02:34:00 +00002099 uint32_t Flag = 0;
2100 if (C == '!')
2101 Invert = !Invert;
Rui Ueyama481ac992017-01-26 02:58:39 +00002102 else if (C == 'w')
Meador Ingeb8897442017-01-24 02:34:00 +00002103 Flag = SHF_WRITE;
Rui Ueyama481ac992017-01-26 02:58:39 +00002104 else if (C == 'x')
Meador Ingeb8897442017-01-24 02:34:00 +00002105 Flag = SHF_EXECINSTR;
Rui Ueyama481ac992017-01-26 02:58:39 +00002106 else if (C == 'a')
Meador Ingeb8897442017-01-24 02:34:00 +00002107 Flag = SHF_ALLOC;
Rui Ueyama481ac992017-01-26 02:58:39 +00002108 else if (C != 'r')
Meador Ingeb8897442017-01-24 02:34:00 +00002109 setError("invalid memory region attribute");
Rui Ueyama481ac992017-01-26 02:58:39 +00002110
Meador Ingeb8897442017-01-24 02:34:00 +00002111 if (Invert)
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002112 NegFlags |= Flag;
Meador Ingeb8897442017-01-24 02:34:00 +00002113 else
2114 Flags |= Flag;
2115 }
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002116 return {Flags, NegFlags};
Meador Ingeb8897442017-01-24 02:34:00 +00002117}
2118
Rui Ueyama07320e42016-04-20 20:13:41 +00002119void elf::readLinkerScript(MemoryBufferRef MB) {
Rui Ueyama22375f22016-11-25 18:51:54 +00002120 ScriptParser(MB).readLinkerScript();
George Rimar20b65982016-08-31 09:08:26 +00002121}
2122
2123void elf::readVersionScript(MemoryBufferRef MB) {
Rui Ueyama22375f22016-11-25 18:51:54 +00002124 ScriptParser(MB).readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00002125}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00002126
Rafael Espindolad0ebd842016-12-08 17:54:26 +00002127void elf::readDynamicList(MemoryBufferRef MB) {
2128 ScriptParser(MB).readDynamicList();
2129}
2130
Rui Ueyama07320e42016-04-20 20:13:41 +00002131template class elf::LinkerScript<ELF32LE>;
2132template class elf::LinkerScript<ELF32BE>;
2133template class elf::LinkerScript<ELF64LE>;
2134template class elf::LinkerScript<ELF64BE>;