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