xref: /freebsd/contrib/llvm-project/lld/MachO/InputFiles.cpp (revision bc7512cc58af2e8bbe5bbf5ca0059b1daa1da897)
1 //===- InputFiles.cpp -----------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains functions to parse Mach-O object files. In this comment,
10 // we describe the Mach-O file structure and how we parse it.
11 //
12 // Mach-O is not very different from ELF or COFF. The notion of symbols,
13 // sections and relocations exists in Mach-O as it does in ELF and COFF.
14 //
15 // Perhaps the notion that is new to those who know ELF/COFF is "subsections".
16 // In ELF/COFF, sections are an atomic unit of data copied from input files to
17 // output files. When we merge or garbage-collect sections, we treat each
18 // section as an atomic unit. In Mach-O, that's not the case. Sections can
19 // consist of multiple subsections, and subsections are a unit of merging and
20 // garbage-collecting. Therefore, Mach-O's subsections are more similar to
21 // ELF/COFF's sections than Mach-O's sections are.
22 //
23 // A section can have multiple symbols. A symbol that does not have the
24 // N_ALT_ENTRY attribute indicates a beginning of a subsection. Therefore, by
25 // definition, a symbol is always present at the beginning of each subsection. A
26 // symbol with N_ALT_ENTRY attribute does not start a new subsection and can
27 // point to a middle of a subsection.
28 //
29 // The notion of subsections also affects how relocations are represented in
30 // Mach-O. All references within a section need to be explicitly represented as
31 // relocations if they refer to different subsections, because we obviously need
32 // to fix up addresses if subsections are laid out in an output file differently
33 // than they were in object files. To represent that, Mach-O relocations can
34 // refer to an unnamed location via its address. Scattered relocations (those
35 // with the R_SCATTERED bit set) always refer to unnamed locations.
36 // Non-scattered relocations refer to an unnamed location if r_extern is not set
37 // and r_symbolnum is zero.
38 //
39 // Without the above differences, I think you can use your knowledge about ELF
40 // and COFF for Mach-O.
41 //
42 //===----------------------------------------------------------------------===//
43 
44 #include "InputFiles.h"
45 #include "Config.h"
46 #include "Driver.h"
47 #include "Dwarf.h"
48 #include "ExportTrie.h"
49 #include "InputSection.h"
50 #include "MachOStructs.h"
51 #include "ObjC.h"
52 #include "OutputSection.h"
53 #include "OutputSegment.h"
54 #include "SymbolTable.h"
55 #include "Symbols.h"
56 #include "SyntheticSections.h"
57 #include "Target.h"
58 
59 #include "lld/Common/CommonLinkerContext.h"
60 #include "lld/Common/DWARF.h"
61 #include "lld/Common/Reproduce.h"
62 #include "llvm/ADT/iterator.h"
63 #include "llvm/BinaryFormat/MachO.h"
64 #include "llvm/LTO/LTO.h"
65 #include "llvm/Support/BinaryStreamReader.h"
66 #include "llvm/Support/Endian.h"
67 #include "llvm/Support/MemoryBuffer.h"
68 #include "llvm/Support/Path.h"
69 #include "llvm/Support/TarWriter.h"
70 #include "llvm/Support/TimeProfiler.h"
71 #include "llvm/TextAPI/Architecture.h"
72 #include "llvm/TextAPI/InterfaceFile.h"
73 
74 #include <type_traits>
75 
76 using namespace llvm;
77 using namespace llvm::MachO;
78 using namespace llvm::support::endian;
79 using namespace llvm::sys;
80 using namespace lld;
81 using namespace lld::macho;
82 
83 // Returns "<internal>", "foo.a(bar.o)", or "baz.o".
84 std::string lld::toString(const InputFile *f) {
85   if (!f)
86     return "<internal>";
87 
88   // Multiple dylibs can be defined in one .tbd file.
89   if (auto dylibFile = dyn_cast<DylibFile>(f))
90     if (f->getName().endswith(".tbd"))
91       return (f->getName() + "(" + dylibFile->installName + ")").str();
92 
93   if (f->archiveName.empty())
94     return std::string(f->getName());
95   return (f->archiveName + "(" + path::filename(f->getName()) + ")").str();
96 }
97 
98 SetVector<InputFile *> macho::inputFiles;
99 std::unique_ptr<TarWriter> macho::tar;
100 int InputFile::idCount = 0;
101 
102 static VersionTuple decodeVersion(uint32_t version) {
103   unsigned major = version >> 16;
104   unsigned minor = (version >> 8) & 0xffu;
105   unsigned subMinor = version & 0xffu;
106   return VersionTuple(major, minor, subMinor);
107 }
108 
109 static std::vector<PlatformInfo> getPlatformInfos(const InputFile *input) {
110   if (!isa<ObjFile>(input) && !isa<DylibFile>(input))
111     return {};
112 
113   const char *hdr = input->mb.getBufferStart();
114 
115   std::vector<PlatformInfo> platformInfos;
116   for (auto *cmd : findCommands<build_version_command>(hdr, LC_BUILD_VERSION)) {
117     PlatformInfo info;
118     info.target.Platform = static_cast<PlatformType>(cmd->platform);
119     info.minimum = decodeVersion(cmd->minos);
120     platformInfos.emplace_back(std::move(info));
121   }
122   for (auto *cmd : findCommands<version_min_command>(
123            hdr, LC_VERSION_MIN_MACOSX, LC_VERSION_MIN_IPHONEOS,
124            LC_VERSION_MIN_TVOS, LC_VERSION_MIN_WATCHOS)) {
125     PlatformInfo info;
126     switch (cmd->cmd) {
127     case LC_VERSION_MIN_MACOSX:
128       info.target.Platform = PLATFORM_MACOS;
129       break;
130     case LC_VERSION_MIN_IPHONEOS:
131       info.target.Platform = PLATFORM_IOS;
132       break;
133     case LC_VERSION_MIN_TVOS:
134       info.target.Platform = PLATFORM_TVOS;
135       break;
136     case LC_VERSION_MIN_WATCHOS:
137       info.target.Platform = PLATFORM_WATCHOS;
138       break;
139     }
140     info.minimum = decodeVersion(cmd->version);
141     platformInfos.emplace_back(std::move(info));
142   }
143 
144   return platformInfos;
145 }
146 
147 static bool checkCompatibility(const InputFile *input) {
148   std::vector<PlatformInfo> platformInfos = getPlatformInfos(input);
149   if (platformInfos.empty())
150     return true;
151 
152   auto it = find_if(platformInfos, [&](const PlatformInfo &info) {
153     return removeSimulator(info.target.Platform) ==
154            removeSimulator(config->platform());
155   });
156   if (it == platformInfos.end()) {
157     std::string platformNames;
158     raw_string_ostream os(platformNames);
159     interleave(
160         platformInfos, os,
161         [&](const PlatformInfo &info) {
162           os << getPlatformName(info.target.Platform);
163         },
164         "/");
165     error(toString(input) + " has platform " + platformNames +
166           Twine(", which is different from target platform ") +
167           getPlatformName(config->platform()));
168     return false;
169   }
170 
171   if (it->minimum > config->platformInfo.minimum)
172     warn(toString(input) + " has version " + it->minimum.getAsString() +
173          ", which is newer than target minimum of " +
174          config->platformInfo.minimum.getAsString());
175 
176   return true;
177 }
178 
179 // This cache mostly exists to store system libraries (and .tbds) as they're
180 // loaded, rather than the input archives, which are already cached at a higher
181 // level, and other files like the filelist that are only read once.
182 // Theoretically this caching could be more efficient by hoisting it, but that
183 // would require altering many callers to track the state.
184 DenseMap<CachedHashStringRef, MemoryBufferRef> macho::cachedReads;
185 // Open a given file path and return it as a memory-mapped file.
186 Optional<MemoryBufferRef> macho::readFile(StringRef path) {
187   CachedHashStringRef key(path);
188   auto entry = cachedReads.find(key);
189   if (entry != cachedReads.end())
190     return entry->second;
191 
192   ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr = MemoryBuffer::getFile(path);
193   if (std::error_code ec = mbOrErr.getError()) {
194     error("cannot open " + path + ": " + ec.message());
195     return None;
196   }
197 
198   std::unique_ptr<MemoryBuffer> &mb = *mbOrErr;
199   MemoryBufferRef mbref = mb->getMemBufferRef();
200   make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take mb ownership
201 
202   // If this is a regular non-fat file, return it.
203   const char *buf = mbref.getBufferStart();
204   const auto *hdr = reinterpret_cast<const fat_header *>(buf);
205   if (mbref.getBufferSize() < sizeof(uint32_t) ||
206       read32be(&hdr->magic) != FAT_MAGIC) {
207     if (tar)
208       tar->append(relativeToRoot(path), mbref.getBuffer());
209     return cachedReads[key] = mbref;
210   }
211 
212   llvm::BumpPtrAllocator &bAlloc = lld::bAlloc();
213 
214   // Object files and archive files may be fat files, which contain multiple
215   // real files for different CPU ISAs. Here, we search for a file that matches
216   // with the current link target and returns it as a MemoryBufferRef.
217   const auto *arch = reinterpret_cast<const fat_arch *>(buf + sizeof(*hdr));
218 
219   for (uint32_t i = 0, n = read32be(&hdr->nfat_arch); i < n; ++i) {
220     if (reinterpret_cast<const char *>(arch + i + 1) >
221         buf + mbref.getBufferSize()) {
222       error(path + ": fat_arch struct extends beyond end of file");
223       return None;
224     }
225 
226     if (read32be(&arch[i].cputype) != static_cast<uint32_t>(target->cpuType) ||
227         read32be(&arch[i].cpusubtype) != target->cpuSubtype)
228       continue;
229 
230     uint32_t offset = read32be(&arch[i].offset);
231     uint32_t size = read32be(&arch[i].size);
232     if (offset + size > mbref.getBufferSize())
233       error(path + ": slice extends beyond end of file");
234     if (tar)
235       tar->append(relativeToRoot(path), mbref.getBuffer());
236     return cachedReads[key] = MemoryBufferRef(StringRef(buf + offset, size),
237                                               path.copy(bAlloc));
238   }
239 
240   error("unable to find matching architecture in " + path);
241   return None;
242 }
243 
244 InputFile::InputFile(Kind kind, const InterfaceFile &interface)
245     : id(idCount++), fileKind(kind), name(saver().save(interface.getPath())) {}
246 
247 // Some sections comprise of fixed-size records, so instead of splitting them at
248 // symbol boundaries, we split them based on size. Records are distinct from
249 // literals in that they may contain references to other sections, instead of
250 // being leaf nodes in the InputSection graph.
251 //
252 // Note that "record" is a term I came up with. In contrast, "literal" is a term
253 // used by the Mach-O format.
254 static Optional<size_t> getRecordSize(StringRef segname, StringRef name) {
255   if (name == section_names::cfString) {
256     if (config->icfLevel != ICFLevel::none && segname == segment_names::data)
257       return target->wordSize == 8 ? 32 : 16;
258   } else if (name == section_names::compactUnwind) {
259     if (segname == segment_names::ld)
260       return target->wordSize == 8 ? 32 : 20;
261   }
262   return {};
263 }
264 
265 // Parse the sequence of sections within a single LC_SEGMENT(_64).
266 // Split each section into subsections.
267 template <class SectionHeader>
268 void ObjFile::parseSections(ArrayRef<SectionHeader> sectionHeaders) {
269   sections.reserve(sectionHeaders.size());
270   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
271 
272   for (const SectionHeader &sec : sectionHeaders) {
273     StringRef name =
274         StringRef(sec.sectname, strnlen(sec.sectname, sizeof(sec.sectname)));
275     StringRef segname =
276         StringRef(sec.segname, strnlen(sec.segname, sizeof(sec.segname)));
277     ArrayRef<uint8_t> data = {isZeroFill(sec.flags) ? nullptr
278                                                     : buf + sec.offset,
279                               static_cast<size_t>(sec.size)};
280     if (sec.align >= 32) {
281       error("alignment " + std::to_string(sec.align) + " of section " + name +
282             " is too large");
283       sections.push_back(sec.addr);
284       continue;
285     }
286     uint32_t align = 1 << sec.align;
287     uint32_t flags = sec.flags;
288 
289     auto splitRecords = [&](int recordSize) -> void {
290       sections.push_back(sec.addr);
291       if (data.empty())
292         return;
293       Subsections &subsections = sections.back().subsections;
294       subsections.reserve(data.size() / recordSize);
295       auto *isec = make<ConcatInputSection>(
296           segname, name, this, data.slice(0, recordSize), align, flags);
297       subsections.push_back({0, isec});
298       for (uint64_t off = recordSize; off < data.size(); off += recordSize) {
299         // Copying requires less memory than constructing a fresh InputSection.
300         auto *copy = make<ConcatInputSection>(*isec);
301         copy->data = data.slice(off, recordSize);
302         subsections.push_back({off, copy});
303       }
304     };
305 
306     if (sectionType(sec.flags) == S_CSTRING_LITERALS ||
307         (config->dedupLiterals && isWordLiteralSection(sec.flags))) {
308       if (sec.nreloc && config->dedupLiterals)
309         fatal(toString(this) + " contains relocations in " + sec.segname + "," +
310               sec.sectname +
311               ", so LLD cannot deduplicate literals. Try re-running without "
312               "--deduplicate-literals.");
313 
314       InputSection *isec;
315       if (sectionType(sec.flags) == S_CSTRING_LITERALS) {
316         isec =
317             make<CStringInputSection>(segname, name, this, data, align, flags);
318         // FIXME: parallelize this?
319         cast<CStringInputSection>(isec)->splitIntoPieces();
320       } else {
321         isec = make<WordLiteralInputSection>(segname, name, this, data, align,
322                                              flags);
323       }
324       sections.push_back(sec.addr);
325       sections.back().subsections.push_back({0, isec});
326     } else if (auto recordSize = getRecordSize(segname, name)) {
327       splitRecords(*recordSize);
328       if (name == section_names::compactUnwind)
329         compactUnwindSection = &sections.back();
330     } else if (segname == segment_names::llvm) {
331       if (name == "__cg_profile" && config->callGraphProfileSort) {
332         TimeTraceScope timeScope("Parsing call graph section");
333         BinaryStreamReader reader(data, support::little);
334         while (!reader.empty()) {
335           uint32_t fromIndex, toIndex;
336           uint64_t count;
337           if (Error err = reader.readInteger(fromIndex))
338             fatal(toString(this) + ": Expected 32-bit integer");
339           if (Error err = reader.readInteger(toIndex))
340             fatal(toString(this) + ": Expected 32-bit integer");
341           if (Error err = reader.readInteger(count))
342             fatal(toString(this) + ": Expected 64-bit integer");
343           callGraph.emplace_back();
344           CallGraphEntry &entry = callGraph.back();
345           entry.fromIndex = fromIndex;
346           entry.toIndex = toIndex;
347           entry.count = count;
348         }
349       }
350       // ld64 does not appear to emit contents from sections within the __LLVM
351       // segment. Symbols within those sections point to bitcode metadata
352       // instead of actual symbols. Global symbols within those sections could
353       // have the same name without causing duplicate symbol errors. Push an
354       // empty entry to ensure indices line up for the remaining sections.
355       // TODO: Evaluate whether the bitcode metadata is needed.
356       sections.push_back(sec.addr);
357     } else {
358       auto *isec =
359           make<ConcatInputSection>(segname, name, this, data, align, flags);
360       if (isDebugSection(isec->getFlags()) &&
361           isec->getSegName() == segment_names::dwarf) {
362         // Instead of emitting DWARF sections, we emit STABS symbols to the
363         // object files that contain them. We filter them out early to avoid
364         // parsing their relocations unnecessarily. But we must still push an
365         // empty entry to ensure the indices line up for the remaining sections.
366         sections.push_back(sec.addr);
367         debugSections.push_back(isec);
368       } else {
369         sections.push_back(sec.addr);
370         sections.back().subsections.push_back({0, isec});
371       }
372     }
373   }
374 }
375 
376 // Find the subsection corresponding to the greatest section offset that is <=
377 // that of the given offset.
378 //
379 // offset: an offset relative to the start of the original InputSection (before
380 // any subsection splitting has occurred). It will be updated to represent the
381 // same location as an offset relative to the start of the containing
382 // subsection.
383 template <class T>
384 static InputSection *findContainingSubsection(const Subsections &subsections,
385                                               T *offset) {
386   static_assert(std::is_same<uint64_t, T>::value ||
387                     std::is_same<uint32_t, T>::value,
388                 "unexpected type for offset");
389   auto it = std::prev(llvm::upper_bound(
390       subsections, *offset,
391       [](uint64_t value, Subsection subsec) { return value < subsec.offset; }));
392   *offset -= it->offset;
393   return it->isec;
394 }
395 
396 template <class SectionHeader>
397 static bool validateRelocationInfo(InputFile *file, const SectionHeader &sec,
398                                    relocation_info rel) {
399   const RelocAttrs &relocAttrs = target->getRelocAttrs(rel.r_type);
400   bool valid = true;
401   auto message = [relocAttrs, file, sec, rel, &valid](const Twine &diagnostic) {
402     valid = false;
403     return (relocAttrs.name + " relocation " + diagnostic + " at offset " +
404             std::to_string(rel.r_address) + " of " + sec.segname + "," +
405             sec.sectname + " in " + toString(file))
406         .str();
407   };
408 
409   if (!relocAttrs.hasAttr(RelocAttrBits::LOCAL) && !rel.r_extern)
410     error(message("must be extern"));
411   if (relocAttrs.hasAttr(RelocAttrBits::PCREL) != rel.r_pcrel)
412     error(message(Twine("must ") + (rel.r_pcrel ? "not " : "") +
413                   "be PC-relative"));
414   if (isThreadLocalVariables(sec.flags) &&
415       !relocAttrs.hasAttr(RelocAttrBits::UNSIGNED))
416     error(message("not allowed in thread-local section, must be UNSIGNED"));
417   if (rel.r_length < 2 || rel.r_length > 3 ||
418       !relocAttrs.hasAttr(static_cast<RelocAttrBits>(1 << rel.r_length))) {
419     static SmallVector<StringRef, 4> widths{"0", "4", "8", "4 or 8"};
420     error(message("has width " + std::to_string(1 << rel.r_length) +
421                   " bytes, but must be " +
422                   widths[(static_cast<int>(relocAttrs.bits) >> 2) & 3] +
423                   " bytes"));
424   }
425   return valid;
426 }
427 
428 template <class SectionHeader>
429 void ObjFile::parseRelocations(ArrayRef<SectionHeader> sectionHeaders,
430                                const SectionHeader &sec,
431                                Subsections &subsections) {
432   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
433   ArrayRef<relocation_info> relInfos(
434       reinterpret_cast<const relocation_info *>(buf + sec.reloff), sec.nreloc);
435 
436   auto subsecIt = subsections.rbegin();
437   for (size_t i = 0; i < relInfos.size(); i++) {
438     // Paired relocations serve as Mach-O's method for attaching a
439     // supplemental datum to a primary relocation record. ELF does not
440     // need them because the *_RELOC_RELA records contain the extra
441     // addend field, vs. *_RELOC_REL which omit the addend.
442     //
443     // The {X86_64,ARM64}_RELOC_SUBTRACTOR record holds the subtrahend,
444     // and the paired *_RELOC_UNSIGNED record holds the minuend. The
445     // datum for each is a symbolic address. The result is the offset
446     // between two addresses.
447     //
448     // The ARM64_RELOC_ADDEND record holds the addend, and the paired
449     // ARM64_RELOC_BRANCH26 or ARM64_RELOC_PAGE21/PAGEOFF12 holds the
450     // base symbolic address.
451     //
452     // Note: X86 does not use *_RELOC_ADDEND because it can embed an
453     // addend into the instruction stream. On X86, a relocatable address
454     // field always occupies an entire contiguous sequence of byte(s),
455     // so there is no need to merge opcode bits with address
456     // bits. Therefore, it's easy and convenient to store addends in the
457     // instruction-stream bytes that would otherwise contain zeroes. By
458     // contrast, RISC ISAs such as ARM64 mix opcode bits with with
459     // address bits so that bitwise arithmetic is necessary to extract
460     // and insert them. Storing addends in the instruction stream is
461     // possible, but inconvenient and more costly at link time.
462 
463     relocation_info relInfo = relInfos[i];
464     bool isSubtrahend =
465         target->hasAttr(relInfo.r_type, RelocAttrBits::SUBTRAHEND);
466     if (isSubtrahend && StringRef(sec.sectname) == section_names::ehFrame) {
467       // __TEXT,__eh_frame only has symbols and SUBTRACTOR relocs when ld64 -r
468       // adds local "EH_Frame1" and "func.eh". Ignore them because they have
469       // gone unused by Mac OS since Snow Leopard (10.6), vintage 2009.
470       ++i;
471       continue;
472     }
473     int64_t pairedAddend = 0;
474     if (target->hasAttr(relInfo.r_type, RelocAttrBits::ADDEND)) {
475       pairedAddend = SignExtend64<24>(relInfo.r_symbolnum);
476       relInfo = relInfos[++i];
477     }
478     assert(i < relInfos.size());
479     if (!validateRelocationInfo(this, sec, relInfo))
480       continue;
481     if (relInfo.r_address & R_SCATTERED)
482       fatal("TODO: Scattered relocations not supported");
483 
484     int64_t embeddedAddend = target->getEmbeddedAddend(mb, sec.offset, relInfo);
485     assert(!(embeddedAddend && pairedAddend));
486     int64_t totalAddend = pairedAddend + embeddedAddend;
487     Reloc r;
488     r.type = relInfo.r_type;
489     r.pcrel = relInfo.r_pcrel;
490     r.length = relInfo.r_length;
491     r.offset = relInfo.r_address;
492     if (relInfo.r_extern) {
493       r.referent = symbols[relInfo.r_symbolnum];
494       r.addend = isSubtrahend ? 0 : totalAddend;
495     } else {
496       assert(!isSubtrahend);
497       const SectionHeader &referentSecHead =
498           sectionHeaders[relInfo.r_symbolnum - 1];
499       uint64_t referentOffset;
500       if (relInfo.r_pcrel) {
501         // The implicit addend for pcrel section relocations is the pcrel offset
502         // in terms of the addresses in the input file. Here we adjust it so
503         // that it describes the offset from the start of the referent section.
504         // FIXME This logic was written around x86_64 behavior -- ARM64 doesn't
505         // have pcrel section relocations. We may want to factor this out into
506         // the arch-specific .cpp file.
507         assert(target->hasAttr(r.type, RelocAttrBits::BYTE4));
508         referentOffset = sec.addr + relInfo.r_address + 4 + totalAddend -
509                          referentSecHead.addr;
510       } else {
511         // The addend for a non-pcrel relocation is its absolute address.
512         referentOffset = totalAddend - referentSecHead.addr;
513       }
514       Subsections &referentSubsections =
515           sections[relInfo.r_symbolnum - 1].subsections;
516       r.referent =
517           findContainingSubsection(referentSubsections, &referentOffset);
518       r.addend = referentOffset;
519     }
520 
521     // Find the subsection that this relocation belongs to.
522     // Though not required by the Mach-O format, clang and gcc seem to emit
523     // relocations in order, so let's take advantage of it. However, ld64 emits
524     // unsorted relocations (in `-r` mode), so we have a fallback for that
525     // uncommon case.
526     InputSection *subsec;
527     while (subsecIt != subsections.rend() && subsecIt->offset > r.offset)
528       ++subsecIt;
529     if (subsecIt == subsections.rend() ||
530         subsecIt->offset + subsecIt->isec->getSize() <= r.offset) {
531       subsec = findContainingSubsection(subsections, &r.offset);
532       // Now that we know the relocs are unsorted, avoid trying the 'fast path'
533       // for the other relocations.
534       subsecIt = subsections.rend();
535     } else {
536       subsec = subsecIt->isec;
537       r.offset -= subsecIt->offset;
538     }
539     subsec->relocs.push_back(r);
540 
541     if (isSubtrahend) {
542       relocation_info minuendInfo = relInfos[++i];
543       // SUBTRACTOR relocations should always be followed by an UNSIGNED one
544       // attached to the same address.
545       assert(target->hasAttr(minuendInfo.r_type, RelocAttrBits::UNSIGNED) &&
546              relInfo.r_address == minuendInfo.r_address);
547       Reloc p;
548       p.type = minuendInfo.r_type;
549       if (minuendInfo.r_extern) {
550         p.referent = symbols[minuendInfo.r_symbolnum];
551         p.addend = totalAddend;
552       } else {
553         uint64_t referentOffset =
554             totalAddend - sectionHeaders[minuendInfo.r_symbolnum - 1].addr;
555         Subsections &referentSubsectVec =
556             sections[minuendInfo.r_symbolnum - 1].subsections;
557         p.referent =
558             findContainingSubsection(referentSubsectVec, &referentOffset);
559         p.addend = referentOffset;
560       }
561       subsec->relocs.push_back(p);
562     }
563   }
564 }
565 
566 template <class NList>
567 static macho::Symbol *createDefined(const NList &sym, StringRef name,
568                                     InputSection *isec, uint64_t value,
569                                     uint64_t size) {
570   // Symbol scope is determined by sym.n_type & (N_EXT | N_PEXT):
571   // N_EXT: Global symbols. These go in the symbol table during the link,
572   //        and also in the export table of the output so that the dynamic
573   //        linker sees them.
574   // N_EXT | N_PEXT: Linkage unit (think: dylib) scoped. These go in the
575   //                 symbol table during the link so that duplicates are
576   //                 either reported (for non-weak symbols) or merged
577   //                 (for weak symbols), but they do not go in the export
578   //                 table of the output.
579   // N_PEXT: llvm-mc does not emit these, but `ld -r` (wherein ld64 emits
580   //         object files) may produce them. LLD does not yet support -r.
581   //         These are translation-unit scoped, identical to the `0` case.
582   // 0: Translation-unit scoped. These are not in the symbol table during
583   //    link, and not in the export table of the output either.
584   bool isWeakDefCanBeHidden =
585       (sym.n_desc & (N_WEAK_DEF | N_WEAK_REF)) == (N_WEAK_DEF | N_WEAK_REF);
586 
587   if (sym.n_type & N_EXT) {
588     bool isPrivateExtern = sym.n_type & N_PEXT;
589     // lld's behavior for merging symbols is slightly different from ld64:
590     // ld64 picks the winning symbol based on several criteria (see
591     // pickBetweenRegularAtoms() in ld64's SymbolTable.cpp), while lld
592     // just merges metadata and keeps the contents of the first symbol
593     // with that name (see SymbolTable::addDefined). For:
594     // * inline function F in a TU built with -fvisibility-inlines-hidden
595     // * and inline function F in another TU built without that flag
596     // ld64 will pick the one from the file built without
597     // -fvisibility-inlines-hidden.
598     // lld will instead pick the one listed first on the link command line and
599     // give it visibility as if the function was built without
600     // -fvisibility-inlines-hidden.
601     // If both functions have the same contents, this will have the same
602     // behavior. If not, it won't, but the input had an ODR violation in
603     // that case.
604     //
605     // Similarly, merging a symbol
606     // that's isPrivateExtern and not isWeakDefCanBeHidden with one
607     // that's not isPrivateExtern but isWeakDefCanBeHidden technically
608     // should produce one
609     // that's not isPrivateExtern but isWeakDefCanBeHidden. That matters
610     // with ld64's semantics, because it means the non-private-extern
611     // definition will continue to take priority if more private extern
612     // definitions are encountered. With lld's semantics there's no observable
613     // difference between a symbol that's isWeakDefCanBeHidden(autohide) or one
614     // that's privateExtern -- neither makes it into the dynamic symbol table,
615     // unless the autohide symbol is explicitly exported.
616     // But if a symbol is both privateExtern and autohide then it can't
617     // be exported.
618     // So we nullify the autohide flag when privateExtern is present
619     // and promote the symbol to privateExtern when it is not already.
620     if (isWeakDefCanBeHidden && isPrivateExtern)
621       isWeakDefCanBeHidden = false;
622     else if (isWeakDefCanBeHidden)
623       isPrivateExtern = true;
624     return symtab->addDefined(
625         name, isec->getFile(), isec, value, size, sym.n_desc & N_WEAK_DEF,
626         isPrivateExtern, sym.n_desc & N_ARM_THUMB_DEF,
627         sym.n_desc & REFERENCED_DYNAMICALLY, sym.n_desc & N_NO_DEAD_STRIP,
628         isWeakDefCanBeHidden);
629   }
630   assert(!isWeakDefCanBeHidden &&
631          "weak_def_can_be_hidden on already-hidden symbol?");
632   return make<Defined>(
633       name, isec->getFile(), isec, value, size, sym.n_desc & N_WEAK_DEF,
634       /*isExternal=*/false, /*isPrivateExtern=*/false,
635       sym.n_desc & N_ARM_THUMB_DEF, sym.n_desc & REFERENCED_DYNAMICALLY,
636       sym.n_desc & N_NO_DEAD_STRIP);
637 }
638 
639 // Absolute symbols are defined symbols that do not have an associated
640 // InputSection. They cannot be weak.
641 template <class NList>
642 static macho::Symbol *createAbsolute(const NList &sym, InputFile *file,
643                                      StringRef name) {
644   if (sym.n_type & N_EXT) {
645     return symtab->addDefined(
646         name, file, nullptr, sym.n_value, /*size=*/0,
647         /*isWeakDef=*/false, sym.n_type & N_PEXT, sym.n_desc & N_ARM_THUMB_DEF,
648         /*isReferencedDynamically=*/false, sym.n_desc & N_NO_DEAD_STRIP,
649         /*isWeakDefCanBeHidden=*/false);
650   }
651   return make<Defined>(name, file, nullptr, sym.n_value, /*size=*/0,
652                        /*isWeakDef=*/false,
653                        /*isExternal=*/false, /*isPrivateExtern=*/false,
654                        sym.n_desc & N_ARM_THUMB_DEF,
655                        /*isReferencedDynamically=*/false,
656                        sym.n_desc & N_NO_DEAD_STRIP);
657 }
658 
659 template <class NList>
660 macho::Symbol *ObjFile::parseNonSectionSymbol(const NList &sym,
661                                               StringRef name) {
662   uint8_t type = sym.n_type & N_TYPE;
663   switch (type) {
664   case N_UNDF:
665     return sym.n_value == 0
666                ? symtab->addUndefined(name, this, sym.n_desc & N_WEAK_REF)
667                : symtab->addCommon(name, this, sym.n_value,
668                                    1 << GET_COMM_ALIGN(sym.n_desc),
669                                    sym.n_type & N_PEXT);
670   case N_ABS:
671     return createAbsolute(sym, this, name);
672   case N_PBUD:
673   case N_INDR:
674     error("TODO: support symbols of type " + std::to_string(type));
675     return nullptr;
676   case N_SECT:
677     llvm_unreachable(
678         "N_SECT symbols should not be passed to parseNonSectionSymbol");
679   default:
680     llvm_unreachable("invalid symbol type");
681   }
682 }
683 
684 template <class NList> static bool isUndef(const NList &sym) {
685   return (sym.n_type & N_TYPE) == N_UNDF && sym.n_value == 0;
686 }
687 
688 template <class LP>
689 void ObjFile::parseSymbols(ArrayRef<typename LP::section> sectionHeaders,
690                            ArrayRef<typename LP::nlist> nList,
691                            const char *strtab, bool subsectionsViaSymbols) {
692   using NList = typename LP::nlist;
693 
694   // Groups indices of the symbols by the sections that contain them.
695   std::vector<std::vector<uint32_t>> symbolsBySection(sections.size());
696   symbols.resize(nList.size());
697   SmallVector<unsigned, 32> undefineds;
698   for (uint32_t i = 0; i < nList.size(); ++i) {
699     const NList &sym = nList[i];
700 
701     // Ignore debug symbols for now.
702     // FIXME: may need special handling.
703     if (sym.n_type & N_STAB)
704       continue;
705 
706     StringRef name = strtab + sym.n_strx;
707     if ((sym.n_type & N_TYPE) == N_SECT) {
708       Subsections &subsections = sections[sym.n_sect - 1].subsections;
709       // parseSections() may have chosen not to parse this section.
710       if (subsections.empty())
711         continue;
712       symbolsBySection[sym.n_sect - 1].push_back(i);
713     } else if (isUndef(sym)) {
714       undefineds.push_back(i);
715     } else {
716       symbols[i] = parseNonSectionSymbol(sym, name);
717     }
718   }
719 
720   for (size_t i = 0; i < sections.size(); ++i) {
721     Subsections &subsections = sections[i].subsections;
722     if (subsections.empty())
723       continue;
724     InputSection *lastIsec = subsections.back().isec;
725     if (lastIsec->getName() == section_names::ehFrame) {
726       // __TEXT,__eh_frame only has symbols and SUBTRACTOR relocs when ld64 -r
727       // adds local "EH_Frame1" and "func.eh". Ignore them because they have
728       // gone unused by Mac OS since Snow Leopard (10.6), vintage 2009.
729       continue;
730     }
731     std::vector<uint32_t> &symbolIndices = symbolsBySection[i];
732     uint64_t sectionAddr = sectionHeaders[i].addr;
733     uint32_t sectionAlign = 1u << sectionHeaders[i].align;
734 
735     // Record-based sections have already been split into subsections during
736     // parseSections(), so we simply need to match Symbols to the corresponding
737     // subsection here.
738     if (getRecordSize(lastIsec->getSegName(), lastIsec->getName())) {
739       for (size_t j = 0; j < symbolIndices.size(); ++j) {
740         uint32_t symIndex = symbolIndices[j];
741         const NList &sym = nList[symIndex];
742         StringRef name = strtab + sym.n_strx;
743         uint64_t symbolOffset = sym.n_value - sectionAddr;
744         InputSection *isec =
745             findContainingSubsection(subsections, &symbolOffset);
746         if (symbolOffset != 0) {
747           error(toString(lastIsec) + ":  symbol " + name +
748                 " at misaligned offset");
749           continue;
750         }
751         symbols[symIndex] = createDefined(sym, name, isec, 0, isec->getSize());
752       }
753       continue;
754     }
755 
756     // Calculate symbol sizes and create subsections by splitting the sections
757     // along symbol boundaries.
758     // We populate subsections by repeatedly splitting the last (highest
759     // address) subsection.
760     llvm::stable_sort(symbolIndices, [&](uint32_t lhs, uint32_t rhs) {
761       return nList[lhs].n_value < nList[rhs].n_value;
762     });
763     for (size_t j = 0; j < symbolIndices.size(); ++j) {
764       uint32_t symIndex = symbolIndices[j];
765       const NList &sym = nList[symIndex];
766       StringRef name = strtab + sym.n_strx;
767       Subsection &subsec = subsections.back();
768       InputSection *isec = subsec.isec;
769 
770       uint64_t subsecAddr = sectionAddr + subsec.offset;
771       size_t symbolOffset = sym.n_value - subsecAddr;
772       uint64_t symbolSize =
773           j + 1 < symbolIndices.size()
774               ? nList[symbolIndices[j + 1]].n_value - sym.n_value
775               : isec->data.size() - symbolOffset;
776       // There are 4 cases where we do not need to create a new subsection:
777       //   1. If the input file does not use subsections-via-symbols.
778       //   2. Multiple symbols at the same address only induce one subsection.
779       //      (The symbolOffset == 0 check covers both this case as well as
780       //      the first loop iteration.)
781       //   3. Alternative entry points do not induce new subsections.
782       //   4. If we have a literal section (e.g. __cstring and __literal4).
783       if (!subsectionsViaSymbols || symbolOffset == 0 ||
784           sym.n_desc & N_ALT_ENTRY || !isa<ConcatInputSection>(isec)) {
785         symbols[symIndex] =
786             createDefined(sym, name, isec, symbolOffset, symbolSize);
787         continue;
788       }
789       auto *concatIsec = cast<ConcatInputSection>(isec);
790 
791       auto *nextIsec = make<ConcatInputSection>(*concatIsec);
792       nextIsec->wasCoalesced = false;
793       if (isZeroFill(isec->getFlags())) {
794         // Zero-fill sections have NULL data.data() non-zero data.size()
795         nextIsec->data = {nullptr, isec->data.size() - symbolOffset};
796         isec->data = {nullptr, symbolOffset};
797       } else {
798         nextIsec->data = isec->data.slice(symbolOffset);
799         isec->data = isec->data.slice(0, symbolOffset);
800       }
801 
802       // By construction, the symbol will be at offset zero in the new
803       // subsection.
804       symbols[symIndex] =
805           createDefined(sym, name, nextIsec, /*value=*/0, symbolSize);
806       // TODO: ld64 appears to preserve the original alignment as well as each
807       // subsection's offset from the last aligned address. We should consider
808       // emulating that behavior.
809       nextIsec->align = MinAlign(sectionAlign, sym.n_value);
810       subsections.push_back({sym.n_value - sectionAddr, nextIsec});
811     }
812   }
813 
814   // Undefined symbols can trigger recursive fetch from Archives due to
815   // LazySymbols. Process defined symbols first so that the relative order
816   // between a defined symbol and an undefined symbol does not change the
817   // symbol resolution behavior. In addition, a set of interconnected symbols
818   // will all be resolved to the same file, instead of being resolved to
819   // different files.
820   for (unsigned i : undefineds) {
821     const NList &sym = nList[i];
822     StringRef name = strtab + sym.n_strx;
823     symbols[i] = parseNonSectionSymbol(sym, name);
824   }
825 }
826 
827 OpaqueFile::OpaqueFile(MemoryBufferRef mb, StringRef segName,
828                        StringRef sectName)
829     : InputFile(OpaqueKind, mb) {
830   const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
831   ArrayRef<uint8_t> data = {buf, mb.getBufferSize()};
832   ConcatInputSection *isec =
833       make<ConcatInputSection>(segName.take_front(16), sectName.take_front(16),
834                                /*file=*/this, data);
835   isec->live = true;
836   sections.push_back(0);
837   sections.back().subsections.push_back({0, isec});
838 }
839 
840 ObjFile::ObjFile(MemoryBufferRef mb, uint32_t modTime, StringRef archiveName,
841                  bool lazy)
842     : InputFile(ObjKind, mb, lazy), modTime(modTime) {
843   this->archiveName = std::string(archiveName);
844   if (lazy) {
845     if (target->wordSize == 8)
846       parseLazy<LP64>();
847     else
848       parseLazy<ILP32>();
849   } else {
850     if (target->wordSize == 8)
851       parse<LP64>();
852     else
853       parse<ILP32>();
854   }
855 }
856 
857 template <class LP> void ObjFile::parse() {
858   using Header = typename LP::mach_header;
859   using SegmentCommand = typename LP::segment_command;
860   using SectionHeader = typename LP::section;
861   using NList = typename LP::nlist;
862 
863   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
864   auto *hdr = reinterpret_cast<const Header *>(mb.getBufferStart());
865 
866   Architecture arch = getArchitectureFromCpuType(hdr->cputype, hdr->cpusubtype);
867   if (arch != config->arch()) {
868     auto msg = config->errorForArchMismatch
869                    ? static_cast<void (*)(const Twine &)>(error)
870                    : warn;
871     msg(toString(this) + " has architecture " + getArchitectureName(arch) +
872         " which is incompatible with target architecture " +
873         getArchitectureName(config->arch()));
874     return;
875   }
876 
877   if (!checkCompatibility(this))
878     return;
879 
880   for (auto *cmd : findCommands<linker_option_command>(hdr, LC_LINKER_OPTION)) {
881     StringRef data{reinterpret_cast<const char *>(cmd + 1),
882                    cmd->cmdsize - sizeof(linker_option_command)};
883     parseLCLinkerOption(this, cmd->count, data);
884   }
885 
886   ArrayRef<SectionHeader> sectionHeaders;
887   if (const load_command *cmd = findCommand(hdr, LP::segmentLCType)) {
888     auto *c = reinterpret_cast<const SegmentCommand *>(cmd);
889     sectionHeaders = ArrayRef<SectionHeader>{
890         reinterpret_cast<const SectionHeader *>(c + 1), c->nsects};
891     parseSections(sectionHeaders);
892   }
893 
894   // TODO: Error on missing LC_SYMTAB?
895   if (const load_command *cmd = findCommand(hdr, LC_SYMTAB)) {
896     auto *c = reinterpret_cast<const symtab_command *>(cmd);
897     ArrayRef<NList> nList(reinterpret_cast<const NList *>(buf + c->symoff),
898                           c->nsyms);
899     const char *strtab = reinterpret_cast<const char *>(buf) + c->stroff;
900     bool subsectionsViaSymbols = hdr->flags & MH_SUBSECTIONS_VIA_SYMBOLS;
901     parseSymbols<LP>(sectionHeaders, nList, strtab, subsectionsViaSymbols);
902   }
903 
904   // The relocations may refer to the symbols, so we parse them after we have
905   // parsed all the symbols.
906   for (size_t i = 0, n = sections.size(); i < n; ++i)
907     if (!sections[i].subsections.empty())
908       parseRelocations(sectionHeaders, sectionHeaders[i],
909                        sections[i].subsections);
910 
911   parseDebugInfo();
912   if (compactUnwindSection)
913     registerCompactUnwind();
914 }
915 
916 template <class LP> void ObjFile::parseLazy() {
917   using Header = typename LP::mach_header;
918   using NList = typename LP::nlist;
919 
920   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
921   auto *hdr = reinterpret_cast<const Header *>(mb.getBufferStart());
922   const load_command *cmd = findCommand(hdr, LC_SYMTAB);
923   if (!cmd)
924     return;
925   auto *c = reinterpret_cast<const symtab_command *>(cmd);
926   ArrayRef<NList> nList(reinterpret_cast<const NList *>(buf + c->symoff),
927                         c->nsyms);
928   const char *strtab = reinterpret_cast<const char *>(buf) + c->stroff;
929   symbols.resize(nList.size());
930   for (auto it : llvm::enumerate(nList)) {
931     const NList &sym = it.value();
932     if ((sym.n_type & N_EXT) && !isUndef(sym)) {
933       // TODO: Bound checking
934       StringRef name = strtab + sym.n_strx;
935       symbols[it.index()] = symtab->addLazyObject(name, *this);
936       if (!lazy)
937         break;
938     }
939   }
940 }
941 
942 void ObjFile::parseDebugInfo() {
943   std::unique_ptr<DwarfObject> dObj = DwarfObject::create(this);
944   if (!dObj)
945     return;
946 
947   auto *ctx = make<DWARFContext>(
948       std::move(dObj), "",
949       [&](Error err) {
950         warn(toString(this) + ": " + toString(std::move(err)));
951       },
952       [&](Error warning) {
953         warn(toString(this) + ": " + toString(std::move(warning)));
954       });
955 
956   // TODO: Since object files can contain a lot of DWARF info, we should verify
957   // that we are parsing just the info we need
958   const DWARFContext::compile_unit_range &units = ctx->compile_units();
959   // FIXME: There can be more than one compile unit per object file. See
960   // PR48637.
961   auto it = units.begin();
962   compileUnit = it->get();
963 }
964 
965 ArrayRef<data_in_code_entry> ObjFile::getDataInCode() const {
966   const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
967   const load_command *cmd = findCommand(buf, LC_DATA_IN_CODE);
968   if (!cmd)
969     return {};
970   const auto *c = reinterpret_cast<const linkedit_data_command *>(cmd);
971   return {reinterpret_cast<const data_in_code_entry *>(buf + c->dataoff),
972           c->datasize / sizeof(data_in_code_entry)};
973 }
974 
975 // Create pointers from symbols to their associated compact unwind entries.
976 void ObjFile::registerCompactUnwind() {
977   for (const Subsection &subsection : compactUnwindSection->subsections) {
978     ConcatInputSection *isec = cast<ConcatInputSection>(subsection.isec);
979     // Hack!! Since each CUE contains a different function address, if ICF
980     // operated naively and compared the entire contents of each CUE, entries
981     // with identical unwind info but belonging to different functions would
982     // never be considered equivalent. To work around this problem, we slice
983     // away the function address here. (Note that we do not adjust the offsets
984     // of the corresponding relocations.) We rely on `relocateCompactUnwind()`
985     // to correctly handle these truncated input sections.
986     isec->data = isec->data.slice(target->wordSize);
987 
988     ConcatInputSection *referentIsec;
989     for (auto it = isec->relocs.begin(); it != isec->relocs.end();) {
990       Reloc &r = *it;
991       // CUE::functionAddress is at offset 0. Skip personality & LSDA relocs.
992       if (r.offset != 0) {
993         ++it;
994         continue;
995       }
996       uint64_t add = r.addend;
997       if (auto *sym = cast_or_null<Defined>(r.referent.dyn_cast<Symbol *>())) {
998         // Check whether the symbol defined in this file is the prevailing one.
999         // Skip if it is e.g. a weak def that didn't prevail.
1000         if (sym->getFile() != this) {
1001           ++it;
1002           continue;
1003         }
1004         add += sym->value;
1005         referentIsec = cast<ConcatInputSection>(sym->isec);
1006       } else {
1007         referentIsec =
1008             cast<ConcatInputSection>(r.referent.dyn_cast<InputSection *>());
1009       }
1010       if (referentIsec->getSegName() != segment_names::text)
1011         error("compact unwind references address in " + toString(referentIsec) +
1012               " which is not in segment __TEXT");
1013       // The functionAddress relocations are typically section relocations.
1014       // However, unwind info operates on a per-symbol basis, so we search for
1015       // the function symbol here.
1016       auto symIt = llvm::lower_bound(
1017           referentIsec->symbols, add,
1018           [](Defined *d, uint64_t add) { return d->value < add; });
1019       // The relocation should point at the exact address of a symbol (with no
1020       // addend).
1021       if (symIt == referentIsec->symbols.end() || (*symIt)->value != add) {
1022         assert(referentIsec->wasCoalesced);
1023         ++it;
1024         continue;
1025       }
1026       (*symIt)->unwindEntry = isec;
1027       // Since we've sliced away the functionAddress, we should remove the
1028       // corresponding relocation too. Given that clang emits relocations in
1029       // reverse order of address, this relocation should be at the end of the
1030       // vector for most of our input object files, so this is typically an O(1)
1031       // operation.
1032       it = isec->relocs.erase(it);
1033     }
1034   }
1035 }
1036 
1037 // The path can point to either a dylib or a .tbd file.
1038 static DylibFile *loadDylib(StringRef path, DylibFile *umbrella) {
1039   Optional<MemoryBufferRef> mbref = readFile(path);
1040   if (!mbref) {
1041     error("could not read dylib file at " + path);
1042     return nullptr;
1043   }
1044   return loadDylib(*mbref, umbrella);
1045 }
1046 
1047 // TBD files are parsed into a series of TAPI documents (InterfaceFiles), with
1048 // the first document storing child pointers to the rest of them. When we are
1049 // processing a given TBD file, we store that top-level document in
1050 // currentTopLevelTapi. When processing re-exports, we search its children for
1051 // potentially matching documents in the same TBD file. Note that the children
1052 // themselves don't point to further documents, i.e. this is a two-level tree.
1053 //
1054 // Re-exports can either refer to on-disk files, or to documents within .tbd
1055 // files.
1056 static DylibFile *findDylib(StringRef path, DylibFile *umbrella,
1057                             const InterfaceFile *currentTopLevelTapi) {
1058   // Search order:
1059   // 1. Install name basename in -F / -L directories.
1060   {
1061     StringRef stem = path::stem(path);
1062     SmallString<128> frameworkName;
1063     path::append(frameworkName, path::Style::posix, stem + ".framework", stem);
1064     bool isFramework = path.endswith(frameworkName);
1065     if (isFramework) {
1066       for (StringRef dir : config->frameworkSearchPaths) {
1067         SmallString<128> candidate = dir;
1068         path::append(candidate, frameworkName);
1069         if (Optional<StringRef> dylibPath = resolveDylibPath(candidate.str()))
1070           return loadDylib(*dylibPath, umbrella);
1071       }
1072     } else if (Optional<StringRef> dylibPath = findPathCombination(
1073                    stem, config->librarySearchPaths, {".tbd", ".dylib"}))
1074       return loadDylib(*dylibPath, umbrella);
1075   }
1076 
1077   // 2. As absolute path.
1078   if (path::is_absolute(path, path::Style::posix))
1079     for (StringRef root : config->systemLibraryRoots)
1080       if (Optional<StringRef> dylibPath = resolveDylibPath((root + path).str()))
1081         return loadDylib(*dylibPath, umbrella);
1082 
1083   // 3. As relative path.
1084 
1085   // TODO: Handle -dylib_file
1086 
1087   // Replace @executable_path, @loader_path, @rpath prefixes in install name.
1088   SmallString<128> newPath;
1089   if (config->outputType == MH_EXECUTE &&
1090       path.consume_front("@executable_path/")) {
1091     // ld64 allows overriding this with the undocumented flag -executable_path.
1092     // lld doesn't currently implement that flag.
1093     // FIXME: Consider using finalOutput instead of outputFile.
1094     path::append(newPath, path::parent_path(config->outputFile), path);
1095     path = newPath;
1096   } else if (path.consume_front("@loader_path/")) {
1097     fs::real_path(umbrella->getName(), newPath);
1098     path::remove_filename(newPath);
1099     path::append(newPath, path);
1100     path = newPath;
1101   } else if (path.startswith("@rpath/")) {
1102     for (StringRef rpath : umbrella->rpaths) {
1103       newPath.clear();
1104       if (rpath.consume_front("@loader_path/")) {
1105         fs::real_path(umbrella->getName(), newPath);
1106         path::remove_filename(newPath);
1107       }
1108       path::append(newPath, rpath, path.drop_front(strlen("@rpath/")));
1109       if (Optional<StringRef> dylibPath = resolveDylibPath(newPath.str()))
1110         return loadDylib(*dylibPath, umbrella);
1111     }
1112   }
1113 
1114   // FIXME: Should this be further up?
1115   if (currentTopLevelTapi) {
1116     for (InterfaceFile &child :
1117          make_pointee_range(currentTopLevelTapi->documents())) {
1118       assert(child.documents().empty());
1119       if (path == child.getInstallName()) {
1120         auto file = make<DylibFile>(child, umbrella);
1121         file->parseReexports(child);
1122         return file;
1123       }
1124     }
1125   }
1126 
1127   if (Optional<StringRef> dylibPath = resolveDylibPath(path))
1128     return loadDylib(*dylibPath, umbrella);
1129 
1130   return nullptr;
1131 }
1132 
1133 // If a re-exported dylib is public (lives in /usr/lib or
1134 // /System/Library/Frameworks), then it is considered implicitly linked: we
1135 // should bind to its symbols directly instead of via the re-exporting umbrella
1136 // library.
1137 static bool isImplicitlyLinked(StringRef path) {
1138   if (!config->implicitDylibs)
1139     return false;
1140 
1141   if (path::parent_path(path) == "/usr/lib")
1142     return true;
1143 
1144   // Match /System/Library/Frameworks/$FOO.framework/**/$FOO
1145   if (path.consume_front("/System/Library/Frameworks/")) {
1146     StringRef frameworkName = path.take_until([](char c) { return c == '.'; });
1147     return path::filename(path) == frameworkName;
1148   }
1149 
1150   return false;
1151 }
1152 
1153 static void loadReexport(StringRef path, DylibFile *umbrella,
1154                          const InterfaceFile *currentTopLevelTapi) {
1155   DylibFile *reexport = findDylib(path, umbrella, currentTopLevelTapi);
1156   if (!reexport)
1157     error("unable to locate re-export with install name " + path);
1158 }
1159 
1160 DylibFile::DylibFile(MemoryBufferRef mb, DylibFile *umbrella,
1161                      bool isBundleLoader)
1162     : InputFile(DylibKind, mb), refState(RefState::Unreferenced),
1163       isBundleLoader(isBundleLoader) {
1164   assert(!isBundleLoader || !umbrella);
1165   if (umbrella == nullptr)
1166     umbrella = this;
1167   this->umbrella = umbrella;
1168 
1169   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
1170   auto *hdr = reinterpret_cast<const mach_header *>(mb.getBufferStart());
1171 
1172   // Initialize installName.
1173   if (const load_command *cmd = findCommand(hdr, LC_ID_DYLIB)) {
1174     auto *c = reinterpret_cast<const dylib_command *>(cmd);
1175     currentVersion = read32le(&c->dylib.current_version);
1176     compatibilityVersion = read32le(&c->dylib.compatibility_version);
1177     installName =
1178         reinterpret_cast<const char *>(cmd) + read32le(&c->dylib.name);
1179   } else if (!isBundleLoader) {
1180     // macho_executable and macho_bundle don't have LC_ID_DYLIB,
1181     // so it's OK.
1182     error("dylib " + toString(this) + " missing LC_ID_DYLIB load command");
1183     return;
1184   }
1185 
1186   if (config->printEachFile)
1187     message(toString(this));
1188   inputFiles.insert(this);
1189 
1190   deadStrippable = hdr->flags & MH_DEAD_STRIPPABLE_DYLIB;
1191 
1192   if (!checkCompatibility(this))
1193     return;
1194 
1195   checkAppExtensionSafety(hdr->flags & MH_APP_EXTENSION_SAFE);
1196 
1197   for (auto *cmd : findCommands<rpath_command>(hdr, LC_RPATH)) {
1198     StringRef rpath{reinterpret_cast<const char *>(cmd) + cmd->path};
1199     rpaths.push_back(rpath);
1200   }
1201 
1202   // Initialize symbols.
1203   exportingFile = isImplicitlyLinked(installName) ? this : this->umbrella;
1204   if (const load_command *cmd = findCommand(hdr, LC_DYLD_INFO_ONLY)) {
1205     auto *c = reinterpret_cast<const dyld_info_command *>(cmd);
1206     struct TrieEntry {
1207       StringRef name;
1208       uint64_t flags;
1209     };
1210 
1211     std::vector<TrieEntry> entries;
1212     // Find all the $ld$* symbols to process first.
1213     parseTrie(buf + c->export_off, c->export_size,
1214               [&](const Twine &name, uint64_t flags) {
1215                 StringRef savedName = saver().save(name);
1216                 if (handleLDSymbol(savedName))
1217                   return;
1218                 entries.push_back({savedName, flags});
1219               });
1220 
1221     // Process the "normal" symbols.
1222     for (TrieEntry &entry : entries) {
1223       if (exportingFile->hiddenSymbols.contains(
1224               CachedHashStringRef(entry.name)))
1225         continue;
1226 
1227       bool isWeakDef = entry.flags & EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION;
1228       bool isTlv = entry.flags & EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL;
1229 
1230       symbols.push_back(
1231           symtab->addDylib(entry.name, exportingFile, isWeakDef, isTlv));
1232     }
1233 
1234   } else {
1235     error("LC_DYLD_INFO_ONLY not found in " + toString(this));
1236     return;
1237   }
1238 }
1239 
1240 void DylibFile::parseLoadCommands(MemoryBufferRef mb) {
1241   auto *hdr = reinterpret_cast<const mach_header *>(mb.getBufferStart());
1242   const uint8_t *p = reinterpret_cast<const uint8_t *>(mb.getBufferStart()) +
1243                      target->headerSize;
1244   for (uint32_t i = 0, n = hdr->ncmds; i < n; ++i) {
1245     auto *cmd = reinterpret_cast<const load_command *>(p);
1246     p += cmd->cmdsize;
1247 
1248     if (!(hdr->flags & MH_NO_REEXPORTED_DYLIBS) &&
1249         cmd->cmd == LC_REEXPORT_DYLIB) {
1250       const auto *c = reinterpret_cast<const dylib_command *>(cmd);
1251       StringRef reexportPath =
1252           reinterpret_cast<const char *>(c) + read32le(&c->dylib.name);
1253       loadReexport(reexportPath, exportingFile, nullptr);
1254     }
1255 
1256     // FIXME: What about LC_LOAD_UPWARD_DYLIB, LC_LAZY_LOAD_DYLIB,
1257     // LC_LOAD_WEAK_DYLIB, LC_REEXPORT_DYLIB (..are reexports from dylibs with
1258     // MH_NO_REEXPORTED_DYLIBS loaded for -flat_namespace)?
1259     if (config->namespaceKind == NamespaceKind::flat &&
1260         cmd->cmd == LC_LOAD_DYLIB) {
1261       const auto *c = reinterpret_cast<const dylib_command *>(cmd);
1262       StringRef dylibPath =
1263           reinterpret_cast<const char *>(c) + read32le(&c->dylib.name);
1264       DylibFile *dylib = findDylib(dylibPath, umbrella, nullptr);
1265       if (!dylib)
1266         error(Twine("unable to locate library '") + dylibPath +
1267               "' loaded from '" + toString(this) + "' for -flat_namespace");
1268     }
1269   }
1270 }
1271 
1272 // Some versions of XCode ship with .tbd files that don't have the right
1273 // platform settings.
1274 static constexpr std::array<StringRef, 3> skipPlatformChecks{
1275     "/usr/lib/system/libsystem_kernel.dylib",
1276     "/usr/lib/system/libsystem_platform.dylib",
1277     "/usr/lib/system/libsystem_pthread.dylib"};
1278 
1279 DylibFile::DylibFile(const InterfaceFile &interface, DylibFile *umbrella,
1280                      bool isBundleLoader)
1281     : InputFile(DylibKind, interface), refState(RefState::Unreferenced),
1282       isBundleLoader(isBundleLoader) {
1283   // FIXME: Add test for the missing TBD code path.
1284 
1285   if (umbrella == nullptr)
1286     umbrella = this;
1287   this->umbrella = umbrella;
1288 
1289   installName = saver().save(interface.getInstallName());
1290   compatibilityVersion = interface.getCompatibilityVersion().rawValue();
1291   currentVersion = interface.getCurrentVersion().rawValue();
1292 
1293   if (config->printEachFile)
1294     message(toString(this));
1295   inputFiles.insert(this);
1296 
1297   if (!is_contained(skipPlatformChecks, installName) &&
1298       !is_contained(interface.targets(), config->platformInfo.target)) {
1299     error(toString(this) + " is incompatible with " +
1300           std::string(config->platformInfo.target));
1301     return;
1302   }
1303 
1304   checkAppExtensionSafety(interface.isApplicationExtensionSafe());
1305 
1306   exportingFile = isImplicitlyLinked(installName) ? this : umbrella;
1307   auto addSymbol = [&](const Twine &name) -> void {
1308     StringRef savedName = saver().save(name);
1309     if (exportingFile->hiddenSymbols.contains(CachedHashStringRef(savedName)))
1310       return;
1311 
1312     symbols.push_back(symtab->addDylib(savedName, exportingFile,
1313                                        /*isWeakDef=*/false,
1314                                        /*isTlv=*/false));
1315   };
1316 
1317   std::vector<const llvm::MachO::Symbol *> normalSymbols;
1318   normalSymbols.reserve(interface.symbolsCount());
1319   for (const auto *symbol : interface.symbols()) {
1320     if (!symbol->getArchitectures().has(config->arch()))
1321       continue;
1322     if (handleLDSymbol(symbol->getName()))
1323       continue;
1324 
1325     switch (symbol->getKind()) {
1326     case SymbolKind::GlobalSymbol:               // Fallthrough
1327     case SymbolKind::ObjectiveCClass:            // Fallthrough
1328     case SymbolKind::ObjectiveCClassEHType:      // Fallthrough
1329     case SymbolKind::ObjectiveCInstanceVariable: // Fallthrough
1330       normalSymbols.push_back(symbol);
1331     }
1332   }
1333 
1334   // TODO(compnerd) filter out symbols based on the target platform
1335   // TODO: handle weak defs, thread locals
1336   for (const auto *symbol : normalSymbols) {
1337     switch (symbol->getKind()) {
1338     case SymbolKind::GlobalSymbol:
1339       addSymbol(symbol->getName());
1340       break;
1341     case SymbolKind::ObjectiveCClass:
1342       // XXX ld64 only creates these symbols when -ObjC is passed in. We may
1343       // want to emulate that.
1344       addSymbol(objc::klass + symbol->getName());
1345       addSymbol(objc::metaclass + symbol->getName());
1346       break;
1347     case SymbolKind::ObjectiveCClassEHType:
1348       addSymbol(objc::ehtype + symbol->getName());
1349       break;
1350     case SymbolKind::ObjectiveCInstanceVariable:
1351       addSymbol(objc::ivar + symbol->getName());
1352       break;
1353     }
1354   }
1355 }
1356 
1357 void DylibFile::parseReexports(const InterfaceFile &interface) {
1358   const InterfaceFile *topLevel =
1359       interface.getParent() == nullptr ? &interface : interface.getParent();
1360   for (const InterfaceFileRef &intfRef : interface.reexportedLibraries()) {
1361     InterfaceFile::const_target_range targets = intfRef.targets();
1362     if (is_contained(skipPlatformChecks, intfRef.getInstallName()) ||
1363         is_contained(targets, config->platformInfo.target))
1364       loadReexport(intfRef.getInstallName(), exportingFile, topLevel);
1365   }
1366 }
1367 
1368 // $ld$ symbols modify the properties/behavior of the library (e.g. its install
1369 // name, compatibility version or hide/add symbols) for specific target
1370 // versions.
1371 bool DylibFile::handleLDSymbol(StringRef originalName) {
1372   if (!originalName.startswith("$ld$"))
1373     return false;
1374 
1375   StringRef action;
1376   StringRef name;
1377   std::tie(action, name) = originalName.drop_front(strlen("$ld$")).split('$');
1378   if (action == "previous")
1379     handleLDPreviousSymbol(name, originalName);
1380   else if (action == "install_name")
1381     handleLDInstallNameSymbol(name, originalName);
1382   else if (action == "hide")
1383     handleLDHideSymbol(name, originalName);
1384   return true;
1385 }
1386 
1387 void DylibFile::handleLDPreviousSymbol(StringRef name, StringRef originalName) {
1388   // originalName: $ld$ previous $ <installname> $ <compatversion> $
1389   // <platformstr> $ <startversion> $ <endversion> $ <symbol-name> $
1390   StringRef installName;
1391   StringRef compatVersion;
1392   StringRef platformStr;
1393   StringRef startVersion;
1394   StringRef endVersion;
1395   StringRef symbolName;
1396   StringRef rest;
1397 
1398   std::tie(installName, name) = name.split('$');
1399   std::tie(compatVersion, name) = name.split('$');
1400   std::tie(platformStr, name) = name.split('$');
1401   std::tie(startVersion, name) = name.split('$');
1402   std::tie(endVersion, name) = name.split('$');
1403   std::tie(symbolName, rest) = name.split('$');
1404   // TODO: ld64 contains some logic for non-empty symbolName as well.
1405   if (!symbolName.empty())
1406     return;
1407   unsigned platform;
1408   if (platformStr.getAsInteger(10, platform) ||
1409       platform != static_cast<unsigned>(config->platform()))
1410     return;
1411 
1412   VersionTuple start;
1413   if (start.tryParse(startVersion)) {
1414     warn("failed to parse start version, symbol '" + originalName +
1415          "' ignored");
1416     return;
1417   }
1418   VersionTuple end;
1419   if (end.tryParse(endVersion)) {
1420     warn("failed to parse end version, symbol '" + originalName + "' ignored");
1421     return;
1422   }
1423   if (config->platformInfo.minimum < start ||
1424       config->platformInfo.minimum >= end)
1425     return;
1426 
1427   this->installName = saver().save(installName);
1428 
1429   if (!compatVersion.empty()) {
1430     VersionTuple cVersion;
1431     if (cVersion.tryParse(compatVersion)) {
1432       warn("failed to parse compatibility version, symbol '" + originalName +
1433            "' ignored");
1434       return;
1435     }
1436     compatibilityVersion = encodeVersion(cVersion);
1437   }
1438 }
1439 
1440 void DylibFile::handleLDInstallNameSymbol(StringRef name,
1441                                           StringRef originalName) {
1442   // originalName: $ld$ install_name $ os<version> $ install_name
1443   StringRef condition, installName;
1444   std::tie(condition, installName) = name.split('$');
1445   VersionTuple version;
1446   if (!condition.consume_front("os") || version.tryParse(condition))
1447     warn("failed to parse os version, symbol '" + originalName + "' ignored");
1448   else if (version == config->platformInfo.minimum)
1449     this->installName = saver().save(installName);
1450 }
1451 
1452 void DylibFile::handleLDHideSymbol(StringRef name, StringRef originalName) {
1453   StringRef symbolName;
1454   bool shouldHide = true;
1455   if (name.startswith("os")) {
1456     // If it's hidden based on versions.
1457     name = name.drop_front(2);
1458     StringRef minVersion;
1459     std::tie(minVersion, symbolName) = name.split('$');
1460     VersionTuple versionTup;
1461     if (versionTup.tryParse(minVersion)) {
1462       warn("Failed to parse hidden version, symbol `" + originalName +
1463            "` ignored.");
1464       return;
1465     }
1466     shouldHide = versionTup == config->platformInfo.minimum;
1467   } else {
1468     symbolName = name;
1469   }
1470 
1471   if (shouldHide)
1472     exportingFile->hiddenSymbols.insert(CachedHashStringRef(symbolName));
1473 }
1474 
1475 void DylibFile::checkAppExtensionSafety(bool dylibIsAppExtensionSafe) const {
1476   if (config->applicationExtension && !dylibIsAppExtensionSafe)
1477     warn("using '-application_extension' with unsafe dylib: " + toString(this));
1478 }
1479 
1480 ArchiveFile::ArchiveFile(std::unique_ptr<object::Archive> &&f)
1481     : InputFile(ArchiveKind, f->getMemoryBufferRef()), file(std::move(f)) {}
1482 
1483 void ArchiveFile::addLazySymbols() {
1484   for (const object::Archive::Symbol &sym : file->symbols())
1485     symtab->addLazyArchive(sym.getName(), this, sym);
1486 }
1487 
1488 static Expected<InputFile *> loadArchiveMember(MemoryBufferRef mb,
1489                                                uint32_t modTime,
1490                                                StringRef archiveName,
1491                                                uint64_t offsetInArchive) {
1492   if (config->zeroModTime)
1493     modTime = 0;
1494 
1495   switch (identify_magic(mb.getBuffer())) {
1496   case file_magic::macho_object:
1497     return make<ObjFile>(mb, modTime, archiveName);
1498   case file_magic::bitcode:
1499     return make<BitcodeFile>(mb, archiveName, offsetInArchive);
1500   default:
1501     return createStringError(inconvertibleErrorCode(),
1502                              mb.getBufferIdentifier() +
1503                                  " has unhandled file type");
1504   }
1505 }
1506 
1507 Error ArchiveFile::fetch(const object::Archive::Child &c, StringRef reason) {
1508   if (!seen.insert(c.getChildOffset()).second)
1509     return Error::success();
1510 
1511   Expected<MemoryBufferRef> mb = c.getMemoryBufferRef();
1512   if (!mb)
1513     return mb.takeError();
1514 
1515   // Thin archives refer to .o files, so --reproduce needs the .o files too.
1516   if (tar && c.getParent()->isThin())
1517     tar->append(relativeToRoot(CHECK(c.getFullName(), this)), mb->getBuffer());
1518 
1519   Expected<TimePoint<std::chrono::seconds>> modTime = c.getLastModified();
1520   if (!modTime)
1521     return modTime.takeError();
1522 
1523   Expected<InputFile *> file =
1524       loadArchiveMember(*mb, toTimeT(*modTime), getName(), c.getChildOffset());
1525 
1526   if (!file)
1527     return file.takeError();
1528 
1529   inputFiles.insert(*file);
1530   printArchiveMemberLoad(reason, *file);
1531   return Error::success();
1532 }
1533 
1534 void ArchiveFile::fetch(const object::Archive::Symbol &sym) {
1535   object::Archive::Child c =
1536       CHECK(sym.getMember(), toString(this) +
1537                                  ": could not get the member defining symbol " +
1538                                  toMachOString(sym));
1539 
1540   // `sym` is owned by a LazySym, which will be replace<>()d by make<ObjFile>
1541   // and become invalid after that call. Copy it to the stack so we can refer
1542   // to it later.
1543   const object::Archive::Symbol symCopy = sym;
1544 
1545   // ld64 doesn't demangle sym here even with -demangle.
1546   // Match that: intentionally don't call toMachOString().
1547   if (Error e = fetch(c, symCopy.getName()))
1548     error(toString(this) + ": could not get the member defining symbol " +
1549           toMachOString(symCopy) + ": " + toString(std::move(e)));
1550 }
1551 
1552 static macho::Symbol *createBitcodeSymbol(const lto::InputFile::Symbol &objSym,
1553                                           BitcodeFile &file) {
1554   StringRef name = saver().save(objSym.getName());
1555 
1556   if (objSym.isUndefined())
1557     return symtab->addUndefined(name, &file, /*isWeakRef=*/objSym.isWeak());
1558 
1559   // TODO: Write a test demonstrating why computing isPrivateExtern before
1560   // LTO compilation is important.
1561   bool isPrivateExtern = false;
1562   switch (objSym.getVisibility()) {
1563   case GlobalValue::HiddenVisibility:
1564     isPrivateExtern = true;
1565     break;
1566   case GlobalValue::ProtectedVisibility:
1567     error(name + " has protected visibility, which is not supported by Mach-O");
1568     break;
1569   case GlobalValue::DefaultVisibility:
1570     break;
1571   }
1572 
1573   if (objSym.isCommon())
1574     return symtab->addCommon(name, &file, objSym.getCommonSize(),
1575                              objSym.getCommonAlignment(), isPrivateExtern);
1576 
1577   return symtab->addDefined(name, &file, /*isec=*/nullptr, /*value=*/0,
1578                             /*size=*/0, objSym.isWeak(), isPrivateExtern,
1579                             /*isThumb=*/false,
1580                             /*isReferencedDynamically=*/false,
1581                             /*noDeadStrip=*/false,
1582                             /*isWeakDefCanBeHidden=*/false);
1583 }
1584 
1585 BitcodeFile::BitcodeFile(MemoryBufferRef mb, StringRef archiveName,
1586                          uint64_t offsetInArchive, bool lazy)
1587     : InputFile(BitcodeKind, mb, lazy) {
1588   this->archiveName = std::string(archiveName);
1589   std::string path = mb.getBufferIdentifier().str();
1590   // ThinLTO assumes that all MemoryBufferRefs given to it have a unique
1591   // name. If two members with the same name are provided, this causes a
1592   // collision and ThinLTO can't proceed.
1593   // So, we append the archive name to disambiguate two members with the same
1594   // name from multiple different archives, and offset within the archive to
1595   // disambiguate two members of the same name from a single archive.
1596   MemoryBufferRef mbref(mb.getBuffer(),
1597                         saver().save(archiveName.empty()
1598                                          ? path
1599                                          : archiveName +
1600                                                sys::path::filename(path) +
1601                                                utostr(offsetInArchive)));
1602 
1603   obj = check(lto::InputFile::create(mbref));
1604   if (lazy)
1605     parseLazy();
1606   else
1607     parse();
1608 }
1609 
1610 void BitcodeFile::parse() {
1611   // Convert LTO Symbols to LLD Symbols in order to perform resolution. The
1612   // "winning" symbol will then be marked as Prevailing at LTO compilation
1613   // time.
1614   symbols.clear();
1615   for (const lto::InputFile::Symbol &objSym : obj->symbols())
1616     symbols.push_back(createBitcodeSymbol(objSym, *this));
1617 }
1618 
1619 void BitcodeFile::parseLazy() {
1620   symbols.resize(obj->symbols().size());
1621   for (auto it : llvm::enumerate(obj->symbols())) {
1622     const lto::InputFile::Symbol &objSym = it.value();
1623     if (!objSym.isUndefined()) {
1624       symbols[it.index()] =
1625           symtab->addLazyObject(saver().save(objSym.getName()), *this);
1626       if (!lazy)
1627         break;
1628     }
1629   }
1630 }
1631 
1632 void macho::extract(InputFile &file, StringRef reason) {
1633   assert(file.lazy);
1634   file.lazy = false;
1635   printArchiveMemberLoad(reason, &file);
1636   if (auto *bitcode = dyn_cast<BitcodeFile>(&file)) {
1637     bitcode->parse();
1638   } else {
1639     auto &f = cast<ObjFile>(file);
1640     if (target->wordSize == 8)
1641       f.parse<LP64>();
1642     else
1643       f.parse<ILP32>();
1644   }
1645 }
1646 
1647 template void ObjFile::parse<LP64>();
1648