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