blob: 33ccf715fe647987a8e4278387454b29bd6b2a18 [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 Ueyama1ebc8ed2016-02-12 21:47:28 +0000240template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000241bool LinkerScript<ELFT>::isDiscarded(InputSectionBase<ELFT> *S) {
George Rimareea31142016-07-21 14:26:59 +0000242 return !S || !S->Live;
Rui Ueyama717677a2016-02-11 21:17:59 +0000243}
244
Rui Ueyama07320e42016-04-20 20:13:41 +0000245template <class ELFT>
246bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) {
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000247 for (StringRef Pat : Opt.KeptSections)
Rui Ueyama722830a2016-06-29 05:32:09 +0000248 if (globMatch(Pat, S->getSectionName()))
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000249 return true;
250 return false;
George Rimar481c2ce2016-02-23 07:47:54 +0000251}
252
George Rimareea31142016-07-21 14:26:59 +0000253static bool match(StringRef Pattern, ArrayRef<StringRef> Arr) {
254 for (StringRef S : Arr)
255 if (globMatch(S, Pattern))
256 return true;
257 return false;
258}
259
George Rimar652852c2016-04-16 10:10:32 +0000260template <class ELFT>
Rui Ueyamaa7f78842016-07-20 17:19:03 +0000261std::vector<OutputSectionBase<ELFT> *>
Eugene Leviante63d81b2016-07-20 14:43:20 +0000262LinkerScript<ELFT>::createSections(OutputSectionFactory<ELFT> &Factory) {
George Rimareea31142016-07-21 14:26:59 +0000263 typedef const std::unique_ptr<ObjectFile<ELFT>> ObjectFile;
Rui Ueyamaa7f78842016-07-20 17:19:03 +0000264 std::vector<OutputSectionBase<ELFT> *> Result;
Davide Italiano246f6812016-07-22 03:36:24 +0000265 DenseSet<OutputSectionBase<ELFT> *> Removed;
Rui Ueyamaa7f78842016-07-20 17:19:03 +0000266
Eugene Leviante63d81b2016-07-20 14:43:20 +0000267 // Add input section to output section. If there is no output section yet,
268 // then create it and add to output section list.
Davide Italiano246f6812016-07-22 03:36:24 +0000269 auto AddInputSec = [&](InputSectionBase<ELFT> *C, StringRef Name,
270 ConstraintKind Constraint) {
Eugene Leviante63d81b2016-07-20 14:43:20 +0000271 OutputSectionBase<ELFT> *Sec;
272 bool IsNew;
273 std::tie(Sec, IsNew) = Factory.create(C, Name);
274 if (IsNew)
Rui Ueyamaa7f78842016-07-20 17:19:03 +0000275 Result.push_back(Sec);
Davide Italiano246f6812016-07-22 03:36:24 +0000276 if ((!(C->getSectionHdr()->sh_flags & SHF_WRITE)) &&
277 Constraint == ReadWrite) {
278 Removed.insert(Sec);
279 return;
280 }
281 if ((C->getSectionHdr()->sh_flags & SHF_WRITE) && Constraint == ReadOnly) {
282 Removed.insert(Sec);
283 return;
284 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000285 Sec->addSection(C);
286 };
287
288 // Select input sections matching rule and add them to corresponding
289 // output section. Section rules are processed in order they're listed
290 // in script, so correct input section order is maintained by design.
George Rimareea31142016-07-21 14:26:59 +0000291 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
292 auto *OutCmd = dyn_cast<OutputSectionCommand>(Base.get());
293 if (!OutCmd)
294 continue;
295
296 for (const std::unique_ptr<BaseCommand> &Cmd : OutCmd->Commands) {
297 auto *InCmd = dyn_cast<InputSectionDescription>(Cmd.get());
298 if (!InCmd)
299 continue;
300
301 for (ObjectFile &F : Symtab<ELFT>::X->getObjectFiles()) {
302 for (InputSectionBase<ELFT> *S : F->getSections()) {
303 if (isDiscarded(S) || S->OutSec)
304 continue;
305
306 if (match(S->getSectionName(), InCmd->Patterns)) {
307 if (OutCmd->Name == "/DISCARD/")
308 S->Live = false;
309 else
Davide Italiano246f6812016-07-22 03:36:24 +0000310 AddInputSec(S, OutCmd->Name, OutCmd->Constraint);
George Rimareea31142016-07-21 14:26:59 +0000311 }
312 }
313 }
314 }
315 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000316
317 // Add all other input sections, which are not listed in script.
George Rimareea31142016-07-21 14:26:59 +0000318 for (ObjectFile &F : Symtab<ELFT>::X->getObjectFiles())
Reid Kleckner3c944ec2016-07-21 18:39:28 +0000319 for (InputSectionBase<ELFT> *S : F->getSections()) {
Eugene Leviante63d81b2016-07-20 14:43:20 +0000320 if (!isDiscarded(S)) {
321 if (!S->OutSec)
Davide Italiano246f6812016-07-22 03:36:24 +0000322 AddInputSec(S, getOutputSectionName(S), NoConstraint);
Eugene Leviante63d81b2016-07-20 14:43:20 +0000323 } else
324 reportDiscarded(S, F);
Reid Kleckner3c944ec2016-07-21 18:39:28 +0000325 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000326
Davide Italiano246f6812016-07-22 03:36:24 +0000327 // Remove from the output all the sections which did not met the constraints.
328 Result.erase(std::remove_if(Result.begin(), Result.end(),
329 [&](OutputSectionBase<ELFT> *Sec) {
330 return Removed.count(Sec);
331 }),
332 Result.end());
Eugene Leviante63d81b2016-07-20 14:43:20 +0000333 return Result;
334}
335
336template <class ELFT>
George Rimar10e576e2016-07-21 16:07:40 +0000337void LinkerScript<ELFT>::dispatchAssignment(SymbolAssignment *Cmd) {
338 uint64_t Val = evalExpr(Cmd->Expr, Dot);
339 if (Cmd->Name == ".") {
340 Dot = Val;
341 } else {
342 auto *D = cast<DefinedRegular<ELFT>>(Symtab<ELFT>::X->find(Cmd->Name));
343 D->Value = Val;
344 }
345}
346
347template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000348void LinkerScript<ELFT>::assignAddresses(
George Rimardbbd8b12016-04-21 11:21:48 +0000349 ArrayRef<OutputSectionBase<ELFT> *> Sections) {
George Rimar652852c2016-04-16 10:10:32 +0000350 // Orphan sections are sections present in the input files which
Rui Ueyama7c18c282016-04-18 21:00:40 +0000351 // are not explicitly placed into the output file by the linker script.
352 // We place orphan sections at end of file.
353 // Other linkers places them using some heuristics as described in
George Rimar652852c2016-04-16 10:10:32 +0000354 // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
Rui Ueyama7c18c282016-04-18 21:00:40 +0000355 for (OutputSectionBase<ELFT> *Sec : Sections) {
George Rimar652852c2016-04-16 10:10:32 +0000356 StringRef Name = Sec->getName();
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000357 if (getSectionIndex(Name) == INT_MAX)
George Rimar076fe152016-07-21 06:43:01 +0000358 Opt.Commands.push_back(llvm::make_unique<OutputSectionCommand>(Name));
George Rimar652852c2016-04-16 10:10:32 +0000359 }
George Rimar652852c2016-04-16 10:10:32 +0000360
Rui Ueyama7c18c282016-04-18 21:00:40 +0000361 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rui Ueyama52c4e172016-07-01 10:42:25 +0000362 Dot = Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
Eugene Leviant467c4d52016-07-01 10:27:36 +0000363 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
George Rimar652852c2016-04-16 10:10:32 +0000364 uintX_t ThreadBssOffset = 0;
George Rimar652852c2016-04-16 10:10:32 +0000365
George Rimar076fe152016-07-21 06:43:01 +0000366 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
367 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
George Rimar10e576e2016-07-21 16:07:40 +0000368 dispatchAssignment(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000369 continue;
370 }
371
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000372 // Find all the sections with required name. There can be more than
George Rimar6ad330a2016-07-19 07:39:07 +0000373 // one section with such name, if the alignment, flags or type
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000374 // attribute differs.
George Rimar076fe152016-07-21 06:43:01 +0000375 auto *Cmd = cast<OutputSectionCommand>(Base.get());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000376 for (OutputSectionBase<ELFT> *Sec : Sections) {
George Rimar076fe152016-07-21 06:43:01 +0000377 if (Sec->getName() != Cmd->Name)
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000378 continue;
George Rimar652852c2016-04-16 10:10:32 +0000379
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000380 if ((Sec->getFlags() & SHF_TLS) && Sec->getType() == SHT_NOBITS) {
381 uintX_t TVA = Dot + ThreadBssOffset;
Rui Ueyama424b4082016-06-17 01:18:46 +0000382 TVA = alignTo(TVA, Sec->getAlignment());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000383 Sec->setVA(TVA);
384 ThreadBssOffset = TVA - Dot + Sec->getSize();
385 continue;
386 }
George Rimar652852c2016-04-16 10:10:32 +0000387
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000388 if (Sec->getFlags() & SHF_ALLOC) {
Rui Ueyama424b4082016-06-17 01:18:46 +0000389 Dot = alignTo(Dot, Sec->getAlignment());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000390 Sec->setVA(Dot);
Rui Ueyama52c4e172016-07-01 10:42:25 +0000391 MinVA = std::min(MinVA, Dot);
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000392 Dot += Sec->getSize();
393 continue;
394 }
George Rimar652852c2016-04-16 10:10:32 +0000395 }
396 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000397
Rafael Espindola64c32d62016-07-07 14:28:47 +0000398 // ELF and Program headers need to be right before the first section in
George Rimarb91e7112016-07-19 07:42:07 +0000399 // memory. Set their addresses accordingly.
Eugene Leviant467c4d52016-07-01 10:27:36 +0000400 MinVA = alignDown(MinVA - Out<ELFT>::ElfHeader->getSize() -
401 Out<ELFT>::ProgramHeaders->getSize(),
402 Target->PageSize);
403 Out<ELFT>::ElfHeader->setVA(MinVA);
404 Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
George Rimar652852c2016-04-16 10:10:32 +0000405}
406
Rui Ueyama07320e42016-04-20 20:13:41 +0000407template <class ELFT>
Rafael Espindola74df5c72016-07-19 12:33:46 +0000408std::vector<PhdrEntry<ELFT>>
Eugene Leviantbbe38602016-07-19 09:25:43 +0000409LinkerScript<ELFT>::createPhdrs(ArrayRef<OutputSectionBase<ELFT> *> Sections) {
410 int TlsNum = -1;
411 int NoteNum = -1;
412 int RelroNum = -1;
413 Phdr *Load = nullptr;
414 uintX_t Flags = PF_R;
415 std::vector<Phdr> Phdrs;
416
417 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Eugene Leviant865bf862016-07-21 10:43:25 +0000418 Phdrs.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000419 Phdr &Added = Phdrs.back();
420
421 if (Cmd.HasFilehdr)
Rui Ueyama18f084f2016-07-20 19:36:41 +0000422 Added.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000423 if (Cmd.HasPhdrs)
Rui Ueyama18f084f2016-07-20 19:36:41 +0000424 Added.add(Out<ELFT>::ProgramHeaders);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000425
426 switch (Cmd.Type) {
427 case PT_INTERP:
Rui Ueyamafd03cfd2016-07-21 11:01:23 +0000428 if (Out<ELFT>::Interp)
Rui Ueyama18f084f2016-07-20 19:36:41 +0000429 Added.add(Out<ELFT>::Interp);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000430 break;
431 case PT_DYNAMIC:
432 if (isOutputDynamic<ELFT>()) {
433 Added.H.p_flags = toPhdrFlags(Out<ELFT>::Dynamic->getFlags());
Rui Ueyama18f084f2016-07-20 19:36:41 +0000434 Added.add(Out<ELFT>::Dynamic);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000435 }
436 break;
437 case PT_TLS:
438 TlsNum = Phdrs.size() - 1;
439 break;
440 case PT_NOTE:
441 NoteNum = Phdrs.size() - 1;
442 break;
443 case PT_GNU_RELRO:
444 RelroNum = Phdrs.size() - 1;
445 break;
446 case PT_GNU_EH_FRAME:
447 if (!Out<ELFT>::EhFrame->empty() && Out<ELFT>::EhFrameHdr) {
448 Added.H.p_flags = toPhdrFlags(Out<ELFT>::EhFrameHdr->getFlags());
Rui Ueyama18f084f2016-07-20 19:36:41 +0000449 Added.add(Out<ELFT>::EhFrameHdr);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000450 }
451 break;
452 }
453 }
454
455 for (OutputSectionBase<ELFT> *Sec : Sections) {
456 if (!(Sec->getFlags() & SHF_ALLOC))
457 break;
458
459 if (TlsNum != -1 && (Sec->getFlags() & SHF_TLS))
Rui Ueyama18f084f2016-07-20 19:36:41 +0000460 Phdrs[TlsNum].add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000461
462 if (!needsPtLoad<ELFT>(Sec))
463 continue;
464
465 const std::vector<size_t> &PhdrIds =
466 getPhdrIndicesForSection(Sec->getName());
467 if (!PhdrIds.empty()) {
468 // Assign headers specified by linker script
469 for (size_t Id : PhdrIds) {
Rui Ueyama18f084f2016-07-20 19:36:41 +0000470 Phdrs[Id].add(Sec);
Eugene Leviant865bf862016-07-21 10:43:25 +0000471 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
472 Phdrs[Id].H.p_flags |= toPhdrFlags(Sec->getFlags());
Eugene Leviantbbe38602016-07-19 09:25:43 +0000473 }
474 } else {
475 // If we have no load segment or flags've changed then we want new load
476 // segment.
477 uintX_t NewFlags = toPhdrFlags(Sec->getFlags());
478 if (Load == nullptr || Flags != NewFlags) {
479 Load = &*Phdrs.emplace(Phdrs.end(), PT_LOAD, NewFlags);
480 Flags = NewFlags;
481 }
Rui Ueyama18f084f2016-07-20 19:36:41 +0000482 Load->add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000483 }
484
485 if (RelroNum != -1 && isRelroSection(Sec))
Rui Ueyama18f084f2016-07-20 19:36:41 +0000486 Phdrs[RelroNum].add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000487 if (NoteNum != -1 && Sec->getType() == SHT_NOTE)
Rui Ueyama18f084f2016-07-20 19:36:41 +0000488 Phdrs[NoteNum].add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000489 }
490 return Phdrs;
491}
492
493template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000494ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000495 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
496 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
497 if (Cmd->Name == Name)
498 return Cmd->Filler;
499 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000500}
501
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000502// Returns the index of the given section name in linker script
503// SECTIONS commands. Sections are laid out as the same order as they
504// were in the script. If a given name did not appear in the script,
505// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000506template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
George Rimar71b26e92016-04-21 10:22:02 +0000507 auto Begin = Opt.Commands.begin();
508 auto End = Opt.Commands.end();
George Rimar076fe152016-07-21 06:43:01 +0000509 auto I =
510 std::find_if(Begin, End, [&](const std::unique_ptr<BaseCommand> &Base) {
511 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
512 if (Cmd->Name == Name)
513 return true;
514 return false;
515 });
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000516 return I == End ? INT_MAX : (I - Begin);
George Rimar71b26e92016-04-21 10:22:02 +0000517}
518
519// A compartor to sort output sections. Returns -1 or 1 if
520// A or B are mentioned in linker script. Otherwise, returns 0.
Rui Ueyama07320e42016-04-20 20:13:41 +0000521template <class ELFT>
522int LinkerScript<ELFT>::compareSections(StringRef A, StringRef B) {
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000523 int I = getSectionIndex(A);
524 int J = getSectionIndex(B);
525 if (I == INT_MAX && J == INT_MAX)
Rui Ueyama717677a2016-02-11 21:17:59 +0000526 return 0;
527 return I < J ? -1 : 1;
528}
529
George Rimar076fe152016-07-21 06:43:01 +0000530template <class ELFT> void LinkerScript<ELFT>::addScriptedSymbols() {
531 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
532 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get()))
533 if (Cmd->Name != "." && Symtab<ELFT>::X->find(Cmd->Name) == nullptr)
534 Symtab<ELFT>::X->addAbsolute(Cmd->Name, STV_DEFAULT);
Eugene Levianteda81a12016-07-12 06:39:48 +0000535}
536
Eugene Leviantbbe38602016-07-19 09:25:43 +0000537template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
538 return !Opt.PhdrsCommands.empty();
539}
540
541// Returns indices of ELF headers containing specific section, identified
542// by Name. Each index is a zero based number of ELF header listed within
543// PHDRS {} script block.
544template <class ELFT>
545std::vector<size_t>
546LinkerScript<ELFT>::getPhdrIndicesForSection(StringRef Name) {
George Rimar076fe152016-07-21 06:43:01 +0000547 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
548 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
549 if (!Cmd || Cmd->Name != Name)
George Rimar31d842f2016-07-20 16:43:03 +0000550 continue;
551
552 std::vector<size_t> Indices;
George Rimar076fe152016-07-21 06:43:01 +0000553 for (StringRef PhdrName : Cmd->Phdrs) {
George Rimar31d842f2016-07-20 16:43:03 +0000554 auto ItPhdr =
555 std::find_if(Opt.PhdrsCommands.rbegin(), Opt.PhdrsCommands.rend(),
George Rimar076fe152016-07-21 06:43:01 +0000556 [&](PhdrsCommand &P) { return P.Name == PhdrName; });
Eugene Leviantbbe38602016-07-19 09:25:43 +0000557 if (ItPhdr == Opt.PhdrsCommands.rend())
558 error("section header '" + PhdrName + "' is not listed in PHDRS");
559 else
560 Indices.push_back(std::distance(ItPhdr, Opt.PhdrsCommands.rend()) - 1);
561 }
George Rimar31d842f2016-07-20 16:43:03 +0000562 return Indices;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000563 }
George Rimar31d842f2016-07-20 16:43:03 +0000564 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000565}
566
Rui Ueyama07320e42016-04-20 20:13:41 +0000567class elf::ScriptParser : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000568 typedef void (ScriptParser::*Handler)();
569
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000570public:
Rui Ueyama07320e42016-04-20 20:13:41 +0000571 ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
George Rimarf23b2322016-02-19 10:45:45 +0000572
Rui Ueyama4a465392016-04-22 22:59:24 +0000573 void run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000574
575private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000576 void addFile(StringRef Path);
577
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000578 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000579 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000580 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000581 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000582 void readInclude();
George Rimarc3794e52016-02-24 09:21:47 +0000583 void readNothing() {}
Rui Ueyamaee592822015-10-07 00:25:09 +0000584 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000585 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000586 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000587 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000588 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000589 void readSections();
590
George Rimar652852c2016-04-16 10:10:32 +0000591 void readLocationCounterValue();
Eugene Levianteda81a12016-07-12 06:39:48 +0000592 void readOutputSectionDescription(StringRef OutSec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000593 std::vector<StringRef> readOutputSectionPhdrs();
594 unsigned readPhdrType();
Eugene Levianteda81a12016-07-12 06:39:48 +0000595 void readSymbolAssignment(StringRef Name);
596 std::vector<StringRef> readSectionsCommandExpr();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000597
George Rimarc3794e52016-02-24 09:21:47 +0000598 const static StringMap<Handler> Cmd;
Rui Ueyama07320e42016-04-20 20:13:41 +0000599 ScriptConfiguration &Opt = *ScriptConfig;
600 StringSaver Saver = {ScriptConfig->Alloc};
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000601 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000602};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000603
Rafael Espindolae0df00b2016-02-28 00:25:54 +0000604const StringMap<elf::ScriptParser::Handler> elf::ScriptParser::Cmd = {
George Rimarc3794e52016-02-24 09:21:47 +0000605 {"ENTRY", &ScriptParser::readEntry},
606 {"EXTERN", &ScriptParser::readExtern},
607 {"GROUP", &ScriptParser::readGroup},
608 {"INCLUDE", &ScriptParser::readInclude},
609 {"INPUT", &ScriptParser::readGroup},
610 {"OUTPUT", &ScriptParser::readOutput},
611 {"OUTPUT_ARCH", &ScriptParser::readOutputArch},
612 {"OUTPUT_FORMAT", &ScriptParser::readOutputFormat},
Eugene Leviantbbe38602016-07-19 09:25:43 +0000613 {"PHDRS", &ScriptParser::readPhdrs},
George Rimarc3794e52016-02-24 09:21:47 +0000614 {"SEARCH_DIR", &ScriptParser::readSearchDir},
615 {"SECTIONS", &ScriptParser::readSections},
616 {";", &ScriptParser::readNothing}};
617
Rui Ueyama717677a2016-02-11 21:17:59 +0000618void ScriptParser::run() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000619 while (!atEOF()) {
620 StringRef Tok = next();
George Rimarc3794e52016-02-24 09:21:47 +0000621 if (Handler Fn = Cmd.lookup(Tok))
622 (this->*Fn)();
623 else
George Rimar57610422016-03-11 14:43:02 +0000624 setError("unknown directive: " + Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000625 }
626}
627
Rui Ueyama717677a2016-02-11 21:17:59 +0000628void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000629 if (IsUnderSysroot && S.startswith("/")) {
630 SmallString<128> Path;
631 (Config->Sysroot + S).toStringRef(Path);
632 if (sys::fs::exists(Path)) {
633 Driver->addFile(Saver.save(Path.str()));
634 return;
635 }
636 }
637
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +0000638 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +0000639 Driver->addFile(S);
640 } else if (S.startswith("=")) {
641 if (Config->Sysroot.empty())
642 Driver->addFile(S.substr(1));
643 else
644 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
645 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +0000646 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +0000647 } else if (sys::fs::exists(S)) {
648 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +0000649 } else {
650 std::string Path = findFromSearchPaths(S);
651 if (Path.empty())
George Rimar777f9632016-03-12 08:31:34 +0000652 setError("unable to find " + S);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000653 else
654 Driver->addFile(Saver.save(Path));
Rui Ueyama52a15092015-10-11 03:28:42 +0000655 }
656}
657
Rui Ueyama717677a2016-02-11 21:17:59 +0000658void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000659 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +0000660 bool Orig = Config->AsNeeded;
661 Config->AsNeeded = true;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000662 while (!Error) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000663 StringRef Tok = next();
664 if (Tok == ")")
Rui Ueyama35da9b62015-10-11 20:59:12 +0000665 break;
Rui Ueyama52a15092015-10-11 03:28:42 +0000666 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000667 }
Rui Ueyama35da9b62015-10-11 20:59:12 +0000668 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000669}
670
Rui Ueyama717677a2016-02-11 21:17:59 +0000671void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +0000672 // -e <symbol> takes predecence over ENTRY(<symbol>).
673 expect("(");
674 StringRef Tok = next();
675 if (Config->Entry.empty())
676 Config->Entry = Tok;
677 expect(")");
678}
679
Rui Ueyama717677a2016-02-11 21:17:59 +0000680void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +0000681 expect("(");
Rui Ueyama025d59b2016-02-02 20:27:59 +0000682 while (!Error) {
George Rimar83f406c2015-10-19 17:35:12 +0000683 StringRef Tok = next();
684 if (Tok == ")")
685 return;
686 Config->Undefined.push_back(Tok);
687 }
688}
689
Rui Ueyama717677a2016-02-11 21:17:59 +0000690void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000691 expect("(");
Rui Ueyama025d59b2016-02-02 20:27:59 +0000692 while (!Error) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000693 StringRef Tok = next();
694 if (Tok == ")")
695 return;
696 if (Tok == "AS_NEEDED") {
697 readAsNeeded();
698 continue;
699 }
Rui Ueyama52a15092015-10-11 03:28:42 +0000700 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000701 }
702}
703
Rui Ueyama717677a2016-02-11 21:17:59 +0000704void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000705 StringRef Tok = next();
706 auto MBOrErr = MemoryBuffer::getFile(Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000707 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +0000708 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000709 return;
710 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000711 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Rui Ueyamaa47ee682015-10-11 01:53:04 +0000712 StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
713 std::vector<StringRef> V = tokenize(S);
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000714 Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000715}
716
Rui Ueyama717677a2016-02-11 21:17:59 +0000717void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +0000718 // -o <file> takes predecence over OUTPUT(<file>).
719 expect("(");
720 StringRef Tok = next();
721 if (Config->OutputFile.empty())
722 Config->OutputFile = Tok;
723 expect(")");
724}
725
Rui Ueyama717677a2016-02-11 21:17:59 +0000726void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +0000727 // Error checking only for now.
728 expect("(");
729 next();
730 expect(")");
731}
732
Rui Ueyama717677a2016-02-11 21:17:59 +0000733void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000734 // Error checking only for now.
735 expect("(");
736 next();
Davide Italiano6836c612015-10-12 21:08:41 +0000737 StringRef Tok = next();
738 if (Tok == ")")
739 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000740 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +0000741 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000742 return;
743 }
Davide Italiano6836c612015-10-12 21:08:41 +0000744 next();
745 expect(",");
746 next();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000747 expect(")");
748}
749
Eugene Leviantbbe38602016-07-19 09:25:43 +0000750void ScriptParser::readPhdrs() {
751 expect("{");
752 while (!Error && !skip("}")) {
753 StringRef Tok = next();
Eugene Leviant865bf862016-07-21 10:43:25 +0000754 Opt.PhdrsCommands.push_back({Tok, PT_NULL, false, false, UINT_MAX});
Eugene Leviantbbe38602016-07-19 09:25:43 +0000755 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
756
757 PhdrCmd.Type = readPhdrType();
758 do {
759 Tok = next();
760 if (Tok == ";")
761 break;
762 if (Tok == "FILEHDR")
763 PhdrCmd.HasFilehdr = true;
764 else if (Tok == "PHDRS")
765 PhdrCmd.HasPhdrs = true;
Eugene Leviant865bf862016-07-21 10:43:25 +0000766 else if (Tok == "FLAGS") {
767 expect("(");
768 next().getAsInteger(0, PhdrCmd.Flags);
769 expect(")");
770 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +0000771 setError("unexpected header attribute: " + Tok);
772 } while (!Error);
773 }
774}
775
Rui Ueyama717677a2016-02-11 21:17:59 +0000776void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +0000777 expect("(");
Rafael Espindola06501922016-03-08 17:13:12 +0000778 Config->SearchPaths.push_back(next());
Davide Italiano68a39a62015-10-08 17:51:41 +0000779 expect(")");
780}
781
Rui Ueyama717677a2016-02-11 21:17:59 +0000782void ScriptParser::readSections() {
Rui Ueyama07320e42016-04-20 20:13:41 +0000783 Opt.DoLayout = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000784 expect("{");
George Rimar652852c2016-04-16 10:10:32 +0000785 while (!Error && !skip("}")) {
786 StringRef Tok = peek();
Eugene Levianteda81a12016-07-12 06:39:48 +0000787 if (Tok == ".") {
George Rimar652852c2016-04-16 10:10:32 +0000788 readLocationCounterValue();
Eugene Levianteda81a12016-07-12 06:39:48 +0000789 continue;
790 }
791 next();
792 if (peek() == "=")
793 readSymbolAssignment(Tok);
George Rimar652852c2016-04-16 10:10:32 +0000794 else
Eugene Levianteda81a12016-07-12 06:39:48 +0000795 readOutputSectionDescription(Tok);
George Rimar652852c2016-04-16 10:10:32 +0000796 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000797}
798
George Rimar652852c2016-04-16 10:10:32 +0000799void ScriptParser::readLocationCounterValue() {
800 expect(".");
801 expect("=");
Eugene Levianteda81a12016-07-12 06:39:48 +0000802 std::vector<StringRef> Expr = readSectionsCommandExpr();
803 if (Expr.empty())
George Rimar652852c2016-04-16 10:10:32 +0000804 error("error in location counter expression");
Eugene Levianteda81a12016-07-12 06:39:48 +0000805 else
George Rimar076fe152016-07-21 06:43:01 +0000806 Opt.Commands.push_back(llvm::make_unique<SymbolAssignment>(".", Expr));
George Rimar652852c2016-04-16 10:10:32 +0000807}
808
Eugene Levianteda81a12016-07-12 06:39:48 +0000809void ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +0000810 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
811 Opt.Commands.emplace_back(Cmd);
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000812 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +0000813
814 // Parse constraints.
815 if (skip("ONLY_IF_RO"))
816 Cmd->Constraint = ReadOnly;
817 if (skip("ONLY_IF_RW"))
818 Cmd->Constraint = ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000819 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000820
Rui Ueyama025d59b2016-02-02 20:27:59 +0000821 while (!Error && !skip("}")) {
George Rimar481c2ce2016-02-23 07:47:54 +0000822 StringRef Tok = next();
823 if (Tok == "*") {
George Rimareea31142016-07-21 14:26:59 +0000824 auto *InCmd = new InputSectionDescription();
825 Cmd->Commands.emplace_back(InCmd);
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000826 expect("(");
827 while (!Error && !skip(")"))
George Rimareea31142016-07-21 14:26:59 +0000828 InCmd->Patterns.push_back(next());
George Rimar481c2ce2016-02-23 07:47:54 +0000829 } else if (Tok == "KEEP") {
830 expect("(");
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000831 expect("*");
832 expect("(");
George Rimareea31142016-07-21 14:26:59 +0000833 auto *InCmd = new InputSectionDescription();
834 Cmd->Commands.emplace_back(InCmd);
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000835 while (!Error && !skip(")")) {
George Rimareea31142016-07-21 14:26:59 +0000836 Opt.KeptSections.push_back(peek());
837 InCmd->Patterns.push_back(next());
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000838 }
George Rimar481c2ce2016-02-23 07:47:54 +0000839 expect(")");
840 } else {
George Rimar777f9632016-03-12 08:31:34 +0000841 setError("unknown command " + Tok);
George Rimar481c2ce2016-02-23 07:47:54 +0000842 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000843 }
George Rimar076fe152016-07-21 06:43:01 +0000844 Cmd->Phdrs = readOutputSectionPhdrs();
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000845
George Rimare2ee72b2016-02-26 14:48:31 +0000846 StringRef Tok = peek();
847 if (Tok.startswith("=")) {
848 if (!Tok.startswith("=0x")) {
Rui Ueyama3ed2f062016-03-13 03:17:44 +0000849 setError("filler should be a hexadecimal value");
George Rimare2ee72b2016-02-26 14:48:31 +0000850 return;
851 }
Rui Ueyama3e808972016-02-28 05:09:11 +0000852 Tok = Tok.substr(3);
George Rimarf6c3cce2016-07-21 07:48:54 +0000853 Cmd->Filler = parseHex(Tok);
George Rimare2ee72b2016-02-26 14:48:31 +0000854 next();
855 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000856}
857
Eugene Levianteda81a12016-07-12 06:39:48 +0000858void ScriptParser::readSymbolAssignment(StringRef Name) {
859 expect("=");
860 std::vector<StringRef> Expr = readSectionsCommandExpr();
861 if (Expr.empty())
862 error("error in symbol assignment expression");
863 else
George Rimar076fe152016-07-21 06:43:01 +0000864 Opt.Commands.push_back(llvm::make_unique<SymbolAssignment>(Name, Expr));
Eugene Levianteda81a12016-07-12 06:39:48 +0000865}
866
867std::vector<StringRef> ScriptParser::readSectionsCommandExpr() {
868 std::vector<StringRef> Expr;
869 while (!Error) {
870 StringRef Tok = next();
871 if (Tok == ";")
872 break;
873 Expr.push_back(Tok);
874 }
875 return Expr;
876}
877
Eugene Leviantbbe38602016-07-19 09:25:43 +0000878std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
879 std::vector<StringRef> Phdrs;
880 while (!Error && peek().startswith(":")) {
881 StringRef Tok = next();
882 Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
883 if (Tok.empty()) {
884 setError("section header name is empty");
885 break;
886 }
Rui Ueyama047404f2016-07-20 19:36:36 +0000887 Phdrs.push_back(Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000888 }
889 return Phdrs;
890}
891
892unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +0000893 StringRef Tok = next();
Rui Ueyamab0f6c592016-07-20 19:36:38 +0000894 unsigned Ret = StringSwitch<unsigned>(Tok)
895 .Case("PT_NULL", PT_NULL)
896 .Case("PT_LOAD", PT_LOAD)
897 .Case("PT_DYNAMIC", PT_DYNAMIC)
898 .Case("PT_INTERP", PT_INTERP)
899 .Case("PT_NOTE", PT_NOTE)
900 .Case("PT_SHLIB", PT_SHLIB)
901 .Case("PT_PHDR", PT_PHDR)
902 .Case("PT_TLS", PT_TLS)
903 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
904 .Case("PT_GNU_STACK", PT_GNU_STACK)
905 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
906 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000907
Rui Ueyamab0f6c592016-07-20 19:36:38 +0000908 if (Ret == (unsigned)-1) {
909 setError("invalid program header type: " + Tok);
910 return PT_NULL;
911 }
912 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000913}
914
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000915static bool isUnderSysroot(StringRef Path) {
916 if (Config->Sysroot == "")
917 return false;
918 for (; !Path.empty(); Path = sys::path::parent_path(Path))
919 if (sys::fs::equivalent(Config->Sysroot, Path))
920 return true;
921 return false;
922}
923
Rui Ueyama07320e42016-04-20 20:13:41 +0000924// Entry point.
925void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000926 StringRef Path = MB.getBufferIdentifier();
Rui Ueyama07320e42016-04-20 20:13:41 +0000927 ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000928}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +0000929
Rui Ueyama07320e42016-04-20 20:13:41 +0000930template class elf::LinkerScript<ELF32LE>;
931template class elf::LinkerScript<ELF32BE>;
932template class elf::LinkerScript<ELF64LE>;
933template class elf::LinkerScript<ELF64BE>;