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/MachO/Architecture.h"
70 
71 using namespace llvm;
72 using namespace llvm::MachO;
73 using namespace llvm::support::endian;
74 using namespace llvm::sys;
75 using namespace lld;
76 using namespace lld::macho;
77 
78 // Returns "<internal>", "foo.a(bar.o)", or "baz.o".
79 std::string lld::toString(const InputFile *f) {
80   if (!f)
81     return "<internal>";
82   if (f->archiveName.empty())
83     return std::string(f->getName());
84   return (path::filename(f->archiveName) + "(" + path::filename(f->getName()) +
85           ")")
86       .str();
87 }
88 
89 SetVector<InputFile *> macho::inputFiles;
90 std::unique_ptr<TarWriter> macho::tar;
91 int InputFile::idCount = 0;
92 
93 // Open a given file path and return it as a memory-mapped file.
94 // Perform no sanity checks--just open, map & return.
95 Optional<MemoryBufferRef> macho::readRawFile(StringRef path) {
96   // Open a file.
97   auto mbOrErr = MemoryBuffer::getFile(path);
98   if (auto ec = mbOrErr.getError()) {
99     error("cannot open " + path + ": " + ec.message());
100     return None;
101   }
102 
103   std::unique_ptr<MemoryBuffer> &mb = *mbOrErr;
104   MemoryBufferRef mbref = mb->getMemBufferRef();
105   make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take mb ownership
106   return mbref;
107 }
108 
109 // Open a given file path and return it as a memory-mapped file.
110 // Assume the file has one of a variety of linkable formats and
111 // perform some basic sanity checks, notably minimum length.
112 Optional<MemoryBufferRef> macho::readLinkableFile(StringRef path) {
113   Optional<MemoryBufferRef> maybeMbref = readRawFile(path);
114   if (!maybeMbref) {
115     return None;
116   }
117   MemoryBufferRef mbref = *maybeMbref;
118 
119   // LD64 hard-codes 20 as minimum header size, which is presumably
120   // the smallest header among the the various linkable input formats
121   // LLD are less demanding. We insist on having only enough data for
122   // a magic number.
123   if (mbref.getBufferSize() < sizeof(uint32_t)) {
124     error("file is too small to contain a magic number: " + path);
125     return None;
126   }
127 
128   // If this is a regular non-fat file, return it.
129   const char *buf = mbref.getBufferStart();
130   auto *hdr = reinterpret_cast<const MachO::fat_header *>(buf);
131   if (read32be(&hdr->magic) != MachO::FAT_MAGIC) {
132     if (tar)
133       tar->append(relativeToRoot(path), mbref.getBuffer());
134     return mbref;
135   }
136 
137   // Object files and archive files may be fat files, which contains
138   // multiple real files for different CPU ISAs. Here, we search for a
139   // file that matches with the current link target and returns it as
140   // a MemoryBufferRef.
141   auto *arch = reinterpret_cast<const MachO::fat_arch *>(buf + sizeof(*hdr));
142 
143   for (uint32_t i = 0, n = read32be(&hdr->nfat_arch); i < n; ++i) {
144     if (reinterpret_cast<const char *>(arch + i + 1) >
145         buf + mbref.getBufferSize()) {
146       error(path + ": fat_arch struct extends beyond end of file");
147       return None;
148     }
149 
150     if (read32be(&arch[i].cputype) != target->cpuType ||
151         read32be(&arch[i].cpusubtype) != target->cpuSubtype)
152       continue;
153 
154     uint32_t offset = read32be(&arch[i].offset);
155     uint32_t size = read32be(&arch[i].size);
156     if (offset + size > mbref.getBufferSize())
157       error(path + ": slice extends beyond end of file");
158     if (tar)
159       tar->append(relativeToRoot(path), mbref.getBuffer());
160     return MemoryBufferRef(StringRef(buf + offset, size), path.copy(bAlloc));
161   }
162 
163   error("unable to find matching architecture in " + path);
164   return None;
165 }
166 
167 const load_command *macho::findCommand(const mach_header_64 *hdr,
168                                        uint32_t type) {
169   const uint8_t *p =
170       reinterpret_cast<const uint8_t *>(hdr) + sizeof(mach_header_64);
171 
172   for (uint32_t i = 0, n = hdr->ncmds; i < n; ++i) {
173     auto *cmd = reinterpret_cast<const load_command *>(p);
174     if (cmd->cmd == type)
175       return cmd;
176     p += cmd->cmdsize;
177   }
178   return nullptr;
179 }
180 
181 void ObjFile::parseSections(ArrayRef<section_64> sections) {
182   subsections.reserve(sections.size());
183   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
184 
185   for (const section_64 &sec : sections) {
186     InputSection *isec = make<InputSection>();
187     isec->file = this;
188     isec->name =
189         StringRef(sec.sectname, strnlen(sec.sectname, sizeof(sec.sectname)));
190     isec->segname =
191         StringRef(sec.segname, strnlen(sec.segname, sizeof(sec.segname)));
192     isec->data = {isZeroFill(sec.flags) ? nullptr : buf + sec.offset,
193                   static_cast<size_t>(sec.size)};
194     if (sec.align >= 32)
195       error("alignment " + std::to_string(sec.align) + " of section " +
196             isec->name + " is too large");
197     else
198       isec->align = 1 << sec.align;
199     isec->flags = sec.flags;
200 
201     if (!(isDebugSection(isec->flags) &&
202           isec->segname == segment_names::dwarf)) {
203       subsections.push_back({{0, isec}});
204     } else {
205       // Instead of emitting DWARF sections, we emit STABS symbols to the
206       // object files that contain them. We filter them out early to avoid
207       // parsing their relocations unnecessarily. But we must still push an
208       // empty map to ensure the indices line up for the remaining sections.
209       subsections.push_back({});
210       debugSections.push_back(isec);
211     }
212   }
213 }
214 
215 // Find the subsection corresponding to the greatest section offset that is <=
216 // that of the given offset.
217 //
218 // offset: an offset relative to the start of the original InputSection (before
219 // any subsection splitting has occurred). It will be updated to represent the
220 // same location as an offset relative to the start of the containing
221 // subsection.
222 static InputSection *findContainingSubsection(SubsectionMap &map,
223                                               uint32_t *offset) {
224   auto it = std::prev(map.upper_bound(*offset));
225   *offset -= it->first;
226   return it->second;
227 }
228 
229 static bool validateRelocationInfo(InputFile *file, const section_64 &sec,
230                                    relocation_info rel) {
231   const TargetInfo::RelocAttrs &relocAttrs = target->getRelocAttrs(rel.r_type);
232   bool valid = true;
233   auto message = [relocAttrs, file, sec, rel, &valid](const Twine &diagnostic) {
234     valid = false;
235     return (relocAttrs.name + " relocation " + diagnostic + " at offset " +
236             std::to_string(rel.r_address) + " of " + sec.segname + "," +
237             sec.sectname + " in " + toString(file))
238         .str();
239   };
240 
241   if (!relocAttrs.hasAttr(RelocAttrBits::LOCAL) && !rel.r_extern)
242     error(message("must be extern"));
243   if (relocAttrs.hasAttr(RelocAttrBits::PCREL) != rel.r_pcrel)
244     error(message(Twine("must ") + (rel.r_pcrel ? "not " : "") +
245                   "be PC-relative"));
246   if (isThreadLocalVariables(sec.flags) &&
247       !relocAttrs.hasAttr(RelocAttrBits::UNSIGNED))
248     error(message("not allowed in thread-local section, must be UNSIGNED"));
249   if (rel.r_length < 2 || rel.r_length > 3 ||
250       !relocAttrs.hasAttr(static_cast<RelocAttrBits>(1 << rel.r_length))) {
251     static SmallVector<StringRef, 4> widths{"0", "4", "8", "4 or 8"};
252     error(message("has width " + std::to_string(1 << rel.r_length) +
253                   " bytes, but must be " +
254                   widths[(static_cast<int>(relocAttrs.bits) >> 2) & 3] +
255                   " bytes"));
256   }
257   return valid;
258 }
259 
260 void ObjFile::parseRelocations(const section_64 &sec,
261                                SubsectionMap &subsecMap) {
262   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
263   ArrayRef<relocation_info> relInfos(
264       reinterpret_cast<const relocation_info *>(buf + sec.reloff), sec.nreloc);
265 
266   for (size_t i = 0; i < relInfos.size(); i++) {
267     // Paired relocations serve as Mach-O's method for attaching a
268     // supplemental datum to a primary relocation record. ELF does not
269     // need them because the *_RELOC_RELA records contain the extra
270     // addend field, vs. *_RELOC_REL which omit the addend.
271     //
272     // The {X86_64,ARM64}_RELOC_SUBTRACTOR record holds the subtrahend,
273     // and the paired *_RELOC_UNSIGNED record holds the minuend. The
274     // datum for each is a symbolic address. The result is the offset
275     // between two addresses.
276     //
277     // The ARM64_RELOC_ADDEND record holds the addend, and the paired
278     // ARM64_RELOC_BRANCH26 or ARM64_RELOC_PAGE21/PAGEOFF12 holds the
279     // base symbolic address.
280     //
281     // Note: X86 does not use *_RELOC_ADDEND because it can embed an
282     // addend into the instruction stream. On X86, a relocatable address
283     // field always occupies an entire contiguous sequence of byte(s),
284     // so there is no need to merge opcode bits with address
285     // bits. Therefore, it's easy and convenient to store addends in the
286     // instruction-stream bytes that would otherwise contain zeroes. By
287     // contrast, RISC ISAs such as ARM64 mix opcode bits with with
288     // address bits so that bitwise arithmetic is necessary to extract
289     // and insert them. Storing addends in the instruction stream is
290     // possible, but inconvenient and more costly at link time.
291 
292     uint64_t pairedAddend = 0;
293     relocation_info relInfo = relInfos[i];
294     if (target->hasAttr(relInfo.r_type, RelocAttrBits::ADDEND)) {
295       pairedAddend = SignExtend64<24>(relInfo.r_symbolnum);
296       relInfo = relInfos[++i];
297     }
298     assert(i < relInfos.size());
299     if (!validateRelocationInfo(this, sec, relInfo))
300       continue;
301     if (relInfo.r_address & R_SCATTERED)
302       fatal("TODO: Scattered relocations not supported");
303 
304     Reloc p;
305     if (target->hasAttr(relInfo.r_type, RelocAttrBits::SUBTRAHEND)) {
306       p.type = relInfo.r_type;
307       p.referent = symbols[relInfo.r_symbolnum];
308       relInfo = relInfos[++i];
309       // SUBTRACTOR relocations should always be followed by an UNSIGNED one
310       // indicating the minuend symbol.
311       assert(target->hasAttr(relInfo.r_type, RelocAttrBits::UNSIGNED) &&
312              relInfo.r_extern);
313     }
314     uint64_t embeddedAddend = target->getEmbeddedAddend(mb, sec, relInfo);
315     assert(!(embeddedAddend && pairedAddend));
316     uint64_t totalAddend = pairedAddend + embeddedAddend;
317     Reloc r;
318     r.type = relInfo.r_type;
319     r.pcrel = relInfo.r_pcrel;
320     r.length = relInfo.r_length;
321     r.offset = relInfo.r_address;
322     if (relInfo.r_extern) {
323       r.referent = symbols[relInfo.r_symbolnum];
324       r.addend = totalAddend;
325     } else {
326       SubsectionMap &referentSubsecMap = subsections[relInfo.r_symbolnum - 1];
327       const section_64 &referentSec = sectionHeaders[relInfo.r_symbolnum - 1];
328       uint32_t referentOffset;
329       if (relInfo.r_pcrel) {
330         // The implicit addend for pcrel section relocations is the pcrel offset
331         // in terms of the addresses in the input file. Here we adjust it so
332         // that it describes the offset from the start of the referent section.
333         assert(target->hasAttr(r.type, RelocAttrBits::BYTE4));
334         referentOffset =
335             sec.addr + relInfo.r_address + 4 + totalAddend - referentSec.addr;
336       } else {
337         // The addend for a non-pcrel relocation is its absolute address.
338         referentOffset = totalAddend - referentSec.addr;
339       }
340       r.referent = findContainingSubsection(referentSubsecMap, &referentOffset);
341       r.addend = referentOffset;
342     }
343 
344     InputSection *subsec = findContainingSubsection(subsecMap, &r.offset);
345     if (p.type != GENERIC_RELOC_INVALID)
346       subsec->relocs.push_back(p);
347     subsec->relocs.push_back(r);
348   }
349 }
350 
351 static macho::Symbol *createDefined(const structs::nlist_64 &sym,
352                                     StringRef name, InputSection *isec,
353                                     uint32_t value) {
354   // Symbol scope is determined by sym.n_type & (N_EXT | N_PEXT):
355   // N_EXT: Global symbols
356   // N_EXT | N_PEXT: Linkage unit (think: dylib) scoped
357   // N_PEXT: Does not occur in input files in practice,
358   //         a private extern must be external.
359   // 0: Translation-unit scoped. These are not in the symbol table.
360 
361   if (sym.n_type & (N_EXT | N_PEXT)) {
362     assert((sym.n_type & N_EXT) && "invalid input");
363     return symtab->addDefined(name, isec->file, isec, value,
364                               sym.n_desc & N_WEAK_DEF, sym.n_type & N_PEXT);
365   }
366   return make<Defined>(name, isec->file, isec, value, sym.n_desc & N_WEAK_DEF,
367                        /*isExternal=*/false, /*isPrivateExtern=*/false);
368 }
369 
370 // Absolute symbols are defined symbols that do not have an associated
371 // InputSection. They cannot be weak.
372 static macho::Symbol *createAbsolute(const structs::nlist_64 &sym,
373                                      InputFile *file, StringRef name) {
374   if (sym.n_type & (N_EXT | N_PEXT)) {
375     assert((sym.n_type & N_EXT) && "invalid input");
376     return symtab->addDefined(name, file, nullptr, sym.n_value,
377                               /*isWeakDef=*/false, sym.n_type & N_PEXT);
378   }
379   return make<Defined>(name, file, nullptr, sym.n_value, /*isWeakDef=*/false,
380                        /*isExternal=*/false, /*isPrivateExtern=*/false);
381 }
382 
383 macho::Symbol *ObjFile::parseNonSectionSymbol(const structs::nlist_64 &sym,
384                                               StringRef name) {
385   uint8_t type = sym.n_type & N_TYPE;
386   switch (type) {
387   case N_UNDF:
388     return sym.n_value == 0
389                ? symtab->addUndefined(name, this, sym.n_desc & N_WEAK_REF)
390                : symtab->addCommon(name, this, sym.n_value,
391                                    1 << GET_COMM_ALIGN(sym.n_desc),
392                                    sym.n_type & N_PEXT);
393   case N_ABS:
394     return createAbsolute(sym, this, name);
395   case N_PBUD:
396   case N_INDR:
397     error("TODO: support symbols of type " + std::to_string(type));
398     return nullptr;
399   case N_SECT:
400     llvm_unreachable(
401         "N_SECT symbols should not be passed to parseNonSectionSymbol");
402   default:
403     llvm_unreachable("invalid symbol type");
404   }
405 }
406 
407 void ObjFile::parseSymbols(ArrayRef<structs::nlist_64> nList,
408                            const char *strtab, bool subsectionsViaSymbols) {
409   // resize(), not reserve(), because we are going to create N_ALT_ENTRY symbols
410   // out-of-sequence.
411   symbols.resize(nList.size());
412   std::vector<size_t> altEntrySymIdxs;
413 
414   for (size_t i = 0, n = nList.size(); i < n; ++i) {
415     const structs::nlist_64 &sym = nList[i];
416     StringRef name = strtab + sym.n_strx;
417 
418     if ((sym.n_type & N_TYPE) != N_SECT) {
419       symbols[i] = parseNonSectionSymbol(sym, name);
420       continue;
421     }
422 
423     const section_64 &sec = sectionHeaders[sym.n_sect - 1];
424     SubsectionMap &subsecMap = subsections[sym.n_sect - 1];
425     assert(!subsecMap.empty());
426     uint64_t offset = sym.n_value - sec.addr;
427 
428     // If the input file does not use subsections-via-symbols, all symbols can
429     // use the same subsection. Otherwise, we must split the sections along
430     // symbol boundaries.
431     if (!subsectionsViaSymbols) {
432       symbols[i] = createDefined(sym, name, subsecMap[0], offset);
433       continue;
434     }
435 
436     // nList entries aren't necessarily arranged in address order. Therefore,
437     // we can't create alt-entry symbols at this point because a later symbol
438     // may split its section, which may affect which subsection the alt-entry
439     // symbol is assigned to. So we need to handle them in a second pass below.
440     if (sym.n_desc & N_ALT_ENTRY) {
441       altEntrySymIdxs.push_back(i);
442       continue;
443     }
444 
445     // Find the subsection corresponding to the greatest section offset that is
446     // <= that of the current symbol. The subsection that we find either needs
447     // to be used directly or split in two.
448     uint32_t firstSize = offset;
449     InputSection *firstIsec = findContainingSubsection(subsecMap, &firstSize);
450 
451     if (firstSize == 0) {
452       // Alias of an existing symbol, or the first symbol in the section. These
453       // are handled by reusing the existing section.
454       symbols[i] = createDefined(sym, name, firstIsec, 0);
455       continue;
456     }
457 
458     // We saw a symbol definition at a new offset. Split the section into two
459     // subsections. The new symbol uses the second subsection.
460     auto *secondIsec = make<InputSection>(*firstIsec);
461     secondIsec->data = firstIsec->data.slice(firstSize);
462     firstIsec->data = firstIsec->data.slice(0, firstSize);
463     // TODO: ld64 appears to preserve the original alignment as well as each
464     // subsection's offset from the last aligned address. We should consider
465     // emulating that behavior.
466     secondIsec->align = MinAlign(firstIsec->align, offset);
467 
468     subsecMap[offset] = secondIsec;
469     // By construction, the symbol will be at offset zero in the new section.
470     symbols[i] = createDefined(sym, name, secondIsec, 0);
471   }
472 
473   for (size_t idx : altEntrySymIdxs) {
474     const structs::nlist_64 &sym = nList[idx];
475     StringRef name = strtab + sym.n_strx;
476     SubsectionMap &subsecMap = subsections[sym.n_sect - 1];
477     uint32_t off = sym.n_value - sectionHeaders[sym.n_sect - 1].addr;
478     InputSection *subsec = findContainingSubsection(subsecMap, &off);
479     symbols[idx] = createDefined(sym, name, subsec, off);
480   }
481 }
482 
483 OpaqueFile::OpaqueFile(MemoryBufferRef mb, StringRef segName,
484                        StringRef sectName)
485     : InputFile(OpaqueKind, mb) {
486   InputSection *isec = make<InputSection>();
487   isec->file = this;
488   isec->name = sectName.take_front(16);
489   isec->segname = segName.take_front(16);
490   const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
491   isec->data = {buf, mb.getBufferSize()};
492   subsections.push_back({{0, isec}});
493 }
494 
495 ObjFile::ObjFile(MemoryBufferRef mb, uint32_t modTime, StringRef archiveName)
496     : InputFile(ObjKind, mb), modTime(modTime) {
497   this->archiveName = std::string(archiveName);
498 
499   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
500   auto *hdr = reinterpret_cast<const mach_header_64 *>(mb.getBufferStart());
501 
502   MachO::Architecture arch =
503       MachO::getArchitectureFromCpuType(hdr->cputype, hdr->cpusubtype);
504   if (arch != config->arch) {
505     error(toString(this) + " has architecture " + getArchitectureName(arch) +
506           " which is incompatible with target architecture " +
507           getArchitectureName(config->arch));
508     return;
509   }
510 
511   if (const load_command *cmd = findCommand(hdr, LC_LINKER_OPTION)) {
512     auto *c = reinterpret_cast<const linker_option_command *>(cmd);
513     StringRef data{reinterpret_cast<const char *>(c + 1),
514                    c->cmdsize - sizeof(linker_option_command)};
515     parseLCLinkerOption(this, c->count, data);
516   }
517 
518   if (const load_command *cmd = findCommand(hdr, LC_SEGMENT_64)) {
519     auto *c = reinterpret_cast<const segment_command_64 *>(cmd);
520     sectionHeaders = ArrayRef<section_64>{
521         reinterpret_cast<const section_64 *>(c + 1), c->nsects};
522     parseSections(sectionHeaders);
523   }
524 
525   // TODO: Error on missing LC_SYMTAB?
526   if (const load_command *cmd = findCommand(hdr, LC_SYMTAB)) {
527     auto *c = reinterpret_cast<const symtab_command *>(cmd);
528     ArrayRef<structs::nlist_64> nList(
529         reinterpret_cast<const structs::nlist_64 *>(buf + c->symoff), c->nsyms);
530     const char *strtab = reinterpret_cast<const char *>(buf) + c->stroff;
531     bool subsectionsViaSymbols = hdr->flags & MH_SUBSECTIONS_VIA_SYMBOLS;
532     parseSymbols(nList, strtab, subsectionsViaSymbols);
533   }
534 
535   // The relocations may refer to the symbols, so we parse them after we have
536   // parsed all the symbols.
537   for (size_t i = 0, n = subsections.size(); i < n; ++i)
538     if (!subsections[i].empty())
539       parseRelocations(sectionHeaders[i], subsections[i]);
540 
541   parseDebugInfo();
542 }
543 
544 void ObjFile::parseDebugInfo() {
545   std::unique_ptr<DwarfObject> dObj = DwarfObject::create(this);
546   if (!dObj)
547     return;
548 
549   auto *ctx = make<DWARFContext>(
550       std::move(dObj), "",
551       [&](Error err) {
552         warn(toString(this) + ": " + toString(std::move(err)));
553       },
554       [&](Error warning) {
555         warn(toString(this) + ": " + toString(std::move(warning)));
556       });
557 
558   // TODO: Since object files can contain a lot of DWARF info, we should verify
559   // that we are parsing just the info we need
560   const DWARFContext::compile_unit_range &units = ctx->compile_units();
561   auto it = units.begin();
562   compileUnit = it->get();
563   assert(std::next(it) == units.end());
564 }
565 
566 // The path can point to either a dylib or a .tbd file.
567 static Optional<DylibFile *> loadDylib(StringRef path, DylibFile *umbrella) {
568   Optional<MemoryBufferRef> mbref = readLinkableFile(path);
569   if (!mbref) {
570     error("could not read dylib file at " + path);
571     return {};
572   }
573   return loadDylib(*mbref, umbrella);
574 }
575 
576 // TBD files are parsed into a series of TAPI documents (InterfaceFiles), with
577 // the first document storing child pointers to the rest of them. When we are
578 // processing a given TBD file, we store that top-level document in
579 // currentTopLevelTapi. When processing re-exports, we search its children for
580 // potentially matching documents in the same TBD file. Note that the children
581 // themselves don't point to further documents, i.e. this is a two-level tree.
582 //
583 // Re-exports can either refer to on-disk files, or to documents within .tbd
584 // files.
585 static Optional<DylibFile *>
586 findDylib(StringRef path, DylibFile *umbrella,
587           const InterfaceFile *currentTopLevelTapi) {
588   if (path::is_absolute(path, path::Style::posix))
589     for (StringRef root : config->systemLibraryRoots)
590       if (Optional<std::string> dylibPath =
591               resolveDylibPath((root + path).str()))
592         return loadDylib(*dylibPath, umbrella);
593 
594   // TODO: Expand @loader_path, @executable_path, @rpath etc, handle -dylib_path
595 
596   if (currentTopLevelTapi) {
597     for (InterfaceFile &child :
598          make_pointee_range(currentTopLevelTapi->documents())) {
599       if (path == child.getInstallName())
600         return make<DylibFile>(child, umbrella);
601       assert(child.documents().empty());
602     }
603   }
604 
605   if (Optional<std::string> dylibPath = resolveDylibPath(path))
606     return loadDylib(*dylibPath, umbrella);
607 
608   return {};
609 }
610 
611 // If a re-exported dylib is public (lives in /usr/lib or
612 // /System/Library/Frameworks), then it is considered implicitly linked: we
613 // should bind to its symbols directly instead of via the re-exporting umbrella
614 // library.
615 static bool isImplicitlyLinked(StringRef path) {
616   if (!config->implicitDylibs)
617     return false;
618 
619   if (path::parent_path(path) == "/usr/lib")
620     return true;
621 
622   // Match /System/Library/Frameworks/$FOO.framework/**/$FOO
623   if (path.consume_front("/System/Library/Frameworks/")) {
624     StringRef frameworkName = path.take_until([](char c) { return c == '.'; });
625     return path::filename(path) == frameworkName;
626   }
627 
628   return false;
629 }
630 
631 void loadReexport(StringRef path, DylibFile *umbrella,
632                   const InterfaceFile *currentTopLevelTapi) {
633   Optional<DylibFile *> reexport =
634       findDylib(path, umbrella, currentTopLevelTapi);
635   if (!reexport)
636     error("unable to locate re-export with install name " + path);
637   else if (isImplicitlyLinked(path))
638     inputFiles.insert(*reexport);
639 }
640 
641 DylibFile::DylibFile(MemoryBufferRef mb, DylibFile *umbrella,
642                      bool isBundleLoader)
643     : InputFile(DylibKind, mb), refState(RefState::Unreferenced),
644       isBundleLoader(isBundleLoader) {
645   assert(!isBundleLoader || !umbrella);
646   if (umbrella == nullptr)
647     umbrella = this;
648 
649   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
650   auto *hdr = reinterpret_cast<const mach_header_64 *>(mb.getBufferStart());
651 
652   // Initialize dylibName.
653   if (const load_command *cmd = findCommand(hdr, LC_ID_DYLIB)) {
654     auto *c = reinterpret_cast<const dylib_command *>(cmd);
655     currentVersion = read32le(&c->dylib.current_version);
656     compatibilityVersion = read32le(&c->dylib.compatibility_version);
657     dylibName = reinterpret_cast<const char *>(cmd) + read32le(&c->dylib.name);
658   } else if (!isBundleLoader) {
659     // macho_executable and macho_bundle don't have LC_ID_DYLIB,
660     // so it's OK.
661     error("dylib " + toString(this) + " missing LC_ID_DYLIB load command");
662     return;
663   }
664 
665   // Initialize symbols.
666   DylibFile *exportingFile = isImplicitlyLinked(dylibName) ? this : umbrella;
667   if (const load_command *cmd = findCommand(hdr, LC_DYLD_INFO_ONLY)) {
668     auto *c = reinterpret_cast<const dyld_info_command *>(cmd);
669     parseTrie(buf + c->export_off, c->export_size,
670               [&](const Twine &name, uint64_t flags) {
671                 bool isWeakDef = flags & EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION;
672                 bool isTlv = flags & EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL;
673                 symbols.push_back(symtab->addDylib(
674                     saver.save(name), exportingFile, isWeakDef, isTlv));
675               });
676   } else {
677     error("LC_DYLD_INFO_ONLY not found in " + toString(this));
678     return;
679   }
680 
681   const uint8_t *p =
682       reinterpret_cast<const uint8_t *>(hdr) + sizeof(mach_header_64);
683   for (uint32_t i = 0, n = hdr->ncmds; i < n; ++i) {
684     auto *cmd = reinterpret_cast<const load_command *>(p);
685     p += cmd->cmdsize;
686 
687     if (!(hdr->flags & MH_NO_REEXPORTED_DYLIBS) &&
688         cmd->cmd == LC_REEXPORT_DYLIB) {
689       const auto *c = reinterpret_cast<const dylib_command *>(cmd);
690       StringRef reexportPath =
691           reinterpret_cast<const char *>(c) + read32le(&c->dylib.name);
692       loadReexport(reexportPath, umbrella, nullptr);
693     }
694 
695     // FIXME: What about LC_LOAD_UPWARD_DYLIB, LC_LAZY_LOAD_DYLIB,
696     // LC_LOAD_WEAK_DYLIB, LC_REEXPORT_DYLIB (..are reexports from dylibs with
697     // MH_NO_REEXPORTED_DYLIBS loaded for -flat_namespace)?
698     if (config->namespaceKind == NamespaceKind::flat &&
699         cmd->cmd == LC_LOAD_DYLIB) {
700       const auto *c = reinterpret_cast<const dylib_command *>(cmd);
701       StringRef dylibPath =
702           reinterpret_cast<const char *>(c) + read32le(&c->dylib.name);
703       Optional<DylibFile *> dylib = findDylib(dylibPath, umbrella, nullptr);
704       if (!dylib)
705         error(Twine("unable to locate library '") + dylibPath +
706               "' loaded from '" + toString(this) + "' for -flat_namespace");
707     }
708   }
709 }
710 
711 DylibFile::DylibFile(const InterfaceFile &interface, DylibFile *umbrella,
712                      bool isBundleLoader)
713     : InputFile(DylibKind, interface), refState(RefState::Unreferenced),
714       isBundleLoader(isBundleLoader) {
715   // FIXME: Add test for the missing TBD code path.
716 
717   if (umbrella == nullptr)
718     umbrella = this;
719 
720   if (!interface.getArchitectures().has(config->arch)) {
721     error(toString(this) + " is incompatible with " +
722           getArchitectureName(config->arch));
723     return;
724   }
725 
726   dylibName = saver.save(interface.getInstallName());
727   compatibilityVersion = interface.getCompatibilityVersion().rawValue();
728   currentVersion = interface.getCurrentVersion().rawValue();
729   DylibFile *exportingFile = isImplicitlyLinked(dylibName) ? this : umbrella;
730   auto addSymbol = [&](const Twine &name) -> void {
731     symbols.push_back(symtab->addDylib(saver.save(name), exportingFile,
732                                        /*isWeakDef=*/false,
733                                        /*isTlv=*/false));
734   };
735   // TODO(compnerd) filter out symbols based on the target platform
736   // TODO: handle weak defs, thread locals
737   for (const auto symbol : interface.symbols()) {
738     if (!symbol->getArchitectures().has(config->arch))
739       continue;
740 
741     switch (symbol->getKind()) {
742     case SymbolKind::GlobalSymbol:
743       addSymbol(symbol->getName());
744       break;
745     case SymbolKind::ObjectiveCClass:
746       // XXX ld64 only creates these symbols when -ObjC is passed in. We may
747       // want to emulate that.
748       addSymbol(objc::klass + symbol->getName());
749       addSymbol(objc::metaclass + symbol->getName());
750       break;
751     case SymbolKind::ObjectiveCClassEHType:
752       addSymbol(objc::ehtype + symbol->getName());
753       break;
754     case SymbolKind::ObjectiveCInstanceVariable:
755       addSymbol(objc::ivar + symbol->getName());
756       break;
757     }
758   }
759 
760   const InterfaceFile *topLevel =
761       interface.getParent() == nullptr ? &interface : interface.getParent();
762 
763   for (InterfaceFileRef intfRef : interface.reexportedLibraries())
764     loadReexport(intfRef.getInstallName(), umbrella, topLevel);
765 }
766 
767 ArchiveFile::ArchiveFile(std::unique_ptr<object::Archive> &&f)
768     : InputFile(ArchiveKind, f->getMemoryBufferRef()), file(std::move(f)) {
769   for (const object::Archive::Symbol &sym : file->symbols())
770     symtab->addLazy(sym.getName(), this, sym);
771 }
772 
773 void ArchiveFile::fetch(const object::Archive::Symbol &sym) {
774   object::Archive::Child c =
775       CHECK(sym.getMember(), toString(this) +
776                                  ": could not get the member for symbol " +
777                                  toMachOString(sym));
778 
779   if (!seen.insert(c.getChildOffset()).second)
780     return;
781 
782   MemoryBufferRef mb =
783       CHECK(c.getMemoryBufferRef(),
784             toString(this) +
785                 ": could not get the buffer for the member defining symbol " +
786                 toMachOString(sym));
787 
788   if (tar && c.getParent()->isThin())
789     tar->append(relativeToRoot(CHECK(c.getFullName(), this)), mb.getBuffer());
790 
791   uint32_t modTime = toTimeT(
792       CHECK(c.getLastModified(), toString(this) +
793                                      ": could not get the modification time "
794                                      "for the member defining symbol " +
795                                      toMachOString(sym)));
796 
797   // `sym` is owned by a LazySym, which will be replace<>() by make<ObjFile>
798   // and become invalid after that call. Copy it to the stack so we can refer
799   // to it later.
800   const object::Archive::Symbol sym_copy = sym;
801 
802   if (Optional<InputFile *> file =
803           loadArchiveMember(mb, modTime, getName(), /*objCOnly=*/false)) {
804     inputFiles.insert(*file);
805     // ld64 doesn't demangle sym here even with -demangle. Match that, so
806     // intentionally no call to toMachOString() here.
807     printArchiveMemberLoad(sym_copy.getName(), *file);
808   }
809 }
810 
811 static macho::Symbol *createBitcodeSymbol(const lto::InputFile::Symbol &objSym,
812                                           BitcodeFile &file) {
813   StringRef name = saver.save(objSym.getName());
814 
815   // TODO: support weak references
816   if (objSym.isUndefined())
817     return symtab->addUndefined(name, &file, /*isWeakRef=*/false);
818 
819   assert(!objSym.isCommon() && "TODO: support common symbols in LTO");
820 
821   // TODO: Write a test demonstrating why computing isPrivateExtern before
822   // LTO compilation is important.
823   bool isPrivateExtern = false;
824   switch (objSym.getVisibility()) {
825   case GlobalValue::HiddenVisibility:
826     isPrivateExtern = true;
827     break;
828   case GlobalValue::ProtectedVisibility:
829     error(name + " has protected visibility, which is not supported by Mach-O");
830     break;
831   case GlobalValue::DefaultVisibility:
832     break;
833   }
834 
835   return symtab->addDefined(name, &file, /*isec=*/nullptr, /*value=*/0,
836                             objSym.isWeak(), isPrivateExtern);
837 }
838 
839 BitcodeFile::BitcodeFile(MemoryBufferRef mbref)
840     : InputFile(BitcodeKind, mbref) {
841   obj = check(lto::InputFile::create(mbref));
842 
843   // Convert LTO Symbols to LLD Symbols in order to perform resolution. The
844   // "winning" symbol will then be marked as Prevailing at LTO compilation
845   // time.
846   for (const lto::InputFile::Symbol &objSym : obj->symbols())
847     symbols.push_back(createBitcodeSymbol(objSym, *this));
848 }
849