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