blob: 64a68493c262390ca2f2062a41fcb487b90a5e6d [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 Ueyama629e0aa52016-07-21 19:45:22 +000011// It parses a linker script and write the result to Config or ScriptConfig
12// objects.
13//
14// If SECTIONS command is used, a ScriptConfig contains an AST
15// of the command which will later be consumed by createSections() and
16// assignAddresses().
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000017//
18//===----------------------------------------------------------------------===//
19
Rui Ueyama717677a2016-02-11 21:17:59 +000020#include "LinkerScript.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000021#include "Config.h"
22#include "Driver.h"
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +000023#include "InputSection.h"
George Rimar652852c2016-04-16 10:10:32 +000024#include "OutputSections.h"
Adhemerval Zanellae77b5bf2016-04-06 20:59:11 +000025#include "ScriptParser.h"
Rui Ueyama93c9af42016-06-29 08:01:32 +000026#include "Strings.h"
Eugene Levianteda81a12016-07-12 06:39:48 +000027#include "Symbols.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000028#include "SymbolTable.h"
Eugene Leviant467c4d52016-07-01 10:27:36 +000029#include "Target.h"
Eugene Leviantbbe38602016-07-19 09:25:43 +000030#include "Writer.h"
Rui Ueyama960504b2016-04-19 18:58:11 +000031#include "llvm/ADT/StringSwitch.h"
George Rimar652852c2016-04-16 10:10:32 +000032#include "llvm/Support/ELF.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000033#include "llvm/Support/FileSystem.h"
34#include "llvm/Support/MemoryBuffer.h"
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +000035#include "llvm/Support/Path.h"
Rui Ueyamaa47ee682015-10-11 01:53:04 +000036#include "llvm/Support/StringSaver.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000037
38using namespace llvm;
George Rimar652852c2016-04-16 10:10:32 +000039using namespace llvm::ELF;
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +000040using namespace llvm::object;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000041using namespace lld;
Rafael Espindolae0df00b2016-02-28 00:25:54 +000042using namespace lld::elf;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000043
Rui Ueyama07320e42016-04-20 20:13:41 +000044ScriptConfiguration *elf::ScriptConfig;
Rui Ueyama717677a2016-02-11 21:17:59 +000045
George Rimar076fe152016-07-21 06:43:01 +000046bool SymbolAssignment::classof(const BaseCommand *C) {
47 return C->Kind == AssignmentKind;
48}
49
50bool OutputSectionCommand::classof(const BaseCommand *C) {
51 return C->Kind == OutputSectionKind;
52}
53
George Rimareea31142016-07-21 14:26:59 +000054bool InputSectionDescription::classof(const BaseCommand *C) {
55 return C->Kind == InputSectionKind;
56}
57
Rui Ueyama9c1112d2016-04-23 00:04:03 +000058// This is an operator-precedence parser to parse and evaluate
59// a linker script expression. For each linker script arithmetic
60// expression (e.g. ". = . + 0x1000"), a new instance of ExprParser
61// is created and ran.
62namespace {
63class ExprParser : public ScriptParserBase {
64public:
65 ExprParser(std::vector<StringRef> &Tokens, uint64_t Dot)
66 : ScriptParserBase(Tokens), Dot(Dot) {}
67
68 uint64_t run();
69
70private:
71 uint64_t parsePrimary();
72 uint64_t parseTernary(uint64_t Cond);
73 uint64_t apply(StringRef Op, uint64_t L, uint64_t R);
74 uint64_t parseExpr1(uint64_t Lhs, int MinPrec);
75 uint64_t parseExpr();
76
77 uint64_t Dot;
78};
79}
80
Rui Ueyama960504b2016-04-19 18:58:11 +000081static int precedence(StringRef Op) {
82 return StringSwitch<int>(Op)
83 .Case("*", 4)
George Rimarab939062016-04-25 08:14:41 +000084 .Case("/", 4)
85 .Case("+", 3)
86 .Case("-", 3)
87 .Case("<", 2)
88 .Case(">", 2)
89 .Case(">=", 2)
90 .Case("<=", 2)
91 .Case("==", 2)
92 .Case("!=", 2)
Rui Ueyama960504b2016-04-19 18:58:11 +000093 .Case("&", 1)
94 .Default(-1);
95}
96
Rui Ueyama9c1112d2016-04-23 00:04:03 +000097static uint64_t evalExpr(std::vector<StringRef> &Tokens, uint64_t Dot) {
98 return ExprParser(Tokens, Dot).run();
Rui Ueyama960504b2016-04-19 18:58:11 +000099}
100
Rui Ueyama9c1112d2016-04-23 00:04:03 +0000101uint64_t ExprParser::run() {
102 uint64_t V = parseExpr();
103 if (!atEOF() && !Error)
104 setError("stray token: " + peek());
105 return V;
Rui Ueyama60118112016-04-20 20:54:13 +0000106}
107
George Rimar92e93fb2016-07-21 19:48:00 +0000108uint64_t static getConstantValue(StringRef C) {
109 if (C == "COMMONPAGESIZE" || C == "MAXPAGESIZE")
110 return Target->PageSize;
111 error("unknown constant: " + C);
112 return 0;
113}
114
Rui Ueyama960504b2016-04-19 18:58:11 +0000115// This is a part of the operator-precedence parser to evaluate
116// arithmetic expressions in SECTIONS command. This function evaluates an
Rui Ueyamae29a9752016-04-22 21:02:27 +0000117// integer literal, a parenthesized expression, the ALIGN function,
118// or the special variable ".".
Rui Ueyama9c1112d2016-04-23 00:04:03 +0000119uint64_t ExprParser::parsePrimary() {
120 StringRef Tok = next();
Rui Ueyama960504b2016-04-19 18:58:11 +0000121 if (Tok == ".")
122 return Dot;
123 if (Tok == "(") {
Rui Ueyama9c1112d2016-04-23 00:04:03 +0000124 uint64_t V = parseExpr();
125 expect(")");
Rui Ueyama960504b2016-04-19 18:58:11 +0000126 return V;
127 }
George Rimardffc1412016-04-22 11:40:53 +0000128 if (Tok == "ALIGN") {
Rui Ueyama9c1112d2016-04-23 00:04:03 +0000129 expect("(");
130 uint64_t V = parseExpr();
131 expect(")");
George Rimardffc1412016-04-22 11:40:53 +0000132 return alignTo(Dot, V);
133 }
George Rimar92e93fb2016-07-21 19:48:00 +0000134 if (Tok == "CONSTANT") {
135 expect("(");
136 uint64_t V = getConstantValue(next());
137 expect(")");
138 return V;
139 }
140 // Documentations says there are two ways to compute
141 // the value of DATA_SEGMENT_ALIGN command, depending on whether the second
142 // uses fewer COMMONPAGESIZE sized pages for the data segment(area between the
143 // result of this expression and `DATA_SEGMENT_END') than the first or not.
144 // That is possible optimization, that we do not support, so we compute that
145 // function always as (ALIGN(MAXPAGESIZE) + (. & (MAXPAGESIZE - 1))) now.
146 if (Tok == "DATA_SEGMENT_ALIGN") {
147 expect("(");
148 uint64_t L = parseExpr();
149 expect(",");
150 parseExpr();
151 expect(")");
152 return alignTo(Dot, L) + (Dot & (L - 1));
153 }
154 // Since we do not support the optimization from comment above,
155 // we can just ignore that command.
156 if (Tok == "DATA_SEGMENT_END") {
157 expect("(");
158 expect(".");
159 expect(")");
160 return Dot;
161 }
Rui Ueyama5fa60982016-04-22 21:05:04 +0000162 uint64_t V = 0;
163 if (Tok.getAsInteger(0, V))
Rui Ueyama9c1112d2016-04-23 00:04:03 +0000164 setError("malformed number: " + Tok);
Rui Ueyama5fa60982016-04-22 21:05:04 +0000165 return V;
Rui Ueyama960504b2016-04-19 18:58:11 +0000166}
167
Rui Ueyama9c1112d2016-04-23 00:04:03 +0000168uint64_t ExprParser::parseTernary(uint64_t Cond) {
169 next();
170 uint64_t V = parseExpr();
171 expect(":");
172 uint64_t W = parseExpr();
George Rimarfba45c42016-04-22 11:28:54 +0000173 return Cond ? V : W;
174}
175
Rui Ueyama9c1112d2016-04-23 00:04:03 +0000176uint64_t ExprParser::apply(StringRef Op, uint64_t L, uint64_t R) {
Rui Ueyama960504b2016-04-19 18:58:11 +0000177 if (Op == "*")
178 return L * R;
179 if (Op == "/") {
180 if (R == 0) {
181 error("division by zero");
George Rimar652852c2016-04-16 10:10:32 +0000182 return 0;
183 }
Rui Ueyama960504b2016-04-19 18:58:11 +0000184 return L / R;
George Rimar652852c2016-04-16 10:10:32 +0000185 }
George Rimarab939062016-04-25 08:14:41 +0000186 if (Op == "+")
187 return L + R;
188 if (Op == "-")
189 return L - R;
190 if (Op == "<")
191 return L < R;
192 if (Op == ">")
193 return L > R;
194 if (Op == ">=")
195 return L >= R;
196 if (Op == "<=")
197 return L <= R;
198 if (Op == "==")
199 return L == R;
200 if (Op == "!=")
201 return L != R;
Rui Ueyama960504b2016-04-19 18:58:11 +0000202 if (Op == "&")
203 return L & R;
Rui Ueyama7a81d672016-04-19 19:04:03 +0000204 llvm_unreachable("invalid operator");
Rui Ueyama960504b2016-04-19 18:58:11 +0000205}
206
Rui Ueyama9c1112d2016-04-23 00:04:03 +0000207// This is a part of the operator-precedence parser.
208// This function assumes that the remaining token stream starts
209// with an operator.
210uint64_t ExprParser::parseExpr1(uint64_t Lhs, int MinPrec) {
211 while (!atEOF()) {
Rui Ueyama960504b2016-04-19 18:58:11 +0000212 // Read an operator and an expression.
Rui Ueyama9c1112d2016-04-23 00:04:03 +0000213 StringRef Op1 = peek();
George Rimarfba45c42016-04-22 11:28:54 +0000214 if (Op1 == "?")
Rui Ueyama9c1112d2016-04-23 00:04:03 +0000215 return parseTernary(Lhs);
Rui Ueyama960504b2016-04-19 18:58:11 +0000216 if (precedence(Op1) < MinPrec)
217 return Lhs;
Rui Ueyama9c1112d2016-04-23 00:04:03 +0000218 next();
219 uint64_t Rhs = parsePrimary();
Rui Ueyama960504b2016-04-19 18:58:11 +0000220
221 // Evaluate the remaining part of the expression first if the
222 // next operator has greater precedence than the previous one.
223 // For example, if we have read "+" and "3", and if the next
224 // operator is "*", then we'll evaluate 3 * ... part first.
Rui Ueyama9c1112d2016-04-23 00:04:03 +0000225 while (!atEOF()) {
226 StringRef Op2 = peek();
Rui Ueyama960504b2016-04-19 18:58:11 +0000227 if (precedence(Op2) <= precedence(Op1))
228 break;
Rui Ueyama9c1112d2016-04-23 00:04:03 +0000229 Rhs = parseExpr1(Rhs, precedence(Op2));
Rui Ueyama960504b2016-04-19 18:58:11 +0000230 }
231
232 Lhs = apply(Op1, Lhs, Rhs);
233 }
234 return Lhs;
235}
236
Rui Ueyama9c1112d2016-04-23 00:04:03 +0000237// Reads and evaluates an arithmetic expression.
238uint64_t ExprParser::parseExpr() { return parseExpr1(parsePrimary(), 0); }
George Rimar652852c2016-04-16 10:10:32 +0000239
Rui Ueyama36a153c2016-07-23 14:09:58 +0000240template <class ELFT> static bool isDiscarded(InputSectionBase<ELFT> *S) {
George Rimareea31142016-07-21 14:26:59 +0000241 return !S || !S->Live;
Rui Ueyama717677a2016-02-11 21:17:59 +0000242}
243
Rui Ueyama07320e42016-04-20 20:13:41 +0000244template <class ELFT>
245bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) {
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000246 for (StringRef Pat : Opt.KeptSections)
Rui Ueyama722830a2016-06-29 05:32:09 +0000247 if (globMatch(Pat, S->getSectionName()))
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000248 return true;
249 return false;
George Rimar481c2ce2016-02-23 07:47:54 +0000250}
251
George Rimareea31142016-07-21 14:26:59 +0000252static bool match(StringRef Pattern, ArrayRef<StringRef> Arr) {
253 for (StringRef S : Arr)
254 if (globMatch(S, Pattern))
255 return true;
256 return false;
257}
258
George Rimar652852c2016-04-16 10:10:32 +0000259template <class ELFT>
Rui Ueyamaa7f78842016-07-20 17:19:03 +0000260std::vector<OutputSectionBase<ELFT> *>
Eugene Leviante63d81b2016-07-20 14:43:20 +0000261LinkerScript<ELFT>::createSections(OutputSectionFactory<ELFT> &Factory) {
George Rimareea31142016-07-21 14:26:59 +0000262 typedef const std::unique_ptr<ObjectFile<ELFT>> ObjectFile;
Rui Ueyamaa7f78842016-07-20 17:19:03 +0000263 std::vector<OutputSectionBase<ELFT> *> Result;
Davide Italiano246f6812016-07-22 03:36:24 +0000264 DenseSet<OutputSectionBase<ELFT> *> Removed;
Rui Ueyamaa7f78842016-07-20 17:19:03 +0000265
Eugene Leviante63d81b2016-07-20 14:43:20 +0000266 // Add input section to output section. If there is no output section yet,
267 // then create it and add to output section list.
Davide Italiano246f6812016-07-22 03:36:24 +0000268 auto AddInputSec = [&](InputSectionBase<ELFT> *C, StringRef Name,
269 ConstraintKind Constraint) {
Eugene Leviante63d81b2016-07-20 14:43:20 +0000270 OutputSectionBase<ELFT> *Sec;
271 bool IsNew;
272 std::tie(Sec, IsNew) = Factory.create(C, Name);
273 if (IsNew)
Rui Ueyamaa7f78842016-07-20 17:19:03 +0000274 Result.push_back(Sec);
Davide Italiano246f6812016-07-22 03:36:24 +0000275 if ((!(C->getSectionHdr()->sh_flags & SHF_WRITE)) &&
276 Constraint == ReadWrite) {
277 Removed.insert(Sec);
278 return;
279 }
280 if ((C->getSectionHdr()->sh_flags & SHF_WRITE) && Constraint == ReadOnly) {
281 Removed.insert(Sec);
282 return;
283 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000284 Sec->addSection(C);
285 };
286
287 // Select input sections matching rule and add them to corresponding
288 // output section. Section rules are processed in order they're listed
289 // in script, so correct input section order is maintained by design.
George Rimareea31142016-07-21 14:26:59 +0000290 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
291 auto *OutCmd = dyn_cast<OutputSectionCommand>(Base.get());
292 if (!OutCmd)
293 continue;
294
295 for (const std::unique_ptr<BaseCommand> &Cmd : OutCmd->Commands) {
296 auto *InCmd = dyn_cast<InputSectionDescription>(Cmd.get());
297 if (!InCmd)
298 continue;
299
300 for (ObjectFile &F : Symtab<ELFT>::X->getObjectFiles()) {
301 for (InputSectionBase<ELFT> *S : F->getSections()) {
302 if (isDiscarded(S) || S->OutSec)
303 continue;
304
305 if (match(S->getSectionName(), InCmd->Patterns)) {
306 if (OutCmd->Name == "/DISCARD/")
307 S->Live = false;
308 else
Davide Italiano246f6812016-07-22 03:36:24 +0000309 AddInputSec(S, OutCmd->Name, OutCmd->Constraint);
George Rimareea31142016-07-21 14:26:59 +0000310 }
311 }
312 }
313 }
314 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000315
316 // Add all other input sections, which are not listed in script.
George Rimareea31142016-07-21 14:26:59 +0000317 for (ObjectFile &F : Symtab<ELFT>::X->getObjectFiles())
Reid Kleckner3c944ec2016-07-21 18:39:28 +0000318 for (InputSectionBase<ELFT> *S : F->getSections()) {
Eugene Leviante63d81b2016-07-20 14:43:20 +0000319 if (!isDiscarded(S)) {
320 if (!S->OutSec)
Davide Italiano246f6812016-07-22 03:36:24 +0000321 AddInputSec(S, getOutputSectionName(S), NoConstraint);
Eugene Leviante63d81b2016-07-20 14:43:20 +0000322 } else
323 reportDiscarded(S, F);
Reid Kleckner3c944ec2016-07-21 18:39:28 +0000324 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000325
Davide Italiano246f6812016-07-22 03:36:24 +0000326 // Remove from the output all the sections which did not met the constraints.
327 Result.erase(std::remove_if(Result.begin(), Result.end(),
328 [&](OutputSectionBase<ELFT> *Sec) {
329 return Removed.count(Sec);
330 }),
331 Result.end());
Eugene Leviante63d81b2016-07-20 14:43:20 +0000332 return Result;
333}
334
335template <class ELFT>
George Rimar10e576e2016-07-21 16:07:40 +0000336void LinkerScript<ELFT>::dispatchAssignment(SymbolAssignment *Cmd) {
337 uint64_t Val = evalExpr(Cmd->Expr, Dot);
338 if (Cmd->Name == ".") {
339 Dot = Val;
Eugene Levianta31c91b2016-07-22 07:38:40 +0000340 } else if (!Cmd->Ignore) {
George Rimar10e576e2016-07-21 16:07:40 +0000341 auto *D = cast<DefinedRegular<ELFT>>(Symtab<ELFT>::X->find(Cmd->Name));
342 D->Value = Val;
343 }
344}
345
346template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000347void LinkerScript<ELFT>::assignAddresses(
George Rimardbbd8b12016-04-21 11:21:48 +0000348 ArrayRef<OutputSectionBase<ELFT> *> Sections) {
George Rimar652852c2016-04-16 10:10:32 +0000349 // Orphan sections are sections present in the input files which
Rui Ueyama7c18c282016-04-18 21:00:40 +0000350 // are not explicitly placed into the output file by the linker script.
351 // We place orphan sections at end of file.
352 // Other linkers places them using some heuristics as described in
George Rimar652852c2016-04-16 10:10:32 +0000353 // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
Rui Ueyama7c18c282016-04-18 21:00:40 +0000354 for (OutputSectionBase<ELFT> *Sec : Sections) {
George Rimar652852c2016-04-16 10:10:32 +0000355 StringRef Name = Sec->getName();
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000356 if (getSectionIndex(Name) == INT_MAX)
George Rimar076fe152016-07-21 06:43:01 +0000357 Opt.Commands.push_back(llvm::make_unique<OutputSectionCommand>(Name));
George Rimar652852c2016-04-16 10:10:32 +0000358 }
George Rimar652852c2016-04-16 10:10:32 +0000359
Rui Ueyama7c18c282016-04-18 21:00:40 +0000360 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rui Ueyama52c4e172016-07-01 10:42:25 +0000361 Dot = Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
Eugene Leviant467c4d52016-07-01 10:27:36 +0000362 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
George Rimar652852c2016-04-16 10:10:32 +0000363 uintX_t ThreadBssOffset = 0;
George Rimar652852c2016-04-16 10:10:32 +0000364
George Rimar076fe152016-07-21 06:43:01 +0000365 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
366 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
George Rimar10e576e2016-07-21 16:07:40 +0000367 dispatchAssignment(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000368 continue;
369 }
370
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000371 // Find all the sections with required name. There can be more than
George Rimar6ad330a2016-07-19 07:39:07 +0000372 // one section with such name, if the alignment, flags or type
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000373 // attribute differs.
George Rimar076fe152016-07-21 06:43:01 +0000374 auto *Cmd = cast<OutputSectionCommand>(Base.get());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000375 for (OutputSectionBase<ELFT> *Sec : Sections) {
George Rimar076fe152016-07-21 06:43:01 +0000376 if (Sec->getName() != Cmd->Name)
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000377 continue;
George Rimar652852c2016-04-16 10:10:32 +0000378
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000379 if ((Sec->getFlags() & SHF_TLS) && Sec->getType() == SHT_NOBITS) {
380 uintX_t TVA = Dot + ThreadBssOffset;
Rui Ueyama424b4082016-06-17 01:18:46 +0000381 TVA = alignTo(TVA, Sec->getAlignment());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000382 Sec->setVA(TVA);
383 ThreadBssOffset = TVA - Dot + Sec->getSize();
384 continue;
385 }
George Rimar652852c2016-04-16 10:10:32 +0000386
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000387 if (Sec->getFlags() & SHF_ALLOC) {
Rui Ueyama424b4082016-06-17 01:18:46 +0000388 Dot = alignTo(Dot, Sec->getAlignment());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000389 Sec->setVA(Dot);
Rui Ueyama52c4e172016-07-01 10:42:25 +0000390 MinVA = std::min(MinVA, Dot);
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000391 Dot += Sec->getSize();
392 continue;
393 }
George Rimar652852c2016-04-16 10:10:32 +0000394 }
395 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000396
Rafael Espindola64c32d62016-07-07 14:28:47 +0000397 // ELF and Program headers need to be right before the first section in
George Rimarb91e7112016-07-19 07:42:07 +0000398 // memory. Set their addresses accordingly.
Eugene Leviant467c4d52016-07-01 10:27:36 +0000399 MinVA = alignDown(MinVA - Out<ELFT>::ElfHeader->getSize() -
400 Out<ELFT>::ProgramHeaders->getSize(),
401 Target->PageSize);
402 Out<ELFT>::ElfHeader->setVA(MinVA);
403 Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
George Rimar652852c2016-04-16 10:10:32 +0000404}
405
Rui Ueyama07320e42016-04-20 20:13:41 +0000406template <class ELFT>
Rafael Espindola74df5c72016-07-19 12:33:46 +0000407std::vector<PhdrEntry<ELFT>>
Eugene Leviantbbe38602016-07-19 09:25:43 +0000408LinkerScript<ELFT>::createPhdrs(ArrayRef<OutputSectionBase<ELFT> *> Sections) {
409 int TlsNum = -1;
410 int NoteNum = -1;
411 int RelroNum = -1;
Rui Ueyamaadca2452016-07-23 14:18:48 +0000412 PhdrEntry<ELFT> *Load = nullptr;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000413 uintX_t Flags = PF_R;
Rui Ueyamaadca2452016-07-23 14:18:48 +0000414 std::vector<PhdrEntry<ELFT>> Phdrs;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000415
416 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Eugene Leviant865bf862016-07-21 10:43:25 +0000417 Phdrs.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
Rui Ueyamaadca2452016-07-23 14:18:48 +0000418 PhdrEntry<ELFT> &Phdr = Phdrs.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000419
420 if (Cmd.HasFilehdr)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000421 Phdr.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000422 if (Cmd.HasPhdrs)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000423 Phdr.add(Out<ELFT>::ProgramHeaders);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000424
425 switch (Cmd.Type) {
426 case PT_INTERP:
Rui Ueyamafd03cfd2016-07-21 11:01:23 +0000427 if (Out<ELFT>::Interp)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000428 Phdr.add(Out<ELFT>::Interp);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000429 break;
430 case PT_DYNAMIC:
431 if (isOutputDynamic<ELFT>()) {
Rui Ueyamaadca2452016-07-23 14:18:48 +0000432 Phdr.H.p_flags = toPhdrFlags(Out<ELFT>::Dynamic->getFlags());
433 Phdr.add(Out<ELFT>::Dynamic);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000434 }
435 break;
436 case PT_TLS:
437 TlsNum = Phdrs.size() - 1;
438 break;
439 case PT_NOTE:
440 NoteNum = Phdrs.size() - 1;
441 break;
442 case PT_GNU_RELRO:
443 RelroNum = Phdrs.size() - 1;
444 break;
445 case PT_GNU_EH_FRAME:
446 if (!Out<ELFT>::EhFrame->empty() && Out<ELFT>::EhFrameHdr) {
Rui Ueyamaadca2452016-07-23 14:18:48 +0000447 Phdr.H.p_flags = toPhdrFlags(Out<ELFT>::EhFrameHdr->getFlags());
448 Phdr.add(Out<ELFT>::EhFrameHdr);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000449 }
450 break;
451 }
452 }
453
454 for (OutputSectionBase<ELFT> *Sec : Sections) {
455 if (!(Sec->getFlags() & SHF_ALLOC))
456 break;
457
458 if (TlsNum != -1 && (Sec->getFlags() & SHF_TLS))
Rui Ueyama18f084f2016-07-20 19:36:41 +0000459 Phdrs[TlsNum].add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000460
461 if (!needsPtLoad<ELFT>(Sec))
462 continue;
463
464 const std::vector<size_t> &PhdrIds =
465 getPhdrIndicesForSection(Sec->getName());
466 if (!PhdrIds.empty()) {
467 // Assign headers specified by linker script
468 for (size_t Id : PhdrIds) {
Rui Ueyama18f084f2016-07-20 19:36:41 +0000469 Phdrs[Id].add(Sec);
Eugene Leviant865bf862016-07-21 10:43:25 +0000470 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
471 Phdrs[Id].H.p_flags |= toPhdrFlags(Sec->getFlags());
Eugene Leviantbbe38602016-07-19 09:25:43 +0000472 }
473 } else {
474 // If we have no load segment or flags've changed then we want new load
475 // segment.
476 uintX_t NewFlags = toPhdrFlags(Sec->getFlags());
477 if (Load == nullptr || Flags != NewFlags) {
478 Load = &*Phdrs.emplace(Phdrs.end(), PT_LOAD, NewFlags);
479 Flags = NewFlags;
480 }
Rui Ueyama18f084f2016-07-20 19:36:41 +0000481 Load->add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000482 }
483
484 if (RelroNum != -1 && isRelroSection(Sec))
Rui Ueyama18f084f2016-07-20 19:36:41 +0000485 Phdrs[RelroNum].add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000486 if (NoteNum != -1 && Sec->getType() == SHT_NOTE)
Rui Ueyama18f084f2016-07-20 19:36:41 +0000487 Phdrs[NoteNum].add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000488 }
489 return Phdrs;
490}
491
492template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000493ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000494 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
495 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
496 if (Cmd->Name == Name)
497 return Cmd->Filler;
498 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000499}
500
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000501// Returns the index of the given section name in linker script
502// SECTIONS commands. Sections are laid out as the same order as they
503// were in the script. If a given name did not appear in the script,
504// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000505template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
George Rimar71b26e92016-04-21 10:22:02 +0000506 auto Begin = Opt.Commands.begin();
507 auto End = Opt.Commands.end();
George Rimar076fe152016-07-21 06:43:01 +0000508 auto I =
509 std::find_if(Begin, End, [&](const std::unique_ptr<BaseCommand> &Base) {
510 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
511 if (Cmd->Name == Name)
512 return true;
513 return false;
514 });
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000515 return I == End ? INT_MAX : (I - Begin);
George Rimar71b26e92016-04-21 10:22:02 +0000516}
517
518// A compartor to sort output sections. Returns -1 or 1 if
519// A or B are mentioned in linker script. Otherwise, returns 0.
Rui Ueyama07320e42016-04-20 20:13:41 +0000520template <class ELFT>
521int LinkerScript<ELFT>::compareSections(StringRef A, StringRef B) {
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000522 int I = getSectionIndex(A);
523 int J = getSectionIndex(B);
524 if (I == INT_MAX && J == INT_MAX)
Rui Ueyama717677a2016-02-11 21:17:59 +0000525 return 0;
526 return I < J ? -1 : 1;
527}
528
George Rimar076fe152016-07-21 06:43:01 +0000529template <class ELFT> void LinkerScript<ELFT>::addScriptedSymbols() {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000530 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
531 auto *Cmd = dyn_cast<SymbolAssignment>(Base.get());
532 if (!Cmd || Cmd->Name == ".")
533 continue;
534
535 if (Symtab<ELFT>::X->find(Cmd->Name) == nullptr)
536 Symtab<ELFT>::X->addAbsolute(Cmd->Name,
537 Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT);
538 else
539 // Symbol already exists in symbol table. If it is provided
540 // then we can't override its value.
541 Cmd->Ignore = Cmd->Provide;
542 }
Eugene Levianteda81a12016-07-12 06:39:48 +0000543}
544
Eugene Leviantbbe38602016-07-19 09:25:43 +0000545template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
546 return !Opt.PhdrsCommands.empty();
547}
548
549// Returns indices of ELF headers containing specific section, identified
550// by Name. Each index is a zero based number of ELF header listed within
551// PHDRS {} script block.
552template <class ELFT>
553std::vector<size_t>
554LinkerScript<ELFT>::getPhdrIndicesForSection(StringRef Name) {
George Rimar076fe152016-07-21 06:43:01 +0000555 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
556 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
557 if (!Cmd || Cmd->Name != Name)
George Rimar31d842f2016-07-20 16:43:03 +0000558 continue;
559
560 std::vector<size_t> Indices;
George Rimar076fe152016-07-21 06:43:01 +0000561 for (StringRef PhdrName : Cmd->Phdrs) {
George Rimar31d842f2016-07-20 16:43:03 +0000562 auto ItPhdr =
563 std::find_if(Opt.PhdrsCommands.rbegin(), Opt.PhdrsCommands.rend(),
George Rimar076fe152016-07-21 06:43:01 +0000564 [&](PhdrsCommand &P) { return P.Name == PhdrName; });
Eugene Leviantbbe38602016-07-19 09:25:43 +0000565 if (ItPhdr == Opt.PhdrsCommands.rend())
566 error("section header '" + PhdrName + "' is not listed in PHDRS");
567 else
568 Indices.push_back(std::distance(ItPhdr, Opt.PhdrsCommands.rend()) - 1);
569 }
George Rimar31d842f2016-07-20 16:43:03 +0000570 return Indices;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000571 }
George Rimar31d842f2016-07-20 16:43:03 +0000572 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000573}
574
Rui Ueyama07320e42016-04-20 20:13:41 +0000575class elf::ScriptParser : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000576 typedef void (ScriptParser::*Handler)();
577
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000578public:
Rui Ueyama07320e42016-04-20 20:13:41 +0000579 ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
George Rimarf23b2322016-02-19 10:45:45 +0000580
Rui Ueyama4a465392016-04-22 22:59:24 +0000581 void run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000582
583private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000584 void addFile(StringRef Path);
585
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000586 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000587 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000588 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000589 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000590 void readInclude();
George Rimarc3794e52016-02-24 09:21:47 +0000591 void readNothing() {}
Rui Ueyamaee592822015-10-07 00:25:09 +0000592 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000593 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000594 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000595 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000596 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000597 void readSections();
598
George Rimar652852c2016-04-16 10:10:32 +0000599 void readLocationCounterValue();
Eugene Levianteda81a12016-07-12 06:39:48 +0000600 void readOutputSectionDescription(StringRef OutSec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000601 std::vector<StringRef> readOutputSectionPhdrs();
602 unsigned readPhdrType();
Eugene Levianta31c91b2016-07-22 07:38:40 +0000603 void readProvide(bool Hidden);
604 SymbolAssignment *readSymbolAssignment(StringRef Name);
Eugene Levianteda81a12016-07-12 06:39:48 +0000605 std::vector<StringRef> readSectionsCommandExpr();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000606
George Rimarc3794e52016-02-24 09:21:47 +0000607 const static StringMap<Handler> Cmd;
Rui Ueyama07320e42016-04-20 20:13:41 +0000608 ScriptConfiguration &Opt = *ScriptConfig;
609 StringSaver Saver = {ScriptConfig->Alloc};
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000610 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000611};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000612
Rafael Espindolae0df00b2016-02-28 00:25:54 +0000613const StringMap<elf::ScriptParser::Handler> elf::ScriptParser::Cmd = {
George Rimarc3794e52016-02-24 09:21:47 +0000614 {"ENTRY", &ScriptParser::readEntry},
615 {"EXTERN", &ScriptParser::readExtern},
616 {"GROUP", &ScriptParser::readGroup},
617 {"INCLUDE", &ScriptParser::readInclude},
618 {"INPUT", &ScriptParser::readGroup},
619 {"OUTPUT", &ScriptParser::readOutput},
620 {"OUTPUT_ARCH", &ScriptParser::readOutputArch},
621 {"OUTPUT_FORMAT", &ScriptParser::readOutputFormat},
Eugene Leviantbbe38602016-07-19 09:25:43 +0000622 {"PHDRS", &ScriptParser::readPhdrs},
George Rimarc3794e52016-02-24 09:21:47 +0000623 {"SEARCH_DIR", &ScriptParser::readSearchDir},
624 {"SECTIONS", &ScriptParser::readSections},
625 {";", &ScriptParser::readNothing}};
626
Rui Ueyama717677a2016-02-11 21:17:59 +0000627void ScriptParser::run() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000628 while (!atEOF()) {
629 StringRef Tok = next();
George Rimarc3794e52016-02-24 09:21:47 +0000630 if (Handler Fn = Cmd.lookup(Tok))
631 (this->*Fn)();
632 else
George Rimar57610422016-03-11 14:43:02 +0000633 setError("unknown directive: " + Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000634 }
635}
636
Rui Ueyama717677a2016-02-11 21:17:59 +0000637void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000638 if (IsUnderSysroot && S.startswith("/")) {
639 SmallString<128> Path;
640 (Config->Sysroot + S).toStringRef(Path);
641 if (sys::fs::exists(Path)) {
642 Driver->addFile(Saver.save(Path.str()));
643 return;
644 }
645 }
646
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +0000647 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +0000648 Driver->addFile(S);
649 } else if (S.startswith("=")) {
650 if (Config->Sysroot.empty())
651 Driver->addFile(S.substr(1));
652 else
653 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
654 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +0000655 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +0000656 } else if (sys::fs::exists(S)) {
657 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +0000658 } else {
659 std::string Path = findFromSearchPaths(S);
660 if (Path.empty())
George Rimar777f9632016-03-12 08:31:34 +0000661 setError("unable to find " + S);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000662 else
663 Driver->addFile(Saver.save(Path));
Rui Ueyama52a15092015-10-11 03:28:42 +0000664 }
665}
666
Rui Ueyama717677a2016-02-11 21:17:59 +0000667void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000668 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +0000669 bool Orig = Config->AsNeeded;
670 Config->AsNeeded = true;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000671 while (!Error) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000672 StringRef Tok = next();
673 if (Tok == ")")
Rui Ueyama35da9b62015-10-11 20:59:12 +0000674 break;
Rui Ueyama52a15092015-10-11 03:28:42 +0000675 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000676 }
Rui Ueyama35da9b62015-10-11 20:59:12 +0000677 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000678}
679
Rui Ueyama717677a2016-02-11 21:17:59 +0000680void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +0000681 // -e <symbol> takes predecence over ENTRY(<symbol>).
682 expect("(");
683 StringRef Tok = next();
684 if (Config->Entry.empty())
685 Config->Entry = Tok;
686 expect(")");
687}
688
Rui Ueyama717677a2016-02-11 21:17:59 +0000689void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +0000690 expect("(");
Rui Ueyama025d59b2016-02-02 20:27:59 +0000691 while (!Error) {
George Rimar83f406c2015-10-19 17:35:12 +0000692 StringRef Tok = next();
693 if (Tok == ")")
694 return;
695 Config->Undefined.push_back(Tok);
696 }
697}
698
Rui Ueyama717677a2016-02-11 21:17:59 +0000699void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000700 expect("(");
Rui Ueyama025d59b2016-02-02 20:27:59 +0000701 while (!Error) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000702 StringRef Tok = next();
703 if (Tok == ")")
704 return;
705 if (Tok == "AS_NEEDED") {
706 readAsNeeded();
707 continue;
708 }
Rui Ueyama52a15092015-10-11 03:28:42 +0000709 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000710 }
711}
712
Rui Ueyama717677a2016-02-11 21:17:59 +0000713void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000714 StringRef Tok = next();
715 auto MBOrErr = MemoryBuffer::getFile(Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000716 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +0000717 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000718 return;
719 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000720 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Rui Ueyamaa47ee682015-10-11 01:53:04 +0000721 StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
722 std::vector<StringRef> V = tokenize(S);
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000723 Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000724}
725
Rui Ueyama717677a2016-02-11 21:17:59 +0000726void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +0000727 // -o <file> takes predecence over OUTPUT(<file>).
728 expect("(");
729 StringRef Tok = next();
730 if (Config->OutputFile.empty())
731 Config->OutputFile = Tok;
732 expect(")");
733}
734
Rui Ueyama717677a2016-02-11 21:17:59 +0000735void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +0000736 // Error checking only for now.
737 expect("(");
738 next();
739 expect(")");
740}
741
Rui Ueyama717677a2016-02-11 21:17:59 +0000742void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000743 // Error checking only for now.
744 expect("(");
745 next();
Davide Italiano6836c612015-10-12 21:08:41 +0000746 StringRef Tok = next();
747 if (Tok == ")")
748 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000749 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +0000750 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000751 return;
752 }
Davide Italiano6836c612015-10-12 21:08:41 +0000753 next();
754 expect(",");
755 next();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000756 expect(")");
757}
758
Eugene Leviantbbe38602016-07-19 09:25:43 +0000759void ScriptParser::readPhdrs() {
760 expect("{");
761 while (!Error && !skip("}")) {
762 StringRef Tok = next();
Eugene Leviant865bf862016-07-21 10:43:25 +0000763 Opt.PhdrsCommands.push_back({Tok, PT_NULL, false, false, UINT_MAX});
Eugene Leviantbbe38602016-07-19 09:25:43 +0000764 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
765
766 PhdrCmd.Type = readPhdrType();
767 do {
768 Tok = next();
769 if (Tok == ";")
770 break;
771 if (Tok == "FILEHDR")
772 PhdrCmd.HasFilehdr = true;
773 else if (Tok == "PHDRS")
774 PhdrCmd.HasPhdrs = true;
Eugene Leviant865bf862016-07-21 10:43:25 +0000775 else if (Tok == "FLAGS") {
776 expect("(");
777 next().getAsInteger(0, PhdrCmd.Flags);
778 expect(")");
779 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +0000780 setError("unexpected header attribute: " + Tok);
781 } while (!Error);
782 }
783}
784
Rui Ueyama717677a2016-02-11 21:17:59 +0000785void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +0000786 expect("(");
Rafael Espindola06501922016-03-08 17:13:12 +0000787 Config->SearchPaths.push_back(next());
Davide Italiano68a39a62015-10-08 17:51:41 +0000788 expect(")");
789}
790
Rui Ueyama717677a2016-02-11 21:17:59 +0000791void ScriptParser::readSections() {
Rui Ueyama07320e42016-04-20 20:13:41 +0000792 Opt.DoLayout = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000793 expect("{");
George Rimar652852c2016-04-16 10:10:32 +0000794 while (!Error && !skip("}")) {
795 StringRef Tok = peek();
Eugene Levianteda81a12016-07-12 06:39:48 +0000796 if (Tok == ".") {
George Rimar652852c2016-04-16 10:10:32 +0000797 readLocationCounterValue();
Eugene Levianteda81a12016-07-12 06:39:48 +0000798 continue;
799 }
800 next();
Eugene Levianta31c91b2016-07-22 07:38:40 +0000801 if (Tok == "PROVIDE")
802 readProvide(false);
803 else if (Tok == "PROVIDE_HIDDEN")
804 readProvide(true);
805 else if (peek() == "=")
Eugene Levianteda81a12016-07-12 06:39:48 +0000806 readSymbolAssignment(Tok);
George Rimar652852c2016-04-16 10:10:32 +0000807 else
Eugene Levianteda81a12016-07-12 06:39:48 +0000808 readOutputSectionDescription(Tok);
George Rimar652852c2016-04-16 10:10:32 +0000809 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000810}
811
George Rimar652852c2016-04-16 10:10:32 +0000812void ScriptParser::readLocationCounterValue() {
813 expect(".");
814 expect("=");
Eugene Levianteda81a12016-07-12 06:39:48 +0000815 std::vector<StringRef> Expr = readSectionsCommandExpr();
816 if (Expr.empty())
George Rimar652852c2016-04-16 10:10:32 +0000817 error("error in location counter expression");
Eugene Levianteda81a12016-07-12 06:39:48 +0000818 else
George Rimar076fe152016-07-21 06:43:01 +0000819 Opt.Commands.push_back(llvm::make_unique<SymbolAssignment>(".", Expr));
George Rimar652852c2016-04-16 10:10:32 +0000820}
821
Eugene Levianteda81a12016-07-12 06:39:48 +0000822void ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +0000823 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
824 Opt.Commands.emplace_back(Cmd);
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000825 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +0000826
827 // Parse constraints.
828 if (skip("ONLY_IF_RO"))
829 Cmd->Constraint = ReadOnly;
830 if (skip("ONLY_IF_RW"))
831 Cmd->Constraint = ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000832 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000833
Rui Ueyama025d59b2016-02-02 20:27:59 +0000834 while (!Error && !skip("}")) {
George Rimar481c2ce2016-02-23 07:47:54 +0000835 StringRef Tok = next();
836 if (Tok == "*") {
George Rimareea31142016-07-21 14:26:59 +0000837 auto *InCmd = new InputSectionDescription();
838 Cmd->Commands.emplace_back(InCmd);
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000839 expect("(");
840 while (!Error && !skip(")"))
George Rimareea31142016-07-21 14:26:59 +0000841 InCmd->Patterns.push_back(next());
George Rimar481c2ce2016-02-23 07:47:54 +0000842 } else if (Tok == "KEEP") {
843 expect("(");
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000844 expect("*");
845 expect("(");
George Rimareea31142016-07-21 14:26:59 +0000846 auto *InCmd = new InputSectionDescription();
847 Cmd->Commands.emplace_back(InCmd);
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000848 while (!Error && !skip(")")) {
George Rimareea31142016-07-21 14:26:59 +0000849 Opt.KeptSections.push_back(peek());
850 InCmd->Patterns.push_back(next());
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000851 }
George Rimar481c2ce2016-02-23 07:47:54 +0000852 expect(")");
853 } else {
George Rimar777f9632016-03-12 08:31:34 +0000854 setError("unknown command " + Tok);
George Rimar481c2ce2016-02-23 07:47:54 +0000855 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000856 }
George Rimar076fe152016-07-21 06:43:01 +0000857 Cmd->Phdrs = readOutputSectionPhdrs();
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000858
George Rimare2ee72b2016-02-26 14:48:31 +0000859 StringRef Tok = peek();
860 if (Tok.startswith("=")) {
861 if (!Tok.startswith("=0x")) {
Rui Ueyama3ed2f062016-03-13 03:17:44 +0000862 setError("filler should be a hexadecimal value");
George Rimare2ee72b2016-02-26 14:48:31 +0000863 return;
864 }
Rui Ueyama3e808972016-02-28 05:09:11 +0000865 Tok = Tok.substr(3);
George Rimarf6c3cce2016-07-21 07:48:54 +0000866 Cmd->Filler = parseHex(Tok);
George Rimare2ee72b2016-02-26 14:48:31 +0000867 next();
868 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000869}
870
Eugene Levianta31c91b2016-07-22 07:38:40 +0000871void ScriptParser::readProvide(bool Hidden) {
872 expect("(");
873 if (SymbolAssignment *Assignment = readSymbolAssignment(next())) {
874 Assignment->Provide = true;
875 Assignment->Hidden = Hidden;
876 }
877 expect(")");
878 expect(";");
Eugene Levianteda81a12016-07-12 06:39:48 +0000879}
880
Eugene Levianta31c91b2016-07-22 07:38:40 +0000881SymbolAssignment *ScriptParser::readSymbolAssignment(StringRef Name) {
882 expect("=");
883 std::vector<StringRef> Expr = readSectionsCommandExpr();
884 if (Expr.empty()) {
885 error("error in symbol assignment expression");
886 } else {
887 Opt.Commands.push_back(llvm::make_unique<SymbolAssignment>(Name, Expr));
888 return static_cast<SymbolAssignment *>(Opt.Commands.back().get());
889 }
890 return nullptr;
891}
892
893// This function reads balanced expression until semicolon is seen.
Eugene Levianteda81a12016-07-12 06:39:48 +0000894std::vector<StringRef> ScriptParser::readSectionsCommandExpr() {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000895 int Braces = 0;
Eugene Levianteda81a12016-07-12 06:39:48 +0000896 std::vector<StringRef> Expr;
897 while (!Error) {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000898 StringRef Tok = peek();
899
900 if (Tok == "(")
901 Braces++;
902 else if (Tok == ")")
903 if (--Braces < 0)
904 break;
905
906 next();
Eugene Levianteda81a12016-07-12 06:39:48 +0000907 if (Tok == ";")
908 break;
909 Expr.push_back(Tok);
910 }
911 return Expr;
912}
913
Eugene Leviantbbe38602016-07-19 09:25:43 +0000914std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
915 std::vector<StringRef> Phdrs;
916 while (!Error && peek().startswith(":")) {
917 StringRef Tok = next();
918 Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
919 if (Tok.empty()) {
920 setError("section header name is empty");
921 break;
922 }
Rui Ueyama047404f2016-07-20 19:36:36 +0000923 Phdrs.push_back(Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000924 }
925 return Phdrs;
926}
927
928unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +0000929 StringRef Tok = next();
Rui Ueyamab0f6c592016-07-20 19:36:38 +0000930 unsigned Ret = StringSwitch<unsigned>(Tok)
931 .Case("PT_NULL", PT_NULL)
932 .Case("PT_LOAD", PT_LOAD)
933 .Case("PT_DYNAMIC", PT_DYNAMIC)
934 .Case("PT_INTERP", PT_INTERP)
935 .Case("PT_NOTE", PT_NOTE)
936 .Case("PT_SHLIB", PT_SHLIB)
937 .Case("PT_PHDR", PT_PHDR)
938 .Case("PT_TLS", PT_TLS)
939 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
940 .Case("PT_GNU_STACK", PT_GNU_STACK)
941 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
942 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000943
Rui Ueyamab0f6c592016-07-20 19:36:38 +0000944 if (Ret == (unsigned)-1) {
945 setError("invalid program header type: " + Tok);
946 return PT_NULL;
947 }
948 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000949}
950
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000951static bool isUnderSysroot(StringRef Path) {
952 if (Config->Sysroot == "")
953 return false;
954 for (; !Path.empty(); Path = sys::path::parent_path(Path))
955 if (sys::fs::equivalent(Config->Sysroot, Path))
956 return true;
957 return false;
958}
959
Rui Ueyama07320e42016-04-20 20:13:41 +0000960// Entry point.
961void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000962 StringRef Path = MB.getBufferIdentifier();
Rui Ueyama07320e42016-04-20 20:13:41 +0000963 ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000964}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +0000965
Rui Ueyama07320e42016-04-20 20:13:41 +0000966template class elf::LinkerScript<ELF32LE>;
967template class elf::LinkerScript<ELF32BE>;
968template class elf::LinkerScript<ELF64LE>;
969template class elf::LinkerScript<ELF64BE>;