xref: /freebsd/contrib/llvm-project/lld/MachO/InputFiles.cpp (revision 0eae32dcef82f6f06de6419a0d623d7def0cc8f6)
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"
485ffd83dbSDimitry Andric #include "ExportTrie.h"
495ffd83dbSDimitry Andric #include "InputSection.h"
505ffd83dbSDimitry Andric #include "MachOStructs.h"
51e8d8bef9SDimitry Andric #include "ObjC.h"
525ffd83dbSDimitry Andric #include "OutputSection.h"
53e8d8bef9SDimitry Andric #include "OutputSegment.h"
545ffd83dbSDimitry Andric #include "SymbolTable.h"
555ffd83dbSDimitry Andric #include "Symbols.h"
56fe6060f1SDimitry Andric #include "SyntheticSections.h"
575ffd83dbSDimitry Andric #include "Target.h"
585ffd83dbSDimitry Andric 
59e8d8bef9SDimitry Andric #include "lld/Common/DWARF.h"
605ffd83dbSDimitry Andric #include "lld/Common/ErrorHandler.h"
615ffd83dbSDimitry Andric #include "lld/Common/Memory.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"
665ffd83dbSDimitry Andric #include "llvm/Support/Endian.h"
675ffd83dbSDimitry Andric #include "llvm/Support/MemoryBuffer.h"
685ffd83dbSDimitry Andric #include "llvm/Support/Path.h"
69e8d8bef9SDimitry Andric #include "llvm/Support/TarWriter.h"
70fe6060f1SDimitry Andric #include "llvm/TextAPI/Architecture.h"
71fe6060f1SDimitry Andric #include "llvm/TextAPI/InterfaceFile.h"
725ffd83dbSDimitry Andric 
73349cc55cSDimitry Andric #include <type_traits>
74349cc55cSDimitry Andric 
755ffd83dbSDimitry Andric using namespace llvm;
765ffd83dbSDimitry Andric using namespace llvm::MachO;
775ffd83dbSDimitry Andric using namespace llvm::support::endian;
785ffd83dbSDimitry Andric using namespace llvm::sys;
795ffd83dbSDimitry Andric using namespace lld;
805ffd83dbSDimitry Andric using namespace lld::macho;
815ffd83dbSDimitry Andric 
82e8d8bef9SDimitry Andric // Returns "<internal>", "foo.a(bar.o)", or "baz.o".
83e8d8bef9SDimitry Andric std::string lld::toString(const InputFile *f) {
84e8d8bef9SDimitry Andric   if (!f)
85e8d8bef9SDimitry Andric     return "<internal>";
86fe6060f1SDimitry Andric 
87fe6060f1SDimitry Andric   // Multiple dylibs can be defined in one .tbd file.
88fe6060f1SDimitry Andric   if (auto dylibFile = dyn_cast<DylibFile>(f))
89fe6060f1SDimitry Andric     if (f->getName().endswith(".tbd"))
90fe6060f1SDimitry Andric       return (f->getName() + "(" + dylibFile->installName + ")").str();
91fe6060f1SDimitry Andric 
92e8d8bef9SDimitry Andric   if (f->archiveName.empty())
93e8d8bef9SDimitry Andric     return std::string(f->getName());
94fe6060f1SDimitry Andric   return (f->archiveName + "(" + path::filename(f->getName()) + ")").str();
95e8d8bef9SDimitry Andric }
96e8d8bef9SDimitry Andric 
97e8d8bef9SDimitry Andric SetVector<InputFile *> macho::inputFiles;
98e8d8bef9SDimitry Andric std::unique_ptr<TarWriter> macho::tar;
99e8d8bef9SDimitry Andric int InputFile::idCount = 0;
1005ffd83dbSDimitry Andric 
101fe6060f1SDimitry Andric static VersionTuple decodeVersion(uint32_t version) {
102fe6060f1SDimitry Andric   unsigned major = version >> 16;
103fe6060f1SDimitry Andric   unsigned minor = (version >> 8) & 0xffu;
104fe6060f1SDimitry Andric   unsigned subMinor = version & 0xffu;
105fe6060f1SDimitry Andric   return VersionTuple(major, minor, subMinor);
106fe6060f1SDimitry Andric }
107fe6060f1SDimitry Andric 
108fe6060f1SDimitry Andric static std::vector<PlatformInfo> getPlatformInfos(const InputFile *input) {
109fe6060f1SDimitry Andric   if (!isa<ObjFile>(input) && !isa<DylibFile>(input))
110fe6060f1SDimitry Andric     return {};
111fe6060f1SDimitry Andric 
112fe6060f1SDimitry Andric   const char *hdr = input->mb.getBufferStart();
113fe6060f1SDimitry Andric 
114fe6060f1SDimitry Andric   std::vector<PlatformInfo> platformInfos;
115fe6060f1SDimitry Andric   for (auto *cmd : findCommands<build_version_command>(hdr, LC_BUILD_VERSION)) {
116fe6060f1SDimitry Andric     PlatformInfo info;
117fe6060f1SDimitry Andric     info.target.Platform = static_cast<PlatformKind>(cmd->platform);
118fe6060f1SDimitry Andric     info.minimum = decodeVersion(cmd->minos);
119fe6060f1SDimitry Andric     platformInfos.emplace_back(std::move(info));
120fe6060f1SDimitry Andric   }
121fe6060f1SDimitry Andric   for (auto *cmd : findCommands<version_min_command>(
122fe6060f1SDimitry Andric            hdr, LC_VERSION_MIN_MACOSX, LC_VERSION_MIN_IPHONEOS,
123fe6060f1SDimitry Andric            LC_VERSION_MIN_TVOS, LC_VERSION_MIN_WATCHOS)) {
124fe6060f1SDimitry Andric     PlatformInfo info;
125fe6060f1SDimitry Andric     switch (cmd->cmd) {
126fe6060f1SDimitry Andric     case LC_VERSION_MIN_MACOSX:
127fe6060f1SDimitry Andric       info.target.Platform = PlatformKind::macOS;
128fe6060f1SDimitry Andric       break;
129fe6060f1SDimitry Andric     case LC_VERSION_MIN_IPHONEOS:
130fe6060f1SDimitry Andric       info.target.Platform = PlatformKind::iOS;
131fe6060f1SDimitry Andric       break;
132fe6060f1SDimitry Andric     case LC_VERSION_MIN_TVOS:
133fe6060f1SDimitry Andric       info.target.Platform = PlatformKind::tvOS;
134fe6060f1SDimitry Andric       break;
135fe6060f1SDimitry Andric     case LC_VERSION_MIN_WATCHOS:
136fe6060f1SDimitry Andric       info.target.Platform = PlatformKind::watchOS;
137fe6060f1SDimitry Andric       break;
138fe6060f1SDimitry Andric     }
139fe6060f1SDimitry Andric     info.minimum = decodeVersion(cmd->version);
140fe6060f1SDimitry Andric     platformInfos.emplace_back(std::move(info));
141fe6060f1SDimitry Andric   }
142fe6060f1SDimitry Andric 
143fe6060f1SDimitry Andric   return platformInfos;
144fe6060f1SDimitry Andric }
145fe6060f1SDimitry Andric 
146fe6060f1SDimitry Andric static bool checkCompatibility(const InputFile *input) {
147fe6060f1SDimitry Andric   std::vector<PlatformInfo> platformInfos = getPlatformInfos(input);
148fe6060f1SDimitry Andric   if (platformInfos.empty())
149fe6060f1SDimitry Andric     return true;
150fe6060f1SDimitry Andric 
151fe6060f1SDimitry Andric   auto it = find_if(platformInfos, [&](const PlatformInfo &info) {
152fe6060f1SDimitry Andric     return removeSimulator(info.target.Platform) ==
153fe6060f1SDimitry Andric            removeSimulator(config->platform());
154fe6060f1SDimitry Andric   });
155fe6060f1SDimitry Andric   if (it == platformInfos.end()) {
156fe6060f1SDimitry Andric     std::string platformNames;
157fe6060f1SDimitry Andric     raw_string_ostream os(platformNames);
158fe6060f1SDimitry Andric     interleave(
159fe6060f1SDimitry Andric         platformInfos, os,
160fe6060f1SDimitry Andric         [&](const PlatformInfo &info) {
161fe6060f1SDimitry Andric           os << getPlatformName(info.target.Platform);
162fe6060f1SDimitry Andric         },
163fe6060f1SDimitry Andric         "/");
164fe6060f1SDimitry Andric     error(toString(input) + " has platform " + platformNames +
165fe6060f1SDimitry Andric           Twine(", which is different from target platform ") +
166fe6060f1SDimitry Andric           getPlatformName(config->platform()));
167fe6060f1SDimitry Andric     return false;
168fe6060f1SDimitry Andric   }
169fe6060f1SDimitry Andric 
170fe6060f1SDimitry Andric   if (it->minimum > config->platformInfo.minimum)
171fe6060f1SDimitry Andric     warn(toString(input) + " has version " + it->minimum.getAsString() +
172fe6060f1SDimitry Andric          ", which is newer than target minimum of " +
173fe6060f1SDimitry Andric          config->platformInfo.minimum.getAsString());
174fe6060f1SDimitry Andric 
175fe6060f1SDimitry Andric   return true;
176fe6060f1SDimitry Andric }
177fe6060f1SDimitry Andric 
178349cc55cSDimitry Andric // This cache mostly exists to store system libraries (and .tbds) as they're
179349cc55cSDimitry Andric // loaded, rather than the input archives, which are already cached at a higher
180349cc55cSDimitry Andric // level, and other files like the filelist that are only read once.
181349cc55cSDimitry Andric // Theoretically this caching could be more efficient by hoisting it, but that
182349cc55cSDimitry Andric // would require altering many callers to track the state.
183349cc55cSDimitry Andric DenseMap<CachedHashStringRef, MemoryBufferRef> macho::cachedReads;
1845ffd83dbSDimitry Andric // Open a given file path and return it as a memory-mapped file.
1855ffd83dbSDimitry Andric Optional<MemoryBufferRef> macho::readFile(StringRef path) {
186349cc55cSDimitry Andric   CachedHashStringRef key(path);
187349cc55cSDimitry Andric   auto entry = cachedReads.find(key);
188349cc55cSDimitry Andric   if (entry != cachedReads.end())
189349cc55cSDimitry Andric     return entry->second;
190349cc55cSDimitry Andric 
191fe6060f1SDimitry Andric   ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr = MemoryBuffer::getFile(path);
192fe6060f1SDimitry Andric   if (std::error_code ec = mbOrErr.getError()) {
1935ffd83dbSDimitry Andric     error("cannot open " + path + ": " + ec.message());
1945ffd83dbSDimitry Andric     return None;
1955ffd83dbSDimitry Andric   }
1965ffd83dbSDimitry Andric 
1975ffd83dbSDimitry Andric   std::unique_ptr<MemoryBuffer> &mb = *mbOrErr;
1985ffd83dbSDimitry Andric   MemoryBufferRef mbref = mb->getMemBufferRef();
1995ffd83dbSDimitry Andric   make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take mb ownership
2005ffd83dbSDimitry Andric 
2015ffd83dbSDimitry Andric   // If this is a regular non-fat file, return it.
2025ffd83dbSDimitry Andric   const char *buf = mbref.getBufferStart();
203fe6060f1SDimitry Andric   const auto *hdr = reinterpret_cast<const fat_header *>(buf);
204fe6060f1SDimitry Andric   if (mbref.getBufferSize() < sizeof(uint32_t) ||
205fe6060f1SDimitry Andric       read32be(&hdr->magic) != FAT_MAGIC) {
206e8d8bef9SDimitry Andric     if (tar)
207e8d8bef9SDimitry Andric       tar->append(relativeToRoot(path), mbref.getBuffer());
208349cc55cSDimitry Andric     return cachedReads[key] = mbref;
209e8d8bef9SDimitry Andric   }
2105ffd83dbSDimitry Andric 
211fe6060f1SDimitry Andric   // Object files and archive files may be fat files, which contain multiple
212fe6060f1SDimitry Andric   // real files for different CPU ISAs. Here, we search for a file that matches
213fe6060f1SDimitry Andric   // with the current link target and returns it as a MemoryBufferRef.
214fe6060f1SDimitry Andric   const auto *arch = reinterpret_cast<const fat_arch *>(buf + sizeof(*hdr));
2155ffd83dbSDimitry Andric 
2165ffd83dbSDimitry Andric   for (uint32_t i = 0, n = read32be(&hdr->nfat_arch); i < n; ++i) {
2175ffd83dbSDimitry Andric     if (reinterpret_cast<const char *>(arch + i + 1) >
2185ffd83dbSDimitry Andric         buf + mbref.getBufferSize()) {
2195ffd83dbSDimitry Andric       error(path + ": fat_arch struct extends beyond end of file");
2205ffd83dbSDimitry Andric       return None;
2215ffd83dbSDimitry Andric     }
2225ffd83dbSDimitry Andric 
223fe6060f1SDimitry Andric     if (read32be(&arch[i].cputype) != static_cast<uint32_t>(target->cpuType) ||
2245ffd83dbSDimitry Andric         read32be(&arch[i].cpusubtype) != target->cpuSubtype)
2255ffd83dbSDimitry Andric       continue;
2265ffd83dbSDimitry Andric 
2275ffd83dbSDimitry Andric     uint32_t offset = read32be(&arch[i].offset);
2285ffd83dbSDimitry Andric     uint32_t size = read32be(&arch[i].size);
2295ffd83dbSDimitry Andric     if (offset + size > mbref.getBufferSize())
2305ffd83dbSDimitry Andric       error(path + ": slice extends beyond end of file");
231e8d8bef9SDimitry Andric     if (tar)
232e8d8bef9SDimitry Andric       tar->append(relativeToRoot(path), mbref.getBuffer());
233349cc55cSDimitry Andric     return cachedReads[key] = MemoryBufferRef(StringRef(buf + offset, size),
234349cc55cSDimitry Andric                                               path.copy(bAlloc));
2355ffd83dbSDimitry Andric   }
2365ffd83dbSDimitry Andric 
2375ffd83dbSDimitry Andric   error("unable to find matching architecture in " + path);
2385ffd83dbSDimitry Andric   return None;
2395ffd83dbSDimitry Andric }
2405ffd83dbSDimitry Andric 
241fe6060f1SDimitry Andric InputFile::InputFile(Kind kind, const InterfaceFile &interface)
242fe6060f1SDimitry Andric     : id(idCount++), fileKind(kind), name(saver.save(interface.getPath())) {}
2435ffd83dbSDimitry Andric 
244349cc55cSDimitry Andric // Some sections comprise of fixed-size records, so instead of splitting them at
245349cc55cSDimitry Andric // symbol boundaries, we split them based on size. Records are distinct from
246349cc55cSDimitry Andric // literals in that they may contain references to other sections, instead of
247349cc55cSDimitry Andric // being leaf nodes in the InputSection graph.
248349cc55cSDimitry Andric //
249349cc55cSDimitry Andric // Note that "record" is a term I came up with. In contrast, "literal" is a term
250349cc55cSDimitry Andric // used by the Mach-O format.
251349cc55cSDimitry Andric static Optional<size_t> getRecordSize(StringRef segname, StringRef name) {
252349cc55cSDimitry Andric   if (name == section_names::cfString) {
253349cc55cSDimitry Andric     if (config->icfLevel != ICFLevel::none && segname == segment_names::data)
254349cc55cSDimitry Andric       return target->wordSize == 8 ? 32 : 16;
255349cc55cSDimitry Andric   } else if (name == section_names::compactUnwind) {
256349cc55cSDimitry Andric     if (segname == segment_names::ld)
257349cc55cSDimitry Andric       return target->wordSize == 8 ? 32 : 20;
258349cc55cSDimitry Andric   }
259349cc55cSDimitry Andric   return {};
260349cc55cSDimitry Andric }
261349cc55cSDimitry Andric 
262349cc55cSDimitry Andric // Parse the sequence of sections within a single LC_SEGMENT(_64).
263349cc55cSDimitry Andric // Split each section into subsections.
264349cc55cSDimitry Andric template <class SectionHeader>
265349cc55cSDimitry Andric void ObjFile::parseSections(ArrayRef<SectionHeader> sectionHeaders) {
266349cc55cSDimitry Andric   sections.reserve(sectionHeaders.size());
2675ffd83dbSDimitry Andric   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
2685ffd83dbSDimitry Andric 
269349cc55cSDimitry Andric   for (const SectionHeader &sec : sectionHeaders) {
270fe6060f1SDimitry Andric     StringRef name =
271e8d8bef9SDimitry Andric         StringRef(sec.sectname, strnlen(sec.sectname, sizeof(sec.sectname)));
272fe6060f1SDimitry Andric     StringRef segname =
273e8d8bef9SDimitry Andric         StringRef(sec.segname, strnlen(sec.segname, sizeof(sec.segname)));
274fe6060f1SDimitry Andric     ArrayRef<uint8_t> data = {isZeroFill(sec.flags) ? nullptr
275fe6060f1SDimitry Andric                                                     : buf + sec.offset,
2765ffd83dbSDimitry Andric                               static_cast<size_t>(sec.size)};
277fe6060f1SDimitry Andric     if (sec.align >= 32) {
278fe6060f1SDimitry Andric       error("alignment " + std::to_string(sec.align) + " of section " + name +
279fe6060f1SDimitry Andric             " is too large");
280349cc55cSDimitry Andric       sections.push_back(sec.addr);
281fe6060f1SDimitry Andric       continue;
282fe6060f1SDimitry Andric     }
283fe6060f1SDimitry Andric     uint32_t align = 1 << sec.align;
284fe6060f1SDimitry Andric     uint32_t flags = sec.flags;
285e8d8bef9SDimitry Andric 
286349cc55cSDimitry Andric     auto splitRecords = [&](int recordSize) -> void {
287349cc55cSDimitry Andric       sections.push_back(sec.addr);
288349cc55cSDimitry Andric       if (data.empty())
289349cc55cSDimitry Andric         return;
290349cc55cSDimitry Andric       Subsections &subsections = sections.back().subsections;
291349cc55cSDimitry Andric       subsections.reserve(data.size() / recordSize);
292349cc55cSDimitry Andric       auto *isec = make<ConcatInputSection>(
293349cc55cSDimitry Andric           segname, name, this, data.slice(0, recordSize), align, flags);
294349cc55cSDimitry Andric       subsections.push_back({0, isec});
295349cc55cSDimitry Andric       for (uint64_t off = recordSize; off < data.size(); off += recordSize) {
296349cc55cSDimitry Andric         // Copying requires less memory than constructing a fresh InputSection.
297349cc55cSDimitry Andric         auto *copy = make<ConcatInputSection>(*isec);
298349cc55cSDimitry Andric         copy->data = data.slice(off, recordSize);
299349cc55cSDimitry Andric         subsections.push_back({off, copy});
300349cc55cSDimitry Andric       }
301349cc55cSDimitry Andric     };
302349cc55cSDimitry Andric 
303fe6060f1SDimitry Andric     if (sectionType(sec.flags) == S_CSTRING_LITERALS ||
304fe6060f1SDimitry Andric         (config->dedupLiterals && isWordLiteralSection(sec.flags))) {
305fe6060f1SDimitry Andric       if (sec.nreloc && config->dedupLiterals)
306fe6060f1SDimitry Andric         fatal(toString(this) + " contains relocations in " + sec.segname + "," +
307fe6060f1SDimitry Andric               sec.sectname +
308fe6060f1SDimitry Andric               ", so LLD cannot deduplicate literals. Try re-running without "
309fe6060f1SDimitry Andric               "--deduplicate-literals.");
310fe6060f1SDimitry Andric 
311fe6060f1SDimitry Andric       InputSection *isec;
312fe6060f1SDimitry Andric       if (sectionType(sec.flags) == S_CSTRING_LITERALS) {
313fe6060f1SDimitry Andric         isec =
314fe6060f1SDimitry Andric             make<CStringInputSection>(segname, name, this, data, align, flags);
315fe6060f1SDimitry Andric         // FIXME: parallelize this?
316fe6060f1SDimitry Andric         cast<CStringInputSection>(isec)->splitIntoPieces();
317fe6060f1SDimitry Andric       } else {
318fe6060f1SDimitry Andric         isec = make<WordLiteralInputSection>(segname, name, this, data, align,
319fe6060f1SDimitry Andric                                              flags);
320fe6060f1SDimitry Andric       }
321349cc55cSDimitry Andric       sections.push_back(sec.addr);
322349cc55cSDimitry Andric       sections.back().subsections.push_back({0, isec});
323349cc55cSDimitry Andric     } else if (auto recordSize = getRecordSize(segname, name)) {
324349cc55cSDimitry Andric       splitRecords(*recordSize);
325349cc55cSDimitry Andric       if (name == section_names::compactUnwind)
326349cc55cSDimitry Andric         compactUnwindSection = &sections.back();
327349cc55cSDimitry Andric     } else if (segname == segment_names::llvm) {
328349cc55cSDimitry Andric       // ld64 does not appear to emit contents from sections within the __LLVM
329349cc55cSDimitry Andric       // segment. Symbols within those sections point to bitcode metadata
330349cc55cSDimitry Andric       // instead of actual symbols. Global symbols within those sections could
331349cc55cSDimitry Andric       // have the same name without causing duplicate symbol errors. Push an
332349cc55cSDimitry Andric       // empty entry to ensure indices line up for the remaining sections.
333349cc55cSDimitry Andric       // TODO: Evaluate whether the bitcode metadata is needed.
334349cc55cSDimitry Andric       sections.push_back(sec.addr);
335fe6060f1SDimitry Andric     } else {
336fe6060f1SDimitry Andric       auto *isec =
337fe6060f1SDimitry Andric           make<ConcatInputSection>(segname, name, this, data, align, flags);
338349cc55cSDimitry Andric       if (isDebugSection(isec->getFlags()) &&
339349cc55cSDimitry Andric           isec->getSegName() == segment_names::dwarf) {
340e8d8bef9SDimitry Andric         // Instead of emitting DWARF sections, we emit STABS symbols to the
341e8d8bef9SDimitry Andric         // object files that contain them. We filter them out early to avoid
342e8d8bef9SDimitry Andric         // parsing their relocations unnecessarily. But we must still push an
343349cc55cSDimitry Andric         // empty entry to ensure the indices line up for the remaining sections.
344349cc55cSDimitry Andric         sections.push_back(sec.addr);
345e8d8bef9SDimitry Andric         debugSections.push_back(isec);
346349cc55cSDimitry Andric       } else {
347349cc55cSDimitry Andric         sections.push_back(sec.addr);
348349cc55cSDimitry Andric         sections.back().subsections.push_back({0, isec});
349e8d8bef9SDimitry Andric       }
3505ffd83dbSDimitry Andric     }
3515ffd83dbSDimitry Andric   }
352fe6060f1SDimitry Andric }
3535ffd83dbSDimitry Andric 
3545ffd83dbSDimitry Andric // Find the subsection corresponding to the greatest section offset that is <=
3555ffd83dbSDimitry Andric // that of the given offset.
3565ffd83dbSDimitry Andric //
3575ffd83dbSDimitry Andric // offset: an offset relative to the start of the original InputSection (before
3585ffd83dbSDimitry Andric // any subsection splitting has occurred). It will be updated to represent the
3595ffd83dbSDimitry Andric // same location as an offset relative to the start of the containing
3605ffd83dbSDimitry Andric // subsection.
361349cc55cSDimitry Andric template <class T>
362349cc55cSDimitry Andric static InputSection *findContainingSubsection(const Subsections &subsections,
363349cc55cSDimitry Andric                                               T *offset) {
364349cc55cSDimitry Andric   static_assert(std::is_same<uint64_t, T>::value ||
365349cc55cSDimitry Andric                     std::is_same<uint32_t, T>::value,
366349cc55cSDimitry Andric                 "unexpected type for offset");
367fe6060f1SDimitry Andric   auto it = std::prev(llvm::upper_bound(
368349cc55cSDimitry Andric       subsections, *offset,
369349cc55cSDimitry Andric       [](uint64_t value, Subsection subsec) { return value < subsec.offset; }));
370fe6060f1SDimitry Andric   *offset -= it->offset;
371fe6060f1SDimitry Andric   return it->isec;
3725ffd83dbSDimitry Andric }
3735ffd83dbSDimitry Andric 
374349cc55cSDimitry Andric template <class SectionHeader>
375349cc55cSDimitry Andric static bool validateRelocationInfo(InputFile *file, const SectionHeader &sec,
376fe6060f1SDimitry Andric                                    relocation_info rel) {
377fe6060f1SDimitry Andric   const RelocAttrs &relocAttrs = target->getRelocAttrs(rel.r_type);
378fe6060f1SDimitry Andric   bool valid = true;
379fe6060f1SDimitry Andric   auto message = [relocAttrs, file, sec, rel, &valid](const Twine &diagnostic) {
380fe6060f1SDimitry Andric     valid = false;
381fe6060f1SDimitry Andric     return (relocAttrs.name + " relocation " + diagnostic + " at offset " +
382fe6060f1SDimitry Andric             std::to_string(rel.r_address) + " of " + sec.segname + "," +
383fe6060f1SDimitry Andric             sec.sectname + " in " + toString(file))
384fe6060f1SDimitry Andric         .str();
385fe6060f1SDimitry Andric   };
386fe6060f1SDimitry Andric 
387fe6060f1SDimitry Andric   if (!relocAttrs.hasAttr(RelocAttrBits::LOCAL) && !rel.r_extern)
388fe6060f1SDimitry Andric     error(message("must be extern"));
389fe6060f1SDimitry Andric   if (relocAttrs.hasAttr(RelocAttrBits::PCREL) != rel.r_pcrel)
390fe6060f1SDimitry Andric     error(message(Twine("must ") + (rel.r_pcrel ? "not " : "") +
391fe6060f1SDimitry Andric                   "be PC-relative"));
392fe6060f1SDimitry Andric   if (isThreadLocalVariables(sec.flags) &&
393fe6060f1SDimitry Andric       !relocAttrs.hasAttr(RelocAttrBits::UNSIGNED))
394fe6060f1SDimitry Andric     error(message("not allowed in thread-local section, must be UNSIGNED"));
395fe6060f1SDimitry Andric   if (rel.r_length < 2 || rel.r_length > 3 ||
396fe6060f1SDimitry Andric       !relocAttrs.hasAttr(static_cast<RelocAttrBits>(1 << rel.r_length))) {
397fe6060f1SDimitry Andric     static SmallVector<StringRef, 4> widths{"0", "4", "8", "4 or 8"};
398fe6060f1SDimitry Andric     error(message("has width " + std::to_string(1 << rel.r_length) +
399fe6060f1SDimitry Andric                   " bytes, but must be " +
400fe6060f1SDimitry Andric                   widths[(static_cast<int>(relocAttrs.bits) >> 2) & 3] +
401fe6060f1SDimitry Andric                   " bytes"));
402fe6060f1SDimitry Andric   }
403fe6060f1SDimitry Andric   return valid;
404fe6060f1SDimitry Andric }
405fe6060f1SDimitry Andric 
406349cc55cSDimitry Andric template <class SectionHeader>
407349cc55cSDimitry Andric void ObjFile::parseRelocations(ArrayRef<SectionHeader> sectionHeaders,
408349cc55cSDimitry Andric                                const SectionHeader &sec,
409349cc55cSDimitry Andric                                Subsections &subsections) {
4105ffd83dbSDimitry Andric   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
411e8d8bef9SDimitry Andric   ArrayRef<relocation_info> relInfos(
412e8d8bef9SDimitry Andric       reinterpret_cast<const relocation_info *>(buf + sec.reloff), sec.nreloc);
4135ffd83dbSDimitry Andric 
414349cc55cSDimitry Andric   auto subsecIt = subsections.rbegin();
415e8d8bef9SDimitry Andric   for (size_t i = 0; i < relInfos.size(); i++) {
416e8d8bef9SDimitry Andric     // Paired relocations serve as Mach-O's method for attaching a
417e8d8bef9SDimitry Andric     // supplemental datum to a primary relocation record. ELF does not
418e8d8bef9SDimitry Andric     // need them because the *_RELOC_RELA records contain the extra
419e8d8bef9SDimitry Andric     // addend field, vs. *_RELOC_REL which omit the addend.
420e8d8bef9SDimitry Andric     //
421e8d8bef9SDimitry Andric     // The {X86_64,ARM64}_RELOC_SUBTRACTOR record holds the subtrahend,
422e8d8bef9SDimitry Andric     // and the paired *_RELOC_UNSIGNED record holds the minuend. The
423fe6060f1SDimitry Andric     // datum for each is a symbolic address. The result is the offset
424fe6060f1SDimitry Andric     // between two addresses.
425e8d8bef9SDimitry Andric     //
426e8d8bef9SDimitry Andric     // The ARM64_RELOC_ADDEND record holds the addend, and the paired
427e8d8bef9SDimitry Andric     // ARM64_RELOC_BRANCH26 or ARM64_RELOC_PAGE21/PAGEOFF12 holds the
428e8d8bef9SDimitry Andric     // base symbolic address.
429e8d8bef9SDimitry Andric     //
430e8d8bef9SDimitry Andric     // Note: X86 does not use *_RELOC_ADDEND because it can embed an
431e8d8bef9SDimitry Andric     // addend into the instruction stream. On X86, a relocatable address
432e8d8bef9SDimitry Andric     // field always occupies an entire contiguous sequence of byte(s),
433e8d8bef9SDimitry Andric     // so there is no need to merge opcode bits with address
434e8d8bef9SDimitry Andric     // bits. Therefore, it's easy and convenient to store addends in the
435e8d8bef9SDimitry Andric     // instruction-stream bytes that would otherwise contain zeroes. By
436e8d8bef9SDimitry Andric     // contrast, RISC ISAs such as ARM64 mix opcode bits with with
437e8d8bef9SDimitry Andric     // address bits so that bitwise arithmetic is necessary to extract
438e8d8bef9SDimitry Andric     // and insert them. Storing addends in the instruction stream is
439e8d8bef9SDimitry Andric     // possible, but inconvenient and more costly at link time.
440e8d8bef9SDimitry Andric 
441fe6060f1SDimitry Andric     relocation_info relInfo = relInfos[i];
442349cc55cSDimitry Andric     bool isSubtrahend =
443349cc55cSDimitry Andric         target->hasAttr(relInfo.r_type, RelocAttrBits::SUBTRAHEND);
444349cc55cSDimitry Andric     if (isSubtrahend && StringRef(sec.sectname) == section_names::ehFrame) {
445349cc55cSDimitry Andric       // __TEXT,__eh_frame only has symbols and SUBTRACTOR relocs when ld64 -r
446349cc55cSDimitry Andric       // adds local "EH_Frame1" and "func.eh". Ignore them because they have
447349cc55cSDimitry Andric       // gone unused by Mac OS since Snow Leopard (10.6), vintage 2009.
448349cc55cSDimitry Andric       ++i;
449349cc55cSDimitry Andric       continue;
450349cc55cSDimitry Andric     }
451349cc55cSDimitry Andric     int64_t pairedAddend = 0;
452fe6060f1SDimitry Andric     if (target->hasAttr(relInfo.r_type, RelocAttrBits::ADDEND)) {
453fe6060f1SDimitry Andric       pairedAddend = SignExtend64<24>(relInfo.r_symbolnum);
454fe6060f1SDimitry Andric       relInfo = relInfos[++i];
455fe6060f1SDimitry Andric     }
456e8d8bef9SDimitry Andric     assert(i < relInfos.size());
457fe6060f1SDimitry Andric     if (!validateRelocationInfo(this, sec, relInfo))
458fe6060f1SDimitry Andric       continue;
459e8d8bef9SDimitry Andric     if (relInfo.r_address & R_SCATTERED)
4605ffd83dbSDimitry Andric       fatal("TODO: Scattered relocations not supported");
4615ffd83dbSDimitry Andric 
462fe6060f1SDimitry Andric     int64_t embeddedAddend = target->getEmbeddedAddend(mb, sec.offset, relInfo);
463fe6060f1SDimitry Andric     assert(!(embeddedAddend && pairedAddend));
464fe6060f1SDimitry Andric     int64_t totalAddend = pairedAddend + embeddedAddend;
4655ffd83dbSDimitry Andric     Reloc r;
466e8d8bef9SDimitry Andric     r.type = relInfo.r_type;
467e8d8bef9SDimitry Andric     r.pcrel = relInfo.r_pcrel;
468e8d8bef9SDimitry Andric     r.length = relInfo.r_length;
469e8d8bef9SDimitry Andric     r.offset = relInfo.r_address;
470e8d8bef9SDimitry Andric     if (relInfo.r_extern) {
471e8d8bef9SDimitry Andric       r.referent = symbols[relInfo.r_symbolnum];
472fe6060f1SDimitry Andric       r.addend = isSubtrahend ? 0 : totalAddend;
4735ffd83dbSDimitry Andric     } else {
474fe6060f1SDimitry Andric       assert(!isSubtrahend);
475349cc55cSDimitry Andric       const SectionHeader &referentSecHead =
476349cc55cSDimitry Andric           sectionHeaders[relInfo.r_symbolnum - 1];
477fe6060f1SDimitry Andric       uint64_t referentOffset;
478e8d8bef9SDimitry Andric       if (relInfo.r_pcrel) {
4795ffd83dbSDimitry Andric         // The implicit addend for pcrel section relocations is the pcrel offset
4805ffd83dbSDimitry Andric         // in terms of the addresses in the input file. Here we adjust it so
481e8d8bef9SDimitry Andric         // that it describes the offset from the start of the referent section.
482fe6060f1SDimitry Andric         // FIXME This logic was written around x86_64 behavior -- ARM64 doesn't
483fe6060f1SDimitry Andric         // have pcrel section relocations. We may want to factor this out into
484fe6060f1SDimitry Andric         // the arch-specific .cpp file.
485fe6060f1SDimitry Andric         assert(target->hasAttr(r.type, RelocAttrBits::BYTE4));
486349cc55cSDimitry Andric         referentOffset = sec.addr + relInfo.r_address + 4 + totalAddend -
487349cc55cSDimitry Andric                          referentSecHead.addr;
4885ffd83dbSDimitry Andric       } else {
4895ffd83dbSDimitry Andric         // The addend for a non-pcrel relocation is its absolute address.
490349cc55cSDimitry Andric         referentOffset = totalAddend - referentSecHead.addr;
4915ffd83dbSDimitry Andric       }
492349cc55cSDimitry Andric       Subsections &referentSubsections =
493349cc55cSDimitry Andric           sections[relInfo.r_symbolnum - 1].subsections;
494349cc55cSDimitry Andric       r.referent =
495349cc55cSDimitry Andric           findContainingSubsection(referentSubsections, &referentOffset);
496e8d8bef9SDimitry Andric       r.addend = referentOffset;
4975ffd83dbSDimitry Andric     }
4985ffd83dbSDimitry Andric 
499fe6060f1SDimitry Andric     // Find the subsection that this relocation belongs to.
500fe6060f1SDimitry Andric     // Though not required by the Mach-O format, clang and gcc seem to emit
501fe6060f1SDimitry Andric     // relocations in order, so let's take advantage of it. However, ld64 emits
502fe6060f1SDimitry Andric     // unsorted relocations (in `-r` mode), so we have a fallback for that
503fe6060f1SDimitry Andric     // uncommon case.
504fe6060f1SDimitry Andric     InputSection *subsec;
505349cc55cSDimitry Andric     while (subsecIt != subsections.rend() && subsecIt->offset > r.offset)
506fe6060f1SDimitry Andric       ++subsecIt;
507349cc55cSDimitry Andric     if (subsecIt == subsections.rend() ||
508fe6060f1SDimitry Andric         subsecIt->offset + subsecIt->isec->getSize() <= r.offset) {
509349cc55cSDimitry Andric       subsec = findContainingSubsection(subsections, &r.offset);
510fe6060f1SDimitry Andric       // Now that we know the relocs are unsorted, avoid trying the 'fast path'
511fe6060f1SDimitry Andric       // for the other relocations.
512349cc55cSDimitry Andric       subsecIt = subsections.rend();
513fe6060f1SDimitry Andric     } else {
514fe6060f1SDimitry Andric       subsec = subsecIt->isec;
515fe6060f1SDimitry Andric       r.offset -= subsecIt->offset;
516fe6060f1SDimitry Andric     }
5175ffd83dbSDimitry Andric     subsec->relocs.push_back(r);
518fe6060f1SDimitry Andric 
519fe6060f1SDimitry Andric     if (isSubtrahend) {
520fe6060f1SDimitry Andric       relocation_info minuendInfo = relInfos[++i];
521fe6060f1SDimitry Andric       // SUBTRACTOR relocations should always be followed by an UNSIGNED one
522fe6060f1SDimitry Andric       // attached to the same address.
523fe6060f1SDimitry Andric       assert(target->hasAttr(minuendInfo.r_type, RelocAttrBits::UNSIGNED) &&
524fe6060f1SDimitry Andric              relInfo.r_address == minuendInfo.r_address);
525fe6060f1SDimitry Andric       Reloc p;
526fe6060f1SDimitry Andric       p.type = minuendInfo.r_type;
527fe6060f1SDimitry Andric       if (minuendInfo.r_extern) {
528fe6060f1SDimitry Andric         p.referent = symbols[minuendInfo.r_symbolnum];
529fe6060f1SDimitry Andric         p.addend = totalAddend;
530fe6060f1SDimitry Andric       } else {
531fe6060f1SDimitry Andric         uint64_t referentOffset =
532fe6060f1SDimitry Andric             totalAddend - sectionHeaders[minuendInfo.r_symbolnum - 1].addr;
533349cc55cSDimitry Andric         Subsections &referentSubsectVec =
534349cc55cSDimitry Andric             sections[minuendInfo.r_symbolnum - 1].subsections;
535fe6060f1SDimitry Andric         p.referent =
536349cc55cSDimitry Andric             findContainingSubsection(referentSubsectVec, &referentOffset);
537fe6060f1SDimitry Andric         p.addend = referentOffset;
538fe6060f1SDimitry Andric       }
539fe6060f1SDimitry Andric       subsec->relocs.push_back(p);
540fe6060f1SDimitry Andric     }
5415ffd83dbSDimitry Andric   }
5425ffd83dbSDimitry Andric }
5435ffd83dbSDimitry Andric 
544fe6060f1SDimitry Andric template <class NList>
545fe6060f1SDimitry Andric static macho::Symbol *createDefined(const NList &sym, StringRef name,
546fe6060f1SDimitry Andric                                     InputSection *isec, uint64_t value,
547fe6060f1SDimitry Andric                                     uint64_t size) {
548e8d8bef9SDimitry Andric   // Symbol scope is determined by sym.n_type & (N_EXT | N_PEXT):
549fe6060f1SDimitry Andric   // N_EXT: Global symbols. These go in the symbol table during the link,
550fe6060f1SDimitry Andric   //        and also in the export table of the output so that the dynamic
551fe6060f1SDimitry Andric   //        linker sees them.
552fe6060f1SDimitry Andric   // N_EXT | N_PEXT: Linkage unit (think: dylib) scoped. These go in the
553fe6060f1SDimitry Andric   //                 symbol table during the link so that duplicates are
554fe6060f1SDimitry Andric   //                 either reported (for non-weak symbols) or merged
555fe6060f1SDimitry Andric   //                 (for weak symbols), but they do not go in the export
556fe6060f1SDimitry Andric   //                 table of the output.
557fe6060f1SDimitry Andric   // N_PEXT: llvm-mc does not emit these, but `ld -r` (wherein ld64 emits
558fe6060f1SDimitry Andric   //         object files) may produce them. LLD does not yet support -r.
559fe6060f1SDimitry Andric   //         These are translation-unit scoped, identical to the `0` case.
560fe6060f1SDimitry Andric   // 0: Translation-unit scoped. These are not in the symbol table during
561fe6060f1SDimitry Andric   //    link, and not in the export table of the output either.
562fe6060f1SDimitry Andric   bool isWeakDefCanBeHidden =
563fe6060f1SDimitry Andric       (sym.n_desc & (N_WEAK_DEF | N_WEAK_REF)) == (N_WEAK_DEF | N_WEAK_REF);
564e8d8bef9SDimitry Andric 
565fe6060f1SDimitry Andric   if (sym.n_type & N_EXT) {
566fe6060f1SDimitry Andric     bool isPrivateExtern = sym.n_type & N_PEXT;
567fe6060f1SDimitry Andric     // lld's behavior for merging symbols is slightly different from ld64:
568fe6060f1SDimitry Andric     // ld64 picks the winning symbol based on several criteria (see
569fe6060f1SDimitry Andric     // pickBetweenRegularAtoms() in ld64's SymbolTable.cpp), while lld
570fe6060f1SDimitry Andric     // just merges metadata and keeps the contents of the first symbol
571fe6060f1SDimitry Andric     // with that name (see SymbolTable::addDefined). For:
572fe6060f1SDimitry Andric     // * inline function F in a TU built with -fvisibility-inlines-hidden
573fe6060f1SDimitry Andric     // * and inline function F in another TU built without that flag
574fe6060f1SDimitry Andric     // ld64 will pick the one from the file built without
575fe6060f1SDimitry Andric     // -fvisibility-inlines-hidden.
576fe6060f1SDimitry Andric     // lld will instead pick the one listed first on the link command line and
577fe6060f1SDimitry Andric     // give it visibility as if the function was built without
578fe6060f1SDimitry Andric     // -fvisibility-inlines-hidden.
579fe6060f1SDimitry Andric     // If both functions have the same contents, this will have the same
580fe6060f1SDimitry Andric     // behavior. If not, it won't, but the input had an ODR violation in
581fe6060f1SDimitry Andric     // that case.
582fe6060f1SDimitry Andric     //
583fe6060f1SDimitry Andric     // Similarly, merging a symbol
584fe6060f1SDimitry Andric     // that's isPrivateExtern and not isWeakDefCanBeHidden with one
585fe6060f1SDimitry Andric     // that's not isPrivateExtern but isWeakDefCanBeHidden technically
586fe6060f1SDimitry Andric     // should produce one
587fe6060f1SDimitry Andric     // that's not isPrivateExtern but isWeakDefCanBeHidden. That matters
588fe6060f1SDimitry Andric     // with ld64's semantics, because it means the non-private-extern
589fe6060f1SDimitry Andric     // definition will continue to take priority if more private extern
590fe6060f1SDimitry Andric     // definitions are encountered. With lld's semantics there's no observable
591349cc55cSDimitry Andric     // difference between a symbol that's isWeakDefCanBeHidden(autohide) or one
592349cc55cSDimitry Andric     // that's privateExtern -- neither makes it into the dynamic symbol table,
593349cc55cSDimitry Andric     // unless the autohide symbol is explicitly exported.
594349cc55cSDimitry Andric     // But if a symbol is both privateExtern and autohide then it can't
595349cc55cSDimitry Andric     // be exported.
596349cc55cSDimitry Andric     // So we nullify the autohide flag when privateExtern is present
597349cc55cSDimitry Andric     // and promote the symbol to privateExtern when it is not already.
598349cc55cSDimitry Andric     if (isWeakDefCanBeHidden && isPrivateExtern)
599349cc55cSDimitry Andric       isWeakDefCanBeHidden = false;
600349cc55cSDimitry Andric     else if (isWeakDefCanBeHidden)
601fe6060f1SDimitry Andric       isPrivateExtern = true;
602fe6060f1SDimitry Andric     return symtab->addDefined(
603fe6060f1SDimitry Andric         name, isec->getFile(), isec, value, size, sym.n_desc & N_WEAK_DEF,
604fe6060f1SDimitry Andric         isPrivateExtern, sym.n_desc & N_ARM_THUMB_DEF,
605349cc55cSDimitry Andric         sym.n_desc & REFERENCED_DYNAMICALLY, sym.n_desc & N_NO_DEAD_STRIP,
606349cc55cSDimitry Andric         isWeakDefCanBeHidden);
607e8d8bef9SDimitry Andric   }
608fe6060f1SDimitry Andric   assert(!isWeakDefCanBeHidden &&
609fe6060f1SDimitry Andric          "weak_def_can_be_hidden on already-hidden symbol?");
610fe6060f1SDimitry Andric   return make<Defined>(
611fe6060f1SDimitry Andric       name, isec->getFile(), isec, value, size, sym.n_desc & N_WEAK_DEF,
612fe6060f1SDimitry Andric       /*isExternal=*/false, /*isPrivateExtern=*/false,
613fe6060f1SDimitry Andric       sym.n_desc & N_ARM_THUMB_DEF, sym.n_desc & REFERENCED_DYNAMICALLY,
614fe6060f1SDimitry Andric       sym.n_desc & N_NO_DEAD_STRIP);
615e8d8bef9SDimitry Andric }
616e8d8bef9SDimitry Andric 
617e8d8bef9SDimitry Andric // Absolute symbols are defined symbols that do not have an associated
618e8d8bef9SDimitry Andric // InputSection. They cannot be weak.
619fe6060f1SDimitry Andric template <class NList>
620fe6060f1SDimitry Andric static macho::Symbol *createAbsolute(const NList &sym, InputFile *file,
621e8d8bef9SDimitry Andric                                      StringRef name) {
622fe6060f1SDimitry Andric   if (sym.n_type & N_EXT) {
623fe6060f1SDimitry Andric     return symtab->addDefined(
624fe6060f1SDimitry Andric         name, file, nullptr, sym.n_value, /*size=*/0,
625fe6060f1SDimitry Andric         /*isWeakDef=*/false, sym.n_type & N_PEXT, sym.n_desc & N_ARM_THUMB_DEF,
626349cc55cSDimitry Andric         /*isReferencedDynamically=*/false, sym.n_desc & N_NO_DEAD_STRIP,
627349cc55cSDimitry Andric         /*isWeakDefCanBeHidden=*/false);
628e8d8bef9SDimitry Andric   }
629fe6060f1SDimitry Andric   return make<Defined>(name, file, nullptr, sym.n_value, /*size=*/0,
630fe6060f1SDimitry Andric                        /*isWeakDef=*/false,
631fe6060f1SDimitry Andric                        /*isExternal=*/false, /*isPrivateExtern=*/false,
632fe6060f1SDimitry Andric                        sym.n_desc & N_ARM_THUMB_DEF,
633fe6060f1SDimitry Andric                        /*isReferencedDynamically=*/false,
634fe6060f1SDimitry Andric                        sym.n_desc & N_NO_DEAD_STRIP);
635e8d8bef9SDimitry Andric }
636e8d8bef9SDimitry Andric 
637fe6060f1SDimitry Andric template <class NList>
638fe6060f1SDimitry Andric macho::Symbol *ObjFile::parseNonSectionSymbol(const NList &sym,
639e8d8bef9SDimitry Andric                                               StringRef name) {
640e8d8bef9SDimitry Andric   uint8_t type = sym.n_type & N_TYPE;
641e8d8bef9SDimitry Andric   switch (type) {
642e8d8bef9SDimitry Andric   case N_UNDF:
643e8d8bef9SDimitry Andric     return sym.n_value == 0
644fe6060f1SDimitry Andric                ? symtab->addUndefined(name, this, sym.n_desc & N_WEAK_REF)
645e8d8bef9SDimitry Andric                : symtab->addCommon(name, this, sym.n_value,
646e8d8bef9SDimitry Andric                                    1 << GET_COMM_ALIGN(sym.n_desc),
647e8d8bef9SDimitry Andric                                    sym.n_type & N_PEXT);
648e8d8bef9SDimitry Andric   case N_ABS:
649fe6060f1SDimitry Andric     return createAbsolute(sym, this, name);
650e8d8bef9SDimitry Andric   case N_PBUD:
651e8d8bef9SDimitry Andric   case N_INDR:
652e8d8bef9SDimitry Andric     error("TODO: support symbols of type " + std::to_string(type));
653e8d8bef9SDimitry Andric     return nullptr;
654e8d8bef9SDimitry Andric   case N_SECT:
655e8d8bef9SDimitry Andric     llvm_unreachable(
656e8d8bef9SDimitry Andric         "N_SECT symbols should not be passed to parseNonSectionSymbol");
657e8d8bef9SDimitry Andric   default:
658e8d8bef9SDimitry Andric     llvm_unreachable("invalid symbol type");
659e8d8bef9SDimitry Andric   }
660e8d8bef9SDimitry Andric }
661e8d8bef9SDimitry Andric 
662349cc55cSDimitry Andric template <class NList> static bool isUndef(const NList &sym) {
663fe6060f1SDimitry Andric   return (sym.n_type & N_TYPE) == N_UNDF && sym.n_value == 0;
664fe6060f1SDimitry Andric }
665fe6060f1SDimitry Andric 
666fe6060f1SDimitry Andric template <class LP>
667fe6060f1SDimitry Andric void ObjFile::parseSymbols(ArrayRef<typename LP::section> sectionHeaders,
668fe6060f1SDimitry Andric                            ArrayRef<typename LP::nlist> nList,
6695ffd83dbSDimitry Andric                            const char *strtab, bool subsectionsViaSymbols) {
670fe6060f1SDimitry Andric   using NList = typename LP::nlist;
671fe6060f1SDimitry Andric 
672fe6060f1SDimitry Andric   // Groups indices of the symbols by the sections that contain them.
673349cc55cSDimitry Andric   std::vector<std::vector<uint32_t>> symbolsBySection(sections.size());
6745ffd83dbSDimitry Andric   symbols.resize(nList.size());
675fe6060f1SDimitry Andric   SmallVector<unsigned, 32> undefineds;
676fe6060f1SDimitry Andric   for (uint32_t i = 0; i < nList.size(); ++i) {
677fe6060f1SDimitry Andric     const NList &sym = nList[i];
6785ffd83dbSDimitry Andric 
679fe6060f1SDimitry Andric     // Ignore debug symbols for now.
680fe6060f1SDimitry Andric     // FIXME: may need special handling.
681fe6060f1SDimitry Andric     if (sym.n_type & N_STAB)
682fe6060f1SDimitry Andric       continue;
683fe6060f1SDimitry Andric 
6845ffd83dbSDimitry Andric     StringRef name = strtab + sym.n_strx;
685fe6060f1SDimitry Andric     if ((sym.n_type & N_TYPE) == N_SECT) {
686349cc55cSDimitry Andric       Subsections &subsections = sections[sym.n_sect - 1].subsections;
687fe6060f1SDimitry Andric       // parseSections() may have chosen not to parse this section.
688349cc55cSDimitry Andric       if (subsections.empty())
689fe6060f1SDimitry Andric         continue;
690fe6060f1SDimitry Andric       symbolsBySection[sym.n_sect - 1].push_back(i);
691fe6060f1SDimitry Andric     } else if (isUndef(sym)) {
692fe6060f1SDimitry Andric       undefineds.push_back(i);
693fe6060f1SDimitry Andric     } else {
694fe6060f1SDimitry Andric       symbols[i] = parseNonSectionSymbol(sym, name);
695fe6060f1SDimitry Andric     }
696fe6060f1SDimitry Andric   }
6975ffd83dbSDimitry Andric 
698349cc55cSDimitry Andric   for (size_t i = 0; i < sections.size(); ++i) {
699349cc55cSDimitry Andric     Subsections &subsections = sections[i].subsections;
700349cc55cSDimitry Andric     if (subsections.empty())
701fe6060f1SDimitry Andric       continue;
702349cc55cSDimitry Andric     InputSection *lastIsec = subsections.back().isec;
703349cc55cSDimitry Andric     if (lastIsec->getName() == section_names::ehFrame) {
704349cc55cSDimitry Andric       // __TEXT,__eh_frame only has symbols and SUBTRACTOR relocs when ld64 -r
705349cc55cSDimitry Andric       // adds local "EH_Frame1" and "func.eh". Ignore them because they have
706349cc55cSDimitry Andric       // gone unused by Mac OS since Snow Leopard (10.6), vintage 2009.
707349cc55cSDimitry Andric       continue;
708349cc55cSDimitry Andric     }
709fe6060f1SDimitry Andric     std::vector<uint32_t> &symbolIndices = symbolsBySection[i];
710fe6060f1SDimitry Andric     uint64_t sectionAddr = sectionHeaders[i].addr;
711fe6060f1SDimitry Andric     uint32_t sectionAlign = 1u << sectionHeaders[i].align;
712fe6060f1SDimitry Andric 
713349cc55cSDimitry Andric     // Record-based sections have already been split into subsections during
714fe6060f1SDimitry Andric     // parseSections(), so we simply need to match Symbols to the corresponding
715fe6060f1SDimitry Andric     // subsection here.
716349cc55cSDimitry Andric     if (getRecordSize(lastIsec->getSegName(), lastIsec->getName())) {
717fe6060f1SDimitry Andric       for (size_t j = 0; j < symbolIndices.size(); ++j) {
718fe6060f1SDimitry Andric         uint32_t symIndex = symbolIndices[j];
719fe6060f1SDimitry Andric         const NList &sym = nList[symIndex];
720fe6060f1SDimitry Andric         StringRef name = strtab + sym.n_strx;
721fe6060f1SDimitry Andric         uint64_t symbolOffset = sym.n_value - sectionAddr;
722349cc55cSDimitry Andric         InputSection *isec =
723349cc55cSDimitry Andric             findContainingSubsection(subsections, &symbolOffset);
724fe6060f1SDimitry Andric         if (symbolOffset != 0) {
725349cc55cSDimitry Andric           error(toString(lastIsec) + ":  symbol " + name +
726fe6060f1SDimitry Andric                 " at misaligned offset");
727fe6060f1SDimitry Andric           continue;
728fe6060f1SDimitry Andric         }
729fe6060f1SDimitry Andric         symbols[symIndex] = createDefined(sym, name, isec, 0, isec->getSize());
730fe6060f1SDimitry Andric       }
7315ffd83dbSDimitry Andric       continue;
7325ffd83dbSDimitry Andric     }
7335ffd83dbSDimitry Andric 
734fe6060f1SDimitry Andric     // Calculate symbol sizes and create subsections by splitting the sections
735fe6060f1SDimitry Andric     // along symbol boundaries.
736349cc55cSDimitry Andric     // We populate subsections by repeatedly splitting the last (highest
737349cc55cSDimitry Andric     // address) subsection.
738fe6060f1SDimitry Andric     llvm::stable_sort(symbolIndices, [&](uint32_t lhs, uint32_t rhs) {
739fe6060f1SDimitry Andric       return nList[lhs].n_value < nList[rhs].n_value;
740fe6060f1SDimitry Andric     });
741fe6060f1SDimitry Andric     for (size_t j = 0; j < symbolIndices.size(); ++j) {
742fe6060f1SDimitry Andric       uint32_t symIndex = symbolIndices[j];
743fe6060f1SDimitry Andric       const NList &sym = nList[symIndex];
744fe6060f1SDimitry Andric       StringRef name = strtab + sym.n_strx;
745349cc55cSDimitry Andric       Subsection &subsec = subsections.back();
746349cc55cSDimitry Andric       InputSection *isec = subsec.isec;
747fe6060f1SDimitry Andric 
748349cc55cSDimitry Andric       uint64_t subsecAddr = sectionAddr + subsec.offset;
749fe6060f1SDimitry Andric       size_t symbolOffset = sym.n_value - subsecAddr;
750fe6060f1SDimitry Andric       uint64_t symbolSize =
751fe6060f1SDimitry Andric           j + 1 < symbolIndices.size()
752fe6060f1SDimitry Andric               ? nList[symbolIndices[j + 1]].n_value - sym.n_value
753fe6060f1SDimitry Andric               : isec->data.size() - symbolOffset;
754fe6060f1SDimitry Andric       // There are 4 cases where we do not need to create a new subsection:
755fe6060f1SDimitry Andric       //   1. If the input file does not use subsections-via-symbols.
756fe6060f1SDimitry Andric       //   2. Multiple symbols at the same address only induce one subsection.
757fe6060f1SDimitry Andric       //      (The symbolOffset == 0 check covers both this case as well as
758fe6060f1SDimitry Andric       //      the first loop iteration.)
759fe6060f1SDimitry Andric       //   3. Alternative entry points do not induce new subsections.
760fe6060f1SDimitry Andric       //   4. If we have a literal section (e.g. __cstring and __literal4).
761fe6060f1SDimitry Andric       if (!subsectionsViaSymbols || symbolOffset == 0 ||
762fe6060f1SDimitry Andric           sym.n_desc & N_ALT_ENTRY || !isa<ConcatInputSection>(isec)) {
763fe6060f1SDimitry Andric         symbols[symIndex] =
764fe6060f1SDimitry Andric             createDefined(sym, name, isec, symbolOffset, symbolSize);
7655ffd83dbSDimitry Andric         continue;
7665ffd83dbSDimitry Andric       }
767fe6060f1SDimitry Andric       auto *concatIsec = cast<ConcatInputSection>(isec);
7685ffd83dbSDimitry Andric 
769fe6060f1SDimitry Andric       auto *nextIsec = make<ConcatInputSection>(*concatIsec);
770fe6060f1SDimitry Andric       nextIsec->wasCoalesced = false;
771fe6060f1SDimitry Andric       if (isZeroFill(isec->getFlags())) {
772fe6060f1SDimitry Andric         // Zero-fill sections have NULL data.data() non-zero data.size()
773fe6060f1SDimitry Andric         nextIsec->data = {nullptr, isec->data.size() - symbolOffset};
774fe6060f1SDimitry Andric         isec->data = {nullptr, symbolOffset};
775fe6060f1SDimitry Andric       } else {
776fe6060f1SDimitry Andric         nextIsec->data = isec->data.slice(symbolOffset);
777fe6060f1SDimitry Andric         isec->data = isec->data.slice(0, symbolOffset);
7785ffd83dbSDimitry Andric       }
7795ffd83dbSDimitry Andric 
780fe6060f1SDimitry Andric       // By construction, the symbol will be at offset zero in the new
781fe6060f1SDimitry Andric       // subsection.
782fe6060f1SDimitry Andric       symbols[symIndex] =
783fe6060f1SDimitry Andric           createDefined(sym, name, nextIsec, /*value=*/0, symbolSize);
7845ffd83dbSDimitry Andric       // TODO: ld64 appears to preserve the original alignment as well as each
7855ffd83dbSDimitry Andric       // subsection's offset from the last aligned address. We should consider
7865ffd83dbSDimitry Andric       // emulating that behavior.
787fe6060f1SDimitry Andric       nextIsec->align = MinAlign(sectionAlign, sym.n_value);
788349cc55cSDimitry Andric       subsections.push_back({sym.n_value - sectionAddr, nextIsec});
789fe6060f1SDimitry Andric     }
7905ffd83dbSDimitry Andric   }
7915ffd83dbSDimitry Andric 
792fe6060f1SDimitry Andric   // Undefined symbols can trigger recursive fetch from Archives due to
793fe6060f1SDimitry Andric   // LazySymbols. Process defined symbols first so that the relative order
794fe6060f1SDimitry Andric   // between a defined symbol and an undefined symbol does not change the
795fe6060f1SDimitry Andric   // symbol resolution behavior. In addition, a set of interconnected symbols
796fe6060f1SDimitry Andric   // will all be resolved to the same file, instead of being resolved to
797fe6060f1SDimitry Andric   // different files.
798fe6060f1SDimitry Andric   for (unsigned i : undefineds) {
799fe6060f1SDimitry Andric     const NList &sym = nList[i];
800e8d8bef9SDimitry Andric     StringRef name = strtab + sym.n_strx;
801fe6060f1SDimitry Andric     symbols[i] = parseNonSectionSymbol(sym, name);
8025ffd83dbSDimitry Andric   }
8035ffd83dbSDimitry Andric }
8045ffd83dbSDimitry Andric 
805e8d8bef9SDimitry Andric OpaqueFile::OpaqueFile(MemoryBufferRef mb, StringRef segName,
806e8d8bef9SDimitry Andric                        StringRef sectName)
807e8d8bef9SDimitry Andric     : InputFile(OpaqueKind, mb) {
808e8d8bef9SDimitry Andric   const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
809fe6060f1SDimitry Andric   ArrayRef<uint8_t> data = {buf, mb.getBufferSize()};
810fe6060f1SDimitry Andric   ConcatInputSection *isec =
811fe6060f1SDimitry Andric       make<ConcatInputSection>(segName.take_front(16), sectName.take_front(16),
812fe6060f1SDimitry Andric                                /*file=*/this, data);
813fe6060f1SDimitry Andric   isec->live = true;
814349cc55cSDimitry Andric   sections.push_back(0);
815349cc55cSDimitry Andric   sections.back().subsections.push_back({0, isec});
816e8d8bef9SDimitry Andric }
817e8d8bef9SDimitry Andric 
818e8d8bef9SDimitry Andric ObjFile::ObjFile(MemoryBufferRef mb, uint32_t modTime, StringRef archiveName)
819e8d8bef9SDimitry Andric     : InputFile(ObjKind, mb), modTime(modTime) {
820e8d8bef9SDimitry Andric   this->archiveName = std::string(archiveName);
821fe6060f1SDimitry Andric   if (target->wordSize == 8)
822fe6060f1SDimitry Andric     parse<LP64>();
823fe6060f1SDimitry Andric   else
824fe6060f1SDimitry Andric     parse<ILP32>();
825e8d8bef9SDimitry Andric }
826e8d8bef9SDimitry Andric 
827fe6060f1SDimitry Andric template <class LP> void ObjFile::parse() {
828fe6060f1SDimitry Andric   using Header = typename LP::mach_header;
829fe6060f1SDimitry Andric   using SegmentCommand = typename LP::segment_command;
830349cc55cSDimitry Andric   using SectionHeader = typename LP::section;
831fe6060f1SDimitry Andric   using NList = typename LP::nlist;
832fe6060f1SDimitry Andric 
833fe6060f1SDimitry Andric   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
834fe6060f1SDimitry Andric   auto *hdr = reinterpret_cast<const Header *>(mb.getBufferStart());
835fe6060f1SDimitry Andric 
836fe6060f1SDimitry Andric   Architecture arch = getArchitectureFromCpuType(hdr->cputype, hdr->cpusubtype);
837fe6060f1SDimitry Andric   if (arch != config->arch()) {
838349cc55cSDimitry Andric     auto msg = config->errorForArchMismatch
839349cc55cSDimitry Andric                    ? static_cast<void (*)(const Twine &)>(error)
840349cc55cSDimitry Andric                    : warn;
841349cc55cSDimitry Andric     msg(toString(this) + " has architecture " + getArchitectureName(arch) +
842fe6060f1SDimitry Andric         " which is incompatible with target architecture " +
843fe6060f1SDimitry Andric         getArchitectureName(config->arch()));
844fe6060f1SDimitry Andric     return;
845fe6060f1SDimitry Andric   }
846fe6060f1SDimitry Andric 
847fe6060f1SDimitry Andric   if (!checkCompatibility(this))
848fe6060f1SDimitry Andric     return;
849fe6060f1SDimitry Andric 
850fe6060f1SDimitry Andric   for (auto *cmd : findCommands<linker_option_command>(hdr, LC_LINKER_OPTION)) {
851fe6060f1SDimitry Andric     StringRef data{reinterpret_cast<const char *>(cmd + 1),
852fe6060f1SDimitry Andric                    cmd->cmdsize - sizeof(linker_option_command)};
853fe6060f1SDimitry Andric     parseLCLinkerOption(this, cmd->count, data);
854fe6060f1SDimitry Andric   }
855fe6060f1SDimitry Andric 
856349cc55cSDimitry Andric   ArrayRef<SectionHeader> sectionHeaders;
857fe6060f1SDimitry Andric   if (const load_command *cmd = findCommand(hdr, LP::segmentLCType)) {
858fe6060f1SDimitry Andric     auto *c = reinterpret_cast<const SegmentCommand *>(cmd);
859349cc55cSDimitry Andric     sectionHeaders = ArrayRef<SectionHeader>{
860349cc55cSDimitry Andric         reinterpret_cast<const SectionHeader *>(c + 1), c->nsects};
8615ffd83dbSDimitry Andric     parseSections(sectionHeaders);
8625ffd83dbSDimitry Andric   }
8635ffd83dbSDimitry Andric 
8645ffd83dbSDimitry Andric   // TODO: Error on missing LC_SYMTAB?
8655ffd83dbSDimitry Andric   if (const load_command *cmd = findCommand(hdr, LC_SYMTAB)) {
8665ffd83dbSDimitry Andric     auto *c = reinterpret_cast<const symtab_command *>(cmd);
867fe6060f1SDimitry Andric     ArrayRef<NList> nList(reinterpret_cast<const NList *>(buf + c->symoff),
868fe6060f1SDimitry Andric                           c->nsyms);
8695ffd83dbSDimitry Andric     const char *strtab = reinterpret_cast<const char *>(buf) + c->stroff;
8705ffd83dbSDimitry Andric     bool subsectionsViaSymbols = hdr->flags & MH_SUBSECTIONS_VIA_SYMBOLS;
871fe6060f1SDimitry Andric     parseSymbols<LP>(sectionHeaders, nList, strtab, subsectionsViaSymbols);
8725ffd83dbSDimitry Andric   }
8735ffd83dbSDimitry Andric 
8745ffd83dbSDimitry Andric   // The relocations may refer to the symbols, so we parse them after we have
8755ffd83dbSDimitry Andric   // parsed all the symbols.
876349cc55cSDimitry Andric   for (size_t i = 0, n = sections.size(); i < n; ++i)
877349cc55cSDimitry Andric     if (!sections[i].subsections.empty())
878349cc55cSDimitry Andric       parseRelocations(sectionHeaders, sectionHeaders[i],
879349cc55cSDimitry Andric                        sections[i].subsections);
880e8d8bef9SDimitry Andric 
881e8d8bef9SDimitry Andric   parseDebugInfo();
882349cc55cSDimitry Andric   if (compactUnwindSection)
883349cc55cSDimitry Andric     registerCompactUnwind();
884e8d8bef9SDimitry Andric }
885e8d8bef9SDimitry Andric 
886e8d8bef9SDimitry Andric void ObjFile::parseDebugInfo() {
887e8d8bef9SDimitry Andric   std::unique_ptr<DwarfObject> dObj = DwarfObject::create(this);
888e8d8bef9SDimitry Andric   if (!dObj)
889e8d8bef9SDimitry Andric     return;
890e8d8bef9SDimitry Andric 
891e8d8bef9SDimitry Andric   auto *ctx = make<DWARFContext>(
892e8d8bef9SDimitry Andric       std::move(dObj), "",
893e8d8bef9SDimitry Andric       [&](Error err) {
894e8d8bef9SDimitry Andric         warn(toString(this) + ": " + toString(std::move(err)));
895e8d8bef9SDimitry Andric       },
896e8d8bef9SDimitry Andric       [&](Error warning) {
897e8d8bef9SDimitry Andric         warn(toString(this) + ": " + toString(std::move(warning)));
898e8d8bef9SDimitry Andric       });
899e8d8bef9SDimitry Andric 
900e8d8bef9SDimitry Andric   // TODO: Since object files can contain a lot of DWARF info, we should verify
901e8d8bef9SDimitry Andric   // that we are parsing just the info we need
902e8d8bef9SDimitry Andric   const DWARFContext::compile_unit_range &units = ctx->compile_units();
903fe6060f1SDimitry Andric   // FIXME: There can be more than one compile unit per object file. See
904fe6060f1SDimitry Andric   // PR48637.
905e8d8bef9SDimitry Andric   auto it = units.begin();
906e8d8bef9SDimitry Andric   compileUnit = it->get();
907fe6060f1SDimitry Andric }
908fe6060f1SDimitry Andric 
909*0eae32dcSDimitry Andric ArrayRef<data_in_code_entry> ObjFile::getDataInCode() const {
910fe6060f1SDimitry Andric   const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
911fe6060f1SDimitry Andric   const load_command *cmd = findCommand(buf, LC_DATA_IN_CODE);
912fe6060f1SDimitry Andric   if (!cmd)
913*0eae32dcSDimitry Andric     return {};
914fe6060f1SDimitry Andric   const auto *c = reinterpret_cast<const linkedit_data_command *>(cmd);
915*0eae32dcSDimitry Andric   return {reinterpret_cast<const data_in_code_entry *>(buf + c->dataoff),
916fe6060f1SDimitry Andric           c->datasize / sizeof(data_in_code_entry)};
917e8d8bef9SDimitry Andric }
918e8d8bef9SDimitry Andric 
919349cc55cSDimitry Andric // Create pointers from symbols to their associated compact unwind entries.
920349cc55cSDimitry Andric void ObjFile::registerCompactUnwind() {
921349cc55cSDimitry Andric   for (const Subsection &subsection : compactUnwindSection->subsections) {
922349cc55cSDimitry Andric     ConcatInputSection *isec = cast<ConcatInputSection>(subsection.isec);
923349cc55cSDimitry Andric     // Hack!! Since each CUE contains a different function address, if ICF
924349cc55cSDimitry Andric     // operated naively and compared the entire contents of each CUE, entries
925349cc55cSDimitry Andric     // with identical unwind info but belonging to different functions would
926349cc55cSDimitry Andric     // never be considered equivalent. To work around this problem, we slice
927349cc55cSDimitry Andric     // away the function address here. (Note that we do not adjust the offsets
928349cc55cSDimitry Andric     // of the corresponding relocations.) We rely on `relocateCompactUnwind()`
929349cc55cSDimitry Andric     // to correctly handle these truncated input sections.
930349cc55cSDimitry Andric     isec->data = isec->data.slice(target->wordSize);
931349cc55cSDimitry Andric 
932349cc55cSDimitry Andric     ConcatInputSection *referentIsec;
933349cc55cSDimitry Andric     for (auto it = isec->relocs.begin(); it != isec->relocs.end();) {
934349cc55cSDimitry Andric       Reloc &r = *it;
935349cc55cSDimitry Andric       // CUE::functionAddress is at offset 0. Skip personality & LSDA relocs.
936349cc55cSDimitry Andric       if (r.offset != 0) {
937349cc55cSDimitry Andric         ++it;
938349cc55cSDimitry Andric         continue;
939349cc55cSDimitry Andric       }
940349cc55cSDimitry Andric       uint64_t add = r.addend;
941349cc55cSDimitry Andric       if (auto *sym = cast_or_null<Defined>(r.referent.dyn_cast<Symbol *>())) {
942349cc55cSDimitry Andric         // Check whether the symbol defined in this file is the prevailing one.
943349cc55cSDimitry Andric         // Skip if it is e.g. a weak def that didn't prevail.
944349cc55cSDimitry Andric         if (sym->getFile() != this) {
945349cc55cSDimitry Andric           ++it;
946349cc55cSDimitry Andric           continue;
947349cc55cSDimitry Andric         }
948349cc55cSDimitry Andric         add += sym->value;
949349cc55cSDimitry Andric         referentIsec = cast<ConcatInputSection>(sym->isec);
950349cc55cSDimitry Andric       } else {
951349cc55cSDimitry Andric         referentIsec =
952349cc55cSDimitry Andric             cast<ConcatInputSection>(r.referent.dyn_cast<InputSection *>());
953349cc55cSDimitry Andric       }
954349cc55cSDimitry Andric       if (referentIsec->getSegName() != segment_names::text)
955349cc55cSDimitry Andric         error("compact unwind references address in " + toString(referentIsec) +
956349cc55cSDimitry Andric               " which is not in segment __TEXT");
957349cc55cSDimitry Andric       // The functionAddress relocations are typically section relocations.
958349cc55cSDimitry Andric       // However, unwind info operates on a per-symbol basis, so we search for
959349cc55cSDimitry Andric       // the function symbol here.
960349cc55cSDimitry Andric       auto symIt = llvm::lower_bound(
961349cc55cSDimitry Andric           referentIsec->symbols, add,
962349cc55cSDimitry Andric           [](Defined *d, uint64_t add) { return d->value < add; });
963349cc55cSDimitry Andric       // The relocation should point at the exact address of a symbol (with no
964349cc55cSDimitry Andric       // addend).
965349cc55cSDimitry Andric       if (symIt == referentIsec->symbols.end() || (*symIt)->value != add) {
966349cc55cSDimitry Andric         assert(referentIsec->wasCoalesced);
967349cc55cSDimitry Andric         ++it;
968349cc55cSDimitry Andric         continue;
969349cc55cSDimitry Andric       }
970349cc55cSDimitry Andric       (*symIt)->unwindEntry = isec;
971349cc55cSDimitry Andric       // Since we've sliced away the functionAddress, we should remove the
972349cc55cSDimitry Andric       // corresponding relocation too. Given that clang emits relocations in
973349cc55cSDimitry Andric       // reverse order of address, this relocation should be at the end of the
974349cc55cSDimitry Andric       // vector for most of our input object files, so this is typically an O(1)
975349cc55cSDimitry Andric       // operation.
976349cc55cSDimitry Andric       it = isec->relocs.erase(it);
977349cc55cSDimitry Andric     }
978349cc55cSDimitry Andric   }
979349cc55cSDimitry Andric }
980349cc55cSDimitry Andric 
981e8d8bef9SDimitry Andric // The path can point to either a dylib or a .tbd file.
982fe6060f1SDimitry Andric static DylibFile *loadDylib(StringRef path, DylibFile *umbrella) {
983e8d8bef9SDimitry Andric   Optional<MemoryBufferRef> mbref = readFile(path);
984e8d8bef9SDimitry Andric   if (!mbref) {
985e8d8bef9SDimitry Andric     error("could not read dylib file at " + path);
986fe6060f1SDimitry Andric     return nullptr;
987e8d8bef9SDimitry Andric   }
988e8d8bef9SDimitry Andric   return loadDylib(*mbref, umbrella);
989e8d8bef9SDimitry Andric }
990e8d8bef9SDimitry Andric 
991e8d8bef9SDimitry Andric // TBD files are parsed into a series of TAPI documents (InterfaceFiles), with
992e8d8bef9SDimitry Andric // the first document storing child pointers to the rest of them. When we are
993fe6060f1SDimitry Andric // processing a given TBD file, we store that top-level document in
994fe6060f1SDimitry Andric // currentTopLevelTapi. When processing re-exports, we search its children for
995fe6060f1SDimitry Andric // potentially matching documents in the same TBD file. Note that the children
996fe6060f1SDimitry Andric // themselves don't point to further documents, i.e. this is a two-level tree.
997e8d8bef9SDimitry Andric //
998e8d8bef9SDimitry Andric // Re-exports can either refer to on-disk files, or to documents within .tbd
999e8d8bef9SDimitry Andric // files.
1000fe6060f1SDimitry Andric static DylibFile *findDylib(StringRef path, DylibFile *umbrella,
1001fe6060f1SDimitry Andric                             const InterfaceFile *currentTopLevelTapi) {
1002fe6060f1SDimitry Andric   // Search order:
1003fe6060f1SDimitry Andric   // 1. Install name basename in -F / -L directories.
1004fe6060f1SDimitry Andric   {
1005fe6060f1SDimitry Andric     StringRef stem = path::stem(path);
1006fe6060f1SDimitry Andric     SmallString<128> frameworkName;
1007fe6060f1SDimitry Andric     path::append(frameworkName, path::Style::posix, stem + ".framework", stem);
1008fe6060f1SDimitry Andric     bool isFramework = path.endswith(frameworkName);
1009fe6060f1SDimitry Andric     if (isFramework) {
1010fe6060f1SDimitry Andric       for (StringRef dir : config->frameworkSearchPaths) {
1011fe6060f1SDimitry Andric         SmallString<128> candidate = dir;
1012fe6060f1SDimitry Andric         path::append(candidate, frameworkName);
1013349cc55cSDimitry Andric         if (Optional<StringRef> dylibPath = resolveDylibPath(candidate.str()))
1014fe6060f1SDimitry Andric           return loadDylib(*dylibPath, umbrella);
1015fe6060f1SDimitry Andric       }
1016fe6060f1SDimitry Andric     } else if (Optional<StringRef> dylibPath = findPathCombination(
1017fe6060f1SDimitry Andric                    stem, config->librarySearchPaths, {".tbd", ".dylib"}))
1018fe6060f1SDimitry Andric       return loadDylib(*dylibPath, umbrella);
1019fe6060f1SDimitry Andric   }
1020fe6060f1SDimitry Andric 
1021fe6060f1SDimitry Andric   // 2. As absolute path.
1022e8d8bef9SDimitry Andric   if (path::is_absolute(path, path::Style::posix))
1023e8d8bef9SDimitry Andric     for (StringRef root : config->systemLibraryRoots)
1024349cc55cSDimitry Andric       if (Optional<StringRef> dylibPath = resolveDylibPath((root + path).str()))
1025e8d8bef9SDimitry Andric         return loadDylib(*dylibPath, umbrella);
1026e8d8bef9SDimitry Andric 
1027fe6060f1SDimitry Andric   // 3. As relative path.
1028e8d8bef9SDimitry Andric 
1029fe6060f1SDimitry Andric   // TODO: Handle -dylib_file
1030fe6060f1SDimitry Andric 
1031fe6060f1SDimitry Andric   // Replace @executable_path, @loader_path, @rpath prefixes in install name.
1032fe6060f1SDimitry Andric   SmallString<128> newPath;
1033fe6060f1SDimitry Andric   if (config->outputType == MH_EXECUTE &&
1034fe6060f1SDimitry Andric       path.consume_front("@executable_path/")) {
1035fe6060f1SDimitry Andric     // ld64 allows overriding this with the undocumented flag -executable_path.
1036fe6060f1SDimitry Andric     // lld doesn't currently implement that flag.
1037fe6060f1SDimitry Andric     // FIXME: Consider using finalOutput instead of outputFile.
1038fe6060f1SDimitry Andric     path::append(newPath, path::parent_path(config->outputFile), path);
1039fe6060f1SDimitry Andric     path = newPath;
1040fe6060f1SDimitry Andric   } else if (path.consume_front("@loader_path/")) {
1041fe6060f1SDimitry Andric     fs::real_path(umbrella->getName(), newPath);
1042fe6060f1SDimitry Andric     path::remove_filename(newPath);
1043fe6060f1SDimitry Andric     path::append(newPath, path);
1044fe6060f1SDimitry Andric     path = newPath;
1045fe6060f1SDimitry Andric   } else if (path.startswith("@rpath/")) {
1046fe6060f1SDimitry Andric     for (StringRef rpath : umbrella->rpaths) {
1047fe6060f1SDimitry Andric       newPath.clear();
1048fe6060f1SDimitry Andric       if (rpath.consume_front("@loader_path/")) {
1049fe6060f1SDimitry Andric         fs::real_path(umbrella->getName(), newPath);
1050fe6060f1SDimitry Andric         path::remove_filename(newPath);
1051fe6060f1SDimitry Andric       }
1052fe6060f1SDimitry Andric       path::append(newPath, rpath, path.drop_front(strlen("@rpath/")));
1053349cc55cSDimitry Andric       if (Optional<StringRef> dylibPath = resolveDylibPath(newPath.str()))
1054fe6060f1SDimitry Andric         return loadDylib(*dylibPath, umbrella);
1055fe6060f1SDimitry Andric     }
1056fe6060f1SDimitry Andric   }
1057fe6060f1SDimitry Andric 
1058fe6060f1SDimitry Andric   // FIXME: Should this be further up?
1059e8d8bef9SDimitry Andric   if (currentTopLevelTapi) {
1060e8d8bef9SDimitry Andric     for (InterfaceFile &child :
1061e8d8bef9SDimitry Andric          make_pointee_range(currentTopLevelTapi->documents())) {
1062e8d8bef9SDimitry Andric       assert(child.documents().empty());
1063fe6060f1SDimitry Andric       if (path == child.getInstallName()) {
1064fe6060f1SDimitry Andric         auto file = make<DylibFile>(child, umbrella);
1065fe6060f1SDimitry Andric         file->parseReexports(child);
1066fe6060f1SDimitry Andric         return file;
1067fe6060f1SDimitry Andric       }
1068e8d8bef9SDimitry Andric     }
1069e8d8bef9SDimitry Andric   }
1070e8d8bef9SDimitry Andric 
1071349cc55cSDimitry Andric   if (Optional<StringRef> dylibPath = resolveDylibPath(path))
1072e8d8bef9SDimitry Andric     return loadDylib(*dylibPath, umbrella);
1073e8d8bef9SDimitry Andric 
1074fe6060f1SDimitry Andric   return nullptr;
1075e8d8bef9SDimitry Andric }
1076e8d8bef9SDimitry Andric 
1077e8d8bef9SDimitry Andric // If a re-exported dylib is public (lives in /usr/lib or
1078e8d8bef9SDimitry Andric // /System/Library/Frameworks), then it is considered implicitly linked: we
1079e8d8bef9SDimitry Andric // should bind to its symbols directly instead of via the re-exporting umbrella
1080e8d8bef9SDimitry Andric // library.
1081e8d8bef9SDimitry Andric static bool isImplicitlyLinked(StringRef path) {
1082e8d8bef9SDimitry Andric   if (!config->implicitDylibs)
1083e8d8bef9SDimitry Andric     return false;
1084e8d8bef9SDimitry Andric 
1085e8d8bef9SDimitry Andric   if (path::parent_path(path) == "/usr/lib")
1086e8d8bef9SDimitry Andric     return true;
1087e8d8bef9SDimitry Andric 
1088e8d8bef9SDimitry Andric   // Match /System/Library/Frameworks/$FOO.framework/**/$FOO
1089e8d8bef9SDimitry Andric   if (path.consume_front("/System/Library/Frameworks/")) {
1090e8d8bef9SDimitry Andric     StringRef frameworkName = path.take_until([](char c) { return c == '.'; });
1091e8d8bef9SDimitry Andric     return path::filename(path) == frameworkName;
1092e8d8bef9SDimitry Andric   }
1093e8d8bef9SDimitry Andric 
1094e8d8bef9SDimitry Andric   return false;
1095e8d8bef9SDimitry Andric }
1096e8d8bef9SDimitry Andric 
1097fe6060f1SDimitry Andric static void loadReexport(StringRef path, DylibFile *umbrella,
1098fe6060f1SDimitry Andric                          const InterfaceFile *currentTopLevelTapi) {
1099fe6060f1SDimitry Andric   DylibFile *reexport = findDylib(path, umbrella, currentTopLevelTapi);
1100fe6060f1SDimitry Andric   if (!reexport)
1101fe6060f1SDimitry Andric     error("unable to locate re-export with install name " + path);
11025ffd83dbSDimitry Andric }
11035ffd83dbSDimitry Andric 
1104fe6060f1SDimitry Andric DylibFile::DylibFile(MemoryBufferRef mb, DylibFile *umbrella,
1105fe6060f1SDimitry Andric                      bool isBundleLoader)
1106fe6060f1SDimitry Andric     : InputFile(DylibKind, mb), refState(RefState::Unreferenced),
1107fe6060f1SDimitry Andric       isBundleLoader(isBundleLoader) {
1108fe6060f1SDimitry Andric   assert(!isBundleLoader || !umbrella);
11095ffd83dbSDimitry Andric   if (umbrella == nullptr)
11105ffd83dbSDimitry Andric     umbrella = this;
1111fe6060f1SDimitry Andric   this->umbrella = umbrella;
11125ffd83dbSDimitry Andric 
11135ffd83dbSDimitry Andric   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
1114fe6060f1SDimitry Andric   auto *hdr = reinterpret_cast<const mach_header *>(mb.getBufferStart());
11155ffd83dbSDimitry Andric 
1116fe6060f1SDimitry Andric   // Initialize installName.
11175ffd83dbSDimitry Andric   if (const load_command *cmd = findCommand(hdr, LC_ID_DYLIB)) {
11185ffd83dbSDimitry Andric     auto *c = reinterpret_cast<const dylib_command *>(cmd);
1119e8d8bef9SDimitry Andric     currentVersion = read32le(&c->dylib.current_version);
1120e8d8bef9SDimitry Andric     compatibilityVersion = read32le(&c->dylib.compatibility_version);
1121fe6060f1SDimitry Andric     installName =
1122fe6060f1SDimitry Andric         reinterpret_cast<const char *>(cmd) + read32le(&c->dylib.name);
1123fe6060f1SDimitry Andric   } else if (!isBundleLoader) {
1124fe6060f1SDimitry Andric     // macho_executable and macho_bundle don't have LC_ID_DYLIB,
1125fe6060f1SDimitry Andric     // so it's OK.
1126e8d8bef9SDimitry Andric     error("dylib " + toString(this) + " missing LC_ID_DYLIB load command");
11275ffd83dbSDimitry Andric     return;
11285ffd83dbSDimitry Andric   }
11295ffd83dbSDimitry Andric 
1130fe6060f1SDimitry Andric   if (config->printEachFile)
1131fe6060f1SDimitry Andric     message(toString(this));
1132fe6060f1SDimitry Andric   inputFiles.insert(this);
1133fe6060f1SDimitry Andric 
1134fe6060f1SDimitry Andric   deadStrippable = hdr->flags & MH_DEAD_STRIPPABLE_DYLIB;
1135fe6060f1SDimitry Andric 
1136fe6060f1SDimitry Andric   if (!checkCompatibility(this))
1137fe6060f1SDimitry Andric     return;
1138fe6060f1SDimitry Andric 
1139fe6060f1SDimitry Andric   checkAppExtensionSafety(hdr->flags & MH_APP_EXTENSION_SAFE);
1140fe6060f1SDimitry Andric 
1141fe6060f1SDimitry Andric   for (auto *cmd : findCommands<rpath_command>(hdr, LC_RPATH)) {
1142fe6060f1SDimitry Andric     StringRef rpath{reinterpret_cast<const char *>(cmd) + cmd->path};
1143fe6060f1SDimitry Andric     rpaths.push_back(rpath);
1144fe6060f1SDimitry Andric   }
1145fe6060f1SDimitry Andric 
11465ffd83dbSDimitry Andric   // Initialize symbols.
1147fe6060f1SDimitry Andric   exportingFile = isImplicitlyLinked(installName) ? this : this->umbrella;
11485ffd83dbSDimitry Andric   if (const load_command *cmd = findCommand(hdr, LC_DYLD_INFO_ONLY)) {
11495ffd83dbSDimitry Andric     auto *c = reinterpret_cast<const dyld_info_command *>(cmd);
1150*0eae32dcSDimitry Andric     struct TrieEntry {
1151*0eae32dcSDimitry Andric       StringRef name;
1152*0eae32dcSDimitry Andric       uint64_t flags;
1153*0eae32dcSDimitry Andric     };
1154*0eae32dcSDimitry Andric 
1155*0eae32dcSDimitry Andric     std::vector<TrieEntry> entries;
1156*0eae32dcSDimitry Andric     // Find all the $ld$* symbols to process first.
11575ffd83dbSDimitry Andric     parseTrie(buf + c->export_off, c->export_size,
11585ffd83dbSDimitry Andric               [&](const Twine &name, uint64_t flags) {
1159fe6060f1SDimitry Andric                 StringRef savedName = saver.save(name);
1160fe6060f1SDimitry Andric                 if (handleLDSymbol(savedName))
1161fe6060f1SDimitry Andric                   return;
1162*0eae32dcSDimitry Andric                 entries.push_back({savedName, flags});
11635ffd83dbSDimitry Andric               });
1164*0eae32dcSDimitry Andric 
1165*0eae32dcSDimitry Andric     // Process the "normal" symbols.
1166*0eae32dcSDimitry Andric     for (TrieEntry &entry : entries) {
1167*0eae32dcSDimitry Andric       if (exportingFile->hiddenSymbols.contains(
1168*0eae32dcSDimitry Andric               CachedHashStringRef(entry.name)))
1169*0eae32dcSDimitry Andric         continue;
1170*0eae32dcSDimitry Andric 
1171*0eae32dcSDimitry Andric       bool isWeakDef = entry.flags & EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION;
1172*0eae32dcSDimitry Andric       bool isTlv = entry.flags & EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL;
1173*0eae32dcSDimitry Andric 
1174*0eae32dcSDimitry Andric       symbols.push_back(
1175*0eae32dcSDimitry Andric           symtab->addDylib(entry.name, exportingFile, isWeakDef, isTlv));
1176*0eae32dcSDimitry Andric     }
1177*0eae32dcSDimitry Andric 
11785ffd83dbSDimitry Andric   } else {
1179e8d8bef9SDimitry Andric     error("LC_DYLD_INFO_ONLY not found in " + toString(this));
11805ffd83dbSDimitry Andric     return;
11815ffd83dbSDimitry Andric   }
1182fe6060f1SDimitry Andric }
11835ffd83dbSDimitry Andric 
1184fe6060f1SDimitry Andric void DylibFile::parseLoadCommands(MemoryBufferRef mb) {
1185fe6060f1SDimitry Andric   auto *hdr = reinterpret_cast<const mach_header *>(mb.getBufferStart());
1186fe6060f1SDimitry Andric   const uint8_t *p = reinterpret_cast<const uint8_t *>(mb.getBufferStart()) +
1187fe6060f1SDimitry Andric                      target->headerSize;
11885ffd83dbSDimitry Andric   for (uint32_t i = 0, n = hdr->ncmds; i < n; ++i) {
11895ffd83dbSDimitry Andric     auto *cmd = reinterpret_cast<const load_command *>(p);
11905ffd83dbSDimitry Andric     p += cmd->cmdsize;
11915ffd83dbSDimitry Andric 
1192fe6060f1SDimitry Andric     if (!(hdr->flags & MH_NO_REEXPORTED_DYLIBS) &&
1193fe6060f1SDimitry Andric         cmd->cmd == LC_REEXPORT_DYLIB) {
1194fe6060f1SDimitry Andric       const auto *c = reinterpret_cast<const dylib_command *>(cmd);
11955ffd83dbSDimitry Andric       StringRef reexportPath =
11965ffd83dbSDimitry Andric           reinterpret_cast<const char *>(c) + read32le(&c->dylib.name);
1197fe6060f1SDimitry Andric       loadReexport(reexportPath, exportingFile, nullptr);
1198fe6060f1SDimitry Andric     }
1199fe6060f1SDimitry Andric 
1200fe6060f1SDimitry Andric     // FIXME: What about LC_LOAD_UPWARD_DYLIB, LC_LAZY_LOAD_DYLIB,
1201fe6060f1SDimitry Andric     // LC_LOAD_WEAK_DYLIB, LC_REEXPORT_DYLIB (..are reexports from dylibs with
1202fe6060f1SDimitry Andric     // MH_NO_REEXPORTED_DYLIBS loaded for -flat_namespace)?
1203fe6060f1SDimitry Andric     if (config->namespaceKind == NamespaceKind::flat &&
1204fe6060f1SDimitry Andric         cmd->cmd == LC_LOAD_DYLIB) {
1205fe6060f1SDimitry Andric       const auto *c = reinterpret_cast<const dylib_command *>(cmd);
1206fe6060f1SDimitry Andric       StringRef dylibPath =
1207fe6060f1SDimitry Andric           reinterpret_cast<const char *>(c) + read32le(&c->dylib.name);
1208fe6060f1SDimitry Andric       DylibFile *dylib = findDylib(dylibPath, umbrella, nullptr);
1209fe6060f1SDimitry Andric       if (!dylib)
1210fe6060f1SDimitry Andric         error(Twine("unable to locate library '") + dylibPath +
1211fe6060f1SDimitry Andric               "' loaded from '" + toString(this) + "' for -flat_namespace");
1212fe6060f1SDimitry Andric     }
12135ffd83dbSDimitry Andric   }
12145ffd83dbSDimitry Andric }
12155ffd83dbSDimitry Andric 
1216fe6060f1SDimitry Andric // Some versions of XCode ship with .tbd files that don't have the right
1217fe6060f1SDimitry Andric // platform settings.
1218fe6060f1SDimitry Andric static constexpr std::array<StringRef, 3> skipPlatformChecks{
1219fe6060f1SDimitry Andric     "/usr/lib/system/libsystem_kernel.dylib",
1220fe6060f1SDimitry Andric     "/usr/lib/system/libsystem_platform.dylib",
1221fe6060f1SDimitry Andric     "/usr/lib/system/libsystem_pthread.dylib"};
1222fe6060f1SDimitry Andric 
1223fe6060f1SDimitry Andric DylibFile::DylibFile(const InterfaceFile &interface, DylibFile *umbrella,
1224fe6060f1SDimitry Andric                      bool isBundleLoader)
1225fe6060f1SDimitry Andric     : InputFile(DylibKind, interface), refState(RefState::Unreferenced),
1226fe6060f1SDimitry Andric       isBundleLoader(isBundleLoader) {
1227fe6060f1SDimitry Andric   // FIXME: Add test for the missing TBD code path.
1228fe6060f1SDimitry Andric 
12295ffd83dbSDimitry Andric   if (umbrella == nullptr)
12305ffd83dbSDimitry Andric     umbrella = this;
1231fe6060f1SDimitry Andric   this->umbrella = umbrella;
12325ffd83dbSDimitry Andric 
1233fe6060f1SDimitry Andric   installName = saver.save(interface.getInstallName());
1234e8d8bef9SDimitry Andric   compatibilityVersion = interface.getCompatibilityVersion().rawValue();
1235e8d8bef9SDimitry Andric   currentVersion = interface.getCurrentVersion().rawValue();
1236fe6060f1SDimitry Andric 
1237fe6060f1SDimitry Andric   if (config->printEachFile)
1238fe6060f1SDimitry Andric     message(toString(this));
1239fe6060f1SDimitry Andric   inputFiles.insert(this);
1240fe6060f1SDimitry Andric 
1241fe6060f1SDimitry Andric   if (!is_contained(skipPlatformChecks, installName) &&
1242fe6060f1SDimitry Andric       !is_contained(interface.targets(), config->platformInfo.target)) {
1243fe6060f1SDimitry Andric     error(toString(this) + " is incompatible with " +
1244fe6060f1SDimitry Andric           std::string(config->platformInfo.target));
1245fe6060f1SDimitry Andric     return;
1246fe6060f1SDimitry Andric   }
1247fe6060f1SDimitry Andric 
1248fe6060f1SDimitry Andric   checkAppExtensionSafety(interface.isApplicationExtensionSafe());
1249fe6060f1SDimitry Andric 
1250fe6060f1SDimitry Andric   exportingFile = isImplicitlyLinked(installName) ? this : umbrella;
1251e8d8bef9SDimitry Andric   auto addSymbol = [&](const Twine &name) -> void {
1252*0eae32dcSDimitry Andric     StringRef savedName = saver.save(name);
1253*0eae32dcSDimitry Andric     if (exportingFile->hiddenSymbols.contains(CachedHashStringRef(savedName)))
1254*0eae32dcSDimitry Andric       return;
1255*0eae32dcSDimitry Andric 
1256*0eae32dcSDimitry Andric     symbols.push_back(symtab->addDylib(savedName, exportingFile,
1257e8d8bef9SDimitry Andric                                        /*isWeakDef=*/false,
1258e8d8bef9SDimitry Andric                                        /*isTlv=*/false));
1259e8d8bef9SDimitry Andric   };
1260*0eae32dcSDimitry Andric 
1261*0eae32dcSDimitry Andric   std::vector<const llvm::MachO::Symbol *> normalSymbols;
1262*0eae32dcSDimitry Andric   normalSymbols.reserve(interface.symbolsCount());
1263fe6060f1SDimitry Andric   for (const auto *symbol : interface.symbols()) {
1264fe6060f1SDimitry Andric     if (!symbol->getArchitectures().has(config->arch()))
1265fe6060f1SDimitry Andric       continue;
1266fe6060f1SDimitry Andric     if (handleLDSymbol(symbol->getName()))
1267e8d8bef9SDimitry Andric       continue;
1268e8d8bef9SDimitry Andric 
1269e8d8bef9SDimitry Andric     switch (symbol->getKind()) {
1270*0eae32dcSDimitry Andric     case SymbolKind::GlobalSymbol:               // Fallthrough
1271*0eae32dcSDimitry Andric     case SymbolKind::ObjectiveCClass:            // Fallthrough
1272*0eae32dcSDimitry Andric     case SymbolKind::ObjectiveCClassEHType:      // Fallthrough
1273*0eae32dcSDimitry Andric     case SymbolKind::ObjectiveCInstanceVariable: // Fallthrough
1274*0eae32dcSDimitry Andric       normalSymbols.push_back(symbol);
1275*0eae32dcSDimitry Andric     }
1276*0eae32dcSDimitry Andric   }
1277*0eae32dcSDimitry Andric 
1278*0eae32dcSDimitry Andric   // TODO(compnerd) filter out symbols based on the target platform
1279*0eae32dcSDimitry Andric   // TODO: handle weak defs, thread locals
1280*0eae32dcSDimitry Andric   for (const auto *symbol : normalSymbols) {
1281*0eae32dcSDimitry Andric     switch (symbol->getKind()) {
1282e8d8bef9SDimitry Andric     case SymbolKind::GlobalSymbol:
1283e8d8bef9SDimitry Andric       addSymbol(symbol->getName());
1284e8d8bef9SDimitry Andric       break;
1285e8d8bef9SDimitry Andric     case SymbolKind::ObjectiveCClass:
1286e8d8bef9SDimitry Andric       // XXX ld64 only creates these symbols when -ObjC is passed in. We may
1287e8d8bef9SDimitry Andric       // want to emulate that.
1288e8d8bef9SDimitry Andric       addSymbol(objc::klass + symbol->getName());
1289e8d8bef9SDimitry Andric       addSymbol(objc::metaclass + symbol->getName());
1290e8d8bef9SDimitry Andric       break;
1291e8d8bef9SDimitry Andric     case SymbolKind::ObjectiveCClassEHType:
1292e8d8bef9SDimitry Andric       addSymbol(objc::ehtype + symbol->getName());
1293e8d8bef9SDimitry Andric       break;
1294e8d8bef9SDimitry Andric     case SymbolKind::ObjectiveCInstanceVariable:
1295e8d8bef9SDimitry Andric       addSymbol(objc::ivar + symbol->getName());
1296e8d8bef9SDimitry Andric       break;
1297e8d8bef9SDimitry Andric     }
12985ffd83dbSDimitry Andric   }
1299e8d8bef9SDimitry Andric }
1300e8d8bef9SDimitry Andric 
1301fe6060f1SDimitry Andric void DylibFile::parseReexports(const InterfaceFile &interface) {
1302fe6060f1SDimitry Andric   const InterfaceFile *topLevel =
1303fe6060f1SDimitry Andric       interface.getParent() == nullptr ? &interface : interface.getParent();
1304349cc55cSDimitry Andric   for (const InterfaceFileRef &intfRef : interface.reexportedLibraries()) {
1305fe6060f1SDimitry Andric     InterfaceFile::const_target_range targets = intfRef.targets();
1306fe6060f1SDimitry Andric     if (is_contained(skipPlatformChecks, intfRef.getInstallName()) ||
1307fe6060f1SDimitry Andric         is_contained(targets, config->platformInfo.target))
1308fe6060f1SDimitry Andric       loadReexport(intfRef.getInstallName(), exportingFile, topLevel);
1309fe6060f1SDimitry Andric   }
1310fe6060f1SDimitry Andric }
1311e8d8bef9SDimitry Andric 
1312fe6060f1SDimitry Andric // $ld$ symbols modify the properties/behavior of the library (e.g. its install
1313fe6060f1SDimitry Andric // name, compatibility version or hide/add symbols) for specific target
1314fe6060f1SDimitry Andric // versions.
1315fe6060f1SDimitry Andric bool DylibFile::handleLDSymbol(StringRef originalName) {
1316fe6060f1SDimitry Andric   if (!originalName.startswith("$ld$"))
1317fe6060f1SDimitry Andric     return false;
1318fe6060f1SDimitry Andric 
1319fe6060f1SDimitry Andric   StringRef action;
1320fe6060f1SDimitry Andric   StringRef name;
1321fe6060f1SDimitry Andric   std::tie(action, name) = originalName.drop_front(strlen("$ld$")).split('$');
1322fe6060f1SDimitry Andric   if (action == "previous")
1323fe6060f1SDimitry Andric     handleLDPreviousSymbol(name, originalName);
1324fe6060f1SDimitry Andric   else if (action == "install_name")
1325fe6060f1SDimitry Andric     handleLDInstallNameSymbol(name, originalName);
1326*0eae32dcSDimitry Andric   else if (action == "hide")
1327*0eae32dcSDimitry Andric     handleLDHideSymbol(name, originalName);
1328fe6060f1SDimitry Andric   return true;
1329fe6060f1SDimitry Andric }
1330fe6060f1SDimitry Andric 
1331fe6060f1SDimitry Andric void DylibFile::handleLDPreviousSymbol(StringRef name, StringRef originalName) {
1332fe6060f1SDimitry Andric   // originalName: $ld$ previous $ <installname> $ <compatversion> $
1333fe6060f1SDimitry Andric   // <platformstr> $ <startversion> $ <endversion> $ <symbol-name> $
1334fe6060f1SDimitry Andric   StringRef installName;
1335fe6060f1SDimitry Andric   StringRef compatVersion;
1336fe6060f1SDimitry Andric   StringRef platformStr;
1337fe6060f1SDimitry Andric   StringRef startVersion;
1338fe6060f1SDimitry Andric   StringRef endVersion;
1339fe6060f1SDimitry Andric   StringRef symbolName;
1340fe6060f1SDimitry Andric   StringRef rest;
1341fe6060f1SDimitry Andric 
1342fe6060f1SDimitry Andric   std::tie(installName, name) = name.split('$');
1343fe6060f1SDimitry Andric   std::tie(compatVersion, name) = name.split('$');
1344fe6060f1SDimitry Andric   std::tie(platformStr, name) = name.split('$');
1345fe6060f1SDimitry Andric   std::tie(startVersion, name) = name.split('$');
1346fe6060f1SDimitry Andric   std::tie(endVersion, name) = name.split('$');
1347fe6060f1SDimitry Andric   std::tie(symbolName, rest) = name.split('$');
1348fe6060f1SDimitry Andric   // TODO: ld64 contains some logic for non-empty symbolName as well.
1349fe6060f1SDimitry Andric   if (!symbolName.empty())
1350fe6060f1SDimitry Andric     return;
1351fe6060f1SDimitry Andric   unsigned platform;
1352fe6060f1SDimitry Andric   if (platformStr.getAsInteger(10, platform) ||
1353fe6060f1SDimitry Andric       platform != static_cast<unsigned>(config->platform()))
1354fe6060f1SDimitry Andric     return;
1355fe6060f1SDimitry Andric 
1356fe6060f1SDimitry Andric   VersionTuple start;
1357fe6060f1SDimitry Andric   if (start.tryParse(startVersion)) {
1358fe6060f1SDimitry Andric     warn("failed to parse start version, symbol '" + originalName +
1359fe6060f1SDimitry Andric          "' ignored");
1360fe6060f1SDimitry Andric     return;
1361fe6060f1SDimitry Andric   }
1362fe6060f1SDimitry Andric   VersionTuple end;
1363fe6060f1SDimitry Andric   if (end.tryParse(endVersion)) {
1364fe6060f1SDimitry Andric     warn("failed to parse end version, symbol '" + originalName + "' ignored");
1365fe6060f1SDimitry Andric     return;
1366fe6060f1SDimitry Andric   }
1367fe6060f1SDimitry Andric   if (config->platformInfo.minimum < start ||
1368fe6060f1SDimitry Andric       config->platformInfo.minimum >= end)
1369fe6060f1SDimitry Andric     return;
1370fe6060f1SDimitry Andric 
1371fe6060f1SDimitry Andric   this->installName = saver.save(installName);
1372fe6060f1SDimitry Andric 
1373fe6060f1SDimitry Andric   if (!compatVersion.empty()) {
1374fe6060f1SDimitry Andric     VersionTuple cVersion;
1375fe6060f1SDimitry Andric     if (cVersion.tryParse(compatVersion)) {
1376fe6060f1SDimitry Andric       warn("failed to parse compatibility version, symbol '" + originalName +
1377fe6060f1SDimitry Andric            "' ignored");
1378fe6060f1SDimitry Andric       return;
1379fe6060f1SDimitry Andric     }
1380fe6060f1SDimitry Andric     compatibilityVersion = encodeVersion(cVersion);
1381fe6060f1SDimitry Andric   }
1382fe6060f1SDimitry Andric }
1383fe6060f1SDimitry Andric 
1384fe6060f1SDimitry Andric void DylibFile::handleLDInstallNameSymbol(StringRef name,
1385fe6060f1SDimitry Andric                                           StringRef originalName) {
1386fe6060f1SDimitry Andric   // originalName: $ld$ install_name $ os<version> $ install_name
1387fe6060f1SDimitry Andric   StringRef condition, installName;
1388fe6060f1SDimitry Andric   std::tie(condition, installName) = name.split('$');
1389fe6060f1SDimitry Andric   VersionTuple version;
1390fe6060f1SDimitry Andric   if (!condition.consume_front("os") || version.tryParse(condition))
1391fe6060f1SDimitry Andric     warn("failed to parse os version, symbol '" + originalName + "' ignored");
1392fe6060f1SDimitry Andric   else if (version == config->platformInfo.minimum)
1393fe6060f1SDimitry Andric     this->installName = saver.save(installName);
1394fe6060f1SDimitry Andric }
1395fe6060f1SDimitry Andric 
1396*0eae32dcSDimitry Andric void DylibFile::handleLDHideSymbol(StringRef name, StringRef originalName) {
1397*0eae32dcSDimitry Andric   StringRef symbolName;
1398*0eae32dcSDimitry Andric   bool shouldHide = true;
1399*0eae32dcSDimitry Andric   if (name.startswith("os")) {
1400*0eae32dcSDimitry Andric     // If it's hidden based on versions.
1401*0eae32dcSDimitry Andric     name = name.drop_front(2);
1402*0eae32dcSDimitry Andric     StringRef minVersion;
1403*0eae32dcSDimitry Andric     std::tie(minVersion, symbolName) = name.split('$');
1404*0eae32dcSDimitry Andric     VersionTuple versionTup;
1405*0eae32dcSDimitry Andric     if (versionTup.tryParse(minVersion)) {
1406*0eae32dcSDimitry Andric       warn("Failed to parse hidden version, symbol `" + originalName +
1407*0eae32dcSDimitry Andric            "` ignored.");
1408*0eae32dcSDimitry Andric       return;
1409*0eae32dcSDimitry Andric     }
1410*0eae32dcSDimitry Andric     shouldHide = versionTup == config->platformInfo.minimum;
1411*0eae32dcSDimitry Andric   } else {
1412*0eae32dcSDimitry Andric     symbolName = name;
1413*0eae32dcSDimitry Andric   }
1414*0eae32dcSDimitry Andric 
1415*0eae32dcSDimitry Andric   if (shouldHide)
1416*0eae32dcSDimitry Andric     exportingFile->hiddenSymbols.insert(CachedHashStringRef(symbolName));
1417*0eae32dcSDimitry Andric }
1418*0eae32dcSDimitry Andric 
1419fe6060f1SDimitry Andric void DylibFile::checkAppExtensionSafety(bool dylibIsAppExtensionSafe) const {
1420fe6060f1SDimitry Andric   if (config->applicationExtension && !dylibIsAppExtensionSafe)
1421fe6060f1SDimitry Andric     warn("using '-application_extension' with unsafe dylib: " + toString(this));
1422e8d8bef9SDimitry Andric }
1423e8d8bef9SDimitry Andric 
1424e8d8bef9SDimitry Andric ArchiveFile::ArchiveFile(std::unique_ptr<object::Archive> &&f)
1425349cc55cSDimitry Andric     : InputFile(ArchiveKind, f->getMemoryBufferRef()), file(std::move(f)) {}
1426349cc55cSDimitry Andric 
1427349cc55cSDimitry Andric void ArchiveFile::addLazySymbols() {
14285ffd83dbSDimitry Andric   for (const object::Archive::Symbol &sym : file->symbols())
14295ffd83dbSDimitry Andric     symtab->addLazy(sym.getName(), this, sym);
14305ffd83dbSDimitry Andric }
14315ffd83dbSDimitry Andric 
1432349cc55cSDimitry Andric static Expected<InputFile *> loadArchiveMember(MemoryBufferRef mb,
1433349cc55cSDimitry Andric                                                uint32_t modTime,
1434349cc55cSDimitry Andric                                                StringRef archiveName,
1435349cc55cSDimitry Andric                                                uint64_t offsetInArchive) {
1436349cc55cSDimitry Andric   if (config->zeroModTime)
1437349cc55cSDimitry Andric     modTime = 0;
1438349cc55cSDimitry Andric 
1439349cc55cSDimitry Andric   switch (identify_magic(mb.getBuffer())) {
1440349cc55cSDimitry Andric   case file_magic::macho_object:
1441349cc55cSDimitry Andric     return make<ObjFile>(mb, modTime, archiveName);
1442349cc55cSDimitry Andric   case file_magic::bitcode:
1443349cc55cSDimitry Andric     return make<BitcodeFile>(mb, archiveName, offsetInArchive);
1444349cc55cSDimitry Andric   default:
1445349cc55cSDimitry Andric     return createStringError(inconvertibleErrorCode(),
1446349cc55cSDimitry Andric                              mb.getBufferIdentifier() +
1447349cc55cSDimitry Andric                                  " has unhandled file type");
1448349cc55cSDimitry Andric   }
1449349cc55cSDimitry Andric }
1450349cc55cSDimitry Andric 
1451349cc55cSDimitry Andric Error ArchiveFile::fetch(const object::Archive::Child &c, StringRef reason) {
1452349cc55cSDimitry Andric   if (!seen.insert(c.getChildOffset()).second)
1453349cc55cSDimitry Andric     return Error::success();
1454349cc55cSDimitry Andric 
1455349cc55cSDimitry Andric   Expected<MemoryBufferRef> mb = c.getMemoryBufferRef();
1456349cc55cSDimitry Andric   if (!mb)
1457349cc55cSDimitry Andric     return mb.takeError();
1458349cc55cSDimitry Andric 
1459349cc55cSDimitry Andric   // Thin archives refer to .o files, so --reproduce needs the .o files too.
1460349cc55cSDimitry Andric   if (tar && c.getParent()->isThin())
1461349cc55cSDimitry Andric     tar->append(relativeToRoot(CHECK(c.getFullName(), this)), mb->getBuffer());
1462349cc55cSDimitry Andric 
1463349cc55cSDimitry Andric   Expected<TimePoint<std::chrono::seconds>> modTime = c.getLastModified();
1464349cc55cSDimitry Andric   if (!modTime)
1465349cc55cSDimitry Andric     return modTime.takeError();
1466349cc55cSDimitry Andric 
1467349cc55cSDimitry Andric   Expected<InputFile *> file =
1468349cc55cSDimitry Andric       loadArchiveMember(*mb, toTimeT(*modTime), getName(), c.getChildOffset());
1469349cc55cSDimitry Andric 
1470349cc55cSDimitry Andric   if (!file)
1471349cc55cSDimitry Andric     return file.takeError();
1472349cc55cSDimitry Andric 
1473349cc55cSDimitry Andric   inputFiles.insert(*file);
1474349cc55cSDimitry Andric   printArchiveMemberLoad(reason, *file);
1475349cc55cSDimitry Andric   return Error::success();
1476349cc55cSDimitry Andric }
1477349cc55cSDimitry Andric 
14785ffd83dbSDimitry Andric void ArchiveFile::fetch(const object::Archive::Symbol &sym) {
14795ffd83dbSDimitry Andric   object::Archive::Child c =
14805ffd83dbSDimitry Andric       CHECK(sym.getMember(), toString(this) +
1481349cc55cSDimitry Andric                                  ": could not get the member defining symbol " +
1482e8d8bef9SDimitry Andric                                  toMachOString(sym));
14835ffd83dbSDimitry Andric 
1484fe6060f1SDimitry Andric   // `sym` is owned by a LazySym, which will be replace<>()d by make<ObjFile>
1485e8d8bef9SDimitry Andric   // and become invalid after that call. Copy it to the stack so we can refer
1486e8d8bef9SDimitry Andric   // to it later.
1487fe6060f1SDimitry Andric   const object::Archive::Symbol symCopy = sym;
1488e8d8bef9SDimitry Andric 
1489fe6060f1SDimitry Andric   // ld64 doesn't demangle sym here even with -demangle.
1490fe6060f1SDimitry Andric   // Match that: intentionally don't call toMachOString().
1491349cc55cSDimitry Andric   if (Error e = fetch(c, symCopy.getName()))
1492349cc55cSDimitry Andric     error(toString(this) + ": could not get the member defining symbol " +
1493349cc55cSDimitry Andric           toMachOString(symCopy) + ": " + toString(std::move(e)));
14945ffd83dbSDimitry Andric }
14955ffd83dbSDimitry Andric 
1496fe6060f1SDimitry Andric static macho::Symbol *createBitcodeSymbol(const lto::InputFile::Symbol &objSym,
1497fe6060f1SDimitry Andric                                           BitcodeFile &file) {
1498fe6060f1SDimitry Andric   StringRef name = saver.save(objSym.getName());
1499fe6060f1SDimitry Andric 
1500fe6060f1SDimitry Andric   if (objSym.isUndefined())
1501*0eae32dcSDimitry Andric     return symtab->addUndefined(name, &file, /*isWeakRef=*/objSym.isWeak());
1502fe6060f1SDimitry Andric 
1503fe6060f1SDimitry Andric   // TODO: Write a test demonstrating why computing isPrivateExtern before
1504fe6060f1SDimitry Andric   // LTO compilation is important.
1505fe6060f1SDimitry Andric   bool isPrivateExtern = false;
1506fe6060f1SDimitry Andric   switch (objSym.getVisibility()) {
1507fe6060f1SDimitry Andric   case GlobalValue::HiddenVisibility:
1508fe6060f1SDimitry Andric     isPrivateExtern = true;
1509fe6060f1SDimitry Andric     break;
1510fe6060f1SDimitry Andric   case GlobalValue::ProtectedVisibility:
1511fe6060f1SDimitry Andric     error(name + " has protected visibility, which is not supported by Mach-O");
1512fe6060f1SDimitry Andric     break;
1513fe6060f1SDimitry Andric   case GlobalValue::DefaultVisibility:
1514fe6060f1SDimitry Andric     break;
1515fe6060f1SDimitry Andric   }
1516fe6060f1SDimitry Andric 
1517349cc55cSDimitry Andric   if (objSym.isCommon())
1518349cc55cSDimitry Andric     return symtab->addCommon(name, &file, objSym.getCommonSize(),
1519349cc55cSDimitry Andric                              objSym.getCommonAlignment(), isPrivateExtern);
1520349cc55cSDimitry Andric 
1521fe6060f1SDimitry Andric   return symtab->addDefined(name, &file, /*isec=*/nullptr, /*value=*/0,
1522fe6060f1SDimitry Andric                             /*size=*/0, objSym.isWeak(), isPrivateExtern,
1523fe6060f1SDimitry Andric                             /*isThumb=*/false,
1524fe6060f1SDimitry Andric                             /*isReferencedDynamically=*/false,
1525349cc55cSDimitry Andric                             /*noDeadStrip=*/false,
1526349cc55cSDimitry Andric                             /*isWeakDefCanBeHidden=*/false);
1527fe6060f1SDimitry Andric }
1528fe6060f1SDimitry Andric 
1529fe6060f1SDimitry Andric BitcodeFile::BitcodeFile(MemoryBufferRef mb, StringRef archiveName,
1530fe6060f1SDimitry Andric                          uint64_t offsetInArchive)
1531fe6060f1SDimitry Andric     : InputFile(BitcodeKind, mb) {
1532*0eae32dcSDimitry Andric   this->archiveName = std::string(archiveName);
1533fe6060f1SDimitry Andric   std::string path = mb.getBufferIdentifier().str();
1534fe6060f1SDimitry Andric   // ThinLTO assumes that all MemoryBufferRefs given to it have a unique
1535fe6060f1SDimitry Andric   // name. If two members with the same name are provided, this causes a
1536fe6060f1SDimitry Andric   // collision and ThinLTO can't proceed.
1537fe6060f1SDimitry Andric   // So, we append the archive name to disambiguate two members with the same
1538fe6060f1SDimitry Andric   // name from multiple different archives, and offset within the archive to
1539fe6060f1SDimitry Andric   // disambiguate two members of the same name from a single archive.
1540fe6060f1SDimitry Andric   MemoryBufferRef mbref(
1541fe6060f1SDimitry Andric       mb.getBuffer(),
1542fe6060f1SDimitry Andric       saver.save(archiveName.empty() ? path
1543fe6060f1SDimitry Andric                                      : archiveName + sys::path::filename(path) +
1544fe6060f1SDimitry Andric                                            utostr(offsetInArchive)));
1545fe6060f1SDimitry Andric 
1546e8d8bef9SDimitry Andric   obj = check(lto::InputFile::create(mbref));
1547fe6060f1SDimitry Andric 
1548fe6060f1SDimitry Andric   // Convert LTO Symbols to LLD Symbols in order to perform resolution. The
1549fe6060f1SDimitry Andric   // "winning" symbol will then be marked as Prevailing at LTO compilation
1550fe6060f1SDimitry Andric   // time.
1551fe6060f1SDimitry Andric   for (const lto::InputFile::Symbol &objSym : obj->symbols())
1552fe6060f1SDimitry Andric     symbols.push_back(createBitcodeSymbol(objSym, *this));
15535ffd83dbSDimitry Andric }
1554fe6060f1SDimitry Andric 
1555fe6060f1SDimitry Andric template void ObjFile::parse<LP64>();
1556