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