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 
490   if (const load_command *cmd = findCommand(hdr, LC_LINKER_OPTION)) {
491     auto *c = reinterpret_cast<const linker_option_command *>(cmd);
492     StringRef data{reinterpret_cast<const char *>(c + 1),
493                    c->cmdsize - sizeof(linker_option_command)};
494     parseLCLinkerOption(this, c->count, data);
495   }
496 
497   if (const load_command *cmd = findCommand(hdr, LC_SEGMENT_64)) {
498     auto *c = reinterpret_cast<const segment_command_64 *>(cmd);
499     sectionHeaders = ArrayRef<section_64>{
500         reinterpret_cast<const section_64 *>(c + 1), c->nsects};
501     parseSections(sectionHeaders);
502   }
503 
504   // TODO: Error on missing LC_SYMTAB?
505   if (const load_command *cmd = findCommand(hdr, LC_SYMTAB)) {
506     auto *c = reinterpret_cast<const symtab_command *>(cmd);
507     ArrayRef<structs::nlist_64> nList(
508         reinterpret_cast<const structs::nlist_64 *>(buf + c->symoff), c->nsyms);
509     const char *strtab = reinterpret_cast<const char *>(buf) + c->stroff;
510     bool subsectionsViaSymbols = hdr->flags & MH_SUBSECTIONS_VIA_SYMBOLS;
511     parseSymbols(nList, strtab, subsectionsViaSymbols);
512   }
513 
514   // The relocations may refer to the symbols, so we parse them after we have
515   // parsed all the symbols.
516   for (size_t i = 0, n = subsections.size(); i < n; ++i)
517     if (!subsections[i].empty())
518       parseRelocations(sectionHeaders[i], subsections[i]);
519 
520   parseDebugInfo();
521 }
522 
523 void ObjFile::parseDebugInfo() {
524   std::unique_ptr<DwarfObject> dObj = DwarfObject::create(this);
525   if (!dObj)
526     return;
527 
528   auto *ctx = make<DWARFContext>(
529       std::move(dObj), "",
530       [&](Error err) {
531         warn(toString(this) + ": " + toString(std::move(err)));
532       },
533       [&](Error warning) {
534         warn(toString(this) + ": " + toString(std::move(warning)));
535       });
536 
537   // TODO: Since object files can contain a lot of DWARF info, we should verify
538   // that we are parsing just the info we need
539   const DWARFContext::compile_unit_range &units = ctx->compile_units();
540   auto it = units.begin();
541   compileUnit = it->get();
542   assert(std::next(it) == units.end());
543 }
544 
545 // The path can point to either a dylib or a .tbd file.
546 static Optional<DylibFile *> loadDylib(StringRef path, DylibFile *umbrella) {
547   Optional<MemoryBufferRef> mbref = readFile(path);
548   if (!mbref) {
549     error("could not read dylib file at " + path);
550     return {};
551   }
552   return loadDylib(*mbref, umbrella);
553 }
554 
555 // TBD files are parsed into a series of TAPI documents (InterfaceFiles), with
556 // the first document storing child pointers to the rest of them. When we are
557 // processing a given TBD file, we store that top-level document in
558 // currentTopLevelTapi. When processing re-exports, we search its children for
559 // potentially matching documents in the same TBD file. Note that the children
560 // themselves don't point to further documents, i.e. this is a two-level tree.
561 //
562 // Re-exports can either refer to on-disk files, or to documents within .tbd
563 // files.
564 static Optional<DylibFile *>
565 findDylib(StringRef path, DylibFile *umbrella,
566           const InterfaceFile *currentTopLevelTapi) {
567   if (path::is_absolute(path, path::Style::posix))
568     for (StringRef root : config->systemLibraryRoots)
569       if (Optional<std::string> dylibPath =
570               resolveDylibPath((root + path).str()))
571         return loadDylib(*dylibPath, umbrella);
572 
573   // TODO: Expand @loader_path, @executable_path, @rpath etc, handle -dylib_path
574 
575   if (currentTopLevelTapi) {
576     for (InterfaceFile &child :
577          make_pointee_range(currentTopLevelTapi->documents())) {
578       if (path == child.getInstallName())
579         return make<DylibFile>(child, umbrella);
580       assert(child.documents().empty());
581     }
582   }
583 
584   if (Optional<std::string> dylibPath = resolveDylibPath(path))
585     return loadDylib(*dylibPath, umbrella);
586 
587   return {};
588 }
589 
590 // If a re-exported dylib is public (lives in /usr/lib or
591 // /System/Library/Frameworks), then it is considered implicitly linked: we
592 // should bind to its symbols directly instead of via the re-exporting umbrella
593 // library.
594 static bool isImplicitlyLinked(StringRef path) {
595   if (!config->implicitDylibs)
596     return false;
597 
598   if (path::parent_path(path) == "/usr/lib")
599     return true;
600 
601   // Match /System/Library/Frameworks/$FOO.framework/**/$FOO
602   if (path.consume_front("/System/Library/Frameworks/")) {
603     StringRef frameworkName = path.take_until([](char c) { return c == '.'; });
604     return path::filename(path) == frameworkName;
605   }
606 
607   return false;
608 }
609 
610 void loadReexport(StringRef path, DylibFile *umbrella,
611                   const InterfaceFile *currentTopLevelTapi) {
612   Optional<DylibFile *> reexport =
613       findDylib(path, umbrella, currentTopLevelTapi);
614   if (!reexport)
615     error("unable to locate re-export with install name " + path);
616   else if (isImplicitlyLinked(path))
617     inputFiles.insert(*reexport);
618 }
619 
620 DylibFile::DylibFile(MemoryBufferRef mb, DylibFile *umbrella,
621                      bool isBundleLoader)
622     : InputFile(DylibKind, mb), refState(RefState::Unreferenced),
623       isBundleLoader(isBundleLoader) {
624   assert(!isBundleLoader || !umbrella);
625   if (umbrella == nullptr)
626     umbrella = this;
627 
628   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
629   auto *hdr = reinterpret_cast<const mach_header_64 *>(mb.getBufferStart());
630 
631   // Initialize dylibName.
632   if (const load_command *cmd = findCommand(hdr, LC_ID_DYLIB)) {
633     auto *c = reinterpret_cast<const dylib_command *>(cmd);
634     currentVersion = read32le(&c->dylib.current_version);
635     compatibilityVersion = read32le(&c->dylib.compatibility_version);
636     dylibName = reinterpret_cast<const char *>(cmd) + read32le(&c->dylib.name);
637   } else if (!isBundleLoader) {
638     // macho_executable and macho_bundle don't have LC_ID_DYLIB,
639     // so it's OK.
640     error("dylib " + toString(this) + " missing LC_ID_DYLIB load command");
641     return;
642   }
643 
644   // Initialize symbols.
645   DylibFile *exportingFile = isImplicitlyLinked(dylibName) ? this : umbrella;
646   if (const load_command *cmd = findCommand(hdr, LC_DYLD_INFO_ONLY)) {
647     auto *c = reinterpret_cast<const dyld_info_command *>(cmd);
648     parseTrie(buf + c->export_off, c->export_size,
649               [&](const Twine &name, uint64_t flags) {
650                 bool isWeakDef = flags & EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION;
651                 bool isTlv = flags & EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL;
652                 symbols.push_back(symtab->addDylib(
653                     saver.save(name), exportingFile, isWeakDef, isTlv));
654               });
655   } else {
656     error("LC_DYLD_INFO_ONLY not found in " + toString(this));
657     return;
658   }
659 
660   const uint8_t *p =
661       reinterpret_cast<const uint8_t *>(hdr) + sizeof(mach_header_64);
662   for (uint32_t i = 0, n = hdr->ncmds; i < n; ++i) {
663     auto *cmd = reinterpret_cast<const load_command *>(p);
664     p += cmd->cmdsize;
665 
666     if (!(hdr->flags & MH_NO_REEXPORTED_DYLIBS) &&
667         cmd->cmd == LC_REEXPORT_DYLIB) {
668       const auto *c = reinterpret_cast<const dylib_command *>(cmd);
669       StringRef reexportPath =
670           reinterpret_cast<const char *>(c) + read32le(&c->dylib.name);
671       loadReexport(reexportPath, umbrella, nullptr);
672     }
673 
674     // FIXME: What about LC_LOAD_UPWARD_DYLIB, LC_LAZY_LOAD_DYLIB,
675     // LC_LOAD_WEAK_DYLIB, LC_REEXPORT_DYLIB (..are reexports from dylibs with
676     // MH_NO_REEXPORTED_DYLIBS loaded for -flat_namespace)?
677     if (config->namespaceKind == NamespaceKind::flat &&
678         cmd->cmd == LC_LOAD_DYLIB) {
679       const auto *c = reinterpret_cast<const dylib_command *>(cmd);
680       StringRef dylibPath =
681           reinterpret_cast<const char *>(c) + read32le(&c->dylib.name);
682       Optional<DylibFile *> dylib = findDylib(dylibPath, umbrella, nullptr);
683       if (!dylib)
684         error(Twine("unable to locate library '") + dylibPath +
685               "' loaded from '" + toString(this) + "' for -flat_namespace");
686     }
687   }
688 }
689 
690 DylibFile::DylibFile(const InterfaceFile &interface, DylibFile *umbrella,
691                      bool isBundleLoader)
692     : InputFile(DylibKind, interface), refState(RefState::Unreferenced),
693       isBundleLoader(isBundleLoader) {
694   // FIXME: Add test for the missing TBD code path.
695 
696   if (umbrella == nullptr)
697     umbrella = this;
698 
699   if (!interface.getArchitectures().has(config->arch)) {
700     error(toString(this) + " is incompatible with " +
701           getArchitectureName(config->arch));
702     return;
703   }
704 
705   dylibName = saver.save(interface.getInstallName());
706   compatibilityVersion = interface.getCompatibilityVersion().rawValue();
707   currentVersion = interface.getCurrentVersion().rawValue();
708   DylibFile *exportingFile = isImplicitlyLinked(dylibName) ? this : umbrella;
709   auto addSymbol = [&](const Twine &name) -> void {
710     symbols.push_back(symtab->addDylib(saver.save(name), exportingFile,
711                                        /*isWeakDef=*/false,
712                                        /*isTlv=*/false));
713   };
714   // TODO(compnerd) filter out symbols based on the target platform
715   // TODO: handle weak defs, thread locals
716   for (const auto symbol : interface.symbols()) {
717     if (!symbol->getArchitectures().has(config->arch))
718       continue;
719 
720     switch (symbol->getKind()) {
721     case SymbolKind::GlobalSymbol:
722       addSymbol(symbol->getName());
723       break;
724     case SymbolKind::ObjectiveCClass:
725       // XXX ld64 only creates these symbols when -ObjC is passed in. We may
726       // want to emulate that.
727       addSymbol(objc::klass + symbol->getName());
728       addSymbol(objc::metaclass + symbol->getName());
729       break;
730     case SymbolKind::ObjectiveCClassEHType:
731       addSymbol(objc::ehtype + symbol->getName());
732       break;
733     case SymbolKind::ObjectiveCInstanceVariable:
734       addSymbol(objc::ivar + symbol->getName());
735       break;
736     }
737   }
738 
739   const InterfaceFile *topLevel =
740       interface.getParent() == nullptr ? &interface : interface.getParent();
741 
742   for (InterfaceFileRef intfRef : interface.reexportedLibraries())
743     loadReexport(intfRef.getInstallName(), umbrella, topLevel);
744 }
745 
746 ArchiveFile::ArchiveFile(std::unique_ptr<object::Archive> &&f)
747     : InputFile(ArchiveKind, f->getMemoryBufferRef()), file(std::move(f)) {
748   for (const object::Archive::Symbol &sym : file->symbols())
749     symtab->addLazy(sym.getName(), this, sym);
750 }
751 
752 void ArchiveFile::fetch(const object::Archive::Symbol &sym) {
753   object::Archive::Child c =
754       CHECK(sym.getMember(), toString(this) +
755                                  ": could not get the member for symbol " +
756                                  toMachOString(sym));
757 
758   if (!seen.insert(c.getChildOffset()).second)
759     return;
760 
761   MemoryBufferRef mb =
762       CHECK(c.getMemoryBufferRef(),
763             toString(this) +
764                 ": could not get the buffer for the member defining symbol " +
765                 toMachOString(sym));
766 
767   if (tar && c.getParent()->isThin())
768     tar->append(relativeToRoot(CHECK(c.getFullName(), this)), mb.getBuffer());
769 
770   uint32_t modTime = toTimeT(
771       CHECK(c.getLastModified(), toString(this) +
772                                      ": could not get the modification time "
773                                      "for the member defining symbol " +
774                                      toMachOString(sym)));
775 
776   // `sym` is owned by a LazySym, which will be replace<>() by make<ObjFile>
777   // and become invalid after that call. Copy it to the stack so we can refer
778   // to it later.
779   const object::Archive::Symbol sym_copy = sym;
780 
781   if (Optional<InputFile *> file =
782           loadArchiveMember(mb, modTime, getName(), /*objCOnly=*/false)) {
783     inputFiles.insert(*file);
784     // ld64 doesn't demangle sym here even with -demangle. Match that, so
785     // intentionally no call to toMachOString() here.
786     printArchiveMemberLoad(sym_copy.getName(), *file);
787   }
788 }
789 
790 static macho::Symbol *createBitcodeSymbol(const lto::InputFile::Symbol &objSym,
791                                           BitcodeFile &file) {
792   StringRef name = saver.save(objSym.getName());
793 
794   // TODO: support weak references
795   if (objSym.isUndefined())
796     return symtab->addUndefined(name, &file, /*isWeakRef=*/false);
797 
798   assert(!objSym.isCommon() && "TODO: support common symbols in LTO");
799 
800   // TODO: Write a test demonstrating why computing isPrivateExtern before
801   // LTO compilation is important.
802   bool isPrivateExtern = false;
803   switch (objSym.getVisibility()) {
804   case GlobalValue::HiddenVisibility:
805     isPrivateExtern = true;
806     break;
807   case GlobalValue::ProtectedVisibility:
808     error(name + " has protected visibility, which is not supported by Mach-O");
809     break;
810   case GlobalValue::DefaultVisibility:
811     break;
812   }
813 
814   return symtab->addDefined(name, &file, /*isec=*/nullptr, /*value=*/0,
815                             objSym.isWeak(), isPrivateExtern);
816 }
817 
818 BitcodeFile::BitcodeFile(MemoryBufferRef mbref)
819     : InputFile(BitcodeKind, mbref) {
820   obj = check(lto::InputFile::create(mbref));
821 
822   // Convert LTO Symbols to LLD Symbols in order to perform resolution. The
823   // "winning" symbol will then be marked as Prevailing at LTO compilation
824   // time.
825   for (const lto::InputFile::Symbol &objSym : obj->symbols())
826     symbols.push_back(createBitcodeSymbol(objSym, *this));
827 }
828