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/DWARF.h"
60 #include "lld/Common/ErrorHandler.h"
61 #include "lld/Common/Memory.h"
62 #include "lld/Common/Reproduce.h"
63 #include "llvm/ADT/iterator.h"
64 #include "llvm/BinaryFormat/MachO.h"
65 #include "llvm/LTO/LTO.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/TextAPI/Architecture.h"
71 #include "llvm/TextAPI/InterfaceFile.h"
72 
73 using namespace llvm;
74 using namespace llvm::MachO;
75 using namespace llvm::support::endian;
76 using namespace llvm::sys;
77 using namespace lld;
78 using namespace lld::macho;
79 
80 // Returns "<internal>", "foo.a(bar.o)", or "baz.o".
81 std::string lld::toString(const InputFile *f) {
82   if (!f)
83     return "<internal>";
84 
85   // Multiple dylibs can be defined in one .tbd file.
86   if (auto dylibFile = dyn_cast<DylibFile>(f))
87     if (f->getName().endswith(".tbd"))
88       return (f->getName() + "(" + dylibFile->installName + ")").str();
89 
90   if (f->archiveName.empty())
91     return std::string(f->getName());
92   return (f->archiveName + "(" + path::filename(f->getName()) + ")").str();
93 }
94 
95 SetVector<InputFile *> macho::inputFiles;
96 std::unique_ptr<TarWriter> macho::tar;
97 int InputFile::idCount = 0;
98 
99 static VersionTuple decodeVersion(uint32_t version) {
100   unsigned major = version >> 16;
101   unsigned minor = (version >> 8) & 0xffu;
102   unsigned subMinor = version & 0xffu;
103   return VersionTuple(major, minor, subMinor);
104 }
105 
106 static std::vector<PlatformInfo> getPlatformInfos(const InputFile *input) {
107   if (!isa<ObjFile>(input) && !isa<DylibFile>(input))
108     return {};
109 
110   const char *hdr = input->mb.getBufferStart();
111 
112   std::vector<PlatformInfo> platformInfos;
113   for (auto *cmd : findCommands<build_version_command>(hdr, LC_BUILD_VERSION)) {
114     PlatformInfo info;
115     info.target.Platform = static_cast<PlatformKind>(cmd->platform);
116     info.minimum = decodeVersion(cmd->minos);
117     platformInfos.emplace_back(std::move(info));
118   }
119   for (auto *cmd : findCommands<version_min_command>(
120            hdr, LC_VERSION_MIN_MACOSX, LC_VERSION_MIN_IPHONEOS,
121            LC_VERSION_MIN_TVOS, LC_VERSION_MIN_WATCHOS)) {
122     PlatformInfo info;
123     switch (cmd->cmd) {
124     case LC_VERSION_MIN_MACOSX:
125       info.target.Platform = PlatformKind::macOS;
126       break;
127     case LC_VERSION_MIN_IPHONEOS:
128       info.target.Platform = PlatformKind::iOS;
129       break;
130     case LC_VERSION_MIN_TVOS:
131       info.target.Platform = PlatformKind::tvOS;
132       break;
133     case LC_VERSION_MIN_WATCHOS:
134       info.target.Platform = PlatformKind::watchOS;
135       break;
136     }
137     info.minimum = decodeVersion(cmd->version);
138     platformInfos.emplace_back(std::move(info));
139   }
140 
141   return platformInfos;
142 }
143 
144 static PlatformKind removeSimulator(PlatformKind platform) {
145   // Mapping of platform to simulator and vice-versa.
146   static const std::map<PlatformKind, PlatformKind> platformMap = {
147       {PlatformKind::iOSSimulator, PlatformKind::iOS},
148       {PlatformKind::tvOSSimulator, PlatformKind::tvOS},
149       {PlatformKind::watchOSSimulator, PlatformKind::watchOS}};
150 
151   auto iter = platformMap.find(platform);
152   if (iter == platformMap.end())
153     return platform;
154   return iter->second;
155 }
156 
157 static bool checkCompatibility(const InputFile *input) {
158   std::vector<PlatformInfo> platformInfos = getPlatformInfos(input);
159   if (platformInfos.empty())
160     return true;
161 
162   auto it = find_if(platformInfos, [&](const PlatformInfo &info) {
163     return removeSimulator(info.target.Platform) ==
164            removeSimulator(config->platform());
165   });
166   if (it == platformInfos.end()) {
167     std::string platformNames;
168     raw_string_ostream os(platformNames);
169     interleave(
170         platformInfos, os,
171         [&](const PlatformInfo &info) {
172           os << getPlatformName(info.target.Platform);
173         },
174         "/");
175     error(toString(input) + " has platform " + platformNames +
176           Twine(", which is different from target platform ") +
177           getPlatformName(config->platform()));
178     return false;
179   }
180 
181   if (it->minimum > config->platformInfo.minimum)
182     warn(toString(input) + " has version " + it->minimum.getAsString() +
183          ", which is newer than target minimum of " +
184          config->platformInfo.minimum.getAsString());
185 
186   return true;
187 }
188 
189 // Open a given file path and return it as a memory-mapped file.
190 Optional<MemoryBufferRef> macho::readFile(StringRef path) {
191   ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr = MemoryBuffer::getFile(path);
192   if (std::error_code ec = mbOrErr.getError()) {
193     error("cannot open " + path + ": " + ec.message());
194     return None;
195   }
196 
197   std::unique_ptr<MemoryBuffer> &mb = *mbOrErr;
198   MemoryBufferRef mbref = mb->getMemBufferRef();
199   make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take mb ownership
200 
201   // If this is a regular non-fat file, return it.
202   const char *buf = mbref.getBufferStart();
203   const auto *hdr = reinterpret_cast<const fat_header *>(buf);
204   if (mbref.getBufferSize() < sizeof(uint32_t) ||
205       read32be(&hdr->magic) != FAT_MAGIC) {
206     if (tar)
207       tar->append(relativeToRoot(path), mbref.getBuffer());
208     return mbref;
209   }
210 
211   // Object files and archive files may be fat files, which contain multiple
212   // real files for different CPU ISAs. Here, we search for a file that matches
213   // with the current link target and returns it as a MemoryBufferRef.
214   const auto *arch = reinterpret_cast<const fat_arch *>(buf + sizeof(*hdr));
215 
216   for (uint32_t i = 0, n = read32be(&hdr->nfat_arch); i < n; ++i) {
217     if (reinterpret_cast<const char *>(arch + i + 1) >
218         buf + mbref.getBufferSize()) {
219       error(path + ": fat_arch struct extends beyond end of file");
220       return None;
221     }
222 
223     if (read32be(&arch[i].cputype) != static_cast<uint32_t>(target->cpuType) ||
224         read32be(&arch[i].cpusubtype) != target->cpuSubtype)
225       continue;
226 
227     uint32_t offset = read32be(&arch[i].offset);
228     uint32_t size = read32be(&arch[i].size);
229     if (offset + size > mbref.getBufferSize())
230       error(path + ": slice extends beyond end of file");
231     if (tar)
232       tar->append(relativeToRoot(path), mbref.getBuffer());
233     return MemoryBufferRef(StringRef(buf + offset, size), path.copy(bAlloc));
234   }
235 
236   error("unable to find matching architecture in " + path);
237   return None;
238 }
239 
240 InputFile::InputFile(Kind kind, const InterfaceFile &interface)
241     : id(idCount++), fileKind(kind), name(saver.save(interface.getPath())) {}
242 
243 template <class Section>
244 void ObjFile::parseSections(ArrayRef<Section> sections) {
245   subsections.reserve(sections.size());
246   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
247 
248   for (const Section &sec : sections) {
249     StringRef name =
250         StringRef(sec.sectname, strnlen(sec.sectname, sizeof(sec.sectname)));
251     StringRef segname =
252         StringRef(sec.segname, strnlen(sec.segname, sizeof(sec.segname)));
253     ArrayRef<uint8_t> data = {isZeroFill(sec.flags) ? nullptr
254                                                     : buf + sec.offset,
255                               static_cast<size_t>(sec.size)};
256     if (sec.align >= 32) {
257       error("alignment " + std::to_string(sec.align) + " of section " + name +
258             " is too large");
259       subsections.push_back({});
260       continue;
261     }
262     uint32_t align = 1 << sec.align;
263     uint32_t flags = sec.flags;
264 
265     if (sectionType(sec.flags) == S_CSTRING_LITERALS ||
266         (config->dedupLiterals && isWordLiteralSection(sec.flags))) {
267       if (sec.nreloc && config->dedupLiterals)
268         fatal(toString(this) + " contains relocations in " + sec.segname + "," +
269               sec.sectname +
270               ", so LLD cannot deduplicate literals. Try re-running without "
271               "--deduplicate-literals.");
272 
273       InputSection *isec;
274       if (sectionType(sec.flags) == S_CSTRING_LITERALS) {
275         isec =
276             make<CStringInputSection>(segname, name, this, data, align, flags);
277         // FIXME: parallelize this?
278         cast<CStringInputSection>(isec)->splitIntoPieces();
279       } else {
280         isec = make<WordLiteralInputSection>(segname, name, this, data, align,
281                                              flags);
282       }
283       subsections.push_back({{0, isec}});
284     } else if (config->icfLevel != ICFLevel::none &&
285                (name == section_names::cfString &&
286                 segname == segment_names::data)) {
287       uint64_t literalSize = target->wordSize == 8 ? 32 : 16;
288       subsections.push_back({});
289       SubsectionMap &subsecMap = subsections.back();
290       for (uint64_t off = 0; off < data.size(); off += literalSize)
291         subsecMap.push_back(
292             {off, make<ConcatInputSection>(segname, name, this,
293                                            data.slice(off, literalSize), align,
294                                            flags)});
295     } else {
296       auto *isec =
297           make<ConcatInputSection>(segname, name, this, data, align, flags);
298       if (!(isDebugSection(isec->getFlags()) &&
299             isec->getSegName() == segment_names::dwarf)) {
300         subsections.push_back({{0, isec}});
301       } else {
302         // Instead of emitting DWARF sections, we emit STABS symbols to the
303         // object files that contain them. We filter them out early to avoid
304         // parsing their relocations unnecessarily. But we must still push an
305         // empty map to ensure the indices line up for the remaining sections.
306         subsections.push_back({});
307         debugSections.push_back(isec);
308       }
309     }
310   }
311 }
312 
313 // Find the subsection corresponding to the greatest section offset that is <=
314 // that of the given offset.
315 //
316 // offset: an offset relative to the start of the original InputSection (before
317 // any subsection splitting has occurred). It will be updated to represent the
318 // same location as an offset relative to the start of the containing
319 // subsection.
320 static InputSection *findContainingSubsection(SubsectionMap &map,
321                                               uint64_t *offset) {
322   auto it = std::prev(llvm::upper_bound(
323       map, *offset, [](uint64_t value, SubsectionEntry subsecEntry) {
324         return value < subsecEntry.offset;
325       }));
326   *offset -= it->offset;
327   return it->isec;
328 }
329 
330 template <class Section>
331 static bool validateRelocationInfo(InputFile *file, const Section &sec,
332                                    relocation_info rel) {
333   const RelocAttrs &relocAttrs = target->getRelocAttrs(rel.r_type);
334   bool valid = true;
335   auto message = [relocAttrs, file, sec, rel, &valid](const Twine &diagnostic) {
336     valid = false;
337     return (relocAttrs.name + " relocation " + diagnostic + " at offset " +
338             std::to_string(rel.r_address) + " of " + sec.segname + "," +
339             sec.sectname + " in " + toString(file))
340         .str();
341   };
342 
343   if (!relocAttrs.hasAttr(RelocAttrBits::LOCAL) && !rel.r_extern)
344     error(message("must be extern"));
345   if (relocAttrs.hasAttr(RelocAttrBits::PCREL) != rel.r_pcrel)
346     error(message(Twine("must ") + (rel.r_pcrel ? "not " : "") +
347                   "be PC-relative"));
348   if (isThreadLocalVariables(sec.flags) &&
349       !relocAttrs.hasAttr(RelocAttrBits::UNSIGNED))
350     error(message("not allowed in thread-local section, must be UNSIGNED"));
351   if (rel.r_length < 2 || rel.r_length > 3 ||
352       !relocAttrs.hasAttr(static_cast<RelocAttrBits>(1 << rel.r_length))) {
353     static SmallVector<StringRef, 4> widths{"0", "4", "8", "4 or 8"};
354     error(message("has width " + std::to_string(1 << rel.r_length) +
355                   " bytes, but must be " +
356                   widths[(static_cast<int>(relocAttrs.bits) >> 2) & 3] +
357                   " bytes"));
358   }
359   return valid;
360 }
361 
362 template <class Section>
363 void ObjFile::parseRelocations(ArrayRef<Section> sectionHeaders,
364                                const Section &sec, SubsectionMap &subsecMap) {
365   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
366   ArrayRef<relocation_info> relInfos(
367       reinterpret_cast<const relocation_info *>(buf + sec.reloff), sec.nreloc);
368 
369   auto subsecIt = subsecMap.rbegin();
370   for (size_t i = 0; i < relInfos.size(); i++) {
371     // Paired relocations serve as Mach-O's method for attaching a
372     // supplemental datum to a primary relocation record. ELF does not
373     // need them because the *_RELOC_RELA records contain the extra
374     // addend field, vs. *_RELOC_REL which omit the addend.
375     //
376     // The {X86_64,ARM64}_RELOC_SUBTRACTOR record holds the subtrahend,
377     // and the paired *_RELOC_UNSIGNED record holds the minuend. The
378     // datum for each is a symbolic address. The result is the offset
379     // between two addresses.
380     //
381     // The ARM64_RELOC_ADDEND record holds the addend, and the paired
382     // ARM64_RELOC_BRANCH26 or ARM64_RELOC_PAGE21/PAGEOFF12 holds the
383     // base symbolic address.
384     //
385     // Note: X86 does not use *_RELOC_ADDEND because it can embed an
386     // addend into the instruction stream. On X86, a relocatable address
387     // field always occupies an entire contiguous sequence of byte(s),
388     // so there is no need to merge opcode bits with address
389     // bits. Therefore, it's easy and convenient to store addends in the
390     // instruction-stream bytes that would otherwise contain zeroes. By
391     // contrast, RISC ISAs such as ARM64 mix opcode bits with with
392     // address bits so that bitwise arithmetic is necessary to extract
393     // and insert them. Storing addends in the instruction stream is
394     // possible, but inconvenient and more costly at link time.
395 
396     int64_t pairedAddend = 0;
397     relocation_info relInfo = relInfos[i];
398     if (target->hasAttr(relInfo.r_type, RelocAttrBits::ADDEND)) {
399       pairedAddend = SignExtend64<24>(relInfo.r_symbolnum);
400       relInfo = relInfos[++i];
401     }
402     assert(i < relInfos.size());
403     if (!validateRelocationInfo(this, sec, relInfo))
404       continue;
405     if (relInfo.r_address & R_SCATTERED)
406       fatal("TODO: Scattered relocations not supported");
407 
408     bool isSubtrahend =
409         target->hasAttr(relInfo.r_type, RelocAttrBits::SUBTRAHEND);
410     int64_t embeddedAddend = target->getEmbeddedAddend(mb, sec.offset, relInfo);
411     assert(!(embeddedAddend && pairedAddend));
412     int64_t totalAddend = pairedAddend + embeddedAddend;
413     Reloc r;
414     r.type = relInfo.r_type;
415     r.pcrel = relInfo.r_pcrel;
416     r.length = relInfo.r_length;
417     r.offset = relInfo.r_address;
418     if (relInfo.r_extern) {
419       r.referent = symbols[relInfo.r_symbolnum];
420       r.addend = isSubtrahend ? 0 : totalAddend;
421     } else {
422       assert(!isSubtrahend);
423       const Section &referentSec = sectionHeaders[relInfo.r_symbolnum - 1];
424       uint64_t referentOffset;
425       if (relInfo.r_pcrel) {
426         // The implicit addend for pcrel section relocations is the pcrel offset
427         // in terms of the addresses in the input file. Here we adjust it so
428         // that it describes the offset from the start of the referent section.
429         // FIXME This logic was written around x86_64 behavior -- ARM64 doesn't
430         // have pcrel section relocations. We may want to factor this out into
431         // the arch-specific .cpp file.
432         assert(target->hasAttr(r.type, RelocAttrBits::BYTE4));
433         referentOffset =
434             sec.addr + relInfo.r_address + 4 + totalAddend - referentSec.addr;
435       } else {
436         // The addend for a non-pcrel relocation is its absolute address.
437         referentOffset = totalAddend - referentSec.addr;
438       }
439       SubsectionMap &referentSubsecMap = subsections[relInfo.r_symbolnum - 1];
440       r.referent = findContainingSubsection(referentSubsecMap, &referentOffset);
441       r.addend = referentOffset;
442     }
443 
444     // Find the subsection that this relocation belongs to.
445     // Though not required by the Mach-O format, clang and gcc seem to emit
446     // relocations in order, so let's take advantage of it. However, ld64 emits
447     // unsorted relocations (in `-r` mode), so we have a fallback for that
448     // uncommon case.
449     InputSection *subsec;
450     while (subsecIt != subsecMap.rend() && subsecIt->offset > r.offset)
451       ++subsecIt;
452     if (subsecIt == subsecMap.rend() ||
453         subsecIt->offset + subsecIt->isec->getSize() <= r.offset) {
454       subsec = findContainingSubsection(subsecMap, &r.offset);
455       // Now that we know the relocs are unsorted, avoid trying the 'fast path'
456       // for the other relocations.
457       subsecIt = subsecMap.rend();
458     } else {
459       subsec = subsecIt->isec;
460       r.offset -= subsecIt->offset;
461     }
462     subsec->relocs.push_back(r);
463 
464     if (isSubtrahend) {
465       relocation_info minuendInfo = relInfos[++i];
466       // SUBTRACTOR relocations should always be followed by an UNSIGNED one
467       // attached to the same address.
468       assert(target->hasAttr(minuendInfo.r_type, RelocAttrBits::UNSIGNED) &&
469              relInfo.r_address == minuendInfo.r_address);
470       Reloc p;
471       p.type = minuendInfo.r_type;
472       if (minuendInfo.r_extern) {
473         p.referent = symbols[minuendInfo.r_symbolnum];
474         p.addend = totalAddend;
475       } else {
476         uint64_t referentOffset =
477             totalAddend - sectionHeaders[minuendInfo.r_symbolnum - 1].addr;
478         SubsectionMap &referentSubsecMap =
479             subsections[minuendInfo.r_symbolnum - 1];
480         p.referent =
481             findContainingSubsection(referentSubsecMap, &referentOffset);
482         p.addend = referentOffset;
483       }
484       subsec->relocs.push_back(p);
485     }
486   }
487 }
488 
489 template <class NList>
490 static macho::Symbol *createDefined(const NList &sym, StringRef name,
491                                     InputSection *isec, uint64_t value,
492                                     uint64_t size) {
493   // Symbol scope is determined by sym.n_type & (N_EXT | N_PEXT):
494   // N_EXT: Global symbols. These go in the symbol table during the link,
495   //        and also in the export table of the output so that the dynamic
496   //        linker sees them.
497   // N_EXT | N_PEXT: Linkage unit (think: dylib) scoped. These go in the
498   //                 symbol table during the link so that duplicates are
499   //                 either reported (for non-weak symbols) or merged
500   //                 (for weak symbols), but they do not go in the export
501   //                 table of the output.
502   // N_PEXT: llvm-mc does not emit these, but `ld -r` (wherein ld64 emits
503   //         object files) may produce them. LLD does not yet support -r.
504   //         These are translation-unit scoped, identical to the `0` case.
505   // 0: Translation-unit scoped. These are not in the symbol table during
506   //    link, and not in the export table of the output either.
507   bool isWeakDefCanBeHidden =
508       (sym.n_desc & (N_WEAK_DEF | N_WEAK_REF)) == (N_WEAK_DEF | N_WEAK_REF);
509 
510   if (sym.n_type & N_EXT) {
511     bool isPrivateExtern = sym.n_type & N_PEXT;
512     // lld's behavior for merging symbols is slightly different from ld64:
513     // ld64 picks the winning symbol based on several criteria (see
514     // pickBetweenRegularAtoms() in ld64's SymbolTable.cpp), while lld
515     // just merges metadata and keeps the contents of the first symbol
516     // with that name (see SymbolTable::addDefined). For:
517     // * inline function F in a TU built with -fvisibility-inlines-hidden
518     // * and inline function F in another TU built without that flag
519     // ld64 will pick the one from the file built without
520     // -fvisibility-inlines-hidden.
521     // lld will instead pick the one listed first on the link command line and
522     // give it visibility as if the function was built without
523     // -fvisibility-inlines-hidden.
524     // If both functions have the same contents, this will have the same
525     // behavior. If not, it won't, but the input had an ODR violation in
526     // that case.
527     //
528     // Similarly, merging a symbol
529     // that's isPrivateExtern and not isWeakDefCanBeHidden with one
530     // that's not isPrivateExtern but isWeakDefCanBeHidden technically
531     // should produce one
532     // that's not isPrivateExtern but isWeakDefCanBeHidden. That matters
533     // with ld64's semantics, because it means the non-private-extern
534     // definition will continue to take priority if more private extern
535     // definitions are encountered. With lld's semantics there's no observable
536     // difference between a symbol that's isWeakDefCanBeHidden or one that's
537     // privateExtern -- neither makes it into the dynamic symbol table. So just
538     // promote isWeakDefCanBeHidden to isPrivateExtern here.
539     if (isWeakDefCanBeHidden)
540       isPrivateExtern = true;
541 
542     return symtab->addDefined(
543         name, isec->getFile(), isec, value, size, sym.n_desc & N_WEAK_DEF,
544         isPrivateExtern, sym.n_desc & N_ARM_THUMB_DEF,
545         sym.n_desc & REFERENCED_DYNAMICALLY, sym.n_desc & N_NO_DEAD_STRIP);
546   }
547 
548   assert(!isWeakDefCanBeHidden &&
549          "weak_def_can_be_hidden on already-hidden symbol?");
550   return make<Defined>(
551       name, isec->getFile(), isec, value, size, sym.n_desc & N_WEAK_DEF,
552       /*isExternal=*/false, /*isPrivateExtern=*/false,
553       sym.n_desc & N_ARM_THUMB_DEF, sym.n_desc & REFERENCED_DYNAMICALLY,
554       sym.n_desc & N_NO_DEAD_STRIP);
555 }
556 
557 // Absolute symbols are defined symbols that do not have an associated
558 // InputSection. They cannot be weak.
559 template <class NList>
560 static macho::Symbol *createAbsolute(const NList &sym, InputFile *file,
561                                      StringRef name) {
562   if (sym.n_type & N_EXT) {
563     return symtab->addDefined(name, file, nullptr, sym.n_value, /*size=*/0,
564                               /*isWeakDef=*/false, sym.n_type & N_PEXT,
565                               sym.n_desc & N_ARM_THUMB_DEF,
566                               /*isReferencedDynamically=*/false,
567                               sym.n_desc & N_NO_DEAD_STRIP);
568   }
569   return make<Defined>(name, file, nullptr, sym.n_value, /*size=*/0,
570                        /*isWeakDef=*/false,
571                        /*isExternal=*/false, /*isPrivateExtern=*/false,
572                        sym.n_desc & N_ARM_THUMB_DEF,
573                        /*isReferencedDynamically=*/false,
574                        sym.n_desc & N_NO_DEAD_STRIP);
575 }
576 
577 template <class NList>
578 macho::Symbol *ObjFile::parseNonSectionSymbol(const NList &sym,
579                                               StringRef name) {
580   uint8_t type = sym.n_type & N_TYPE;
581   switch (type) {
582   case N_UNDF:
583     return sym.n_value == 0
584                ? symtab->addUndefined(name, this, sym.n_desc & N_WEAK_REF)
585                : symtab->addCommon(name, this, sym.n_value,
586                                    1 << GET_COMM_ALIGN(sym.n_desc),
587                                    sym.n_type & N_PEXT);
588   case N_ABS:
589     return createAbsolute(sym, this, name);
590   case N_PBUD:
591   case N_INDR:
592     error("TODO: support symbols of type " + std::to_string(type));
593     return nullptr;
594   case N_SECT:
595     llvm_unreachable(
596         "N_SECT symbols should not be passed to parseNonSectionSymbol");
597   default:
598     llvm_unreachable("invalid symbol type");
599   }
600 }
601 
602 template <class LP>
603 void ObjFile::parseSymbols(ArrayRef<typename LP::section> sectionHeaders,
604                            ArrayRef<typename LP::nlist> nList,
605                            const char *strtab, bool subsectionsViaSymbols) {
606   using NList = typename LP::nlist;
607 
608   // Groups indices of the symbols by the sections that contain them.
609   std::vector<std::vector<uint32_t>> symbolsBySection(subsections.size());
610   symbols.resize(nList.size());
611   for (uint32_t i = 0; i < nList.size(); ++i) {
612     const NList &sym = nList[i];
613 
614     // Ignore debug symbols for now.
615     // FIXME: may need special handling.
616     if (sym.n_type & N_STAB)
617       continue;
618 
619     StringRef name = strtab + sym.n_strx;
620     if ((sym.n_type & N_TYPE) == N_SECT) {
621       SubsectionMap &subsecMap = subsections[sym.n_sect - 1];
622       // parseSections() may have chosen not to parse this section.
623       if (subsecMap.empty())
624         continue;
625       symbolsBySection[sym.n_sect - 1].push_back(i);
626     } else {
627       symbols[i] = parseNonSectionSymbol(sym, name);
628     }
629   }
630 
631   for (size_t i = 0; i < subsections.size(); ++i) {
632     SubsectionMap &subsecMap = subsections[i];
633     if (subsecMap.empty())
634       continue;
635 
636     std::vector<uint32_t> &symbolIndices = symbolsBySection[i];
637     uint64_t sectionAddr = sectionHeaders[i].addr;
638     uint32_t sectionAlign = 1u << sectionHeaders[i].align;
639 
640     InputSection *isec = subsecMap.back().isec;
641     // __cfstring has already been split into subsections during
642     // parseSections(), so we simply need to match Symbols to the corresponding
643     // subsection here.
644     if (config->icfLevel != ICFLevel::none && isCfStringSection(isec)) {
645       for (size_t j = 0; j < symbolIndices.size(); ++j) {
646         uint32_t symIndex = symbolIndices[j];
647         const NList &sym = nList[symIndex];
648         StringRef name = strtab + sym.n_strx;
649         uint64_t symbolOffset = sym.n_value - sectionAddr;
650         InputSection *isec = findContainingSubsection(subsecMap, &symbolOffset);
651         if (symbolOffset != 0) {
652           error(toString(this) + ": __cfstring contains symbol " + name +
653                 " at misaligned offset");
654           continue;
655         }
656         symbols[symIndex] = createDefined(sym, name, isec, 0, isec->getSize());
657       }
658       continue;
659     }
660 
661     // Calculate symbol sizes and create subsections by splitting the sections
662     // along symbol boundaries.
663     // We populate subsecMap by repeatedly splitting the last (highest address)
664     // subsection.
665     llvm::stable_sort(symbolIndices, [&](uint32_t lhs, uint32_t rhs) {
666       return nList[lhs].n_value < nList[rhs].n_value;
667     });
668     SubsectionEntry subsecEntry = subsecMap.back();
669     for (size_t j = 0; j < symbolIndices.size(); ++j) {
670       uint32_t symIndex = symbolIndices[j];
671       const NList &sym = nList[symIndex];
672       StringRef name = strtab + sym.n_strx;
673       InputSection *isec = subsecEntry.isec;
674 
675       uint64_t subsecAddr = sectionAddr + subsecEntry.offset;
676       size_t symbolOffset = sym.n_value - subsecAddr;
677       uint64_t symbolSize =
678           j + 1 < symbolIndices.size()
679               ? nList[symbolIndices[j + 1]].n_value - sym.n_value
680               : isec->data.size() - symbolOffset;
681       // There are 4 cases where we do not need to create a new subsection:
682       //   1. If the input file does not use subsections-via-symbols.
683       //   2. Multiple symbols at the same address only induce one subsection.
684       //      (The symbolOffset == 0 check covers both this case as well as
685       //      the first loop iteration.)
686       //   3. Alternative entry points do not induce new subsections.
687       //   4. If we have a literal section (e.g. __cstring and __literal4).
688       if (!subsectionsViaSymbols || symbolOffset == 0 ||
689           sym.n_desc & N_ALT_ENTRY || !isa<ConcatInputSection>(isec)) {
690         symbols[symIndex] =
691             createDefined(sym, name, isec, symbolOffset, symbolSize);
692         continue;
693       }
694       auto *concatIsec = cast<ConcatInputSection>(isec);
695 
696       auto *nextIsec = make<ConcatInputSection>(*concatIsec);
697       nextIsec->numRefs = 0;
698       nextIsec->wasCoalesced = false;
699       if (isZeroFill(isec->getFlags())) {
700         // Zero-fill sections have NULL data.data() non-zero data.size()
701         nextIsec->data = {nullptr, isec->data.size() - symbolOffset};
702         isec->data = {nullptr, symbolOffset};
703       } else {
704         nextIsec->data = isec->data.slice(symbolOffset);
705         isec->data = isec->data.slice(0, symbolOffset);
706       }
707 
708       // By construction, the symbol will be at offset zero in the new
709       // subsection.
710       symbols[symIndex] =
711           createDefined(sym, name, nextIsec, /*value=*/0, symbolSize);
712       // TODO: ld64 appears to preserve the original alignment as well as each
713       // subsection's offset from the last aligned address. We should consider
714       // emulating that behavior.
715       nextIsec->align = MinAlign(sectionAlign, sym.n_value);
716       subsecMap.push_back({sym.n_value - sectionAddr, nextIsec});
717       subsecEntry = subsecMap.back();
718     }
719   }
720 }
721 
722 OpaqueFile::OpaqueFile(MemoryBufferRef mb, StringRef segName,
723                        StringRef sectName)
724     : InputFile(OpaqueKind, mb) {
725   const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
726   ArrayRef<uint8_t> data = {buf, mb.getBufferSize()};
727   ConcatInputSection *isec =
728       make<ConcatInputSection>(segName.take_front(16), sectName.take_front(16),
729                                /*file=*/this, data);
730   isec->live = true;
731   subsections.push_back({{0, isec}});
732 }
733 
734 ObjFile::ObjFile(MemoryBufferRef mb, uint32_t modTime, StringRef archiveName)
735     : InputFile(ObjKind, mb), modTime(modTime) {
736   this->archiveName = std::string(archiveName);
737   if (target->wordSize == 8)
738     parse<LP64>();
739   else
740     parse<ILP32>();
741 }
742 
743 template <class LP> void ObjFile::parse() {
744   using Header = typename LP::mach_header;
745   using SegmentCommand = typename LP::segment_command;
746   using Section = typename LP::section;
747   using NList = typename LP::nlist;
748 
749   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
750   auto *hdr = reinterpret_cast<const Header *>(mb.getBufferStart());
751 
752   Architecture arch = getArchitectureFromCpuType(hdr->cputype, hdr->cpusubtype);
753   if (arch != config->arch()) {
754     error(toString(this) + " has architecture " + getArchitectureName(arch) +
755           " which is incompatible with target architecture " +
756           getArchitectureName(config->arch()));
757     return;
758   }
759 
760   if (!checkCompatibility(this))
761     return;
762 
763   for (auto *cmd : findCommands<linker_option_command>(hdr, LC_LINKER_OPTION)) {
764     StringRef data{reinterpret_cast<const char *>(cmd + 1),
765                    cmd->cmdsize - sizeof(linker_option_command)};
766     parseLCLinkerOption(this, cmd->count, data);
767   }
768 
769   ArrayRef<Section> sectionHeaders;
770   if (const load_command *cmd = findCommand(hdr, LP::segmentLCType)) {
771     auto *c = reinterpret_cast<const SegmentCommand *>(cmd);
772     sectionHeaders =
773         ArrayRef<Section>{reinterpret_cast<const Section *>(c + 1), c->nsects};
774     parseSections(sectionHeaders);
775   }
776 
777   // TODO: Error on missing LC_SYMTAB?
778   if (const load_command *cmd = findCommand(hdr, LC_SYMTAB)) {
779     auto *c = reinterpret_cast<const symtab_command *>(cmd);
780     ArrayRef<NList> nList(reinterpret_cast<const NList *>(buf + c->symoff),
781                           c->nsyms);
782     const char *strtab = reinterpret_cast<const char *>(buf) + c->stroff;
783     bool subsectionsViaSymbols = hdr->flags & MH_SUBSECTIONS_VIA_SYMBOLS;
784     parseSymbols<LP>(sectionHeaders, nList, strtab, subsectionsViaSymbols);
785   }
786 
787   // The relocations may refer to the symbols, so we parse them after we have
788   // parsed all the symbols.
789   for (size_t i = 0, n = subsections.size(); i < n; ++i)
790     if (!subsections[i].empty())
791       parseRelocations(sectionHeaders, sectionHeaders[i], subsections[i]);
792 
793   parseDebugInfo();
794   if (config->emitDataInCodeInfo)
795     parseDataInCode();
796 }
797 
798 void ObjFile::parseDebugInfo() {
799   std::unique_ptr<DwarfObject> dObj = DwarfObject::create(this);
800   if (!dObj)
801     return;
802 
803   auto *ctx = make<DWARFContext>(
804       std::move(dObj), "",
805       [&](Error err) {
806         warn(toString(this) + ": " + toString(std::move(err)));
807       },
808       [&](Error warning) {
809         warn(toString(this) + ": " + toString(std::move(warning)));
810       });
811 
812   // TODO: Since object files can contain a lot of DWARF info, we should verify
813   // that we are parsing just the info we need
814   const DWARFContext::compile_unit_range &units = ctx->compile_units();
815   // FIXME: There can be more than one compile unit per object file. See
816   // PR48637.
817   auto it = units.begin();
818   compileUnit = it->get();
819 }
820 
821 void ObjFile::parseDataInCode() {
822   const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
823   const load_command *cmd = findCommand(buf, LC_DATA_IN_CODE);
824   if (!cmd)
825     return;
826   const auto *c = reinterpret_cast<const linkedit_data_command *>(cmd);
827   dataInCodeEntries = {
828       reinterpret_cast<const data_in_code_entry *>(buf + c->dataoff),
829       c->datasize / sizeof(data_in_code_entry)};
830   assert(is_sorted(dataInCodeEntries, [](const data_in_code_entry &lhs,
831                                          const data_in_code_entry &rhs) {
832     return lhs.offset < rhs.offset;
833   }));
834 }
835 
836 // The path can point to either a dylib or a .tbd file.
837 static DylibFile *loadDylib(StringRef path, DylibFile *umbrella) {
838   Optional<MemoryBufferRef> mbref = readFile(path);
839   if (!mbref) {
840     error("could not read dylib file at " + path);
841     return nullptr;
842   }
843   return loadDylib(*mbref, umbrella);
844 }
845 
846 // TBD files are parsed into a series of TAPI documents (InterfaceFiles), with
847 // the first document storing child pointers to the rest of them. When we are
848 // processing a given TBD file, we store that top-level document in
849 // currentTopLevelTapi. When processing re-exports, we search its children for
850 // potentially matching documents in the same TBD file. Note that the children
851 // themselves don't point to further documents, i.e. this is a two-level tree.
852 //
853 // Re-exports can either refer to on-disk files, or to documents within .tbd
854 // files.
855 static DylibFile *findDylib(StringRef path, DylibFile *umbrella,
856                             const InterfaceFile *currentTopLevelTapi) {
857   if (path::is_absolute(path, path::Style::posix))
858     for (StringRef root : config->systemLibraryRoots)
859       if (Optional<std::string> dylibPath =
860               resolveDylibPath((root + path).str()))
861         return loadDylib(*dylibPath, umbrella);
862 
863   // TODO: Handle -dylib_file
864 
865   SmallString<128> newPath;
866   if (config->outputType == MH_EXECUTE &&
867       path.consume_front("@executable_path/")) {
868     // ld64 allows overriding this with the undocumented flag -executable_path.
869     // lld doesn't currently implement that flag.
870     // FIXME: Consider using finalOutput instead of outputFile.
871     path::append(newPath, path::parent_path(config->outputFile), path);
872     path = newPath;
873   } else if (path.consume_front("@loader_path/")) {
874     fs::real_path(umbrella->getName(), newPath);
875     path::remove_filename(newPath);
876     path::append(newPath, path);
877     path = newPath;
878   } else if (path.startswith("@rpath/")) {
879     for (StringRef rpath : umbrella->rpaths) {
880       newPath.clear();
881       if (rpath.consume_front("@loader_path/")) {
882         fs::real_path(umbrella->getName(), newPath);
883         path::remove_filename(newPath);
884       }
885       path::append(newPath, rpath, path.drop_front(strlen("@rpath/")));
886       if (Optional<std::string> dylibPath = resolveDylibPath(newPath))
887         return loadDylib(*dylibPath, umbrella);
888     }
889   }
890 
891   if (currentTopLevelTapi) {
892     for (InterfaceFile &child :
893          make_pointee_range(currentTopLevelTapi->documents())) {
894       assert(child.documents().empty());
895       if (path == child.getInstallName()) {
896         auto file = make<DylibFile>(child, umbrella);
897         file->parseReexports(child);
898         return file;
899       }
900     }
901   }
902 
903   if (Optional<std::string> dylibPath = resolveDylibPath(path))
904     return loadDylib(*dylibPath, umbrella);
905 
906   return nullptr;
907 }
908 
909 // If a re-exported dylib is public (lives in /usr/lib or
910 // /System/Library/Frameworks), then it is considered implicitly linked: we
911 // should bind to its symbols directly instead of via the re-exporting umbrella
912 // library.
913 static bool isImplicitlyLinked(StringRef path) {
914   if (!config->implicitDylibs)
915     return false;
916 
917   if (path::parent_path(path) == "/usr/lib")
918     return true;
919 
920   // Match /System/Library/Frameworks/$FOO.framework/**/$FOO
921   if (path.consume_front("/System/Library/Frameworks/")) {
922     StringRef frameworkName = path.take_until([](char c) { return c == '.'; });
923     return path::filename(path) == frameworkName;
924   }
925 
926   return false;
927 }
928 
929 static void loadReexport(StringRef path, DylibFile *umbrella,
930                          const InterfaceFile *currentTopLevelTapi) {
931   DylibFile *reexport = findDylib(path, umbrella, currentTopLevelTapi);
932   if (!reexport)
933     error("unable to locate re-export with install name " + path);
934 }
935 
936 DylibFile::DylibFile(MemoryBufferRef mb, DylibFile *umbrella,
937                      bool isBundleLoader)
938     : InputFile(DylibKind, mb), refState(RefState::Unreferenced),
939       isBundleLoader(isBundleLoader) {
940   assert(!isBundleLoader || !umbrella);
941   if (umbrella == nullptr)
942     umbrella = this;
943   this->umbrella = umbrella;
944 
945   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
946   auto *hdr = reinterpret_cast<const mach_header *>(mb.getBufferStart());
947 
948   // Initialize installName.
949   if (const load_command *cmd = findCommand(hdr, LC_ID_DYLIB)) {
950     auto *c = reinterpret_cast<const dylib_command *>(cmd);
951     currentVersion = read32le(&c->dylib.current_version);
952     compatibilityVersion = read32le(&c->dylib.compatibility_version);
953     installName =
954         reinterpret_cast<const char *>(cmd) + read32le(&c->dylib.name);
955   } else if (!isBundleLoader) {
956     // macho_executable and macho_bundle don't have LC_ID_DYLIB,
957     // so it's OK.
958     error("dylib " + toString(this) + " missing LC_ID_DYLIB load command");
959     return;
960   }
961 
962   if (config->printEachFile)
963     message(toString(this));
964   inputFiles.insert(this);
965 
966   deadStrippable = hdr->flags & MH_DEAD_STRIPPABLE_DYLIB;
967 
968   if (!checkCompatibility(this))
969     return;
970 
971   for (auto *cmd : findCommands<rpath_command>(hdr, LC_RPATH)) {
972     StringRef rpath{reinterpret_cast<const char *>(cmd) + cmd->path};
973     rpaths.push_back(rpath);
974   }
975 
976   // Initialize symbols.
977   exportingFile = isImplicitlyLinked(installName) ? this : this->umbrella;
978   if (const load_command *cmd = findCommand(hdr, LC_DYLD_INFO_ONLY)) {
979     auto *c = reinterpret_cast<const dyld_info_command *>(cmd);
980     parseTrie(buf + c->export_off, c->export_size,
981               [&](const Twine &name, uint64_t flags) {
982                 StringRef savedName = saver.save(name);
983                 if (handleLDSymbol(savedName))
984                   return;
985                 bool isWeakDef = flags & EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION;
986                 bool isTlv = flags & EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL;
987                 symbols.push_back(symtab->addDylib(savedName, exportingFile,
988                                                    isWeakDef, isTlv));
989               });
990   } else {
991     error("LC_DYLD_INFO_ONLY not found in " + toString(this));
992     return;
993   }
994 }
995 
996 void DylibFile::parseLoadCommands(MemoryBufferRef mb) {
997   auto *hdr = reinterpret_cast<const mach_header *>(mb.getBufferStart());
998   const uint8_t *p = reinterpret_cast<const uint8_t *>(mb.getBufferStart()) +
999                      target->headerSize;
1000   for (uint32_t i = 0, n = hdr->ncmds; i < n; ++i) {
1001     auto *cmd = reinterpret_cast<const load_command *>(p);
1002     p += cmd->cmdsize;
1003 
1004     if (!(hdr->flags & MH_NO_REEXPORTED_DYLIBS) &&
1005         cmd->cmd == LC_REEXPORT_DYLIB) {
1006       const auto *c = reinterpret_cast<const dylib_command *>(cmd);
1007       StringRef reexportPath =
1008           reinterpret_cast<const char *>(c) + read32le(&c->dylib.name);
1009       loadReexport(reexportPath, exportingFile, nullptr);
1010     }
1011 
1012     // FIXME: What about LC_LOAD_UPWARD_DYLIB, LC_LAZY_LOAD_DYLIB,
1013     // LC_LOAD_WEAK_DYLIB, LC_REEXPORT_DYLIB (..are reexports from dylibs with
1014     // MH_NO_REEXPORTED_DYLIBS loaded for -flat_namespace)?
1015     if (config->namespaceKind == NamespaceKind::flat &&
1016         cmd->cmd == LC_LOAD_DYLIB) {
1017       const auto *c = reinterpret_cast<const dylib_command *>(cmd);
1018       StringRef dylibPath =
1019           reinterpret_cast<const char *>(c) + read32le(&c->dylib.name);
1020       DylibFile *dylib = findDylib(dylibPath, umbrella, nullptr);
1021       if (!dylib)
1022         error(Twine("unable to locate library '") + dylibPath +
1023               "' loaded from '" + toString(this) + "' for -flat_namespace");
1024     }
1025   }
1026 }
1027 
1028 // Some versions of XCode ship with .tbd files that don't have the right
1029 // platform settings.
1030 static constexpr std::array<StringRef, 3> skipPlatformChecks{
1031     "/usr/lib/system/libsystem_kernel.dylib",
1032     "/usr/lib/system/libsystem_platform.dylib",
1033     "/usr/lib/system/libsystem_pthread.dylib"};
1034 
1035 DylibFile::DylibFile(const InterfaceFile &interface, DylibFile *umbrella,
1036                      bool isBundleLoader)
1037     : InputFile(DylibKind, interface), refState(RefState::Unreferenced),
1038       isBundleLoader(isBundleLoader) {
1039   // FIXME: Add test for the missing TBD code path.
1040 
1041   if (umbrella == nullptr)
1042     umbrella = this;
1043   this->umbrella = umbrella;
1044 
1045   installName = saver.save(interface.getInstallName());
1046   compatibilityVersion = interface.getCompatibilityVersion().rawValue();
1047   currentVersion = interface.getCurrentVersion().rawValue();
1048 
1049   if (config->printEachFile)
1050     message(toString(this));
1051   inputFiles.insert(this);
1052 
1053   if (!is_contained(skipPlatformChecks, installName) &&
1054       !is_contained(interface.targets(), config->platformInfo.target)) {
1055     error(toString(this) + " is incompatible with " +
1056           std::string(config->platformInfo.target));
1057     return;
1058   }
1059 
1060   exportingFile = isImplicitlyLinked(installName) ? this : umbrella;
1061   auto addSymbol = [&](const Twine &name) -> void {
1062     symbols.push_back(symtab->addDylib(saver.save(name), exportingFile,
1063                                        /*isWeakDef=*/false,
1064                                        /*isTlv=*/false));
1065   };
1066   // TODO(compnerd) filter out symbols based on the target platform
1067   // TODO: handle weak defs, thread locals
1068   for (const auto *symbol : interface.symbols()) {
1069     if (!symbol->getArchitectures().has(config->arch()))
1070       continue;
1071 
1072     if (handleLDSymbol(symbol->getName()))
1073       continue;
1074 
1075     switch (symbol->getKind()) {
1076     case SymbolKind::GlobalSymbol:
1077       addSymbol(symbol->getName());
1078       break;
1079     case SymbolKind::ObjectiveCClass:
1080       // XXX ld64 only creates these symbols when -ObjC is passed in. We may
1081       // want to emulate that.
1082       addSymbol(objc::klass + symbol->getName());
1083       addSymbol(objc::metaclass + symbol->getName());
1084       break;
1085     case SymbolKind::ObjectiveCClassEHType:
1086       addSymbol(objc::ehtype + symbol->getName());
1087       break;
1088     case SymbolKind::ObjectiveCInstanceVariable:
1089       addSymbol(objc::ivar + symbol->getName());
1090       break;
1091     }
1092   }
1093 }
1094 
1095 void DylibFile::parseReexports(const InterfaceFile &interface) {
1096   const InterfaceFile *topLevel =
1097       interface.getParent() == nullptr ? &interface : interface.getParent();
1098   for (InterfaceFileRef intfRef : interface.reexportedLibraries()) {
1099     InterfaceFile::const_target_range targets = intfRef.targets();
1100     if (is_contained(skipPlatformChecks, intfRef.getInstallName()) ||
1101         is_contained(targets, config->platformInfo.target))
1102       loadReexport(intfRef.getInstallName(), exportingFile, topLevel);
1103   }
1104 }
1105 
1106 // $ld$ symbols modify the properties/behavior of the library (e.g. its install
1107 // name, compatibility version or hide/add symbols) for specific target
1108 // versions.
1109 bool DylibFile::handleLDSymbol(StringRef originalName) {
1110   if (!originalName.startswith("$ld$"))
1111     return false;
1112 
1113   StringRef action;
1114   StringRef name;
1115   std::tie(action, name) = originalName.drop_front(strlen("$ld$")).split('$');
1116   if (action == "previous")
1117     handleLDPreviousSymbol(name, originalName);
1118   else if (action == "install_name")
1119     handleLDInstallNameSymbol(name, originalName);
1120   return true;
1121 }
1122 
1123 void DylibFile::handleLDPreviousSymbol(StringRef name, StringRef originalName) {
1124   // originalName: $ld$ previous $ <installname> $ <compatversion> $
1125   // <platformstr> $ <startversion> $ <endversion> $ <symbol-name> $
1126   StringRef installName;
1127   StringRef compatVersion;
1128   StringRef platformStr;
1129   StringRef startVersion;
1130   StringRef endVersion;
1131   StringRef symbolName;
1132   StringRef rest;
1133 
1134   std::tie(installName, name) = name.split('$');
1135   std::tie(compatVersion, name) = name.split('$');
1136   std::tie(platformStr, name) = name.split('$');
1137   std::tie(startVersion, name) = name.split('$');
1138   std::tie(endVersion, name) = name.split('$');
1139   std::tie(symbolName, rest) = name.split('$');
1140   // TODO: ld64 contains some logic for non-empty symbolName as well.
1141   if (!symbolName.empty())
1142     return;
1143   unsigned platform;
1144   if (platformStr.getAsInteger(10, platform) ||
1145       platform != static_cast<unsigned>(config->platform()))
1146     return;
1147 
1148   VersionTuple start;
1149   if (start.tryParse(startVersion)) {
1150     warn("failed to parse start version, symbol '" + originalName +
1151          "' ignored");
1152     return;
1153   }
1154   VersionTuple end;
1155   if (end.tryParse(endVersion)) {
1156     warn("failed to parse end version, symbol '" + originalName + "' ignored");
1157     return;
1158   }
1159   if (config->platformInfo.minimum < start ||
1160       config->platformInfo.minimum >= end)
1161     return;
1162 
1163   this->installName = saver.save(installName);
1164 
1165   if (!compatVersion.empty()) {
1166     VersionTuple cVersion;
1167     if (cVersion.tryParse(compatVersion)) {
1168       warn("failed to parse compatibility version, symbol '" + originalName +
1169            "' ignored");
1170       return;
1171     }
1172     compatibilityVersion = encodeVersion(cVersion);
1173   }
1174 }
1175 
1176 void DylibFile::handleLDInstallNameSymbol(StringRef name,
1177                                           StringRef originalName) {
1178   // originalName: $ld$ install_name $ os<version> $ install_name
1179   StringRef condition, installName;
1180   std::tie(condition, installName) = name.split('$');
1181   VersionTuple version;
1182   if (!condition.consume_front("os") || version.tryParse(condition))
1183     warn("failed to parse os version, symbol '" + originalName + "' ignored");
1184   else if (version == config->platformInfo.minimum)
1185     this->installName = saver.save(installName);
1186 }
1187 
1188 ArchiveFile::ArchiveFile(std::unique_ptr<object::Archive> &&f)
1189     : InputFile(ArchiveKind, f->getMemoryBufferRef()), file(std::move(f)) {
1190   for (const object::Archive::Symbol &sym : file->symbols())
1191     symtab->addLazy(sym.getName(), this, sym);
1192 }
1193 
1194 void ArchiveFile::fetch(const object::Archive::Symbol &sym) {
1195   object::Archive::Child c =
1196       CHECK(sym.getMember(), toString(this) +
1197                                  ": could not get the member for symbol " +
1198                                  toMachOString(sym));
1199 
1200   if (!seen.insert(c.getChildOffset()).second)
1201     return;
1202 
1203   MemoryBufferRef mb =
1204       CHECK(c.getMemoryBufferRef(),
1205             toString(this) +
1206                 ": could not get the buffer for the member defining symbol " +
1207                 toMachOString(sym));
1208 
1209   if (tar && c.getParent()->isThin())
1210     tar->append(relativeToRoot(CHECK(c.getFullName(), this)), mb.getBuffer());
1211 
1212   uint32_t modTime = toTimeT(
1213       CHECK(c.getLastModified(), toString(this) +
1214                                      ": could not get the modification time "
1215                                      "for the member defining symbol " +
1216                                      toMachOString(sym)));
1217 
1218   // `sym` is owned by a LazySym, which will be replace<>()d by make<ObjFile>
1219   // and become invalid after that call. Copy it to the stack so we can refer
1220   // to it later.
1221   const object::Archive::Symbol symCopy = sym;
1222 
1223   if (Optional<InputFile *> file =
1224           loadArchiveMember(mb, modTime, getName(), /*objCOnly=*/false)) {
1225     inputFiles.insert(*file);
1226     // ld64 doesn't demangle sym here even with -demangle.
1227     // Match that: intentionally don't call toMachOString().
1228     printArchiveMemberLoad(symCopy.getName(), *file);
1229   }
1230 }
1231 
1232 static macho::Symbol *createBitcodeSymbol(const lto::InputFile::Symbol &objSym,
1233                                           BitcodeFile &file) {
1234   StringRef name = saver.save(objSym.getName());
1235 
1236   // TODO: support weak references
1237   if (objSym.isUndefined())
1238     return symtab->addUndefined(name, &file, /*isWeakRef=*/false);
1239 
1240   assert(!objSym.isCommon() && "TODO: support common symbols in LTO");
1241 
1242   // TODO: Write a test demonstrating why computing isPrivateExtern before
1243   // LTO compilation is important.
1244   bool isPrivateExtern = false;
1245   switch (objSym.getVisibility()) {
1246   case GlobalValue::HiddenVisibility:
1247     isPrivateExtern = true;
1248     break;
1249   case GlobalValue::ProtectedVisibility:
1250     error(name + " has protected visibility, which is not supported by Mach-O");
1251     break;
1252   case GlobalValue::DefaultVisibility:
1253     break;
1254   }
1255 
1256   return symtab->addDefined(name, &file, /*isec=*/nullptr, /*value=*/0,
1257                             /*size=*/0, objSym.isWeak(), isPrivateExtern,
1258                             /*isThumb=*/false,
1259                             /*isReferencedDynamically=*/false,
1260                             /*noDeadStrip=*/false);
1261 }
1262 
1263 BitcodeFile::BitcodeFile(MemoryBufferRef mbref)
1264     : InputFile(BitcodeKind, mbref) {
1265   obj = check(lto::InputFile::create(mbref));
1266 
1267   // Convert LTO Symbols to LLD Symbols in order to perform resolution. The
1268   // "winning" symbol will then be marked as Prevailing at LTO compilation
1269   // time.
1270   for (const lto::InputFile::Symbol &objSym : obj->symbols())
1271     symbols.push_back(createBitcodeSymbol(objSym, *this));
1272 }
1273 
1274 template void ObjFile::parse<LP64>();
1275