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