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