16acd3003SFangrui Song //===- InputFiles.cpp -----------------------------------------------------===//
26acd3003SFangrui Song //
36acd3003SFangrui Song // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
46acd3003SFangrui Song // See https://llvm.org/LICENSE.txt for license information.
56acd3003SFangrui Song // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
66acd3003SFangrui Song //
76acd3003SFangrui Song //===----------------------------------------------------------------------===//
86acd3003SFangrui Song //
96acd3003SFangrui Song // This file contains functions to parse Mach-O object files. In this comment,
106acd3003SFangrui Song // we describe the Mach-O file structure and how we parse it.
116acd3003SFangrui Song //
126acd3003SFangrui Song // Mach-O is not very different from ELF or COFF. The notion of symbols,
136acd3003SFangrui Song // sections and relocations exists in Mach-O as it does in ELF and COFF.
146acd3003SFangrui Song //
156acd3003SFangrui Song // Perhaps the notion that is new to those who know ELF/COFF is "subsections".
166acd3003SFangrui Song // In ELF/COFF, sections are an atomic unit of data copied from input files to
176acd3003SFangrui Song // output files. When we merge or garbage-collect sections, we treat each
186acd3003SFangrui Song // section as an atomic unit. In Mach-O, that's not the case. Sections can
196acd3003SFangrui Song // consist of multiple subsections, and subsections are a unit of merging and
206acd3003SFangrui Song // garbage-collecting. Therefore, Mach-O's subsections are more similar to
216acd3003SFangrui Song // ELF/COFF's sections than Mach-O's sections are.
226acd3003SFangrui Song //
236acd3003SFangrui Song // A section can have multiple symbols. A symbol that does not have the
246acd3003SFangrui Song // N_ALT_ENTRY attribute indicates a beginning of a subsection. Therefore, by
256acd3003SFangrui Song // definition, a symbol is always present at the beginning of each subsection. A
266acd3003SFangrui Song // symbol with N_ALT_ENTRY attribute does not start a new subsection and can
276acd3003SFangrui Song // point to a middle of a subsection.
286acd3003SFangrui Song //
296acd3003SFangrui Song // The notion of subsections also affects how relocations are represented in
306acd3003SFangrui Song // Mach-O. All references within a section need to be explicitly represented as
316acd3003SFangrui Song // relocations if they refer to different subsections, because we obviously need
326acd3003SFangrui Song // to fix up addresses if subsections are laid out in an output file differently
336acd3003SFangrui Song // than they were in object files. To represent that, Mach-O relocations can
346acd3003SFangrui Song // refer to an unnamed location via its address. Scattered relocations (those
356acd3003SFangrui Song // with the R_SCATTERED bit set) always refer to unnamed locations.
366acd3003SFangrui Song // Non-scattered relocations refer to an unnamed location if r_extern is not set
376acd3003SFangrui Song // and r_symbolnum is zero.
386acd3003SFangrui Song //
396acd3003SFangrui Song // Without the above differences, I think you can use your knowledge about ELF
406acd3003SFangrui Song // and COFF for Mach-O.
416acd3003SFangrui Song //
426acd3003SFangrui Song //===----------------------------------------------------------------------===//
436acd3003SFangrui Song 
446acd3003SFangrui Song #include "InputFiles.h"
4587b6fd3eSJez Ng #include "Config.h"
46c519bc7eSNico Weber #include "Driver.h"
473fcb0eebSJez Ng #include "Dwarf.h"
487bbdbacdSJez Ng #include "ExportTrie.h"
496acd3003SFangrui Song #include "InputSection.h"
501e1a3f67SJez Ng #include "MachOStructs.h"
51cf918c80SJez Ng #include "ObjC.h"
526cb07313SKellie Medlin #include "OutputSection.h"
53cf918c80SJez Ng #include "OutputSegment.h"
546acd3003SFangrui Song #include "SymbolTable.h"
556acd3003SFangrui Song #include "Symbols.h"
566acd3003SFangrui Song #include "Target.h"
576acd3003SFangrui Song 
583fcb0eebSJez Ng #include "lld/Common/DWARF.h"
596acd3003SFangrui Song #include "lld/Common/ErrorHandler.h"
606acd3003SFangrui Song #include "lld/Common/Memory.h"
6183e60f5aSNico Weber #include "lld/Common/Reproduce.h"
627394460dSJez Ng #include "llvm/ADT/iterator.h"
636acd3003SFangrui Song #include "llvm/BinaryFormat/MachO.h"
6421f83113SJez Ng #include "llvm/LTO/LTO.h"
656acd3003SFangrui Song #include "llvm/Support/Endian.h"
666acd3003SFangrui Song #include "llvm/Support/MemoryBuffer.h"
6787b6fd3eSJez Ng #include "llvm/Support/Path.h"
6883e60f5aSNico Weber #include "llvm/Support/TarWriter.h"
694752cdc9SJez Ng #include "llvm/TextAPI/MachO/Architecture.h"
706acd3003SFangrui Song 
716acd3003SFangrui Song using namespace llvm;
726acd3003SFangrui Song using namespace llvm::MachO;
736acd3003SFangrui Song using namespace llvm::support::endian;
7487b6fd3eSJez Ng using namespace llvm::sys;
756acd3003SFangrui Song using namespace lld;
766acd3003SFangrui Song using namespace lld::macho;
776acd3003SFangrui Song 
78b2f00f24SNico Weber // Returns "<internal>", "foo.a(bar.o)", or "baz.o".
79b2f00f24SNico Weber std::string lld::toString(const InputFile *f) {
80b2f00f24SNico Weber   if (!f)
81b2f00f24SNico Weber     return "<internal>";
820d4dadc6SJez Ng 
830d4dadc6SJez Ng   // Multiple dylibs can be defined in one .tbd file.
840d4dadc6SJez Ng   if (auto dylibFile = dyn_cast<DylibFile>(f))
850d4dadc6SJez Ng     if (f->getName().endswith(".tbd"))
860d4dadc6SJez Ng       return (f->getName() + "(" + dylibFile->dylibName + ")").str();
870d4dadc6SJez Ng 
88b2f00f24SNico Weber   if (f->archiveName.empty())
89b2f00f24SNico Weber     return std::string(f->getName());
90b2f00f24SNico Weber   return (path::filename(f->archiveName) + "(" + path::filename(f->getName()) +
91b2f00f24SNico Weber           ")")
92b2f00f24SNico Weber       .str();
93b2f00f24SNico Weber }
94b2f00f24SNico Weber 
95544148aeSJez Ng SetVector<InputFile *> macho::inputFiles;
9683e60f5aSNico Weber std::unique_ptr<TarWriter> macho::tar;
9778f6498cSJez Ng int InputFile::idCount = 0;
986acd3003SFangrui Song 
996acd3003SFangrui Song // Open a given file path and return it as a memory-mapped file.
1004af1522aSGreg McGary Optional<MemoryBufferRef> macho::readFile(StringRef path) {
1016acd3003SFangrui Song   // Open a file.
1026acd3003SFangrui Song   auto mbOrErr = MemoryBuffer::getFile(path);
1036acd3003SFangrui Song   if (auto ec = mbOrErr.getError()) {
1046acd3003SFangrui Song     error("cannot open " + path + ": " + ec.message());
1056acd3003SFangrui Song     return None;
1066acd3003SFangrui Song   }
1076acd3003SFangrui Song 
1086acd3003SFangrui Song   std::unique_ptr<MemoryBuffer> &mb = *mbOrErr;
1096acd3003SFangrui Song   MemoryBufferRef mbref = mb->getMemBufferRef();
1106acd3003SFangrui Song   make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take mb ownership
111060efd24SJez Ng 
112060efd24SJez Ng   // If this is a regular non-fat file, return it.
113060efd24SJez Ng   const char *buf = mbref.getBufferStart();
114060efd24SJez Ng   auto *hdr = reinterpret_cast<const MachO::fat_header *>(buf);
1154af1522aSGreg McGary   if (mbref.getBufferSize() < sizeof(uint32_t) ||
1164af1522aSGreg McGary       read32be(&hdr->magic) != MachO::FAT_MAGIC) {
11783e60f5aSNico Weber     if (tar)
11883e60f5aSNico Weber       tar->append(relativeToRoot(path), mbref.getBuffer());
1196acd3003SFangrui Song     return mbref;
12083e60f5aSNico Weber   }
121060efd24SJez Ng 
122918948dbSJez Ng   // Object files and archive files may be fat files, which contains
123918948dbSJez Ng   // multiple real files for different CPU ISAs. Here, we search for a
124918948dbSJez Ng   // file that matches with the current link target and returns it as
125918948dbSJez Ng   // a MemoryBufferRef.
126918948dbSJez Ng   auto *arch = reinterpret_cast<const MachO::fat_arch *>(buf + sizeof(*hdr));
127918948dbSJez Ng 
128918948dbSJez Ng   for (uint32_t i = 0, n = read32be(&hdr->nfat_arch); i < n; ++i) {
129918948dbSJez Ng     if (reinterpret_cast<const char *>(arch + i + 1) >
130918948dbSJez Ng         buf + mbref.getBufferSize()) {
131918948dbSJez Ng       error(path + ": fat_arch struct extends beyond end of file");
132918948dbSJez Ng       return None;
133918948dbSJez Ng     }
134918948dbSJez Ng 
135918948dbSJez Ng     if (read32be(&arch[i].cputype) != target->cpuType ||
136918948dbSJez Ng         read32be(&arch[i].cpusubtype) != target->cpuSubtype)
137918948dbSJez Ng       continue;
138918948dbSJez Ng 
139918948dbSJez Ng     uint32_t offset = read32be(&arch[i].offset);
140918948dbSJez Ng     uint32_t size = read32be(&arch[i].size);
141918948dbSJez Ng     if (offset + size > mbref.getBufferSize())
142918948dbSJez Ng       error(path + ": slice extends beyond end of file");
14383e60f5aSNico Weber     if (tar)
14483e60f5aSNico Weber       tar->append(relativeToRoot(path), mbref.getBuffer());
145918948dbSJez Ng     return MemoryBufferRef(StringRef(buf + offset, size), path.copy(bAlloc));
146918948dbSJez Ng   }
147918948dbSJez Ng 
148918948dbSJez Ng   error("unable to find matching architecture in " + path);
149060efd24SJez Ng   return None;
1506acd3003SFangrui Song }
1516acd3003SFangrui Song 
152cf918c80SJez Ng const load_command *macho::findCommand(const mach_header_64 *hdr,
1536acd3003SFangrui Song                                        uint32_t type) {
1546acd3003SFangrui Song   const uint8_t *p =
1556acd3003SFangrui Song       reinterpret_cast<const uint8_t *>(hdr) + sizeof(mach_header_64);
1566acd3003SFangrui Song 
1576acd3003SFangrui Song   for (uint32_t i = 0, n = hdr->ncmds; i < n; ++i) {
1586acd3003SFangrui Song     auto *cmd = reinterpret_cast<const load_command *>(p);
1596acd3003SFangrui Song     if (cmd->cmd == type)
1606acd3003SFangrui Song       return cmd;
1616acd3003SFangrui Song     p += cmd->cmdsize;
1626acd3003SFangrui Song   }
1636acd3003SFangrui Song   return nullptr;
1646acd3003SFangrui Song }
1656acd3003SFangrui Song 
1667b007ac0SJez Ng void ObjFile::parseSections(ArrayRef<section_64> sections) {
1674eb6f485SJez Ng   subsections.reserve(sections.size());
1686acd3003SFangrui Song   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
1696acd3003SFangrui Song 
1706acd3003SFangrui Song   for (const section_64 &sec : sections) {
1716acd3003SFangrui Song     InputSection *isec = make<InputSection>();
1726acd3003SFangrui Song     isec->file = this;
173cf918c80SJez Ng     isec->name =
174cf918c80SJez Ng         StringRef(sec.sectname, strnlen(sec.sectname, sizeof(sec.sectname)));
175cf918c80SJez Ng     isec->segname =
176cf918c80SJez Ng         StringRef(sec.segname, strnlen(sec.segname, sizeof(sec.segname)));
17774871cdaSJez Ng     isec->data = {isZeroFill(sec.flags) ? nullptr : buf + sec.offset,
17874871cdaSJez Ng                   static_cast<size_t>(sec.size)};
1796acd3003SFangrui Song     if (sec.align >= 32)
1806acd3003SFangrui Song       error("alignment " + std::to_string(sec.align) + " of section " +
1816acd3003SFangrui Song             isec->name + " is too large");
1826acd3003SFangrui Song     else
1836acd3003SFangrui Song       isec->align = 1 << sec.align;
1846acd3003SFangrui Song     isec->flags = sec.flags;
185863f7a74SJez Ng 
186863f7a74SJez Ng     if (!(isDebugSection(isec->flags) &&
187863f7a74SJez Ng           isec->segname == segment_names::dwarf)) {
1884eb6f485SJez Ng       subsections.push_back({{0, isec}});
189863f7a74SJez Ng     } else {
190863f7a74SJez Ng       // Instead of emitting DWARF sections, we emit STABS symbols to the
191863f7a74SJez Ng       // object files that contain them. We filter them out early to avoid
192863f7a74SJez Ng       // parsing their relocations unnecessarily. But we must still push an
193863f7a74SJez Ng       // empty map to ensure the indices line up for the remaining sections.
194863f7a74SJez Ng       subsections.push_back({});
195863f7a74SJez Ng       debugSections.push_back(isec);
196863f7a74SJez Ng     }
1974eb6f485SJez Ng   }
1986acd3003SFangrui Song }
1996acd3003SFangrui Song 
2004eb6f485SJez Ng // Find the subsection corresponding to the greatest section offset that is <=
2014eb6f485SJez Ng // that of the given offset.
2024eb6f485SJez Ng //
2034eb6f485SJez Ng // offset: an offset relative to the start of the original InputSection (before
2044eb6f485SJez Ng // any subsection splitting has occurred). It will be updated to represent the
2054eb6f485SJez Ng // same location as an offset relative to the start of the containing
2064eb6f485SJez Ng // subsection.
2074eb6f485SJez Ng static InputSection *findContainingSubsection(SubsectionMap &map,
2084eb6f485SJez Ng                                               uint32_t *offset) {
2094eb6f485SJez Ng   auto it = std::prev(map.upper_bound(*offset));
2104eb6f485SJez Ng   *offset -= it->first;
2114eb6f485SJez Ng   return it->second;
2126acd3003SFangrui Song }
2136acd3003SFangrui Song 
214e5d780e0SJez Ng static bool validateRelocationInfo(InputFile *file, const section_64 &sec,
2153a9d2f14SGreg McGary                                    relocation_info rel) {
2163a9d2f14SGreg McGary   const TargetInfo::RelocAttrs &relocAttrs = target->getRelocAttrs(rel.r_type);
2173a9d2f14SGreg McGary   bool valid = true;
218e5d780e0SJez Ng   auto message = [relocAttrs, file, sec, rel, &valid](const Twine &diagnostic) {
2193a9d2f14SGreg McGary     valid = false;
2203a9d2f14SGreg McGary     return (relocAttrs.name + " relocation " + diagnostic + " at offset " +
2213a9d2f14SGreg McGary             std::to_string(rel.r_address) + " of " + sec.segname + "," +
222e5d780e0SJez Ng             sec.sectname + " in " + toString(file))
2233a9d2f14SGreg McGary         .str();
2243a9d2f14SGreg McGary   };
2253a9d2f14SGreg McGary 
2263a9d2f14SGreg McGary   if (!relocAttrs.hasAttr(RelocAttrBits::LOCAL) && !rel.r_extern)
2273a9d2f14SGreg McGary     error(message("must be extern"));
2283a9d2f14SGreg McGary   if (relocAttrs.hasAttr(RelocAttrBits::PCREL) != rel.r_pcrel)
2293a9d2f14SGreg McGary     error(message(Twine("must ") + (rel.r_pcrel ? "not " : "") +
2303a9d2f14SGreg McGary                   "be PC-relative"));
2313a9d2f14SGreg McGary   if (isThreadLocalVariables(sec.flags) &&
2325e851733SJez Ng       !relocAttrs.hasAttr(RelocAttrBits::UNSIGNED))
2333a9d2f14SGreg McGary     error(message("not allowed in thread-local section, must be UNSIGNED"));
2343a9d2f14SGreg McGary   if (rel.r_length < 2 || rel.r_length > 3 ||
2353a9d2f14SGreg McGary       !relocAttrs.hasAttr(static_cast<RelocAttrBits>(1 << rel.r_length))) {
23687104faaSGreg McGary     static SmallVector<StringRef, 4> widths{"0", "4", "8", "4 or 8"};
2373a9d2f14SGreg McGary     error(message("has width " + std::to_string(1 << rel.r_length) +
2383a9d2f14SGreg McGary                   " bytes, but must be " +
2393a9d2f14SGreg McGary                   widths[(static_cast<int>(relocAttrs.bits) >> 2) & 3] +
2403a9d2f14SGreg McGary                   " bytes"));
2413a9d2f14SGreg McGary   }
2423a9d2f14SGreg McGary   return valid;
2433a9d2f14SGreg McGary }
2443a9d2f14SGreg McGary 
2457b007ac0SJez Ng void ObjFile::parseRelocations(const section_64 &sec,
2464eb6f485SJez Ng                                SubsectionMap &subsecMap) {
2476acd3003SFangrui Song   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
248d4ec3346SGreg McGary   ArrayRef<relocation_info> relInfos(
249d4ec3346SGreg McGary       reinterpret_cast<const relocation_info *>(buf + sec.reloff), sec.nreloc);
2506acd3003SFangrui Song 
251d4ec3346SGreg McGary   for (size_t i = 0; i < relInfos.size(); i++) {
252d4ec3346SGreg McGary     // Paired relocations serve as Mach-O's method for attaching a
253d4ec3346SGreg McGary     // supplemental datum to a primary relocation record. ELF does not
254d4ec3346SGreg McGary     // need them because the *_RELOC_RELA records contain the extra
255d4ec3346SGreg McGary     // addend field, vs. *_RELOC_REL which omit the addend.
256d4ec3346SGreg McGary     //
257d4ec3346SGreg McGary     // The {X86_64,ARM64}_RELOC_SUBTRACTOR record holds the subtrahend,
258d4ec3346SGreg McGary     // and the paired *_RELOC_UNSIGNED record holds the minuend. The
2593a9d2f14SGreg McGary     // datum for each is a symbolic address. The result is the offset
2603a9d2f14SGreg McGary     // between two addresses.
261d4ec3346SGreg McGary     //
262d4ec3346SGreg McGary     // The ARM64_RELOC_ADDEND record holds the addend, and the paired
263d4ec3346SGreg McGary     // ARM64_RELOC_BRANCH26 or ARM64_RELOC_PAGE21/PAGEOFF12 holds the
264d4ec3346SGreg McGary     // base symbolic address.
265d4ec3346SGreg McGary     //
266d4ec3346SGreg McGary     // Note: X86 does not use *_RELOC_ADDEND because it can embed an
267d4ec3346SGreg McGary     // addend into the instruction stream. On X86, a relocatable address
268d4ec3346SGreg McGary     // field always occupies an entire contiguous sequence of byte(s),
269d4ec3346SGreg McGary     // so there is no need to merge opcode bits with address
270d4ec3346SGreg McGary     // bits. Therefore, it's easy and convenient to store addends in the
271d4ec3346SGreg McGary     // instruction-stream bytes that would otherwise contain zeroes. By
272d4ec3346SGreg McGary     // contrast, RISC ISAs such as ARM64 mix opcode bits with with
273d4ec3346SGreg McGary     // address bits so that bitwise arithmetic is necessary to extract
274d4ec3346SGreg McGary     // and insert them. Storing addends in the instruction stream is
275d4ec3346SGreg McGary     // possible, but inconvenient and more costly at link time.
276d4ec3346SGreg McGary 
2773a9d2f14SGreg McGary     uint64_t pairedAddend = 0;
2783a9d2f14SGreg McGary     relocation_info relInfo = relInfos[i];
2793a9d2f14SGreg McGary     if (target->hasAttr(relInfo.r_type, RelocAttrBits::ADDEND)) {
2803a9d2f14SGreg McGary       pairedAddend = SignExtend64<24>(relInfo.r_symbolnum);
2813a9d2f14SGreg McGary       relInfo = relInfos[++i];
2823a9d2f14SGreg McGary     }
283d4ec3346SGreg McGary     assert(i < relInfos.size());
284e5d780e0SJez Ng     if (!validateRelocationInfo(this, sec, relInfo))
2853a9d2f14SGreg McGary       continue;
286d4ec3346SGreg McGary     if (relInfo.r_address & R_SCATTERED)
2874eb6f485SJez Ng       fatal("TODO: Scattered relocations not supported");
2884eb6f485SJez Ng 
2893a9d2f14SGreg McGary     Reloc p;
2903a9d2f14SGreg McGary     if (target->hasAttr(relInfo.r_type, RelocAttrBits::SUBTRAHEND)) {
2913a9d2f14SGreg McGary       p.type = relInfo.r_type;
2923a9d2f14SGreg McGary       p.referent = symbols[relInfo.r_symbolnum];
2933a9d2f14SGreg McGary       relInfo = relInfos[++i];
29454139013SJez Ng       // SUBTRACTOR relocations should always be followed by an UNSIGNED one
29554139013SJez Ng       // indicating the minuend symbol.
29654139013SJez Ng       assert(target->hasAttr(relInfo.r_type, RelocAttrBits::UNSIGNED) &&
29754139013SJez Ng              relInfo.r_extern);
2983a9d2f14SGreg McGary     }
29982b3da6fSJez Ng     uint64_t embeddedAddend = target->getEmbeddedAddend(mb, sec, relInfo);
30082b3da6fSJez Ng     assert(!(embeddedAddend && pairedAddend));
30182b3da6fSJez Ng     uint64_t totalAddend = pairedAddend + embeddedAddend;
3024eb6f485SJez Ng     Reloc r;
3031a3ef041SGreg McGary     r.type = relInfo.r_type;
3041a3ef041SGreg McGary     r.pcrel = relInfo.r_pcrel;
3051a3ef041SGreg McGary     r.length = relInfo.r_length;
306d4ec3346SGreg McGary     r.offset = relInfo.r_address;
3071a3ef041SGreg McGary     if (relInfo.r_extern) {
3081a3ef041SGreg McGary       r.referent = symbols[relInfo.r_symbolnum];
3093a9d2f14SGreg McGary       r.addend = totalAddend;
310198b0c57SJez Ng     } else {
3111a3ef041SGreg McGary       SubsectionMap &referentSubsecMap = subsections[relInfo.r_symbolnum - 1];
3121a3ef041SGreg McGary       const section_64 &referentSec = sectionHeaders[relInfo.r_symbolnum - 1];
3131a3ef041SGreg McGary       uint32_t referentOffset;
3141a3ef041SGreg McGary       if (relInfo.r_pcrel) {
3154eb6f485SJez Ng         // The implicit addend for pcrel section relocations is the pcrel offset
316fcde378dSJez Ng         // in terms of the addresses in the input file. Here we adjust it so
3171a3ef041SGreg McGary         // that it describes the offset from the start of the referent section.
318f083f652SJez Ng         assert(target->hasAttr(r.type, RelocAttrBits::BYTE4));
3191a3ef041SGreg McGary         referentOffset =
3203a9d2f14SGreg McGary             sec.addr + relInfo.r_address + 4 + totalAddend - referentSec.addr;
321fcde378dSJez Ng       } else {
322fcde378dSJez Ng         // The addend for a non-pcrel relocation is its absolute address.
3233a9d2f14SGreg McGary         referentOffset = totalAddend - referentSec.addr;
324fcde378dSJez Ng       }
3251a3ef041SGreg McGary       r.referent = findContainingSubsection(referentSubsecMap, &referentOffset);
3261a3ef041SGreg McGary       r.addend = referentOffset;
3274eb6f485SJez Ng     }
3284eb6f485SJez Ng 
3296f6d9186SJez Ng     InputSection *subsec = findContainingSubsection(subsecMap, &r.offset);
33054139013SJez Ng     if (p.type != GENERIC_RELOC_INVALID)
3313a9d2f14SGreg McGary       subsec->relocs.push_back(p);
3324eb6f485SJez Ng     subsec->relocs.push_back(r);
3336acd3003SFangrui Song   }
3346acd3003SFangrui Song }
3354eb6f485SJez Ng 
33662a3f0c9SJez Ng static macho::Symbol *createDefined(const structs::nlist_64 &sym,
33762a3f0c9SJez Ng                                     StringRef name, InputSection *isec,
33862a3f0c9SJez Ng                                     uint32_t value) {
33913f439a1SNico Weber   // Symbol scope is determined by sym.n_type & (N_EXT | N_PEXT):
34013f439a1SNico Weber   // N_EXT: Global symbols
34113f439a1SNico Weber   // N_EXT | N_PEXT: Linkage unit (think: dylib) scoped
34213f439a1SNico Weber   // N_PEXT: Does not occur in input files in practice,
34313f439a1SNico Weber   //         a private extern must be external.
34413f439a1SNico Weber   // 0: Translation-unit scoped. These are not in the symbol table.
34513f439a1SNico Weber 
34613f439a1SNico Weber   if (sym.n_type & (N_EXT | N_PEXT)) {
34713f439a1SNico Weber     assert((sym.n_type & N_EXT) && "invalid input");
348163dcd85SJez Ng     return symtab->addDefined(name, isec->file, isec, value,
349163dcd85SJez Ng                               sym.n_desc & N_WEAK_DEF, sym.n_type & N_PEXT);
35013f439a1SNico Weber   }
351163dcd85SJez Ng   return make<Defined>(name, isec->file, isec, value, sym.n_desc & N_WEAK_DEF,
35213f439a1SNico Weber                        /*isExternal=*/false, /*isPrivateExtern=*/false);
35362a3f0c9SJez Ng }
35462a3f0c9SJez Ng 
35562a3f0c9SJez Ng // Absolute symbols are defined symbols that do not have an associated
35662a3f0c9SJez Ng // InputSection. They cannot be weak.
35762a3f0c9SJez Ng static macho::Symbol *createAbsolute(const structs::nlist_64 &sym,
358163dcd85SJez Ng                                      InputFile *file, StringRef name) {
35913f439a1SNico Weber   if (sym.n_type & (N_EXT | N_PEXT)) {
36013f439a1SNico Weber     assert((sym.n_type & N_EXT) && "invalid input");
361163dcd85SJez Ng     return symtab->addDefined(name, file, nullptr, sym.n_value,
362163dcd85SJez Ng                               /*isWeakDef=*/false, sym.n_type & N_PEXT);
36313f439a1SNico Weber   }
364163dcd85SJez Ng   return make<Defined>(name, file, nullptr, sym.n_value, /*isWeakDef=*/false,
36513f439a1SNico Weber                        /*isExternal=*/false, /*isPrivateExtern=*/false);
36662a3f0c9SJez Ng }
36762a3f0c9SJez Ng 
3687b007ac0SJez Ng macho::Symbol *ObjFile::parseNonSectionSymbol(const structs::nlist_64 &sym,
36962a3f0c9SJez Ng                                               StringRef name) {
37062a3f0c9SJez Ng   uint8_t type = sym.n_type & N_TYPE;
37162a3f0c9SJez Ng   switch (type) {
37262a3f0c9SJez Ng   case N_UNDF:
37362a3f0c9SJez Ng     return sym.n_value == 0
374163dcd85SJez Ng                ? symtab->addUndefined(name, this, sym.n_desc & N_WEAK_REF)
37562a3f0c9SJez Ng                : symtab->addCommon(name, this, sym.n_value,
37613f439a1SNico Weber                                    1 << GET_COMM_ALIGN(sym.n_desc),
37713f439a1SNico Weber                                    sym.n_type & N_PEXT);
37862a3f0c9SJez Ng   case N_ABS:
379163dcd85SJez Ng     return createAbsolute(sym, this, name);
38062a3f0c9SJez Ng   case N_PBUD:
38162a3f0c9SJez Ng   case N_INDR:
38262a3f0c9SJez Ng     error("TODO: support symbols of type " + std::to_string(type));
38362a3f0c9SJez Ng     return nullptr;
38462a3f0c9SJez Ng   case N_SECT:
38562a3f0c9SJez Ng     llvm_unreachable(
38662a3f0c9SJez Ng         "N_SECT symbols should not be passed to parseNonSectionSymbol");
38762a3f0c9SJez Ng   default:
38862a3f0c9SJez Ng     llvm_unreachable("invalid symbol type");
38962a3f0c9SJez Ng   }
39062a3f0c9SJez Ng }
39162a3f0c9SJez Ng 
3927b007ac0SJez Ng void ObjFile::parseSymbols(ArrayRef<structs::nlist_64> nList,
3931e1a3f67SJez Ng                            const char *strtab, bool subsectionsViaSymbols) {
3944eb6f485SJez Ng   // resize(), not reserve(), because we are going to create N_ALT_ENTRY symbols
3954eb6f485SJez Ng   // out-of-sequence.
3964eb6f485SJez Ng   symbols.resize(nList.size());
3974eb6f485SJez Ng   std::vector<size_t> altEntrySymIdxs;
3984eb6f485SJez Ng 
3994eb6f485SJez Ng   for (size_t i = 0, n = nList.size(); i < n; ++i) {
4001e1a3f67SJez Ng     const structs::nlist_64 &sym = nList[i];
4014eb6f485SJez Ng     StringRef name = strtab + sym.n_strx;
40262a3f0c9SJez Ng 
40362a3f0c9SJez Ng     if ((sym.n_type & N_TYPE) != N_SECT) {
40462a3f0c9SJez Ng       symbols[i] = parseNonSectionSymbol(sym, name);
4054eb6f485SJez Ng       continue;
4064eb6f485SJez Ng     }
4074eb6f485SJez Ng 
4084eb6f485SJez Ng     const section_64 &sec = sectionHeaders[sym.n_sect - 1];
4094eb6f485SJez Ng     SubsectionMap &subsecMap = subsections[sym.n_sect - 1];
410*3c19b4f3SJez Ng 
411*3c19b4f3SJez Ng     // parseSections() may have chosen not to parse this section.
412*3c19b4f3SJez Ng     if (subsecMap.empty())
413*3c19b4f3SJez Ng       continue;
414*3c19b4f3SJez Ng 
4154eb6f485SJez Ng     uint64_t offset = sym.n_value - sec.addr;
4164eb6f485SJez Ng 
4174eb6f485SJez Ng     // If the input file does not use subsections-via-symbols, all symbols can
4184eb6f485SJez Ng     // use the same subsection. Otherwise, we must split the sections along
4194eb6f485SJez Ng     // symbol boundaries.
4204eb6f485SJez Ng     if (!subsectionsViaSymbols) {
42162a3f0c9SJez Ng       symbols[i] = createDefined(sym, name, subsecMap[0], offset);
4224eb6f485SJez Ng       continue;
4234eb6f485SJez Ng     }
4244eb6f485SJez Ng 
4254eb6f485SJez Ng     // nList entries aren't necessarily arranged in address order. Therefore,
4264eb6f485SJez Ng     // we can't create alt-entry symbols at this point because a later symbol
4274eb6f485SJez Ng     // may split its section, which may affect which subsection the alt-entry
4284eb6f485SJez Ng     // symbol is assigned to. So we need to handle them in a second pass below.
4294eb6f485SJez Ng     if (sym.n_desc & N_ALT_ENTRY) {
4304eb6f485SJez Ng       altEntrySymIdxs.push_back(i);
4314eb6f485SJez Ng       continue;
4324eb6f485SJez Ng     }
4334eb6f485SJez Ng 
4344eb6f485SJez Ng     // Find the subsection corresponding to the greatest section offset that is
4354eb6f485SJez Ng     // <= that of the current symbol. The subsection that we find either needs
4364eb6f485SJez Ng     // to be used directly or split in two.
4374eb6f485SJez Ng     uint32_t firstSize = offset;
4384eb6f485SJez Ng     InputSection *firstIsec = findContainingSubsection(subsecMap, &firstSize);
4394eb6f485SJez Ng 
4404eb6f485SJez Ng     if (firstSize == 0) {
4414eb6f485SJez Ng       // Alias of an existing symbol, or the first symbol in the section. These
4424eb6f485SJez Ng       // are handled by reusing the existing section.
44362a3f0c9SJez Ng       symbols[i] = createDefined(sym, name, firstIsec, 0);
4444eb6f485SJez Ng       continue;
4454eb6f485SJez Ng     }
4464eb6f485SJez Ng 
4474eb6f485SJez Ng     // We saw a symbol definition at a new offset. Split the section into two
4484eb6f485SJez Ng     // subsections. The new symbol uses the second subsection.
4494eb6f485SJez Ng     auto *secondIsec = make<InputSection>(*firstIsec);
4504eb6f485SJez Ng     secondIsec->data = firstIsec->data.slice(firstSize);
4514eb6f485SJez Ng     firstIsec->data = firstIsec->data.slice(0, firstSize);
4524eb6f485SJez Ng     // TODO: ld64 appears to preserve the original alignment as well as each
4534eb6f485SJez Ng     // subsection's offset from the last aligned address. We should consider
4544eb6f485SJez Ng     // emulating that behavior.
4554eb6f485SJez Ng     secondIsec->align = MinAlign(firstIsec->align, offset);
4564eb6f485SJez Ng 
4574eb6f485SJez Ng     subsecMap[offset] = secondIsec;
4584eb6f485SJez Ng     // By construction, the symbol will be at offset zero in the new section.
45962a3f0c9SJez Ng     symbols[i] = createDefined(sym, name, secondIsec, 0);
4604eb6f485SJez Ng   }
4614eb6f485SJez Ng 
4624eb6f485SJez Ng   for (size_t idx : altEntrySymIdxs) {
4631e1a3f67SJez Ng     const structs::nlist_64 &sym = nList[idx];
46462a3f0c9SJez Ng     StringRef name = strtab + sym.n_strx;
4654eb6f485SJez Ng     SubsectionMap &subsecMap = subsections[sym.n_sect - 1];
4664eb6f485SJez Ng     uint32_t off = sym.n_value - sectionHeaders[sym.n_sect - 1].addr;
4674eb6f485SJez Ng     InputSection *subsec = findContainingSubsection(subsecMap, &off);
46862a3f0c9SJez Ng     symbols[idx] = createDefined(sym, name, subsec, off);
4696acd3003SFangrui Song   }
4706acd3003SFangrui Song }
4716acd3003SFangrui Song 
472a379f2c2SGreg McGary OpaqueFile::OpaqueFile(MemoryBufferRef mb, StringRef segName,
473a379f2c2SGreg McGary                        StringRef sectName)
474a379f2c2SGreg McGary     : InputFile(OpaqueKind, mb) {
475a379f2c2SGreg McGary   InputSection *isec = make<InputSection>();
476a379f2c2SGreg McGary   isec->file = this;
477a379f2c2SGreg McGary   isec->name = sectName.take_front(16);
478a379f2c2SGreg McGary   isec->segname = segName.take_front(16);
479a379f2c2SGreg McGary   const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
480a379f2c2SGreg McGary   isec->data = {buf, mb.getBufferSize()};
481a379f2c2SGreg McGary   subsections.push_back({{0, isec}});
482a379f2c2SGreg McGary }
483a379f2c2SGreg McGary 
484b2f00f24SNico Weber ObjFile::ObjFile(MemoryBufferRef mb, uint32_t modTime, StringRef archiveName)
485b768d57bSJez Ng     : InputFile(ObjKind, mb), modTime(modTime) {
486b2f00f24SNico Weber   this->archiveName = std::string(archiveName);
487b2f00f24SNico Weber 
4886acd3003SFangrui Song   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
4896acd3003SFangrui Song   auto *hdr = reinterpret_cast<const mach_header_64 *>(mb.getBufferStart());
4906acd3003SFangrui Song 
4914752cdc9SJez Ng   MachO::Architecture arch =
4924752cdc9SJez Ng       MachO::getArchitectureFromCpuType(hdr->cputype, hdr->cpusubtype);
49355a32812SJez Ng   if (arch != config->target.Arch) {
4944752cdc9SJez Ng     error(toString(this) + " has architecture " + getArchitectureName(arch) +
4954752cdc9SJez Ng           " which is incompatible with target architecture " +
49655a32812SJez Ng           getArchitectureName(config->target.Arch));
4974752cdc9SJez Ng     return;
4984752cdc9SJez Ng   }
499b63919e1SJez Ng   // TODO: check platform too
5004752cdc9SJez Ng 
50116b1f6e3SNico Weber   if (const load_command *cmd = findCommand(hdr, LC_LINKER_OPTION)) {
50216b1f6e3SNico Weber     auto *c = reinterpret_cast<const linker_option_command *>(cmd);
50316b1f6e3SNico Weber     StringRef data{reinterpret_cast<const char *>(c + 1),
50416b1f6e3SNico Weber                    c->cmdsize - sizeof(linker_option_command)};
50516b1f6e3SNico Weber     parseLCLinkerOption(this, c->count, data);
50616b1f6e3SNico Weber   }
50716b1f6e3SNico Weber 
5086acd3003SFangrui Song   if (const load_command *cmd = findCommand(hdr, LC_SEGMENT_64)) {
5096acd3003SFangrui Song     auto *c = reinterpret_cast<const segment_command_64 *>(cmd);
5104eb6f485SJez Ng     sectionHeaders = ArrayRef<section_64>{
5116acd3003SFangrui Song         reinterpret_cast<const section_64 *>(c + 1), c->nsects};
5124eb6f485SJez Ng     parseSections(sectionHeaders);
5136acd3003SFangrui Song   }
5146acd3003SFangrui Song 
515060efd24SJez Ng   // TODO: Error on missing LC_SYMTAB?
5166acd3003SFangrui Song   if (const load_command *cmd = findCommand(hdr, LC_SYMTAB)) {
5176acd3003SFangrui Song     auto *c = reinterpret_cast<const symtab_command *>(cmd);
5181e1a3f67SJez Ng     ArrayRef<structs::nlist_64> nList(
5191e1a3f67SJez Ng         reinterpret_cast<const structs::nlist_64 *>(buf + c->symoff), c->nsyms);
5204eb6f485SJez Ng     const char *strtab = reinterpret_cast<const char *>(buf) + c->stroff;
5214eb6f485SJez Ng     bool subsectionsViaSymbols = hdr->flags & MH_SUBSECTIONS_VIA_SYMBOLS;
5224eb6f485SJez Ng     parseSymbols(nList, strtab, subsectionsViaSymbols);
5236acd3003SFangrui Song   }
5246acd3003SFangrui Song 
5256acd3003SFangrui Song   // The relocations may refer to the symbols, so we parse them after we have
5264eb6f485SJez Ng   // parsed all the symbols.
5274eb6f485SJez Ng   for (size_t i = 0, n = subsections.size(); i < n; ++i)
528863f7a74SJez Ng     if (!subsections[i].empty())
5294eb6f485SJez Ng       parseRelocations(sectionHeaders[i], subsections[i]);
5303fcb0eebSJez Ng 
5313fcb0eebSJez Ng   parseDebugInfo();
5323fcb0eebSJez Ng }
5333fcb0eebSJez Ng 
5343fcb0eebSJez Ng void ObjFile::parseDebugInfo() {
5353fcb0eebSJez Ng   std::unique_ptr<DwarfObject> dObj = DwarfObject::create(this);
5363fcb0eebSJez Ng   if (!dObj)
5373fcb0eebSJez Ng     return;
5383fcb0eebSJez Ng 
5393fcb0eebSJez Ng   auto *ctx = make<DWARFContext>(
5403fcb0eebSJez Ng       std::move(dObj), "",
541b2f00f24SNico Weber       [&](Error err) {
542b2f00f24SNico Weber         warn(toString(this) + ": " + toString(std::move(err)));
543b2f00f24SNico Weber       },
5443fcb0eebSJez Ng       [&](Error warning) {
545b2f00f24SNico Weber         warn(toString(this) + ": " + toString(std::move(warning)));
5463fcb0eebSJez Ng       });
5473fcb0eebSJez Ng 
5483fcb0eebSJez Ng   // TODO: Since object files can contain a lot of DWARF info, we should verify
5493fcb0eebSJez Ng   // that we are parsing just the info we need
5503fcb0eebSJez Ng   const DWARFContext::compile_unit_range &units = ctx->compile_units();
551fc011b5eSJez Ng   // FIXME: There can be more than one compile unit per object file. See
552fc011b5eSJez Ng   // PR48637.
5533fcb0eebSJez Ng   auto it = units.begin();
5543fcb0eebSJez Ng   compileUnit = it->get();
5556acd3003SFangrui Song }
5566acd3003SFangrui Song 
5577394460dSJez Ng // The path can point to either a dylib or a .tbd file.
5587394460dSJez Ng static Optional<DylibFile *> loadDylib(StringRef path, DylibFile *umbrella) {
5594af1522aSGreg McGary   Optional<MemoryBufferRef> mbref = readFile(path);
5607394460dSJez Ng   if (!mbref) {
5617394460dSJez Ng     error("could not read dylib file at " + path);
5627394460dSJez Ng     return {};
5637394460dSJez Ng   }
56476c36c11SJez Ng   return loadDylib(*mbref, umbrella);
5657394460dSJez Ng }
5667394460dSJez Ng 
5677394460dSJez Ng // TBD files are parsed into a series of TAPI documents (InterfaceFiles), with
5687394460dSJez Ng // the first document storing child pointers to the rest of them. When we are
5699a2e2de1SVy Nguyen // processing a given TBD file, we store that top-level document in
5709a2e2de1SVy Nguyen // currentTopLevelTapi. When processing re-exports, we search its children for
5719a2e2de1SVy Nguyen // potentially matching documents in the same TBD file. Note that the children
5729a2e2de1SVy Nguyen // themselves don't point to further documents, i.e. this is a two-level tree.
5737394460dSJez Ng //
5747394460dSJez Ng // Re-exports can either refer to on-disk files, or to documents within .tbd
5757394460dSJez Ng // files.
5769a2e2de1SVy Nguyen static Optional<DylibFile *>
5779a2e2de1SVy Nguyen findDylib(StringRef path, DylibFile *umbrella,
5789a2e2de1SVy Nguyen           const InterfaceFile *currentTopLevelTapi) {
5797394460dSJez Ng   if (path::is_absolute(path, path::Style::posix))
5807394460dSJez Ng     for (StringRef root : config->systemLibraryRoots)
5817394460dSJez Ng       if (Optional<std::string> dylibPath =
5827394460dSJez Ng               resolveDylibPath((root + path).str()))
5837394460dSJez Ng         return loadDylib(*dylibPath, umbrella);
5847394460dSJez Ng 
5858174f33dSNico Weber   // TODO: Expand @loader_path, @executable_path, @rpath etc, handle -dylib_path
5867394460dSJez Ng 
5879c702814SJez Ng   if (currentTopLevelTapi) {
5887394460dSJez Ng     for (InterfaceFile &child :
5897394460dSJez Ng          make_pointee_range(currentTopLevelTapi->documents())) {
5908601be80SJez Ng       assert(child.documents().empty());
5917394460dSJez Ng       if (path == child.getInstallName())
5927394460dSJez Ng         return make<DylibFile>(child, umbrella);
5937394460dSJez Ng     }
5947394460dSJez Ng   }
5957394460dSJez Ng 
5967394460dSJez Ng   if (Optional<std::string> dylibPath = resolveDylibPath(path))
5977394460dSJez Ng     return loadDylib(*dylibPath, umbrella);
5987394460dSJez Ng 
5997394460dSJez Ng   return {};
6007394460dSJez Ng }
6017394460dSJez Ng 
6026a348f61SJez Ng // If a re-exported dylib is public (lives in /usr/lib or
6036a348f61SJez Ng // /System/Library/Frameworks), then it is considered implicitly linked: we
6046a348f61SJez Ng // should bind to its symbols directly instead of via the re-exporting umbrella
6056a348f61SJez Ng // library.
6066a348f61SJez Ng static bool isImplicitlyLinked(StringRef path) {
6076a348f61SJez Ng   if (!config->implicitDylibs)
6086a348f61SJez Ng     return false;
6096a348f61SJez Ng 
6103aa8e071SJez Ng   if (path::parent_path(path) == "/usr/lib")
6113aa8e071SJez Ng     return true;
6123aa8e071SJez Ng 
6133aa8e071SJez Ng   // Match /System/Library/Frameworks/$FOO.framework/**/$FOO
6143aa8e071SJez Ng   if (path.consume_front("/System/Library/Frameworks/")) {
6153aa8e071SJez Ng     StringRef frameworkName = path.take_until([](char c) { return c == '.'; });
6163aa8e071SJez Ng     return path::filename(path) == frameworkName;
6173aa8e071SJez Ng   }
6183aa8e071SJez Ng 
6193aa8e071SJez Ng   return false;
6206a348f61SJez Ng }
6216a348f61SJez Ng 
6229a2e2de1SVy Nguyen void loadReexport(StringRef path, DylibFile *umbrella,
6239a2e2de1SVy Nguyen                   const InterfaceFile *currentTopLevelTapi) {
6249a2e2de1SVy Nguyen   Optional<DylibFile *> reexport =
6259a2e2de1SVy Nguyen       findDylib(path, umbrella, currentTopLevelTapi);
6268174f33dSNico Weber   if (!reexport)
6278174f33dSNico Weber     error("unable to locate re-export with install name " + path);
6288174f33dSNico Weber   else if (isImplicitlyLinked(path))
629544148aeSJez Ng     inputFiles.insert(*reexport);
6306a348f61SJez Ng }
6316a348f61SJez Ng 
6325a856f5bSVy Nguyen DylibFile::DylibFile(MemoryBufferRef mb, DylibFile *umbrella,
6335a856f5bSVy Nguyen                      bool isBundleLoader)
6345a856f5bSVy Nguyen     : InputFile(DylibKind, mb), refState(RefState::Unreferenced),
6355a856f5bSVy Nguyen       isBundleLoader(isBundleLoader) {
6365a856f5bSVy Nguyen   assert(!isBundleLoader || !umbrella);
63787b6fd3eSJez Ng   if (umbrella == nullptr)
63887b6fd3eSJez Ng     umbrella = this;
63987b6fd3eSJez Ng 
640060efd24SJez Ng   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
641060efd24SJez Ng   auto *hdr = reinterpret_cast<const mach_header_64 *>(mb.getBufferStart());
642060efd24SJez Ng 
643060efd24SJez Ng   // Initialize dylibName.
644060efd24SJez Ng   if (const load_command *cmd = findCommand(hdr, LC_ID_DYLIB)) {
645060efd24SJez Ng     auto *c = reinterpret_cast<const dylib_command *>(cmd);
646ec88746aSNico Weber     currentVersion = read32le(&c->dylib.current_version);
647ec88746aSNico Weber     compatibilityVersion = read32le(&c->dylib.compatibility_version);
648060efd24SJez Ng     dylibName = reinterpret_cast<const char *>(cmd) + read32le(&c->dylib.name);
6495a856f5bSVy Nguyen   } else if (!isBundleLoader) {
6505a856f5bSVy Nguyen     // macho_executable and macho_bundle don't have LC_ID_DYLIB,
6515a856f5bSVy Nguyen     // so it's OK.
652b2f00f24SNico Weber     error("dylib " + toString(this) + " missing LC_ID_DYLIB load command");
653060efd24SJez Ng     return;
654060efd24SJez Ng   }
655060efd24SJez Ng 
656060efd24SJez Ng   // Initialize symbols.
6576a348f61SJez Ng   DylibFile *exportingFile = isImplicitlyLinked(dylibName) ? this : umbrella;
6587bbdbacdSJez Ng   if (const load_command *cmd = findCommand(hdr, LC_DYLD_INFO_ONLY)) {
6597bbdbacdSJez Ng     auto *c = reinterpret_cast<const dyld_info_command *>(cmd);
6607bbdbacdSJez Ng     parseTrie(buf + c->export_off, c->export_size,
6617bbdbacdSJez Ng               [&](const Twine &name, uint64_t flags) {
66231d58858SJez Ng                 bool isWeakDef = flags & EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION;
6633c9100fbSJez Ng                 bool isTlv = flags & EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL;
6646a348f61SJez Ng                 symbols.push_back(symtab->addDylib(
6656a348f61SJez Ng                     saver.save(name), exportingFile, isWeakDef, isTlv));
6667bbdbacdSJez Ng               });
6677bbdbacdSJez Ng   } else {
668b2f00f24SNico Weber     error("LC_DYLD_INFO_ONLY not found in " + toString(this));
66987b6fd3eSJez Ng     return;
67087b6fd3eSJez Ng   }
67187b6fd3eSJez Ng 
67287b6fd3eSJez Ng   const uint8_t *p =
67387b6fd3eSJez Ng       reinterpret_cast<const uint8_t *>(hdr) + sizeof(mach_header_64);
67487b6fd3eSJez Ng   for (uint32_t i = 0, n = hdr->ncmds; i < n; ++i) {
67587b6fd3eSJez Ng     auto *cmd = reinterpret_cast<const load_command *>(p);
67687b6fd3eSJez Ng     p += cmd->cmdsize;
67787b6fd3eSJez Ng 
6788174f33dSNico Weber     if (!(hdr->flags & MH_NO_REEXPORTED_DYLIBS) &&
6798174f33dSNico Weber         cmd->cmd == LC_REEXPORT_DYLIB) {
6808174f33dSNico Weber       const auto *c = reinterpret_cast<const dylib_command *>(cmd);
68187b6fd3eSJez Ng       StringRef reexportPath =
68287b6fd3eSJez Ng           reinterpret_cast<const char *>(c) + read32le(&c->dylib.name);
6835d9aafc0SJez Ng       loadReexport(reexportPath, exportingFile, nullptr);
684060efd24SJez Ng     }
6858174f33dSNico Weber 
6868174f33dSNico Weber     // FIXME: What about LC_LOAD_UPWARD_DYLIB, LC_LAZY_LOAD_DYLIB,
6878174f33dSNico Weber     // LC_LOAD_WEAK_DYLIB, LC_REEXPORT_DYLIB (..are reexports from dylibs with
6888174f33dSNico Weber     // MH_NO_REEXPORTED_DYLIBS loaded for -flat_namespace)?
6898174f33dSNico Weber     if (config->namespaceKind == NamespaceKind::flat &&
6908174f33dSNico Weber         cmd->cmd == LC_LOAD_DYLIB) {
6918174f33dSNico Weber       const auto *c = reinterpret_cast<const dylib_command *>(cmd);
6928174f33dSNico Weber       StringRef dylibPath =
6938174f33dSNico Weber           reinterpret_cast<const char *>(c) + read32le(&c->dylib.name);
6949a2e2de1SVy Nguyen       Optional<DylibFile *> dylib = findDylib(dylibPath, umbrella, nullptr);
6958174f33dSNico Weber       if (!dylib)
6968174f33dSNico Weber         error(Twine("unable to locate library '") + dylibPath +
6978174f33dSNico Weber               "' loaded from '" + toString(this) + "' for -flat_namespace");
6988174f33dSNico Weber     }
6998174f33dSNico Weber   }
700060efd24SJez Ng }
701060efd24SJez Ng 
7025a856f5bSVy Nguyen DylibFile::DylibFile(const InterfaceFile &interface, DylibFile *umbrella,
7035a856f5bSVy Nguyen                      bool isBundleLoader)
7045a856f5bSVy Nguyen     : InputFile(DylibKind, interface), refState(RefState::Unreferenced),
7055a856f5bSVy Nguyen       isBundleLoader(isBundleLoader) {
7065a856f5bSVy Nguyen   // FIXME: Add test for the missing TBD code path.
7075a856f5bSVy Nguyen 
7086fe27b5fSSaleem Abdulrasool   if (umbrella == nullptr)
7096fe27b5fSSaleem Abdulrasool     umbrella = this;
7106fe27b5fSSaleem Abdulrasool 
7110d4dadc6SJez Ng   dylibName = saver.save(interface.getInstallName());
7120d4dadc6SJez Ng   compatibilityVersion = interface.getCompatibilityVersion().rawValue();
7130d4dadc6SJez Ng   currentVersion = interface.getCurrentVersion().rawValue();
7140d4dadc6SJez Ng 
71555a32812SJez Ng   if (!is_contained(interface.targets(), config->target)) {
7164752cdc9SJez Ng     error(toString(this) + " is incompatible with " +
71755a32812SJez Ng           std::string(config->target));
7184752cdc9SJez Ng     return;
7194752cdc9SJez Ng   }
7204752cdc9SJez Ng 
7216a348f61SJez Ng   DylibFile *exportingFile = isImplicitlyLinked(dylibName) ? this : umbrella;
722a499898eSJez Ng   auto addSymbol = [&](const Twine &name) -> void {
7236a348f61SJez Ng     symbols.push_back(symtab->addDylib(saver.save(name), exportingFile,
724a499898eSJez Ng                                        /*isWeakDef=*/false,
725a499898eSJez Ng                                        /*isTlv=*/false));
726a499898eSJez Ng   };
7276fe27b5fSSaleem Abdulrasool   // TODO(compnerd) filter out symbols based on the target platform
7283c9100fbSJez Ng   // TODO: handle weak defs, thread locals
7297e6d6754SJez Ng   for (const auto symbol : interface.symbols()) {
73055a32812SJez Ng     if (!symbol->getArchitectures().has(config->target.Arch))
731a499898eSJez Ng       continue;
732a499898eSJez Ng 
733a499898eSJez Ng     switch (symbol->getKind()) {
734a499898eSJez Ng     case SymbolKind::GlobalSymbol:
735a499898eSJez Ng       addSymbol(symbol->getName());
736a499898eSJez Ng       break;
737a499898eSJez Ng     case SymbolKind::ObjectiveCClass:
738a499898eSJez Ng       // XXX ld64 only creates these symbols when -ObjC is passed in. We may
739a499898eSJez Ng       // want to emulate that.
740cf918c80SJez Ng       addSymbol(objc::klass + symbol->getName());
741cf918c80SJez Ng       addSymbol(objc::metaclass + symbol->getName());
742a499898eSJez Ng       break;
743a499898eSJez Ng     case SymbolKind::ObjectiveCClassEHType:
744cf918c80SJez Ng       addSymbol(objc::ehtype + symbol->getName());
745a499898eSJez Ng       break;
746a499898eSJez Ng     case SymbolKind::ObjectiveCInstanceVariable:
747cf918c80SJez Ng       addSymbol(objc::ivar + symbol->getName());
748a499898eSJez Ng       break;
749a499898eSJez Ng     }
750a499898eSJez Ng   }
7517394460dSJez Ng 
7529a2e2de1SVy Nguyen   const InterfaceFile *topLevel =
7539a2e2de1SVy Nguyen       interface.getParent() == nullptr ? &interface : interface.getParent();
7547394460dSJez Ng 
75555a32812SJez Ng   for (InterfaceFileRef intfRef : interface.reexportedLibraries()) {
75655a32812SJez Ng     auto targets = intfRef.targets();
75755a32812SJez Ng     if (is_contained(targets, config->target))
7585d9aafc0SJez Ng       loadReexport(intfRef.getInstallName(), exportingFile, topLevel);
7596fe27b5fSSaleem Abdulrasool   }
76055a32812SJez Ng }
7616fe27b5fSSaleem Abdulrasool 
762e98b441aSJez Ng ArchiveFile::ArchiveFile(std::unique_ptr<object::Archive> &&f)
7632b920ae7SKellie Medlin     : InputFile(ArchiveKind, f->getMemoryBufferRef()), file(std::move(f)) {
7642b920ae7SKellie Medlin   for (const object::Archive::Symbol &sym : file->symbols())
7652b920ae7SKellie Medlin     symtab->addLazy(sym.getName(), this, sym);
7662b920ae7SKellie Medlin }
7672b920ae7SKellie Medlin 
7682b920ae7SKellie Medlin void ArchiveFile::fetch(const object::Archive::Symbol &sym) {
7692b920ae7SKellie Medlin   object::Archive::Child c =
7702b920ae7SKellie Medlin       CHECK(sym.getMember(), toString(this) +
7712b920ae7SKellie Medlin                                  ": could not get the member for symbol " +
77207ab597bSNico Weber                                  toMachOString(sym));
7732b920ae7SKellie Medlin 
7742b920ae7SKellie Medlin   if (!seen.insert(c.getChildOffset()).second)
7752b920ae7SKellie Medlin     return;
7762b920ae7SKellie Medlin 
7772b920ae7SKellie Medlin   MemoryBufferRef mb =
7782b920ae7SKellie Medlin       CHECK(c.getMemoryBufferRef(),
7792b920ae7SKellie Medlin             toString(this) +
7802b920ae7SKellie Medlin                 ": could not get the buffer for the member defining symbol " +
78107ab597bSNico Weber                 toMachOString(sym));
782b768d57bSJez Ng 
783ca634393SNico Weber   if (tar && c.getParent()->isThin())
784ca634393SNico Weber     tar->append(relativeToRoot(CHECK(c.getFullName(), this)), mb.getBuffer());
785ca634393SNico Weber 
786b768d57bSJez Ng   uint32_t modTime = toTimeT(
787b768d57bSJez Ng       CHECK(c.getLastModified(), toString(this) +
788b768d57bSJez Ng                                      ": could not get the modification time "
789b768d57bSJez Ng                                      "for the member defining symbol " +
79007ab597bSNico Weber                                      toMachOString(sym)));
791b768d57bSJez Ng 
7923422f3ccSNico Weber   // `sym` is owned by a LazySym, which will be replace<>() by make<ObjFile>
7933422f3ccSNico Weber   // and become invalid after that call. Copy it to the stack so we can refer
7943422f3ccSNico Weber   // to it later.
7953422f3ccSNico Weber   const object::Archive::Symbol sym_copy = sym;
7963422f3ccSNico Weber 
797f843bb82SJez Ng   if (Optional<InputFile *> file =
798f843bb82SJez Ng           loadArchiveMember(mb, modTime, getName(), /*objCOnly=*/false)) {
799f843bb82SJez Ng     inputFiles.insert(*file);
8003422f3ccSNico Weber     // ld64 doesn't demangle sym here even with -demangle. Match that, so
8013422f3ccSNico Weber     // intentionally no call to toMachOString() here.
802f843bb82SJez Ng     printArchiveMemberLoad(sym_copy.getName(), *file);
803f843bb82SJez Ng   }
8042b920ae7SKellie Medlin }
8052b920ae7SKellie Medlin 
80684579fc2SJez Ng static macho::Symbol *createBitcodeSymbol(const lto::InputFile::Symbol &objSym,
80784579fc2SJez Ng                                           BitcodeFile &file) {
80884579fc2SJez Ng   StringRef name = saver.save(objSym.getName());
80984579fc2SJez Ng 
81084579fc2SJez Ng   // TODO: support weak references
81184579fc2SJez Ng   if (objSym.isUndefined())
81284579fc2SJez Ng     return symtab->addUndefined(name, &file, /*isWeakRef=*/false);
81384579fc2SJez Ng 
81484579fc2SJez Ng   assert(!objSym.isCommon() && "TODO: support common symbols in LTO");
81584579fc2SJez Ng 
81684579fc2SJez Ng   // TODO: Write a test demonstrating why computing isPrivateExtern before
81784579fc2SJez Ng   // LTO compilation is important.
81884579fc2SJez Ng   bool isPrivateExtern = false;
81984579fc2SJez Ng   switch (objSym.getVisibility()) {
82084579fc2SJez Ng   case GlobalValue::HiddenVisibility:
82184579fc2SJez Ng     isPrivateExtern = true;
82284579fc2SJez Ng     break;
82384579fc2SJez Ng   case GlobalValue::ProtectedVisibility:
82484579fc2SJez Ng     error(name + " has protected visibility, which is not supported by Mach-O");
82584579fc2SJez Ng     break;
82684579fc2SJez Ng   case GlobalValue::DefaultVisibility:
82784579fc2SJez Ng     break;
82884579fc2SJez Ng   }
82984579fc2SJez Ng 
83084579fc2SJez Ng   return symtab->addDefined(name, &file, /*isec=*/nullptr, /*value=*/0,
83184579fc2SJez Ng                             objSym.isWeak(), isPrivateExtern);
83284579fc2SJez Ng }
83384579fc2SJez Ng 
83421f83113SJez Ng BitcodeFile::BitcodeFile(MemoryBufferRef mbref)
83521f83113SJez Ng     : InputFile(BitcodeKind, mbref) {
83621f83113SJez Ng   obj = check(lto::InputFile::create(mbref));
83784579fc2SJez Ng 
83884579fc2SJez Ng   // Convert LTO Symbols to LLD Symbols in order to perform resolution. The
83984579fc2SJez Ng   // "winning" symbol will then be marked as Prevailing at LTO compilation
84084579fc2SJez Ng   // time.
84184579fc2SJez Ng   for (const lto::InputFile::Symbol &objSym : obj->symbols())
84284579fc2SJez Ng     symbols.push_back(createBitcodeSymbol(objSym, *this));
84321f83113SJez Ng }
844