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>";
82b2f00f24SNico Weber   if (f->archiveName.empty())
83b2f00f24SNico Weber     return std::string(f->getName());
84b2f00f24SNico Weber   return (path::filename(f->archiveName) + "(" + path::filename(f->getName()) +
85b2f00f24SNico Weber           ")")
86b2f00f24SNico Weber       .str();
87b2f00f24SNico Weber }
88b2f00f24SNico Weber 
89544148aeSJez Ng SetVector<InputFile *> macho::inputFiles;
9083e60f5aSNico Weber std::unique_ptr<TarWriter> macho::tar;
9178f6498cSJez Ng int InputFile::idCount = 0;
926acd3003SFangrui Song 
936acd3003SFangrui Song // Open a given file path and return it as a memory-mapped file.
946acd3003SFangrui Song Optional<MemoryBufferRef> macho::readFile(StringRef path) {
956acd3003SFangrui Song   // Open a file.
966acd3003SFangrui Song   auto mbOrErr = MemoryBuffer::getFile(path);
976acd3003SFangrui Song   if (auto ec = mbOrErr.getError()) {
986acd3003SFangrui Song     error("cannot open " + path + ": " + ec.message());
996acd3003SFangrui Song     return None;
1006acd3003SFangrui Song   }
1016acd3003SFangrui Song 
1026acd3003SFangrui Song   std::unique_ptr<MemoryBuffer> &mb = *mbOrErr;
1036acd3003SFangrui Song   MemoryBufferRef mbref = mb->getMemBufferRef();
1046acd3003SFangrui Song   make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take mb ownership
105060efd24SJez Ng 
106060efd24SJez Ng   // If this is a regular non-fat file, return it.
107060efd24SJez Ng   const char *buf = mbref.getBufferStart();
108060efd24SJez Ng   auto *hdr = reinterpret_cast<const MachO::fat_header *>(buf);
10983e60f5aSNico Weber   if (read32be(&hdr->magic) != MachO::FAT_MAGIC) {
11083e60f5aSNico Weber     if (tar)
11183e60f5aSNico Weber       tar->append(relativeToRoot(path), mbref.getBuffer());
1126acd3003SFangrui Song     return mbref;
11383e60f5aSNico Weber   }
114060efd24SJez Ng 
115918948dbSJez Ng   // Object files and archive files may be fat files, which contains
116918948dbSJez Ng   // multiple real files for different CPU ISAs. Here, we search for a
117918948dbSJez Ng   // file that matches with the current link target and returns it as
118918948dbSJez Ng   // a MemoryBufferRef.
119918948dbSJez Ng   auto *arch = reinterpret_cast<const MachO::fat_arch *>(buf + sizeof(*hdr));
120918948dbSJez Ng 
121918948dbSJez Ng   for (uint32_t i = 0, n = read32be(&hdr->nfat_arch); i < n; ++i) {
122918948dbSJez Ng     if (reinterpret_cast<const char *>(arch + i + 1) >
123918948dbSJez Ng         buf + mbref.getBufferSize()) {
124918948dbSJez Ng       error(path + ": fat_arch struct extends beyond end of file");
125918948dbSJez Ng       return None;
126918948dbSJez Ng     }
127918948dbSJez Ng 
128918948dbSJez Ng     if (read32be(&arch[i].cputype) != target->cpuType ||
129918948dbSJez Ng         read32be(&arch[i].cpusubtype) != target->cpuSubtype)
130918948dbSJez Ng       continue;
131918948dbSJez Ng 
132918948dbSJez Ng     uint32_t offset = read32be(&arch[i].offset);
133918948dbSJez Ng     uint32_t size = read32be(&arch[i].size);
134918948dbSJez Ng     if (offset + size > mbref.getBufferSize())
135918948dbSJez Ng       error(path + ": slice extends beyond end of file");
13683e60f5aSNico Weber     if (tar)
13783e60f5aSNico Weber       tar->append(relativeToRoot(path), mbref.getBuffer());
138918948dbSJez Ng     return MemoryBufferRef(StringRef(buf + offset, size), path.copy(bAlloc));
139918948dbSJez Ng   }
140918948dbSJez Ng 
141918948dbSJez Ng   error("unable to find matching architecture in " + path);
142060efd24SJez Ng   return None;
1436acd3003SFangrui Song }
1446acd3003SFangrui Song 
145cf918c80SJez Ng const load_command *macho::findCommand(const mach_header_64 *hdr,
1466acd3003SFangrui Song                                        uint32_t type) {
1476acd3003SFangrui Song   const uint8_t *p =
1486acd3003SFangrui Song       reinterpret_cast<const uint8_t *>(hdr) + sizeof(mach_header_64);
1496acd3003SFangrui Song 
1506acd3003SFangrui Song   for (uint32_t i = 0, n = hdr->ncmds; i < n; ++i) {
1516acd3003SFangrui Song     auto *cmd = reinterpret_cast<const load_command *>(p);
1526acd3003SFangrui Song     if (cmd->cmd == type)
1536acd3003SFangrui Song       return cmd;
1546acd3003SFangrui Song     p += cmd->cmdsize;
1556acd3003SFangrui Song   }
1566acd3003SFangrui Song   return nullptr;
1576acd3003SFangrui Song }
1586acd3003SFangrui Song 
1597b007ac0SJez Ng void ObjFile::parseSections(ArrayRef<section_64> sections) {
1604eb6f485SJez Ng   subsections.reserve(sections.size());
1616acd3003SFangrui Song   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
1626acd3003SFangrui Song 
1636acd3003SFangrui Song   for (const section_64 &sec : sections) {
1646acd3003SFangrui Song     InputSection *isec = make<InputSection>();
1656acd3003SFangrui Song     isec->file = this;
166cf918c80SJez Ng     isec->name =
167cf918c80SJez Ng         StringRef(sec.sectname, strnlen(sec.sectname, sizeof(sec.sectname)));
168cf918c80SJez Ng     isec->segname =
169cf918c80SJez Ng         StringRef(sec.segname, strnlen(sec.segname, sizeof(sec.segname)));
17074871cdaSJez Ng     isec->data = {isZeroFill(sec.flags) ? nullptr : buf + sec.offset,
17174871cdaSJez Ng                   static_cast<size_t>(sec.size)};
1726acd3003SFangrui Song     if (sec.align >= 32)
1736acd3003SFangrui Song       error("alignment " + std::to_string(sec.align) + " of section " +
1746acd3003SFangrui Song             isec->name + " is too large");
1756acd3003SFangrui Song     else
1766acd3003SFangrui Song       isec->align = 1 << sec.align;
1776acd3003SFangrui Song     isec->flags = sec.flags;
178863f7a74SJez Ng 
179863f7a74SJez Ng     if (!(isDebugSection(isec->flags) &&
180863f7a74SJez Ng           isec->segname == segment_names::dwarf)) {
1814eb6f485SJez Ng       subsections.push_back({{0, isec}});
182863f7a74SJez Ng     } else {
183863f7a74SJez Ng       // Instead of emitting DWARF sections, we emit STABS symbols to the
184863f7a74SJez Ng       // object files that contain them. We filter them out early to avoid
185863f7a74SJez Ng       // parsing their relocations unnecessarily. But we must still push an
186863f7a74SJez Ng       // empty map to ensure the indices line up for the remaining sections.
187863f7a74SJez Ng       subsections.push_back({});
188863f7a74SJez Ng       debugSections.push_back(isec);
189863f7a74SJez Ng     }
1904eb6f485SJez Ng   }
1916acd3003SFangrui Song }
1926acd3003SFangrui Song 
1934eb6f485SJez Ng // Find the subsection corresponding to the greatest section offset that is <=
1944eb6f485SJez Ng // that of the given offset.
1954eb6f485SJez Ng //
1964eb6f485SJez Ng // offset: an offset relative to the start of the original InputSection (before
1974eb6f485SJez Ng // any subsection splitting has occurred). It will be updated to represent the
1984eb6f485SJez Ng // same location as an offset relative to the start of the containing
1994eb6f485SJez Ng // subsection.
2004eb6f485SJez Ng static InputSection *findContainingSubsection(SubsectionMap &map,
2014eb6f485SJez Ng                                               uint32_t *offset) {
2024eb6f485SJez Ng   auto it = std::prev(map.upper_bound(*offset));
2034eb6f485SJez Ng   *offset -= it->first;
2044eb6f485SJez Ng   return it->second;
2056acd3003SFangrui Song }
2066acd3003SFangrui Song 
207e5d780e0SJez Ng static bool validateRelocationInfo(InputFile *file, const section_64 &sec,
2083a9d2f14SGreg McGary                                    relocation_info rel) {
2093a9d2f14SGreg McGary   const TargetInfo::RelocAttrs &relocAttrs = target->getRelocAttrs(rel.r_type);
2103a9d2f14SGreg McGary   bool valid = true;
211e5d780e0SJez Ng   auto message = [relocAttrs, file, sec, rel, &valid](const Twine &diagnostic) {
2123a9d2f14SGreg McGary     valid = false;
2133a9d2f14SGreg McGary     return (relocAttrs.name + " relocation " + diagnostic + " at offset " +
2143a9d2f14SGreg McGary             std::to_string(rel.r_address) + " of " + sec.segname + "," +
215e5d780e0SJez Ng             sec.sectname + " in " + toString(file))
2163a9d2f14SGreg McGary         .str();
2173a9d2f14SGreg McGary   };
2183a9d2f14SGreg McGary 
2193a9d2f14SGreg McGary   if (!relocAttrs.hasAttr(RelocAttrBits::LOCAL) && !rel.r_extern)
2203a9d2f14SGreg McGary     error(message("must be extern"));
2213a9d2f14SGreg McGary   if (relocAttrs.hasAttr(RelocAttrBits::PCREL) != rel.r_pcrel)
2223a9d2f14SGreg McGary     error(message(Twine("must ") + (rel.r_pcrel ? "not " : "") +
2233a9d2f14SGreg McGary                   "be PC-relative"));
2243a9d2f14SGreg McGary   if (isThreadLocalVariables(sec.flags) &&
2255e851733SJez Ng       !relocAttrs.hasAttr(RelocAttrBits::UNSIGNED))
2263a9d2f14SGreg McGary     error(message("not allowed in thread-local section, must be UNSIGNED"));
2273a9d2f14SGreg McGary   if (rel.r_length < 2 || rel.r_length > 3 ||
2283a9d2f14SGreg McGary       !relocAttrs.hasAttr(static_cast<RelocAttrBits>(1 << rel.r_length))) {
22987104faaSGreg McGary     static SmallVector<StringRef, 4> widths{"0", "4", "8", "4 or 8"};
2303a9d2f14SGreg McGary     error(message("has width " + std::to_string(1 << rel.r_length) +
2313a9d2f14SGreg McGary                   " bytes, but must be " +
2323a9d2f14SGreg McGary                   widths[(static_cast<int>(relocAttrs.bits) >> 2) & 3] +
2333a9d2f14SGreg McGary                   " bytes"));
2343a9d2f14SGreg McGary   }
2353a9d2f14SGreg McGary   return valid;
2363a9d2f14SGreg McGary }
2373a9d2f14SGreg McGary 
2387b007ac0SJez Ng void ObjFile::parseRelocations(const section_64 &sec,
2394eb6f485SJez Ng                                SubsectionMap &subsecMap) {
2406acd3003SFangrui Song   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
241d4ec3346SGreg McGary   ArrayRef<relocation_info> relInfos(
242d4ec3346SGreg McGary       reinterpret_cast<const relocation_info *>(buf + sec.reloff), sec.nreloc);
2436acd3003SFangrui Song 
244d4ec3346SGreg McGary   for (size_t i = 0; i < relInfos.size(); i++) {
245d4ec3346SGreg McGary     // Paired relocations serve as Mach-O's method for attaching a
246d4ec3346SGreg McGary     // supplemental datum to a primary relocation record. ELF does not
247d4ec3346SGreg McGary     // need them because the *_RELOC_RELA records contain the extra
248d4ec3346SGreg McGary     // addend field, vs. *_RELOC_REL which omit the addend.
249d4ec3346SGreg McGary     //
250d4ec3346SGreg McGary     // The {X86_64,ARM64}_RELOC_SUBTRACTOR record holds the subtrahend,
251d4ec3346SGreg McGary     // and the paired *_RELOC_UNSIGNED record holds the minuend. The
2523a9d2f14SGreg McGary     // datum for each is a symbolic address. The result is the offset
2533a9d2f14SGreg McGary     // between two addresses.
254d4ec3346SGreg McGary     //
255d4ec3346SGreg McGary     // The ARM64_RELOC_ADDEND record holds the addend, and the paired
256d4ec3346SGreg McGary     // ARM64_RELOC_BRANCH26 or ARM64_RELOC_PAGE21/PAGEOFF12 holds the
257d4ec3346SGreg McGary     // base symbolic address.
258d4ec3346SGreg McGary     //
259d4ec3346SGreg McGary     // Note: X86 does not use *_RELOC_ADDEND because it can embed an
260d4ec3346SGreg McGary     // addend into the instruction stream. On X86, a relocatable address
261d4ec3346SGreg McGary     // field always occupies an entire contiguous sequence of byte(s),
262d4ec3346SGreg McGary     // so there is no need to merge opcode bits with address
263d4ec3346SGreg McGary     // bits. Therefore, it's easy and convenient to store addends in the
264d4ec3346SGreg McGary     // instruction-stream bytes that would otherwise contain zeroes. By
265d4ec3346SGreg McGary     // contrast, RISC ISAs such as ARM64 mix opcode bits with with
266d4ec3346SGreg McGary     // address bits so that bitwise arithmetic is necessary to extract
267d4ec3346SGreg McGary     // and insert them. Storing addends in the instruction stream is
268d4ec3346SGreg McGary     // possible, but inconvenient and more costly at link time.
269d4ec3346SGreg McGary 
2703a9d2f14SGreg McGary     uint64_t pairedAddend = 0;
2713a9d2f14SGreg McGary     relocation_info relInfo = relInfos[i];
2723a9d2f14SGreg McGary     if (target->hasAttr(relInfo.r_type, RelocAttrBits::ADDEND)) {
2733a9d2f14SGreg McGary       pairedAddend = SignExtend64<24>(relInfo.r_symbolnum);
2743a9d2f14SGreg McGary       relInfo = relInfos[++i];
2753a9d2f14SGreg McGary     }
276d4ec3346SGreg McGary     assert(i < relInfos.size());
277e5d780e0SJez Ng     if (!validateRelocationInfo(this, sec, relInfo))
2783a9d2f14SGreg McGary       continue;
279d4ec3346SGreg McGary     if (relInfo.r_address & R_SCATTERED)
2804eb6f485SJez Ng       fatal("TODO: Scattered relocations not supported");
2813a9d2f14SGreg McGary     uint64_t embeddedAddend = target->getEmbeddedAddend(mb, sec, relInfo);
2823a9d2f14SGreg McGary     assert(!(embeddedAddend && pairedAddend));
2833a9d2f14SGreg McGary     uint64_t totalAddend = pairedAddend + embeddedAddend;
2844eb6f485SJez Ng 
2853a9d2f14SGreg McGary     Reloc p;
2863a9d2f14SGreg McGary     if (target->hasAttr(relInfo.r_type, RelocAttrBits::SUBTRAHEND)) {
2873a9d2f14SGreg McGary       p.type = relInfo.r_type;
2883a9d2f14SGreg McGary       p.referent = symbols[relInfo.r_symbolnum];
2893a9d2f14SGreg McGary       relInfo = relInfos[++i];
290*54139013SJez Ng       // SUBTRACTOR relocations should always be followed by an UNSIGNED one
291*54139013SJez Ng       // indicating the minuend symbol.
292*54139013SJez Ng       assert(target->hasAttr(relInfo.r_type, RelocAttrBits::UNSIGNED) &&
293*54139013SJez Ng              relInfo.r_extern);
2943a9d2f14SGreg McGary     }
2954eb6f485SJez Ng     Reloc r;
2961a3ef041SGreg McGary     r.type = relInfo.r_type;
2971a3ef041SGreg McGary     r.pcrel = relInfo.r_pcrel;
2981a3ef041SGreg McGary     r.length = relInfo.r_length;
299d4ec3346SGreg McGary     r.offset = relInfo.r_address;
3001a3ef041SGreg McGary     if (relInfo.r_extern) {
3011a3ef041SGreg McGary       r.referent = symbols[relInfo.r_symbolnum];
3023a9d2f14SGreg McGary       r.addend = totalAddend;
303198b0c57SJez Ng     } else {
3041a3ef041SGreg McGary       SubsectionMap &referentSubsecMap = subsections[relInfo.r_symbolnum - 1];
3051a3ef041SGreg McGary       const section_64 &referentSec = sectionHeaders[relInfo.r_symbolnum - 1];
3061a3ef041SGreg McGary       uint32_t referentOffset;
3071a3ef041SGreg McGary       if (relInfo.r_pcrel) {
3084eb6f485SJez Ng         // The implicit addend for pcrel section relocations is the pcrel offset
309fcde378dSJez Ng         // in terms of the addresses in the input file. Here we adjust it so
3101a3ef041SGreg McGary         // that it describes the offset from the start of the referent section.
3114eb6f485SJez Ng         // TODO: The offset of 4 is probably not right for ARM64, nor for
3124eb6f485SJez Ng         //       relocations with r_length != 2.
3131a3ef041SGreg McGary         referentOffset =
3143a9d2f14SGreg McGary             sec.addr + relInfo.r_address + 4 + totalAddend - referentSec.addr;
315fcde378dSJez Ng       } else {
316fcde378dSJez Ng         // The addend for a non-pcrel relocation is its absolute address.
3173a9d2f14SGreg McGary         referentOffset = totalAddend - referentSec.addr;
318fcde378dSJez Ng       }
3191a3ef041SGreg McGary       r.referent = findContainingSubsection(referentSubsecMap, &referentOffset);
3201a3ef041SGreg McGary       r.addend = referentOffset;
3214eb6f485SJez Ng     }
3224eb6f485SJez Ng 
3236f6d9186SJez Ng     InputSection *subsec = findContainingSubsection(subsecMap, &r.offset);
324*54139013SJez Ng     if (p.type != GENERIC_RELOC_INVALID)
3253a9d2f14SGreg McGary       subsec->relocs.push_back(p);
3264eb6f485SJez Ng     subsec->relocs.push_back(r);
3276acd3003SFangrui Song   }
3286acd3003SFangrui Song }
3294eb6f485SJez Ng 
33062a3f0c9SJez Ng static macho::Symbol *createDefined(const structs::nlist_64 &sym,
33162a3f0c9SJez Ng                                     StringRef name, InputSection *isec,
33262a3f0c9SJez Ng                                     uint32_t value) {
33313f439a1SNico Weber   // Symbol scope is determined by sym.n_type & (N_EXT | N_PEXT):
33413f439a1SNico Weber   // N_EXT: Global symbols
33513f439a1SNico Weber   // N_EXT | N_PEXT: Linkage unit (think: dylib) scoped
33613f439a1SNico Weber   // N_PEXT: Does not occur in input files in practice,
33713f439a1SNico Weber   //         a private extern must be external.
33813f439a1SNico Weber   // 0: Translation-unit scoped. These are not in the symbol table.
33913f439a1SNico Weber 
34013f439a1SNico Weber   if (sym.n_type & (N_EXT | N_PEXT)) {
34113f439a1SNico Weber     assert((sym.n_type & N_EXT) && "invalid input");
342163dcd85SJez Ng     return symtab->addDefined(name, isec->file, isec, value,
343163dcd85SJez Ng                               sym.n_desc & N_WEAK_DEF, sym.n_type & N_PEXT);
34413f439a1SNico Weber   }
345163dcd85SJez Ng   return make<Defined>(name, isec->file, isec, value, sym.n_desc & N_WEAK_DEF,
34613f439a1SNico Weber                        /*isExternal=*/false, /*isPrivateExtern=*/false);
34762a3f0c9SJez Ng }
34862a3f0c9SJez Ng 
34962a3f0c9SJez Ng // Absolute symbols are defined symbols that do not have an associated
35062a3f0c9SJez Ng // InputSection. They cannot be weak.
35162a3f0c9SJez Ng static macho::Symbol *createAbsolute(const structs::nlist_64 &sym,
352163dcd85SJez Ng                                      InputFile *file, StringRef name) {
35313f439a1SNico Weber   if (sym.n_type & (N_EXT | N_PEXT)) {
35413f439a1SNico Weber     assert((sym.n_type & N_EXT) && "invalid input");
355163dcd85SJez Ng     return symtab->addDefined(name, file, nullptr, sym.n_value,
356163dcd85SJez Ng                               /*isWeakDef=*/false, sym.n_type & N_PEXT);
35713f439a1SNico Weber   }
358163dcd85SJez Ng   return make<Defined>(name, file, nullptr, sym.n_value, /*isWeakDef=*/false,
35913f439a1SNico Weber                        /*isExternal=*/false, /*isPrivateExtern=*/false);
36062a3f0c9SJez Ng }
36162a3f0c9SJez Ng 
3627b007ac0SJez Ng macho::Symbol *ObjFile::parseNonSectionSymbol(const structs::nlist_64 &sym,
36362a3f0c9SJez Ng                                               StringRef name) {
36462a3f0c9SJez Ng   uint8_t type = sym.n_type & N_TYPE;
36562a3f0c9SJez Ng   switch (type) {
36662a3f0c9SJez Ng   case N_UNDF:
36762a3f0c9SJez Ng     return sym.n_value == 0
368163dcd85SJez Ng                ? symtab->addUndefined(name, this, sym.n_desc & N_WEAK_REF)
36962a3f0c9SJez Ng                : symtab->addCommon(name, this, sym.n_value,
37013f439a1SNico Weber                                    1 << GET_COMM_ALIGN(sym.n_desc),
37113f439a1SNico Weber                                    sym.n_type & N_PEXT);
37262a3f0c9SJez Ng   case N_ABS:
373163dcd85SJez Ng     return createAbsolute(sym, this, name);
37462a3f0c9SJez Ng   case N_PBUD:
37562a3f0c9SJez Ng   case N_INDR:
37662a3f0c9SJez Ng     error("TODO: support symbols of type " + std::to_string(type));
37762a3f0c9SJez Ng     return nullptr;
37862a3f0c9SJez Ng   case N_SECT:
37962a3f0c9SJez Ng     llvm_unreachable(
38062a3f0c9SJez Ng         "N_SECT symbols should not be passed to parseNonSectionSymbol");
38162a3f0c9SJez Ng   default:
38262a3f0c9SJez Ng     llvm_unreachable("invalid symbol type");
38362a3f0c9SJez Ng   }
38462a3f0c9SJez Ng }
38562a3f0c9SJez Ng 
3867b007ac0SJez Ng void ObjFile::parseSymbols(ArrayRef<structs::nlist_64> nList,
3871e1a3f67SJez Ng                            const char *strtab, bool subsectionsViaSymbols) {
3884eb6f485SJez Ng   // resize(), not reserve(), because we are going to create N_ALT_ENTRY symbols
3894eb6f485SJez Ng   // out-of-sequence.
3904eb6f485SJez Ng   symbols.resize(nList.size());
3914eb6f485SJez Ng   std::vector<size_t> altEntrySymIdxs;
3924eb6f485SJez Ng 
3934eb6f485SJez Ng   for (size_t i = 0, n = nList.size(); i < n; ++i) {
3941e1a3f67SJez Ng     const structs::nlist_64 &sym = nList[i];
3954eb6f485SJez Ng     StringRef name = strtab + sym.n_strx;
39662a3f0c9SJez Ng 
39762a3f0c9SJez Ng     if ((sym.n_type & N_TYPE) != N_SECT) {
39862a3f0c9SJez Ng       symbols[i] = parseNonSectionSymbol(sym, name);
3994eb6f485SJez Ng       continue;
4004eb6f485SJez Ng     }
4014eb6f485SJez Ng 
4024eb6f485SJez Ng     const section_64 &sec = sectionHeaders[sym.n_sect - 1];
4034eb6f485SJez Ng     SubsectionMap &subsecMap = subsections[sym.n_sect - 1];
404863f7a74SJez Ng     assert(!subsecMap.empty());
4054eb6f485SJez Ng     uint64_t offset = sym.n_value - sec.addr;
4064eb6f485SJez Ng 
4074eb6f485SJez Ng     // If the input file does not use subsections-via-symbols, all symbols can
4084eb6f485SJez Ng     // use the same subsection. Otherwise, we must split the sections along
4094eb6f485SJez Ng     // symbol boundaries.
4104eb6f485SJez Ng     if (!subsectionsViaSymbols) {
41162a3f0c9SJez Ng       symbols[i] = createDefined(sym, name, subsecMap[0], offset);
4124eb6f485SJez Ng       continue;
4134eb6f485SJez Ng     }
4144eb6f485SJez Ng 
4154eb6f485SJez Ng     // nList entries aren't necessarily arranged in address order. Therefore,
4164eb6f485SJez Ng     // we can't create alt-entry symbols at this point because a later symbol
4174eb6f485SJez Ng     // may split its section, which may affect which subsection the alt-entry
4184eb6f485SJez Ng     // symbol is assigned to. So we need to handle them in a second pass below.
4194eb6f485SJez Ng     if (sym.n_desc & N_ALT_ENTRY) {
4204eb6f485SJez Ng       altEntrySymIdxs.push_back(i);
4214eb6f485SJez Ng       continue;
4224eb6f485SJez Ng     }
4234eb6f485SJez Ng 
4244eb6f485SJez Ng     // Find the subsection corresponding to the greatest section offset that is
4254eb6f485SJez Ng     // <= that of the current symbol. The subsection that we find either needs
4264eb6f485SJez Ng     // to be used directly or split in two.
4274eb6f485SJez Ng     uint32_t firstSize = offset;
4284eb6f485SJez Ng     InputSection *firstIsec = findContainingSubsection(subsecMap, &firstSize);
4294eb6f485SJez Ng 
4304eb6f485SJez Ng     if (firstSize == 0) {
4314eb6f485SJez Ng       // Alias of an existing symbol, or the first symbol in the section. These
4324eb6f485SJez Ng       // are handled by reusing the existing section.
43362a3f0c9SJez Ng       symbols[i] = createDefined(sym, name, firstIsec, 0);
4344eb6f485SJez Ng       continue;
4354eb6f485SJez Ng     }
4364eb6f485SJez Ng 
4374eb6f485SJez Ng     // We saw a symbol definition at a new offset. Split the section into two
4384eb6f485SJez Ng     // subsections. The new symbol uses the second subsection.
4394eb6f485SJez Ng     auto *secondIsec = make<InputSection>(*firstIsec);
4404eb6f485SJez Ng     secondIsec->data = firstIsec->data.slice(firstSize);
4414eb6f485SJez Ng     firstIsec->data = firstIsec->data.slice(0, firstSize);
4424eb6f485SJez Ng     // TODO: ld64 appears to preserve the original alignment as well as each
4434eb6f485SJez Ng     // subsection's offset from the last aligned address. We should consider
4444eb6f485SJez Ng     // emulating that behavior.
4454eb6f485SJez Ng     secondIsec->align = MinAlign(firstIsec->align, offset);
4464eb6f485SJez Ng 
4474eb6f485SJez Ng     subsecMap[offset] = secondIsec;
4484eb6f485SJez Ng     // By construction, the symbol will be at offset zero in the new section.
44962a3f0c9SJez Ng     symbols[i] = createDefined(sym, name, secondIsec, 0);
4504eb6f485SJez Ng   }
4514eb6f485SJez Ng 
4524eb6f485SJez Ng   for (size_t idx : altEntrySymIdxs) {
4531e1a3f67SJez Ng     const structs::nlist_64 &sym = nList[idx];
45462a3f0c9SJez Ng     StringRef name = strtab + sym.n_strx;
4554eb6f485SJez Ng     SubsectionMap &subsecMap = subsections[sym.n_sect - 1];
4564eb6f485SJez Ng     uint32_t off = sym.n_value - sectionHeaders[sym.n_sect - 1].addr;
4574eb6f485SJez Ng     InputSection *subsec = findContainingSubsection(subsecMap, &off);
45862a3f0c9SJez Ng     symbols[idx] = createDefined(sym, name, subsec, off);
4596acd3003SFangrui Song   }
4606acd3003SFangrui Song }
4616acd3003SFangrui Song 
462a379f2c2SGreg McGary OpaqueFile::OpaqueFile(MemoryBufferRef mb, StringRef segName,
463a379f2c2SGreg McGary                        StringRef sectName)
464a379f2c2SGreg McGary     : InputFile(OpaqueKind, mb) {
465a379f2c2SGreg McGary   InputSection *isec = make<InputSection>();
466a379f2c2SGreg McGary   isec->file = this;
467a379f2c2SGreg McGary   isec->name = sectName.take_front(16);
468a379f2c2SGreg McGary   isec->segname = segName.take_front(16);
469a379f2c2SGreg McGary   const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
470a379f2c2SGreg McGary   isec->data = {buf, mb.getBufferSize()};
471a379f2c2SGreg McGary   subsections.push_back({{0, isec}});
472a379f2c2SGreg McGary }
473a379f2c2SGreg McGary 
474b2f00f24SNico Weber ObjFile::ObjFile(MemoryBufferRef mb, uint32_t modTime, StringRef archiveName)
475b768d57bSJez Ng     : InputFile(ObjKind, mb), modTime(modTime) {
476b2f00f24SNico Weber   this->archiveName = std::string(archiveName);
477b2f00f24SNico Weber 
4786acd3003SFangrui Song   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
4796acd3003SFangrui Song   auto *hdr = reinterpret_cast<const mach_header_64 *>(mb.getBufferStart());
4806acd3003SFangrui Song 
4814752cdc9SJez Ng   MachO::Architecture arch =
4824752cdc9SJez Ng       MachO::getArchitectureFromCpuType(hdr->cputype, hdr->cpusubtype);
4834752cdc9SJez Ng   if (arch != config->arch) {
4844752cdc9SJez Ng     error(toString(this) + " has architecture " + getArchitectureName(arch) +
4854752cdc9SJez Ng           " which is incompatible with target architecture " +
4864752cdc9SJez Ng           getArchitectureName(config->arch));
4874752cdc9SJez Ng     return;
4884752cdc9SJez Ng   }
4894752cdc9SJez Ng 
49016b1f6e3SNico Weber   if (const load_command *cmd = findCommand(hdr, LC_LINKER_OPTION)) {
49116b1f6e3SNico Weber     auto *c = reinterpret_cast<const linker_option_command *>(cmd);
49216b1f6e3SNico Weber     StringRef data{reinterpret_cast<const char *>(c + 1),
49316b1f6e3SNico Weber                    c->cmdsize - sizeof(linker_option_command)};
49416b1f6e3SNico Weber     parseLCLinkerOption(this, c->count, data);
49516b1f6e3SNico Weber   }
49616b1f6e3SNico Weber 
4976acd3003SFangrui Song   if (const load_command *cmd = findCommand(hdr, LC_SEGMENT_64)) {
4986acd3003SFangrui Song     auto *c = reinterpret_cast<const segment_command_64 *>(cmd);
4994eb6f485SJez Ng     sectionHeaders = ArrayRef<section_64>{
5006acd3003SFangrui Song         reinterpret_cast<const section_64 *>(c + 1), c->nsects};
5014eb6f485SJez Ng     parseSections(sectionHeaders);
5026acd3003SFangrui Song   }
5036acd3003SFangrui Song 
504060efd24SJez Ng   // TODO: Error on missing LC_SYMTAB?
5056acd3003SFangrui Song   if (const load_command *cmd = findCommand(hdr, LC_SYMTAB)) {
5066acd3003SFangrui Song     auto *c = reinterpret_cast<const symtab_command *>(cmd);
5071e1a3f67SJez Ng     ArrayRef<structs::nlist_64> nList(
5081e1a3f67SJez Ng         reinterpret_cast<const structs::nlist_64 *>(buf + c->symoff), c->nsyms);
5094eb6f485SJez Ng     const char *strtab = reinterpret_cast<const char *>(buf) + c->stroff;
5104eb6f485SJez Ng     bool subsectionsViaSymbols = hdr->flags & MH_SUBSECTIONS_VIA_SYMBOLS;
5114eb6f485SJez Ng     parseSymbols(nList, strtab, subsectionsViaSymbols);
5126acd3003SFangrui Song   }
5136acd3003SFangrui Song 
5146acd3003SFangrui Song   // The relocations may refer to the symbols, so we parse them after we have
5154eb6f485SJez Ng   // parsed all the symbols.
5164eb6f485SJez Ng   for (size_t i = 0, n = subsections.size(); i < n; ++i)
517863f7a74SJez Ng     if (!subsections[i].empty())
5184eb6f485SJez Ng       parseRelocations(sectionHeaders[i], subsections[i]);
5193fcb0eebSJez Ng 
5203fcb0eebSJez Ng   parseDebugInfo();
5213fcb0eebSJez Ng }
5223fcb0eebSJez Ng 
5233fcb0eebSJez Ng void ObjFile::parseDebugInfo() {
5243fcb0eebSJez Ng   std::unique_ptr<DwarfObject> dObj = DwarfObject::create(this);
5253fcb0eebSJez Ng   if (!dObj)
5263fcb0eebSJez Ng     return;
5273fcb0eebSJez Ng 
5283fcb0eebSJez Ng   auto *ctx = make<DWARFContext>(
5293fcb0eebSJez Ng       std::move(dObj), "",
530b2f00f24SNico Weber       [&](Error err) {
531b2f00f24SNico Weber         warn(toString(this) + ": " + toString(std::move(err)));
532b2f00f24SNico Weber       },
5333fcb0eebSJez Ng       [&](Error warning) {
534b2f00f24SNico Weber         warn(toString(this) + ": " + toString(std::move(warning)));
5353fcb0eebSJez Ng       });
5363fcb0eebSJez Ng 
5373fcb0eebSJez Ng   // TODO: Since object files can contain a lot of DWARF info, we should verify
5383fcb0eebSJez Ng   // that we are parsing just the info we need
5393fcb0eebSJez Ng   const DWARFContext::compile_unit_range &units = ctx->compile_units();
5403fcb0eebSJez Ng   auto it = units.begin();
5413fcb0eebSJez Ng   compileUnit = it->get();
5423fcb0eebSJez Ng   assert(std::next(it) == units.end());
5436acd3003SFangrui Song }
5446acd3003SFangrui Song 
5457394460dSJez Ng // The path can point to either a dylib or a .tbd file.
5467394460dSJez Ng static Optional<DylibFile *> loadDylib(StringRef path, DylibFile *umbrella) {
5477394460dSJez Ng   Optional<MemoryBufferRef> mbref = readFile(path);
5487394460dSJez Ng   if (!mbref) {
5497394460dSJez Ng     error("could not read dylib file at " + path);
5507394460dSJez Ng     return {};
5517394460dSJez Ng   }
55276c36c11SJez Ng   return loadDylib(*mbref, umbrella);
5537394460dSJez Ng }
5547394460dSJez Ng 
5557394460dSJez Ng // TBD files are parsed into a series of TAPI documents (InterfaceFiles), with
5567394460dSJez Ng // the first document storing child pointers to the rest of them. When we are
5577394460dSJez Ng // processing a given TBD file, we store that top-level document here. When
5587394460dSJez Ng // processing re-exports, we search its children for potentially matching
5597394460dSJez Ng // documents in the same TBD file. Note that the children themselves don't
5607394460dSJez Ng // point to further documents, i.e. this is a two-level tree.
5617394460dSJez Ng //
5627394460dSJez Ng // ld64 allows a TAPI re-export to reference documents nested within other TBD
5637394460dSJez Ng // files, but that seems like a strange design, so this is an intentional
5647394460dSJez Ng // deviation.
5657394460dSJez Ng const InterfaceFile *currentTopLevelTapi = nullptr;
5667394460dSJez Ng 
5677394460dSJez Ng // Re-exports can either refer to on-disk files, or to documents within .tbd
5687394460dSJez Ng // files.
5696a348f61SJez Ng static Optional<DylibFile *> loadReexportHelper(StringRef path,
5706a348f61SJez Ng                                                 DylibFile *umbrella) {
5717394460dSJez Ng   if (path::is_absolute(path, path::Style::posix))
5727394460dSJez Ng     for (StringRef root : config->systemLibraryRoots)
5737394460dSJez Ng       if (Optional<std::string> dylibPath =
5747394460dSJez Ng               resolveDylibPath((root + path).str()))
5757394460dSJez Ng         return loadDylib(*dylibPath, umbrella);
5767394460dSJez Ng 
5777394460dSJez Ng   // TODO: Expand @loader_path, @executable_path etc
5787394460dSJez Ng 
5799c702814SJez Ng   if (currentTopLevelTapi) {
5807394460dSJez Ng     for (InterfaceFile &child :
5817394460dSJez Ng          make_pointee_range(currentTopLevelTapi->documents())) {
5827394460dSJez Ng       if (path == child.getInstallName())
5837394460dSJez Ng         return make<DylibFile>(child, umbrella);
5847394460dSJez Ng       assert(child.documents().empty());
5857394460dSJez Ng     }
5867394460dSJez Ng   }
5877394460dSJez Ng 
5887394460dSJez Ng   if (Optional<std::string> dylibPath = resolveDylibPath(path))
5897394460dSJez Ng     return loadDylib(*dylibPath, umbrella);
5907394460dSJez Ng 
5917394460dSJez Ng   error("unable to locate re-export with install name " + path);
5927394460dSJez Ng   return {};
5937394460dSJez Ng }
5947394460dSJez Ng 
5956a348f61SJez Ng // If a re-exported dylib is public (lives in /usr/lib or
5966a348f61SJez Ng // /System/Library/Frameworks), then it is considered implicitly linked: we
5976a348f61SJez Ng // should bind to its symbols directly instead of via the re-exporting umbrella
5986a348f61SJez Ng // library.
5996a348f61SJez Ng static bool isImplicitlyLinked(StringRef path) {
6006a348f61SJez Ng   if (!config->implicitDylibs)
6016a348f61SJez Ng     return false;
6026a348f61SJez Ng 
6033aa8e071SJez Ng   if (path::parent_path(path) == "/usr/lib")
6043aa8e071SJez Ng     return true;
6053aa8e071SJez Ng 
6063aa8e071SJez Ng   // Match /System/Library/Frameworks/$FOO.framework/**/$FOO
6073aa8e071SJez Ng   if (path.consume_front("/System/Library/Frameworks/")) {
6083aa8e071SJez Ng     StringRef frameworkName = path.take_until([](char c) { return c == '.'; });
6093aa8e071SJez Ng     return path::filename(path) == frameworkName;
6103aa8e071SJez Ng   }
6113aa8e071SJez Ng 
6123aa8e071SJez Ng   return false;
6136a348f61SJez Ng }
6146a348f61SJez Ng 
61576c36c11SJez Ng void loadReexport(StringRef path, DylibFile *umbrella) {
6166a348f61SJez Ng   Optional<DylibFile *> reexport = loadReexportHelper(path, umbrella);
6176a348f61SJez Ng   if (reexport && isImplicitlyLinked(path))
618544148aeSJez Ng     inputFiles.insert(*reexport);
6196a348f61SJez Ng }
6206a348f61SJez Ng 
6215a856f5bSVy Nguyen DylibFile::DylibFile(MemoryBufferRef mb, DylibFile *umbrella,
6225a856f5bSVy Nguyen                      bool isBundleLoader)
6235a856f5bSVy Nguyen     : InputFile(DylibKind, mb), refState(RefState::Unreferenced),
6245a856f5bSVy Nguyen       isBundleLoader(isBundleLoader) {
6255a856f5bSVy Nguyen   assert(!isBundleLoader || !umbrella);
62687b6fd3eSJez Ng   if (umbrella == nullptr)
62787b6fd3eSJez Ng     umbrella = this;
62887b6fd3eSJez Ng 
629060efd24SJez Ng   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
630060efd24SJez Ng   auto *hdr = reinterpret_cast<const mach_header_64 *>(mb.getBufferStart());
631060efd24SJez Ng 
632060efd24SJez Ng   // Initialize dylibName.
633060efd24SJez Ng   if (const load_command *cmd = findCommand(hdr, LC_ID_DYLIB)) {
634060efd24SJez Ng     auto *c = reinterpret_cast<const dylib_command *>(cmd);
635ec88746aSNico Weber     currentVersion = read32le(&c->dylib.current_version);
636ec88746aSNico Weber     compatibilityVersion = read32le(&c->dylib.compatibility_version);
637060efd24SJez Ng     dylibName = reinterpret_cast<const char *>(cmd) + read32le(&c->dylib.name);
6385a856f5bSVy Nguyen   } else if (!isBundleLoader) {
6395a856f5bSVy Nguyen     // macho_executable and macho_bundle don't have LC_ID_DYLIB,
6405a856f5bSVy Nguyen     // so it's OK.
641b2f00f24SNico Weber     error("dylib " + toString(this) + " missing LC_ID_DYLIB load command");
642060efd24SJez Ng     return;
643060efd24SJez Ng   }
644060efd24SJez Ng 
645060efd24SJez Ng   // Initialize symbols.
6466a348f61SJez Ng   DylibFile *exportingFile = isImplicitlyLinked(dylibName) ? this : umbrella;
6477bbdbacdSJez Ng   if (const load_command *cmd = findCommand(hdr, LC_DYLD_INFO_ONLY)) {
6487bbdbacdSJez Ng     auto *c = reinterpret_cast<const dyld_info_command *>(cmd);
6497bbdbacdSJez Ng     parseTrie(buf + c->export_off, c->export_size,
6507bbdbacdSJez Ng               [&](const Twine &name, uint64_t flags) {
65131d58858SJez Ng                 bool isWeakDef = flags & EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION;
6523c9100fbSJez Ng                 bool isTlv = flags & EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL;
6536a348f61SJez Ng                 symbols.push_back(symtab->addDylib(
6546a348f61SJez Ng                     saver.save(name), exportingFile, isWeakDef, isTlv));
6557bbdbacdSJez Ng               });
6567bbdbacdSJez Ng   } else {
657b2f00f24SNico Weber     error("LC_DYLD_INFO_ONLY not found in " + toString(this));
65887b6fd3eSJez Ng     return;
65987b6fd3eSJez Ng   }
66087b6fd3eSJez Ng 
66187b6fd3eSJez Ng   if (hdr->flags & MH_NO_REEXPORTED_DYLIBS)
66287b6fd3eSJez Ng     return;
66387b6fd3eSJez Ng 
66487b6fd3eSJez Ng   const uint8_t *p =
66587b6fd3eSJez Ng       reinterpret_cast<const uint8_t *>(hdr) + sizeof(mach_header_64);
66687b6fd3eSJez Ng   for (uint32_t i = 0, n = hdr->ncmds; i < n; ++i) {
66787b6fd3eSJez Ng     auto *cmd = reinterpret_cast<const load_command *>(p);
66887b6fd3eSJez Ng     p += cmd->cmdsize;
66987b6fd3eSJez Ng     if (cmd->cmd != LC_REEXPORT_DYLIB)
67087b6fd3eSJez Ng       continue;
67187b6fd3eSJez Ng 
67287b6fd3eSJez Ng     auto *c = reinterpret_cast<const dylib_command *>(cmd);
67387b6fd3eSJez Ng     StringRef reexportPath =
67487b6fd3eSJez Ng         reinterpret_cast<const char *>(c) + read32le(&c->dylib.name);
67576c36c11SJez Ng     loadReexport(reexportPath, umbrella);
676060efd24SJez Ng   }
677060efd24SJez Ng }
678060efd24SJez Ng 
6795a856f5bSVy Nguyen DylibFile::DylibFile(const InterfaceFile &interface, DylibFile *umbrella,
6805a856f5bSVy Nguyen                      bool isBundleLoader)
6815a856f5bSVy Nguyen     : InputFile(DylibKind, interface), refState(RefState::Unreferenced),
6825a856f5bSVy Nguyen       isBundleLoader(isBundleLoader) {
6835a856f5bSVy Nguyen   // FIXME: Add test for the missing TBD code path.
6845a856f5bSVy Nguyen 
6856fe27b5fSSaleem Abdulrasool   if (umbrella == nullptr)
6866fe27b5fSSaleem Abdulrasool     umbrella = this;
6876fe27b5fSSaleem Abdulrasool 
6884752cdc9SJez Ng   if (!interface.getArchitectures().has(config->arch)) {
6894752cdc9SJez Ng     error(toString(this) + " is incompatible with " +
6904752cdc9SJez Ng           getArchitectureName(config->arch));
6914752cdc9SJez Ng     return;
6924752cdc9SJez Ng   }
6934752cdc9SJez Ng 
6947e6d6754SJez Ng   dylibName = saver.save(interface.getInstallName());
695ec88746aSNico Weber   compatibilityVersion = interface.getCompatibilityVersion().rawValue();
696ec88746aSNico Weber   currentVersion = interface.getCurrentVersion().rawValue();
6976a348f61SJez Ng   DylibFile *exportingFile = isImplicitlyLinked(dylibName) ? this : umbrella;
698a499898eSJez Ng   auto addSymbol = [&](const Twine &name) -> void {
6996a348f61SJez Ng     symbols.push_back(symtab->addDylib(saver.save(name), exportingFile,
700a499898eSJez Ng                                        /*isWeakDef=*/false,
701a499898eSJez Ng                                        /*isTlv=*/false));
702a499898eSJez Ng   };
7036fe27b5fSSaleem Abdulrasool   // TODO(compnerd) filter out symbols based on the target platform
7043c9100fbSJez Ng   // TODO: handle weak defs, thread locals
7057e6d6754SJez Ng   for (const auto symbol : interface.symbols()) {
706a499898eSJez Ng     if (!symbol->getArchitectures().has(config->arch))
707a499898eSJez Ng       continue;
708a499898eSJez Ng 
709a499898eSJez Ng     switch (symbol->getKind()) {
710a499898eSJez Ng     case SymbolKind::GlobalSymbol:
711a499898eSJez Ng       addSymbol(symbol->getName());
712a499898eSJez Ng       break;
713a499898eSJez Ng     case SymbolKind::ObjectiveCClass:
714a499898eSJez Ng       // XXX ld64 only creates these symbols when -ObjC is passed in. We may
715a499898eSJez Ng       // want to emulate that.
716cf918c80SJez Ng       addSymbol(objc::klass + symbol->getName());
717cf918c80SJez Ng       addSymbol(objc::metaclass + symbol->getName());
718a499898eSJez Ng       break;
719a499898eSJez Ng     case SymbolKind::ObjectiveCClassEHType:
720cf918c80SJez Ng       addSymbol(objc::ehtype + symbol->getName());
721a499898eSJez Ng       break;
722a499898eSJez Ng     case SymbolKind::ObjectiveCInstanceVariable:
723cf918c80SJez Ng       addSymbol(objc::ivar + symbol->getName());
724a499898eSJez Ng       break;
725a499898eSJez Ng     }
726a499898eSJez Ng   }
7277394460dSJez Ng 
7287394460dSJez Ng   bool isTopLevelTapi = false;
7297394460dSJez Ng   if (currentTopLevelTapi == nullptr) {
7307394460dSJez Ng     currentTopLevelTapi = &interface;
7317394460dSJez Ng     isTopLevelTapi = true;
7327394460dSJez Ng   }
7337394460dSJez Ng 
7347394460dSJez Ng   for (InterfaceFileRef intfRef : interface.reexportedLibraries())
73576c36c11SJez Ng     loadReexport(intfRef.getInstallName(), umbrella);
7367394460dSJez Ng 
7377394460dSJez Ng   if (isTopLevelTapi)
7387394460dSJez Ng     currentTopLevelTapi = nullptr;
7396fe27b5fSSaleem Abdulrasool }
7406fe27b5fSSaleem Abdulrasool 
741e98b441aSJez Ng ArchiveFile::ArchiveFile(std::unique_ptr<object::Archive> &&f)
7422b920ae7SKellie Medlin     : InputFile(ArchiveKind, f->getMemoryBufferRef()), file(std::move(f)) {
7432b920ae7SKellie Medlin   for (const object::Archive::Symbol &sym : file->symbols())
7442b920ae7SKellie Medlin     symtab->addLazy(sym.getName(), this, sym);
7452b920ae7SKellie Medlin }
7462b920ae7SKellie Medlin 
7472b920ae7SKellie Medlin void ArchiveFile::fetch(const object::Archive::Symbol &sym) {
7482b920ae7SKellie Medlin   object::Archive::Child c =
7492b920ae7SKellie Medlin       CHECK(sym.getMember(), toString(this) +
7502b920ae7SKellie Medlin                                  ": could not get the member for symbol " +
75107ab597bSNico Weber                                  toMachOString(sym));
7522b920ae7SKellie Medlin 
7532b920ae7SKellie Medlin   if (!seen.insert(c.getChildOffset()).second)
7542b920ae7SKellie Medlin     return;
7552b920ae7SKellie Medlin 
7562b920ae7SKellie Medlin   MemoryBufferRef mb =
7572b920ae7SKellie Medlin       CHECK(c.getMemoryBufferRef(),
7582b920ae7SKellie Medlin             toString(this) +
7592b920ae7SKellie Medlin                 ": could not get the buffer for the member defining symbol " +
76007ab597bSNico Weber                 toMachOString(sym));
761b768d57bSJez Ng 
762ca634393SNico Weber   if (tar && c.getParent()->isThin())
763ca634393SNico Weber     tar->append(relativeToRoot(CHECK(c.getFullName(), this)), mb.getBuffer());
764ca634393SNico Weber 
765b768d57bSJez Ng   uint32_t modTime = toTimeT(
766b768d57bSJez Ng       CHECK(c.getLastModified(), toString(this) +
767b768d57bSJez Ng                                      ": could not get the modification time "
768b768d57bSJez Ng                                      "for the member defining symbol " +
76907ab597bSNico Weber                                      toMachOString(sym)));
770b768d57bSJez Ng 
7713422f3ccSNico Weber   // `sym` is owned by a LazySym, which will be replace<>() by make<ObjFile>
7723422f3ccSNico Weber   // and become invalid after that call. Copy it to the stack so we can refer
7733422f3ccSNico Weber   // to it later.
7743422f3ccSNico Weber   const object::Archive::Symbol sym_copy = sym;
7753422f3ccSNico Weber 
776f843bb82SJez Ng   if (Optional<InputFile *> file =
777f843bb82SJez Ng           loadArchiveMember(mb, modTime, getName(), /*objCOnly=*/false)) {
778f843bb82SJez Ng     inputFiles.insert(*file);
7793422f3ccSNico Weber     // ld64 doesn't demangle sym here even with -demangle. Match that, so
7803422f3ccSNico Weber     // intentionally no call to toMachOString() here.
781f843bb82SJez Ng     printArchiveMemberLoad(sym_copy.getName(), *file);
782f843bb82SJez Ng   }
7832b920ae7SKellie Medlin }
7842b920ae7SKellie Medlin 
78584579fc2SJez Ng static macho::Symbol *createBitcodeSymbol(const lto::InputFile::Symbol &objSym,
78684579fc2SJez Ng                                           BitcodeFile &file) {
78784579fc2SJez Ng   StringRef name = saver.save(objSym.getName());
78884579fc2SJez Ng 
78984579fc2SJez Ng   // TODO: support weak references
79084579fc2SJez Ng   if (objSym.isUndefined())
79184579fc2SJez Ng     return symtab->addUndefined(name, &file, /*isWeakRef=*/false);
79284579fc2SJez Ng 
79384579fc2SJez Ng   assert(!objSym.isCommon() && "TODO: support common symbols in LTO");
79484579fc2SJez Ng 
79584579fc2SJez Ng   // TODO: Write a test demonstrating why computing isPrivateExtern before
79684579fc2SJez Ng   // LTO compilation is important.
79784579fc2SJez Ng   bool isPrivateExtern = false;
79884579fc2SJez Ng   switch (objSym.getVisibility()) {
79984579fc2SJez Ng   case GlobalValue::HiddenVisibility:
80084579fc2SJez Ng     isPrivateExtern = true;
80184579fc2SJez Ng     break;
80284579fc2SJez Ng   case GlobalValue::ProtectedVisibility:
80384579fc2SJez Ng     error(name + " has protected visibility, which is not supported by Mach-O");
80484579fc2SJez Ng     break;
80584579fc2SJez Ng   case GlobalValue::DefaultVisibility:
80684579fc2SJez Ng     break;
80784579fc2SJez Ng   }
80884579fc2SJez Ng 
80984579fc2SJez Ng   return symtab->addDefined(name, &file, /*isec=*/nullptr, /*value=*/0,
81084579fc2SJez Ng                             objSym.isWeak(), isPrivateExtern);
81184579fc2SJez Ng }
81284579fc2SJez Ng 
81321f83113SJez Ng BitcodeFile::BitcodeFile(MemoryBufferRef mbref)
81421f83113SJez Ng     : InputFile(BitcodeKind, mbref) {
81521f83113SJez Ng   obj = check(lto::InputFile::create(mbref));
81684579fc2SJez Ng 
81784579fc2SJez Ng   // Convert LTO Symbols to LLD Symbols in order to perform resolution. The
81884579fc2SJez Ng   // "winning" symbol will then be marked as Prevailing at LTO compilation
81984579fc2SJez Ng   // time.
82084579fc2SJez Ng   for (const lto::InputFile::Symbol &objSym : obj->symbols())
82184579fc2SJez Ng     symbols.push_back(createBitcodeSymbol(objSym, *this));
82221f83113SJez Ng }
823