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