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