blob: 8dfbfe8f8ed8d3332d0ce59927484f2b9544b821 [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
Rafael Espindola679828f2017-02-17 16:26:13 +000094template <class ELFT> void LinkerScript<ELFT>::setDot(Expr E, bool InSec) {
95 uintX_t Val = E(Dot);
96 if (Val < Dot) {
97 if (InSec)
98 error("unable to move location counter backward for: " + CurOutSec->Name);
99 else
100 error("unable to move location counter backward");
101 }
102 Dot = Val;
103 // Update to location counter means update to section size.
104 if (InSec)
105 CurOutSec->Size = Dot - CurOutSec->Addr;
106}
107
George Rimarb2b70972017-02-07 10:23:28 +0000108// Sets value of a symbol. Two kinds of symbols are processed: synthetic
109// symbols, whose value is an offset from beginning of section and regular
110// symbols whose value is absolute.
111template <class ELFT>
Rafael Espindola4cd73522017-02-17 16:01:51 +0000112void LinkerScript<ELFT>::assignSymbol(SymbolAssignment *Cmd, bool InSec) {
113 if (Cmd->Name == ".") {
Rafael Espindola679828f2017-02-17 16:26:13 +0000114 setDot(Cmd->Expression, InSec);
Rafael Espindola4cd73522017-02-17 16:01:51 +0000115 return;
116 }
117
George Rimarb2b70972017-02-07 10:23:28 +0000118 if (!Cmd->Sym)
Meador Inge8f1f3c42017-01-09 18:36:57 +0000119 return;
120
George Rimarb2b70972017-02-07 10:23:28 +0000121 if (auto *Body = dyn_cast<DefinedSynthetic>(Cmd->Sym)) {
122 Body->Section = Cmd->Expression.Section();
Rafael Espindolaea590d92017-02-08 15:19:03 +0000123 if (Body->Section) {
124 uint64_t VA = 0;
125 if (Body->Section->Flags & SHF_ALLOC)
126 VA = Body->Section->Addr;
127 Body->Value = Cmd->Expression(Dot) - VA;
128 }
George Rimarb2b70972017-02-07 10:23:28 +0000129 return;
Meador Inge8f1f3c42017-01-09 18:36:57 +0000130 }
George Rimarb2b70972017-02-07 10:23:28 +0000131
132 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(Dot);
Eugene Leviantdb741e72016-09-07 07:08:43 +0000133}
Meador Inge8f1f3c42017-01-09 18:36:57 +0000134
Rafael Espindola4cd73522017-02-17 16:01:51 +0000135template <class ELFT>
136void LinkerScript<ELFT>::addSymbol(SymbolAssignment *Cmd) {
Rui Ueyama16024212016-08-11 23:22:52 +0000137 if (Cmd->Name == ".")
Meador Inge8f1f3c42017-01-09 18:36:57 +0000138 return;
139
140 // If a symbol was in PROVIDE(), we need to define it only when
141 // it is a referenced undefined symbol.
Rui Ueyama16024212016-08-11 23:22:52 +0000142 SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
Meador Inge8f1f3c42017-01-09 18:36:57 +0000143 if (Cmd->Provide && (!B || B->isDefined()))
144 return;
145
146 // Otherwise, create a new symbol if one does not exist or an
147 // undefined one does exist.
148 if (Cmd->Expression.IsAbsolute())
149 Cmd->Sym = addRegular<ELFT>(Cmd);
150 else
151 Cmd->Sym = addSynthetic<ELFT>(Cmd);
George Rimarb2b70972017-02-07 10:23:28 +0000152
153 // If there are sections, then let the value be assigned later in
154 // `assignAddresses`.
155 if (!ScriptConfig->HasSections)
Rafael Espindola4cd73522017-02-17 16:01:51 +0000156 assignSymbol(Cmd);
Eugene Leviantceabe802016-08-11 07:56:43 +0000157}
158
George Rimar076fe152016-07-21 06:43:01 +0000159bool SymbolAssignment::classof(const BaseCommand *C) {
160 return C->Kind == AssignmentKind;
161}
162
163bool OutputSectionCommand::classof(const BaseCommand *C) {
164 return C->Kind == OutputSectionKind;
165}
166
George Rimareea31142016-07-21 14:26:59 +0000167bool InputSectionDescription::classof(const BaseCommand *C) {
168 return C->Kind == InputSectionKind;
169}
170
George Rimareefa7582016-08-04 09:29:31 +0000171bool AssertCommand::classof(const BaseCommand *C) {
172 return C->Kind == AssertKind;
173}
174
George Rimare38cbab2016-09-26 19:22:50 +0000175bool BytesDataCommand::classof(const BaseCommand *C) {
176 return C->Kind == BytesDataKind;
177}
178
Eugene Zelenko22886a22016-11-05 01:00:56 +0000179template <class ELFT> LinkerScript<ELFT>::LinkerScript() = default;
180template <class ELFT> LinkerScript<ELFT>::~LinkerScript() = default;
Rui Ueyamaf34d0e02016-08-12 01:24:53 +0000181
Rui Ueyamae0be2902016-11-21 02:10:12 +0000182template <class ELFT> static StringRef basename(InputSectionBase<ELFT> *S) {
183 if (S->getFile())
184 return sys::path::filename(S->getFile()->getName());
185 return "";
186}
187
Rui Ueyama07320e42016-04-20 20:13:41 +0000188template <class ELFT>
189bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) {
Rui Ueyamae0be2902016-11-21 02:10:12 +0000190 for (InputSectionDescription *ID : Opt.KeptSections)
191 if (ID->FilePat.match(basename(S)))
192 for (SectionPattern &P : ID->SectionPatterns)
193 if (P.SectionPat.match(S->Name))
194 return true;
George Rimareea31142016-07-21 14:26:59 +0000195 return false;
196}
197
George Rimar575208c2016-09-15 19:15:12 +0000198static bool comparePriority(InputSectionData *A, InputSectionData *B) {
199 return getPriority(A->Name) < getPriority(B->Name);
200}
201
Rafael Espindolac0028d32016-09-08 20:47:52 +0000202static bool compareName(InputSectionData *A, InputSectionData *B) {
Rafael Espindola042a3f22016-09-08 14:06:08 +0000203 return A->Name < B->Name;
Rui Ueyama742c3832016-08-04 22:27:00 +0000204}
George Rimar350ece42016-08-03 08:35:59 +0000205
Rafael Espindolac0028d32016-09-08 20:47:52 +0000206static bool compareAlignment(InputSectionData *A, InputSectionData *B) {
Rui Ueyama742c3832016-08-04 22:27:00 +0000207 // ">" is not a mistake. Larger alignments are placed before smaller
208 // alignments in order to reduce the amount of padding necessary.
209 // This is compatible with GNU.
210 return A->Alignment > B->Alignment;
211}
George Rimar350ece42016-08-03 08:35:59 +0000212
Rafael Espindolac0028d32016-09-08 20:47:52 +0000213static std::function<bool(InputSectionData *, InputSectionData *)>
George Rimarbe394db2016-09-16 20:21:55 +0000214getComparator(SortSectionPolicy K) {
215 switch (K) {
216 case SortSectionPolicy::Alignment:
217 return compareAlignment;
218 case SortSectionPolicy::Name:
Rafael Espindolac0028d32016-09-08 20:47:52 +0000219 return compareName;
George Rimarbe394db2016-09-16 20:21:55 +0000220 case SortSectionPolicy::Priority:
221 return comparePriority;
222 default:
223 llvm_unreachable("unknown sort policy");
224 }
Rui Ueyama742c3832016-08-04 22:27:00 +0000225}
George Rimar0702c4e2016-07-29 15:32:46 +0000226
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000227template <class ELFT>
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000228static bool matchConstraints(ArrayRef<InputSectionBase<ELFT> *> Sections,
George Rimar06ae6832016-08-12 09:07:57 +0000229 ConstraintKind Kind) {
George Rimar8f66df92016-08-12 20:38:20 +0000230 if (Kind == ConstraintKind::NoConstraint)
231 return true;
Rafael Espindolae746e522016-09-21 18:33:44 +0000232 bool IsRW = llvm::any_of(Sections, [=](InputSectionData *Sec2) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000233 auto *Sec = static_cast<InputSectionBase<ELFT> *>(Sec2);
Rafael Espindola1854a8e2016-10-26 12:36:56 +0000234 return Sec->Flags & SHF_WRITE;
George Rimar06ae6832016-08-12 09:07:57 +0000235 });
Rafael Espindolae746e522016-09-21 18:33:44 +0000236 return (IsRW && Kind == ConstraintKind::ReadWrite) ||
237 (!IsRW && Kind == ConstraintKind::ReadOnly);
George Rimar06ae6832016-08-12 09:07:57 +0000238}
239
George Rimar07171f22016-09-21 15:56:44 +0000240static void sortSections(InputSectionData **Begin, InputSectionData **End,
Rui Ueyamaee924702016-09-20 19:42:41 +0000241 SortSectionPolicy K) {
242 if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
George Rimar07171f22016-09-21 15:56:44 +0000243 std::stable_sort(Begin, End, getComparator(K));
Rui Ueyamaee924702016-09-20 19:42:41 +0000244}
245
Rafael Espindolad3190792016-09-16 15:10:23 +0000246// Compute and remember which sections the InputSectionDescription matches.
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000247template <class ELFT>
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000248void LinkerScript<ELFT>::computeInputSections(InputSectionDescription *I) {
Rui Ueyama4dc07be2016-09-17 02:23:40 +0000249 // Collects all sections that satisfy constraints of I
250 // and attach them to I.
251 for (SectionPattern &Pat : I->SectionPatterns) {
George Rimar07171f22016-09-21 15:56:44 +0000252 size_t SizeBefore = I->Sections.size();
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000253
254 for (InputSectionBase<ELFT> *S : Symtab<ELFT>::X->Sections) {
Rui Ueyamaf94efdd2016-11-20 23:15:52 +0000255 if (!S->Live || S->Assigned)
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000256 continue;
Rafael Espindola908a3d32017-02-16 14:36:09 +0000257 // For -emit-relocs we have to ignore entries like
258 // .rela.dyn : { *(.rela.data) }
259 // which are common because they are in the default bfd script.
260 if (S->Type == SHT_REL || S->Type == SHT_RELA)
261 continue;
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000262
Rui Ueyamae0be2902016-11-21 02:10:12 +0000263 StringRef Filename = basename(S);
264 if (!I->FilePat.match(Filename) || Pat.ExcludedFilePat.match(Filename))
265 continue;
266 if (!Pat.SectionPat.match(S->Name))
267 continue;
268 I->Sections.push_back(S);
269 S->Assigned = true;
George Rimar395281c2016-09-16 17:42:10 +0000270 }
Rafael Espindolad3190792016-09-16 15:10:23 +0000271
George Rimar07171f22016-09-21 15:56:44 +0000272 // Sort sections as instructed by SORT-family commands and --sort-section
273 // option. Because SORT-family commands can be nested at most two depth
274 // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
275 // line option is respected even if a SORT command is given, the exact
276 // behavior we have here is a bit complicated. Here are the rules.
277 //
278 // 1. If two SORT commands are given, --sort-section is ignored.
279 // 2. If one SORT command is given, and if it is not SORT_NONE,
280 // --sort-section is handled as an inner SORT command.
281 // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
282 // 4. If no SORT command is given, sort according to --sort-section.
283 InputSectionData **Begin = I->Sections.data() + SizeBefore;
284 InputSectionData **End = I->Sections.data() + I->Sections.size();
285 if (Pat.SortOuter != SortSectionPolicy::None) {
286 if (Pat.SortInner == SortSectionPolicy::Default)
287 sortSections(Begin, End, Config->SortSection);
288 else
289 sortSections(Begin, End, Pat.SortInner);
290 sortSections(Begin, End, Pat.SortOuter);
291 }
Rui Ueyamaee924702016-09-20 19:42:41 +0000292 }
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000293}
294
295template <class ELFT>
296void LinkerScript<ELFT>::discard(ArrayRef<InputSectionBase<ELFT> *> V) {
297 for (InputSectionBase<ELFT> *S : V) {
298 S->Live = false;
Rafael Espindolaecbfd872017-02-17 17:35:07 +0000299 if (S == In<ELFT>::ShStrTab)
300 error("discarding .shstrtab section is not allowed");
George Rimar647c1682017-02-17 19:34:05 +0000301 discard(S->DependentSections);
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000302 }
303}
304
George Rimar06ae6832016-08-12 09:07:57 +0000305template <class ELFT>
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000306std::vector<InputSectionBase<ELFT> *>
George Rimar06ae6832016-08-12 09:07:57 +0000307LinkerScript<ELFT>::createInputSectionList(OutputSectionCommand &OutCmd) {
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000308 std::vector<InputSectionBase<ELFT> *> Ret;
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000309
George Rimar06ae6832016-08-12 09:07:57 +0000310 for (const std::unique_ptr<BaseCommand> &Base : OutCmd.Commands) {
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000311 auto *Cmd = dyn_cast<InputSectionDescription>(Base.get());
312 if (!Cmd)
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000313 continue;
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000314 computeInputSections(Cmd);
Rafael Espindolad3190792016-09-16 15:10:23 +0000315 for (InputSectionData *S : Cmd->Sections)
316 Ret.push_back(static_cast<InputSectionBase<ELFT> *>(S));
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000317 }
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000318
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000319 return Ret;
320}
321
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000322template <class ELFT>
Eugene Leviant20d03192016-09-16 15:30:47 +0000323void LinkerScript<ELFT>::processCommands(OutputSectionFactory<ELFT> &Factory) {
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000324 for (unsigned I = 0; I < Opt.Commands.size(); ++I) {
325 auto Iter = Opt.Commands.begin() + I;
326 const std::unique_ptr<BaseCommand> &Base1 = *Iter;
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000327
328 // Handle symbol assignments outside of any output section.
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000329 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base1.get())) {
Rafael Espindola4cd73522017-02-17 16:01:51 +0000330 addSymbol(Cmd);
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000331 continue;
332 }
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000333
Eugene Leviant20d03192016-09-16 15:30:47 +0000334 if (auto *Cmd = dyn_cast<AssertCommand>(Base1.get())) {
335 // If we don't have SECTIONS then output sections have already been
George Rimar194470cd2016-09-17 19:21:05 +0000336 // created by Writer<ELFT>. The LinkerScript<ELFT>::assignAddresses
Eugene Leviant20d03192016-09-16 15:30:47 +0000337 // will not be called, so ASSERT should be evaluated now.
338 if (!Opt.HasSections)
339 Cmd->Expression(0);
340 continue;
341 }
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000342
Eugene Leviantceabe802016-08-11 07:56:43 +0000343 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000344 std::vector<InputSectionBase<ELFT> *> V = createInputSectionList(*Cmd);
345
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000346 // The output section name `/DISCARD/' is special.
347 // Any input section assigned to it is discarded.
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000348 if (Cmd->Name == "/DISCARD/") {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000349 discard(V);
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000350 continue;
351 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000352
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000353 // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive
354 // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input
355 // sections satisfy a given constraint. If not, a directive is handled
356 // as if it wasn't present from the beginning.
357 //
358 // Because we'll iterate over Commands many more times, the easiest
359 // way to "make it as if it wasn't present" is to just remove it.
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000360 if (!matchConstraints<ELFT>(V, Cmd->Constraint)) {
361 for (InputSectionBase<ELFT> *S : V)
Rui Ueyamaf94efdd2016-11-20 23:15:52 +0000362 S->Assigned = false;
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000363 Opt.Commands.erase(Iter);
George Rimardfbbbc82016-09-17 09:50:10 +0000364 --I;
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000365 continue;
366 }
367
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000368 // A directive may contain symbol definitions like this:
369 // ".foo : { ...; bar = .; }". Handle them.
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000370 for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
371 if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base.get()))
Rafael Espindola4cd73522017-02-17 16:01:51 +0000372 addSymbol(OutCmd);
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000373
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000374 // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign
375 // is given, input sections are aligned to that value, whether the
376 // given value is larger or smaller than the original section alignment.
377 if (Cmd->SubalignExpr) {
378 uint32_t Subalign = Cmd->SubalignExpr(0);
379 for (InputSectionBase<ELFT> *S : V)
380 S->Alignment = Subalign;
George Rimardb24d9c2016-08-19 15:18:23 +0000381 }
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000382
383 // Add input sections to an output section.
384 for (InputSectionBase<ELFT> *S : V)
Rafael Espindola82902742017-02-16 17:32:26 +0000385 Factory.addInputSec(S, Cmd->Name);
Eugene Leviantceabe802016-08-11 07:56:43 +0000386 }
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000387 }
Eugene Leviant20d03192016-09-16 15:30:47 +0000388}
Eugene Leviante63d81b2016-07-20 14:43:20 +0000389
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000390// Add sections that didn't match any sections command.
Eugene Leviant20d03192016-09-16 15:30:47 +0000391template <class ELFT>
George Rimar93c64022016-12-15 15:38:09 +0000392void LinkerScript<ELFT>::addOrphanSections(
393 OutputSectionFactory<ELFT> &Factory) {
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000394 for (InputSectionBase<ELFT> *S : Symtab<ELFT>::X->Sections)
Rafael Espindola8f9026b2016-11-08 18:23:02 +0000395 if (S->Live && !S->OutSec)
Rafael Espindola82902742017-02-16 17:32:26 +0000396 Factory.addInputSec(S, getOutputSectionName(S->Name));
Eugene Leviante63d81b2016-07-20 14:43:20 +0000397}
398
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000399template <class ELFT> static bool isTbss(OutputSectionBase *Sec) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000400 return (Sec->Flags & SHF_TLS) && Sec->Type == SHT_NOBITS;
Rafael Espindolaa940e532016-09-22 12:35:44 +0000401}
402
Rafael Espindolad3190792016-09-16 15:10:23 +0000403template <class ELFT> void LinkerScript<ELFT>::output(InputSection<ELFT> *S) {
404 if (!AlreadyOutputIS.insert(S).second)
405 return;
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000406 bool IsTbss = isTbss<ELFT>(CurOutSec);
Eugene Leviant20889c52016-08-31 08:13:33 +0000407
Rafael Espindolad3190792016-09-16 15:10:23 +0000408 uintX_t Pos = IsTbss ? Dot + ThreadBssOffset : Dot;
409 Pos = alignTo(Pos, S->Alignment);
Rafael Espindola04a2e342016-11-09 01:42:41 +0000410 S->OutSecOff = Pos - CurOutSec->Addr;
Rafael Espindolad3190792016-09-16 15:10:23 +0000411 Pos += S->getSize();
412
413 // Update output section size after adding each section. This is so that
414 // SIZEOF works correctly in the case below:
415 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
Rafael Espindola04a2e342016-11-09 01:42:41 +0000416 CurOutSec->Size = Pos - CurOutSec->Addr;
Rafael Espindolad3190792016-09-16 15:10:23 +0000417
Meador Ingeb8897442017-01-24 02:34:00 +0000418 // If there is a memory region associated with this input section, then
419 // place the section in that region and update the region index.
420 if (CurMemRegion) {
421 CurMemRegion->Offset += CurOutSec->Size;
422 uint64_t CurSize = CurMemRegion->Offset - CurMemRegion->Origin;
423 if (CurSize > CurMemRegion->Length) {
424 uint64_t OverflowAmt = CurSize - CurMemRegion->Length;
425 error("section '" + CurOutSec->Name + "' will not fit in region '" +
426 CurMemRegion->Name + "': overflowed by " + Twine(OverflowAmt) +
427 " bytes");
428 }
429 }
430
Rafael Espindola7252ae52016-09-22 12:00:08 +0000431 if (IsTbss)
432 ThreadBssOffset = Pos - Dot;
433 else
Rafael Espindolad3190792016-09-16 15:10:23 +0000434 Dot = Pos;
435}
436
437template <class ELFT> void LinkerScript<ELFT>::flush() {
Rafael Espindola65499b92016-09-23 20:10:47 +0000438 if (!CurOutSec || !AlreadyOutputOS.insert(CurOutSec).second)
439 return;
440 if (auto *OutSec = dyn_cast<OutputSection<ELFT>>(CurOutSec)) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000441 for (InputSection<ELFT> *I : OutSec->Sections)
442 output(I);
Rafael Espindola65499b92016-09-23 20:10:47 +0000443 } else {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000444 Dot += CurOutSec->Size;
Eugene Leviant20889c52016-08-31 08:13:33 +0000445 }
446}
447
448template <class ELFT>
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000449void LinkerScript<ELFT>::switchTo(OutputSectionBase *Sec) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000450 if (CurOutSec == Sec)
451 return;
452 if (AlreadyOutputOS.count(Sec))
453 return;
454
455 flush();
456 CurOutSec = Sec;
457
Rafael Espindola04a2e342016-11-09 01:42:41 +0000458 Dot = alignTo(Dot, CurOutSec->Addralign);
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000459 CurOutSec->Addr = isTbss<ELFT>(CurOutSec) ? Dot + ThreadBssOffset : Dot;
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000460
461 // If neither AT nor AT> is specified for an allocatable section, the linker
462 // will set the LMA such that the difference between VMA and LMA for the
463 // section is the same as the preceding output section in the same region
464 // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
465 CurOutSec->setLMAOffset(LMAOffset);
Rafael Espindolad3190792016-09-16 15:10:23 +0000466}
467
468template <class ELFT> void LinkerScript<ELFT>::process(BaseCommand &Base) {
George Rimare38cbab2016-09-26 19:22:50 +0000469 // This handles the assignments to symbol or to a location counter (.)
Rafael Espindolad3190792016-09-16 15:10:23 +0000470 if (auto *AssignCmd = dyn_cast<SymbolAssignment>(&Base)) {
Rafael Espindola4cd73522017-02-17 16:01:51 +0000471 assignSymbol(AssignCmd, true);
Eugene Leviantceabe802016-08-11 07:56:43 +0000472 return;
Rui Ueyama2de509c2016-08-12 00:55:08 +0000473 }
George Rimare38cbab2016-09-26 19:22:50 +0000474
475 // Handle BYTE(), SHORT(), LONG(), or QUAD().
476 if (auto *DataCmd = dyn_cast<BytesDataCommand>(&Base)) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000477 DataCmd->Offset = Dot - CurOutSec->Addr;
George Rimare38cbab2016-09-26 19:22:50 +0000478 Dot += DataCmd->Size;
Rafael Espindola04a2e342016-11-09 01:42:41 +0000479 CurOutSec->Size = Dot - CurOutSec->Addr;
George Rimare38cbab2016-09-26 19:22:50 +0000480 return;
481 }
482
Meador Ingeb2d99d62016-11-22 18:01:50 +0000483 if (auto *AssertCmd = dyn_cast<AssertCommand>(&Base)) {
484 AssertCmd->Expression(Dot);
485 return;
486 }
487
George Rimare38cbab2016-09-26 19:22:50 +0000488 // It handles single input section description command,
489 // calculates and assigns the offsets for each section and also
490 // updates the output section size.
Rafael Espindolad3190792016-09-16 15:10:23 +0000491 auto &ICmd = cast<InputSectionDescription>(Base);
492 for (InputSectionData *ID : ICmd.Sections) {
George Rimar3fb5a6d2016-11-29 16:05:27 +0000493 // We tentatively added all synthetic sections at the beginning and removed
494 // empty ones afterwards (because there is no way to know whether they were
495 // going be empty or not other than actually running linker scripts.)
496 // We need to ignore remains of empty sections.
497 if (auto *Sec = dyn_cast<SyntheticSection<ELFT>>(ID))
498 if (Sec->empty())
499 continue;
500
Rafael Espindolad3190792016-09-16 15:10:23 +0000501 auto *IB = static_cast<InputSectionBase<ELFT> *>(ID);
502 switchTo(IB->OutSec);
503 if (auto *I = dyn_cast<InputSection<ELFT>>(IB))
504 output(I);
Rafael Espindola65499b92016-09-23 20:10:47 +0000505 else
506 flush();
Eugene Leviantceabe802016-08-11 07:56:43 +0000507 }
508}
509
George Rimar8f66df92016-08-12 20:38:20 +0000510template <class ELFT>
Rafael Espindola2b074552017-02-03 22:27:05 +0000511static OutputSectionBase *
512findSection(StringRef Name, const std::vector<OutputSectionBase *> &Sections) {
513 auto End = Sections.end();
514 auto HasName = [=](OutputSectionBase *Sec) { return Sec->getName() == Name; };
515 auto I = std::find_if(Sections.begin(), End, HasName);
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000516 std::vector<OutputSectionBase *> Ret;
Rafael Espindola2b074552017-02-03 22:27:05 +0000517 if (I == End)
518 return nullptr;
519 assert(std::find_if(I + 1, End, HasName) == End);
520 return *I;
George Rimar8f66df92016-08-12 20:38:20 +0000521}
522
Meador Ingeb8897442017-01-24 02:34:00 +0000523// This function searches for a memory region to place the given output
524// section in. If found, a pointer to the appropriate memory region is
525// returned. Otherwise, a nullptr is returned.
526template <class ELFT>
527MemoryRegion *LinkerScript<ELFT>::findMemoryRegion(OutputSectionCommand *Cmd,
528 OutputSectionBase *Sec) {
529 // If a memory region name was specified in the output section command,
530 // then try to find that region first.
531 if (!Cmd->MemoryRegionName.empty()) {
532 auto It = Opt.MemoryRegions.find(Cmd->MemoryRegionName);
533 if (It != Opt.MemoryRegions.end())
534 return &It->second;
535 error("memory region '" + Cmd->MemoryRegionName + "' not declared");
536 return nullptr;
537 }
538
539 // The memory region name is empty, thus a suitable region must be
540 // searched for in the region map. If the region map is empty, just
541 // return. Note that this check doesn't happen at the very beginning
542 // so that uses of undeclared regions can be caught.
543 if (!Opt.MemoryRegions.size())
544 return nullptr;
545
546 // See if a region can be found by matching section flags.
547 for (auto &MRI : Opt.MemoryRegions) {
548 MemoryRegion &MR = MRI.second;
Rui Ueyama8a8a9532017-01-26 02:58:59 +0000549 if ((MR.Flags & Sec->Flags) != 0 && (MR.NegFlags & Sec->Flags) == 0)
Meador Ingeb8897442017-01-24 02:34:00 +0000550 return &MR;
551 }
552
553 // Otherwise, no suitable region was found.
554 if (Sec->Flags & SHF_ALLOC)
555 error("no memory region specified for section '" + Sec->Name + "'");
556 return nullptr;
557}
558
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000559// This function assigns offsets to input sections and an output section
560// for a single sections command (e.g. ".text { *(.text); }").
Rafael Espindolad3190792016-09-16 15:10:23 +0000561template <class ELFT>
562void LinkerScript<ELFT>::assignOffsets(OutputSectionCommand *Cmd) {
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000563 if (Cmd->LMAExpr)
564 LMAOffset = Cmd->LMAExpr(Dot) - Dot;
Rafael Espindola2b074552017-02-03 22:27:05 +0000565 OutputSectionBase *Sec = findSection<ELFT>(Cmd->Name, *OutputSections);
566 if (!Sec)
Rafael Espindolad3190792016-09-16 15:10:23 +0000567 return;
Meador Ingeb8897442017-01-24 02:34:00 +0000568
Rafael Espindola679828f2017-02-17 16:26:13 +0000569 if (Cmd->AddrExpr && Sec->Flags & SHF_ALLOC)
570 setDot(Cmd->AddrExpr);
571
Petr Hosek165088a2017-02-07 23:42:31 +0000572 // Handle align (e.g. ".foo : ALIGN(16) { ... }").
573 if (Cmd->AlignExpr)
574 Sec->updateAlignment(Cmd->AlignExpr(0));
575
Meador Ingeb8897442017-01-24 02:34:00 +0000576 // Try and find an appropriate memory region to assign offsets in.
577 CurMemRegion = findMemoryRegion(Cmd, Sec);
578 if (CurMemRegion)
579 Dot = CurMemRegion->Offset;
580 switchTo(Sec);
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000581
Rafael Espindolad3190792016-09-16 15:10:23 +0000582 // Find the last section output location. We will output orphan sections
583 // there so that end symbols point to the correct location.
584 auto E = std::find_if(Cmd->Commands.rbegin(), Cmd->Commands.rend(),
585 [](const std::unique_ptr<BaseCommand> &Cmd) {
586 return !isa<SymbolAssignment>(*Cmd);
587 })
588 .base();
589 for (auto I = Cmd->Commands.begin(); I != E; ++I)
590 process(**I);
Rafael Espindola65499b92016-09-23 20:10:47 +0000591 flush();
George Rimarb31dd372016-09-19 13:27:31 +0000592 std::for_each(E, Cmd->Commands.end(),
593 [this](std::unique_ptr<BaseCommand> &B) { process(*B.get()); });
Rafael Espindolad3190792016-09-16 15:10:23 +0000594}
595
Rafael Espindola07fe6122016-11-14 14:23:35 +0000596template <class ELFT> void LinkerScript<ELFT>::removeEmptyCommands() {
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000597 // It is common practice to use very generic linker scripts. So for any
598 // given run some of the output sections in the script will be empty.
599 // We could create corresponding empty output sections, but that would
600 // clutter the output.
601 // We instead remove trivially empty sections. The bfd linker seems even
602 // more aggressive at removing them.
603 auto Pos = std::remove_if(
604 Opt.Commands.begin(), Opt.Commands.end(),
605 [&](const std::unique_ptr<BaseCommand> &Base) {
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000606 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
Rafael Espindola2b074552017-02-03 22:27:05 +0000607 return !findSection<ELFT>(Cmd->Name, *OutputSections);
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000608 return false;
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000609 });
610 Opt.Commands.erase(Pos, Opt.Commands.end());
Rafael Espindola07fe6122016-11-14 14:23:35 +0000611}
612
Rafael Espindola6a537372016-11-14 14:33:49 +0000613static bool isAllSectionDescription(const OutputSectionCommand &Cmd) {
614 for (const std::unique_ptr<BaseCommand> &I : Cmd.Commands)
615 if (!isa<InputSectionDescription>(*I))
616 return false;
617 return true;
618}
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000619
Rafael Espindola6a537372016-11-14 14:33:49 +0000620template <class ELFT> void LinkerScript<ELFT>::adjustSectionsBeforeSorting() {
Rafael Espindola9546fff2016-09-22 14:40:50 +0000621 // If the output section contains only symbol assignments, create a
622 // corresponding output section. The bfd linker seems to only create them if
623 // '.' is assigned to, but creating these section should not have any bad
624 // consequeces and gives us a section to put the symbol in.
625 uintX_t Flags = SHF_ALLOC;
Rafael Espindolaf93b8c22016-11-26 06:55:35 +0000626 uint32_t Type = SHT_NOBITS;
Rafael Espindola9546fff2016-09-22 14:40:50 +0000627 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
628 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
629 if (!Cmd)
630 continue;
Rafael Espindola2b074552017-02-03 22:27:05 +0000631 if (OutputSectionBase *Sec =
632 findSection<ELFT>(Cmd->Name, *OutputSections)) {
633 Flags = Sec->Flags;
634 Type = Sec->Type;
Rafael Espindola9546fff2016-09-22 14:40:50 +0000635 continue;
636 }
637
Rafael Espindola6a537372016-11-14 14:33:49 +0000638 if (isAllSectionDescription(*Cmd))
639 continue;
640
Rui Ueyama95642b92016-11-01 23:09:07 +0000641 auto *OutSec = make<OutputSection<ELFT>>(Cmd->Name, Type, Flags);
Rafael Espindola9546fff2016-09-22 14:40:50 +0000642 OutputSections->push_back(OutSec);
643 }
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000644}
645
646template <class ELFT> void LinkerScript<ELFT>::adjustSectionsAfterSorting() {
647 placeOrphanSections();
648
649 // If output section command doesn't specify any segments,
650 // and we haven't previously assigned any section to segment,
651 // then we simply assign section to the very first load segment.
652 // Below is an example of such linker script:
653 // PHDRS { seg PT_LOAD; }
654 // SECTIONS { .aaa : { *(.aaa) } }
655 std::vector<StringRef> DefPhdrs;
656 auto FirstPtLoad =
657 std::find_if(Opt.PhdrsCommands.begin(), Opt.PhdrsCommands.end(),
658 [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; });
659 if (FirstPtLoad != Opt.PhdrsCommands.end())
660 DefPhdrs.push_back(FirstPtLoad->Name);
661
662 // Walk the commands and propagate the program headers to commands that don't
663 // explicitly specify them.
664 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
665 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
666 if (!Cmd)
667 continue;
668 if (Cmd->Phdrs.empty())
669 Cmd->Phdrs = DefPhdrs;
670 else
671 DefPhdrs = Cmd->Phdrs;
672 }
Rafael Espindola6a537372016-11-14 14:33:49 +0000673
674 removeEmptyCommands();
Rafael Espindola9546fff2016-09-22 14:40:50 +0000675}
676
Rafael Espindola15c57952016-09-22 18:05:49 +0000677// When placing orphan sections, we want to place them after symbol assignments
678// so that an orphan after
679// begin_foo = .;
680// foo : { *(foo) }
681// end_foo = .;
682// doesn't break the intended meaning of the begin/end symbols.
683// We don't want to go over sections since Writer<ELFT>::sortSections is the
684// one in charge of deciding the order of the sections.
685// We don't want to go over alignments, since doing so in
686// rx_sec : { *(rx_sec) }
687// . = ALIGN(0x1000);
688// /* The RW PT_LOAD starts here*/
689// rw_sec : { *(rw_sec) }
690// would mean that the RW PT_LOAD would become unaligned.
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000691static bool shouldSkip(const BaseCommand &Cmd) {
Rafael Espindola15c57952016-09-22 18:05:49 +0000692 if (isa<OutputSectionCommand>(Cmd))
693 return false;
694 const auto *Assign = dyn_cast<SymbolAssignment>(&Cmd);
695 if (!Assign)
696 return true;
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000697 return Assign->Name != ".";
Rafael Espindola15c57952016-09-22 18:05:49 +0000698}
699
Rui Ueyama6697ec22017-02-02 23:26:12 +0000700// Orphan sections are sections present in the input files which are
701// not explicitly placed into the output file by the linker script.
702//
703// When the control reaches this function, Opt.Commands contains
704// output section commands for non-orphan sections only. This function
705// adds new elements for orphan sections to Opt.Commands so that all
706// sections are explicitly handled by Opt.Commands.
707//
708// Writer<ELFT>::sortSections has already sorted output sections.
709// What we need to do is to scan OutputSections vector and
710// Opt.Commands in parallel to find orphan sections. If there is an
711// output section that doesn't have a corresponding entry in
712// Opt.Commands, we will insert a new entry to Opt.Commands.
713//
714// There is some ambiguity as to where exactly a new entry should be
715// inserted, because Opt.Commands contains not only output section
716// commands but other types of commands such as symbol assignment
717// expressions. There's no correct answer here due to the lack of the
718// formal specification of the linker script. We use heuristics to
719// determine whether a new output command should be added before or
720// after another commands. For the details, look at shouldSkip
721// function.
George Rimar93c64022016-12-15 15:38:09 +0000722template <class ELFT> void LinkerScript<ELFT>::placeOrphanSections() {
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000723 // The OutputSections are already in the correct order.
724 // This loops creates or moves commands as needed so that they are in the
725 // correct order.
726 int CmdIndex = 0;
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000727
728 // As a horrible special case, skip the first . assignment if it is before any
729 // section. We do this because it is common to set a load address by starting
730 // the script with ". = 0xabcd" and the expectation is that every section is
731 // after that.
732 auto FirstSectionOrDotAssignment =
733 std::find_if(Opt.Commands.begin(), Opt.Commands.end(),
734 [](const std::unique_ptr<BaseCommand> &Cmd) {
735 if (isa<OutputSectionCommand>(*Cmd))
736 return true;
737 const auto *Assign = dyn_cast<SymbolAssignment>(Cmd.get());
738 if (!Assign)
739 return false;
740 return Assign->Name == ".";
741 });
742 if (FirstSectionOrDotAssignment != Opt.Commands.end()) {
743 CmdIndex = FirstSectionOrDotAssignment - Opt.Commands.begin();
744 if (isa<SymbolAssignment>(**FirstSectionOrDotAssignment))
745 ++CmdIndex;
746 }
747
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000748 for (OutputSectionBase *Sec : *OutputSections) {
George Rimar652852c2016-04-16 10:10:32 +0000749 StringRef Name = Sec->getName();
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000750
751 // Find the last spot where we can insert a command and still get the
Rafael Espindola15c57952016-09-22 18:05:49 +0000752 // correct result.
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000753 auto CmdIter = Opt.Commands.begin() + CmdIndex;
754 auto E = Opt.Commands.end();
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000755 while (CmdIter != E && shouldSkip(**CmdIter)) {
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000756 ++CmdIter;
757 ++CmdIndex;
758 }
759
760 auto Pos =
761 std::find_if(CmdIter, E, [&](const std::unique_ptr<BaseCommand> &Base) {
762 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
763 return Cmd && Cmd->Name == Name;
764 });
765 if (Pos == E) {
766 Opt.Commands.insert(CmdIter,
767 llvm::make_unique<OutputSectionCommand>(Name));
Rafael Espindola15c57952016-09-22 18:05:49 +0000768 ++CmdIndex;
769 continue;
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000770 }
Rafael Espindola15c57952016-09-22 18:05:49 +0000771
772 // Continue from where we found it.
773 CmdIndex = (Pos - Opt.Commands.begin()) + 1;
George Rimar652852c2016-04-16 10:10:32 +0000774 }
Rafael Espindola337f9032016-11-14 14:13:32 +0000775}
776
777template <class ELFT>
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000778void LinkerScript<ELFT>::assignAddresses(std::vector<PhdrEntry> &Phdrs) {
Rui Ueyama7c18c282016-04-18 21:00:40 +0000779 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rafael Espindolabe607332016-09-30 00:16:11 +0000780 Dot = 0;
George Rimar652852c2016-04-16 10:10:32 +0000781
Rafael Espindola06f47432017-02-06 22:21:46 +0000782 // A symbol can be assigned before any section is mentioned in the linker
783 // script. In an DSO, the symbol values are addresses, so the only important
784 // section values are:
785 // * SHN_UNDEF
786 // * SHN_ABS
787 // * Any value meaning a regular section.
788 // To handle that, create a dummy aether section that fills the void before
789 // the linker scripts switches to another section. It has an index of one
790 // which will map to whatever the first actual section is.
791 auto *Aether = make<OutputSectionBase>("", 0, SHF_ALLOC);
792 Aether->SectionIndex = 1;
793 switchTo(Aether);
794
George Rimar076fe152016-07-21 06:43:01 +0000795 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
796 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
Rafael Espindola4cd73522017-02-17 16:01:51 +0000797 assignSymbol(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000798 continue;
799 }
800
George Rimareefa7582016-08-04 09:29:31 +0000801 if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
802 Cmd->Expression(Dot);
803 continue;
804 }
805
George Rimar076fe152016-07-21 06:43:01 +0000806 auto *Cmd = cast<OutputSectionCommand>(Base.get());
Rafael Espindolad3190792016-09-16 15:10:23 +0000807 assignOffsets(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000808 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000809
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000810 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
Rafael Espindolaea590d92017-02-08 15:19:03 +0000811 for (OutputSectionBase *Sec : *OutputSections) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000812 if (Sec->Flags & SHF_ALLOC)
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000813 MinVA = std::min<uint64_t>(MinVA, Sec->Addr);
Rafael Espindolaea590d92017-02-08 15:19:03 +0000814 else
815 Sec->Addr = 0;
816 }
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000817
Rafael Espindola8c495e22017-01-20 20:41:18 +0000818 allocateHeaders<ELFT>(Phdrs, *OutputSections, MinVA);
George Rimar652852c2016-04-16 10:10:32 +0000819}
820
Rui Ueyama464daad2016-08-22 04:55:20 +0000821// Creates program headers as instructed by PHDRS linker script command.
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000822template <class ELFT> std::vector<PhdrEntry> LinkerScript<ELFT>::createPhdrs() {
823 std::vector<PhdrEntry> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000824
Rui Ueyama464daad2016-08-22 04:55:20 +0000825 // Process PHDRS and FILEHDR keywords because they are not
826 // real output sections and cannot be added in the following loop.
Eugene Leviantbbe38602016-07-19 09:25:43 +0000827 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000828 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000829 PhdrEntry &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000830
831 if (Cmd.HasFilehdr)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000832 Phdr.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000833 if (Cmd.HasPhdrs)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000834 Phdr.add(Out<ELFT>::ProgramHeaders);
Eugene Leviant56b21c82016-09-09 09:46:16 +0000835
836 if (Cmd.LMAExpr) {
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000837 Phdr.p_paddr = Cmd.LMAExpr(0);
Eugene Leviant56b21c82016-09-09 09:46:16 +0000838 Phdr.HasLMA = true;
839 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000840 }
841
Rui Ueyama464daad2016-08-22 04:55:20 +0000842 // Add output sections to program headers.
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000843 for (OutputSectionBase *Sec : *OutputSections) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000844 if (!(Sec->Flags & SHF_ALLOC))
Eugene Leviantbbe38602016-07-19 09:25:43 +0000845 break;
846
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000847 // Assign headers specified by linker script
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000848 for (size_t Id : getPhdrIndices(Sec->getName())) {
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000849 Ret[Id].add(Sec);
850 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000851 Ret[Id].p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000852 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000853 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000854 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000855}
856
Eugene Leviantf9bc3bd2016-08-16 06:40:58 +0000857template <class ELFT> bool LinkerScript<ELFT>::ignoreInterpSection() {
858 // Ignore .interp section in case we have PHDRS specification
859 // and PT_INTERP isn't listed.
860 return !Opt.PhdrsCommands.empty() &&
861 llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
862 return Cmd.Type == PT_INTERP;
863 }) == Opt.PhdrsCommands.end();
864}
865
George Rimar93c64022016-12-15 15:38:09 +0000866template <class ELFT> uint32_t LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000867 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
868 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
869 if (Cmd->Name == Name)
870 return Cmd->Filler;
Rui Ueyama16068ae2016-11-19 18:05:56 +0000871 return 0;
George Rimare2ee72b2016-02-26 14:48:31 +0000872}
873
George Rimare38cbab2016-09-26 19:22:50 +0000874template <class ELFT>
875static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) {
876 const endianness E = ELFT::TargetEndianness;
877
878 switch (Size) {
879 case 1:
880 *Buf = (uint8_t)Data;
881 break;
882 case 2:
883 write16<E>(Buf, Data);
884 break;
885 case 4:
886 write32<E>(Buf, Data);
887 break;
888 case 8:
889 write64<E>(Buf, Data);
890 break;
891 default:
892 llvm_unreachable("unsupported Size argument");
893 }
894}
895
896template <class ELFT>
897void LinkerScript<ELFT>::writeDataBytes(StringRef Name, uint8_t *Buf) {
898 int I = getSectionIndex(Name);
899 if (I == INT_MAX)
900 return;
901
Rui Ueyama6e68c5e2016-11-19 18:05:58 +0000902 auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I].get());
903 for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
904 if (auto *Data = dyn_cast<BytesDataCommand>(Base.get()))
Meador Inge95c7d8d2016-12-08 23:21:30 +0000905 writeInt<ELFT>(Buf + Data->Offset, Data->Expression(0), Data->Size);
George Rimare38cbab2016-09-26 19:22:50 +0000906}
907
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000908template <class ELFT> bool LinkerScript<ELFT>::hasLMA(StringRef Name) {
George Rimar8ceadb32016-08-17 07:44:19 +0000909 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
910 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000911 if (Cmd->LMAExpr && Cmd->Name == Name)
912 return true;
913 return false;
George Rimar8ceadb32016-08-17 07:44:19 +0000914}
915
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000916// Returns the index of the given section name in linker script
917// SECTIONS commands. Sections are laid out as the same order as they
918// were in the script. If a given name did not appear in the script,
919// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000920template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
Rui Ueyama6e68c5e2016-11-19 18:05:58 +0000921 for (int I = 0, E = Opt.Commands.size(); I != E; ++I)
922 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I].get()))
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000923 if (Cmd->Name == Name)
924 return I;
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000925 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000926}
927
Eugene Leviantbbe38602016-07-19 09:25:43 +0000928template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
929 return !Opt.PhdrsCommands.empty();
930}
931
George Rimar9e694502016-07-29 16:18:47 +0000932template <class ELFT>
Eugene Levianted30ce72016-11-28 09:58:04 +0000933const OutputSectionBase *LinkerScript<ELFT>::getOutputSection(const Twine &Loc,
934 StringRef Name) {
Eugene Leviantafaa9342016-11-16 09:49:39 +0000935 static OutputSectionBase FakeSec("", 0, 0);
George Rimar96659df2016-08-30 09:54:01 +0000936
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000937 for (OutputSectionBase *Sec : *OutputSections)
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000938 if (Sec->getName() == Name)
Eugene Leviantafaa9342016-11-16 09:49:39 +0000939 return Sec;
Eugene Levianted30ce72016-11-28 09:58:04 +0000940
941 error(Loc + ": undefined section " + Name);
Eugene Leviantafaa9342016-11-16 09:49:39 +0000942 return &FakeSec;
Eugene Leviant36fac7f2016-09-08 09:08:30 +0000943}
944
Rui Ueyamaedf75e72016-11-17 20:27:10 +0000945// This function is essentially the same as getOutputSection(Name)->Size,
946// but it won't print out an error message if a given section is not found.
947//
948// Linker script does not create an output section if its content is empty.
949// We want to allow SIZEOF(.foo) where .foo is a section which happened to
950// be empty. That is why this function is different from getOutputSection().
951template <class ELFT>
952uint64_t LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
953 for (OutputSectionBase *Sec : *OutputSections)
954 if (Sec->getName() == Name)
955 return Sec->Size;
956 return 0;
957}
958
George Rimar884e7862016-09-08 08:19:13 +0000959template <class ELFT> uint64_t LinkerScript<ELFT>::getHeaderSize() {
Rafael Espindola0d4b6d52016-09-22 16:47:21 +0000960 return elf::getHeaderSize<ELFT>();
George Rimare32a3592016-08-10 07:59:34 +0000961}
962
Eugene Leviantf6aeed32016-12-22 13:13:12 +0000963template <class ELFT>
964uint64_t LinkerScript<ELFT>::getSymbolValue(const Twine &Loc, StringRef S) {
George Rimar884e7862016-09-08 08:19:13 +0000965 if (SymbolBody *B = Symtab<ELFT>::X->find(S))
966 return B->getVA<ELFT>();
Eugene Leviantf6aeed32016-12-22 13:13:12 +0000967 error(Loc + ": symbol not found: " + S);
George Rimar884e7862016-09-08 08:19:13 +0000968 return 0;
969}
970
George Rimarf34f45f2016-09-23 13:17:23 +0000971template <class ELFT> bool LinkerScript<ELFT>::isDefined(StringRef S) {
972 return Symtab<ELFT>::X->find(S) != nullptr;
973}
974
Rafael Espindola2f831dc2016-10-31 19:56:37 +0000975template <class ELFT> bool LinkerScript<ELFT>::isAbsolute(StringRef S) {
976 SymbolBody *Sym = Symtab<ELFT>::X->find(S);
977 auto *DR = dyn_cast_or_null<DefinedRegular<ELFT>>(Sym);
978 return DR && !DR->Section;
979}
980
Eugene Leviantafaa9342016-11-16 09:49:39 +0000981// Gets section symbol belongs to. Symbol "." doesn't belong to any
982// specific section but isn't absolute at the same time, so we try
983// to find suitable section for it as well.
984template <class ELFT>
985const OutputSectionBase *LinkerScript<ELFT>::getSymbolSection(StringRef S) {
Rafael Espindola06f47432017-02-06 22:21:46 +0000986 if (SymbolBody *Sym = Symtab<ELFT>::X->find(S))
987 return SymbolTableSection<ELFT>::getOutputSection(Sym);
988 return CurOutSec;
Eugene Leviantafaa9342016-11-16 09:49:39 +0000989}
990
Eugene Leviantbbe38602016-07-19 09:25:43 +0000991// Returns indices of ELF headers containing specific section, identified
992// by Name. Each index is a zero based number of ELF header listed within
993// PHDRS {} script block.
994template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000995std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000996 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
997 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000998 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000999 continue;
1000
Rui Ueyama29c5a2a2016-07-26 00:27:36 +00001001 std::vector<size_t> Ret;
1002 for (StringRef PhdrName : Cmd->Phdrs)
Eugene Leviant2a942c42016-12-05 16:38:32 +00001003 Ret.push_back(getPhdrIndex(Cmd->Location, PhdrName));
Rui Ueyama29c5a2a2016-07-26 00:27:36 +00001004 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001005 }
George Rimar31d842f2016-07-20 16:43:03 +00001006 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +00001007}
1008
Rui Ueyama29c5a2a2016-07-26 00:27:36 +00001009template <class ELFT>
Eugene Leviant2a942c42016-12-05 16:38:32 +00001010size_t LinkerScript<ELFT>::getPhdrIndex(const Twine &Loc, StringRef PhdrName) {
Rui Ueyama29c5a2a2016-07-26 00:27:36 +00001011 size_t I = 0;
1012 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
1013 if (Cmd.Name == PhdrName)
1014 return I;
1015 ++I;
1016 }
Eugene Leviant2a942c42016-12-05 16:38:32 +00001017 error(Loc + ": section header '" + PhdrName + "' is not listed in PHDRS");
Rui Ueyama29c5a2a2016-07-26 00:27:36 +00001018 return 0;
1019}
1020
Rui Ueyama794366a2017-02-14 04:47:05 +00001021class elf::ScriptParser final : public ScriptLexer {
George Rimarc3794e52016-02-24 09:21:47 +00001022 typedef void (ScriptParser::*Handler)();
1023
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001024public:
Rui Ueyama22375f22016-11-25 18:51:54 +00001025 ScriptParser(MemoryBufferRef MB)
Rui Ueyama794366a2017-02-14 04:47:05 +00001026 : ScriptLexer(MB),
Rui Ueyama22375f22016-11-25 18:51:54 +00001027 IsUnderSysroot(isUnderSysroot(MB.getBufferIdentifier())) {}
George Rimarf23b2322016-02-19 10:45:45 +00001028
George Rimar20b65982016-08-31 09:08:26 +00001029 void readLinkerScript();
1030 void readVersionScript();
Rafael Espindolad0ebd842016-12-08 17:54:26 +00001031 void readDynamicList();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001032
1033private:
Rui Ueyama52a15092015-10-11 03:28:42 +00001034 void addFile(StringRef Path);
1035
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001036 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +00001037 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +00001038 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001039 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001040 void readInclude();
Meador Ingeb8897442017-01-24 02:34:00 +00001041 void readMemory();
Rui Ueyamaee592822015-10-07 00:25:09 +00001042 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +00001043 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001044 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +00001045 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +00001046 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001047 void readSections();
Rui Ueyama95769b42016-08-31 20:03:54 +00001048 void readVersion();
1049 void readVersionScriptCommand();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001050
Rui Ueyama113cdec2016-07-24 23:05:57 +00001051 SymbolAssignment *readAssignment(StringRef Name);
George Rimare38cbab2016-09-26 19:22:50 +00001052 BytesDataCommand *readBytesDataCommand(StringRef Tok);
Rui Ueyama16068ae2016-11-19 18:05:56 +00001053 uint32_t readFill();
Rui Ueyama10416562016-08-04 02:03:27 +00001054 OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
Rui Ueyama16068ae2016-11-19 18:05:56 +00001055 uint32_t readOutputSectionFiller(StringRef Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001056 std::vector<StringRef> readOutputSectionPhdrs();
George Rimara2496cb2016-08-30 09:46:59 +00001057 InputSectionDescription *readInputSectionDescription(StringRef Tok);
Eugene Leviantdb688452016-11-03 10:54:58 +00001058 StringMatcher readFilePatterns();
George Rimar07171f22016-09-21 15:56:44 +00001059 std::vector<SectionPattern> readInputSectionsList();
George Rimara2496cb2016-08-30 09:46:59 +00001060 InputSectionDescription *readInputSectionRules(StringRef FilePattern);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001061 unsigned readPhdrType();
George Rimarbe394db2016-09-16 20:21:55 +00001062 SortSectionPolicy readSortKind();
Petr Hoseka35e39c2016-08-16 01:11:16 +00001063 SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
Rafael Espindolac96da112016-11-01 11:30:45 +00001064 SymbolAssignment *readProvideOrAssignment(StringRef Tok);
George Rimar03fc0102016-07-28 07:18:23 +00001065 void readSort();
George Rimareefa7582016-08-04 09:29:31 +00001066 Expr readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001067
Rui Ueyama24e626c2017-01-26 02:58:19 +00001068 uint64_t readMemoryAssignment(StringRef, StringRef, StringRef);
1069 std::pair<uint32_t, uint32_t> readMemoryAttributes();
1070
Rui Ueyama708019c2016-07-24 18:19:40 +00001071 Expr readExpr();
1072 Expr readExpr1(Expr Lhs, int MinPrec);
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001073 StringRef readParenLiteral();
Rui Ueyama708019c2016-07-24 18:19:40 +00001074 Expr readPrimary();
1075 Expr readTernary(Expr Cond);
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001076 Expr readParenExpr();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001077
George Rimar20b65982016-08-31 09:08:26 +00001078 // For parsing version script.
Rui Ueyama12450b22016-11-18 06:30:09 +00001079 std::vector<SymbolVersion> readVersionExtern();
1080 void readAnonymousDeclaration();
Rui Ueyama95769b42016-08-31 20:03:54 +00001081 void readVersionDeclaration(StringRef VerStr);
Rui Ueyama12450b22016-11-18 06:30:09 +00001082 std::vector<SymbolVersion> readSymbols();
Rafael Espindolae999ddb2017-01-10 16:37:24 +00001083 void readLocals();
George Rimar20b65982016-08-31 09:08:26 +00001084
Rui Ueyama07320e42016-04-20 20:13:41 +00001085 ScriptConfiguration &Opt = *ScriptConfig;
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001086 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001087};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001088
Rafael Espindolad0ebd842016-12-08 17:54:26 +00001089void ScriptParser::readDynamicList() {
1090 expect("{");
1091 readAnonymousDeclaration();
1092 if (!atEOF())
1093 setError("EOF expected, but got " + next());
1094}
1095
George Rimar20b65982016-08-31 09:08:26 +00001096void ScriptParser::readVersionScript() {
Rui Ueyama95769b42016-08-31 20:03:54 +00001097 readVersionScriptCommand();
1098 if (!atEOF())
1099 setError("EOF expected, but got " + next());
1100}
1101
1102void ScriptParser::readVersionScriptCommand() {
Rui Ueyama83043f22016-10-17 16:01:53 +00001103 if (consume("{")) {
Rui Ueyama12450b22016-11-18 06:30:09 +00001104 readAnonymousDeclaration();
George Rimar20b65982016-08-31 09:08:26 +00001105 return;
1106 }
1107
Rui Ueyama95769b42016-08-31 20:03:54 +00001108 while (!atEOF() && !Error && peek() != "}") {
George Rimar20b65982016-08-31 09:08:26 +00001109 StringRef VerStr = next();
1110 if (VerStr == "{") {
Rui Ueyama95769b42016-08-31 20:03:54 +00001111 setError("anonymous version definition is used in "
1112 "combination with other version definitions");
George Rimar20b65982016-08-31 09:08:26 +00001113 return;
1114 }
1115 expect("{");
Rui Ueyama95769b42016-08-31 20:03:54 +00001116 readVersionDeclaration(VerStr);
George Rimar20b65982016-08-31 09:08:26 +00001117 }
1118}
1119
Rui Ueyama95769b42016-08-31 20:03:54 +00001120void ScriptParser::readVersion() {
1121 expect("{");
1122 readVersionScriptCommand();
1123 expect("}");
1124}
1125
George Rimar20b65982016-08-31 09:08:26 +00001126void ScriptParser::readLinkerScript() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001127 while (!atEOF()) {
1128 StringRef Tok = next();
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001129 if (Tok == ";")
1130 continue;
1131
Eugene Leviant20d03192016-09-16 15:30:47 +00001132 if (Tok == "ASSERT") {
1133 Opt.Commands.emplace_back(new AssertCommand(readAssert()));
1134 } else if (Tok == "ENTRY") {
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001135 readEntry();
1136 } else if (Tok == "EXTERN") {
1137 readExtern();
1138 } else if (Tok == "GROUP" || Tok == "INPUT") {
1139 readGroup();
1140 } else if (Tok == "INCLUDE") {
1141 readInclude();
Meador Ingeb8897442017-01-24 02:34:00 +00001142 } else if (Tok == "MEMORY") {
1143 readMemory();
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001144 } else if (Tok == "OUTPUT") {
1145 readOutput();
1146 } else if (Tok == "OUTPUT_ARCH") {
1147 readOutputArch();
1148 } else if (Tok == "OUTPUT_FORMAT") {
1149 readOutputFormat();
1150 } else if (Tok == "PHDRS") {
1151 readPhdrs();
1152 } else if (Tok == "SEARCH_DIR") {
1153 readSearchDir();
1154 } else if (Tok == "SECTIONS") {
1155 readSections();
1156 } else if (Tok == "VERSION") {
1157 readVersion();
Rafael Espindolac96da112016-11-01 11:30:45 +00001158 } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok)) {
Eugene Leviant20d03192016-09-16 15:30:47 +00001159 Opt.Commands.emplace_back(Cmd);
Petr Hoseke5d3ca52016-08-31 15:31:17 +00001160 } else {
George Rimar57610422016-03-11 14:43:02 +00001161 setError("unknown directive: " + Tok);
Petr Hoseke5d3ca52016-08-31 15:31:17 +00001162 }
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001163 }
1164}
1165
Rui Ueyama717677a2016-02-11 21:17:59 +00001166void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001167 if (IsUnderSysroot && S.startswith("/")) {
Justin Bogner5af16872016-10-17 06:08:48 +00001168 SmallString<128> PathData;
1169 StringRef Path = (Config->Sysroot + S).toStringRef(PathData);
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001170 if (sys::fs::exists(Path)) {
Justin Bogner5af16872016-10-17 06:08:48 +00001171 Driver->addFile(Saver.save(Path));
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001172 return;
1173 }
1174 }
1175
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +00001176 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +00001177 Driver->addFile(S);
1178 } else if (S.startswith("=")) {
1179 if (Config->Sysroot.empty())
1180 Driver->addFile(S.substr(1));
1181 else
1182 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
1183 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +00001184 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +00001185 } else if (sys::fs::exists(S)) {
1186 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +00001187 } else {
Rui Ueyama061f9282016-11-19 19:23:58 +00001188 if (Optional<std::string> Path = findFromSearchPaths(S))
1189 Driver->addFile(Saver.save(*Path));
Rui Ueyama025d59b2016-02-02 20:27:59 +00001190 else
Rui Ueyama061f9282016-11-19 19:23:58 +00001191 setError("unable to find " + S);
Rui Ueyama52a15092015-10-11 03:28:42 +00001192 }
1193}
1194
Rui Ueyama717677a2016-02-11 21:17:59 +00001195void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001196 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +00001197 bool Orig = Config->AsNeeded;
1198 Config->AsNeeded = true;
Rui Ueyama83043f22016-10-17 16:01:53 +00001199 while (!Error && !consume(")"))
George Rimarcd574a52016-09-09 14:35:36 +00001200 addFile(unquote(next()));
Rui Ueyama35da9b62015-10-11 20:59:12 +00001201 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001202}
1203
Rui Ueyama717677a2016-02-11 21:17:59 +00001204void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +00001205 // -e <symbol> takes predecence over ENTRY(<symbol>).
1206 expect("(");
1207 StringRef Tok = next();
1208 if (Config->Entry.empty())
1209 Config->Entry = Tok;
1210 expect(")");
1211}
1212
Rui Ueyama717677a2016-02-11 21:17:59 +00001213void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +00001214 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001215 while (!Error && !consume(")"))
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001216 Config->Undefined.push_back(next());
George Rimar83f406c2015-10-19 17:35:12 +00001217}
1218
Rui Ueyama717677a2016-02-11 21:17:59 +00001219void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001220 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001221 while (!Error && !consume(")")) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001222 StringRef Tok = next();
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001223 if (Tok == "AS_NEEDED")
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001224 readAsNeeded();
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001225 else
George Rimarcd574a52016-09-09 14:35:36 +00001226 addFile(unquote(Tok));
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001227 }
1228}
1229
Rui Ueyama717677a2016-02-11 21:17:59 +00001230void ScriptParser::readInclude() {
George Rimard4500652016-12-21 09:42:25 +00001231 StringRef Tok = unquote(next());
Rui Ueyamaec1c75e2017-01-09 01:42:02 +00001232
George Rimard4500652016-12-21 09:42:25 +00001233 // https://sourceware.org/binutils/docs/ld/File-Commands.html:
1234 // The file will be searched for in the current directory, and in any
1235 // directory specified with the -L option.
Rui Ueyamaec1c75e2017-01-09 01:42:02 +00001236 if (sys::fs::exists(Tok)) {
1237 if (Optional<MemoryBufferRef> MB = readFile(Tok))
1238 tokenize(*MB);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001239 return;
1240 }
Rui Ueyamaec1c75e2017-01-09 01:42:02 +00001241 if (Optional<std::string> Path = findFromSearchPaths(Tok)) {
1242 if (Optional<MemoryBufferRef> MB = readFile(*Path))
1243 tokenize(*MB);
1244 return;
1245 }
1246 setError("cannot open " + Tok);
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001247}
1248
Rui Ueyama717677a2016-02-11 21:17:59 +00001249void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +00001250 // -o <file> takes predecence over OUTPUT(<file>).
1251 expect("(");
1252 StringRef Tok = next();
1253 if (Config->OutputFile.empty())
George Rimarcd574a52016-09-09 14:35:36 +00001254 Config->OutputFile = unquote(Tok);
Rui Ueyamaee592822015-10-07 00:25:09 +00001255 expect(")");
1256}
1257
Rui Ueyama717677a2016-02-11 21:17:59 +00001258void ScriptParser::readOutputArch() {
George Rimar4e01c3e2017-02-08 09:59:06 +00001259 // OUTPUT_ARCH is ignored for now.
Davide Italiano9159ce92015-10-12 21:50:08 +00001260 expect("(");
George Rimar4e01c3e2017-02-08 09:59:06 +00001261 while (!Error && !consume(")"))
1262 skip();
Davide Italiano9159ce92015-10-12 21:50:08 +00001263}
1264
Rui Ueyama717677a2016-02-11 21:17:59 +00001265void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001266 // Error checking only for now.
1267 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001268 skip();
Davide Italiano6836c612015-10-12 21:08:41 +00001269 StringRef Tok = next();
1270 if (Tok == ")")
George Rimar6c55f0e2016-09-08 08:20:30 +00001271 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +00001272 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +00001273 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001274 return;
1275 }
Justin Bogner5424e7c2016-10-17 06:21:13 +00001276 skip();
Davide Italiano6836c612015-10-12 21:08:41 +00001277 expect(",");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001278 skip();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001279 expect(")");
1280}
1281
Eugene Leviantbbe38602016-07-19 09:25:43 +00001282void ScriptParser::readPhdrs() {
1283 expect("{");
Rui Ueyama83043f22016-10-17 16:01:53 +00001284 while (!Error && !consume("}")) {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001285 StringRef Tok = next();
Eugene Leviant56b21c82016-09-09 09:46:16 +00001286 Opt.PhdrsCommands.push_back(
1287 {Tok, PT_NULL, false, false, UINT_MAX, nullptr});
Eugene Leviantbbe38602016-07-19 09:25:43 +00001288 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
1289
1290 PhdrCmd.Type = readPhdrType();
1291 do {
1292 Tok = next();
1293 if (Tok == ";")
1294 break;
1295 if (Tok == "FILEHDR")
1296 PhdrCmd.HasFilehdr = true;
1297 else if (Tok == "PHDRS")
1298 PhdrCmd.HasPhdrs = true;
Eugene Leviant56b21c82016-09-09 09:46:16 +00001299 else if (Tok == "AT")
1300 PhdrCmd.LMAExpr = readParenExpr();
Eugene Leviant865bf862016-07-21 10:43:25 +00001301 else if (Tok == "FLAGS") {
1302 expect("(");
Rafael Espindolaeb685cd2016-08-02 22:14:57 +00001303 // Passing 0 for the value of dot is a bit of a hack. It means that
1304 // we accept expressions like ".|1".
1305 PhdrCmd.Flags = readExpr()(0);
Eugene Leviant865bf862016-07-21 10:43:25 +00001306 expect(")");
1307 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +00001308 setError("unexpected header attribute: " + Tok);
1309 } while (!Error);
1310 }
1311}
1312
Rui Ueyama717677a2016-02-11 21:17:59 +00001313void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +00001314 expect("(");
Rui Ueyama86c5fb82016-09-08 23:26:54 +00001315 StringRef Tok = next();
Rui Ueyama6c7ad132016-09-02 19:20:33 +00001316 if (!Config->Nostdlib)
George Rimarcd574a52016-09-09 14:35:36 +00001317 Config->SearchPaths.push_back(unquote(Tok));
Davide Italiano68a39a62015-10-08 17:51:41 +00001318 expect(")");
1319}
1320
Rui Ueyama717677a2016-02-11 21:17:59 +00001321void ScriptParser::readSections() {
Eugene Leviante05336ff2016-09-14 08:32:36 +00001322 Opt.HasSections = true;
George Rimar18a30962016-11-28 10:11:10 +00001323 // -no-rosegment is used to avoid placing read only non-executable sections in
1324 // their own segment. We do the same if SECTIONS command is present in linker
1325 // script. See comment for computeFlags().
1326 Config->SingleRoRx = true;
1327
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001328 expect("{");
Rui Ueyama83043f22016-10-17 16:01:53 +00001329 while (!Error && !consume("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +00001330 StringRef Tok = next();
Rafael Espindolac96da112016-11-01 11:30:45 +00001331 BaseCommand *Cmd = readProvideOrAssignment(Tok);
Eugene Leviantceabe802016-08-11 07:56:43 +00001332 if (!Cmd) {
1333 if (Tok == "ASSERT")
1334 Cmd = new AssertCommand(readAssert());
1335 else
1336 Cmd = readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +00001337 }
Rui Ueyama10416562016-08-04 02:03:27 +00001338 Opt.Commands.emplace_back(Cmd);
George Rimar652852c2016-04-16 10:10:32 +00001339 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001340}
1341
Rui Ueyama708019c2016-07-24 18:19:40 +00001342static int precedence(StringRef Op) {
1343 return StringSwitch<int>(Op)
Rui Ueyama0120e3f2016-09-23 18:06:51 +00001344 .Cases("*", "/", 5)
1345 .Cases("+", "-", 4)
1346 .Cases("<<", ">>", 3)
Rui Ueyama9c4ac5f2016-09-23 22:22:34 +00001347 .Cases("<", "<=", ">", ">=", "==", "!=", 2)
Rui Ueyama0120e3f2016-09-23 18:06:51 +00001348 .Cases("&", "|", 1)
Rui Ueyama708019c2016-07-24 18:19:40 +00001349 .Default(-1);
1350}
1351
Eugene Leviantdb688452016-11-03 10:54:58 +00001352StringMatcher ScriptParser::readFilePatterns() {
Rui Ueyama10416562016-08-04 02:03:27 +00001353 std::vector<StringRef> V;
Rui Ueyama83043f22016-10-17 16:01:53 +00001354 while (!Error && !consume(")"))
Rui Ueyama10416562016-08-04 02:03:27 +00001355 V.push_back(next());
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001356 return StringMatcher(V);
George Rimar0702c4e2016-07-29 15:32:46 +00001357}
1358
George Rimarbe394db2016-09-16 20:21:55 +00001359SortSectionPolicy ScriptParser::readSortKind() {
Rui Ueyama83043f22016-10-17 16:01:53 +00001360 if (consume("SORT") || consume("SORT_BY_NAME"))
George Rimarbe394db2016-09-16 20:21:55 +00001361 return SortSectionPolicy::Name;
Rui Ueyama83043f22016-10-17 16:01:53 +00001362 if (consume("SORT_BY_ALIGNMENT"))
George Rimarbe394db2016-09-16 20:21:55 +00001363 return SortSectionPolicy::Alignment;
Rui Ueyama83043f22016-10-17 16:01:53 +00001364 if (consume("SORT_BY_INIT_PRIORITY"))
George Rimarbe394db2016-09-16 20:21:55 +00001365 return SortSectionPolicy::Priority;
Rui Ueyama83043f22016-10-17 16:01:53 +00001366 if (consume("SORT_NONE"))
Rui Ueyamab2a0abd2016-09-16 21:14:55 +00001367 return SortSectionPolicy::None;
1368 return SortSectionPolicy::Default;
George Rimarbe394db2016-09-16 20:21:55 +00001369}
1370
George Rimar395281c2016-09-16 17:42:10 +00001371// Method reads a list of sequence of excluded files and section globs given in
1372// a following form: ((EXCLUDE_FILE(file_pattern+))? section_pattern+)+
1373// Example: *(.foo.1 EXCLUDE_FILE (*a.o) .foo.2 EXCLUDE_FILE (*b.o) .foo.3)
George Rimaraf03be12016-09-17 19:17:25 +00001374// The semantics of that is next:
1375// * Include .foo.1 from every file.
1376// * Include .foo.2 from every file but a.o
1377// * Include .foo.3 from every file but b.o
George Rimar07171f22016-09-21 15:56:44 +00001378std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
1379 std::vector<SectionPattern> Ret;
George Rimar601e9892016-09-21 08:53:21 +00001380 while (!Error && peek() != ")") {
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001381 StringMatcher ExcludeFilePat;
Rui Ueyama83043f22016-10-17 16:01:53 +00001382 if (consume("EXCLUDE_FILE")) {
George Rimar395281c2016-09-16 17:42:10 +00001383 expect("(");
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001384 ExcludeFilePat = readFilePatterns();
George Rimar395281c2016-09-16 17:42:10 +00001385 }
1386
George Rimar601e9892016-09-21 08:53:21 +00001387 std::vector<StringRef> V;
1388 while (!Error && peek() != ")" && peek() != "EXCLUDE_FILE")
1389 V.push_back(next());
1390
1391 if (!V.empty())
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001392 Ret.push_back({std::move(ExcludeFilePat), StringMatcher(V)});
George Rimar601e9892016-09-21 08:53:21 +00001393 else
1394 setError("section pattern is expected");
George Rimar395281c2016-09-16 17:42:10 +00001395 }
George Rimar07171f22016-09-21 15:56:44 +00001396 return Ret;
George Rimar395281c2016-09-16 17:42:10 +00001397}
1398
Rui Ueyamaf8f6f1e2016-11-18 07:03:56 +00001399// Reads contents of "SECTIONS" directive. That directive contains a
1400// list of glob patterns for input sections. The grammar is as follows.
1401//
1402// <patterns> ::= <section-list>
1403// | <sort> "(" <section-list> ")"
1404// | <sort> "(" <sort> "(" <section-list> ")" ")"
1405//
1406// <sort> ::= "SORT" | "SORT_BY_NAME" | "SORT_BY_ALIGNMENT"
1407// | "SORT_BY_INIT_PRIORITY" | "SORT_NONE"
1408//
1409// <section-list> is parsed by readInputSectionsList().
George Rimara2496cb2016-08-30 09:46:59 +00001410InputSectionDescription *
1411ScriptParser::readInputSectionRules(StringRef FilePattern) {
George Rimarc91930a2016-09-02 21:17:20 +00001412 auto *Cmd = new InputSectionDescription(FilePattern);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001413 expect("(");
Rui Ueyamaf373dd72016-11-24 01:43:21 +00001414 while (!Error && !consume(")")) {
George Rimar07171f22016-09-21 15:56:44 +00001415 SortSectionPolicy Outer = readSortKind();
1416 SortSectionPolicy Inner = SortSectionPolicy::Default;
1417 std::vector<SectionPattern> V;
1418 if (Outer != SortSectionPolicy::Default) {
George Rimar350ece42016-08-03 08:35:59 +00001419 expect("(");
George Rimar07171f22016-09-21 15:56:44 +00001420 Inner = readSortKind();
1421 if (Inner != SortSectionPolicy::Default) {
1422 expect("(");
1423 V = readInputSectionsList();
1424 expect(")");
1425 } else {
1426 V = readInputSectionsList();
1427 }
George Rimar350ece42016-08-03 08:35:59 +00001428 expect(")");
1429 } else {
George Rimar07171f22016-09-21 15:56:44 +00001430 V = readInputSectionsList();
George Rimar350ece42016-08-03 08:35:59 +00001431 }
George Rimar0702c4e2016-07-29 15:32:46 +00001432
George Rimar07171f22016-09-21 15:56:44 +00001433 for (SectionPattern &Pat : V) {
1434 Pat.SortInner = Inner;
1435 Pat.SortOuter = Outer;
1436 }
1437
1438 std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns));
1439 }
Rui Ueyama10416562016-08-04 02:03:27 +00001440 return Cmd;
Davide Italianoe7282792016-07-27 01:44:01 +00001441}
1442
George Rimara2496cb2016-08-30 09:46:59 +00001443InputSectionDescription *
1444ScriptParser::readInputSectionDescription(StringRef Tok) {
George Rimar06598002016-07-28 21:51:30 +00001445 // Input section wildcard can be surrounded by KEEP.
1446 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
George Rimara2496cb2016-08-30 09:46:59 +00001447 if (Tok == "KEEP") {
George Rimar06598002016-07-28 21:51:30 +00001448 expect("(");
George Rimara2496cb2016-08-30 09:46:59 +00001449 StringRef FilePattern = next();
1450 InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
George Rimar06598002016-07-28 21:51:30 +00001451 expect(")");
Eugene Leviantcf43f172016-10-05 09:36:59 +00001452 Opt.KeptSections.push_back(Cmd);
Rui Ueyama10416562016-08-04 02:03:27 +00001453 return Cmd;
George Rimar06598002016-07-28 21:51:30 +00001454 }
George Rimara2496cb2016-08-30 09:46:59 +00001455 return readInputSectionRules(Tok);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001456}
1457
George Rimar03fc0102016-07-28 07:18:23 +00001458void ScriptParser::readSort() {
1459 expect("(");
1460 expect("CONSTRUCTORS");
1461 expect(")");
1462}
1463
George Rimareefa7582016-08-04 09:29:31 +00001464Expr ScriptParser::readAssert() {
1465 expect("(");
1466 Expr E = readExpr();
1467 expect(",");
George Rimarcd574a52016-09-09 14:35:36 +00001468 StringRef Msg = unquote(next());
George Rimareefa7582016-08-04 09:29:31 +00001469 expect(")");
1470 return [=](uint64_t Dot) {
1471 uint64_t V = E(Dot);
1472 if (!V)
1473 error(Msg);
1474 return V;
1475 };
1476}
1477
Rui Ueyama25150e82016-09-06 17:46:43 +00001478// Reads a FILL(expr) command. We handle the FILL command as an
1479// alias for =fillexp section attribute, which is different from
1480// what GNU linkers do.
1481// https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
Rui Ueyama16068ae2016-11-19 18:05:56 +00001482uint32_t ScriptParser::readFill() {
George Rimarff1f29e2016-09-06 13:51:57 +00001483 expect("(");
Rui Ueyama16068ae2016-11-19 18:05:56 +00001484 uint32_t V = readOutputSectionFiller(next());
George Rimarff1f29e2016-09-06 13:51:57 +00001485 expect(")");
1486 expect(";");
1487 return V;
1488}
1489
Rui Ueyama10416562016-08-04 02:03:27 +00001490OutputSectionCommand *
1491ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +00001492 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
Eugene Leviant2a942c42016-12-05 16:38:32 +00001493 Cmd->Location = getCurrentLocation();
George Rimar58e5c4d2016-07-25 08:29:46 +00001494
1495 // Read an address expression.
1496 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
1497 if (peek() != ":")
1498 Cmd->AddrExpr = readExpr();
1499
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001500 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +00001501
Rui Ueyama83043f22016-10-17 16:01:53 +00001502 if (consume("AT"))
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001503 Cmd->LMAExpr = readParenExpr();
Rui Ueyama83043f22016-10-17 16:01:53 +00001504 if (consume("ALIGN"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001505 Cmd->AlignExpr = readParenExpr();
Rui Ueyama83043f22016-10-17 16:01:53 +00001506 if (consume("SUBALIGN"))
George Rimardb24d9c2016-08-19 15:18:23 +00001507 Cmd->SubalignExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001508
Davide Italiano246f6812016-07-22 03:36:24 +00001509 // Parse constraints.
Rui Ueyama83043f22016-10-17 16:01:53 +00001510 if (consume("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001511 Cmd->Constraint = ConstraintKind::ReadOnly;
Rui Ueyama83043f22016-10-17 16:01:53 +00001512 if (consume("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001513 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001514 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001515
Rui Ueyama83043f22016-10-17 16:01:53 +00001516 while (!Error && !consume("}")) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001517 StringRef Tok = next();
George Rimar2fe07922017-01-31 08:50:11 +00001518 if (Tok == ";") {
George Rimar69750752017-02-01 09:14:22 +00001519 // Empty commands are allowed. Do nothing here.
George Rimar2fe07922017-01-31 08:50:11 +00001520 } else if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok)) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001521 Cmd->Commands.emplace_back(Assignment);
Meador Ingeb2d99d62016-11-22 18:01:50 +00001522 } else if (BytesDataCommand *Data = readBytesDataCommand(Tok)) {
George Rimare38cbab2016-09-26 19:22:50 +00001523 Cmd->Commands.emplace_back(Data);
Meador Ingeb2d99d62016-11-22 18:01:50 +00001524 } else if (Tok == "ASSERT") {
1525 Cmd->Commands.emplace_back(new AssertCommand(readAssert()));
1526 expect(";");
George Rimar8e2eca22017-01-23 09:36:19 +00001527 } else if (Tok == "CONSTRUCTORS") {
1528 // CONSTRUCTORS is a keyword to make the linker recognize C++ ctors/dtors
1529 // by name. This is for very old file formats such as ECOFF/XCOFF.
1530 // For ELF, we should ignore.
Meador Ingeb2d99d62016-11-22 18:01:50 +00001531 } else if (Tok == "FILL") {
George Rimarff1f29e2016-09-06 13:51:57 +00001532 Cmd->Filler = readFill();
Meador Ingeb2d99d62016-11-22 18:01:50 +00001533 } else if (Tok == "SORT") {
George Rimar03fc0102016-07-28 07:18:23 +00001534 readSort();
Meador Ingeb2d99d62016-11-22 18:01:50 +00001535 } else if (peek() == "(") {
George Rimara2496cb2016-08-30 09:46:59 +00001536 Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
Meador Ingeb2d99d62016-11-22 18:01:50 +00001537 } else {
Eugene Leviantceabe802016-08-11 07:56:43 +00001538 setError("unknown command " + Tok);
Meador Ingeb2d99d62016-11-22 18:01:50 +00001539 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001540 }
Meador Ingeb8897442017-01-24 02:34:00 +00001541
1542 if (consume(">"))
1543 Cmd->MemoryRegionName = next();
1544
George Rimar076fe152016-07-21 06:43:01 +00001545 Cmd->Phdrs = readOutputSectionPhdrs();
George Rimar4ebc5622016-09-23 13:29:20 +00001546
Rui Ueyama83043f22016-10-17 16:01:53 +00001547 if (consume("="))
George Rimar4ebc5622016-09-23 13:29:20 +00001548 Cmd->Filler = readOutputSectionFiller(next());
1549 else if (peek().startswith("="))
George Rimarff1f29e2016-09-06 13:51:57 +00001550 Cmd->Filler = readOutputSectionFiller(next().drop_front());
George Rimar4ebc5622016-09-23 13:29:20 +00001551
George Rimar7185a1a2017-01-17 15:32:12 +00001552 // Consume optional comma following output section command.
1553 consume(",");
1554
Rui Ueyama10416562016-08-04 02:03:27 +00001555 return Cmd;
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001556}
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001557
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001558// Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
1559// https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
1560//
1561// ld.gold is not fully compatible with ld.bfd. ld.bfd handles
1562// hexstrings as blobs of arbitrary sizes, while ld.gold handles them
1563// as 32-bit big-endian values. We will do the same as ld.gold does
1564// because it's simpler than what ld.bfd does.
Rui Ueyama16068ae2016-11-19 18:05:56 +00001565uint32_t ScriptParser::readOutputSectionFiller(StringRef Tok) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001566 uint32_t V;
Rui Ueyama16068ae2016-11-19 18:05:56 +00001567 if (!Tok.getAsInteger(0, V))
1568 return V;
1569 setError("invalid filler expression: " + Tok);
1570 return 0;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001571}
1572
Petr Hoseka35e39c2016-08-16 01:11:16 +00001573SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
Eugene Levianta31c91b2016-07-22 07:38:40 +00001574 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +00001575 SymbolAssignment *Cmd = readAssignment(next());
Petr Hoseka35e39c2016-08-16 01:11:16 +00001576 Cmd->Provide = Provide;
Rui Ueyama174e0a12016-07-29 00:29:25 +00001577 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001578 expect(")");
1579 expect(";");
Rui Ueyama10416562016-08-04 02:03:27 +00001580 return Cmd;
Eugene Levianteda81a12016-07-12 06:39:48 +00001581}
1582
Rafael Espindolac96da112016-11-01 11:30:45 +00001583SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001584 SymbolAssignment *Cmd = nullptr;
1585 if (peek() == "=" || peek() == "+=") {
1586 Cmd = readAssignment(Tok);
1587 expect(";");
1588 } else if (Tok == "PROVIDE") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001589 Cmd = readProvideHidden(true, false);
1590 } else if (Tok == "HIDDEN") {
1591 Cmd = readProvideHidden(false, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001592 } else if (Tok == "PROVIDE_HIDDEN") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001593 Cmd = readProvideHidden(true, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001594 }
1595 return Cmd;
1596}
1597
Eugene Leviantf6aeed32016-12-22 13:13:12 +00001598static uint64_t getSymbolValue(const Twine &Loc, StringRef S, uint64_t Dot) {
George Rimar30835ea2016-07-28 21:08:56 +00001599 if (S == ".")
1600 return Dot;
Eugene Leviantf6aeed32016-12-22 13:13:12 +00001601 return ScriptBase->getSymbolValue(Loc, S);
George Rimare32a3592016-08-10 07:59:34 +00001602}
1603
Rafael Espindola2f831dc2016-10-31 19:56:37 +00001604static bool isAbsolute(StringRef S) {
1605 if (S == ".")
1606 return false;
1607 return ScriptBase->isAbsolute(S);
1608}
1609
George Rimar30835ea2016-07-28 21:08:56 +00001610SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1611 StringRef Op = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +00001612 Expr E;
George Rimar30835ea2016-07-28 21:08:56 +00001613 assert(Op == "=" || Op == "+=");
Rui Ueyama83043f22016-10-17 16:01:53 +00001614 if (consume("ABSOLUTE")) {
Rui Ueyama731a66a2017-02-15 19:58:17 +00001615 E = readExpr();
Rui Ueyama009d1742016-11-18 06:49:09 +00001616 E.IsAbsolute = [] { return true; };
Eugene Leviantdb741e72016-09-07 07:08:43 +00001617 } else {
1618 E = readExpr();
1619 }
Eugene Leviantf6aeed32016-12-22 13:13:12 +00001620 if (Op == "+=") {
1621 std::string Loc = getCurrentLocation();
1622 E = [=](uint64_t Dot) {
1623 return getSymbolValue(Loc, Name, Dot) + E(Dot);
1624 };
1625 }
Rafael Espindolaf6613932016-10-31 17:43:38 +00001626 return new SymbolAssignment(Name, E);
George Rimar30835ea2016-07-28 21:08:56 +00001627}
1628
1629// This is an operator-precedence parser to parse a linker
1630// script expression.
Rui Ueyama731a66a2017-02-15 19:58:17 +00001631Expr ScriptParser::readExpr() {
1632 // Our lexer is context-aware. Set the in-expression bit so that
1633 // they apply different tokenization rules.
1634 bool Orig = InExpr;
1635 InExpr = true;
1636 Expr E = readExpr1(readPrimary(), 0);
1637 InExpr = Orig;
1638 return E;
1639}
George Rimar30835ea2016-07-28 21:08:56 +00001640
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001641static Expr combine(StringRef Op, Expr L, Expr R) {
George Rimarcc4d3e52017-02-01 09:01:16 +00001642 auto IsAbs = [=] { return L.IsAbsolute() && R.IsAbsolute(); };
1643 auto GetOutSec = [=] {
1644 const OutputSectionBase *S = L.Section();
1645 return S ? S : R.Section();
1646 };
1647
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001648 if (Op == "*")
1649 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1650 if (Op == "/") {
1651 return [=](uint64_t Dot) -> uint64_t {
1652 uint64_t RHS = R(Dot);
1653 if (RHS == 0) {
1654 error("division by zero");
1655 return 0;
1656 }
1657 return L(Dot) / RHS;
1658 };
1659 }
1660 if (Op == "+")
George Rimarcc4d3e52017-02-01 09:01:16 +00001661 return {[=](uint64_t Dot) { return L(Dot) + R(Dot); }, IsAbs, GetOutSec};
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001662 if (Op == "-")
George Rimarcc4d3e52017-02-01 09:01:16 +00001663 return {[=](uint64_t Dot) { return L(Dot) - R(Dot); }, IsAbs, GetOutSec};
George Rimarc8ccd1f2016-09-23 13:13:55 +00001664 if (Op == "<<")
1665 return [=](uint64_t Dot) { return L(Dot) << R(Dot); };
1666 if (Op == ">>")
1667 return [=](uint64_t Dot) { return L(Dot) >> R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001668 if (Op == "<")
1669 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
1670 if (Op == ">")
1671 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
1672 if (Op == ">=")
1673 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
1674 if (Op == "<=")
1675 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
1676 if (Op == "==")
1677 return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
1678 if (Op == "!=")
1679 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
1680 if (Op == "&")
1681 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
Rafael Espindolacc3dd622016-08-22 21:33:35 +00001682 if (Op == "|")
1683 return [=](uint64_t Dot) { return L(Dot) | R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001684 llvm_unreachable("invalid operator");
1685}
1686
Rui Ueyama708019c2016-07-24 18:19:40 +00001687// This is a part of the operator-precedence parser. This function
1688// assumes that the remaining token stream starts with an operator.
1689Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1690 while (!atEOF() && !Error) {
1691 // Read an operator and an expression.
Rui Ueyama46247b82016-11-18 06:49:07 +00001692 if (consume("?"))
Rui Ueyama708019c2016-07-24 18:19:40 +00001693 return readTernary(Lhs);
Rui Ueyama46247b82016-11-18 06:49:07 +00001694 StringRef Op1 = peek();
Rui Ueyama708019c2016-07-24 18:19:40 +00001695 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +00001696 break;
Justin Bogner5424e7c2016-10-17 06:21:13 +00001697 skip();
Rui Ueyama708019c2016-07-24 18:19:40 +00001698 Expr Rhs = readPrimary();
1699
1700 // Evaluate the remaining part of the expression first if the
1701 // next operator has greater precedence than the previous one.
1702 // For example, if we have read "+" and "3", and if the next
1703 // operator is "*", then we'll evaluate 3 * ... part first.
1704 while (!atEOF()) {
1705 StringRef Op2 = peek();
1706 if (precedence(Op2) <= precedence(Op1))
1707 break;
1708 Rhs = readExpr1(Rhs, precedence(Op2));
1709 }
1710
1711 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +00001712 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001713 return Lhs;
1714}
1715
1716uint64_t static getConstant(StringRef S) {
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001717 if (S == "COMMONPAGESIZE")
Rui Ueyama708019c2016-07-24 18:19:40 +00001718 return Target->PageSize;
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001719 if (S == "MAXPAGESIZE")
Petr Hosek997f8832016-09-28 15:20:47 +00001720 return Config->MaxPageSize;
Rui Ueyama708019c2016-07-24 18:19:40 +00001721 error("unknown constant: " + S);
1722 return 0;
1723}
1724
Rui Ueyama626e0b02016-09-02 18:19:00 +00001725// Parses Tok as an integer. Returns true if successful.
1726// It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1727// and decimal numbers. Decimal numbers may have "K" (kilo) or
1728// "M" (mega) prefixes.
George Rimar9f2f7ad2016-09-02 16:01:42 +00001729static bool readInteger(StringRef Tok, uint64_t &Result) {
Rui Ueyama46247b82016-11-18 06:49:07 +00001730 // Negative number
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001731 if (Tok.startswith("-")) {
1732 if (!readInteger(Tok.substr(1), Result))
1733 return false;
1734 Result = -Result;
1735 return true;
1736 }
Rui Ueyama46247b82016-11-18 06:49:07 +00001737
1738 // Hexadecimal
George Rimar9f2f7ad2016-09-02 16:01:42 +00001739 if (Tok.startswith_lower("0x"))
1740 return !Tok.substr(2).getAsInteger(16, Result);
1741 if (Tok.endswith_lower("H"))
1742 return !Tok.drop_back().getAsInteger(16, Result);
1743
Rui Ueyama46247b82016-11-18 06:49:07 +00001744 // Decimal
George Rimar9f2f7ad2016-09-02 16:01:42 +00001745 int Suffix = 1;
1746 if (Tok.endswith_lower("K")) {
1747 Suffix = 1024;
1748 Tok = Tok.drop_back();
1749 } else if (Tok.endswith_lower("M")) {
1750 Suffix = 1024 * 1024;
1751 Tok = Tok.drop_back();
1752 }
1753 if (Tok.getAsInteger(10, Result))
1754 return false;
1755 Result *= Suffix;
1756 return true;
1757}
1758
George Rimare38cbab2016-09-26 19:22:50 +00001759BytesDataCommand *ScriptParser::readBytesDataCommand(StringRef Tok) {
1760 int Size = StringSwitch<unsigned>(Tok)
1761 .Case("BYTE", 1)
1762 .Case("SHORT", 2)
1763 .Case("LONG", 4)
1764 .Case("QUAD", 8)
1765 .Default(-1);
1766 if (Size == -1)
1767 return nullptr;
1768
Meador Inge95c7d8d2016-12-08 23:21:30 +00001769 return new BytesDataCommand(readParenExpr(), Size);
George Rimare38cbab2016-09-26 19:22:50 +00001770}
1771
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001772StringRef ScriptParser::readParenLiteral() {
1773 expect("(");
1774 StringRef Tok = next();
1775 expect(")");
1776 return Tok;
1777}
1778
Rui Ueyama708019c2016-07-24 18:19:40 +00001779Expr ScriptParser::readPrimary() {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001780 if (peek() == "(")
1781 return readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001782
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001783 StringRef Tok = next();
Rui Ueyamab5f1c3e2016-12-01 04:36:49 +00001784 std::string Location = getCurrentLocation();
Rui Ueyama708019c2016-07-24 18:19:40 +00001785
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001786 if (Tok == "~") {
1787 Expr E = readPrimary();
1788 return [=](uint64_t Dot) { return ~E(Dot); };
1789 }
1790 if (Tok == "-") {
1791 Expr E = readPrimary();
1792 return [=](uint64_t Dot) { return -E(Dot); };
1793 }
1794
Rui Ueyama708019c2016-07-24 18:19:40 +00001795 // Built-in functions are parsed here.
1796 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
George Rimar96659df2016-08-30 09:54:01 +00001797 if (Tok == "ADDR") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001798 StringRef Name = readParenLiteral();
Eugene Levianted30ce72016-11-28 09:58:04 +00001799 return {[=](uint64_t Dot) {
1800 return ScriptBase->getOutputSection(Location, Name)->Addr;
1801 },
1802 [=] { return false; },
1803 [=] { return ScriptBase->getOutputSection(Location, Name); }};
George Rimar96659df2016-08-30 09:54:01 +00001804 }
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001805 if (Tok == "LOADADDR") {
1806 StringRef Name = readParenLiteral();
Eugene Leviantafaa9342016-11-16 09:49:39 +00001807 return [=](uint64_t Dot) {
Eugene Levianted30ce72016-11-28 09:58:04 +00001808 return ScriptBase->getOutputSection(Location, Name)->getLMA();
Eugene Leviantafaa9342016-11-16 09:49:39 +00001809 };
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001810 }
George Rimareefa7582016-08-04 09:29:31 +00001811 if (Tok == "ASSERT")
1812 return readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001813 if (Tok == "ALIGN") {
Rui Ueyama5d804dc2016-12-16 18:19:35 +00001814 expect("(");
1815 Expr E = readExpr();
1816 if (consume(",")) {
1817 Expr E2 = readExpr();
1818 expect(")");
1819 return [=](uint64_t Dot) { return alignTo(E(Dot), E2(Dot)); };
1820 }
1821 expect(")");
Rui Ueyama708019c2016-07-24 18:19:40 +00001822 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1823 }
1824 if (Tok == "CONSTANT") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001825 StringRef Name = readParenLiteral();
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001826 return [=](uint64_t Dot) { return getConstant(Name); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001827 }
George Rimarf34f45f2016-09-23 13:17:23 +00001828 if (Tok == "DEFINED") {
Rui Ueyama0ee25a62016-11-17 03:52:14 +00001829 StringRef Name = readParenLiteral();
1830 return [=](uint64_t Dot) { return ScriptBase->isDefined(Name) ? 1 : 0; };
George Rimarf34f45f2016-09-23 13:17:23 +00001831 }
Rafael Espindola54c145c2016-07-28 18:16:24 +00001832 if (Tok == "SEGMENT_START") {
1833 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001834 skip();
Rafael Espindola54c145c2016-07-28 18:16:24 +00001835 expect(",");
George Rimar8c658bf2016-09-17 18:14:56 +00001836 Expr E = readExpr();
Rafael Espindola54c145c2016-07-28 18:16:24 +00001837 expect(")");
George Rimar8c658bf2016-09-17 18:14:56 +00001838 return [=](uint64_t Dot) { return E(Dot); };
Rafael Espindola54c145c2016-07-28 18:16:24 +00001839 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001840 if (Tok == "DATA_SEGMENT_ALIGN") {
1841 expect("(");
1842 Expr E = readExpr();
1843 expect(",");
1844 readExpr();
1845 expect(")");
Rui Ueyamaf7791bb2016-07-26 19:34:10 +00001846 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001847 }
1848 if (Tok == "DATA_SEGMENT_END") {
1849 expect("(");
1850 expect(".");
1851 expect(")");
1852 return [](uint64_t Dot) { return Dot; };
1853 }
George Rimar276b4e62016-07-26 17:58:44 +00001854 // GNU linkers implements more complicated logic to handle
1855 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1856 // the next page boundary for simplicity.
1857 if (Tok == "DATA_SEGMENT_RELRO_END") {
1858 expect("(");
Rafael Espindola97bdc722016-09-14 19:14:01 +00001859 readExpr();
George Rimar276b4e62016-07-26 17:58:44 +00001860 expect(",");
1861 readExpr();
1862 expect(")");
1863 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1864 }
George Rimar9e694502016-07-29 16:18:47 +00001865 if (Tok == "SIZEOF") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001866 StringRef Name = readParenLiteral();
Rui Ueyamaedf75e72016-11-17 20:27:10 +00001867 return [=](uint64_t Dot) { return ScriptBase->getOutputSectionSize(Name); };
George Rimar9e694502016-07-29 16:18:47 +00001868 }
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001869 if (Tok == "ALIGNOF") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001870 StringRef Name = readParenLiteral();
Eugene Leviantafaa9342016-11-16 09:49:39 +00001871 return [=](uint64_t Dot) {
Eugene Levianted30ce72016-11-28 09:58:04 +00001872 return ScriptBase->getOutputSection(Location, Name)->Addralign;
Eugene Leviantafaa9342016-11-16 09:49:39 +00001873 };
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001874 }
George Rimare32a3592016-08-10 07:59:34 +00001875 if (Tok == "SIZEOF_HEADERS")
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001876 return [=](uint64_t Dot) { return ScriptBase->getHeaderSize(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001877
George Rimar9f2f7ad2016-09-02 16:01:42 +00001878 // Tok is a literal number.
1879 uint64_t V;
1880 if (readInteger(Tok, V))
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001881 return [=](uint64_t Dot) { return V; };
George Rimar9f2f7ad2016-09-02 16:01:42 +00001882
1883 // Tok is a symbol name.
1884 if (Tok != "." && !isValidCIdentifier(Tok))
1885 setError("malformed number: " + Tok);
Eugene Leviantf6aeed32016-12-22 13:13:12 +00001886 return {[=](uint64_t Dot) { return getSymbolValue(Location, Tok, Dot); },
Rui Ueyama009d1742016-11-18 06:49:09 +00001887 [=] { return isAbsolute(Tok); },
1888 [=] { return ScriptBase->getSymbolSection(Tok); }};
Rui Ueyama708019c2016-07-24 18:19:40 +00001889}
1890
1891Expr ScriptParser::readTernary(Expr Cond) {
Rui Ueyama708019c2016-07-24 18:19:40 +00001892 Expr L = readExpr();
1893 expect(":");
1894 Expr R = readExpr();
1895 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1896}
1897
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001898Expr ScriptParser::readParenExpr() {
1899 expect("(");
1900 Expr E = readExpr();
1901 expect(")");
1902 return E;
1903}
1904
Eugene Leviantbbe38602016-07-19 09:25:43 +00001905std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1906 std::vector<StringRef> Phdrs;
1907 while (!Error && peek().startswith(":")) {
1908 StringRef Tok = next();
George Rimarda841c12016-11-14 10:03:54 +00001909 Phdrs.push_back((Tok.size() == 1) ? next() : Tok.substr(1));
Eugene Leviantbbe38602016-07-19 09:25:43 +00001910 }
1911 return Phdrs;
1912}
1913
George Rimar95dd7182016-10-18 10:49:50 +00001914// Read a program header type name. The next token must be a
1915// name of a program header type or a constant (e.g. "0x3").
Eugene Leviantbbe38602016-07-19 09:25:43 +00001916unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001917 StringRef Tok = next();
George Rimar95dd7182016-10-18 10:49:50 +00001918 uint64_t Val;
1919 if (readInteger(Tok, Val))
1920 return Val;
1921
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001922 unsigned Ret = StringSwitch<unsigned>(Tok)
George Rimar6c55f0e2016-09-08 08:20:30 +00001923 .Case("PT_NULL", PT_NULL)
1924 .Case("PT_LOAD", PT_LOAD)
1925 .Case("PT_DYNAMIC", PT_DYNAMIC)
1926 .Case("PT_INTERP", PT_INTERP)
1927 .Case("PT_NOTE", PT_NOTE)
1928 .Case("PT_SHLIB", PT_SHLIB)
1929 .Case("PT_PHDR", PT_PHDR)
1930 .Case("PT_TLS", PT_TLS)
1931 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1932 .Case("PT_GNU_STACK", PT_GNU_STACK)
1933 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
George Rimar270173f2016-10-14 13:02:22 +00001934 .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
George Rimarcc6e5672016-10-14 10:34:36 +00001935 .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
George Rimara2a32c22016-12-06 17:57:42 +00001936 .Case("PT_OPENBSD_BOOTDATA", PT_OPENBSD_BOOTDATA)
George Rimar6c55f0e2016-09-08 08:20:30 +00001937 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001938
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001939 if (Ret == (unsigned)-1) {
1940 setError("invalid program header type: " + Tok);
1941 return PT_NULL;
1942 }
1943 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001944}
1945
Rui Ueyama12450b22016-11-18 06:30:09 +00001946// Reads a list of symbols, e.g. "{ global: foo; bar; local: *; };".
1947void ScriptParser::readAnonymousDeclaration() {
1948 // Read global symbols first. "global:" is default, so if there's
1949 // no label, we assume global symbols.
Rafael Espindola45242682017-02-03 13:24:01 +00001950 if (peek() != "local") {
1951 if (consume("global"))
1952 expect(":");
Peter Collingbourne904c5ed2017-02-13 18:31:12 +00001953 for (SymbolVersion V : readSymbols())
1954 Config->VersionScriptGlobals.push_back(V);
Rafael Espindola45242682017-02-03 13:24:01 +00001955 }
Rafael Espindolae999ddb2017-01-10 16:37:24 +00001956 readLocals();
Rui Ueyama12450b22016-11-18 06:30:09 +00001957 expect("}");
1958 expect(";");
1959}
1960
Rafael Espindolae999ddb2017-01-10 16:37:24 +00001961void ScriptParser::readLocals() {
Rafael Espindola45242682017-02-03 13:24:01 +00001962 if (!consume("local"))
Rafael Espindolae999ddb2017-01-10 16:37:24 +00001963 return;
Rafael Espindola45242682017-02-03 13:24:01 +00001964 expect(":");
Rafael Espindolae999ddb2017-01-10 16:37:24 +00001965 std::vector<SymbolVersion> Locals = readSymbols();
1966 for (SymbolVersion V : Locals) {
1967 if (V.Name == "*") {
1968 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1969 continue;
1970 }
1971 Config->VersionScriptLocals.push_back(V);
1972 }
1973}
1974
Rui Ueyama12450b22016-11-18 06:30:09 +00001975// Reads a list of symbols, e.g. "VerStr { global: foo; bar; local: *; };".
Rui Ueyama95769b42016-08-31 20:03:54 +00001976void ScriptParser::readVersionDeclaration(StringRef VerStr) {
George Rimar20b65982016-08-31 09:08:26 +00001977 // Identifiers start at 2 because 0 and 1 are reserved
1978 // for VER_NDX_LOCAL and VER_NDX_GLOBAL constants.
Rui Ueyamada805c42016-11-17 03:39:21 +00001979 uint16_t VersionId = Config->VersionDefinitions.size() + 2;
George Rimar20b65982016-08-31 09:08:26 +00001980 Config->VersionDefinitions.push_back({VerStr, VersionId});
1981
Rui Ueyama12450b22016-11-18 06:30:09 +00001982 // Read global symbols.
Rafael Espindola45242682017-02-03 13:24:01 +00001983 if (peek() != "local") {
1984 if (consume("global"))
1985 expect(":");
Rui Ueyama12450b22016-11-18 06:30:09 +00001986 Config->VersionDefinitions.back().Globals = readSymbols();
Rafael Espindola45242682017-02-03 13:24:01 +00001987 }
Rafael Espindolae999ddb2017-01-10 16:37:24 +00001988 readLocals();
George Rimar20b65982016-08-31 09:08:26 +00001989 expect("}");
1990
Rui Ueyama12450b22016-11-18 06:30:09 +00001991 // Each version may have a parent version. For example, "Ver2"
1992 // defined as "Ver2 { global: foo; local: *; } Ver1;" has "Ver1"
1993 // as a parent. This version hierarchy is, probably against your
1994 // instinct, purely for hint; the runtime doesn't care about it
1995 // at all. In LLD, we simply ignore it.
1996 if (peek() != ";")
Justin Bogner5424e7c2016-10-17 06:21:13 +00001997 skip();
George Rimar20b65982016-08-31 09:08:26 +00001998 expect(";");
1999}
2000
Rui Ueyama12450b22016-11-18 06:30:09 +00002001// Reads a list of symbols for a versions cript.
2002std::vector<SymbolVersion> ScriptParser::readSymbols() {
2003 std::vector<SymbolVersion> Ret;
George Rimare0fc2422016-11-16 17:59:10 +00002004 for (;;) {
Rafael Espindola1ef90d22016-12-09 16:44:05 +00002005 if (consume("extern")) {
Rui Ueyama12450b22016-11-18 06:30:09 +00002006 for (SymbolVersion V : readVersionExtern())
2007 Ret.push_back(V);
Rafael Espindola1ef90d22016-12-09 16:44:05 +00002008 continue;
2009 }
George Rimare0fc2422016-11-16 17:59:10 +00002010
Dmitry Mikulinf3965c02017-02-07 19:50:47 +00002011 if (peek() == "}" || (peek() == "local" && peek(1) == ":") || Error)
Rui Ueyama12450b22016-11-18 06:30:09 +00002012 break;
Rui Ueyama0ee25a62016-11-17 03:52:14 +00002013 StringRef Tok = next();
Rui Ueyama12450b22016-11-18 06:30:09 +00002014 Ret.push_back({unquote(Tok), false, hasWildcard(Tok)});
George Rimare0fc2422016-11-16 17:59:10 +00002015 expect(";");
2016 }
Rui Ueyama12450b22016-11-18 06:30:09 +00002017 return Ret;
George Rimare0fc2422016-11-16 17:59:10 +00002018}
2019
Rui Ueyama12450b22016-11-18 06:30:09 +00002020// Reads an "extern C++" directive, e.g.,
2021// "extern "C++" { ns::*; "f(int, double)"; };"
2022std::vector<SymbolVersion> ScriptParser::readVersionExtern() {
Rafael Espindola7e714152016-12-08 17:26:53 +00002023 StringRef Tok = next();
2024 bool IsCXX = Tok == "\"C++\"";
2025 if (!IsCXX && Tok != "\"C\"")
Rafael Espindolad0ebd842016-12-08 17:54:26 +00002026 setError("Unknown language");
George Rimar20b65982016-08-31 09:08:26 +00002027 expect("{");
2028
Rui Ueyama12450b22016-11-18 06:30:09 +00002029 std::vector<SymbolVersion> Ret;
Rui Ueyama0ee25a62016-11-17 03:52:14 +00002030 while (!Error && peek() != "}") {
2031 StringRef Tok = next();
2032 bool HasWildcard = !Tok.startswith("\"") && hasWildcard(Tok);
Rafael Espindola7e714152016-12-08 17:26:53 +00002033 Ret.push_back({unquote(Tok), IsCXX, HasWildcard});
George Rimar20b65982016-08-31 09:08:26 +00002034 expect(";");
2035 }
2036
2037 expect("}");
2038 expect(";");
Rui Ueyama12450b22016-11-18 06:30:09 +00002039 return Ret;
George Rimar20b65982016-08-31 09:08:26 +00002040}
2041
Rui Ueyama24e626c2017-01-26 02:58:19 +00002042uint64_t ScriptParser::readMemoryAssignment(
2043 StringRef S1, StringRef S2, StringRef S3) {
2044 if (!(consume(S1) || consume(S2) || consume(S3))) {
2045 setError("expected one of: " + S1 + ", " + S2 + ", or " + S3);
2046 return 0;
2047 }
2048 expect("=");
2049
2050 // TODO: Fully support constant expressions.
2051 uint64_t Val;
2052 if (!readInteger(next(), Val))
2053 setError("nonconstant expression for "+ S1);
2054 return Val;
2055}
2056
2057// Parse the MEMORY command as specified in:
2058// https://sourceware.org/binutils/docs/ld/MEMORY.html
2059//
2060// MEMORY { name [(attr)] : ORIGIN = origin, LENGTH = len ... }
Meador Ingeb8897442017-01-24 02:34:00 +00002061void ScriptParser::readMemory() {
2062 expect("{");
2063 while (!Error && !consume("}")) {
2064 StringRef Name = next();
Rui Ueyama24e626c2017-01-26 02:58:19 +00002065
Meador Ingeb8897442017-01-24 02:34:00 +00002066 uint32_t Flags = 0;
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002067 uint32_t NegFlags = 0;
Meador Ingeb8897442017-01-24 02:34:00 +00002068 if (consume("(")) {
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002069 std::tie(Flags, NegFlags) = readMemoryAttributes();
Meador Ingeb8897442017-01-24 02:34:00 +00002070 expect(")");
2071 }
2072 expect(":");
2073
Rui Ueyama24e626c2017-01-26 02:58:19 +00002074 uint64_t Origin = readMemoryAssignment("ORIGIN", "org", "o");
Meador Ingeb8897442017-01-24 02:34:00 +00002075 expect(",");
Rui Ueyama24e626c2017-01-26 02:58:19 +00002076 uint64_t Length = readMemoryAssignment("LENGTH", "len", "l");
Meador Ingeb8897442017-01-24 02:34:00 +00002077
Meador Ingeb8897442017-01-24 02:34:00 +00002078 // Add the memory region to the region map (if it doesn't already exist).
2079 auto It = Opt.MemoryRegions.find(Name);
2080 if (It != Opt.MemoryRegions.end())
2081 setError("region '" + Name + "' already defined");
2082 else
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002083 Opt.MemoryRegions[Name] = {Name, Origin, Length, Origin, Flags, NegFlags};
Meador Ingeb8897442017-01-24 02:34:00 +00002084 }
2085}
2086
2087// This function parses the attributes used to match against section
2088// flags when placing output sections in a memory region. These flags
2089// are only used when an explicit memory region name is not used.
2090std::pair<uint32_t, uint32_t> ScriptParser::readMemoryAttributes() {
2091 uint32_t Flags = 0;
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002092 uint32_t NegFlags = 0;
Meador Ingeb8897442017-01-24 02:34:00 +00002093 bool Invert = false;
Rui Ueyama481ac992017-01-26 02:58:39 +00002094
2095 for (char C : next().lower()) {
Meador Ingeb8897442017-01-24 02:34:00 +00002096 uint32_t Flag = 0;
2097 if (C == '!')
2098 Invert = !Invert;
Rui Ueyama481ac992017-01-26 02:58:39 +00002099 else if (C == 'w')
Meador Ingeb8897442017-01-24 02:34:00 +00002100 Flag = SHF_WRITE;
Rui Ueyama481ac992017-01-26 02:58:39 +00002101 else if (C == 'x')
Meador Ingeb8897442017-01-24 02:34:00 +00002102 Flag = SHF_EXECINSTR;
Rui Ueyama481ac992017-01-26 02:58:39 +00002103 else if (C == 'a')
Meador Ingeb8897442017-01-24 02:34:00 +00002104 Flag = SHF_ALLOC;
Rui Ueyama481ac992017-01-26 02:58:39 +00002105 else if (C != 'r')
Meador Ingeb8897442017-01-24 02:34:00 +00002106 setError("invalid memory region attribute");
Rui Ueyama481ac992017-01-26 02:58:39 +00002107
Meador Ingeb8897442017-01-24 02:34:00 +00002108 if (Invert)
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002109 NegFlags |= Flag;
Meador Ingeb8897442017-01-24 02:34:00 +00002110 else
2111 Flags |= Flag;
2112 }
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002113 return {Flags, NegFlags};
Meador Ingeb8897442017-01-24 02:34:00 +00002114}
2115
Rui Ueyama07320e42016-04-20 20:13:41 +00002116void elf::readLinkerScript(MemoryBufferRef MB) {
Rui Ueyama22375f22016-11-25 18:51:54 +00002117 ScriptParser(MB).readLinkerScript();
George Rimar20b65982016-08-31 09:08:26 +00002118}
2119
2120void elf::readVersionScript(MemoryBufferRef MB) {
Rui Ueyama22375f22016-11-25 18:51:54 +00002121 ScriptParser(MB).readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00002122}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00002123
Rafael Espindolad0ebd842016-12-08 17:54:26 +00002124void elf::readDynamicList(MemoryBufferRef MB) {
2125 ScriptParser(MB).readDynamicList();
2126}
2127
Rui Ueyama07320e42016-04-20 20:13:41 +00002128template class elf::LinkerScript<ELF32LE>;
2129template class elf::LinkerScript<ELF32BE>;
2130template class elf::LinkerScript<ELF64LE>;
2131template class elf::LinkerScript<ELF64BE>;