1//===- InputFiles.cpp -----------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains functions to parse Mach-O object files. In this comment,
10// we describe the Mach-O file structure and how we parse it.
11//
12// Mach-O is not very different from ELF or COFF. The notion of symbols,
13// sections and relocations exists in Mach-O as it does in ELF and COFF.
14//
15// Perhaps the notion that is new to those who know ELF/COFF is "subsections".
16// In ELF/COFF, sections are an atomic unit of data copied from input files to
17// output files. When we merge or garbage-collect sections, we treat each
18// section as an atomic unit. In Mach-O, that's not the case. Sections can
19// consist of multiple subsections, and subsections are a unit of merging and
20// garbage-collecting. Therefore, Mach-O's subsections are more similar to
21// ELF/COFF's sections than Mach-O's sections are.
22//
23// A section can have multiple symbols. A symbol that does not have the
24// N_ALT_ENTRY attribute indicates a beginning of a subsection. Therefore, by
25// definition, a symbol is always present at the beginning of each subsection. A
26// symbol with N_ALT_ENTRY attribute does not start a new subsection and can
27// point to a middle of a subsection.
28//
29// The notion of subsections also affects how relocations are represented in
30// Mach-O. All references within a section need to be explicitly represented as
31// relocations if they refer to different subsections, because we obviously need
32// to fix up addresses if subsections are laid out in an output file differently
33// than they were in object files. To represent that, Mach-O relocations can
34// refer to an unnamed location via its address. Scattered relocations (those
35// with the R_SCATTERED bit set) always refer to unnamed locations.
36// Non-scattered relocations refer to an unnamed location if r_extern is not set
37// and r_symbolnum is zero.
38//
39// Without the above differences, I think you can use your knowledge about ELF
40// and COFF for Mach-O.
41//
42//===----------------------------------------------------------------------===//
43
44#include "InputFiles.h"
45#include "Config.h"
46#include "Driver.h"
47#include "Dwarf.h"
48#include "EhFrame.h"
49#include "ExportTrie.h"
50#include "InputSection.h"
51#include "ObjC.h"
52#include "OutputSection.h"
53#include "OutputSegment.h"
54#include "SymbolTable.h"
55#include "Symbols.h"
56#include "SyntheticSections.h"
57#include "Target.h"
58
59#include "lld/Common/CommonLinkerContext.h"
60#include "lld/Common/DWARF.h"
61#include "lld/Common/Reproduce.h"
62#include "llvm/ADT/iterator.h"
63#include "llvm/BinaryFormat/MachO.h"
64#include "llvm/LTO/LTO.h"
65#include "llvm/Support/BinaryStreamReader.h"
66#include "llvm/Support/Endian.h"
67#include "llvm/Support/MemoryBuffer.h"
68#include "llvm/Support/Path.h"
69#include "llvm/Support/TarWriter.h"
70#include "llvm/Support/TimeProfiler.h"
71#include "llvm/TextAPI/Architecture.h"
72#include "llvm/TextAPI/InterfaceFile.h"
73
74#include <optional>
75#include <type_traits>
76
77using namespace llvm;
78using namespace llvm::MachO;
79using namespace llvm::support::endian;
80using namespace llvm::sys;
81using namespace lld;
82using namespace lld::macho;
83
84// Returns "<internal>", "foo.a(bar.o)", or "baz.o".
85std::string lld::toString(const InputFile *f) {
86 if (!f)
87 return "<internal>";
88
89 // Multiple dylibs can be defined in one .tbd file.
90 if (const auto *dylibFile = dyn_cast<DylibFile>(Val: f))
91 if (f->getName().ends_with(Suffix: ".tbd"))
92 return (f->getName() + "(" + dylibFile->installName + ")").str();
93
94 if (f->archiveName.empty())
95 return std::string(f->getName());
96 return (f->archiveName + "(" + path::filename(path: f->getName()) + ")").str();
97}
98
99std::string lld::toString(const Section &sec) {
100 return (toString(f: sec.file) + ":(" + sec.name + ")").str();
101}
102
103SetVector<InputFile *> macho::inputFiles;
104std::unique_ptr<TarWriter> macho::tar;
105int InputFile::idCount = 0;
106
107static VersionTuple decodeVersion(uint32_t version) {
108 unsigned major = version >> 16;
109 unsigned minor = (version >> 8) & 0xffu;
110 unsigned subMinor = version & 0xffu;
111 return VersionTuple(major, minor, subMinor);
112}
113
114static std::vector<PlatformInfo> getPlatformInfos(const InputFile *input) {
115 if (!isa<ObjFile>(Val: input) && !isa<DylibFile>(Val: input))
116 return {};
117
118 const char *hdr = input->mb.getBufferStart();
119
120 // "Zippered" object files can have multiple LC_BUILD_VERSION load commands.
121 std::vector<PlatformInfo> platformInfos;
122 for (auto *cmd : findCommands<build_version_command>(anyHdr: hdr, types: LC_BUILD_VERSION)) {
123 PlatformInfo info;
124 info.target.Platform = static_cast<PlatformType>(cmd->platform);
125 info.target.MinDeployment = decodeVersion(version: cmd->minos);
126 platformInfos.emplace_back(args: std::move(info));
127 }
128 for (auto *cmd : findCommands<version_min_command>(
129 anyHdr: hdr, types: LC_VERSION_MIN_MACOSX, types: LC_VERSION_MIN_IPHONEOS,
130 types: LC_VERSION_MIN_TVOS, types: LC_VERSION_MIN_WATCHOS)) {
131 PlatformInfo info;
132 switch (cmd->cmd) {
133 case LC_VERSION_MIN_MACOSX:
134 info.target.Platform = PLATFORM_MACOS;
135 break;
136 case LC_VERSION_MIN_IPHONEOS:
137 info.target.Platform = PLATFORM_IOS;
138 break;
139 case LC_VERSION_MIN_TVOS:
140 info.target.Platform = PLATFORM_TVOS;
141 break;
142 case LC_VERSION_MIN_WATCHOS:
143 info.target.Platform = PLATFORM_WATCHOS;
144 break;
145 }
146 info.target.MinDeployment = decodeVersion(version: cmd->version);
147 platformInfos.emplace_back(args: std::move(info));
148 }
149
150 return platformInfos;
151}
152
153static bool checkCompatibility(const InputFile *input) {
154 std::vector<PlatformInfo> platformInfos = getPlatformInfos(input);
155 if (platformInfos.empty())
156 return true;
157
158 auto it = find_if(Range&: platformInfos, P: [&](const PlatformInfo &info) {
159 return removeSimulator(platform: info.target.Platform) ==
160 removeSimulator(platform: config->platform());
161 });
162 if (it == platformInfos.end()) {
163 std::string platformNames;
164 raw_string_ostream os(platformNames);
165 interleave(
166 c: platformInfos, os,
167 each_fn: [&](const PlatformInfo &info) {
168 os << getPlatformName(Platform: info.target.Platform);
169 },
170 separator: "/");
171 error(msg: toString(f: input) + " has platform " + platformNames +
172 Twine(", which is different from target platform ") +
173 getPlatformName(Platform: config->platform()));
174 return false;
175 }
176
177 if (it->target.MinDeployment > config->platformInfo.target.MinDeployment)
178 warn(msg: toString(f: input) + " has version " +
179 it->target.MinDeployment.getAsString() +
180 ", which is newer than target minimum of " +
181 config->platformInfo.target.MinDeployment.getAsString());
182
183 return true;
184}
185
186template <class Header>
187static bool compatWithTargetArch(const InputFile *file, const Header *hdr) {
188 uint32_t cpuType;
189 std::tie(args&: cpuType, args: std::ignore) = getCPUTypeFromArchitecture(Arch: config->arch());
190
191 if (hdr->cputype != cpuType) {
192 Architecture arch =
193 getArchitectureFromCpuType(hdr->cputype, hdr->cpusubtype);
194 auto msg = config->errorForArchMismatch
195 ? static_cast<void (*)(const Twine &)>(error)
196 : warn;
197
198 msg(toString(f: file) + " has architecture " + getArchitectureName(Arch: arch) +
199 " which is incompatible with target architecture " +
200 getArchitectureName(Arch: config->arch()));
201 return false;
202 }
203
204 return checkCompatibility(input: file);
205}
206
207// This cache mostly exists to store system libraries (and .tbds) as they're
208// loaded, rather than the input archives, which are already cached at a higher
209// level, and other files like the filelist that are only read once.
210// Theoretically this caching could be more efficient by hoisting it, but that
211// would require altering many callers to track the state.
212DenseMap<CachedHashStringRef, MemoryBufferRef> macho::cachedReads;
213// Open a given file path and return it as a memory-mapped file.
214std::optional<MemoryBufferRef> macho::readFile(StringRef path) {
215 CachedHashStringRef key(path);
216 auto entry = cachedReads.find(Val: key);
217 if (entry != cachedReads.end())
218 return entry->second;
219
220 ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr =
221 MemoryBuffer::getFile(Filename: path, IsText: false, /*RequiresNullTerminator=*/false);
222 if (std::error_code ec = mbOrErr.getError()) {
223 error(msg: "cannot open " + path + ": " + ec.message());
224 return std::nullopt;
225 }
226
227 std::unique_ptr<MemoryBuffer> &mb = *mbOrErr;
228 MemoryBufferRef mbref = mb->getMemBufferRef();
229 make<std::unique_ptr<MemoryBuffer>>(args: std::move(mb)); // take mb ownership
230
231 // If this is a regular non-fat file, return it.
232 const char *buf = mbref.getBufferStart();
233 const auto *hdr = reinterpret_cast<const fat_header *>(buf);
234 if (mbref.getBufferSize() < sizeof(uint32_t) ||
235 read32be(P: &hdr->magic) != FAT_MAGIC) {
236 if (tar)
237 tar->append(Path: relativeToRoot(path), Data: mbref.getBuffer());
238 return cachedReads[key] = mbref;
239 }
240
241 llvm::BumpPtrAllocator &bAlloc = lld::bAlloc();
242
243 // Object files and archive files may be fat files, which contain multiple
244 // real files for different CPU ISAs. Here, we search for a file that matches
245 // with the current link target and returns it as a MemoryBufferRef.
246 const auto *arch = reinterpret_cast<const fat_arch *>(buf + sizeof(*hdr));
247 auto getArchName = [](uint32_t cpuType, uint32_t cpuSubtype) {
248 return getArchitectureName(Arch: getArchitectureFromCpuType(CPUType: cpuType, CPUSubType: cpuSubtype));
249 };
250
251 std::vector<StringRef> archs;
252 for (uint32_t i = 0, n = read32be(P: &hdr->nfat_arch); i < n; ++i) {
253 if (reinterpret_cast<const char *>(arch + i + 1) >
254 buf + mbref.getBufferSize()) {
255 error(msg: path + ": fat_arch struct extends beyond end of file");
256 return std::nullopt;
257 }
258
259 uint32_t cpuType = read32be(P: &arch[i].cputype);
260 uint32_t cpuSubtype =
261 read32be(P: &arch[i].cpusubtype) & ~MachO::CPU_SUBTYPE_MASK;
262
263 // FIXME: LD64 has a more complex fallback logic here.
264 // Consider implementing that as well?
265 if (cpuType != static_cast<uint32_t>(target->cpuType) ||
266 cpuSubtype != target->cpuSubtype) {
267 archs.emplace_back(args: getArchName(cpuType, cpuSubtype));
268 continue;
269 }
270
271 uint32_t offset = read32be(P: &arch[i].offset);
272 uint32_t size = read32be(P: &arch[i].size);
273 if (offset + size > mbref.getBufferSize())
274 error(msg: path + ": slice extends beyond end of file");
275 if (tar)
276 tar->append(Path: relativeToRoot(path), Data: mbref.getBuffer());
277 return cachedReads[key] = MemoryBufferRef(StringRef(buf + offset, size),
278 path.copy(A&: bAlloc));
279 }
280
281 auto targetArchName = getArchName(target->cpuType, target->cpuSubtype);
282 warn(msg: path + ": ignoring file because it is universal (" + join(R&: archs, Separator: ",") +
283 ") but does not contain the " + targetArchName + " architecture");
284 return std::nullopt;
285}
286
287InputFile::InputFile(Kind kind, const InterfaceFile &interface)
288 : id(idCount++), fileKind(kind), name(saver().save(S: interface.getPath())) {}
289
290// Some sections comprise of fixed-size records, so instead of splitting them at
291// symbol boundaries, we split them based on size. Records are distinct from
292// literals in that they may contain references to other sections, instead of
293// being leaf nodes in the InputSection graph.
294//
295// Note that "record" is a term I came up with. In contrast, "literal" is a term
296// used by the Mach-O format.
297static std::optional<size_t> getRecordSize(StringRef segname, StringRef name) {
298 if (name == section_names::compactUnwind) {
299 if (segname == segment_names::ld)
300 return target->wordSize == 8 ? 32 : 20;
301 }
302 if (!config->dedupStrings)
303 return {};
304
305 if (name == section_names::cfString && segname == segment_names::data)
306 return target->wordSize == 8 ? 32 : 16;
307
308 if (config->icfLevel == ICFLevel::none)
309 return {};
310
311 if (name == section_names::objcClassRefs && segname == segment_names::data)
312 return target->wordSize;
313
314 if (name == section_names::objcSelrefs && segname == segment_names::data)
315 return target->wordSize;
316 return {};
317}
318
319static Error parseCallGraph(ArrayRef<uint8_t> data,
320 std::vector<CallGraphEntry> &callGraph) {
321 TimeTraceScope timeScope("Parsing call graph section");
322 BinaryStreamReader reader(data, llvm::endianness::little);
323 while (!reader.empty()) {
324 uint32_t fromIndex, toIndex;
325 uint64_t count;
326 if (Error err = reader.readInteger(Dest&: fromIndex))
327 return err;
328 if (Error err = reader.readInteger(Dest&: toIndex))
329 return err;
330 if (Error err = reader.readInteger(Dest&: count))
331 return err;
332 callGraph.emplace_back(args&: fromIndex, args&: toIndex, args&: count);
333 }
334 return Error::success();
335}
336
337// Parse the sequence of sections within a single LC_SEGMENT(_64).
338// Split each section into subsections.
339template <class SectionHeader>
340void ObjFile::parseSections(ArrayRef<SectionHeader> sectionHeaders) {
341 sections.reserve(n: sectionHeaders.size());
342 auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
343
344 for (const SectionHeader &sec : sectionHeaders) {
345 StringRef name =
346 StringRef(sec.sectname, strnlen(sec.sectname, sizeof(sec.sectname)));
347 StringRef segname =
348 StringRef(sec.segname, strnlen(sec.segname, sizeof(sec.segname)));
349 sections.push_back(make<Section>(this, segname, name, sec.flags, sec.addr));
350 if (sec.align >= 32) {
351 error("alignment " + std::to_string(sec.align) + " of section " + name +
352 " is too large");
353 continue;
354 }
355 Section &section = *sections.back();
356 uint32_t align = 1 << sec.align;
357 ArrayRef<uint8_t> data = {isZeroFill(sec.flags) ? nullptr
358 : buf + sec.offset,
359 static_cast<size_t>(sec.size)};
360
361 auto splitRecords = [&](size_t recordSize) -> void {
362 if (data.empty())
363 return;
364 Subsections &subsections = section.subsections;
365 subsections.reserve(n: data.size() / recordSize);
366 for (uint64_t off = 0; off < data.size(); off += recordSize) {
367 auto *isec = make<ConcatInputSection>(
368 args&: section, args: data.slice(N: off, M: std::min(a: data.size(), b: recordSize)), args&: align);
369 subsections.push_back(x: {.offset: off, .isec: isec});
370 }
371 section.doneSplitting = true;
372 };
373
374 if (sectionType(sec.flags) == S_CSTRING_LITERALS) {
375 if (sec.nreloc)
376 fatal(toString(f: this) + ": " + sec.segname + "," + sec.sectname +
377 " contains relocations, which is unsupported");
378 bool dedupLiterals =
379 name == section_names::objcMethname || config->dedupStrings;
380 InputSection *isec =
381 make<CStringInputSection>(args&: section, args&: data, args&: align, args&: dedupLiterals);
382 // FIXME: parallelize this?
383 cast<CStringInputSection>(Val: isec)->splitIntoPieces();
384 section.subsections.push_back(x: {.offset: 0, .isec: isec});
385 } else if (isWordLiteralSection(sec.flags)) {
386 if (sec.nreloc)
387 fatal(toString(f: this) + ": " + sec.segname + "," + sec.sectname +
388 " contains relocations, which is unsupported");
389 InputSection *isec = make<WordLiteralInputSection>(args&: section, args&: data, args&: align);
390 section.subsections.push_back(x: {.offset: 0, .isec: isec});
391 } else if (auto recordSize = getRecordSize(segname, name)) {
392 splitRecords(*recordSize);
393 } else if (name == section_names::ehFrame &&
394 segname == segment_names::text) {
395 splitEhFrames(dataArr: data, ehFrameSection&: *sections.back());
396 } else if (segname == segment_names::llvm) {
397 if (config->callGraphProfileSort && name == section_names::cgProfile)
398 checkError(e: parseCallGraph(data, callGraph));
399 // ld64 does not appear to emit contents from sections within the __LLVM
400 // segment. Symbols within those sections point to bitcode metadata
401 // instead of actual symbols. Global symbols within those sections could
402 // have the same name without causing duplicate symbol errors. To avoid
403 // spurious duplicate symbol errors, we do not parse these sections.
404 // TODO: Evaluate whether the bitcode metadata is needed.
405 } else if (name == section_names::objCImageInfo &&
406 segname == segment_names::data) {
407 objCImageInfo = data;
408 } else {
409 if (name == section_names::addrSig)
410 addrSigSection = sections.back();
411
412 auto *isec = make<ConcatInputSection>(args&: section, args&: data, args&: align);
413 if (isDebugSection(flags: isec->getFlags()) &&
414 isec->getSegName() == segment_names::dwarf) {
415 // Instead of emitting DWARF sections, we emit STABS symbols to the
416 // object files that contain them. We filter them out early to avoid
417 // parsing their relocations unnecessarily.
418 debugSections.push_back(x: isec);
419 } else {
420 section.subsections.push_back(x: {.offset: 0, .isec: isec});
421 }
422 }
423 }
424}
425
426void ObjFile::splitEhFrames(ArrayRef<uint8_t> data, Section &ehFrameSection) {
427 EhReader reader(this, data, /*dataOff=*/0);
428 size_t off = 0;
429 while (off < reader.size()) {
430 uint64_t frameOff = off;
431 uint64_t length = reader.readLength(off: &off);
432 if (length == 0)
433 break;
434 uint64_t fullLength = length + (off - frameOff);
435 off += length;
436 // We hard-code an alignment of 1 here because we don't actually want our
437 // EH frames to be aligned to the section alignment. EH frame decoders don't
438 // expect this alignment. Moreover, each EH frame must start where the
439 // previous one ends, and where it ends is indicated by the length field.
440 // Unless we update the length field (troublesome), we should keep the
441 // alignment to 1.
442 // Note that we still want to preserve the alignment of the overall section,
443 // just not of the individual EH frames.
444 ehFrameSection.subsections.push_back(
445 x: {.offset: frameOff, .isec: make<ConcatInputSection>(args&: ehFrameSection,
446 args: data.slice(N: frameOff, M: fullLength),
447 /*align=*/args: 1)});
448 }
449 ehFrameSection.doneSplitting = true;
450}
451
452template <class T>
453static Section *findContainingSection(const std::vector<Section *> &sections,
454 T *offset) {
455 static_assert(std::is_same<uint64_t, T>::value ||
456 std::is_same<uint32_t, T>::value,
457 "unexpected type for offset");
458 auto it = std::prev(llvm::upper_bound(
459 sections, *offset,
460 [](uint64_t value, const Section *sec) { return value < sec->addr; }));
461 *offset -= (*it)->addr;
462 return *it;
463}
464
465// Find the subsection corresponding to the greatest section offset that is <=
466// that of the given offset.
467//
468// offset: an offset relative to the start of the original InputSection (before
469// any subsection splitting has occurred). It will be updated to represent the
470// same location as an offset relative to the start of the containing
471// subsection.
472template <class T>
473static InputSection *findContainingSubsection(const Section &section,
474 T *offset) {
475 static_assert(std::is_same<uint64_t, T>::value ||
476 std::is_same<uint32_t, T>::value,
477 "unexpected type for offset");
478 auto it = std::prev(llvm::upper_bound(
479 section.subsections, *offset,
480 [](uint64_t value, Subsection subsec) { return value < subsec.offset; }));
481 *offset -= it->offset;
482 return it->isec;
483}
484
485// Find a symbol at offset `off` within `isec`.
486static Defined *findSymbolAtOffset(const ConcatInputSection *isec,
487 uint64_t off) {
488 auto it = llvm::lower_bound(Range: isec->symbols, Value&: off, C: [](Defined *d, uint64_t off) {
489 return d->value < off;
490 });
491 // The offset should point at the exact address of a symbol (with no addend.)
492 if (it == isec->symbols.end() || (*it)->value != off) {
493 assert(isec->wasCoalesced);
494 return nullptr;
495 }
496 return *it;
497}
498
499template <class SectionHeader>
500static bool validateRelocationInfo(InputFile *file, const SectionHeader &sec,
501 relocation_info rel) {
502 const RelocAttrs &relocAttrs = target->getRelocAttrs(type: rel.r_type);
503 bool valid = true;
504 auto message = [relocAttrs, file, sec, rel, &valid](const Twine &diagnostic) {
505 valid = false;
506 return (relocAttrs.name + " relocation " + diagnostic + " at offset " +
507 std::to_string(val: rel.r_address) + " of " + sec.segname + "," +
508 sec.sectname + " in " + toString(f: file))
509 .str();
510 };
511
512 if (!relocAttrs.hasAttr(b: RelocAttrBits::LOCAL) && !rel.r_extern)
513 error(message("must be extern"));
514 if (relocAttrs.hasAttr(b: RelocAttrBits::PCREL) != rel.r_pcrel)
515 error(message(Twine("must ") + (rel.r_pcrel ? "not " : "") +
516 "be PC-relative"));
517 if (isThreadLocalVariables(sec.flags) &&
518 !relocAttrs.hasAttr(b: RelocAttrBits::UNSIGNED))
519 error(message("not allowed in thread-local section, must be UNSIGNED"));
520 if (!relocAttrs.hasAttr(b: static_cast<RelocAttrBits>(1 << rel.r_length))) {
521 error(message("has invalid width of " + std::to_string(val: 1 << rel.r_length) +
522 " bytes"));
523 }
524 return valid;
525}
526
527template <class SectionHeader>
528void ObjFile::parseRelocations(ArrayRef<SectionHeader> sectionHeaders,
529 const SectionHeader &sec, Section &section) {
530 auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
531 ArrayRef<relocation_info> relInfos(
532 reinterpret_cast<const relocation_info *>(buf + sec.reloff), sec.nreloc);
533
534 Subsections &subsections = section.subsections;
535 auto subsecIt = subsections.rbegin();
536 for (size_t i = 0; i < relInfos.size(); i++) {
537 // Paired relocations serve as Mach-O's method for attaching a
538 // supplemental datum to a primary relocation record. ELF does not
539 // need them because the *_RELOC_RELA records contain the extra
540 // addend field, vs. *_RELOC_REL which omit the addend.
541 //
542 // The {X86_64,ARM64}_RELOC_SUBTRACTOR record holds the subtrahend,
543 // and the paired *_RELOC_UNSIGNED record holds the minuend. The
544 // datum for each is a symbolic address. The result is the offset
545 // between two addresses.
546 //
547 // The ARM64_RELOC_ADDEND record holds the addend, and the paired
548 // ARM64_RELOC_BRANCH26 or ARM64_RELOC_PAGE21/PAGEOFF12 holds the
549 // base symbolic address.
550 //
551 // Note: X86 does not use *_RELOC_ADDEND because it can embed an addend into
552 // the instruction stream. On X86, a relocatable address field always
553 // occupies an entire contiguous sequence of byte(s), so there is no need to
554 // merge opcode bits with address bits. Therefore, it's easy and convenient
555 // to store addends in the instruction-stream bytes that would otherwise
556 // contain zeroes. By contrast, RISC ISAs such as ARM64 mix opcode bits with
557 // address bits so that bitwise arithmetic is necessary to extract and
558 // insert them. Storing addends in the instruction stream is possible, but
559 // inconvenient and more costly at link time.
560
561 relocation_info relInfo = relInfos[i];
562 bool isSubtrahend =
563 target->hasAttr(type: relInfo.r_type, bit: RelocAttrBits::SUBTRAHEND);
564 int64_t pairedAddend = 0;
565 if (target->hasAttr(type: relInfo.r_type, bit: RelocAttrBits::ADDEND)) {
566 pairedAddend = SignExtend64<24>(x: relInfo.r_symbolnum);
567 relInfo = relInfos[++i];
568 }
569 assert(i < relInfos.size());
570 if (!validateRelocationInfo(this, sec, relInfo))
571 continue;
572 if (relInfo.r_address & R_SCATTERED)
573 fatal(msg: "TODO: Scattered relocations not supported");
574
575 int64_t embeddedAddend = target->getEmbeddedAddend(mb, offset: sec.offset, relInfo);
576 assert(!(embeddedAddend && pairedAddend));
577 int64_t totalAddend = pairedAddend + embeddedAddend;
578 Relocation r;
579 r.type = relInfo.r_type;
580 r.pcrel = relInfo.r_pcrel;
581 r.length = relInfo.r_length;
582 r.offset = relInfo.r_address;
583 if (relInfo.r_extern) {
584 r.referent = symbols[relInfo.r_symbolnum];
585 r.addend = isSubtrahend ? 0 : totalAddend;
586 } else {
587 assert(!isSubtrahend);
588 const SectionHeader &referentSecHead =
589 sectionHeaders[relInfo.r_symbolnum - 1];
590 uint64_t referentOffset;
591 if (relInfo.r_pcrel) {
592 // The implicit addend for pcrel section relocations is the pcrel offset
593 // in terms of the addresses in the input file. Here we adjust it so
594 // that it describes the offset from the start of the referent section.
595 // FIXME This logic was written around x86_64 behavior -- ARM64 doesn't
596 // have pcrel section relocations. We may want to factor this out into
597 // the arch-specific .cpp file.
598 referentOffset = sec.addr + relInfo.r_address +
599 (1ull << relInfo.r_length) + totalAddend -
600 referentSecHead.addr;
601 } else {
602 // The addend for a non-pcrel relocation is its absolute address.
603 referentOffset = totalAddend - referentSecHead.addr;
604 }
605 r.referent = findContainingSubsection(section: *sections[relInfo.r_symbolnum - 1],
606 offset: &referentOffset);
607 r.addend = referentOffset;
608 }
609
610 // Find the subsection that this relocation belongs to.
611 // Though not required by the Mach-O format, clang and gcc seem to emit
612 // relocations in order, so let's take advantage of it. However, ld64 emits
613 // unsorted relocations (in `-r` mode), so we have a fallback for that
614 // uncommon case.
615 InputSection *subsec;
616 while (subsecIt != subsections.rend() && subsecIt->offset > r.offset)
617 ++subsecIt;
618 if (subsecIt == subsections.rend() ||
619 subsecIt->offset + subsecIt->isec->getSize() <= r.offset) {
620 subsec = findContainingSubsection(section, offset: &r.offset);
621 // Now that we know the relocs are unsorted, avoid trying the 'fast path'
622 // for the other relocations.
623 subsecIt = subsections.rend();
624 } else {
625 subsec = subsecIt->isec;
626 r.offset -= subsecIt->offset;
627 }
628 subsec->relocs.push_back(x: r);
629
630 if (isSubtrahend) {
631 relocation_info minuendInfo = relInfos[++i];
632 // SUBTRACTOR relocations should always be followed by an UNSIGNED one
633 // attached to the same address.
634 assert(target->hasAttr(minuendInfo.r_type, RelocAttrBits::UNSIGNED) &&
635 relInfo.r_address == minuendInfo.r_address);
636 Relocation p;
637 p.type = minuendInfo.r_type;
638 if (minuendInfo.r_extern) {
639 p.referent = symbols[minuendInfo.r_symbolnum];
640 p.addend = totalAddend;
641 } else {
642 uint64_t referentOffset =
643 totalAddend - sectionHeaders[minuendInfo.r_symbolnum - 1].addr;
644 p.referent = findContainingSubsection(
645 section: *sections[minuendInfo.r_symbolnum - 1], offset: &referentOffset);
646 p.addend = referentOffset;
647 }
648 subsec->relocs.push_back(x: p);
649 }
650 }
651}
652
653template <class NList>
654static macho::Symbol *createDefined(const NList &sym, StringRef name,
655 InputSection *isec, uint64_t value,
656 uint64_t size, bool forceHidden) {
657 // Symbol scope is determined by sym.n_type & (N_EXT | N_PEXT):
658 // N_EXT: Global symbols. These go in the symbol table during the link,
659 // and also in the export table of the output so that the dynamic
660 // linker sees them.
661 // N_EXT | N_PEXT: Linkage unit (think: dylib) scoped. These go in the
662 // symbol table during the link so that duplicates are
663 // either reported (for non-weak symbols) or merged
664 // (for weak symbols), but they do not go in the export
665 // table of the output.
666 // N_PEXT: llvm-mc does not emit these, but `ld -r` (wherein ld64 emits
667 // object files) may produce them. LLD does not yet support -r.
668 // These are translation-unit scoped, identical to the `0` case.
669 // 0: Translation-unit scoped. These are not in the symbol table during
670 // link, and not in the export table of the output either.
671 bool isWeakDefCanBeHidden =
672 (sym.n_desc & (N_WEAK_DEF | N_WEAK_REF)) == (N_WEAK_DEF | N_WEAK_REF);
673
674 assert(!(sym.n_desc & N_ARM_THUMB_DEF) && "ARM32 arch is not supported");
675
676 if (sym.n_type & N_EXT) {
677 // -load_hidden makes us treat global symbols as linkage unit scoped.
678 // Duplicates are reported but the symbol does not go in the export trie.
679 bool isPrivateExtern = sym.n_type & N_PEXT || forceHidden;
680
681 // lld's behavior for merging symbols is slightly different from ld64:
682 // ld64 picks the winning symbol based on several criteria (see
683 // pickBetweenRegularAtoms() in ld64's SymbolTable.cpp), while lld
684 // just merges metadata and keeps the contents of the first symbol
685 // with that name (see SymbolTable::addDefined). For:
686 // * inline function F in a TU built with -fvisibility-inlines-hidden
687 // * and inline function F in another TU built without that flag
688 // ld64 will pick the one from the file built without
689 // -fvisibility-inlines-hidden.
690 // lld will instead pick the one listed first on the link command line and
691 // give it visibility as if the function was built without
692 // -fvisibility-inlines-hidden.
693 // If both functions have the same contents, this will have the same
694 // behavior. If not, it won't, but the input had an ODR violation in
695 // that case.
696 //
697 // Similarly, merging a symbol
698 // that's isPrivateExtern and not isWeakDefCanBeHidden with one
699 // that's not isPrivateExtern but isWeakDefCanBeHidden technically
700 // should produce one
701 // that's not isPrivateExtern but isWeakDefCanBeHidden. That matters
702 // with ld64's semantics, because it means the non-private-extern
703 // definition will continue to take priority if more private extern
704 // definitions are encountered. With lld's semantics there's no observable
705 // difference between a symbol that's isWeakDefCanBeHidden(autohide) or one
706 // that's privateExtern -- neither makes it into the dynamic symbol table,
707 // unless the autohide symbol is explicitly exported.
708 // But if a symbol is both privateExtern and autohide then it can't
709 // be exported.
710 // So we nullify the autohide flag when privateExtern is present
711 // and promote the symbol to privateExtern when it is not already.
712 if (isWeakDefCanBeHidden && isPrivateExtern)
713 isWeakDefCanBeHidden = false;
714 else if (isWeakDefCanBeHidden)
715 isPrivateExtern = true;
716 return symtab->addDefined(
717 name, isec->getFile(), isec, value, size, isWeakDef: sym.n_desc & N_WEAK_DEF,
718 isPrivateExtern, isReferencedDynamically: sym.n_desc & REFERENCED_DYNAMICALLY,
719 noDeadStrip: sym.n_desc & N_NO_DEAD_STRIP, isWeakDefCanBeHidden);
720 }
721 bool includeInSymtab = !isPrivateLabel(name) && !isEhFrameSection(isec);
722 return make<Defined>(
723 name, isec->getFile(), isec, value, size, sym.n_desc & N_WEAK_DEF,
724 /*isExternal=*/false, /*isPrivateExtern=*/false, includeInSymtab,
725 sym.n_desc & REFERENCED_DYNAMICALLY, sym.n_desc & N_NO_DEAD_STRIP);
726}
727
728// Absolute symbols are defined symbols that do not have an associated
729// InputSection. They cannot be weak.
730template <class NList>
731static macho::Symbol *createAbsolute(const NList &sym, InputFile *file,
732 StringRef name, bool forceHidden) {
733 assert(!(sym.n_desc & N_ARM_THUMB_DEF) && "ARM32 arch is not supported");
734
735 if (sym.n_type & N_EXT) {
736 bool isPrivateExtern = sym.n_type & N_PEXT || forceHidden;
737 return symtab->addDefined(name, file, nullptr, value: sym.n_value, /*size=*/0,
738 /*isWeakDef=*/false, isPrivateExtern,
739 /*isReferencedDynamically=*/false,
740 noDeadStrip: sym.n_desc & N_NO_DEAD_STRIP,
741 /*isWeakDefCanBeHidden=*/false);
742 }
743 return make<Defined>(name, file, nullptr, sym.n_value, /*size=*/0,
744 /*isWeakDef=*/false,
745 /*isExternal=*/false, /*isPrivateExtern=*/false,
746 /*includeInSymtab=*/true,
747 /*isReferencedDynamically=*/false,
748 sym.n_desc & N_NO_DEAD_STRIP);
749}
750
751template <class NList>
752macho::Symbol *ObjFile::parseNonSectionSymbol(const NList &sym,
753 const char *strtab) {
754 StringRef name = StringRef(strtab + sym.n_strx);
755 uint8_t type = sym.n_type & N_TYPE;
756 bool isPrivateExtern = sym.n_type & N_PEXT || forceHidden;
757 switch (type) {
758 case N_UNDF:
759 return sym.n_value == 0
760 ? symtab->addUndefined(name, this, isWeakRef: sym.n_desc & N_WEAK_REF)
761 : symtab->addCommon(name, this, size: sym.n_value,
762 align: 1 << GET_COMM_ALIGN(sym.n_desc),
763 isPrivateExtern);
764 case N_ABS:
765 return createAbsolute(sym, this, name, forceHidden);
766 case N_INDR: {
767 // Not much point in making local aliases -- relocs in the current file can
768 // just refer to the actual symbol itself. ld64 ignores these symbols too.
769 if (!(sym.n_type & N_EXT))
770 return nullptr;
771 StringRef aliasedName = StringRef(strtab + sym.n_value);
772 // isPrivateExtern is the only symbol flag that has an impact on the final
773 // aliased symbol.
774 auto *alias = make<AliasSymbol>(args: this, args&: name, args&: aliasedName, args&: isPrivateExtern);
775 aliases.push_back(x: alias);
776 return alias;
777 }
778 case N_PBUD:
779 error(msg: "TODO: support symbols of type N_PBUD");
780 return nullptr;
781 case N_SECT:
782 llvm_unreachable(
783 "N_SECT symbols should not be passed to parseNonSectionSymbol");
784 default:
785 llvm_unreachable("invalid symbol type");
786 }
787}
788
789template <class NList> static bool isUndef(const NList &sym) {
790 return (sym.n_type & N_TYPE) == N_UNDF && sym.n_value == 0;
791}
792
793template <class LP>
794void ObjFile::parseSymbols(ArrayRef<typename LP::section> sectionHeaders,
795 ArrayRef<typename LP::nlist> nList,
796 const char *strtab, bool subsectionsViaSymbols) {
797 using NList = typename LP::nlist;
798
799 // Groups indices of the symbols by the sections that contain them.
800 std::vector<std::vector<uint32_t>> symbolsBySection(sections.size());
801 symbols.resize(nList.size());
802 SmallVector<unsigned, 32> undefineds;
803 for (uint32_t i = 0; i < nList.size(); ++i) {
804 const NList &sym = nList[i];
805
806 // Ignore debug symbols for now.
807 // FIXME: may need special handling.
808 if (sym.n_type & N_STAB)
809 continue;
810
811 if ((sym.n_type & N_TYPE) == N_SECT) {
812 if (sym.n_sect == 0) {
813 fatal(msg: "section symbol " + StringRef(strtab + sym.n_strx) + " in " +
814 toString(f: this) + " has an invalid section index [0]");
815 }
816 if (sym.n_sect > sections.size()) {
817 fatal(msg: "section symbol " + StringRef(strtab + sym.n_strx) + " in " +
818 toString(f: this) + " has an invalid section index [" +
819 Twine(static_cast<unsigned>(sym.n_sect)) +
820 "] greater than the total number of sections [" +
821 Twine(sections.size()) + "]");
822 }
823 Subsections &subsections = sections[sym.n_sect - 1]->subsections;
824 // parseSections() may have chosen not to parse this section.
825 if (subsections.empty())
826 continue;
827 symbolsBySection[sym.n_sect - 1].push_back(i);
828 } else if (isUndef(sym)) {
829 undefineds.push_back(Elt: i);
830 } else {
831 symbols[i] = parseNonSectionSymbol(sym, strtab);
832 }
833 }
834
835 for (size_t i = 0; i < sections.size(); ++i) {
836 Subsections &subsections = sections[i]->subsections;
837 if (subsections.empty())
838 continue;
839 std::vector<uint32_t> &symbolIndices = symbolsBySection[i];
840 uint64_t sectionAddr = sectionHeaders[i].addr;
841 uint32_t sectionAlign = 1u << sectionHeaders[i].align;
842
843 // Some sections have already been split into subsections during
844 // parseSections(), so we simply need to match Symbols to the corresponding
845 // subsection here.
846 if (sections[i]->doneSplitting) {
847 for (size_t j = 0; j < symbolIndices.size(); ++j) {
848 const uint32_t symIndex = symbolIndices[j];
849 const NList &sym = nList[symIndex];
850 StringRef name = strtab + sym.n_strx;
851 uint64_t symbolOffset = sym.n_value - sectionAddr;
852 InputSection *isec =
853 findContainingSubsection(section: *sections[i], offset: &symbolOffset);
854 if (symbolOffset != 0) {
855 error(msg: toString(sec: *sections[i]) + ": symbol " + name +
856 " at misaligned offset");
857 continue;
858 }
859 symbols[symIndex] =
860 createDefined(sym, name, isec, 0, isec->getSize(), forceHidden);
861 }
862 continue;
863 }
864 sections[i]->doneSplitting = true;
865
866 auto getSymName = [strtab](const NList& sym) -> StringRef {
867 return StringRef(strtab + sym.n_strx);
868 };
869
870 // Calculate symbol sizes and create subsections by splitting the sections
871 // along symbol boundaries.
872 // We populate subsections by repeatedly splitting the last (highest
873 // address) subsection.
874 llvm::stable_sort(symbolIndices, [&](uint32_t lhs, uint32_t rhs) {
875 // Put extern weak symbols after other symbols at the same address so
876 // that weak symbol coalescing works correctly. See
877 // SymbolTable::addDefined() for details.
878 if (nList[lhs].n_value == nList[rhs].n_value &&
879 nList[lhs].n_type & N_EXT && nList[rhs].n_type & N_EXT)
880 return !(nList[lhs].n_desc & N_WEAK_DEF) && (nList[rhs].n_desc & N_WEAK_DEF);
881 return nList[lhs].n_value < nList[rhs].n_value;
882 });
883 for (size_t j = 0; j < symbolIndices.size(); ++j) {
884 const uint32_t symIndex = symbolIndices[j];
885 const NList &sym = nList[symIndex];
886 StringRef name = getSymName(sym);
887 Subsection &subsec = subsections.back();
888 InputSection *isec = subsec.isec;
889
890 uint64_t subsecAddr = sectionAddr + subsec.offset;
891 size_t symbolOffset = sym.n_value - subsecAddr;
892 uint64_t symbolSize =
893 j + 1 < symbolIndices.size()
894 ? nList[symbolIndices[j + 1]].n_value - sym.n_value
895 : isec->data.size() - symbolOffset;
896 // There are 4 cases where we do not need to create a new subsection:
897 // 1. If the input file does not use subsections-via-symbols.
898 // 2. Multiple symbols at the same address only induce one subsection.
899 // (The symbolOffset == 0 check covers both this case as well as
900 // the first loop iteration.)
901 // 3. Alternative entry points do not induce new subsections.
902 // 4. If we have a literal section (e.g. __cstring and __literal4).
903 if (!subsectionsViaSymbols || symbolOffset == 0 ||
904 sym.n_desc & N_ALT_ENTRY || !isa<ConcatInputSection>(Val: isec)) {
905 isec->hasAltEntry = symbolOffset != 0;
906 symbols[symIndex] = createDefined(sym, name, isec, symbolOffset,
907 symbolSize, forceHidden);
908 continue;
909 }
910 auto *concatIsec = cast<ConcatInputSection>(Val: isec);
911
912 auto *nextIsec = make<ConcatInputSection>(args&: *concatIsec);
913 nextIsec->wasCoalesced = false;
914 if (isZeroFill(flags: isec->getFlags())) {
915 // Zero-fill sections have NULL data.data() non-zero data.size()
916 nextIsec->data = {nullptr, isec->data.size() - symbolOffset};
917 isec->data = {nullptr, symbolOffset};
918 } else {
919 nextIsec->data = isec->data.slice(N: symbolOffset);
920 isec->data = isec->data.slice(N: 0, M: symbolOffset);
921 }
922
923 // By construction, the symbol will be at offset zero in the new
924 // subsection.
925 symbols[symIndex] = createDefined(sym, name, nextIsec, /*value=*/0,
926 symbolSize, forceHidden);
927 // TODO: ld64 appears to preserve the original alignment as well as each
928 // subsection's offset from the last aligned address. We should consider
929 // emulating that behavior.
930 nextIsec->align = MinAlign(sectionAlign, sym.n_value);
931 subsections.push_back({sym.n_value - sectionAddr, nextIsec});
932 }
933 }
934
935 // Undefined symbols can trigger recursive fetch from Archives due to
936 // LazySymbols. Process defined symbols first so that the relative order
937 // between a defined symbol and an undefined symbol does not change the
938 // symbol resolution behavior. In addition, a set of interconnected symbols
939 // will all be resolved to the same file, instead of being resolved to
940 // different files.
941 for (unsigned i : undefineds)
942 symbols[i] = parseNonSectionSymbol(nList[i], strtab);
943}
944
945OpaqueFile::OpaqueFile(MemoryBufferRef mb, StringRef segName,
946 StringRef sectName)
947 : InputFile(OpaqueKind, mb) {
948 const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
949 ArrayRef<uint8_t> data = {buf, mb.getBufferSize()};
950 sections.push_back(x: make<Section>(/*file=*/args: this, args: segName.take_front(N: 16),
951 args: sectName.take_front(N: 16),
952 /*flags=*/args: 0, /*addr=*/args: 0));
953 Section &section = *sections.back();
954 ConcatInputSection *isec = make<ConcatInputSection>(args&: section, args&: data);
955 isec->live = true;
956 section.subsections.push_back(x: {.offset: 0, .isec: isec});
957}
958
959template <class LP>
960void ObjFile::parseLinkerOptions(SmallVectorImpl<StringRef> &LCLinkerOptions) {
961 using Header = typename LP::mach_header;
962 auto *hdr = reinterpret_cast<const Header *>(mb.getBufferStart());
963
964 for (auto *cmd : findCommands<linker_option_command>(hdr, LC_LINKER_OPTION)) {
965 StringRef data{reinterpret_cast<const char *>(cmd + 1),
966 cmd->cmdsize - sizeof(linker_option_command)};
967 parseLCLinkerOption(LCLinkerOptions, this, cmd->count, data);
968 }
969}
970
971SmallVector<StringRef> macho::unprocessedLCLinkerOptions;
972ObjFile::ObjFile(MemoryBufferRef mb, uint32_t modTime, StringRef archiveName,
973 bool lazy, bool forceHidden, bool compatArch,
974 bool builtFromBitcode)
975 : InputFile(ObjKind, mb, lazy), modTime(modTime), forceHidden(forceHidden),
976 builtFromBitcode(builtFromBitcode) {
977 this->archiveName = std::string(archiveName);
978 this->compatArch = compatArch;
979 if (lazy) {
980 if (target->wordSize == 8)
981 parseLazy<LP64>();
982 else
983 parseLazy<ILP32>();
984 } else {
985 if (target->wordSize == 8)
986 parse<LP64>();
987 else
988 parse<ILP32>();
989 }
990}
991
992template <class LP> void ObjFile::parse() {
993 using Header = typename LP::mach_header;
994 using SegmentCommand = typename LP::segment_command;
995 using SectionHeader = typename LP::section;
996 using NList = typename LP::nlist;
997
998 auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
999 auto *hdr = reinterpret_cast<const Header *>(mb.getBufferStart());
1000
1001 // If we've already checked the arch, then don't need to check again.
1002 if (!compatArch)
1003 return;
1004 if (!(compatArch = compatWithTargetArch(this, hdr)))
1005 return;
1006
1007 // We will resolve LC linker options once all native objects are loaded after
1008 // LTO is finished.
1009 SmallVector<StringRef, 4> LCLinkerOptions;
1010 parseLinkerOptions<LP>(LCLinkerOptions);
1011 unprocessedLCLinkerOptions.append(RHS: LCLinkerOptions);
1012
1013 ArrayRef<SectionHeader> sectionHeaders;
1014 if (const load_command *cmd = findCommand(hdr, LP::segmentLCType)) {
1015 auto *c = reinterpret_cast<const SegmentCommand *>(cmd);
1016 sectionHeaders = ArrayRef<SectionHeader>{
1017 reinterpret_cast<const SectionHeader *>(c + 1), c->nsects};
1018 parseSections(sectionHeaders);
1019 }
1020
1021 // TODO: Error on missing LC_SYMTAB?
1022 if (const load_command *cmd = findCommand(hdr, LC_SYMTAB)) {
1023 auto *c = reinterpret_cast<const symtab_command *>(cmd);
1024 ArrayRef<NList> nList(reinterpret_cast<const NList *>(buf + c->symoff),
1025 c->nsyms);
1026 const char *strtab = reinterpret_cast<const char *>(buf) + c->stroff;
1027 bool subsectionsViaSymbols = hdr->flags & MH_SUBSECTIONS_VIA_SYMBOLS;
1028 parseSymbols<LP>(sectionHeaders, nList, strtab, subsectionsViaSymbols);
1029 }
1030
1031 // The relocations may refer to the symbols, so we parse them after we have
1032 // parsed all the symbols.
1033 for (size_t i = 0, n = sections.size(); i < n; ++i)
1034 if (!sections[i]->subsections.empty())
1035 parseRelocations(sectionHeaders, sectionHeaders[i], *sections[i]);
1036
1037 parseDebugInfo();
1038
1039 Section *ehFrameSection = nullptr;
1040 Section *compactUnwindSection = nullptr;
1041 for (Section *sec : sections) {
1042 Section **s = StringSwitch<Section **>(sec->name)
1043 .Case(S: section_names::compactUnwind, Value: &compactUnwindSection)
1044 .Case(S: section_names::ehFrame, Value: &ehFrameSection)
1045 .Default(Value: nullptr);
1046 if (s)
1047 *s = sec;
1048 }
1049 if (compactUnwindSection)
1050 registerCompactUnwind(compactUnwindSection&: *compactUnwindSection);
1051 if (ehFrameSection)
1052 registerEhFrames(ehFrameSection&: *ehFrameSection);
1053}
1054
1055template <class LP> void ObjFile::parseLazy() {
1056 using Header = typename LP::mach_header;
1057 using NList = typename LP::nlist;
1058
1059 auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
1060 auto *hdr = reinterpret_cast<const Header *>(mb.getBufferStart());
1061
1062 if (!compatArch)
1063 return;
1064 if (!(compatArch = compatWithTargetArch(this, hdr)))
1065 return;
1066
1067 const load_command *cmd = findCommand(hdr, LC_SYMTAB);
1068 if (!cmd)
1069 return;
1070 auto *c = reinterpret_cast<const symtab_command *>(cmd);
1071 ArrayRef<NList> nList(reinterpret_cast<const NList *>(buf + c->symoff),
1072 c->nsyms);
1073 const char *strtab = reinterpret_cast<const char *>(buf) + c->stroff;
1074 symbols.resize(nList.size());
1075 for (const auto &[i, sym] : llvm::enumerate(nList)) {
1076 if ((sym.n_type & N_EXT) && !isUndef(sym)) {
1077 // TODO: Bound checking
1078 StringRef name = strtab + sym.n_strx;
1079 symbols[i] = symtab->addLazyObject(name, file&: *this);
1080 if (!lazy)
1081 break;
1082 }
1083 }
1084}
1085
1086void ObjFile::parseDebugInfo() {
1087 std::unique_ptr<DwarfObject> dObj = DwarfObject::create(this);
1088 if (!dObj)
1089 return;
1090
1091 // We do not re-use the context from getDwarf() here as that function
1092 // constructs an expensive DWARFCache object.
1093 auto *ctx = make<DWARFContext>(
1094 args: std::move(dObj), args: "",
1095 args: [&](Error err) {
1096 warn(msg: toString(f: this) + ": " + toString(E: std::move(err)));
1097 },
1098 args: [&](Error warning) {
1099 warn(msg: toString(f: this) + ": " + toString(E: std::move(warning)));
1100 });
1101
1102 // TODO: Since object files can contain a lot of DWARF info, we should verify
1103 // that we are parsing just the info we need
1104 const DWARFContext::compile_unit_range &units = ctx->compile_units();
1105 // FIXME: There can be more than one compile unit per object file. See
1106 // PR48637.
1107 auto it = units.begin();
1108 compileUnit = it != units.end() ? it->get() : nullptr;
1109}
1110
1111ArrayRef<data_in_code_entry> ObjFile::getDataInCode() const {
1112 const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
1113 const load_command *cmd = findCommand(anyHdr: buf, types: LC_DATA_IN_CODE);
1114 if (!cmd)
1115 return {};
1116 const auto *c = reinterpret_cast<const linkedit_data_command *>(cmd);
1117 return {reinterpret_cast<const data_in_code_entry *>(buf + c->dataoff),
1118 c->datasize / sizeof(data_in_code_entry)};
1119}
1120
1121ArrayRef<uint8_t> ObjFile::getOptimizationHints() const {
1122 const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
1123 if (auto *cmd =
1124 findCommand<linkedit_data_command>(anyHdr: buf, types: LC_LINKER_OPTIMIZATION_HINT))
1125 return {buf + cmd->dataoff, cmd->datasize};
1126 return {};
1127}
1128
1129// Create pointers from symbols to their associated compact unwind entries.
1130void ObjFile::registerCompactUnwind(Section &compactUnwindSection) {
1131 for (const Subsection &subsection : compactUnwindSection.subsections) {
1132 ConcatInputSection *isec = cast<ConcatInputSection>(Val: subsection.isec);
1133 // Hack!! Each compact unwind entry (CUE) has its UNSIGNED relocations embed
1134 // their addends in its data. Thus if ICF operated naively and compared the
1135 // entire contents of each CUE, entries with identical unwind info but e.g.
1136 // belonging to different functions would never be considered equivalent. To
1137 // work around this problem, we remove some parts of the data containing the
1138 // embedded addends. In particular, we remove the function address and LSDA
1139 // pointers. Since these locations are at the start and end of the entry,
1140 // we can do this using a simple, efficient slice rather than performing a
1141 // copy. We are not losing any information here because the embedded
1142 // addends have already been parsed in the corresponding Reloc structs.
1143 //
1144 // Removing these pointers would not be safe if they were pointers to
1145 // absolute symbols. In that case, there would be no corresponding
1146 // relocation. However, (AFAIK) MC cannot emit references to absolute
1147 // symbols for either the function address or the LSDA. However, it *can* do
1148 // so for the personality pointer, so we are not slicing that field away.
1149 //
1150 // Note that we do not adjust the offsets of the corresponding relocations;
1151 // instead, we rely on `relocateCompactUnwind()` to correctly handle these
1152 // truncated input sections.
1153 isec->data = isec->data.slice(N: target->wordSize, M: 8 + target->wordSize);
1154 uint32_t encoding = read32le(P: isec->data.data() + sizeof(uint32_t));
1155 // llvm-mc omits CU entries for functions that need DWARF encoding, but
1156 // `ld -r` doesn't. We can ignore them because we will re-synthesize these
1157 // CU entries from the DWARF info during the output phase.
1158 if ((encoding & static_cast<uint32_t>(UNWIND_MODE_MASK)) ==
1159 target->modeDwarfEncoding)
1160 continue;
1161
1162 ConcatInputSection *referentIsec;
1163 for (auto it = isec->relocs.begin(); it != isec->relocs.end();) {
1164 Relocation &r = *it;
1165 // CUE::functionAddress is at offset 0. Skip personality & LSDA relocs.
1166 if (r.offset != 0) {
1167 ++it;
1168 continue;
1169 }
1170 uint64_t add = r.addend;
1171 if (auto *sym = cast_or_null<Defined>(Val: r.referent.dyn_cast<Symbol *>())) {
1172 // Check whether the symbol defined in this file is the prevailing one.
1173 // Skip if it is e.g. a weak def that didn't prevail.
1174 if (sym->getFile() != this) {
1175 ++it;
1176 continue;
1177 }
1178 add += sym->value;
1179 referentIsec = cast<ConcatInputSection>(Val: sym->isec());
1180 } else {
1181 referentIsec =
1182 cast<ConcatInputSection>(Val: r.referent.dyn_cast<InputSection *>());
1183 }
1184 // Unwind info lives in __DATA, and finalization of __TEXT will occur
1185 // before finalization of __DATA. Moreover, the finalization of unwind
1186 // info depends on the exact addresses that it references. So it is safe
1187 // for compact unwind to reference addresses in __TEXT, but not addresses
1188 // in any other segment.
1189 if (referentIsec->getSegName() != segment_names::text)
1190 error(msg: isec->getLocation(off: r.offset) + " references section " +
1191 referentIsec->getName() + " which is not in segment __TEXT");
1192 // The functionAddress relocations are typically section relocations.
1193 // However, unwind info operates on a per-symbol basis, so we search for
1194 // the function symbol here.
1195 Defined *d = findSymbolAtOffset(isec: referentIsec, off: add);
1196 if (!d) {
1197 ++it;
1198 continue;
1199 }
1200 d->originalUnwindEntry = isec;
1201 // Now that the symbol points to the unwind entry, we can remove the reloc
1202 // that points from the unwind entry back to the symbol.
1203 //
1204 // First, the symbol keeps the unwind entry alive (and not vice versa), so
1205 // this keeps dead-stripping simple.
1206 //
1207 // Moreover, it reduces the work that ICF needs to do to figure out if
1208 // functions with unwind info are foldable.
1209 //
1210 // However, this does make it possible for ICF to fold CUEs that point to
1211 // distinct functions (if the CUEs are otherwise identical).
1212 // UnwindInfoSection takes care of this by re-duplicating the CUEs so that
1213 // each one can hold a distinct functionAddress value.
1214 //
1215 // Given that clang emits relocations in reverse order of address, this
1216 // relocation should be at the end of the vector for most of our input
1217 // object files, so this erase() is typically an O(1) operation.
1218 it = isec->relocs.erase(position: it);
1219 }
1220 }
1221}
1222
1223struct CIE {
1224 macho::Symbol *personalitySymbol = nullptr;
1225 bool fdesHaveAug = false;
1226 uint8_t lsdaPtrSize = 0; // 0 => no LSDA
1227 uint8_t funcPtrSize = 0;
1228};
1229
1230static uint8_t pointerEncodingToSize(uint8_t enc) {
1231 switch (enc & 0xf) {
1232 case dwarf::DW_EH_PE_absptr:
1233 return target->wordSize;
1234 case dwarf::DW_EH_PE_sdata4:
1235 return 4;
1236 case dwarf::DW_EH_PE_sdata8:
1237 // ld64 doesn't actually support sdata8, but this seems simple enough...
1238 return 8;
1239 default:
1240 return 0;
1241 };
1242}
1243
1244static CIE parseCIE(const InputSection *isec, const EhReader &reader,
1245 size_t off) {
1246 // Handling the full generality of possible DWARF encodings would be a major
1247 // pain. We instead take advantage of our knowledge of how llvm-mc encodes
1248 // DWARF and handle just that.
1249 constexpr uint8_t expectedPersonalityEnc =
1250 dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_sdata4;
1251
1252 CIE cie;
1253 uint8_t version = reader.readByte(off: &off);
1254 if (version != 1 && version != 3)
1255 fatal(msg: "Expected CIE version of 1 or 3, got " + Twine(version));
1256 StringRef aug = reader.readString(off: &off);
1257 reader.skipLeb128(off: &off); // skip code alignment
1258 reader.skipLeb128(off: &off); // skip data alignment
1259 reader.skipLeb128(off: &off); // skip return address register
1260 reader.skipLeb128(off: &off); // skip aug data length
1261 uint64_t personalityAddrOff = 0;
1262 for (char c : aug) {
1263 switch (c) {
1264 case 'z':
1265 cie.fdesHaveAug = true;
1266 break;
1267 case 'P': {
1268 uint8_t personalityEnc = reader.readByte(off: &off);
1269 if (personalityEnc != expectedPersonalityEnc)
1270 reader.failOn(errOff: off, msg: "unexpected personality encoding 0x" +
1271 Twine::utohexstr(Val: personalityEnc));
1272 personalityAddrOff = off;
1273 off += 4;
1274 break;
1275 }
1276 case 'L': {
1277 uint8_t lsdaEnc = reader.readByte(off: &off);
1278 cie.lsdaPtrSize = pointerEncodingToSize(enc: lsdaEnc);
1279 if (cie.lsdaPtrSize == 0)
1280 reader.failOn(errOff: off, msg: "unexpected LSDA encoding 0x" +
1281 Twine::utohexstr(Val: lsdaEnc));
1282 break;
1283 }
1284 case 'R': {
1285 uint8_t pointerEnc = reader.readByte(off: &off);
1286 cie.funcPtrSize = pointerEncodingToSize(enc: pointerEnc);
1287 if (cie.funcPtrSize == 0 || !(pointerEnc & dwarf::DW_EH_PE_pcrel))
1288 reader.failOn(errOff: off, msg: "unexpected pointer encoding 0x" +
1289 Twine::utohexstr(Val: pointerEnc));
1290 break;
1291 }
1292 default:
1293 break;
1294 }
1295 }
1296 if (personalityAddrOff != 0) {
1297 const auto *personalityReloc = isec->getRelocAt(off: personalityAddrOff);
1298 if (!personalityReloc)
1299 reader.failOn(errOff: off, msg: "Failed to locate relocation for personality symbol");
1300 cie.personalitySymbol = cast<macho::Symbol *>(Val: personalityReloc->referent);
1301 }
1302 return cie;
1303}
1304
1305// EH frame target addresses may be encoded as pcrel offsets. However, instead
1306// of using an actual pcrel reloc, ld64 emits subtractor relocations instead.
1307// This function recovers the target address from the subtractors, essentially
1308// performing the inverse operation of EhRelocator.
1309//
1310// Concretely, we expect our relocations to write the value of `PC -
1311// target_addr` to `PC`. `PC` itself is denoted by a minuend relocation that
1312// points to a symbol plus an addend.
1313//
1314// It is important that the minuend relocation point to a symbol within the
1315// same section as the fixup value, since sections may get moved around.
1316//
1317// For example, for arm64, llvm-mc emits relocations for the target function
1318// address like so:
1319//
1320// ltmp:
1321// <CIE start>
1322// ...
1323// <CIE end>
1324// ... multiple FDEs ...
1325// <FDE start>
1326// <target function address - (ltmp + pcrel offset)>
1327// ...
1328//
1329// If any of the FDEs in `multiple FDEs` get dead-stripped, then `FDE start`
1330// will move to an earlier address, and `ltmp + pcrel offset` will no longer
1331// reflect an accurate pcrel value. To avoid this problem, we "canonicalize"
1332// our relocation by adding an `EH_Frame` symbol at `FDE start`, and updating
1333// the reloc to be `target function address - (EH_Frame + new pcrel offset)`.
1334//
1335// If `Invert` is set, then we instead expect `target_addr - PC` to be written
1336// to `PC`.
1337template <bool Invert = false>
1338Defined *
1339targetSymFromCanonicalSubtractor(const InputSection *isec,
1340 std::vector<Relocation>::iterator relocIt) {
1341 Relocation &subtrahend = *relocIt;
1342 Relocation &minuend = *std::next(x: relocIt);
1343 assert(target->hasAttr(subtrahend.type, RelocAttrBits::SUBTRAHEND));
1344 assert(target->hasAttr(minuend.type, RelocAttrBits::UNSIGNED));
1345 // Note: pcSym may *not* be exactly at the PC; there's usually a non-zero
1346 // addend.
1347 auto *pcSym = cast<Defined>(Val: cast<macho::Symbol *>(Val&: subtrahend.referent));
1348 Defined *target =
1349 cast_or_null<Defined>(Val: minuend.referent.dyn_cast<macho::Symbol *>());
1350 if (!pcSym) {
1351 auto *targetIsec =
1352 cast<ConcatInputSection>(Val: cast<InputSection *>(Val&: minuend.referent));
1353 target = findSymbolAtOffset(isec: targetIsec, off: minuend.addend);
1354 }
1355 if (Invert)
1356 std::swap(a&: pcSym, b&: target);
1357 if (pcSym->isec() == isec) {
1358 if (pcSym->value - (Invert ? -1 : 1) * minuend.addend != subtrahend.offset)
1359 fatal(msg: "invalid FDE relocation in __eh_frame");
1360 } else {
1361 // Ensure the pcReloc points to a symbol within the current EH frame.
1362 // HACK: we should really verify that the original relocation's semantics
1363 // are preserved. In particular, we should have
1364 // `oldSym->value + oldOffset == newSym + newOffset`. However, we don't
1365 // have an easy way to access the offsets from this point in the code; some
1366 // refactoring is needed for that.
1367 Relocation &pcReloc = Invert ? minuend : subtrahend;
1368 pcReloc.referent = isec->symbols[0];
1369 assert(isec->symbols[0]->value == 0);
1370 minuend.addend = pcReloc.offset * (Invert ? 1LL : -1LL);
1371 }
1372 return target;
1373}
1374
1375Defined *findSymbolAtAddress(const std::vector<Section *> &sections,
1376 uint64_t addr) {
1377 Section *sec = findContainingSection(sections, offset: &addr);
1378 auto *isec = cast<ConcatInputSection>(Val: findContainingSubsection(section: *sec, offset: &addr));
1379 return findSymbolAtOffset(isec, off: addr);
1380}
1381
1382// For symbols that don't have compact unwind info, associate them with the more
1383// general-purpose (and verbose) DWARF unwind info found in __eh_frame.
1384//
1385// This requires us to parse the contents of __eh_frame. See EhFrame.h for a
1386// description of its format.
1387//
1388// While parsing, we also look for what MC calls "abs-ified" relocations -- they
1389// are relocations which are implicitly encoded as offsets in the section data.
1390// We convert them into explicit Reloc structs so that the EH frames can be
1391// handled just like a regular ConcatInputSection later in our output phase.
1392//
1393// We also need to handle the case where our input object file has explicit
1394// relocations. This is the case when e.g. it's the output of `ld -r`. We only
1395// look for the "abs-ified" relocation if an explicit relocation is absent.
1396void ObjFile::registerEhFrames(Section &ehFrameSection) {
1397 DenseMap<const InputSection *, CIE> cieMap;
1398 for (const Subsection &subsec : ehFrameSection.subsections) {
1399 auto *isec = cast<ConcatInputSection>(Val: subsec.isec);
1400 uint64_t isecOff = subsec.offset;
1401
1402 // Subtractor relocs require the subtrahend to be a symbol reloc. Ensure
1403 // that all EH frames have an associated symbol so that we can generate
1404 // subtractor relocs that reference them.
1405 if (isec->symbols.size() == 0)
1406 make<Defined>(args: "EH_Frame", args: isec->getFile(), args&: isec, /*value=*/args: 0,
1407 args: isec->getSize(), /*isWeakDef=*/args: false, /*isExternal=*/args: false,
1408 /*isPrivateExtern=*/args: false, /*includeInSymtab=*/args: false,
1409 /*isReferencedDynamically=*/args: false,
1410 /*noDeadStrip=*/args: false);
1411 else if (isec->symbols[0]->value != 0)
1412 fatal(msg: "found symbol at unexpected offset in __eh_frame");
1413
1414 EhReader reader(this, isec->data, subsec.offset);
1415 size_t dataOff = 0; // Offset from the start of the EH frame.
1416 reader.skipValidLength(off: &dataOff); // readLength() already validated this.
1417 // cieOffOff is the offset from the start of the EH frame to the cieOff
1418 // value, which is itself an offset from the current PC to a CIE.
1419 const size_t cieOffOff = dataOff;
1420
1421 EhRelocator ehRelocator(isec);
1422 auto cieOffRelocIt = llvm::find_if(Range&: isec->relocs, P: [=](const Relocation &r) {
1423 return r.offset == cieOffOff;
1424 });
1425 InputSection *cieIsec = nullptr;
1426 if (cieOffRelocIt != isec->relocs.end()) {
1427 // We already have an explicit relocation for the CIE offset.
1428 cieIsec =
1429 targetSymFromCanonicalSubtractor</*Invert=*/true>(isec, relocIt: cieOffRelocIt)
1430 ->isec();
1431 dataOff += sizeof(uint32_t);
1432 } else {
1433 // If we haven't found a relocation, then the CIE offset is most likely
1434 // embedded in the section data (AKA an "abs-ified" reloc.). Parse that
1435 // and generate a Reloc struct.
1436 uint32_t cieMinuend = reader.readU32(off: &dataOff);
1437 if (cieMinuend == 0) {
1438 cieIsec = isec;
1439 } else {
1440 uint32_t cieOff = isecOff + dataOff - cieMinuend;
1441 cieIsec = findContainingSubsection(section: ehFrameSection, offset: &cieOff);
1442 if (cieIsec == nullptr)
1443 fatal(msg: "failed to find CIE");
1444 }
1445 if (cieIsec != isec)
1446 ehRelocator.makeNegativePcRel(off: cieOffOff, target: cieIsec->symbols[0],
1447 /*length=*/2);
1448 }
1449 if (cieIsec == isec) {
1450 cieMap[cieIsec] = parseCIE(isec, reader, off: dataOff);
1451 continue;
1452 }
1453
1454 assert(cieMap.contains(cieIsec));
1455 const CIE &cie = cieMap[cieIsec];
1456 // Offset of the function address within the EH frame.
1457 const size_t funcAddrOff = dataOff;
1458 uint64_t funcAddr = reader.readPointer(off: &dataOff, size: cie.funcPtrSize) +
1459 ehFrameSection.addr + isecOff + funcAddrOff;
1460 uint32_t funcLength = reader.readPointer(off: &dataOff, size: cie.funcPtrSize);
1461 size_t lsdaAddrOff = 0; // Offset of the LSDA address within the EH frame.
1462 std::optional<uint64_t> lsdaAddrOpt;
1463 if (cie.fdesHaveAug) {
1464 reader.skipLeb128(off: &dataOff);
1465 lsdaAddrOff = dataOff;
1466 if (cie.lsdaPtrSize != 0) {
1467 uint64_t lsdaOff = reader.readPointer(off: &dataOff, size: cie.lsdaPtrSize);
1468 if (lsdaOff != 0) // FIXME possible to test this?
1469 lsdaAddrOpt = ehFrameSection.addr + isecOff + lsdaAddrOff + lsdaOff;
1470 }
1471 }
1472
1473 auto funcAddrRelocIt = isec->relocs.end();
1474 auto lsdaAddrRelocIt = isec->relocs.end();
1475 for (auto it = isec->relocs.begin(); it != isec->relocs.end(); ++it) {
1476 if (it->offset == funcAddrOff)
1477 funcAddrRelocIt = it++; // Found subtrahend; skip over minuend reloc
1478 else if (lsdaAddrOpt && it->offset == lsdaAddrOff)
1479 lsdaAddrRelocIt = it++; // Found subtrahend; skip over minuend reloc
1480 }
1481
1482 Defined *funcSym;
1483 if (funcAddrRelocIt != isec->relocs.end()) {
1484 funcSym = targetSymFromCanonicalSubtractor(isec, relocIt: funcAddrRelocIt);
1485 // Canonicalize the symbol. If there are multiple symbols at the same
1486 // address, we want both `registerEhFrame` and `registerCompactUnwind`
1487 // to register the unwind entry under same symbol.
1488 // This is not particularly efficient, but we should run into this case
1489 // infrequently (only when handling the output of `ld -r`).
1490 if (funcSym->isec())
1491 funcSym = findSymbolAtOffset(isec: cast<ConcatInputSection>(Val: funcSym->isec()),
1492 off: funcSym->value);
1493 } else {
1494 funcSym = findSymbolAtAddress(sections, addr: funcAddr);
1495 ehRelocator.makePcRel(off: funcAddrOff, target: funcSym, length: target->p2WordSize);
1496 }
1497 // The symbol has been coalesced, or already has a compact unwind entry.
1498 if (!funcSym || funcSym->getFile() != this || funcSym->unwindEntry()) {
1499 // We must prune unused FDEs for correctness, so we cannot rely on
1500 // -dead_strip being enabled.
1501 isec->live = false;
1502 continue;
1503 }
1504
1505 InputSection *lsdaIsec = nullptr;
1506 if (lsdaAddrRelocIt != isec->relocs.end()) {
1507 lsdaIsec =
1508 targetSymFromCanonicalSubtractor(isec, relocIt: lsdaAddrRelocIt)->isec();
1509 } else if (lsdaAddrOpt) {
1510 uint64_t lsdaAddr = *lsdaAddrOpt;
1511 Section *sec = findContainingSection(sections, offset: &lsdaAddr);
1512 lsdaIsec =
1513 cast<ConcatInputSection>(Val: findContainingSubsection(section: *sec, offset: &lsdaAddr));
1514 ehRelocator.makePcRel(off: lsdaAddrOff, target: lsdaIsec, length: target->p2WordSize);
1515 }
1516
1517 fdes[isec] = {.funcLength: funcLength, .personality: cie.personalitySymbol, .lsda: lsdaIsec};
1518 funcSym->originalUnwindEntry = isec;
1519 ehRelocator.commit();
1520 }
1521
1522 // __eh_frame is marked as S_ATTR_LIVE_SUPPORT in input files, because FDEs
1523 // are normally required to be kept alive if they reference a live symbol.
1524 // However, we've explicitly created a dependency from a symbol to its FDE, so
1525 // dead-stripping will just work as usual, and S_ATTR_LIVE_SUPPORT will only
1526 // serve to incorrectly prevent us from dead-stripping duplicate FDEs for a
1527 // live symbol (e.g. if there were multiple weak copies). Remove this flag to
1528 // let dead-stripping proceed correctly.
1529 ehFrameSection.flags &= ~S_ATTR_LIVE_SUPPORT;
1530}
1531
1532std::string ObjFile::sourceFile() const {
1533 const char *unitName = compileUnit->getUnitDIE().getShortName();
1534 // DWARF allows DW_AT_name to be absolute, in which case nothing should be
1535 // prepended. As for the styles, debug info can contain paths from any OS, not
1536 // necessarily an OS we're currently running on. Moreover different
1537 // compilation units can be compiled on different operating systems and linked
1538 // together later.
1539 if (sys::path::is_absolute(path: unitName, style: llvm::sys::path::Style::posix) ||
1540 sys::path::is_absolute(path: unitName, style: llvm::sys::path::Style::windows))
1541 return unitName;
1542 SmallString<261> dir(compileUnit->getCompilationDir());
1543 StringRef sep = sys::path::get_separator();
1544 // We don't use `path::append` here because we want an empty `dir` to result
1545 // in an absolute path. `append` would give us a relative path for that case.
1546 if (!dir.ends_with(Suffix: sep))
1547 dir += sep;
1548 return (dir + unitName).str();
1549}
1550
1551lld::DWARFCache *ObjFile::getDwarf() {
1552 llvm::call_once(flag&: initDwarf, F: [this]() {
1553 auto dwObj = DwarfObject::create(this);
1554 if (!dwObj)
1555 return;
1556 dwarfCache = std::make_unique<DWARFCache>(args: std::make_unique<DWARFContext>(
1557 args: std::move(dwObj), args: "",
1558 args: [&](Error err) { warn(msg: getName() + ": " + toString(E: std::move(err))); },
1559 args: [&](Error warning) {
1560 warn(msg: getName() + ": " + toString(E: std::move(warning)));
1561 }));
1562 });
1563
1564 return dwarfCache.get();
1565}
1566// The path can point to either a dylib or a .tbd file.
1567static DylibFile *loadDylib(StringRef path, DylibFile *umbrella) {
1568 std::optional<MemoryBufferRef> mbref = readFile(path);
1569 if (!mbref) {
1570 error(msg: "could not read dylib file at " + path);
1571 return nullptr;
1572 }
1573 return loadDylib(mbref: *mbref, umbrella);
1574}
1575
1576// TBD files are parsed into a series of TAPI documents (InterfaceFiles), with
1577// the first document storing child pointers to the rest of them. When we are
1578// processing a given TBD file, we store that top-level document in
1579// currentTopLevelTapi. When processing re-exports, we search its children for
1580// potentially matching documents in the same TBD file. Note that the children
1581// themselves don't point to further documents, i.e. this is a two-level tree.
1582//
1583// Re-exports can either refer to on-disk files, or to documents within .tbd
1584// files.
1585static DylibFile *findDylib(StringRef path, DylibFile *umbrella,
1586 const InterfaceFile *currentTopLevelTapi) {
1587 // Search order:
1588 // 1. Install name basename in -F / -L directories.
1589 {
1590 // Framework names can be in multiple formats:
1591 // - Foo.framework/Foo
1592 // - Foo.framework/Versions/A/Foo
1593 StringRef stem = path::stem(path);
1594 SmallString<128> frameworkName("/");
1595 frameworkName += stem;
1596 frameworkName += ".framework/";
1597 size_t i = path.rfind(Str: frameworkName);
1598 if (i != StringRef::npos) {
1599 StringRef frameworkPath = path.substr(Start: i + 1);
1600 for (StringRef dir : config->frameworkSearchPaths) {
1601 SmallString<128> candidate = dir;
1602 path::append(path&: candidate, a: frameworkPath);
1603 if (std::optional<StringRef> dylibPath =
1604 resolveDylibPath(path: candidate.str()))
1605 return loadDylib(path: *dylibPath, umbrella);
1606 }
1607 } else if (std::optional<StringRef> dylibPath = findPathCombination(
1608 name: stem, roots: config->librarySearchPaths, extensions: {".tbd", ".dylib", ".so"}))
1609 return loadDylib(path: *dylibPath, umbrella);
1610 }
1611
1612 // 2. As absolute path.
1613 if (path::is_absolute(path, style: path::Style::posix))
1614 for (StringRef root : config->systemLibraryRoots)
1615 if (std::optional<StringRef> dylibPath =
1616 resolveDylibPath(path: (root + path).str()))
1617 return loadDylib(path: *dylibPath, umbrella);
1618
1619 // 3. As relative path.
1620
1621 // TODO: Handle -dylib_file
1622
1623 // Replace @executable_path, @loader_path, @rpath prefixes in install name.
1624 SmallString<128> newPath;
1625 if (config->outputType == MH_EXECUTE &&
1626 path.consume_front(Prefix: "@executable_path/")) {
1627 // ld64 allows overriding this with the undocumented flag -executable_path.
1628 // lld doesn't currently implement that flag.
1629 // FIXME: Consider using finalOutput instead of outputFile.
1630 path::append(path&: newPath, a: path::parent_path(path: config->outputFile), b: path);
1631 path = newPath;
1632 } else if (path.consume_front(Prefix: "@loader_path/")) {
1633 fs::real_path(path: umbrella->getName(), output&: newPath);
1634 path::remove_filename(path&: newPath);
1635 path::append(path&: newPath, a: path);
1636 path = newPath;
1637 } else if (path.starts_with(Prefix: "@rpath/")) {
1638 for (StringRef rpath : umbrella->rpaths) {
1639 newPath.clear();
1640 if (rpath.consume_front(Prefix: "@loader_path/")) {
1641 fs::real_path(path: umbrella->getName(), output&: newPath);
1642 path::remove_filename(path&: newPath);
1643 }
1644 path::append(path&: newPath, a: rpath, b: path.drop_front(N: strlen(s: "@rpath/")));
1645 if (std::optional<StringRef> dylibPath = resolveDylibPath(path: newPath.str()))
1646 return loadDylib(path: *dylibPath, umbrella);
1647 }
1648 // If not found in umbrella, try the rpaths specified via -rpath too.
1649 for (StringRef rpath : config->runtimePaths) {
1650 newPath.clear();
1651 if (rpath.consume_front(Prefix: "@loader_path/")) {
1652 fs::real_path(path: umbrella->getName(), output&: newPath);
1653 path::remove_filename(path&: newPath);
1654 }
1655 path::append(path&: newPath, a: rpath, b: path.drop_front(N: strlen(s: "@rpath/")));
1656 if (std::optional<StringRef> dylibPath = resolveDylibPath(path: newPath.str()))
1657 return loadDylib(path: *dylibPath, umbrella);
1658 }
1659 }
1660
1661 // FIXME: Should this be further up?
1662 if (currentTopLevelTapi) {
1663 for (InterfaceFile &child :
1664 make_pointee_range(Range: currentTopLevelTapi->documents())) {
1665 assert(child.documents().empty());
1666 if (path == child.getInstallName()) {
1667 auto *file = make<DylibFile>(args&: child, args&: umbrella, /*isBundleLoader=*/args: false,
1668 /*explicitlyLinked=*/args: false);
1669 file->parseReexports(interface: child);
1670 return file;
1671 }
1672 }
1673 }
1674
1675 if (std::optional<StringRef> dylibPath = resolveDylibPath(path))
1676 return loadDylib(path: *dylibPath, umbrella);
1677
1678 return nullptr;
1679}
1680
1681// If a re-exported dylib is public (lives in /usr/lib or
1682// /System/Library/Frameworks), then it is considered implicitly linked: we
1683// should bind to its symbols directly instead of via the re-exporting umbrella
1684// library.
1685static bool isImplicitlyLinked(StringRef path) {
1686 if (!config->implicitDylibs)
1687 return false;
1688
1689 if (path::parent_path(path) == "/usr/lib")
1690 return true;
1691
1692 // Match /System/Library/Frameworks/$FOO.framework/**/$FOO
1693 if (path.consume_front(Prefix: "/System/Library/Frameworks/")) {
1694 StringRef frameworkName = path.take_until(F: [](char c) { return c == '.'; });
1695 return path::filename(path) == frameworkName;
1696 }
1697
1698 return false;
1699}
1700
1701void DylibFile::loadReexport(StringRef path, DylibFile *umbrella,
1702 const InterfaceFile *currentTopLevelTapi) {
1703 DylibFile *reexport = findDylib(path, umbrella, currentTopLevelTapi);
1704 if (!reexport) {
1705 // If not found in umbrella, retry since some rpaths might have been
1706 // defined in "this" dylib (which contains the LC_REEXPORT_DYLIB cmd) and
1707 // not in the umbrella.
1708 DylibFile *reexport2 = findDylib(path, umbrella: this, currentTopLevelTapi);
1709 if (!reexport2) {
1710 error(msg: toString(f: this) + ": unable to locate re-export with install name " +
1711 path);
1712 }
1713 }
1714}
1715
1716DylibFile::DylibFile(MemoryBufferRef mb, DylibFile *umbrella,
1717 bool isBundleLoader, bool explicitlyLinked)
1718 : InputFile(DylibKind, mb), refState(RefState::Unreferenced),
1719 explicitlyLinked(explicitlyLinked), isBundleLoader(isBundleLoader) {
1720 assert(!isBundleLoader || !umbrella);
1721 if (umbrella == nullptr)
1722 umbrella = this;
1723 this->umbrella = umbrella;
1724
1725 auto *hdr = reinterpret_cast<const mach_header *>(mb.getBufferStart());
1726
1727 // Initialize installName.
1728 if (const load_command *cmd = findCommand(anyHdr: hdr, types: LC_ID_DYLIB)) {
1729 auto *c = reinterpret_cast<const dylib_command *>(cmd);
1730 currentVersion = read32le(P: &c->dylib.current_version);
1731 compatibilityVersion = read32le(P: &c->dylib.compatibility_version);
1732 installName =
1733 reinterpret_cast<const char *>(cmd) + read32le(P: &c->dylib.name);
1734 } else if (!isBundleLoader) {
1735 // macho_executable and macho_bundle don't have LC_ID_DYLIB,
1736 // so it's OK.
1737 error(msg: toString(f: this) + ": dylib missing LC_ID_DYLIB load command");
1738 return;
1739 }
1740
1741 if (config->printEachFile)
1742 message(msg: toString(f: this));
1743 inputFiles.insert(X: this);
1744
1745 deadStrippable = hdr->flags & MH_DEAD_STRIPPABLE_DYLIB;
1746
1747 if (!checkCompatibility(input: this))
1748 return;
1749
1750 checkAppExtensionSafety(dylibIsAppExtensionSafe: hdr->flags & MH_APP_EXTENSION_SAFE);
1751
1752 for (auto *cmd : findCommands<rpath_command>(anyHdr: hdr, types: LC_RPATH)) {
1753 StringRef rpath{reinterpret_cast<const char *>(cmd) + cmd->path};
1754 rpaths.push_back(Elt: rpath);
1755 }
1756
1757 // Initialize symbols.
1758 bool canBeImplicitlyLinked = findCommand(anyHdr: hdr, types: LC_SUB_CLIENT) == nullptr;
1759 exportingFile = (canBeImplicitlyLinked && isImplicitlyLinked(path: installName))
1760 ? this
1761 : this->umbrella;
1762
1763 if (!canBeImplicitlyLinked) {
1764 for (auto *cmd : findCommands<sub_client_command>(anyHdr: hdr, types: LC_SUB_CLIENT)) {
1765 StringRef allowableClient{reinterpret_cast<const char *>(cmd) +
1766 cmd->client};
1767 allowableClients.push_back(Elt: allowableClient);
1768 }
1769 }
1770
1771 const auto *dyldInfo = findCommand<dyld_info_command>(anyHdr: hdr, types: LC_DYLD_INFO_ONLY);
1772 const auto *exportsTrie =
1773 findCommand<linkedit_data_command>(anyHdr: hdr, types: LC_DYLD_EXPORTS_TRIE);
1774 if (dyldInfo && exportsTrie) {
1775 // It's unclear what should happen in this case. Maybe we should only error
1776 // out if the two load commands refer to different data?
1777 error(msg: toString(f: this) +
1778 ": dylib has both LC_DYLD_INFO_ONLY and LC_DYLD_EXPORTS_TRIE");
1779 return;
1780 }
1781
1782 if (dyldInfo) {
1783 parseExportedSymbols(offset: dyldInfo->export_off, size: dyldInfo->export_size);
1784 } else if (exportsTrie) {
1785 parseExportedSymbols(offset: exportsTrie->dataoff, size: exportsTrie->datasize);
1786 } else {
1787 error(msg: "No LC_DYLD_INFO_ONLY or LC_DYLD_EXPORTS_TRIE found in " +
1788 toString(f: this));
1789 }
1790}
1791
1792void DylibFile::parseExportedSymbols(uint32_t offset, uint32_t size) {
1793 struct TrieEntry {
1794 StringRef name;
1795 uint64_t flags;
1796 };
1797
1798 auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
1799 std::vector<TrieEntry> entries;
1800 // Find all the $ld$* symbols to process first.
1801 parseTrie(fileName: toString(f: this), buf: buf + offset, size,
1802 [&](const Twine &name, uint64_t flags) {
1803 StringRef savedName = saver().save(S: name);
1804 if (handleLDSymbol(originalName: savedName))
1805 return;
1806 entries.push_back(x: {.name: savedName, .flags: flags});
1807 });
1808
1809 // Process the "normal" symbols.
1810 for (TrieEntry &entry : entries) {
1811 if (exportingFile->hiddenSymbols.contains(V: CachedHashStringRef(entry.name)))
1812 continue;
1813
1814 bool isWeakDef = entry.flags & EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION;
1815 bool isTlv = entry.flags & EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL;
1816
1817 symbols.push_back(
1818 x: symtab->addDylib(name: entry.name, file: exportingFile, isWeakDef, isTlv));
1819 }
1820}
1821
1822void DylibFile::parseLoadCommands(MemoryBufferRef mb) {
1823 auto *hdr = reinterpret_cast<const mach_header *>(mb.getBufferStart());
1824 const uint8_t *p = reinterpret_cast<const uint8_t *>(mb.getBufferStart()) +
1825 target->headerSize;
1826 for (uint32_t i = 0, n = hdr->ncmds; i < n; ++i) {
1827 auto *cmd = reinterpret_cast<const load_command *>(p);
1828 p += cmd->cmdsize;
1829
1830 if (!(hdr->flags & MH_NO_REEXPORTED_DYLIBS) &&
1831 cmd->cmd == LC_REEXPORT_DYLIB) {
1832 const auto *c = reinterpret_cast<const dylib_command *>(cmd);
1833 StringRef reexportPath =
1834 reinterpret_cast<const char *>(c) + read32le(P: &c->dylib.name);
1835 loadReexport(path: reexportPath, umbrella: exportingFile, currentTopLevelTapi: nullptr);
1836 }
1837
1838 // FIXME: What about LC_LOAD_UPWARD_DYLIB, LC_LAZY_LOAD_DYLIB,
1839 // LC_LOAD_WEAK_DYLIB, LC_REEXPORT_DYLIB (..are reexports from dylibs with
1840 // MH_NO_REEXPORTED_DYLIBS loaded for -flat_namespace)?
1841 if (config->namespaceKind == NamespaceKind::flat &&
1842 cmd->cmd == LC_LOAD_DYLIB) {
1843 const auto *c = reinterpret_cast<const dylib_command *>(cmd);
1844 StringRef dylibPath =
1845 reinterpret_cast<const char *>(c) + read32le(P: &c->dylib.name);
1846 DylibFile *dylib = findDylib(path: dylibPath, umbrella, currentTopLevelTapi: nullptr);
1847 if (!dylib)
1848 error(msg: Twine("unable to locate library '") + dylibPath +
1849 "' loaded from '" + toString(f: this) + "' for -flat_namespace");
1850 }
1851 }
1852}
1853
1854// Some versions of Xcode ship with .tbd files that don't have the right
1855// platform settings.
1856constexpr std::array<StringRef, 3> skipPlatformChecks{
1857 "/usr/lib/system/libsystem_kernel.dylib",
1858 "/usr/lib/system/libsystem_platform.dylib",
1859 "/usr/lib/system/libsystem_pthread.dylib"};
1860
1861static bool skipPlatformCheckForCatalyst(const InterfaceFile &interface,
1862 bool explicitlyLinked) {
1863 // Catalyst outputs can link against implicitly linked macOS-only libraries.
1864 if (config->platform() != PLATFORM_MACCATALYST || explicitlyLinked)
1865 return false;
1866 return is_contained(Range: interface.targets(),
1867 Element: MachO::Target(config->arch(), PLATFORM_MACOS));
1868}
1869
1870static bool isArchABICompatible(ArchitectureSet archSet,
1871 Architecture targetArch) {
1872 uint32_t cpuType;
1873 uint32_t targetCpuType;
1874 std::tie(args&: targetCpuType, args: std::ignore) = getCPUTypeFromArchitecture(Arch: targetArch);
1875
1876 return llvm::any_of(Range&: archSet, P: [&](const auto &p) {
1877 std::tie(args&: cpuType, args: std::ignore) = getCPUTypeFromArchitecture(p);
1878 return cpuType == targetCpuType;
1879 });
1880}
1881
1882static bool isTargetPlatformArchCompatible(
1883 InterfaceFile::const_target_range interfaceTargets, Target target) {
1884 if (is_contained(Range&: interfaceTargets, Element: target))
1885 return true;
1886
1887 if (config->forceExactCpuSubtypeMatch)
1888 return false;
1889
1890 ArchitectureSet archSet;
1891 for (const auto &p : interfaceTargets)
1892 if (p.Platform == target.Platform)
1893 archSet.set(p.Arch);
1894 if (archSet.empty())
1895 return false;
1896
1897 return isArchABICompatible(archSet, targetArch: target.Arch);
1898}
1899
1900DylibFile::DylibFile(const InterfaceFile &interface, DylibFile *umbrella,
1901 bool isBundleLoader, bool explicitlyLinked)
1902 : InputFile(DylibKind, interface), refState(RefState::Unreferenced),
1903 explicitlyLinked(explicitlyLinked), isBundleLoader(isBundleLoader) {
1904 // FIXME: Add test for the missing TBD code path.
1905
1906 if (umbrella == nullptr)
1907 umbrella = this;
1908 this->umbrella = umbrella;
1909
1910 installName = saver().save(S: interface.getInstallName());
1911 compatibilityVersion = interface.getCompatibilityVersion().rawValue();
1912 currentVersion = interface.getCurrentVersion().rawValue();
1913 for (const auto &rpath : interface.rpaths())
1914 if (rpath.first == config->platformInfo.target)
1915 rpaths.push_back(Elt: saver().save(S: rpath.second));
1916
1917 if (config->printEachFile)
1918 message(msg: toString(f: this));
1919 inputFiles.insert(X: this);
1920
1921 if (!is_contained(Range: skipPlatformChecks, Element: installName) &&
1922 !isTargetPlatformArchCompatible(interfaceTargets: interface.targets(),
1923 target: config->platformInfo.target) &&
1924 !skipPlatformCheckForCatalyst(interface, explicitlyLinked)) {
1925 error(msg: toString(f: this) + " is incompatible with " +
1926 std::string(config->platformInfo.target));
1927 return;
1928 }
1929
1930 checkAppExtensionSafety(dylibIsAppExtensionSafe: interface.isApplicationExtensionSafe());
1931
1932 bool canBeImplicitlyLinked = interface.allowableClients().size() == 0;
1933 exportingFile = (canBeImplicitlyLinked && isImplicitlyLinked(path: installName))
1934 ? this
1935 : umbrella;
1936
1937 if (!canBeImplicitlyLinked)
1938 for (const auto &allowableClient : interface.allowableClients())
1939 allowableClients.push_back(
1940 Elt: *make<std::string>(args: allowableClient.getInstallName().data()));
1941
1942 auto addSymbol = [&](const llvm::MachO::Symbol &symbol,
1943 const Twine &name) -> void {
1944 StringRef savedName = saver().save(S: name);
1945 if (exportingFile->hiddenSymbols.contains(V: CachedHashStringRef(savedName)))
1946 return;
1947
1948 symbols.push_back(x: symtab->addDylib(name: savedName, file: exportingFile,
1949 isWeakDef: symbol.isWeakDefined(),
1950 isTlv: symbol.isThreadLocalValue()));
1951 };
1952
1953 std::vector<const llvm::MachO::Symbol *> normalSymbols;
1954 normalSymbols.reserve(n: interface.symbolsCount());
1955 for (const auto *symbol : interface.symbols()) {
1956 if (!isArchABICompatible(archSet: symbol->getArchitectures(), targetArch: config->arch()))
1957 continue;
1958 if (handleLDSymbol(originalName: symbol->getName()))
1959 continue;
1960
1961 switch (symbol->getKind()) {
1962 case EncodeKind::GlobalSymbol:
1963 case EncodeKind::ObjectiveCClass:
1964 case EncodeKind::ObjectiveCClassEHType:
1965 case EncodeKind::ObjectiveCInstanceVariable:
1966 normalSymbols.push_back(x: symbol);
1967 }
1968 }
1969 // interface.symbols() order is non-deterministic.
1970 llvm::sort(C&: normalSymbols,
1971 Comp: [](auto *l, auto *r) { return l->getName() < r->getName(); });
1972
1973 // TODO(compnerd) filter out symbols based on the target platform
1974 for (const auto *symbol : normalSymbols) {
1975 switch (symbol->getKind()) {
1976 case EncodeKind::GlobalSymbol:
1977 addSymbol(*symbol, symbol->getName());
1978 break;
1979 case EncodeKind::ObjectiveCClass:
1980 // XXX ld64 only creates these symbols when -ObjC is passed in. We may
1981 // want to emulate that.
1982 addSymbol(*symbol, objc::symbol_names::klass + symbol->getName());
1983 addSymbol(*symbol, objc::symbol_names::metaclass + symbol->getName());
1984 break;
1985 case EncodeKind::ObjectiveCClassEHType:
1986 addSymbol(*symbol, objc::symbol_names::ehtype + symbol->getName());
1987 break;
1988 case EncodeKind::ObjectiveCInstanceVariable:
1989 addSymbol(*symbol, objc::symbol_names::ivar + symbol->getName());
1990 break;
1991 }
1992 }
1993}
1994
1995DylibFile::DylibFile(DylibFile *umbrella)
1996 : InputFile(DylibKind, MemoryBufferRef{}), refState(RefState::Unreferenced),
1997 explicitlyLinked(false), isBundleLoader(false) {
1998 if (umbrella == nullptr)
1999 umbrella = this;
2000 this->umbrella = umbrella;
2001}
2002
2003void DylibFile::parseReexports(const InterfaceFile &interface) {
2004 const InterfaceFile *topLevel =
2005 interface.getParent() == nullptr ? &interface : interface.getParent();
2006 for (const InterfaceFileRef &intfRef : interface.reexportedLibraries()) {
2007 InterfaceFile::const_target_range targets = intfRef.targets();
2008 if (is_contained(Range: skipPlatformChecks, Element: intfRef.getInstallName()) ||
2009 isTargetPlatformArchCompatible(interfaceTargets: targets, target: config->platformInfo.target))
2010 loadReexport(path: intfRef.getInstallName(), umbrella: exportingFile, currentTopLevelTapi: topLevel);
2011 }
2012}
2013
2014bool DylibFile::isExplicitlyLinked() const {
2015 if (!explicitlyLinked)
2016 return false;
2017
2018 // If this dylib was explicitly linked, but at least one of the symbols
2019 // of the synthetic dylibs it created via $ld$previous symbols is
2020 // referenced, then that synthetic dylib fulfils the explicit linkedness
2021 // and we can deadstrip this dylib if it's unreferenced.
2022 for (const auto *dylib : extraDylibs)
2023 if (dylib->isReferenced())
2024 return false;
2025
2026 return true;
2027}
2028
2029DylibFile *DylibFile::getSyntheticDylib(StringRef installName,
2030 uint32_t currentVersion,
2031 uint32_t compatVersion) {
2032 for (DylibFile *dylib : extraDylibs)
2033 if (dylib->installName == installName) {
2034 // FIXME: Check what to do if different $ld$previous symbols
2035 // request the same dylib, but with different versions.
2036 return dylib;
2037 }
2038
2039 auto *dylib = make<DylibFile>(args: umbrella == this ? nullptr : umbrella);
2040 dylib->installName = saver().save(S: installName);
2041 dylib->currentVersion = currentVersion;
2042 dylib->compatibilityVersion = compatVersion;
2043 extraDylibs.push_back(Elt: dylib);
2044 return dylib;
2045}
2046
2047// $ld$ symbols modify the properties/behavior of the library (e.g. its install
2048// name, compatibility version or hide/add symbols) for specific target
2049// versions.
2050bool DylibFile::handleLDSymbol(StringRef originalName) {
2051 if (!originalName.starts_with(Prefix: "$ld$"))
2052 return false;
2053
2054 StringRef action;
2055 StringRef name;
2056 std::tie(args&: action, args&: name) = originalName.drop_front(N: strlen(s: "$ld$")).split(Separator: '$');
2057 if (action == "previous")
2058 handleLDPreviousSymbol(name, originalName);
2059 else if (action == "install_name")
2060 handleLDInstallNameSymbol(name, originalName);
2061 else if (action == "hide")
2062 handleLDHideSymbol(name, originalName);
2063 return true;
2064}
2065
2066void DylibFile::handleLDPreviousSymbol(StringRef name, StringRef originalName) {
2067 // originalName: $ld$ previous $ <installname> $ <compatversion> $
2068 // <platformstr> $ <startversion> $ <endversion> $ <symbol-name> $
2069 StringRef installName;
2070 StringRef compatVersion;
2071 StringRef platformStr;
2072 StringRef startVersion;
2073 StringRef endVersion;
2074 StringRef symbolName;
2075 StringRef rest;
2076
2077 std::tie(args&: installName, args&: name) = name.split(Separator: '$');
2078 std::tie(args&: compatVersion, args&: name) = name.split(Separator: '$');
2079 std::tie(args&: platformStr, args&: name) = name.split(Separator: '$');
2080 std::tie(args&: startVersion, args&: name) = name.split(Separator: '$');
2081 std::tie(args&: endVersion, args&: name) = name.split(Separator: '$');
2082 std::tie(args&: symbolName, args&: rest) = name.rsplit(Separator: '$');
2083
2084 // FIXME: Does this do the right thing for zippered files?
2085 unsigned platform;
2086 if (platformStr.getAsInteger(Radix: 10, Result&: platform) ||
2087 platform != static_cast<unsigned>(config->platform()))
2088 return;
2089
2090 VersionTuple start;
2091 if (start.tryParse(string: startVersion)) {
2092 warn(msg: toString(f: this) + ": failed to parse start version, symbol '" +
2093 originalName + "' ignored");
2094 return;
2095 }
2096 VersionTuple end;
2097 if (end.tryParse(string: endVersion)) {
2098 warn(msg: toString(f: this) + ": failed to parse end version, symbol '" +
2099 originalName + "' ignored");
2100 return;
2101 }
2102 if (config->platformInfo.target.MinDeployment < start ||
2103 config->platformInfo.target.MinDeployment >= end)
2104 return;
2105
2106 // Initialized to compatibilityVersion for the symbolName branch below.
2107 uint32_t newCompatibilityVersion = compatibilityVersion;
2108 uint32_t newCurrentVersionForSymbol = currentVersion;
2109 if (!compatVersion.empty()) {
2110 VersionTuple cVersion;
2111 if (cVersion.tryParse(string: compatVersion)) {
2112 warn(msg: toString(f: this) +
2113 ": failed to parse compatibility version, symbol '" + originalName +
2114 "' ignored");
2115 return;
2116 }
2117 newCompatibilityVersion = encodeVersion(version: cVersion);
2118 newCurrentVersionForSymbol = newCompatibilityVersion;
2119 }
2120
2121 if (!symbolName.empty()) {
2122 // A $ld$previous$ symbol with symbol name adds a symbol with that name to
2123 // a dylib with given name and version.
2124 auto *dylib = getSyntheticDylib(installName, currentVersion: newCurrentVersionForSymbol,
2125 compatVersion: newCompatibilityVersion);
2126
2127 // The tbd file usually contains the $ld$previous symbol for an old version,
2128 // and then the symbol itself later, for newer deployment targets, like so:
2129 // symbols: [
2130 // '$ld$previous$/Another$$1$3.0$14.0$_zzz$',
2131 // _zzz,
2132 // ]
2133 // Since the symbols are sorted, adding them to the symtab in the given
2134 // order means the $ld$previous version of _zzz will prevail, as desired.
2135 dylib->symbols.push_back(x: symtab->addDylib(
2136 name: saver().save(S: symbolName), file: dylib, /*isWeakDef=*/false, /*isTlv=*/false));
2137 return;
2138 }
2139
2140 // A $ld$previous$ symbol without symbol name modifies the dylib it's in.
2141 this->installName = saver().save(S: installName);
2142 this->compatibilityVersion = newCompatibilityVersion;
2143}
2144
2145void DylibFile::handleLDInstallNameSymbol(StringRef name,
2146 StringRef originalName) {
2147 // originalName: $ld$ install_name $ os<version> $ install_name
2148 StringRef condition, installName;
2149 std::tie(args&: condition, args&: installName) = name.split(Separator: '$');
2150 VersionTuple version;
2151 if (!condition.consume_front(Prefix: "os") || version.tryParse(string: condition))
2152 warn(msg: toString(f: this) + ": failed to parse os version, symbol '" +
2153 originalName + "' ignored");
2154 else if (version == config->platformInfo.target.MinDeployment)
2155 this->installName = saver().save(S: installName);
2156}
2157
2158void DylibFile::handleLDHideSymbol(StringRef name, StringRef originalName) {
2159 StringRef symbolName;
2160 bool shouldHide = true;
2161 if (name.starts_with(Prefix: "os")) {
2162 // If it's hidden based on versions.
2163 name = name.drop_front(N: 2);
2164 StringRef minVersion;
2165 std::tie(args&: minVersion, args&: symbolName) = name.split(Separator: '$');
2166 VersionTuple versionTup;
2167 if (versionTup.tryParse(string: minVersion)) {
2168 warn(msg: toString(f: this) + ": failed to parse hidden version, symbol `" + originalName +
2169 "` ignored.");
2170 return;
2171 }
2172 shouldHide = versionTup == config->platformInfo.target.MinDeployment;
2173 } else {
2174 symbolName = name;
2175 }
2176
2177 if (shouldHide)
2178 exportingFile->hiddenSymbols.insert(V: CachedHashStringRef(symbolName));
2179}
2180
2181void DylibFile::checkAppExtensionSafety(bool dylibIsAppExtensionSafe) const {
2182 if (config->applicationExtension && !dylibIsAppExtensionSafe)
2183 warn(msg: "using '-application_extension' with unsafe dylib: " + toString(f: this));
2184}
2185
2186ArchiveFile::ArchiveFile(std::unique_ptr<object::Archive> &&f, bool forceHidden)
2187 : InputFile(ArchiveKind, f->getMemoryBufferRef()), file(std::move(f)),
2188 forceHidden(forceHidden) {}
2189
2190void ArchiveFile::addLazySymbols() {
2191 // Avoid calling getMemoryBufferRef() on zero-symbol archive
2192 // since that crashes.
2193 if (file->isEmpty() ||
2194 (file->hasSymbolTable() && file->getNumberOfSymbols() == 0))
2195 return;
2196
2197 if (!file->hasSymbolTable()) {
2198 // No index, treat each child as a lazy object file.
2199 Error e = Error::success();
2200 for (const object::Archive::Child &c : file->children(Err&: e)) {
2201 // Check `seen` but don't insert so a future eager load can still happen.
2202 if (seen.contains(V: c.getChildOffset()))
2203 continue;
2204 if (!seenLazy.insert(V: c.getChildOffset()).second)
2205 continue;
2206 auto file = childToObjectFile(c, /*lazy=*/true);
2207 if (!file)
2208 error(msg: toString(f: this) +
2209 ": couldn't process child: " + toString(E: file.takeError()));
2210 inputFiles.insert(X: *file);
2211 }
2212 if (e)
2213 error(msg: toString(f: this) +
2214 ": Archive::children failed: " + toString(E: std::move(e)));
2215 return;
2216 }
2217
2218 Error err = Error::success();
2219 auto child = file->child_begin(Err&: err);
2220 // Ignore the I/O error here - will be reported later.
2221 if (!err) {
2222 Expected<MemoryBufferRef> mbOrErr = child->getMemoryBufferRef();
2223 if (!mbOrErr) {
2224 llvm::consumeError(Err: mbOrErr.takeError());
2225 } else {
2226 if (identify_magic(magic: mbOrErr->getBuffer()) == file_magic::macho_object) {
2227 if (target->wordSize == 8)
2228 compatArch = compatWithTargetArch(
2229 file: this, hdr: reinterpret_cast<const LP64::mach_header *>(
2230 mbOrErr->getBufferStart()));
2231 else
2232 compatArch = compatWithTargetArch(
2233 file: this, hdr: reinterpret_cast<const ILP32::mach_header *>(
2234 mbOrErr->getBufferStart()));
2235 if (!compatArch)
2236 return;
2237 }
2238 }
2239 }
2240
2241 for (const object::Archive::Symbol &sym : file->symbols())
2242 symtab->addLazyArchive(name: sym.getName(), file: this, sym);
2243}
2244
2245static Expected<InputFile *>
2246loadArchiveMember(MemoryBufferRef mb, uint32_t modTime, StringRef archiveName,
2247 uint64_t offsetInArchive, bool forceHidden, bool compatArch,
2248 bool lazy) {
2249 if (config->zeroModTime)
2250 modTime = 0;
2251
2252 switch (identify_magic(magic: mb.getBuffer())) {
2253 case file_magic::macho_object:
2254 return make<ObjFile>(args&: mb, args&: modTime, args&: archiveName, args&: lazy, args&: forceHidden,
2255 args&: compatArch);
2256 case file_magic::bitcode:
2257 return make<BitcodeFile>(args&: mb, args&: archiveName, args&: offsetInArchive, args&: lazy,
2258 args&: forceHidden, args&: compatArch);
2259 default:
2260 return createStringError(EC: inconvertibleErrorCode(),
2261 S: mb.getBufferIdentifier() +
2262 " has unhandled file type");
2263 }
2264}
2265
2266Error ArchiveFile::fetch(const object::Archive::Child &c, StringRef reason) {
2267 if (!seen.insert(V: c.getChildOffset()).second)
2268 return Error::success();
2269 auto file = childToObjectFile(c, /*lazy=*/false);
2270 if (!file)
2271 return file.takeError();
2272
2273 inputFiles.insert(X: *file);
2274 printArchiveMemberLoad(reason, *file);
2275 return Error::success();
2276}
2277
2278void ArchiveFile::fetch(const object::Archive::Symbol &sym) {
2279 object::Archive::Child c =
2280 CHECK(sym.getMember(), toString(this) +
2281 ": could not get the member defining symbol " +
2282 toMachOString(sym));
2283
2284 // `sym` is owned by a LazySym, which will be replace<>()d by make<ObjFile>
2285 // and become invalid after that call. Copy it to the stack so we can refer
2286 // to it later.
2287 const object::Archive::Symbol symCopy = sym;
2288
2289 // ld64 doesn't demangle sym here even with -demangle.
2290 // Match that: intentionally don't call toMachOString().
2291 if (Error e = fetch(c, reason: symCopy.getName()))
2292 error(msg: toString(f: this) + ": could not get the member defining symbol " +
2293 toMachOString(symCopy) + ": " + toString(E: std::move(e)));
2294}
2295
2296Expected<InputFile *>
2297ArchiveFile::childToObjectFile(const llvm::object::Archive::Child &c,
2298 bool lazy) {
2299 Expected<MemoryBufferRef> mb = c.getMemoryBufferRef();
2300 if (!mb)
2301 return mb.takeError();
2302
2303 Expected<TimePoint<std::chrono::seconds>> modTime = c.getLastModified();
2304 if (!modTime)
2305 return modTime.takeError();
2306
2307 return loadArchiveMember(mb: *mb, modTime: toTimeT(TP: *modTime), archiveName: getName(),
2308 offsetInArchive: c.getChildOffset(), forceHidden, compatArch, lazy);
2309}
2310
2311static macho::Symbol *createBitcodeSymbol(const lto::InputFile::Symbol &objSym,
2312 BitcodeFile &file) {
2313 StringRef name = saver().save(S: objSym.getName());
2314
2315 if (objSym.isUndefined())
2316 return symtab->addUndefined(name, &file, /*isWeakRef=*/objSym.isWeak());
2317
2318 // TODO: Write a test demonstrating why computing isPrivateExtern before
2319 // LTO compilation is important.
2320 bool isPrivateExtern = false;
2321 switch (objSym.getVisibility()) {
2322 case GlobalValue::HiddenVisibility:
2323 isPrivateExtern = true;
2324 break;
2325 case GlobalValue::ProtectedVisibility:
2326 error(msg: name + " has protected visibility, which is not supported by Mach-O");
2327 break;
2328 case GlobalValue::DefaultVisibility:
2329 break;
2330 }
2331 isPrivateExtern = isPrivateExtern || objSym.canBeOmittedFromSymbolTable() ||
2332 file.forceHidden;
2333
2334 if (objSym.isCommon())
2335 return symtab->addCommon(name, &file, size: objSym.getCommonSize(),
2336 align: objSym.getCommonAlignment(), isPrivateExtern);
2337
2338 return symtab->addDefined(name, &file, /*isec=*/nullptr, /*value=*/0,
2339 /*size=*/0, isWeakDef: objSym.isWeak(), isPrivateExtern,
2340 /*isReferencedDynamically=*/false,
2341 /*noDeadStrip=*/false,
2342 /*isWeakDefCanBeHidden=*/false);
2343}
2344
2345BitcodeFile::BitcodeFile(MemoryBufferRef mb, StringRef archiveName,
2346 uint64_t offsetInArchive, bool lazy, bool forceHidden,
2347 bool compatArch)
2348 : InputFile(BitcodeKind, mb, lazy), forceHidden(forceHidden) {
2349 this->archiveName = std::string(archiveName);
2350 this->compatArch = compatArch;
2351 std::string path = mb.getBufferIdentifier().str();
2352 if (config->thinLTOIndexOnly)
2353 path = replaceThinLTOSuffix(path: mb.getBufferIdentifier());
2354
2355 // If the parent archive already determines that the arch is not compat with
2356 // target, then just return.
2357 if (!compatArch)
2358 return;
2359
2360 // ThinLTO assumes that all MemoryBufferRefs given to it have a unique
2361 // name. If two members with the same name are provided, this causes a
2362 // collision and ThinLTO can't proceed.
2363 // So, we append the archive name to disambiguate two members with the same
2364 // name from multiple different archives, and offset within the archive to
2365 // disambiguate two members of the same name from a single archive.
2366 MemoryBufferRef mbref(mb.getBuffer(),
2367 saver().save(S: archiveName.empty()
2368 ? path
2369 : archiveName + "(" +
2370 sys::path::filename(path) + ")" +
2371 utostr(X: offsetInArchive)));
2372 obj = check(e: lto::InputFile::create(Object: mbref));
2373 if (lazy)
2374 parseLazy();
2375 else
2376 parse();
2377}
2378
2379void BitcodeFile::parse() {
2380 // Convert LTO Symbols to LLD Symbols in order to perform resolution. The
2381 // "winning" symbol will then be marked as Prevailing at LTO compilation
2382 // time.
2383 symbols.resize(new_size: obj->symbols().size());
2384
2385 // Process defined symbols first. See the comment at the end of
2386 // ObjFile<>::parseSymbols.
2387 for (auto it : llvm::enumerate(First: obj->symbols()))
2388 if (!it.value().isUndefined())
2389 symbols[it.index()] = createBitcodeSymbol(objSym: it.value(), file&: *this);
2390 for (auto it : llvm::enumerate(First: obj->symbols()))
2391 if (it.value().isUndefined())
2392 symbols[it.index()] = createBitcodeSymbol(objSym: it.value(), file&: *this);
2393}
2394
2395void BitcodeFile::parseLazy() {
2396 symbols.resize(new_size: obj->symbols().size());
2397 for (const auto &[i, objSym] : llvm::enumerate(First: obj->symbols())) {
2398 if (!objSym.isUndefined()) {
2399 symbols[i] = symtab->addLazyObject(name: saver().save(S: objSym.getName()), file&: *this);
2400 if (!lazy)
2401 break;
2402 }
2403 }
2404}
2405
2406std::string macho::replaceThinLTOSuffix(StringRef path) {
2407 auto [suffix, repl] = config->thinLTOObjectSuffixReplace;
2408 if (path.consume_back(Suffix: suffix))
2409 return (path + repl).str();
2410 return std::string(path);
2411}
2412
2413void macho::extract(InputFile &file, StringRef reason) {
2414 if (!file.lazy)
2415 return;
2416 file.lazy = false;
2417
2418 printArchiveMemberLoad(reason, &file);
2419 if (auto *bitcode = dyn_cast<BitcodeFile>(Val: &file)) {
2420 bitcode->parse();
2421 } else {
2422 auto &f = cast<ObjFile>(Val&: file);
2423 if (target->wordSize == 8)
2424 f.parse<LP64>();
2425 else
2426 f.parse<ILP32>();
2427 }
2428}
2429
2430template void ObjFile::parse<LP64>();
2431