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