-
Notifications
You must be signed in to change notification settings - Fork 13.3k
/
Copy pathInputFiles.cpp
2399 lines (2174 loc) · 95.5 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
//
//===----------------------------------------------------------------------===//
//
// This file contains functions to parse Mach-O object files. In this comment,
// we describe the Mach-O file structure and how we parse it.
//
// Mach-O is not very different from ELF or COFF. The notion of symbols,
// sections and relocations exists in Mach-O as it does in ELF and COFF.
//
// Perhaps the notion that is new to those who know ELF/COFF is "subsections".
// In ELF/COFF, sections are an atomic unit of data copied from input files to
// output files. When we merge or garbage-collect sections, we treat each
// section as an atomic unit. In Mach-O, that's not the case. Sections can
// consist of multiple subsections, and subsections are a unit of merging and
// garbage-collecting. Therefore, Mach-O's subsections are more similar to
// ELF/COFF's sections than Mach-O's sections are.
//
// A section can have multiple symbols. A symbol that does not have the
// N_ALT_ENTRY attribute indicates a beginning of a subsection. Therefore, by
// definition, a symbol is always present at the beginning of each subsection. A
// symbol with N_ALT_ENTRY attribute does not start a new subsection and can
// point to a middle of a subsection.
//
// The notion of subsections also affects how relocations are represented in
// Mach-O. All references within a section need to be explicitly represented as
// relocations if they refer to different subsections, because we obviously need
// to fix up addresses if subsections are laid out in an output file differently
// than they were in object files. To represent that, Mach-O relocations can
// refer to an unnamed location via its address. Scattered relocations (those
// with the R_SCATTERED bit set) always refer to unnamed locations.
// Non-scattered relocations refer to an unnamed location if r_extern is not set
// and r_symbolnum is zero.
//
// Without the above differences, I think you can use your knowledge about ELF
// and COFF for Mach-O.
//
//===----------------------------------------------------------------------===//
#include "InputFiles.h"
#include "Config.h"
#include "Driver.h"
#include "Dwarf.h"
#include "EhFrame.h"
#include "ExportTrie.h"
#include "InputSection.h"
#include "MachOStructs.h"
#include "ObjC.h"
#include "OutputSection.h"
#include "OutputSegment.h"
#include "SymbolTable.h"
#include "Symbols.h"
#include "SyntheticSections.h"
#include "Target.h"
#include "lld/Common/CommonLinkerContext.h"
#include "lld/Common/DWARF.h"
#include "lld/Common/Reproduce.h"
#include "llvm/ADT/iterator.h"
#include "llvm/BinaryFormat/MachO.h"
#include "llvm/LTO/LTO.h"
#include "llvm/Support/BinaryStreamReader.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/LEB128.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/TarWriter.h"
#include "llvm/Support/TimeProfiler.h"
#include "llvm/TextAPI/Architecture.h"
#include "llvm/TextAPI/InterfaceFile.h"
#include <optional>
#include <type_traits>
using namespace llvm;
using namespace llvm::MachO;
using namespace llvm::support::endian;
using namespace llvm::sys;
using namespace lld;
using namespace lld::macho;
// Returns "<internal>", "foo.a(bar.o)", or "baz.o".
std::string lld::toString(const InputFile *f) {
if (!f)
return "<internal>";
// Multiple dylibs can be defined in one .tbd file.
if (const auto *dylibFile = dyn_cast<DylibFile>(f))
if (f->getName().ends_with(".tbd"))
return (f->getName() + "(" + dylibFile->installName + ")").str();
if (f->archiveName.empty())
return std::string(f->getName());
return (f->archiveName + "(" + path::filename(f->getName()) + ")").str();
}
std::string lld::toString(const Section &sec) {
return (toString(sec.file) + ":(" + sec.name + ")").str();
}
SetVector<InputFile *> macho::inputFiles;
std::unique_ptr<TarWriter> macho::tar;
int InputFile::idCount = 0;
static VersionTuple decodeVersion(uint32_t version) {
unsigned major = version >> 16;
unsigned minor = (version >> 8) & 0xffu;
unsigned subMinor = version & 0xffu;
return VersionTuple(major, minor, subMinor);
}
static std::vector<PlatformInfo> getPlatformInfos(const InputFile *input) {
if (!isa<ObjFile>(input) && !isa<DylibFile>(input))
return {};
const char *hdr = input->mb.getBufferStart();
// "Zippered" object files can have multiple LC_BUILD_VERSION load commands.
std::vector<PlatformInfo> platformInfos;
for (auto *cmd : findCommands<build_version_command>(hdr, LC_BUILD_VERSION)) {
PlatformInfo info;
info.target.Platform = static_cast<PlatformType>(cmd->platform);
info.target.MinDeployment = decodeVersion(cmd->minos);
platformInfos.emplace_back(std::move(info));
}
for (auto *cmd : findCommands<version_min_command>(
hdr, LC_VERSION_MIN_MACOSX, LC_VERSION_MIN_IPHONEOS,
LC_VERSION_MIN_TVOS, LC_VERSION_MIN_WATCHOS)) {
PlatformInfo info;
switch (cmd->cmd) {
case LC_VERSION_MIN_MACOSX:
info.target.Platform = PLATFORM_MACOS;
break;
case LC_VERSION_MIN_IPHONEOS:
info.target.Platform = PLATFORM_IOS;
break;
case LC_VERSION_MIN_TVOS:
info.target.Platform = PLATFORM_TVOS;
break;
case LC_VERSION_MIN_WATCHOS:
info.target.Platform = PLATFORM_WATCHOS;
break;
}
info.target.MinDeployment = decodeVersion(cmd->version);
platformInfos.emplace_back(std::move(info));
}
return platformInfos;
}
static bool checkCompatibility(const InputFile *input) {
std::vector<PlatformInfo> platformInfos = getPlatformInfos(input);
if (platformInfos.empty())
return true;
auto it = find_if(platformInfos, [&](const PlatformInfo &info) {
return removeSimulator(info.target.Platform) ==
removeSimulator(config->platform());
});
if (it == platformInfos.end()) {
std::string platformNames;
raw_string_ostream os(platformNames);
interleave(
platformInfos, os,
[&](const PlatformInfo &info) {
os << getPlatformName(info.target.Platform);
},
"/");
error(toString(input) + " has platform " + platformNames +
Twine(", which is different from target platform ") +
getPlatformName(config->platform()));
return false;
}
if (it->target.MinDeployment > config->platformInfo.target.MinDeployment)
warn(toString(input) + " has version " +
it->target.MinDeployment.getAsString() +
", which is newer than target minimum of " +
config->platformInfo.target.MinDeployment.getAsString());
return true;
}
template <class Header>
static bool compatWithTargetArch(const InputFile *file, const Header *hdr) {
uint32_t cpuType;
std::tie(cpuType, std::ignore) = getCPUTypeFromArchitecture(config->arch());
if (hdr->cputype != cpuType) {
Architecture arch =
getArchitectureFromCpuType(hdr->cputype, hdr->cpusubtype);
auto msg = config->errorForArchMismatch
? static_cast<void (*)(const Twine &)>(error)
: warn;
msg(toString(file) + " has architecture " + getArchitectureName(arch) +
" which is incompatible with target architecture " +
getArchitectureName(config->arch()));
return false;
}
return checkCompatibility(file);
}
// This cache mostly exists to store system libraries (and .tbds) as they're
// loaded, rather than the input archives, which are already cached at a higher
// level, and other files like the filelist that are only read once.
// Theoretically this caching could be more efficient by hoisting it, but that
// would require altering many callers to track the state.
DenseMap<CachedHashStringRef, MemoryBufferRef> macho::cachedReads;
// Open a given file path and return it as a memory-mapped file.
std::optional<MemoryBufferRef> macho::readFile(StringRef path) {
CachedHashStringRef key(path);
auto entry = cachedReads.find(key);
if (entry != cachedReads.end())
return entry->second;
ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr = MemoryBuffer::getFile(path);
if (std::error_code ec = mbOrErr.getError()) {
error("cannot open " + path + ": " + ec.message());
return std::nullopt;
}
std::unique_ptr<MemoryBuffer> &mb = *mbOrErr;
MemoryBufferRef mbref = mb->getMemBufferRef();
make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take mb ownership
// If this is a regular non-fat file, return it.
const char *buf = mbref.getBufferStart();
const auto *hdr = reinterpret_cast<const fat_header *>(buf);
if (mbref.getBufferSize() < sizeof(uint32_t) ||
read32be(&hdr->magic) != FAT_MAGIC) {
if (tar)
tar->append(relativeToRoot(path), mbref.getBuffer());
return cachedReads[key] = mbref;
}
llvm::BumpPtrAllocator &bAlloc = lld::bAlloc();
// Object files and archive files may be fat files, which contain multiple
// real files for different CPU ISAs. Here, we search for a file that matches
// with the current link target and returns it as a MemoryBufferRef.
const auto *arch = reinterpret_cast<const fat_arch *>(buf + sizeof(*hdr));
auto getArchName = [](uint32_t cpuType, uint32_t cpuSubtype) {
return getArchitectureName(getArchitectureFromCpuType(cpuType, cpuSubtype));
};
std::vector<StringRef> archs;
for (uint32_t i = 0, n = read32be(&hdr->nfat_arch); i < n; ++i) {
if (reinterpret_cast<const char *>(arch + i + 1) >
buf + mbref.getBufferSize()) {
error(path + ": fat_arch struct extends beyond end of file");
return std::nullopt;
}
uint32_t cpuType = read32be(&arch[i].cputype);
uint32_t cpuSubtype =
read32be(&arch[i].cpusubtype) & ~MachO::CPU_SUBTYPE_MASK;
// FIXME: LD64 has a more complex fallback logic here.
// Consider implementing that as well?
if (cpuType != static_cast<uint32_t>(target->cpuType) ||
cpuSubtype != target->cpuSubtype) {
archs.emplace_back(getArchName(cpuType, cpuSubtype));
continue;
}
uint32_t offset = read32be(&arch[i].offset);
uint32_t size = read32be(&arch[i].size);
if (offset + size > mbref.getBufferSize())
error(path + ": slice extends beyond end of file");
if (tar)
tar->append(relativeToRoot(path), mbref.getBuffer());
return cachedReads[key] = MemoryBufferRef(StringRef(buf + offset, size),
path.copy(bAlloc));
}
auto targetArchName = getArchName(target->cpuType, target->cpuSubtype);
warn(path + ": ignoring file because it is universal (" + join(archs, ",") +
") but does not contain the " + targetArchName + " architecture");
return std::nullopt;
}
InputFile::InputFile(Kind kind, const InterfaceFile &interface)
: id(idCount++), fileKind(kind), name(saver().save(interface.getPath())) {}
// Some sections comprise of fixed-size records, so instead of splitting them at
// symbol boundaries, we split them based on size. Records are distinct from
// literals in that they may contain references to other sections, instead of
// being leaf nodes in the InputSection graph.
//
// Note that "record" is a term I came up with. In contrast, "literal" is a term
// used by the Mach-O format.
static std::optional<size_t> getRecordSize(StringRef segname, StringRef name) {
if (name == section_names::compactUnwind) {
if (segname == segment_names::ld)
return target->wordSize == 8 ? 32 : 20;
}
if (!config->dedupStrings)
return {};
if (name == section_names::cfString && segname == segment_names::data)
return target->wordSize == 8 ? 32 : 16;
if (config->icfLevel == ICFLevel::none)
return {};
if (name == section_names::objcClassRefs && segname == segment_names::data)
return target->wordSize;
if (name == section_names::objcSelrefs && segname == segment_names::data)
return target->wordSize;
return {};
}
static Error parseCallGraph(ArrayRef<uint8_t> data,
std::vector<CallGraphEntry> &callGraph) {
TimeTraceScope timeScope("Parsing call graph section");
BinaryStreamReader reader(data, llvm::endianness::little);
while (!reader.empty()) {
uint32_t fromIndex, toIndex;
uint64_t count;
if (Error err = reader.readInteger(fromIndex))
return err;
if (Error err = reader.readInteger(toIndex))
return err;
if (Error err = reader.readInteger(count))
return err;
callGraph.emplace_back(fromIndex, toIndex, count);
}
return Error::success();
}
// Parse the sequence of sections within a single LC_SEGMENT(_64).
// Split each section into subsections.
template <class SectionHeader>
void ObjFile::parseSections(ArrayRef<SectionHeader> sectionHeaders) {
sections.reserve(sectionHeaders.size());
auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
for (const SectionHeader &sec : sectionHeaders) {
StringRef name =
StringRef(sec.sectname, strnlen(sec.sectname, sizeof(sec.sectname)));
StringRef segname =
StringRef(sec.segname, strnlen(sec.segname, sizeof(sec.segname)));
sections.push_back(make<Section>(this, segname, name, sec.flags, sec.addr));
if (sec.align >= 32) {
error("alignment " + std::to_string(sec.align) + " of section " + name +
" is too large");
continue;
}
Section §ion = *sections.back();
uint32_t align = 1 << sec.align;
ArrayRef<uint8_t> data = {isZeroFill(sec.flags) ? nullptr
: buf + sec.offset,
static_cast<size_t>(sec.size)};
auto splitRecords = [&](size_t recordSize) -> void {
if (data.empty())
return;
Subsections &subsections = section.subsections;
subsections.reserve(data.size() / recordSize);
for (uint64_t off = 0; off < data.size(); off += recordSize) {
auto *isec = make<ConcatInputSection>(
section, data.slice(off, std::min(data.size(), recordSize)), align);
subsections.push_back({off, isec});
}
section.doneSplitting = true;
};
if (sectionType(sec.flags) == S_CSTRING_LITERALS) {
if (sec.nreloc)
fatal(toString(this) + ": " + sec.segname + "," + sec.sectname +
" contains relocations, which is unsupported");
bool dedupLiterals =
name == section_names::objcMethname || config->dedupStrings;
InputSection *isec =
make<CStringInputSection>(section, data, align, dedupLiterals);
// FIXME: parallelize this?
cast<CStringInputSection>(isec)->splitIntoPieces();
section.subsections.push_back({0, isec});
} else if (isWordLiteralSection(sec.flags)) {
if (sec.nreloc)
fatal(toString(this) + ": " + sec.segname + "," + sec.sectname +
" contains relocations, which is unsupported");
InputSection *isec = make<WordLiteralInputSection>(section, data, align);
section.subsections.push_back({0, isec});
} else if (auto recordSize = getRecordSize(segname, name)) {
splitRecords(*recordSize);
} else if (name == section_names::ehFrame &&
segname == segment_names::text) {
splitEhFrames(data, *sections.back());
} else if (segname == segment_names::llvm) {
if (config->callGraphProfileSort && name == section_names::cgProfile)
checkError(parseCallGraph(data, callGraph));
// ld64 does not appear to emit contents from sections within the __LLVM
// segment. Symbols within those sections point to bitcode metadata
// instead of actual symbols. Global symbols within those sections could
// have the same name without causing duplicate symbol errors. To avoid
// spurious duplicate symbol errors, we do not parse these sections.
// TODO: Evaluate whether the bitcode metadata is needed.
} else if (name == section_names::objCImageInfo &&
segname == segment_names::data) {
objCImageInfo = data;
} else {
if (name == section_names::addrSig)
addrSigSection = sections.back();
auto *isec = make<ConcatInputSection>(section, data, align);
if (isDebugSection(isec->getFlags()) &&
isec->getSegName() == segment_names::dwarf) {
// Instead of emitting DWARF sections, we emit STABS symbols to the
// object files that contain them. We filter them out early to avoid
// parsing their relocations unnecessarily.
debugSections.push_back(isec);
} else {
section.subsections.push_back({0, isec});
}
}
}
}
void ObjFile::splitEhFrames(ArrayRef<uint8_t> data, Section &ehFrameSection) {
EhReader reader(this, data, /*dataOff=*/0);
size_t off = 0;
while (off < reader.size()) {
uint64_t frameOff = off;
uint64_t length = reader.readLength(&off);
if (length == 0)
break;
uint64_t fullLength = length + (off - frameOff);
off += length;
// We hard-code an alignment of 1 here because we don't actually want our
// EH frames to be aligned to the section alignment. EH frame decoders don't
// expect this alignment. Moreover, each EH frame must start where the
// previous one ends, and where it ends is indicated by the length field.
// Unless we update the length field (troublesome), we should keep the
// alignment to 1.
// Note that we still want to preserve the alignment of the overall section,
// just not of the individual EH frames.
ehFrameSection.subsections.push_back(
{frameOff, make<ConcatInputSection>(ehFrameSection,
data.slice(frameOff, fullLength),
/*align=*/1)});
}
ehFrameSection.doneSplitting = true;
}
template <class T>
static Section *findContainingSection(const std::vector<Section *> §ions,
T *offset) {
static_assert(std::is_same<uint64_t, T>::value ||
std::is_same<uint32_t, T>::value,
"unexpected type for offset");
auto it = std::prev(llvm::upper_bound(
sections, *offset,
[](uint64_t value, const Section *sec) { return value < sec->addr; }));
*offset -= (*it)->addr;
return *it;
}
// Find the subsection corresponding to the greatest section offset that is <=
// that of the given offset.
//
// offset: an offset relative to the start of the original InputSection (before
// any subsection splitting has occurred). It will be updated to represent the
// same location as an offset relative to the start of the containing
// subsection.
template <class T>
static InputSection *findContainingSubsection(const Section §ion,
T *offset) {
static_assert(std::is_same<uint64_t, T>::value ||
std::is_same<uint32_t, T>::value,
"unexpected type for offset");
auto it = std::prev(llvm::upper_bound(
section.subsections, *offset,
[](uint64_t value, Subsection subsec) { return value < subsec.offset; }));
*offset -= it->offset;
return it->isec;
}
// Find a symbol at offset `off` within `isec`.
static Defined *findSymbolAtOffset(const ConcatInputSection *isec,
uint64_t off) {
auto it = llvm::lower_bound(isec->symbols, off, [](Defined *d, uint64_t off) {
return d->value < off;
});
// The offset should point at the exact address of a symbol (with no addend.)
if (it == isec->symbols.end() || (*it)->value != off) {
assert(isec->wasCoalesced);
return nullptr;
}
return *it;
}
template <class SectionHeader>
static bool validateRelocationInfo(InputFile *file, const SectionHeader &sec,
relocation_info rel) {
const RelocAttrs &relocAttrs = target->getRelocAttrs(rel.r_type);
bool valid = true;
auto message = [relocAttrs, file, sec, rel, &valid](const Twine &diagnostic) {
valid = false;
return (relocAttrs.name + " relocation " + diagnostic + " at offset " +
std::to_string(rel.r_address) + " of " + sec.segname + "," +
sec.sectname + " in " + toString(file))
.str();
};
if (!relocAttrs.hasAttr(RelocAttrBits::LOCAL) && !rel.r_extern)
error(message("must be extern"));
if (relocAttrs.hasAttr(RelocAttrBits::PCREL) != rel.r_pcrel)
error(message(Twine("must ") + (rel.r_pcrel ? "not " : "") +
"be PC-relative"));
if (isThreadLocalVariables(sec.flags) &&
!relocAttrs.hasAttr(RelocAttrBits::UNSIGNED))
error(message("not allowed in thread-local section, must be UNSIGNED"));
if (rel.r_length < 2 || rel.r_length > 3 ||
!relocAttrs.hasAttr(static_cast<RelocAttrBits>(1 << rel.r_length))) {
static SmallVector<StringRef, 4> widths{"0", "4", "8", "4 or 8"};
error(message("has width " + std::to_string(1 << rel.r_length) +
" bytes, but must be " +
widths[(static_cast<int>(relocAttrs.bits) >> 2) & 3] +
" bytes"));
}
return valid;
}
template <class SectionHeader>
void ObjFile::parseRelocations(ArrayRef<SectionHeader> sectionHeaders,
const SectionHeader &sec, Section §ion) {
auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
ArrayRef<relocation_info> relInfos(
reinterpret_cast<const relocation_info *>(buf + sec.reloff), sec.nreloc);
Subsections &subsections = section.subsections;
auto subsecIt = subsections.rbegin();
for (size_t i = 0; i < relInfos.size(); i++) {
// Paired relocations serve as Mach-O's method for attaching a
// supplemental datum to a primary relocation record. ELF does not
// need them because the *_RELOC_RELA records contain the extra
// addend field, vs. *_RELOC_REL which omit the addend.
//
// The {X86_64,ARM64}_RELOC_SUBTRACTOR record holds the subtrahend,
// and the paired *_RELOC_UNSIGNED record holds the minuend. The
// datum for each is a symbolic address. The result is the offset
// between two addresses.
//
// The ARM64_RELOC_ADDEND record holds the addend, and the paired
// ARM64_RELOC_BRANCH26 or ARM64_RELOC_PAGE21/PAGEOFF12 holds the
// base symbolic address.
//
// Note: X86 does not use *_RELOC_ADDEND because it can embed an addend into
// the instruction stream. On X86, a relocatable address field always
// occupies an entire contiguous sequence of byte(s), so there is no need to
// merge opcode bits with address bits. Therefore, it's easy and convenient
// to store addends in the instruction-stream bytes that would otherwise
// contain zeroes. By contrast, RISC ISAs such as ARM64 mix opcode bits with
// address bits so that bitwise arithmetic is necessary to extract and
// insert them. Storing addends in the instruction stream is possible, but
// inconvenient and more costly at link time.
relocation_info relInfo = relInfos[i];
bool isSubtrahend =
target->hasAttr(relInfo.r_type, RelocAttrBits::SUBTRAHEND);
int64_t pairedAddend = 0;
if (target->hasAttr(relInfo.r_type, RelocAttrBits::ADDEND)) {
pairedAddend = SignExtend64<24>(relInfo.r_symbolnum);
relInfo = relInfos[++i];
}
assert(i < relInfos.size());
if (!validateRelocationInfo(this, sec, relInfo))
continue;
if (relInfo.r_address & R_SCATTERED)
fatal("TODO: Scattered relocations not supported");
int64_t embeddedAddend = target->getEmbeddedAddend(mb, sec.offset, relInfo);
assert(!(embeddedAddend && pairedAddend));
int64_t totalAddend = pairedAddend + embeddedAddend;
Reloc r;
r.type = relInfo.r_type;
r.pcrel = relInfo.r_pcrel;
r.length = relInfo.r_length;
r.offset = relInfo.r_address;
if (relInfo.r_extern) {
r.referent = symbols[relInfo.r_symbolnum];
r.addend = isSubtrahend ? 0 : totalAddend;
} else {
assert(!isSubtrahend);
const SectionHeader &referentSecHead =
sectionHeaders[relInfo.r_symbolnum - 1];
uint64_t referentOffset;
if (relInfo.r_pcrel) {
// The implicit addend for pcrel section relocations is the pcrel offset
// in terms of the addresses in the input file. Here we adjust it so
// that it describes the offset from the start of the referent section.
// FIXME This logic was written around x86_64 behavior -- ARM64 doesn't
// have pcrel section relocations. We may want to factor this out into
// the arch-specific .cpp file.
assert(target->hasAttr(r.type, RelocAttrBits::BYTE4));
referentOffset = sec.addr + relInfo.r_address + 4 + totalAddend -
referentSecHead.addr;
} else {
// The addend for a non-pcrel relocation is its absolute address.
referentOffset = totalAddend - referentSecHead.addr;
}
r.referent = findContainingSubsection(*sections[relInfo.r_symbolnum - 1],
&referentOffset);
r.addend = referentOffset;
}
// Find the subsection that this relocation belongs to.
// Though not required by the Mach-O format, clang and gcc seem to emit
// relocations in order, so let's take advantage of it. However, ld64 emits
// unsorted relocations (in `-r` mode), so we have a fallback for that
// uncommon case.
InputSection *subsec;
while (subsecIt != subsections.rend() && subsecIt->offset > r.offset)
++subsecIt;
if (subsecIt == subsections.rend() ||
subsecIt->offset + subsecIt->isec->getSize() <= r.offset) {
subsec = findContainingSubsection(section, &r.offset);
// Now that we know the relocs are unsorted, avoid trying the 'fast path'
// for the other relocations.
subsecIt = subsections.rend();
} else {
subsec = subsecIt->isec;
r.offset -= subsecIt->offset;
}
subsec->relocs.push_back(r);
if (isSubtrahend) {
relocation_info minuendInfo = relInfos[++i];
// SUBTRACTOR relocations should always be followed by an UNSIGNED one
// attached to the same address.
assert(target->hasAttr(minuendInfo.r_type, RelocAttrBits::UNSIGNED) &&
relInfo.r_address == minuendInfo.r_address);
Reloc p;
p.type = minuendInfo.r_type;
if (minuendInfo.r_extern) {
p.referent = symbols[minuendInfo.r_symbolnum];
p.addend = totalAddend;
} else {
uint64_t referentOffset =
totalAddend - sectionHeaders[minuendInfo.r_symbolnum - 1].addr;
p.referent = findContainingSubsection(
*sections[minuendInfo.r_symbolnum - 1], &referentOffset);
p.addend = referentOffset;
}
subsec->relocs.push_back(p);
}
}
}
template <class NList>
static macho::Symbol *createDefined(const NList &sym, StringRef name,
InputSection *isec, uint64_t value,
uint64_t size, bool forceHidden) {
// Symbol scope is determined by sym.n_type & (N_EXT | N_PEXT):
// N_EXT: Global symbols. These go in the symbol table during the link,
// and also in the export table of the output so that the dynamic
// linker sees them.
// N_EXT | N_PEXT: Linkage unit (think: dylib) scoped. These go in the
// symbol table during the link so that duplicates are
// either reported (for non-weak symbols) or merged
// (for weak symbols), but they do not go in the export
// table of the output.
// N_PEXT: llvm-mc does not emit these, but `ld -r` (wherein ld64 emits
// object files) may produce them. LLD does not yet support -r.
// These are translation-unit scoped, identical to the `0` case.
// 0: Translation-unit scoped. These are not in the symbol table during
// link, and not in the export table of the output either.
bool isWeakDefCanBeHidden =
(sym.n_desc & (N_WEAK_DEF | N_WEAK_REF)) == (N_WEAK_DEF | N_WEAK_REF);
assert(!(sym.n_desc & N_ARM_THUMB_DEF) && "ARM32 arch is not supported");
if (sym.n_type & N_EXT) {
// -load_hidden makes us treat global symbols as linkage unit scoped.
// Duplicates are reported but the symbol does not go in the export trie.
bool isPrivateExtern = sym.n_type & N_PEXT || forceHidden;
// lld's behavior for merging symbols is slightly different from ld64:
// ld64 picks the winning symbol based on several criteria (see
// pickBetweenRegularAtoms() in ld64's SymbolTable.cpp), while lld
// just merges metadata and keeps the contents of the first symbol
// with that name (see SymbolTable::addDefined). For:
// * inline function F in a TU built with -fvisibility-inlines-hidden
// * and inline function F in another TU built without that flag
// ld64 will pick the one from the file built without
// -fvisibility-inlines-hidden.
// lld will instead pick the one listed first on the link command line and
// give it visibility as if the function was built without
// -fvisibility-inlines-hidden.
// If both functions have the same contents, this will have the same
// behavior. If not, it won't, but the input had an ODR violation in
// that case.
//
// Similarly, merging a symbol
// that's isPrivateExtern and not isWeakDefCanBeHidden with one
// that's not isPrivateExtern but isWeakDefCanBeHidden technically
// should produce one
// that's not isPrivateExtern but isWeakDefCanBeHidden. That matters
// with ld64's semantics, because it means the non-private-extern
// definition will continue to take priority if more private extern
// definitions are encountered. With lld's semantics there's no observable
// difference between a symbol that's isWeakDefCanBeHidden(autohide) or one
// that's privateExtern -- neither makes it into the dynamic symbol table,
// unless the autohide symbol is explicitly exported.
// But if a symbol is both privateExtern and autohide then it can't
// be exported.
// So we nullify the autohide flag when privateExtern is present
// and promote the symbol to privateExtern when it is not already.
if (isWeakDefCanBeHidden && isPrivateExtern)
isWeakDefCanBeHidden = false;
else if (isWeakDefCanBeHidden)
isPrivateExtern = true;
return symtab->addDefined(
name, isec->getFile(), isec, value, size, sym.n_desc & N_WEAK_DEF,
isPrivateExtern, sym.n_desc & REFERENCED_DYNAMICALLY,
sym.n_desc & N_NO_DEAD_STRIP, isWeakDefCanBeHidden);
}
bool includeInSymtab = !isPrivateLabel(name) && !isEhFrameSection(isec);
return make<Defined>(
name, isec->getFile(), isec, value, size, sym.n_desc & N_WEAK_DEF,
/*isExternal=*/false, /*isPrivateExtern=*/false, includeInSymtab,
sym.n_desc & REFERENCED_DYNAMICALLY, sym.n_desc & N_NO_DEAD_STRIP);
}
// Absolute symbols are defined symbols that do not have an associated
// InputSection. They cannot be weak.
template <class NList>
static macho::Symbol *createAbsolute(const NList &sym, InputFile *file,
StringRef name, bool forceHidden) {
assert(!(sym.n_desc & N_ARM_THUMB_DEF) && "ARM32 arch is not supported");
if (sym.n_type & N_EXT) {
bool isPrivateExtern = sym.n_type & N_PEXT || forceHidden;
return symtab->addDefined(name, file, nullptr, sym.n_value, /*size=*/0,
/*isWeakDef=*/false, isPrivateExtern,
/*isReferencedDynamically=*/false,
sym.n_desc & N_NO_DEAD_STRIP,
/*isWeakDefCanBeHidden=*/false);
}
return make<Defined>(name, file, nullptr, sym.n_value, /*size=*/0,
/*isWeakDef=*/false,
/*isExternal=*/false, /*isPrivateExtern=*/false,
/*includeInSymtab=*/true,
/*isReferencedDynamically=*/false,
sym.n_desc & N_NO_DEAD_STRIP);
}
template <class NList>
macho::Symbol *ObjFile::parseNonSectionSymbol(const NList &sym,
const char *strtab) {
StringRef name = StringRef(strtab + sym.n_strx);
uint8_t type = sym.n_type & N_TYPE;
bool isPrivateExtern = sym.n_type & N_PEXT || forceHidden;
switch (type) {
case N_UNDF:
return sym.n_value == 0
? symtab->addUndefined(name, this, sym.n_desc & N_WEAK_REF)
: symtab->addCommon(name, this, sym.n_value,
1 << GET_COMM_ALIGN(sym.n_desc),
isPrivateExtern);
case N_ABS:
return createAbsolute(sym, this, name, forceHidden);
case N_INDR: {
// Not much point in making local aliases -- relocs in the current file can
// just refer to the actual symbol itself. ld64 ignores these symbols too.
if (!(sym.n_type & N_EXT))
return nullptr;
StringRef aliasedName = StringRef(strtab + sym.n_value);
// isPrivateExtern is the only symbol flag that has an impact on the final
// aliased symbol.
auto *alias = make<AliasSymbol>(this, name, aliasedName, isPrivateExtern);
aliases.push_back(alias);
return alias;
}
case N_PBUD:
error("TODO: support symbols of type N_PBUD");
return nullptr;
case N_SECT:
llvm_unreachable(
"N_SECT symbols should not be passed to parseNonSectionSymbol");
default:
llvm_unreachable("invalid symbol type");
}
}
template <class NList> static bool isUndef(const NList &sym) {
return (sym.n_type & N_TYPE) == N_UNDF && sym.n_value == 0;
}
template <class LP>
void ObjFile::parseSymbols(ArrayRef<typename LP::section> sectionHeaders,
ArrayRef<typename LP::nlist> nList,
const char *strtab, bool subsectionsViaSymbols) {
using NList = typename LP::nlist;
// Groups indices of the symbols by the sections that contain them.
std::vector<std::vector<uint32_t>> symbolsBySection(sections.size());
symbols.resize(nList.size());
SmallVector<unsigned, 32> undefineds;
for (uint32_t i = 0; i < nList.size(); ++i) {
const NList &sym = nList[i];
// Ignore debug symbols for now.
// FIXME: may need special handling.
if (sym.n_type & N_STAB)
continue;
if ((sym.n_type & N_TYPE) == N_SECT) {
Subsections &subsections = sections[sym.n_sect - 1]->subsections;
// parseSections() may have chosen not to parse this section.
if (subsections.empty())
continue;
symbolsBySection[sym.n_sect - 1].push_back(i);
} else if (isUndef(sym)) {
undefineds.push_back(i);
} else {
symbols[i] = parseNonSectionSymbol(sym, strtab);
}
}
for (size_t i = 0; i < sections.size(); ++i) {
Subsections &subsections = sections[i]->subsections;
if (subsections.empty())
continue;
std::vector<uint32_t> &symbolIndices = symbolsBySection[i];
uint64_t sectionAddr = sectionHeaders[i].addr;
uint32_t sectionAlign = 1u << sectionHeaders[i].align;
// Some sections have already been split into subsections during
// parseSections(), so we simply need to match Symbols to the corresponding
// subsection here.
if (sections[i]->doneSplitting) {
for (size_t j = 0; j < symbolIndices.size(); ++j) {
const uint32_t symIndex = symbolIndices[j];
const NList &sym = nList[symIndex];
StringRef name = strtab + sym.n_strx;
uint64_t symbolOffset = sym.n_value - sectionAddr;
InputSection *isec =
findContainingSubsection(*sections[i], &symbolOffset);
if (symbolOffset != 0) {
error(toString(*sections[i]) + ": symbol " + name +
" at misaligned offset");
continue;
}
symbols[symIndex] =
createDefined(sym, name, isec, 0, isec->getSize(), forceHidden);
}
continue;
}
sections[i]->doneSplitting = true;
auto getSymName = [strtab](const NList& sym) -> StringRef {
return StringRef(strtab + sym.n_strx);
};
// Calculate symbol sizes and create subsections by splitting the sections
// along symbol boundaries.
// We populate subsections by repeatedly splitting the last (highest
// address) subsection.
llvm::stable_sort(symbolIndices, [&](uint32_t lhs, uint32_t rhs) {
// Put extern weak symbols after other symbols at the same address so
// that weak symbol coalescing works correctly. See
// SymbolTable::addDefined() for details.
if (nList[lhs].n_value == nList[rhs].n_value &&
nList[lhs].n_type & N_EXT && nList[rhs].n_type & N_EXT)
return !(nList[lhs].n_desc & N_WEAK_DEF) && (nList[rhs].n_desc & N_WEAK_DEF);
return nList[lhs].n_value < nList[rhs].n_value;
});
for (size_t j = 0; j < symbolIndices.size(); ++j) {
const uint32_t symIndex = symbolIndices[j];
const NList &sym = nList[symIndex];
StringRef name = getSymName(sym);
Subsection &subsec = subsections.back();
InputSection *isec = subsec.isec;
uint64_t subsecAddr = sectionAddr + subsec.offset;
size_t symbolOffset = sym.n_value - subsecAddr;
uint64_t symbolSize =
j + 1 < symbolIndices.size()
? nList[symbolIndices[j + 1]].n_value - sym.n_value
: isec->data.size() - symbolOffset;
// There are 4 cases where we do not need to create a new subsection:
// 1. If the input file does not use subsections-via-symbols.
// 2. Multiple symbols at the same address only induce one subsection.
// (The symbolOffset == 0 check covers both this case as well as
// the first loop iteration.)
// 3. Alternative entry points do not induce new subsections.
// 4. If we have a literal section (e.g. __cstring and __literal4).
if (!subsectionsViaSymbols || symbolOffset == 0 ||
sym.n_desc & N_ALT_ENTRY || !isa<ConcatInputSection>(isec)) {
isec->hasAltEntry = symbolOffset != 0;
symbols[symIndex] = createDefined(sym, name, isec, symbolOffset,
symbolSize, forceHidden);
continue;
}
auto *concatIsec = cast<ConcatInputSection>(isec);
auto *nextIsec = make<ConcatInputSection>(*concatIsec);
nextIsec->wasCoalesced = false;
if (isZeroFill(isec->getFlags())) {
// Zero-fill sections have NULL data.data() non-zero data.size()
nextIsec->data = {nullptr, isec->data.size() - symbolOffset};
isec->data = {nullptr, symbolOffset};
} else {
nextIsec->data = isec->data.slice(symbolOffset);
isec->data = isec->data.slice(0, symbolOffset);
}
// By construction, the symbol will be at offset zero in the new
// subsection.
symbols[symIndex] = createDefined(sym, name, nextIsec, /*value=*/0,
symbolSize, forceHidden);
// TODO: ld64 appears to preserve the original alignment as well as each
// subsection's offset from the last aligned address. We should consider
// emulating that behavior.
nextIsec->align = MinAlign(sectionAlign, sym.n_value);
subsections.push_back({sym.n_value - sectionAddr, nextIsec});
}
}
// Undefined symbols can trigger recursive fetch from Archives due to
// LazySymbols. Process defined symbols first so that the relative order
// between a defined symbol and an undefined symbol does not change the
// symbol resolution behavior. In addition, a set of interconnected symbols
// will all be resolved to the same file, instead of being resolved to
// different files.
for (unsigned i : undefineds)
symbols[i] = parseNonSectionSymbol(nList[i], strtab);
}
OpaqueFile::OpaqueFile(MemoryBufferRef mb, StringRef segName,
StringRef sectName)
: InputFile(OpaqueKind, mb) {
const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
ArrayRef<uint8_t> data = {buf, mb.getBufferSize()};
sections.push_back(make<Section>(/*file=*/this, segName.take_front(16),
sectName.take_front(16),
/*flags=*/0, /*addr=*/0));
Section §ion = *sections.back();
ConcatInputSection *isec = make<ConcatInputSection>(section, data);
isec->live = true;
section.subsections.push_back({0, isec});
}
template <class LP>
void ObjFile::parseLinkerOptions(SmallVectorImpl<StringRef> &LCLinkerOptions) {
using Header = typename LP::mach_header;
auto *hdr = reinterpret_cast<const Header *>(mb.getBufferStart());
for (auto *cmd : findCommands<linker_option_command>(hdr, LC_LINKER_OPTION)) {
StringRef data{reinterpret_cast<const char *>(cmd + 1),
cmd->cmdsize - sizeof(linker_option_command)};
parseLCLinkerOption(LCLinkerOptions, this, cmd->count, data);
}
}
SmallVector<StringRef> macho::unprocessedLCLinkerOptions;
ObjFile::ObjFile(MemoryBufferRef mb, uint32_t modTime, StringRef archiveName,
bool lazy, bool forceHidden, bool compatArch,
bool builtFromBitcode)
: InputFile(ObjKind, mb, lazy), modTime(modTime), forceHidden(forceHidden),
builtFromBitcode(builtFromBitcode) {
this->archiveName = std::string(archiveName);
this->compatArch = compatArch;
if (lazy) {
if (target->wordSize == 8)
parseLazy<LP64>();
else
parseLazy<ILP32>();
} else {
if (target->wordSize == 8)
parse<LP64>();
else
parse<ILP32>();
}
}
template <class LP> void ObjFile::parse() {
using Header = typename LP::mach_header;
using SegmentCommand = typename LP::segment_command;
using SectionHeader = typename LP::section;
using NList = typename LP::nlist;
auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
auto *hdr = reinterpret_cast<const Header *>(mb.getBufferStart());
// If we've already checked the arch, then don't need to check again.
if (!compatArch)
return;
if (!(compatArch = compatWithTargetArch(this, hdr)))
return;