forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInputFiles.cpp
1910 lines (1728 loc) · 71.4 KB
/
InputFiles.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
//===- InputFiles.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
//
//===----------------------------------------------------------------------===//
#include "InputFiles.h"
#include "Config.h"
#include "DWARF.h"
#include "Driver.h"
#include "InputSection.h"
#include "LinkerScript.h"
#include "SymbolTable.h"
#include "Symbols.h"
#include "SyntheticSections.h"
#include "Target.h"
#include "lld/Common/CommonLinkerContext.h"
#include "lld/Common/DWARF.h"
#include "llvm/ADT/CachedHashString.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/LTO/LTO.h"
#include "llvm/Object/IRObjectFile.h"
#include "llvm/Support/ARMAttributeParser.h"
#include "llvm/Support/ARMBuildAttributes.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/RISCVAttributeParser.h"
#include "llvm/Support/TimeProfiler.h"
#include "llvm/Support/raw_ostream.h"
#include <optional>
using namespace llvm;
using namespace llvm::ELF;
using namespace llvm::object;
using namespace llvm::sys;
using namespace llvm::sys::fs;
using namespace llvm::support::endian;
using namespace lld;
using namespace lld::elf;
// This function is explicitly instantiated in ARM.cpp, don't do it here to
// avoid warnings with MSVC.
extern template void ObjFile<ELF32LE>::importCmseSymbols();
extern template void ObjFile<ELF32BE>::importCmseSymbols();
extern template void ObjFile<ELF64LE>::importCmseSymbols();
extern template void ObjFile<ELF64BE>::importCmseSymbols();
// Returns "<internal>", "foo.a(bar.o)" or "baz.o".
std::string elf::toStr(Ctx &ctx, const InputFile *f) {
static std::mutex mu;
if (!f)
return "<internal>";
{
std::lock_guard<std::mutex> lock(mu);
if (f->toStringCache.empty()) {
if (f->archiveName.empty())
f->toStringCache = f->getName();
else
(f->archiveName + "(" + f->getName() + ")").toVector(f->toStringCache);
}
}
return std::string(f->toStringCache);
}
const ELFSyncStream &elf::operator<<(const ELFSyncStream &s,
const InputFile *f) {
return s << toStr(s.ctx, f);
}
static ELFKind getELFKind(Ctx &ctx, MemoryBufferRef mb, StringRef archiveName) {
unsigned char size;
unsigned char endian;
std::tie(size, endian) = getElfArchType(mb.getBuffer());
auto report = [&](StringRef msg) {
StringRef filename = mb.getBufferIdentifier();
if (archiveName.empty())
Fatal(ctx) << filename << ": " << msg;
else
Fatal(ctx) << archiveName << "(" << filename << "): " << msg;
};
if (!mb.getBuffer().starts_with(ElfMagic))
report("not an ELF file");
if (endian != ELFDATA2LSB && endian != ELFDATA2MSB)
report("corrupted ELF file: invalid data encoding");
if (size != ELFCLASS32 && size != ELFCLASS64)
report("corrupted ELF file: invalid file class");
size_t bufSize = mb.getBuffer().size();
if ((size == ELFCLASS32 && bufSize < sizeof(Elf32_Ehdr)) ||
(size == ELFCLASS64 && bufSize < sizeof(Elf64_Ehdr)))
report("corrupted ELF file: file is too short");
if (size == ELFCLASS32)
return (endian == ELFDATA2LSB) ? ELF32LEKind : ELF32BEKind;
return (endian == ELFDATA2LSB) ? ELF64LEKind : ELF64BEKind;
}
// For ARM only, to set the EF_ARM_ABI_FLOAT_SOFT or EF_ARM_ABI_FLOAT_HARD
// flag in the ELF Header we need to look at Tag_ABI_VFP_args to find out how
// the input objects have been compiled.
static void updateARMVFPArgs(Ctx &ctx, const ARMAttributeParser &attributes,
const InputFile *f) {
std::optional<unsigned> attr =
attributes.getAttributeValue(ARMBuildAttrs::ABI_VFP_args);
if (!attr)
// If an ABI tag isn't present then it is implicitly given the value of 0
// which maps to ARMBuildAttrs::BaseAAPCS. However many assembler files,
// including some in glibc that don't use FP args (and should have value 3)
// don't have the attribute so we do not consider an implicit value of 0
// as a clash.
return;
unsigned vfpArgs = *attr;
ARMVFPArgKind arg;
switch (vfpArgs) {
case ARMBuildAttrs::BaseAAPCS:
arg = ARMVFPArgKind::Base;
break;
case ARMBuildAttrs::HardFPAAPCS:
arg = ARMVFPArgKind::VFP;
break;
case ARMBuildAttrs::ToolChainFPPCS:
// Tool chain specific convention that conforms to neither AAPCS variant.
arg = ARMVFPArgKind::ToolChain;
break;
case ARMBuildAttrs::CompatibleFPAAPCS:
// Object compatible with all conventions.
return;
default:
ErrAlways(ctx) << f << ": unknown Tag_ABI_VFP_args value: " << vfpArgs;
return;
}
// Follow ld.bfd and error if there is a mix of calling conventions.
if (ctx.arg.armVFPArgs != arg && ctx.arg.armVFPArgs != ARMVFPArgKind::Default)
ErrAlways(ctx) << f << ": incompatible Tag_ABI_VFP_args";
else
ctx.arg.armVFPArgs = arg;
}
// The ARM support in lld makes some use of instructions that are not available
// on all ARM architectures. Namely:
// - Use of BLX instruction for interworking between ARM and Thumb state.
// - Use of the extended Thumb branch encoding in relocation.
// - Use of the MOVT/MOVW instructions in Thumb Thunks.
// The ARM Attributes section contains information about the architecture chosen
// at compile time. We follow the convention that if at least one input object
// is compiled with an architecture that supports these features then lld is
// permitted to use them.
static void updateSupportedARMFeatures(Ctx &ctx,
const ARMAttributeParser &attributes) {
std::optional<unsigned> attr =
attributes.getAttributeValue(ARMBuildAttrs::CPU_arch);
if (!attr)
return;
auto arch = *attr;
switch (arch) {
case ARMBuildAttrs::Pre_v4:
case ARMBuildAttrs::v4:
case ARMBuildAttrs::v4T:
// Architectures prior to v5 do not support BLX instruction
break;
case ARMBuildAttrs::v5T:
case ARMBuildAttrs::v5TE:
case ARMBuildAttrs::v5TEJ:
case ARMBuildAttrs::v6:
case ARMBuildAttrs::v6KZ:
case ARMBuildAttrs::v6K:
ctx.arg.armHasBlx = true;
// Architectures used in pre-Cortex processors do not support
// The J1 = 1 J2 = 1 Thumb branch range extension, with the exception
// of Architecture v6T2 (arm1156t2-s and arm1156t2f-s) that do.
break;
default:
// All other Architectures have BLX and extended branch encoding
ctx.arg.armHasBlx = true;
ctx.arg.armJ1J2BranchEncoding = true;
if (arch != ARMBuildAttrs::v6_M && arch != ARMBuildAttrs::v6S_M)
// All Architectures used in Cortex processors with the exception
// of v6-M and v6S-M have the MOVT and MOVW instructions.
ctx.arg.armHasMovtMovw = true;
break;
}
// Only ARMv8-M or later architectures have CMSE support.
std::optional<unsigned> profile =
attributes.getAttributeValue(ARMBuildAttrs::CPU_arch_profile);
if (!profile)
return;
if (arch >= ARMBuildAttrs::CPUArch::v8_M_Base &&
profile == ARMBuildAttrs::MicroControllerProfile)
ctx.arg.armCMSESupport = true;
// The thumb PLT entries require Thumb2 which can be used on multiple archs.
// For now, let's limit it to ones where ARM isn't available and we know have
// Thumb2.
std::optional<unsigned> armISA =
attributes.getAttributeValue(ARMBuildAttrs::ARM_ISA_use);
std::optional<unsigned> thumb =
attributes.getAttributeValue(ARMBuildAttrs::THUMB_ISA_use);
ctx.arg.armHasArmISA |= armISA && *armISA >= ARMBuildAttrs::Allowed;
ctx.arg.armHasThumb2ISA |= thumb && *thumb >= ARMBuildAttrs::AllowThumb32;
}
InputFile::InputFile(Ctx &ctx, Kind k, MemoryBufferRef m)
: ctx(ctx), mb(m), groupId(ctx.driver.nextGroupId), fileKind(k) {
// All files within the same --{start,end}-group get the same group ID.
// Otherwise, a new file will get a new group ID.
if (!ctx.driver.isInGroup)
++ctx.driver.nextGroupId;
}
InputFile::~InputFile() {}
std::optional<MemoryBufferRef> elf::readFile(Ctx &ctx, StringRef path) {
llvm::TimeTraceScope timeScope("Load input files", path);
// The --chroot option changes our virtual root directory.
// This is useful when you are dealing with files created by --reproduce.
if (!ctx.arg.chroot.empty() && path.starts_with("/"))
path = ctx.saver.save(ctx.arg.chroot + path);
bool remapped = false;
auto it = ctx.arg.remapInputs.find(path);
if (it != ctx.arg.remapInputs.end()) {
path = it->second;
remapped = true;
} else {
for (const auto &[pat, toFile] : ctx.arg.remapInputsWildcards) {
if (pat.match(path)) {
path = toFile;
remapped = true;
break;
}
}
}
if (remapped) {
// Use /dev/null to indicate an input file that should be ignored. Change
// the path to NUL on Windows.
#ifdef _WIN32
if (path == "/dev/null")
path = "NUL";
#endif
}
Log(ctx) << path;
ctx.arg.dependencyFiles.insert(llvm::CachedHashString(path));
auto mbOrErr = MemoryBuffer::getFile(path, /*IsText=*/false,
/*RequiresNullTerminator=*/false);
if (auto ec = mbOrErr.getError()) {
ErrAlways(ctx) << "cannot open " << path << ": " << ec.message();
return std::nullopt;
}
MemoryBufferRef mbref = (*mbOrErr)->getMemBufferRef();
ctx.memoryBuffers.push_back(std::move(*mbOrErr)); // take MB ownership
if (ctx.tar)
ctx.tar->append(relativeToRoot(path), mbref.getBuffer());
return mbref;
}
// All input object files must be for the same architecture
// (e.g. it does not make sense to link x86 object files with
// MIPS object files.) This function checks for that error.
static bool isCompatible(Ctx &ctx, InputFile *file) {
if (!file->isElf() && !isa<BitcodeFile>(file))
return true;
if (file->ekind == ctx.arg.ekind && file->emachine == ctx.arg.emachine) {
if (ctx.arg.emachine != EM_MIPS)
return true;
if (isMipsN32Abi(ctx, *file) == ctx.arg.mipsN32Abi)
return true;
}
StringRef target =
!ctx.arg.bfdname.empty() ? ctx.arg.bfdname : ctx.arg.emulation;
if (!target.empty()) {
Err(ctx) << file << " is incompatible with " << target;
return false;
}
InputFile *existing = nullptr;
if (!ctx.objectFiles.empty())
existing = ctx.objectFiles[0];
else if (!ctx.sharedFiles.empty())
existing = ctx.sharedFiles[0];
else if (!ctx.bitcodeFiles.empty())
existing = ctx.bitcodeFiles[0];
auto diag = Err(ctx);
diag << file << " is incompatible";
if (existing)
diag << " with " << existing;
return false;
}
template <class ELFT> static void doParseFile(Ctx &ctx, InputFile *file) {
if (!isCompatible(ctx, file))
return;
// Lazy object file
if (file->lazy) {
if (auto *f = dyn_cast<BitcodeFile>(file)) {
ctx.lazyBitcodeFiles.push_back(f);
f->parseLazy();
} else {
cast<ObjFile<ELFT>>(file)->parseLazy();
}
return;
}
if (ctx.arg.trace)
Msg(ctx) << file;
if (file->kind() == InputFile::ObjKind) {
ctx.objectFiles.push_back(cast<ELFFileBase>(file));
cast<ObjFile<ELFT>>(file)->parse();
} else if (auto *f = dyn_cast<SharedFile>(file)) {
f->parse<ELFT>();
} else if (auto *f = dyn_cast<BitcodeFile>(file)) {
ctx.bitcodeFiles.push_back(f);
f->parse();
} else {
ctx.binaryFiles.push_back(cast<BinaryFile>(file));
cast<BinaryFile>(file)->parse();
}
}
// Add symbols in File to the symbol table.
void elf::parseFile(Ctx &ctx, InputFile *file) {
invokeELFT(doParseFile, ctx, file);
}
// This function is explicitly instantiated in ARM.cpp. Mark it extern here,
// to avoid warnings when building with MSVC.
extern template void ObjFile<ELF32LE>::importCmseSymbols();
extern template void ObjFile<ELF32BE>::importCmseSymbols();
extern template void ObjFile<ELF64LE>::importCmseSymbols();
extern template void ObjFile<ELF64BE>::importCmseSymbols();
template <class ELFT>
static void
doParseFiles(Ctx &ctx,
const SmallVector<std::unique_ptr<InputFile>, 0> &files) {
// Add all files to the symbol table. This will add almost all symbols that we
// need to the symbol table. This process might add files to the link due to
// addDependentLibrary.
for (size_t i = 0; i < files.size(); ++i) {
llvm::TimeTraceScope timeScope("Parse input files", files[i]->getName());
doParseFile<ELFT>(ctx, files[i].get());
}
if (ctx.driver.armCmseImpLib)
cast<ObjFile<ELFT>>(*ctx.driver.armCmseImpLib).importCmseSymbols();
}
void elf::parseFiles(Ctx &ctx,
const SmallVector<std::unique_ptr<InputFile>, 0> &files) {
llvm::TimeTraceScope timeScope("Parse input files");
invokeELFT(doParseFiles, ctx, files);
}
// Concatenates arguments to construct a string representing an error location.
StringRef InputFile::getNameForScript() const {
if (archiveName.empty())
return getName();
if (nameForScriptCache.empty())
nameForScriptCache = (archiveName + Twine(':') + getName()).str();
return nameForScriptCache;
}
// An ELF object file may contain a `.deplibs` section. If it exists, the
// section contains a list of library specifiers such as `m` for libm. This
// function resolves a given name by finding the first matching library checking
// the various ways that a library can be specified to LLD. This ELF extension
// is a form of autolinking and is called `dependent libraries`. It is currently
// unique to LLVM and lld.
static void addDependentLibrary(Ctx &ctx, StringRef specifier,
const InputFile *f) {
if (!ctx.arg.dependentLibraries)
return;
if (std::optional<std::string> s = searchLibraryBaseName(ctx, specifier))
ctx.driver.addFile(ctx.saver.save(*s), /*withLOption=*/true);
else if (std::optional<std::string> s = findFromSearchPaths(ctx, specifier))
ctx.driver.addFile(ctx.saver.save(*s), /*withLOption=*/true);
else if (fs::exists(specifier))
ctx.driver.addFile(specifier, /*withLOption=*/false);
else
ErrAlways(ctx)
<< f << ": unable to find library from dependent library specifier: "
<< specifier;
}
// Record the membership of a section group so that in the garbage collection
// pass, section group members are kept or discarded as a unit.
template <class ELFT>
static void handleSectionGroup(ArrayRef<InputSectionBase *> sections,
ArrayRef<typename ELFT::Word> entries) {
bool hasAlloc = false;
for (uint32_t index : entries.slice(1)) {
if (index >= sections.size())
return;
if (InputSectionBase *s = sections[index])
if (s != &InputSection::discarded && s->flags & SHF_ALLOC)
hasAlloc = true;
}
// If any member has the SHF_ALLOC flag, the whole group is subject to garbage
// collection. See the comment in markLive(). This rule retains .debug_types
// and .rela.debug_types.
if (!hasAlloc)
return;
// Connect the members in a circular doubly-linked list via
// nextInSectionGroup.
InputSectionBase *head;
InputSectionBase *prev = nullptr;
for (uint32_t index : entries.slice(1)) {
InputSectionBase *s = sections[index];
if (!s || s == &InputSection::discarded)
continue;
if (prev)
prev->nextInSectionGroup = s;
else
head = s;
prev = s;
}
if (prev)
prev->nextInSectionGroup = head;
}
template <class ELFT> void ObjFile<ELFT>::initDwarf() {
dwarf = std::make_unique<DWARFCache>(std::make_unique<DWARFContext>(
std::make_unique<LLDDwarfObj<ELFT>>(this), "",
[&](Error err) { Warn(ctx) << getName() + ": " << std::move(err); },
[&](Error warning) {
Warn(ctx) << getName() << ": " << std::move(warning);
}));
}
DWARFCache *ELFFileBase::getDwarf() {
assert(fileKind == ObjKind);
llvm::call_once(initDwarf, [this]() {
switch (ekind) {
default:
llvm_unreachable("");
case ELF32LEKind:
return cast<ObjFile<ELF32LE>>(this)->initDwarf();
case ELF32BEKind:
return cast<ObjFile<ELF32BE>>(this)->initDwarf();
case ELF64LEKind:
return cast<ObjFile<ELF64LE>>(this)->initDwarf();
case ELF64BEKind:
return cast<ObjFile<ELF64BE>>(this)->initDwarf();
}
});
return dwarf.get();
}
ELFFileBase::ELFFileBase(Ctx &ctx, Kind k, ELFKind ekind, MemoryBufferRef mb)
: InputFile(ctx, k, mb) {
this->ekind = ekind;
}
ELFFileBase::~ELFFileBase() {}
template <typename Elf_Shdr>
static const Elf_Shdr *findSection(ArrayRef<Elf_Shdr> sections, uint32_t type) {
for (const Elf_Shdr &sec : sections)
if (sec.sh_type == type)
return &sec;
return nullptr;
}
void ELFFileBase::init() {
switch (ekind) {
case ELF32LEKind:
init<ELF32LE>(fileKind);
break;
case ELF32BEKind:
init<ELF32BE>(fileKind);
break;
case ELF64LEKind:
init<ELF64LE>(fileKind);
break;
case ELF64BEKind:
init<ELF64BE>(fileKind);
break;
default:
llvm_unreachable("getELFKind");
}
}
template <class ELFT> void ELFFileBase::init(InputFile::Kind k) {
using Elf_Shdr = typename ELFT::Shdr;
using Elf_Sym = typename ELFT::Sym;
// Initialize trivial attributes.
const ELFFile<ELFT> &obj = getObj<ELFT>();
emachine = obj.getHeader().e_machine;
osabi = obj.getHeader().e_ident[llvm::ELF::EI_OSABI];
abiVersion = obj.getHeader().e_ident[llvm::ELF::EI_ABIVERSION];
ArrayRef<Elf_Shdr> sections = CHECK2(obj.sections(), this);
elfShdrs = sections.data();
numELFShdrs = sections.size();
// Find a symbol table.
const Elf_Shdr *symtabSec =
findSection(sections, k == SharedKind ? SHT_DYNSYM : SHT_SYMTAB);
if (!symtabSec)
return;
// Initialize members corresponding to a symbol table.
firstGlobal = symtabSec->sh_info;
ArrayRef<Elf_Sym> eSyms = CHECK2(obj.symbols(symtabSec), this);
if (firstGlobal == 0 || firstGlobal > eSyms.size())
Fatal(ctx) << this << ": invalid sh_info in symbol table";
elfSyms = reinterpret_cast<const void *>(eSyms.data());
numSymbols = eSyms.size();
stringTable = CHECK2(obj.getStringTableForSymtab(*symtabSec, sections), this);
}
template <class ELFT>
uint32_t ObjFile<ELFT>::getSectionIndex(const Elf_Sym &sym) const {
return CHECK2(
this->getObj().getSectionIndex(sym, getELFSyms<ELFT>(), shndxTable),
this);
}
template <class ELFT> void ObjFile<ELFT>::parse(bool ignoreComdats) {
object::ELFFile<ELFT> obj = this->getObj();
// Read a section table. justSymbols is usually false.
if (this->justSymbols) {
initializeJustSymbols();
initializeSymbols(obj);
return;
}
// Handle dependent libraries and selection of section groups as these are not
// done in parallel.
ArrayRef<Elf_Shdr> objSections = getELFShdrs<ELFT>();
StringRef shstrtab = CHECK2(obj.getSectionStringTable(objSections), this);
uint64_t size = objSections.size();
sections.resize(size);
for (size_t i = 0; i != size; ++i) {
const Elf_Shdr &sec = objSections[i];
if (LLVM_LIKELY(sec.sh_type == SHT_PROGBITS))
continue;
if (LLVM_LIKELY(sec.sh_type == SHT_GROUP)) {
StringRef signature = getShtGroupSignature(objSections, sec);
ArrayRef<Elf_Word> entries =
CHECK2(obj.template getSectionContentsAsArray<Elf_Word>(sec), this);
if (entries.empty())
Fatal(ctx) << this << ": empty SHT_GROUP";
Elf_Word flag = entries[0];
if (flag && flag != GRP_COMDAT)
Fatal(ctx) << this << ": unsupported SHT_GROUP format";
bool keepGroup = !flag || ignoreComdats ||
ctx.symtab->comdatGroups
.try_emplace(CachedHashStringRef(signature), this)
.second;
if (keepGroup) {
if (!ctx.arg.resolveGroups)
sections[i] = createInputSection(
i, sec, check(obj.getSectionName(sec, shstrtab)));
} else {
// Otherwise, discard group members.
for (uint32_t secIndex : entries.slice(1)) {
if (secIndex >= size)
Fatal(ctx) << this
<< ": invalid section index in group: " << secIndex;
sections[secIndex] = &InputSection::discarded;
}
}
continue;
}
if (sec.sh_type == SHT_LLVM_DEPENDENT_LIBRARIES && !ctx.arg.relocatable) {
StringRef name = check(obj.getSectionName(sec, shstrtab));
ArrayRef<char> data = CHECK2(
this->getObj().template getSectionContentsAsArray<char>(sec), this);
if (!data.empty() && data.back() != '\0') {
Err(ctx)
<< this
<< ": corrupted dependent libraries section (unterminated string): "
<< name;
} else {
for (const char *d = data.begin(), *e = data.end(); d < e;) {
StringRef s(d);
addDependentLibrary(ctx, s, this);
d += s.size() + 1;
}
}
sections[i] = &InputSection::discarded;
continue;
}
switch (ctx.arg.emachine) {
case EM_ARM:
if (sec.sh_type == SHT_ARM_ATTRIBUTES) {
ARMAttributeParser attributes;
ArrayRef<uint8_t> contents =
check(this->getObj().getSectionContents(sec));
StringRef name = check(obj.getSectionName(sec, shstrtab));
sections[i] = &InputSection::discarded;
if (Error e = attributes.parse(contents, ekind == ELF32LEKind
? llvm::endianness::little
: llvm::endianness::big)) {
InputSection isec(*this, sec, name);
Warn(ctx) << &isec << ": " << std::move(e);
} else {
updateSupportedARMFeatures(ctx, attributes);
updateARMVFPArgs(ctx, attributes, this);
// FIXME: Retain the first attribute section we see. The eglibc ARM
// dynamic loaders require the presence of an attribute section for
// dlopen to work. In a full implementation we would merge all
// attribute sections.
if (ctx.in.attributes == nullptr) {
ctx.in.attributes =
std::make_unique<InputSection>(*this, sec, name);
sections[i] = ctx.in.attributes.get();
}
}
}
break;
case EM_AARCH64:
// Producing a static binary with MTE globals is not currently supported,
// remove all SHT_AARCH64_MEMTAG_GLOBALS_STATIC sections as they're unused
// medatada, and we don't want them to end up in the output file for
// static executables.
if (sec.sh_type == SHT_AARCH64_MEMTAG_GLOBALS_STATIC &&
!canHaveMemtagGlobals(ctx))
sections[i] = &InputSection::discarded;
break;
}
}
// Read a symbol table.
initializeSymbols(obj);
}
// Sections with SHT_GROUP and comdat bits define comdat section groups.
// They are identified and deduplicated by group name. This function
// returns a group name.
template <class ELFT>
StringRef ObjFile<ELFT>::getShtGroupSignature(ArrayRef<Elf_Shdr> sections,
const Elf_Shdr &sec) {
typename ELFT::SymRange symbols = this->getELFSyms<ELFT>();
if (sec.sh_info >= symbols.size())
Fatal(ctx) << this << ": invalid symbol index";
const typename ELFT::Sym &sym = symbols[sec.sh_info];
return CHECK2(sym.getName(this->stringTable), this);
}
template <class ELFT>
bool ObjFile<ELFT>::shouldMerge(const Elf_Shdr &sec, StringRef name) {
// On a regular link we don't merge sections if -O0 (default is -O1). This
// sometimes makes the linker significantly faster, although the output will
// be bigger.
//
// Doing the same for -r would create a problem as it would combine sections
// with different sh_entsize. One option would be to just copy every SHF_MERGE
// section as is to the output. While this would produce a valid ELF file with
// usable SHF_MERGE sections, tools like (llvm-)?dwarfdump get confused when
// they see two .debug_str. We could have separate logic for combining
// SHF_MERGE sections based both on their name and sh_entsize, but that seems
// to be more trouble than it is worth. Instead, we just use the regular (-O1)
// logic for -r.
if (ctx.arg.optimize == 0 && !ctx.arg.relocatable)
return false;
// A mergeable section with size 0 is useless because they don't have
// any data to merge. A mergeable string section with size 0 can be
// argued as invalid because it doesn't end with a null character.
// We'll avoid a mess by handling them as if they were non-mergeable.
if (sec.sh_size == 0)
return false;
// Check for sh_entsize. The ELF spec is not clear about the zero
// sh_entsize. It says that "the member [sh_entsize] contains 0 if
// the section does not hold a table of fixed-size entries". We know
// that Rust 1.13 produces a string mergeable section with a zero
// sh_entsize. Here we just accept it rather than being picky about it.
uint64_t entSize = sec.sh_entsize;
if (entSize == 0)
return false;
if (sec.sh_size % entSize)
Fatal(ctx) << this << ":(" << name << "): SHF_MERGE section size ("
<< uint64_t(sec.sh_size)
<< ") must be a multiple of sh_entsize (" << entSize << ")";
if (sec.sh_flags & SHF_WRITE)
Fatal(ctx) << this << ":(" << name
<< "): writable SHF_MERGE section is not supported";
return true;
}
// This is for --just-symbols.
//
// --just-symbols is a very minor feature that allows you to link your
// output against other existing program, so that if you load both your
// program and the other program into memory, your output can refer the
// other program's symbols.
//
// When the option is given, we link "just symbols". The section table is
// initialized with null pointers.
template <class ELFT> void ObjFile<ELFT>::initializeJustSymbols() {
sections.resize(numELFShdrs);
}
static bool isKnownSpecificSectionType(uint32_t t, uint32_t flags) {
if (SHT_LOUSER <= t && t <= SHT_HIUSER && !(flags & SHF_ALLOC))
return true;
if (SHT_LOOS <= t && t <= SHT_HIOS && !(flags & SHF_OS_NONCONFORMING))
return true;
// Allow all processor-specific types. This is different from GNU ld.
return SHT_LOPROC <= t && t <= SHT_HIPROC;
}
template <class ELFT>
void ObjFile<ELFT>::initializeSections(bool ignoreComdats,
const llvm::object::ELFFile<ELFT> &obj) {
ArrayRef<Elf_Shdr> objSections = getELFShdrs<ELFT>();
StringRef shstrtab = CHECK2(obj.getSectionStringTable(objSections), this);
uint64_t size = objSections.size();
SmallVector<ArrayRef<Elf_Word>, 0> selectedGroups;
for (size_t i = 0; i != size; ++i) {
if (this->sections[i] == &InputSection::discarded)
continue;
const Elf_Shdr &sec = objSections[i];
const uint32_t type = sec.sh_type;
// SHF_EXCLUDE'ed sections are discarded by the linker. However,
// if -r is given, we'll let the final link discard such sections.
// This is compatible with GNU.
if ((sec.sh_flags & SHF_EXCLUDE) && !ctx.arg.relocatable) {
if (type == SHT_LLVM_CALL_GRAPH_PROFILE)
cgProfileSectionIndex = i;
if (type == SHT_LLVM_ADDRSIG) {
// We ignore the address-significance table if we know that the object
// file was created by objcopy or ld -r. This is because these tools
// will reorder the symbols in the symbol table, invalidating the data
// in the address-significance table, which refers to symbols by index.
if (sec.sh_link != 0)
this->addrsigSec = &sec;
else if (ctx.arg.icf == ICFLevel::Safe)
Warn(ctx) << this
<< ": --icf=safe conservatively ignores "
"SHT_LLVM_ADDRSIG [index "
<< i
<< "] with sh_link=0 "
"(likely created using objcopy or ld -r)";
}
this->sections[i] = &InputSection::discarded;
continue;
}
switch (type) {
case SHT_GROUP: {
if (!ctx.arg.relocatable)
sections[i] = &InputSection::discarded;
StringRef signature =
cantFail(this->getELFSyms<ELFT>()[sec.sh_info].getName(stringTable));
ArrayRef<Elf_Word> entries =
cantFail(obj.template getSectionContentsAsArray<Elf_Word>(sec));
if ((entries[0] & GRP_COMDAT) == 0 || ignoreComdats ||
ctx.symtab->comdatGroups.find(CachedHashStringRef(signature))
->second == this)
selectedGroups.push_back(entries);
break;
}
case SHT_SYMTAB_SHNDX:
shndxTable = CHECK2(obj.getSHNDXTable(sec, objSections), this);
break;
case SHT_SYMTAB:
case SHT_STRTAB:
case SHT_REL:
case SHT_RELA:
case SHT_CREL:
case SHT_NULL:
break;
case SHT_PROGBITS:
case SHT_NOTE:
case SHT_NOBITS:
case SHT_INIT_ARRAY:
case SHT_FINI_ARRAY:
case SHT_PREINIT_ARRAY:
this->sections[i] =
createInputSection(i, sec, check(obj.getSectionName(sec, shstrtab)));
break;
case SHT_LLVM_LTO:
// Discard .llvm.lto in a relocatable link that does not use the bitcode.
// The concatenated output does not properly reflect the linking
// semantics. In addition, since we do not use the bitcode wrapper format,
// the concatenated raw bitcode would be invalid.
if (ctx.arg.relocatable && !ctx.arg.fatLTOObjects) {
sections[i] = &InputSection::discarded;
break;
}
[[fallthrough]];
default:
this->sections[i] =
createInputSection(i, sec, check(obj.getSectionName(sec, shstrtab)));
if (type == SHT_LLVM_SYMPART)
ctx.hasSympart.store(true, std::memory_order_relaxed);
else if (ctx.arg.rejectMismatch &&
!isKnownSpecificSectionType(type, sec.sh_flags))
Err(ctx) << this->sections[i] << ": unknown section type 0x"
<< Twine::utohexstr(type);
break;
}
}
// We have a second loop. It is used to:
// 1) handle SHF_LINK_ORDER sections.
// 2) create relocation sections. In some cases the section header index of a
// relocation section may be smaller than that of the relocated section. In
// such cases, the relocation section would attempt to reference a target
// section that has not yet been created. For simplicity, delay creation of
// relocation sections until now.
for (size_t i = 0; i != size; ++i) {
if (this->sections[i] == &InputSection::discarded)
continue;
const Elf_Shdr &sec = objSections[i];
if (isStaticRelSecType(sec.sh_type)) {
// Find a relocation target section and associate this section with that.
// Target may have been discarded if it is in a different section group
// and the group is discarded, even though it's a violation of the spec.
// We handle that situation gracefully by discarding dangling relocation
// sections.
const uint32_t info = sec.sh_info;
InputSectionBase *s = getRelocTarget(i, info);
if (!s)
continue;
// ELF spec allows mergeable sections with relocations, but they are rare,
// and it is in practice hard to merge such sections by contents, because
// applying relocations at end of linking changes section contents. So, we
// simply handle such sections as non-mergeable ones. Degrading like this
// is acceptable because section merging is optional.
if (auto *ms = dyn_cast<MergeInputSection>(s)) {
s = makeThreadLocal<InputSection>(ms->file, ms->name, ms->type,
ms->flags, ms->addralign, ms->entsize,
ms->contentMaybeDecompress());
sections[info] = s;
}
if (s->relSecIdx != 0)
ErrAlways(ctx) << s
<< ": multiple relocation sections to one section are "
"not supported";
s->relSecIdx = i;
// Relocation sections are usually removed from the output, so return
// `nullptr` for the normal case. However, if -r or --emit-relocs is
// specified, we need to copy them to the output. (Some post link analysis
// tools specify --emit-relocs to obtain the information.)
if (ctx.arg.copyRelocs) {
auto *isec = makeThreadLocal<InputSection>(
*this, sec, check(obj.getSectionName(sec, shstrtab)));
// If the relocated section is discarded (due to /DISCARD/ or
// --gc-sections), the relocation section should be discarded as well.
s->dependentSections.push_back(isec);
sections[i] = isec;
}
continue;
}
// A SHF_LINK_ORDER section with sh_link=0 is handled as if it did not have
// the flag.
if (!sec.sh_link || !(sec.sh_flags & SHF_LINK_ORDER))
continue;
InputSectionBase *linkSec = nullptr;
if (sec.sh_link < size)
linkSec = this->sections[sec.sh_link];
if (!linkSec)
Fatal(ctx) << this
<< ": invalid sh_link index: " << uint32_t(sec.sh_link);
// A SHF_LINK_ORDER section is discarded if its linked-to section is
// discarded.
InputSection *isec = cast<InputSection>(this->sections[i]);
linkSec->dependentSections.push_back(isec);
if (!isa<InputSection>(linkSec))
ErrAlways(ctx)
<< "a section " << isec->name
<< " with SHF_LINK_ORDER should not refer a non-regular section: "
<< linkSec;
}
for (ArrayRef<Elf_Word> entries : selectedGroups)
handleSectionGroup<ELFT>(this->sections, entries);
}
// Read the following info from the .note.gnu.property section and write it to
// the corresponding fields in `ObjFile`:
// - Feature flags (32 bits) representing x86 or AArch64 features for
// hardware-assisted call flow control;
// - AArch64 PAuth ABI core info (16 bytes).
template <class ELFT>
static void readGnuProperty(Ctx &ctx, const InputSection &sec,
ObjFile<ELFT> &f) {
using Elf_Nhdr = typename ELFT::Nhdr;
using Elf_Note = typename ELFT::Note;
ArrayRef<uint8_t> data = sec.content();
auto reportFatal = [&](const uint8_t *place, const Twine &msg) {
Fatal(ctx) << sec.file << ":(" << sec.name << "+0x"
<< Twine::utohexstr(place - sec.content().data())
<< "): " << msg;
};
while (!data.empty()) {
// Read one NOTE record.
auto *nhdr = reinterpret_cast<const Elf_Nhdr *>(data.data());
if (data.size() < sizeof(Elf_Nhdr) ||
data.size() < nhdr->getSize(sec.addralign))
reportFatal(data.data(), "data is too short");
Elf_Note note(*nhdr);
if (nhdr->n_type != NT_GNU_PROPERTY_TYPE_0 || note.getName() != "GNU") {
data = data.slice(nhdr->getSize(sec.addralign));
continue;
}
uint32_t featureAndType = ctx.arg.emachine == EM_AARCH64
? GNU_PROPERTY_AARCH64_FEATURE_1_AND
: GNU_PROPERTY_X86_FEATURE_1_AND;
// Read a body of a NOTE record, which consists of type-length-value fields.
ArrayRef<uint8_t> desc = note.getDesc(sec.addralign);
while (!desc.empty()) {
const uint8_t *place = desc.data();
if (desc.size() < 8)
reportFatal(place, "program property is too short");
uint32_t type = read32<ELFT::Endianness>(desc.data());
uint32_t size = read32<ELFT::Endianness>(desc.data() + 4);
desc = desc.slice(8);
if (desc.size() < size)
reportFatal(place, "program property is too short");
if (type == featureAndType) {
// We found a FEATURE_1_AND field. There may be more than one of these
// in a .note.gnu.property section, for a relocatable object we
// accumulate the bits set.
if (size < 4)
reportFatal(place, "FEATURE_1_AND entry is too short");
f.andFeatures |= read32<ELFT::Endianness>(desc.data());
} else if (ctx.arg.emachine == EM_AARCH64 &&
type == GNU_PROPERTY_AARCH64_FEATURE_PAUTH) {
if (!f.aarch64PauthAbiCoreInfo.empty()) {
reportFatal(data.data(),
"multiple GNU_PROPERTY_AARCH64_FEATURE_PAUTH entries are "
"not supported");
} else if (size != 16) {
reportFatal(data.data(), "GNU_PROPERTY_AARCH64_FEATURE_PAUTH entry "
"is invalid: expected 16 bytes, but got " +
Twine(size));
}
f.aarch64PauthAbiCoreInfo = desc;
}
// Padding is present in the note descriptor, if necessary.
desc = desc.slice(alignTo<(ELFT::Is64Bits ? 8 : 4)>(size));
}
// Go to next NOTE record to look for more FEATURE_1_AND descriptions.
data = data.slice(nhdr->getSize(sec.addralign));
}
}
template <class ELFT>
InputSectionBase *ObjFile<ELFT>::getRelocTarget(uint32_t idx, uint32_t info) {
if (info < this->sections.size()) {
InputSectionBase *target = this->sections[info];
// Strictly speaking, a relocation section must be included in the
// group of the section it relocates. However, LLVM 3.3 and earlier
// would fail to do so, so we gracefully handle that case.
if (target == &InputSection::discarded)
return nullptr;
if (target != nullptr)