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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
|
//===- lib/Driver/GnuLdDriver.cpp -----------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
///
/// Concrete instance of the Driver for GNU's ld.
///
//===----------------------------------------------------------------------===//
#include "lld/Driver/Driver.h"
#include "lld/ReaderWriter/ELFLinkingContext.h"
#include "lld/ReaderWriter/ELFTargets.h"
#include "lld/ReaderWriter/LinkerScript.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Option/Arg.h"
#include "llvm/Option/Option.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Errc.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/raw_ostream.h"
#include <cstring>
#include <tuple>
using namespace lld;
using llvm::BumpPtrAllocator;
namespace {
// Create enum with OPT_xxx values for each option in GnuLdOptions.td
enum {
OPT_INVALID = 0,
#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
HELP, META) \
OPT_##ID,
#include "GnuLdOptions.inc"
#undef OPTION
};
// Create prefix string literals used in GnuLdOptions.td
#define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
#include "GnuLdOptions.inc"
#undef PREFIX
// Create table mapping all options defined in GnuLdOptions.td
static const llvm::opt::OptTable::Info infoTable[] = {
#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
HELPTEXT, METAVAR) \
{ PREFIX, NAME, HELPTEXT, METAVAR, OPT_##ID, llvm::opt::Option::KIND##Class, \
PARAM, FLAGS, OPT_##GROUP, OPT_##ALIAS, ALIASARGS },
#include "GnuLdOptions.inc"
#undef OPTION
};
// Create OptTable class for parsing actual command line arguments
class GnuLdOptTable : public llvm::opt::OptTable {
public:
GnuLdOptTable() : OptTable(infoTable, llvm::array_lengthof(infoTable)){}
};
class DriverStringSaver : public llvm::cl::StringSaver {
public:
DriverStringSaver(BumpPtrAllocator &alloc) : _alloc(alloc) {}
const char *SaveString(const char *s) override {
char *p = _alloc.Allocate<char>(strlen(s) + 1);
strcpy(p, s);
return p;
}
private:
BumpPtrAllocator &_alloc;
};
} // anonymous namespace
// If a command line option starts with "@", the driver reads its suffix as a
// file, parse its contents as a list of command line options, and insert them
// at the original @file position. If file cannot be read, @file is not expanded
// and left unmodified. @file can appear in a response file, so it's a recursive
// process.
static std::tuple<int, const char **>
maybeExpandResponseFiles(int argc, const char **argv, BumpPtrAllocator &alloc) {
// Expand response files.
SmallVector<const char *, 256> smallvec;
for (int i = 0; i < argc; ++i)
smallvec.push_back(argv[i]);
DriverStringSaver saver(alloc);
llvm::cl::ExpandResponseFiles(saver, llvm::cl::TokenizeGNUCommandLine, smallvec);
// Pack the results to a C-array and return it.
argc = smallvec.size();
const char **copy = alloc.Allocate<const char *>(argc + 1);
std::copy(smallvec.begin(), smallvec.end(), copy);
copy[argc] = nullptr;
return std::make_tuple(argc, copy);
}
static std::error_code
getFileMagic(StringRef path, llvm::sys::fs::file_magic &magic) {
std::error_code ec = llvm::sys::fs::identify_magic(path, magic);
if (ec)
return ec;
switch (magic) {
case llvm::sys::fs::file_magic::archive:
case llvm::sys::fs::file_magic::elf_relocatable:
case llvm::sys::fs::file_magic::elf_shared_object:
case llvm::sys::fs::file_magic::unknown:
return std::error_code();
default:
return make_dynamic_error_code(StringRef("unknown type of object file"));
}
}
// Parses an argument of --defsym=<sym>=<number>
static bool parseDefsymAsAbsolute(StringRef opt, StringRef &sym,
uint64_t &addr) {
size_t equalPos = opt.find('=');
if (equalPos == 0 || equalPos == StringRef::npos)
return false;
sym = opt.substr(0, equalPos);
if (opt.substr(equalPos + 1).getAsInteger(0, addr))
return false;
return true;
}
// Parses an argument of --defsym=<sym>=<sym>
static bool parseDefsymAsAlias(StringRef opt, StringRef &sym,
StringRef &target) {
size_t equalPos = opt.find('=');
if (equalPos == 0 || equalPos == StringRef::npos)
return false;
sym = opt.substr(0, equalPos);
target = opt.substr(equalPos + 1);
return !target.empty();
}
// Parses dashz options for max-page-size.
static bool parseZOption(StringRef opt, uint64_t &val) {
size_t equalPos = opt.find('=');
if (equalPos == 0 || equalPos == StringRef::npos)
return false;
StringRef value = opt.substr(equalPos + 1);
val = 0;
if (value.getAsInteger(0, val) || !val)
return false;
return true;
}
bool GnuLdDriver::linkELF(int argc, const char *argv[], raw_ostream &diag) {
BumpPtrAllocator alloc;
std::tie(argc, argv) = maybeExpandResponseFiles(argc, argv, alloc);
std::unique_ptr<ELFLinkingContext> options;
if (!parse(argc, argv, options, diag))
return false;
if (!options)
return true;
return link(*options, diag);
}
static llvm::Optional<llvm::Triple::ArchType>
getArchType(const llvm::Triple &triple, StringRef value) {
switch (triple.getArch()) {
case llvm::Triple::x86:
case llvm::Triple::x86_64:
if (value == "elf_i386")
return llvm::Triple::x86;
if (value == "elf_x86_64")
return llvm::Triple::x86_64;
return llvm::None;
case llvm::Triple::mipsel:
case llvm::Triple::mips64el:
if (value == "elf32ltsmip")
return llvm::Triple::mipsel;
if (value == "elf64ltsmip")
return llvm::Triple::mips64el;
return llvm::None;
case llvm::Triple::aarch64:
if (value == "aarch64linux")
return llvm::Triple::aarch64;
return llvm::None;
case llvm::Triple::arm:
if (value == "armelf_linux_eabi")
return llvm::Triple::arm;
return llvm::None;
default:
return llvm::None;
}
}
static bool isLinkerScript(StringRef path, raw_ostream &diag) {
llvm::sys::fs::file_magic magic = llvm::sys::fs::file_magic::unknown;
std::error_code ec = getFileMagic(path, magic);
if (ec) {
diag << "unknown input file format for file " << path << "\n";
return false;
}
return magic == llvm::sys::fs::file_magic::unknown;
}
static ErrorOr<StringRef>
findFile(ELFLinkingContext &ctx, StringRef path, bool dashL) {
// If the path was referred to by using a -l argument, let's search
// for the file in the search path.
if (dashL) {
ErrorOr<StringRef> pathOrErr = ctx.searchLibrary(path);
if (std::error_code ec = pathOrErr.getError())
return make_dynamic_error_code(
Twine("Unable to find library -l") + path + ": " + ec.message());
path = pathOrErr.get();
}
if (!llvm::sys::fs::exists(path))
return make_dynamic_error_code(
Twine("lld: cannot find file ") + path);
return path;
}
static bool isPathUnderSysroot(StringRef sysroot, StringRef path) {
if (sysroot.empty())
return false;
while (!path.empty() && !llvm::sys::fs::equivalent(sysroot, path))
path = llvm::sys::path::parent_path(path);
return !path.empty();
}
static std::error_code
addFilesFromLinkerScript(ELFLinkingContext &ctx, StringRef scriptPath,
const std::vector<script::Path> &inputPaths,
raw_ostream &diag) {
bool sysroot = (!ctx.getSysroot().empty()
&& isPathUnderSysroot(ctx.getSysroot(), scriptPath));
for (const script::Path &path : inputPaths) {
ErrorOr<StringRef> pathOrErr = path._isDashlPrefix
? ctx.searchLibrary(path._path) : ctx.searchFile(path._path, sysroot);
if (std::error_code ec = pathOrErr.getError()) {
auto file = llvm::make_unique<ErrorFile>(path._path, ec);
ctx.getNodes().push_back(llvm::make_unique<FileNode>(std::move(file)));
continue;
}
std::vector<std::unique_ptr<File>> files
= loadFile(ctx, pathOrErr.get(), false);
for (std::unique_ptr<File> &file : files) {
if (ctx.logInputFiles())
diag << file->path() << "\n";
ctx.getNodes().push_back(llvm::make_unique<FileNode>(std::move(file)));
}
}
return std::error_code();
}
std::error_code GnuLdDriver::evalLinkerScript(ELFLinkingContext &ctx,
std::unique_ptr<MemoryBuffer> mb,
raw_ostream &diag,
bool nostdlib) {
// Read the script file from disk and parse.
StringRef path = mb->getBufferIdentifier();
auto parser = llvm::make_unique<script::Parser>(std::move(mb));
if (std::error_code ec = parser->parse())
return ec;
script::LinkerScript *script = parser->get();
if (!script)
return LinkerScriptReaderError::parse_error;
// Evaluate script commands.
// Currently we only recognize this subset of linker script commands.
for (const script::Command *c : script->_commands) {
if (auto *input = dyn_cast<script::Input>(c))
if (std::error_code ec = addFilesFromLinkerScript(
ctx, path, input->getPaths(), diag))
return ec;
if (auto *group = dyn_cast<script::Group>(c)) {
int origSize = ctx.getNodes().size();
if (std::error_code ec = addFilesFromLinkerScript(
ctx, path, group->getPaths(), diag))
return ec;
size_t groupSize = ctx.getNodes().size() - origSize;
ctx.getNodes().push_back(llvm::make_unique<GroupEnd>(groupSize));
}
if (auto *searchDir = dyn_cast<script::SearchDir>(c))
if (!nostdlib)
ctx.addSearchPath(searchDir->getSearchPath());
if (auto *entry = dyn_cast<script::Entry>(c))
ctx.setEntrySymbolName(entry->getEntryName());
if (auto *output = dyn_cast<script::Output>(c))
ctx.setOutputPath(output->getOutputFileName());
}
// Transfer ownership of the script to the linking context
ctx.addLinkerScript(std::move(parser));
return std::error_code();
}
bool GnuLdDriver::applyEmulation(llvm::Triple &triple,
llvm::opt::InputArgList &args,
raw_ostream &diag) {
llvm::opt::Arg *arg = args.getLastArg(OPT_m);
if (!arg)
return true;
llvm::Optional<llvm::Triple::ArchType> arch =
getArchType(triple, arg->getValue());
if (!arch) {
diag << "error: unsupported emulation '" << arg->getValue() << "'.\n";
return false;
}
triple.setArch(*arch);
return true;
}
void GnuLdDriver::addPlatformSearchDirs(ELFLinkingContext &ctx,
llvm::Triple &triple,
llvm::Triple &baseTriple) {
if (triple.getOS() == llvm::Triple::NetBSD &&
triple.getArch() == llvm::Triple::x86 &&
baseTriple.getArch() == llvm::Triple::x86_64) {
ctx.addSearchPath("=/usr/lib/i386");
return;
}
ctx.addSearchPath("=/usr/lib");
}
std::unique_ptr<ELFLinkingContext>
GnuLdDriver::createELFLinkingContext(llvm::Triple triple) {
std::unique_ptr<ELFLinkingContext> p;
// FIXME: #include "llvm/Config/Targets.def"
#define LLVM_TARGET(targetName) \
if ((p = elf::targetName##LinkingContext::create(triple))) return p;
LLVM_TARGET(AArch64)
LLVM_TARGET(ARM)
LLVM_TARGET(Hexagon)
LLVM_TARGET(Mips)
LLVM_TARGET(X86)
LLVM_TARGET(X86_64)
#undef LLVM_TARGET
return nullptr;
}
bool GnuLdDriver::parse(int argc, const char *argv[],
std::unique_ptr<ELFLinkingContext> &context,
raw_ostream &diag) {
// Parse command line options using GnuLdOptions.td
std::unique_ptr<llvm::opt::InputArgList> parsedArgs;
GnuLdOptTable table;
unsigned missingIndex;
unsigned missingCount;
parsedArgs.reset(
table.ParseArgs(&argv[1], &argv[argc], missingIndex, missingCount));
if (missingCount) {
diag << "error: missing arg value for '"
<< parsedArgs->getArgString(missingIndex) << "' expected "
<< missingCount << " argument(s).\n";
return false;
}
// Handle --help
if (parsedArgs->getLastArg(OPT_help)) {
table.PrintHelp(llvm::outs(), argv[0], "LLVM Linker", false);
return true;
}
// Use -target or use default target triple to instantiate LinkingContext
llvm::Triple baseTriple;
if (llvm::opt::Arg *trip = parsedArgs->getLastArg(OPT_target))
baseTriple = llvm::Triple(trip->getValue());
else
baseTriple = getDefaultTarget(argv[0]);
llvm::Triple triple(baseTriple);
if (!applyEmulation(triple, *parsedArgs, diag))
return false;
std::unique_ptr<ELFLinkingContext> ctx(createELFLinkingContext(triple));
if (!ctx) {
diag << "unknown target triple\n";
return false;
}
std::stack<int> groupStack;
int numfiles = 0;
bool asNeeded = false;
bool wholeArchive = false;
bool hasNoStdLib = false;
// Ignore unknown arguments.
for (auto unknownArg : parsedArgs->filtered(OPT_UNKNOWN))
diag << "warning: ignoring unknown argument: "
<< unknownArg->getValue() << "\n";
// Set sys root path.
if (llvm::opt::Arg *sysRootPath = parsedArgs->getLastArg(OPT_sysroot))
ctx->setSysroot(sysRootPath->getValue());
// Add all search paths.
for (auto libDir : parsedArgs->filtered(OPT_L))
ctx->addSearchPath(libDir->getValue());
// Add the default search directory specific to the target.
if (!(hasNoStdLib = parsedArgs->hasArg(OPT_nostdlib)))
addPlatformSearchDirs(*ctx, triple, baseTriple);
// Handle --demangle option(For compatibility)
if (parsedArgs->getLastArg(OPT_demangle))
ctx->setDemangleSymbols(true);
// Handle --no-demangle option.
if (parsedArgs->getLastArg(OPT_no_demangle))
ctx->setDemangleSymbols(false);
// Figure out output kind ( -r, -static, -shared)
if (llvm::opt::Arg *kind =
parsedArgs->getLastArg(OPT_relocatable, OPT_static, OPT_shared,
OPT_nmagic, OPT_omagic, OPT_no_omagic)) {
switch (kind->getOption().getID()) {
case OPT_relocatable:
ctx->setOutputELFType(llvm::ELF::ET_REL);
ctx->setPrintRemainingUndefines(false);
ctx->setAllowRemainingUndefines(true);
break;
case OPT_static:
ctx->setOutputELFType(llvm::ELF::ET_EXEC);
ctx->setIsStaticExecutable(true);
break;
case OPT_shared:
ctx->setOutputELFType(llvm::ELF::ET_DYN);
ctx->setAllowShlibUndefines(true);
ctx->setUseShlibUndefines(false);
ctx->setPrintRemainingUndefines(false);
ctx->setAllowRemainingUndefines(true);
break;
}
}
// Figure out if the output type is nmagic/omagic
if (llvm::opt::Arg *kind =
parsedArgs->getLastArg(OPT_nmagic, OPT_omagic, OPT_no_omagic)) {
switch (kind->getOption().getID()) {
case OPT_nmagic:
ctx->setOutputMagic(ELFLinkingContext::OutputMagic::NMAGIC);
ctx->setIsStaticExecutable(true);
break;
case OPT_omagic:
ctx->setOutputMagic(ELFLinkingContext::OutputMagic::OMAGIC);
ctx->setIsStaticExecutable(true);
break;
case OPT_no_omagic:
ctx->setOutputMagic(ELFLinkingContext::OutputMagic::DEFAULT);
ctx->setNoAllowDynamicLibraries();
break;
}
}
for (auto inputArg : *parsedArgs) {
switch (inputArg->getOption().getID()) {
case OPT_merge_strings:
ctx->setMergeCommonStrings(true);
break;
case OPT_t:
ctx->setLogInputFiles(true);
break;
case OPT_use_shlib_undefs:
ctx->setUseShlibUndefines(true);
break;
case OPT_no_allow_shlib_undefs:
ctx->setAllowShlibUndefines(false);
break;
case OPT_allow_shlib_undefs:
ctx->setAllowShlibUndefines(true);
break;
}
}
// Register possible input file parsers.
ctx->registry().addSupportELFObjects(
ctx->mergeCommonStrings(),
ctx->targetHandler());
ctx->registry().addSupportArchives(ctx->logInputFiles());
ctx->registry().addSupportYamlFiles();
ctx->registry().addSupportNativeObjects();
if (ctx->allowLinkWithDynamicLibraries())
ctx->registry().addSupportELFDynamicSharedObjects(
ctx->useShlibUndefines(), ctx->targetHandler());
// Process all the arguments and create input files.
for (auto inputArg : *parsedArgs) {
switch (inputArg->getOption().getID()) {
case OPT_mllvm:
ctx->appendLLVMOption(inputArg->getValue());
break;
case OPT_e:
ctx->setEntrySymbolName(inputArg->getValue());
break;
case OPT_output:
ctx->setOutputPath(inputArg->getValue());
break;
case OPT_noinhibit_exec:
ctx->setAllowRemainingUndefines(true);
break;
case OPT_export_dynamic:
ctx->setExportDynamic(true);
break;
case OPT_allow_multiple_definition:
ctx->setAllowDuplicates(true);
break;
case OPT_dynamic_linker:
ctx->setInterpreter(inputArg->getValue());
break;
case OPT_u:
ctx->addInitialUndefinedSymbol(inputArg->getValue());
break;
case OPT_init:
ctx->setInitFunction(inputArg->getValue());
break;
case OPT_fini:
ctx->setFiniFunction(inputArg->getValue());
break;
case OPT_output_filetype:
ctx->setOutputFileType(inputArg->getValue());
break;
case OPT_no_whole_archive:
wholeArchive = false;
break;
case OPT_whole_archive:
wholeArchive = true;
break;
case OPT_as_needed:
asNeeded = true;
break;
case OPT_no_as_needed:
asNeeded = false;
break;
case OPT_defsym: {
StringRef sym, target;
uint64_t addr;
if (parseDefsymAsAbsolute(inputArg->getValue(), sym, addr)) {
ctx->addInitialAbsoluteSymbol(sym, addr);
} else if (parseDefsymAsAlias(inputArg->getValue(), sym, target)) {
ctx->addAlias(sym, target);
} else {
diag << "invalid --defsym: " << inputArg->getValue() << "\n";
return false;
}
break;
}
case OPT_start_group:
groupStack.push(numfiles);
break;
case OPT_end_group: {
if (groupStack.empty()) {
diag << "stray --end-group\n";
return false;
}
int startGroupPos = groupStack.top();
ctx->getNodes().push_back(
llvm::make_unique<GroupEnd>(numfiles - startGroupPos));
groupStack.pop();
break;
}
case OPT_z: {
StringRef extOpt = inputArg->getValue();
if (extOpt == "muldefs")
ctx->setAllowDuplicates(true);
else if (extOpt.startswith("max-page-size")) {
// Parse -z max-page-size option.
// The default page size is considered the minimum page size the user
// can set, check the user input if its atleast the minimum page size
// and does not exceed the maximum page size allowed for the target.
uint64_t maxPageSize = 0;
// Error if the page size user set is less than the maximum page size
// and greather than the default page size and the user page size is a
// modulo of the default page size.
if ((!parseZOption(extOpt, maxPageSize)) ||
(maxPageSize < ctx->getPageSize()) ||
(maxPageSize % ctx->getPageSize())) {
diag << "invalid option: " << extOpt << "\n";
return false;
}
ctx->setMaxPageSize(maxPageSize);
} else
diag << "warning: ignoring unknown argument for -z: " << extOpt << "\n";
break;
}
case OPT_INPUT:
case OPT_l: {
bool dashL = (inputArg->getOption().getID() == OPT_l);
StringRef path = inputArg->getValue();
ErrorOr<StringRef> pathOrErr = findFile(*ctx, path, dashL);
if (std::error_code ec = pathOrErr.getError()) {
auto file = llvm::make_unique<ErrorFile>(path, ec);
auto node = llvm::make_unique<FileNode>(std::move(file));
node->setAsNeeded(asNeeded);
ctx->getNodes().push_back(std::move(node));
break;
}
StringRef realpath = pathOrErr.get();
bool isScript =
(!path.endswith(".objtxt") && isLinkerScript(realpath, diag));
if (isScript) {
if (ctx->logInputFiles())
diag << path << "\n";
ErrorOr<std::unique_ptr<MemoryBuffer>> mb =
MemoryBuffer::getFileOrSTDIN(realpath);
if (std::error_code ec = mb.getError()) {
diag << "Cannot open " << path << ": " << ec.message() << "\n";
return false;
}
std::error_code ec =
evalLinkerScript(*ctx, std::move(mb.get()), diag, hasNoStdLib);
if (ec) {
diag << path << ": Error parsing linker script: "
<< ec.message() << "\n";
return false;
}
break;
}
std::vector<std::unique_ptr<File>> files
= loadFile(*ctx, realpath, wholeArchive);
for (std::unique_ptr<File> &file : files) {
if (ctx->logInputFiles())
diag << file->path() << "\n";
auto node = llvm::make_unique<FileNode>(std::move(file));
node->setAsNeeded(asNeeded);
ctx->getNodes().push_back(std::move(node));
}
numfiles += files.size();
break;
}
case OPT_rpath: {
SmallVector<StringRef, 2> rpaths;
StringRef(inputArg->getValue()).split(rpaths, ":");
for (auto path : rpaths)
ctx->addRpath(path);
break;
}
case OPT_rpath_link: {
SmallVector<StringRef, 2> rpaths;
StringRef(inputArg->getValue()).split(rpaths, ":");
for (auto path : rpaths)
ctx->addRpathLink(path);
break;
}
case OPT_strip_all: {
ctx->setStripSymbols(true);
break;
}
case OPT_soname:
ctx->setSharedObjectName(inputArg->getValue());
break;
case OPT_rosegment:
ctx->setCreateSeparateROSegment();
break;
case OPT_no_align_segments:
ctx->setAlignSegments(false);
break;
case OPT_image_base: {
uint64_t baseAddress = 0;
StringRef inputValue = inputArg->getValue();
if ((inputValue.getAsInteger(0, baseAddress)) || !baseAddress) {
diag << "invalid value for image base " << inputValue << "\n";
return false;
}
ctx->setBaseAddress(baseAddress);
break;
}
default:
break;
} // end switch on option ID
} // end for
if (ctx->getNodes().empty()) {
diag << "No input files\n";
return false;
}
// Set default output file name if the output file was not specified.
if (ctx->outputPath().empty()) {
switch (ctx->outputFileType()) {
case LinkingContext::OutputFileType::YAML:
ctx->setOutputPath("-");
break;
case LinkingContext::OutputFileType::Native:
ctx->setOutputPath("a.native");
break;
default:
ctx->setOutputPath("a.out");
break;
}
}
// Validate the combination of options used.
if (!ctx->validate(diag))
return false;
context.swap(ctx);
return true;
}
/// Get the default target triple based on either the program name
/// (e.g. "x86-ibm-linux-lld") or the primary target llvm was configured for.
llvm::Triple GnuLdDriver::getDefaultTarget(const char *progName) {
SmallVector<StringRef, 4> components;
llvm::SplitString(llvm::sys::path::stem(progName), components, "-");
// If has enough parts to be start with a triple.
if (components.size() >= 4) {
llvm::Triple triple(components[0], components[1], components[2],
components[3]);
// If first component looks like an arch.
if (triple.getArch() != llvm::Triple::UnknownArch)
return triple;
}
// Fallback to use whatever default triple llvm was configured for.
return llvm::Triple(llvm::sys::getDefaultTargetTriple());
}
|