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"
48e183bf8eSJez Ng #include "EhFrame.h"
497bbdbacdSJez Ng #include "ExportTrie.h"
506acd3003SFangrui Song #include "InputSection.h"
511e1a3f67SJez Ng #include "MachOStructs.h"
52cf918c80SJez Ng #include "ObjC.h"
536cb07313SKellie Medlin #include "OutputSection.h"
54cf918c80SJez Ng #include "OutputSegment.h"
556acd3003SFangrui Song #include "SymbolTable.h"
566acd3003SFangrui Song #include "Symbols.h"
5704259cdeSJez Ng #include "SyntheticSections.h"
586acd3003SFangrui Song #include "Target.h"
596acd3003SFangrui Song 
6083d59e05SAlexandre Ganea #include "lld/Common/CommonLinkerContext.h"
613fcb0eebSJez Ng #include "lld/Common/DWARF.h"
6283e60f5aSNico Weber #include "lld/Common/Reproduce.h"
637394460dSJez Ng #include "llvm/ADT/iterator.h"
646acd3003SFangrui Song #include "llvm/BinaryFormat/MachO.h"
6521f83113SJez Ng #include "llvm/LTO/LTO.h"
666db04b97SLeonard Grey #include "llvm/Support/BinaryStreamReader.h"
676acd3003SFangrui Song #include "llvm/Support/Endian.h"
68a3f67f09SDaniel Bertalan #include "llvm/Support/LEB128.h"
696acd3003SFangrui Song #include "llvm/Support/MemoryBuffer.h"
7087b6fd3eSJez Ng #include "llvm/Support/Path.h"
7183e60f5aSNico Weber #include "llvm/Support/TarWriter.h"
726db04b97SLeonard Grey #include "llvm/Support/TimeProfiler.h"
730116d04dSCyndy Ishida #include "llvm/TextAPI/Architecture.h"
740116d04dSCyndy Ishida #include "llvm/TextAPI/InterfaceFile.h"
756acd3003SFangrui Song 
7634d15eacSVy Nguyen #include <type_traits>
7734d15eacSVy Nguyen 
786acd3003SFangrui Song using namespace llvm;
796acd3003SFangrui Song using namespace llvm::MachO;
806acd3003SFangrui Song using namespace llvm::support::endian;
8187b6fd3eSJez Ng using namespace llvm::sys;
826acd3003SFangrui Song using namespace lld;
836acd3003SFangrui Song using namespace lld::macho;
846acd3003SFangrui Song 
85b2f00f24SNico Weber // Returns "<internal>", "foo.a(bar.o)", or "baz.o".
toString(const InputFile * f)86b2f00f24SNico Weber std::string lld::toString(const InputFile *f) {
87b2f00f24SNico Weber   if (!f)
88b2f00f24SNico Weber     return "<internal>";
890d4dadc6SJez Ng 
900d4dadc6SJez Ng   // Multiple dylibs can be defined in one .tbd file.
910d4dadc6SJez Ng   if (auto dylibFile = dyn_cast<DylibFile>(f))
920d4dadc6SJez Ng     if (f->getName().endswith(".tbd"))
937def7006SNico Weber       return (f->getName() + "(" + dylibFile->installName + ")").str();
940d4dadc6SJez Ng 
95b2f00f24SNico Weber   if (f->archiveName.empty())
96b2f00f24SNico Weber     return std::string(f->getName());
973142fc3bSJez Ng   return (f->archiveName + "(" + path::filename(f->getName()) + ")").str();
98b2f00f24SNico Weber }
99b2f00f24SNico Weber 
toString(const Section & sec)100f004ecf6SJez Ng std::string lld::toString(const Section &sec) {
101f004ecf6SJez Ng   return (toString(sec.file) + ":(" + sec.name + ")").str();
102f004ecf6SJez Ng }
103f004ecf6SJez Ng 
104544148aeSJez Ng SetVector<InputFile *> macho::inputFiles;
10583e60f5aSNico Weber std::unique_ptr<TarWriter> macho::tar;
10678f6498cSJez Ng int InputFile::idCount = 0;
1076acd3003SFangrui Song 
decodeVersion(uint32_t version)1085c835e1aSAlexander Shaposhnikov static VersionTuple decodeVersion(uint32_t version) {
1095c835e1aSAlexander Shaposhnikov   unsigned major = version >> 16;
1105c835e1aSAlexander Shaposhnikov   unsigned minor = (version >> 8) & 0xffu;
1115c835e1aSAlexander Shaposhnikov   unsigned subMinor = version & 0xffu;
1125c835e1aSAlexander Shaposhnikov   return VersionTuple(major, minor, subMinor);
1135c835e1aSAlexander Shaposhnikov }
1145c835e1aSAlexander Shaposhnikov 
getPlatformInfos(const InputFile * input)11592607602SJez Ng static std::vector<PlatformInfo> getPlatformInfos(const InputFile *input) {
1165c835e1aSAlexander Shaposhnikov   if (!isa<ObjFile>(input) && !isa<DylibFile>(input))
11792607602SJez Ng     return {};
1185c835e1aSAlexander Shaposhnikov 
119001ba653SJez Ng   const char *hdr = input->mb.getBufferStart();
120b5720354SAlexander Shaposhnikov 
12188984792SNico Weber   // "Zippered" object files can have multiple LC_BUILD_VERSION load commands.
12292607602SJez Ng   std::vector<PlatformInfo> platformInfos;
12392607602SJez Ng   for (auto *cmd : findCommands<build_version_command>(hdr, LC_BUILD_VERSION)) {
12492607602SJez Ng     PlatformInfo info;
1253025c3edSJuergen Ributzka     info.target.Platform = static_cast<PlatformType>(cmd->platform);
12692607602SJez Ng     info.minimum = decodeVersion(cmd->minos);
12792607602SJez Ng     platformInfos.emplace_back(std::move(info));
128b5720354SAlexander Shaposhnikov   }
12992607602SJez Ng   for (auto *cmd : findCommands<version_min_command>(
130b5720354SAlexander Shaposhnikov            hdr, LC_VERSION_MIN_MACOSX, LC_VERSION_MIN_IPHONEOS,
131b5720354SAlexander Shaposhnikov            LC_VERSION_MIN_TVOS, LC_VERSION_MIN_WATCHOS)) {
13292607602SJez Ng     PlatformInfo info;
133b5720354SAlexander Shaposhnikov     switch (cmd->cmd) {
134b5720354SAlexander Shaposhnikov     case LC_VERSION_MIN_MACOSX:
1353025c3edSJuergen Ributzka       info.target.Platform = PLATFORM_MACOS;
136b5720354SAlexander Shaposhnikov       break;
137b5720354SAlexander Shaposhnikov     case LC_VERSION_MIN_IPHONEOS:
1383025c3edSJuergen Ributzka       info.target.Platform = PLATFORM_IOS;
139b5720354SAlexander Shaposhnikov       break;
140b5720354SAlexander Shaposhnikov     case LC_VERSION_MIN_TVOS:
1413025c3edSJuergen Ributzka       info.target.Platform = PLATFORM_TVOS;
142b5720354SAlexander Shaposhnikov       break;
143b5720354SAlexander Shaposhnikov     case LC_VERSION_MIN_WATCHOS:
1443025c3edSJuergen Ributzka       info.target.Platform = PLATFORM_WATCHOS;
145b5720354SAlexander Shaposhnikov       break;
146b5720354SAlexander Shaposhnikov     }
14792607602SJez Ng     info.minimum = decodeVersion(cmd->version);
14892607602SJez Ng     platformInfos.emplace_back(std::move(info));
1495c835e1aSAlexander Shaposhnikov   }
1505c835e1aSAlexander Shaposhnikov 
15192607602SJez Ng   return platformInfos;
1525c835e1aSAlexander Shaposhnikov }
1535c835e1aSAlexander Shaposhnikov 
checkCompatibility(const InputFile * input)154001ba653SJez Ng static bool checkCompatibility(const InputFile *input) {
15592607602SJez Ng   std::vector<PlatformInfo> platformInfos = getPlatformInfos(input);
15692607602SJez Ng   if (platformInfos.empty())
1575c835e1aSAlexander Shaposhnikov     return true;
15823233ad1SVy Nguyen 
15992607602SJez Ng   auto it = find_if(platformInfos, [&](const PlatformInfo &info) {
16092607602SJez Ng     return removeSimulator(info.target.Platform) ==
16192607602SJez Ng            removeSimulator(config->platform());
16292607602SJez Ng   });
16392607602SJez Ng   if (it == platformInfos.end()) {
16492607602SJez Ng     std::string platformNames;
16592607602SJez Ng     raw_string_ostream os(platformNames);
16692607602SJez Ng     interleave(
16792607602SJez Ng         platformInfos, os,
16892607602SJez Ng         [&](const PlatformInfo &info) {
16992607602SJez Ng           os << getPlatformName(info.target.Platform);
17092607602SJez Ng         },
17192607602SJez Ng         "/");
17292607602SJez Ng     error(toString(input) + " has platform " + platformNames +
1735c835e1aSAlexander Shaposhnikov           Twine(", which is different from target platform ") +
174ed4a4e33SJez Ng           getPlatformName(config->platform()));
1755c835e1aSAlexander Shaposhnikov     return false;
1765c835e1aSAlexander Shaposhnikov   }
17792607602SJez Ng 
178d52d1b93SJez Ng   if (it->minimum > config->platformInfo.minimum)
179d52d1b93SJez Ng     warn(toString(input) + " has version " + it->minimum.getAsString() +
1808c17a875SJez Ng          ", which is newer than target minimum of " +
1815c835e1aSAlexander Shaposhnikov          config->platformInfo.minimum.getAsString());
182d52d1b93SJez Ng 
183d52d1b93SJez Ng   return true;
1845c835e1aSAlexander Shaposhnikov }
1855c835e1aSAlexander Shaposhnikov 
186d49e7244SKeith Smiley // This cache mostly exists to store system libraries (and .tbds) as they're
187d49e7244SKeith Smiley // loaded, rather than the input archives, which are already cached at a higher
188d49e7244SKeith Smiley // level, and other files like the filelist that are only read once.
189d49e7244SKeith Smiley // Theoretically this caching could be more efficient by hoisting it, but that
190d49e7244SKeith Smiley // would require altering many callers to track the state.
1910bce3e3bSKeith Smiley DenseMap<CachedHashStringRef, MemoryBufferRef> macho::cachedReads;
1926acd3003SFangrui Song // Open a given file path and return it as a memory-mapped file.
readFile(StringRef path)1934af1522aSGreg McGary Optional<MemoryBufferRef> macho::readFile(StringRef path) {
194d49e7244SKeith Smiley   CachedHashStringRef key(path);
1950bce3e3bSKeith Smiley   auto entry = cachedReads.find(key);
1960bce3e3bSKeith Smiley   if (entry != cachedReads.end())
197d49e7244SKeith Smiley     return entry->second;
198d49e7244SKeith Smiley 
199fdc0c219SGreg McGary   ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr = MemoryBuffer::getFile(path);
200fdc0c219SGreg McGary   if (std::error_code ec = mbOrErr.getError()) {
2016acd3003SFangrui Song     error("cannot open " + path + ": " + ec.message());
2026acd3003SFangrui Song     return None;
2036acd3003SFangrui Song   }
2046acd3003SFangrui Song 
2056acd3003SFangrui Song   std::unique_ptr<MemoryBuffer> &mb = *mbOrErr;
2066acd3003SFangrui Song   MemoryBufferRef mbref = mb->getMemBufferRef();
2076acd3003SFangrui Song   make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take mb ownership
208060efd24SJez Ng 
209060efd24SJez Ng   // If this is a regular non-fat file, return it.
210060efd24SJez Ng   const char *buf = mbref.getBufferStart();
2111752f285SJez Ng   const auto *hdr = reinterpret_cast<const fat_header *>(buf);
2124af1522aSGreg McGary   if (mbref.getBufferSize() < sizeof(uint32_t) ||
2131752f285SJez Ng       read32be(&hdr->magic) != FAT_MAGIC) {
21483e60f5aSNico Weber     if (tar)
21583e60f5aSNico Weber       tar->append(relativeToRoot(path), mbref.getBuffer());
2160bce3e3bSKeith Smiley     return cachedReads[key] = mbref;
21783e60f5aSNico Weber   }
218060efd24SJez Ng 
21983d59e05SAlexandre Ganea   llvm::BumpPtrAllocator &bAlloc = lld::bAlloc();
22083d59e05SAlexandre Ganea 
2218535834eSJez Ng   // Object files and archive files may be fat files, which contain multiple
2228535834eSJez Ng   // real files for different CPU ISAs. Here, we search for a file that matches
2238535834eSJez Ng   // with the current link target and returns it as a MemoryBufferRef.
2241752f285SJez Ng   const auto *arch = reinterpret_cast<const fat_arch *>(buf + sizeof(*hdr));
225918948dbSJez Ng 
226918948dbSJez Ng   for (uint32_t i = 0, n = read32be(&hdr->nfat_arch); i < n; ++i) {
227918948dbSJez Ng     if (reinterpret_cast<const char *>(arch + i + 1) >
228918948dbSJez Ng         buf + mbref.getBufferSize()) {
229918948dbSJez Ng       error(path + ": fat_arch struct extends beyond end of file");
230918948dbSJez Ng       return None;
231918948dbSJez Ng     }
232918948dbSJez Ng 
233b1c3c2e4SJez Ng     if (read32be(&arch[i].cputype) != static_cast<uint32_t>(target->cpuType) ||
234918948dbSJez Ng         read32be(&arch[i].cpusubtype) != target->cpuSubtype)
235918948dbSJez Ng       continue;
236918948dbSJez Ng 
237918948dbSJez Ng     uint32_t offset = read32be(&arch[i].offset);
238918948dbSJez Ng     uint32_t size = read32be(&arch[i].size);
239918948dbSJez Ng     if (offset + size > mbref.getBufferSize())
240918948dbSJez Ng       error(path + ": slice extends beyond end of file");
24183e60f5aSNico Weber     if (tar)
24283e60f5aSNico Weber       tar->append(relativeToRoot(path), mbref.getBuffer());
2430bce3e3bSKeith Smiley     return cachedReads[key] = MemoryBufferRef(StringRef(buf + offset, size),
244d49e7244SKeith Smiley                                               path.copy(bAlloc));
245918948dbSJez Ng   }
246918948dbSJez Ng 
247918948dbSJez Ng   error("unable to find matching architecture in " + path);
248060efd24SJez Ng   return None;
2496acd3003SFangrui Song }
2506acd3003SFangrui Song 
InputFile(Kind kind,const InterfaceFile & interface)2511752f285SJez Ng InputFile::InputFile(Kind kind, const InterfaceFile &interface)
25283d59e05SAlexandre Ganea     : id(idCount++), fileKind(kind), name(saver().save(interface.getPath())) {}
2531752f285SJez Ng 
25491ace9f0SJez Ng // Some sections comprise of fixed-size records, so instead of splitting them at
25591ace9f0SJez Ng // symbol boundaries, we split them based on size. Records are distinct from
25691ace9f0SJez Ng // literals in that they may contain references to other sections, instead of
25791ace9f0SJez Ng // being leaf nodes in the InputSection graph.
25891ace9f0SJez Ng //
25991ace9f0SJez Ng // Note that "record" is a term I came up with. In contrast, "literal" is a term
26091ace9f0SJez Ng // used by the Mach-O format.
getRecordSize(StringRef segname,StringRef name)26191ace9f0SJez Ng static Optional<size_t> getRecordSize(StringRef segname, StringRef name) {
262ce2ae381SJez Ng   if (name == section_names::compactUnwind) {
263002eda70SJez Ng     if (segname == segment_names::ld)
264002eda70SJez Ng       return target->wordSize == 8 ? 32 : 20;
265002eda70SJez Ng   }
26615f685eaSKeith Smiley   if (!config->dedupLiterals)
267ce2ae381SJez Ng     return {};
268ce2ae381SJez Ng 
269ce2ae381SJez Ng   if (name == section_names::cfString && segname == segment_names::data)
270ce2ae381SJez Ng     return target->wordSize == 8 ? 32 : 16;
27115f685eaSKeith Smiley 
27215f685eaSKeith Smiley   if (config->icfLevel == ICFLevel::none)
27315f685eaSKeith Smiley     return {};
27415f685eaSKeith Smiley 
275ce2ae381SJez Ng   if (name == section_names::objcClassRefs && segname == segment_names::data)
276ce2ae381SJez Ng     return target->wordSize;
27791ace9f0SJez Ng   return {};
27891ace9f0SJez Ng }
27991ace9f0SJez Ng 
parseCallGraph(ArrayRef<uint8_t> data,std::vector<CallGraphEntry> & callGraph)28094c28d28SJez Ng static Error parseCallGraph(ArrayRef<uint8_t> data,
28194c28d28SJez Ng                             std::vector<CallGraphEntry> &callGraph) {
28294c28d28SJez Ng   TimeTraceScope timeScope("Parsing call graph section");
28394c28d28SJez Ng   BinaryStreamReader reader(data, support::little);
28494c28d28SJez Ng   while (!reader.empty()) {
28594c28d28SJez Ng     uint32_t fromIndex, toIndex;
28694c28d28SJez Ng     uint64_t count;
28794c28d28SJez Ng     if (Error err = reader.readInteger(fromIndex))
28894c28d28SJez Ng       return err;
28994c28d28SJez Ng     if (Error err = reader.readInteger(toIndex))
29094c28d28SJez Ng       return err;
29194c28d28SJez Ng     if (Error err = reader.readInteger(count))
29294c28d28SJez Ng       return err;
29394c28d28SJez Ng     callGraph.emplace_back(fromIndex, toIndex, count);
29494c28d28SJez Ng   }
29594c28d28SJez Ng   return Error::success();
29694c28d28SJez Ng }
29794c28d28SJez Ng 
2983a1b3c9aSGreg McGary // Parse the sequence of sections within a single LC_SEGMENT(_64).
2993a1b3c9aSGreg McGary // Split each section into subsections.
3003a1b3c9aSGreg McGary template <class SectionHeader>
parseSections(ArrayRef<SectionHeader> sectionHeaders)3013a1b3c9aSGreg McGary void ObjFile::parseSections(ArrayRef<SectionHeader> sectionHeaders) {
3023a1b3c9aSGreg McGary   sections.reserve(sectionHeaders.size());
30304259cdeSJez Ng   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
30404259cdeSJez Ng 
3053a1b3c9aSGreg McGary   for (const SectionHeader &sec : sectionHeaders) {
306681cfeb5SJez Ng     StringRef name =
307681cfeb5SJez Ng         StringRef(sec.sectname, strnlen(sec.sectname, sizeof(sec.sectname)));
308681cfeb5SJez Ng     StringRef segname =
309681cfeb5SJez Ng         StringRef(sec.segname, strnlen(sec.segname, sizeof(sec.segname)));
3102b78ef06SJez Ng     sections.push_back(make<Section>(this, segname, name, sec.flags, sec.addr));
311cc17bfe4SJez Ng     if (sec.align >= 32) {
312681cfeb5SJez Ng       error("alignment " + std::to_string(sec.align) + " of section " + name +
313681cfeb5SJez Ng             " is too large");
314cc17bfe4SJez Ng       continue;
315cc17bfe4SJez Ng     }
316f004ecf6SJez Ng     Section &section = *sections.back();
317681cfeb5SJez Ng     uint32_t align = 1 << sec.align;
318e4b28621SJez Ng     ArrayRef<uint8_t> data = {isZeroFill(sec.flags) ? nullptr
319e4b28621SJez Ng                                                     : buf + sec.offset,
320e4b28621SJez Ng                               static_cast<size_t>(sec.size)};
321681cfeb5SJez Ng 
32291ace9f0SJez Ng     auto splitRecords = [&](int recordSize) -> void {
3233f35dd06SVy Nguyen       if (data.empty())
32491ace9f0SJez Ng         return;
325f004ecf6SJez Ng       Subsections &subsections = section.subsections;
3263a1b3c9aSGreg McGary       subsections.reserve(data.size() / recordSize);
3272b78ef06SJez Ng       for (uint64_t off = 0; off < data.size(); off += recordSize) {
32891ace9f0SJez Ng         auto *isec = make<ConcatInputSection>(
3292b78ef06SJez Ng             section, data.slice(off, recordSize), align);
3302b78ef06SJez Ng         subsections.push_back({off, isec});
33191ace9f0SJez Ng       }
332e183bf8eSJez Ng       section.doneSplitting = true;
33391ace9f0SJez Ng     };
33491ace9f0SJez Ng 
335a8a6e5b0SLeonard Grey     if (sectionType(sec.flags) == S_CSTRING_LITERALS ||
336a8a6e5b0SLeonard Grey         (config->dedupLiterals && isWordLiteralSection(sec.flags))) {
337a8a6e5b0SLeonard Grey       if (sec.nreloc && config->dedupLiterals)
33804259cdeSJez Ng         fatal(toString(this) + " contains relocations in " + sec.segname + "," +
33904259cdeSJez Ng               sec.sectname +
34004259cdeSJez Ng               ", so LLD cannot deduplicate literals. Try re-running without "
34104259cdeSJez Ng               "--deduplicate-literals.");
34204259cdeSJez Ng 
3435d88f2ddSJez Ng       InputSection *isec;
3445d88f2ddSJez Ng       if (sectionType(sec.flags) == S_CSTRING_LITERALS) {
3452b78ef06SJez Ng         isec = make<CStringInputSection>(section, data, align);
3465d88f2ddSJez Ng         // FIXME: parallelize this?
3475d88f2ddSJez Ng         cast<CStringInputSection>(isec)->splitIntoPieces();
3485d88f2ddSJez Ng       } else {
3492b78ef06SJez Ng         isec = make<WordLiteralInputSection>(section, data, align);
3505d88f2ddSJez Ng       }
351f004ecf6SJez Ng       section.subsections.push_back({0, isec});
35291ace9f0SJez Ng     } else if (auto recordSize = getRecordSize(segname, name)) {
35391ace9f0SJez Ng       splitRecords(*recordSize);
354403d61aeSJez Ng     } else if (name == section_names::ehFrame &&
355e183bf8eSJez Ng                segname == segment_names::text) {
356e183bf8eSJez Ng       splitEhFrames(data, *sections.back());
35708d55c5cSVincent Lee     } else if (segname == segment_names::llvm) {
35894c28d28SJez Ng       if (config->callGraphProfileSort && name == section_names::cgProfile)
35994c28d28SJez Ng         checkError(parseCallGraph(data, callGraph));
36008d55c5cSVincent Lee       // ld64 does not appear to emit contents from sections within the __LLVM
36108d55c5cSVincent Lee       // segment. Symbols within those sections point to bitcode metadata
36208d55c5cSVincent Lee       // instead of actual symbols. Global symbols within those sections could
3639408b75eSJez Ng       // have the same name without causing duplicate symbol errors. To avoid
3649408b75eSJez Ng       // spurious duplicate symbol errors, we do not parse these sections.
36508d55c5cSVincent Lee       // TODO: Evaluate whether the bitcode metadata is needed.
366d23da0ecSJez Ng     } else if (name == section_names::objCImageInfo &&
367d23da0ecSJez Ng                segname == segment_names::data) {
368d23da0ecSJez Ng       objCImageInfo = data;
36904259cdeSJez Ng     } else {
370e29dc0c6SAlex Borcan       if (name == section_names::addrSig)
371e29dc0c6SAlex Borcan         addrSigSection = sections.back();
372e29dc0c6SAlex Borcan 
3732b78ef06SJez Ng       auto *isec = make<ConcatInputSection>(section, data, align);
37415dc93e6SVincent Lee       if (isDebugSection(isec->getFlags()) &&
37515dc93e6SVincent Lee           isec->getSegName() == segment_names::dwarf) {
376863f7a74SJez Ng         // Instead of emitting DWARF sections, we emit STABS symbols to the
377863f7a74SJez Ng         // object files that contain them. We filter them out early to avoid
3789408b75eSJez Ng         // parsing their relocations unnecessarily.
379863f7a74SJez Ng         debugSections.push_back(isec);
38015dc93e6SVincent Lee       } else {
381f004ecf6SJez Ng         section.subsections.push_back({0, isec});
382863f7a74SJez Ng       }
3834eb6f485SJez Ng     }
3846acd3003SFangrui Song   }
38504259cdeSJez Ng }
3866acd3003SFangrui Song 
splitEhFrames(ArrayRef<uint8_t> data,Section & ehFrameSection)387e183bf8eSJez Ng void ObjFile::splitEhFrames(ArrayRef<uint8_t> data, Section &ehFrameSection) {
388d6e5bfceSJez Ng   EhReader reader(this, data, /*dataOff=*/0);
389e183bf8eSJez Ng   size_t off = 0;
390e183bf8eSJez Ng   while (off < reader.size()) {
391e183bf8eSJez Ng     uint64_t frameOff = off;
392e183bf8eSJez Ng     uint64_t length = reader.readLength(&off);
393e183bf8eSJez Ng     if (length == 0)
394e183bf8eSJez Ng       break;
395e183bf8eSJez Ng     uint64_t fullLength = length + (off - frameOff);
396e183bf8eSJez Ng     off += length;
397e183bf8eSJez Ng     // We hard-code an alignment of 1 here because we don't actually want our
398e183bf8eSJez Ng     // EH frames to be aligned to the section alignment. EH frame decoders don't
399e183bf8eSJez Ng     // expect this alignment. Moreover, each EH frame must start where the
400e183bf8eSJez Ng     // previous one ends, and where it ends is indicated by the length field.
401e183bf8eSJez Ng     // Unless we update the length field (troublesome), we should keep the
402e183bf8eSJez Ng     // alignment to 1.
403e183bf8eSJez Ng     // Note that we still want to preserve the alignment of the overall section,
404e183bf8eSJez Ng     // just not of the individual EH frames.
405e183bf8eSJez Ng     ehFrameSection.subsections.push_back(
406e183bf8eSJez Ng         {frameOff, make<ConcatInputSection>(ehFrameSection,
407e183bf8eSJez Ng                                             data.slice(frameOff, fullLength),
408e183bf8eSJez Ng                                             /*align=*/1)});
409e183bf8eSJez Ng   }
410e183bf8eSJez Ng   ehFrameSection.doneSplitting = true;
411e183bf8eSJez Ng }
412e183bf8eSJez Ng 
413e183bf8eSJez Ng template <class T>
findContainingSection(const std::vector<Section * > & sections,T * offset)414e183bf8eSJez Ng static Section *findContainingSection(const std::vector<Section *> &sections,
415e183bf8eSJez Ng                                       T *offset) {
416e183bf8eSJez Ng   static_assert(std::is_same<uint64_t, T>::value ||
417e183bf8eSJez Ng                     std::is_same<uint32_t, T>::value,
418e183bf8eSJez Ng                 "unexpected type for offset");
419e183bf8eSJez Ng   auto it = std::prev(llvm::upper_bound(
420e183bf8eSJez Ng       sections, *offset,
421e183bf8eSJez Ng       [](uint64_t value, const Section *sec) { return value < sec->addr; }));
422e183bf8eSJez Ng   *offset -= (*it)->addr;
423e183bf8eSJez Ng   return *it;
424e183bf8eSJez Ng }
425e183bf8eSJez Ng 
4264eb6f485SJez Ng // Find the subsection corresponding to the greatest section offset that is <=
4274eb6f485SJez Ng // that of the given offset.
4284eb6f485SJez Ng //
4294eb6f485SJez Ng // offset: an offset relative to the start of the original InputSection (before
4304eb6f485SJez Ng // any subsection splitting has occurred). It will be updated to represent the
4314eb6f485SJez Ng // same location as an offset relative to the start of the containing
4324eb6f485SJez Ng // subsection.
43393bf271fSShoaib Meenai template <class T>
findContainingSubsection(const Section & section,T * offset)4341c0234dfSJez Ng static InputSection *findContainingSubsection(const Section &section,
43593bf271fSShoaib Meenai                                               T *offset) {
43634d15eacSVy Nguyen   static_assert(std::is_same<uint64_t, T>::value ||
43734d15eacSVy Nguyen                     std::is_same<uint32_t, T>::value,
43834d15eacSVy Nguyen                 "unexpected type for offset");
439f1e4e2fbSAlexander Shaposhnikov   auto it = std::prev(llvm::upper_bound(
4401c0234dfSJez Ng       section.subsections, *offset,
4413a1b3c9aSGreg McGary       [](uint64_t value, Subsection subsec) { return value < subsec.offset; }));
442f1e4e2fbSAlexander Shaposhnikov   *offset -= it->offset;
443f1e4e2fbSAlexander Shaposhnikov   return it->isec;
4446acd3003SFangrui Song }
4456acd3003SFangrui Song 
446da6b6b3cSJez Ng // Find a symbol at offset `off` within `isec`.
findSymbolAtOffset(const ConcatInputSection * isec,uint64_t off)447da6b6b3cSJez Ng static Defined *findSymbolAtOffset(const ConcatInputSection *isec,
448da6b6b3cSJez Ng                                    uint64_t off) {
449da6b6b3cSJez Ng   auto it = llvm::lower_bound(isec->symbols, off, [](Defined *d, uint64_t off) {
450da6b6b3cSJez Ng     return d->value < off;
451da6b6b3cSJez Ng   });
452da6b6b3cSJez Ng   // The offset should point at the exact address of a symbol (with no addend.)
453da6b6b3cSJez Ng   if (it == isec->symbols.end() || (*it)->value != off) {
454da6b6b3cSJez Ng     assert(isec->wasCoalesced);
455da6b6b3cSJez Ng     return nullptr;
456da6b6b3cSJez Ng   }
457da6b6b3cSJez Ng   return *it;
458da6b6b3cSJez Ng }
459da6b6b3cSJez Ng 
460a3f67f09SDaniel Bertalan // Linker optimization hints mark a sequence of instructions used for
461a3f67f09SDaniel Bertalan // synthesizing an address which that be transformed into a faster sequence. The
462a3f67f09SDaniel Bertalan // transformations depend on conditions that are determined at link time, like
463a3f67f09SDaniel Bertalan // the distance to the referenced symbol or its alignment.
464a3f67f09SDaniel Bertalan //
465a3f67f09SDaniel Bertalan // Each hint has a type and refers to 2 or 3 instructions. Each of those
466a3f67f09SDaniel Bertalan // instructions must have a corresponding relocation. After addresses have been
467a3f67f09SDaniel Bertalan // finalized and relocations have been performed, we check if the requirements
468a3f67f09SDaniel Bertalan // hold, and perform the optimizations if they do.
469a3f67f09SDaniel Bertalan //
470a3f67f09SDaniel Bertalan // Similar linker relaxations exist for ELF as well, with the difference being
471a3f67f09SDaniel Bertalan // that the explicit marking allows for the relaxation of non-consecutive
472a3f67f09SDaniel Bertalan // relocations too.
473a3f67f09SDaniel Bertalan //
474a3f67f09SDaniel Bertalan // The specific types of hints are documented in Arch/ARM64.cpp
parseOptimizationHints(ArrayRef<uint8_t> data)475a3f67f09SDaniel Bertalan void ObjFile::parseOptimizationHints(ArrayRef<uint8_t> data) {
476a3f67f09SDaniel Bertalan   auto expectedArgCount = [](uint8_t type) {
477a3f67f09SDaniel Bertalan     switch (type) {
478a3f67f09SDaniel Bertalan     case LOH_ARM64_ADRP_ADRP:
479a3f67f09SDaniel Bertalan     case LOH_ARM64_ADRP_LDR:
480a3f67f09SDaniel Bertalan     case LOH_ARM64_ADRP_ADD:
481a3f67f09SDaniel Bertalan     case LOH_ARM64_ADRP_LDR_GOT:
482a3f67f09SDaniel Bertalan       return 2;
483a3f67f09SDaniel Bertalan     case LOH_ARM64_ADRP_ADD_LDR:
484a3f67f09SDaniel Bertalan     case LOH_ARM64_ADRP_ADD_STR:
485a3f67f09SDaniel Bertalan     case LOH_ARM64_ADRP_LDR_GOT_LDR:
486a3f67f09SDaniel Bertalan     case LOH_ARM64_ADRP_LDR_GOT_STR:
487a3f67f09SDaniel Bertalan       return 3;
488a3f67f09SDaniel Bertalan     }
489a3f67f09SDaniel Bertalan     return -1;
490a3f67f09SDaniel Bertalan   };
491a3f67f09SDaniel Bertalan 
492a3f67f09SDaniel Bertalan   // Each hint contains at least 4 ULEB128-encoded fields, so in the worst case,
493a3f67f09SDaniel Bertalan   // there are data.size() / 4 LOHs. It's a huge overestimation though, as
494a3f67f09SDaniel Bertalan   // offsets are unlikely to fall in the 0-127 byte range, so we pre-allocate
495a3f67f09SDaniel Bertalan   // half as much.
496a3f67f09SDaniel Bertalan   optimizationHints.reserve(data.size() / 8);
497a3f67f09SDaniel Bertalan 
498a3f67f09SDaniel Bertalan   for (const uint8_t *p = data.begin(); p < data.end();) {
499a3f67f09SDaniel Bertalan     const ptrdiff_t inputOffset = p - data.begin();
500a3f67f09SDaniel Bertalan     unsigned int n = 0;
501a3f67f09SDaniel Bertalan     uint8_t type = decodeULEB128(p, &n, data.end());
502a3f67f09SDaniel Bertalan     p += n;
503a3f67f09SDaniel Bertalan 
504a3f67f09SDaniel Bertalan     // An entry of type 0 terminates the list.
505a3f67f09SDaniel Bertalan     if (type == 0)
506a3f67f09SDaniel Bertalan       break;
507a3f67f09SDaniel Bertalan 
508a3f67f09SDaniel Bertalan     int expectedCount = expectedArgCount(type);
509a3f67f09SDaniel Bertalan     if (LLVM_UNLIKELY(expectedCount == -1)) {
510a3f67f09SDaniel Bertalan       error("Linker optimization hint at offset " + Twine(inputOffset) +
511a3f67f09SDaniel Bertalan             " has unknown type " + Twine(type));
512a3f67f09SDaniel Bertalan       return;
513a3f67f09SDaniel Bertalan     }
514a3f67f09SDaniel Bertalan 
515a3f67f09SDaniel Bertalan     uint8_t argCount = decodeULEB128(p, &n, data.end());
516a3f67f09SDaniel Bertalan     p += n;
517a3f67f09SDaniel Bertalan 
518a3f67f09SDaniel Bertalan     if (LLVM_UNLIKELY(argCount != expectedCount)) {
519a3f67f09SDaniel Bertalan       error("Linker optimization hint at offset " + Twine(inputOffset) +
520a3f67f09SDaniel Bertalan             " has " + Twine(argCount) + " arguments instead of the expected " +
521a3f67f09SDaniel Bertalan             Twine(expectedCount));
522a3f67f09SDaniel Bertalan       return;
523a3f67f09SDaniel Bertalan     }
524a3f67f09SDaniel Bertalan 
525a3f67f09SDaniel Bertalan     uint64_t offset0 = decodeULEB128(p, &n, data.end());
526a3f67f09SDaniel Bertalan     p += n;
527a3f67f09SDaniel Bertalan 
528a3f67f09SDaniel Bertalan     int16_t delta[2];
529a3f67f09SDaniel Bertalan     for (int i = 0; i < argCount - 1; ++i) {
530a3f67f09SDaniel Bertalan       uint64_t address = decodeULEB128(p, &n, data.end());
531a3f67f09SDaniel Bertalan       p += n;
532a3f67f09SDaniel Bertalan       int64_t d = address - offset0;
533a3f67f09SDaniel Bertalan       if (LLVM_UNLIKELY(d > std::numeric_limits<int16_t>::max() ||
534a3f67f09SDaniel Bertalan                         d < std::numeric_limits<int16_t>::min())) {
535a3f67f09SDaniel Bertalan         error("Linker optimization hint at offset " + Twine(inputOffset) +
536a3f67f09SDaniel Bertalan               " has addresses too far apart");
537a3f67f09SDaniel Bertalan         return;
538a3f67f09SDaniel Bertalan       }
539a3f67f09SDaniel Bertalan       delta[i] = d;
540a3f67f09SDaniel Bertalan     }
541a3f67f09SDaniel Bertalan 
542a3f67f09SDaniel Bertalan     optimizationHints.push_back({offset0, {delta[0], delta[1]}, type});
543a3f67f09SDaniel Bertalan   }
544a3f67f09SDaniel Bertalan 
545a3f67f09SDaniel Bertalan   // We sort the per-object vector of optimization hints so each section only
546a3f67f09SDaniel Bertalan   // needs to hold an ArrayRef to a contiguous range of hints.
547a3f67f09SDaniel Bertalan   llvm::sort(optimizationHints,
548a3f67f09SDaniel Bertalan              [](const OptimizationHint &a, const OptimizationHint &b) {
549a3f67f09SDaniel Bertalan                return a.offset0 < b.offset0;
550a3f67f09SDaniel Bertalan              });
551a3f67f09SDaniel Bertalan 
552a3f67f09SDaniel Bertalan   auto section = sections.begin();
553a3f67f09SDaniel Bertalan   auto subsection = (*section)->subsections.begin();
554a3f67f09SDaniel Bertalan   uint64_t subsectionBase = 0;
555a3f67f09SDaniel Bertalan   uint64_t subsectionEnd = 0;
556a3f67f09SDaniel Bertalan 
557a3f67f09SDaniel Bertalan   auto updateAddr = [&]() {
558a3f67f09SDaniel Bertalan     subsectionBase = (*section)->addr + subsection->offset;
559a3f67f09SDaniel Bertalan     subsectionEnd = subsectionBase + subsection->isec->getSize();
560a3f67f09SDaniel Bertalan   };
561a3f67f09SDaniel Bertalan 
562a3f67f09SDaniel Bertalan   auto advanceSubsection = [&]() {
563a3f67f09SDaniel Bertalan     if (section == sections.end())
564a3f67f09SDaniel Bertalan       return;
565a3f67f09SDaniel Bertalan     ++subsection;
566ec315a5fSJez Ng     while (subsection == (*section)->subsections.end()) {
567a3f67f09SDaniel Bertalan       ++section;
568a3f67f09SDaniel Bertalan       if (section == sections.end())
569a3f67f09SDaniel Bertalan         return;
570a3f67f09SDaniel Bertalan       subsection = (*section)->subsections.begin();
571a3f67f09SDaniel Bertalan     }
572a3f67f09SDaniel Bertalan   };
573a3f67f09SDaniel Bertalan 
574a3f67f09SDaniel Bertalan   updateAddr();
575a3f67f09SDaniel Bertalan   auto hintStart = optimizationHints.begin();
576a3f67f09SDaniel Bertalan   for (auto hintEnd = hintStart, end = optimizationHints.end(); hintEnd != end;
577a3f67f09SDaniel Bertalan        ++hintEnd) {
578a3f67f09SDaniel Bertalan     if (hintEnd->offset0 >= subsectionEnd) {
579a3f67f09SDaniel Bertalan       subsection->isec->optimizationHints =
580a3f67f09SDaniel Bertalan           ArrayRef<OptimizationHint>(&*hintStart, hintEnd - hintStart);
581a3f67f09SDaniel Bertalan 
582a3f67f09SDaniel Bertalan       hintStart = hintEnd;
583a3f67f09SDaniel Bertalan       while (hintStart->offset0 >= subsectionEnd) {
584a3f67f09SDaniel Bertalan         advanceSubsection();
585a3f67f09SDaniel Bertalan         if (section == sections.end())
586a3f67f09SDaniel Bertalan           break;
587a3f67f09SDaniel Bertalan         updateAddr();
588ec315a5fSJez Ng         assert(hintStart->offset0 >= subsectionBase);
589a3f67f09SDaniel Bertalan       }
590a3f67f09SDaniel Bertalan     }
591a3f67f09SDaniel Bertalan 
592a3f67f09SDaniel Bertalan     hintEnd->offset0 -= subsectionBase;
593a3f67f09SDaniel Bertalan     for (int i = 0, count = expectedArgCount(hintEnd->type); i < count - 1;
594a3f67f09SDaniel Bertalan          ++i) {
595a3f67f09SDaniel Bertalan       if (LLVM_UNLIKELY(
596a3f67f09SDaniel Bertalan               hintEnd->delta[i] < -static_cast<int64_t>(hintEnd->offset0) ||
597a3f67f09SDaniel Bertalan               hintEnd->delta[i] >=
598a3f67f09SDaniel Bertalan                   static_cast<int64_t>(subsectionEnd - hintEnd->offset0))) {
599a3f67f09SDaniel Bertalan         error("Linker optimization hint spans multiple sections");
600a3f67f09SDaniel Bertalan         return;
601a3f67f09SDaniel Bertalan       }
602a3f67f09SDaniel Bertalan     }
603a3f67f09SDaniel Bertalan   }
604a3f67f09SDaniel Bertalan   if (section != sections.end())
605a3f67f09SDaniel Bertalan     subsection->isec->optimizationHints = ArrayRef<OptimizationHint>(
606a3f67f09SDaniel Bertalan         &*hintStart, optimizationHints.end() - hintStart);
607a3f67f09SDaniel Bertalan }
608a3f67f09SDaniel Bertalan 
6093a1b3c9aSGreg McGary template <class SectionHeader>
validateRelocationInfo(InputFile * file,const SectionHeader & sec,relocation_info rel)6103a1b3c9aSGreg McGary static bool validateRelocationInfo(InputFile *file, const SectionHeader &sec,
6113a9d2f14SGreg McGary                                    relocation_info rel) {
6125433a791SJez Ng   const RelocAttrs &relocAttrs = target->getRelocAttrs(rel.r_type);
6133a9d2f14SGreg McGary   bool valid = true;
614e5d780e0SJez Ng   auto message = [relocAttrs, file, sec, rel, &valid](const Twine &diagnostic) {
6153a9d2f14SGreg McGary     valid = false;
6163a9d2f14SGreg McGary     return (relocAttrs.name + " relocation " + diagnostic + " at offset " +
6173a9d2f14SGreg McGary             std::to_string(rel.r_address) + " of " + sec.segname + "," +
618e5d780e0SJez Ng             sec.sectname + " in " + toString(file))
6193a9d2f14SGreg McGary         .str();
6203a9d2f14SGreg McGary   };
6213a9d2f14SGreg McGary 
6223a9d2f14SGreg McGary   if (!relocAttrs.hasAttr(RelocAttrBits::LOCAL) && !rel.r_extern)
6233a9d2f14SGreg McGary     error(message("must be extern"));
6243a9d2f14SGreg McGary   if (relocAttrs.hasAttr(RelocAttrBits::PCREL) != rel.r_pcrel)
6253a9d2f14SGreg McGary     error(message(Twine("must ") + (rel.r_pcrel ? "not " : "") +
6263a9d2f14SGreg McGary                   "be PC-relative"));
6273a9d2f14SGreg McGary   if (isThreadLocalVariables(sec.flags) &&
6285e851733SJez Ng       !relocAttrs.hasAttr(RelocAttrBits::UNSIGNED))
6293a9d2f14SGreg McGary     error(message("not allowed in thread-local section, must be UNSIGNED"));
6303a9d2f14SGreg McGary   if (rel.r_length < 2 || rel.r_length > 3 ||
6313a9d2f14SGreg McGary       !relocAttrs.hasAttr(static_cast<RelocAttrBits>(1 << rel.r_length))) {
63287104faaSGreg McGary     static SmallVector<StringRef, 4> widths{"0", "4", "8", "4 or 8"};
6333a9d2f14SGreg McGary     error(message("has width " + std::to_string(1 << rel.r_length) +
6343a9d2f14SGreg McGary                   " bytes, but must be " +
6353a9d2f14SGreg McGary                   widths[(static_cast<int>(relocAttrs.bits) >> 2) & 3] +
6363a9d2f14SGreg McGary                   " bytes"));
6373a9d2f14SGreg McGary   }
6383a9d2f14SGreg McGary   return valid;
6393a9d2f14SGreg McGary }
6403a9d2f14SGreg McGary 
6413a1b3c9aSGreg McGary template <class SectionHeader>
parseRelocations(ArrayRef<SectionHeader> sectionHeaders,const SectionHeader & sec,Section & section)6423a1b3c9aSGreg McGary void ObjFile::parseRelocations(ArrayRef<SectionHeader> sectionHeaders,
643c0ec1036SVy Nguyen                                const SectionHeader &sec, Section &section) {
6446acd3003SFangrui Song   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
645d4ec3346SGreg McGary   ArrayRef<relocation_info> relInfos(
646d4ec3346SGreg McGary       reinterpret_cast<const relocation_info *>(buf + sec.reloff), sec.nreloc);
6476acd3003SFangrui Song 
6481c0234dfSJez Ng   Subsections &subsections = section.subsections;
6493a1b3c9aSGreg McGary   auto subsecIt = subsections.rbegin();
650d4ec3346SGreg McGary   for (size_t i = 0; i < relInfos.size(); i++) {
651d4ec3346SGreg McGary     // Paired relocations serve as Mach-O's method for attaching a
652d4ec3346SGreg McGary     // supplemental datum to a primary relocation record. ELF does not
653d4ec3346SGreg McGary     // need them because the *_RELOC_RELA records contain the extra
654d4ec3346SGreg McGary     // addend field, vs. *_RELOC_REL which omit the addend.
655d4ec3346SGreg McGary     //
656d4ec3346SGreg McGary     // The {X86_64,ARM64}_RELOC_SUBTRACTOR record holds the subtrahend,
657d4ec3346SGreg McGary     // and the paired *_RELOC_UNSIGNED record holds the minuend. The
6583a9d2f14SGreg McGary     // datum for each is a symbolic address. The result is the offset
6593a9d2f14SGreg McGary     // between two addresses.
660d4ec3346SGreg McGary     //
661d4ec3346SGreg McGary     // The ARM64_RELOC_ADDEND record holds the addend, and the paired
662d4ec3346SGreg McGary     // ARM64_RELOC_BRANCH26 or ARM64_RELOC_PAGE21/PAGEOFF12 holds the
663d4ec3346SGreg McGary     // base symbolic address.
664d4ec3346SGreg McGary     //
665d4ec3346SGreg McGary     // Note: X86 does not use *_RELOC_ADDEND because it can embed an
666d4ec3346SGreg McGary     // addend into the instruction stream. On X86, a relocatable address
667d4ec3346SGreg McGary     // field always occupies an entire contiguous sequence of byte(s),
668d4ec3346SGreg McGary     // so there is no need to merge opcode bits with address
669d4ec3346SGreg McGary     // bits. Therefore, it's easy and convenient to store addends in the
670d4ec3346SGreg McGary     // instruction-stream bytes that would otherwise contain zeroes. By
671d4ec3346SGreg McGary     // contrast, RISC ISAs such as ARM64 mix opcode bits with with
672d4ec3346SGreg McGary     // address bits so that bitwise arithmetic is necessary to extract
673d4ec3346SGreg McGary     // and insert them. Storing addends in the instruction stream is
674d4ec3346SGreg McGary     // possible, but inconvenient and more costly at link time.
675d4ec3346SGreg McGary 
6763a9d2f14SGreg McGary     relocation_info relInfo = relInfos[i];
6779cc489a4SGreg McGary     bool isSubtrahend =
6789cc489a4SGreg McGary         target->hasAttr(relInfo.r_type, RelocAttrBits::SUBTRAHEND);
6799cc489a4SGreg McGary     int64_t pairedAddend = 0;
6803a9d2f14SGreg McGary     if (target->hasAttr(relInfo.r_type, RelocAttrBits::ADDEND)) {
6813a9d2f14SGreg McGary       pairedAddend = SignExtend64<24>(relInfo.r_symbolnum);
6823a9d2f14SGreg McGary       relInfo = relInfos[++i];
6833a9d2f14SGreg McGary     }
684d4ec3346SGreg McGary     assert(i < relInfos.size());
685e5d780e0SJez Ng     if (!validateRelocationInfo(this, sec, relInfo))
6863a9d2f14SGreg McGary       continue;
687d4ec3346SGreg McGary     if (relInfo.r_address & R_SCATTERED)
6884eb6f485SJez Ng       fatal("TODO: Scattered relocations not supported");
6894eb6f485SJez Ng 
690817d98d8SJez Ng     int64_t embeddedAddend = target->getEmbeddedAddend(mb, sec.offset, relInfo);
69182b3da6fSJez Ng     assert(!(embeddedAddend && pairedAddend));
692dc8bee92SJez Ng     int64_t totalAddend = pairedAddend + embeddedAddend;
6934eb6f485SJez Ng     Reloc r;
6941a3ef041SGreg McGary     r.type = relInfo.r_type;
6951a3ef041SGreg McGary     r.pcrel = relInfo.r_pcrel;
6961a3ef041SGreg McGary     r.length = relInfo.r_length;
697d4ec3346SGreg McGary     r.offset = relInfo.r_address;
6981a3ef041SGreg McGary     if (relInfo.r_extern) {
6991a3ef041SGreg McGary       r.referent = symbols[relInfo.r_symbolnum];
7001aa29dffSJez Ng       r.addend = isSubtrahend ? 0 : totalAddend;
701198b0c57SJez Ng     } else {
7021aa29dffSJez Ng       assert(!isSubtrahend);
7033a1b3c9aSGreg McGary       const SectionHeader &referentSecHead =
7043a1b3c9aSGreg McGary           sectionHeaders[relInfo.r_symbolnum - 1];
705f1e4e2fbSAlexander Shaposhnikov       uint64_t referentOffset;
7061a3ef041SGreg McGary       if (relInfo.r_pcrel) {
7074eb6f485SJez Ng         // The implicit addend for pcrel section relocations is the pcrel offset
708fcde378dSJez Ng         // in terms of the addresses in the input file. Here we adjust it so
7091a3ef041SGreg McGary         // that it describes the offset from the start of the referent section.
710e8a30583SJez Ng         // FIXME This logic was written around x86_64 behavior -- ARM64 doesn't
711e8a30583SJez Ng         // have pcrel section relocations. We may want to factor this out into
712e8a30583SJez Ng         // the arch-specific .cpp file.
713f083f652SJez Ng         assert(target->hasAttr(r.type, RelocAttrBits::BYTE4));
7143a1b3c9aSGreg McGary         referentOffset = sec.addr + relInfo.r_address + 4 + totalAddend -
7153a1b3c9aSGreg McGary                          referentSecHead.addr;
716fcde378dSJez Ng       } else {
717fcde378dSJez Ng         // The addend for a non-pcrel relocation is its absolute address.
7183a1b3c9aSGreg McGary         referentOffset = totalAddend - referentSecHead.addr;
719fcde378dSJez Ng       }
7201c0234dfSJez Ng       r.referent = findContainingSubsection(*sections[relInfo.r_symbolnum - 1],
7211c0234dfSJez Ng                                             &referentOffset);
7221a3ef041SGreg McGary       r.addend = referentOffset;
7234eb6f485SJez Ng     }
7244eb6f485SJez Ng 
725bcaf57caSJez Ng     // Find the subsection that this relocation belongs to.
726bcaf57caSJez Ng     // Though not required by the Mach-O format, clang and gcc seem to emit
727bcaf57caSJez Ng     // relocations in order, so let's take advantage of it. However, ld64 emits
728bcaf57caSJez Ng     // unsorted relocations (in `-r` mode), so we have a fallback for that
729bcaf57caSJez Ng     // uncommon case.
730bcaf57caSJez Ng     InputSection *subsec;
7313a1b3c9aSGreg McGary     while (subsecIt != subsections.rend() && subsecIt->offset > r.offset)
732bcaf57caSJez Ng       ++subsecIt;
7333a1b3c9aSGreg McGary     if (subsecIt == subsections.rend() ||
734bcaf57caSJez Ng         subsecIt->offset + subsecIt->isec->getSize() <= r.offset) {
7351c0234dfSJez Ng       subsec = findContainingSubsection(section, &r.offset);
736bcaf57caSJez Ng       // Now that we know the relocs are unsorted, avoid trying the 'fast path'
737bcaf57caSJez Ng       // for the other relocations.
7383a1b3c9aSGreg McGary       subsecIt = subsections.rend();
739bcaf57caSJez Ng     } else {
740bcaf57caSJez Ng       subsec = subsecIt->isec;
741bcaf57caSJez Ng       r.offset -= subsecIt->offset;
742bcaf57caSJez Ng     }
7434eb6f485SJez Ng     subsec->relocs.push_back(r);
744a723db92SJez Ng 
7451aa29dffSJez Ng     if (isSubtrahend) {
7461aa29dffSJez Ng       relocation_info minuendInfo = relInfos[++i];
747a723db92SJez Ng       // SUBTRACTOR relocations should always be followed by an UNSIGNED one
7481aa29dffSJez Ng       // attached to the same address.
7491aa29dffSJez Ng       assert(target->hasAttr(minuendInfo.r_type, RelocAttrBits::UNSIGNED) &&
7501aa29dffSJez Ng              relInfo.r_address == minuendInfo.r_address);
751a723db92SJez Ng       Reloc p;
7521aa29dffSJez Ng       p.type = minuendInfo.r_type;
7531aa29dffSJez Ng       if (minuendInfo.r_extern) {
7541aa29dffSJez Ng         p.referent = symbols[minuendInfo.r_symbolnum];
7551aa29dffSJez Ng         p.addend = totalAddend;
7561aa29dffSJez Ng       } else {
7571aa29dffSJez Ng         uint64_t referentOffset =
7581aa29dffSJez Ng             totalAddend - sectionHeaders[minuendInfo.r_symbolnum - 1].addr;
7591c0234dfSJez Ng         p.referent = findContainingSubsection(
7601c0234dfSJez Ng             *sections[minuendInfo.r_symbolnum - 1], &referentOffset);
7611aa29dffSJez Ng         p.addend = referentOffset;
7621aa29dffSJez Ng       }
763a723db92SJez Ng       subsec->relocs.push_back(p);
764a723db92SJez Ng     }
7656acd3003SFangrui Song   }
7666acd3003SFangrui Song }
7674eb6f485SJez Ng 
768817d98d8SJez Ng template <class NList>
createDefined(const NList & sym,StringRef name,InputSection * isec,uint64_t value,uint64_t size,bool forceHidden)769817d98d8SJez Ng static macho::Symbol *createDefined(const NList &sym, StringRef name,
770817d98d8SJez Ng                                     InputSection *isec, uint64_t value,
771595fc59fSDaniel Bertalan                                     uint64_t size, bool forceHidden) {
77213f439a1SNico Weber   // Symbol scope is determined by sym.n_type & (N_EXT | N_PEXT):
773a38ebed2SNico Weber   // N_EXT: Global symbols. These go in the symbol table during the link,
774a38ebed2SNico Weber   //        and also in the export table of the output so that the dynamic
775a38ebed2SNico Weber   //        linker sees them.
776a38ebed2SNico Weber   // N_EXT | N_PEXT: Linkage unit (think: dylib) scoped. These go in the
777a38ebed2SNico Weber   //                 symbol table during the link so that duplicates are
778a38ebed2SNico Weber   //                 either reported (for non-weak symbols) or merged
779a38ebed2SNico Weber   //                 (for weak symbols), but they do not go in the export
780a38ebed2SNico Weber   //                 table of the output.
7814c49f9ceSJez Ng   // N_PEXT: llvm-mc does not emit these, but `ld -r` (wherein ld64 emits
7824c49f9ceSJez Ng   //         object files) may produce them. LLD does not yet support -r.
7834c49f9ceSJez Ng   //         These are translation-unit scoped, identical to the `0` case.
784a38ebed2SNico Weber   // 0: Translation-unit scoped. These are not in the symbol table during
785a38ebed2SNico Weber   //    link, and not in the export table of the output either.
786a38ebed2SNico Weber   bool isWeakDefCanBeHidden =
787a38ebed2SNico Weber       (sym.n_desc & (N_WEAK_DEF | N_WEAK_REF)) == (N_WEAK_DEF | N_WEAK_REF);
78813f439a1SNico Weber 
7894c49f9ceSJez Ng   if (sym.n_type & N_EXT) {
790595fc59fSDaniel Bertalan     // -load_hidden makes us treat global symbols as linkage unit scoped.
791595fc59fSDaniel Bertalan     // Duplicates are reported but the symbol does not go in the export trie.
792595fc59fSDaniel Bertalan     bool isPrivateExtern = sym.n_type & N_PEXT || forceHidden;
793595fc59fSDaniel Bertalan 
794a38ebed2SNico Weber     // lld's behavior for merging symbols is slightly different from ld64:
795a38ebed2SNico Weber     // ld64 picks the winning symbol based on several criteria (see
796a38ebed2SNico Weber     // pickBetweenRegularAtoms() in ld64's SymbolTable.cpp), while lld
797a38ebed2SNico Weber     // just merges metadata and keeps the contents of the first symbol
798a38ebed2SNico Weber     // with that name (see SymbolTable::addDefined). For:
799a38ebed2SNico Weber     // * inline function F in a TU built with -fvisibility-inlines-hidden
800a38ebed2SNico Weber     // * and inline function F in another TU built without that flag
801a38ebed2SNico Weber     // ld64 will pick the one from the file built without
802a38ebed2SNico Weber     // -fvisibility-inlines-hidden.
803a38ebed2SNico Weber     // lld will instead pick the one listed first on the link command line and
804a38ebed2SNico Weber     // give it visibility as if the function was built without
805a38ebed2SNico Weber     // -fvisibility-inlines-hidden.
806a38ebed2SNico Weber     // If both functions have the same contents, this will have the same
807a38ebed2SNico Weber     // behavior. If not, it won't, but the input had an ODR violation in
808a38ebed2SNico Weber     // that case.
809a38ebed2SNico Weber     //
810a38ebed2SNico Weber     // Similarly, merging a symbol
811a38ebed2SNico Weber     // that's isPrivateExtern and not isWeakDefCanBeHidden with one
812a38ebed2SNico Weber     // that's not isPrivateExtern but isWeakDefCanBeHidden technically
813a38ebed2SNico Weber     // should produce one
814a38ebed2SNico Weber     // that's not isPrivateExtern but isWeakDefCanBeHidden. That matters
815a38ebed2SNico Weber     // with ld64's semantics, because it means the non-private-extern
816a38ebed2SNico Weber     // definition will continue to take priority if more private extern
817a38ebed2SNico Weber     // definitions are encountered. With lld's semantics there's no observable
8189b29dae3SVy Nguyen     // difference between a symbol that's isWeakDefCanBeHidden(autohide) or one
8199b29dae3SVy Nguyen     // that's privateExtern -- neither makes it into the dynamic symbol table,
8209b29dae3SVy Nguyen     // unless the autohide symbol is explicitly exported.
8219b29dae3SVy Nguyen     // But if a symbol is both privateExtern and autohide then it can't
8229b29dae3SVy Nguyen     // be exported.
8239b29dae3SVy Nguyen     // So we nullify the autohide flag when privateExtern is present
8249b29dae3SVy Nguyen     // and promote the symbol to privateExtern when it is not already.
8259b29dae3SVy Nguyen     if (isWeakDefCanBeHidden && isPrivateExtern)
8269b29dae3SVy Nguyen       isWeakDefCanBeHidden = false;
8279b29dae3SVy Nguyen     else if (isWeakDefCanBeHidden)
828a38ebed2SNico Weber       isPrivateExtern = true;
829a5645513SNico Weber     return symtab->addDefined(
830f6b6e721SJez Ng         name, isec->getFile(), isec, value, size, sym.n_desc & N_WEAK_DEF,
831a5645513SNico Weber         isPrivateExtern, sym.n_desc & N_ARM_THUMB_DEF,
8329b29dae3SVy Nguyen         sym.n_desc & REFERENCED_DYNAMICALLY, sym.n_desc & N_NO_DEAD_STRIP,
8339b29dae3SVy Nguyen         isWeakDefCanBeHidden);
83413f439a1SNico Weber   }
835a38ebed2SNico Weber   assert(!isWeakDefCanBeHidden &&
836a38ebed2SNico Weber          "weak_def_can_be_hidden on already-hidden symbol?");
837e183bf8eSJez Ng   bool includeInSymtab =
838e183bf8eSJez Ng       !name.startswith("l") && !name.startswith("L") && !isEhFrameSection(isec);
83957501e51SAlexander Shaposhnikov   return make<Defined>(
840f6b6e721SJez Ng       name, isec->getFile(), isec, value, size, sym.n_desc & N_WEAK_DEF,
8411cff723fSJez Ng       /*isExternal=*/false, /*isPrivateExtern=*/false, includeInSymtab,
842a5645513SNico Weber       sym.n_desc & N_ARM_THUMB_DEF, sym.n_desc & REFERENCED_DYNAMICALLY,
843a5645513SNico Weber       sym.n_desc & N_NO_DEAD_STRIP);
84462a3f0c9SJez Ng }
84562a3f0c9SJez Ng 
84662a3f0c9SJez Ng // Absolute symbols are defined symbols that do not have an associated
84762a3f0c9SJez Ng // InputSection. They cannot be weak.
848817d98d8SJez Ng template <class NList>
createAbsolute(const NList & sym,InputFile * file,StringRef name,bool forceHidden)849817d98d8SJez Ng static macho::Symbol *createAbsolute(const NList &sym, InputFile *file,
850595fc59fSDaniel Bertalan                                      StringRef name, bool forceHidden) {
8514c49f9ceSJez Ng   if (sym.n_type & N_EXT) {
852595fc59fSDaniel Bertalan     bool isPrivateExtern = sym.n_type & N_PEXT || forceHidden;
85311a0d236SJez Ng     return symtab->addDefined(
85411a0d236SJez Ng         name, file, nullptr, sym.n_value, /*size=*/0,
855595fc59fSDaniel Bertalan         /*isWeakDef=*/false, isPrivateExtern, sym.n_desc & N_ARM_THUMB_DEF,
8569b29dae3SVy Nguyen         /*isReferencedDynamically=*/false, sym.n_desc & N_NO_DEAD_STRIP,
8579b29dae3SVy Nguyen         /*isWeakDefCanBeHidden=*/false);
85813f439a1SNico Weber   }
859f6ad0453SAlexander Shaposhnikov   return make<Defined>(name, file, nullptr, sym.n_value, /*size=*/0,
860f6ad0453SAlexander Shaposhnikov                        /*isWeakDef=*/false,
86105c5363bSJez Ng                        /*isExternal=*/false, /*isPrivateExtern=*/false,
8621cff723fSJez Ng                        /*includeInSymtab=*/true, sym.n_desc & N_ARM_THUMB_DEF,
863a5645513SNico Weber                        /*isReferencedDynamically=*/false,
864a5645513SNico Weber                        sym.n_desc & N_NO_DEAD_STRIP);
86562a3f0c9SJez Ng }
86662a3f0c9SJez Ng 
867817d98d8SJez Ng template <class NList>
parseNonSectionSymbol(const NList & sym,StringRef name)868817d98d8SJez Ng macho::Symbol *ObjFile::parseNonSectionSymbol(const NList &sym,
86962a3f0c9SJez Ng                                               StringRef name) {
87062a3f0c9SJez Ng   uint8_t type = sym.n_type & N_TYPE;
871595fc59fSDaniel Bertalan   bool isPrivateExtern = sym.n_type & N_PEXT || forceHidden;
87262a3f0c9SJez Ng   switch (type) {
87362a3f0c9SJez Ng   case N_UNDF:
87462a3f0c9SJez Ng     return sym.n_value == 0
875163dcd85SJez Ng                ? symtab->addUndefined(name, this, sym.n_desc & N_WEAK_REF)
87662a3f0c9SJez Ng                : symtab->addCommon(name, this, sym.n_value,
87713f439a1SNico Weber                                    1 << GET_COMM_ALIGN(sym.n_desc),
878595fc59fSDaniel Bertalan                                    isPrivateExtern);
87962a3f0c9SJez Ng   case N_ABS:
880595fc59fSDaniel Bertalan     return createAbsolute(sym, this, name, forceHidden);
88162a3f0c9SJez Ng   case N_PBUD:
88262a3f0c9SJez Ng   case N_INDR:
88362a3f0c9SJez Ng     error("TODO: support symbols of type " + std::to_string(type));
88462a3f0c9SJez Ng     return nullptr;
88562a3f0c9SJez Ng   case N_SECT:
88662a3f0c9SJez Ng     llvm_unreachable(
88762a3f0c9SJez Ng         "N_SECT symbols should not be passed to parseNonSectionSymbol");
88862a3f0c9SJez Ng   default:
88962a3f0c9SJez Ng     llvm_unreachable("invalid symbol type");
89062a3f0c9SJez Ng   }
89162a3f0c9SJez Ng }
89262a3f0c9SJez Ng 
isUndef(const NList & sym)8933f35dd06SVy Nguyen template <class NList> static bool isUndef(const NList &sym) {
894fbb45947SNico Weber   return (sym.n_type & N_TYPE) == N_UNDF && sym.n_value == 0;
895fbb45947SNico Weber }
896fbb45947SNico Weber 
897817d98d8SJez Ng template <class LP>
parseSymbols(ArrayRef<typename LP::section> sectionHeaders,ArrayRef<typename LP::nlist> nList,const char * strtab,bool subsectionsViaSymbols)898817d98d8SJez Ng void ObjFile::parseSymbols(ArrayRef<typename LP::section> sectionHeaders,
899817d98d8SJez Ng                            ArrayRef<typename LP::nlist> nList,
9001e1a3f67SJez Ng                            const char *strtab, bool subsectionsViaSymbols) {
901817d98d8SJez Ng   using NList = typename LP::nlist;
902817d98d8SJez Ng 
903ceec6107SJez Ng   // Groups indices of the symbols by the sections that contain them.
9043a1b3c9aSGreg McGary   std::vector<std::vector<uint32_t>> symbolsBySection(sections.size());
905f1e4e2fbSAlexander Shaposhnikov   symbols.resize(nList.size());
906fbb45947SNico Weber   SmallVector<unsigned, 32> undefineds;
907ceec6107SJez Ng   for (uint32_t i = 0; i < nList.size(); ++i) {
908817d98d8SJez Ng     const NList &sym = nList[i];
909c7c5a1c9SVy Nguyen 
910c7c5a1c9SVy Nguyen     // Ignore debug symbols for now.
911c7c5a1c9SVy Nguyen     // FIXME: may need special handling.
912c7c5a1c9SVy Nguyen     if (sym.n_type & N_STAB)
913c7c5a1c9SVy Nguyen       continue;
914c7c5a1c9SVy Nguyen 
915ceec6107SJez Ng     if ((sym.n_type & N_TYPE) == N_SECT) {
9162b78ef06SJez Ng       Subsections &subsections = sections[sym.n_sect - 1]->subsections;
9173c19b4f3SJez Ng       // parseSections() may have chosen not to parse this section.
9183a1b3c9aSGreg McGary       if (subsections.empty())
9193c19b4f3SJez Ng         continue;
920ceec6107SJez Ng       symbolsBySection[sym.n_sect - 1].push_back(i);
921fbb45947SNico Weber     } else if (isUndef(sym)) {
922fbb45947SNico Weber       undefineds.push_back(i);
923ceec6107SJez Ng     } else {
924888d0a5eSDaniel Bertalan       symbols[i] = parseNonSectionSymbol(sym, StringRef(strtab + sym.n_strx));
925ceec6107SJez Ng     }
926ceec6107SJez Ng   }
9273c19b4f3SJez Ng 
9283a1b3c9aSGreg McGary   for (size_t i = 0; i < sections.size(); ++i) {
9292b78ef06SJez Ng     Subsections &subsections = sections[i]->subsections;
9303a1b3c9aSGreg McGary     if (subsections.empty())
931ceec6107SJez Ng       continue;
932ceec6107SJez Ng     std::vector<uint32_t> &symbolIndices = symbolsBySection[i];
933ceec6107SJez Ng     uint64_t sectionAddr = sectionHeaders[i].addr;
9347f673fcaSNico Weber     uint32_t sectionAlign = 1u << sectionHeaders[i].align;
935f6ad0453SAlexander Shaposhnikov 
936e183bf8eSJez Ng     // Some sections have already been split into subsections during
937ac2dd06bSJez Ng     // parseSections(), so we simply need to match Symbols to the corresponding
938ac2dd06bSJez Ng     // subsection here.
939e183bf8eSJez Ng     if (sections[i]->doneSplitting) {
940ac2dd06bSJez Ng       for (size_t j = 0; j < symbolIndices.size(); ++j) {
941ac2dd06bSJez Ng         uint32_t symIndex = symbolIndices[j];
942ac2dd06bSJez Ng         const NList &sym = nList[symIndex];
943ac2dd06bSJez Ng         StringRef name = strtab + sym.n_strx;
944ac2dd06bSJez Ng         uint64_t symbolOffset = sym.n_value - sectionAddr;
9453a1b3c9aSGreg McGary         InputSection *isec =
9461c0234dfSJez Ng             findContainingSubsection(*sections[i], &symbolOffset);
947ac2dd06bSJez Ng         if (symbolOffset != 0) {
948f004ecf6SJez Ng           error(toString(*sections[i]) + ":  symbol " + name +
949ac2dd06bSJez Ng                 " at misaligned offset");
950ac2dd06bSJez Ng           continue;
951ac2dd06bSJez Ng         }
952595fc59fSDaniel Bertalan         symbols[symIndex] =
953595fc59fSDaniel Bertalan             createDefined(sym, name, isec, 0, isec->getSize(), forceHidden);
954ac2dd06bSJez Ng       }
955ac2dd06bSJez Ng       continue;
956ac2dd06bSJez Ng     }
957e183bf8eSJez Ng     sections[i]->doneSplitting = true;
958ac2dd06bSJez Ng 
959ac2dd06bSJez Ng     // Calculate symbol sizes and create subsections by splitting the sections
960ac2dd06bSJez Ng     // along symbol boundaries.
9613a1b3c9aSGreg McGary     // We populate subsections by repeatedly splitting the last (highest
9623a1b3c9aSGreg McGary     // address) subsection.
963ac2dd06bSJez Ng     llvm::stable_sort(symbolIndices, [&](uint32_t lhs, uint32_t rhs) {
964ac2dd06bSJez Ng       return nList[lhs].n_value < nList[rhs].n_value;
965ac2dd06bSJez Ng     });
966ceec6107SJez Ng     for (size_t j = 0; j < symbolIndices.size(); ++j) {
967ceec6107SJez Ng       uint32_t symIndex = symbolIndices[j];
968ceec6107SJez Ng       const NList &sym = nList[symIndex];
969ceec6107SJez Ng       StringRef name = strtab + sym.n_strx;
9709cc489a4SGreg McGary       Subsection &subsec = subsections.back();
9713a1b3c9aSGreg McGary       InputSection *isec = subsec.isec;
972ceec6107SJez Ng 
9733a1b3c9aSGreg McGary       uint64_t subsecAddr = sectionAddr + subsec.offset;
9749777f3fdSMuhammad Omair Javaid       size_t symbolOffset = sym.n_value - subsecAddr;
975ceec6107SJez Ng       uint64_t symbolSize =
976ceec6107SJez Ng           j + 1 < symbolIndices.size()
977ceec6107SJez Ng               ? nList[symbolIndices[j + 1]].n_value - sym.n_value
978ceec6107SJez Ng               : isec->data.size() - symbolOffset;
97904259cdeSJez Ng       // There are 4 cases where we do not need to create a new subsection:
980ceec6107SJez Ng       //   1. If the input file does not use subsections-via-symbols.
981ceec6107SJez Ng       //   2. Multiple symbols at the same address only induce one subsection.
982d5a70db1SNico Weber       //      (The symbolOffset == 0 check covers both this case as well as
983d5a70db1SNico Weber       //      the first loop iteration.)
984ceec6107SJez Ng       //   3. Alternative entry points do not induce new subsections.
98504259cdeSJez Ng       //   4. If we have a literal section (e.g. __cstring and __literal4).
986ceec6107SJez Ng       if (!subsectionsViaSymbols || symbolOffset == 0 ||
98704259cdeSJez Ng           sym.n_desc & N_ALT_ENTRY || !isa<ConcatInputSection>(isec)) {
988595fc59fSDaniel Bertalan         symbols[symIndex] = createDefined(sym, name, isec, symbolOffset,
989595fc59fSDaniel Bertalan                                           symbolSize, forceHidden);
9904eb6f485SJez Ng         continue;
9914eb6f485SJez Ng       }
99204259cdeSJez Ng       auto *concatIsec = cast<ConcatInputSection>(isec);
9934eb6f485SJez Ng 
99404259cdeSJez Ng       auto *nextIsec = make<ConcatInputSection>(*concatIsec);
995a5645513SNico Weber       nextIsec->wasCoalesced = false;
996f6b6e721SJez Ng       if (isZeroFill(isec->getFlags())) {
997f27e4548SGreg McGary         // Zero-fill sections have NULL data.data() non-zero data.size()
998f27e4548SGreg McGary         nextIsec->data = {nullptr, isec->data.size() - symbolOffset};
999f27e4548SGreg McGary         isec->data = {nullptr, symbolOffset};
1000f27e4548SGreg McGary       } else {
1001f27e4548SGreg McGary         nextIsec->data = isec->data.slice(symbolOffset);
1002ceec6107SJez Ng         isec->data = isec->data.slice(0, symbolOffset);
1003f27e4548SGreg McGary       }
10044eb6f485SJez Ng 
10052461804bSJez Ng       // By construction, the symbol will be at offset zero in the new
10062461804bSJez Ng       // subsection.
1007595fc59fSDaniel Bertalan       symbols[symIndex] = createDefined(sym, name, nextIsec, /*value=*/0,
1008595fc59fSDaniel Bertalan                                         symbolSize, forceHidden);
1009ceec6107SJez Ng       // TODO: ld64 appears to preserve the original alignment as well as each
1010ceec6107SJez Ng       // subsection's offset from the last aligned address. We should consider
1011ceec6107SJez Ng       // emulating that behavior.
10127f673fcaSNico Weber       nextIsec->align = MinAlign(sectionAlign, sym.n_value);
10133a1b3c9aSGreg McGary       subsections.push_back({sym.n_value - sectionAddr, nextIsec});
1014ceec6107SJez Ng     }
1015ceec6107SJez Ng   }
1016fbb45947SNico Weber 
1017fbb45947SNico Weber   // Undefined symbols can trigger recursive fetch from Archives due to
1018fbb45947SNico Weber   // LazySymbols. Process defined symbols first so that the relative order
1019fbb45947SNico Weber   // between a defined symbol and an undefined symbol does not change the
1020fbb45947SNico Weber   // symbol resolution behavior. In addition, a set of interconnected symbols
1021fbb45947SNico Weber   // will all be resolved to the same file, instead of being resolved to
1022fbb45947SNico Weber   // different files.
1023fbb45947SNico Weber   for (unsigned i : undefineds) {
1024fbb45947SNico Weber     const NList &sym = nList[i];
1025fbb45947SNico Weber     StringRef name = strtab + sym.n_strx;
1026fbb45947SNico Weber     symbols[i] = parseNonSectionSymbol(sym, name);
1027fbb45947SNico Weber   }
10286acd3003SFangrui Song }
10296acd3003SFangrui Song 
OpaqueFile(MemoryBufferRef mb,StringRef segName,StringRef sectName)1030a379f2c2SGreg McGary OpaqueFile::OpaqueFile(MemoryBufferRef mb, StringRef segName,
1031a379f2c2SGreg McGary                        StringRef sectName)
1032a379f2c2SGreg McGary     : InputFile(OpaqueKind, mb) {
1033a379f2c2SGreg McGary   const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
1034f6b6e721SJez Ng   ArrayRef<uint8_t> data = {buf, mb.getBufferSize()};
10352b78ef06SJez Ng   sections.push_back(make<Section>(/*file=*/this, segName.take_front(16),
10362b78ef06SJez Ng                                    sectName.take_front(16),
10372b78ef06SJez Ng                                    /*flags=*/0, /*addr=*/0));
10382b78ef06SJez Ng   Section &section = *sections.back();
10392b78ef06SJez Ng   ConcatInputSection *isec = make<ConcatInputSection>(section, data);
1040a5645513SNico Weber   isec->live = true;
10412b78ef06SJez Ng   section.subsections.push_back({0, isec});
1042a379f2c2SGreg McGary }
1043a379f2c2SGreg McGary 
ObjFile(MemoryBufferRef mb,uint32_t modTime,StringRef archiveName,bool lazy,bool forceHidden)10440aae2bf3SFangrui Song ObjFile::ObjFile(MemoryBufferRef mb, uint32_t modTime, StringRef archiveName,
1045595fc59fSDaniel Bertalan                  bool lazy, bool forceHidden)
1046595fc59fSDaniel Bertalan     : InputFile(ObjKind, mb, lazy), modTime(modTime), forceHidden(forceHidden) {
1047b2f00f24SNico Weber   this->archiveName = std::string(archiveName);
10480aae2bf3SFangrui Song   if (lazy) {
10490aae2bf3SFangrui Song     if (target->wordSize == 8)
10500aae2bf3SFangrui Song       parseLazy<LP64>();
10510aae2bf3SFangrui Song     else
10520aae2bf3SFangrui Song       parseLazy<ILP32>();
10530aae2bf3SFangrui Song   } else {
1054817d98d8SJez Ng     if (target->wordSize == 8)
1055817d98d8SJez Ng       parse<LP64>();
1056817d98d8SJez Ng     else
1057817d98d8SJez Ng       parse<ILP32>();
1058817d98d8SJez Ng   }
10590aae2bf3SFangrui Song }
1060817d98d8SJez Ng 
parse()1061817d98d8SJez Ng template <class LP> void ObjFile::parse() {
1062817d98d8SJez Ng   using Header = typename LP::mach_header;
1063817d98d8SJez Ng   using SegmentCommand = typename LP::segment_command;
10643a1b3c9aSGreg McGary   using SectionHeader = typename LP::section;
1065817d98d8SJez Ng   using NList = typename LP::nlist;
1066b2f00f24SNico Weber 
10676acd3003SFangrui Song   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
1068817d98d8SJez Ng   auto *hdr = reinterpret_cast<const Header *>(mb.getBufferStart());
10696acd3003SFangrui Song 
10701752f285SJez Ng   Architecture arch = getArchitectureFromCpuType(hdr->cputype, hdr->cpusubtype);
1071ed4a4e33SJez Ng   if (arch != config->arch()) {
10726629ec3eSKeith Smiley     auto msg = config->errorForArchMismatch
10736629ec3eSKeith Smiley                    ? static_cast<void (*)(const Twine &)>(error)
10746629ec3eSKeith Smiley                    : warn;
10756629ec3eSKeith Smiley     msg(toString(this) + " has architecture " + getArchitectureName(arch) +
10764752cdc9SJez Ng         " which is incompatible with target architecture " +
1077ed4a4e33SJez Ng         getArchitectureName(config->arch()));
10784752cdc9SJez Ng     return;
10794752cdc9SJez Ng   }
1080fc5d804dSVy Nguyen 
1081001ba653SJez Ng   if (!checkCompatibility(this))
1082fc5d804dSVy Nguyen     return;
10834752cdc9SJez Ng 
1084eeac6b2bSJez Ng   for (auto *cmd : findCommands<linker_option_command>(hdr, LC_LINKER_OPTION)) {
1085eeac6b2bSJez Ng     StringRef data{reinterpret_cast<const char *>(cmd + 1),
1086eeac6b2bSJez Ng                    cmd->cmdsize - sizeof(linker_option_command)};
1087eeac6b2bSJez Ng     parseLCLinkerOption(this, cmd->count, data);
108816b1f6e3SNico Weber   }
108916b1f6e3SNico Weber 
10903a1b3c9aSGreg McGary   ArrayRef<SectionHeader> sectionHeaders;
1091817d98d8SJez Ng   if (const load_command *cmd = findCommand(hdr, LP::segmentLCType)) {
1092817d98d8SJez Ng     auto *c = reinterpret_cast<const SegmentCommand *>(cmd);
10933a1b3c9aSGreg McGary     sectionHeaders = ArrayRef<SectionHeader>{
10943a1b3c9aSGreg McGary         reinterpret_cast<const SectionHeader *>(c + 1), c->nsects};
10954eb6f485SJez Ng     parseSections(sectionHeaders);
10966acd3003SFangrui Song   }
10976acd3003SFangrui Song 
1098060efd24SJez Ng   // TODO: Error on missing LC_SYMTAB?
10996acd3003SFangrui Song   if (const load_command *cmd = findCommand(hdr, LC_SYMTAB)) {
11006acd3003SFangrui Song     auto *c = reinterpret_cast<const symtab_command *>(cmd);
1101817d98d8SJez Ng     ArrayRef<NList> nList(reinterpret_cast<const NList *>(buf + c->symoff),
1102817d98d8SJez Ng                           c->nsyms);
11034eb6f485SJez Ng     const char *strtab = reinterpret_cast<const char *>(buf) + c->stroff;
11044eb6f485SJez Ng     bool subsectionsViaSymbols = hdr->flags & MH_SUBSECTIONS_VIA_SYMBOLS;
1105817d98d8SJez Ng     parseSymbols<LP>(sectionHeaders, nList, strtab, subsectionsViaSymbols);
11066acd3003SFangrui Song   }
11076acd3003SFangrui Song 
11086acd3003SFangrui Song   // The relocations may refer to the symbols, so we parse them after we have
11094eb6f485SJez Ng   // parsed all the symbols.
11103a1b3c9aSGreg McGary   for (size_t i = 0, n = sections.size(); i < n; ++i)
11112b78ef06SJez Ng     if (!sections[i]->subsections.empty())
11121c0234dfSJez Ng       parseRelocations(sectionHeaders, sectionHeaders[i], *sections[i]);
11133fcb0eebSJez Ng 
1114a3f67f09SDaniel Bertalan   if (!config->ignoreOptimizationHints)
1115a3f67f09SDaniel Bertalan     if (auto *cmd = findCommand<linkedit_data_command>(
1116a3f67f09SDaniel Bertalan             hdr, LC_LINKER_OPTIMIZATION_HINT))
1117a3f67f09SDaniel Bertalan       parseOptimizationHints({buf + cmd->dataoff, cmd->datasize});
1118a3f67f09SDaniel Bertalan 
11193fcb0eebSJez Ng   parseDebugInfo();
1120e6382d23SJez Ng 
1121e6382d23SJez Ng   Section *ehFrameSection = nullptr;
1122e6382d23SJez Ng   Section *compactUnwindSection = nullptr;
1123e6382d23SJez Ng   for (Section *sec : sections) {
1124e6382d23SJez Ng     Section **s = StringSwitch<Section **>(sec->name)
1125e6382d23SJez Ng                       .Case(section_names::compactUnwind, &compactUnwindSection)
1126e6382d23SJez Ng                       .Case(section_names::ehFrame, &ehFrameSection)
1127e6382d23SJez Ng                       .Default(nullptr);
1128e6382d23SJez Ng     if (s)
1129e6382d23SJez Ng       *s = sec;
1130e6382d23SJez Ng   }
11319cc489a4SGreg McGary   if (compactUnwindSection)
1132e6382d23SJez Ng     registerCompactUnwind(*compactUnwindSection);
1133403d61aeSJez Ng   if (ehFrameSection)
1134e183bf8eSJez Ng     registerEhFrames(*ehFrameSection);
11353fcb0eebSJez Ng }
11363fcb0eebSJez Ng 
parseLazy()11370aae2bf3SFangrui Song template <class LP> void ObjFile::parseLazy() {
11380aae2bf3SFangrui Song   using Header = typename LP::mach_header;
11390aae2bf3SFangrui Song   using NList = typename LP::nlist;
11400aae2bf3SFangrui Song 
11410aae2bf3SFangrui Song   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
11420aae2bf3SFangrui Song   auto *hdr = reinterpret_cast<const Header *>(mb.getBufferStart());
11430aae2bf3SFangrui Song   const load_command *cmd = findCommand(hdr, LC_SYMTAB);
11440aae2bf3SFangrui Song   if (!cmd)
11450aae2bf3SFangrui Song     return;
11460aae2bf3SFangrui Song   auto *c = reinterpret_cast<const symtab_command *>(cmd);
11470aae2bf3SFangrui Song   ArrayRef<NList> nList(reinterpret_cast<const NList *>(buf + c->symoff),
11480aae2bf3SFangrui Song                         c->nsyms);
11490aae2bf3SFangrui Song   const char *strtab = reinterpret_cast<const char *>(buf) + c->stroff;
11500aae2bf3SFangrui Song   symbols.resize(nList.size());
11510aae2bf3SFangrui Song   for (auto it : llvm::enumerate(nList)) {
11520aae2bf3SFangrui Song     const NList &sym = it.value();
11530aae2bf3SFangrui Song     if ((sym.n_type & N_EXT) && !isUndef(sym)) {
11540aae2bf3SFangrui Song       // TODO: Bound checking
11550aae2bf3SFangrui Song       StringRef name = strtab + sym.n_strx;
11560aae2bf3SFangrui Song       symbols[it.index()] = symtab->addLazyObject(name, *this);
11570aae2bf3SFangrui Song       if (!lazy)
11580aae2bf3SFangrui Song         break;
11590aae2bf3SFangrui Song     }
11600aae2bf3SFangrui Song   }
11610aae2bf3SFangrui Song }
11620aae2bf3SFangrui Song 
parseDebugInfo()11633fcb0eebSJez Ng void ObjFile::parseDebugInfo() {
11643fcb0eebSJez Ng   std::unique_ptr<DwarfObject> dObj = DwarfObject::create(this);
11653fcb0eebSJez Ng   if (!dObj)
11663fcb0eebSJez Ng     return;
11673fcb0eebSJez Ng 
11685792797cSDaniel Bertalan   // We do not re-use the context from getDwarf() here as that function
11695792797cSDaniel Bertalan   // constructs an expensive DWARFCache object.
11703fcb0eebSJez Ng   auto *ctx = make<DWARFContext>(
11713fcb0eebSJez Ng       std::move(dObj), "",
1172b2f00f24SNico Weber       [&](Error err) {
1173b2f00f24SNico Weber         warn(toString(this) + ": " + toString(std::move(err)));
1174b2f00f24SNico Weber       },
11753fcb0eebSJez Ng       [&](Error warning) {
1176b2f00f24SNico Weber         warn(toString(this) + ": " + toString(std::move(warning)));
11773fcb0eebSJez Ng       });
11783fcb0eebSJez Ng 
11793fcb0eebSJez Ng   // TODO: Since object files can contain a lot of DWARF info, we should verify
11803fcb0eebSJez Ng   // that we are parsing just the info we need
11813fcb0eebSJez Ng   const DWARFContext::compile_unit_range &units = ctx->compile_units();
1182fc011b5eSJez Ng   // FIXME: There can be more than one compile unit per object file. See
1183fc011b5eSJez Ng   // PR48637.
11843fcb0eebSJez Ng   auto it = units.begin();
118577b6efbdSDaniel Bertalan   compileUnit = it != units.end() ? it->get() : nullptr;
11866acd3003SFangrui Song }
11876acd3003SFangrui Song 
getDataInCode() const1188098430cdSJez Ng ArrayRef<data_in_code_entry> ObjFile::getDataInCode() const {
1189928394d1SAlexander Shaposhnikov   const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
1190928394d1SAlexander Shaposhnikov   const load_command *cmd = findCommand(buf, LC_DATA_IN_CODE);
1191928394d1SAlexander Shaposhnikov   if (!cmd)
1192098430cdSJez Ng     return {};
1193928394d1SAlexander Shaposhnikov   const auto *c = reinterpret_cast<const linkedit_data_command *>(cmd);
1194098430cdSJez Ng   return {reinterpret_cast<const data_in_code_entry *>(buf + c->dataoff),
1195928394d1SAlexander Shaposhnikov           c->datasize / sizeof(data_in_code_entry)};
1196928394d1SAlexander Shaposhnikov }
1197928394d1SAlexander Shaposhnikov 
1198002eda70SJez Ng // Create pointers from symbols to their associated compact unwind entries.
registerCompactUnwind(Section & compactUnwindSection)1199e6382d23SJez Ng void ObjFile::registerCompactUnwind(Section &compactUnwindSection) {
1200e6382d23SJez Ng   for (const Subsection &subsection : compactUnwindSection.subsections) {
12013a1b3c9aSGreg McGary     ConcatInputSection *isec = cast<ConcatInputSection>(subsection.isec);
1202f6017abbSJez Ng     // Hack!! Each compact unwind entry (CUE) has its UNSIGNED relocations embed
1203f6017abbSJez Ng     // their addends in its data. Thus if ICF operated naively and compared the
1204f6017abbSJez Ng     // entire contents of each CUE, entries with identical unwind info but e.g.
1205f6017abbSJez Ng     // belonging to different functions would never be considered equivalent. To
1206f6017abbSJez Ng     // work around this problem, we remove some parts of the data containing the
1207f6017abbSJez Ng     // embedded addends. In particular, we remove the function address and LSDA
1208f6017abbSJez Ng     // pointers.  Since these locations are at the start and end of the entry,
1209f6017abbSJez Ng     // we can do this using a simple, efficient slice rather than performing a
1210f6017abbSJez Ng     // copy.  We are not losing any information here because the embedded
1211f6017abbSJez Ng     // addends have already been parsed in the corresponding Reloc structs.
1212f6017abbSJez Ng     //
1213f6017abbSJez Ng     // Removing these pointers would not be safe if they were pointers to
1214f6017abbSJez Ng     // absolute symbols. In that case, there would be no corresponding
1215f6017abbSJez Ng     // relocation. However, (AFAIK) MC cannot emit references to absolute
1216f6017abbSJez Ng     // symbols for either the function address or the LSDA. However, it *can* do
1217f6017abbSJez Ng     // so for the personality pointer, so we are not slicing that field away.
1218f6017abbSJez Ng     //
1219f6017abbSJez Ng     // Note that we do not adjust the offsets of the corresponding relocations;
1220f6017abbSJez Ng     // instead, we rely on `relocateCompactUnwind()` to correctly handle these
1221f6017abbSJez Ng     // truncated input sections.
1222f6017abbSJez Ng     isec->data = isec->data.slice(target->wordSize, 8 + target->wordSize);
1223e183bf8eSJez Ng     uint32_t encoding = read32le(isec->data.data() + sizeof(uint32_t));
1224e183bf8eSJez Ng     // llvm-mc omits CU entries for functions that need DWARF encoding, but
1225e183bf8eSJez Ng     // `ld -r` doesn't. We can ignore them because we will re-synthesize these
1226e183bf8eSJez Ng     // CU entries from the DWARF info during the output phase.
1227e183bf8eSJez Ng     if ((encoding & target->modeDwarfEncoding) == target->modeDwarfEncoding)
1228e183bf8eSJez Ng       continue;
1229d9b6f7e3SJez Ng 
1230002eda70SJez Ng     ConcatInputSection *referentIsec;
1231d9b6f7e3SJez Ng     for (auto it = isec->relocs.begin(); it != isec->relocs.end();) {
1232d9b6f7e3SJez Ng       Reloc &r = *it;
12339cc489a4SGreg McGary       // CUE::functionAddress is at offset 0. Skip personality & LSDA relocs.
1234d9b6f7e3SJez Ng       if (r.offset != 0) {
1235d9b6f7e3SJez Ng         ++it;
1236002eda70SJez Ng         continue;
1237d9b6f7e3SJez Ng       }
1238002eda70SJez Ng       uint64_t add = r.addend;
1239002eda70SJez Ng       if (auto *sym = cast_or_null<Defined>(r.referent.dyn_cast<Symbol *>())) {
1240ad8df21dSJez Ng         // Check whether the symbol defined in this file is the prevailing one.
1241ad8df21dSJez Ng         // Skip if it is e.g. a weak def that didn't prevail.
1242d9b6f7e3SJez Ng         if (sym->getFile() != this) {
1243d9b6f7e3SJez Ng           ++it;
1244ad8df21dSJez Ng           continue;
1245d9b6f7e3SJez Ng         }
1246002eda70SJez Ng         add += sym->value;
1247002eda70SJez Ng         referentIsec = cast<ConcatInputSection>(sym->isec);
1248002eda70SJez Ng       } else {
1249002eda70SJez Ng         referentIsec =
1250002eda70SJez Ng             cast<ConcatInputSection>(r.referent.dyn_cast<InputSection *>());
1251002eda70SJez Ng       }
125282dcf306SJez Ng       // Unwind info lives in __DATA, and finalization of __TEXT will occur
125382dcf306SJez Ng       // before finalization of __DATA. Moreover, the finalization of unwind
125482dcf306SJez Ng       // info depends on the exact addresses that it references. So it is safe
125582dcf306SJez Ng       // for compact unwind to reference addresses in __TEXT, but not addresses
125682dcf306SJez Ng       // in any other segment.
12571d2a4cd5SJez Ng       if (referentIsec->getSegName() != segment_names::text)
125806f863acSJez Ng         error(isec->getLocation(r.offset) + " references section " +
125906f863acSJez Ng               referentIsec->getName() + " which is not in segment __TEXT");
1260002eda70SJez Ng       // The functionAddress relocations are typically section relocations.
1261002eda70SJez Ng       // However, unwind info operates on a per-symbol basis, so we search for
1262002eda70SJez Ng       // the function symbol here.
1263da6b6b3cSJez Ng       Defined *d = findSymbolAtOffset(referentIsec, add);
1264da6b6b3cSJez Ng       if (!d) {
1265d9b6f7e3SJez Ng         ++it;
1266002eda70SJez Ng         continue;
1267002eda70SJez Ng       }
1268da6b6b3cSJez Ng       d->unwindEntry = isec;
1269fe47cfb3SJez Ng       // Now that the symbol points to the unwind entry, we can remove the reloc
1270fe47cfb3SJez Ng       // that points from the unwind entry back to the symbol.
1271fe47cfb3SJez Ng       //
1272fe47cfb3SJez Ng       // First, the symbol keeps the unwind entry alive (and not vice versa), so
1273fe47cfb3SJez Ng       // this keeps dead-stripping simple.
1274fe47cfb3SJez Ng       //
1275fe47cfb3SJez Ng       // Moreover, it reduces the work that ICF needs to do to figure out if
1276fe47cfb3SJez Ng       // functions with unwind info are foldable.
1277fe47cfb3SJez Ng       //
1278fe47cfb3SJez Ng       // However, this does make it possible for ICF to fold CUEs that point to
1279fe47cfb3SJez Ng       // distinct functions (if the CUEs are otherwise identical).
1280fe47cfb3SJez Ng       // UnwindInfoSection takes care of this by re-duplicating the CUEs so that
1281fe47cfb3SJez Ng       // each one can hold a distinct functionAddress value.
1282fe47cfb3SJez Ng       //
1283fe47cfb3SJez Ng       // Given that clang emits relocations in reverse order of address, this
1284fe47cfb3SJez Ng       // relocation should be at the end of the vector for most of our input
1285fe47cfb3SJez Ng       // object files, so this erase() is typically an O(1) operation.
1286d9b6f7e3SJez Ng       it = isec->relocs.erase(it);
1287002eda70SJez Ng     }
1288002eda70SJez Ng   }
1289002eda70SJez Ng }
1290002eda70SJez Ng 
1291e183bf8eSJez Ng struct CIE {
1292e183bf8eSJez Ng   macho::Symbol *personalitySymbol = nullptr;
1293e183bf8eSJez Ng   bool fdesHaveAug = false;
1294d6e5bfceSJez Ng   uint8_t lsdaPtrSize = 0; // 0 => no LSDA
1295d6e5bfceSJez Ng   uint8_t funcPtrSize = 0;
1296e183bf8eSJez Ng };
1297e183bf8eSJez Ng 
pointerEncodingToSize(uint8_t enc)1298d6e5bfceSJez Ng static uint8_t pointerEncodingToSize(uint8_t enc) {
1299d6e5bfceSJez Ng   switch (enc & 0xf) {
1300d6e5bfceSJez Ng   case dwarf::DW_EH_PE_absptr:
1301d6e5bfceSJez Ng     return target->wordSize;
1302d6e5bfceSJez Ng   case dwarf::DW_EH_PE_sdata4:
1303d6e5bfceSJez Ng     return 4;
1304d6e5bfceSJez Ng   case dwarf::DW_EH_PE_sdata8:
1305d6e5bfceSJez Ng     // ld64 doesn't actually support sdata8, but this seems simple enough...
1306d6e5bfceSJez Ng     return 8;
1307d6e5bfceSJez Ng   default:
1308d6e5bfceSJez Ng     return 0;
1309d6e5bfceSJez Ng   };
1310d6e5bfceSJez Ng }
1311d6e5bfceSJez Ng 
parseCIE(const InputSection * isec,const EhReader & reader,size_t off)1312e183bf8eSJez Ng static CIE parseCIE(const InputSection *isec, const EhReader &reader,
1313e183bf8eSJez Ng                     size_t off) {
1314e183bf8eSJez Ng   // Handling the full generality of possible DWARF encodings would be a major
1315e183bf8eSJez Ng   // pain. We instead take advantage of our knowledge of how llvm-mc encodes
1316e183bf8eSJez Ng   // DWARF and handle just that.
1317e183bf8eSJez Ng   constexpr uint8_t expectedPersonalityEnc =
1318e183bf8eSJez Ng       dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_sdata4;
1319e183bf8eSJez Ng 
1320e183bf8eSJez Ng   CIE cie;
1321e183bf8eSJez Ng   uint8_t version = reader.readByte(&off);
1322e183bf8eSJez Ng   if (version != 1 && version != 3)
1323e183bf8eSJez Ng     fatal("Expected CIE version of 1 or 3, got " + Twine(version));
1324e183bf8eSJez Ng   StringRef aug = reader.readString(&off);
1325e183bf8eSJez Ng   reader.skipLeb128(&off); // skip code alignment
1326e183bf8eSJez Ng   reader.skipLeb128(&off); // skip data alignment
1327e183bf8eSJez Ng   reader.skipLeb128(&off); // skip return address register
1328e183bf8eSJez Ng   reader.skipLeb128(&off); // skip aug data length
1329e183bf8eSJez Ng   uint64_t personalityAddrOff = 0;
1330e183bf8eSJez Ng   for (char c : aug) {
1331e183bf8eSJez Ng     switch (c) {
1332e183bf8eSJez Ng     case 'z':
1333e183bf8eSJez Ng       cie.fdesHaveAug = true;
1334e183bf8eSJez Ng       break;
1335e183bf8eSJez Ng     case 'P': {
1336e183bf8eSJez Ng       uint8_t personalityEnc = reader.readByte(&off);
1337e183bf8eSJez Ng       if (personalityEnc != expectedPersonalityEnc)
1338e183bf8eSJez Ng         reader.failOn(off, "unexpected personality encoding 0x" +
1339e183bf8eSJez Ng                                Twine::utohexstr(personalityEnc));
1340e183bf8eSJez Ng       personalityAddrOff = off;
1341e183bf8eSJez Ng       off += 4;
1342e183bf8eSJez Ng       break;
1343e183bf8eSJez Ng     }
1344e183bf8eSJez Ng     case 'L': {
1345e183bf8eSJez Ng       uint8_t lsdaEnc = reader.readByte(&off);
1346d6e5bfceSJez Ng       cie.lsdaPtrSize = pointerEncodingToSize(lsdaEnc);
1347d6e5bfceSJez Ng       if (cie.lsdaPtrSize == 0)
1348e183bf8eSJez Ng         reader.failOn(off, "unexpected LSDA encoding 0x" +
1349e183bf8eSJez Ng                                Twine::utohexstr(lsdaEnc));
1350e183bf8eSJez Ng       break;
1351e183bf8eSJez Ng     }
1352e183bf8eSJez Ng     case 'R': {
1353e183bf8eSJez Ng       uint8_t pointerEnc = reader.readByte(&off);
1354d6e5bfceSJez Ng       cie.funcPtrSize = pointerEncodingToSize(pointerEnc);
1355d6e5bfceSJez Ng       if (cie.funcPtrSize == 0 || !(pointerEnc & dwarf::DW_EH_PE_pcrel))
1356e183bf8eSJez Ng         reader.failOn(off, "unexpected pointer encoding 0x" +
1357e183bf8eSJez Ng                                Twine::utohexstr(pointerEnc));
1358e183bf8eSJez Ng       break;
1359e183bf8eSJez Ng     }
1360e183bf8eSJez Ng     default:
1361e183bf8eSJez Ng       break;
1362e183bf8eSJez Ng     }
1363e183bf8eSJez Ng   }
1364e183bf8eSJez Ng   if (personalityAddrOff != 0) {
1365e183bf8eSJez Ng     auto personalityRelocIt =
1366e183bf8eSJez Ng         llvm::find_if(isec->relocs, [=](const macho::Reloc &r) {
1367e183bf8eSJez Ng           return r.offset == personalityAddrOff;
1368e183bf8eSJez Ng         });
1369e183bf8eSJez Ng     if (personalityRelocIt == isec->relocs.end())
1370e183bf8eSJez Ng       reader.failOn(off, "Failed to locate relocation for personality symbol");
1371e183bf8eSJez Ng     cie.personalitySymbol = personalityRelocIt->referent.get<macho::Symbol *>();
1372e183bf8eSJez Ng   }
1373e183bf8eSJez Ng   return cie;
1374e183bf8eSJez Ng }
1375e183bf8eSJez Ng 
1376e183bf8eSJez Ng // EH frame target addresses may be encoded as pcrel offsets. However, instead
1377e183bf8eSJez Ng // of using an actual pcrel reloc, ld64 emits subtractor relocations instead.
1378e183bf8eSJez Ng // This function recovers the target address from the subtractors, essentially
1379e183bf8eSJez Ng // performing the inverse operation of EhRelocator.
1380e183bf8eSJez Ng //
1381e183bf8eSJez Ng // Concretely, we expect our relocations to write the value of `PC -
1382e183bf8eSJez Ng // target_addr` to `PC`. `PC` itself is denoted by a minuend relocation that
1383b422dac2SJez Ng // points to a symbol plus an addend.
1384b422dac2SJez Ng //
1385b422dac2SJez Ng // It is important that the minuend relocation point to a symbol within the
1386b422dac2SJez Ng // same section as the fixup value, since sections may get moved around.
1387b422dac2SJez Ng //
1388b422dac2SJez Ng // For example, for arm64, llvm-mc emits relocations for the target function
1389b422dac2SJez Ng // address like so:
1390b422dac2SJez Ng //
1391b422dac2SJez Ng //   ltmp:
1392b422dac2SJez Ng //     <CIE start>
1393b422dac2SJez Ng //     ...
1394b422dac2SJez Ng //     <CIE end>
1395b422dac2SJez Ng //     ... multiple FDEs ...
1396b422dac2SJez Ng //     <FDE start>
1397b422dac2SJez Ng //     <target function address - (ltmp + pcrel offset)>
1398b422dac2SJez Ng //     ...
1399b422dac2SJez Ng //
1400b422dac2SJez Ng // If any of the FDEs in `multiple FDEs` get dead-stripped, then `FDE start`
1401b422dac2SJez Ng // will move to an earlier address, and `ltmp + pcrel offset` will no longer
1402b422dac2SJez Ng // reflect an accurate pcrel value. To avoid this problem, we "canonicalize"
1403b422dac2SJez Ng // our relocation by adding an `EH_Frame` symbol at `FDE start`, and updating
1404b422dac2SJez Ng // the reloc to be `target function address - (EH_Frame + new pcrel offset)`.
1405e183bf8eSJez Ng //
1406e183bf8eSJez Ng // If `Invert` is set, then we instead expect `target_addr - PC` to be written
1407e183bf8eSJez Ng // to `PC`.
1408e183bf8eSJez Ng template <bool Invert = false>
1409e183bf8eSJez Ng Defined *
targetSymFromCanonicalSubtractor(const InputSection * isec,std::vector<macho::Reloc>::iterator relocIt)1410b422dac2SJez Ng targetSymFromCanonicalSubtractor(const InputSection *isec,
1411e183bf8eSJez Ng                                  std::vector<macho::Reloc>::iterator relocIt) {
1412b422dac2SJez Ng   macho::Reloc &subtrahend = *relocIt;
1413b422dac2SJez Ng   macho::Reloc &minuend = *std::next(relocIt);
1414e183bf8eSJez Ng   assert(target->hasAttr(subtrahend.type, RelocAttrBits::SUBTRAHEND));
1415e183bf8eSJez Ng   assert(target->hasAttr(minuend.type, RelocAttrBits::UNSIGNED));
1416e183bf8eSJez Ng   // Note: pcSym may *not* be exactly at the PC; there's usually a non-zero
1417e183bf8eSJez Ng   // addend.
1418e183bf8eSJez Ng   auto *pcSym = cast<Defined>(subtrahend.referent.get<macho::Symbol *>());
1419e183bf8eSJez Ng   Defined *target =
1420e183bf8eSJez Ng       cast_or_null<Defined>(minuend.referent.dyn_cast<macho::Symbol *>());
1421e183bf8eSJez Ng   if (!pcSym) {
1422e183bf8eSJez Ng     auto *targetIsec =
1423e183bf8eSJez Ng         cast<ConcatInputSection>(minuend.referent.get<InputSection *>());
1424e183bf8eSJez Ng     target = findSymbolAtOffset(targetIsec, minuend.addend);
1425e183bf8eSJez Ng   }
1426e183bf8eSJez Ng   if (Invert)
1427e183bf8eSJez Ng     std::swap(pcSym, target);
1428b422dac2SJez Ng   if (pcSym->isec == isec) {
1429b422dac2SJez Ng     if (pcSym->value - (Invert ? -1 : 1) * minuend.addend != subtrahend.offset)
1430e183bf8eSJez Ng       fatal("invalid FDE relocation in __eh_frame");
1431b422dac2SJez Ng   } else {
1432b422dac2SJez Ng     // Ensure the pcReloc points to a symbol within the current EH frame.
1433b422dac2SJez Ng     // HACK: we should really verify that the original relocation's semantics
1434b422dac2SJez Ng     // are preserved. In particular, we should have
1435b422dac2SJez Ng     // `oldSym->value + oldOffset == newSym + newOffset`. However, we don't
1436b422dac2SJez Ng     // have an easy way to access the offsets from this point in the code; some
1437b422dac2SJez Ng     // refactoring is needed for that.
1438b422dac2SJez Ng     macho::Reloc &pcReloc = Invert ? minuend : subtrahend;
1439b422dac2SJez Ng     pcReloc.referent = isec->symbols[0];
1440b422dac2SJez Ng     assert(isec->symbols[0]->value == 0);
1441b422dac2SJez Ng     minuend.addend = pcReloc.offset * (Invert ? 1LL : -1LL);
1442b422dac2SJez Ng   }
1443e183bf8eSJez Ng   return target;
1444e183bf8eSJez Ng }
1445e183bf8eSJez Ng 
findSymbolAtAddress(const std::vector<Section * > & sections,uint64_t addr)1446e183bf8eSJez Ng Defined *findSymbolAtAddress(const std::vector<Section *> &sections,
1447e183bf8eSJez Ng                              uint64_t addr) {
1448e183bf8eSJez Ng   Section *sec = findContainingSection(sections, &addr);
1449e183bf8eSJez Ng   auto *isec = cast<ConcatInputSection>(findContainingSubsection(*sec, &addr));
1450e183bf8eSJez Ng   return findSymbolAtOffset(isec, addr);
1451e183bf8eSJez Ng }
1452e183bf8eSJez Ng 
1453e183bf8eSJez Ng // For symbols that don't have compact unwind info, associate them with the more
1454e183bf8eSJez Ng // general-purpose (and verbose) DWARF unwind info found in __eh_frame.
1455e183bf8eSJez Ng //
1456e183bf8eSJez Ng // This requires us to parse the contents of __eh_frame. See EhFrame.h for a
1457e183bf8eSJez Ng // description of its format.
1458e183bf8eSJez Ng //
1459e183bf8eSJez Ng // While parsing, we also look for what MC calls "abs-ified" relocations -- they
1460e183bf8eSJez Ng // are relocations which are implicitly encoded as offsets in the section data.
1461e183bf8eSJez Ng // We convert them into explicit Reloc structs so that the EH frames can be
1462e183bf8eSJez Ng // handled just like a regular ConcatInputSection later in our output phase.
1463e183bf8eSJez Ng //
1464e183bf8eSJez Ng // We also need to handle the case where our input object file has explicit
1465e183bf8eSJez Ng // relocations. This is the case when e.g. it's the output of `ld -r`. We only
1466e183bf8eSJez Ng // look for the "abs-ified" relocation if an explicit relocation is absent.
registerEhFrames(Section & ehFrameSection)1467e183bf8eSJez Ng void ObjFile::registerEhFrames(Section &ehFrameSection) {
1468e183bf8eSJez Ng   DenseMap<const InputSection *, CIE> cieMap;
1469e183bf8eSJez Ng   for (const Subsection &subsec : ehFrameSection.subsections) {
1470e183bf8eSJez Ng     auto *isec = cast<ConcatInputSection>(subsec.isec);
1471e183bf8eSJez Ng     uint64_t isecOff = subsec.offset;
1472e183bf8eSJez Ng 
1473e183bf8eSJez Ng     // Subtractor relocs require the subtrahend to be a symbol reloc. Ensure
1474e183bf8eSJez Ng     // that all EH frames have an associated symbol so that we can generate
1475e183bf8eSJez Ng     // subtractor relocs that reference them.
1476e183bf8eSJez Ng     if (isec->symbols.size() == 0)
1477e183bf8eSJez Ng       isec->symbols.push_back(make<Defined>(
1478e183bf8eSJez Ng           "EH_Frame", isec->getFile(), isec, /*value=*/0, /*size=*/0,
1479e183bf8eSJez Ng           /*isWeakDef=*/false, /*isExternal=*/false, /*isPrivateExtern=*/false,
1480e183bf8eSJez Ng           /*includeInSymtab=*/false, /*isThumb=*/false,
1481e183bf8eSJez Ng           /*isReferencedDynamically=*/false, /*noDeadStrip=*/false));
1482e183bf8eSJez Ng     else if (isec->symbols[0]->value != 0)
1483e183bf8eSJez Ng       fatal("found symbol at unexpected offset in __eh_frame");
1484e183bf8eSJez Ng 
1485d6e5bfceSJez Ng     EhReader reader(this, isec->data, subsec.offset);
1486e183bf8eSJez Ng     size_t dataOff = 0; // Offset from the start of the EH frame.
1487e183bf8eSJez Ng     reader.skipValidLength(&dataOff); // readLength() already validated this.
1488e183bf8eSJez Ng     // cieOffOff is the offset from the start of the EH frame to the cieOff
1489e183bf8eSJez Ng     // value, which is itself an offset from the current PC to a CIE.
1490e183bf8eSJez Ng     const size_t cieOffOff = dataOff;
1491e183bf8eSJez Ng 
1492e183bf8eSJez Ng     EhRelocator ehRelocator(isec);
1493e183bf8eSJez Ng     auto cieOffRelocIt = llvm::find_if(
1494e183bf8eSJez Ng         isec->relocs, [=](const Reloc &r) { return r.offset == cieOffOff; });
1495e183bf8eSJez Ng     InputSection *cieIsec = nullptr;
1496e183bf8eSJez Ng     if (cieOffRelocIt != isec->relocs.end()) {
1497e183bf8eSJez Ng       // We already have an explicit relocation for the CIE offset.
1498e183bf8eSJez Ng       cieIsec =
1499b422dac2SJez Ng           targetSymFromCanonicalSubtractor</*Invert=*/true>(isec, cieOffRelocIt)
1500e183bf8eSJez Ng               ->isec;
1501e183bf8eSJez Ng       dataOff += sizeof(uint32_t);
1502e183bf8eSJez Ng     } else {
1503e183bf8eSJez Ng       // If we haven't found a relocation, then the CIE offset is most likely
1504e183bf8eSJez Ng       // embedded in the section data (AKA an "abs-ified" reloc.). Parse that
1505e183bf8eSJez Ng       // and generate a Reloc struct.
1506e183bf8eSJez Ng       uint32_t cieMinuend = reader.readU32(&dataOff);
1507e183bf8eSJez Ng       if (cieMinuend == 0)
1508e183bf8eSJez Ng         cieIsec = isec;
1509e183bf8eSJez Ng       else {
1510e183bf8eSJez Ng         uint32_t cieOff = isecOff + dataOff - cieMinuend;
1511e183bf8eSJez Ng         cieIsec = findContainingSubsection(ehFrameSection, &cieOff);
1512e183bf8eSJez Ng         if (cieIsec == nullptr)
1513e183bf8eSJez Ng           fatal("failed to find CIE");
1514e183bf8eSJez Ng       }
1515e183bf8eSJez Ng       if (cieIsec != isec)
1516e183bf8eSJez Ng         ehRelocator.makeNegativePcRel(cieOffOff, cieIsec->symbols[0],
1517e183bf8eSJez Ng                                       /*length=*/2);
1518e183bf8eSJez Ng     }
1519e183bf8eSJez Ng     if (cieIsec == isec) {
1520e183bf8eSJez Ng       cieMap[cieIsec] = parseCIE(isec, reader, dataOff);
1521e183bf8eSJez Ng       continue;
1522e183bf8eSJez Ng     }
1523e183bf8eSJez Ng 
1524e183bf8eSJez Ng     assert(cieMap.count(cieIsec));
1525e183bf8eSJez Ng     const CIE &cie = cieMap[cieIsec];
1526d6e5bfceSJez Ng     // Offset of the function address within the EH frame.
1527d6e5bfceSJez Ng     const size_t funcAddrOff = dataOff;
1528d6e5bfceSJez Ng     uint64_t funcAddr = reader.readPointer(&dataOff, cie.funcPtrSize) +
1529d6e5bfceSJez Ng                         ehFrameSection.addr + isecOff + funcAddrOff;
1530d6e5bfceSJez Ng     uint32_t funcLength = reader.readPointer(&dataOff, cie.funcPtrSize);
1531d6e5bfceSJez Ng     size_t lsdaAddrOff = 0; // Offset of the LSDA address within the EH frame.
1532e183bf8eSJez Ng     Optional<uint64_t> lsdaAddrOpt;
1533e183bf8eSJez Ng     if (cie.fdesHaveAug) {
1534e183bf8eSJez Ng       reader.skipLeb128(&dataOff);
1535e183bf8eSJez Ng       lsdaAddrOff = dataOff;
1536d6e5bfceSJez Ng       if (cie.lsdaPtrSize != 0) {
1537d6e5bfceSJez Ng         uint64_t lsdaOff = reader.readPointer(&dataOff, cie.lsdaPtrSize);
1538e183bf8eSJez Ng         if (lsdaOff != 0) // FIXME possible to test this?
1539e183bf8eSJez Ng           lsdaAddrOpt = ehFrameSection.addr + isecOff + lsdaAddrOff + lsdaOff;
1540e183bf8eSJez Ng       }
1541e183bf8eSJez Ng     }
1542e183bf8eSJez Ng 
1543e183bf8eSJez Ng     auto funcAddrRelocIt = isec->relocs.end();
1544e183bf8eSJez Ng     auto lsdaAddrRelocIt = isec->relocs.end();
1545e183bf8eSJez Ng     for (auto it = isec->relocs.begin(); it != isec->relocs.end(); ++it) {
1546e183bf8eSJez Ng       if (it->offset == funcAddrOff)
1547e183bf8eSJez Ng         funcAddrRelocIt = it++; // Found subtrahend; skip over minuend reloc
1548e183bf8eSJez Ng       else if (lsdaAddrOpt && it->offset == lsdaAddrOff)
1549e183bf8eSJez Ng         lsdaAddrRelocIt = it++; // Found subtrahend; skip over minuend reloc
1550e183bf8eSJez Ng     }
1551e183bf8eSJez Ng 
1552e183bf8eSJez Ng     Defined *funcSym;
1553e183bf8eSJez Ng     if (funcAddrRelocIt != isec->relocs.end()) {
1554b422dac2SJez Ng       funcSym = targetSymFromCanonicalSubtractor(isec, funcAddrRelocIt);
1555241f62d8SJez Ng       // Canonicalize the symbol. If there are multiple symbols at the same
1556241f62d8SJez Ng       // address, we want both `registerEhFrame` and `registerCompactUnwind`
1557241f62d8SJez Ng       // to register the unwind entry under same symbol.
1558241f62d8SJez Ng       // This is not particularly efficient, but we should run into this case
1559241f62d8SJez Ng       // infrequently (only when handling the output of `ld -r`).
1560b35e0d0cSJez Ng       if (funcSym->isec)
1561241f62d8SJez Ng         funcSym = findSymbolAtOffset(cast<ConcatInputSection>(funcSym->isec),
1562241f62d8SJez Ng                                      funcSym->value);
1563e183bf8eSJez Ng     } else {
1564e183bf8eSJez Ng       funcSym = findSymbolAtAddress(sections, funcAddr);
1565e183bf8eSJez Ng       ehRelocator.makePcRel(funcAddrOff, funcSym, target->p2WordSize);
1566e183bf8eSJez Ng     }
1567e183bf8eSJez Ng     // The symbol has been coalesced, or already has a compact unwind entry.
1568e183bf8eSJez Ng     if (!funcSym || funcSym->getFile() != this || funcSym->unwindEntry) {
1569e183bf8eSJez Ng       // We must prune unused FDEs for correctness, so we cannot rely on
1570e183bf8eSJez Ng       // -dead_strip being enabled.
1571e183bf8eSJez Ng       isec->live = false;
1572e183bf8eSJez Ng       continue;
1573e183bf8eSJez Ng     }
1574e183bf8eSJez Ng 
1575e183bf8eSJez Ng     InputSection *lsdaIsec = nullptr;
1576e183bf8eSJez Ng     if (lsdaAddrRelocIt != isec->relocs.end()) {
1577b422dac2SJez Ng       lsdaIsec = targetSymFromCanonicalSubtractor(isec, lsdaAddrRelocIt)->isec;
1578e183bf8eSJez Ng     } else if (lsdaAddrOpt) {
1579e183bf8eSJez Ng       uint64_t lsdaAddr = *lsdaAddrOpt;
1580e183bf8eSJez Ng       Section *sec = findContainingSection(sections, &lsdaAddr);
1581e183bf8eSJez Ng       lsdaIsec =
1582e183bf8eSJez Ng           cast<ConcatInputSection>(findContainingSubsection(*sec, &lsdaAddr));
1583e183bf8eSJez Ng       ehRelocator.makePcRel(lsdaAddrOff, lsdaIsec, target->p2WordSize);
1584e183bf8eSJez Ng     }
1585e183bf8eSJez Ng 
1586e183bf8eSJez Ng     fdes[isec] = {funcLength, cie.personalitySymbol, lsdaIsec};
1587e183bf8eSJez Ng     funcSym->unwindEntry = isec;
1588e183bf8eSJez Ng     ehRelocator.commit();
1589e183bf8eSJez Ng   }
1590*a5ae700cSShoaib Meenai 
1591*a5ae700cSShoaib Meenai   // __eh_frame is marked as S_ATTR_LIVE_SUPPORT in input files, because FDEs
1592*a5ae700cSShoaib Meenai   // are normally required to be kept alive if they reference a live symbol.
1593*a5ae700cSShoaib Meenai   // However, we've explicitly created a dependency from a symbol to its FDE, so
1594*a5ae700cSShoaib Meenai   // dead-stripping will just work as usual, and S_ATTR_LIVE_SUPPORT will only
1595*a5ae700cSShoaib Meenai   // serve to incorrectly prevent us from dead-stripping duplicate FDEs for a
1596*a5ae700cSShoaib Meenai   // live symbol (e.g. if there were multiple weak copies). Remove this flag to
1597*a5ae700cSShoaib Meenai   // let dead-stripping proceed correctly.
1598*a5ae700cSShoaib Meenai   ehFrameSection.flags &= ~S_ATTR_LIVE_SUPPORT;
1599e183bf8eSJez Ng }
1600e183bf8eSJez Ng 
sourceFile() const16015792797cSDaniel Bertalan std::string ObjFile::sourceFile() const {
16025792797cSDaniel Bertalan   SmallString<261> dir(compileUnit->getCompilationDir());
16035792797cSDaniel Bertalan   StringRef sep = sys::path::get_separator();
16045792797cSDaniel Bertalan   // We don't use `path::append` here because we want an empty `dir` to result
16055792797cSDaniel Bertalan   // in an absolute path. `append` would give us a relative path for that case.
16065792797cSDaniel Bertalan   if (!dir.endswith(sep))
16075792797cSDaniel Bertalan     dir += sep;
16085792797cSDaniel Bertalan   return (dir + compileUnit->getUnitDIE().getShortName()).str();
16095792797cSDaniel Bertalan }
16105792797cSDaniel Bertalan 
getDwarf()16115792797cSDaniel Bertalan lld::DWARFCache *ObjFile::getDwarf() {
16125792797cSDaniel Bertalan   llvm::call_once(initDwarf, [this]() {
16135792797cSDaniel Bertalan     auto dwObj = DwarfObject::create(this);
16145792797cSDaniel Bertalan     if (!dwObj)
16155792797cSDaniel Bertalan       return;
16165792797cSDaniel Bertalan     dwarfCache = std::make_unique<DWARFCache>(std::make_unique<DWARFContext>(
16175792797cSDaniel Bertalan         std::move(dwObj), "",
16185792797cSDaniel Bertalan         [&](Error err) { warn(getName() + ": " + toString(std::move(err))); },
16195792797cSDaniel Bertalan         [&](Error warning) {
16205792797cSDaniel Bertalan           warn(getName() + ": " + toString(std::move(warning)));
16215792797cSDaniel Bertalan         }));
16225792797cSDaniel Bertalan   });
16235792797cSDaniel Bertalan 
16245792797cSDaniel Bertalan   return dwarfCache.get();
16255792797cSDaniel Bertalan }
16267394460dSJez Ng // The path can point to either a dylib or a .tbd file.
loadDylib(StringRef path,DylibFile * umbrella)16278f89c054SVy Nguyen static DylibFile *loadDylib(StringRef path, DylibFile *umbrella) {
16284af1522aSGreg McGary   Optional<MemoryBufferRef> mbref = readFile(path);
16297394460dSJez Ng   if (!mbref) {
16307394460dSJez Ng     error("could not read dylib file at " + path);
16318f89c054SVy Nguyen     return nullptr;
16327394460dSJez Ng   }
163376c36c11SJez Ng   return loadDylib(*mbref, umbrella);
16347394460dSJez Ng }
16357394460dSJez Ng 
16367394460dSJez Ng // TBD files are parsed into a series of TAPI documents (InterfaceFiles), with
16377394460dSJez Ng // the first document storing child pointers to the rest of them. When we are
16389a2e2de1SVy Nguyen // processing a given TBD file, we store that top-level document in
16399a2e2de1SVy Nguyen // currentTopLevelTapi. When processing re-exports, we search its children for
16409a2e2de1SVy Nguyen // potentially matching documents in the same TBD file. Note that the children
16419a2e2de1SVy Nguyen // themselves don't point to further documents, i.e. this is a two-level tree.
16427394460dSJez Ng //
16437394460dSJez Ng // Re-exports can either refer to on-disk files, or to documents within .tbd
16447394460dSJez Ng // files.
findDylib(StringRef path,DylibFile * umbrella,const InterfaceFile * currentTopLevelTapi)164552489021SNico Weber static DylibFile *findDylib(StringRef path, DylibFile *umbrella,
16469a2e2de1SVy Nguyen                             const InterfaceFile *currentTopLevelTapi) {
16478e8701abSNico Weber   // Search order:
16488e8701abSNico Weber   // 1. Install name basename in -F / -L directories.
16498e8701abSNico Weber   {
16508e8701abSNico Weber     StringRef stem = path::stem(path);
16518e8701abSNico Weber     SmallString<128> frameworkName;
1652dd57915bSNico Weber     path::append(frameworkName, path::Style::posix, stem + ".framework", stem);
16538e8701abSNico Weber     bool isFramework = path.endswith(frameworkName);
16548e8701abSNico Weber     if (isFramework) {
16558e8701abSNico Weber       for (StringRef dir : config->frameworkSearchPaths) {
16568e8701abSNico Weber         SmallString<128> candidate = dir;
16578e8701abSNico Weber         path::append(candidate, frameworkName);
1658aab0f226SKaining Zhong         if (Optional<StringRef> dylibPath = resolveDylibPath(candidate.str()))
16598e8701abSNico Weber           return loadDylib(*dylibPath, umbrella);
16608e8701abSNico Weber       }
16618e8701abSNico Weber     } else if (Optional<StringRef> dylibPath = findPathCombination(
16628e8701abSNico Weber                    stem, config->librarySearchPaths, {".tbd", ".dylib"}))
16638e8701abSNico Weber       return loadDylib(*dylibPath, umbrella);
16648e8701abSNico Weber   }
16658e8701abSNico Weber 
16668e8701abSNico Weber   // 2. As absolute path.
16677394460dSJez Ng   if (path::is_absolute(path, path::Style::posix))
16687394460dSJez Ng     for (StringRef root : config->systemLibraryRoots)
1669aab0f226SKaining Zhong       if (Optional<StringRef> dylibPath = resolveDylibPath((root + path).str()))
16707394460dSJez Ng         return loadDylib(*dylibPath, umbrella);
16717394460dSJez Ng 
16728e8701abSNico Weber   // 3. As relative path.
16738e8701abSNico Weber 
1674c5ffe979SNico Weber   // TODO: Handle -dylib_file
1675c5ffe979SNico Weber 
16768e8701abSNico Weber   // Replace @executable_path, @loader_path, @rpath prefixes in install name.
1677a48bd587SNico Weber   SmallString<128> newPath;
1678a48bd587SNico Weber   if (config->outputType == MH_EXECUTE &&
1679a48bd587SNico Weber       path.consume_front("@executable_path/")) {
1680a48bd587SNico Weber     // ld64 allows overriding this with the undocumented flag -executable_path.
1681a48bd587SNico Weber     // lld doesn't currently implement that flag.
16822c25f39fSNico Weber     // FIXME: Consider using finalOutput instead of outputFile.
16830e399eb5SNico Weber     path::append(newPath, path::parent_path(config->outputFile), path);
1684a48bd587SNico Weber     path = newPath;
168552489021SNico Weber   } else if (path.consume_front("@loader_path/")) {
16860e399eb5SNico Weber     fs::real_path(umbrella->getName(), newPath);
16870e399eb5SNico Weber     path::remove_filename(newPath);
16880e399eb5SNico Weber     path::append(newPath, path);
168952489021SNico Weber     path = newPath;
1690c5ffe979SNico Weber   } else if (path.startswith("@rpath/")) {
1691c5ffe979SNico Weber     for (StringRef rpath : umbrella->rpaths) {
1692c5ffe979SNico Weber       newPath.clear();
16930e399eb5SNico Weber       if (rpath.consume_front("@loader_path/")) {
16940e399eb5SNico Weber         fs::real_path(umbrella->getName(), newPath);
16950e399eb5SNico Weber         path::remove_filename(newPath);
16960e399eb5SNico Weber       }
1697c5ffe979SNico Weber       path::append(newPath, rpath, path.drop_front(strlen("@rpath/")));
1698aab0f226SKaining Zhong       if (Optional<StringRef> dylibPath = resolveDylibPath(newPath.str()))
1699c5ffe979SNico Weber         return loadDylib(*dylibPath, umbrella);
1700c5ffe979SNico Weber     }
1701a48bd587SNico Weber   }
17027394460dSJez Ng 
17038e8701abSNico Weber   // FIXME: Should this be further up?
17049c702814SJez Ng   if (currentTopLevelTapi) {
17057394460dSJez Ng     for (InterfaceFile &child :
17067394460dSJez Ng          make_pointee_range(currentTopLevelTapi->documents())) {
17078601be80SJez Ng       assert(child.documents().empty());
17086881f29aSJez Ng       if (path == child.getInstallName()) {
17093254f468SNico Weber         auto file = make<DylibFile>(child, umbrella, /*isBundleLoader=*/false,
17103254f468SNico Weber                                     /*explicitlyLinked=*/false);
17116881f29aSJez Ng         file->parseReexports(child);
17126881f29aSJez Ng         return file;
17136881f29aSJez Ng       }
17147394460dSJez Ng     }
17157394460dSJez Ng   }
17167394460dSJez Ng 
1717aab0f226SKaining Zhong   if (Optional<StringRef> dylibPath = resolveDylibPath(path))
17187394460dSJez Ng     return loadDylib(*dylibPath, umbrella);
17197394460dSJez Ng 
17208f89c054SVy Nguyen   return nullptr;
17217394460dSJez Ng }
17227394460dSJez Ng 
17236a348f61SJez Ng // If a re-exported dylib is public (lives in /usr/lib or
17246a348f61SJez Ng // /System/Library/Frameworks), then it is considered implicitly linked: we
17256a348f61SJez Ng // should bind to its symbols directly instead of via the re-exporting umbrella
17266a348f61SJez Ng // library.
isImplicitlyLinked(StringRef path)17276a348f61SJez Ng static bool isImplicitlyLinked(StringRef path) {
17286a348f61SJez Ng   if (!config->implicitDylibs)
17296a348f61SJez Ng     return false;
17306a348f61SJez Ng 
17313aa8e071SJez Ng   if (path::parent_path(path) == "/usr/lib")
17323aa8e071SJez Ng     return true;
17333aa8e071SJez Ng 
17343aa8e071SJez Ng   // Match /System/Library/Frameworks/$FOO.framework/**/$FOO
17353aa8e071SJez Ng   if (path.consume_front("/System/Library/Frameworks/")) {
17363aa8e071SJez Ng     StringRef frameworkName = path.take_until([](char c) { return c == '.'; });
17373aa8e071SJez Ng     return path::filename(path) == frameworkName;
17383aa8e071SJez Ng   }
17393aa8e071SJez Ng 
17403aa8e071SJez Ng   return false;
17416a348f61SJez Ng }
17426a348f61SJez Ng 
loadReexport(StringRef path,DylibFile * umbrella,const InterfaceFile * currentTopLevelTapi)174352489021SNico Weber static void loadReexport(StringRef path, DylibFile *umbrella,
17449a2e2de1SVy Nguyen                          const InterfaceFile *currentTopLevelTapi) {
17458f89c054SVy Nguyen   DylibFile *reexport = findDylib(path, umbrella, currentTopLevelTapi);
17468174f33dSNico Weber   if (!reexport)
17478174f33dSNico Weber     error("unable to locate re-export with install name " + path);
17486a348f61SJez Ng }
17496a348f61SJez Ng 
DylibFile(MemoryBufferRef mb,DylibFile * umbrella,bool isBundleLoader,bool explicitlyLinked)17505a856f5bSVy Nguyen DylibFile::DylibFile(MemoryBufferRef mb, DylibFile *umbrella,
17513254f468SNico Weber                      bool isBundleLoader, bool explicitlyLinked)
17525a856f5bSVy Nguyen     : InputFile(DylibKind, mb), refState(RefState::Unreferenced),
17533254f468SNico Weber       explicitlyLinked(explicitlyLinked), isBundleLoader(isBundleLoader) {
17545a856f5bSVy Nguyen   assert(!isBundleLoader || !umbrella);
175587b6fd3eSJez Ng   if (umbrella == nullptr)
175687b6fd3eSJez Ng     umbrella = this;
17576881f29aSJez Ng   this->umbrella = umbrella;
175887b6fd3eSJez Ng 
1759001ba653SJez Ng   auto *hdr = reinterpret_cast<const mach_header *>(mb.getBufferStart());
1760060efd24SJez Ng 
17617def7006SNico Weber   // Initialize installName.
1762060efd24SJez Ng   if (const load_command *cmd = findCommand(hdr, LC_ID_DYLIB)) {
1763060efd24SJez Ng     auto *c = reinterpret_cast<const dylib_command *>(cmd);
1764ec88746aSNico Weber     currentVersion = read32le(&c->dylib.current_version);
1765ec88746aSNico Weber     compatibilityVersion = read32le(&c->dylib.compatibility_version);
17667def7006SNico Weber     installName =
17677def7006SNico Weber         reinterpret_cast<const char *>(cmd) + read32le(&c->dylib.name);
17685a856f5bSVy Nguyen   } else if (!isBundleLoader) {
17695a856f5bSVy Nguyen     // macho_executable and macho_bundle don't have LC_ID_DYLIB,
17705a856f5bSVy Nguyen     // so it's OK.
1771b2f00f24SNico Weber     error("dylib " + toString(this) + " missing LC_ID_DYLIB load command");
1772060efd24SJez Ng     return;
1773060efd24SJez Ng   }
1774060efd24SJez Ng 
1775476e4d65SNico Weber   if (config->printEachFile)
1776476e4d65SNico Weber     message(toString(this));
177717c43c40SNico Weber   inputFiles.insert(this);
1778476e4d65SNico Weber 
17792c190341SNico Weber   deadStrippable = hdr->flags & MH_DEAD_STRIPPABLE_DYLIB;
17802c190341SNico Weber 
1781001ba653SJez Ng   if (!checkCompatibility(this))
1782fc5d804dSVy Nguyen     return;
1783fc5d804dSVy Nguyen 
1784f21801daSNico Weber   checkAppExtensionSafety(hdr->flags & MH_APP_EXTENSION_SAFE);
1785f21801daSNico Weber 
1786c5ffe979SNico Weber   for (auto *cmd : findCommands<rpath_command>(hdr, LC_RPATH)) {
1787c5ffe979SNico Weber     StringRef rpath{reinterpret_cast<const char *>(cmd) + cmd->path};
1788c5ffe979SNico Weber     rpaths.push_back(rpath);
1789c5ffe979SNico Weber   }
1790c5ffe979SNico Weber 
1791060efd24SJez Ng   // Initialize symbols.
17927def7006SNico Weber   exportingFile = isImplicitlyLinked(installName) ? this : this->umbrella;
179394e0f8e0SDaniel Bertalan 
179494e0f8e0SDaniel Bertalan   const auto *dyldInfo = findCommand<dyld_info_command>(hdr, LC_DYLD_INFO_ONLY);
179594e0f8e0SDaniel Bertalan   const auto *exportsTrie =
179694e0f8e0SDaniel Bertalan       findCommand<linkedit_data_command>(hdr, LC_DYLD_EXPORTS_TRIE);
179794e0f8e0SDaniel Bertalan   if (dyldInfo && exportsTrie) {
179894e0f8e0SDaniel Bertalan     // It's unclear what should happen in this case. Maybe we should only error
179994e0f8e0SDaniel Bertalan     // out if the two load commands refer to different data?
180094e0f8e0SDaniel Bertalan     error("dylib " + toString(this) +
180194e0f8e0SDaniel Bertalan           " has both LC_DYLD_INFO_ONLY and LC_DYLD_EXPORTS_TRIE");
180294e0f8e0SDaniel Bertalan     return;
180394e0f8e0SDaniel Bertalan   } else if (dyldInfo) {
180494e0f8e0SDaniel Bertalan     parseExportedSymbols(dyldInfo->export_off, dyldInfo->export_size);
180594e0f8e0SDaniel Bertalan   } else if (exportsTrie) {
180694e0f8e0SDaniel Bertalan     parseExportedSymbols(exportsTrie->dataoff, exportsTrie->datasize);
180794e0f8e0SDaniel Bertalan   } else {
180894e0f8e0SDaniel Bertalan     error("No LC_DYLD_INFO_ONLY or LC_DYLD_EXPORTS_TRIE found in " +
180994e0f8e0SDaniel Bertalan           toString(this));
181094e0f8e0SDaniel Bertalan     return;
181194e0f8e0SDaniel Bertalan   }
181294e0f8e0SDaniel Bertalan }
181394e0f8e0SDaniel Bertalan 
parseExportedSymbols(uint32_t offset,uint32_t size)181494e0f8e0SDaniel Bertalan void DylibFile::parseExportedSymbols(uint32_t offset, uint32_t size) {
18154f90e67eSVy Nguyen   struct TrieEntry {
18164f90e67eSVy Nguyen     StringRef name;
18174f90e67eSVy Nguyen     uint64_t flags;
18184f90e67eSVy Nguyen   };
18194f90e67eSVy Nguyen 
182094e0f8e0SDaniel Bertalan   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
18214f90e67eSVy Nguyen   std::vector<TrieEntry> entries;
18224f90e67eSVy Nguyen   // Find all the $ld$* symbols to process first.
182394e0f8e0SDaniel Bertalan   parseTrie(buf + offset, size, [&](const Twine &name, uint64_t flags) {
182483d59e05SAlexandre Ganea     StringRef savedName = saver().save(name);
18255e49ee87SAlexander Shaposhnikov     if (handleLDSymbol(savedName))
18261309c181SAlexander Shaposhnikov       return;
18274f90e67eSVy Nguyen     entries.push_back({savedName, flags});
18287bbdbacdSJez Ng   });
18294f90e67eSVy Nguyen 
18304f90e67eSVy Nguyen   // Process the "normal" symbols.
18314f90e67eSVy Nguyen   for (TrieEntry &entry : entries) {
183294e0f8e0SDaniel Bertalan     if (exportingFile->hiddenSymbols.contains(CachedHashStringRef(entry.name)))
18334f90e67eSVy Nguyen       continue;
18344f90e67eSVy Nguyen 
18354f90e67eSVy Nguyen     bool isWeakDef = entry.flags & EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION;
18364f90e67eSVy Nguyen     bool isTlv = entry.flags & EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL;
18374f90e67eSVy Nguyen 
18384f90e67eSVy Nguyen     symbols.push_back(
18394f90e67eSVy Nguyen         symtab->addDylib(entry.name, exportingFile, isWeakDef, isTlv));
18404f90e67eSVy Nguyen   }
184124979e11SNico Weber }
184287b6fd3eSJez Ng 
parseLoadCommands(MemoryBufferRef mb)18436881f29aSJez Ng void DylibFile::parseLoadCommands(MemoryBufferRef mb) {
184424979e11SNico Weber   auto *hdr = reinterpret_cast<const mach_header *>(mb.getBufferStart());
184524979e11SNico Weber   const uint8_t *p = reinterpret_cast<const uint8_t *>(mb.getBufferStart()) +
184624979e11SNico Weber                      target->headerSize;
184787b6fd3eSJez Ng   for (uint32_t i = 0, n = hdr->ncmds; i < n; ++i) {
184887b6fd3eSJez Ng     auto *cmd = reinterpret_cast<const load_command *>(p);
184987b6fd3eSJez Ng     p += cmd->cmdsize;
185087b6fd3eSJez Ng 
18518174f33dSNico Weber     if (!(hdr->flags & MH_NO_REEXPORTED_DYLIBS) &&
18528174f33dSNico Weber         cmd->cmd == LC_REEXPORT_DYLIB) {
18538174f33dSNico Weber       const auto *c = reinterpret_cast<const dylib_command *>(cmd);
185487b6fd3eSJez Ng       StringRef reexportPath =
185587b6fd3eSJez Ng           reinterpret_cast<const char *>(c) + read32le(&c->dylib.name);
18565d9aafc0SJez Ng       loadReexport(reexportPath, exportingFile, nullptr);
1857060efd24SJez Ng     }
18588174f33dSNico Weber 
18598174f33dSNico Weber     // FIXME: What about LC_LOAD_UPWARD_DYLIB, LC_LAZY_LOAD_DYLIB,
18608174f33dSNico Weber     // LC_LOAD_WEAK_DYLIB, LC_REEXPORT_DYLIB (..are reexports from dylibs with
18618174f33dSNico Weber     // MH_NO_REEXPORTED_DYLIBS loaded for -flat_namespace)?
18628174f33dSNico Weber     if (config->namespaceKind == NamespaceKind::flat &&
18638174f33dSNico Weber         cmd->cmd == LC_LOAD_DYLIB) {
18648174f33dSNico Weber       const auto *c = reinterpret_cast<const dylib_command *>(cmd);
18658174f33dSNico Weber       StringRef dylibPath =
18668174f33dSNico Weber           reinterpret_cast<const char *>(c) + read32le(&c->dylib.name);
18678f89c054SVy Nguyen       DylibFile *dylib = findDylib(dylibPath, umbrella, nullptr);
18688174f33dSNico Weber       if (!dylib)
18698174f33dSNico Weber         error(Twine("unable to locate library '") + dylibPath +
18708174f33dSNico Weber               "' loaded from '" + toString(this) + "' for -flat_namespace");
18718174f33dSNico Weber     }
18728174f33dSNico Weber   }
1873060efd24SJez Ng }
1874060efd24SJez Ng 
18753254f468SNico Weber // Some versions of Xcode ship with .tbd files that don't have the right
187624979e11SNico Weber // platform settings.
1877010acc52SNico Weber constexpr std::array<StringRef, 3> skipPlatformChecks{
187824979e11SNico Weber     "/usr/lib/system/libsystem_kernel.dylib",
187924979e11SNico Weber     "/usr/lib/system/libsystem_platform.dylib",
1880010acc52SNico Weber     "/usr/lib/system/libsystem_pthread.dylib"};
188124979e11SNico Weber 
skipPlatformCheckForCatalyst(const InterfaceFile & interface,bool explicitlyLinked)18823254f468SNico Weber static bool skipPlatformCheckForCatalyst(const InterfaceFile &interface,
18833254f468SNico Weber                                          bool explicitlyLinked) {
18843254f468SNico Weber   // Catalyst outputs can link against implicitly linked macOS-only libraries.
18853254f468SNico Weber   if (config->platform() != PLATFORM_MACCATALYST || explicitlyLinked)
18863254f468SNico Weber     return false;
18873254f468SNico Weber   return is_contained(interface.targets(),
18883254f468SNico Weber                       MachO::Target(config->arch(), PLATFORM_MACOS));
18893254f468SNico Weber }
18903254f468SNico Weber 
DylibFile(const InterfaceFile & interface,DylibFile * umbrella,bool isBundleLoader,bool explicitlyLinked)18915a856f5bSVy Nguyen DylibFile::DylibFile(const InterfaceFile &interface, DylibFile *umbrella,
18923254f468SNico Weber                      bool isBundleLoader, bool explicitlyLinked)
18935a856f5bSVy Nguyen     : InputFile(DylibKind, interface), refState(RefState::Unreferenced),
18943254f468SNico Weber       explicitlyLinked(explicitlyLinked), isBundleLoader(isBundleLoader) {
18955a856f5bSVy Nguyen   // FIXME: Add test for the missing TBD code path.
18965a856f5bSVy Nguyen 
18976fe27b5fSSaleem Abdulrasool   if (umbrella == nullptr)
18986fe27b5fSSaleem Abdulrasool     umbrella = this;
18996881f29aSJez Ng   this->umbrella = umbrella;
19006fe27b5fSSaleem Abdulrasool 
190183d59e05SAlexandre Ganea   installName = saver().save(interface.getInstallName());
19020d4dadc6SJez Ng   compatibilityVersion = interface.getCompatibilityVersion().rawValue();
19030d4dadc6SJez Ng   currentVersion = interface.getCurrentVersion().rawValue();
19040d4dadc6SJez Ng 
1905476e4d65SNico Weber   if (config->printEachFile)
1906476e4d65SNico Weber     message(toString(this));
190717c43c40SNico Weber   inputFiles.insert(this);
1908476e4d65SNico Weber 
19097def7006SNico Weber   if (!is_contained(skipPlatformChecks, installName) &&
19103254f468SNico Weber       !is_contained(interface.targets(), config->platformInfo.target) &&
19113254f468SNico Weber       !skipPlatformCheckForCatalyst(interface, explicitlyLinked)) {
19124752cdc9SJez Ng     error(toString(this) + " is incompatible with " +
19135c835e1aSAlexander Shaposhnikov           std::string(config->platformInfo.target));
19144752cdc9SJez Ng     return;
19154752cdc9SJez Ng   }
19164752cdc9SJez Ng 
1917f21801daSNico Weber   checkAppExtensionSafety(interface.isApplicationExtensionSafe());
1918f21801daSNico Weber 
19197def7006SNico Weber   exportingFile = isImplicitlyLinked(installName) ? this : umbrella;
1920a499898eSJez Ng   auto addSymbol = [&](const Twine &name) -> void {
192183d59e05SAlexandre Ganea     StringRef savedName = saver().save(name);
19224f90e67eSVy Nguyen     if (exportingFile->hiddenSymbols.contains(CachedHashStringRef(savedName)))
19234f90e67eSVy Nguyen       return;
19244f90e67eSVy Nguyen 
19254f90e67eSVy Nguyen     symbols.push_back(symtab->addDylib(savedName, exportingFile,
1926a499898eSJez Ng                                        /*isWeakDef=*/false,
1927a499898eSJez Ng                                        /*isTlv=*/false));
1928a499898eSJez Ng   };
19294f90e67eSVy Nguyen 
19304f90e67eSVy Nguyen   std::vector<const llvm::MachO::Symbol *> normalSymbols;
19314f90e67eSVy Nguyen   normalSymbols.reserve(interface.symbolsCount());
1932fdc0c219SGreg McGary   for (const auto *symbol : interface.symbols()) {
1933ed4a4e33SJez Ng     if (!symbol->getArchitectures().has(config->arch()))
1934a499898eSJez Ng       continue;
19355e49ee87SAlexander Shaposhnikov     if (handleLDSymbol(symbol->getName()))
19361309c181SAlexander Shaposhnikov       continue;
19371309c181SAlexander Shaposhnikov 
1938a499898eSJez Ng     switch (symbol->getKind()) {
19394f90e67eSVy Nguyen     case SymbolKind::GlobalSymbol:               // Fallthrough
19404f90e67eSVy Nguyen     case SymbolKind::ObjectiveCClass:            // Fallthrough
19414f90e67eSVy Nguyen     case SymbolKind::ObjectiveCClassEHType:      // Fallthrough
19424f90e67eSVy Nguyen     case SymbolKind::ObjectiveCInstanceVariable: // Fallthrough
19434f90e67eSVy Nguyen       normalSymbols.push_back(symbol);
19444f90e67eSVy Nguyen     }
19454f90e67eSVy Nguyen   }
19464f90e67eSVy Nguyen 
19474f90e67eSVy Nguyen   // TODO(compnerd) filter out symbols based on the target platform
19484f90e67eSVy Nguyen   // TODO: handle weak defs, thread locals
19494f90e67eSVy Nguyen   for (const auto *symbol : normalSymbols) {
19504f90e67eSVy Nguyen     switch (symbol->getKind()) {
1951a499898eSJez Ng     case SymbolKind::GlobalSymbol:
1952a499898eSJez Ng       addSymbol(symbol->getName());
1953a499898eSJez Ng       break;
1954a499898eSJez Ng     case SymbolKind::ObjectiveCClass:
1955a499898eSJez Ng       // XXX ld64 only creates these symbols when -ObjC is passed in. We may
1956a499898eSJez Ng       // want to emulate that.
1957cf918c80SJez Ng       addSymbol(objc::klass + symbol->getName());
1958cf918c80SJez Ng       addSymbol(objc::metaclass + symbol->getName());
1959a499898eSJez Ng       break;
1960a499898eSJez Ng     case SymbolKind::ObjectiveCClassEHType:
1961cf918c80SJez Ng       addSymbol(objc::ehtype + symbol->getName());
1962a499898eSJez Ng       break;
1963a499898eSJez Ng     case SymbolKind::ObjectiveCInstanceVariable:
1964cf918c80SJez Ng       addSymbol(objc::ivar + symbol->getName());
1965a499898eSJez Ng       break;
1966a499898eSJez Ng     }
1967a499898eSJez Ng   }
196824979e11SNico Weber }
19697394460dSJez Ng 
DylibFile(DylibFile * umbrella)197008c239e2SNico Weber DylibFile::DylibFile(DylibFile *umbrella)
197108c239e2SNico Weber     : InputFile(DylibKind, MemoryBufferRef{}), refState(RefState::Unreferenced),
197208c239e2SNico Weber       explicitlyLinked(false), isBundleLoader(false) {
197308c239e2SNico Weber   if (umbrella == nullptr)
197408c239e2SNico Weber     umbrella = this;
197508c239e2SNico Weber   this->umbrella = umbrella;
197608c239e2SNico Weber }
197708c239e2SNico Weber 
parseReexports(const InterfaceFile & interface)19786881f29aSJez Ng void DylibFile::parseReexports(const InterfaceFile &interface) {
19799a2e2de1SVy Nguyen   const InterfaceFile *topLevel =
19809a2e2de1SVy Nguyen       interface.getParent() == nullptr ? &interface : interface.getParent();
19813f35dd06SVy Nguyen   for (const InterfaceFileRef &intfRef : interface.reexportedLibraries()) {
1982fdc0c219SGreg McGary     InterfaceFile::const_target_range targets = intfRef.targets();
19837208bd4bSJez Ng     if (is_contained(skipPlatformChecks, intfRef.getInstallName()) ||
19845c835e1aSAlexander Shaposhnikov         is_contained(targets, config->platformInfo.target))
19855d9aafc0SJez Ng       loadReexport(intfRef.getInstallName(), exportingFile, topLevel);
19866fe27b5fSSaleem Abdulrasool   }
198755a32812SJez Ng }
19886fe27b5fSSaleem Abdulrasool 
isExplicitlyLinked() const198908c239e2SNico Weber bool DylibFile::isExplicitlyLinked() const {
199008c239e2SNico Weber   if (!explicitlyLinked)
199108c239e2SNico Weber     return false;
199208c239e2SNico Weber 
199308c239e2SNico Weber   // If this dylib was explicitly linked, but at least one of the symbols
199408c239e2SNico Weber   // of the synthetic dylibs it created via $ld$previous symbols is
199508c239e2SNico Weber   // referenced, then that synthetic dylib fulfils the explicit linkedness
199608c239e2SNico Weber   // and we can deadstrip this dylib if it's unreferenced.
199708c239e2SNico Weber   for (const auto *dylib : extraDylibs)
199808c239e2SNico Weber     if (dylib->isReferenced())
199908c239e2SNico Weber       return false;
200008c239e2SNico Weber 
200108c239e2SNico Weber   return true;
200208c239e2SNico Weber }
200308c239e2SNico Weber 
getSyntheticDylib(StringRef installName,uint32_t currentVersion,uint32_t compatVersion)200408c239e2SNico Weber DylibFile *DylibFile::getSyntheticDylib(StringRef installName,
200508c239e2SNico Weber                                         uint32_t currentVersion,
200608c239e2SNico Weber                                         uint32_t compatVersion) {
200708c239e2SNico Weber   for (DylibFile *dylib : extraDylibs)
200808c239e2SNico Weber     if (dylib->installName == installName) {
200908c239e2SNico Weber       // FIXME: Check what to do if different $ld$previous symbols
201008c239e2SNico Weber       // request the same dylib, but with different versions.
201108c239e2SNico Weber       return dylib;
201208c239e2SNico Weber     }
201308c239e2SNico Weber 
201408c239e2SNico Weber   auto *dylib = make<DylibFile>(umbrella == this ? nullptr : umbrella);
201508c239e2SNico Weber   dylib->installName = saver().save(installName);
201608c239e2SNico Weber   dylib->currentVersion = currentVersion;
201708c239e2SNico Weber   dylib->compatibilityVersion = compatVersion;
201808c239e2SNico Weber   extraDylibs.push_back(dylib);
201908c239e2SNico Weber   return dylib;
202008c239e2SNico Weber }
202108c239e2SNico Weber 
20221309c181SAlexander Shaposhnikov // $ld$ symbols modify the properties/behavior of the library (e.g. its install
20231309c181SAlexander Shaposhnikov // name, compatibility version or hide/add symbols) for specific target
20241309c181SAlexander Shaposhnikov // versions.
handleLDSymbol(StringRef originalName)20255e49ee87SAlexander Shaposhnikov bool DylibFile::handleLDSymbol(StringRef originalName) {
20261309c181SAlexander Shaposhnikov   if (!originalName.startswith("$ld$"))
20271309c181SAlexander Shaposhnikov     return false;
20281309c181SAlexander Shaposhnikov 
20291309c181SAlexander Shaposhnikov   StringRef action;
20301309c181SAlexander Shaposhnikov   StringRef name;
2031e9104374SNico Weber   std::tie(action, name) = originalName.drop_front(strlen("$ld$")).split('$');
20325e49ee87SAlexander Shaposhnikov   if (action == "previous")
20335e49ee87SAlexander Shaposhnikov     handleLDPreviousSymbol(name, originalName);
20345e49ee87SAlexander Shaposhnikov   else if (action == "install_name")
20355e49ee87SAlexander Shaposhnikov     handleLDInstallNameSymbol(name, originalName);
20364f90e67eSVy Nguyen   else if (action == "hide")
20374f90e67eSVy Nguyen     handleLDHideSymbol(name, originalName);
20381309c181SAlexander Shaposhnikov   return true;
20395e49ee87SAlexander Shaposhnikov }
20401309c181SAlexander Shaposhnikov 
handleLDPreviousSymbol(StringRef name,StringRef originalName)20415e49ee87SAlexander Shaposhnikov void DylibFile::handleLDPreviousSymbol(StringRef name, StringRef originalName) {
20425e49ee87SAlexander Shaposhnikov   // originalName: $ld$ previous $ <installname> $ <compatversion> $
20435e49ee87SAlexander Shaposhnikov   // <platformstr> $ <startversion> $ <endversion> $ <symbol-name> $
20441309c181SAlexander Shaposhnikov   StringRef installName;
20451309c181SAlexander Shaposhnikov   StringRef compatVersion;
20461309c181SAlexander Shaposhnikov   StringRef platformStr;
20471309c181SAlexander Shaposhnikov   StringRef startVersion;
20481309c181SAlexander Shaposhnikov   StringRef endVersion;
20491309c181SAlexander Shaposhnikov   StringRef symbolName;
20501309c181SAlexander Shaposhnikov   StringRef rest;
20511309c181SAlexander Shaposhnikov 
20521309c181SAlexander Shaposhnikov   std::tie(installName, name) = name.split('$');
20531309c181SAlexander Shaposhnikov   std::tie(compatVersion, name) = name.split('$');
20541309c181SAlexander Shaposhnikov   std::tie(platformStr, name) = name.split('$');
20551309c181SAlexander Shaposhnikov   std::tie(startVersion, name) = name.split('$');
2056e9104374SNico Weber   std::tie(endVersion, name) = name.split('$');
205708c239e2SNico Weber   std::tie(symbolName, rest) = name.rsplit('$');
205808c239e2SNico Weber 
205908c239e2SNico Weber   // FIXME: Does this do the right thing for zippered files?
20601309c181SAlexander Shaposhnikov   unsigned platform;
20611309c181SAlexander Shaposhnikov   if (platformStr.getAsInteger(10, platform) ||
20621309c181SAlexander Shaposhnikov       platform != static_cast<unsigned>(config->platform()))
20635e49ee87SAlexander Shaposhnikov     return;
20641309c181SAlexander Shaposhnikov 
20651309c181SAlexander Shaposhnikov   VersionTuple start;
20661309c181SAlexander Shaposhnikov   if (start.tryParse(startVersion)) {
20671309c181SAlexander Shaposhnikov     warn("failed to parse start version, symbol '" + originalName +
20681309c181SAlexander Shaposhnikov          "' ignored");
20695e49ee87SAlexander Shaposhnikov     return;
20701309c181SAlexander Shaposhnikov   }
20711309c181SAlexander Shaposhnikov   VersionTuple end;
20721309c181SAlexander Shaposhnikov   if (end.tryParse(endVersion)) {
20731309c181SAlexander Shaposhnikov     warn("failed to parse end version, symbol '" + originalName + "' ignored");
20745e49ee87SAlexander Shaposhnikov     return;
20751309c181SAlexander Shaposhnikov   }
20761309c181SAlexander Shaposhnikov   if (config->platformInfo.minimum < start ||
20771309c181SAlexander Shaposhnikov       config->platformInfo.minimum >= end)
20785e49ee87SAlexander Shaposhnikov     return;
20791309c181SAlexander Shaposhnikov 
208008c239e2SNico Weber   // Initialized to compatibilityVersion for the symbolName branch below.
208108c239e2SNico Weber   uint32_t newCompatibilityVersion = compatibilityVersion;
208208c239e2SNico Weber   uint32_t newCurrentVersionForSymbol = currentVersion;
20831309c181SAlexander Shaposhnikov   if (!compatVersion.empty()) {
20841309c181SAlexander Shaposhnikov     VersionTuple cVersion;
20851309c181SAlexander Shaposhnikov     if (cVersion.tryParse(compatVersion)) {
20861309c181SAlexander Shaposhnikov       warn("failed to parse compatibility version, symbol '" + originalName +
20871309c181SAlexander Shaposhnikov            "' ignored");
20885e49ee87SAlexander Shaposhnikov       return;
20891309c181SAlexander Shaposhnikov     }
209008c239e2SNico Weber     newCompatibilityVersion = encodeVersion(cVersion);
209108c239e2SNico Weber     newCurrentVersionForSymbol = newCompatibilityVersion;
20921309c181SAlexander Shaposhnikov   }
209308c239e2SNico Weber 
209408c239e2SNico Weber   if (!symbolName.empty()) {
209508c239e2SNico Weber     // A $ld$previous$ symbol with symbol name adds a symbol with that name to
209608c239e2SNico Weber     // a dylib with given name and version.
209708c239e2SNico Weber     auto *dylib = getSyntheticDylib(installName, newCurrentVersionForSymbol,
209808c239e2SNico Weber                                     newCompatibilityVersion);
209908c239e2SNico Weber 
210008c239e2SNico Weber     // Just adding the symbol to the symtab works because dylibs contain their
210108c239e2SNico Weber     // symbols in alphabetical order, guaranteeing $ld$ symbols to precede
210208c239e2SNico Weber     // normal symbols.
210308c239e2SNico Weber     dylib->symbols.push_back(symtab->addDylib(
210408c239e2SNico Weber         saver().save(symbolName), dylib, /*isWeakDef=*/false, /*isTlv=*/false));
210508c239e2SNico Weber     return;
210608c239e2SNico Weber   }
210708c239e2SNico Weber 
210808c239e2SNico Weber   // A $ld$previous$ symbol without symbol name modifies the dylib it's in.
210908c239e2SNico Weber   this->installName = saver().save(installName);
211008c239e2SNico Weber   this->compatibilityVersion = newCompatibilityVersion;
21115e49ee87SAlexander Shaposhnikov }
21121309c181SAlexander Shaposhnikov 
handleLDInstallNameSymbol(StringRef name,StringRef originalName)21135e49ee87SAlexander Shaposhnikov void DylibFile::handleLDInstallNameSymbol(StringRef name,
21145e49ee87SAlexander Shaposhnikov                                           StringRef originalName) {
21155e49ee87SAlexander Shaposhnikov   // originalName: $ld$ install_name $ os<version> $ install_name
21165e49ee87SAlexander Shaposhnikov   StringRef condition, installName;
21175e49ee87SAlexander Shaposhnikov   std::tie(condition, installName) = name.split('$');
21185e49ee87SAlexander Shaposhnikov   VersionTuple version;
2119e9104374SNico Weber   if (!condition.consume_front("os") || version.tryParse(condition))
21205e49ee87SAlexander Shaposhnikov     warn("failed to parse os version, symbol '" + originalName + "' ignored");
2121e9104374SNico Weber   else if (version == config->platformInfo.minimum)
212283d59e05SAlexandre Ganea     this->installName = saver().save(installName);
21231309c181SAlexander Shaposhnikov }
21241309c181SAlexander Shaposhnikov 
handleLDHideSymbol(StringRef name,StringRef originalName)21254f90e67eSVy Nguyen void DylibFile::handleLDHideSymbol(StringRef name, StringRef originalName) {
21264f90e67eSVy Nguyen   StringRef symbolName;
21274f90e67eSVy Nguyen   bool shouldHide = true;
21284f90e67eSVy Nguyen   if (name.startswith("os")) {
21294f90e67eSVy Nguyen     // If it's hidden based on versions.
21304f90e67eSVy Nguyen     name = name.drop_front(2);
21314f90e67eSVy Nguyen     StringRef minVersion;
21324f90e67eSVy Nguyen     std::tie(minVersion, symbolName) = name.split('$');
21334f90e67eSVy Nguyen     VersionTuple versionTup;
21344f90e67eSVy Nguyen     if (versionTup.tryParse(minVersion)) {
21354f90e67eSVy Nguyen       warn("Failed to parse hidden version, symbol `" + originalName +
21364f90e67eSVy Nguyen            "` ignored.");
21374f90e67eSVy Nguyen       return;
21384f90e67eSVy Nguyen     }
21394f90e67eSVy Nguyen     shouldHide = versionTup == config->platformInfo.minimum;
21404f90e67eSVy Nguyen   } else {
21414f90e67eSVy Nguyen     symbolName = name;
21424f90e67eSVy Nguyen   }
21434f90e67eSVy Nguyen 
21444f90e67eSVy Nguyen   if (shouldHide)
21454f90e67eSVy Nguyen     exportingFile->hiddenSymbols.insert(CachedHashStringRef(symbolName));
21464f90e67eSVy Nguyen }
21474f90e67eSVy Nguyen 
checkAppExtensionSafety(bool dylibIsAppExtensionSafe) const2148f21801daSNico Weber void DylibFile::checkAppExtensionSafety(bool dylibIsAppExtensionSafe) const {
2149f21801daSNico Weber   if (config->applicationExtension && !dylibIsAppExtensionSafe)
2150f21801daSNico Weber     warn("using '-application_extension' with unsafe dylib: " + toString(this));
2151f21801daSNico Weber }
2152f21801daSNico Weber 
ArchiveFile(std::unique_ptr<object::Archive> && f,bool forceHidden)2153595fc59fSDaniel Bertalan ArchiveFile::ArchiveFile(std::unique_ptr<object::Archive> &&f, bool forceHidden)
2154595fc59fSDaniel Bertalan     : InputFile(ArchiveKind, f->getMemoryBufferRef()), file(std::move(f)),
2155595fc59fSDaniel Bertalan       forceHidden(forceHidden) {}
21569065fe55SJez Ng 
addLazySymbols()21579065fe55SJez Ng void ArchiveFile::addLazySymbols() {
21582b920ae7SKellie Medlin   for (const object::Archive::Symbol &sym : file->symbols())
215997a5dccbSFangrui Song     symtab->addLazyArchive(sym.getName(), this, sym);
21602b920ae7SKellie Medlin }
21612b920ae7SKellie Medlin 
2162595fc59fSDaniel Bertalan static Expected<InputFile *>
loadArchiveMember(MemoryBufferRef mb,uint32_t modTime,StringRef archiveName,uint64_t offsetInArchive,bool forceHidden)2163595fc59fSDaniel Bertalan loadArchiveMember(MemoryBufferRef mb, uint32_t modTime, StringRef archiveName,
2164595fc59fSDaniel Bertalan                   uint64_t offsetInArchive, bool forceHidden) {
21659065fe55SJez Ng   if (config->zeroModTime)
21669065fe55SJez Ng     modTime = 0;
21679065fe55SJez Ng 
21689065fe55SJez Ng   switch (identify_magic(mb.getBuffer())) {
21699065fe55SJez Ng   case file_magic::macho_object:
2170595fc59fSDaniel Bertalan     return make<ObjFile>(mb, modTime, archiveName, /*lazy=*/false, forceHidden);
21719065fe55SJez Ng   case file_magic::bitcode:
2172595fc59fSDaniel Bertalan     return make<BitcodeFile>(mb, archiveName, offsetInArchive, /*lazy=*/false,
2173595fc59fSDaniel Bertalan                              forceHidden);
21749065fe55SJez Ng   default:
21759065fe55SJez Ng     return createStringError(inconvertibleErrorCode(),
21769065fe55SJez Ng                              mb.getBufferIdentifier() +
21779065fe55SJez Ng                                  " has unhandled file type");
21789065fe55SJez Ng   }
21799065fe55SJez Ng }
21809065fe55SJez Ng 
fetch(const object::Archive::Child & c,StringRef reason)21819065fe55SJez Ng Error ArchiveFile::fetch(const object::Archive::Child &c, StringRef reason) {
21829065fe55SJez Ng   if (!seen.insert(c.getChildOffset()).second)
21839065fe55SJez Ng     return Error::success();
21849065fe55SJez Ng 
21859065fe55SJez Ng   Expected<MemoryBufferRef> mb = c.getMemoryBufferRef();
21869065fe55SJez Ng   if (!mb)
21879065fe55SJez Ng     return mb.takeError();
21889065fe55SJez Ng 
21899065fe55SJez Ng   // Thin archives refer to .o files, so --reproduce needs the .o files too.
21909065fe55SJez Ng   if (tar && c.getParent()->isThin())
21919065fe55SJez Ng     tar->append(relativeToRoot(CHECK(c.getFullName(), this)), mb->getBuffer());
21929065fe55SJez Ng 
21939065fe55SJez Ng   Expected<TimePoint<std::chrono::seconds>> modTime = c.getLastModified();
21949065fe55SJez Ng   if (!modTime)
21959065fe55SJez Ng     return modTime.takeError();
21969065fe55SJez Ng 
2197595fc59fSDaniel Bertalan   Expected<InputFile *> file = loadArchiveMember(
2198595fc59fSDaniel Bertalan       *mb, toTimeT(*modTime), getName(), c.getChildOffset(), forceHidden);
21999065fe55SJez Ng 
22009065fe55SJez Ng   if (!file)
22019065fe55SJez Ng     return file.takeError();
22029065fe55SJez Ng 
22039065fe55SJez Ng   inputFiles.insert(*file);
22049065fe55SJez Ng   printArchiveMemberLoad(reason, *file);
22059065fe55SJez Ng   return Error::success();
22069065fe55SJez Ng }
22079065fe55SJez Ng 
fetch(const object::Archive::Symbol & sym)22082b920ae7SKellie Medlin void ArchiveFile::fetch(const object::Archive::Symbol &sym) {
22092b920ae7SKellie Medlin   object::Archive::Child c =
22102b920ae7SKellie Medlin       CHECK(sym.getMember(), toString(this) +
22119065fe55SJez Ng                                  ": could not get the member defining symbol " +
221207ab597bSNico Weber                                  toMachOString(sym));
22132b920ae7SKellie Medlin 
22144b456038SNico Weber   // `sym` is owned by a LazySym, which will be replace<>()d by make<ObjFile>
22153422f3ccSNico Weber   // and become invalid after that call. Copy it to the stack so we can refer
22163422f3ccSNico Weber   // to it later.
22174b456038SNico Weber   const object::Archive::Symbol symCopy = sym;
22183422f3ccSNico Weber 
22194b456038SNico Weber   // ld64 doesn't demangle sym here even with -demangle.
22204b456038SNico Weber   // Match that: intentionally don't call toMachOString().
22219065fe55SJez Ng   if (Error e = fetch(c, symCopy.getName()))
22229065fe55SJez Ng     error(toString(this) + ": could not get the member defining symbol " +
22239065fe55SJez Ng           toMachOString(symCopy) + ": " + toString(std::move(e)));
22242b920ae7SKellie Medlin }
22252b920ae7SKellie Medlin 
createBitcodeSymbol(const lto::InputFile::Symbol & objSym,BitcodeFile & file)222684579fc2SJez Ng static macho::Symbol *createBitcodeSymbol(const lto::InputFile::Symbol &objSym,
222784579fc2SJez Ng                                           BitcodeFile &file) {
222883d59e05SAlexandre Ganea   StringRef name = saver().save(objSym.getName());
222984579fc2SJez Ng 
223084579fc2SJez Ng   if (objSym.isUndefined())
2231c4b45eebSNico Weber     return symtab->addUndefined(name, &file, /*isWeakRef=*/objSym.isWeak());
223284579fc2SJez Ng 
223384579fc2SJez Ng   // TODO: Write a test demonstrating why computing isPrivateExtern before
223484579fc2SJez Ng   // LTO compilation is important.
223584579fc2SJez Ng   bool isPrivateExtern = false;
223684579fc2SJez Ng   switch (objSym.getVisibility()) {
223784579fc2SJez Ng   case GlobalValue::HiddenVisibility:
223884579fc2SJez Ng     isPrivateExtern = true;
223984579fc2SJez Ng     break;
224084579fc2SJez Ng   case GlobalValue::ProtectedVisibility:
224184579fc2SJez Ng     error(name + " has protected visibility, which is not supported by Mach-O");
224284579fc2SJez Ng     break;
224384579fc2SJez Ng   case GlobalValue::DefaultVisibility:
224484579fc2SJez Ng     break;
224584579fc2SJez Ng   }
2246595fc59fSDaniel Bertalan   isPrivateExtern = isPrivateExtern || objSym.canBeOmittedFromSymbolTable() ||
2247595fc59fSDaniel Bertalan                     file.forceHidden;
224884579fc2SJez Ng 
2249e49374f9SJez Ng   if (objSym.isCommon())
2250e49374f9SJez Ng     return symtab->addCommon(name, &file, objSym.getCommonSize(),
2251e49374f9SJez Ng                              objSym.getCommonAlignment(), isPrivateExtern);
2252e49374f9SJez Ng 
225384579fc2SJez Ng   return symtab->addDefined(name, &file, /*isec=*/nullptr, /*value=*/0,
225405c5363bSJez Ng                             /*size=*/0, objSym.isWeak(), isPrivateExtern,
22554a12248eSNico Weber                             /*isThumb=*/false,
2256a5645513SNico Weber                             /*isReferencedDynamically=*/false,
22579b29dae3SVy Nguyen                             /*noDeadStrip=*/false,
22589b29dae3SVy Nguyen                             /*isWeakDefCanBeHidden=*/false);
225984579fc2SJez Ng }
226084579fc2SJez Ng 
BitcodeFile(MemoryBufferRef mb,StringRef archiveName,uint64_t offsetInArchive,bool lazy,bool forceHidden)22615acc6d45SLeonard Grey BitcodeFile::BitcodeFile(MemoryBufferRef mb, StringRef archiveName,
2262595fc59fSDaniel Bertalan                          uint64_t offsetInArchive, bool lazy, bool forceHidden)
2263595fc59fSDaniel Bertalan     : InputFile(BitcodeKind, mb, lazy), forceHidden(forceHidden) {
22648a1f2d65SJez Ng   this->archiveName = std::string(archiveName);
22655acc6d45SLeonard Grey   std::string path = mb.getBufferIdentifier().str();
22665acc6d45SLeonard Grey   // ThinLTO assumes that all MemoryBufferRefs given to it have a unique
22675acc6d45SLeonard Grey   // name. If two members with the same name are provided, this causes a
22685acc6d45SLeonard Grey   // collision and ThinLTO can't proceed.
22695acc6d45SLeonard Grey   // So, we append the archive name to disambiguate two members with the same
22705acc6d45SLeonard Grey   // name from multiple different archives, and offset within the archive to
22715acc6d45SLeonard Grey   // disambiguate two members of the same name from a single archive.
227283d59e05SAlexandre Ganea   MemoryBufferRef mbref(mb.getBuffer(),
227383d59e05SAlexandre Ganea                         saver().save(archiveName.empty()
227483d59e05SAlexandre Ganea                                          ? path
227583d59e05SAlexandre Ganea                                          : archiveName +
227683d59e05SAlexandre Ganea                                                sys::path::filename(path) +
22775acc6d45SLeonard Grey                                                utostr(offsetInArchive)));
22785acc6d45SLeonard Grey 
227921f83113SJez Ng   obj = check(lto::InputFile::create(mbref));
22800aae2bf3SFangrui Song   if (lazy)
22810aae2bf3SFangrui Song     parseLazy();
22820aae2bf3SFangrui Song   else
22830aae2bf3SFangrui Song     parse();
22840aae2bf3SFangrui Song }
228584579fc2SJez Ng 
parse()22860aae2bf3SFangrui Song void BitcodeFile::parse() {
228784579fc2SJez Ng   // Convert LTO Symbols to LLD Symbols in order to perform resolution. The
228884579fc2SJez Ng   // "winning" symbol will then be marked as Prevailing at LTO compilation
228984579fc2SJez Ng   // time.
22900aae2bf3SFangrui Song   symbols.clear();
229184579fc2SJez Ng   for (const lto::InputFile::Symbol &objSym : obj->symbols())
229284579fc2SJez Ng     symbols.push_back(createBitcodeSymbol(objSym, *this));
229321f83113SJez Ng }
2294817d98d8SJez Ng 
parseLazy()22950aae2bf3SFangrui Song void BitcodeFile::parseLazy() {
22960aae2bf3SFangrui Song   symbols.resize(obj->symbols().size());
22970aae2bf3SFangrui Song   for (auto it : llvm::enumerate(obj->symbols())) {
22980aae2bf3SFangrui Song     const lto::InputFile::Symbol &objSym = it.value();
22990aae2bf3SFangrui Song     if (!objSym.isUndefined()) {
23000aae2bf3SFangrui Song       symbols[it.index()] =
230183d59e05SAlexandre Ganea           symtab->addLazyObject(saver().save(objSym.getName()), *this);
23020aae2bf3SFangrui Song       if (!lazy)
23030aae2bf3SFangrui Song         break;
23040aae2bf3SFangrui Song     }
23050aae2bf3SFangrui Song   }
23060aae2bf3SFangrui Song }
23070aae2bf3SFangrui Song 
extract(InputFile & file,StringRef reason)23080aae2bf3SFangrui Song void macho::extract(InputFile &file, StringRef reason) {
23090aae2bf3SFangrui Song   assert(file.lazy);
23100aae2bf3SFangrui Song   file.lazy = false;
23110aae2bf3SFangrui Song   printArchiveMemberLoad(reason, &file);
23120aae2bf3SFangrui Song   if (auto *bitcode = dyn_cast<BitcodeFile>(&file)) {
23130aae2bf3SFangrui Song     bitcode->parse();
23140aae2bf3SFangrui Song   } else {
23150aae2bf3SFangrui Song     auto &f = cast<ObjFile>(file);
23160aae2bf3SFangrui Song     if (target->wordSize == 8)
23170aae2bf3SFangrui Song       f.parse<LP64>();
23180aae2bf3SFangrui Song     else
23190aae2bf3SFangrui Song       f.parse<ILP32>();
23200aae2bf3SFangrui Song   }
23210aae2bf3SFangrui Song }
23220aae2bf3SFangrui Song 
2323817d98d8SJez Ng template void ObjFile::parse<LP64>();
2324