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