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 "ExportTrie.h"
49 #include "InputSection.h"
50 #include "MachOStructs.h"
51 #include "ObjC.h"
52 #include "OutputSection.h"
53 #include "OutputSegment.h"
54 #include "SymbolTable.h"
55 #include "Symbols.h"
56 #include "SyntheticSections.h"
57 #include "Target.h"
58 
59 #include "lld/Common/DWARF.h"
60 #include "lld/Common/ErrorHandler.h"
61 #include "lld/Common/Memory.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/Endian.h"
67 #include "llvm/Support/MemoryBuffer.h"
68 #include "llvm/Support/Path.h"
69 #include "llvm/Support/TarWriter.h"
70 #include "llvm/TextAPI/Architecture.h"
71 #include "llvm/TextAPI/InterfaceFile.h"
72 
73 using namespace llvm;
74 using namespace llvm::MachO;
75 using namespace llvm::support::endian;
76 using namespace llvm::sys;
77 using namespace lld;
78 using namespace lld::macho;
79 
80 // Returns "<internal>", "foo.a(bar.o)", or "baz.o".
81 std::string lld::toString(const InputFile *f) {
82   if (!f)
83     return "<internal>";
84 
85   // Multiple dylibs can be defined in one .tbd file.
86   if (auto dylibFile = dyn_cast<DylibFile>(f))
87     if (f->getName().endswith(".tbd"))
88       return (f->getName() + "(" + dylibFile->installName + ")").str();
89 
90   if (f->archiveName.empty())
91     return std::string(f->getName());
92   return (f->archiveName + "(" + path::filename(f->getName()) + ")").str();
93 }
94 
95 SetVector<InputFile *> macho::inputFiles;
96 std::unique_ptr<TarWriter> macho::tar;
97 int InputFile::idCount = 0;
98 
99 static VersionTuple decodeVersion(uint32_t version) {
100   unsigned major = version >> 16;
101   unsigned minor = (version >> 8) & 0xffu;
102   unsigned subMinor = version & 0xffu;
103   return VersionTuple(major, minor, subMinor);
104 }
105 
106 static std::vector<PlatformInfo> getPlatformInfos(const InputFile *input) {
107   if (!isa<ObjFile>(input) && !isa<DylibFile>(input))
108     return {};
109 
110   const char *hdr = input->mb.getBufferStart();
111 
112   std::vector<PlatformInfo> platformInfos;
113   for (auto *cmd : findCommands<build_version_command>(hdr, LC_BUILD_VERSION)) {
114     PlatformInfo info;
115     info.target.Platform = static_cast<PlatformKind>(cmd->platform);
116     info.minimum = decodeVersion(cmd->minos);
117     platformInfos.emplace_back(std::move(info));
118   }
119   for (auto *cmd : findCommands<version_min_command>(
120            hdr, LC_VERSION_MIN_MACOSX, LC_VERSION_MIN_IPHONEOS,
121            LC_VERSION_MIN_TVOS, LC_VERSION_MIN_WATCHOS)) {
122     PlatformInfo info;
123     switch (cmd->cmd) {
124     case LC_VERSION_MIN_MACOSX:
125       info.target.Platform = PlatformKind::macOS;
126       break;
127     case LC_VERSION_MIN_IPHONEOS:
128       info.target.Platform = PlatformKind::iOS;
129       break;
130     case LC_VERSION_MIN_TVOS:
131       info.target.Platform = PlatformKind::tvOS;
132       break;
133     case LC_VERSION_MIN_WATCHOS:
134       info.target.Platform = PlatformKind::watchOS;
135       break;
136     }
137     info.minimum = decodeVersion(cmd->version);
138     platformInfos.emplace_back(std::move(info));
139   }
140 
141   return platformInfos;
142 }
143 
144 static PlatformKind removeSimulator(PlatformKind platform) {
145   // Mapping of platform to simulator and vice-versa.
146   static const std::map<PlatformKind, PlatformKind> platformMap = {
147       {PlatformKind::iOSSimulator, PlatformKind::iOS},
148       {PlatformKind::tvOSSimulator, PlatformKind::tvOS},
149       {PlatformKind::watchOSSimulator, PlatformKind::watchOS}};
150 
151   auto iter = platformMap.find(platform);
152   if (iter == platformMap.end())
153     return platform;
154   return iter->second;
155 }
156 
157 static bool checkCompatibility(const InputFile *input) {
158   std::vector<PlatformInfo> platformInfos = getPlatformInfos(input);
159   if (platformInfos.empty())
160     return true;
161 
162   auto it = find_if(platformInfos, [&](const PlatformInfo &info) {
163     return removeSimulator(info.target.Platform) ==
164            removeSimulator(config->platform());
165   });
166   if (it == platformInfos.end()) {
167     std::string platformNames;
168     raw_string_ostream os(platformNames);
169     interleave(
170         platformInfos, os,
171         [&](const PlatformInfo &info) {
172           os << getPlatformName(info.target.Platform);
173         },
174         "/");
175     error(toString(input) + " has platform " + platformNames +
176           Twine(", which is different from target platform ") +
177           getPlatformName(config->platform()));
178     return false;
179   }
180 
181   if (it->minimum > config->platformInfo.minimum)
182     warn(toString(input) + " has version " + it->minimum.getAsString() +
183          ", which is newer than target minimum of " +
184          config->platformInfo.minimum.getAsString());
185 
186   return true;
187 }
188 
189 // Open a given file path and return it as a memory-mapped file.
190 Optional<MemoryBufferRef> macho::readFile(StringRef path) {
191   ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr = MemoryBuffer::getFile(path);
192   if (std::error_code ec = mbOrErr.getError()) {
193     error("cannot open " + path + ": " + ec.message());
194     return None;
195   }
196 
197   std::unique_ptr<MemoryBuffer> &mb = *mbOrErr;
198   MemoryBufferRef mbref = mb->getMemBufferRef();
199   make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take mb ownership
200 
201   // If this is a regular non-fat file, return it.
202   const char *buf = mbref.getBufferStart();
203   const auto *hdr = reinterpret_cast<const fat_header *>(buf);
204   if (mbref.getBufferSize() < sizeof(uint32_t) ||
205       read32be(&hdr->magic) != FAT_MAGIC) {
206     if (tar)
207       tar->append(relativeToRoot(path), mbref.getBuffer());
208     return mbref;
209   }
210 
211   // Object files and archive files may be fat files, which contain multiple
212   // real files for different CPU ISAs. Here, we search for a file that matches
213   // with the current link target and returns it as a MemoryBufferRef.
214   const auto *arch = reinterpret_cast<const fat_arch *>(buf + sizeof(*hdr));
215 
216   for (uint32_t i = 0, n = read32be(&hdr->nfat_arch); i < n; ++i) {
217     if (reinterpret_cast<const char *>(arch + i + 1) >
218         buf + mbref.getBufferSize()) {
219       error(path + ": fat_arch struct extends beyond end of file");
220       return None;
221     }
222 
223     if (read32be(&arch[i].cputype) != static_cast<uint32_t>(target->cpuType) ||
224         read32be(&arch[i].cpusubtype) != target->cpuSubtype)
225       continue;
226 
227     uint32_t offset = read32be(&arch[i].offset);
228     uint32_t size = read32be(&arch[i].size);
229     if (offset + size > mbref.getBufferSize())
230       error(path + ": slice extends beyond end of file");
231     if (tar)
232       tar->append(relativeToRoot(path), mbref.getBuffer());
233     return MemoryBufferRef(StringRef(buf + offset, size), path.copy(bAlloc));
234   }
235 
236   error("unable to find matching architecture in " + path);
237   return None;
238 }
239 
240 InputFile::InputFile(Kind kind, const InterfaceFile &interface)
241     : id(idCount++), fileKind(kind), name(saver.save(interface.getPath())) {}
242 
243 template <class Section>
244 void ObjFile::parseSections(ArrayRef<Section> sections) {
245   subsections.reserve(sections.size());
246   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
247 
248   for (const Section &sec : sections) {
249     StringRef name =
250         StringRef(sec.sectname, strnlen(sec.sectname, sizeof(sec.sectname)));
251     StringRef segname =
252         StringRef(sec.segname, strnlen(sec.segname, sizeof(sec.segname)));
253     ArrayRef<uint8_t> data = {isZeroFill(sec.flags) ? nullptr
254                                                     : buf + sec.offset,
255                               static_cast<size_t>(sec.size)};
256     if (sec.align >= 32) {
257       error("alignment " + std::to_string(sec.align) + " of section " + name +
258             " is too large");
259       subsections.push_back({});
260       continue;
261     }
262     uint32_t align = 1 << sec.align;
263     uint32_t flags = sec.flags;
264 
265     if (sectionType(sec.flags) == S_CSTRING_LITERALS ||
266         (config->dedupLiterals && isWordLiteralSection(sec.flags))) {
267       if (sec.nreloc && config->dedupLiterals)
268         fatal(toString(this) + " contains relocations in " + sec.segname + "," +
269               sec.sectname +
270               ", so LLD cannot deduplicate literals. Try re-running without "
271               "--deduplicate-literals.");
272 
273       InputSection *isec;
274       if (sectionType(sec.flags) == S_CSTRING_LITERALS) {
275         isec =
276             make<CStringInputSection>(segname, name, this, data, align, flags);
277         // FIXME: parallelize this?
278         cast<CStringInputSection>(isec)->splitIntoPieces();
279       } else {
280         isec = make<WordLiteralInputSection>(segname, name, this, data, align,
281                                              flags);
282       }
283       subsections.push_back({{0, isec}});
284     } else {
285       auto *isec =
286           make<ConcatInputSection>(segname, name, this, data, align, flags);
287       if (!(isDebugSection(isec->flags) &&
288             isec->segname == segment_names::dwarf)) {
289         subsections.push_back({{0, isec}});
290       } else {
291         // Instead of emitting DWARF sections, we emit STABS symbols to the
292         // object files that contain them. We filter them out early to avoid
293         // parsing their relocations unnecessarily. But we must still push an
294         // empty map to ensure the indices line up for the remaining sections.
295         subsections.push_back({});
296         debugSections.push_back(isec);
297       }
298     }
299   }
300 }
301 
302 // Find the subsection corresponding to the greatest section offset that is <=
303 // that of the given offset.
304 //
305 // offset: an offset relative to the start of the original InputSection (before
306 // any subsection splitting has occurred). It will be updated to represent the
307 // same location as an offset relative to the start of the containing
308 // subsection.
309 static InputSection *findContainingSubsection(SubsectionMap &map,
310                                               uint64_t *offset) {
311   auto it = std::prev(llvm::upper_bound(
312       map, *offset, [](uint64_t value, SubsectionEntry subsecEntry) {
313         return value < subsecEntry.offset;
314       }));
315   *offset -= it->offset;
316   return it->isec;
317 }
318 
319 template <class Section>
320 static bool validateRelocationInfo(InputFile *file, const Section &sec,
321                                    relocation_info rel) {
322   const RelocAttrs &relocAttrs = target->getRelocAttrs(rel.r_type);
323   bool valid = true;
324   auto message = [relocAttrs, file, sec, rel, &valid](const Twine &diagnostic) {
325     valid = false;
326     return (relocAttrs.name + " relocation " + diagnostic + " at offset " +
327             std::to_string(rel.r_address) + " of " + sec.segname + "," +
328             sec.sectname + " in " + toString(file))
329         .str();
330   };
331 
332   if (!relocAttrs.hasAttr(RelocAttrBits::LOCAL) && !rel.r_extern)
333     error(message("must be extern"));
334   if (relocAttrs.hasAttr(RelocAttrBits::PCREL) != rel.r_pcrel)
335     error(message(Twine("must ") + (rel.r_pcrel ? "not " : "") +
336                   "be PC-relative"));
337   if (isThreadLocalVariables(sec.flags) &&
338       !relocAttrs.hasAttr(RelocAttrBits::UNSIGNED))
339     error(message("not allowed in thread-local section, must be UNSIGNED"));
340   if (rel.r_length < 2 || rel.r_length > 3 ||
341       !relocAttrs.hasAttr(static_cast<RelocAttrBits>(1 << rel.r_length))) {
342     static SmallVector<StringRef, 4> widths{"0", "4", "8", "4 or 8"};
343     error(message("has width " + std::to_string(1 << rel.r_length) +
344                   " bytes, but must be " +
345                   widths[(static_cast<int>(relocAttrs.bits) >> 2) & 3] +
346                   " bytes"));
347   }
348   return valid;
349 }
350 
351 template <class Section>
352 void ObjFile::parseRelocations(ArrayRef<Section> sectionHeaders,
353                                const Section &sec, SubsectionMap &subsecMap) {
354   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
355   ArrayRef<relocation_info> relInfos(
356       reinterpret_cast<const relocation_info *>(buf + sec.reloff), sec.nreloc);
357 
358   for (size_t i = 0; i < relInfos.size(); i++) {
359     // Paired relocations serve as Mach-O's method for attaching a
360     // supplemental datum to a primary relocation record. ELF does not
361     // need them because the *_RELOC_RELA records contain the extra
362     // addend field, vs. *_RELOC_REL which omit the addend.
363     //
364     // The {X86_64,ARM64}_RELOC_SUBTRACTOR record holds the subtrahend,
365     // and the paired *_RELOC_UNSIGNED record holds the minuend. The
366     // datum for each is a symbolic address. The result is the offset
367     // between two addresses.
368     //
369     // The ARM64_RELOC_ADDEND record holds the addend, and the paired
370     // ARM64_RELOC_BRANCH26 or ARM64_RELOC_PAGE21/PAGEOFF12 holds the
371     // base symbolic address.
372     //
373     // Note: X86 does not use *_RELOC_ADDEND because it can embed an
374     // addend into the instruction stream. On X86, a relocatable address
375     // field always occupies an entire contiguous sequence of byte(s),
376     // so there is no need to merge opcode bits with address
377     // bits. Therefore, it's easy and convenient to store addends in the
378     // instruction-stream bytes that would otherwise contain zeroes. By
379     // contrast, RISC ISAs such as ARM64 mix opcode bits with with
380     // address bits so that bitwise arithmetic is necessary to extract
381     // and insert them. Storing addends in the instruction stream is
382     // possible, but inconvenient and more costly at link time.
383 
384     int64_t pairedAddend = 0;
385     relocation_info relInfo = relInfos[i];
386     if (target->hasAttr(relInfo.r_type, RelocAttrBits::ADDEND)) {
387       pairedAddend = SignExtend64<24>(relInfo.r_symbolnum);
388       relInfo = relInfos[++i];
389     }
390     assert(i < relInfos.size());
391     if (!validateRelocationInfo(this, sec, relInfo))
392       continue;
393     if (relInfo.r_address & R_SCATTERED)
394       fatal("TODO: Scattered relocations not supported");
395 
396     bool isSubtrahend =
397         target->hasAttr(relInfo.r_type, RelocAttrBits::SUBTRAHEND);
398     int64_t embeddedAddend = target->getEmbeddedAddend(mb, sec.offset, relInfo);
399     assert(!(embeddedAddend && pairedAddend));
400     int64_t totalAddend = pairedAddend + embeddedAddend;
401     Reloc r;
402     r.type = relInfo.r_type;
403     r.pcrel = relInfo.r_pcrel;
404     r.length = relInfo.r_length;
405     r.offset = relInfo.r_address;
406     if (relInfo.r_extern) {
407       r.referent = symbols[relInfo.r_symbolnum];
408       r.addend = isSubtrahend ? 0 : totalAddend;
409     } else {
410       assert(!isSubtrahend);
411       const Section &referentSec = sectionHeaders[relInfo.r_symbolnum - 1];
412       uint64_t referentOffset;
413       if (relInfo.r_pcrel) {
414         // The implicit addend for pcrel section relocations is the pcrel offset
415         // in terms of the addresses in the input file. Here we adjust it so
416         // that it describes the offset from the start of the referent section.
417         // FIXME This logic was written around x86_64 behavior -- ARM64 doesn't
418         // have pcrel section relocations. We may want to factor this out into
419         // the arch-specific .cpp file.
420         assert(target->hasAttr(r.type, RelocAttrBits::BYTE4));
421         referentOffset =
422             sec.addr + relInfo.r_address + 4 + totalAddend - referentSec.addr;
423       } else {
424         // The addend for a non-pcrel relocation is its absolute address.
425         referentOffset = totalAddend - referentSec.addr;
426       }
427       SubsectionMap &referentSubsecMap = subsections[relInfo.r_symbolnum - 1];
428       r.referent = findContainingSubsection(referentSubsecMap, &referentOffset);
429       r.addend = referentOffset;
430     }
431 
432     InputSection *subsec = findContainingSubsection(subsecMap, &r.offset);
433     subsec->relocs.push_back(r);
434 
435     if (isSubtrahend) {
436       relocation_info minuendInfo = relInfos[++i];
437       // SUBTRACTOR relocations should always be followed by an UNSIGNED one
438       // attached to the same address.
439       assert(target->hasAttr(minuendInfo.r_type, RelocAttrBits::UNSIGNED) &&
440              relInfo.r_address == minuendInfo.r_address);
441       Reloc p;
442       p.type = minuendInfo.r_type;
443       if (minuendInfo.r_extern) {
444         p.referent = symbols[minuendInfo.r_symbolnum];
445         p.addend = totalAddend;
446       } else {
447         uint64_t referentOffset =
448             totalAddend - sectionHeaders[minuendInfo.r_symbolnum - 1].addr;
449         SubsectionMap &referentSubsecMap =
450             subsections[minuendInfo.r_symbolnum - 1];
451         p.referent =
452             findContainingSubsection(referentSubsecMap, &referentOffset);
453         p.addend = referentOffset;
454       }
455       subsec->relocs.push_back(p);
456     }
457   }
458 }
459 
460 template <class NList>
461 static macho::Symbol *createDefined(const NList &sym, StringRef name,
462                                     InputSection *isec, uint64_t value,
463                                     uint64_t size) {
464   // Symbol scope is determined by sym.n_type & (N_EXT | N_PEXT):
465   // N_EXT: Global symbols. These go in the symbol table during the link,
466   //        and also in the export table of the output so that the dynamic
467   //        linker sees them.
468   // N_EXT | N_PEXT: Linkage unit (think: dylib) scoped. These go in the
469   //                 symbol table during the link so that duplicates are
470   //                 either reported (for non-weak symbols) or merged
471   //                 (for weak symbols), but they do not go in the export
472   //                 table of the output.
473   // N_PEXT: llvm-mc does not emit these, but `ld -r` (wherein ld64 emits
474   //         object files) may produce them. LLD does not yet support -r.
475   //         These are translation-unit scoped, identical to the `0` case.
476   // 0: Translation-unit scoped. These are not in the symbol table during
477   //    link, and not in the export table of the output either.
478   bool isWeakDefCanBeHidden =
479       (sym.n_desc & (N_WEAK_DEF | N_WEAK_REF)) == (N_WEAK_DEF | N_WEAK_REF);
480 
481   if (sym.n_type & N_EXT) {
482     bool isPrivateExtern = sym.n_type & N_PEXT;
483     // lld's behavior for merging symbols is slightly different from ld64:
484     // ld64 picks the winning symbol based on several criteria (see
485     // pickBetweenRegularAtoms() in ld64's SymbolTable.cpp), while lld
486     // just merges metadata and keeps the contents of the first symbol
487     // with that name (see SymbolTable::addDefined). For:
488     // * inline function F in a TU built with -fvisibility-inlines-hidden
489     // * and inline function F in another TU built without that flag
490     // ld64 will pick the one from the file built without
491     // -fvisibility-inlines-hidden.
492     // lld will instead pick the one listed first on the link command line and
493     // give it visibility as if the function was built without
494     // -fvisibility-inlines-hidden.
495     // If both functions have the same contents, this will have the same
496     // behavior. If not, it won't, but the input had an ODR violation in
497     // that case.
498     //
499     // Similarly, merging a symbol
500     // that's isPrivateExtern and not isWeakDefCanBeHidden with one
501     // that's not isPrivateExtern but isWeakDefCanBeHidden technically
502     // should produce one
503     // that's not isPrivateExtern but isWeakDefCanBeHidden. That matters
504     // with ld64's semantics, because it means the non-private-extern
505     // definition will continue to take priority if more private extern
506     // definitions are encountered. With lld's semantics there's no observable
507     // difference between a symbol that's isWeakDefCanBeHidden or one that's
508     // privateExtern -- neither makes it into the dynamic symbol table. So just
509     // promote isWeakDefCanBeHidden to isPrivateExtern here.
510     if (isWeakDefCanBeHidden)
511       isPrivateExtern = true;
512 
513     return symtab->addDefined(
514         name, isec->file, isec, value, size, sym.n_desc & N_WEAK_DEF,
515         isPrivateExtern, sym.n_desc & N_ARM_THUMB_DEF,
516         sym.n_desc & REFERENCED_DYNAMICALLY, sym.n_desc & N_NO_DEAD_STRIP);
517   }
518 
519   assert(!isWeakDefCanBeHidden &&
520          "weak_def_can_be_hidden on already-hidden symbol?");
521   return make<Defined>(
522       name, isec->file, isec, value, size, sym.n_desc & N_WEAK_DEF,
523       /*isExternal=*/false, /*isPrivateExtern=*/false,
524       sym.n_desc & N_ARM_THUMB_DEF, sym.n_desc & REFERENCED_DYNAMICALLY,
525       sym.n_desc & N_NO_DEAD_STRIP);
526 }
527 
528 // Absolute symbols are defined symbols that do not have an associated
529 // InputSection. They cannot be weak.
530 template <class NList>
531 static macho::Symbol *createAbsolute(const NList &sym, InputFile *file,
532                                      StringRef name) {
533   if (sym.n_type & N_EXT) {
534     return symtab->addDefined(name, file, nullptr, sym.n_value, /*size=*/0,
535                               /*isWeakDef=*/false, sym.n_type & N_PEXT,
536                               sym.n_desc & N_ARM_THUMB_DEF,
537                               /*isReferencedDynamically=*/false,
538                               sym.n_desc & N_NO_DEAD_STRIP);
539   }
540   return make<Defined>(name, file, nullptr, sym.n_value, /*size=*/0,
541                        /*isWeakDef=*/false,
542                        /*isExternal=*/false, /*isPrivateExtern=*/false,
543                        sym.n_desc & N_ARM_THUMB_DEF,
544                        /*isReferencedDynamically=*/false,
545                        sym.n_desc & N_NO_DEAD_STRIP);
546 }
547 
548 template <class NList>
549 macho::Symbol *ObjFile::parseNonSectionSymbol(const NList &sym,
550                                               StringRef name) {
551   uint8_t type = sym.n_type & N_TYPE;
552   switch (type) {
553   case N_UNDF:
554     return sym.n_value == 0
555                ? symtab->addUndefined(name, this, sym.n_desc & N_WEAK_REF)
556                : symtab->addCommon(name, this, sym.n_value,
557                                    1 << GET_COMM_ALIGN(sym.n_desc),
558                                    sym.n_type & N_PEXT);
559   case N_ABS:
560     return createAbsolute(sym, this, name);
561   case N_PBUD:
562   case N_INDR:
563     error("TODO: support symbols of type " + std::to_string(type));
564     return nullptr;
565   case N_SECT:
566     llvm_unreachable(
567         "N_SECT symbols should not be passed to parseNonSectionSymbol");
568   default:
569     llvm_unreachable("invalid symbol type");
570   }
571 }
572 
573 template <class LP>
574 void ObjFile::parseSymbols(ArrayRef<typename LP::section> sectionHeaders,
575                            ArrayRef<typename LP::nlist> nList,
576                            const char *strtab, bool subsectionsViaSymbols) {
577   using NList = typename LP::nlist;
578 
579   // Groups indices of the symbols by the sections that contain them.
580   std::vector<std::vector<uint32_t>> symbolsBySection(subsections.size());
581   symbols.resize(nList.size());
582   for (uint32_t i = 0; i < nList.size(); ++i) {
583     const NList &sym = nList[i];
584     StringRef name = strtab + sym.n_strx;
585     if ((sym.n_type & N_TYPE) == N_SECT) {
586       SubsectionMap &subsecMap = subsections[sym.n_sect - 1];
587       // parseSections() may have chosen not to parse this section.
588       if (subsecMap.empty())
589         continue;
590       symbolsBySection[sym.n_sect - 1].push_back(i);
591     } else {
592       symbols[i] = parseNonSectionSymbol(sym, name);
593     }
594   }
595 
596   // Calculate symbol sizes and create subsections by splitting the sections
597   // along symbol boundaries.
598   for (size_t i = 0; i < subsections.size(); ++i) {
599     SubsectionMap &subsecMap = subsections[i];
600     if (subsecMap.empty())
601       continue;
602 
603     std::vector<uint32_t> &symbolIndices = symbolsBySection[i];
604     llvm::stable_sort(symbolIndices, [&](uint32_t lhs, uint32_t rhs) {
605       return nList[lhs].n_value < nList[rhs].n_value;
606     });
607     uint64_t sectionAddr = sectionHeaders[i].addr;
608     uint32_t sectionAlign = 1u << sectionHeaders[i].align;
609 
610     // We populate subsecMap by repeatedly splitting the last (highest address)
611     // subsection.
612     SubsectionEntry subsecEntry = subsecMap.back();
613     for (size_t j = 0; j < symbolIndices.size(); ++j) {
614       uint32_t symIndex = symbolIndices[j];
615       const NList &sym = nList[symIndex];
616       StringRef name = strtab + sym.n_strx;
617       InputSection *isec = subsecEntry.isec;
618 
619       uint64_t subsecAddr = sectionAddr + subsecEntry.offset;
620       size_t symbolOffset = sym.n_value - subsecAddr;
621       uint64_t symbolSize =
622           j + 1 < symbolIndices.size()
623               ? nList[symbolIndices[j + 1]].n_value - sym.n_value
624               : isec->data.size() - symbolOffset;
625       // There are 4 cases where we do not need to create a new subsection:
626       //   1. If the input file does not use subsections-via-symbols.
627       //   2. Multiple symbols at the same address only induce one subsection.
628       //      (The symbolOffset == 0 check covers both this case as well as
629       //      the first loop iteration.)
630       //   3. Alternative entry points do not induce new subsections.
631       //   4. If we have a literal section (e.g. __cstring and __literal4).
632       if (!subsectionsViaSymbols || symbolOffset == 0 ||
633           sym.n_desc & N_ALT_ENTRY || !isa<ConcatInputSection>(isec)) {
634         symbols[symIndex] =
635             createDefined(sym, name, isec, symbolOffset, symbolSize);
636         continue;
637       }
638       auto *concatIsec = cast<ConcatInputSection>(isec);
639 
640       auto *nextIsec = make<ConcatInputSection>(*concatIsec);
641       nextIsec->numRefs = 0;
642       nextIsec->wasCoalesced = false;
643       if (isZeroFill(isec->flags)) {
644         // Zero-fill sections have NULL data.data() non-zero data.size()
645         nextIsec->data = {nullptr, isec->data.size() - symbolOffset};
646         isec->data = {nullptr, symbolOffset};
647       } else {
648         nextIsec->data = isec->data.slice(symbolOffset);
649         isec->data = isec->data.slice(0, symbolOffset);
650       }
651 
652       // By construction, the symbol will be at offset zero in the new
653       // subsection.
654       symbols[symIndex] =
655           createDefined(sym, name, nextIsec, /*value=*/0, symbolSize);
656       // TODO: ld64 appears to preserve the original alignment as well as each
657       // subsection's offset from the last aligned address. We should consider
658       // emulating that behavior.
659       nextIsec->align = MinAlign(sectionAlign, sym.n_value);
660       subsecMap.push_back({sym.n_value - sectionAddr, nextIsec});
661       subsecEntry = subsecMap.back();
662     }
663   }
664 }
665 
666 OpaqueFile::OpaqueFile(MemoryBufferRef mb, StringRef segName,
667                        StringRef sectName)
668     : InputFile(OpaqueKind, mb) {
669   ConcatInputSection *isec =
670       make<ConcatInputSection>(segName.take_front(16), sectName.take_front(16));
671   isec->file = this;
672   const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
673   isec->data = {buf, mb.getBufferSize()};
674   isec->live = true;
675   subsections.push_back({{0, isec}});
676 }
677 
678 ObjFile::ObjFile(MemoryBufferRef mb, uint32_t modTime, StringRef archiveName)
679     : InputFile(ObjKind, mb), modTime(modTime) {
680   this->archiveName = std::string(archiveName);
681   if (target->wordSize == 8)
682     parse<LP64>();
683   else
684     parse<ILP32>();
685 }
686 
687 template <class LP> void ObjFile::parse() {
688   using Header = typename LP::mach_header;
689   using SegmentCommand = typename LP::segment_command;
690   using Section = typename LP::section;
691   using NList = typename LP::nlist;
692 
693   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
694   auto *hdr = reinterpret_cast<const Header *>(mb.getBufferStart());
695 
696   Architecture arch = getArchitectureFromCpuType(hdr->cputype, hdr->cpusubtype);
697   if (arch != config->arch()) {
698     error(toString(this) + " has architecture " + getArchitectureName(arch) +
699           " which is incompatible with target architecture " +
700           getArchitectureName(config->arch()));
701     return;
702   }
703 
704   if (!checkCompatibility(this))
705     return;
706 
707   for (auto *cmd : findCommands<linker_option_command>(hdr, LC_LINKER_OPTION)) {
708     StringRef data{reinterpret_cast<const char *>(cmd + 1),
709                    cmd->cmdsize - sizeof(linker_option_command)};
710     parseLCLinkerOption(this, cmd->count, data);
711   }
712 
713   ArrayRef<Section> sectionHeaders;
714   if (const load_command *cmd = findCommand(hdr, LP::segmentLCType)) {
715     auto *c = reinterpret_cast<const SegmentCommand *>(cmd);
716     sectionHeaders =
717         ArrayRef<Section>{reinterpret_cast<const Section *>(c + 1), c->nsects};
718     parseSections(sectionHeaders);
719   }
720 
721   // TODO: Error on missing LC_SYMTAB?
722   if (const load_command *cmd = findCommand(hdr, LC_SYMTAB)) {
723     auto *c = reinterpret_cast<const symtab_command *>(cmd);
724     ArrayRef<NList> nList(reinterpret_cast<const NList *>(buf + c->symoff),
725                           c->nsyms);
726     const char *strtab = reinterpret_cast<const char *>(buf) + c->stroff;
727     bool subsectionsViaSymbols = hdr->flags & MH_SUBSECTIONS_VIA_SYMBOLS;
728     parseSymbols<LP>(sectionHeaders, nList, strtab, subsectionsViaSymbols);
729   }
730 
731   // The relocations may refer to the symbols, so we parse them after we have
732   // parsed all the symbols.
733   for (size_t i = 0, n = subsections.size(); i < n; ++i)
734     if (!subsections[i].empty())
735       parseRelocations(sectionHeaders, sectionHeaders[i], subsections[i]);
736 
737   parseDebugInfo();
738   if (config->emitDataInCodeInfo)
739     parseDataInCode();
740 }
741 
742 void ObjFile::parseDebugInfo() {
743   std::unique_ptr<DwarfObject> dObj = DwarfObject::create(this);
744   if (!dObj)
745     return;
746 
747   auto *ctx = make<DWARFContext>(
748       std::move(dObj), "",
749       [&](Error err) {
750         warn(toString(this) + ": " + toString(std::move(err)));
751       },
752       [&](Error warning) {
753         warn(toString(this) + ": " + toString(std::move(warning)));
754       });
755 
756   // TODO: Since object files can contain a lot of DWARF info, we should verify
757   // that we are parsing just the info we need
758   const DWARFContext::compile_unit_range &units = ctx->compile_units();
759   // FIXME: There can be more than one compile unit per object file. See
760   // PR48637.
761   auto it = units.begin();
762   compileUnit = it->get();
763 }
764 
765 void ObjFile::parseDataInCode() {
766   const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
767   const load_command *cmd = findCommand(buf, LC_DATA_IN_CODE);
768   if (!cmd)
769     return;
770   const auto *c = reinterpret_cast<const linkedit_data_command *>(cmd);
771   dataInCodeEntries = {
772       reinterpret_cast<const data_in_code_entry *>(buf + c->dataoff),
773       c->datasize / sizeof(data_in_code_entry)};
774   assert(is_sorted(dataInCodeEntries, [](const data_in_code_entry &lhs,
775                                          const data_in_code_entry &rhs) {
776     return lhs.offset < rhs.offset;
777   }));
778 }
779 
780 // The path can point to either a dylib or a .tbd file.
781 static DylibFile *loadDylib(StringRef path, DylibFile *umbrella) {
782   Optional<MemoryBufferRef> mbref = readFile(path);
783   if (!mbref) {
784     error("could not read dylib file at " + path);
785     return nullptr;
786   }
787   return loadDylib(*mbref, umbrella);
788 }
789 
790 // TBD files are parsed into a series of TAPI documents (InterfaceFiles), with
791 // the first document storing child pointers to the rest of them. When we are
792 // processing a given TBD file, we store that top-level document in
793 // currentTopLevelTapi. When processing re-exports, we search its children for
794 // potentially matching documents in the same TBD file. Note that the children
795 // themselves don't point to further documents, i.e. this is a two-level tree.
796 //
797 // Re-exports can either refer to on-disk files, or to documents within .tbd
798 // files.
799 static DylibFile *findDylib(StringRef path, DylibFile *umbrella,
800                             const InterfaceFile *currentTopLevelTapi) {
801   if (path::is_absolute(path, path::Style::posix))
802     for (StringRef root : config->systemLibraryRoots)
803       if (Optional<std::string> dylibPath =
804               resolveDylibPath((root + path).str()))
805         return loadDylib(*dylibPath, umbrella);
806 
807   // TODO: Handle -dylib_file
808 
809   SmallString<128> newPath;
810   if (config->outputType == MH_EXECUTE &&
811       path.consume_front("@executable_path/")) {
812     // ld64 allows overriding this with the undocumented flag -executable_path.
813     // lld doesn't currently implement that flag.
814     path::append(newPath, path::parent_path(config->outputFile), path);
815     path = newPath;
816   } else if (path.consume_front("@loader_path/")) {
817     fs::real_path(umbrella->getName(), newPath);
818     path::remove_filename(newPath);
819     path::append(newPath, path);
820     path = newPath;
821   } else if (path.startswith("@rpath/")) {
822     for (StringRef rpath : umbrella->rpaths) {
823       newPath.clear();
824       if (rpath.consume_front("@loader_path/")) {
825         fs::real_path(umbrella->getName(), newPath);
826         path::remove_filename(newPath);
827       }
828       path::append(newPath, rpath, path.drop_front(strlen("@rpath/")));
829       if (Optional<std::string> dylibPath = resolveDylibPath(newPath))
830         return loadDylib(*dylibPath, umbrella);
831     }
832   }
833 
834   if (currentTopLevelTapi) {
835     for (InterfaceFile &child :
836          make_pointee_range(currentTopLevelTapi->documents())) {
837       assert(child.documents().empty());
838       if (path == child.getInstallName()) {
839         auto file = make<DylibFile>(child, umbrella);
840         file->parseReexports(child);
841         return file;
842       }
843     }
844   }
845 
846   if (Optional<std::string> dylibPath = resolveDylibPath(path))
847     return loadDylib(*dylibPath, umbrella);
848 
849   return nullptr;
850 }
851 
852 // If a re-exported dylib is public (lives in /usr/lib or
853 // /System/Library/Frameworks), then it is considered implicitly linked: we
854 // should bind to its symbols directly instead of via the re-exporting umbrella
855 // library.
856 static bool isImplicitlyLinked(StringRef path) {
857   if (!config->implicitDylibs)
858     return false;
859 
860   if (path::parent_path(path) == "/usr/lib")
861     return true;
862 
863   // Match /System/Library/Frameworks/$FOO.framework/**/$FOO
864   if (path.consume_front("/System/Library/Frameworks/")) {
865     StringRef frameworkName = path.take_until([](char c) { return c == '.'; });
866     return path::filename(path) == frameworkName;
867   }
868 
869   return false;
870 }
871 
872 static void loadReexport(StringRef path, DylibFile *umbrella,
873                          const InterfaceFile *currentTopLevelTapi) {
874   DylibFile *reexport = findDylib(path, umbrella, currentTopLevelTapi);
875   if (!reexport)
876     error("unable to locate re-export with install name " + path);
877 }
878 
879 DylibFile::DylibFile(MemoryBufferRef mb, DylibFile *umbrella,
880                      bool isBundleLoader)
881     : InputFile(DylibKind, mb), refState(RefState::Unreferenced),
882       isBundleLoader(isBundleLoader) {
883   assert(!isBundleLoader || !umbrella);
884   if (umbrella == nullptr)
885     umbrella = this;
886   this->umbrella = umbrella;
887 
888   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
889   auto *hdr = reinterpret_cast<const mach_header *>(mb.getBufferStart());
890 
891   // Initialize installName.
892   if (const load_command *cmd = findCommand(hdr, LC_ID_DYLIB)) {
893     auto *c = reinterpret_cast<const dylib_command *>(cmd);
894     currentVersion = read32le(&c->dylib.current_version);
895     compatibilityVersion = read32le(&c->dylib.compatibility_version);
896     installName =
897         reinterpret_cast<const char *>(cmd) + read32le(&c->dylib.name);
898   } else if (!isBundleLoader) {
899     // macho_executable and macho_bundle don't have LC_ID_DYLIB,
900     // so it's OK.
901     error("dylib " + toString(this) + " missing LC_ID_DYLIB load command");
902     return;
903   }
904 
905   if (config->printEachFile)
906     message(toString(this));
907   inputFiles.insert(this);
908 
909   deadStrippable = hdr->flags & MH_DEAD_STRIPPABLE_DYLIB;
910 
911   if (!checkCompatibility(this))
912     return;
913 
914   for (auto *cmd : findCommands<rpath_command>(hdr, LC_RPATH)) {
915     StringRef rpath{reinterpret_cast<const char *>(cmd) + cmd->path};
916     rpaths.push_back(rpath);
917   }
918 
919   // Initialize symbols.
920   exportingFile = isImplicitlyLinked(installName) ? this : this->umbrella;
921   if (const load_command *cmd = findCommand(hdr, LC_DYLD_INFO_ONLY)) {
922     auto *c = reinterpret_cast<const dyld_info_command *>(cmd);
923     parseTrie(buf + c->export_off, c->export_size,
924               [&](const Twine &name, uint64_t flags) {
925                 StringRef savedName = saver.save(name);
926                 if (handleLDSymbol(savedName))
927                   return;
928                 bool isWeakDef = flags & EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION;
929                 bool isTlv = flags & EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL;
930                 symbols.push_back(symtab->addDylib(savedName, exportingFile,
931                                                    isWeakDef, isTlv));
932               });
933   } else {
934     error("LC_DYLD_INFO_ONLY not found in " + toString(this));
935     return;
936   }
937 }
938 
939 void DylibFile::parseLoadCommands(MemoryBufferRef mb) {
940   auto *hdr = reinterpret_cast<const mach_header *>(mb.getBufferStart());
941   const uint8_t *p = reinterpret_cast<const uint8_t *>(mb.getBufferStart()) +
942                      target->headerSize;
943   for (uint32_t i = 0, n = hdr->ncmds; i < n; ++i) {
944     auto *cmd = reinterpret_cast<const load_command *>(p);
945     p += cmd->cmdsize;
946 
947     if (!(hdr->flags & MH_NO_REEXPORTED_DYLIBS) &&
948         cmd->cmd == LC_REEXPORT_DYLIB) {
949       const auto *c = reinterpret_cast<const dylib_command *>(cmd);
950       StringRef reexportPath =
951           reinterpret_cast<const char *>(c) + read32le(&c->dylib.name);
952       loadReexport(reexportPath, exportingFile, nullptr);
953     }
954 
955     // FIXME: What about LC_LOAD_UPWARD_DYLIB, LC_LAZY_LOAD_DYLIB,
956     // LC_LOAD_WEAK_DYLIB, LC_REEXPORT_DYLIB (..are reexports from dylibs with
957     // MH_NO_REEXPORTED_DYLIBS loaded for -flat_namespace)?
958     if (config->namespaceKind == NamespaceKind::flat &&
959         cmd->cmd == LC_LOAD_DYLIB) {
960       const auto *c = reinterpret_cast<const dylib_command *>(cmd);
961       StringRef dylibPath =
962           reinterpret_cast<const char *>(c) + read32le(&c->dylib.name);
963       DylibFile *dylib = findDylib(dylibPath, umbrella, nullptr);
964       if (!dylib)
965         error(Twine("unable to locate library '") + dylibPath +
966               "' loaded from '" + toString(this) + "' for -flat_namespace");
967     }
968   }
969 }
970 
971 // Some versions of XCode ship with .tbd files that don't have the right
972 // platform settings.
973 static constexpr std::array<StringRef, 3> skipPlatformChecks{
974     "/usr/lib/system/libsystem_kernel.dylib",
975     "/usr/lib/system/libsystem_platform.dylib",
976     "/usr/lib/system/libsystem_pthread.dylib"};
977 
978 DylibFile::DylibFile(const InterfaceFile &interface, DylibFile *umbrella,
979                      bool isBundleLoader)
980     : InputFile(DylibKind, interface), refState(RefState::Unreferenced),
981       isBundleLoader(isBundleLoader) {
982   // FIXME: Add test for the missing TBD code path.
983 
984   if (umbrella == nullptr)
985     umbrella = this;
986   this->umbrella = umbrella;
987 
988   installName = saver.save(interface.getInstallName());
989   compatibilityVersion = interface.getCompatibilityVersion().rawValue();
990   currentVersion = interface.getCurrentVersion().rawValue();
991 
992   if (config->printEachFile)
993     message(toString(this));
994   inputFiles.insert(this);
995 
996   if (!is_contained(skipPlatformChecks, installName) &&
997       !is_contained(interface.targets(), config->platformInfo.target)) {
998     error(toString(this) + " is incompatible with " +
999           std::string(config->platformInfo.target));
1000     return;
1001   }
1002 
1003   exportingFile = isImplicitlyLinked(installName) ? this : umbrella;
1004   auto addSymbol = [&](const Twine &name) -> void {
1005     symbols.push_back(symtab->addDylib(saver.save(name), exportingFile,
1006                                        /*isWeakDef=*/false,
1007                                        /*isTlv=*/false));
1008   };
1009   // TODO(compnerd) filter out symbols based on the target platform
1010   // TODO: handle weak defs, thread locals
1011   for (const auto *symbol : interface.symbols()) {
1012     if (!symbol->getArchitectures().has(config->arch()))
1013       continue;
1014 
1015     if (handleLDSymbol(symbol->getName()))
1016       continue;
1017 
1018     switch (symbol->getKind()) {
1019     case SymbolKind::GlobalSymbol:
1020       addSymbol(symbol->getName());
1021       break;
1022     case SymbolKind::ObjectiveCClass:
1023       // XXX ld64 only creates these symbols when -ObjC is passed in. We may
1024       // want to emulate that.
1025       addSymbol(objc::klass + symbol->getName());
1026       addSymbol(objc::metaclass + symbol->getName());
1027       break;
1028     case SymbolKind::ObjectiveCClassEHType:
1029       addSymbol(objc::ehtype + symbol->getName());
1030       break;
1031     case SymbolKind::ObjectiveCInstanceVariable:
1032       addSymbol(objc::ivar + symbol->getName());
1033       break;
1034     }
1035   }
1036 }
1037 
1038 void DylibFile::parseReexports(const InterfaceFile &interface) {
1039   const InterfaceFile *topLevel =
1040       interface.getParent() == nullptr ? &interface : interface.getParent();
1041   for (InterfaceFileRef intfRef : interface.reexportedLibraries()) {
1042     InterfaceFile::const_target_range targets = intfRef.targets();
1043     if (is_contained(skipPlatformChecks, intfRef.getInstallName()) ||
1044         is_contained(targets, config->platformInfo.target))
1045       loadReexport(intfRef.getInstallName(), exportingFile, topLevel);
1046   }
1047 }
1048 
1049 // $ld$ symbols modify the properties/behavior of the library (e.g. its install
1050 // name, compatibility version or hide/add symbols) for specific target
1051 // versions.
1052 bool DylibFile::handleLDSymbol(StringRef originalName) {
1053   if (!originalName.startswith("$ld$"))
1054     return false;
1055 
1056   StringRef action;
1057   StringRef name;
1058   std::tie(action, name) = originalName.drop_front(strlen("$ld$")).split('$');
1059   if (action == "previous")
1060     handleLDPreviousSymbol(name, originalName);
1061   else if (action == "install_name")
1062     handleLDInstallNameSymbol(name, originalName);
1063   return true;
1064 }
1065 
1066 void DylibFile::handleLDPreviousSymbol(StringRef name, StringRef originalName) {
1067   // originalName: $ld$ previous $ <installname> $ <compatversion> $
1068   // <platformstr> $ <startversion> $ <endversion> $ <symbol-name> $
1069   StringRef installName;
1070   StringRef compatVersion;
1071   StringRef platformStr;
1072   StringRef startVersion;
1073   StringRef endVersion;
1074   StringRef symbolName;
1075   StringRef rest;
1076 
1077   std::tie(installName, name) = name.split('$');
1078   std::tie(compatVersion, name) = name.split('$');
1079   std::tie(platformStr, name) = name.split('$');
1080   std::tie(startVersion, name) = name.split('$');
1081   std::tie(endVersion, name) = name.split('$');
1082   std::tie(symbolName, rest) = name.split('$');
1083   // TODO: ld64 contains some logic for non-empty symbolName as well.
1084   if (!symbolName.empty())
1085     return;
1086   unsigned platform;
1087   if (platformStr.getAsInteger(10, platform) ||
1088       platform != static_cast<unsigned>(config->platform()))
1089     return;
1090 
1091   VersionTuple start;
1092   if (start.tryParse(startVersion)) {
1093     warn("failed to parse start version, symbol '" + originalName +
1094          "' ignored");
1095     return;
1096   }
1097   VersionTuple end;
1098   if (end.tryParse(endVersion)) {
1099     warn("failed to parse end version, symbol '" + originalName + "' ignored");
1100     return;
1101   }
1102   if (config->platformInfo.minimum < start ||
1103       config->platformInfo.minimum >= end)
1104     return;
1105 
1106   this->installName = saver.save(installName);
1107 
1108   if (!compatVersion.empty()) {
1109     VersionTuple cVersion;
1110     if (cVersion.tryParse(compatVersion)) {
1111       warn("failed to parse compatibility version, symbol '" + originalName +
1112            "' ignored");
1113       return;
1114     }
1115     compatibilityVersion = encodeVersion(cVersion);
1116   }
1117 }
1118 
1119 void DylibFile::handleLDInstallNameSymbol(StringRef name,
1120                                           StringRef originalName) {
1121   // originalName: $ld$ install_name $ os<version> $ install_name
1122   StringRef condition, installName;
1123   std::tie(condition, installName) = name.split('$');
1124   VersionTuple version;
1125   if (!condition.consume_front("os") || version.tryParse(condition))
1126     warn("failed to parse os version, symbol '" + originalName + "' ignored");
1127   else if (version == config->platformInfo.minimum)
1128     this->installName = saver.save(installName);
1129 }
1130 
1131 ArchiveFile::ArchiveFile(std::unique_ptr<object::Archive> &&f)
1132     : InputFile(ArchiveKind, f->getMemoryBufferRef()), file(std::move(f)) {
1133   for (const object::Archive::Symbol &sym : file->symbols())
1134     symtab->addLazy(sym.getName(), this, sym);
1135 }
1136 
1137 void ArchiveFile::fetch(const object::Archive::Symbol &sym) {
1138   object::Archive::Child c =
1139       CHECK(sym.getMember(), toString(this) +
1140                                  ": could not get the member for symbol " +
1141                                  toMachOString(sym));
1142 
1143   if (!seen.insert(c.getChildOffset()).second)
1144     return;
1145 
1146   MemoryBufferRef mb =
1147       CHECK(c.getMemoryBufferRef(),
1148             toString(this) +
1149                 ": could not get the buffer for the member defining symbol " +
1150                 toMachOString(sym));
1151 
1152   if (tar && c.getParent()->isThin())
1153     tar->append(relativeToRoot(CHECK(c.getFullName(), this)), mb.getBuffer());
1154 
1155   uint32_t modTime = toTimeT(
1156       CHECK(c.getLastModified(), toString(this) +
1157                                      ": could not get the modification time "
1158                                      "for the member defining symbol " +
1159                                      toMachOString(sym)));
1160 
1161   // `sym` is owned by a LazySym, which will be replace<>()d by make<ObjFile>
1162   // and become invalid after that call. Copy it to the stack so we can refer
1163   // to it later.
1164   const object::Archive::Symbol symCopy = sym;
1165 
1166   if (Optional<InputFile *> file =
1167           loadArchiveMember(mb, modTime, getName(), /*objCOnly=*/false)) {
1168     inputFiles.insert(*file);
1169     // ld64 doesn't demangle sym here even with -demangle.
1170     // Match that: intentionally don't call toMachOString().
1171     printArchiveMemberLoad(symCopy.getName(), *file);
1172   }
1173 }
1174 
1175 static macho::Symbol *createBitcodeSymbol(const lto::InputFile::Symbol &objSym,
1176                                           BitcodeFile &file) {
1177   StringRef name = saver.save(objSym.getName());
1178 
1179   // TODO: support weak references
1180   if (objSym.isUndefined())
1181     return symtab->addUndefined(name, &file, /*isWeakRef=*/false);
1182 
1183   assert(!objSym.isCommon() && "TODO: support common symbols in LTO");
1184 
1185   // TODO: Write a test demonstrating why computing isPrivateExtern before
1186   // LTO compilation is important.
1187   bool isPrivateExtern = false;
1188   switch (objSym.getVisibility()) {
1189   case GlobalValue::HiddenVisibility:
1190     isPrivateExtern = true;
1191     break;
1192   case GlobalValue::ProtectedVisibility:
1193     error(name + " has protected visibility, which is not supported by Mach-O");
1194     break;
1195   case GlobalValue::DefaultVisibility:
1196     break;
1197   }
1198 
1199   return symtab->addDefined(name, &file, /*isec=*/nullptr, /*value=*/0,
1200                             /*size=*/0, objSym.isWeak(), isPrivateExtern,
1201                             /*isThumb=*/false,
1202                             /*isReferencedDynamically=*/false,
1203                             /*noDeadStrip=*/false);
1204 }
1205 
1206 BitcodeFile::BitcodeFile(MemoryBufferRef mbref)
1207     : InputFile(BitcodeKind, mbref) {
1208   obj = check(lto::InputFile::create(mbref));
1209 
1210   // Convert LTO Symbols to LLD Symbols in order to perform resolution. The
1211   // "winning" symbol will then be marked as Prevailing at LTO compilation
1212   // time.
1213   for (const lto::InputFile::Symbol &objSym : obj->symbols())
1214     symbols.push_back(createBitcodeSymbol(objSym, *this));
1215 }
1216 
1217 template void ObjFile::parse<LP64>();
1218