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