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