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