xref: /freebsd/contrib/llvm-project/lld/MachO/InputFiles.cpp (revision 0d8fe2373503aeac48492f28073049a8bfa4feb5)
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   // Symbol scope is determined by sym.n_type & (N_EXT | N_PEXT):
284   // N_EXT: Global symbols
285   // N_EXT | N_PEXT: Linkage unit (think: dylib) scoped
286   // N_PEXT: Does not occur in input files in practice,
287   //         a private extern must be external.
288   // 0: Translation-unit scoped. These are not in the symbol table.
289 
290   if (sym.n_type & (N_EXT | N_PEXT)) {
291     assert((sym.n_type & N_EXT) && "invalid input");
292     return symtab->addDefined(name, isec, value, sym.n_desc & N_WEAK_DEF,
293                               sym.n_type & N_PEXT);
294   }
295   return make<Defined>(name, isec, value, sym.n_desc & N_WEAK_DEF,
296                        /*isExternal=*/false, /*isPrivateExtern=*/false);
297 }
298 
299 // Absolute symbols are defined symbols that do not have an associated
300 // InputSection. They cannot be weak.
301 static macho::Symbol *createAbsolute(const structs::nlist_64 &sym,
302                                      StringRef name) {
303   if (sym.n_type & (N_EXT | N_PEXT)) {
304     assert((sym.n_type & N_EXT) && "invalid input");
305     return symtab->addDefined(name, nullptr, sym.n_value, /*isWeakDef=*/false,
306                               sym.n_type & N_PEXT);
307   }
308   return make<Defined>(name, nullptr, sym.n_value, /*isWeakDef=*/false,
309                        /*isExternal=*/false, /*isPrivateExtern=*/false);
310 }
311 
312 macho::Symbol *ObjFile::parseNonSectionSymbol(const structs::nlist_64 &sym,
313                                               StringRef name) {
314   uint8_t type = sym.n_type & N_TYPE;
315   switch (type) {
316   case N_UNDF:
317     return sym.n_value == 0
318                ? symtab->addUndefined(name, sym.n_desc & N_WEAK_REF)
319                : symtab->addCommon(name, this, sym.n_value,
320                                    1 << GET_COMM_ALIGN(sym.n_desc),
321                                    sym.n_type & N_PEXT);
322   case N_ABS:
323     return createAbsolute(sym, name);
324   case N_PBUD:
325   case N_INDR:
326     error("TODO: support symbols of type " + std::to_string(type));
327     return nullptr;
328   case N_SECT:
329     llvm_unreachable(
330         "N_SECT symbols should not be passed to parseNonSectionSymbol");
331   default:
332     llvm_unreachable("invalid symbol type");
333   }
334 }
335 
336 void ObjFile::parseSymbols(ArrayRef<structs::nlist_64> nList,
337                            const char *strtab, bool subsectionsViaSymbols) {
338   // resize(), not reserve(), because we are going to create N_ALT_ENTRY symbols
339   // out-of-sequence.
340   symbols.resize(nList.size());
341   std::vector<size_t> altEntrySymIdxs;
342 
343   for (size_t i = 0, n = nList.size(); i < n; ++i) {
344     const structs::nlist_64 &sym = nList[i];
345     StringRef name = strtab + sym.n_strx;
346 
347     if ((sym.n_type & N_TYPE) != N_SECT) {
348       symbols[i] = parseNonSectionSymbol(sym, name);
349       continue;
350     }
351 
352     const section_64 &sec = sectionHeaders[sym.n_sect - 1];
353     SubsectionMap &subsecMap = subsections[sym.n_sect - 1];
354     assert(!subsecMap.empty());
355     uint64_t offset = sym.n_value - sec.addr;
356 
357     // If the input file does not use subsections-via-symbols, all symbols can
358     // use the same subsection. Otherwise, we must split the sections along
359     // symbol boundaries.
360     if (!subsectionsViaSymbols) {
361       symbols[i] = createDefined(sym, name, subsecMap[0], offset);
362       continue;
363     }
364 
365     // nList entries aren't necessarily arranged in address order. Therefore,
366     // we can't create alt-entry symbols at this point because a later symbol
367     // may split its section, which may affect which subsection the alt-entry
368     // symbol is assigned to. So we need to handle them in a second pass below.
369     if (sym.n_desc & N_ALT_ENTRY) {
370       altEntrySymIdxs.push_back(i);
371       continue;
372     }
373 
374     // Find the subsection corresponding to the greatest section offset that is
375     // <= that of the current symbol. The subsection that we find either needs
376     // to be used directly or split in two.
377     uint32_t firstSize = offset;
378     InputSection *firstIsec = findContainingSubsection(subsecMap, &firstSize);
379 
380     if (firstSize == 0) {
381       // Alias of an existing symbol, or the first symbol in the section. These
382       // are handled by reusing the existing section.
383       symbols[i] = createDefined(sym, name, firstIsec, 0);
384       continue;
385     }
386 
387     // We saw a symbol definition at a new offset. Split the section into two
388     // subsections. The new symbol uses the second subsection.
389     auto *secondIsec = make<InputSection>(*firstIsec);
390     secondIsec->data = firstIsec->data.slice(firstSize);
391     firstIsec->data = firstIsec->data.slice(0, firstSize);
392     // TODO: ld64 appears to preserve the original alignment as well as each
393     // subsection's offset from the last aligned address. We should consider
394     // emulating that behavior.
395     secondIsec->align = MinAlign(firstIsec->align, offset);
396 
397     subsecMap[offset] = secondIsec;
398     // By construction, the symbol will be at offset zero in the new section.
399     symbols[i] = createDefined(sym, name, secondIsec, 0);
400   }
401 
402   for (size_t idx : altEntrySymIdxs) {
403     const structs::nlist_64 &sym = nList[idx];
404     StringRef name = strtab + sym.n_strx;
405     SubsectionMap &subsecMap = subsections[sym.n_sect - 1];
406     uint32_t off = sym.n_value - sectionHeaders[sym.n_sect - 1].addr;
407     InputSection *subsec = findContainingSubsection(subsecMap, &off);
408     symbols[idx] = createDefined(sym, name, subsec, off);
409   }
410 }
411 
412 OpaqueFile::OpaqueFile(MemoryBufferRef mb, StringRef segName,
413                        StringRef sectName)
414     : InputFile(OpaqueKind, mb) {
415   InputSection *isec = make<InputSection>();
416   isec->file = this;
417   isec->name = sectName.take_front(16);
418   isec->segname = segName.take_front(16);
419   const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
420   isec->data = {buf, mb.getBufferSize()};
421   subsections.push_back({{0, isec}});
422 }
423 
424 ObjFile::ObjFile(MemoryBufferRef mb, uint32_t modTime, StringRef archiveName)
425     : InputFile(ObjKind, mb), modTime(modTime) {
426   this->archiveName = std::string(archiveName);
427 
428   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
429   auto *hdr = reinterpret_cast<const mach_header_64 *>(mb.getBufferStart());
430 
431   if (const load_command *cmd = findCommand(hdr, LC_LINKER_OPTION)) {
432     auto *c = reinterpret_cast<const linker_option_command *>(cmd);
433     StringRef data{reinterpret_cast<const char *>(c + 1),
434                    c->cmdsize - sizeof(linker_option_command)};
435     parseLCLinkerOption(this, c->count, data);
436   }
437 
438   if (const load_command *cmd = findCommand(hdr, LC_SEGMENT_64)) {
439     auto *c = reinterpret_cast<const segment_command_64 *>(cmd);
440     sectionHeaders = ArrayRef<section_64>{
441         reinterpret_cast<const section_64 *>(c + 1), c->nsects};
442     parseSections(sectionHeaders);
443   }
444 
445   // TODO: Error on missing LC_SYMTAB?
446   if (const load_command *cmd = findCommand(hdr, LC_SYMTAB)) {
447     auto *c = reinterpret_cast<const symtab_command *>(cmd);
448     ArrayRef<structs::nlist_64> nList(
449         reinterpret_cast<const structs::nlist_64 *>(buf + c->symoff), c->nsyms);
450     const char *strtab = reinterpret_cast<const char *>(buf) + c->stroff;
451     bool subsectionsViaSymbols = hdr->flags & MH_SUBSECTIONS_VIA_SYMBOLS;
452     parseSymbols(nList, strtab, subsectionsViaSymbols);
453   }
454 
455   // The relocations may refer to the symbols, so we parse them after we have
456   // parsed all the symbols.
457   for (size_t i = 0, n = subsections.size(); i < n; ++i)
458     if (!subsections[i].empty())
459       parseRelocations(sectionHeaders[i], subsections[i]);
460 
461   parseDebugInfo();
462 }
463 
464 void ObjFile::parseDebugInfo() {
465   std::unique_ptr<DwarfObject> dObj = DwarfObject::create(this);
466   if (!dObj)
467     return;
468 
469   auto *ctx = make<DWARFContext>(
470       std::move(dObj), "",
471       [&](Error err) {
472         warn(toString(this) + ": " + toString(std::move(err)));
473       },
474       [&](Error warning) {
475         warn(toString(this) + ": " + toString(std::move(warning)));
476       });
477 
478   // TODO: Since object files can contain a lot of DWARF info, we should verify
479   // that we are parsing just the info we need
480   const DWARFContext::compile_unit_range &units = ctx->compile_units();
481   auto it = units.begin();
482   compileUnit = it->get();
483   assert(std::next(it) == units.end());
484 }
485 
486 // The path can point to either a dylib or a .tbd file.
487 static Optional<DylibFile *> loadDylib(StringRef path, DylibFile *umbrella) {
488   Optional<MemoryBufferRef> mbref = readFile(path);
489   if (!mbref) {
490     error("could not read dylib file at " + path);
491     return {};
492   }
493   return loadDylib(*mbref, umbrella);
494 }
495 
496 // TBD files are parsed into a series of TAPI documents (InterfaceFiles), with
497 // the first document storing child pointers to the rest of them. When we are
498 // processing a given TBD file, we store that top-level document here. When
499 // processing re-exports, we search its children for potentially matching
500 // documents in the same TBD file. Note that the children themselves don't
501 // point to further documents, i.e. this is a two-level tree.
502 //
503 // ld64 allows a TAPI re-export to reference documents nested within other TBD
504 // files, but that seems like a strange design, so this is an intentional
505 // deviation.
506 const InterfaceFile *currentTopLevelTapi = nullptr;
507 
508 // Re-exports can either refer to on-disk files, or to documents within .tbd
509 // files.
510 static Optional<DylibFile *> loadReexportHelper(StringRef path,
511                                                 DylibFile *umbrella) {
512   if (path::is_absolute(path, path::Style::posix))
513     for (StringRef root : config->systemLibraryRoots)
514       if (Optional<std::string> dylibPath =
515               resolveDylibPath((root + path).str()))
516         return loadDylib(*dylibPath, umbrella);
517 
518   // TODO: Expand @loader_path, @executable_path etc
519 
520   if (currentTopLevelTapi) {
521     for (InterfaceFile &child :
522          make_pointee_range(currentTopLevelTapi->documents())) {
523       if (path == child.getInstallName())
524         return make<DylibFile>(child, umbrella);
525       assert(child.documents().empty());
526     }
527   }
528 
529   if (Optional<std::string> dylibPath = resolveDylibPath(path))
530     return loadDylib(*dylibPath, umbrella);
531 
532   error("unable to locate re-export with install name " + path);
533   return {};
534 }
535 
536 // If a re-exported dylib is public (lives in /usr/lib or
537 // /System/Library/Frameworks), then it is considered implicitly linked: we
538 // should bind to its symbols directly instead of via the re-exporting umbrella
539 // library.
540 static bool isImplicitlyLinked(StringRef path) {
541   if (!config->implicitDylibs)
542     return false;
543 
544   if (path::parent_path(path) == "/usr/lib")
545     return true;
546 
547   // Match /System/Library/Frameworks/$FOO.framework/**/$FOO
548   if (path.consume_front("/System/Library/Frameworks/")) {
549     StringRef frameworkName = path.take_until([](char c) { return c == '.'; });
550     return path::filename(path) == frameworkName;
551   }
552 
553   return false;
554 }
555 
556 void loadReexport(StringRef path, DylibFile *umbrella) {
557   Optional<DylibFile *> reexport = loadReexportHelper(path, umbrella);
558   if (reexport && isImplicitlyLinked(path))
559     inputFiles.insert(*reexport);
560 }
561 
562 DylibFile::DylibFile(MemoryBufferRef mb, DylibFile *umbrella)
563     : InputFile(DylibKind, mb), refState(RefState::Unreferenced) {
564   if (umbrella == nullptr)
565     umbrella = this;
566 
567   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
568   auto *hdr = reinterpret_cast<const mach_header_64 *>(mb.getBufferStart());
569 
570   // Initialize dylibName.
571   if (const load_command *cmd = findCommand(hdr, LC_ID_DYLIB)) {
572     auto *c = reinterpret_cast<const dylib_command *>(cmd);
573     currentVersion = read32le(&c->dylib.current_version);
574     compatibilityVersion = read32le(&c->dylib.compatibility_version);
575     dylibName = reinterpret_cast<const char *>(cmd) + read32le(&c->dylib.name);
576   } else {
577     error("dylib " + toString(this) + " missing LC_ID_DYLIB load command");
578     return;
579   }
580 
581   // Initialize symbols.
582   DylibFile *exportingFile = isImplicitlyLinked(dylibName) ? this : umbrella;
583   if (const load_command *cmd = findCommand(hdr, LC_DYLD_INFO_ONLY)) {
584     auto *c = reinterpret_cast<const dyld_info_command *>(cmd);
585     parseTrie(buf + c->export_off, c->export_size,
586               [&](const Twine &name, uint64_t flags) {
587                 bool isWeakDef = flags & EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION;
588                 bool isTlv = flags & EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL;
589                 symbols.push_back(symtab->addDylib(
590                     saver.save(name), exportingFile, isWeakDef, isTlv));
591               });
592   } else {
593     error("LC_DYLD_INFO_ONLY not found in " + toString(this));
594     return;
595   }
596 
597   if (hdr->flags & MH_NO_REEXPORTED_DYLIBS)
598     return;
599 
600   const uint8_t *p =
601       reinterpret_cast<const uint8_t *>(hdr) + sizeof(mach_header_64);
602   for (uint32_t i = 0, n = hdr->ncmds; i < n; ++i) {
603     auto *cmd = reinterpret_cast<const load_command *>(p);
604     p += cmd->cmdsize;
605     if (cmd->cmd != LC_REEXPORT_DYLIB)
606       continue;
607 
608     auto *c = reinterpret_cast<const dylib_command *>(cmd);
609     StringRef reexportPath =
610         reinterpret_cast<const char *>(c) + read32le(&c->dylib.name);
611     loadReexport(reexportPath, umbrella);
612   }
613 }
614 
615 DylibFile::DylibFile(const InterfaceFile &interface, DylibFile *umbrella)
616     : InputFile(DylibKind, interface), refState(RefState::Unreferenced) {
617   if (umbrella == nullptr)
618     umbrella = this;
619 
620   dylibName = saver.save(interface.getInstallName());
621   compatibilityVersion = interface.getCompatibilityVersion().rawValue();
622   currentVersion = interface.getCurrentVersion().rawValue();
623   DylibFile *exportingFile = isImplicitlyLinked(dylibName) ? this : umbrella;
624   auto addSymbol = [&](const Twine &name) -> void {
625     symbols.push_back(symtab->addDylib(saver.save(name), exportingFile,
626                                        /*isWeakDef=*/false,
627                                        /*isTlv=*/false));
628   };
629   // TODO(compnerd) filter out symbols based on the target platform
630   // TODO: handle weak defs, thread locals
631   for (const auto symbol : interface.symbols()) {
632     if (!symbol->getArchitectures().has(config->arch))
633       continue;
634 
635     switch (symbol->getKind()) {
636     case SymbolKind::GlobalSymbol:
637       addSymbol(symbol->getName());
638       break;
639     case SymbolKind::ObjectiveCClass:
640       // XXX ld64 only creates these symbols when -ObjC is passed in. We may
641       // want to emulate that.
642       addSymbol(objc::klass + symbol->getName());
643       addSymbol(objc::metaclass + symbol->getName());
644       break;
645     case SymbolKind::ObjectiveCClassEHType:
646       addSymbol(objc::ehtype + symbol->getName());
647       break;
648     case SymbolKind::ObjectiveCInstanceVariable:
649       addSymbol(objc::ivar + symbol->getName());
650       break;
651     }
652   }
653 
654   bool isTopLevelTapi = false;
655   if (currentTopLevelTapi == nullptr) {
656     currentTopLevelTapi = &interface;
657     isTopLevelTapi = true;
658   }
659 
660   for (InterfaceFileRef intfRef : interface.reexportedLibraries())
661     loadReexport(intfRef.getInstallName(), umbrella);
662 
663   if (isTopLevelTapi)
664     currentTopLevelTapi = nullptr;
665 }
666 
667 ArchiveFile::ArchiveFile(std::unique_ptr<object::Archive> &&f)
668     : InputFile(ArchiveKind, f->getMemoryBufferRef()), file(std::move(f)) {
669   for (const object::Archive::Symbol &sym : file->symbols())
670     symtab->addLazy(sym.getName(), this, sym);
671 }
672 
673 void ArchiveFile::fetch(const object::Archive::Symbol &sym) {
674   object::Archive::Child c =
675       CHECK(sym.getMember(), toString(this) +
676                                  ": could not get the member for symbol " +
677                                  toMachOString(sym));
678 
679   if (!seen.insert(c.getChildOffset()).second)
680     return;
681 
682   MemoryBufferRef mb =
683       CHECK(c.getMemoryBufferRef(),
684             toString(this) +
685                 ": could not get the buffer for the member defining symbol " +
686                 toMachOString(sym));
687 
688   if (tar && c.getParent()->isThin())
689     tar->append(relativeToRoot(CHECK(c.getFullName(), this)), mb.getBuffer());
690 
691   uint32_t modTime = toTimeT(
692       CHECK(c.getLastModified(), toString(this) +
693                                      ": could not get the modification time "
694                                      "for the member defining symbol " +
695                                      toMachOString(sym)));
696 
697   // `sym` is owned by a LazySym, which will be replace<>() by make<ObjFile>
698   // and become invalid after that call. Copy it to the stack so we can refer
699   // to it later.
700   const object::Archive::Symbol sym_copy = sym;
701 
702   InputFile *file;
703   switch (identify_magic(mb.getBuffer())) {
704   case file_magic::macho_object:
705     file = make<ObjFile>(mb, modTime, getName());
706     break;
707   case file_magic::bitcode:
708     file = make<BitcodeFile>(mb);
709     break;
710   default:
711     StringRef bufname =
712         CHECK(c.getName(), toString(this) + ": could not get buffer name");
713     error(toString(this) + ": archive member " + bufname +
714           " has unhandled file type");
715     return;
716   }
717   inputFiles.insert(file);
718 
719   // ld64 doesn't demangle sym here even with -demangle. Match that, so
720   // intentionally no call to toMachOString() here.
721   printArchiveMemberLoad(sym_copy.getName(), file);
722 }
723 
724 BitcodeFile::BitcodeFile(MemoryBufferRef mbref)
725     : InputFile(BitcodeKind, mbref) {
726   obj = check(lto::InputFile::create(mbref));
727 }
728