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