1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
|
//===- LinkerScript.cpp ---------------------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the parser/evaluator of the linker script.
// It does not construct an AST but consume linker script directives directly.
// Results are written to Driver or Config object.
//
//===----------------------------------------------------------------------===//
#include "LinkerScript.h"
#include "Config.h"
#include "Driver.h"
#include "InputSection.h"
#include "OutputSections.h"
#include "ScriptParser.h"
#include "SymbolTable.h"
#include "llvm/Support/ELF.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/StringSaver.h"
using namespace llvm;
using namespace llvm::ELF;
using namespace llvm::object;
using namespace lld;
using namespace lld::elf;
LinkerScript *elf::Script;
static uint64_t getInteger(StringRef S) {
uint64_t V;
if (S.getAsInteger(0, V)) {
error("malformed number: " + S);
return 0;
}
return V;
}
// Evaluates the expression given by list of tokens.
uint64_t LinkerScript::evaluate(std::vector<StringRef> &Tokens,
uint64_t LocCounter) {
uint64_t Result = 0;
for (size_t I = 0, E = Tokens.size(); I < E; ++I) {
// Each second token should be '+' as this is the
// only operator we support now.
if (I % 2 == 1) {
if (Tokens[I] == "+")
continue;
error("error in location counter expression");
return 0;
}
StringRef Tok = Tokens[I];
if (Tok == ".")
Result += LocCounter;
else
Result += getInteger(Tok);
}
return Result;
}
template <class ELFT>
SectionRule *LinkerScript::find(InputSectionBase<ELFT> *S) {
for (SectionRule &R : Sections)
if (R.match(S))
return &R;
return nullptr;
}
template <class ELFT>
StringRef LinkerScript::getOutputSection(InputSectionBase<ELFT> *S) {
SectionRule *R = find(S);
return R ? R->Dest : "";
}
template <class ELFT>
bool LinkerScript::isDiscarded(InputSectionBase<ELFT> *S) {
return getOutputSection(S) == "/DISCARD/";
}
template <class ELFT> bool LinkerScript::shouldKeep(InputSectionBase<ELFT> *S) {
SectionRule *R = find(S);
return R && R->Keep;
}
template <class ELFT>
static OutputSectionBase<ELFT> *
findSection(std::vector<OutputSectionBase<ELFT> *> &V, StringRef Name) {
for (OutputSectionBase<ELFT> *Sec : V)
if (Sec->getName() == Name)
return Sec;
return nullptr;
}
template <class ELFT>
void LinkerScript::assignAddresses(
std::vector<OutputSectionBase<ELFT> *> &Sections) {
typedef typename ELFT::uint uintX_t;
// Orphan sections are sections present in the input files which
// are not explicitly placed into the output file by the linker script.
// We place orphan sections at end of file.
// Other linkers places them using some heuristics as described in
// https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
for (OutputSectionBase<ELFT> *Sec : Sections) {
StringRef Name = Sec->getName();
auto I = std::find(SectionOrder.begin(), SectionOrder.end(), Name);
if (I == SectionOrder.end())
Locations.push_back({Command::Section, {}, {Name}});
}
// Assign addresses as instructed by linker script SECTIONS sub-commands.
uintX_t ThreadBssOffset = 0;
uintX_t VA =
Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
for (LocationNode &Node : Locations) {
if (Node.Type == Command::Expr) {
VA = evaluate(Node.Expr, VA);
continue;
}
OutputSectionBase<ELFT> *Sec = findSection(Sections, Node.SectionName);
if (!Sec)
continue;
if ((Sec->getFlags() & SHF_TLS) && Sec->getType() == SHT_NOBITS) {
uintX_t TVA = VA + ThreadBssOffset;
TVA = alignTo(TVA, Sec->getAlign());
Sec->setVA(TVA);
ThreadBssOffset = TVA - VA + Sec->getSize();
continue;
}
if (Sec->getFlags() & SHF_ALLOC) {
VA = alignTo(VA, Sec->getAlign());
Sec->setVA(VA);
VA += Sec->getSize();
continue;
}
}
}
ArrayRef<uint8_t> LinkerScript::getFiller(StringRef Name) {
auto I = Filler.find(Name);
if (I == Filler.end())
return {};
return I->second;
}
// A compartor to sort output sections. Returns -1 or 1 if both
// A and B are mentioned in linker scripts. Otherwise, returns 0
// to use the default rule which is implemented in Writer.cpp.
int LinkerScript::compareSections(StringRef A, StringRef B) {
auto E = SectionOrder.end();
auto I = std::find(SectionOrder.begin(), E, A);
auto J = std::find(SectionOrder.begin(), E, B);
if (I == E || J == E)
return 0;
return I < J ? -1 : 1;
}
// Returns true if S matches T. S can contain glob meta-characters.
// The asterisk ('*') matches zero or more characacters, and the question
// mark ('?') matches one character.
static bool matchStr(StringRef S, StringRef T) {
for (;;) {
if (S.empty())
return T.empty();
if (S[0] == '*') {
S = S.substr(1);
if (S.empty())
// Fast path. If a pattern is '*', it matches anything.
return true;
for (size_t I = 0, E = T.size(); I < E; ++I)
if (matchStr(S, T.substr(I)))
return true;
return false;
}
if (T.empty() || (S[0] != T[0] && S[0] != '?'))
return false;
S = S.substr(1);
T = T.substr(1);
}
}
template <class ELFT> bool SectionRule::match(InputSectionBase<ELFT> *S) {
return matchStr(SectionPattern, S->getSectionName());
}
class elf::ScriptParser final : public elf::ScriptParserBase {
typedef void (ScriptParser::*Handler)();
public:
ScriptParser(BumpPtrAllocator *A, StringRef S, bool B)
: ScriptParserBase(S), Saver(*A), IsUnderSysroot(B) {}
void run() override;
private:
void addFile(StringRef Path);
void readAsNeeded();
void readEntry();
void readExtern();
void readGroup();
void readInclude();
void readNothing() {}
void readOutput();
void readOutputArch();
void readOutputFormat();
void readSearchDir();
void readSections();
void readLocationCounterValue();
void readOutputSectionDescription();
void readSectionPatterns(StringRef OutSec, bool Keep);
StringSaver Saver;
const static StringMap<Handler> Cmd;
bool IsUnderSysroot;
};
const StringMap<elf::ScriptParser::Handler> elf::ScriptParser::Cmd = {
{"ENTRY", &ScriptParser::readEntry},
{"EXTERN", &ScriptParser::readExtern},
{"GROUP", &ScriptParser::readGroup},
{"INCLUDE", &ScriptParser::readInclude},
{"INPUT", &ScriptParser::readGroup},
{"OUTPUT", &ScriptParser::readOutput},
{"OUTPUT_ARCH", &ScriptParser::readOutputArch},
{"OUTPUT_FORMAT", &ScriptParser::readOutputFormat},
{"SEARCH_DIR", &ScriptParser::readSearchDir},
{"SECTIONS", &ScriptParser::readSections},
{";", &ScriptParser::readNothing}};
void ScriptParser::run() {
while (!atEOF()) {
StringRef Tok = next();
if (Handler Fn = Cmd.lookup(Tok))
(this->*Fn)();
else
setError("unknown directive: " + Tok);
}
}
void ScriptParser::addFile(StringRef S) {
if (IsUnderSysroot && S.startswith("/")) {
SmallString<128> Path;
(Config->Sysroot + S).toStringRef(Path);
if (sys::fs::exists(Path)) {
Driver->addFile(Saver.save(Path.str()));
return;
}
}
if (sys::path::is_absolute(S)) {
Driver->addFile(S);
} else if (S.startswith("=")) {
if (Config->Sysroot.empty())
Driver->addFile(S.substr(1));
else
Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
} else if (S.startswith("-l")) {
Driver->addLibrary(S.substr(2));
} else if (sys::fs::exists(S)) {
Driver->addFile(S);
} else {
std::string Path = findFromSearchPaths(S);
if (Path.empty())
setError("unable to find " + S);
else
Driver->addFile(Saver.save(Path));
}
}
void ScriptParser::readAsNeeded() {
expect("(");
bool Orig = Config->AsNeeded;
Config->AsNeeded = true;
while (!Error) {
StringRef Tok = next();
if (Tok == ")")
break;
addFile(Tok);
}
Config->AsNeeded = Orig;
}
void ScriptParser::readEntry() {
// -e <symbol> takes predecence over ENTRY(<symbol>).
expect("(");
StringRef Tok = next();
if (Config->Entry.empty())
Config->Entry = Tok;
expect(")");
}
void ScriptParser::readExtern() {
expect("(");
while (!Error) {
StringRef Tok = next();
if (Tok == ")")
return;
Config->Undefined.push_back(Tok);
}
}
void ScriptParser::readGroup() {
expect("(");
while (!Error) {
StringRef Tok = next();
if (Tok == ")")
return;
if (Tok == "AS_NEEDED") {
readAsNeeded();
continue;
}
addFile(Tok);
}
}
void ScriptParser::readInclude() {
StringRef Tok = next();
auto MBOrErr = MemoryBuffer::getFile(Tok);
if (!MBOrErr) {
setError("cannot open " + Tok);
return;
}
std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
std::vector<StringRef> V = tokenize(S);
Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
}
void ScriptParser::readOutput() {
// -o <file> takes predecence over OUTPUT(<file>).
expect("(");
StringRef Tok = next();
if (Config->OutputFile.empty())
Config->OutputFile = Tok;
expect(")");
}
void ScriptParser::readOutputArch() {
// Error checking only for now.
expect("(");
next();
expect(")");
}
void ScriptParser::readOutputFormat() {
// Error checking only for now.
expect("(");
next();
StringRef Tok = next();
if (Tok == ")")
return;
if (Tok != ",") {
setError("unexpected token: " + Tok);
return;
}
next();
expect(",");
next();
expect(")");
}
void ScriptParser::readSearchDir() {
expect("(");
Config->SearchPaths.push_back(next());
expect(")");
}
void ScriptParser::readSections() {
Script->DoLayout = true;
expect("{");
while (!Error && !skip("}")) {
StringRef Tok = peek();
if (Tok == ".")
readLocationCounterValue();
else
readOutputSectionDescription();
}
}
void ScriptParser::readSectionPatterns(StringRef OutSec, bool Keep) {
expect("(");
while (!Error && !skip(")"))
Script->Sections.emplace_back(OutSec, next(), Keep);
}
void ScriptParser::readLocationCounterValue() {
expect(".");
expect("=");
Script->Locations.push_back({Command::Expr, {}, {}});
LocationNode &Node = Script->Locations.back();
while (!Error) {
StringRef Tok = next();
if (Tok == ";")
break;
Node.Expr.push_back(Tok);
}
if (Node.Expr.empty())
error("error in location counter expression");
}
void ScriptParser::readOutputSectionDescription() {
StringRef OutSec = next();
Script->SectionOrder.push_back(OutSec);
Script->Locations.push_back({Command::Section, {}, {OutSec}});
expect(":");
expect("{");
while (!Error && !skip("}")) {
StringRef Tok = next();
if (Tok == "*") {
readSectionPatterns(OutSec, false);
} else if (Tok == "KEEP") {
expect("(");
next(); // Skip *
readSectionPatterns(OutSec, true);
expect(")");
} else {
setError("unknown command " + Tok);
}
}
StringRef Tok = peek();
if (Tok.startswith("=")) {
if (!Tok.startswith("=0x")) {
setError("filler should be a hexadecimal value");
return;
}
Tok = Tok.substr(3);
Script->Filler[OutSec] = parseHex(Tok);
next();
}
}
static bool isUnderSysroot(StringRef Path) {
if (Config->Sysroot == "")
return false;
for (; !Path.empty(); Path = sys::path::parent_path(Path))
if (sys::fs::equivalent(Config->Sysroot, Path))
return true;
return false;
}
// Entry point. The other functions or classes are private to this file.
void LinkerScript::read(MemoryBufferRef MB) {
StringRef Path = MB.getBufferIdentifier();
ScriptParser(&Alloc, MB.getBuffer(), isUnderSysroot(Path)).run();
}
template StringRef LinkerScript::getOutputSection(InputSectionBase<ELF32LE> *);
template StringRef LinkerScript::getOutputSection(InputSectionBase<ELF32BE> *);
template StringRef LinkerScript::getOutputSection(InputSectionBase<ELF64LE> *);
template StringRef LinkerScript::getOutputSection(InputSectionBase<ELF64BE> *);
template bool LinkerScript::isDiscarded(InputSectionBase<ELF32LE> *);
template bool LinkerScript::isDiscarded(InputSectionBase<ELF32BE> *);
template bool LinkerScript::isDiscarded(InputSectionBase<ELF64LE> *);
template bool LinkerScript::isDiscarded(InputSectionBase<ELF64BE> *);
template bool LinkerScript::shouldKeep(InputSectionBase<ELF32LE> *);
template bool LinkerScript::shouldKeep(InputSectionBase<ELF32BE> *);
template bool LinkerScript::shouldKeep(InputSectionBase<ELF64LE> *);
template bool LinkerScript::shouldKeep(InputSectionBase<ELF64BE> *);
template void
LinkerScript::assignAddresses(std::vector<OutputSectionBase<ELF32LE> *> &);
template void
LinkerScript::assignAddresses(std::vector<OutputSectionBase<ELF32BE> *> &);
template void
LinkerScript::assignAddresses(std::vector<OutputSectionBase<ELF64LE> *> &);
template void
LinkerScript::assignAddresses(std::vector<OutputSectionBase<ELF64BE> *> &);
|