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