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 SetVector<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 ObjFile::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 
178     if (!(isDebugSection(isec->flags) &&
179           isec->segname == segment_names::dwarf)) {
180       subsections.push_back({{0, isec}});
181     } else {
182       // Instead of emitting DWARF sections, we emit STABS symbols to the
183       // object files that contain them. We filter them out early to avoid
184       // parsing their relocations unnecessarily. But we must still push an
185       // empty map to ensure the indices line up for the remaining sections.
186       subsections.push_back({});
187       debugSections.push_back(isec);
188     }
189   }
190 }
191 
192 // Find the subsection corresponding to the greatest section offset that is <=
193 // that of the given offset.
194 //
195 // offset: an offset relative to the start of the original InputSection (before
196 // any subsection splitting has occurred). It will be updated to represent the
197 // same location as an offset relative to the start of the containing
198 // subsection.
199 static InputSection *findContainingSubsection(SubsectionMap &map,
200                                               uint32_t *offset) {
201   auto it = std::prev(map.upper_bound(*offset));
202   *offset -= it->first;
203   return it->second;
204 }
205 
206 void ObjFile::parseRelocations(const section_64 &sec,
207                                SubsectionMap &subsecMap) {
208   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
209   ArrayRef<relocation_info> relInfos(
210       reinterpret_cast<const relocation_info *>(buf + sec.reloff), sec.nreloc);
211 
212   for (size_t i = 0; i < relInfos.size(); i++) {
213     // Paired relocations serve as Mach-O's method for attaching a
214     // supplemental datum to a primary relocation record. ELF does not
215     // need them because the *_RELOC_RELA records contain the extra
216     // addend field, vs. *_RELOC_REL which omit the addend.
217     //
218     // The {X86_64,ARM64}_RELOC_SUBTRACTOR record holds the subtrahend,
219     // and the paired *_RELOC_UNSIGNED record holds the minuend. The
220     // datum for each is a symbolic address. The result is the runtime
221     // offset between two addresses.
222     //
223     // The ARM64_RELOC_ADDEND record holds the addend, and the paired
224     // ARM64_RELOC_BRANCH26 or ARM64_RELOC_PAGE21/PAGEOFF12 holds the
225     // base symbolic address.
226     //
227     // Note: X86 does not use *_RELOC_ADDEND because it can embed an
228     // addend into the instruction stream. On X86, a relocatable address
229     // field always occupies an entire contiguous sequence of byte(s),
230     // so there is no need to merge opcode bits with address
231     // bits. Therefore, it's easy and convenient to store addends in the
232     // instruction-stream bytes that would otherwise contain zeroes. By
233     // contrast, RISC ISAs such as ARM64 mix opcode bits with with
234     // address bits so that bitwise arithmetic is necessary to extract
235     // and insert them. Storing addends in the instruction stream is
236     // possible, but inconvenient and more costly at link time.
237 
238     relocation_info pairedInfo = relInfos[i];
239     relocation_info relInfo =
240         target->isPairedReloc(pairedInfo) ? relInfos[++i] : pairedInfo;
241     assert(i < relInfos.size());
242     if (relInfo.r_address & R_SCATTERED)
243       fatal("TODO: Scattered relocations not supported");
244 
245     Reloc r;
246     r.type = relInfo.r_type;
247     r.pcrel = relInfo.r_pcrel;
248     r.length = relInfo.r_length;
249     r.offset = relInfo.r_address;
250     // For unpaired relocs, pairdInfo (just a copy of relInfo) is ignored
251     uint64_t rawAddend = target->getAddend(mb, sec, relInfo, pairedInfo);
252     if (relInfo.r_extern) {
253       r.referent = symbols[relInfo.r_symbolnum];
254       r.addend = rawAddend;
255     } else {
256       SubsectionMap &referentSubsecMap = subsections[relInfo.r_symbolnum - 1];
257       const section_64 &referentSec = sectionHeaders[relInfo.r_symbolnum - 1];
258       uint32_t referentOffset;
259       if (relInfo.r_pcrel) {
260         // The implicit addend for pcrel section relocations is the pcrel offset
261         // in terms of the addresses in the input file. Here we adjust it so
262         // that it describes the offset from the start of the referent section.
263         // TODO: The offset of 4 is probably not right for ARM64, nor for
264         //       relocations with r_length != 2.
265         referentOffset =
266             sec.addr + relInfo.r_address + 4 + rawAddend - referentSec.addr;
267       } else {
268         // The addend for a non-pcrel relocation is its absolute address.
269         referentOffset = rawAddend - referentSec.addr;
270       }
271       r.referent = findContainingSubsection(referentSubsecMap, &referentOffset);
272       r.addend = referentOffset;
273     }
274 
275     InputSection *subsec = findContainingSubsection(subsecMap, &r.offset);
276     subsec->relocs.push_back(r);
277   }
278 }
279 
280 static macho::Symbol *createDefined(const structs::nlist_64 &sym,
281                                     StringRef name, InputSection *isec,
282                                     uint32_t value) {
283   if (sym.n_type & N_EXT)
284     // Global defined symbol
285     return symtab->addDefined(name, isec, value, sym.n_desc & N_WEAK_DEF);
286   // Local defined symbol
287   return make<Defined>(name, isec, value, sym.n_desc & N_WEAK_DEF,
288                        /*isExternal=*/false);
289 }
290 
291 // Absolute symbols are defined symbols that do not have an associated
292 // InputSection. They cannot be weak.
293 static macho::Symbol *createAbsolute(const structs::nlist_64 &sym,
294                                      StringRef name) {
295   if (sym.n_type & N_EXT)
296     return symtab->addDefined(name, nullptr, sym.n_value, /*isWeakDef=*/false);
297   return make<Defined>(name, nullptr, sym.n_value, /*isWeakDef=*/false,
298                        /*isExternal=*/false);
299 }
300 
301 macho::Symbol *ObjFile::parseNonSectionSymbol(const structs::nlist_64 &sym,
302                                               StringRef name) {
303   uint8_t type = sym.n_type & N_TYPE;
304   switch (type) {
305   case N_UNDF:
306     return sym.n_value == 0
307                ? symtab->addUndefined(name, sym.n_desc & N_WEAK_REF)
308                : symtab->addCommon(name, this, sym.n_value,
309                                    1 << GET_COMM_ALIGN(sym.n_desc));
310   case N_ABS:
311     return createAbsolute(sym, name);
312   case N_PBUD:
313   case N_INDR:
314     error("TODO: support symbols of type " + std::to_string(type));
315     return nullptr;
316   case N_SECT:
317     llvm_unreachable(
318         "N_SECT symbols should not be passed to parseNonSectionSymbol");
319   default:
320     llvm_unreachable("invalid symbol type");
321   }
322 }
323 
324 void ObjFile::parseSymbols(ArrayRef<structs::nlist_64> nList,
325                            const char *strtab, bool subsectionsViaSymbols) {
326   // resize(), not reserve(), because we are going to create N_ALT_ENTRY symbols
327   // out-of-sequence.
328   symbols.resize(nList.size());
329   std::vector<size_t> altEntrySymIdxs;
330 
331   for (size_t i = 0, n = nList.size(); i < n; ++i) {
332     const structs::nlist_64 &sym = nList[i];
333     StringRef name = strtab + sym.n_strx;
334 
335     if ((sym.n_type & N_TYPE) != N_SECT) {
336       symbols[i] = parseNonSectionSymbol(sym, name);
337       continue;
338     }
339 
340     const section_64 &sec = sectionHeaders[sym.n_sect - 1];
341     SubsectionMap &subsecMap = subsections[sym.n_sect - 1];
342     assert(!subsecMap.empty());
343     uint64_t offset = sym.n_value - sec.addr;
344 
345     // If the input file does not use subsections-via-symbols, all symbols can
346     // use the same subsection. Otherwise, we must split the sections along
347     // symbol boundaries.
348     if (!subsectionsViaSymbols) {
349       symbols[i] = createDefined(sym, name, subsecMap[0], offset);
350       continue;
351     }
352 
353     // nList entries aren't necessarily arranged in address order. Therefore,
354     // we can't create alt-entry symbols at this point because a later symbol
355     // may split its section, which may affect which subsection the alt-entry
356     // symbol is assigned to. So we need to handle them in a second pass below.
357     if (sym.n_desc & N_ALT_ENTRY) {
358       altEntrySymIdxs.push_back(i);
359       continue;
360     }
361 
362     // Find the subsection corresponding to the greatest section offset that is
363     // <= that of the current symbol. The subsection that we find either needs
364     // to be used directly or split in two.
365     uint32_t firstSize = offset;
366     InputSection *firstIsec = findContainingSubsection(subsecMap, &firstSize);
367 
368     if (firstSize == 0) {
369       // Alias of an existing symbol, or the first symbol in the section. These
370       // are handled by reusing the existing section.
371       symbols[i] = createDefined(sym, name, firstIsec, 0);
372       continue;
373     }
374 
375     // We saw a symbol definition at a new offset. Split the section into two
376     // subsections. The new symbol uses the second subsection.
377     auto *secondIsec = make<InputSection>(*firstIsec);
378     secondIsec->data = firstIsec->data.slice(firstSize);
379     firstIsec->data = firstIsec->data.slice(0, firstSize);
380     // TODO: ld64 appears to preserve the original alignment as well as each
381     // subsection's offset from the last aligned address. We should consider
382     // emulating that behavior.
383     secondIsec->align = MinAlign(firstIsec->align, offset);
384 
385     subsecMap[offset] = secondIsec;
386     // By construction, the symbol will be at offset zero in the new section.
387     symbols[i] = createDefined(sym, name, secondIsec, 0);
388   }
389 
390   for (size_t idx : altEntrySymIdxs) {
391     const structs::nlist_64 &sym = nList[idx];
392     StringRef name = strtab + sym.n_strx;
393     SubsectionMap &subsecMap = subsections[sym.n_sect - 1];
394     uint32_t off = sym.n_value - sectionHeaders[sym.n_sect - 1].addr;
395     InputSection *subsec = findContainingSubsection(subsecMap, &off);
396     symbols[idx] = createDefined(sym, name, subsec, off);
397   }
398 }
399 
400 OpaqueFile::OpaqueFile(MemoryBufferRef mb, StringRef segName,
401                        StringRef sectName)
402     : InputFile(OpaqueKind, mb) {
403   InputSection *isec = make<InputSection>();
404   isec->file = this;
405   isec->name = sectName.take_front(16);
406   isec->segname = segName.take_front(16);
407   const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
408   isec->data = {buf, mb.getBufferSize()};
409   subsections.push_back({{0, isec}});
410 }
411 
412 ObjFile::ObjFile(MemoryBufferRef mb, uint32_t modTime, StringRef archiveName)
413     : InputFile(ObjKind, mb), modTime(modTime) {
414   this->archiveName = std::string(archiveName);
415 
416   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
417   auto *hdr = reinterpret_cast<const mach_header_64 *>(mb.getBufferStart());
418 
419   if (const load_command *cmd = findCommand(hdr, LC_LINKER_OPTION)) {
420     auto *c = reinterpret_cast<const linker_option_command *>(cmd);
421     StringRef data{reinterpret_cast<const char *>(c + 1),
422                    c->cmdsize - sizeof(linker_option_command)};
423     parseLCLinkerOption(this, c->count, data);
424   }
425 
426   if (const load_command *cmd = findCommand(hdr, LC_SEGMENT_64)) {
427     auto *c = reinterpret_cast<const segment_command_64 *>(cmd);
428     sectionHeaders = ArrayRef<section_64>{
429         reinterpret_cast<const section_64 *>(c + 1), c->nsects};
430     parseSections(sectionHeaders);
431   }
432 
433   // TODO: Error on missing LC_SYMTAB?
434   if (const load_command *cmd = findCommand(hdr, LC_SYMTAB)) {
435     auto *c = reinterpret_cast<const symtab_command *>(cmd);
436     ArrayRef<structs::nlist_64> nList(
437         reinterpret_cast<const structs::nlist_64 *>(buf + c->symoff), c->nsyms);
438     const char *strtab = reinterpret_cast<const char *>(buf) + c->stroff;
439     bool subsectionsViaSymbols = hdr->flags & MH_SUBSECTIONS_VIA_SYMBOLS;
440     parseSymbols(nList, strtab, subsectionsViaSymbols);
441   }
442 
443   // The relocations may refer to the symbols, so we parse them after we have
444   // parsed all the symbols.
445   for (size_t i = 0, n = subsections.size(); i < n; ++i)
446     if (!subsections[i].empty())
447       parseRelocations(sectionHeaders[i], subsections[i]);
448 
449   parseDebugInfo();
450 }
451 
452 void ObjFile::parseDebugInfo() {
453   std::unique_ptr<DwarfObject> dObj = DwarfObject::create(this);
454   if (!dObj)
455     return;
456 
457   auto *ctx = make<DWARFContext>(
458       std::move(dObj), "",
459       [&](Error err) {
460         warn(toString(this) + ": " + toString(std::move(err)));
461       },
462       [&](Error warning) {
463         warn(toString(this) + ": " + toString(std::move(warning)));
464       });
465 
466   // TODO: Since object files can contain a lot of DWARF info, we should verify
467   // that we are parsing just the info we need
468   const DWARFContext::compile_unit_range &units = ctx->compile_units();
469   auto it = units.begin();
470   compileUnit = it->get();
471   assert(std::next(it) == units.end());
472 }
473 
474 // The path can point to either a dylib or a .tbd file.
475 static Optional<DylibFile *> loadDylib(StringRef path, DylibFile *umbrella) {
476   Optional<MemoryBufferRef> mbref = readFile(path);
477   if (!mbref) {
478     error("could not read dylib file at " + path);
479     return {};
480   }
481   return loadDylib(*mbref, umbrella);
482 }
483 
484 // TBD files are parsed into a series of TAPI documents (InterfaceFiles), with
485 // the first document storing child pointers to the rest of them. When we are
486 // processing a given TBD file, we store that top-level document here. When
487 // processing re-exports, we search its children for potentially matching
488 // documents in the same TBD file. Note that the children themselves don't
489 // point to further documents, i.e. this is a two-level tree.
490 //
491 // ld64 allows a TAPI re-export to reference documents nested within other TBD
492 // files, but that seems like a strange design, so this is an intentional
493 // deviation.
494 const InterfaceFile *currentTopLevelTapi = nullptr;
495 
496 // Re-exports can either refer to on-disk files, or to documents within .tbd
497 // files.
498 static Optional<DylibFile *> loadReexportHelper(StringRef path,
499                                                 DylibFile *umbrella) {
500   if (path::is_absolute(path, path::Style::posix))
501     for (StringRef root : config->systemLibraryRoots)
502       if (Optional<std::string> dylibPath =
503               resolveDylibPath((root + path).str()))
504         return loadDylib(*dylibPath, umbrella);
505 
506   // TODO: Expand @loader_path, @executable_path etc
507 
508   if (currentTopLevelTapi) {
509     for (InterfaceFile &child :
510          make_pointee_range(currentTopLevelTapi->documents())) {
511       if (path == child.getInstallName())
512         return make<DylibFile>(child, umbrella);
513       assert(child.documents().empty());
514     }
515   }
516 
517   if (Optional<std::string> dylibPath = resolveDylibPath(path))
518     return loadDylib(*dylibPath, umbrella);
519 
520   error("unable to locate re-export with install name " + path);
521   return {};
522 }
523 
524 // If a re-exported dylib is public (lives in /usr/lib or
525 // /System/Library/Frameworks), then it is considered implicitly linked: we
526 // should bind to its symbols directly instead of via the re-exporting umbrella
527 // library.
528 static bool isImplicitlyLinked(StringRef path) {
529   if (!config->implicitDylibs)
530     return false;
531 
532   if (path::parent_path(path) == "/usr/lib")
533     return true;
534 
535   // Match /System/Library/Frameworks/$FOO.framework/**/$FOO
536   if (path.consume_front("/System/Library/Frameworks/")) {
537     StringRef frameworkName = path.take_until([](char c) { return c == '.'; });
538     return path::filename(path) == frameworkName;
539   }
540 
541   return false;
542 }
543 
544 void loadReexport(StringRef path, DylibFile *umbrella) {
545   Optional<DylibFile *> reexport = loadReexportHelper(path, umbrella);
546   if (reexport && isImplicitlyLinked(path))
547     inputFiles.insert(*reexport);
548 }
549 
550 DylibFile::DylibFile(MemoryBufferRef mb, DylibFile *umbrella)
551     : InputFile(DylibKind, mb), refState(RefState::Unreferenced) {
552   if (umbrella == nullptr)
553     umbrella = this;
554 
555   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
556   auto *hdr = reinterpret_cast<const mach_header_64 *>(mb.getBufferStart());
557 
558   // Initialize dylibName.
559   if (const load_command *cmd = findCommand(hdr, LC_ID_DYLIB)) {
560     auto *c = reinterpret_cast<const dylib_command *>(cmd);
561     currentVersion = read32le(&c->dylib.current_version);
562     compatibilityVersion = read32le(&c->dylib.compatibility_version);
563     dylibName = reinterpret_cast<const char *>(cmd) + read32le(&c->dylib.name);
564   } else {
565     error("dylib " + toString(this) + " missing LC_ID_DYLIB load command");
566     return;
567   }
568 
569   // Initialize symbols.
570   DylibFile *exportingFile = isImplicitlyLinked(dylibName) ? this : umbrella;
571   if (const load_command *cmd = findCommand(hdr, LC_DYLD_INFO_ONLY)) {
572     auto *c = reinterpret_cast<const dyld_info_command *>(cmd);
573     parseTrie(buf + c->export_off, c->export_size,
574               [&](const Twine &name, uint64_t flags) {
575                 bool isWeakDef = flags & EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION;
576                 bool isTlv = flags & EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL;
577                 symbols.push_back(symtab->addDylib(
578                     saver.save(name), exportingFile, isWeakDef, isTlv));
579               });
580   } else {
581     error("LC_DYLD_INFO_ONLY not found in " + toString(this));
582     return;
583   }
584 
585   if (hdr->flags & MH_NO_REEXPORTED_DYLIBS)
586     return;
587 
588   const uint8_t *p =
589       reinterpret_cast<const uint8_t *>(hdr) + sizeof(mach_header_64);
590   for (uint32_t i = 0, n = hdr->ncmds; i < n; ++i) {
591     auto *cmd = reinterpret_cast<const load_command *>(p);
592     p += cmd->cmdsize;
593     if (cmd->cmd != LC_REEXPORT_DYLIB)
594       continue;
595 
596     auto *c = reinterpret_cast<const dylib_command *>(cmd);
597     StringRef reexportPath =
598         reinterpret_cast<const char *>(c) + read32le(&c->dylib.name);
599     loadReexport(reexportPath, umbrella);
600   }
601 }
602 
603 DylibFile::DylibFile(const InterfaceFile &interface, DylibFile *umbrella)
604     : InputFile(DylibKind, interface), refState(RefState::Unreferenced) {
605   if (umbrella == nullptr)
606     umbrella = this;
607 
608   dylibName = saver.save(interface.getInstallName());
609   compatibilityVersion = interface.getCompatibilityVersion().rawValue();
610   currentVersion = interface.getCurrentVersion().rawValue();
611   DylibFile *exportingFile = isImplicitlyLinked(dylibName) ? this : umbrella;
612   auto addSymbol = [&](const Twine &name) -> void {
613     symbols.push_back(symtab->addDylib(saver.save(name), exportingFile,
614                                        /*isWeakDef=*/false,
615                                        /*isTlv=*/false));
616   };
617   // TODO(compnerd) filter out symbols based on the target platform
618   // TODO: handle weak defs, thread locals
619   for (const auto symbol : interface.symbols()) {
620     if (!symbol->getArchitectures().has(config->arch))
621       continue;
622 
623     switch (symbol->getKind()) {
624     case SymbolKind::GlobalSymbol:
625       addSymbol(symbol->getName());
626       break;
627     case SymbolKind::ObjectiveCClass:
628       // XXX ld64 only creates these symbols when -ObjC is passed in. We may
629       // want to emulate that.
630       addSymbol(objc::klass + symbol->getName());
631       addSymbol(objc::metaclass + symbol->getName());
632       break;
633     case SymbolKind::ObjectiveCClassEHType:
634       addSymbol(objc::ehtype + symbol->getName());
635       break;
636     case SymbolKind::ObjectiveCInstanceVariable:
637       addSymbol(objc::ivar + symbol->getName());
638       break;
639     }
640   }
641 
642   bool isTopLevelTapi = false;
643   if (currentTopLevelTapi == nullptr) {
644     currentTopLevelTapi = &interface;
645     isTopLevelTapi = true;
646   }
647 
648   for (InterfaceFileRef intfRef : interface.reexportedLibraries())
649     loadReexport(intfRef.getInstallName(), umbrella);
650 
651   if (isTopLevelTapi)
652     currentTopLevelTapi = nullptr;
653 }
654 
655 ArchiveFile::ArchiveFile(std::unique_ptr<llvm::object::Archive> &&f)
656     : InputFile(ArchiveKind, f->getMemoryBufferRef()), file(std::move(f)) {
657   for (const object::Archive::Symbol &sym : file->symbols())
658     symtab->addLazy(sym.getName(), this, sym);
659 }
660 
661 void ArchiveFile::fetch(const object::Archive::Symbol &sym) {
662   object::Archive::Child c =
663       CHECK(sym.getMember(), toString(this) +
664                                  ": could not get the member for symbol " +
665                                  toMachOString(sym));
666 
667   if (!seen.insert(c.getChildOffset()).second)
668     return;
669 
670   MemoryBufferRef mb =
671       CHECK(c.getMemoryBufferRef(),
672             toString(this) +
673                 ": could not get the buffer for the member defining symbol " +
674                 toMachOString(sym));
675 
676   if (tar && c.getParent()->isThin())
677     tar->append(relativeToRoot(CHECK(c.getFullName(), this)), mb.getBuffer());
678 
679   uint32_t modTime = toTimeT(
680       CHECK(c.getLastModified(), toString(this) +
681                                      ": could not get the modification time "
682                                      "for the member defining symbol " +
683                                      toMachOString(sym)));
684 
685   // `sym` is owned by a LazySym, which will be replace<>() by make<ObjFile>
686   // and become invalid after that call. Copy it to the stack so we can refer
687   // to it later.
688   const object::Archive::Symbol sym_copy = sym;
689 
690   InputFile *file;
691   switch (identify_magic(mb.getBuffer())) {
692   case file_magic::macho_object:
693     file = make<ObjFile>(mb, modTime, getName());
694     break;
695   case file_magic::bitcode:
696     file = make<BitcodeFile>(mb);
697     break;
698   default:
699     StringRef bufname =
700         CHECK(c.getName(), toString(this) + ": could not get buffer name");
701     error(toString(this) + ": archive member " + bufname +
702           " has unhandled file type");
703     return;
704   }
705   inputFiles.insert(file);
706 
707   // ld64 doesn't demangle sym here even with -demangle. Match that, so
708   // intentionally no call to toMachOString() here.
709   printArchiveMemberLoad(sym_copy.getName(), file);
710 }
711 
712 BitcodeFile::BitcodeFile(MemoryBufferRef mbref)
713     : InputFile(BitcodeKind, mbref) {
714   obj = check(lto::InputFile::create(mbref));
715 }
716