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>(name, isec->file, isec, value, size,
502                        sym.n_desc & N_WEAK_DEF,
503                        /*isExternal=*/false, /*isPrivateExtern=*/false,
504                        sym.n_desc & N_ARM_THUMB_DEF,
505                        sym.n_desc & REFERENCED_DYNAMICALLY);
506 }
507 
508 // Absolute symbols are defined symbols that do not have an associated
509 // InputSection. They cannot be weak.
510 template <class NList>
511 static macho::Symbol *createAbsolute(const NList &sym, InputFile *file,
512                                      StringRef name) {
513   if (sym.n_type & (N_EXT | N_PEXT)) {
514     assert((sym.n_type & N_EXT) && "invalid input");
515     return symtab->addDefined(name, file, nullptr, sym.n_value, /*size=*/0,
516                               /*isWeakDef=*/false, sym.n_type & N_PEXT,
517                               sym.n_desc & N_ARM_THUMB_DEF,
518                               /*isReferencedDynamically=*/false);
519   }
520   return make<Defined>(name, file, nullptr, sym.n_value, /*size=*/0,
521                        /*isWeakDef=*/false,
522                        /*isExternal=*/false, /*isPrivateExtern=*/false,
523                        sym.n_desc & N_ARM_THUMB_DEF,
524                        /*isReferencedDynamically=*/false);
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->canOmitFromOutput = 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   subsections.push_back({{0, isec}});
647 }
648 
649 ObjFile::ObjFile(MemoryBufferRef mb, uint32_t modTime, StringRef archiveName)
650     : InputFile(ObjKind, mb), modTime(modTime) {
651   this->archiveName = std::string(archiveName);
652   if (target->wordSize == 8)
653     parse<LP64>();
654   else
655     parse<ILP32>();
656 }
657 
658 template <class LP> void ObjFile::parse() {
659   using Header = typename LP::mach_header;
660   using SegmentCommand = typename LP::segment_command;
661   using Section = typename LP::section;
662   using NList = typename LP::nlist;
663 
664   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
665   auto *hdr = reinterpret_cast<const Header *>(mb.getBufferStart());
666 
667   Architecture arch = getArchitectureFromCpuType(hdr->cputype, hdr->cpusubtype);
668   if (arch != config->arch()) {
669     error(toString(this) + " has architecture " + getArchitectureName(arch) +
670           " which is incompatible with target architecture " +
671           getArchitectureName(config->arch()));
672     return;
673   }
674 
675   if (!checkCompatibility(this))
676     return;
677 
678   if (const load_command *cmd = findCommand(hdr, LC_LINKER_OPTION)) {
679     auto *c = reinterpret_cast<const linker_option_command *>(cmd);
680     StringRef data{reinterpret_cast<const char *>(c + 1),
681                    c->cmdsize - sizeof(linker_option_command)};
682     parseLCLinkerOption(this, c->count, data);
683   }
684 
685   ArrayRef<Section> sectionHeaders;
686   if (const load_command *cmd = findCommand(hdr, LP::segmentLCType)) {
687     auto *c = reinterpret_cast<const SegmentCommand *>(cmd);
688     sectionHeaders =
689         ArrayRef<Section>{reinterpret_cast<const Section *>(c + 1), c->nsects};
690     parseSections(sectionHeaders);
691   }
692 
693   // TODO: Error on missing LC_SYMTAB?
694   if (const load_command *cmd = findCommand(hdr, LC_SYMTAB)) {
695     auto *c = reinterpret_cast<const symtab_command *>(cmd);
696     ArrayRef<NList> nList(reinterpret_cast<const NList *>(buf + c->symoff),
697                           c->nsyms);
698     const char *strtab = reinterpret_cast<const char *>(buf) + c->stroff;
699     bool subsectionsViaSymbols = hdr->flags & MH_SUBSECTIONS_VIA_SYMBOLS;
700     parseSymbols<LP>(sectionHeaders, nList, strtab, subsectionsViaSymbols);
701   }
702 
703   // The relocations may refer to the symbols, so we parse them after we have
704   // parsed all the symbols.
705   for (size_t i = 0, n = subsections.size(); i < n; ++i)
706     if (!subsections[i].empty())
707       parseRelocations(sectionHeaders, sectionHeaders[i], subsections[i]);
708 
709   parseDebugInfo();
710 }
711 
712 void ObjFile::parseDebugInfo() {
713   std::unique_ptr<DwarfObject> dObj = DwarfObject::create(this);
714   if (!dObj)
715     return;
716 
717   auto *ctx = make<DWARFContext>(
718       std::move(dObj), "",
719       [&](Error err) {
720         warn(toString(this) + ": " + toString(std::move(err)));
721       },
722       [&](Error warning) {
723         warn(toString(this) + ": " + toString(std::move(warning)));
724       });
725 
726   // TODO: Since object files can contain a lot of DWARF info, we should verify
727   // that we are parsing just the info we need
728   const DWARFContext::compile_unit_range &units = ctx->compile_units();
729   // FIXME: There can be more than one compile unit per object file. See
730   // PR48637.
731   auto it = units.begin();
732   compileUnit = it->get();
733 }
734 
735 // The path can point to either a dylib or a .tbd file.
736 static Optional<DylibFile *> loadDylib(StringRef path, DylibFile *umbrella) {
737   Optional<MemoryBufferRef> mbref = readFile(path);
738   if (!mbref) {
739     error("could not read dylib file at " + path);
740     return {};
741   }
742   return loadDylib(*mbref, umbrella);
743 }
744 
745 // TBD files are parsed into a series of TAPI documents (InterfaceFiles), with
746 // the first document storing child pointers to the rest of them. When we are
747 // processing a given TBD file, we store that top-level document in
748 // currentTopLevelTapi. When processing re-exports, we search its children for
749 // potentially matching documents in the same TBD file. Note that the children
750 // themselves don't point to further documents, i.e. this is a two-level tree.
751 //
752 // Re-exports can either refer to on-disk files, or to documents within .tbd
753 // files.
754 static Optional<DylibFile *>
755 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 {};
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   Optional<DylibFile *> reexport =
803       findDylib(path, umbrella, currentTopLevelTapi);
804   if (!reexport)
805     error("unable to locate re-export with install name " + path);
806   else if (isImplicitlyLinked(path))
807     inputFiles.insert(*reexport);
808 }
809 
810 DylibFile::DylibFile(MemoryBufferRef mb, DylibFile *umbrella,
811                      bool isBundleLoader)
812     : InputFile(DylibKind, mb), refState(RefState::Unreferenced),
813       isBundleLoader(isBundleLoader) {
814   assert(!isBundleLoader || !umbrella);
815   if (umbrella == nullptr)
816     umbrella = this;
817 
818   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
819   auto *hdr = reinterpret_cast<const mach_header *>(mb.getBufferStart());
820 
821   // Initialize dylibName.
822   if (const load_command *cmd = findCommand(hdr, LC_ID_DYLIB)) {
823     auto *c = reinterpret_cast<const dylib_command *>(cmd);
824     currentVersion = read32le(&c->dylib.current_version);
825     compatibilityVersion = read32le(&c->dylib.compatibility_version);
826     dylibName = reinterpret_cast<const char *>(cmd) + read32le(&c->dylib.name);
827   } else if (!isBundleLoader) {
828     // macho_executable and macho_bundle don't have LC_ID_DYLIB,
829     // so it's OK.
830     error("dylib " + toString(this) + " missing LC_ID_DYLIB load command");
831     return;
832   }
833 
834   if (!checkCompatibility(this))
835     return;
836 
837   // Initialize symbols.
838   DylibFile *exportingFile = isImplicitlyLinked(dylibName) ? this : umbrella;
839   if (const load_command *cmd = findCommand(hdr, LC_DYLD_INFO_ONLY)) {
840     auto *c = reinterpret_cast<const dyld_info_command *>(cmd);
841     parseTrie(buf + c->export_off, c->export_size,
842               [&](const Twine &name, uint64_t flags) {
843                 bool isWeakDef = flags & EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION;
844                 bool isTlv = flags & EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL;
845                 symbols.push_back(symtab->addDylib(
846                     saver.save(name), exportingFile, isWeakDef, isTlv));
847               });
848   } else {
849     error("LC_DYLD_INFO_ONLY not found in " + toString(this));
850     return;
851   }
852 
853   const uint8_t *p =
854       reinterpret_cast<const uint8_t *>(hdr) + target->headerSize;
855   for (uint32_t i = 0, n = hdr->ncmds; i < n; ++i) {
856     auto *cmd = reinterpret_cast<const load_command *>(p);
857     p += cmd->cmdsize;
858 
859     if (!(hdr->flags & MH_NO_REEXPORTED_DYLIBS) &&
860         cmd->cmd == LC_REEXPORT_DYLIB) {
861       const auto *c = reinterpret_cast<const dylib_command *>(cmd);
862       StringRef reexportPath =
863           reinterpret_cast<const char *>(c) + read32le(&c->dylib.name);
864       loadReexport(reexportPath, exportingFile, nullptr);
865     }
866 
867     // FIXME: What about LC_LOAD_UPWARD_DYLIB, LC_LAZY_LOAD_DYLIB,
868     // LC_LOAD_WEAK_DYLIB, LC_REEXPORT_DYLIB (..are reexports from dylibs with
869     // MH_NO_REEXPORTED_DYLIBS loaded for -flat_namespace)?
870     if (config->namespaceKind == NamespaceKind::flat &&
871         cmd->cmd == LC_LOAD_DYLIB) {
872       const auto *c = reinterpret_cast<const dylib_command *>(cmd);
873       StringRef dylibPath =
874           reinterpret_cast<const char *>(c) + read32le(&c->dylib.name);
875       Optional<DylibFile *> dylib = findDylib(dylibPath, umbrella, nullptr);
876       if (!dylib)
877         error(Twine("unable to locate library '") + dylibPath +
878               "' loaded from '" + toString(this) + "' for -flat_namespace");
879     }
880   }
881 }
882 
883 DylibFile::DylibFile(const InterfaceFile &interface, DylibFile *umbrella,
884                      bool isBundleLoader)
885     : InputFile(DylibKind, interface), refState(RefState::Unreferenced),
886       isBundleLoader(isBundleLoader) {
887   // FIXME: Add test for the missing TBD code path.
888 
889   if (umbrella == nullptr)
890     umbrella = this;
891 
892   dylibName = saver.save(interface.getInstallName());
893   compatibilityVersion = interface.getCompatibilityVersion().rawValue();
894   currentVersion = interface.getCurrentVersion().rawValue();
895 
896   // Some versions of XCode ship with .tbd files that don't have the right
897   // platform settings.
898   static constexpr std::array<StringRef, 3> skipPlatformChecks{
899       "/usr/lib/system/libsystem_kernel.dylib",
900       "/usr/lib/system/libsystem_platform.dylib",
901       "/usr/lib/system/libsystem_pthread.dylib"};
902 
903   if (!is_contained(skipPlatformChecks, dylibName) &&
904       !is_contained(interface.targets(), config->platformInfo.target)) {
905     error(toString(this) + " is incompatible with " +
906           std::string(config->platformInfo.target));
907     return;
908   }
909 
910   DylibFile *exportingFile = isImplicitlyLinked(dylibName) ? this : umbrella;
911   auto addSymbol = [&](const Twine &name) -> void {
912     symbols.push_back(symtab->addDylib(saver.save(name), exportingFile,
913                                        /*isWeakDef=*/false,
914                                        /*isTlv=*/false));
915   };
916   // TODO(compnerd) filter out symbols based on the target platform
917   // TODO: handle weak defs, thread locals
918   for (const auto *symbol : interface.symbols()) {
919     if (!symbol->getArchitectures().has(config->arch()))
920       continue;
921 
922     switch (symbol->getKind()) {
923     case SymbolKind::GlobalSymbol:
924       addSymbol(symbol->getName());
925       break;
926     case SymbolKind::ObjectiveCClass:
927       // XXX ld64 only creates these symbols when -ObjC is passed in. We may
928       // want to emulate that.
929       addSymbol(objc::klass + symbol->getName());
930       addSymbol(objc::metaclass + symbol->getName());
931       break;
932     case SymbolKind::ObjectiveCClassEHType:
933       addSymbol(objc::ehtype + symbol->getName());
934       break;
935     case SymbolKind::ObjectiveCInstanceVariable:
936       addSymbol(objc::ivar + symbol->getName());
937       break;
938     }
939   }
940 
941   const InterfaceFile *topLevel =
942       interface.getParent() == nullptr ? &interface : interface.getParent();
943 
944   for (InterfaceFileRef intfRef : interface.reexportedLibraries()) {
945     InterfaceFile::const_target_range targets = intfRef.targets();
946     if (is_contained(skipPlatformChecks, intfRef.getInstallName()) ||
947         is_contained(targets, config->platformInfo.target))
948       loadReexport(intfRef.getInstallName(), exportingFile, topLevel);
949   }
950 }
951 
952 ArchiveFile::ArchiveFile(std::unique_ptr<object::Archive> &&f)
953     : InputFile(ArchiveKind, f->getMemoryBufferRef()), file(std::move(f)) {
954   for (const object::Archive::Symbol &sym : file->symbols())
955     symtab->addLazy(sym.getName(), this, sym);
956 }
957 
958 void ArchiveFile::fetch(const object::Archive::Symbol &sym) {
959   object::Archive::Child c =
960       CHECK(sym.getMember(), toString(this) +
961                                  ": could not get the member for symbol " +
962                                  toMachOString(sym));
963 
964   if (!seen.insert(c.getChildOffset()).second)
965     return;
966 
967   MemoryBufferRef mb =
968       CHECK(c.getMemoryBufferRef(),
969             toString(this) +
970                 ": could not get the buffer for the member defining symbol " +
971                 toMachOString(sym));
972 
973   if (tar && c.getParent()->isThin())
974     tar->append(relativeToRoot(CHECK(c.getFullName(), this)), mb.getBuffer());
975 
976   uint32_t modTime = toTimeT(
977       CHECK(c.getLastModified(), toString(this) +
978                                      ": could not get the modification time "
979                                      "for the member defining symbol " +
980                                      toMachOString(sym)));
981 
982   // `sym` is owned by a LazySym, which will be replace<>()d by make<ObjFile>
983   // and become invalid after that call. Copy it to the stack so we can refer
984   // to it later.
985   const object::Archive::Symbol symCopy = sym;
986 
987   if (Optional<InputFile *> file =
988           loadArchiveMember(mb, modTime, getName(), /*objCOnly=*/false)) {
989     inputFiles.insert(*file);
990     // ld64 doesn't demangle sym here even with -demangle.
991     // Match that: intentionally don't call toMachOString().
992     printArchiveMemberLoad(symCopy.getName(), *file);
993   }
994 }
995 
996 static macho::Symbol *createBitcodeSymbol(const lto::InputFile::Symbol &objSym,
997                                           BitcodeFile &file) {
998   StringRef name = saver.save(objSym.getName());
999 
1000   // TODO: support weak references
1001   if (objSym.isUndefined())
1002     return symtab->addUndefined(name, &file, /*isWeakRef=*/false);
1003 
1004   assert(!objSym.isCommon() && "TODO: support common symbols in LTO");
1005 
1006   // TODO: Write a test demonstrating why computing isPrivateExtern before
1007   // LTO compilation is important.
1008   bool isPrivateExtern = false;
1009   switch (objSym.getVisibility()) {
1010   case GlobalValue::HiddenVisibility:
1011     isPrivateExtern = true;
1012     break;
1013   case GlobalValue::ProtectedVisibility:
1014     error(name + " has protected visibility, which is not supported by Mach-O");
1015     break;
1016   case GlobalValue::DefaultVisibility:
1017     break;
1018   }
1019 
1020   return symtab->addDefined(name, &file, /*isec=*/nullptr, /*value=*/0,
1021                             /*size=*/0, objSym.isWeak(), isPrivateExtern,
1022                             /*isThumb=*/false,
1023                             /*isReferencedDynamically=*/false);
1024 }
1025 
1026 BitcodeFile::BitcodeFile(MemoryBufferRef mbref)
1027     : InputFile(BitcodeKind, mbref) {
1028   obj = check(lto::InputFile::create(mbref));
1029 
1030   // Convert LTO Symbols to LLD Symbols in order to perform resolution. The
1031   // "winning" symbol will then be marked as Prevailing at LTO compilation
1032   // time.
1033   for (const lto::InputFile::Symbol &objSym : obj->symbols())
1034     symbols.push_back(createBitcodeSymbol(objSym, *this));
1035 }
1036 
1037 template void ObjFile::parse<LP64>();
1038