blob: e56e1a2ce4a43078758f8b5259d73a3c0637c1b3 [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.
11// It does not construct an AST but consume linker script directives directly.
Rui Ueyama34f29242015-10-13 19:51:57 +000012// Results are written to Driver or Config object.
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000013//
14//===----------------------------------------------------------------------===//
15
Rui Ueyama717677a2016-02-11 21:17:59 +000016#include "LinkerScript.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000017#include "Config.h"
18#include "Driver.h"
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +000019#include "InputSection.h"
George Rimar652852c2016-04-16 10:10:32 +000020#include "OutputSections.h"
Adhemerval Zanellae77b5bf2016-04-06 20:59:11 +000021#include "ScriptParser.h"
Rui Ueyama93c9af42016-06-29 08:01:32 +000022#include "Strings.h"
Eugene Levianteda81a12016-07-12 06:39:48 +000023#include "Symbols.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000024#include "SymbolTable.h"
Eugene Leviant467c4d52016-07-01 10:27:36 +000025#include "Target.h"
Eugene Leviantbbe38602016-07-19 09:25:43 +000026#include "Writer.h"
Rui Ueyama960504b2016-04-19 18:58:11 +000027#include "llvm/ADT/StringSwitch.h"
George Rimar652852c2016-04-16 10:10:32 +000028#include "llvm/Support/ELF.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000029#include "llvm/Support/FileSystem.h"
30#include "llvm/Support/MemoryBuffer.h"
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +000031#include "llvm/Support/Path.h"
Rui Ueyamaa47ee682015-10-11 01:53:04 +000032#include "llvm/Support/StringSaver.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000033
34using namespace llvm;
George Rimar652852c2016-04-16 10:10:32 +000035using namespace llvm::ELF;
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +000036using namespace llvm::object;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000037using namespace lld;
Rafael Espindolae0df00b2016-02-28 00:25:54 +000038using namespace lld::elf;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000039
Rui Ueyama07320e42016-04-20 20:13:41 +000040ScriptConfiguration *elf::ScriptConfig;
Rui Ueyama717677a2016-02-11 21:17:59 +000041
Rui Ueyama9c1112d2016-04-23 00:04:03 +000042// This is an operator-precedence parser to parse and evaluate
43// a linker script expression. For each linker script arithmetic
44// expression (e.g. ". = . + 0x1000"), a new instance of ExprParser
45// is created and ran.
46namespace {
47class ExprParser : public ScriptParserBase {
48public:
49 ExprParser(std::vector<StringRef> &Tokens, uint64_t Dot)
50 : ScriptParserBase(Tokens), Dot(Dot) {}
51
52 uint64_t run();
53
54private:
55 uint64_t parsePrimary();
56 uint64_t parseTernary(uint64_t Cond);
57 uint64_t apply(StringRef Op, uint64_t L, uint64_t R);
58 uint64_t parseExpr1(uint64_t Lhs, int MinPrec);
59 uint64_t parseExpr();
60
61 uint64_t Dot;
62};
63}
64
Rui Ueyama960504b2016-04-19 18:58:11 +000065static int precedence(StringRef Op) {
66 return StringSwitch<int>(Op)
67 .Case("*", 4)
George Rimarab939062016-04-25 08:14:41 +000068 .Case("/", 4)
69 .Case("+", 3)
70 .Case("-", 3)
71 .Case("<", 2)
72 .Case(">", 2)
73 .Case(">=", 2)
74 .Case("<=", 2)
75 .Case("==", 2)
76 .Case("!=", 2)
Rui Ueyama960504b2016-04-19 18:58:11 +000077 .Case("&", 1)
78 .Default(-1);
79}
80
Rui Ueyama9c1112d2016-04-23 00:04:03 +000081static uint64_t evalExpr(std::vector<StringRef> &Tokens, uint64_t Dot) {
82 return ExprParser(Tokens, Dot).run();
Rui Ueyama960504b2016-04-19 18:58:11 +000083}
84
Rui Ueyama9c1112d2016-04-23 00:04:03 +000085uint64_t ExprParser::run() {
86 uint64_t V = parseExpr();
87 if (!atEOF() && !Error)
88 setError("stray token: " + peek());
89 return V;
Rui Ueyama60118112016-04-20 20:54:13 +000090}
91
Rui Ueyama960504b2016-04-19 18:58:11 +000092// This is a part of the operator-precedence parser to evaluate
93// arithmetic expressions in SECTIONS command. This function evaluates an
Rui Ueyamae29a9752016-04-22 21:02:27 +000094// integer literal, a parenthesized expression, the ALIGN function,
95// or the special variable ".".
Rui Ueyama9c1112d2016-04-23 00:04:03 +000096uint64_t ExprParser::parsePrimary() {
97 StringRef Tok = next();
Rui Ueyama960504b2016-04-19 18:58:11 +000098 if (Tok == ".")
99 return Dot;
100 if (Tok == "(") {
Rui Ueyama9c1112d2016-04-23 00:04:03 +0000101 uint64_t V = parseExpr();
102 expect(")");
Rui Ueyama960504b2016-04-19 18:58:11 +0000103 return V;
104 }
George Rimardffc1412016-04-22 11:40:53 +0000105 if (Tok == "ALIGN") {
Rui Ueyama9c1112d2016-04-23 00:04:03 +0000106 expect("(");
107 uint64_t V = parseExpr();
108 expect(")");
George Rimardffc1412016-04-22 11:40:53 +0000109 return alignTo(Dot, V);
110 }
Rui Ueyama5fa60982016-04-22 21:05:04 +0000111 uint64_t V = 0;
112 if (Tok.getAsInteger(0, V))
Rui Ueyama9c1112d2016-04-23 00:04:03 +0000113 setError("malformed number: " + Tok);
Rui Ueyama5fa60982016-04-22 21:05:04 +0000114 return V;
Rui Ueyama960504b2016-04-19 18:58:11 +0000115}
116
Rui Ueyama9c1112d2016-04-23 00:04:03 +0000117uint64_t ExprParser::parseTernary(uint64_t Cond) {
118 next();
119 uint64_t V = parseExpr();
120 expect(":");
121 uint64_t W = parseExpr();
George Rimarfba45c42016-04-22 11:28:54 +0000122 return Cond ? V : W;
123}
124
Rui Ueyama9c1112d2016-04-23 00:04:03 +0000125uint64_t ExprParser::apply(StringRef Op, uint64_t L, uint64_t R) {
Rui Ueyama960504b2016-04-19 18:58:11 +0000126 if (Op == "*")
127 return L * R;
128 if (Op == "/") {
129 if (R == 0) {
130 error("division by zero");
George Rimar652852c2016-04-16 10:10:32 +0000131 return 0;
132 }
Rui Ueyama960504b2016-04-19 18:58:11 +0000133 return L / R;
George Rimar652852c2016-04-16 10:10:32 +0000134 }
George Rimarab939062016-04-25 08:14:41 +0000135 if (Op == "+")
136 return L + R;
137 if (Op == "-")
138 return L - R;
139 if (Op == "<")
140 return L < R;
141 if (Op == ">")
142 return L > R;
143 if (Op == ">=")
144 return L >= R;
145 if (Op == "<=")
146 return L <= R;
147 if (Op == "==")
148 return L == R;
149 if (Op == "!=")
150 return L != R;
Rui Ueyama960504b2016-04-19 18:58:11 +0000151 if (Op == "&")
152 return L & R;
Rui Ueyama7a81d672016-04-19 19:04:03 +0000153 llvm_unreachable("invalid operator");
Rui Ueyama960504b2016-04-19 18:58:11 +0000154}
155
Rui Ueyama9c1112d2016-04-23 00:04:03 +0000156// This is a part of the operator-precedence parser.
157// This function assumes that the remaining token stream starts
158// with an operator.
159uint64_t ExprParser::parseExpr1(uint64_t Lhs, int MinPrec) {
160 while (!atEOF()) {
Rui Ueyama960504b2016-04-19 18:58:11 +0000161 // Read an operator and an expression.
Rui Ueyama9c1112d2016-04-23 00:04:03 +0000162 StringRef Op1 = peek();
George Rimarfba45c42016-04-22 11:28:54 +0000163 if (Op1 == "?")
Rui Ueyama9c1112d2016-04-23 00:04:03 +0000164 return parseTernary(Lhs);
Rui Ueyama960504b2016-04-19 18:58:11 +0000165 if (precedence(Op1) < MinPrec)
166 return Lhs;
Rui Ueyama9c1112d2016-04-23 00:04:03 +0000167 next();
168 uint64_t Rhs = parsePrimary();
Rui Ueyama960504b2016-04-19 18:58:11 +0000169
170 // Evaluate the remaining part of the expression first if the
171 // next operator has greater precedence than the previous one.
172 // For example, if we have read "+" and "3", and if the next
173 // operator is "*", then we'll evaluate 3 * ... part first.
Rui Ueyama9c1112d2016-04-23 00:04:03 +0000174 while (!atEOF()) {
175 StringRef Op2 = peek();
Rui Ueyama960504b2016-04-19 18:58:11 +0000176 if (precedence(Op2) <= precedence(Op1))
177 break;
Rui Ueyama9c1112d2016-04-23 00:04:03 +0000178 Rhs = parseExpr1(Rhs, precedence(Op2));
Rui Ueyama960504b2016-04-19 18:58:11 +0000179 }
180
181 Lhs = apply(Op1, Lhs, Rhs);
182 }
183 return Lhs;
184}
185
Rui Ueyama9c1112d2016-04-23 00:04:03 +0000186// Reads and evaluates an arithmetic expression.
187uint64_t ExprParser::parseExpr() { return parseExpr1(parsePrimary(), 0); }
George Rimar652852c2016-04-16 10:10:32 +0000188
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +0000189template <class ELFT>
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000190StringRef LinkerScript<ELFT>::getOutputSection(InputSectionBase<ELFT> *S) {
Rui Ueyama07320e42016-04-20 20:13:41 +0000191 for (SectionRule &R : Opt.Sections)
Rui Ueyama722830a2016-06-29 05:32:09 +0000192 if (globMatch(R.SectionPattern, S->getSectionName()))
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000193 return R.Dest;
194 return "";
Rui Ueyama717677a2016-02-11 21:17:59 +0000195}
196
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +0000197template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000198bool LinkerScript<ELFT>::isDiscarded(InputSectionBase<ELFT> *S) {
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +0000199 return getOutputSection(S) == "/DISCARD/";
Rui Ueyama717677a2016-02-11 21:17:59 +0000200}
201
Rui Ueyama07320e42016-04-20 20:13:41 +0000202template <class ELFT>
203bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) {
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000204 for (StringRef Pat : Opt.KeptSections)
Rui Ueyama722830a2016-06-29 05:32:09 +0000205 if (globMatch(Pat, S->getSectionName()))
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000206 return true;
207 return false;
George Rimar481c2ce2016-02-23 07:47:54 +0000208}
209
George Rimar652852c2016-04-16 10:10:32 +0000210template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000211void LinkerScript<ELFT>::assignAddresses(
George Rimardbbd8b12016-04-21 11:21:48 +0000212 ArrayRef<OutputSectionBase<ELFT> *> Sections) {
George Rimar652852c2016-04-16 10:10:32 +0000213 // Orphan sections are sections present in the input files which
Rui Ueyama7c18c282016-04-18 21:00:40 +0000214 // are not explicitly placed into the output file by the linker script.
215 // We place orphan sections at end of file.
216 // Other linkers places them using some heuristics as described in
George Rimar652852c2016-04-16 10:10:32 +0000217 // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
Rui Ueyama7c18c282016-04-18 21:00:40 +0000218 for (OutputSectionBase<ELFT> *Sec : Sections) {
George Rimar652852c2016-04-16 10:10:32 +0000219 StringRef Name = Sec->getName();
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000220 if (getSectionIndex(Name) == INT_MAX)
Eugene Leviantbbe38602016-07-19 09:25:43 +0000221 Opt.Commands.push_back({SectionKind, {}, Name, {}});
George Rimar652852c2016-04-16 10:10:32 +0000222 }
George Rimar652852c2016-04-16 10:10:32 +0000223
Rui Ueyama7c18c282016-04-18 21:00:40 +0000224 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rui Ueyama52c4e172016-07-01 10:42:25 +0000225 Dot = Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
Eugene Leviant467c4d52016-07-01 10:27:36 +0000226 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
George Rimar652852c2016-04-16 10:10:32 +0000227 uintX_t ThreadBssOffset = 0;
George Rimar652852c2016-04-16 10:10:32 +0000228
Rui Ueyama07320e42016-04-20 20:13:41 +0000229 for (SectionsCommand &Cmd : Opt.Commands) {
Rui Ueyama05ef4cf2016-07-15 04:19:37 +0000230 if (Cmd.Kind == AssignmentKind) {
231 uint64_t Val = evalExpr(Cmd.Expr, Dot);
232
233 if (Cmd.Name == ".") {
234 Dot = Val;
235 } else {
236 auto *D = cast<DefinedRegular<ELFT>>(Symtab<ELFT>::X->find(Cmd.Name));
237 D->Value = Val;
238 }
George Rimar652852c2016-04-16 10:10:32 +0000239 continue;
240 }
241
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000242 // Find all the sections with required name. There can be more than
George Rimar6ad330a2016-07-19 07:39:07 +0000243 // one section with such name, if the alignment, flags or type
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000244 // attribute differs.
Rui Ueyama05ef4cf2016-07-15 04:19:37 +0000245 assert(Cmd.Kind == SectionKind);
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000246 for (OutputSectionBase<ELFT> *Sec : Sections) {
Eugene Levianteda81a12016-07-12 06:39:48 +0000247 if (Sec->getName() != Cmd.Name)
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000248 continue;
George Rimar652852c2016-04-16 10:10:32 +0000249
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000250 if ((Sec->getFlags() & SHF_TLS) && Sec->getType() == SHT_NOBITS) {
251 uintX_t TVA = Dot + ThreadBssOffset;
Rui Ueyama424b4082016-06-17 01:18:46 +0000252 TVA = alignTo(TVA, Sec->getAlignment());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000253 Sec->setVA(TVA);
254 ThreadBssOffset = TVA - Dot + Sec->getSize();
255 continue;
256 }
George Rimar652852c2016-04-16 10:10:32 +0000257
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000258 if (Sec->getFlags() & SHF_ALLOC) {
Rui Ueyama424b4082016-06-17 01:18:46 +0000259 Dot = alignTo(Dot, Sec->getAlignment());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000260 Sec->setVA(Dot);
Rui Ueyama52c4e172016-07-01 10:42:25 +0000261 MinVA = std::min(MinVA, Dot);
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000262 Dot += Sec->getSize();
263 continue;
264 }
George Rimar652852c2016-04-16 10:10:32 +0000265 }
266 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000267
Rafael Espindola64c32d62016-07-07 14:28:47 +0000268 // ELF and Program headers need to be right before the first section in
George Rimarb91e7112016-07-19 07:42:07 +0000269 // memory. Set their addresses accordingly.
Eugene Leviant467c4d52016-07-01 10:27:36 +0000270 MinVA = alignDown(MinVA - Out<ELFT>::ElfHeader->getSize() -
271 Out<ELFT>::ProgramHeaders->getSize(),
272 Target->PageSize);
273 Out<ELFT>::ElfHeader->setVA(MinVA);
274 Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
George Rimar652852c2016-04-16 10:10:32 +0000275}
276
Rui Ueyama07320e42016-04-20 20:13:41 +0000277template <class ELFT>
Rafael Espindola74df5c72016-07-19 12:33:46 +0000278std::vector<PhdrEntry<ELFT>>
Eugene Leviantbbe38602016-07-19 09:25:43 +0000279LinkerScript<ELFT>::createPhdrs(ArrayRef<OutputSectionBase<ELFT> *> Sections) {
280 int TlsNum = -1;
281 int NoteNum = -1;
282 int RelroNum = -1;
283 Phdr *Load = nullptr;
284 uintX_t Flags = PF_R;
285 std::vector<Phdr> Phdrs;
286
287 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
288 Phdrs.emplace_back(Cmd.Type, PF_R);
289 Phdr &Added = Phdrs.back();
290
291 if (Cmd.HasFilehdr)
292 Added.AddSec(Out<ELFT>::ElfHeader);
293 if (Cmd.HasPhdrs)
294 Added.AddSec(Out<ELFT>::ProgramHeaders);
295
296 switch (Cmd.Type) {
297 case PT_INTERP:
298 if (needsInterpSection<ELFT>())
299 Added.AddSec(Out<ELFT>::Interp);
300 break;
301 case PT_DYNAMIC:
302 if (isOutputDynamic<ELFT>()) {
303 Added.H.p_flags = toPhdrFlags(Out<ELFT>::Dynamic->getFlags());
304 Added.AddSec(Out<ELFT>::Dynamic);
305 }
306 break;
307 case PT_TLS:
308 TlsNum = Phdrs.size() - 1;
309 break;
310 case PT_NOTE:
311 NoteNum = Phdrs.size() - 1;
312 break;
313 case PT_GNU_RELRO:
314 RelroNum = Phdrs.size() - 1;
315 break;
316 case PT_GNU_EH_FRAME:
317 if (!Out<ELFT>::EhFrame->empty() && Out<ELFT>::EhFrameHdr) {
318 Added.H.p_flags = toPhdrFlags(Out<ELFT>::EhFrameHdr->getFlags());
319 Added.AddSec(Out<ELFT>::EhFrameHdr);
320 }
321 break;
322 }
323 }
324
325 for (OutputSectionBase<ELFT> *Sec : Sections) {
326 if (!(Sec->getFlags() & SHF_ALLOC))
327 break;
328
329 if (TlsNum != -1 && (Sec->getFlags() & SHF_TLS))
330 Phdrs[TlsNum].AddSec(Sec);
331
332 if (!needsPtLoad<ELFT>(Sec))
333 continue;
334
335 const std::vector<size_t> &PhdrIds =
336 getPhdrIndicesForSection(Sec->getName());
337 if (!PhdrIds.empty()) {
338 // Assign headers specified by linker script
339 for (size_t Id : PhdrIds) {
340 Phdrs[Id].AddSec(Sec);
341 Phdrs[Id].H.p_flags |= toPhdrFlags(Sec->getFlags());
342 }
343 } else {
344 // If we have no load segment or flags've changed then we want new load
345 // segment.
346 uintX_t NewFlags = toPhdrFlags(Sec->getFlags());
347 if (Load == nullptr || Flags != NewFlags) {
348 Load = &*Phdrs.emplace(Phdrs.end(), PT_LOAD, NewFlags);
349 Flags = NewFlags;
350 }
351 Load->AddSec(Sec);
352 }
353
354 if (RelroNum != -1 && isRelroSection(Sec))
355 Phdrs[RelroNum].AddSec(Sec);
356 if (NoteNum != -1 && Sec->getType() == SHT_NOTE)
357 Phdrs[NoteNum].AddSec(Sec);
358 }
359 return Phdrs;
360}
361
362template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000363ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
364 auto I = Opt.Filler.find(Name);
365 if (I == Opt.Filler.end())
Rui Ueyama3e808972016-02-28 05:09:11 +0000366 return {};
367 return I->second;
George Rimare2ee72b2016-02-26 14:48:31 +0000368}
369
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000370// Returns the index of the given section name in linker script
371// SECTIONS commands. Sections are laid out as the same order as they
372// were in the script. If a given name did not appear in the script,
373// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar71b26e92016-04-21 10:22:02 +0000374template <class ELFT>
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000375int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
George Rimar71b26e92016-04-21 10:22:02 +0000376 auto Begin = Opt.Commands.begin();
377 auto End = Opt.Commands.end();
378 auto I = std::find_if(Begin, End, [&](SectionsCommand &N) {
Eugene Levianteda81a12016-07-12 06:39:48 +0000379 return N.Kind == SectionKind && N.Name == Name;
George Rimar71b26e92016-04-21 10:22:02 +0000380 });
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000381 return I == End ? INT_MAX : (I - Begin);
George Rimar71b26e92016-04-21 10:22:02 +0000382}
383
384// A compartor to sort output sections. Returns -1 or 1 if
385// A or B are mentioned in linker script. Otherwise, returns 0.
Rui Ueyama07320e42016-04-20 20:13:41 +0000386template <class ELFT>
387int LinkerScript<ELFT>::compareSections(StringRef A, StringRef B) {
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000388 int I = getSectionIndex(A);
389 int J = getSectionIndex(B);
390 if (I == INT_MAX && J == INT_MAX)
Rui Ueyama717677a2016-02-11 21:17:59 +0000391 return 0;
392 return I < J ? -1 : 1;
393}
394
Eugene Leviantb0304112016-07-14 09:21:24 +0000395template <class ELFT>
396void LinkerScript<ELFT>::addScriptedSymbols() {
Eugene Levianteda81a12016-07-12 06:39:48 +0000397 for (SectionsCommand &Cmd : Opt.Commands)
Rui Ueyama05ef4cf2016-07-15 04:19:37 +0000398 if (Cmd.Kind == AssignmentKind)
Eugene Leviant0e36f422016-07-15 11:20:04 +0000399 if (Cmd.Name != "." && Symtab<ELFT>::X->find(Cmd.Name) == nullptr)
Rui Ueyama05ef4cf2016-07-15 04:19:37 +0000400 Symtab<ELFT>::X->addAbsolute(Cmd.Name, STV_DEFAULT);
Eugene Levianteda81a12016-07-12 06:39:48 +0000401}
402
Eugene Leviantbbe38602016-07-19 09:25:43 +0000403template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
404 return !Opt.PhdrsCommands.empty();
405}
406
407// Returns indices of ELF headers containing specific section, identified
408// by Name. Each index is a zero based number of ELF header listed within
409// PHDRS {} script block.
410template <class ELFT>
411std::vector<size_t>
412LinkerScript<ELFT>::getPhdrIndicesForSection(StringRef Name) {
413 std::vector<size_t> Indices;
414 auto ItSect = std::find_if(
415 Opt.Commands.begin(), Opt.Commands.end(),
416 [Name](const SectionsCommand &Cmd) { return Cmd.Name == Name; });
417 if (ItSect != Opt.Commands.end()) {
418 SectionsCommand &SecCmd = (*ItSect);
419 for (StringRef PhdrName : SecCmd.Phdrs) {
420 auto ItPhdr = std::find_if(
421 Opt.PhdrsCommands.rbegin(), Opt.PhdrsCommands.rend(),
422 [PhdrName](PhdrsCommand &Cmd) { return Cmd.Name == PhdrName; });
423 if (ItPhdr == Opt.PhdrsCommands.rend())
424 error("section header '" + PhdrName + "' is not listed in PHDRS");
425 else
426 Indices.push_back(std::distance(ItPhdr, Opt.PhdrsCommands.rend()) - 1);
427 }
428 }
429 return Indices;
430}
431
Rui Ueyama07320e42016-04-20 20:13:41 +0000432class elf::ScriptParser : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000433 typedef void (ScriptParser::*Handler)();
434
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000435public:
Rui Ueyama07320e42016-04-20 20:13:41 +0000436 ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
George Rimarf23b2322016-02-19 10:45:45 +0000437
Rui Ueyama4a465392016-04-22 22:59:24 +0000438 void run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000439
440private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000441 void addFile(StringRef Path);
442
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000443 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000444 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000445 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000446 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000447 void readInclude();
George Rimarc3794e52016-02-24 09:21:47 +0000448 void readNothing() {}
Rui Ueyamaee592822015-10-07 00:25:09 +0000449 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000450 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000451 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000452 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000453 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000454 void readSections();
455
George Rimar652852c2016-04-16 10:10:32 +0000456 void readLocationCounterValue();
Eugene Levianteda81a12016-07-12 06:39:48 +0000457 void readOutputSectionDescription(StringRef OutSec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000458 std::vector<StringRef> readOutputSectionPhdrs();
459 unsigned readPhdrType();
Eugene Levianteda81a12016-07-12 06:39:48 +0000460 void readSymbolAssignment(StringRef Name);
461 std::vector<StringRef> readSectionsCommandExpr();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000462
George Rimarc3794e52016-02-24 09:21:47 +0000463 const static StringMap<Handler> Cmd;
Rui Ueyama07320e42016-04-20 20:13:41 +0000464 ScriptConfiguration &Opt = *ScriptConfig;
465 StringSaver Saver = {ScriptConfig->Alloc};
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000466 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000467};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000468
Rafael Espindolae0df00b2016-02-28 00:25:54 +0000469const StringMap<elf::ScriptParser::Handler> elf::ScriptParser::Cmd = {
George Rimarc3794e52016-02-24 09:21:47 +0000470 {"ENTRY", &ScriptParser::readEntry},
471 {"EXTERN", &ScriptParser::readExtern},
472 {"GROUP", &ScriptParser::readGroup},
473 {"INCLUDE", &ScriptParser::readInclude},
474 {"INPUT", &ScriptParser::readGroup},
475 {"OUTPUT", &ScriptParser::readOutput},
476 {"OUTPUT_ARCH", &ScriptParser::readOutputArch},
477 {"OUTPUT_FORMAT", &ScriptParser::readOutputFormat},
Eugene Leviantbbe38602016-07-19 09:25:43 +0000478 {"PHDRS", &ScriptParser::readPhdrs},
George Rimarc3794e52016-02-24 09:21:47 +0000479 {"SEARCH_DIR", &ScriptParser::readSearchDir},
480 {"SECTIONS", &ScriptParser::readSections},
481 {";", &ScriptParser::readNothing}};
482
Rui Ueyama717677a2016-02-11 21:17:59 +0000483void ScriptParser::run() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000484 while (!atEOF()) {
485 StringRef Tok = next();
George Rimarc3794e52016-02-24 09:21:47 +0000486 if (Handler Fn = Cmd.lookup(Tok))
487 (this->*Fn)();
488 else
George Rimar57610422016-03-11 14:43:02 +0000489 setError("unknown directive: " + Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000490 }
491}
492
Rui Ueyama717677a2016-02-11 21:17:59 +0000493void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000494 if (IsUnderSysroot && S.startswith("/")) {
495 SmallString<128> Path;
496 (Config->Sysroot + S).toStringRef(Path);
497 if (sys::fs::exists(Path)) {
498 Driver->addFile(Saver.save(Path.str()));
499 return;
500 }
501 }
502
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +0000503 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +0000504 Driver->addFile(S);
505 } else if (S.startswith("=")) {
506 if (Config->Sysroot.empty())
507 Driver->addFile(S.substr(1));
508 else
509 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
510 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +0000511 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +0000512 } else if (sys::fs::exists(S)) {
513 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +0000514 } else {
515 std::string Path = findFromSearchPaths(S);
516 if (Path.empty())
George Rimar777f9632016-03-12 08:31:34 +0000517 setError("unable to find " + S);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000518 else
519 Driver->addFile(Saver.save(Path));
Rui Ueyama52a15092015-10-11 03:28:42 +0000520 }
521}
522
Rui Ueyama717677a2016-02-11 21:17:59 +0000523void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000524 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +0000525 bool Orig = Config->AsNeeded;
526 Config->AsNeeded = true;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000527 while (!Error) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000528 StringRef Tok = next();
529 if (Tok == ")")
Rui Ueyama35da9b62015-10-11 20:59:12 +0000530 break;
Rui Ueyama52a15092015-10-11 03:28:42 +0000531 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000532 }
Rui Ueyama35da9b62015-10-11 20:59:12 +0000533 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000534}
535
Rui Ueyama717677a2016-02-11 21:17:59 +0000536void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +0000537 // -e <symbol> takes predecence over ENTRY(<symbol>).
538 expect("(");
539 StringRef Tok = next();
540 if (Config->Entry.empty())
541 Config->Entry = Tok;
542 expect(")");
543}
544
Rui Ueyama717677a2016-02-11 21:17:59 +0000545void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +0000546 expect("(");
Rui Ueyama025d59b2016-02-02 20:27:59 +0000547 while (!Error) {
George Rimar83f406c2015-10-19 17:35:12 +0000548 StringRef Tok = next();
549 if (Tok == ")")
550 return;
551 Config->Undefined.push_back(Tok);
552 }
553}
554
Rui Ueyama717677a2016-02-11 21:17:59 +0000555void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000556 expect("(");
Rui Ueyama025d59b2016-02-02 20:27:59 +0000557 while (!Error) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000558 StringRef Tok = next();
559 if (Tok == ")")
560 return;
561 if (Tok == "AS_NEEDED") {
562 readAsNeeded();
563 continue;
564 }
Rui Ueyama52a15092015-10-11 03:28:42 +0000565 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000566 }
567}
568
Rui Ueyama717677a2016-02-11 21:17:59 +0000569void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000570 StringRef Tok = next();
571 auto MBOrErr = MemoryBuffer::getFile(Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000572 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +0000573 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000574 return;
575 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000576 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Rui Ueyamaa47ee682015-10-11 01:53:04 +0000577 StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
578 std::vector<StringRef> V = tokenize(S);
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000579 Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000580}
581
Rui Ueyama717677a2016-02-11 21:17:59 +0000582void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +0000583 // -o <file> takes predecence over OUTPUT(<file>).
584 expect("(");
585 StringRef Tok = next();
586 if (Config->OutputFile.empty())
587 Config->OutputFile = Tok;
588 expect(")");
589}
590
Rui Ueyama717677a2016-02-11 21:17:59 +0000591void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +0000592 // Error checking only for now.
593 expect("(");
594 next();
595 expect(")");
596}
597
Rui Ueyama717677a2016-02-11 21:17:59 +0000598void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000599 // Error checking only for now.
600 expect("(");
601 next();
Davide Italiano6836c612015-10-12 21:08:41 +0000602 StringRef Tok = next();
603 if (Tok == ")")
604 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000605 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +0000606 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000607 return;
608 }
Davide Italiano6836c612015-10-12 21:08:41 +0000609 next();
610 expect(",");
611 next();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000612 expect(")");
613}
614
Eugene Leviantbbe38602016-07-19 09:25:43 +0000615void ScriptParser::readPhdrs() {
616 expect("{");
617 while (!Error && !skip("}")) {
618 StringRef Tok = next();
619 Opt.PhdrsCommands.push_back({Tok, PT_NULL, false, false});
620 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
621
622 PhdrCmd.Type = readPhdrType();
623 do {
624 Tok = next();
625 if (Tok == ";")
626 break;
627 if (Tok == "FILEHDR")
628 PhdrCmd.HasFilehdr = true;
629 else if (Tok == "PHDRS")
630 PhdrCmd.HasPhdrs = true;
631 else
632 setError("unexpected header attribute: " + Tok);
633 } while (!Error);
634 }
635}
636
Rui Ueyama717677a2016-02-11 21:17:59 +0000637void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +0000638 expect("(");
Rafael Espindola06501922016-03-08 17:13:12 +0000639 Config->SearchPaths.push_back(next());
Davide Italiano68a39a62015-10-08 17:51:41 +0000640 expect(")");
641}
642
Rui Ueyama717677a2016-02-11 21:17:59 +0000643void ScriptParser::readSections() {
Rui Ueyama07320e42016-04-20 20:13:41 +0000644 Opt.DoLayout = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000645 expect("{");
George Rimar652852c2016-04-16 10:10:32 +0000646 while (!Error && !skip("}")) {
647 StringRef Tok = peek();
Eugene Levianteda81a12016-07-12 06:39:48 +0000648 if (Tok == ".") {
George Rimar652852c2016-04-16 10:10:32 +0000649 readLocationCounterValue();
Eugene Levianteda81a12016-07-12 06:39:48 +0000650 continue;
651 }
652 next();
653 if (peek() == "=")
654 readSymbolAssignment(Tok);
George Rimar652852c2016-04-16 10:10:32 +0000655 else
Eugene Levianteda81a12016-07-12 06:39:48 +0000656 readOutputSectionDescription(Tok);
George Rimar652852c2016-04-16 10:10:32 +0000657 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000658}
659
George Rimar652852c2016-04-16 10:10:32 +0000660void ScriptParser::readLocationCounterValue() {
661 expect(".");
662 expect("=");
Eugene Levianteda81a12016-07-12 06:39:48 +0000663 std::vector<StringRef> Expr = readSectionsCommandExpr();
664 if (Expr.empty())
George Rimar652852c2016-04-16 10:10:32 +0000665 error("error in location counter expression");
Eugene Levianteda81a12016-07-12 06:39:48 +0000666 else
Eugene Leviantbbe38602016-07-19 09:25:43 +0000667 Opt.Commands.push_back({AssignmentKind, std::move(Expr), ".", {}});
George Rimar652852c2016-04-16 10:10:32 +0000668}
669
Eugene Levianteda81a12016-07-12 06:39:48 +0000670void ScriptParser::readOutputSectionDescription(StringRef OutSec) {
Eugene Leviantbbe38602016-07-19 09:25:43 +0000671 Opt.Commands.push_back({SectionKind, {}, OutSec, {}});
672 SectionsCommand &Cmd = Opt.Commands.back();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000673 expect(":");
674 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000675
Rui Ueyama025d59b2016-02-02 20:27:59 +0000676 while (!Error && !skip("}")) {
George Rimar481c2ce2016-02-23 07:47:54 +0000677 StringRef Tok = next();
678 if (Tok == "*") {
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000679 expect("(");
680 while (!Error && !skip(")"))
681 Opt.Sections.emplace_back(OutSec, next());
George Rimar481c2ce2016-02-23 07:47:54 +0000682 } else if (Tok == "KEEP") {
683 expect("(");
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000684 expect("*");
685 expect("(");
686 while (!Error && !skip(")")) {
687 StringRef Sec = next();
688 Opt.Sections.emplace_back(OutSec, Sec);
689 Opt.KeptSections.push_back(Sec);
690 }
George Rimar481c2ce2016-02-23 07:47:54 +0000691 expect(")");
692 } else {
George Rimar777f9632016-03-12 08:31:34 +0000693 setError("unknown command " + Tok);
George Rimar481c2ce2016-02-23 07:47:54 +0000694 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000695 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000696 Cmd.Phdrs = readOutputSectionPhdrs();
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000697
George Rimare2ee72b2016-02-26 14:48:31 +0000698 StringRef Tok = peek();
699 if (Tok.startswith("=")) {
700 if (!Tok.startswith("=0x")) {
Rui Ueyama3ed2f062016-03-13 03:17:44 +0000701 setError("filler should be a hexadecimal value");
George Rimare2ee72b2016-02-26 14:48:31 +0000702 return;
703 }
Rui Ueyama3e808972016-02-28 05:09:11 +0000704 Tok = Tok.substr(3);
Rui Ueyama07320e42016-04-20 20:13:41 +0000705 Opt.Filler[OutSec] = parseHex(Tok);
George Rimare2ee72b2016-02-26 14:48:31 +0000706 next();
707 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000708}
709
Eugene Levianteda81a12016-07-12 06:39:48 +0000710void ScriptParser::readSymbolAssignment(StringRef Name) {
711 expect("=");
712 std::vector<StringRef> Expr = readSectionsCommandExpr();
713 if (Expr.empty())
714 error("error in symbol assignment expression");
715 else
Eugene Leviantbbe38602016-07-19 09:25:43 +0000716 Opt.Commands.push_back({AssignmentKind, std::move(Expr), Name, {}});
Eugene Levianteda81a12016-07-12 06:39:48 +0000717}
718
719std::vector<StringRef> ScriptParser::readSectionsCommandExpr() {
720 std::vector<StringRef> Expr;
721 while (!Error) {
722 StringRef Tok = next();
723 if (Tok == ";")
724 break;
725 Expr.push_back(Tok);
726 }
727 return Expr;
728}
729
Eugene Leviantbbe38602016-07-19 09:25:43 +0000730std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
731 std::vector<StringRef> Phdrs;
732 while (!Error && peek().startswith(":")) {
733 StringRef Tok = next();
734 Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
735 if (Tok.empty()) {
736 setError("section header name is empty");
737 break;
738 }
739 else
740 Phdrs.push_back(Tok);
741 }
742 return Phdrs;
743}
744
745unsigned ScriptParser::readPhdrType() {
746 static const char *typeNames[] = {
747 "PT_NULL", "PT_LOAD", "PT_DYNAMIC", "PT_INTERP",
748 "PT_NOTE", "PT_SHLIB", "PT_PHDR", "PT_TLS",
749 "PT_GNU_EH_FRAME", "PT_GNU_STACK", "PT_GNU_RELRO"};
750 static unsigned typeCodes[] = {
751 PT_NULL, PT_LOAD, PT_DYNAMIC, PT_INTERP, PT_NOTE, PT_SHLIB,
752 PT_PHDR, PT_TLS, PT_GNU_EH_FRAME, PT_GNU_STACK, PT_GNU_RELRO};
753
754 unsigned PhdrType = PT_NULL;
755 StringRef Tok = next();
756 auto It = std::find(std::begin(typeNames), std::end(typeNames), Tok);
757 if (It != std::end(typeNames))
758 PhdrType = typeCodes[std::distance(std::begin(typeNames), It)];
759 else
760 setError("invalid program header type");
761
762 return PhdrType;
763}
764
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000765static bool isUnderSysroot(StringRef Path) {
766 if (Config->Sysroot == "")
767 return false;
768 for (; !Path.empty(); Path = sys::path::parent_path(Path))
769 if (sys::fs::equivalent(Config->Sysroot, Path))
770 return true;
771 return false;
772}
773
Rui Ueyama07320e42016-04-20 20:13:41 +0000774// Entry point.
775void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000776 StringRef Path = MB.getBufferIdentifier();
Rui Ueyama07320e42016-04-20 20:13:41 +0000777 ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000778}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +0000779
Rui Ueyama07320e42016-04-20 20:13:41 +0000780template class elf::LinkerScript<ELF32LE>;
781template class elf::LinkerScript<ELF32BE>;
782template class elf::LinkerScript<ELF64LE>;
783template class elf::LinkerScript<ELF64BE>;