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 #include "llvm/TextAPI/MachO/Architecture.h"
70 
71 using namespace llvm;
72 using namespace llvm::MachO;
73 using namespace llvm::support::endian;
74 using namespace llvm::sys;
75 using namespace lld;
76 using namespace lld::macho;
77 
78 // Returns "<internal>", "foo.a(bar.o)", or "baz.o".
79 std::string lld::toString(const InputFile *f) {
80   if (!f)
81     return "<internal>";
82   if (f->archiveName.empty())
83     return std::string(f->getName());
84   return (path::filename(f->archiveName) + "(" + path::filename(f->getName()) +
85           ")")
86       .str();
87 }
88 
89 SetVector<InputFile *> macho::inputFiles;
90 std::unique_ptr<TarWriter> macho::tar;
91 int InputFile::idCount = 0;
92 
93 // Open a given file path and return it as a memory-mapped file.
94 Optional<MemoryBufferRef> macho::readFile(StringRef path) {
95   // Open a file.
96   auto mbOrErr = MemoryBuffer::getFile(path);
97   if (auto ec = mbOrErr.getError()) {
98     error("cannot open " + path + ": " + ec.message());
99     return None;
100   }
101 
102   std::unique_ptr<MemoryBuffer> &mb = *mbOrErr;
103   MemoryBufferRef mbref = mb->getMemBufferRef();
104   make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take mb ownership
105 
106   // If this is a regular non-fat file, return it.
107   const char *buf = mbref.getBufferStart();
108   auto *hdr = reinterpret_cast<const MachO::fat_header *>(buf);
109   if (mbref.getBufferSize() < sizeof(uint32_t) ||
110       read32be(&hdr->magic) != MachO::FAT_MAGIC) {
111     if (tar)
112       tar->append(relativeToRoot(path), mbref.getBuffer());
113     return mbref;
114   }
115 
116   // Object files and archive files may be fat files, which contains
117   // multiple real files for different CPU ISAs. Here, we search for a
118   // file that matches with the current link target and returns it as
119   // a MemoryBufferRef.
120   auto *arch = reinterpret_cast<const MachO::fat_arch *>(buf + sizeof(*hdr));
121 
122   for (uint32_t i = 0, n = read32be(&hdr->nfat_arch); i < n; ++i) {
123     if (reinterpret_cast<const char *>(arch + i + 1) >
124         buf + mbref.getBufferSize()) {
125       error(path + ": fat_arch struct extends beyond end of file");
126       return None;
127     }
128 
129     if (read32be(&arch[i].cputype) != target->cpuType ||
130         read32be(&arch[i].cpusubtype) != target->cpuSubtype)
131       continue;
132 
133     uint32_t offset = read32be(&arch[i].offset);
134     uint32_t size = read32be(&arch[i].size);
135     if (offset + size > mbref.getBufferSize())
136       error(path + ": slice extends beyond end of file");
137     if (tar)
138       tar->append(relativeToRoot(path), mbref.getBuffer());
139     return MemoryBufferRef(StringRef(buf + offset, size), path.copy(bAlloc));
140   }
141 
142   error("unable to find matching architecture in " + path);
143   return None;
144 }
145 
146 const load_command *macho::findCommand(const mach_header_64 *hdr,
147                                        uint32_t type) {
148   const uint8_t *p =
149       reinterpret_cast<const uint8_t *>(hdr) + sizeof(mach_header_64);
150 
151   for (uint32_t i = 0, n = hdr->ncmds; i < n; ++i) {
152     auto *cmd = reinterpret_cast<const load_command *>(p);
153     if (cmd->cmd == type)
154       return cmd;
155     p += cmd->cmdsize;
156   }
157   return nullptr;
158 }
159 
160 void ObjFile::parseSections(ArrayRef<section_64> sections) {
161   subsections.reserve(sections.size());
162   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
163 
164   for (const section_64 &sec : sections) {
165     InputSection *isec = make<InputSection>();
166     isec->file = this;
167     isec->name =
168         StringRef(sec.sectname, strnlen(sec.sectname, sizeof(sec.sectname)));
169     isec->segname =
170         StringRef(sec.segname, strnlen(sec.segname, sizeof(sec.segname)));
171     isec->data = {isZeroFill(sec.flags) ? nullptr : buf + sec.offset,
172                   static_cast<size_t>(sec.size)};
173     if (sec.align >= 32)
174       error("alignment " + std::to_string(sec.align) + " of section " +
175             isec->name + " is too large");
176     else
177       isec->align = 1 << sec.align;
178     isec->flags = sec.flags;
179 
180     if (!(isDebugSection(isec->flags) &&
181           isec->segname == segment_names::dwarf)) {
182       subsections.push_back({{0, isec}});
183     } else {
184       // Instead of emitting DWARF sections, we emit STABS symbols to the
185       // object files that contain them. We filter them out early to avoid
186       // parsing their relocations unnecessarily. But we must still push an
187       // empty map to ensure the indices line up for the remaining sections.
188       subsections.push_back({});
189       debugSections.push_back(isec);
190     }
191   }
192 }
193 
194 // Find the subsection corresponding to the greatest section offset that is <=
195 // that of the given offset.
196 //
197 // offset: an offset relative to the start of the original InputSection (before
198 // any subsection splitting has occurred). It will be updated to represent the
199 // same location as an offset relative to the start of the containing
200 // subsection.
201 static InputSection *findContainingSubsection(SubsectionMap &map,
202                                               uint32_t *offset) {
203   auto it = std::prev(map.upper_bound(*offset));
204   *offset -= it->first;
205   return it->second;
206 }
207 
208 static bool validateRelocationInfo(InputFile *file, const section_64 &sec,
209                                    relocation_info rel) {
210   const TargetInfo::RelocAttrs &relocAttrs = target->getRelocAttrs(rel.r_type);
211   bool valid = true;
212   auto message = [relocAttrs, file, sec, rel, &valid](const Twine &diagnostic) {
213     valid = false;
214     return (relocAttrs.name + " relocation " + diagnostic + " at offset " +
215             std::to_string(rel.r_address) + " of " + sec.segname + "," +
216             sec.sectname + " in " + toString(file))
217         .str();
218   };
219 
220   if (!relocAttrs.hasAttr(RelocAttrBits::LOCAL) && !rel.r_extern)
221     error(message("must be extern"));
222   if (relocAttrs.hasAttr(RelocAttrBits::PCREL) != rel.r_pcrel)
223     error(message(Twine("must ") + (rel.r_pcrel ? "not " : "") +
224                   "be PC-relative"));
225   if (isThreadLocalVariables(sec.flags) &&
226       !relocAttrs.hasAttr(RelocAttrBits::UNSIGNED))
227     error(message("not allowed in thread-local section, must be UNSIGNED"));
228   if (rel.r_length < 2 || rel.r_length > 3 ||
229       !relocAttrs.hasAttr(static_cast<RelocAttrBits>(1 << rel.r_length))) {
230     static SmallVector<StringRef, 4> widths{"0", "4", "8", "4 or 8"};
231     error(message("has width " + std::to_string(1 << rel.r_length) +
232                   " bytes, but must be " +
233                   widths[(static_cast<int>(relocAttrs.bits) >> 2) & 3] +
234                   " bytes"));
235   }
236   return valid;
237 }
238 
239 void ObjFile::parseRelocations(const section_64 &sec,
240                                SubsectionMap &subsecMap) {
241   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
242   ArrayRef<relocation_info> relInfos(
243       reinterpret_cast<const relocation_info *>(buf + sec.reloff), sec.nreloc);
244 
245   for (size_t i = 0; i < relInfos.size(); i++) {
246     // Paired relocations serve as Mach-O's method for attaching a
247     // supplemental datum to a primary relocation record. ELF does not
248     // need them because the *_RELOC_RELA records contain the extra
249     // addend field, vs. *_RELOC_REL which omit the addend.
250     //
251     // The {X86_64,ARM64}_RELOC_SUBTRACTOR record holds the subtrahend,
252     // and the paired *_RELOC_UNSIGNED record holds the minuend. The
253     // datum for each is a symbolic address. The result is the offset
254     // between two addresses.
255     //
256     // The ARM64_RELOC_ADDEND record holds the addend, and the paired
257     // ARM64_RELOC_BRANCH26 or ARM64_RELOC_PAGE21/PAGEOFF12 holds the
258     // base symbolic address.
259     //
260     // Note: X86 does not use *_RELOC_ADDEND because it can embed an
261     // addend into the instruction stream. On X86, a relocatable address
262     // field always occupies an entire contiguous sequence of byte(s),
263     // so there is no need to merge opcode bits with address
264     // bits. Therefore, it's easy and convenient to store addends in the
265     // instruction-stream bytes that would otherwise contain zeroes. By
266     // contrast, RISC ISAs such as ARM64 mix opcode bits with with
267     // address bits so that bitwise arithmetic is necessary to extract
268     // and insert them. Storing addends in the instruction stream is
269     // possible, but inconvenient and more costly at link time.
270 
271     uint64_t pairedAddend = 0;
272     relocation_info relInfo = relInfos[i];
273     if (target->hasAttr(relInfo.r_type, RelocAttrBits::ADDEND)) {
274       pairedAddend = SignExtend64<24>(relInfo.r_symbolnum);
275       relInfo = relInfos[++i];
276     }
277     assert(i < relInfos.size());
278     if (!validateRelocationInfo(this, sec, relInfo))
279       continue;
280     if (relInfo.r_address & R_SCATTERED)
281       fatal("TODO: Scattered relocations not supported");
282 
283     Reloc p;
284     if (target->hasAttr(relInfo.r_type, RelocAttrBits::SUBTRAHEND)) {
285       p.type = relInfo.r_type;
286       p.referent = symbols[relInfo.r_symbolnum];
287       relInfo = relInfos[++i];
288       // SUBTRACTOR relocations should always be followed by an UNSIGNED one
289       // indicating the minuend symbol.
290       assert(target->hasAttr(relInfo.r_type, RelocAttrBits::UNSIGNED) &&
291              relInfo.r_extern);
292     }
293     uint64_t embeddedAddend = target->getEmbeddedAddend(mb, sec, relInfo);
294     assert(!(embeddedAddend && pairedAddend));
295     uint64_t totalAddend = pairedAddend + embeddedAddend;
296     Reloc r;
297     r.type = relInfo.r_type;
298     r.pcrel = relInfo.r_pcrel;
299     r.length = relInfo.r_length;
300     r.offset = relInfo.r_address;
301     if (relInfo.r_extern) {
302       r.referent = symbols[relInfo.r_symbolnum];
303       r.addend = totalAddend;
304     } else {
305       SubsectionMap &referentSubsecMap = subsections[relInfo.r_symbolnum - 1];
306       const section_64 &referentSec = sectionHeaders[relInfo.r_symbolnum - 1];
307       uint32_t referentOffset;
308       if (relInfo.r_pcrel) {
309         // The implicit addend for pcrel section relocations is the pcrel offset
310         // in terms of the addresses in the input file. Here we adjust it so
311         // that it describes the offset from the start of the referent section.
312         assert(target->hasAttr(r.type, RelocAttrBits::BYTE4));
313         referentOffset =
314             sec.addr + relInfo.r_address + 4 + totalAddend - referentSec.addr;
315       } else {
316         // The addend for a non-pcrel relocation is its absolute address.
317         referentOffset = totalAddend - referentSec.addr;
318       }
319       r.referent = findContainingSubsection(referentSubsecMap, &referentOffset);
320       r.addend = referentOffset;
321     }
322 
323     InputSection *subsec = findContainingSubsection(subsecMap, &r.offset);
324     if (p.type != GENERIC_RELOC_INVALID)
325       subsec->relocs.push_back(p);
326     subsec->relocs.push_back(r);
327   }
328 }
329 
330 static macho::Symbol *createDefined(const structs::nlist_64 &sym,
331                                     StringRef name, InputSection *isec,
332                                     uint32_t value) {
333   // Symbol scope is determined by sym.n_type & (N_EXT | N_PEXT):
334   // N_EXT: Global symbols
335   // N_EXT | N_PEXT: Linkage unit (think: dylib) scoped
336   // N_PEXT: Does not occur in input files in practice,
337   //         a private extern must be external.
338   // 0: Translation-unit scoped. These are not in the symbol table.
339 
340   if (sym.n_type & (N_EXT | N_PEXT)) {
341     assert((sym.n_type & N_EXT) && "invalid input");
342     return symtab->addDefined(name, isec->file, isec, value,
343                               sym.n_desc & N_WEAK_DEF, sym.n_type & N_PEXT);
344   }
345   return make<Defined>(name, isec->file, isec, value, sym.n_desc & N_WEAK_DEF,
346                        /*isExternal=*/false, /*isPrivateExtern=*/false);
347 }
348 
349 // Absolute symbols are defined symbols that do not have an associated
350 // InputSection. They cannot be weak.
351 static macho::Symbol *createAbsolute(const structs::nlist_64 &sym,
352                                      InputFile *file, StringRef name) {
353   if (sym.n_type & (N_EXT | N_PEXT)) {
354     assert((sym.n_type & N_EXT) && "invalid input");
355     return symtab->addDefined(name, file, nullptr, sym.n_value,
356                               /*isWeakDef=*/false, sym.n_type & N_PEXT);
357   }
358   return make<Defined>(name, file, nullptr, sym.n_value, /*isWeakDef=*/false,
359                        /*isExternal=*/false, /*isPrivateExtern=*/false);
360 }
361 
362 macho::Symbol *ObjFile::parseNonSectionSymbol(const structs::nlist_64 &sym,
363                                               StringRef name) {
364   uint8_t type = sym.n_type & N_TYPE;
365   switch (type) {
366   case N_UNDF:
367     return sym.n_value == 0
368                ? symtab->addUndefined(name, this, sym.n_desc & N_WEAK_REF)
369                : symtab->addCommon(name, this, sym.n_value,
370                                    1 << GET_COMM_ALIGN(sym.n_desc),
371                                    sym.n_type & N_PEXT);
372   case N_ABS:
373     return createAbsolute(sym, this, name);
374   case N_PBUD:
375   case N_INDR:
376     error("TODO: support symbols of type " + std::to_string(type));
377     return nullptr;
378   case N_SECT:
379     llvm_unreachable(
380         "N_SECT symbols should not be passed to parseNonSectionSymbol");
381   default:
382     llvm_unreachable("invalid symbol type");
383   }
384 }
385 
386 void ObjFile::parseSymbols(ArrayRef<structs::nlist_64> nList,
387                            const char *strtab, bool subsectionsViaSymbols) {
388   // resize(), not reserve(), because we are going to create N_ALT_ENTRY symbols
389   // out-of-sequence.
390   symbols.resize(nList.size());
391   std::vector<size_t> altEntrySymIdxs;
392 
393   for (size_t i = 0, n = nList.size(); i < n; ++i) {
394     const structs::nlist_64 &sym = nList[i];
395     StringRef name = strtab + sym.n_strx;
396 
397     if ((sym.n_type & N_TYPE) != N_SECT) {
398       symbols[i] = parseNonSectionSymbol(sym, name);
399       continue;
400     }
401 
402     const section_64 &sec = sectionHeaders[sym.n_sect - 1];
403     SubsectionMap &subsecMap = subsections[sym.n_sect - 1];
404     assert(!subsecMap.empty());
405     uint64_t offset = sym.n_value - sec.addr;
406 
407     // If the input file does not use subsections-via-symbols, all symbols can
408     // use the same subsection. Otherwise, we must split the sections along
409     // symbol boundaries.
410     if (!subsectionsViaSymbols) {
411       symbols[i] = createDefined(sym, name, subsecMap[0], offset);
412       continue;
413     }
414 
415     // nList entries aren't necessarily arranged in address order. Therefore,
416     // we can't create alt-entry symbols at this point because a later symbol
417     // may split its section, which may affect which subsection the alt-entry
418     // symbol is assigned to. So we need to handle them in a second pass below.
419     if (sym.n_desc & N_ALT_ENTRY) {
420       altEntrySymIdxs.push_back(i);
421       continue;
422     }
423 
424     // Find the subsection corresponding to the greatest section offset that is
425     // <= that of the current symbol. The subsection that we find either needs
426     // to be used directly or split in two.
427     uint32_t firstSize = offset;
428     InputSection *firstIsec = findContainingSubsection(subsecMap, &firstSize);
429 
430     if (firstSize == 0) {
431       // Alias of an existing symbol, or the first symbol in the section. These
432       // are handled by reusing the existing section.
433       symbols[i] = createDefined(sym, name, firstIsec, 0);
434       continue;
435     }
436 
437     // We saw a symbol definition at a new offset. Split the section into two
438     // subsections. The new symbol uses the second subsection.
439     auto *secondIsec = make<InputSection>(*firstIsec);
440     secondIsec->data = firstIsec->data.slice(firstSize);
441     firstIsec->data = firstIsec->data.slice(0, firstSize);
442     // TODO: ld64 appears to preserve the original alignment as well as each
443     // subsection's offset from the last aligned address. We should consider
444     // emulating that behavior.
445     secondIsec->align = MinAlign(firstIsec->align, offset);
446 
447     subsecMap[offset] = secondIsec;
448     // By construction, the symbol will be at offset zero in the new section.
449     symbols[i] = createDefined(sym, name, secondIsec, 0);
450   }
451 
452   for (size_t idx : altEntrySymIdxs) {
453     const structs::nlist_64 &sym = nList[idx];
454     StringRef name = strtab + sym.n_strx;
455     SubsectionMap &subsecMap = subsections[sym.n_sect - 1];
456     uint32_t off = sym.n_value - sectionHeaders[sym.n_sect - 1].addr;
457     InputSection *subsec = findContainingSubsection(subsecMap, &off);
458     symbols[idx] = createDefined(sym, name, subsec, off);
459   }
460 }
461 
462 OpaqueFile::OpaqueFile(MemoryBufferRef mb, StringRef segName,
463                        StringRef sectName)
464     : InputFile(OpaqueKind, mb) {
465   InputSection *isec = make<InputSection>();
466   isec->file = this;
467   isec->name = sectName.take_front(16);
468   isec->segname = segName.take_front(16);
469   const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
470   isec->data = {buf, mb.getBufferSize()};
471   subsections.push_back({{0, isec}});
472 }
473 
474 ObjFile::ObjFile(MemoryBufferRef mb, uint32_t modTime, StringRef archiveName)
475     : InputFile(ObjKind, mb), modTime(modTime) {
476   this->archiveName = std::string(archiveName);
477 
478   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
479   auto *hdr = reinterpret_cast<const mach_header_64 *>(mb.getBufferStart());
480 
481   MachO::Architecture arch =
482       MachO::getArchitectureFromCpuType(hdr->cputype, hdr->cpusubtype);
483   if (arch != config->arch) {
484     error(toString(this) + " has architecture " + getArchitectureName(arch) +
485           " which is incompatible with target architecture " +
486           getArchitectureName(config->arch));
487     return;
488   }
489   // TODO: check platform too
490 
491   if (const load_command *cmd = findCommand(hdr, LC_LINKER_OPTION)) {
492     auto *c = reinterpret_cast<const linker_option_command *>(cmd);
493     StringRef data{reinterpret_cast<const char *>(c + 1),
494                    c->cmdsize - sizeof(linker_option_command)};
495     parseLCLinkerOption(this, c->count, data);
496   }
497 
498   if (const load_command *cmd = findCommand(hdr, LC_SEGMENT_64)) {
499     auto *c = reinterpret_cast<const segment_command_64 *>(cmd);
500     sectionHeaders = ArrayRef<section_64>{
501         reinterpret_cast<const section_64 *>(c + 1), c->nsects};
502     parseSections(sectionHeaders);
503   }
504 
505   // TODO: Error on missing LC_SYMTAB?
506   if (const load_command *cmd = findCommand(hdr, LC_SYMTAB)) {
507     auto *c = reinterpret_cast<const symtab_command *>(cmd);
508     ArrayRef<structs::nlist_64> nList(
509         reinterpret_cast<const structs::nlist_64 *>(buf + c->symoff), c->nsyms);
510     const char *strtab = reinterpret_cast<const char *>(buf) + c->stroff;
511     bool subsectionsViaSymbols = hdr->flags & MH_SUBSECTIONS_VIA_SYMBOLS;
512     parseSymbols(nList, strtab, subsectionsViaSymbols);
513   }
514 
515   // The relocations may refer to the symbols, so we parse them after we have
516   // parsed all the symbols.
517   for (size_t i = 0, n = subsections.size(); i < n; ++i)
518     if (!subsections[i].empty())
519       parseRelocations(sectionHeaders[i], subsections[i]);
520 
521   parseDebugInfo();
522 }
523 
524 void ObjFile::parseDebugInfo() {
525   std::unique_ptr<DwarfObject> dObj = DwarfObject::create(this);
526   if (!dObj)
527     return;
528 
529   auto *ctx = make<DWARFContext>(
530       std::move(dObj), "",
531       [&](Error err) {
532         warn(toString(this) + ": " + toString(std::move(err)));
533       },
534       [&](Error warning) {
535         warn(toString(this) + ": " + toString(std::move(warning)));
536       });
537 
538   // TODO: Since object files can contain a lot of DWARF info, we should verify
539   // that we are parsing just the info we need
540   const DWARFContext::compile_unit_range &units = ctx->compile_units();
541   auto it = units.begin();
542   compileUnit = it->get();
543   assert(std::next(it) == units.end());
544 }
545 
546 // The path can point to either a dylib or a .tbd file.
547 static Optional<DylibFile *> loadDylib(StringRef path, DylibFile *umbrella) {
548   Optional<MemoryBufferRef> mbref = readFile(path);
549   if (!mbref) {
550     error("could not read dylib file at " + path);
551     return {};
552   }
553   return loadDylib(*mbref, umbrella);
554 }
555 
556 // TBD files are parsed into a series of TAPI documents (InterfaceFiles), with
557 // the first document storing child pointers to the rest of them. When we are
558 // processing a given TBD file, we store that top-level document in
559 // currentTopLevelTapi. When processing re-exports, we search its children for
560 // potentially matching documents in the same TBD file. Note that the children
561 // themselves don't point to further documents, i.e. this is a two-level tree.
562 //
563 // Re-exports can either refer to on-disk files, or to documents within .tbd
564 // files.
565 static Optional<DylibFile *>
566 findDylib(StringRef path, DylibFile *umbrella,
567           const InterfaceFile *currentTopLevelTapi) {
568   if (path::is_absolute(path, path::Style::posix))
569     for (StringRef root : config->systemLibraryRoots)
570       if (Optional<std::string> dylibPath =
571               resolveDylibPath((root + path).str()))
572         return loadDylib(*dylibPath, umbrella);
573 
574   // TODO: Expand @loader_path, @executable_path, @rpath etc, handle -dylib_path
575 
576   if (currentTopLevelTapi) {
577     for (InterfaceFile &child :
578          make_pointee_range(currentTopLevelTapi->documents())) {
579       if (path == child.getInstallName())
580         return make<DylibFile>(child, umbrella);
581       assert(child.documents().empty());
582     }
583   }
584 
585   if (Optional<std::string> dylibPath = resolveDylibPath(path))
586     return loadDylib(*dylibPath, umbrella);
587 
588   return {};
589 }
590 
591 // If a re-exported dylib is public (lives in /usr/lib or
592 // /System/Library/Frameworks), then it is considered implicitly linked: we
593 // should bind to its symbols directly instead of via the re-exporting umbrella
594 // library.
595 static bool isImplicitlyLinked(StringRef path) {
596   if (!config->implicitDylibs)
597     return false;
598 
599   if (path::parent_path(path) == "/usr/lib")
600     return true;
601 
602   // Match /System/Library/Frameworks/$FOO.framework/**/$FOO
603   if (path.consume_front("/System/Library/Frameworks/")) {
604     StringRef frameworkName = path.take_until([](char c) { return c == '.'; });
605     return path::filename(path) == frameworkName;
606   }
607 
608   return false;
609 }
610 
611 void loadReexport(StringRef path, DylibFile *umbrella,
612                   const InterfaceFile *currentTopLevelTapi) {
613   Optional<DylibFile *> reexport =
614       findDylib(path, umbrella, currentTopLevelTapi);
615   if (!reexport)
616     error("unable to locate re-export with install name " + path);
617   else if (isImplicitlyLinked(path))
618     inputFiles.insert(*reexport);
619 }
620 
621 DylibFile::DylibFile(MemoryBufferRef mb, DylibFile *umbrella,
622                      bool isBundleLoader)
623     : InputFile(DylibKind, mb), refState(RefState::Unreferenced),
624       isBundleLoader(isBundleLoader) {
625   assert(!isBundleLoader || !umbrella);
626   if (umbrella == nullptr)
627     umbrella = this;
628 
629   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
630   auto *hdr = reinterpret_cast<const mach_header_64 *>(mb.getBufferStart());
631 
632   // Initialize dylibName.
633   if (const load_command *cmd = findCommand(hdr, LC_ID_DYLIB)) {
634     auto *c = reinterpret_cast<const dylib_command *>(cmd);
635     currentVersion = read32le(&c->dylib.current_version);
636     compatibilityVersion = read32le(&c->dylib.compatibility_version);
637     dylibName = reinterpret_cast<const char *>(cmd) + read32le(&c->dylib.name);
638   } else if (!isBundleLoader) {
639     // macho_executable and macho_bundle don't have LC_ID_DYLIB,
640     // so it's OK.
641     error("dylib " + toString(this) + " missing LC_ID_DYLIB load command");
642     return;
643   }
644 
645   // Initialize symbols.
646   DylibFile *exportingFile = isImplicitlyLinked(dylibName) ? this : umbrella;
647   if (const load_command *cmd = findCommand(hdr, LC_DYLD_INFO_ONLY)) {
648     auto *c = reinterpret_cast<const dyld_info_command *>(cmd);
649     parseTrie(buf + c->export_off, c->export_size,
650               [&](const Twine &name, uint64_t flags) {
651                 bool isWeakDef = flags & EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION;
652                 bool isTlv = flags & EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL;
653                 symbols.push_back(symtab->addDylib(
654                     saver.save(name), exportingFile, isWeakDef, isTlv));
655               });
656   } else {
657     error("LC_DYLD_INFO_ONLY not found in " + toString(this));
658     return;
659   }
660 
661   const uint8_t *p =
662       reinterpret_cast<const uint8_t *>(hdr) + sizeof(mach_header_64);
663   for (uint32_t i = 0, n = hdr->ncmds; i < n; ++i) {
664     auto *cmd = reinterpret_cast<const load_command *>(p);
665     p += cmd->cmdsize;
666 
667     if (!(hdr->flags & MH_NO_REEXPORTED_DYLIBS) &&
668         cmd->cmd == LC_REEXPORT_DYLIB) {
669       const auto *c = reinterpret_cast<const dylib_command *>(cmd);
670       StringRef reexportPath =
671           reinterpret_cast<const char *>(c) + read32le(&c->dylib.name);
672       loadReexport(reexportPath, umbrella, nullptr);
673     }
674 
675     // FIXME: What about LC_LOAD_UPWARD_DYLIB, LC_LAZY_LOAD_DYLIB,
676     // LC_LOAD_WEAK_DYLIB, LC_REEXPORT_DYLIB (..are reexports from dylibs with
677     // MH_NO_REEXPORTED_DYLIBS loaded for -flat_namespace)?
678     if (config->namespaceKind == NamespaceKind::flat &&
679         cmd->cmd == LC_LOAD_DYLIB) {
680       const auto *c = reinterpret_cast<const dylib_command *>(cmd);
681       StringRef dylibPath =
682           reinterpret_cast<const char *>(c) + read32le(&c->dylib.name);
683       Optional<DylibFile *> dylib = findDylib(dylibPath, umbrella, nullptr);
684       if (!dylib)
685         error(Twine("unable to locate library '") + dylibPath +
686               "' loaded from '" + toString(this) + "' for -flat_namespace");
687     }
688   }
689 }
690 
691 DylibFile::DylibFile(const InterfaceFile &interface, DylibFile *umbrella,
692                      bool isBundleLoader)
693     : InputFile(DylibKind, interface), refState(RefState::Unreferenced),
694       isBundleLoader(isBundleLoader) {
695   // FIXME: Add test for the missing TBD code path.
696 
697   if (umbrella == nullptr)
698     umbrella = this;
699 
700   if (!interface.getArchitectures().has(config->arch)) {
701     error(toString(this) + " is incompatible with " +
702           getArchitectureName(config->arch));
703     return;
704   }
705 
706   dylibName = saver.save(interface.getInstallName());
707   compatibilityVersion = interface.getCompatibilityVersion().rawValue();
708   currentVersion = interface.getCurrentVersion().rawValue();
709   DylibFile *exportingFile = isImplicitlyLinked(dylibName) ? this : umbrella;
710   auto addSymbol = [&](const Twine &name) -> void {
711     symbols.push_back(symtab->addDylib(saver.save(name), exportingFile,
712                                        /*isWeakDef=*/false,
713                                        /*isTlv=*/false));
714   };
715   // TODO(compnerd) filter out symbols based on the target platform
716   // TODO: handle weak defs, thread locals
717   for (const auto symbol : interface.symbols()) {
718     if (!symbol->getArchitectures().has(config->arch))
719       continue;
720 
721     switch (symbol->getKind()) {
722     case SymbolKind::GlobalSymbol:
723       addSymbol(symbol->getName());
724       break;
725     case SymbolKind::ObjectiveCClass:
726       // XXX ld64 only creates these symbols when -ObjC is passed in. We may
727       // want to emulate that.
728       addSymbol(objc::klass + symbol->getName());
729       addSymbol(objc::metaclass + symbol->getName());
730       break;
731     case SymbolKind::ObjectiveCClassEHType:
732       addSymbol(objc::ehtype + symbol->getName());
733       break;
734     case SymbolKind::ObjectiveCInstanceVariable:
735       addSymbol(objc::ivar + symbol->getName());
736       break;
737     }
738   }
739 
740   const InterfaceFile *topLevel =
741       interface.getParent() == nullptr ? &interface : interface.getParent();
742 
743   for (InterfaceFileRef intfRef : interface.reexportedLibraries())
744     loadReexport(intfRef.getInstallName(), umbrella, topLevel);
745 }
746 
747 ArchiveFile::ArchiveFile(std::unique_ptr<object::Archive> &&f)
748     : InputFile(ArchiveKind, f->getMemoryBufferRef()), file(std::move(f)) {
749   for (const object::Archive::Symbol &sym : file->symbols())
750     symtab->addLazy(sym.getName(), this, sym);
751 }
752 
753 void ArchiveFile::fetch(const object::Archive::Symbol &sym) {
754   object::Archive::Child c =
755       CHECK(sym.getMember(), toString(this) +
756                                  ": could not get the member for symbol " +
757                                  toMachOString(sym));
758 
759   if (!seen.insert(c.getChildOffset()).second)
760     return;
761 
762   MemoryBufferRef mb =
763       CHECK(c.getMemoryBufferRef(),
764             toString(this) +
765                 ": could not get the buffer for the member defining symbol " +
766                 toMachOString(sym));
767 
768   if (tar && c.getParent()->isThin())
769     tar->append(relativeToRoot(CHECK(c.getFullName(), this)), mb.getBuffer());
770 
771   uint32_t modTime = toTimeT(
772       CHECK(c.getLastModified(), toString(this) +
773                                      ": could not get the modification time "
774                                      "for the member defining symbol " +
775                                      toMachOString(sym)));
776 
777   // `sym` is owned by a LazySym, which will be replace<>() by make<ObjFile>
778   // and become invalid after that call. Copy it to the stack so we can refer
779   // to it later.
780   const object::Archive::Symbol sym_copy = sym;
781 
782   if (Optional<InputFile *> file =
783           loadArchiveMember(mb, modTime, getName(), /*objCOnly=*/false)) {
784     inputFiles.insert(*file);
785     // ld64 doesn't demangle sym here even with -demangle. Match that, so
786     // intentionally no call to toMachOString() here.
787     printArchiveMemberLoad(sym_copy.getName(), *file);
788   }
789 }
790 
791 static macho::Symbol *createBitcodeSymbol(const lto::InputFile::Symbol &objSym,
792                                           BitcodeFile &file) {
793   StringRef name = saver.save(objSym.getName());
794 
795   // TODO: support weak references
796   if (objSym.isUndefined())
797     return symtab->addUndefined(name, &file, /*isWeakRef=*/false);
798 
799   assert(!objSym.isCommon() && "TODO: support common symbols in LTO");
800 
801   // TODO: Write a test demonstrating why computing isPrivateExtern before
802   // LTO compilation is important.
803   bool isPrivateExtern = false;
804   switch (objSym.getVisibility()) {
805   case GlobalValue::HiddenVisibility:
806     isPrivateExtern = true;
807     break;
808   case GlobalValue::ProtectedVisibility:
809     error(name + " has protected visibility, which is not supported by Mach-O");
810     break;
811   case GlobalValue::DefaultVisibility:
812     break;
813   }
814 
815   return symtab->addDefined(name, &file, /*isec=*/nullptr, /*value=*/0,
816                             objSym.isWeak(), isPrivateExtern);
817 }
818 
819 BitcodeFile::BitcodeFile(MemoryBufferRef mbref)
820     : InputFile(BitcodeKind, mbref) {
821   obj = check(lto::InputFile::create(mbref));
822 
823   // Convert LTO Symbols to LLD Symbols in order to perform resolution. The
824   // "winning" symbol will then be marked as Prevailing at LTO compilation
825   // time.
826   for (const lto::InputFile::Symbol &objSym : obj->symbols())
827     symbols.push_back(createBitcodeSymbol(objSym, *this));
828 }
829