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