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