-
Notifications
You must be signed in to change notification settings - Fork 12.5k
/
Copy pathDriver.cpp
2487 lines (2217 loc) · 93.3 KB
/
Driver.cpp
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
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===- Driver.cpp ---------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// The driver drives the entire linking process. It is responsible for
// parsing command line options and doing whatever it is instructed to do.
//
// One notable thing in the LLD's driver when compared to other linkers is
// that the LLD's driver is agnostic on the host operating system.
// Other linkers usually have implicit default values (such as a dynamic
// linker path or library paths) for each host OS.
//
// I don't think implicit default values are useful because they are
// usually explicitly specified by the compiler driver. They can even
// be harmful when you are doing cross-linking. Therefore, in LLD, we
// simply trust the compiler driver to pass all required options and
// don't try to make effort on our side.
//
//===----------------------------------------------------------------------===//
#include "Driver.h"
#include "Config.h"
#include "ICF.h"
#include "InputFiles.h"
#include "InputSection.h"
#include "LinkerScript.h"
#include "MarkLive.h"
#include "OutputSections.h"
#include "ScriptParser.h"
#include "SymbolTable.h"
#include "Symbols.h"
#include "SyntheticSections.h"
#include "Target.h"
#include "Writer.h"
#include "lld/Common/Args.h"
#include "lld/Common/Driver.h"
#include "lld/Common/ErrorHandler.h"
#include "lld/Common/Filesystem.h"
#include "lld/Common/Memory.h"
#include "lld/Common/Strings.h"
#include "lld/Common/TargetOptionsCommandFlags.h"
#include "lld/Common/Version.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Config/llvm-config.h"
#include "llvm/LTO/LTO.h"
#include "llvm/Remarks/HotnessThresholdParser.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Compression.h"
#include "llvm/Support/GlobPattern.h"
#include "llvm/Support/LEB128.h"
#include "llvm/Support/Parallel.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/TarWriter.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/TimeProfiler.h"
#include "llvm/Support/raw_ostream.h"
#include <cstdlib>
#include <utility>
using namespace llvm;
using namespace llvm::ELF;
using namespace llvm::object;
using namespace llvm::sys;
using namespace llvm::support;
using namespace lld;
using namespace lld::elf;
Configuration *elf::config;
LinkerDriver *elf::driver;
static void setConfigs(opt::InputArgList &args);
static void readConfigs(opt::InputArgList &args);
bool elf::link(ArrayRef<const char *> args, bool canExitEarly,
raw_ostream &stdoutOS, raw_ostream &stderrOS) {
lld::stdoutOS = &stdoutOS;
lld::stderrOS = &stderrOS;
errorHandler().cleanupCallback = []() {
freeArena();
inputSections.clear();
outputSections.clear();
archiveFiles.clear();
binaryFiles.clear();
bitcodeFiles.clear();
lazyObjFiles.clear();
objectFiles.clear();
sharedFiles.clear();
backwardReferences.clear();
whyExtract.clear();
tar = nullptr;
memset(&in, 0, sizeof(in));
partitions = {Partition()};
SharedFile::vernauxNum = 0;
};
errorHandler().logName = args::getFilenameWithoutExe(args[0]);
errorHandler().errorLimitExceededMsg =
"too many errors emitted, stopping now (use "
"-error-limit=0 to see all errors)";
errorHandler().exitEarly = canExitEarly;
stderrOS.enable_colors(stderrOS.has_colors());
config = make<Configuration>();
driver = make<LinkerDriver>();
script = make<LinkerScript>();
symtab = make<SymbolTable>();
partitions = {Partition()};
config->progName = args[0];
driver->linkerMain(args);
// Exit immediately if we don't need to return to the caller.
// This saves time because the overhead of calling destructors
// for all globally-allocated objects is not negligible.
if (canExitEarly)
exitLld(errorCount() ? 1 : 0);
bool ret = errorCount() == 0;
if (!canExitEarly)
errorHandler().reset();
return ret;
}
// Parses a linker -m option.
static std::tuple<ELFKind, uint16_t, uint8_t> parseEmulation(StringRef emul) {
uint8_t osabi = 0;
StringRef s = emul;
if (s.endswith("_fbsd")) {
s = s.drop_back(5);
osabi = ELFOSABI_FREEBSD;
}
std::pair<ELFKind, uint16_t> ret =
StringSwitch<std::pair<ELFKind, uint16_t>>(s)
.Cases("aarch64elf", "aarch64linux", {ELF64LEKind, EM_AARCH64})
.Cases("aarch64elfb", "aarch64linuxb", {ELF64BEKind, EM_AARCH64})
.Cases("armelf", "armelf_linux_eabi", {ELF32LEKind, EM_ARM})
.Case("elf32_x86_64", {ELF32LEKind, EM_X86_64})
.Cases("elf32btsmip", "elf32btsmipn32", {ELF32BEKind, EM_MIPS})
.Cases("elf32ltsmip", "elf32ltsmipn32", {ELF32LEKind, EM_MIPS})
.Case("elf32lriscv", {ELF32LEKind, EM_RISCV})
.Cases("elf32ppc", "elf32ppclinux", {ELF32BEKind, EM_PPC})
.Cases("elf32lppc", "elf32lppclinux", {ELF32LEKind, EM_PPC})
.Case("elf64btsmip", {ELF64BEKind, EM_MIPS})
.Case("elf64ltsmip", {ELF64LEKind, EM_MIPS})
.Case("elf64lriscv", {ELF64LEKind, EM_RISCV})
.Case("elf64ppc", {ELF64BEKind, EM_PPC64})
.Case("elf64lppc", {ELF64LEKind, EM_PPC64})
.Cases("elf_amd64", "elf_x86_64", {ELF64LEKind, EM_X86_64})
.Case("elf_i386", {ELF32LEKind, EM_386})
.Case("elf_iamcu", {ELF32LEKind, EM_IAMCU})
.Case("elf64_sparc", {ELF64BEKind, EM_SPARCV9})
.Case("msp430elf", {ELF32LEKind, EM_MSP430})
.Default({ELFNoneKind, EM_NONE});
if (ret.first == ELFNoneKind)
error("unknown emulation: " + emul);
if (ret.second == EM_MSP430)
osabi = ELFOSABI_STANDALONE;
return std::make_tuple(ret.first, ret.second, osabi);
}
// Returns slices of MB by parsing MB as an archive file.
// Each slice consists of a member file in the archive.
std::vector<std::pair<MemoryBufferRef, uint64_t>> static getArchiveMembers(
MemoryBufferRef mb) {
std::unique_ptr<Archive> file =
CHECK(Archive::create(mb),
mb.getBufferIdentifier() + ": failed to parse archive");
std::vector<std::pair<MemoryBufferRef, uint64_t>> v;
Error err = Error::success();
bool addToTar = file->isThin() && tar;
for (const Archive::Child &c : file->children(err)) {
MemoryBufferRef mbref =
CHECK(c.getMemoryBufferRef(),
mb.getBufferIdentifier() +
": could not get the buffer for a child of the archive");
if (addToTar)
tar->append(relativeToRoot(check(c.getFullName())), mbref.getBuffer());
v.push_back(std::make_pair(mbref, c.getChildOffset()));
}
if (err)
fatal(mb.getBufferIdentifier() + ": Archive::children failed: " +
toString(std::move(err)));
// Take ownership of memory buffers created for members of thin archives.
for (std::unique_ptr<MemoryBuffer> &mb : file->takeThinBuffers())
make<std::unique_ptr<MemoryBuffer>>(std::move(mb));
return v;
}
// Opens a file and create a file object. Path has to be resolved already.
void LinkerDriver::addFile(StringRef path, bool withLOption) {
using namespace sys::fs;
Optional<MemoryBufferRef> buffer = readFile(path);
if (!buffer.hasValue())
return;
MemoryBufferRef mbref = *buffer;
if (config->formatBinary) {
files.push_back(make<BinaryFile>(mbref));
return;
}
switch (identify_magic(mbref.getBuffer())) {
case file_magic::unknown:
readLinkerScript(mbref);
return;
case file_magic::archive: {
if (inWholeArchive) {
for (const auto &p : getArchiveMembers(mbref))
files.push_back(createObjectFile(p.first, path, p.second));
return;
}
std::unique_ptr<Archive> file =
CHECK(Archive::create(mbref), path + ": failed to parse archive");
// If an archive file has no symbol table, it is likely that a user
// is attempting LTO and using a default ar command that doesn't
// understand the LLVM bitcode file. It is a pretty common error, so
// we'll handle it as if it had a symbol table.
if (!file->isEmpty() && !file->hasSymbolTable()) {
// Check if all members are bitcode files. If not, ignore, which is the
// default action without the LTO hack described above.
for (const std::pair<MemoryBufferRef, uint64_t> &p :
getArchiveMembers(mbref))
if (identify_magic(p.first.getBuffer()) != file_magic::bitcode) {
error(path + ": archive has no index; run ranlib to add one");
return;
}
for (const std::pair<MemoryBufferRef, uint64_t> &p :
getArchiveMembers(mbref))
files.push_back(make<LazyObjFile>(p.first, path, p.second));
return;
}
// Handle the regular case.
files.push_back(make<ArchiveFile>(std::move(file)));
return;
}
case file_magic::elf_shared_object:
if (config->isStatic || config->relocatable) {
error("attempted static link of dynamic object " + path);
return;
}
// Shared objects are identified by soname. soname is (if specified)
// DT_SONAME and falls back to filename. If a file was specified by -lfoo,
// the directory part is ignored. Note that path may be a temporary and
// cannot be stored into SharedFile::soName.
path = mbref.getBufferIdentifier();
files.push_back(
make<SharedFile>(mbref, withLOption ? path::filename(path) : path));
return;
case file_magic::bitcode:
case file_magic::elf_relocatable:
if (inLib)
files.push_back(make<LazyObjFile>(mbref, "", 0));
else
files.push_back(createObjectFile(mbref));
break;
default:
error(path + ": unknown file type");
}
}
// Add a given library by searching it from input search paths.
void LinkerDriver::addLibrary(StringRef name) {
if (Optional<std::string> path = searchLibrary(name))
addFile(*path, /*withLOption=*/true);
else
error("unable to find library -l" + name, ErrorTag::LibNotFound, {name});
}
// This function is called on startup. We need this for LTO since
// LTO calls LLVM functions to compile bitcode files to native code.
// Technically this can be delayed until we read bitcode files, but
// we don't bother to do lazily because the initialization is fast.
static void initLLVM() {
InitializeAllTargets();
InitializeAllTargetMCs();
InitializeAllAsmPrinters();
InitializeAllAsmParsers();
}
// Some command line options or some combinations of them are not allowed.
// This function checks for such errors.
static void checkOptions() {
// The MIPS ABI as of 2016 does not support the GNU-style symbol lookup
// table which is a relatively new feature.
if (config->emachine == EM_MIPS && config->gnuHash)
error("the .gnu.hash section is not compatible with the MIPS target");
if (config->fixCortexA53Errata843419 && config->emachine != EM_AARCH64)
error("--fix-cortex-a53-843419 is only supported on AArch64 targets");
if (config->fixCortexA8 && config->emachine != EM_ARM)
error("--fix-cortex-a8 is only supported on ARM targets");
if (config->tocOptimize && config->emachine != EM_PPC64)
error("--toc-optimize is only supported on PowerPC64 targets");
if (config->pcRelOptimize && config->emachine != EM_PPC64)
error("--pcrel-optimize is only supported on PowerPC64 targets");
if (config->pie && config->shared)
error("-shared and -pie may not be used together");
if (!config->shared && !config->filterList.empty())
error("-F may not be used without -shared");
if (!config->shared && !config->auxiliaryList.empty())
error("-f may not be used without -shared");
if (!config->relocatable && !config->defineCommon)
error("-no-define-common not supported in non relocatable output");
if (config->strip == StripPolicy::All && config->emitRelocs)
error("--strip-all and --emit-relocs may not be used together");
if (config->zText && config->zIfuncNoplt)
error("-z text and -z ifunc-noplt may not be used together");
if (config->relocatable) {
if (config->shared)
error("-r and -shared may not be used together");
if (config->gdbIndex)
error("-r and --gdb-index may not be used together");
if (config->icf != ICFLevel::None)
error("-r and --icf may not be used together");
if (config->pie)
error("-r and -pie may not be used together");
if (config->exportDynamic)
error("-r and --export-dynamic may not be used together");
}
if (config->executeOnly) {
if (config->emachine != EM_AARCH64)
error("--execute-only is only supported on AArch64 targets");
if (config->singleRoRx && !script->hasSectionsCommand)
error("--execute-only and --no-rosegment cannot be used together");
}
if (config->zRetpolineplt && config->zForceIbt)
error("-z force-ibt may not be used with -z retpolineplt");
if (config->emachine != EM_AARCH64) {
if (config->zPacPlt)
error("-z pac-plt only supported on AArch64");
if (config->zForceBti)
error("-z force-bti only supported on AArch64");
}
}
static const char *getReproduceOption(opt::InputArgList &args) {
if (auto *arg = args.getLastArg(OPT_reproduce))
return arg->getValue();
return getenv("LLD_REPRODUCE");
}
static bool hasZOption(opt::InputArgList &args, StringRef key) {
for (auto *arg : args.filtered(OPT_z))
if (key == arg->getValue())
return true;
return false;
}
static bool getZFlag(opt::InputArgList &args, StringRef k1, StringRef k2,
bool Default) {
for (auto *arg : args.filtered_reverse(OPT_z)) {
if (k1 == arg->getValue())
return true;
if (k2 == arg->getValue())
return false;
}
return Default;
}
static SeparateSegmentKind getZSeparate(opt::InputArgList &args) {
for (auto *arg : args.filtered_reverse(OPT_z)) {
StringRef v = arg->getValue();
if (v == "noseparate-code")
return SeparateSegmentKind::None;
if (v == "separate-code")
return SeparateSegmentKind::Code;
if (v == "separate-loadable-segments")
return SeparateSegmentKind::Loadable;
}
return SeparateSegmentKind::None;
}
static GnuStackKind getZGnuStack(opt::InputArgList &args) {
for (auto *arg : args.filtered_reverse(OPT_z)) {
if (StringRef("execstack") == arg->getValue())
return GnuStackKind::Exec;
if (StringRef("noexecstack") == arg->getValue())
return GnuStackKind::NoExec;
if (StringRef("nognustack") == arg->getValue())
return GnuStackKind::None;
}
return GnuStackKind::NoExec;
}
static uint8_t getZStartStopVisibility(opt::InputArgList &args) {
for (auto *arg : args.filtered_reverse(OPT_z)) {
std::pair<StringRef, StringRef> kv = StringRef(arg->getValue()).split('=');
if (kv.first == "start-stop-visibility") {
if (kv.second == "default")
return STV_DEFAULT;
else if (kv.second == "internal")
return STV_INTERNAL;
else if (kv.second == "hidden")
return STV_HIDDEN;
else if (kv.second == "protected")
return STV_PROTECTED;
error("unknown -z start-stop-visibility= value: " + StringRef(kv.second));
}
}
return STV_PROTECTED;
}
static bool isKnownZFlag(StringRef s) {
return s == "combreloc" || s == "copyreloc" || s == "defs" ||
s == "execstack" || s == "force-bti" || s == "force-ibt" ||
s == "global" || s == "hazardplt" || s == "ifunc-noplt" ||
s == "initfirst" || s == "interpose" ||
s == "keep-text-section-prefix" || s == "lazy" || s == "muldefs" ||
s == "separate-code" || s == "separate-loadable-segments" ||
s == "start-stop-gc" || s == "nocombreloc" || s == "nocopyreloc" ||
s == "nodefaultlib" || s == "nodelete" || s == "nodlopen" ||
s == "noexecstack" || s == "nognustack" ||
s == "nokeep-text-section-prefix" || s == "norelro" ||
s == "noseparate-code" || s == "nostart-stop-gc" || s == "notext" ||
s == "now" || s == "origin" || s == "pac-plt" || s == "rel" ||
s == "rela" || s == "relro" || s == "retpolineplt" ||
s == "rodynamic" || s == "shstk" || s == "text" || s == "undefs" ||
s == "wxneeded" || s.startswith("common-page-size=") ||
s.startswith("dead-reloc-in-nonalloc=") ||
s.startswith("max-page-size=") || s.startswith("stack-size=") ||
s.startswith("start-stop-visibility=");
}
// Report a warning for an unknown -z option.
static void checkZOptions(opt::InputArgList &args) {
for (auto *arg : args.filtered(OPT_z))
if (!isKnownZFlag(arg->getValue()))
warn("unknown -z value: " + StringRef(arg->getValue()));
}
void LinkerDriver::linkerMain(ArrayRef<const char *> argsArr) {
ELFOptTable parser;
opt::InputArgList args = parser.parse(argsArr.slice(1));
// Interpret the flags early because error()/warn() depend on them.
errorHandler().errorLimit = args::getInteger(args, OPT_error_limit, 20);
errorHandler().fatalWarnings =
args.hasFlag(OPT_fatal_warnings, OPT_no_fatal_warnings, false);
checkZOptions(args);
// Handle -help
if (args.hasArg(OPT_help)) {
printHelp();
return;
}
// Handle -v or -version.
//
// A note about "compatible with GNU linkers" message: this is a hack for
// scripts generated by GNU Libtool up to 2021-10 to recognize LLD as
// a GNU compatible linker. See
// <https://lists.gnu.org/archive/html/libtool/2017-01/msg00007.html>.
//
// This is somewhat ugly hack, but in reality, we had no choice other
// than doing this. Considering the very long release cycle of Libtool,
// it is not easy to improve it to recognize LLD as a GNU compatible
// linker in a timely manner. Even if we can make it, there are still a
// lot of "configure" scripts out there that are generated by old version
// of Libtool. We cannot convince every software developer to migrate to
// the latest version and re-generate scripts. So we have this hack.
if (args.hasArg(OPT_v) || args.hasArg(OPT_version))
message(getLLDVersion() + " (compatible with GNU linkers)");
if (const char *path = getReproduceOption(args)) {
// Note that --reproduce is a debug option so you can ignore it
// if you are trying to understand the whole picture of the code.
Expected<std::unique_ptr<TarWriter>> errOrWriter =
TarWriter::create(path, path::stem(path));
if (errOrWriter) {
tar = std::move(*errOrWriter);
tar->append("response.txt", createResponseFile(args));
tar->append("version.txt", getLLDVersion() + "\n");
StringRef ltoSampleProfile = args.getLastArgValue(OPT_lto_sample_profile);
if (!ltoSampleProfile.empty())
readFile(ltoSampleProfile);
} else {
error("--reproduce: " + toString(errOrWriter.takeError()));
}
}
readConfigs(args);
// The behavior of -v or --version is a bit strange, but this is
// needed for compatibility with GNU linkers.
if (args.hasArg(OPT_v) && !args.hasArg(OPT_INPUT))
return;
if (args.hasArg(OPT_version))
return;
// Initialize time trace profiler.
if (config->timeTraceEnabled)
timeTraceProfilerInitialize(config->timeTraceGranularity, config->progName);
{
llvm::TimeTraceScope timeScope("ExecuteLinker");
initLLVM();
createFiles(args);
if (errorCount())
return;
inferMachineType();
setConfigs(args);
checkOptions();
if (errorCount())
return;
// The Target instance handles target-specific stuff, such as applying
// relocations or writing a PLT section. It also contains target-dependent
// values such as a default image base address.
target = getTarget();
switch (config->ekind) {
case ELF32LEKind:
link<ELF32LE>(args);
break;
case ELF32BEKind:
link<ELF32BE>(args);
break;
case ELF64LEKind:
link<ELF64LE>(args);
break;
case ELF64BEKind:
link<ELF64BE>(args);
break;
default:
llvm_unreachable("unknown Config->EKind");
}
}
if (config->timeTraceEnabled) {
checkError(timeTraceProfilerWrite(
args.getLastArgValue(OPT_time_trace_file_eq).str(),
config->outputFile));
timeTraceProfilerCleanup();
}
}
static std::string getRpath(opt::InputArgList &args) {
std::vector<StringRef> v = args::getStrings(args, OPT_rpath);
return llvm::join(v.begin(), v.end(), ":");
}
// Determines what we should do if there are remaining unresolved
// symbols after the name resolution.
static void setUnresolvedSymbolPolicy(opt::InputArgList &args) {
UnresolvedPolicy errorOrWarn = args.hasFlag(OPT_error_unresolved_symbols,
OPT_warn_unresolved_symbols, true)
? UnresolvedPolicy::ReportError
: UnresolvedPolicy::Warn;
// -shared implies --unresolved-symbols=ignore-all because missing
// symbols are likely to be resolved at runtime.
bool diagRegular = !config->shared, diagShlib = !config->shared;
for (const opt::Arg *arg : args) {
switch (arg->getOption().getID()) {
case OPT_unresolved_symbols: {
StringRef s = arg->getValue();
if (s == "ignore-all") {
diagRegular = false;
diagShlib = false;
} else if (s == "ignore-in-object-files") {
diagRegular = false;
diagShlib = true;
} else if (s == "ignore-in-shared-libs") {
diagRegular = true;
diagShlib = false;
} else if (s == "report-all") {
diagRegular = true;
diagShlib = true;
} else {
error("unknown --unresolved-symbols value: " + s);
}
break;
}
case OPT_no_undefined:
diagRegular = true;
break;
case OPT_z:
if (StringRef(arg->getValue()) == "defs")
diagRegular = true;
else if (StringRef(arg->getValue()) == "undefs")
diagRegular = false;
break;
case OPT_allow_shlib_undefined:
diagShlib = false;
break;
case OPT_no_allow_shlib_undefined:
diagShlib = true;
break;
}
}
config->unresolvedSymbols =
diagRegular ? errorOrWarn : UnresolvedPolicy::Ignore;
config->unresolvedSymbolsInShlib =
diagShlib ? errorOrWarn : UnresolvedPolicy::Ignore;
}
static Target2Policy getTarget2(opt::InputArgList &args) {
StringRef s = args.getLastArgValue(OPT_target2, "got-rel");
if (s == "rel")
return Target2Policy::Rel;
if (s == "abs")
return Target2Policy::Abs;
if (s == "got-rel")
return Target2Policy::GotRel;
error("unknown --target2 option: " + s);
return Target2Policy::GotRel;
}
static bool isOutputFormatBinary(opt::InputArgList &args) {
StringRef s = args.getLastArgValue(OPT_oformat, "elf");
if (s == "binary")
return true;
if (!s.startswith("elf"))
error("unknown --oformat value: " + s);
return false;
}
static DiscardPolicy getDiscard(opt::InputArgList &args) {
auto *arg =
args.getLastArg(OPT_discard_all, OPT_discard_locals, OPT_discard_none);
if (!arg)
return DiscardPolicy::Default;
if (arg->getOption().getID() == OPT_discard_all)
return DiscardPolicy::All;
if (arg->getOption().getID() == OPT_discard_locals)
return DiscardPolicy::Locals;
return DiscardPolicy::None;
}
static StringRef getDynamicLinker(opt::InputArgList &args) {
auto *arg = args.getLastArg(OPT_dynamic_linker, OPT_no_dynamic_linker);
if (!arg)
return "";
if (arg->getOption().getID() == OPT_no_dynamic_linker) {
// --no-dynamic-linker suppresses undefined weak symbols in .dynsym
config->noDynamicLinker = true;
return "";
}
return arg->getValue();
}
static ICFLevel getICF(opt::InputArgList &args) {
auto *arg = args.getLastArg(OPT_icf_none, OPT_icf_safe, OPT_icf_all);
if (!arg || arg->getOption().getID() == OPT_icf_none)
return ICFLevel::None;
if (arg->getOption().getID() == OPT_icf_safe)
return ICFLevel::Safe;
return ICFLevel::All;
}
static StripPolicy getStrip(opt::InputArgList &args) {
if (args.hasArg(OPT_relocatable))
return StripPolicy::None;
auto *arg = args.getLastArg(OPT_strip_all, OPT_strip_debug);
if (!arg)
return StripPolicy::None;
if (arg->getOption().getID() == OPT_strip_all)
return StripPolicy::All;
return StripPolicy::Debug;
}
static uint64_t parseSectionAddress(StringRef s, opt::InputArgList &args,
const opt::Arg &arg) {
uint64_t va = 0;
if (s.startswith("0x"))
s = s.drop_front(2);
if (!to_integer(s, va, 16))
error("invalid argument: " + arg.getAsString(args));
return va;
}
static StringMap<uint64_t> getSectionStartMap(opt::InputArgList &args) {
StringMap<uint64_t> ret;
for (auto *arg : args.filtered(OPT_section_start)) {
StringRef name;
StringRef addr;
std::tie(name, addr) = StringRef(arg->getValue()).split('=');
ret[name] = parseSectionAddress(addr, args, *arg);
}
if (auto *arg = args.getLastArg(OPT_Ttext))
ret[".text"] = parseSectionAddress(arg->getValue(), args, *arg);
if (auto *arg = args.getLastArg(OPT_Tdata))
ret[".data"] = parseSectionAddress(arg->getValue(), args, *arg);
if (auto *arg = args.getLastArg(OPT_Tbss))
ret[".bss"] = parseSectionAddress(arg->getValue(), args, *arg);
return ret;
}
static SortSectionPolicy getSortSection(opt::InputArgList &args) {
StringRef s = args.getLastArgValue(OPT_sort_section);
if (s == "alignment")
return SortSectionPolicy::Alignment;
if (s == "name")
return SortSectionPolicy::Name;
if (!s.empty())
error("unknown --sort-section rule: " + s);
return SortSectionPolicy::Default;
}
static OrphanHandlingPolicy getOrphanHandling(opt::InputArgList &args) {
StringRef s = args.getLastArgValue(OPT_orphan_handling, "place");
if (s == "warn")
return OrphanHandlingPolicy::Warn;
if (s == "error")
return OrphanHandlingPolicy::Error;
if (s != "place")
error("unknown --orphan-handling mode: " + s);
return OrphanHandlingPolicy::Place;
}
// Parse --build-id or --build-id=<style>. We handle "tree" as a
// synonym for "sha1" because all our hash functions including
// --build-id=sha1 are actually tree hashes for performance reasons.
static std::pair<BuildIdKind, std::vector<uint8_t>>
getBuildId(opt::InputArgList &args) {
auto *arg = args.getLastArg(OPT_build_id, OPT_build_id_eq);
if (!arg)
return {BuildIdKind::None, {}};
if (arg->getOption().getID() == OPT_build_id)
return {BuildIdKind::Fast, {}};
StringRef s = arg->getValue();
if (s == "fast")
return {BuildIdKind::Fast, {}};
if (s == "md5")
return {BuildIdKind::Md5, {}};
if (s == "sha1" || s == "tree")
return {BuildIdKind::Sha1, {}};
if (s == "uuid")
return {BuildIdKind::Uuid, {}};
if (s.startswith("0x"))
return {BuildIdKind::Hexstring, parseHex(s.substr(2))};
if (s != "none")
error("unknown --build-id style: " + s);
return {BuildIdKind::None, {}};
}
static std::pair<bool, bool> getPackDynRelocs(opt::InputArgList &args) {
StringRef s = args.getLastArgValue(OPT_pack_dyn_relocs, "none");
if (s == "android")
return {true, false};
if (s == "relr")
return {false, true};
if (s == "android+relr")
return {true, true};
if (s != "none")
error("unknown --pack-dyn-relocs format: " + s);
return {false, false};
}
static void readCallGraph(MemoryBufferRef mb) {
// Build a map from symbol name to section
DenseMap<StringRef, Symbol *> map;
for (InputFile *file : objectFiles)
for (Symbol *sym : file->getSymbols())
map[sym->getName()] = sym;
auto findSection = [&](StringRef name) -> InputSectionBase * {
Symbol *sym = map.lookup(name);
if (!sym) {
if (config->warnSymbolOrdering)
warn(mb.getBufferIdentifier() + ": no such symbol: " + name);
return nullptr;
}
maybeWarnUnorderableSymbol(sym);
if (Defined *dr = dyn_cast_or_null<Defined>(sym))
return dyn_cast_or_null<InputSectionBase>(dr->section);
return nullptr;
};
for (StringRef line : args::getLines(mb)) {
SmallVector<StringRef, 3> fields;
line.split(fields, ' ');
uint64_t count;
if (fields.size() != 3 || !to_integer(fields[2], count)) {
error(mb.getBufferIdentifier() + ": parse error");
return;
}
if (InputSectionBase *from = findSection(fields[0]))
if (InputSectionBase *to = findSection(fields[1]))
config->callGraphProfile[std::make_pair(from, to)] += count;
}
}
// If SHT_LLVM_CALL_GRAPH_PROFILE and its relocation section exist, returns
// true and populates cgProfile and symbolIndices.
template <class ELFT>
static bool
processCallGraphRelocations(SmallVector<uint32_t, 32> &symbolIndices,
ArrayRef<typename ELFT::CGProfile> &cgProfile,
ObjFile<ELFT> *inputObj) {
symbolIndices.clear();
const ELFFile<ELFT> &obj = inputObj->getObj();
ArrayRef<Elf_Shdr_Impl<ELFT>> objSections =
CHECK(obj.sections(), "could not retrieve object sections");
if (inputObj->cgProfileSectionIndex == SHN_UNDEF)
return false;
cgProfile =
check(obj.template getSectionContentsAsArray<typename ELFT::CGProfile>(
objSections[inputObj->cgProfileSectionIndex]));
for (size_t i = 0, e = objSections.size(); i < e; ++i) {
const Elf_Shdr_Impl<ELFT> &sec = objSections[i];
if (sec.sh_info == inputObj->cgProfileSectionIndex) {
if (sec.sh_type == SHT_RELA) {
ArrayRef<typename ELFT::Rela> relas =
CHECK(obj.relas(sec), "could not retrieve cg profile rela section");
for (const typename ELFT::Rela &rel : relas)
symbolIndices.push_back(rel.getSymbol(config->isMips64EL));
break;
}
if (sec.sh_type == SHT_REL) {
ArrayRef<typename ELFT::Rel> rels =
CHECK(obj.rels(sec), "could not retrieve cg profile rel section");
for (const typename ELFT::Rel &rel : rels)
symbolIndices.push_back(rel.getSymbol(config->isMips64EL));
break;
}
}
}
if (symbolIndices.empty())
warn("SHT_LLVM_CALL_GRAPH_PROFILE exists, but relocation section doesn't");
return !symbolIndices.empty();
}
template <class ELFT> static void readCallGraphsFromObjectFiles() {
SmallVector<uint32_t, 32> symbolIndices;
ArrayRef<typename ELFT::CGProfile> cgProfile;
for (auto file : objectFiles) {
auto *obj = cast<ObjFile<ELFT>>(file);
if (!processCallGraphRelocations(symbolIndices, cgProfile, obj))
continue;
if (symbolIndices.size() != cgProfile.size() * 2)
fatal("number of relocations doesn't match Weights");
for (uint32_t i = 0, size = cgProfile.size(); i < size; ++i) {
const Elf_CGProfile_Impl<ELFT> &cgpe = cgProfile[i];
uint32_t fromIndex = symbolIndices[i * 2];
uint32_t toIndex = symbolIndices[i * 2 + 1];
auto *fromSym = dyn_cast<Defined>(&obj->getSymbol(fromIndex));
auto *toSym = dyn_cast<Defined>(&obj->getSymbol(toIndex));
if (!fromSym || !toSym)
continue;
auto *from = dyn_cast_or_null<InputSectionBase>(fromSym->section);
auto *to = dyn_cast_or_null<InputSectionBase>(toSym->section);
if (from && to)
config->callGraphProfile[{from, to}] += cgpe.cgp_weight;
}
}
}
static bool getCompressDebugSections(opt::InputArgList &args) {
StringRef s = args.getLastArgValue(OPT_compress_debug_sections, "none");
if (s == "none")
return false;
if (s != "zlib")
error("unknown --compress-debug-sections value: " + s);
if (!zlib::isAvailable())
error("--compress-debug-sections: zlib is not available");
return true;
}
static StringRef getAliasSpelling(opt::Arg *arg) {
if (const opt::Arg *alias = arg->getAlias())
return alias->getSpelling();
return arg->getSpelling();
}
static std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &args,
unsigned id) {
auto *arg = args.getLastArg(id);
if (!arg)
return {"", ""};
StringRef s = arg->getValue();
std::pair<StringRef, StringRef> ret = s.split(';');
if (ret.second.empty())
error(getAliasSpelling(arg) + " expects 'old;new' format, but got " + s);
return ret;
}
// Parse the symbol ordering file and warn for any duplicate entries.
static std::vector<StringRef> getSymbolOrderingFile(MemoryBufferRef mb) {
SetVector<StringRef> names;
for (StringRef s : args::getLines(mb))
if (!names.insert(s) && config->warnSymbolOrdering)
warn(mb.getBufferIdentifier() + ": duplicate ordered symbol: " + s);
return names.takeVector();
}
static bool getIsRela(opt::InputArgList &args) {
// If -z rel or -z rela is specified, use the last option.
for (auto *arg : args.filtered_reverse(OPT_z)) {
StringRef s(arg->getValue());
if (s == "rel")
return false;
if (s == "rela")
return true;
}
// Otherwise use the psABI defined relocation entry format.
uint16_t m = config->emachine;
return m == EM_AARCH64 || m == EM_AMDGPU || m == EM_HEXAGON || m == EM_PPC ||
m == EM_PPC64 || m == EM_RISCV || m == EM_X86_64;
}
static void parseClangOption(StringRef opt, const Twine &msg) {
std::string err;
raw_string_ostream os(err);
const char *argv[] = {config->progName.data(), opt.data()};
if (cl::ParseCommandLineOptions(2, argv, "", &os))
return;
os.flush();
error(msg + ": " + StringRef(err).trim());
}
// Initializes Config members by the command line options.
static void readConfigs(opt::InputArgList &args) {
errorHandler().verbose = args.hasArg(OPT_verbose);
errorHandler().vsDiagnostics =
args.hasArg(OPT_visual_studio_diagnostics_format, false);
config->allowMultipleDefinition =
args.hasFlag(OPT_allow_multiple_definition,
OPT_no_allow_multiple_definition, false) ||
hasZOption(args, "muldefs");
config->auxiliaryList = args::getStrings(args, OPT_auxiliary);
if (opt::Arg *arg =
args.getLastArg(OPT_Bno_symbolic, OPT_Bsymbolic_non_weak_functions,
OPT_Bsymbolic_functions, OPT_Bsymbolic)) {
if (arg->getOption().matches(OPT_Bsymbolic_non_weak_functions))
config->bsymbolic = BsymbolicKind::NonWeakFunctions;
else if (arg->getOption().matches(OPT_Bsymbolic_functions))
config->bsymbolic = BsymbolicKind::Functions;
else if (arg->getOption().matches(OPT_Bsymbolic))
config->bsymbolic = BsymbolicKind::All;
}
config->checkSections =
args.hasFlag(OPT_check_sections, OPT_no_check_sections, true);
config->chroot = args.getLastArgValue(OPT_chroot);
config->compressDebugSections = getCompressDebugSections(args);
config->cref = args.hasArg(OPT_cref);
config->defineCommon = args.hasFlag(OPT_define_common, OPT_no_define_common,
!args.hasArg(OPT_relocatable));