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(
492         name, isec->file, isec, value, size, sym.n_desc & N_WEAK_DEF,
493         isPrivateExtern, sym.n_desc & N_ARM_THUMB_DEF,
494         sym.n_desc & REFERENCED_DYNAMICALLY, sym.n_desc & N_NO_DEAD_STRIP);
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       sym.n_desc & N_NO_DEAD_STRIP);
504 }
505 
506 // Absolute symbols are defined symbols that do not have an associated
507 // InputSection. They cannot be weak.
508 template <class NList>
509 static macho::Symbol *createAbsolute(const NList &sym, InputFile *file,
510                                      StringRef name) {
511   if (sym.n_type & (N_EXT | N_PEXT)) {
512     assert((sym.n_type & N_EXT) && "invalid input");
513     return symtab->addDefined(name, file, nullptr, sym.n_value, /*size=*/0,
514                               /*isWeakDef=*/false, sym.n_type & N_PEXT,
515                               sym.n_desc & N_ARM_THUMB_DEF,
516                               /*isReferencedDynamically=*/false,
517                               sym.n_desc & N_NO_DEAD_STRIP);
518   }
519   return make<Defined>(name, file, nullptr, sym.n_value, /*size=*/0,
520                        /*isWeakDef=*/false,
521                        /*isExternal=*/false, /*isPrivateExtern=*/false,
522                        sym.n_desc & N_ARM_THUMB_DEF,
523                        /*isReferencedDynamically=*/false,
524                        sym.n_desc & N_NO_DEAD_STRIP);
525 }
526 
527 template <class NList>
528 macho::Symbol *ObjFile::parseNonSectionSymbol(const NList &sym,
529                                               StringRef name) {
530   uint8_t type = sym.n_type & N_TYPE;
531   switch (type) {
532   case N_UNDF:
533     return sym.n_value == 0
534                ? symtab->addUndefined(name, this, sym.n_desc & N_WEAK_REF)
535                : symtab->addCommon(name, this, sym.n_value,
536                                    1 << GET_COMM_ALIGN(sym.n_desc),
537                                    sym.n_type & N_PEXT);
538   case N_ABS:
539     return createAbsolute(sym, this, name);
540   case N_PBUD:
541   case N_INDR:
542     error("TODO: support symbols of type " + std::to_string(type));
543     return nullptr;
544   case N_SECT:
545     llvm_unreachable(
546         "N_SECT symbols should not be passed to parseNonSectionSymbol");
547   default:
548     llvm_unreachable("invalid symbol type");
549   }
550 }
551 
552 template <class LP>
553 void ObjFile::parseSymbols(ArrayRef<typename LP::section> sectionHeaders,
554                            ArrayRef<typename LP::nlist> nList,
555                            const char *strtab, bool subsectionsViaSymbols) {
556   using NList = typename LP::nlist;
557 
558   // Groups indices of the symbols by the sections that contain them.
559   std::vector<std::vector<uint32_t>> symbolsBySection(subsections.size());
560   symbols.resize(nList.size());
561   for (uint32_t i = 0; i < nList.size(); ++i) {
562     const NList &sym = nList[i];
563     StringRef name = strtab + sym.n_strx;
564     if ((sym.n_type & N_TYPE) == N_SECT) {
565       SubsectionMap &subsecMap = subsections[sym.n_sect - 1];
566       // parseSections() may have chosen not to parse this section.
567       if (subsecMap.empty())
568         continue;
569       symbolsBySection[sym.n_sect - 1].push_back(i);
570     } else {
571       symbols[i] = parseNonSectionSymbol(sym, name);
572     }
573   }
574 
575   // Calculate symbol sizes and create subsections by splitting the sections
576   // along symbol boundaries.
577   for (size_t i = 0; i < subsections.size(); ++i) {
578     SubsectionMap &subsecMap = subsections[i];
579     if (subsecMap.empty())
580       continue;
581 
582     std::vector<uint32_t> &symbolIndices = symbolsBySection[i];
583     llvm::sort(symbolIndices, [&](uint32_t lhs, uint32_t rhs) {
584       return nList[lhs].n_value < nList[rhs].n_value;
585     });
586     uint64_t sectionAddr = sectionHeaders[i].addr;
587     uint32_t sectionAlign = 1u << sectionHeaders[i].align;
588 
589     // We populate subsecMap by repeatedly splitting the last (highest address)
590     // subsection.
591     SubsectionEntry subsecEntry = subsecMap.back();
592     for (size_t j = 0; j < symbolIndices.size(); ++j) {
593       uint32_t symIndex = symbolIndices[j];
594       const NList &sym = nList[symIndex];
595       StringRef name = strtab + sym.n_strx;
596       InputSection *isec = subsecEntry.isec;
597 
598       uint64_t subsecAddr = sectionAddr + subsecEntry.offset;
599       uint64_t symbolOffset = sym.n_value - subsecAddr;
600       uint64_t symbolSize =
601           j + 1 < symbolIndices.size()
602               ? nList[symbolIndices[j + 1]].n_value - sym.n_value
603               : isec->data.size() - symbolOffset;
604       // There are 3 cases where we do not need to create a new subsection:
605       //   1. If the input file does not use subsections-via-symbols.
606       //   2. Multiple symbols at the same address only induce one subsection.
607       //      (The symbolOffset == 0 check covers both this case as well as
608       //      the first loop iteration.)
609       //   3. Alternative entry points do not induce new subsections.
610       if (!subsectionsViaSymbols || symbolOffset == 0 ||
611           sym.n_desc & N_ALT_ENTRY) {
612         symbols[symIndex] =
613             createDefined(sym, name, isec, symbolOffset, symbolSize);
614         continue;
615       }
616 
617       auto *nextIsec = make<InputSection>(*isec);
618       nextIsec->data = isec->data.slice(symbolOffset);
619       nextIsec->numRefs = 0;
620       nextIsec->wasCoalesced = false;
621       isec->data = isec->data.slice(0, symbolOffset);
622 
623       // By construction, the symbol will be at offset zero in the new
624       // subsection.
625       symbols[symIndex] =
626           createDefined(sym, name, nextIsec, /*value=*/0, symbolSize);
627       // TODO: ld64 appears to preserve the original alignment as well as each
628       // subsection's offset from the last aligned address. We should consider
629       // emulating that behavior.
630       nextIsec->align = MinAlign(sectionAlign, sym.n_value);
631       subsecMap.push_back({sym.n_value - sectionAddr, nextIsec});
632       subsecEntry = subsecMap.back();
633     }
634   }
635 }
636 
637 OpaqueFile::OpaqueFile(MemoryBufferRef mb, StringRef segName,
638                        StringRef sectName)
639     : InputFile(OpaqueKind, mb) {
640   InputSection *isec = make<InputSection>();
641   isec->file = this;
642   isec->name = sectName.take_front(16);
643   isec->segname = segName.take_front(16);
644   const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
645   isec->data = {buf, mb.getBufferSize()};
646   isec->live = true;
647   subsections.push_back({{0, isec}});
648 }
649 
650 ObjFile::ObjFile(MemoryBufferRef mb, uint32_t modTime, StringRef archiveName)
651     : InputFile(ObjKind, mb), modTime(modTime) {
652   this->archiveName = std::string(archiveName);
653   if (target->wordSize == 8)
654     parse<LP64>();
655   else
656     parse<ILP32>();
657 }
658 
659 template <class LP> void ObjFile::parse() {
660   using Header = typename LP::mach_header;
661   using SegmentCommand = typename LP::segment_command;
662   using Section = typename LP::section;
663   using NList = typename LP::nlist;
664 
665   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
666   auto *hdr = reinterpret_cast<const Header *>(mb.getBufferStart());
667 
668   Architecture arch = getArchitectureFromCpuType(hdr->cputype, hdr->cpusubtype);
669   if (arch != config->arch()) {
670     error(toString(this) + " has architecture " + getArchitectureName(arch) +
671           " which is incompatible with target architecture " +
672           getArchitectureName(config->arch()));
673     return;
674   }
675 
676   if (!checkCompatibility(this))
677     return;
678 
679   if (const load_command *cmd = findCommand(hdr, LC_LINKER_OPTION)) {
680     auto *c = reinterpret_cast<const linker_option_command *>(cmd);
681     StringRef data{reinterpret_cast<const char *>(c + 1),
682                    c->cmdsize - sizeof(linker_option_command)};
683     parseLCLinkerOption(this, c->count, data);
684   }
685 
686   ArrayRef<Section> sectionHeaders;
687   if (const load_command *cmd = findCommand(hdr, LP::segmentLCType)) {
688     auto *c = reinterpret_cast<const SegmentCommand *>(cmd);
689     sectionHeaders =
690         ArrayRef<Section>{reinterpret_cast<const Section *>(c + 1), c->nsects};
691     parseSections(sectionHeaders);
692   }
693 
694   // TODO: Error on missing LC_SYMTAB?
695   if (const load_command *cmd = findCommand(hdr, LC_SYMTAB)) {
696     auto *c = reinterpret_cast<const symtab_command *>(cmd);
697     ArrayRef<NList> nList(reinterpret_cast<const NList *>(buf + c->symoff),
698                           c->nsyms);
699     const char *strtab = reinterpret_cast<const char *>(buf) + c->stroff;
700     bool subsectionsViaSymbols = hdr->flags & MH_SUBSECTIONS_VIA_SYMBOLS;
701     parseSymbols<LP>(sectionHeaders, nList, strtab, subsectionsViaSymbols);
702   }
703 
704   // The relocations may refer to the symbols, so we parse them after we have
705   // parsed all the symbols.
706   for (size_t i = 0, n = subsections.size(); i < n; ++i)
707     if (!subsections[i].empty())
708       parseRelocations(sectionHeaders, sectionHeaders[i], subsections[i]);
709 
710   parseDebugInfo();
711 }
712 
713 void ObjFile::parseDebugInfo() {
714   std::unique_ptr<DwarfObject> dObj = DwarfObject::create(this);
715   if (!dObj)
716     return;
717 
718   auto *ctx = make<DWARFContext>(
719       std::move(dObj), "",
720       [&](Error err) {
721         warn(toString(this) + ": " + toString(std::move(err)));
722       },
723       [&](Error warning) {
724         warn(toString(this) + ": " + toString(std::move(warning)));
725       });
726 
727   // TODO: Since object files can contain a lot of DWARF info, we should verify
728   // that we are parsing just the info we need
729   const DWARFContext::compile_unit_range &units = ctx->compile_units();
730   // FIXME: There can be more than one compile unit per object file. See
731   // PR48637.
732   auto it = units.begin();
733   compileUnit = it->get();
734 }
735 
736 // The path can point to either a dylib or a .tbd file.
737 static DylibFile *loadDylib(StringRef path, DylibFile *umbrella) {
738   Optional<MemoryBufferRef> mbref = readFile(path);
739   if (!mbref) {
740     error("could not read dylib file at " + path);
741     return nullptr;
742   }
743   return loadDylib(*mbref, umbrella);
744 }
745 
746 // TBD files are parsed into a series of TAPI documents (InterfaceFiles), with
747 // the first document storing child pointers to the rest of them. When we are
748 // processing a given TBD file, we store that top-level document in
749 // currentTopLevelTapi. When processing re-exports, we search its children for
750 // potentially matching documents in the same TBD file. Note that the children
751 // themselves don't point to further documents, i.e. this is a two-level tree.
752 //
753 // Re-exports can either refer to on-disk files, or to documents within .tbd
754 // files.
755 DylibFile *findDylib(StringRef path, DylibFile *umbrella,
756                      const InterfaceFile *currentTopLevelTapi) {
757   if (path::is_absolute(path, path::Style::posix))
758     for (StringRef root : config->systemLibraryRoots)
759       if (Optional<std::string> dylibPath =
760               resolveDylibPath((root + path).str()))
761         return loadDylib(*dylibPath, umbrella);
762 
763   // TODO: Expand @loader_path, @executable_path, @rpath etc, handle -dylib_path
764 
765   if (currentTopLevelTapi) {
766     for (InterfaceFile &child :
767          make_pointee_range(currentTopLevelTapi->documents())) {
768       assert(child.documents().empty());
769       if (path == child.getInstallName())
770         return make<DylibFile>(child, umbrella);
771     }
772   }
773 
774   if (Optional<std::string> dylibPath = resolveDylibPath(path))
775     return loadDylib(*dylibPath, umbrella);
776 
777   return nullptr;
778 }
779 
780 // If a re-exported dylib is public (lives in /usr/lib or
781 // /System/Library/Frameworks), then it is considered implicitly linked: we
782 // should bind to its symbols directly instead of via the re-exporting umbrella
783 // library.
784 static bool isImplicitlyLinked(StringRef path) {
785   if (!config->implicitDylibs)
786     return false;
787 
788   if (path::parent_path(path) == "/usr/lib")
789     return true;
790 
791   // Match /System/Library/Frameworks/$FOO.framework/**/$FOO
792   if (path.consume_front("/System/Library/Frameworks/")) {
793     StringRef frameworkName = path.take_until([](char c) { return c == '.'; });
794     return path::filename(path) == frameworkName;
795   }
796 
797   return false;
798 }
799 
800 void loadReexport(StringRef path, DylibFile *umbrella,
801                   const InterfaceFile *currentTopLevelTapi) {
802   DylibFile *reexport = findDylib(path, umbrella, currentTopLevelTapi);
803   if (!reexport)
804     error("unable to locate re-export with install name " + path);
805   else if (isImplicitlyLinked(path))
806     inputFiles.insert(reexport);
807 }
808 
809 DylibFile::DylibFile(MemoryBufferRef mb, DylibFile *umbrella,
810                      bool isBundleLoader)
811     : InputFile(DylibKind, mb), refState(RefState::Unreferenced),
812       isBundleLoader(isBundleLoader) {
813   assert(!isBundleLoader || !umbrella);
814   if (umbrella == nullptr)
815     umbrella = this;
816 
817   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
818   auto *hdr = reinterpret_cast<const mach_header *>(mb.getBufferStart());
819 
820   // Initialize dylibName.
821   if (const load_command *cmd = findCommand(hdr, LC_ID_DYLIB)) {
822     auto *c = reinterpret_cast<const dylib_command *>(cmd);
823     currentVersion = read32le(&c->dylib.current_version);
824     compatibilityVersion = read32le(&c->dylib.compatibility_version);
825     dylibName = reinterpret_cast<const char *>(cmd) + read32le(&c->dylib.name);
826   } else if (!isBundleLoader) {
827     // macho_executable and macho_bundle don't have LC_ID_DYLIB,
828     // so it's OK.
829     error("dylib " + toString(this) + " missing LC_ID_DYLIB load command");
830     return;
831   }
832 
833   if (config->printEachFile)
834     message(toString(this));
835 
836   deadStrippable = hdr->flags & MH_DEAD_STRIPPABLE_DYLIB;
837 
838   if (!checkCompatibility(this))
839     return;
840 
841   // Initialize symbols.
842   exportingFile = isImplicitlyLinked(dylibName) ? this : umbrella;
843   if (const load_command *cmd = findCommand(hdr, LC_DYLD_INFO_ONLY)) {
844     auto *c = reinterpret_cast<const dyld_info_command *>(cmd);
845     parseTrie(buf + c->export_off, c->export_size,
846               [&](const Twine &name, uint64_t flags) {
847                 bool isWeakDef = flags & EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION;
848                 bool isTlv = flags & EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL;
849                 symbols.push_back(symtab->addDylib(
850                     saver.save(name), exportingFile, isWeakDef, isTlv));
851               });
852   } else {
853     error("LC_DYLD_INFO_ONLY not found in " + toString(this));
854     return;
855   }
856 }
857 
858 void DylibFile::parseLoadCommands(MemoryBufferRef mb, DylibFile *umbrella) {
859   auto *hdr = reinterpret_cast<const mach_header *>(mb.getBufferStart());
860   const uint8_t *p = reinterpret_cast<const uint8_t *>(mb.getBufferStart()) +
861                      target->headerSize;
862   for (uint32_t i = 0, n = hdr->ncmds; i < n; ++i) {
863     auto *cmd = reinterpret_cast<const load_command *>(p);
864     p += cmd->cmdsize;
865 
866     if (!(hdr->flags & MH_NO_REEXPORTED_DYLIBS) &&
867         cmd->cmd == LC_REEXPORT_DYLIB) {
868       const auto *c = reinterpret_cast<const dylib_command *>(cmd);
869       StringRef reexportPath =
870           reinterpret_cast<const char *>(c) + read32le(&c->dylib.name);
871       loadReexport(reexportPath, exportingFile, nullptr);
872     }
873 
874     // FIXME: What about LC_LOAD_UPWARD_DYLIB, LC_LAZY_LOAD_DYLIB,
875     // LC_LOAD_WEAK_DYLIB, LC_REEXPORT_DYLIB (..are reexports from dylibs with
876     // MH_NO_REEXPORTED_DYLIBS loaded for -flat_namespace)?
877     if (config->namespaceKind == NamespaceKind::flat &&
878         cmd->cmd == LC_LOAD_DYLIB) {
879       const auto *c = reinterpret_cast<const dylib_command *>(cmd);
880       StringRef dylibPath =
881           reinterpret_cast<const char *>(c) + read32le(&c->dylib.name);
882       DylibFile *dylib = findDylib(dylibPath, umbrella, nullptr);
883       if (!dylib)
884         error(Twine("unable to locate library '") + dylibPath +
885               "' loaded from '" + toString(this) + "' for -flat_namespace");
886     }
887   }
888 }
889 
890 // Some versions of XCode ship with .tbd files that don't have the right
891 // platform settings.
892 static constexpr std::array<StringRef, 3> skipPlatformChecks{
893     "/usr/lib/system/libsystem_kernel.dylib",
894     "/usr/lib/system/libsystem_platform.dylib",
895     "/usr/lib/system/libsystem_pthread.dylib"};
896 
897 DylibFile::DylibFile(const InterfaceFile &interface, DylibFile *umbrella,
898                      bool isBundleLoader)
899     : InputFile(DylibKind, interface), refState(RefState::Unreferenced),
900       isBundleLoader(isBundleLoader) {
901   // FIXME: Add test for the missing TBD code path.
902 
903   if (umbrella == nullptr)
904     umbrella = this;
905 
906   dylibName = saver.save(interface.getInstallName());
907   compatibilityVersion = interface.getCompatibilityVersion().rawValue();
908   currentVersion = interface.getCurrentVersion().rawValue();
909 
910   if (config->printEachFile)
911     message(toString(this));
912 
913   if (!is_contained(skipPlatformChecks, dylibName) &&
914       !is_contained(interface.targets(), config->platformInfo.target)) {
915     error(toString(this) + " is incompatible with " +
916           std::string(config->platformInfo.target));
917     return;
918   }
919 
920   exportingFile = isImplicitlyLinked(dylibName) ? this : umbrella;
921   auto addSymbol = [&](const Twine &name) -> void {
922     symbols.push_back(symtab->addDylib(saver.save(name), exportingFile,
923                                        /*isWeakDef=*/false,
924                                        /*isTlv=*/false));
925   };
926   // TODO(compnerd) filter out symbols based on the target platform
927   // TODO: handle weak defs, thread locals
928   for (const auto *symbol : interface.symbols()) {
929     if (!symbol->getArchitectures().has(config->arch()))
930       continue;
931 
932     switch (symbol->getKind()) {
933     case SymbolKind::GlobalSymbol:
934       addSymbol(symbol->getName());
935       break;
936     case SymbolKind::ObjectiveCClass:
937       // XXX ld64 only creates these symbols when -ObjC is passed in. We may
938       // want to emulate that.
939       addSymbol(objc::klass + symbol->getName());
940       addSymbol(objc::metaclass + symbol->getName());
941       break;
942     case SymbolKind::ObjectiveCClassEHType:
943       addSymbol(objc::ehtype + symbol->getName());
944       break;
945     case SymbolKind::ObjectiveCInstanceVariable:
946       addSymbol(objc::ivar + symbol->getName());
947       break;
948     }
949   }
950 }
951 
952 void DylibFile::parseReexports(const llvm::MachO::InterfaceFile &interface) {
953   const InterfaceFile *topLevel =
954       interface.getParent() == nullptr ? &interface : interface.getParent();
955   for (InterfaceFileRef intfRef : interface.reexportedLibraries()) {
956     InterfaceFile::const_target_range targets = intfRef.targets();
957     if (is_contained(skipPlatformChecks, intfRef.getInstallName()) ||
958         is_contained(targets, config->platformInfo.target))
959       loadReexport(intfRef.getInstallName(), exportingFile, topLevel);
960   }
961 }
962 
963 ArchiveFile::ArchiveFile(std::unique_ptr<object::Archive> &&f)
964     : InputFile(ArchiveKind, f->getMemoryBufferRef()), file(std::move(f)) {
965   for (const object::Archive::Symbol &sym : file->symbols())
966     symtab->addLazy(sym.getName(), this, sym);
967 }
968 
969 void ArchiveFile::fetch(const object::Archive::Symbol &sym) {
970   object::Archive::Child c =
971       CHECK(sym.getMember(), toString(this) +
972                                  ": could not get the member for symbol " +
973                                  toMachOString(sym));
974 
975   if (!seen.insert(c.getChildOffset()).second)
976     return;
977 
978   MemoryBufferRef mb =
979       CHECK(c.getMemoryBufferRef(),
980             toString(this) +
981                 ": could not get the buffer for the member defining symbol " +
982                 toMachOString(sym));
983 
984   if (tar && c.getParent()->isThin())
985     tar->append(relativeToRoot(CHECK(c.getFullName(), this)), mb.getBuffer());
986 
987   uint32_t modTime = toTimeT(
988       CHECK(c.getLastModified(), toString(this) +
989                                      ": could not get the modification time "
990                                      "for the member defining symbol " +
991                                      toMachOString(sym)));
992 
993   // `sym` is owned by a LazySym, which will be replace<>()d by make<ObjFile>
994   // and become invalid after that call. Copy it to the stack so we can refer
995   // to it later.
996   const object::Archive::Symbol symCopy = sym;
997 
998   if (Optional<InputFile *> file =
999           loadArchiveMember(mb, modTime, getName(), /*objCOnly=*/false)) {
1000     inputFiles.insert(*file);
1001     // ld64 doesn't demangle sym here even with -demangle.
1002     // Match that: intentionally don't call toMachOString().
1003     printArchiveMemberLoad(symCopy.getName(), *file);
1004   }
1005 }
1006 
1007 static macho::Symbol *createBitcodeSymbol(const lto::InputFile::Symbol &objSym,
1008                                           BitcodeFile &file) {
1009   StringRef name = saver.save(objSym.getName());
1010 
1011   // TODO: support weak references
1012   if (objSym.isUndefined())
1013     return symtab->addUndefined(name, &file, /*isWeakRef=*/false);
1014 
1015   assert(!objSym.isCommon() && "TODO: support common symbols in LTO");
1016 
1017   // TODO: Write a test demonstrating why computing isPrivateExtern before
1018   // LTO compilation is important.
1019   bool isPrivateExtern = false;
1020   switch (objSym.getVisibility()) {
1021   case GlobalValue::HiddenVisibility:
1022     isPrivateExtern = true;
1023     break;
1024   case GlobalValue::ProtectedVisibility:
1025     error(name + " has protected visibility, which is not supported by Mach-O");
1026     break;
1027   case GlobalValue::DefaultVisibility:
1028     break;
1029   }
1030 
1031   return symtab->addDefined(name, &file, /*isec=*/nullptr, /*value=*/0,
1032                             /*size=*/0, objSym.isWeak(), isPrivateExtern,
1033                             /*isThumb=*/false,
1034                             /*isReferencedDynamically=*/false,
1035                             /*noDeadStrip=*/false);
1036 }
1037 
1038 BitcodeFile::BitcodeFile(MemoryBufferRef mbref)
1039     : InputFile(BitcodeKind, mbref) {
1040   obj = check(lto::InputFile::create(mbref));
1041 
1042   // Convert LTO Symbols to LLD Symbols in order to perform resolution. The
1043   // "winning" symbol will then be marked as Prevailing at LTO compilation
1044   // time.
1045   for (const lto::InputFile::Symbol &objSym : obj->symbols())
1046     symbols.push_back(createBitcodeSymbol(objSym, *this));
1047 }
1048 
1049 template void ObjFile::parse<LP64>();
1050