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