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