blob: aaf2b9da803bdd2b916600f26fa08a0d8386dd5a [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) {
Eugene Leviante63d81b2016-07-20 14:43:20 +0000199 return !S || !S->Live || 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>
Eugene Leviante63d81b2016-07-20 14:43:20 +0000211std::vector<std::unique_ptr<OutputSectionBase<ELFT>>>
212LinkerScript<ELFT>::createSections(OutputSectionFactory<ELFT> &Factory) {
213 std::vector<std::unique_ptr<OutputSectionBase<ELFT>>> Result;
214 // Add input section to output section. If there is no output section yet,
215 // then create it and add to output section list.
216 auto AddInputSec = [&](InputSectionBase<ELFT> *C, StringRef Name) {
217 OutputSectionBase<ELFT> *Sec;
218 bool IsNew;
219 std::tie(Sec, IsNew) = Factory.create(C, Name);
220 if (IsNew)
221 Result.emplace_back(Sec);
222 Sec->addSection(C);
223 };
224
225 // Select input sections matching rule and add them to corresponding
226 // output section. Section rules are processed in order they're listed
227 // in script, so correct input section order is maintained by design.
228 for (SectionRule &R : Opt.Sections)
229 for (const std::unique_ptr<ObjectFile<ELFT>> &F :
230 Symtab<ELFT>::X->getObjectFiles())
231 for (InputSectionBase<ELFT> *S : F->getSections())
232 if (!isDiscarded(S) && !S->OutSec &&
233 globMatch(R.SectionPattern, S->getSectionName()))
234 // Add single input section to output section.
235 AddInputSec(S, R.Dest);
236
237 // Add all other input sections, which are not listed in script.
238 for (const std::unique_ptr<ObjectFile<ELFT>> &F :
239 Symtab<ELFT>::X->getObjectFiles())
240 for (InputSectionBase<ELFT> *S : F->getSections())
241 if (!isDiscarded(S)) {
242 if (!S->OutSec)
243 AddInputSec(S, getOutputSectionName(S));
244 } else
245 reportDiscarded(S, F);
246
247 return Result;
248}
249
250template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000251void LinkerScript<ELFT>::assignAddresses(
George Rimardbbd8b12016-04-21 11:21:48 +0000252 ArrayRef<OutputSectionBase<ELFT> *> Sections) {
George Rimar652852c2016-04-16 10:10:32 +0000253 // Orphan sections are sections present in the input files which
Rui Ueyama7c18c282016-04-18 21:00:40 +0000254 // are not explicitly placed into the output file by the linker script.
255 // We place orphan sections at end of file.
256 // Other linkers places them using some heuristics as described in
George Rimar652852c2016-04-16 10:10:32 +0000257 // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
Rui Ueyama7c18c282016-04-18 21:00:40 +0000258 for (OutputSectionBase<ELFT> *Sec : Sections) {
George Rimar652852c2016-04-16 10:10:32 +0000259 StringRef Name = Sec->getName();
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000260 if (getSectionIndex(Name) == INT_MAX)
Eugene Leviantbbe38602016-07-19 09:25:43 +0000261 Opt.Commands.push_back({SectionKind, {}, Name, {}});
George Rimar652852c2016-04-16 10:10:32 +0000262 }
George Rimar652852c2016-04-16 10:10:32 +0000263
Rui Ueyama7c18c282016-04-18 21:00:40 +0000264 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rui Ueyama52c4e172016-07-01 10:42:25 +0000265 Dot = Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
Eugene Leviant467c4d52016-07-01 10:27:36 +0000266 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
George Rimar652852c2016-04-16 10:10:32 +0000267 uintX_t ThreadBssOffset = 0;
George Rimar652852c2016-04-16 10:10:32 +0000268
Rui Ueyama07320e42016-04-20 20:13:41 +0000269 for (SectionsCommand &Cmd : Opt.Commands) {
Rui Ueyama05ef4cf2016-07-15 04:19:37 +0000270 if (Cmd.Kind == AssignmentKind) {
271 uint64_t Val = evalExpr(Cmd.Expr, Dot);
272
273 if (Cmd.Name == ".") {
274 Dot = Val;
275 } else {
276 auto *D = cast<DefinedRegular<ELFT>>(Symtab<ELFT>::X->find(Cmd.Name));
277 D->Value = Val;
278 }
George Rimar652852c2016-04-16 10:10:32 +0000279 continue;
280 }
281
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000282 // Find all the sections with required name. There can be more than
George Rimar6ad330a2016-07-19 07:39:07 +0000283 // one section with such name, if the alignment, flags or type
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000284 // attribute differs.
Rui Ueyama05ef4cf2016-07-15 04:19:37 +0000285 assert(Cmd.Kind == SectionKind);
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000286 for (OutputSectionBase<ELFT> *Sec : Sections) {
Eugene Levianteda81a12016-07-12 06:39:48 +0000287 if (Sec->getName() != Cmd.Name)
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000288 continue;
George Rimar652852c2016-04-16 10:10:32 +0000289
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000290 if ((Sec->getFlags() & SHF_TLS) && Sec->getType() == SHT_NOBITS) {
291 uintX_t TVA = Dot + ThreadBssOffset;
Rui Ueyama424b4082016-06-17 01:18:46 +0000292 TVA = alignTo(TVA, Sec->getAlignment());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000293 Sec->setVA(TVA);
294 ThreadBssOffset = TVA - Dot + Sec->getSize();
295 continue;
296 }
George Rimar652852c2016-04-16 10:10:32 +0000297
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000298 if (Sec->getFlags() & SHF_ALLOC) {
Rui Ueyama424b4082016-06-17 01:18:46 +0000299 Dot = alignTo(Dot, Sec->getAlignment());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000300 Sec->setVA(Dot);
Rui Ueyama52c4e172016-07-01 10:42:25 +0000301 MinVA = std::min(MinVA, Dot);
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000302 Dot += Sec->getSize();
303 continue;
304 }
George Rimar652852c2016-04-16 10:10:32 +0000305 }
306 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000307
Rafael Espindola64c32d62016-07-07 14:28:47 +0000308 // ELF and Program headers need to be right before the first section in
George Rimarb91e7112016-07-19 07:42:07 +0000309 // memory. Set their addresses accordingly.
Eugene Leviant467c4d52016-07-01 10:27:36 +0000310 MinVA = alignDown(MinVA - Out<ELFT>::ElfHeader->getSize() -
311 Out<ELFT>::ProgramHeaders->getSize(),
312 Target->PageSize);
313 Out<ELFT>::ElfHeader->setVA(MinVA);
314 Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
George Rimar652852c2016-04-16 10:10:32 +0000315}
316
Rui Ueyama07320e42016-04-20 20:13:41 +0000317template <class ELFT>
Rafael Espindola74df5c72016-07-19 12:33:46 +0000318std::vector<PhdrEntry<ELFT>>
Eugene Leviantbbe38602016-07-19 09:25:43 +0000319LinkerScript<ELFT>::createPhdrs(ArrayRef<OutputSectionBase<ELFT> *> Sections) {
320 int TlsNum = -1;
321 int NoteNum = -1;
322 int RelroNum = -1;
323 Phdr *Load = nullptr;
324 uintX_t Flags = PF_R;
325 std::vector<Phdr> Phdrs;
326
327 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
328 Phdrs.emplace_back(Cmd.Type, PF_R);
329 Phdr &Added = Phdrs.back();
330
331 if (Cmd.HasFilehdr)
332 Added.AddSec(Out<ELFT>::ElfHeader);
333 if (Cmd.HasPhdrs)
334 Added.AddSec(Out<ELFT>::ProgramHeaders);
335
336 switch (Cmd.Type) {
337 case PT_INTERP:
338 if (needsInterpSection<ELFT>())
339 Added.AddSec(Out<ELFT>::Interp);
340 break;
341 case PT_DYNAMIC:
342 if (isOutputDynamic<ELFT>()) {
343 Added.H.p_flags = toPhdrFlags(Out<ELFT>::Dynamic->getFlags());
344 Added.AddSec(Out<ELFT>::Dynamic);
345 }
346 break;
347 case PT_TLS:
348 TlsNum = Phdrs.size() - 1;
349 break;
350 case PT_NOTE:
351 NoteNum = Phdrs.size() - 1;
352 break;
353 case PT_GNU_RELRO:
354 RelroNum = Phdrs.size() - 1;
355 break;
356 case PT_GNU_EH_FRAME:
357 if (!Out<ELFT>::EhFrame->empty() && Out<ELFT>::EhFrameHdr) {
358 Added.H.p_flags = toPhdrFlags(Out<ELFT>::EhFrameHdr->getFlags());
359 Added.AddSec(Out<ELFT>::EhFrameHdr);
360 }
361 break;
362 }
363 }
364
365 for (OutputSectionBase<ELFT> *Sec : Sections) {
366 if (!(Sec->getFlags() & SHF_ALLOC))
367 break;
368
369 if (TlsNum != -1 && (Sec->getFlags() & SHF_TLS))
370 Phdrs[TlsNum].AddSec(Sec);
371
372 if (!needsPtLoad<ELFT>(Sec))
373 continue;
374
375 const std::vector<size_t> &PhdrIds =
376 getPhdrIndicesForSection(Sec->getName());
377 if (!PhdrIds.empty()) {
378 // Assign headers specified by linker script
379 for (size_t Id : PhdrIds) {
380 Phdrs[Id].AddSec(Sec);
381 Phdrs[Id].H.p_flags |= toPhdrFlags(Sec->getFlags());
382 }
383 } else {
384 // If we have no load segment or flags've changed then we want new load
385 // segment.
386 uintX_t NewFlags = toPhdrFlags(Sec->getFlags());
387 if (Load == nullptr || Flags != NewFlags) {
388 Load = &*Phdrs.emplace(Phdrs.end(), PT_LOAD, NewFlags);
389 Flags = NewFlags;
390 }
391 Load->AddSec(Sec);
392 }
393
394 if (RelroNum != -1 && isRelroSection(Sec))
395 Phdrs[RelroNum].AddSec(Sec);
396 if (NoteNum != -1 && Sec->getType() == SHT_NOTE)
397 Phdrs[NoteNum].AddSec(Sec);
398 }
399 return Phdrs;
400}
401
402template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000403ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
404 auto I = Opt.Filler.find(Name);
405 if (I == Opt.Filler.end())
Rui Ueyama3e808972016-02-28 05:09:11 +0000406 return {};
407 return I->second;
George Rimare2ee72b2016-02-26 14:48:31 +0000408}
409
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000410// Returns the index of the given section name in linker script
411// SECTIONS commands. Sections are laid out as the same order as they
412// were in the script. If a given name did not appear in the script,
413// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar71b26e92016-04-21 10:22:02 +0000414template <class ELFT>
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000415int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
George Rimar71b26e92016-04-21 10:22:02 +0000416 auto Begin = Opt.Commands.begin();
417 auto End = Opt.Commands.end();
418 auto I = std::find_if(Begin, End, [&](SectionsCommand &N) {
Eugene Levianteda81a12016-07-12 06:39:48 +0000419 return N.Kind == SectionKind && N.Name == Name;
George Rimar71b26e92016-04-21 10:22:02 +0000420 });
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000421 return I == End ? INT_MAX : (I - Begin);
George Rimar71b26e92016-04-21 10:22:02 +0000422}
423
424// A compartor to sort output sections. Returns -1 or 1 if
425// A or B are mentioned in linker script. Otherwise, returns 0.
Rui Ueyama07320e42016-04-20 20:13:41 +0000426template <class ELFT>
427int LinkerScript<ELFT>::compareSections(StringRef A, StringRef B) {
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000428 int I = getSectionIndex(A);
429 int J = getSectionIndex(B);
430 if (I == INT_MAX && J == INT_MAX)
Rui Ueyama717677a2016-02-11 21:17:59 +0000431 return 0;
432 return I < J ? -1 : 1;
433}
434
Eugene Leviantb0304112016-07-14 09:21:24 +0000435template <class ELFT>
436void LinkerScript<ELFT>::addScriptedSymbols() {
Eugene Levianteda81a12016-07-12 06:39:48 +0000437 for (SectionsCommand &Cmd : Opt.Commands)
Rui Ueyama05ef4cf2016-07-15 04:19:37 +0000438 if (Cmd.Kind == AssignmentKind)
Eugene Leviant0e36f422016-07-15 11:20:04 +0000439 if (Cmd.Name != "." && Symtab<ELFT>::X->find(Cmd.Name) == nullptr)
Rui Ueyama05ef4cf2016-07-15 04:19:37 +0000440 Symtab<ELFT>::X->addAbsolute(Cmd.Name, STV_DEFAULT);
Eugene Levianteda81a12016-07-12 06:39:48 +0000441}
442
Eugene Leviantbbe38602016-07-19 09:25:43 +0000443template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
444 return !Opt.PhdrsCommands.empty();
445}
446
447// Returns indices of ELF headers containing specific section, identified
448// by Name. Each index is a zero based number of ELF header listed within
449// PHDRS {} script block.
450template <class ELFT>
451std::vector<size_t>
452LinkerScript<ELFT>::getPhdrIndicesForSection(StringRef Name) {
453 std::vector<size_t> Indices;
454 auto ItSect = std::find_if(
455 Opt.Commands.begin(), Opt.Commands.end(),
456 [Name](const SectionsCommand &Cmd) { return Cmd.Name == Name; });
457 if (ItSect != Opt.Commands.end()) {
458 SectionsCommand &SecCmd = (*ItSect);
459 for (StringRef PhdrName : SecCmd.Phdrs) {
460 auto ItPhdr = std::find_if(
461 Opt.PhdrsCommands.rbegin(), Opt.PhdrsCommands.rend(),
462 [PhdrName](PhdrsCommand &Cmd) { return Cmd.Name == PhdrName; });
463 if (ItPhdr == Opt.PhdrsCommands.rend())
464 error("section header '" + PhdrName + "' is not listed in PHDRS");
465 else
466 Indices.push_back(std::distance(ItPhdr, Opt.PhdrsCommands.rend()) - 1);
467 }
468 }
469 return Indices;
470}
471
Rui Ueyama07320e42016-04-20 20:13:41 +0000472class elf::ScriptParser : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000473 typedef void (ScriptParser::*Handler)();
474
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000475public:
Rui Ueyama07320e42016-04-20 20:13:41 +0000476 ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
George Rimarf23b2322016-02-19 10:45:45 +0000477
Rui Ueyama4a465392016-04-22 22:59:24 +0000478 void run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000479
480private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000481 void addFile(StringRef Path);
482
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000483 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000484 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000485 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000486 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000487 void readInclude();
George Rimarc3794e52016-02-24 09:21:47 +0000488 void readNothing() {}
Rui Ueyamaee592822015-10-07 00:25:09 +0000489 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000490 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000491 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000492 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000493 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000494 void readSections();
495
George Rimar652852c2016-04-16 10:10:32 +0000496 void readLocationCounterValue();
Eugene Levianteda81a12016-07-12 06:39:48 +0000497 void readOutputSectionDescription(StringRef OutSec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000498 std::vector<StringRef> readOutputSectionPhdrs();
499 unsigned readPhdrType();
Eugene Levianteda81a12016-07-12 06:39:48 +0000500 void readSymbolAssignment(StringRef Name);
501 std::vector<StringRef> readSectionsCommandExpr();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000502
George Rimarc3794e52016-02-24 09:21:47 +0000503 const static StringMap<Handler> Cmd;
Rui Ueyama07320e42016-04-20 20:13:41 +0000504 ScriptConfiguration &Opt = *ScriptConfig;
505 StringSaver Saver = {ScriptConfig->Alloc};
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000506 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000507};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000508
Rafael Espindolae0df00b2016-02-28 00:25:54 +0000509const StringMap<elf::ScriptParser::Handler> elf::ScriptParser::Cmd = {
George Rimarc3794e52016-02-24 09:21:47 +0000510 {"ENTRY", &ScriptParser::readEntry},
511 {"EXTERN", &ScriptParser::readExtern},
512 {"GROUP", &ScriptParser::readGroup},
513 {"INCLUDE", &ScriptParser::readInclude},
514 {"INPUT", &ScriptParser::readGroup},
515 {"OUTPUT", &ScriptParser::readOutput},
516 {"OUTPUT_ARCH", &ScriptParser::readOutputArch},
517 {"OUTPUT_FORMAT", &ScriptParser::readOutputFormat},
Eugene Leviantbbe38602016-07-19 09:25:43 +0000518 {"PHDRS", &ScriptParser::readPhdrs},
George Rimarc3794e52016-02-24 09:21:47 +0000519 {"SEARCH_DIR", &ScriptParser::readSearchDir},
520 {"SECTIONS", &ScriptParser::readSections},
521 {";", &ScriptParser::readNothing}};
522
Rui Ueyama717677a2016-02-11 21:17:59 +0000523void ScriptParser::run() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000524 while (!atEOF()) {
525 StringRef Tok = next();
George Rimarc3794e52016-02-24 09:21:47 +0000526 if (Handler Fn = Cmd.lookup(Tok))
527 (this->*Fn)();
528 else
George Rimar57610422016-03-11 14:43:02 +0000529 setError("unknown directive: " + Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000530 }
531}
532
Rui Ueyama717677a2016-02-11 21:17:59 +0000533void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000534 if (IsUnderSysroot && S.startswith("/")) {
535 SmallString<128> Path;
536 (Config->Sysroot + S).toStringRef(Path);
537 if (sys::fs::exists(Path)) {
538 Driver->addFile(Saver.save(Path.str()));
539 return;
540 }
541 }
542
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +0000543 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +0000544 Driver->addFile(S);
545 } else if (S.startswith("=")) {
546 if (Config->Sysroot.empty())
547 Driver->addFile(S.substr(1));
548 else
549 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
550 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +0000551 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +0000552 } else if (sys::fs::exists(S)) {
553 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +0000554 } else {
555 std::string Path = findFromSearchPaths(S);
556 if (Path.empty())
George Rimar777f9632016-03-12 08:31:34 +0000557 setError("unable to find " + S);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000558 else
559 Driver->addFile(Saver.save(Path));
Rui Ueyama52a15092015-10-11 03:28:42 +0000560 }
561}
562
Rui Ueyama717677a2016-02-11 21:17:59 +0000563void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000564 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +0000565 bool Orig = Config->AsNeeded;
566 Config->AsNeeded = true;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000567 while (!Error) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000568 StringRef Tok = next();
569 if (Tok == ")")
Rui Ueyama35da9b62015-10-11 20:59:12 +0000570 break;
Rui Ueyama52a15092015-10-11 03:28:42 +0000571 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000572 }
Rui Ueyama35da9b62015-10-11 20:59:12 +0000573 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000574}
575
Rui Ueyama717677a2016-02-11 21:17:59 +0000576void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +0000577 // -e <symbol> takes predecence over ENTRY(<symbol>).
578 expect("(");
579 StringRef Tok = next();
580 if (Config->Entry.empty())
581 Config->Entry = Tok;
582 expect(")");
583}
584
Rui Ueyama717677a2016-02-11 21:17:59 +0000585void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +0000586 expect("(");
Rui Ueyama025d59b2016-02-02 20:27:59 +0000587 while (!Error) {
George Rimar83f406c2015-10-19 17:35:12 +0000588 StringRef Tok = next();
589 if (Tok == ")")
590 return;
591 Config->Undefined.push_back(Tok);
592 }
593}
594
Rui Ueyama717677a2016-02-11 21:17:59 +0000595void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000596 expect("(");
Rui Ueyama025d59b2016-02-02 20:27:59 +0000597 while (!Error) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000598 StringRef Tok = next();
599 if (Tok == ")")
600 return;
601 if (Tok == "AS_NEEDED") {
602 readAsNeeded();
603 continue;
604 }
Rui Ueyama52a15092015-10-11 03:28:42 +0000605 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000606 }
607}
608
Rui Ueyama717677a2016-02-11 21:17:59 +0000609void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000610 StringRef Tok = next();
611 auto MBOrErr = MemoryBuffer::getFile(Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000612 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +0000613 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000614 return;
615 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000616 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Rui Ueyamaa47ee682015-10-11 01:53:04 +0000617 StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
618 std::vector<StringRef> V = tokenize(S);
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000619 Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000620}
621
Rui Ueyama717677a2016-02-11 21:17:59 +0000622void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +0000623 // -o <file> takes predecence over OUTPUT(<file>).
624 expect("(");
625 StringRef Tok = next();
626 if (Config->OutputFile.empty())
627 Config->OutputFile = Tok;
628 expect(")");
629}
630
Rui Ueyama717677a2016-02-11 21:17:59 +0000631void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +0000632 // Error checking only for now.
633 expect("(");
634 next();
635 expect(")");
636}
637
Rui Ueyama717677a2016-02-11 21:17:59 +0000638void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000639 // Error checking only for now.
640 expect("(");
641 next();
Davide Italiano6836c612015-10-12 21:08:41 +0000642 StringRef Tok = next();
643 if (Tok == ")")
644 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000645 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +0000646 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000647 return;
648 }
Davide Italiano6836c612015-10-12 21:08:41 +0000649 next();
650 expect(",");
651 next();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000652 expect(")");
653}
654
Eugene Leviantbbe38602016-07-19 09:25:43 +0000655void ScriptParser::readPhdrs() {
656 expect("{");
657 while (!Error && !skip("}")) {
658 StringRef Tok = next();
659 Opt.PhdrsCommands.push_back({Tok, PT_NULL, false, false});
660 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
661
662 PhdrCmd.Type = readPhdrType();
663 do {
664 Tok = next();
665 if (Tok == ";")
666 break;
667 if (Tok == "FILEHDR")
668 PhdrCmd.HasFilehdr = true;
669 else if (Tok == "PHDRS")
670 PhdrCmd.HasPhdrs = true;
671 else
672 setError("unexpected header attribute: " + Tok);
673 } while (!Error);
674 }
675}
676
Rui Ueyama717677a2016-02-11 21:17:59 +0000677void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +0000678 expect("(");
Rafael Espindola06501922016-03-08 17:13:12 +0000679 Config->SearchPaths.push_back(next());
Davide Italiano68a39a62015-10-08 17:51:41 +0000680 expect(")");
681}
682
Rui Ueyama717677a2016-02-11 21:17:59 +0000683void ScriptParser::readSections() {
Rui Ueyama07320e42016-04-20 20:13:41 +0000684 Opt.DoLayout = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000685 expect("{");
George Rimar652852c2016-04-16 10:10:32 +0000686 while (!Error && !skip("}")) {
687 StringRef Tok = peek();
Eugene Levianteda81a12016-07-12 06:39:48 +0000688 if (Tok == ".") {
George Rimar652852c2016-04-16 10:10:32 +0000689 readLocationCounterValue();
Eugene Levianteda81a12016-07-12 06:39:48 +0000690 continue;
691 }
692 next();
693 if (peek() == "=")
694 readSymbolAssignment(Tok);
George Rimar652852c2016-04-16 10:10:32 +0000695 else
Eugene Levianteda81a12016-07-12 06:39:48 +0000696 readOutputSectionDescription(Tok);
George Rimar652852c2016-04-16 10:10:32 +0000697 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000698}
699
George Rimar652852c2016-04-16 10:10:32 +0000700void ScriptParser::readLocationCounterValue() {
701 expect(".");
702 expect("=");
Eugene Levianteda81a12016-07-12 06:39:48 +0000703 std::vector<StringRef> Expr = readSectionsCommandExpr();
704 if (Expr.empty())
George Rimar652852c2016-04-16 10:10:32 +0000705 error("error in location counter expression");
Eugene Levianteda81a12016-07-12 06:39:48 +0000706 else
Eugene Leviantbbe38602016-07-19 09:25:43 +0000707 Opt.Commands.push_back({AssignmentKind, std::move(Expr), ".", {}});
George Rimar652852c2016-04-16 10:10:32 +0000708}
709
Eugene Levianteda81a12016-07-12 06:39:48 +0000710void ScriptParser::readOutputSectionDescription(StringRef OutSec) {
Eugene Leviantbbe38602016-07-19 09:25:43 +0000711 Opt.Commands.push_back({SectionKind, {}, OutSec, {}});
712 SectionsCommand &Cmd = Opt.Commands.back();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000713 expect(":");
714 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000715
Rui Ueyama025d59b2016-02-02 20:27:59 +0000716 while (!Error && !skip("}")) {
George Rimar481c2ce2016-02-23 07:47:54 +0000717 StringRef Tok = next();
718 if (Tok == "*") {
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000719 expect("(");
720 while (!Error && !skip(")"))
721 Opt.Sections.emplace_back(OutSec, next());
George Rimar481c2ce2016-02-23 07:47:54 +0000722 } else if (Tok == "KEEP") {
723 expect("(");
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000724 expect("*");
725 expect("(");
726 while (!Error && !skip(")")) {
727 StringRef Sec = next();
728 Opt.Sections.emplace_back(OutSec, Sec);
729 Opt.KeptSections.push_back(Sec);
730 }
George Rimar481c2ce2016-02-23 07:47:54 +0000731 expect(")");
732 } else {
George Rimar777f9632016-03-12 08:31:34 +0000733 setError("unknown command " + Tok);
George Rimar481c2ce2016-02-23 07:47:54 +0000734 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000735 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000736 Cmd.Phdrs = readOutputSectionPhdrs();
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000737
George Rimare2ee72b2016-02-26 14:48:31 +0000738 StringRef Tok = peek();
739 if (Tok.startswith("=")) {
740 if (!Tok.startswith("=0x")) {
Rui Ueyama3ed2f062016-03-13 03:17:44 +0000741 setError("filler should be a hexadecimal value");
George Rimare2ee72b2016-02-26 14:48:31 +0000742 return;
743 }
Rui Ueyama3e808972016-02-28 05:09:11 +0000744 Tok = Tok.substr(3);
Rui Ueyama07320e42016-04-20 20:13:41 +0000745 Opt.Filler[OutSec] = parseHex(Tok);
George Rimare2ee72b2016-02-26 14:48:31 +0000746 next();
747 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000748}
749
Eugene Levianteda81a12016-07-12 06:39:48 +0000750void ScriptParser::readSymbolAssignment(StringRef Name) {
751 expect("=");
752 std::vector<StringRef> Expr = readSectionsCommandExpr();
753 if (Expr.empty())
754 error("error in symbol assignment expression");
755 else
Eugene Leviantbbe38602016-07-19 09:25:43 +0000756 Opt.Commands.push_back({AssignmentKind, std::move(Expr), Name, {}});
Eugene Levianteda81a12016-07-12 06:39:48 +0000757}
758
759std::vector<StringRef> ScriptParser::readSectionsCommandExpr() {
760 std::vector<StringRef> Expr;
761 while (!Error) {
762 StringRef Tok = next();
763 if (Tok == ";")
764 break;
765 Expr.push_back(Tok);
766 }
767 return Expr;
768}
769
Eugene Leviantbbe38602016-07-19 09:25:43 +0000770std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
771 std::vector<StringRef> Phdrs;
772 while (!Error && peek().startswith(":")) {
773 StringRef Tok = next();
774 Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
775 if (Tok.empty()) {
776 setError("section header name is empty");
777 break;
778 }
779 else
780 Phdrs.push_back(Tok);
781 }
782 return Phdrs;
783}
784
785unsigned ScriptParser::readPhdrType() {
786 static const char *typeNames[] = {
787 "PT_NULL", "PT_LOAD", "PT_DYNAMIC", "PT_INTERP",
788 "PT_NOTE", "PT_SHLIB", "PT_PHDR", "PT_TLS",
789 "PT_GNU_EH_FRAME", "PT_GNU_STACK", "PT_GNU_RELRO"};
790 static unsigned typeCodes[] = {
791 PT_NULL, PT_LOAD, PT_DYNAMIC, PT_INTERP, PT_NOTE, PT_SHLIB,
792 PT_PHDR, PT_TLS, PT_GNU_EH_FRAME, PT_GNU_STACK, PT_GNU_RELRO};
793
794 unsigned PhdrType = PT_NULL;
795 StringRef Tok = next();
796 auto It = std::find(std::begin(typeNames), std::end(typeNames), Tok);
797 if (It != std::end(typeNames))
798 PhdrType = typeCodes[std::distance(std::begin(typeNames), It)];
799 else
800 setError("invalid program header type");
801
802 return PhdrType;
803}
804
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000805static bool isUnderSysroot(StringRef Path) {
806 if (Config->Sysroot == "")
807 return false;
808 for (; !Path.empty(); Path = sys::path::parent_path(Path))
809 if (sys::fs::equivalent(Config->Sysroot, Path))
810 return true;
811 return false;
812}
813
Rui Ueyama07320e42016-04-20 20:13:41 +0000814// Entry point.
815void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000816 StringRef Path = MB.getBufferIdentifier();
Rui Ueyama07320e42016-04-20 20:13:41 +0000817 ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000818}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +0000819
Rui Ueyama07320e42016-04-20 20:13:41 +0000820template class elf::LinkerScript<ELF32LE>;
821template class elf::LinkerScript<ELF32BE>;
822template class elf::LinkerScript<ELF64LE>;
823template class elf::LinkerScript<ELF64BE>;