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