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