xref: /freebsd/contrib/llvm-project/lld/MachO/InputFiles.cpp (revision 61cfbce3347e4372143bcabf7b197577b9f3958a)
15ffd83dbSDimitry Andric //===- InputFiles.cpp -----------------------------------------------------===//
25ffd83dbSDimitry Andric //
35ffd83dbSDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
45ffd83dbSDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
55ffd83dbSDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
65ffd83dbSDimitry Andric //
75ffd83dbSDimitry Andric //===----------------------------------------------------------------------===//
85ffd83dbSDimitry Andric //
95ffd83dbSDimitry Andric // This file contains functions to parse Mach-O object files. In this comment,
105ffd83dbSDimitry Andric // we describe the Mach-O file structure and how we parse it.
115ffd83dbSDimitry Andric //
125ffd83dbSDimitry Andric // Mach-O is not very different from ELF or COFF. The notion of symbols,
135ffd83dbSDimitry Andric // sections and relocations exists in Mach-O as it does in ELF and COFF.
145ffd83dbSDimitry Andric //
155ffd83dbSDimitry Andric // Perhaps the notion that is new to those who know ELF/COFF is "subsections".
165ffd83dbSDimitry Andric // In ELF/COFF, sections are an atomic unit of data copied from input files to
175ffd83dbSDimitry Andric // output files. When we merge or garbage-collect sections, we treat each
185ffd83dbSDimitry Andric // section as an atomic unit. In Mach-O, that's not the case. Sections can
195ffd83dbSDimitry Andric // consist of multiple subsections, and subsections are a unit of merging and
205ffd83dbSDimitry Andric // garbage-collecting. Therefore, Mach-O's subsections are more similar to
215ffd83dbSDimitry Andric // ELF/COFF's sections than Mach-O's sections are.
225ffd83dbSDimitry Andric //
235ffd83dbSDimitry Andric // A section can have multiple symbols. A symbol that does not have the
245ffd83dbSDimitry Andric // N_ALT_ENTRY attribute indicates a beginning of a subsection. Therefore, by
255ffd83dbSDimitry Andric // definition, a symbol is always present at the beginning of each subsection. A
265ffd83dbSDimitry Andric // symbol with N_ALT_ENTRY attribute does not start a new subsection and can
275ffd83dbSDimitry Andric // point to a middle of a subsection.
285ffd83dbSDimitry Andric //
295ffd83dbSDimitry Andric // The notion of subsections also affects how relocations are represented in
305ffd83dbSDimitry Andric // Mach-O. All references within a section need to be explicitly represented as
315ffd83dbSDimitry Andric // relocations if they refer to different subsections, because we obviously need
325ffd83dbSDimitry Andric // to fix up addresses if subsections are laid out in an output file differently
335ffd83dbSDimitry Andric // than they were in object files. To represent that, Mach-O relocations can
345ffd83dbSDimitry Andric // refer to an unnamed location via its address. Scattered relocations (those
355ffd83dbSDimitry Andric // with the R_SCATTERED bit set) always refer to unnamed locations.
365ffd83dbSDimitry Andric // Non-scattered relocations refer to an unnamed location if r_extern is not set
375ffd83dbSDimitry Andric // and r_symbolnum is zero.
385ffd83dbSDimitry Andric //
395ffd83dbSDimitry Andric // Without the above differences, I think you can use your knowledge about ELF
405ffd83dbSDimitry Andric // and COFF for Mach-O.
415ffd83dbSDimitry Andric //
425ffd83dbSDimitry Andric //===----------------------------------------------------------------------===//
435ffd83dbSDimitry Andric 
445ffd83dbSDimitry Andric #include "InputFiles.h"
455ffd83dbSDimitry Andric #include "Config.h"
46e8d8bef9SDimitry Andric #include "Driver.h"
47e8d8bef9SDimitry Andric #include "Dwarf.h"
4881ad6265SDimitry Andric #include "EhFrame.h"
495ffd83dbSDimitry Andric #include "ExportTrie.h"
505ffd83dbSDimitry Andric #include "InputSection.h"
515ffd83dbSDimitry Andric #include "MachOStructs.h"
52e8d8bef9SDimitry Andric #include "ObjC.h"
535ffd83dbSDimitry Andric #include "OutputSection.h"
54e8d8bef9SDimitry Andric #include "OutputSegment.h"
555ffd83dbSDimitry Andric #include "SymbolTable.h"
565ffd83dbSDimitry Andric #include "Symbols.h"
57fe6060f1SDimitry Andric #include "SyntheticSections.h"
585ffd83dbSDimitry Andric #include "Target.h"
595ffd83dbSDimitry Andric 
6004eeddc0SDimitry Andric #include "lld/Common/CommonLinkerContext.h"
61e8d8bef9SDimitry Andric #include "lld/Common/DWARF.h"
62e8d8bef9SDimitry Andric #include "lld/Common/Reproduce.h"
63e8d8bef9SDimitry Andric #include "llvm/ADT/iterator.h"
645ffd83dbSDimitry Andric #include "llvm/BinaryFormat/MachO.h"
65e8d8bef9SDimitry Andric #include "llvm/LTO/LTO.h"
6604eeddc0SDimitry Andric #include "llvm/Support/BinaryStreamReader.h"
675ffd83dbSDimitry Andric #include "llvm/Support/Endian.h"
6881ad6265SDimitry Andric #include "llvm/Support/LEB128.h"
695ffd83dbSDimitry Andric #include "llvm/Support/MemoryBuffer.h"
705ffd83dbSDimitry Andric #include "llvm/Support/Path.h"
71e8d8bef9SDimitry Andric #include "llvm/Support/TarWriter.h"
7204eeddc0SDimitry Andric #include "llvm/Support/TimeProfiler.h"
73fe6060f1SDimitry Andric #include "llvm/TextAPI/Architecture.h"
74fe6060f1SDimitry Andric #include "llvm/TextAPI/InterfaceFile.h"
755ffd83dbSDimitry Andric 
76349cc55cSDimitry Andric #include <type_traits>
77349cc55cSDimitry Andric 
785ffd83dbSDimitry Andric using namespace llvm;
795ffd83dbSDimitry Andric using namespace llvm::MachO;
805ffd83dbSDimitry Andric using namespace llvm::support::endian;
815ffd83dbSDimitry Andric using namespace llvm::sys;
825ffd83dbSDimitry Andric using namespace lld;
835ffd83dbSDimitry Andric using namespace lld::macho;
845ffd83dbSDimitry Andric 
85e8d8bef9SDimitry Andric // Returns "<internal>", "foo.a(bar.o)", or "baz.o".
86e8d8bef9SDimitry Andric std::string lld::toString(const InputFile *f) {
87e8d8bef9SDimitry Andric   if (!f)
88e8d8bef9SDimitry Andric     return "<internal>";
89fe6060f1SDimitry Andric 
90fe6060f1SDimitry Andric   // Multiple dylibs can be defined in one .tbd file.
91fe6060f1SDimitry Andric   if (auto dylibFile = dyn_cast<DylibFile>(f))
92fe6060f1SDimitry Andric     if (f->getName().endswith(".tbd"))
93fe6060f1SDimitry Andric       return (f->getName() + "(" + dylibFile->installName + ")").str();
94fe6060f1SDimitry Andric 
95e8d8bef9SDimitry Andric   if (f->archiveName.empty())
96e8d8bef9SDimitry Andric     return std::string(f->getName());
97fe6060f1SDimitry Andric   return (f->archiveName + "(" + path::filename(f->getName()) + ")").str();
98e8d8bef9SDimitry Andric }
99e8d8bef9SDimitry Andric 
10081ad6265SDimitry Andric std::string lld::toString(const Section &sec) {
10181ad6265SDimitry Andric   return (toString(sec.file) + ":(" + sec.name + ")").str();
10281ad6265SDimitry Andric }
10381ad6265SDimitry Andric 
104e8d8bef9SDimitry Andric SetVector<InputFile *> macho::inputFiles;
105e8d8bef9SDimitry Andric std::unique_ptr<TarWriter> macho::tar;
106e8d8bef9SDimitry Andric int InputFile::idCount = 0;
1075ffd83dbSDimitry Andric 
108fe6060f1SDimitry Andric static VersionTuple decodeVersion(uint32_t version) {
109fe6060f1SDimitry Andric   unsigned major = version >> 16;
110fe6060f1SDimitry Andric   unsigned minor = (version >> 8) & 0xffu;
111fe6060f1SDimitry Andric   unsigned subMinor = version & 0xffu;
112fe6060f1SDimitry Andric   return VersionTuple(major, minor, subMinor);
113fe6060f1SDimitry Andric }
114fe6060f1SDimitry Andric 
115fe6060f1SDimitry Andric static std::vector<PlatformInfo> getPlatformInfos(const InputFile *input) {
116fe6060f1SDimitry Andric   if (!isa<ObjFile>(input) && !isa<DylibFile>(input))
117fe6060f1SDimitry Andric     return {};
118fe6060f1SDimitry Andric 
119fe6060f1SDimitry Andric   const char *hdr = input->mb.getBufferStart();
120fe6060f1SDimitry Andric 
12181ad6265SDimitry Andric   // "Zippered" object files can have multiple LC_BUILD_VERSION load commands.
122fe6060f1SDimitry Andric   std::vector<PlatformInfo> platformInfos;
123fe6060f1SDimitry Andric   for (auto *cmd : findCommands<build_version_command>(hdr, LC_BUILD_VERSION)) {
124fe6060f1SDimitry Andric     PlatformInfo info;
12504eeddc0SDimitry Andric     info.target.Platform = static_cast<PlatformType>(cmd->platform);
126fe6060f1SDimitry Andric     info.minimum = decodeVersion(cmd->minos);
127fe6060f1SDimitry Andric     platformInfos.emplace_back(std::move(info));
128fe6060f1SDimitry Andric   }
129fe6060f1SDimitry Andric   for (auto *cmd : findCommands<version_min_command>(
130fe6060f1SDimitry Andric            hdr, LC_VERSION_MIN_MACOSX, LC_VERSION_MIN_IPHONEOS,
131fe6060f1SDimitry Andric            LC_VERSION_MIN_TVOS, LC_VERSION_MIN_WATCHOS)) {
132fe6060f1SDimitry Andric     PlatformInfo info;
133fe6060f1SDimitry Andric     switch (cmd->cmd) {
134fe6060f1SDimitry Andric     case LC_VERSION_MIN_MACOSX:
13504eeddc0SDimitry Andric       info.target.Platform = PLATFORM_MACOS;
136fe6060f1SDimitry Andric       break;
137fe6060f1SDimitry Andric     case LC_VERSION_MIN_IPHONEOS:
13804eeddc0SDimitry Andric       info.target.Platform = PLATFORM_IOS;
139fe6060f1SDimitry Andric       break;
140fe6060f1SDimitry Andric     case LC_VERSION_MIN_TVOS:
14104eeddc0SDimitry Andric       info.target.Platform = PLATFORM_TVOS;
142fe6060f1SDimitry Andric       break;
143fe6060f1SDimitry Andric     case LC_VERSION_MIN_WATCHOS:
14404eeddc0SDimitry Andric       info.target.Platform = PLATFORM_WATCHOS;
145fe6060f1SDimitry Andric       break;
146fe6060f1SDimitry Andric     }
147fe6060f1SDimitry Andric     info.minimum = decodeVersion(cmd->version);
148fe6060f1SDimitry Andric     platformInfos.emplace_back(std::move(info));
149fe6060f1SDimitry Andric   }
150fe6060f1SDimitry Andric 
151fe6060f1SDimitry Andric   return platformInfos;
152fe6060f1SDimitry Andric }
153fe6060f1SDimitry Andric 
154fe6060f1SDimitry Andric static bool checkCompatibility(const InputFile *input) {
155fe6060f1SDimitry Andric   std::vector<PlatformInfo> platformInfos = getPlatformInfos(input);
156fe6060f1SDimitry Andric   if (platformInfos.empty())
157fe6060f1SDimitry Andric     return true;
158fe6060f1SDimitry Andric 
159fe6060f1SDimitry Andric   auto it = find_if(platformInfos, [&](const PlatformInfo &info) {
160fe6060f1SDimitry Andric     return removeSimulator(info.target.Platform) ==
161fe6060f1SDimitry Andric            removeSimulator(config->platform());
162fe6060f1SDimitry Andric   });
163fe6060f1SDimitry Andric   if (it == platformInfos.end()) {
164fe6060f1SDimitry Andric     std::string platformNames;
165fe6060f1SDimitry Andric     raw_string_ostream os(platformNames);
166fe6060f1SDimitry Andric     interleave(
167fe6060f1SDimitry Andric         platformInfos, os,
168fe6060f1SDimitry Andric         [&](const PlatformInfo &info) {
169fe6060f1SDimitry Andric           os << getPlatformName(info.target.Platform);
170fe6060f1SDimitry Andric         },
171fe6060f1SDimitry Andric         "/");
172fe6060f1SDimitry Andric     error(toString(input) + " has platform " + platformNames +
173fe6060f1SDimitry Andric           Twine(", which is different from target platform ") +
174fe6060f1SDimitry Andric           getPlatformName(config->platform()));
175fe6060f1SDimitry Andric     return false;
176fe6060f1SDimitry Andric   }
177fe6060f1SDimitry Andric 
178fe6060f1SDimitry Andric   if (it->minimum > config->platformInfo.minimum)
179fe6060f1SDimitry Andric     warn(toString(input) + " has version " + it->minimum.getAsString() +
180fe6060f1SDimitry Andric          ", which is newer than target minimum of " +
181fe6060f1SDimitry Andric          config->platformInfo.minimum.getAsString());
182fe6060f1SDimitry Andric 
183fe6060f1SDimitry Andric   return true;
184fe6060f1SDimitry Andric }
185fe6060f1SDimitry Andric 
186349cc55cSDimitry Andric // This cache mostly exists to store system libraries (and .tbds) as they're
187349cc55cSDimitry Andric // loaded, rather than the input archives, which are already cached at a higher
188349cc55cSDimitry Andric // level, and other files like the filelist that are only read once.
189349cc55cSDimitry Andric // Theoretically this caching could be more efficient by hoisting it, but that
190349cc55cSDimitry Andric // would require altering many callers to track the state.
191349cc55cSDimitry Andric DenseMap<CachedHashStringRef, MemoryBufferRef> macho::cachedReads;
1925ffd83dbSDimitry Andric // Open a given file path and return it as a memory-mapped file.
1935ffd83dbSDimitry Andric Optional<MemoryBufferRef> macho::readFile(StringRef path) {
194349cc55cSDimitry Andric   CachedHashStringRef key(path);
195349cc55cSDimitry Andric   auto entry = cachedReads.find(key);
196349cc55cSDimitry Andric   if (entry != cachedReads.end())
197349cc55cSDimitry Andric     return entry->second;
198349cc55cSDimitry Andric 
199fe6060f1SDimitry Andric   ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr = MemoryBuffer::getFile(path);
200fe6060f1SDimitry Andric   if (std::error_code ec = mbOrErr.getError()) {
2015ffd83dbSDimitry Andric     error("cannot open " + path + ": " + ec.message());
2025ffd83dbSDimitry Andric     return None;
2035ffd83dbSDimitry Andric   }
2045ffd83dbSDimitry Andric 
2055ffd83dbSDimitry Andric   std::unique_ptr<MemoryBuffer> &mb = *mbOrErr;
2065ffd83dbSDimitry Andric   MemoryBufferRef mbref = mb->getMemBufferRef();
2075ffd83dbSDimitry Andric   make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take mb ownership
2085ffd83dbSDimitry Andric 
2095ffd83dbSDimitry Andric   // If this is a regular non-fat file, return it.
2105ffd83dbSDimitry Andric   const char *buf = mbref.getBufferStart();
211fe6060f1SDimitry Andric   const auto *hdr = reinterpret_cast<const fat_header *>(buf);
212fe6060f1SDimitry Andric   if (mbref.getBufferSize() < sizeof(uint32_t) ||
213fe6060f1SDimitry Andric       read32be(&hdr->magic) != FAT_MAGIC) {
214e8d8bef9SDimitry Andric     if (tar)
215e8d8bef9SDimitry Andric       tar->append(relativeToRoot(path), mbref.getBuffer());
216349cc55cSDimitry Andric     return cachedReads[key] = mbref;
217e8d8bef9SDimitry Andric   }
2185ffd83dbSDimitry Andric 
21904eeddc0SDimitry Andric   llvm::BumpPtrAllocator &bAlloc = lld::bAlloc();
22004eeddc0SDimitry Andric 
221fe6060f1SDimitry Andric   // Object files and archive files may be fat files, which contain multiple
222fe6060f1SDimitry Andric   // real files for different CPU ISAs. Here, we search for a file that matches
223fe6060f1SDimitry Andric   // with the current link target and returns it as a MemoryBufferRef.
224fe6060f1SDimitry Andric   const auto *arch = reinterpret_cast<const fat_arch *>(buf + sizeof(*hdr));
2255ffd83dbSDimitry Andric 
2265ffd83dbSDimitry Andric   for (uint32_t i = 0, n = read32be(&hdr->nfat_arch); i < n; ++i) {
2275ffd83dbSDimitry Andric     if (reinterpret_cast<const char *>(arch + i + 1) >
2285ffd83dbSDimitry Andric         buf + mbref.getBufferSize()) {
2295ffd83dbSDimitry Andric       error(path + ": fat_arch struct extends beyond end of file");
2305ffd83dbSDimitry Andric       return None;
2315ffd83dbSDimitry Andric     }
2325ffd83dbSDimitry Andric 
233fe6060f1SDimitry Andric     if (read32be(&arch[i].cputype) != static_cast<uint32_t>(target->cpuType) ||
2345ffd83dbSDimitry Andric         read32be(&arch[i].cpusubtype) != target->cpuSubtype)
2355ffd83dbSDimitry Andric       continue;
2365ffd83dbSDimitry Andric 
2375ffd83dbSDimitry Andric     uint32_t offset = read32be(&arch[i].offset);
2385ffd83dbSDimitry Andric     uint32_t size = read32be(&arch[i].size);
2395ffd83dbSDimitry Andric     if (offset + size > mbref.getBufferSize())
2405ffd83dbSDimitry Andric       error(path + ": slice extends beyond end of file");
241e8d8bef9SDimitry Andric     if (tar)
242e8d8bef9SDimitry Andric       tar->append(relativeToRoot(path), mbref.getBuffer());
243349cc55cSDimitry Andric     return cachedReads[key] = MemoryBufferRef(StringRef(buf + offset, size),
244349cc55cSDimitry Andric                                               path.copy(bAlloc));
2455ffd83dbSDimitry Andric   }
2465ffd83dbSDimitry Andric 
2475ffd83dbSDimitry Andric   error("unable to find matching architecture in " + path);
2485ffd83dbSDimitry Andric   return None;
2495ffd83dbSDimitry Andric }
2505ffd83dbSDimitry Andric 
251fe6060f1SDimitry Andric InputFile::InputFile(Kind kind, const InterfaceFile &interface)
25204eeddc0SDimitry Andric     : id(idCount++), fileKind(kind), name(saver().save(interface.getPath())) {}
2535ffd83dbSDimitry Andric 
254349cc55cSDimitry Andric // Some sections comprise of fixed-size records, so instead of splitting them at
255349cc55cSDimitry Andric // symbol boundaries, we split them based on size. Records are distinct from
256349cc55cSDimitry Andric // literals in that they may contain references to other sections, instead of
257349cc55cSDimitry Andric // being leaf nodes in the InputSection graph.
258349cc55cSDimitry Andric //
259349cc55cSDimitry Andric // Note that "record" is a term I came up with. In contrast, "literal" is a term
260349cc55cSDimitry Andric // used by the Mach-O format.
261349cc55cSDimitry Andric static Optional<size_t> getRecordSize(StringRef segname, StringRef name) {
26281ad6265SDimitry Andric   if (name == section_names::compactUnwind) {
263349cc55cSDimitry Andric     if (segname == segment_names::ld)
264349cc55cSDimitry Andric       return target->wordSize == 8 ? 32 : 20;
265349cc55cSDimitry Andric   }
266fcaf7f86SDimitry Andric   if (!config->dedupLiterals)
267349cc55cSDimitry Andric     return {};
26881ad6265SDimitry Andric 
26981ad6265SDimitry Andric   if (name == section_names::cfString && segname == segment_names::data)
27081ad6265SDimitry Andric     return target->wordSize == 8 ? 32 : 16;
271fcaf7f86SDimitry Andric 
272fcaf7f86SDimitry Andric   if (config->icfLevel == ICFLevel::none)
273fcaf7f86SDimitry Andric     return {};
274fcaf7f86SDimitry Andric 
27581ad6265SDimitry Andric   if (name == section_names::objcClassRefs && segname == segment_names::data)
27681ad6265SDimitry Andric     return target->wordSize;
27781ad6265SDimitry Andric   return {};
27881ad6265SDimitry Andric }
27981ad6265SDimitry Andric 
28081ad6265SDimitry Andric static Error parseCallGraph(ArrayRef<uint8_t> data,
28181ad6265SDimitry Andric                             std::vector<CallGraphEntry> &callGraph) {
28281ad6265SDimitry Andric   TimeTraceScope timeScope("Parsing call graph section");
28381ad6265SDimitry Andric   BinaryStreamReader reader(data, support::little);
28481ad6265SDimitry Andric   while (!reader.empty()) {
28581ad6265SDimitry Andric     uint32_t fromIndex, toIndex;
28681ad6265SDimitry Andric     uint64_t count;
28781ad6265SDimitry Andric     if (Error err = reader.readInteger(fromIndex))
28881ad6265SDimitry Andric       return err;
28981ad6265SDimitry Andric     if (Error err = reader.readInteger(toIndex))
29081ad6265SDimitry Andric       return err;
29181ad6265SDimitry Andric     if (Error err = reader.readInteger(count))
29281ad6265SDimitry Andric       return err;
29381ad6265SDimitry Andric     callGraph.emplace_back(fromIndex, toIndex, count);
29481ad6265SDimitry Andric   }
29581ad6265SDimitry Andric   return Error::success();
296349cc55cSDimitry Andric }
297349cc55cSDimitry Andric 
298349cc55cSDimitry Andric // Parse the sequence of sections within a single LC_SEGMENT(_64).
299349cc55cSDimitry Andric // Split each section into subsections.
300349cc55cSDimitry Andric template <class SectionHeader>
301349cc55cSDimitry Andric void ObjFile::parseSections(ArrayRef<SectionHeader> sectionHeaders) {
302349cc55cSDimitry Andric   sections.reserve(sectionHeaders.size());
3035ffd83dbSDimitry Andric   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
3045ffd83dbSDimitry Andric 
305349cc55cSDimitry Andric   for (const SectionHeader &sec : sectionHeaders) {
306fe6060f1SDimitry Andric     StringRef name =
307e8d8bef9SDimitry Andric         StringRef(sec.sectname, strnlen(sec.sectname, sizeof(sec.sectname)));
308fe6060f1SDimitry Andric     StringRef segname =
309e8d8bef9SDimitry Andric         StringRef(sec.segname, strnlen(sec.segname, sizeof(sec.segname)));
31081ad6265SDimitry Andric     sections.push_back(make<Section>(this, segname, name, sec.flags, sec.addr));
311fe6060f1SDimitry Andric     if (sec.align >= 32) {
312fe6060f1SDimitry Andric       error("alignment " + std::to_string(sec.align) + " of section " + name +
313fe6060f1SDimitry Andric             " is too large");
314fe6060f1SDimitry Andric       continue;
315fe6060f1SDimitry Andric     }
31681ad6265SDimitry Andric     Section &section = *sections.back();
317fe6060f1SDimitry Andric     uint32_t align = 1 << sec.align;
31881ad6265SDimitry Andric     ArrayRef<uint8_t> data = {isZeroFill(sec.flags) ? nullptr
31981ad6265SDimitry Andric                                                     : buf + sec.offset,
32081ad6265SDimitry Andric                               static_cast<size_t>(sec.size)};
321e8d8bef9SDimitry Andric 
322349cc55cSDimitry Andric     auto splitRecords = [&](int recordSize) -> void {
323349cc55cSDimitry Andric       if (data.empty())
324349cc55cSDimitry Andric         return;
32581ad6265SDimitry Andric       Subsections &subsections = section.subsections;
326349cc55cSDimitry Andric       subsections.reserve(data.size() / recordSize);
32781ad6265SDimitry Andric       for (uint64_t off = 0; off < data.size(); off += recordSize) {
328349cc55cSDimitry Andric         auto *isec = make<ConcatInputSection>(
32981ad6265SDimitry Andric             section, data.slice(off, recordSize), align);
33081ad6265SDimitry Andric         subsections.push_back({off, isec});
331349cc55cSDimitry Andric       }
33281ad6265SDimitry Andric       section.doneSplitting = true;
333349cc55cSDimitry Andric     };
334349cc55cSDimitry Andric 
335fe6060f1SDimitry Andric     if (sectionType(sec.flags) == S_CSTRING_LITERALS ||
336fe6060f1SDimitry Andric         (config->dedupLiterals && isWordLiteralSection(sec.flags))) {
337fe6060f1SDimitry Andric       if (sec.nreloc && config->dedupLiterals)
338fe6060f1SDimitry Andric         fatal(toString(this) + " contains relocations in " + sec.segname + "," +
339fe6060f1SDimitry Andric               sec.sectname +
340fe6060f1SDimitry Andric               ", so LLD cannot deduplicate literals. Try re-running without "
341fe6060f1SDimitry Andric               "--deduplicate-literals.");
342fe6060f1SDimitry Andric 
343fe6060f1SDimitry Andric       InputSection *isec;
344fe6060f1SDimitry Andric       if (sectionType(sec.flags) == S_CSTRING_LITERALS) {
34581ad6265SDimitry Andric         isec = make<CStringInputSection>(section, data, align);
346fe6060f1SDimitry Andric         // FIXME: parallelize this?
347fe6060f1SDimitry Andric         cast<CStringInputSection>(isec)->splitIntoPieces();
348fe6060f1SDimitry Andric       } else {
34981ad6265SDimitry Andric         isec = make<WordLiteralInputSection>(section, data, align);
350fe6060f1SDimitry Andric       }
35181ad6265SDimitry Andric       section.subsections.push_back({0, isec});
352349cc55cSDimitry Andric     } else if (auto recordSize = getRecordSize(segname, name)) {
353349cc55cSDimitry Andric       splitRecords(*recordSize);
354753f127fSDimitry Andric     } else if (name == section_names::ehFrame &&
35581ad6265SDimitry Andric                segname == segment_names::text) {
35681ad6265SDimitry Andric       splitEhFrames(data, *sections.back());
357349cc55cSDimitry Andric     } else if (segname == segment_names::llvm) {
35881ad6265SDimitry Andric       if (config->callGraphProfileSort && name == section_names::cgProfile)
35981ad6265SDimitry Andric         checkError(parseCallGraph(data, callGraph));
360349cc55cSDimitry Andric       // ld64 does not appear to emit contents from sections within the __LLVM
361349cc55cSDimitry Andric       // segment. Symbols within those sections point to bitcode metadata
362349cc55cSDimitry Andric       // instead of actual symbols. Global symbols within those sections could
36381ad6265SDimitry Andric       // have the same name without causing duplicate symbol errors. To avoid
36481ad6265SDimitry Andric       // spurious duplicate symbol errors, we do not parse these sections.
365349cc55cSDimitry Andric       // TODO: Evaluate whether the bitcode metadata is needed.
366fcaf7f86SDimitry Andric     } else if (name == section_names::objCImageInfo &&
367fcaf7f86SDimitry Andric                segname == segment_names::data) {
368fcaf7f86SDimitry Andric       objCImageInfo = data;
369fe6060f1SDimitry Andric     } else {
37081ad6265SDimitry Andric       if (name == section_names::addrSig)
37181ad6265SDimitry Andric         addrSigSection = sections.back();
37281ad6265SDimitry Andric 
37381ad6265SDimitry Andric       auto *isec = make<ConcatInputSection>(section, data, align);
374349cc55cSDimitry Andric       if (isDebugSection(isec->getFlags()) &&
375349cc55cSDimitry Andric           isec->getSegName() == segment_names::dwarf) {
376e8d8bef9SDimitry Andric         // Instead of emitting DWARF sections, we emit STABS symbols to the
377e8d8bef9SDimitry Andric         // object files that contain them. We filter them out early to avoid
37881ad6265SDimitry Andric         // parsing their relocations unnecessarily.
379e8d8bef9SDimitry Andric         debugSections.push_back(isec);
380349cc55cSDimitry Andric       } else {
38181ad6265SDimitry Andric         section.subsections.push_back({0, isec});
382e8d8bef9SDimitry Andric       }
3835ffd83dbSDimitry Andric     }
3845ffd83dbSDimitry Andric   }
385fe6060f1SDimitry Andric }
3865ffd83dbSDimitry Andric 
38781ad6265SDimitry Andric void ObjFile::splitEhFrames(ArrayRef<uint8_t> data, Section &ehFrameSection) {
388*61cfbce3SDimitry Andric   EhReader reader(this, data, /*dataOff=*/0);
38981ad6265SDimitry Andric   size_t off = 0;
39081ad6265SDimitry Andric   while (off < reader.size()) {
39181ad6265SDimitry Andric     uint64_t frameOff = off;
39281ad6265SDimitry Andric     uint64_t length = reader.readLength(&off);
39381ad6265SDimitry Andric     if (length == 0)
39481ad6265SDimitry Andric       break;
39581ad6265SDimitry Andric     uint64_t fullLength = length + (off - frameOff);
39681ad6265SDimitry Andric     off += length;
39781ad6265SDimitry Andric     // We hard-code an alignment of 1 here because we don't actually want our
39881ad6265SDimitry Andric     // EH frames to be aligned to the section alignment. EH frame decoders don't
39981ad6265SDimitry Andric     // expect this alignment. Moreover, each EH frame must start where the
40081ad6265SDimitry Andric     // previous one ends, and where it ends is indicated by the length field.
40181ad6265SDimitry Andric     // Unless we update the length field (troublesome), we should keep the
40281ad6265SDimitry Andric     // alignment to 1.
40381ad6265SDimitry Andric     // Note that we still want to preserve the alignment of the overall section,
40481ad6265SDimitry Andric     // just not of the individual EH frames.
40581ad6265SDimitry Andric     ehFrameSection.subsections.push_back(
40681ad6265SDimitry Andric         {frameOff, make<ConcatInputSection>(ehFrameSection,
40781ad6265SDimitry Andric                                             data.slice(frameOff, fullLength),
40881ad6265SDimitry Andric                                             /*align=*/1)});
40981ad6265SDimitry Andric   }
41081ad6265SDimitry Andric   ehFrameSection.doneSplitting = true;
41181ad6265SDimitry Andric }
41281ad6265SDimitry Andric 
41381ad6265SDimitry Andric template <class T>
41481ad6265SDimitry Andric static Section *findContainingSection(const std::vector<Section *> &sections,
41581ad6265SDimitry Andric                                       T *offset) {
41681ad6265SDimitry Andric   static_assert(std::is_same<uint64_t, T>::value ||
41781ad6265SDimitry Andric                     std::is_same<uint32_t, T>::value,
41881ad6265SDimitry Andric                 "unexpected type for offset");
41981ad6265SDimitry Andric   auto it = std::prev(llvm::upper_bound(
42081ad6265SDimitry Andric       sections, *offset,
42181ad6265SDimitry Andric       [](uint64_t value, const Section *sec) { return value < sec->addr; }));
42281ad6265SDimitry Andric   *offset -= (*it)->addr;
42381ad6265SDimitry Andric   return *it;
42481ad6265SDimitry Andric }
42581ad6265SDimitry Andric 
4265ffd83dbSDimitry Andric // Find the subsection corresponding to the greatest section offset that is <=
4275ffd83dbSDimitry Andric // that of the given offset.
4285ffd83dbSDimitry Andric //
4295ffd83dbSDimitry Andric // offset: an offset relative to the start of the original InputSection (before
4305ffd83dbSDimitry Andric // any subsection splitting has occurred). It will be updated to represent the
4315ffd83dbSDimitry Andric // same location as an offset relative to the start of the containing
4325ffd83dbSDimitry Andric // subsection.
433349cc55cSDimitry Andric template <class T>
43481ad6265SDimitry Andric static InputSection *findContainingSubsection(const Section &section,
435349cc55cSDimitry Andric                                               T *offset) {
436349cc55cSDimitry Andric   static_assert(std::is_same<uint64_t, T>::value ||
437349cc55cSDimitry Andric                     std::is_same<uint32_t, T>::value,
438349cc55cSDimitry Andric                 "unexpected type for offset");
439fe6060f1SDimitry Andric   auto it = std::prev(llvm::upper_bound(
44081ad6265SDimitry Andric       section.subsections, *offset,
441349cc55cSDimitry Andric       [](uint64_t value, Subsection subsec) { return value < subsec.offset; }));
442fe6060f1SDimitry Andric   *offset -= it->offset;
443fe6060f1SDimitry Andric   return it->isec;
4445ffd83dbSDimitry Andric }
4455ffd83dbSDimitry Andric 
44681ad6265SDimitry Andric // Find a symbol at offset `off` within `isec`.
44781ad6265SDimitry Andric static Defined *findSymbolAtOffset(const ConcatInputSection *isec,
44881ad6265SDimitry Andric                                    uint64_t off) {
44981ad6265SDimitry Andric   auto it = llvm::lower_bound(isec->symbols, off, [](Defined *d, uint64_t off) {
45081ad6265SDimitry Andric     return d->value < off;
45181ad6265SDimitry Andric   });
45281ad6265SDimitry Andric   // The offset should point at the exact address of a symbol (with no addend.)
45381ad6265SDimitry Andric   if (it == isec->symbols.end() || (*it)->value != off) {
45481ad6265SDimitry Andric     assert(isec->wasCoalesced);
45581ad6265SDimitry Andric     return nullptr;
45681ad6265SDimitry Andric   }
45781ad6265SDimitry Andric   return *it;
45881ad6265SDimitry Andric }
45981ad6265SDimitry Andric 
46081ad6265SDimitry Andric // Linker optimization hints mark a sequence of instructions used for
46181ad6265SDimitry Andric // synthesizing an address which that be transformed into a faster sequence. The
46281ad6265SDimitry Andric // transformations depend on conditions that are determined at link time, like
46381ad6265SDimitry Andric // the distance to the referenced symbol or its alignment.
46481ad6265SDimitry Andric //
46581ad6265SDimitry Andric // Each hint has a type and refers to 2 or 3 instructions. Each of those
46681ad6265SDimitry Andric // instructions must have a corresponding relocation. After addresses have been
46781ad6265SDimitry Andric // finalized and relocations have been performed, we check if the requirements
46881ad6265SDimitry Andric // hold, and perform the optimizations if they do.
46981ad6265SDimitry Andric //
47081ad6265SDimitry Andric // Similar linker relaxations exist for ELF as well, with the difference being
47181ad6265SDimitry Andric // that the explicit marking allows for the relaxation of non-consecutive
47281ad6265SDimitry Andric // relocations too.
47381ad6265SDimitry Andric //
47481ad6265SDimitry Andric // The specific types of hints are documented in Arch/ARM64.cpp
47581ad6265SDimitry Andric void ObjFile::parseOptimizationHints(ArrayRef<uint8_t> data) {
47681ad6265SDimitry Andric   auto expectedArgCount = [](uint8_t type) {
47781ad6265SDimitry Andric     switch (type) {
47881ad6265SDimitry Andric     case LOH_ARM64_ADRP_ADRP:
47981ad6265SDimitry Andric     case LOH_ARM64_ADRP_LDR:
48081ad6265SDimitry Andric     case LOH_ARM64_ADRP_ADD:
48181ad6265SDimitry Andric     case LOH_ARM64_ADRP_LDR_GOT:
48281ad6265SDimitry Andric       return 2;
48381ad6265SDimitry Andric     case LOH_ARM64_ADRP_ADD_LDR:
48481ad6265SDimitry Andric     case LOH_ARM64_ADRP_ADD_STR:
48581ad6265SDimitry Andric     case LOH_ARM64_ADRP_LDR_GOT_LDR:
48681ad6265SDimitry Andric     case LOH_ARM64_ADRP_LDR_GOT_STR:
48781ad6265SDimitry Andric       return 3;
48881ad6265SDimitry Andric     }
48981ad6265SDimitry Andric     return -1;
49081ad6265SDimitry Andric   };
49181ad6265SDimitry Andric 
49281ad6265SDimitry Andric   // Each hint contains at least 4 ULEB128-encoded fields, so in the worst case,
49381ad6265SDimitry Andric   // there are data.size() / 4 LOHs. It's a huge overestimation though, as
49481ad6265SDimitry Andric   // offsets are unlikely to fall in the 0-127 byte range, so we pre-allocate
49581ad6265SDimitry Andric   // half as much.
49681ad6265SDimitry Andric   optimizationHints.reserve(data.size() / 8);
49781ad6265SDimitry Andric 
49881ad6265SDimitry Andric   for (const uint8_t *p = data.begin(); p < data.end();) {
49981ad6265SDimitry Andric     const ptrdiff_t inputOffset = p - data.begin();
50081ad6265SDimitry Andric     unsigned int n = 0;
50181ad6265SDimitry Andric     uint8_t type = decodeULEB128(p, &n, data.end());
50281ad6265SDimitry Andric     p += n;
50381ad6265SDimitry Andric 
50481ad6265SDimitry Andric     // An entry of type 0 terminates the list.
50581ad6265SDimitry Andric     if (type == 0)
50681ad6265SDimitry Andric       break;
50781ad6265SDimitry Andric 
50881ad6265SDimitry Andric     int expectedCount = expectedArgCount(type);
50981ad6265SDimitry Andric     if (LLVM_UNLIKELY(expectedCount == -1)) {
51081ad6265SDimitry Andric       error("Linker optimization hint at offset " + Twine(inputOffset) +
51181ad6265SDimitry Andric             " has unknown type " + Twine(type));
51281ad6265SDimitry Andric       return;
51381ad6265SDimitry Andric     }
51481ad6265SDimitry Andric 
51581ad6265SDimitry Andric     uint8_t argCount = decodeULEB128(p, &n, data.end());
51681ad6265SDimitry Andric     p += n;
51781ad6265SDimitry Andric 
51881ad6265SDimitry Andric     if (LLVM_UNLIKELY(argCount != expectedCount)) {
51981ad6265SDimitry Andric       error("Linker optimization hint at offset " + Twine(inputOffset) +
52081ad6265SDimitry Andric             " has " + Twine(argCount) + " arguments instead of the expected " +
52181ad6265SDimitry Andric             Twine(expectedCount));
52281ad6265SDimitry Andric       return;
52381ad6265SDimitry Andric     }
52481ad6265SDimitry Andric 
52581ad6265SDimitry Andric     uint64_t offset0 = decodeULEB128(p, &n, data.end());
52681ad6265SDimitry Andric     p += n;
52781ad6265SDimitry Andric 
52881ad6265SDimitry Andric     int16_t delta[2];
52981ad6265SDimitry Andric     for (int i = 0; i < argCount - 1; ++i) {
53081ad6265SDimitry Andric       uint64_t address = decodeULEB128(p, &n, data.end());
53181ad6265SDimitry Andric       p += n;
53281ad6265SDimitry Andric       int64_t d = address - offset0;
53381ad6265SDimitry Andric       if (LLVM_UNLIKELY(d > std::numeric_limits<int16_t>::max() ||
53481ad6265SDimitry Andric                         d < std::numeric_limits<int16_t>::min())) {
53581ad6265SDimitry Andric         error("Linker optimization hint at offset " + Twine(inputOffset) +
53681ad6265SDimitry Andric               " has addresses too far apart");
53781ad6265SDimitry Andric         return;
53881ad6265SDimitry Andric       }
53981ad6265SDimitry Andric       delta[i] = d;
54081ad6265SDimitry Andric     }
54181ad6265SDimitry Andric 
54281ad6265SDimitry Andric     optimizationHints.push_back({offset0, {delta[0], delta[1]}, type});
54381ad6265SDimitry Andric   }
54481ad6265SDimitry Andric 
54581ad6265SDimitry Andric   // We sort the per-object vector of optimization hints so each section only
54681ad6265SDimitry Andric   // needs to hold an ArrayRef to a contiguous range of hints.
54781ad6265SDimitry Andric   llvm::sort(optimizationHints,
54881ad6265SDimitry Andric              [](const OptimizationHint &a, const OptimizationHint &b) {
54981ad6265SDimitry Andric                return a.offset0 < b.offset0;
55081ad6265SDimitry Andric              });
55181ad6265SDimitry Andric 
55281ad6265SDimitry Andric   auto section = sections.begin();
55381ad6265SDimitry Andric   auto subsection = (*section)->subsections.begin();
55481ad6265SDimitry Andric   uint64_t subsectionBase = 0;
55581ad6265SDimitry Andric   uint64_t subsectionEnd = 0;
55681ad6265SDimitry Andric 
55781ad6265SDimitry Andric   auto updateAddr = [&]() {
55881ad6265SDimitry Andric     subsectionBase = (*section)->addr + subsection->offset;
55981ad6265SDimitry Andric     subsectionEnd = subsectionBase + subsection->isec->getSize();
56081ad6265SDimitry Andric   };
56181ad6265SDimitry Andric 
56281ad6265SDimitry Andric   auto advanceSubsection = [&]() {
56381ad6265SDimitry Andric     if (section == sections.end())
56481ad6265SDimitry Andric       return;
56581ad6265SDimitry Andric     ++subsection;
566fcaf7f86SDimitry Andric     while (subsection == (*section)->subsections.end()) {
56781ad6265SDimitry Andric       ++section;
56881ad6265SDimitry Andric       if (section == sections.end())
56981ad6265SDimitry Andric         return;
57081ad6265SDimitry Andric       subsection = (*section)->subsections.begin();
57181ad6265SDimitry Andric     }
57281ad6265SDimitry Andric   };
57381ad6265SDimitry Andric 
57481ad6265SDimitry Andric   updateAddr();
57581ad6265SDimitry Andric   auto hintStart = optimizationHints.begin();
57681ad6265SDimitry Andric   for (auto hintEnd = hintStart, end = optimizationHints.end(); hintEnd != end;
57781ad6265SDimitry Andric        ++hintEnd) {
57881ad6265SDimitry Andric     if (hintEnd->offset0 >= subsectionEnd) {
57981ad6265SDimitry Andric       subsection->isec->optimizationHints =
58081ad6265SDimitry Andric           ArrayRef<OptimizationHint>(&*hintStart, hintEnd - hintStart);
58181ad6265SDimitry Andric 
58281ad6265SDimitry Andric       hintStart = hintEnd;
58381ad6265SDimitry Andric       while (hintStart->offset0 >= subsectionEnd) {
58481ad6265SDimitry Andric         advanceSubsection();
58581ad6265SDimitry Andric         if (section == sections.end())
58681ad6265SDimitry Andric           break;
58781ad6265SDimitry Andric         updateAddr();
588fcaf7f86SDimitry Andric         assert(hintStart->offset0 >= subsectionBase);
58981ad6265SDimitry Andric       }
59081ad6265SDimitry Andric     }
59181ad6265SDimitry Andric 
59281ad6265SDimitry Andric     hintEnd->offset0 -= subsectionBase;
59381ad6265SDimitry Andric     for (int i = 0, count = expectedArgCount(hintEnd->type); i < count - 1;
59481ad6265SDimitry Andric          ++i) {
59581ad6265SDimitry Andric       if (LLVM_UNLIKELY(
59681ad6265SDimitry Andric               hintEnd->delta[i] < -static_cast<int64_t>(hintEnd->offset0) ||
59781ad6265SDimitry Andric               hintEnd->delta[i] >=
59881ad6265SDimitry Andric                   static_cast<int64_t>(subsectionEnd - hintEnd->offset0))) {
59981ad6265SDimitry Andric         error("Linker optimization hint spans multiple sections");
60081ad6265SDimitry Andric         return;
60181ad6265SDimitry Andric       }
60281ad6265SDimitry Andric     }
60381ad6265SDimitry Andric   }
60481ad6265SDimitry Andric   if (section != sections.end())
60581ad6265SDimitry Andric     subsection->isec->optimizationHints = ArrayRef<OptimizationHint>(
60681ad6265SDimitry Andric         &*hintStart, optimizationHints.end() - hintStart);
60781ad6265SDimitry Andric }
60881ad6265SDimitry Andric 
609349cc55cSDimitry Andric template <class SectionHeader>
610349cc55cSDimitry Andric static bool validateRelocationInfo(InputFile *file, const SectionHeader &sec,
611fe6060f1SDimitry Andric                                    relocation_info rel) {
612fe6060f1SDimitry Andric   const RelocAttrs &relocAttrs = target->getRelocAttrs(rel.r_type);
613fe6060f1SDimitry Andric   bool valid = true;
614fe6060f1SDimitry Andric   auto message = [relocAttrs, file, sec, rel, &valid](const Twine &diagnostic) {
615fe6060f1SDimitry Andric     valid = false;
616fe6060f1SDimitry Andric     return (relocAttrs.name + " relocation " + diagnostic + " at offset " +
617fe6060f1SDimitry Andric             std::to_string(rel.r_address) + " of " + sec.segname + "," +
618fe6060f1SDimitry Andric             sec.sectname + " in " + toString(file))
619fe6060f1SDimitry Andric         .str();
620fe6060f1SDimitry Andric   };
621fe6060f1SDimitry Andric 
622fe6060f1SDimitry Andric   if (!relocAttrs.hasAttr(RelocAttrBits::LOCAL) && !rel.r_extern)
623fe6060f1SDimitry Andric     error(message("must be extern"));
624fe6060f1SDimitry Andric   if (relocAttrs.hasAttr(RelocAttrBits::PCREL) != rel.r_pcrel)
625fe6060f1SDimitry Andric     error(message(Twine("must ") + (rel.r_pcrel ? "not " : "") +
626fe6060f1SDimitry Andric                   "be PC-relative"));
627fe6060f1SDimitry Andric   if (isThreadLocalVariables(sec.flags) &&
628fe6060f1SDimitry Andric       !relocAttrs.hasAttr(RelocAttrBits::UNSIGNED))
629fe6060f1SDimitry Andric     error(message("not allowed in thread-local section, must be UNSIGNED"));
630fe6060f1SDimitry Andric   if (rel.r_length < 2 || rel.r_length > 3 ||
631fe6060f1SDimitry Andric       !relocAttrs.hasAttr(static_cast<RelocAttrBits>(1 << rel.r_length))) {
632fe6060f1SDimitry Andric     static SmallVector<StringRef, 4> widths{"0", "4", "8", "4 or 8"};
633fe6060f1SDimitry Andric     error(message("has width " + std::to_string(1 << rel.r_length) +
634fe6060f1SDimitry Andric                   " bytes, but must be " +
635fe6060f1SDimitry Andric                   widths[(static_cast<int>(relocAttrs.bits) >> 2) & 3] +
636fe6060f1SDimitry Andric                   " bytes"));
637fe6060f1SDimitry Andric   }
638fe6060f1SDimitry Andric   return valid;
639fe6060f1SDimitry Andric }
640fe6060f1SDimitry Andric 
641349cc55cSDimitry Andric template <class SectionHeader>
642349cc55cSDimitry Andric void ObjFile::parseRelocations(ArrayRef<SectionHeader> sectionHeaders,
64381ad6265SDimitry Andric                                const SectionHeader &sec, Section &section) {
6445ffd83dbSDimitry Andric   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
645e8d8bef9SDimitry Andric   ArrayRef<relocation_info> relInfos(
646e8d8bef9SDimitry Andric       reinterpret_cast<const relocation_info *>(buf + sec.reloff), sec.nreloc);
6475ffd83dbSDimitry Andric 
64881ad6265SDimitry Andric   Subsections &subsections = section.subsections;
649349cc55cSDimitry Andric   auto subsecIt = subsections.rbegin();
650e8d8bef9SDimitry Andric   for (size_t i = 0; i < relInfos.size(); i++) {
651e8d8bef9SDimitry Andric     // Paired relocations serve as Mach-O's method for attaching a
652e8d8bef9SDimitry Andric     // supplemental datum to a primary relocation record. ELF does not
653e8d8bef9SDimitry Andric     // need them because the *_RELOC_RELA records contain the extra
654e8d8bef9SDimitry Andric     // addend field, vs. *_RELOC_REL which omit the addend.
655e8d8bef9SDimitry Andric     //
656e8d8bef9SDimitry Andric     // The {X86_64,ARM64}_RELOC_SUBTRACTOR record holds the subtrahend,
657e8d8bef9SDimitry Andric     // and the paired *_RELOC_UNSIGNED record holds the minuend. The
658fe6060f1SDimitry Andric     // datum for each is a symbolic address. The result is the offset
659fe6060f1SDimitry Andric     // between two addresses.
660e8d8bef9SDimitry Andric     //
661e8d8bef9SDimitry Andric     // The ARM64_RELOC_ADDEND record holds the addend, and the paired
662e8d8bef9SDimitry Andric     // ARM64_RELOC_BRANCH26 or ARM64_RELOC_PAGE21/PAGEOFF12 holds the
663e8d8bef9SDimitry Andric     // base symbolic address.
664e8d8bef9SDimitry Andric     //
665e8d8bef9SDimitry Andric     // Note: X86 does not use *_RELOC_ADDEND because it can embed an
666e8d8bef9SDimitry Andric     // addend into the instruction stream. On X86, a relocatable address
667e8d8bef9SDimitry Andric     // field always occupies an entire contiguous sequence of byte(s),
668e8d8bef9SDimitry Andric     // so there is no need to merge opcode bits with address
669e8d8bef9SDimitry Andric     // bits. Therefore, it's easy and convenient to store addends in the
670e8d8bef9SDimitry Andric     // instruction-stream bytes that would otherwise contain zeroes. By
671e8d8bef9SDimitry Andric     // contrast, RISC ISAs such as ARM64 mix opcode bits with with
672e8d8bef9SDimitry Andric     // address bits so that bitwise arithmetic is necessary to extract
673e8d8bef9SDimitry Andric     // and insert them. Storing addends in the instruction stream is
674e8d8bef9SDimitry Andric     // possible, but inconvenient and more costly at link time.
675e8d8bef9SDimitry Andric 
676fe6060f1SDimitry Andric     relocation_info relInfo = relInfos[i];
677349cc55cSDimitry Andric     bool isSubtrahend =
678349cc55cSDimitry Andric         target->hasAttr(relInfo.r_type, RelocAttrBits::SUBTRAHEND);
679349cc55cSDimitry Andric     int64_t pairedAddend = 0;
680fe6060f1SDimitry Andric     if (target->hasAttr(relInfo.r_type, RelocAttrBits::ADDEND)) {
681fe6060f1SDimitry Andric       pairedAddend = SignExtend64<24>(relInfo.r_symbolnum);
682fe6060f1SDimitry Andric       relInfo = relInfos[++i];
683fe6060f1SDimitry Andric     }
684e8d8bef9SDimitry Andric     assert(i < relInfos.size());
685fe6060f1SDimitry Andric     if (!validateRelocationInfo(this, sec, relInfo))
686fe6060f1SDimitry Andric       continue;
687e8d8bef9SDimitry Andric     if (relInfo.r_address & R_SCATTERED)
6885ffd83dbSDimitry Andric       fatal("TODO: Scattered relocations not supported");
6895ffd83dbSDimitry Andric 
690fe6060f1SDimitry Andric     int64_t embeddedAddend = target->getEmbeddedAddend(mb, sec.offset, relInfo);
691fe6060f1SDimitry Andric     assert(!(embeddedAddend && pairedAddend));
692fe6060f1SDimitry Andric     int64_t totalAddend = pairedAddend + embeddedAddend;
6935ffd83dbSDimitry Andric     Reloc r;
694e8d8bef9SDimitry Andric     r.type = relInfo.r_type;
695e8d8bef9SDimitry Andric     r.pcrel = relInfo.r_pcrel;
696e8d8bef9SDimitry Andric     r.length = relInfo.r_length;
697e8d8bef9SDimitry Andric     r.offset = relInfo.r_address;
698e8d8bef9SDimitry Andric     if (relInfo.r_extern) {
699e8d8bef9SDimitry Andric       r.referent = symbols[relInfo.r_symbolnum];
700fe6060f1SDimitry Andric       r.addend = isSubtrahend ? 0 : totalAddend;
7015ffd83dbSDimitry Andric     } else {
702fe6060f1SDimitry Andric       assert(!isSubtrahend);
703349cc55cSDimitry Andric       const SectionHeader &referentSecHead =
704349cc55cSDimitry Andric           sectionHeaders[relInfo.r_symbolnum - 1];
705fe6060f1SDimitry Andric       uint64_t referentOffset;
706e8d8bef9SDimitry Andric       if (relInfo.r_pcrel) {
7075ffd83dbSDimitry Andric         // The implicit addend for pcrel section relocations is the pcrel offset
7085ffd83dbSDimitry Andric         // in terms of the addresses in the input file. Here we adjust it so
709e8d8bef9SDimitry Andric         // that it describes the offset from the start of the referent section.
710fe6060f1SDimitry Andric         // FIXME This logic was written around x86_64 behavior -- ARM64 doesn't
711fe6060f1SDimitry Andric         // have pcrel section relocations. We may want to factor this out into
712fe6060f1SDimitry Andric         // the arch-specific .cpp file.
713fe6060f1SDimitry Andric         assert(target->hasAttr(r.type, RelocAttrBits::BYTE4));
714349cc55cSDimitry Andric         referentOffset = sec.addr + relInfo.r_address + 4 + totalAddend -
715349cc55cSDimitry Andric                          referentSecHead.addr;
7165ffd83dbSDimitry Andric       } else {
7175ffd83dbSDimitry Andric         // The addend for a non-pcrel relocation is its absolute address.
718349cc55cSDimitry Andric         referentOffset = totalAddend - referentSecHead.addr;
7195ffd83dbSDimitry Andric       }
72081ad6265SDimitry Andric       r.referent = findContainingSubsection(*sections[relInfo.r_symbolnum - 1],
72181ad6265SDimitry Andric                                             &referentOffset);
722e8d8bef9SDimitry Andric       r.addend = referentOffset;
7235ffd83dbSDimitry Andric     }
7245ffd83dbSDimitry Andric 
725fe6060f1SDimitry Andric     // Find the subsection that this relocation belongs to.
726fe6060f1SDimitry Andric     // Though not required by the Mach-O format, clang and gcc seem to emit
727fe6060f1SDimitry Andric     // relocations in order, so let's take advantage of it. However, ld64 emits
728fe6060f1SDimitry Andric     // unsorted relocations (in `-r` mode), so we have a fallback for that
729fe6060f1SDimitry Andric     // uncommon case.
730fe6060f1SDimitry Andric     InputSection *subsec;
731349cc55cSDimitry Andric     while (subsecIt != subsections.rend() && subsecIt->offset > r.offset)
732fe6060f1SDimitry Andric       ++subsecIt;
733349cc55cSDimitry Andric     if (subsecIt == subsections.rend() ||
734fe6060f1SDimitry Andric         subsecIt->offset + subsecIt->isec->getSize() <= r.offset) {
73581ad6265SDimitry Andric       subsec = findContainingSubsection(section, &r.offset);
736fe6060f1SDimitry Andric       // Now that we know the relocs are unsorted, avoid trying the 'fast path'
737fe6060f1SDimitry Andric       // for the other relocations.
738349cc55cSDimitry Andric       subsecIt = subsections.rend();
739fe6060f1SDimitry Andric     } else {
740fe6060f1SDimitry Andric       subsec = subsecIt->isec;
741fe6060f1SDimitry Andric       r.offset -= subsecIt->offset;
742fe6060f1SDimitry Andric     }
7435ffd83dbSDimitry Andric     subsec->relocs.push_back(r);
744fe6060f1SDimitry Andric 
745fe6060f1SDimitry Andric     if (isSubtrahend) {
746fe6060f1SDimitry Andric       relocation_info minuendInfo = relInfos[++i];
747fe6060f1SDimitry Andric       // SUBTRACTOR relocations should always be followed by an UNSIGNED one
748fe6060f1SDimitry Andric       // attached to the same address.
749fe6060f1SDimitry Andric       assert(target->hasAttr(minuendInfo.r_type, RelocAttrBits::UNSIGNED) &&
750fe6060f1SDimitry Andric              relInfo.r_address == minuendInfo.r_address);
751fe6060f1SDimitry Andric       Reloc p;
752fe6060f1SDimitry Andric       p.type = minuendInfo.r_type;
753fe6060f1SDimitry Andric       if (minuendInfo.r_extern) {
754fe6060f1SDimitry Andric         p.referent = symbols[minuendInfo.r_symbolnum];
755fe6060f1SDimitry Andric         p.addend = totalAddend;
756fe6060f1SDimitry Andric       } else {
757fe6060f1SDimitry Andric         uint64_t referentOffset =
758fe6060f1SDimitry Andric             totalAddend - sectionHeaders[minuendInfo.r_symbolnum - 1].addr;
75981ad6265SDimitry Andric         p.referent = findContainingSubsection(
76081ad6265SDimitry Andric             *sections[minuendInfo.r_symbolnum - 1], &referentOffset);
761fe6060f1SDimitry Andric         p.addend = referentOffset;
762fe6060f1SDimitry Andric       }
763fe6060f1SDimitry Andric       subsec->relocs.push_back(p);
764fe6060f1SDimitry Andric     }
7655ffd83dbSDimitry Andric   }
7665ffd83dbSDimitry Andric }
7675ffd83dbSDimitry Andric 
768fe6060f1SDimitry Andric template <class NList>
769fe6060f1SDimitry Andric static macho::Symbol *createDefined(const NList &sym, StringRef name,
770fe6060f1SDimitry Andric                                     InputSection *isec, uint64_t value,
771972a253aSDimitry Andric                                     uint64_t size, bool forceHidden) {
772e8d8bef9SDimitry Andric   // Symbol scope is determined by sym.n_type & (N_EXT | N_PEXT):
773fe6060f1SDimitry Andric   // N_EXT: Global symbols. These go in the symbol table during the link,
774fe6060f1SDimitry Andric   //        and also in the export table of the output so that the dynamic
775fe6060f1SDimitry Andric   //        linker sees them.
776fe6060f1SDimitry Andric   // N_EXT | N_PEXT: Linkage unit (think: dylib) scoped. These go in the
777fe6060f1SDimitry Andric   //                 symbol table during the link so that duplicates are
778fe6060f1SDimitry Andric   //                 either reported (for non-weak symbols) or merged
779fe6060f1SDimitry Andric   //                 (for weak symbols), but they do not go in the export
780fe6060f1SDimitry Andric   //                 table of the output.
781fe6060f1SDimitry Andric   // N_PEXT: llvm-mc does not emit these, but `ld -r` (wherein ld64 emits
782fe6060f1SDimitry Andric   //         object files) may produce them. LLD does not yet support -r.
783fe6060f1SDimitry Andric   //         These are translation-unit scoped, identical to the `0` case.
784fe6060f1SDimitry Andric   // 0: Translation-unit scoped. These are not in the symbol table during
785fe6060f1SDimitry Andric   //    link, and not in the export table of the output either.
786fe6060f1SDimitry Andric   bool isWeakDefCanBeHidden =
787fe6060f1SDimitry Andric       (sym.n_desc & (N_WEAK_DEF | N_WEAK_REF)) == (N_WEAK_DEF | N_WEAK_REF);
788e8d8bef9SDimitry Andric 
789fe6060f1SDimitry Andric   if (sym.n_type & N_EXT) {
790972a253aSDimitry Andric     // -load_hidden makes us treat global symbols as linkage unit scoped.
791972a253aSDimitry Andric     // Duplicates are reported but the symbol does not go in the export trie.
792972a253aSDimitry Andric     bool isPrivateExtern = sym.n_type & N_PEXT || forceHidden;
793972a253aSDimitry Andric 
794fe6060f1SDimitry Andric     // lld's behavior for merging symbols is slightly different from ld64:
795fe6060f1SDimitry Andric     // ld64 picks the winning symbol based on several criteria (see
796fe6060f1SDimitry Andric     // pickBetweenRegularAtoms() in ld64's SymbolTable.cpp), while lld
797fe6060f1SDimitry Andric     // just merges metadata and keeps the contents of the first symbol
798fe6060f1SDimitry Andric     // with that name (see SymbolTable::addDefined). For:
799fe6060f1SDimitry Andric     // * inline function F in a TU built with -fvisibility-inlines-hidden
800fe6060f1SDimitry Andric     // * and inline function F in another TU built without that flag
801fe6060f1SDimitry Andric     // ld64 will pick the one from the file built without
802fe6060f1SDimitry Andric     // -fvisibility-inlines-hidden.
803fe6060f1SDimitry Andric     // lld will instead pick the one listed first on the link command line and
804fe6060f1SDimitry Andric     // give it visibility as if the function was built without
805fe6060f1SDimitry Andric     // -fvisibility-inlines-hidden.
806fe6060f1SDimitry Andric     // If both functions have the same contents, this will have the same
807fe6060f1SDimitry Andric     // behavior. If not, it won't, but the input had an ODR violation in
808fe6060f1SDimitry Andric     // that case.
809fe6060f1SDimitry Andric     //
810fe6060f1SDimitry Andric     // Similarly, merging a symbol
811fe6060f1SDimitry Andric     // that's isPrivateExtern and not isWeakDefCanBeHidden with one
812fe6060f1SDimitry Andric     // that's not isPrivateExtern but isWeakDefCanBeHidden technically
813fe6060f1SDimitry Andric     // should produce one
814fe6060f1SDimitry Andric     // that's not isPrivateExtern but isWeakDefCanBeHidden. That matters
815fe6060f1SDimitry Andric     // with ld64's semantics, because it means the non-private-extern
816fe6060f1SDimitry Andric     // definition will continue to take priority if more private extern
817fe6060f1SDimitry Andric     // definitions are encountered. With lld's semantics there's no observable
818349cc55cSDimitry Andric     // difference between a symbol that's isWeakDefCanBeHidden(autohide) or one
819349cc55cSDimitry Andric     // that's privateExtern -- neither makes it into the dynamic symbol table,
820349cc55cSDimitry Andric     // unless the autohide symbol is explicitly exported.
821349cc55cSDimitry Andric     // But if a symbol is both privateExtern and autohide then it can't
822349cc55cSDimitry Andric     // be exported.
823349cc55cSDimitry Andric     // So we nullify the autohide flag when privateExtern is present
824349cc55cSDimitry Andric     // and promote the symbol to privateExtern when it is not already.
825349cc55cSDimitry Andric     if (isWeakDefCanBeHidden && isPrivateExtern)
826349cc55cSDimitry Andric       isWeakDefCanBeHidden = false;
827349cc55cSDimitry Andric     else if (isWeakDefCanBeHidden)
828fe6060f1SDimitry Andric       isPrivateExtern = true;
829fe6060f1SDimitry Andric     return symtab->addDefined(
830fe6060f1SDimitry Andric         name, isec->getFile(), isec, value, size, sym.n_desc & N_WEAK_DEF,
831fe6060f1SDimitry Andric         isPrivateExtern, sym.n_desc & N_ARM_THUMB_DEF,
832349cc55cSDimitry Andric         sym.n_desc & REFERENCED_DYNAMICALLY, sym.n_desc & N_NO_DEAD_STRIP,
833349cc55cSDimitry Andric         isWeakDefCanBeHidden);
834e8d8bef9SDimitry Andric   }
835fe6060f1SDimitry Andric   assert(!isWeakDefCanBeHidden &&
836fe6060f1SDimitry Andric          "weak_def_can_be_hidden on already-hidden symbol?");
83781ad6265SDimitry Andric   bool includeInSymtab =
83881ad6265SDimitry Andric       !name.startswith("l") && !name.startswith("L") && !isEhFrameSection(isec);
839fe6060f1SDimitry Andric   return make<Defined>(
840fe6060f1SDimitry Andric       name, isec->getFile(), isec, value, size, sym.n_desc & N_WEAK_DEF,
84181ad6265SDimitry Andric       /*isExternal=*/false, /*isPrivateExtern=*/false, includeInSymtab,
842fe6060f1SDimitry Andric       sym.n_desc & N_ARM_THUMB_DEF, sym.n_desc & REFERENCED_DYNAMICALLY,
843fe6060f1SDimitry Andric       sym.n_desc & N_NO_DEAD_STRIP);
844e8d8bef9SDimitry Andric }
845e8d8bef9SDimitry Andric 
846e8d8bef9SDimitry Andric // Absolute symbols are defined symbols that do not have an associated
847e8d8bef9SDimitry Andric // InputSection. They cannot be weak.
848fe6060f1SDimitry Andric template <class NList>
849fe6060f1SDimitry Andric static macho::Symbol *createAbsolute(const NList &sym, InputFile *file,
850972a253aSDimitry Andric                                      StringRef name, bool forceHidden) {
851fe6060f1SDimitry Andric   if (sym.n_type & N_EXT) {
852972a253aSDimitry Andric     bool isPrivateExtern = sym.n_type & N_PEXT || forceHidden;
853fe6060f1SDimitry Andric     return symtab->addDefined(
854fe6060f1SDimitry Andric         name, file, nullptr, sym.n_value, /*size=*/0,
855972a253aSDimitry Andric         /*isWeakDef=*/false, isPrivateExtern, sym.n_desc & N_ARM_THUMB_DEF,
856349cc55cSDimitry Andric         /*isReferencedDynamically=*/false, sym.n_desc & N_NO_DEAD_STRIP,
857349cc55cSDimitry Andric         /*isWeakDefCanBeHidden=*/false);
858e8d8bef9SDimitry Andric   }
859fe6060f1SDimitry Andric   return make<Defined>(name, file, nullptr, sym.n_value, /*size=*/0,
860fe6060f1SDimitry Andric                        /*isWeakDef=*/false,
861fe6060f1SDimitry Andric                        /*isExternal=*/false, /*isPrivateExtern=*/false,
86281ad6265SDimitry Andric                        /*includeInSymtab=*/true, sym.n_desc & N_ARM_THUMB_DEF,
863fe6060f1SDimitry Andric                        /*isReferencedDynamically=*/false,
864fe6060f1SDimitry Andric                        sym.n_desc & N_NO_DEAD_STRIP);
865e8d8bef9SDimitry Andric }
866e8d8bef9SDimitry Andric 
867fe6060f1SDimitry Andric template <class NList>
868fe6060f1SDimitry Andric macho::Symbol *ObjFile::parseNonSectionSymbol(const NList &sym,
869e8d8bef9SDimitry Andric                                               StringRef name) {
870e8d8bef9SDimitry Andric   uint8_t type = sym.n_type & N_TYPE;
871972a253aSDimitry Andric   bool isPrivateExtern = sym.n_type & N_PEXT || forceHidden;
872e8d8bef9SDimitry Andric   switch (type) {
873e8d8bef9SDimitry Andric   case N_UNDF:
874e8d8bef9SDimitry Andric     return sym.n_value == 0
875fe6060f1SDimitry Andric                ? symtab->addUndefined(name, this, sym.n_desc & N_WEAK_REF)
876e8d8bef9SDimitry Andric                : symtab->addCommon(name, this, sym.n_value,
877e8d8bef9SDimitry Andric                                    1 << GET_COMM_ALIGN(sym.n_desc),
878972a253aSDimitry Andric                                    isPrivateExtern);
879e8d8bef9SDimitry Andric   case N_ABS:
880972a253aSDimitry Andric     return createAbsolute(sym, this, name, forceHidden);
881e8d8bef9SDimitry Andric   case N_PBUD:
882e8d8bef9SDimitry Andric   case N_INDR:
883e8d8bef9SDimitry Andric     error("TODO: support symbols of type " + std::to_string(type));
884e8d8bef9SDimitry Andric     return nullptr;
885e8d8bef9SDimitry Andric   case N_SECT:
886e8d8bef9SDimitry Andric     llvm_unreachable(
887e8d8bef9SDimitry Andric         "N_SECT symbols should not be passed to parseNonSectionSymbol");
888e8d8bef9SDimitry Andric   default:
889e8d8bef9SDimitry Andric     llvm_unreachable("invalid symbol type");
890e8d8bef9SDimitry Andric   }
891e8d8bef9SDimitry Andric }
892e8d8bef9SDimitry Andric 
893349cc55cSDimitry Andric template <class NList> static bool isUndef(const NList &sym) {
894fe6060f1SDimitry Andric   return (sym.n_type & N_TYPE) == N_UNDF && sym.n_value == 0;
895fe6060f1SDimitry Andric }
896fe6060f1SDimitry Andric 
897fe6060f1SDimitry Andric template <class LP>
898fe6060f1SDimitry Andric void ObjFile::parseSymbols(ArrayRef<typename LP::section> sectionHeaders,
899fe6060f1SDimitry Andric                            ArrayRef<typename LP::nlist> nList,
9005ffd83dbSDimitry Andric                            const char *strtab, bool subsectionsViaSymbols) {
901fe6060f1SDimitry Andric   using NList = typename LP::nlist;
902fe6060f1SDimitry Andric 
903fe6060f1SDimitry Andric   // Groups indices of the symbols by the sections that contain them.
904349cc55cSDimitry Andric   std::vector<std::vector<uint32_t>> symbolsBySection(sections.size());
9055ffd83dbSDimitry Andric   symbols.resize(nList.size());
906fe6060f1SDimitry Andric   SmallVector<unsigned, 32> undefineds;
907fe6060f1SDimitry Andric   for (uint32_t i = 0; i < nList.size(); ++i) {
908fe6060f1SDimitry Andric     const NList &sym = nList[i];
9095ffd83dbSDimitry Andric 
910fe6060f1SDimitry Andric     // Ignore debug symbols for now.
911fe6060f1SDimitry Andric     // FIXME: may need special handling.
912fe6060f1SDimitry Andric     if (sym.n_type & N_STAB)
913fe6060f1SDimitry Andric       continue;
914fe6060f1SDimitry Andric 
915fe6060f1SDimitry Andric     if ((sym.n_type & N_TYPE) == N_SECT) {
91681ad6265SDimitry Andric       Subsections &subsections = sections[sym.n_sect - 1]->subsections;
917fe6060f1SDimitry Andric       // parseSections() may have chosen not to parse this section.
918349cc55cSDimitry Andric       if (subsections.empty())
919fe6060f1SDimitry Andric         continue;
920fe6060f1SDimitry Andric       symbolsBySection[sym.n_sect - 1].push_back(i);
921fe6060f1SDimitry Andric     } else if (isUndef(sym)) {
922fe6060f1SDimitry Andric       undefineds.push_back(i);
923fe6060f1SDimitry Andric     } else {
924fcaf7f86SDimitry Andric       symbols[i] = parseNonSectionSymbol(sym, StringRef(strtab + sym.n_strx));
925fe6060f1SDimitry Andric     }
926fe6060f1SDimitry Andric   }
9275ffd83dbSDimitry Andric 
928349cc55cSDimitry Andric   for (size_t i = 0; i < sections.size(); ++i) {
92981ad6265SDimitry Andric     Subsections &subsections = sections[i]->subsections;
930349cc55cSDimitry Andric     if (subsections.empty())
931fe6060f1SDimitry Andric       continue;
932fe6060f1SDimitry Andric     std::vector<uint32_t> &symbolIndices = symbolsBySection[i];
933fe6060f1SDimitry Andric     uint64_t sectionAddr = sectionHeaders[i].addr;
934fe6060f1SDimitry Andric     uint32_t sectionAlign = 1u << sectionHeaders[i].align;
935fe6060f1SDimitry Andric 
93681ad6265SDimitry Andric     // Some sections have already been split into subsections during
937fe6060f1SDimitry Andric     // parseSections(), so we simply need to match Symbols to the corresponding
938fe6060f1SDimitry Andric     // subsection here.
93981ad6265SDimitry Andric     if (sections[i]->doneSplitting) {
940fe6060f1SDimitry Andric       for (size_t j = 0; j < symbolIndices.size(); ++j) {
941fe6060f1SDimitry Andric         uint32_t symIndex = symbolIndices[j];
942fe6060f1SDimitry Andric         const NList &sym = nList[symIndex];
943fe6060f1SDimitry Andric         StringRef name = strtab + sym.n_strx;
944fe6060f1SDimitry Andric         uint64_t symbolOffset = sym.n_value - sectionAddr;
945349cc55cSDimitry Andric         InputSection *isec =
94681ad6265SDimitry Andric             findContainingSubsection(*sections[i], &symbolOffset);
947fe6060f1SDimitry Andric         if (symbolOffset != 0) {
94881ad6265SDimitry Andric           error(toString(*sections[i]) + ":  symbol " + name +
949fe6060f1SDimitry Andric                 " at misaligned offset");
950fe6060f1SDimitry Andric           continue;
951fe6060f1SDimitry Andric         }
952972a253aSDimitry Andric         symbols[symIndex] =
953972a253aSDimitry Andric             createDefined(sym, name, isec, 0, isec->getSize(), forceHidden);
954fe6060f1SDimitry Andric       }
9555ffd83dbSDimitry Andric       continue;
9565ffd83dbSDimitry Andric     }
95781ad6265SDimitry Andric     sections[i]->doneSplitting = true;
9585ffd83dbSDimitry Andric 
959fe6060f1SDimitry Andric     // Calculate symbol sizes and create subsections by splitting the sections
960fe6060f1SDimitry Andric     // along symbol boundaries.
961349cc55cSDimitry Andric     // We populate subsections by repeatedly splitting the last (highest
962349cc55cSDimitry Andric     // address) subsection.
963fe6060f1SDimitry Andric     llvm::stable_sort(symbolIndices, [&](uint32_t lhs, uint32_t rhs) {
964fe6060f1SDimitry Andric       return nList[lhs].n_value < nList[rhs].n_value;
965fe6060f1SDimitry Andric     });
966fe6060f1SDimitry Andric     for (size_t j = 0; j < symbolIndices.size(); ++j) {
967fe6060f1SDimitry Andric       uint32_t symIndex = symbolIndices[j];
968fe6060f1SDimitry Andric       const NList &sym = nList[symIndex];
969fe6060f1SDimitry Andric       StringRef name = strtab + sym.n_strx;
970349cc55cSDimitry Andric       Subsection &subsec = subsections.back();
971349cc55cSDimitry Andric       InputSection *isec = subsec.isec;
972fe6060f1SDimitry Andric 
973349cc55cSDimitry Andric       uint64_t subsecAddr = sectionAddr + subsec.offset;
974fe6060f1SDimitry Andric       size_t symbolOffset = sym.n_value - subsecAddr;
975fe6060f1SDimitry Andric       uint64_t symbolSize =
976fe6060f1SDimitry Andric           j + 1 < symbolIndices.size()
977fe6060f1SDimitry Andric               ? nList[symbolIndices[j + 1]].n_value - sym.n_value
978fe6060f1SDimitry Andric               : isec->data.size() - symbolOffset;
979fe6060f1SDimitry Andric       // There are 4 cases where we do not need to create a new subsection:
980fe6060f1SDimitry Andric       //   1. If the input file does not use subsections-via-symbols.
981fe6060f1SDimitry Andric       //   2. Multiple symbols at the same address only induce one subsection.
982fe6060f1SDimitry Andric       //      (The symbolOffset == 0 check covers both this case as well as
983fe6060f1SDimitry Andric       //      the first loop iteration.)
984fe6060f1SDimitry Andric       //   3. Alternative entry points do not induce new subsections.
985fe6060f1SDimitry Andric       //   4. If we have a literal section (e.g. __cstring and __literal4).
986fe6060f1SDimitry Andric       if (!subsectionsViaSymbols || symbolOffset == 0 ||
987fe6060f1SDimitry Andric           sym.n_desc & N_ALT_ENTRY || !isa<ConcatInputSection>(isec)) {
988972a253aSDimitry Andric         symbols[symIndex] = createDefined(sym, name, isec, symbolOffset,
989972a253aSDimitry Andric                                           symbolSize, forceHidden);
9905ffd83dbSDimitry Andric         continue;
9915ffd83dbSDimitry Andric       }
992fe6060f1SDimitry Andric       auto *concatIsec = cast<ConcatInputSection>(isec);
9935ffd83dbSDimitry Andric 
994fe6060f1SDimitry Andric       auto *nextIsec = make<ConcatInputSection>(*concatIsec);
995fe6060f1SDimitry Andric       nextIsec->wasCoalesced = false;
996fe6060f1SDimitry Andric       if (isZeroFill(isec->getFlags())) {
997fe6060f1SDimitry Andric         // Zero-fill sections have NULL data.data() non-zero data.size()
998fe6060f1SDimitry Andric         nextIsec->data = {nullptr, isec->data.size() - symbolOffset};
999fe6060f1SDimitry Andric         isec->data = {nullptr, symbolOffset};
1000fe6060f1SDimitry Andric       } else {
1001fe6060f1SDimitry Andric         nextIsec->data = isec->data.slice(symbolOffset);
1002fe6060f1SDimitry Andric         isec->data = isec->data.slice(0, symbolOffset);
10035ffd83dbSDimitry Andric       }
10045ffd83dbSDimitry Andric 
1005fe6060f1SDimitry Andric       // By construction, the symbol will be at offset zero in the new
1006fe6060f1SDimitry Andric       // subsection.
1007972a253aSDimitry Andric       symbols[symIndex] = createDefined(sym, name, nextIsec, /*value=*/0,
1008972a253aSDimitry Andric                                         symbolSize, forceHidden);
10095ffd83dbSDimitry Andric       // TODO: ld64 appears to preserve the original alignment as well as each
10105ffd83dbSDimitry Andric       // subsection's offset from the last aligned address. We should consider
10115ffd83dbSDimitry Andric       // emulating that behavior.
1012fe6060f1SDimitry Andric       nextIsec->align = MinAlign(sectionAlign, sym.n_value);
1013349cc55cSDimitry Andric       subsections.push_back({sym.n_value - sectionAddr, nextIsec});
1014fe6060f1SDimitry Andric     }
10155ffd83dbSDimitry Andric   }
10165ffd83dbSDimitry Andric 
1017fe6060f1SDimitry Andric   // Undefined symbols can trigger recursive fetch from Archives due to
1018fe6060f1SDimitry Andric   // LazySymbols. Process defined symbols first so that the relative order
1019fe6060f1SDimitry Andric   // between a defined symbol and an undefined symbol does not change the
1020fe6060f1SDimitry Andric   // symbol resolution behavior. In addition, a set of interconnected symbols
1021fe6060f1SDimitry Andric   // will all be resolved to the same file, instead of being resolved to
1022fe6060f1SDimitry Andric   // different files.
1023fe6060f1SDimitry Andric   for (unsigned i : undefineds) {
1024fe6060f1SDimitry Andric     const NList &sym = nList[i];
1025e8d8bef9SDimitry Andric     StringRef name = strtab + sym.n_strx;
1026fe6060f1SDimitry Andric     symbols[i] = parseNonSectionSymbol(sym, name);
10275ffd83dbSDimitry Andric   }
10285ffd83dbSDimitry Andric }
10295ffd83dbSDimitry Andric 
1030e8d8bef9SDimitry Andric OpaqueFile::OpaqueFile(MemoryBufferRef mb, StringRef segName,
1031e8d8bef9SDimitry Andric                        StringRef sectName)
1032e8d8bef9SDimitry Andric     : InputFile(OpaqueKind, mb) {
1033e8d8bef9SDimitry Andric   const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
1034fe6060f1SDimitry Andric   ArrayRef<uint8_t> data = {buf, mb.getBufferSize()};
103581ad6265SDimitry Andric   sections.push_back(make<Section>(/*file=*/this, segName.take_front(16),
103681ad6265SDimitry Andric                                    sectName.take_front(16),
103781ad6265SDimitry Andric                                    /*flags=*/0, /*addr=*/0));
103881ad6265SDimitry Andric   Section &section = *sections.back();
103981ad6265SDimitry Andric   ConcatInputSection *isec = make<ConcatInputSection>(section, data);
1040fe6060f1SDimitry Andric   isec->live = true;
104181ad6265SDimitry Andric   section.subsections.push_back({0, isec});
1042e8d8bef9SDimitry Andric }
1043e8d8bef9SDimitry Andric 
104404eeddc0SDimitry Andric ObjFile::ObjFile(MemoryBufferRef mb, uint32_t modTime, StringRef archiveName,
1045972a253aSDimitry Andric                  bool lazy, bool forceHidden)
1046972a253aSDimitry Andric     : InputFile(ObjKind, mb, lazy), modTime(modTime), forceHidden(forceHidden) {
1047e8d8bef9SDimitry Andric   this->archiveName = std::string(archiveName);
104804eeddc0SDimitry Andric   if (lazy) {
104904eeddc0SDimitry Andric     if (target->wordSize == 8)
105004eeddc0SDimitry Andric       parseLazy<LP64>();
105104eeddc0SDimitry Andric     else
105204eeddc0SDimitry Andric       parseLazy<ILP32>();
105304eeddc0SDimitry Andric   } else {
1054fe6060f1SDimitry Andric     if (target->wordSize == 8)
1055fe6060f1SDimitry Andric       parse<LP64>();
1056fe6060f1SDimitry Andric     else
1057fe6060f1SDimitry Andric       parse<ILP32>();
1058e8d8bef9SDimitry Andric   }
105904eeddc0SDimitry Andric }
1060e8d8bef9SDimitry Andric 
1061fe6060f1SDimitry Andric template <class LP> void ObjFile::parse() {
1062fe6060f1SDimitry Andric   using Header = typename LP::mach_header;
1063fe6060f1SDimitry Andric   using SegmentCommand = typename LP::segment_command;
1064349cc55cSDimitry Andric   using SectionHeader = typename LP::section;
1065fe6060f1SDimitry Andric   using NList = typename LP::nlist;
1066fe6060f1SDimitry Andric 
1067fe6060f1SDimitry Andric   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
1068fe6060f1SDimitry Andric   auto *hdr = reinterpret_cast<const Header *>(mb.getBufferStart());
1069fe6060f1SDimitry Andric 
1070fe6060f1SDimitry Andric   Architecture arch = getArchitectureFromCpuType(hdr->cputype, hdr->cpusubtype);
1071fe6060f1SDimitry Andric   if (arch != config->arch()) {
1072349cc55cSDimitry Andric     auto msg = config->errorForArchMismatch
1073349cc55cSDimitry Andric                    ? static_cast<void (*)(const Twine &)>(error)
1074349cc55cSDimitry Andric                    : warn;
1075349cc55cSDimitry Andric     msg(toString(this) + " has architecture " + getArchitectureName(arch) +
1076fe6060f1SDimitry Andric         " which is incompatible with target architecture " +
1077fe6060f1SDimitry Andric         getArchitectureName(config->arch()));
1078fe6060f1SDimitry Andric     return;
1079fe6060f1SDimitry Andric   }
1080fe6060f1SDimitry Andric 
1081fe6060f1SDimitry Andric   if (!checkCompatibility(this))
1082fe6060f1SDimitry Andric     return;
1083fe6060f1SDimitry Andric 
1084fe6060f1SDimitry Andric   for (auto *cmd : findCommands<linker_option_command>(hdr, LC_LINKER_OPTION)) {
1085fe6060f1SDimitry Andric     StringRef data{reinterpret_cast<const char *>(cmd + 1),
1086fe6060f1SDimitry Andric                    cmd->cmdsize - sizeof(linker_option_command)};
1087fe6060f1SDimitry Andric     parseLCLinkerOption(this, cmd->count, data);
1088fe6060f1SDimitry Andric   }
1089fe6060f1SDimitry Andric 
1090349cc55cSDimitry Andric   ArrayRef<SectionHeader> sectionHeaders;
1091fe6060f1SDimitry Andric   if (const load_command *cmd = findCommand(hdr, LP::segmentLCType)) {
1092fe6060f1SDimitry Andric     auto *c = reinterpret_cast<const SegmentCommand *>(cmd);
1093349cc55cSDimitry Andric     sectionHeaders = ArrayRef<SectionHeader>{
1094349cc55cSDimitry Andric         reinterpret_cast<const SectionHeader *>(c + 1), c->nsects};
10955ffd83dbSDimitry Andric     parseSections(sectionHeaders);
10965ffd83dbSDimitry Andric   }
10975ffd83dbSDimitry Andric 
10985ffd83dbSDimitry Andric   // TODO: Error on missing LC_SYMTAB?
10995ffd83dbSDimitry Andric   if (const load_command *cmd = findCommand(hdr, LC_SYMTAB)) {
11005ffd83dbSDimitry Andric     auto *c = reinterpret_cast<const symtab_command *>(cmd);
1101fe6060f1SDimitry Andric     ArrayRef<NList> nList(reinterpret_cast<const NList *>(buf + c->symoff),
1102fe6060f1SDimitry Andric                           c->nsyms);
11035ffd83dbSDimitry Andric     const char *strtab = reinterpret_cast<const char *>(buf) + c->stroff;
11045ffd83dbSDimitry Andric     bool subsectionsViaSymbols = hdr->flags & MH_SUBSECTIONS_VIA_SYMBOLS;
1105fe6060f1SDimitry Andric     parseSymbols<LP>(sectionHeaders, nList, strtab, subsectionsViaSymbols);
11065ffd83dbSDimitry Andric   }
11075ffd83dbSDimitry Andric 
11085ffd83dbSDimitry Andric   // The relocations may refer to the symbols, so we parse them after we have
11095ffd83dbSDimitry Andric   // parsed all the symbols.
1110349cc55cSDimitry Andric   for (size_t i = 0, n = sections.size(); i < n; ++i)
111181ad6265SDimitry Andric     if (!sections[i]->subsections.empty())
111281ad6265SDimitry Andric       parseRelocations(sectionHeaders, sectionHeaders[i], *sections[i]);
111381ad6265SDimitry Andric 
111481ad6265SDimitry Andric   if (!config->ignoreOptimizationHints)
111581ad6265SDimitry Andric     if (auto *cmd = findCommand<linkedit_data_command>(
111681ad6265SDimitry Andric             hdr, LC_LINKER_OPTIMIZATION_HINT))
111781ad6265SDimitry Andric       parseOptimizationHints({buf + cmd->dataoff, cmd->datasize});
1118e8d8bef9SDimitry Andric 
1119e8d8bef9SDimitry Andric   parseDebugInfo();
112081ad6265SDimitry Andric 
112181ad6265SDimitry Andric   Section *ehFrameSection = nullptr;
112281ad6265SDimitry Andric   Section *compactUnwindSection = nullptr;
112381ad6265SDimitry Andric   for (Section *sec : sections) {
112481ad6265SDimitry Andric     Section **s = StringSwitch<Section **>(sec->name)
112581ad6265SDimitry Andric                       .Case(section_names::compactUnwind, &compactUnwindSection)
112681ad6265SDimitry Andric                       .Case(section_names::ehFrame, &ehFrameSection)
112781ad6265SDimitry Andric                       .Default(nullptr);
112881ad6265SDimitry Andric     if (s)
112981ad6265SDimitry Andric       *s = sec;
113081ad6265SDimitry Andric   }
1131349cc55cSDimitry Andric   if (compactUnwindSection)
113281ad6265SDimitry Andric     registerCompactUnwind(*compactUnwindSection);
1133753f127fSDimitry Andric   if (ehFrameSection)
113481ad6265SDimitry Andric     registerEhFrames(*ehFrameSection);
1135e8d8bef9SDimitry Andric }
1136e8d8bef9SDimitry Andric 
113704eeddc0SDimitry Andric template <class LP> void ObjFile::parseLazy() {
113804eeddc0SDimitry Andric   using Header = typename LP::mach_header;
113904eeddc0SDimitry Andric   using NList = typename LP::nlist;
114004eeddc0SDimitry Andric 
114104eeddc0SDimitry Andric   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
114204eeddc0SDimitry Andric   auto *hdr = reinterpret_cast<const Header *>(mb.getBufferStart());
114304eeddc0SDimitry Andric   const load_command *cmd = findCommand(hdr, LC_SYMTAB);
114404eeddc0SDimitry Andric   if (!cmd)
114504eeddc0SDimitry Andric     return;
114604eeddc0SDimitry Andric   auto *c = reinterpret_cast<const symtab_command *>(cmd);
114704eeddc0SDimitry Andric   ArrayRef<NList> nList(reinterpret_cast<const NList *>(buf + c->symoff),
114804eeddc0SDimitry Andric                         c->nsyms);
114904eeddc0SDimitry Andric   const char *strtab = reinterpret_cast<const char *>(buf) + c->stroff;
115004eeddc0SDimitry Andric   symbols.resize(nList.size());
115104eeddc0SDimitry Andric   for (auto it : llvm::enumerate(nList)) {
115204eeddc0SDimitry Andric     const NList &sym = it.value();
115304eeddc0SDimitry Andric     if ((sym.n_type & N_EXT) && !isUndef(sym)) {
115404eeddc0SDimitry Andric       // TODO: Bound checking
115504eeddc0SDimitry Andric       StringRef name = strtab + sym.n_strx;
115604eeddc0SDimitry Andric       symbols[it.index()] = symtab->addLazyObject(name, *this);
115704eeddc0SDimitry Andric       if (!lazy)
115804eeddc0SDimitry Andric         break;
115904eeddc0SDimitry Andric     }
116004eeddc0SDimitry Andric   }
116104eeddc0SDimitry Andric }
116204eeddc0SDimitry Andric 
1163e8d8bef9SDimitry Andric void ObjFile::parseDebugInfo() {
1164e8d8bef9SDimitry Andric   std::unique_ptr<DwarfObject> dObj = DwarfObject::create(this);
1165e8d8bef9SDimitry Andric   if (!dObj)
1166e8d8bef9SDimitry Andric     return;
1167e8d8bef9SDimitry Andric 
116881ad6265SDimitry Andric   // We do not re-use the context from getDwarf() here as that function
116981ad6265SDimitry Andric   // constructs an expensive DWARFCache object.
1170e8d8bef9SDimitry Andric   auto *ctx = make<DWARFContext>(
1171e8d8bef9SDimitry Andric       std::move(dObj), "",
1172e8d8bef9SDimitry Andric       [&](Error err) {
1173e8d8bef9SDimitry Andric         warn(toString(this) + ": " + toString(std::move(err)));
1174e8d8bef9SDimitry Andric       },
1175e8d8bef9SDimitry Andric       [&](Error warning) {
1176e8d8bef9SDimitry Andric         warn(toString(this) + ": " + toString(std::move(warning)));
1177e8d8bef9SDimitry Andric       });
1178e8d8bef9SDimitry Andric 
1179e8d8bef9SDimitry Andric   // TODO: Since object files can contain a lot of DWARF info, we should verify
1180e8d8bef9SDimitry Andric   // that we are parsing just the info we need
1181e8d8bef9SDimitry Andric   const DWARFContext::compile_unit_range &units = ctx->compile_units();
1182fe6060f1SDimitry Andric   // FIXME: There can be more than one compile unit per object file. See
1183fe6060f1SDimitry Andric   // PR48637.
1184e8d8bef9SDimitry Andric   auto it = units.begin();
118581ad6265SDimitry Andric   compileUnit = it != units.end() ? it->get() : nullptr;
1186fe6060f1SDimitry Andric }
1187fe6060f1SDimitry Andric 
11880eae32dcSDimitry Andric ArrayRef<data_in_code_entry> ObjFile::getDataInCode() const {
1189fe6060f1SDimitry Andric   const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
1190fe6060f1SDimitry Andric   const load_command *cmd = findCommand(buf, LC_DATA_IN_CODE);
1191fe6060f1SDimitry Andric   if (!cmd)
11920eae32dcSDimitry Andric     return {};
1193fe6060f1SDimitry Andric   const auto *c = reinterpret_cast<const linkedit_data_command *>(cmd);
11940eae32dcSDimitry Andric   return {reinterpret_cast<const data_in_code_entry *>(buf + c->dataoff),
1195fe6060f1SDimitry Andric           c->datasize / sizeof(data_in_code_entry)};
1196e8d8bef9SDimitry Andric }
1197e8d8bef9SDimitry Andric 
1198349cc55cSDimitry Andric // Create pointers from symbols to their associated compact unwind entries.
119981ad6265SDimitry Andric void ObjFile::registerCompactUnwind(Section &compactUnwindSection) {
120081ad6265SDimitry Andric   for (const Subsection &subsection : compactUnwindSection.subsections) {
1201349cc55cSDimitry Andric     ConcatInputSection *isec = cast<ConcatInputSection>(subsection.isec);
1202fcaf7f86SDimitry Andric     // Hack!! Each compact unwind entry (CUE) has its UNSIGNED relocations embed
1203fcaf7f86SDimitry Andric     // their addends in its data. Thus if ICF operated naively and compared the
1204fcaf7f86SDimitry Andric     // entire contents of each CUE, entries with identical unwind info but e.g.
1205fcaf7f86SDimitry Andric     // belonging to different functions would never be considered equivalent. To
1206fcaf7f86SDimitry Andric     // work around this problem, we remove some parts of the data containing the
1207fcaf7f86SDimitry Andric     // embedded addends. In particular, we remove the function address and LSDA
1208fcaf7f86SDimitry Andric     // pointers.  Since these locations are at the start and end of the entry,
1209fcaf7f86SDimitry Andric     // we can do this using a simple, efficient slice rather than performing a
1210fcaf7f86SDimitry Andric     // copy.  We are not losing any information here because the embedded
1211fcaf7f86SDimitry Andric     // addends have already been parsed in the corresponding Reloc structs.
1212fcaf7f86SDimitry Andric     //
1213fcaf7f86SDimitry Andric     // Removing these pointers would not be safe if they were pointers to
1214fcaf7f86SDimitry Andric     // absolute symbols. In that case, there would be no corresponding
1215fcaf7f86SDimitry Andric     // relocation. However, (AFAIK) MC cannot emit references to absolute
1216fcaf7f86SDimitry Andric     // symbols for either the function address or the LSDA. However, it *can* do
1217fcaf7f86SDimitry Andric     // so for the personality pointer, so we are not slicing that field away.
1218fcaf7f86SDimitry Andric     //
1219fcaf7f86SDimitry Andric     // Note that we do not adjust the offsets of the corresponding relocations;
1220fcaf7f86SDimitry Andric     // instead, we rely on `relocateCompactUnwind()` to correctly handle these
1221fcaf7f86SDimitry Andric     // truncated input sections.
1222fcaf7f86SDimitry Andric     isec->data = isec->data.slice(target->wordSize, 8 + target->wordSize);
122381ad6265SDimitry Andric     uint32_t encoding = read32le(isec->data.data() + sizeof(uint32_t));
122481ad6265SDimitry Andric     // llvm-mc omits CU entries for functions that need DWARF encoding, but
122581ad6265SDimitry Andric     // `ld -r` doesn't. We can ignore them because we will re-synthesize these
122681ad6265SDimitry Andric     // CU entries from the DWARF info during the output phase.
122781ad6265SDimitry Andric     if ((encoding & target->modeDwarfEncoding) == target->modeDwarfEncoding)
122881ad6265SDimitry Andric       continue;
1229349cc55cSDimitry Andric 
1230349cc55cSDimitry Andric     ConcatInputSection *referentIsec;
1231349cc55cSDimitry Andric     for (auto it = isec->relocs.begin(); it != isec->relocs.end();) {
1232349cc55cSDimitry Andric       Reloc &r = *it;
1233349cc55cSDimitry Andric       // CUE::functionAddress is at offset 0. Skip personality & LSDA relocs.
1234349cc55cSDimitry Andric       if (r.offset != 0) {
1235349cc55cSDimitry Andric         ++it;
1236349cc55cSDimitry Andric         continue;
1237349cc55cSDimitry Andric       }
1238349cc55cSDimitry Andric       uint64_t add = r.addend;
1239349cc55cSDimitry Andric       if (auto *sym = cast_or_null<Defined>(r.referent.dyn_cast<Symbol *>())) {
1240349cc55cSDimitry Andric         // Check whether the symbol defined in this file is the prevailing one.
1241349cc55cSDimitry Andric         // Skip if it is e.g. a weak def that didn't prevail.
1242349cc55cSDimitry Andric         if (sym->getFile() != this) {
1243349cc55cSDimitry Andric           ++it;
1244349cc55cSDimitry Andric           continue;
1245349cc55cSDimitry Andric         }
1246349cc55cSDimitry Andric         add += sym->value;
1247349cc55cSDimitry Andric         referentIsec = cast<ConcatInputSection>(sym->isec);
1248349cc55cSDimitry Andric       } else {
1249349cc55cSDimitry Andric         referentIsec =
1250349cc55cSDimitry Andric             cast<ConcatInputSection>(r.referent.dyn_cast<InputSection *>());
1251349cc55cSDimitry Andric       }
125281ad6265SDimitry Andric       // Unwind info lives in __DATA, and finalization of __TEXT will occur
125381ad6265SDimitry Andric       // before finalization of __DATA. Moreover, the finalization of unwind
125481ad6265SDimitry Andric       // info depends on the exact addresses that it references. So it is safe
125581ad6265SDimitry Andric       // for compact unwind to reference addresses in __TEXT, but not addresses
125681ad6265SDimitry Andric       // in any other segment.
1257349cc55cSDimitry Andric       if (referentIsec->getSegName() != segment_names::text)
125881ad6265SDimitry Andric         error(isec->getLocation(r.offset) + " references section " +
125981ad6265SDimitry Andric               referentIsec->getName() + " which is not in segment __TEXT");
1260349cc55cSDimitry Andric       // The functionAddress relocations are typically section relocations.
1261349cc55cSDimitry Andric       // However, unwind info operates on a per-symbol basis, so we search for
1262349cc55cSDimitry Andric       // the function symbol here.
126381ad6265SDimitry Andric       Defined *d = findSymbolAtOffset(referentIsec, add);
126481ad6265SDimitry Andric       if (!d) {
1265349cc55cSDimitry Andric         ++it;
1266349cc55cSDimitry Andric         continue;
1267349cc55cSDimitry Andric       }
126881ad6265SDimitry Andric       d->unwindEntry = isec;
1269fcaf7f86SDimitry Andric       // Now that the symbol points to the unwind entry, we can remove the reloc
1270fcaf7f86SDimitry Andric       // that points from the unwind entry back to the symbol.
1271fcaf7f86SDimitry Andric       //
1272fcaf7f86SDimitry Andric       // First, the symbol keeps the unwind entry alive (and not vice versa), so
1273fcaf7f86SDimitry Andric       // this keeps dead-stripping simple.
1274fcaf7f86SDimitry Andric       //
1275fcaf7f86SDimitry Andric       // Moreover, it reduces the work that ICF needs to do to figure out if
1276fcaf7f86SDimitry Andric       // functions with unwind info are foldable.
1277fcaf7f86SDimitry Andric       //
1278fcaf7f86SDimitry Andric       // However, this does make it possible for ICF to fold CUEs that point to
1279fcaf7f86SDimitry Andric       // distinct functions (if the CUEs are otherwise identical).
1280fcaf7f86SDimitry Andric       // UnwindInfoSection takes care of this by re-duplicating the CUEs so that
1281fcaf7f86SDimitry Andric       // each one can hold a distinct functionAddress value.
1282fcaf7f86SDimitry Andric       //
1283fcaf7f86SDimitry Andric       // Given that clang emits relocations in reverse order of address, this
1284fcaf7f86SDimitry Andric       // relocation should be at the end of the vector for most of our input
1285fcaf7f86SDimitry Andric       // object files, so this erase() is typically an O(1) operation.
1286349cc55cSDimitry Andric       it = isec->relocs.erase(it);
1287349cc55cSDimitry Andric     }
1288349cc55cSDimitry Andric   }
1289349cc55cSDimitry Andric }
1290349cc55cSDimitry Andric 
129181ad6265SDimitry Andric struct CIE {
129281ad6265SDimitry Andric   macho::Symbol *personalitySymbol = nullptr;
129381ad6265SDimitry Andric   bool fdesHaveAug = false;
1294*61cfbce3SDimitry Andric   uint8_t lsdaPtrSize = 0; // 0 => no LSDA
1295*61cfbce3SDimitry Andric   uint8_t funcPtrSize = 0;
129681ad6265SDimitry Andric };
129781ad6265SDimitry Andric 
1298*61cfbce3SDimitry Andric static uint8_t pointerEncodingToSize(uint8_t enc) {
1299*61cfbce3SDimitry Andric   switch (enc & 0xf) {
1300*61cfbce3SDimitry Andric   case dwarf::DW_EH_PE_absptr:
1301*61cfbce3SDimitry Andric     return target->wordSize;
1302*61cfbce3SDimitry Andric   case dwarf::DW_EH_PE_sdata4:
1303*61cfbce3SDimitry Andric     return 4;
1304*61cfbce3SDimitry Andric   case dwarf::DW_EH_PE_sdata8:
1305*61cfbce3SDimitry Andric     // ld64 doesn't actually support sdata8, but this seems simple enough...
1306*61cfbce3SDimitry Andric     return 8;
1307*61cfbce3SDimitry Andric   default:
1308*61cfbce3SDimitry Andric     return 0;
1309*61cfbce3SDimitry Andric   };
1310*61cfbce3SDimitry Andric }
1311*61cfbce3SDimitry Andric 
131281ad6265SDimitry Andric static CIE parseCIE(const InputSection *isec, const EhReader &reader,
131381ad6265SDimitry Andric                     size_t off) {
131481ad6265SDimitry Andric   // Handling the full generality of possible DWARF encodings would be a major
131581ad6265SDimitry Andric   // pain. We instead take advantage of our knowledge of how llvm-mc encodes
131681ad6265SDimitry Andric   // DWARF and handle just that.
131781ad6265SDimitry Andric   constexpr uint8_t expectedPersonalityEnc =
131881ad6265SDimitry Andric       dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_sdata4;
131981ad6265SDimitry Andric 
132081ad6265SDimitry Andric   CIE cie;
132181ad6265SDimitry Andric   uint8_t version = reader.readByte(&off);
132281ad6265SDimitry Andric   if (version != 1 && version != 3)
132381ad6265SDimitry Andric     fatal("Expected CIE version of 1 or 3, got " + Twine(version));
132481ad6265SDimitry Andric   StringRef aug = reader.readString(&off);
132581ad6265SDimitry Andric   reader.skipLeb128(&off); // skip code alignment
132681ad6265SDimitry Andric   reader.skipLeb128(&off); // skip data alignment
132781ad6265SDimitry Andric   reader.skipLeb128(&off); // skip return address register
132881ad6265SDimitry Andric   reader.skipLeb128(&off); // skip aug data length
132981ad6265SDimitry Andric   uint64_t personalityAddrOff = 0;
133081ad6265SDimitry Andric   for (char c : aug) {
133181ad6265SDimitry Andric     switch (c) {
133281ad6265SDimitry Andric     case 'z':
133381ad6265SDimitry Andric       cie.fdesHaveAug = true;
133481ad6265SDimitry Andric       break;
133581ad6265SDimitry Andric     case 'P': {
133681ad6265SDimitry Andric       uint8_t personalityEnc = reader.readByte(&off);
133781ad6265SDimitry Andric       if (personalityEnc != expectedPersonalityEnc)
133881ad6265SDimitry Andric         reader.failOn(off, "unexpected personality encoding 0x" +
133981ad6265SDimitry Andric                                Twine::utohexstr(personalityEnc));
134081ad6265SDimitry Andric       personalityAddrOff = off;
134181ad6265SDimitry Andric       off += 4;
134281ad6265SDimitry Andric       break;
134381ad6265SDimitry Andric     }
134481ad6265SDimitry Andric     case 'L': {
134581ad6265SDimitry Andric       uint8_t lsdaEnc = reader.readByte(&off);
1346*61cfbce3SDimitry Andric       cie.lsdaPtrSize = pointerEncodingToSize(lsdaEnc);
1347*61cfbce3SDimitry Andric       if (cie.lsdaPtrSize == 0)
134881ad6265SDimitry Andric         reader.failOn(off, "unexpected LSDA encoding 0x" +
134981ad6265SDimitry Andric                                Twine::utohexstr(lsdaEnc));
135081ad6265SDimitry Andric       break;
135181ad6265SDimitry Andric     }
135281ad6265SDimitry Andric     case 'R': {
135381ad6265SDimitry Andric       uint8_t pointerEnc = reader.readByte(&off);
1354*61cfbce3SDimitry Andric       cie.funcPtrSize = pointerEncodingToSize(pointerEnc);
1355*61cfbce3SDimitry Andric       if (cie.funcPtrSize == 0 || !(pointerEnc & dwarf::DW_EH_PE_pcrel))
135681ad6265SDimitry Andric         reader.failOn(off, "unexpected pointer encoding 0x" +
135781ad6265SDimitry Andric                                Twine::utohexstr(pointerEnc));
135881ad6265SDimitry Andric       break;
135981ad6265SDimitry Andric     }
136081ad6265SDimitry Andric     default:
136181ad6265SDimitry Andric       break;
136281ad6265SDimitry Andric     }
136381ad6265SDimitry Andric   }
136481ad6265SDimitry Andric   if (personalityAddrOff != 0) {
136581ad6265SDimitry Andric     auto personalityRelocIt =
136681ad6265SDimitry Andric         llvm::find_if(isec->relocs, [=](const macho::Reloc &r) {
136781ad6265SDimitry Andric           return r.offset == personalityAddrOff;
136881ad6265SDimitry Andric         });
136981ad6265SDimitry Andric     if (personalityRelocIt == isec->relocs.end())
137081ad6265SDimitry Andric       reader.failOn(off, "Failed to locate relocation for personality symbol");
137181ad6265SDimitry Andric     cie.personalitySymbol = personalityRelocIt->referent.get<macho::Symbol *>();
137281ad6265SDimitry Andric   }
137381ad6265SDimitry Andric   return cie;
137481ad6265SDimitry Andric }
137581ad6265SDimitry Andric 
137681ad6265SDimitry Andric // EH frame target addresses may be encoded as pcrel offsets. However, instead
137781ad6265SDimitry Andric // of using an actual pcrel reloc, ld64 emits subtractor relocations instead.
137881ad6265SDimitry Andric // This function recovers the target address from the subtractors, essentially
137981ad6265SDimitry Andric // performing the inverse operation of EhRelocator.
138081ad6265SDimitry Andric //
138181ad6265SDimitry Andric // Concretely, we expect our relocations to write the value of `PC -
138281ad6265SDimitry Andric // target_addr` to `PC`. `PC` itself is denoted by a minuend relocation that
138381ad6265SDimitry Andric // points to a symbol plus an addend.
138481ad6265SDimitry Andric //
138581ad6265SDimitry Andric // It is important that the minuend relocation point to a symbol within the
138681ad6265SDimitry Andric // same section as the fixup value, since sections may get moved around.
138781ad6265SDimitry Andric //
138881ad6265SDimitry Andric // For example, for arm64, llvm-mc emits relocations for the target function
138981ad6265SDimitry Andric // address like so:
139081ad6265SDimitry Andric //
139181ad6265SDimitry Andric //   ltmp:
139281ad6265SDimitry Andric //     <CIE start>
139381ad6265SDimitry Andric //     ...
139481ad6265SDimitry Andric //     <CIE end>
139581ad6265SDimitry Andric //     ... multiple FDEs ...
139681ad6265SDimitry Andric //     <FDE start>
139781ad6265SDimitry Andric //     <target function address - (ltmp + pcrel offset)>
139881ad6265SDimitry Andric //     ...
139981ad6265SDimitry Andric //
140081ad6265SDimitry Andric // If any of the FDEs in `multiple FDEs` get dead-stripped, then `FDE start`
140181ad6265SDimitry Andric // will move to an earlier address, and `ltmp + pcrel offset` will no longer
140281ad6265SDimitry Andric // reflect an accurate pcrel value. To avoid this problem, we "canonicalize"
140381ad6265SDimitry Andric // our relocation by adding an `EH_Frame` symbol at `FDE start`, and updating
140481ad6265SDimitry Andric // the reloc to be `target function address - (EH_Frame + new pcrel offset)`.
140581ad6265SDimitry Andric //
140681ad6265SDimitry Andric // If `Invert` is set, then we instead expect `target_addr - PC` to be written
140781ad6265SDimitry Andric // to `PC`.
140881ad6265SDimitry Andric template <bool Invert = false>
140981ad6265SDimitry Andric Defined *
141081ad6265SDimitry Andric targetSymFromCanonicalSubtractor(const InputSection *isec,
141181ad6265SDimitry Andric                                  std::vector<macho::Reloc>::iterator relocIt) {
141281ad6265SDimitry Andric   macho::Reloc &subtrahend = *relocIt;
141381ad6265SDimitry Andric   macho::Reloc &minuend = *std::next(relocIt);
141481ad6265SDimitry Andric   assert(target->hasAttr(subtrahend.type, RelocAttrBits::SUBTRAHEND));
141581ad6265SDimitry Andric   assert(target->hasAttr(minuend.type, RelocAttrBits::UNSIGNED));
141681ad6265SDimitry Andric   // Note: pcSym may *not* be exactly at the PC; there's usually a non-zero
141781ad6265SDimitry Andric   // addend.
141881ad6265SDimitry Andric   auto *pcSym = cast<Defined>(subtrahend.referent.get<macho::Symbol *>());
141981ad6265SDimitry Andric   Defined *target =
142081ad6265SDimitry Andric       cast_or_null<Defined>(minuend.referent.dyn_cast<macho::Symbol *>());
142181ad6265SDimitry Andric   if (!pcSym) {
142281ad6265SDimitry Andric     auto *targetIsec =
142381ad6265SDimitry Andric         cast<ConcatInputSection>(minuend.referent.get<InputSection *>());
142481ad6265SDimitry Andric     target = findSymbolAtOffset(targetIsec, minuend.addend);
142581ad6265SDimitry Andric   }
142681ad6265SDimitry Andric   if (Invert)
142781ad6265SDimitry Andric     std::swap(pcSym, target);
142881ad6265SDimitry Andric   if (pcSym->isec == isec) {
142981ad6265SDimitry Andric     if (pcSym->value - (Invert ? -1 : 1) * minuend.addend != subtrahend.offset)
143081ad6265SDimitry Andric       fatal("invalid FDE relocation in __eh_frame");
143181ad6265SDimitry Andric   } else {
143281ad6265SDimitry Andric     // Ensure the pcReloc points to a symbol within the current EH frame.
143381ad6265SDimitry Andric     // HACK: we should really verify that the original relocation's semantics
143481ad6265SDimitry Andric     // are preserved. In particular, we should have
143581ad6265SDimitry Andric     // `oldSym->value + oldOffset == newSym + newOffset`. However, we don't
143681ad6265SDimitry Andric     // have an easy way to access the offsets from this point in the code; some
143781ad6265SDimitry Andric     // refactoring is needed for that.
143881ad6265SDimitry Andric     macho::Reloc &pcReloc = Invert ? minuend : subtrahend;
143981ad6265SDimitry Andric     pcReloc.referent = isec->symbols[0];
144081ad6265SDimitry Andric     assert(isec->symbols[0]->value == 0);
144181ad6265SDimitry Andric     minuend.addend = pcReloc.offset * (Invert ? 1LL : -1LL);
144281ad6265SDimitry Andric   }
144381ad6265SDimitry Andric   return target;
144481ad6265SDimitry Andric }
144581ad6265SDimitry Andric 
144681ad6265SDimitry Andric Defined *findSymbolAtAddress(const std::vector<Section *> &sections,
144781ad6265SDimitry Andric                              uint64_t addr) {
144881ad6265SDimitry Andric   Section *sec = findContainingSection(sections, &addr);
144981ad6265SDimitry Andric   auto *isec = cast<ConcatInputSection>(findContainingSubsection(*sec, &addr));
145081ad6265SDimitry Andric   return findSymbolAtOffset(isec, addr);
145181ad6265SDimitry Andric }
145281ad6265SDimitry Andric 
145381ad6265SDimitry Andric // For symbols that don't have compact unwind info, associate them with the more
145481ad6265SDimitry Andric // general-purpose (and verbose) DWARF unwind info found in __eh_frame.
145581ad6265SDimitry Andric //
145681ad6265SDimitry Andric // This requires us to parse the contents of __eh_frame. See EhFrame.h for a
145781ad6265SDimitry Andric // description of its format.
145881ad6265SDimitry Andric //
145981ad6265SDimitry Andric // While parsing, we also look for what MC calls "abs-ified" relocations -- they
146081ad6265SDimitry Andric // are relocations which are implicitly encoded as offsets in the section data.
146181ad6265SDimitry Andric // We convert them into explicit Reloc structs so that the EH frames can be
146281ad6265SDimitry Andric // handled just like a regular ConcatInputSection later in our output phase.
146381ad6265SDimitry Andric //
146481ad6265SDimitry Andric // We also need to handle the case where our input object file has explicit
146581ad6265SDimitry Andric // relocations. This is the case when e.g. it's the output of `ld -r`. We only
146681ad6265SDimitry Andric // look for the "abs-ified" relocation if an explicit relocation is absent.
146781ad6265SDimitry Andric void ObjFile::registerEhFrames(Section &ehFrameSection) {
146881ad6265SDimitry Andric   DenseMap<const InputSection *, CIE> cieMap;
146981ad6265SDimitry Andric   for (const Subsection &subsec : ehFrameSection.subsections) {
147081ad6265SDimitry Andric     auto *isec = cast<ConcatInputSection>(subsec.isec);
147181ad6265SDimitry Andric     uint64_t isecOff = subsec.offset;
147281ad6265SDimitry Andric 
147381ad6265SDimitry Andric     // Subtractor relocs require the subtrahend to be a symbol reloc. Ensure
147481ad6265SDimitry Andric     // that all EH frames have an associated symbol so that we can generate
147581ad6265SDimitry Andric     // subtractor relocs that reference them.
147681ad6265SDimitry Andric     if (isec->symbols.size() == 0)
147781ad6265SDimitry Andric       isec->symbols.push_back(make<Defined>(
147881ad6265SDimitry Andric           "EH_Frame", isec->getFile(), isec, /*value=*/0, /*size=*/0,
147981ad6265SDimitry Andric           /*isWeakDef=*/false, /*isExternal=*/false, /*isPrivateExtern=*/false,
148081ad6265SDimitry Andric           /*includeInSymtab=*/false, /*isThumb=*/false,
148181ad6265SDimitry Andric           /*isReferencedDynamically=*/false, /*noDeadStrip=*/false));
148281ad6265SDimitry Andric     else if (isec->symbols[0]->value != 0)
148381ad6265SDimitry Andric       fatal("found symbol at unexpected offset in __eh_frame");
148481ad6265SDimitry Andric 
1485*61cfbce3SDimitry Andric     EhReader reader(this, isec->data, subsec.offset);
148681ad6265SDimitry Andric     size_t dataOff = 0; // Offset from the start of the EH frame.
148781ad6265SDimitry Andric     reader.skipValidLength(&dataOff); // readLength() already validated this.
148881ad6265SDimitry Andric     // cieOffOff is the offset from the start of the EH frame to the cieOff
148981ad6265SDimitry Andric     // value, which is itself an offset from the current PC to a CIE.
149081ad6265SDimitry Andric     const size_t cieOffOff = dataOff;
149181ad6265SDimitry Andric 
149281ad6265SDimitry Andric     EhRelocator ehRelocator(isec);
149381ad6265SDimitry Andric     auto cieOffRelocIt = llvm::find_if(
149481ad6265SDimitry Andric         isec->relocs, [=](const Reloc &r) { return r.offset == cieOffOff; });
149581ad6265SDimitry Andric     InputSection *cieIsec = nullptr;
149681ad6265SDimitry Andric     if (cieOffRelocIt != isec->relocs.end()) {
149781ad6265SDimitry Andric       // We already have an explicit relocation for the CIE offset.
149881ad6265SDimitry Andric       cieIsec =
149981ad6265SDimitry Andric           targetSymFromCanonicalSubtractor</*Invert=*/true>(isec, cieOffRelocIt)
150081ad6265SDimitry Andric               ->isec;
150181ad6265SDimitry Andric       dataOff += sizeof(uint32_t);
150281ad6265SDimitry Andric     } else {
150381ad6265SDimitry Andric       // If we haven't found a relocation, then the CIE offset is most likely
150481ad6265SDimitry Andric       // embedded in the section data (AKA an "abs-ified" reloc.). Parse that
150581ad6265SDimitry Andric       // and generate a Reloc struct.
150681ad6265SDimitry Andric       uint32_t cieMinuend = reader.readU32(&dataOff);
150781ad6265SDimitry Andric       if (cieMinuend == 0)
150881ad6265SDimitry Andric         cieIsec = isec;
150981ad6265SDimitry Andric       else {
151081ad6265SDimitry Andric         uint32_t cieOff = isecOff + dataOff - cieMinuend;
151181ad6265SDimitry Andric         cieIsec = findContainingSubsection(ehFrameSection, &cieOff);
151281ad6265SDimitry Andric         if (cieIsec == nullptr)
151381ad6265SDimitry Andric           fatal("failed to find CIE");
151481ad6265SDimitry Andric       }
151581ad6265SDimitry Andric       if (cieIsec != isec)
151681ad6265SDimitry Andric         ehRelocator.makeNegativePcRel(cieOffOff, cieIsec->symbols[0],
151781ad6265SDimitry Andric                                       /*length=*/2);
151881ad6265SDimitry Andric     }
151981ad6265SDimitry Andric     if (cieIsec == isec) {
152081ad6265SDimitry Andric       cieMap[cieIsec] = parseCIE(isec, reader, dataOff);
152181ad6265SDimitry Andric       continue;
152281ad6265SDimitry Andric     }
152381ad6265SDimitry Andric 
152481ad6265SDimitry Andric     assert(cieMap.count(cieIsec));
152581ad6265SDimitry Andric     const CIE &cie = cieMap[cieIsec];
1526*61cfbce3SDimitry Andric     // Offset of the function address within the EH frame.
1527*61cfbce3SDimitry Andric     const size_t funcAddrOff = dataOff;
1528*61cfbce3SDimitry Andric     uint64_t funcAddr = reader.readPointer(&dataOff, cie.funcPtrSize) +
1529*61cfbce3SDimitry Andric                         ehFrameSection.addr + isecOff + funcAddrOff;
1530*61cfbce3SDimitry Andric     uint32_t funcLength = reader.readPointer(&dataOff, cie.funcPtrSize);
1531*61cfbce3SDimitry Andric     size_t lsdaAddrOff = 0; // Offset of the LSDA address within the EH frame.
153281ad6265SDimitry Andric     Optional<uint64_t> lsdaAddrOpt;
153381ad6265SDimitry Andric     if (cie.fdesHaveAug) {
153481ad6265SDimitry Andric       reader.skipLeb128(&dataOff);
153581ad6265SDimitry Andric       lsdaAddrOff = dataOff;
1536*61cfbce3SDimitry Andric       if (cie.lsdaPtrSize != 0) {
1537*61cfbce3SDimitry Andric         uint64_t lsdaOff = reader.readPointer(&dataOff, cie.lsdaPtrSize);
153881ad6265SDimitry Andric         if (lsdaOff != 0) // FIXME possible to test this?
153981ad6265SDimitry Andric           lsdaAddrOpt = ehFrameSection.addr + isecOff + lsdaAddrOff + lsdaOff;
154081ad6265SDimitry Andric       }
154181ad6265SDimitry Andric     }
154281ad6265SDimitry Andric 
154381ad6265SDimitry Andric     auto funcAddrRelocIt = isec->relocs.end();
154481ad6265SDimitry Andric     auto lsdaAddrRelocIt = isec->relocs.end();
154581ad6265SDimitry Andric     for (auto it = isec->relocs.begin(); it != isec->relocs.end(); ++it) {
154681ad6265SDimitry Andric       if (it->offset == funcAddrOff)
154781ad6265SDimitry Andric         funcAddrRelocIt = it++; // Found subtrahend; skip over minuend reloc
154881ad6265SDimitry Andric       else if (lsdaAddrOpt && it->offset == lsdaAddrOff)
154981ad6265SDimitry Andric         lsdaAddrRelocIt = it++; // Found subtrahend; skip over minuend reloc
155081ad6265SDimitry Andric     }
155181ad6265SDimitry Andric 
155281ad6265SDimitry Andric     Defined *funcSym;
155381ad6265SDimitry Andric     if (funcAddrRelocIt != isec->relocs.end()) {
155481ad6265SDimitry Andric       funcSym = targetSymFromCanonicalSubtractor(isec, funcAddrRelocIt);
1555fcaf7f86SDimitry Andric       // Canonicalize the symbol. If there are multiple symbols at the same
1556fcaf7f86SDimitry Andric       // address, we want both `registerEhFrame` and `registerCompactUnwind`
1557fcaf7f86SDimitry Andric       // to register the unwind entry under same symbol.
1558fcaf7f86SDimitry Andric       // This is not particularly efficient, but we should run into this case
1559fcaf7f86SDimitry Andric       // infrequently (only when handling the output of `ld -r`).
1560fcaf7f86SDimitry Andric       if (funcSym->isec)
1561fcaf7f86SDimitry Andric         funcSym = findSymbolAtOffset(cast<ConcatInputSection>(funcSym->isec),
1562fcaf7f86SDimitry Andric                                      funcSym->value);
156381ad6265SDimitry Andric     } else {
156481ad6265SDimitry Andric       funcSym = findSymbolAtAddress(sections, funcAddr);
156581ad6265SDimitry Andric       ehRelocator.makePcRel(funcAddrOff, funcSym, target->p2WordSize);
156681ad6265SDimitry Andric     }
156781ad6265SDimitry Andric     // The symbol has been coalesced, or already has a compact unwind entry.
156881ad6265SDimitry Andric     if (!funcSym || funcSym->getFile() != this || funcSym->unwindEntry) {
156981ad6265SDimitry Andric       // We must prune unused FDEs for correctness, so we cannot rely on
157081ad6265SDimitry Andric       // -dead_strip being enabled.
157181ad6265SDimitry Andric       isec->live = false;
157281ad6265SDimitry Andric       continue;
157381ad6265SDimitry Andric     }
157481ad6265SDimitry Andric 
157581ad6265SDimitry Andric     InputSection *lsdaIsec = nullptr;
157681ad6265SDimitry Andric     if (lsdaAddrRelocIt != isec->relocs.end()) {
157781ad6265SDimitry Andric       lsdaIsec = targetSymFromCanonicalSubtractor(isec, lsdaAddrRelocIt)->isec;
157881ad6265SDimitry Andric     } else if (lsdaAddrOpt) {
157981ad6265SDimitry Andric       uint64_t lsdaAddr = *lsdaAddrOpt;
158081ad6265SDimitry Andric       Section *sec = findContainingSection(sections, &lsdaAddr);
158181ad6265SDimitry Andric       lsdaIsec =
158281ad6265SDimitry Andric           cast<ConcatInputSection>(findContainingSubsection(*sec, &lsdaAddr));
158381ad6265SDimitry Andric       ehRelocator.makePcRel(lsdaAddrOff, lsdaIsec, target->p2WordSize);
158481ad6265SDimitry Andric     }
158581ad6265SDimitry Andric 
158681ad6265SDimitry Andric     fdes[isec] = {funcLength, cie.personalitySymbol, lsdaIsec};
158781ad6265SDimitry Andric     funcSym->unwindEntry = isec;
158881ad6265SDimitry Andric     ehRelocator.commit();
158981ad6265SDimitry Andric   }
159081ad6265SDimitry Andric }
159181ad6265SDimitry Andric 
159281ad6265SDimitry Andric std::string ObjFile::sourceFile() const {
159381ad6265SDimitry Andric   SmallString<261> dir(compileUnit->getCompilationDir());
159481ad6265SDimitry Andric   StringRef sep = sys::path::get_separator();
159581ad6265SDimitry Andric   // We don't use `path::append` here because we want an empty `dir` to result
159681ad6265SDimitry Andric   // in an absolute path. `append` would give us a relative path for that case.
159781ad6265SDimitry Andric   if (!dir.endswith(sep))
159881ad6265SDimitry Andric     dir += sep;
159981ad6265SDimitry Andric   return (dir + compileUnit->getUnitDIE().getShortName()).str();
160081ad6265SDimitry Andric }
160181ad6265SDimitry Andric 
160281ad6265SDimitry Andric lld::DWARFCache *ObjFile::getDwarf() {
160381ad6265SDimitry Andric   llvm::call_once(initDwarf, [this]() {
160481ad6265SDimitry Andric     auto dwObj = DwarfObject::create(this);
160581ad6265SDimitry Andric     if (!dwObj)
160681ad6265SDimitry Andric       return;
160781ad6265SDimitry Andric     dwarfCache = std::make_unique<DWARFCache>(std::make_unique<DWARFContext>(
160881ad6265SDimitry Andric         std::move(dwObj), "",
160981ad6265SDimitry Andric         [&](Error err) { warn(getName() + ": " + toString(std::move(err))); },
161081ad6265SDimitry Andric         [&](Error warning) {
161181ad6265SDimitry Andric           warn(getName() + ": " + toString(std::move(warning)));
161281ad6265SDimitry Andric         }));
161381ad6265SDimitry Andric   });
161481ad6265SDimitry Andric 
161581ad6265SDimitry Andric   return dwarfCache.get();
161681ad6265SDimitry Andric }
1617e8d8bef9SDimitry Andric // The path can point to either a dylib or a .tbd file.
1618fe6060f1SDimitry Andric static DylibFile *loadDylib(StringRef path, DylibFile *umbrella) {
1619e8d8bef9SDimitry Andric   Optional<MemoryBufferRef> mbref = readFile(path);
1620e8d8bef9SDimitry Andric   if (!mbref) {
1621e8d8bef9SDimitry Andric     error("could not read dylib file at " + path);
1622fe6060f1SDimitry Andric     return nullptr;
1623e8d8bef9SDimitry Andric   }
1624e8d8bef9SDimitry Andric   return loadDylib(*mbref, umbrella);
1625e8d8bef9SDimitry Andric }
1626e8d8bef9SDimitry Andric 
1627e8d8bef9SDimitry Andric // TBD files are parsed into a series of TAPI documents (InterfaceFiles), with
1628e8d8bef9SDimitry Andric // the first document storing child pointers to the rest of them. When we are
1629fe6060f1SDimitry Andric // processing a given TBD file, we store that top-level document in
1630fe6060f1SDimitry Andric // currentTopLevelTapi. When processing re-exports, we search its children for
1631fe6060f1SDimitry Andric // potentially matching documents in the same TBD file. Note that the children
1632fe6060f1SDimitry Andric // themselves don't point to further documents, i.e. this is a two-level tree.
1633e8d8bef9SDimitry Andric //
1634e8d8bef9SDimitry Andric // Re-exports can either refer to on-disk files, or to documents within .tbd
1635e8d8bef9SDimitry Andric // files.
1636fe6060f1SDimitry Andric static DylibFile *findDylib(StringRef path, DylibFile *umbrella,
1637fe6060f1SDimitry Andric                             const InterfaceFile *currentTopLevelTapi) {
1638fe6060f1SDimitry Andric   // Search order:
1639fe6060f1SDimitry Andric   // 1. Install name basename in -F / -L directories.
1640fe6060f1SDimitry Andric   {
1641fe6060f1SDimitry Andric     StringRef stem = path::stem(path);
1642fe6060f1SDimitry Andric     SmallString<128> frameworkName;
1643fe6060f1SDimitry Andric     path::append(frameworkName, path::Style::posix, stem + ".framework", stem);
1644fe6060f1SDimitry Andric     bool isFramework = path.endswith(frameworkName);
1645fe6060f1SDimitry Andric     if (isFramework) {
1646fe6060f1SDimitry Andric       for (StringRef dir : config->frameworkSearchPaths) {
1647fe6060f1SDimitry Andric         SmallString<128> candidate = dir;
1648fe6060f1SDimitry Andric         path::append(candidate, frameworkName);
1649349cc55cSDimitry Andric         if (Optional<StringRef> dylibPath = resolveDylibPath(candidate.str()))
1650fe6060f1SDimitry Andric           return loadDylib(*dylibPath, umbrella);
1651fe6060f1SDimitry Andric       }
1652fe6060f1SDimitry Andric     } else if (Optional<StringRef> dylibPath = findPathCombination(
1653fe6060f1SDimitry Andric                    stem, config->librarySearchPaths, {".tbd", ".dylib"}))
1654fe6060f1SDimitry Andric       return loadDylib(*dylibPath, umbrella);
1655fe6060f1SDimitry Andric   }
1656fe6060f1SDimitry Andric 
1657fe6060f1SDimitry Andric   // 2. As absolute path.
1658e8d8bef9SDimitry Andric   if (path::is_absolute(path, path::Style::posix))
1659e8d8bef9SDimitry Andric     for (StringRef root : config->systemLibraryRoots)
1660349cc55cSDimitry Andric       if (Optional<StringRef> dylibPath = resolveDylibPath((root + path).str()))
1661e8d8bef9SDimitry Andric         return loadDylib(*dylibPath, umbrella);
1662e8d8bef9SDimitry Andric 
1663fe6060f1SDimitry Andric   // 3. As relative path.
1664e8d8bef9SDimitry Andric 
1665fe6060f1SDimitry Andric   // TODO: Handle -dylib_file
1666fe6060f1SDimitry Andric 
1667fe6060f1SDimitry Andric   // Replace @executable_path, @loader_path, @rpath prefixes in install name.
1668fe6060f1SDimitry Andric   SmallString<128> newPath;
1669fe6060f1SDimitry Andric   if (config->outputType == MH_EXECUTE &&
1670fe6060f1SDimitry Andric       path.consume_front("@executable_path/")) {
1671fe6060f1SDimitry Andric     // ld64 allows overriding this with the undocumented flag -executable_path.
1672fe6060f1SDimitry Andric     // lld doesn't currently implement that flag.
1673fe6060f1SDimitry Andric     // FIXME: Consider using finalOutput instead of outputFile.
1674fe6060f1SDimitry Andric     path::append(newPath, path::parent_path(config->outputFile), path);
1675fe6060f1SDimitry Andric     path = newPath;
1676fe6060f1SDimitry Andric   } else if (path.consume_front("@loader_path/")) {
1677fe6060f1SDimitry Andric     fs::real_path(umbrella->getName(), newPath);
1678fe6060f1SDimitry Andric     path::remove_filename(newPath);
1679fe6060f1SDimitry Andric     path::append(newPath, path);
1680fe6060f1SDimitry Andric     path = newPath;
1681fe6060f1SDimitry Andric   } else if (path.startswith("@rpath/")) {
1682fe6060f1SDimitry Andric     for (StringRef rpath : umbrella->rpaths) {
1683fe6060f1SDimitry Andric       newPath.clear();
1684fe6060f1SDimitry Andric       if (rpath.consume_front("@loader_path/")) {
1685fe6060f1SDimitry Andric         fs::real_path(umbrella->getName(), newPath);
1686fe6060f1SDimitry Andric         path::remove_filename(newPath);
1687fe6060f1SDimitry Andric       }
1688fe6060f1SDimitry Andric       path::append(newPath, rpath, path.drop_front(strlen("@rpath/")));
1689349cc55cSDimitry Andric       if (Optional<StringRef> dylibPath = resolveDylibPath(newPath.str()))
1690fe6060f1SDimitry Andric         return loadDylib(*dylibPath, umbrella);
1691fe6060f1SDimitry Andric     }
1692fe6060f1SDimitry Andric   }
1693fe6060f1SDimitry Andric 
1694fe6060f1SDimitry Andric   // FIXME: Should this be further up?
1695e8d8bef9SDimitry Andric   if (currentTopLevelTapi) {
1696e8d8bef9SDimitry Andric     for (InterfaceFile &child :
1697e8d8bef9SDimitry Andric          make_pointee_range(currentTopLevelTapi->documents())) {
1698e8d8bef9SDimitry Andric       assert(child.documents().empty());
1699fe6060f1SDimitry Andric       if (path == child.getInstallName()) {
170081ad6265SDimitry Andric         auto file = make<DylibFile>(child, umbrella, /*isBundleLoader=*/false,
170181ad6265SDimitry Andric                                     /*explicitlyLinked=*/false);
1702fe6060f1SDimitry Andric         file->parseReexports(child);
1703fe6060f1SDimitry Andric         return file;
1704fe6060f1SDimitry Andric       }
1705e8d8bef9SDimitry Andric     }
1706e8d8bef9SDimitry Andric   }
1707e8d8bef9SDimitry Andric 
1708349cc55cSDimitry Andric   if (Optional<StringRef> dylibPath = resolveDylibPath(path))
1709e8d8bef9SDimitry Andric     return loadDylib(*dylibPath, umbrella);
1710e8d8bef9SDimitry Andric 
1711fe6060f1SDimitry Andric   return nullptr;
1712e8d8bef9SDimitry Andric }
1713e8d8bef9SDimitry Andric 
1714e8d8bef9SDimitry Andric // If a re-exported dylib is public (lives in /usr/lib or
1715e8d8bef9SDimitry Andric // /System/Library/Frameworks), then it is considered implicitly linked: we
1716e8d8bef9SDimitry Andric // should bind to its symbols directly instead of via the re-exporting umbrella
1717e8d8bef9SDimitry Andric // library.
1718e8d8bef9SDimitry Andric static bool isImplicitlyLinked(StringRef path) {
1719e8d8bef9SDimitry Andric   if (!config->implicitDylibs)
1720e8d8bef9SDimitry Andric     return false;
1721e8d8bef9SDimitry Andric 
1722e8d8bef9SDimitry Andric   if (path::parent_path(path) == "/usr/lib")
1723e8d8bef9SDimitry Andric     return true;
1724e8d8bef9SDimitry Andric 
1725e8d8bef9SDimitry Andric   // Match /System/Library/Frameworks/$FOO.framework/**/$FOO
1726e8d8bef9SDimitry Andric   if (path.consume_front("/System/Library/Frameworks/")) {
1727e8d8bef9SDimitry Andric     StringRef frameworkName = path.take_until([](char c) { return c == '.'; });
1728e8d8bef9SDimitry Andric     return path::filename(path) == frameworkName;
1729e8d8bef9SDimitry Andric   }
1730e8d8bef9SDimitry Andric 
1731e8d8bef9SDimitry Andric   return false;
1732e8d8bef9SDimitry Andric }
1733e8d8bef9SDimitry Andric 
1734fe6060f1SDimitry Andric static void loadReexport(StringRef path, DylibFile *umbrella,
1735fe6060f1SDimitry Andric                          const InterfaceFile *currentTopLevelTapi) {
1736fe6060f1SDimitry Andric   DylibFile *reexport = findDylib(path, umbrella, currentTopLevelTapi);
1737fe6060f1SDimitry Andric   if (!reexport)
1738fe6060f1SDimitry Andric     error("unable to locate re-export with install name " + path);
17395ffd83dbSDimitry Andric }
17405ffd83dbSDimitry Andric 
1741fe6060f1SDimitry Andric DylibFile::DylibFile(MemoryBufferRef mb, DylibFile *umbrella,
174281ad6265SDimitry Andric                      bool isBundleLoader, bool explicitlyLinked)
1743fe6060f1SDimitry Andric     : InputFile(DylibKind, mb), refState(RefState::Unreferenced),
174481ad6265SDimitry Andric       explicitlyLinked(explicitlyLinked), isBundleLoader(isBundleLoader) {
1745fe6060f1SDimitry Andric   assert(!isBundleLoader || !umbrella);
17465ffd83dbSDimitry Andric   if (umbrella == nullptr)
17475ffd83dbSDimitry Andric     umbrella = this;
1748fe6060f1SDimitry Andric   this->umbrella = umbrella;
17495ffd83dbSDimitry Andric 
1750fe6060f1SDimitry Andric   auto *hdr = reinterpret_cast<const mach_header *>(mb.getBufferStart());
17515ffd83dbSDimitry Andric 
1752fe6060f1SDimitry Andric   // Initialize installName.
17535ffd83dbSDimitry Andric   if (const load_command *cmd = findCommand(hdr, LC_ID_DYLIB)) {
17545ffd83dbSDimitry Andric     auto *c = reinterpret_cast<const dylib_command *>(cmd);
1755e8d8bef9SDimitry Andric     currentVersion = read32le(&c->dylib.current_version);
1756e8d8bef9SDimitry Andric     compatibilityVersion = read32le(&c->dylib.compatibility_version);
1757fe6060f1SDimitry Andric     installName =
1758fe6060f1SDimitry Andric         reinterpret_cast<const char *>(cmd) + read32le(&c->dylib.name);
1759fe6060f1SDimitry Andric   } else if (!isBundleLoader) {
1760fe6060f1SDimitry Andric     // macho_executable and macho_bundle don't have LC_ID_DYLIB,
1761fe6060f1SDimitry Andric     // so it's OK.
1762e8d8bef9SDimitry Andric     error("dylib " + toString(this) + " missing LC_ID_DYLIB load command");
17635ffd83dbSDimitry Andric     return;
17645ffd83dbSDimitry Andric   }
17655ffd83dbSDimitry Andric 
1766fe6060f1SDimitry Andric   if (config->printEachFile)
1767fe6060f1SDimitry Andric     message(toString(this));
1768fe6060f1SDimitry Andric   inputFiles.insert(this);
1769fe6060f1SDimitry Andric 
1770fe6060f1SDimitry Andric   deadStrippable = hdr->flags & MH_DEAD_STRIPPABLE_DYLIB;
1771fe6060f1SDimitry Andric 
1772fe6060f1SDimitry Andric   if (!checkCompatibility(this))
1773fe6060f1SDimitry Andric     return;
1774fe6060f1SDimitry Andric 
1775fe6060f1SDimitry Andric   checkAppExtensionSafety(hdr->flags & MH_APP_EXTENSION_SAFE);
1776fe6060f1SDimitry Andric 
1777fe6060f1SDimitry Andric   for (auto *cmd : findCommands<rpath_command>(hdr, LC_RPATH)) {
1778fe6060f1SDimitry Andric     StringRef rpath{reinterpret_cast<const char *>(cmd) + cmd->path};
1779fe6060f1SDimitry Andric     rpaths.push_back(rpath);
1780fe6060f1SDimitry Andric   }
1781fe6060f1SDimitry Andric 
17825ffd83dbSDimitry Andric   // Initialize symbols.
1783fe6060f1SDimitry Andric   exportingFile = isImplicitlyLinked(installName) ? this : this->umbrella;
1784753f127fSDimitry Andric 
1785753f127fSDimitry Andric   const auto *dyldInfo = findCommand<dyld_info_command>(hdr, LC_DYLD_INFO_ONLY);
1786753f127fSDimitry Andric   const auto *exportsTrie =
1787753f127fSDimitry Andric       findCommand<linkedit_data_command>(hdr, LC_DYLD_EXPORTS_TRIE);
1788753f127fSDimitry Andric   if (dyldInfo && exportsTrie) {
1789753f127fSDimitry Andric     // It's unclear what should happen in this case. Maybe we should only error
1790753f127fSDimitry Andric     // out if the two load commands refer to different data?
1791753f127fSDimitry Andric     error("dylib " + toString(this) +
1792753f127fSDimitry Andric           " has both LC_DYLD_INFO_ONLY and LC_DYLD_EXPORTS_TRIE");
1793753f127fSDimitry Andric     return;
1794753f127fSDimitry Andric   } else if (dyldInfo) {
1795753f127fSDimitry Andric     parseExportedSymbols(dyldInfo->export_off, dyldInfo->export_size);
1796753f127fSDimitry Andric   } else if (exportsTrie) {
1797753f127fSDimitry Andric     parseExportedSymbols(exportsTrie->dataoff, exportsTrie->datasize);
1798753f127fSDimitry Andric   } else {
1799753f127fSDimitry Andric     error("No LC_DYLD_INFO_ONLY or LC_DYLD_EXPORTS_TRIE found in " +
1800753f127fSDimitry Andric           toString(this));
1801753f127fSDimitry Andric     return;
1802753f127fSDimitry Andric   }
1803753f127fSDimitry Andric }
1804753f127fSDimitry Andric 
1805753f127fSDimitry Andric void DylibFile::parseExportedSymbols(uint32_t offset, uint32_t size) {
18060eae32dcSDimitry Andric   struct TrieEntry {
18070eae32dcSDimitry Andric     StringRef name;
18080eae32dcSDimitry Andric     uint64_t flags;
18090eae32dcSDimitry Andric   };
18100eae32dcSDimitry Andric 
1811753f127fSDimitry Andric   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
18120eae32dcSDimitry Andric   std::vector<TrieEntry> entries;
18130eae32dcSDimitry Andric   // Find all the $ld$* symbols to process first.
1814753f127fSDimitry Andric   parseTrie(buf + offset, size, [&](const Twine &name, uint64_t flags) {
181504eeddc0SDimitry Andric     StringRef savedName = saver().save(name);
1816fe6060f1SDimitry Andric     if (handleLDSymbol(savedName))
1817fe6060f1SDimitry Andric       return;
18180eae32dcSDimitry Andric     entries.push_back({savedName, flags});
18195ffd83dbSDimitry Andric   });
18200eae32dcSDimitry Andric 
18210eae32dcSDimitry Andric   // Process the "normal" symbols.
18220eae32dcSDimitry Andric   for (TrieEntry &entry : entries) {
1823753f127fSDimitry Andric     if (exportingFile->hiddenSymbols.contains(CachedHashStringRef(entry.name)))
18240eae32dcSDimitry Andric       continue;
18250eae32dcSDimitry Andric 
18260eae32dcSDimitry Andric     bool isWeakDef = entry.flags & EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION;
18270eae32dcSDimitry Andric     bool isTlv = entry.flags & EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL;
18280eae32dcSDimitry Andric 
18290eae32dcSDimitry Andric     symbols.push_back(
18300eae32dcSDimitry Andric         symtab->addDylib(entry.name, exportingFile, isWeakDef, isTlv));
18310eae32dcSDimitry Andric   }
1832fe6060f1SDimitry Andric }
18335ffd83dbSDimitry Andric 
1834fe6060f1SDimitry Andric void DylibFile::parseLoadCommands(MemoryBufferRef mb) {
1835fe6060f1SDimitry Andric   auto *hdr = reinterpret_cast<const mach_header *>(mb.getBufferStart());
1836fe6060f1SDimitry Andric   const uint8_t *p = reinterpret_cast<const uint8_t *>(mb.getBufferStart()) +
1837fe6060f1SDimitry Andric                      target->headerSize;
18385ffd83dbSDimitry Andric   for (uint32_t i = 0, n = hdr->ncmds; i < n; ++i) {
18395ffd83dbSDimitry Andric     auto *cmd = reinterpret_cast<const load_command *>(p);
18405ffd83dbSDimitry Andric     p += cmd->cmdsize;
18415ffd83dbSDimitry Andric 
1842fe6060f1SDimitry Andric     if (!(hdr->flags & MH_NO_REEXPORTED_DYLIBS) &&
1843fe6060f1SDimitry Andric         cmd->cmd == LC_REEXPORT_DYLIB) {
1844fe6060f1SDimitry Andric       const auto *c = reinterpret_cast<const dylib_command *>(cmd);
18455ffd83dbSDimitry Andric       StringRef reexportPath =
18465ffd83dbSDimitry Andric           reinterpret_cast<const char *>(c) + read32le(&c->dylib.name);
1847fe6060f1SDimitry Andric       loadReexport(reexportPath, exportingFile, nullptr);
1848fe6060f1SDimitry Andric     }
1849fe6060f1SDimitry Andric 
1850fe6060f1SDimitry Andric     // FIXME: What about LC_LOAD_UPWARD_DYLIB, LC_LAZY_LOAD_DYLIB,
1851fe6060f1SDimitry Andric     // LC_LOAD_WEAK_DYLIB, LC_REEXPORT_DYLIB (..are reexports from dylibs with
1852fe6060f1SDimitry Andric     // MH_NO_REEXPORTED_DYLIBS loaded for -flat_namespace)?
1853fe6060f1SDimitry Andric     if (config->namespaceKind == NamespaceKind::flat &&
1854fe6060f1SDimitry Andric         cmd->cmd == LC_LOAD_DYLIB) {
1855fe6060f1SDimitry Andric       const auto *c = reinterpret_cast<const dylib_command *>(cmd);
1856fe6060f1SDimitry Andric       StringRef dylibPath =
1857fe6060f1SDimitry Andric           reinterpret_cast<const char *>(c) + read32le(&c->dylib.name);
1858fe6060f1SDimitry Andric       DylibFile *dylib = findDylib(dylibPath, umbrella, nullptr);
1859fe6060f1SDimitry Andric       if (!dylib)
1860fe6060f1SDimitry Andric         error(Twine("unable to locate library '") + dylibPath +
1861fe6060f1SDimitry Andric               "' loaded from '" + toString(this) + "' for -flat_namespace");
1862fe6060f1SDimitry Andric     }
18635ffd83dbSDimitry Andric   }
18645ffd83dbSDimitry Andric }
18655ffd83dbSDimitry Andric 
186681ad6265SDimitry Andric // Some versions of Xcode ship with .tbd files that don't have the right
1867fe6060f1SDimitry Andric // platform settings.
186881ad6265SDimitry Andric constexpr std::array<StringRef, 3> skipPlatformChecks{
1869fe6060f1SDimitry Andric     "/usr/lib/system/libsystem_kernel.dylib",
1870fe6060f1SDimitry Andric     "/usr/lib/system/libsystem_platform.dylib",
1871fe6060f1SDimitry Andric     "/usr/lib/system/libsystem_pthread.dylib"};
1872fe6060f1SDimitry Andric 
187381ad6265SDimitry Andric static bool skipPlatformCheckForCatalyst(const InterfaceFile &interface,
187481ad6265SDimitry Andric                                          bool explicitlyLinked) {
187581ad6265SDimitry Andric   // Catalyst outputs can link against implicitly linked macOS-only libraries.
187681ad6265SDimitry Andric   if (config->platform() != PLATFORM_MACCATALYST || explicitlyLinked)
187781ad6265SDimitry Andric     return false;
187881ad6265SDimitry Andric   return is_contained(interface.targets(),
187981ad6265SDimitry Andric                       MachO::Target(config->arch(), PLATFORM_MACOS));
188081ad6265SDimitry Andric }
188181ad6265SDimitry Andric 
1882fe6060f1SDimitry Andric DylibFile::DylibFile(const InterfaceFile &interface, DylibFile *umbrella,
188381ad6265SDimitry Andric                      bool isBundleLoader, bool explicitlyLinked)
1884fe6060f1SDimitry Andric     : InputFile(DylibKind, interface), refState(RefState::Unreferenced),
188581ad6265SDimitry Andric       explicitlyLinked(explicitlyLinked), isBundleLoader(isBundleLoader) {
1886fe6060f1SDimitry Andric   // FIXME: Add test for the missing TBD code path.
1887fe6060f1SDimitry Andric 
18885ffd83dbSDimitry Andric   if (umbrella == nullptr)
18895ffd83dbSDimitry Andric     umbrella = this;
1890fe6060f1SDimitry Andric   this->umbrella = umbrella;
18915ffd83dbSDimitry Andric 
189204eeddc0SDimitry Andric   installName = saver().save(interface.getInstallName());
1893e8d8bef9SDimitry Andric   compatibilityVersion = interface.getCompatibilityVersion().rawValue();
1894e8d8bef9SDimitry Andric   currentVersion = interface.getCurrentVersion().rawValue();
1895fe6060f1SDimitry Andric 
1896fe6060f1SDimitry Andric   if (config->printEachFile)
1897fe6060f1SDimitry Andric     message(toString(this));
1898fe6060f1SDimitry Andric   inputFiles.insert(this);
1899fe6060f1SDimitry Andric 
1900fe6060f1SDimitry Andric   if (!is_contained(skipPlatformChecks, installName) &&
190181ad6265SDimitry Andric       !is_contained(interface.targets(), config->platformInfo.target) &&
190281ad6265SDimitry Andric       !skipPlatformCheckForCatalyst(interface, explicitlyLinked)) {
1903fe6060f1SDimitry Andric     error(toString(this) + " is incompatible with " +
1904fe6060f1SDimitry Andric           std::string(config->platformInfo.target));
1905fe6060f1SDimitry Andric     return;
1906fe6060f1SDimitry Andric   }
1907fe6060f1SDimitry Andric 
1908fe6060f1SDimitry Andric   checkAppExtensionSafety(interface.isApplicationExtensionSafe());
1909fe6060f1SDimitry Andric 
1910fe6060f1SDimitry Andric   exportingFile = isImplicitlyLinked(installName) ? this : umbrella;
1911e8d8bef9SDimitry Andric   auto addSymbol = [&](const Twine &name) -> void {
191204eeddc0SDimitry Andric     StringRef savedName = saver().save(name);
19130eae32dcSDimitry Andric     if (exportingFile->hiddenSymbols.contains(CachedHashStringRef(savedName)))
19140eae32dcSDimitry Andric       return;
19150eae32dcSDimitry Andric 
19160eae32dcSDimitry Andric     symbols.push_back(symtab->addDylib(savedName, exportingFile,
1917e8d8bef9SDimitry Andric                                        /*isWeakDef=*/false,
1918e8d8bef9SDimitry Andric                                        /*isTlv=*/false));
1919e8d8bef9SDimitry Andric   };
19200eae32dcSDimitry Andric 
19210eae32dcSDimitry Andric   std::vector<const llvm::MachO::Symbol *> normalSymbols;
19220eae32dcSDimitry Andric   normalSymbols.reserve(interface.symbolsCount());
1923fe6060f1SDimitry Andric   for (const auto *symbol : interface.symbols()) {
1924fe6060f1SDimitry Andric     if (!symbol->getArchitectures().has(config->arch()))
1925fe6060f1SDimitry Andric       continue;
1926fe6060f1SDimitry Andric     if (handleLDSymbol(symbol->getName()))
1927e8d8bef9SDimitry Andric       continue;
1928e8d8bef9SDimitry Andric 
1929e8d8bef9SDimitry Andric     switch (symbol->getKind()) {
19300eae32dcSDimitry Andric     case SymbolKind::GlobalSymbol:               // Fallthrough
19310eae32dcSDimitry Andric     case SymbolKind::ObjectiveCClass:            // Fallthrough
19320eae32dcSDimitry Andric     case SymbolKind::ObjectiveCClassEHType:      // Fallthrough
19330eae32dcSDimitry Andric     case SymbolKind::ObjectiveCInstanceVariable: // Fallthrough
19340eae32dcSDimitry Andric       normalSymbols.push_back(symbol);
19350eae32dcSDimitry Andric     }
19360eae32dcSDimitry Andric   }
19370eae32dcSDimitry Andric 
19380eae32dcSDimitry Andric   // TODO(compnerd) filter out symbols based on the target platform
19390eae32dcSDimitry Andric   // TODO: handle weak defs, thread locals
19400eae32dcSDimitry Andric   for (const auto *symbol : normalSymbols) {
19410eae32dcSDimitry Andric     switch (symbol->getKind()) {
1942e8d8bef9SDimitry Andric     case SymbolKind::GlobalSymbol:
1943e8d8bef9SDimitry Andric       addSymbol(symbol->getName());
1944e8d8bef9SDimitry Andric       break;
1945e8d8bef9SDimitry Andric     case SymbolKind::ObjectiveCClass:
1946e8d8bef9SDimitry Andric       // XXX ld64 only creates these symbols when -ObjC is passed in. We may
1947e8d8bef9SDimitry Andric       // want to emulate that.
1948e8d8bef9SDimitry Andric       addSymbol(objc::klass + symbol->getName());
1949e8d8bef9SDimitry Andric       addSymbol(objc::metaclass + symbol->getName());
1950e8d8bef9SDimitry Andric       break;
1951e8d8bef9SDimitry Andric     case SymbolKind::ObjectiveCClassEHType:
1952e8d8bef9SDimitry Andric       addSymbol(objc::ehtype + symbol->getName());
1953e8d8bef9SDimitry Andric       break;
1954e8d8bef9SDimitry Andric     case SymbolKind::ObjectiveCInstanceVariable:
1955e8d8bef9SDimitry Andric       addSymbol(objc::ivar + symbol->getName());
1956e8d8bef9SDimitry Andric       break;
1957e8d8bef9SDimitry Andric     }
19585ffd83dbSDimitry Andric   }
1959e8d8bef9SDimitry Andric }
1960e8d8bef9SDimitry Andric 
1961*61cfbce3SDimitry Andric DylibFile::DylibFile(DylibFile *umbrella)
1962*61cfbce3SDimitry Andric     : InputFile(DylibKind, MemoryBufferRef{}), refState(RefState::Unreferenced),
1963*61cfbce3SDimitry Andric       explicitlyLinked(false), isBundleLoader(false) {
1964*61cfbce3SDimitry Andric   if (umbrella == nullptr)
1965*61cfbce3SDimitry Andric     umbrella = this;
1966*61cfbce3SDimitry Andric   this->umbrella = umbrella;
1967*61cfbce3SDimitry Andric }
1968*61cfbce3SDimitry Andric 
1969fe6060f1SDimitry Andric void DylibFile::parseReexports(const InterfaceFile &interface) {
1970fe6060f1SDimitry Andric   const InterfaceFile *topLevel =
1971fe6060f1SDimitry Andric       interface.getParent() == nullptr ? &interface : interface.getParent();
1972349cc55cSDimitry Andric   for (const InterfaceFileRef &intfRef : interface.reexportedLibraries()) {
1973fe6060f1SDimitry Andric     InterfaceFile::const_target_range targets = intfRef.targets();
1974fe6060f1SDimitry Andric     if (is_contained(skipPlatformChecks, intfRef.getInstallName()) ||
1975fe6060f1SDimitry Andric         is_contained(targets, config->platformInfo.target))
1976fe6060f1SDimitry Andric       loadReexport(intfRef.getInstallName(), exportingFile, topLevel);
1977fe6060f1SDimitry Andric   }
1978fe6060f1SDimitry Andric }
1979e8d8bef9SDimitry Andric 
1980*61cfbce3SDimitry Andric bool DylibFile::isExplicitlyLinked() const {
1981*61cfbce3SDimitry Andric   if (!explicitlyLinked)
1982*61cfbce3SDimitry Andric     return false;
1983*61cfbce3SDimitry Andric 
1984*61cfbce3SDimitry Andric   // If this dylib was explicitly linked, but at least one of the symbols
1985*61cfbce3SDimitry Andric   // of the synthetic dylibs it created via $ld$previous symbols is
1986*61cfbce3SDimitry Andric   // referenced, then that synthetic dylib fulfils the explicit linkedness
1987*61cfbce3SDimitry Andric   // and we can deadstrip this dylib if it's unreferenced.
1988*61cfbce3SDimitry Andric   for (const auto *dylib : extraDylibs)
1989*61cfbce3SDimitry Andric     if (dylib->isReferenced())
1990*61cfbce3SDimitry Andric       return false;
1991*61cfbce3SDimitry Andric 
1992*61cfbce3SDimitry Andric   return true;
1993*61cfbce3SDimitry Andric }
1994*61cfbce3SDimitry Andric 
1995*61cfbce3SDimitry Andric DylibFile *DylibFile::getSyntheticDylib(StringRef installName,
1996*61cfbce3SDimitry Andric                                         uint32_t currentVersion,
1997*61cfbce3SDimitry Andric                                         uint32_t compatVersion) {
1998*61cfbce3SDimitry Andric   for (DylibFile *dylib : extraDylibs)
1999*61cfbce3SDimitry Andric     if (dylib->installName == installName) {
2000*61cfbce3SDimitry Andric       // FIXME: Check what to do if different $ld$previous symbols
2001*61cfbce3SDimitry Andric       // request the same dylib, but with different versions.
2002*61cfbce3SDimitry Andric       return dylib;
2003*61cfbce3SDimitry Andric     }
2004*61cfbce3SDimitry Andric 
2005*61cfbce3SDimitry Andric   auto *dylib = make<DylibFile>(umbrella == this ? nullptr : umbrella);
2006*61cfbce3SDimitry Andric   dylib->installName = saver().save(installName);
2007*61cfbce3SDimitry Andric   dylib->currentVersion = currentVersion;
2008*61cfbce3SDimitry Andric   dylib->compatibilityVersion = compatVersion;
2009*61cfbce3SDimitry Andric   extraDylibs.push_back(dylib);
2010*61cfbce3SDimitry Andric   return dylib;
2011*61cfbce3SDimitry Andric }
2012*61cfbce3SDimitry Andric 
2013fe6060f1SDimitry Andric // $ld$ symbols modify the properties/behavior of the library (e.g. its install
2014fe6060f1SDimitry Andric // name, compatibility version or hide/add symbols) for specific target
2015fe6060f1SDimitry Andric // versions.
2016fe6060f1SDimitry Andric bool DylibFile::handleLDSymbol(StringRef originalName) {
2017fe6060f1SDimitry Andric   if (!originalName.startswith("$ld$"))
2018fe6060f1SDimitry Andric     return false;
2019fe6060f1SDimitry Andric 
2020fe6060f1SDimitry Andric   StringRef action;
2021fe6060f1SDimitry Andric   StringRef name;
2022fe6060f1SDimitry Andric   std::tie(action, name) = originalName.drop_front(strlen("$ld$")).split('$');
2023fe6060f1SDimitry Andric   if (action == "previous")
2024fe6060f1SDimitry Andric     handleLDPreviousSymbol(name, originalName);
2025fe6060f1SDimitry Andric   else if (action == "install_name")
2026fe6060f1SDimitry Andric     handleLDInstallNameSymbol(name, originalName);
20270eae32dcSDimitry Andric   else if (action == "hide")
20280eae32dcSDimitry Andric     handleLDHideSymbol(name, originalName);
2029fe6060f1SDimitry Andric   return true;
2030fe6060f1SDimitry Andric }
2031fe6060f1SDimitry Andric 
2032fe6060f1SDimitry Andric void DylibFile::handleLDPreviousSymbol(StringRef name, StringRef originalName) {
2033fe6060f1SDimitry Andric   // originalName: $ld$ previous $ <installname> $ <compatversion> $
2034fe6060f1SDimitry Andric   // <platformstr> $ <startversion> $ <endversion> $ <symbol-name> $
2035fe6060f1SDimitry Andric   StringRef installName;
2036fe6060f1SDimitry Andric   StringRef compatVersion;
2037fe6060f1SDimitry Andric   StringRef platformStr;
2038fe6060f1SDimitry Andric   StringRef startVersion;
2039fe6060f1SDimitry Andric   StringRef endVersion;
2040fe6060f1SDimitry Andric   StringRef symbolName;
2041fe6060f1SDimitry Andric   StringRef rest;
2042fe6060f1SDimitry Andric 
2043fe6060f1SDimitry Andric   std::tie(installName, name) = name.split('$');
2044fe6060f1SDimitry Andric   std::tie(compatVersion, name) = name.split('$');
2045fe6060f1SDimitry Andric   std::tie(platformStr, name) = name.split('$');
2046fe6060f1SDimitry Andric   std::tie(startVersion, name) = name.split('$');
2047fe6060f1SDimitry Andric   std::tie(endVersion, name) = name.split('$');
2048*61cfbce3SDimitry Andric   std::tie(symbolName, rest) = name.rsplit('$');
2049*61cfbce3SDimitry Andric 
2050*61cfbce3SDimitry Andric   // FIXME: Does this do the right thing for zippered files?
2051fe6060f1SDimitry Andric   unsigned platform;
2052fe6060f1SDimitry Andric   if (platformStr.getAsInteger(10, platform) ||
2053fe6060f1SDimitry Andric       platform != static_cast<unsigned>(config->platform()))
2054fe6060f1SDimitry Andric     return;
2055fe6060f1SDimitry Andric 
2056fe6060f1SDimitry Andric   VersionTuple start;
2057fe6060f1SDimitry Andric   if (start.tryParse(startVersion)) {
2058fe6060f1SDimitry Andric     warn("failed to parse start version, symbol '" + originalName +
2059fe6060f1SDimitry Andric          "' ignored");
2060fe6060f1SDimitry Andric     return;
2061fe6060f1SDimitry Andric   }
2062fe6060f1SDimitry Andric   VersionTuple end;
2063fe6060f1SDimitry Andric   if (end.tryParse(endVersion)) {
2064fe6060f1SDimitry Andric     warn("failed to parse end version, symbol '" + originalName + "' ignored");
2065fe6060f1SDimitry Andric     return;
2066fe6060f1SDimitry Andric   }
2067fe6060f1SDimitry Andric   if (config->platformInfo.minimum < start ||
2068fe6060f1SDimitry Andric       config->platformInfo.minimum >= end)
2069fe6060f1SDimitry Andric     return;
2070fe6060f1SDimitry Andric 
2071*61cfbce3SDimitry Andric   // Initialized to compatibilityVersion for the symbolName branch below.
2072*61cfbce3SDimitry Andric   uint32_t newCompatibilityVersion = compatibilityVersion;
2073*61cfbce3SDimitry Andric   uint32_t newCurrentVersionForSymbol = currentVersion;
2074fe6060f1SDimitry Andric   if (!compatVersion.empty()) {
2075fe6060f1SDimitry Andric     VersionTuple cVersion;
2076fe6060f1SDimitry Andric     if (cVersion.tryParse(compatVersion)) {
2077fe6060f1SDimitry Andric       warn("failed to parse compatibility version, symbol '" + originalName +
2078fe6060f1SDimitry Andric            "' ignored");
2079fe6060f1SDimitry Andric       return;
2080fe6060f1SDimitry Andric     }
2081*61cfbce3SDimitry Andric     newCompatibilityVersion = encodeVersion(cVersion);
2082*61cfbce3SDimitry Andric     newCurrentVersionForSymbol = newCompatibilityVersion;
2083fe6060f1SDimitry Andric   }
2084*61cfbce3SDimitry Andric 
2085*61cfbce3SDimitry Andric   if (!symbolName.empty()) {
2086*61cfbce3SDimitry Andric     // A $ld$previous$ symbol with symbol name adds a symbol with that name to
2087*61cfbce3SDimitry Andric     // a dylib with given name and version.
2088*61cfbce3SDimitry Andric     auto *dylib = getSyntheticDylib(installName, newCurrentVersionForSymbol,
2089*61cfbce3SDimitry Andric                                     newCompatibilityVersion);
2090*61cfbce3SDimitry Andric 
2091*61cfbce3SDimitry Andric     // Just adding the symbol to the symtab works because dylibs contain their
2092*61cfbce3SDimitry Andric     // symbols in alphabetical order, guaranteeing $ld$ symbols to precede
2093*61cfbce3SDimitry Andric     // normal symbols.
2094*61cfbce3SDimitry Andric     dylib->symbols.push_back(symtab->addDylib(
2095*61cfbce3SDimitry Andric         saver().save(symbolName), dylib, /*isWeakDef=*/false, /*isTlv=*/false));
2096*61cfbce3SDimitry Andric     return;
2097*61cfbce3SDimitry Andric   }
2098*61cfbce3SDimitry Andric 
2099*61cfbce3SDimitry Andric   // A $ld$previous$ symbol without symbol name modifies the dylib it's in.
2100*61cfbce3SDimitry Andric   this->installName = saver().save(installName);
2101*61cfbce3SDimitry Andric   this->compatibilityVersion = newCompatibilityVersion;
2102fe6060f1SDimitry Andric }
2103fe6060f1SDimitry Andric 
2104fe6060f1SDimitry Andric void DylibFile::handleLDInstallNameSymbol(StringRef name,
2105fe6060f1SDimitry Andric                                           StringRef originalName) {
2106fe6060f1SDimitry Andric   // originalName: $ld$ install_name $ os<version> $ install_name
2107fe6060f1SDimitry Andric   StringRef condition, installName;
2108fe6060f1SDimitry Andric   std::tie(condition, installName) = name.split('$');
2109fe6060f1SDimitry Andric   VersionTuple version;
2110fe6060f1SDimitry Andric   if (!condition.consume_front("os") || version.tryParse(condition))
2111fe6060f1SDimitry Andric     warn("failed to parse os version, symbol '" + originalName + "' ignored");
2112fe6060f1SDimitry Andric   else if (version == config->platformInfo.minimum)
211304eeddc0SDimitry Andric     this->installName = saver().save(installName);
2114fe6060f1SDimitry Andric }
2115fe6060f1SDimitry Andric 
21160eae32dcSDimitry Andric void DylibFile::handleLDHideSymbol(StringRef name, StringRef originalName) {
21170eae32dcSDimitry Andric   StringRef symbolName;
21180eae32dcSDimitry Andric   bool shouldHide = true;
21190eae32dcSDimitry Andric   if (name.startswith("os")) {
21200eae32dcSDimitry Andric     // If it's hidden based on versions.
21210eae32dcSDimitry Andric     name = name.drop_front(2);
21220eae32dcSDimitry Andric     StringRef minVersion;
21230eae32dcSDimitry Andric     std::tie(minVersion, symbolName) = name.split('$');
21240eae32dcSDimitry Andric     VersionTuple versionTup;
21250eae32dcSDimitry Andric     if (versionTup.tryParse(minVersion)) {
21260eae32dcSDimitry Andric       warn("Failed to parse hidden version, symbol `" + originalName +
21270eae32dcSDimitry Andric            "` ignored.");
21280eae32dcSDimitry Andric       return;
21290eae32dcSDimitry Andric     }
21300eae32dcSDimitry Andric     shouldHide = versionTup == config->platformInfo.minimum;
21310eae32dcSDimitry Andric   } else {
21320eae32dcSDimitry Andric     symbolName = name;
21330eae32dcSDimitry Andric   }
21340eae32dcSDimitry Andric 
21350eae32dcSDimitry Andric   if (shouldHide)
21360eae32dcSDimitry Andric     exportingFile->hiddenSymbols.insert(CachedHashStringRef(symbolName));
21370eae32dcSDimitry Andric }
21380eae32dcSDimitry Andric 
2139fe6060f1SDimitry Andric void DylibFile::checkAppExtensionSafety(bool dylibIsAppExtensionSafe) const {
2140fe6060f1SDimitry Andric   if (config->applicationExtension && !dylibIsAppExtensionSafe)
2141fe6060f1SDimitry Andric     warn("using '-application_extension' with unsafe dylib: " + toString(this));
2142e8d8bef9SDimitry Andric }
2143e8d8bef9SDimitry Andric 
2144972a253aSDimitry Andric ArchiveFile::ArchiveFile(std::unique_ptr<object::Archive> &&f, bool forceHidden)
2145972a253aSDimitry Andric     : InputFile(ArchiveKind, f->getMemoryBufferRef()), file(std::move(f)),
2146972a253aSDimitry Andric       forceHidden(forceHidden) {}
2147349cc55cSDimitry Andric 
2148349cc55cSDimitry Andric void ArchiveFile::addLazySymbols() {
21495ffd83dbSDimitry Andric   for (const object::Archive::Symbol &sym : file->symbols())
215004eeddc0SDimitry Andric     symtab->addLazyArchive(sym.getName(), this, sym);
21515ffd83dbSDimitry Andric }
21525ffd83dbSDimitry Andric 
2153972a253aSDimitry Andric static Expected<InputFile *>
2154972a253aSDimitry Andric loadArchiveMember(MemoryBufferRef mb, uint32_t modTime, StringRef archiveName,
2155972a253aSDimitry Andric                   uint64_t offsetInArchive, bool forceHidden) {
2156349cc55cSDimitry Andric   if (config->zeroModTime)
2157349cc55cSDimitry Andric     modTime = 0;
2158349cc55cSDimitry Andric 
2159349cc55cSDimitry Andric   switch (identify_magic(mb.getBuffer())) {
2160349cc55cSDimitry Andric   case file_magic::macho_object:
2161972a253aSDimitry Andric     return make<ObjFile>(mb, modTime, archiveName, /*lazy=*/false, forceHidden);
2162349cc55cSDimitry Andric   case file_magic::bitcode:
2163972a253aSDimitry Andric     return make<BitcodeFile>(mb, archiveName, offsetInArchive, /*lazy=*/false,
2164972a253aSDimitry Andric                              forceHidden);
2165349cc55cSDimitry Andric   default:
2166349cc55cSDimitry Andric     return createStringError(inconvertibleErrorCode(),
2167349cc55cSDimitry Andric                              mb.getBufferIdentifier() +
2168349cc55cSDimitry Andric                                  " has unhandled file type");
2169349cc55cSDimitry Andric   }
2170349cc55cSDimitry Andric }
2171349cc55cSDimitry Andric 
2172349cc55cSDimitry Andric Error ArchiveFile::fetch(const object::Archive::Child &c, StringRef reason) {
2173349cc55cSDimitry Andric   if (!seen.insert(c.getChildOffset()).second)
2174349cc55cSDimitry Andric     return Error::success();
2175349cc55cSDimitry Andric 
2176349cc55cSDimitry Andric   Expected<MemoryBufferRef> mb = c.getMemoryBufferRef();
2177349cc55cSDimitry Andric   if (!mb)
2178349cc55cSDimitry Andric     return mb.takeError();
2179349cc55cSDimitry Andric 
2180349cc55cSDimitry Andric   // Thin archives refer to .o files, so --reproduce needs the .o files too.
2181349cc55cSDimitry Andric   if (tar && c.getParent()->isThin())
2182349cc55cSDimitry Andric     tar->append(relativeToRoot(CHECK(c.getFullName(), this)), mb->getBuffer());
2183349cc55cSDimitry Andric 
2184349cc55cSDimitry Andric   Expected<TimePoint<std::chrono::seconds>> modTime = c.getLastModified();
2185349cc55cSDimitry Andric   if (!modTime)
2186349cc55cSDimitry Andric     return modTime.takeError();
2187349cc55cSDimitry Andric 
2188972a253aSDimitry Andric   Expected<InputFile *> file = loadArchiveMember(
2189972a253aSDimitry Andric       *mb, toTimeT(*modTime), getName(), c.getChildOffset(), forceHidden);
2190349cc55cSDimitry Andric 
2191349cc55cSDimitry Andric   if (!file)
2192349cc55cSDimitry Andric     return file.takeError();
2193349cc55cSDimitry Andric 
2194349cc55cSDimitry Andric   inputFiles.insert(*file);
2195349cc55cSDimitry Andric   printArchiveMemberLoad(reason, *file);
2196349cc55cSDimitry Andric   return Error::success();
2197349cc55cSDimitry Andric }
2198349cc55cSDimitry Andric 
21995ffd83dbSDimitry Andric void ArchiveFile::fetch(const object::Archive::Symbol &sym) {
22005ffd83dbSDimitry Andric   object::Archive::Child c =
22015ffd83dbSDimitry Andric       CHECK(sym.getMember(), toString(this) +
2202349cc55cSDimitry Andric                                  ": could not get the member defining symbol " +
2203e8d8bef9SDimitry Andric                                  toMachOString(sym));
22045ffd83dbSDimitry Andric 
2205fe6060f1SDimitry Andric   // `sym` is owned by a LazySym, which will be replace<>()d by make<ObjFile>
2206e8d8bef9SDimitry Andric   // and become invalid after that call. Copy it to the stack so we can refer
2207e8d8bef9SDimitry Andric   // to it later.
2208fe6060f1SDimitry Andric   const object::Archive::Symbol symCopy = sym;
2209e8d8bef9SDimitry Andric 
2210fe6060f1SDimitry Andric   // ld64 doesn't demangle sym here even with -demangle.
2211fe6060f1SDimitry Andric   // Match that: intentionally don't call toMachOString().
2212349cc55cSDimitry Andric   if (Error e = fetch(c, symCopy.getName()))
2213349cc55cSDimitry Andric     error(toString(this) + ": could not get the member defining symbol " +
2214349cc55cSDimitry Andric           toMachOString(symCopy) + ": " + toString(std::move(e)));
22155ffd83dbSDimitry Andric }
22165ffd83dbSDimitry Andric 
2217fe6060f1SDimitry Andric static macho::Symbol *createBitcodeSymbol(const lto::InputFile::Symbol &objSym,
2218fe6060f1SDimitry Andric                                           BitcodeFile &file) {
221904eeddc0SDimitry Andric   StringRef name = saver().save(objSym.getName());
2220fe6060f1SDimitry Andric 
2221fe6060f1SDimitry Andric   if (objSym.isUndefined())
22220eae32dcSDimitry Andric     return symtab->addUndefined(name, &file, /*isWeakRef=*/objSym.isWeak());
2223fe6060f1SDimitry Andric 
2224fe6060f1SDimitry Andric   // TODO: Write a test demonstrating why computing isPrivateExtern before
2225fe6060f1SDimitry Andric   // LTO compilation is important.
2226fe6060f1SDimitry Andric   bool isPrivateExtern = false;
2227fe6060f1SDimitry Andric   switch (objSym.getVisibility()) {
2228fe6060f1SDimitry Andric   case GlobalValue::HiddenVisibility:
2229fe6060f1SDimitry Andric     isPrivateExtern = true;
2230fe6060f1SDimitry Andric     break;
2231fe6060f1SDimitry Andric   case GlobalValue::ProtectedVisibility:
2232fe6060f1SDimitry Andric     error(name + " has protected visibility, which is not supported by Mach-O");
2233fe6060f1SDimitry Andric     break;
2234fe6060f1SDimitry Andric   case GlobalValue::DefaultVisibility:
2235fe6060f1SDimitry Andric     break;
2236fe6060f1SDimitry Andric   }
2237972a253aSDimitry Andric   isPrivateExtern = isPrivateExtern || objSym.canBeOmittedFromSymbolTable() ||
2238972a253aSDimitry Andric                     file.forceHidden;
2239fe6060f1SDimitry Andric 
2240349cc55cSDimitry Andric   if (objSym.isCommon())
2241349cc55cSDimitry Andric     return symtab->addCommon(name, &file, objSym.getCommonSize(),
2242349cc55cSDimitry Andric                              objSym.getCommonAlignment(), isPrivateExtern);
2243349cc55cSDimitry Andric 
2244fe6060f1SDimitry Andric   return symtab->addDefined(name, &file, /*isec=*/nullptr, /*value=*/0,
2245fe6060f1SDimitry Andric                             /*size=*/0, objSym.isWeak(), isPrivateExtern,
2246fe6060f1SDimitry Andric                             /*isThumb=*/false,
2247fe6060f1SDimitry Andric                             /*isReferencedDynamically=*/false,
2248349cc55cSDimitry Andric                             /*noDeadStrip=*/false,
2249349cc55cSDimitry Andric                             /*isWeakDefCanBeHidden=*/false);
2250fe6060f1SDimitry Andric }
2251fe6060f1SDimitry Andric 
2252fe6060f1SDimitry Andric BitcodeFile::BitcodeFile(MemoryBufferRef mb, StringRef archiveName,
2253972a253aSDimitry Andric                          uint64_t offsetInArchive, bool lazy, bool forceHidden)
2254972a253aSDimitry Andric     : InputFile(BitcodeKind, mb, lazy), forceHidden(forceHidden) {
22550eae32dcSDimitry Andric   this->archiveName = std::string(archiveName);
2256fe6060f1SDimitry Andric   std::string path = mb.getBufferIdentifier().str();
2257fe6060f1SDimitry Andric   // ThinLTO assumes that all MemoryBufferRefs given to it have a unique
2258fe6060f1SDimitry Andric   // name. If two members with the same name are provided, this causes a
2259fe6060f1SDimitry Andric   // collision and ThinLTO can't proceed.
2260fe6060f1SDimitry Andric   // So, we append the archive name to disambiguate two members with the same
2261fe6060f1SDimitry Andric   // name from multiple different archives, and offset within the archive to
2262fe6060f1SDimitry Andric   // disambiguate two members of the same name from a single archive.
226304eeddc0SDimitry Andric   MemoryBufferRef mbref(mb.getBuffer(),
226404eeddc0SDimitry Andric                         saver().save(archiveName.empty()
226504eeddc0SDimitry Andric                                          ? path
226604eeddc0SDimitry Andric                                          : archiveName +
226704eeddc0SDimitry Andric                                                sys::path::filename(path) +
2268fe6060f1SDimitry Andric                                                utostr(offsetInArchive)));
2269fe6060f1SDimitry Andric 
2270e8d8bef9SDimitry Andric   obj = check(lto::InputFile::create(mbref));
227104eeddc0SDimitry Andric   if (lazy)
227204eeddc0SDimitry Andric     parseLazy();
227304eeddc0SDimitry Andric   else
227404eeddc0SDimitry Andric     parse();
227504eeddc0SDimitry Andric }
2276fe6060f1SDimitry Andric 
227704eeddc0SDimitry Andric void BitcodeFile::parse() {
2278fe6060f1SDimitry Andric   // Convert LTO Symbols to LLD Symbols in order to perform resolution. The
2279fe6060f1SDimitry Andric   // "winning" symbol will then be marked as Prevailing at LTO compilation
2280fe6060f1SDimitry Andric   // time.
228104eeddc0SDimitry Andric   symbols.clear();
2282fe6060f1SDimitry Andric   for (const lto::InputFile::Symbol &objSym : obj->symbols())
2283fe6060f1SDimitry Andric     symbols.push_back(createBitcodeSymbol(objSym, *this));
22845ffd83dbSDimitry Andric }
2285fe6060f1SDimitry Andric 
228604eeddc0SDimitry Andric void BitcodeFile::parseLazy() {
228704eeddc0SDimitry Andric   symbols.resize(obj->symbols().size());
228804eeddc0SDimitry Andric   for (auto it : llvm::enumerate(obj->symbols())) {
228904eeddc0SDimitry Andric     const lto::InputFile::Symbol &objSym = it.value();
229004eeddc0SDimitry Andric     if (!objSym.isUndefined()) {
229104eeddc0SDimitry Andric       symbols[it.index()] =
229204eeddc0SDimitry Andric           symtab->addLazyObject(saver().save(objSym.getName()), *this);
229304eeddc0SDimitry Andric       if (!lazy)
229404eeddc0SDimitry Andric         break;
229504eeddc0SDimitry Andric     }
229604eeddc0SDimitry Andric   }
229704eeddc0SDimitry Andric }
229804eeddc0SDimitry Andric 
229904eeddc0SDimitry Andric void macho::extract(InputFile &file, StringRef reason) {
230004eeddc0SDimitry Andric   assert(file.lazy);
230104eeddc0SDimitry Andric   file.lazy = false;
230204eeddc0SDimitry Andric   printArchiveMemberLoad(reason, &file);
230304eeddc0SDimitry Andric   if (auto *bitcode = dyn_cast<BitcodeFile>(&file)) {
230404eeddc0SDimitry Andric     bitcode->parse();
230504eeddc0SDimitry Andric   } else {
230604eeddc0SDimitry Andric     auto &f = cast<ObjFile>(file);
230704eeddc0SDimitry Andric     if (target->wordSize == 8)
230804eeddc0SDimitry Andric       f.parse<LP64>();
230904eeddc0SDimitry Andric     else
231004eeddc0SDimitry Andric       f.parse<ILP32>();
231104eeddc0SDimitry Andric   }
231204eeddc0SDimitry Andric }
231304eeddc0SDimitry Andric 
2314fe6060f1SDimitry Andric template void ObjFile::parse<LP64>();
2315