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 "Target.h"
57 
58 #include "lld/Common/DWARF.h"
59 #include "lld/Common/ErrorHandler.h"
60 #include "lld/Common/Memory.h"
61 #include "lld/Common/Reproduce.h"
62 #include "llvm/ADT/iterator.h"
63 #include "llvm/BinaryFormat/MachO.h"
64 #include "llvm/LTO/LTO.h"
65 #include "llvm/Support/Endian.h"
66 #include "llvm/Support/MemoryBuffer.h"
67 #include "llvm/Support/Path.h"
68 #include "llvm/Support/TarWriter.h"
69 
70 using namespace llvm;
71 using namespace llvm::MachO;
72 using namespace llvm::support::endian;
73 using namespace llvm::sys;
74 using namespace lld;
75 using namespace lld::macho;
76 
77 // Returns "<internal>", "foo.a(bar.o)", or "baz.o".
78 std::string lld::toString(const InputFile *f) {
79   if (!f)
80     return "<internal>";
81   if (f->archiveName.empty())
82     return std::string(f->getName());
83   return (path::filename(f->archiveName) + "(" + path::filename(f->getName()) +
84           ")")
85       .str();
86 }
87 
88 std::vector<InputFile *> macho::inputFiles;
89 std::unique_ptr<TarWriter> macho::tar;
90 int InputFile::idCount = 0;
91 
92 // Open a given file path and return it as a memory-mapped file.
93 Optional<MemoryBufferRef> macho::readFile(StringRef path) {
94   // Open a file.
95   auto mbOrErr = MemoryBuffer::getFile(path);
96   if (auto ec = mbOrErr.getError()) {
97     error("cannot open " + path + ": " + ec.message());
98     return None;
99   }
100 
101   std::unique_ptr<MemoryBuffer> &mb = *mbOrErr;
102   MemoryBufferRef mbref = mb->getMemBufferRef();
103   make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take mb ownership
104 
105   // If this is a regular non-fat file, return it.
106   const char *buf = mbref.getBufferStart();
107   auto *hdr = reinterpret_cast<const MachO::fat_header *>(buf);
108   if (read32be(&hdr->magic) != MachO::FAT_MAGIC) {
109     if (tar)
110       tar->append(relativeToRoot(path), mbref.getBuffer());
111     return mbref;
112   }
113 
114   // Object files and archive files may be fat files, which contains
115   // multiple real files for different CPU ISAs. Here, we search for a
116   // file that matches with the current link target and returns it as
117   // a MemoryBufferRef.
118   auto *arch = reinterpret_cast<const MachO::fat_arch *>(buf + sizeof(*hdr));
119 
120   for (uint32_t i = 0, n = read32be(&hdr->nfat_arch); i < n; ++i) {
121     if (reinterpret_cast<const char *>(arch + i + 1) >
122         buf + mbref.getBufferSize()) {
123       error(path + ": fat_arch struct extends beyond end of file");
124       return None;
125     }
126 
127     if (read32be(&arch[i].cputype) != target->cpuType ||
128         read32be(&arch[i].cpusubtype) != target->cpuSubtype)
129       continue;
130 
131     uint32_t offset = read32be(&arch[i].offset);
132     uint32_t size = read32be(&arch[i].size);
133     if (offset + size > mbref.getBufferSize())
134       error(path + ": slice extends beyond end of file");
135     if (tar)
136       tar->append(relativeToRoot(path), mbref.getBuffer());
137     return MemoryBufferRef(StringRef(buf + offset, size), path.copy(bAlloc));
138   }
139 
140   error("unable to find matching architecture in " + path);
141   return None;
142 }
143 
144 const load_command *macho::findCommand(const mach_header_64 *hdr,
145                                        uint32_t type) {
146   const uint8_t *p =
147       reinterpret_cast<const uint8_t *>(hdr) + sizeof(mach_header_64);
148 
149   for (uint32_t i = 0, n = hdr->ncmds; i < n; ++i) {
150     auto *cmd = reinterpret_cast<const load_command *>(p);
151     if (cmd->cmd == type)
152       return cmd;
153     p += cmd->cmdsize;
154   }
155   return nullptr;
156 }
157 
158 void InputFile::parseSections(ArrayRef<section_64> sections) {
159   subsections.reserve(sections.size());
160   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
161 
162   for (const section_64 &sec : sections) {
163     InputSection *isec = make<InputSection>();
164     isec->file = this;
165     isec->name =
166         StringRef(sec.sectname, strnlen(sec.sectname, sizeof(sec.sectname)));
167     isec->segname =
168         StringRef(sec.segname, strnlen(sec.segname, sizeof(sec.segname)));
169     isec->data = {isZeroFill(sec.flags) ? nullptr : buf + sec.offset,
170                   static_cast<size_t>(sec.size)};
171     if (sec.align >= 32)
172       error("alignment " + std::to_string(sec.align) + " of section " +
173             isec->name + " is too large");
174     else
175       isec->align = 1 << sec.align;
176     isec->flags = sec.flags;
177     subsections.push_back({{0, isec}});
178   }
179 }
180 
181 // Find the subsection corresponding to the greatest section offset that is <=
182 // that of the given offset.
183 //
184 // offset: an offset relative to the start of the original InputSection (before
185 // any subsection splitting has occurred). It will be updated to represent the
186 // same location as an offset relative to the start of the containing
187 // subsection.
188 static InputSection *findContainingSubsection(SubsectionMap &map,
189                                               uint32_t *offset) {
190   auto it = std::prev(map.upper_bound(*offset));
191   *offset -= it->first;
192   return it->second;
193 }
194 
195 void InputFile::parseRelocations(const section_64 &sec,
196                                  SubsectionMap &subsecMap) {
197   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
198   ArrayRef<any_relocation_info> anyRelInfos(
199       reinterpret_cast<const any_relocation_info *>(buf + sec.reloff),
200       sec.nreloc);
201 
202   for (const any_relocation_info &anyRelInfo : anyRelInfos) {
203     if (anyRelInfo.r_word0 & R_SCATTERED)
204       fatal("TODO: Scattered relocations not supported");
205 
206     auto relInfo = reinterpret_cast<const relocation_info &>(anyRelInfo);
207 
208     Reloc r;
209     r.type = relInfo.r_type;
210     r.pcrel = relInfo.r_pcrel;
211     r.length = relInfo.r_length;
212     uint64_t rawAddend = target->getImplicitAddend(mb, sec, relInfo);
213 
214     if (relInfo.r_extern) {
215       r.referent = symbols[relInfo.r_symbolnum];
216       r.addend = rawAddend;
217     } else {
218       if (relInfo.r_symbolnum == 0 || relInfo.r_symbolnum > subsections.size())
219         fatal("invalid section index in relocation for offset " +
220               std::to_string(r.offset) + " in section " + sec.sectname +
221               " of " + getName());
222 
223       SubsectionMap &referentSubsecMap = subsections[relInfo.r_symbolnum - 1];
224       const section_64 &referentSec = sectionHeaders[relInfo.r_symbolnum - 1];
225       uint32_t referentOffset;
226       if (relInfo.r_pcrel) {
227         // The implicit addend for pcrel section relocations is the pcrel offset
228         // in terms of the addresses in the input file. Here we adjust it so
229         // that it describes the offset from the start of the referent section.
230         // TODO: The offset of 4 is probably not right for ARM64, nor for
231         //       relocations with r_length != 2.
232         referentOffset =
233             sec.addr + relInfo.r_address + 4 + rawAddend - referentSec.addr;
234       } else {
235         // The addend for a non-pcrel relocation is its absolute address.
236         referentOffset = rawAddend - referentSec.addr;
237       }
238       r.referent = findContainingSubsection(referentSubsecMap, &referentOffset);
239       r.addend = referentOffset;
240     }
241 
242     r.offset = relInfo.r_address;
243     InputSection *subsec = findContainingSubsection(subsecMap, &r.offset);
244     subsec->relocs.push_back(r);
245   }
246 }
247 
248 static macho::Symbol *createDefined(const structs::nlist_64 &sym,
249                                     StringRef name, InputSection *isec,
250                                     uint32_t value) {
251   if (sym.n_type & N_EXT)
252     // Global defined symbol
253     return symtab->addDefined(name, isec, value, sym.n_desc & N_WEAK_DEF);
254   // Local defined symbol
255   return make<Defined>(name, isec, value, sym.n_desc & N_WEAK_DEF,
256                        /*isExternal=*/false);
257 }
258 
259 // Absolute symbols are defined symbols that do not have an associated
260 // InputSection. They cannot be weak.
261 static macho::Symbol *createAbsolute(const structs::nlist_64 &sym,
262                                      StringRef name) {
263   if (sym.n_type & N_EXT)
264     return symtab->addDefined(name, nullptr, sym.n_value, /*isWeakDef=*/false);
265   return make<Defined>(name, nullptr, sym.n_value, /*isWeakDef=*/false,
266                        /*isExternal=*/false);
267 }
268 
269 macho::Symbol *InputFile::parseNonSectionSymbol(const structs::nlist_64 &sym,
270                                                 StringRef name) {
271   uint8_t type = sym.n_type & N_TYPE;
272   switch (type) {
273   case N_UNDF:
274     return sym.n_value == 0
275                ? symtab->addUndefined(name)
276                : symtab->addCommon(name, this, sym.n_value,
277                                    1 << GET_COMM_ALIGN(sym.n_desc));
278   case N_ABS:
279     return createAbsolute(sym, name);
280   case N_PBUD:
281   case N_INDR:
282     error("TODO: support symbols of type " + std::to_string(type));
283     return nullptr;
284   case N_SECT:
285     llvm_unreachable(
286         "N_SECT symbols should not be passed to parseNonSectionSymbol");
287   default:
288     llvm_unreachable("invalid symbol type");
289   }
290 }
291 
292 void InputFile::parseSymbols(ArrayRef<structs::nlist_64> nList,
293                              const char *strtab, bool subsectionsViaSymbols) {
294   // resize(), not reserve(), because we are going to create N_ALT_ENTRY symbols
295   // out-of-sequence.
296   symbols.resize(nList.size());
297   std::vector<size_t> altEntrySymIdxs;
298 
299   for (size_t i = 0, n = nList.size(); i < n; ++i) {
300     const structs::nlist_64 &sym = nList[i];
301     StringRef name = strtab + sym.n_strx;
302 
303     if ((sym.n_type & N_TYPE) != N_SECT) {
304       symbols[i] = parseNonSectionSymbol(sym, name);
305       continue;
306     }
307 
308     const section_64 &sec = sectionHeaders[sym.n_sect - 1];
309     SubsectionMap &subsecMap = subsections[sym.n_sect - 1];
310     uint64_t offset = sym.n_value - sec.addr;
311 
312     // If the input file does not use subsections-via-symbols, all symbols can
313     // use the same subsection. Otherwise, we must split the sections along
314     // symbol boundaries.
315     if (!subsectionsViaSymbols) {
316       symbols[i] = createDefined(sym, name, subsecMap[0], offset);
317       continue;
318     }
319 
320     // nList entries aren't necessarily arranged in address order. Therefore,
321     // we can't create alt-entry symbols at this point because a later symbol
322     // may split its section, which may affect which subsection the alt-entry
323     // symbol is assigned to. So we need to handle them in a second pass below.
324     if (sym.n_desc & N_ALT_ENTRY) {
325       altEntrySymIdxs.push_back(i);
326       continue;
327     }
328 
329     // Find the subsection corresponding to the greatest section offset that is
330     // <= that of the current symbol. The subsection that we find either needs
331     // to be used directly or split in two.
332     uint32_t firstSize = offset;
333     InputSection *firstIsec = findContainingSubsection(subsecMap, &firstSize);
334 
335     if (firstSize == 0) {
336       // Alias of an existing symbol, or the first symbol in the section. These
337       // are handled by reusing the existing section.
338       symbols[i] = createDefined(sym, name, firstIsec, 0);
339       continue;
340     }
341 
342     // We saw a symbol definition at a new offset. Split the section into two
343     // subsections. The new symbol uses the second subsection.
344     auto *secondIsec = make<InputSection>(*firstIsec);
345     secondIsec->data = firstIsec->data.slice(firstSize);
346     firstIsec->data = firstIsec->data.slice(0, firstSize);
347     // TODO: ld64 appears to preserve the original alignment as well as each
348     // subsection's offset from the last aligned address. We should consider
349     // emulating that behavior.
350     secondIsec->align = MinAlign(firstIsec->align, offset);
351 
352     subsecMap[offset] = secondIsec;
353     // By construction, the symbol will be at offset zero in the new section.
354     symbols[i] = createDefined(sym, name, secondIsec, 0);
355   }
356 
357   for (size_t idx : altEntrySymIdxs) {
358     const structs::nlist_64 &sym = nList[idx];
359     StringRef name = strtab + sym.n_strx;
360     SubsectionMap &subsecMap = subsections[sym.n_sect - 1];
361     uint32_t off = sym.n_value - sectionHeaders[sym.n_sect - 1].addr;
362     InputSection *subsec = findContainingSubsection(subsecMap, &off);
363     symbols[idx] = createDefined(sym, name, subsec, off);
364   }
365 }
366 
367 OpaqueFile::OpaqueFile(MemoryBufferRef mb, StringRef segName,
368                        StringRef sectName)
369     : InputFile(OpaqueKind, mb) {
370   InputSection *isec = make<InputSection>();
371   isec->file = this;
372   isec->name = sectName.take_front(16);
373   isec->segname = segName.take_front(16);
374   const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
375   isec->data = {buf, mb.getBufferSize()};
376   subsections.push_back({{0, isec}});
377 }
378 
379 ObjFile::ObjFile(MemoryBufferRef mb, uint32_t modTime, StringRef archiveName)
380     : InputFile(ObjKind, mb), modTime(modTime) {
381   this->archiveName = std::string(archiveName);
382 
383   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
384   auto *hdr = reinterpret_cast<const mach_header_64 *>(mb.getBufferStart());
385 
386   if (const load_command *cmd = findCommand(hdr, LC_LINKER_OPTION)) {
387     auto *c = reinterpret_cast<const linker_option_command *>(cmd);
388     StringRef data{reinterpret_cast<const char *>(c + 1),
389                    c->cmdsize - sizeof(linker_option_command)};
390     parseLCLinkerOption(this, c->count, data);
391   }
392 
393   if (const load_command *cmd = findCommand(hdr, LC_SEGMENT_64)) {
394     auto *c = reinterpret_cast<const segment_command_64 *>(cmd);
395     sectionHeaders = ArrayRef<section_64>{
396         reinterpret_cast<const section_64 *>(c + 1), c->nsects};
397     parseSections(sectionHeaders);
398   }
399 
400   // TODO: Error on missing LC_SYMTAB?
401   if (const load_command *cmd = findCommand(hdr, LC_SYMTAB)) {
402     auto *c = reinterpret_cast<const symtab_command *>(cmd);
403     ArrayRef<structs::nlist_64> nList(
404         reinterpret_cast<const structs::nlist_64 *>(buf + c->symoff), c->nsyms);
405     const char *strtab = reinterpret_cast<const char *>(buf) + c->stroff;
406     bool subsectionsViaSymbols = hdr->flags & MH_SUBSECTIONS_VIA_SYMBOLS;
407     parseSymbols(nList, strtab, subsectionsViaSymbols);
408   }
409 
410   // The relocations may refer to the symbols, so we parse them after we have
411   // parsed all the symbols.
412   for (size_t i = 0, n = subsections.size(); i < n; ++i)
413     parseRelocations(sectionHeaders[i], subsections[i]);
414 
415   parseDebugInfo();
416 }
417 
418 void ObjFile::parseDebugInfo() {
419   std::unique_ptr<DwarfObject> dObj = DwarfObject::create(this);
420   if (!dObj)
421     return;
422 
423   auto *ctx = make<DWARFContext>(
424       std::move(dObj), "",
425       [&](Error err) {
426         warn(toString(this) + ": " + toString(std::move(err)));
427       },
428       [&](Error warning) {
429         warn(toString(this) + ": " + toString(std::move(warning)));
430       });
431 
432   // TODO: Since object files can contain a lot of DWARF info, we should verify
433   // that we are parsing just the info we need
434   const DWARFContext::compile_unit_range &units = ctx->compile_units();
435   auto it = units.begin();
436   compileUnit = it->get();
437   assert(std::next(it) == units.end());
438 }
439 
440 // The path can point to either a dylib or a .tbd file.
441 static Optional<DylibFile *> loadDylib(StringRef path, DylibFile *umbrella) {
442   Optional<MemoryBufferRef> mbref = readFile(path);
443   if (!mbref) {
444     error("could not read dylib file at " + path);
445     return {};
446   }
447 
448   file_magic magic = identify_magic(mbref->getBuffer());
449   if (magic == file_magic::tapi_file)
450     return makeDylibFromTAPI(*mbref, umbrella);
451   assert(magic == file_magic::macho_dynamically_linked_shared_lib);
452   return make<DylibFile>(*mbref, umbrella);
453 }
454 
455 // TBD files are parsed into a series of TAPI documents (InterfaceFiles), with
456 // the first document storing child pointers to the rest of them. When we are
457 // processing a given TBD file, we store that top-level document here. When
458 // processing re-exports, we search its children for potentially matching
459 // documents in the same TBD file. Note that the children themselves don't
460 // point to further documents, i.e. this is a two-level tree.
461 //
462 // ld64 allows a TAPI re-export to reference documents nested within other TBD
463 // files, but that seems like a strange design, so this is an intentional
464 // deviation.
465 const InterfaceFile *currentTopLevelTapi = nullptr;
466 
467 // Re-exports can either refer to on-disk files, or to documents within .tbd
468 // files.
469 static Optional<DylibFile *> loadReexport(StringRef path, DylibFile *umbrella) {
470   if (path::is_absolute(path, path::Style::posix))
471     for (StringRef root : config->systemLibraryRoots)
472       if (Optional<std::string> dylibPath =
473               resolveDylibPath((root + path).str()))
474         return loadDylib(*dylibPath, umbrella);
475 
476   // TODO: Expand @loader_path, @executable_path etc
477 
478   if (currentTopLevelTapi) {
479     for (InterfaceFile &child :
480          make_pointee_range(currentTopLevelTapi->documents())) {
481       if (path == child.getInstallName())
482         return make<DylibFile>(child, umbrella);
483       assert(child.documents().empty());
484     }
485   }
486 
487   if (Optional<std::string> dylibPath = resolveDylibPath(path))
488     return loadDylib(*dylibPath, umbrella);
489 
490   error("unable to locate re-export with install name " + path);
491   return {};
492 }
493 
494 DylibFile::DylibFile(MemoryBufferRef mb, DylibFile *umbrella)
495     : InputFile(DylibKind, mb) {
496   if (umbrella == nullptr)
497     umbrella = this;
498 
499   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
500   auto *hdr = reinterpret_cast<const mach_header_64 *>(mb.getBufferStart());
501 
502   // Initialize dylibName.
503   if (const load_command *cmd = findCommand(hdr, LC_ID_DYLIB)) {
504     auto *c = reinterpret_cast<const dylib_command *>(cmd);
505     dylibName = reinterpret_cast<const char *>(cmd) + read32le(&c->dylib.name);
506   } else {
507     error("dylib " + toString(this) + " missing LC_ID_DYLIB load command");
508     return;
509   }
510 
511   // Initialize symbols.
512   // TODO: if a re-exported dylib is public (lives in /usr/lib or
513   // /System/Library/Frameworks), we should bind to its symbols directly
514   // instead of the re-exporting umbrella library.
515   if (const load_command *cmd = findCommand(hdr, LC_DYLD_INFO_ONLY)) {
516     auto *c = reinterpret_cast<const dyld_info_command *>(cmd);
517     parseTrie(buf + c->export_off, c->export_size,
518               [&](const Twine &name, uint64_t flags) {
519                 bool isWeakDef = flags & EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION;
520                 bool isTlv = flags & EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL;
521                 symbols.push_back(symtab->addDylib(saver.save(name), umbrella,
522                                                    isWeakDef, isTlv));
523               });
524   } else {
525     error("LC_DYLD_INFO_ONLY not found in " + toString(this));
526     return;
527   }
528 
529   if (hdr->flags & MH_NO_REEXPORTED_DYLIBS)
530     return;
531 
532   const uint8_t *p =
533       reinterpret_cast<const uint8_t *>(hdr) + sizeof(mach_header_64);
534   for (uint32_t i = 0, n = hdr->ncmds; i < n; ++i) {
535     auto *cmd = reinterpret_cast<const load_command *>(p);
536     p += cmd->cmdsize;
537     if (cmd->cmd != LC_REEXPORT_DYLIB)
538       continue;
539 
540     auto *c = reinterpret_cast<const dylib_command *>(cmd);
541     StringRef reexportPath =
542         reinterpret_cast<const char *>(c) + read32le(&c->dylib.name);
543     if (Optional<DylibFile *> reexport = loadReexport(reexportPath, umbrella))
544       reexported.push_back(*reexport);
545   }
546 }
547 
548 DylibFile::DylibFile(const InterfaceFile &interface, DylibFile *umbrella)
549     : InputFile(DylibKind, interface) {
550   if (umbrella == nullptr)
551     umbrella = this;
552 
553   dylibName = saver.save(interface.getInstallName());
554   auto addSymbol = [&](const Twine &name) -> void {
555     symbols.push_back(symtab->addDylib(saver.save(name), umbrella,
556                                        /*isWeakDef=*/false,
557                                        /*isTlv=*/false));
558   };
559   // TODO(compnerd) filter out symbols based on the target platform
560   // TODO: handle weak defs, thread locals
561   for (const auto symbol : interface.symbols()) {
562     if (!symbol->getArchitectures().has(config->arch))
563       continue;
564 
565     switch (symbol->getKind()) {
566     case SymbolKind::GlobalSymbol:
567       addSymbol(symbol->getName());
568       break;
569     case SymbolKind::ObjectiveCClass:
570       // XXX ld64 only creates these symbols when -ObjC is passed in. We may
571       // want to emulate that.
572       addSymbol(objc::klass + symbol->getName());
573       addSymbol(objc::metaclass + symbol->getName());
574       break;
575     case SymbolKind::ObjectiveCClassEHType:
576       addSymbol(objc::ehtype + symbol->getName());
577       break;
578     case SymbolKind::ObjectiveCInstanceVariable:
579       addSymbol(objc::ivar + symbol->getName());
580       break;
581     }
582   }
583 
584   bool isTopLevelTapi = false;
585   if (currentTopLevelTapi == nullptr) {
586     currentTopLevelTapi = &interface;
587     isTopLevelTapi = true;
588   }
589 
590   for (InterfaceFileRef intfRef : interface.reexportedLibraries())
591     if (Optional<DylibFile *> reexport =
592             loadReexport(intfRef.getInstallName(), umbrella))
593       reexported.push_back(*reexport);
594 
595   if (isTopLevelTapi)
596     currentTopLevelTapi = nullptr;
597 }
598 
599 ArchiveFile::ArchiveFile(std::unique_ptr<llvm::object::Archive> &&f)
600     : InputFile(ArchiveKind, f->getMemoryBufferRef()), file(std::move(f)) {
601   for (const object::Archive::Symbol &sym : file->symbols())
602     symtab->addLazy(sym.getName(), this, sym);
603 }
604 
605 void ArchiveFile::fetch(const object::Archive::Symbol &sym) {
606   object::Archive::Child c =
607       CHECK(sym.getMember(), toString(this) +
608                                  ": could not get the member for symbol " +
609                                  toMachOString(sym));
610 
611   if (!seen.insert(c.getChildOffset()).second)
612     return;
613 
614   MemoryBufferRef mb =
615       CHECK(c.getMemoryBufferRef(),
616             toString(this) +
617                 ": could not get the buffer for the member defining symbol " +
618                 toMachOString(sym));
619 
620   if (tar && c.getParent()->isThin())
621     tar->append(relativeToRoot(CHECK(c.getFullName(), this)), mb.getBuffer());
622 
623   uint32_t modTime = toTimeT(
624       CHECK(c.getLastModified(), toString(this) +
625                                      ": could not get the modification time "
626                                      "for the member defining symbol " +
627                                      toMachOString(sym)));
628 
629   // `sym` is owned by a LazySym, which will be replace<>() by make<ObjFile>
630   // and become invalid after that call. Copy it to the stack so we can refer
631   // to it later.
632   const object::Archive::Symbol sym_copy = sym;
633 
634   auto file = make<ObjFile>(mb, modTime, getName());
635 
636   // ld64 doesn't demangle sym here even with -demangle. Match that, so
637   // intentionally no call to toMachOString() here.
638   printArchiveMemberLoad(sym_copy.getName(), file);
639 
640   symbols.insert(symbols.end(), file->symbols.begin(), file->symbols.end());
641   subsections.insert(subsections.end(), file->subsections.begin(),
642                      file->subsections.end());
643 }
644 
645 BitcodeFile::BitcodeFile(MemoryBufferRef mbref)
646     : InputFile(BitcodeKind, mbref) {
647   obj = check(lto::InputFile::create(mbref));
648 }
649