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, uint64_t size) {
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, size,
346                               sym.n_desc & N_WEAK_DEF, sym.n_type & N_PEXT);
347   }
348   return make<Defined>(name, isec->file, isec, value, size,
349                        sym.n_desc & N_WEAK_DEF,
350                        /*isExternal=*/false, /*isPrivateExtern=*/false);
351 }
352 
353 // Checks if the version specified in `cmd` is compatible with target
354 // version. IOW, check if cmd's version >= config's version.
355 static bool hasCompatVersion(const InputFile *input,
356                              const build_version_command *cmd) {
357 
358   if (config->target.Platform != static_cast<PlatformKind>(cmd->platform)) {
359     error(toString(input) + " has platform " +
360           getPlatformName(static_cast<PlatformKind>(cmd->platform)) +
361           Twine(", which is different from target platform ") +
362           getPlatformName(config->target.Platform));
363     return false;
364   }
365 
366   unsigned major = cmd->minos >> 16;
367   unsigned minor = (cmd->minos >> 8) & 0xffu;
368   unsigned subMinor = cmd->minos & 0xffu;
369   VersionTuple version(major, minor, subMinor);
370   if (version >= config->platformInfo.minimum)
371     return true;
372 
373   error(toString(input) + " has version " + version.getAsString() +
374         ", which is incompatible with target version of " +
375         config->platformInfo.minimum.getAsString());
376   return false;
377 }
378 
379 // Absolute symbols are defined symbols that do not have an associated
380 // InputSection. They cannot be weak.
381 static macho::Symbol *createAbsolute(const structs::nlist_64 &sym,
382                                      InputFile *file, StringRef name) {
383   if (sym.n_type & (N_EXT | N_PEXT)) {
384     assert((sym.n_type & N_EXT) && "invalid input");
385     return symtab->addDefined(name, file, nullptr, sym.n_value, /*size=*/0,
386                               /*isWeakDef=*/false, sym.n_type & N_PEXT);
387   }
388   return make<Defined>(name, file, nullptr, sym.n_value, /*size=*/0,
389                        /*isWeakDef=*/false,
390                        /*isExternal=*/false, /*isPrivateExtern=*/false);
391 }
392 
393 macho::Symbol *ObjFile::parseNonSectionSymbol(const structs::nlist_64 &sym,
394                                               StringRef name) {
395   uint8_t type = sym.n_type & N_TYPE;
396   switch (type) {
397   case N_UNDF:
398     return sym.n_value == 0
399                ? symtab->addUndefined(name, this, sym.n_desc & N_WEAK_REF)
400                : symtab->addCommon(name, this, sym.n_value,
401                                    1 << GET_COMM_ALIGN(sym.n_desc),
402                                    sym.n_type & N_PEXT);
403   case N_ABS:
404     return createAbsolute(sym, this, name);
405   case N_PBUD:
406   case N_INDR:
407     error("TODO: support symbols of type " + std::to_string(type));
408     return nullptr;
409   case N_SECT:
410     llvm_unreachable(
411         "N_SECT symbols should not be passed to parseNonSectionSymbol");
412   default:
413     llvm_unreachable("invalid symbol type");
414   }
415 }
416 
417 void ObjFile::parseSymbols(ArrayRef<structs::nlist_64> nList,
418                            const char *strtab, bool subsectionsViaSymbols) {
419   // Precompute the boundaries of symbols within a section.
420   // If subsectionsViaSymbols is True then the corresponding subsections will be
421   // created, otherwise these boundaries are used for the calculation of symbols
422   // sizes only.
423 
424   for (const structs::nlist_64 &sym : nList) {
425     if ((sym.n_type & N_TYPE) == N_SECT && !(sym.n_desc & N_ALT_ENTRY) &&
426         !subsections[sym.n_sect - 1].empty()) {
427       SubsectionMapping &subsectionMapping = subsections[sym.n_sect - 1];
428       subsectionMapping.push_back(
429           {sym.n_value - sectionHeaders[sym.n_sect - 1].addr,
430            subsectionMapping.front().isec});
431     }
432   }
433 
434   for (SubsectionMapping &subsectionMap : subsections) {
435     if (subsectionMap.empty())
436       continue;
437     llvm::sort(subsectionMap,
438                [](const SubsectionEntry &lhs, const SubsectionEntry &rhs) {
439                  return lhs.offset < rhs.offset;
440                });
441     subsectionMap.erase(
442         std::unique(subsectionMap.begin(), subsectionMap.end(),
443                     [](const SubsectionEntry &lhs, const SubsectionEntry &rhs) {
444                       return lhs.offset == rhs.offset;
445                     }),
446         subsectionMap.end());
447     if (!subsectionsViaSymbols)
448       continue;
449     for (size_t i = 0; i < subsectionMap.size(); ++i) {
450       uint32_t offset = subsectionMap[i].offset;
451       InputSection *&isec = subsectionMap[i].isec;
452       uint32_t end = i + 1 < subsectionMap.size() ? subsectionMap[i + 1].offset
453                                                   : isec->data.size();
454       isec = make<InputSection>(*isec);
455       isec->data = isec->data.slice(offset, end - offset);
456       // TODO: ld64 appears to preserve the original alignment as well as each
457       // subsection's offset from the last aligned address. We should consider
458       // emulating that behavior.
459       isec->align = MinAlign(isec->align, offset);
460     }
461   }
462 
463   symbols.resize(nList.size());
464   for (size_t i = 0, n = nList.size(); i < n; ++i) {
465     const structs::nlist_64 &sym = nList[i];
466     StringRef name = strtab + sym.n_strx;
467 
468     if ((sym.n_type & N_TYPE) != N_SECT) {
469       symbols[i] = parseNonSectionSymbol(sym, name);
470       continue;
471     }
472 
473     const section_64 &sec = sectionHeaders[sym.n_sect - 1];
474     SubsectionMapping &subsecMap = subsections[sym.n_sect - 1];
475 
476     // parseSections() may have chosen not to parse this section.
477     if (subsecMap.empty())
478       continue;
479 
480     uint64_t offset = sym.n_value - sec.addr;
481 
482     auto it = llvm::upper_bound(
483         subsecMap, offset, [](uint64_t value, SubsectionEntry subsectionEntry) {
484           return value < subsectionEntry.offset;
485         });
486     uint32_t size = it != subsecMap.end()
487                         ? it->offset - offset
488                         : subsecMap.front().isec->getSize() - offset;
489 
490     // If the input file does not use subsections-via-symbols, all symbols can
491     // use the same subsection. Otherwise, we must split the sections along
492     // symbol boundaries.
493     if (!subsectionsViaSymbols) {
494       symbols[i] =
495           createDefined(sym, name, subsecMap.front().isec, offset, size);
496       continue;
497     }
498 
499     InputSection *subsec = (--it)->isec;
500     symbols[i] = createDefined(sym, name, subsec, offset - it->offset, size);
501   }
502 
503   if (!subsectionsViaSymbols)
504     for (SubsectionMapping &subsectionMap : subsections)
505       if (!subsectionMap.empty())
506         subsectionMap = {subsectionMap.front()};
507 }
508 
509 OpaqueFile::OpaqueFile(MemoryBufferRef mb, StringRef segName,
510                        StringRef sectName)
511     : InputFile(OpaqueKind, mb) {
512   InputSection *isec = make<InputSection>();
513   isec->file = this;
514   isec->name = sectName.take_front(16);
515   isec->segname = segName.take_front(16);
516   const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
517   isec->data = {buf, mb.getBufferSize()};
518   subsections.push_back({{0, isec}});
519 }
520 
521 ObjFile::ObjFile(MemoryBufferRef mb, uint32_t modTime, StringRef archiveName)
522     : InputFile(ObjKind, mb), modTime(modTime) {
523   this->archiveName = std::string(archiveName);
524 
525   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
526   auto *hdr = reinterpret_cast<const mach_header_64 *>(mb.getBufferStart());
527 
528   Architecture arch = getArchitectureFromCpuType(hdr->cputype, hdr->cpusubtype);
529   if (arch != config->target.Arch) {
530     error(toString(this) + " has architecture " + getArchitectureName(arch) +
531           " which is incompatible with target architecture " +
532           getArchitectureName(config->target.Arch));
533     return;
534   }
535 
536   if (const auto *cmd =
537           findCommand<build_version_command>(hdr, LC_BUILD_VERSION)) {
538     if (!hasCompatVersion(this, cmd))
539       return;
540   }
541 
542   if (const load_command *cmd = findCommand(hdr, LC_LINKER_OPTION)) {
543     auto *c = reinterpret_cast<const linker_option_command *>(cmd);
544     StringRef data{reinterpret_cast<const char *>(c + 1),
545                    c->cmdsize - sizeof(linker_option_command)};
546     parseLCLinkerOption(this, c->count, data);
547   }
548 
549   if (const load_command *cmd = findCommand(hdr, LC_SEGMENT_64)) {
550     auto *c = reinterpret_cast<const segment_command_64 *>(cmd);
551     sectionHeaders = ArrayRef<section_64>{
552         reinterpret_cast<const section_64 *>(c + 1), c->nsects};
553     parseSections(sectionHeaders);
554   }
555 
556   // TODO: Error on missing LC_SYMTAB?
557   if (const load_command *cmd = findCommand(hdr, LC_SYMTAB)) {
558     auto *c = reinterpret_cast<const symtab_command *>(cmd);
559     ArrayRef<structs::nlist_64> nList(
560         reinterpret_cast<const structs::nlist_64 *>(buf + c->symoff), c->nsyms);
561     const char *strtab = reinterpret_cast<const char *>(buf) + c->stroff;
562     bool subsectionsViaSymbols = hdr->flags & MH_SUBSECTIONS_VIA_SYMBOLS;
563     parseSymbols(nList, strtab, subsectionsViaSymbols);
564   }
565 
566   // The relocations may refer to the symbols, so we parse them after we have
567   // parsed all the symbols.
568   for (size_t i = 0, n = subsections.size(); i < n; ++i)
569     if (!subsections[i].empty())
570       parseRelocations(sectionHeaders[i], subsections[i]);
571 
572   parseDebugInfo();
573 }
574 
575 void ObjFile::parseDebugInfo() {
576   std::unique_ptr<DwarfObject> dObj = DwarfObject::create(this);
577   if (!dObj)
578     return;
579 
580   auto *ctx = make<DWARFContext>(
581       std::move(dObj), "",
582       [&](Error err) {
583         warn(toString(this) + ": " + toString(std::move(err)));
584       },
585       [&](Error warning) {
586         warn(toString(this) + ": " + toString(std::move(warning)));
587       });
588 
589   // TODO: Since object files can contain a lot of DWARF info, we should verify
590   // that we are parsing just the info we need
591   const DWARFContext::compile_unit_range &units = ctx->compile_units();
592   // FIXME: There can be more than one compile unit per object file. See
593   // PR48637.
594   auto it = units.begin();
595   compileUnit = it->get();
596 }
597 
598 // The path can point to either a dylib or a .tbd file.
599 static Optional<DylibFile *> loadDylib(StringRef path, DylibFile *umbrella) {
600   Optional<MemoryBufferRef> mbref = readFile(path);
601   if (!mbref) {
602     error("could not read dylib file at " + path);
603     return {};
604   }
605   return loadDylib(*mbref, umbrella);
606 }
607 
608 // TBD files are parsed into a series of TAPI documents (InterfaceFiles), with
609 // the first document storing child pointers to the rest of them. When we are
610 // processing a given TBD file, we store that top-level document in
611 // currentTopLevelTapi. When processing re-exports, we search its children for
612 // potentially matching documents in the same TBD file. Note that the children
613 // themselves don't point to further documents, i.e. this is a two-level tree.
614 //
615 // Re-exports can either refer to on-disk files, or to documents within .tbd
616 // files.
617 static Optional<DylibFile *>
618 findDylib(StringRef path, DylibFile *umbrella,
619           const InterfaceFile *currentTopLevelTapi) {
620   if (path::is_absolute(path, path::Style::posix))
621     for (StringRef root : config->systemLibraryRoots)
622       if (Optional<std::string> dylibPath =
623               resolveDylibPath((root + path).str()))
624         return loadDylib(*dylibPath, umbrella);
625 
626   // TODO: Expand @loader_path, @executable_path, @rpath etc, handle -dylib_path
627 
628   if (currentTopLevelTapi) {
629     for (InterfaceFile &child :
630          make_pointee_range(currentTopLevelTapi->documents())) {
631       assert(child.documents().empty());
632       if (path == child.getInstallName())
633         return make<DylibFile>(child, umbrella);
634     }
635   }
636 
637   if (Optional<std::string> dylibPath = resolveDylibPath(path))
638     return loadDylib(*dylibPath, umbrella);
639 
640   return {};
641 }
642 
643 // If a re-exported dylib is public (lives in /usr/lib or
644 // /System/Library/Frameworks), then it is considered implicitly linked: we
645 // should bind to its symbols directly instead of via the re-exporting umbrella
646 // library.
647 static bool isImplicitlyLinked(StringRef path) {
648   if (!config->implicitDylibs)
649     return false;
650 
651   if (path::parent_path(path) == "/usr/lib")
652     return true;
653 
654   // Match /System/Library/Frameworks/$FOO.framework/**/$FOO
655   if (path.consume_front("/System/Library/Frameworks/")) {
656     StringRef frameworkName = path.take_until([](char c) { return c == '.'; });
657     return path::filename(path) == frameworkName;
658   }
659 
660   return false;
661 }
662 
663 void loadReexport(StringRef path, DylibFile *umbrella,
664                   const InterfaceFile *currentTopLevelTapi) {
665   Optional<DylibFile *> reexport =
666       findDylib(path, umbrella, currentTopLevelTapi);
667   if (!reexport)
668     error("unable to locate re-export with install name " + path);
669   else if (isImplicitlyLinked(path))
670     inputFiles.insert(*reexport);
671 }
672 
673 DylibFile::DylibFile(MemoryBufferRef mb, DylibFile *umbrella,
674                      bool isBundleLoader)
675     : InputFile(DylibKind, mb), refState(RefState::Unreferenced),
676       isBundleLoader(isBundleLoader) {
677   assert(!isBundleLoader || !umbrella);
678   if (umbrella == nullptr)
679     umbrella = this;
680 
681   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
682   auto *hdr = reinterpret_cast<const mach_header_64 *>(mb.getBufferStart());
683 
684   // Initialize dylibName.
685   if (const load_command *cmd = findCommand(hdr, LC_ID_DYLIB)) {
686     auto *c = reinterpret_cast<const dylib_command *>(cmd);
687     currentVersion = read32le(&c->dylib.current_version);
688     compatibilityVersion = read32le(&c->dylib.compatibility_version);
689     dylibName = reinterpret_cast<const char *>(cmd) + read32le(&c->dylib.name);
690   } else if (!isBundleLoader) {
691     // macho_executable and macho_bundle don't have LC_ID_DYLIB,
692     // so it's OK.
693     error("dylib " + toString(this) + " missing LC_ID_DYLIB load command");
694     return;
695   }
696 
697   if (const build_version_command *cmd =
698           findCommand<build_version_command>(hdr, LC_BUILD_VERSION)) {
699     if (!hasCompatVersion(this, cmd))
700       return;
701   }
702 
703   // Initialize symbols.
704   DylibFile *exportingFile = isImplicitlyLinked(dylibName) ? this : umbrella;
705   if (const load_command *cmd = findCommand(hdr, LC_DYLD_INFO_ONLY)) {
706     auto *c = reinterpret_cast<const dyld_info_command *>(cmd);
707     parseTrie(buf + c->export_off, c->export_size,
708               [&](const Twine &name, uint64_t flags) {
709                 bool isWeakDef = flags & EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION;
710                 bool isTlv = flags & EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL;
711                 symbols.push_back(symtab->addDylib(
712                     saver.save(name), exportingFile, isWeakDef, isTlv));
713               });
714   } else {
715     error("LC_DYLD_INFO_ONLY not found in " + toString(this));
716     return;
717   }
718 
719   const uint8_t *p =
720       reinterpret_cast<const uint8_t *>(hdr) + sizeof(mach_header_64);
721   for (uint32_t i = 0, n = hdr->ncmds; i < n; ++i) {
722     auto *cmd = reinterpret_cast<const load_command *>(p);
723     p += cmd->cmdsize;
724 
725     if (!(hdr->flags & MH_NO_REEXPORTED_DYLIBS) &&
726         cmd->cmd == LC_REEXPORT_DYLIB) {
727       const auto *c = reinterpret_cast<const dylib_command *>(cmd);
728       StringRef reexportPath =
729           reinterpret_cast<const char *>(c) + read32le(&c->dylib.name);
730       loadReexport(reexportPath, exportingFile, nullptr);
731     }
732 
733     // FIXME: What about LC_LOAD_UPWARD_DYLIB, LC_LAZY_LOAD_DYLIB,
734     // LC_LOAD_WEAK_DYLIB, LC_REEXPORT_DYLIB (..are reexports from dylibs with
735     // MH_NO_REEXPORTED_DYLIBS loaded for -flat_namespace)?
736     if (config->namespaceKind == NamespaceKind::flat &&
737         cmd->cmd == LC_LOAD_DYLIB) {
738       const auto *c = reinterpret_cast<const dylib_command *>(cmd);
739       StringRef dylibPath =
740           reinterpret_cast<const char *>(c) + read32le(&c->dylib.name);
741       Optional<DylibFile *> dylib = findDylib(dylibPath, umbrella, nullptr);
742       if (!dylib)
743         error(Twine("unable to locate library '") + dylibPath +
744               "' loaded from '" + toString(this) + "' for -flat_namespace");
745     }
746   }
747 }
748 
749 DylibFile::DylibFile(const InterfaceFile &interface, DylibFile *umbrella,
750                      bool isBundleLoader)
751     : InputFile(DylibKind, interface), refState(RefState::Unreferenced),
752       isBundleLoader(isBundleLoader) {
753   // FIXME: Add test for the missing TBD code path.
754 
755   if (umbrella == nullptr)
756     umbrella = this;
757 
758   dylibName = saver.save(interface.getInstallName());
759   compatibilityVersion = interface.getCompatibilityVersion().rawValue();
760   currentVersion = interface.getCurrentVersion().rawValue();
761 
762   if (!is_contained(interface.targets(), config->target)) {
763     error(toString(this) + " is incompatible with " +
764           std::string(config->target));
765     return;
766   }
767 
768   DylibFile *exportingFile = isImplicitlyLinked(dylibName) ? this : umbrella;
769   auto addSymbol = [&](const Twine &name) -> void {
770     symbols.push_back(symtab->addDylib(saver.save(name), exportingFile,
771                                        /*isWeakDef=*/false,
772                                        /*isTlv=*/false));
773   };
774   // TODO(compnerd) filter out symbols based on the target platform
775   // TODO: handle weak defs, thread locals
776   for (const auto *symbol : interface.symbols()) {
777     if (!symbol->getArchitectures().has(config->target.Arch))
778       continue;
779 
780     switch (symbol->getKind()) {
781     case SymbolKind::GlobalSymbol:
782       addSymbol(symbol->getName());
783       break;
784     case SymbolKind::ObjectiveCClass:
785       // XXX ld64 only creates these symbols when -ObjC is passed in. We may
786       // want to emulate that.
787       addSymbol(objc::klass + symbol->getName());
788       addSymbol(objc::metaclass + symbol->getName());
789       break;
790     case SymbolKind::ObjectiveCClassEHType:
791       addSymbol(objc::ehtype + symbol->getName());
792       break;
793     case SymbolKind::ObjectiveCInstanceVariable:
794       addSymbol(objc::ivar + symbol->getName());
795       break;
796     }
797   }
798 
799   const InterfaceFile *topLevel =
800       interface.getParent() == nullptr ? &interface : interface.getParent();
801 
802   for (InterfaceFileRef intfRef : interface.reexportedLibraries()) {
803     InterfaceFile::const_target_range targets = intfRef.targets();
804     if (is_contained(targets, config->target))
805       loadReexport(intfRef.getInstallName(), exportingFile, topLevel);
806   }
807 }
808 
809 ArchiveFile::ArchiveFile(std::unique_ptr<object::Archive> &&f)
810     : InputFile(ArchiveKind, f->getMemoryBufferRef()), file(std::move(f)) {
811   for (const object::Archive::Symbol &sym : file->symbols())
812     symtab->addLazy(sym.getName(), this, sym);
813 }
814 
815 void ArchiveFile::fetch(const object::Archive::Symbol &sym) {
816   object::Archive::Child c =
817       CHECK(sym.getMember(), toString(this) +
818                                  ": could not get the member for symbol " +
819                                  toMachOString(sym));
820 
821   if (!seen.insert(c.getChildOffset()).second)
822     return;
823 
824   MemoryBufferRef mb =
825       CHECK(c.getMemoryBufferRef(),
826             toString(this) +
827                 ": could not get the buffer for the member defining symbol " +
828                 toMachOString(sym));
829 
830   if (tar && c.getParent()->isThin())
831     tar->append(relativeToRoot(CHECK(c.getFullName(), this)), mb.getBuffer());
832 
833   uint32_t modTime = toTimeT(
834       CHECK(c.getLastModified(), toString(this) +
835                                      ": could not get the modification time "
836                                      "for the member defining symbol " +
837                                      toMachOString(sym)));
838 
839   // `sym` is owned by a LazySym, which will be replace<>() by make<ObjFile>
840   // and become invalid after that call. Copy it to the stack so we can refer
841   // to it later.
842   const object::Archive::Symbol sym_copy = sym;
843 
844   if (Optional<InputFile *> file =
845           loadArchiveMember(mb, modTime, getName(), /*objCOnly=*/false)) {
846     inputFiles.insert(*file);
847     // ld64 doesn't demangle sym here even with -demangle. Match that, so
848     // intentionally no call to toMachOString() here.
849     printArchiveMemberLoad(sym_copy.getName(), *file);
850   }
851 }
852 
853 static macho::Symbol *createBitcodeSymbol(const lto::InputFile::Symbol &objSym,
854                                           BitcodeFile &file) {
855   StringRef name = saver.save(objSym.getName());
856 
857   // TODO: support weak references
858   if (objSym.isUndefined())
859     return symtab->addUndefined(name, &file, /*isWeakRef=*/false);
860 
861   assert(!objSym.isCommon() && "TODO: support common symbols in LTO");
862 
863   // TODO: Write a test demonstrating why computing isPrivateExtern before
864   // LTO compilation is important.
865   bool isPrivateExtern = false;
866   switch (objSym.getVisibility()) {
867   case GlobalValue::HiddenVisibility:
868     isPrivateExtern = true;
869     break;
870   case GlobalValue::ProtectedVisibility:
871     error(name + " has protected visibility, which is not supported by Mach-O");
872     break;
873   case GlobalValue::DefaultVisibility:
874     break;
875   }
876 
877   return symtab->addDefined(name, &file, /*isec=*/nullptr, /*value=*/0,
878                             /*size=*/0, objSym.isWeak(), isPrivateExtern);
879 }
880 
881 BitcodeFile::BitcodeFile(MemoryBufferRef mbref)
882     : InputFile(BitcodeKind, mbref) {
883   obj = check(lto::InputFile::create(mbref));
884 
885   // Convert LTO Symbols to LLD Symbols in order to perform resolution. The
886   // "winning" symbol will then be marked as Prevailing at LTO compilation
887   // time.
888   for (const lto::InputFile::Symbol &objSym : obj->symbols())
889     symbols.push_back(createBitcodeSymbol(objSym, *this));
890 }
891