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 "ExportTrie.h"
46 #include "InputSection.h"
47 #include "OutputSection.h"
48 #include "SymbolTable.h"
49 #include "Symbols.h"
50 #include "Target.h"
51 
52 #include "lld/Common/ErrorHandler.h"
53 #include "lld/Common/Memory.h"
54 #include "llvm/BinaryFormat/MachO.h"
55 #include "llvm/Support/Endian.h"
56 #include "llvm/Support/MemoryBuffer.h"
57 
58 using namespace llvm;
59 using namespace llvm::MachO;
60 using namespace llvm::support::endian;
61 using namespace lld;
62 using namespace lld::macho;
63 
64 std::vector<InputFile *> macho::inputFiles;
65 
66 // Open a given file path and return it as a memory-mapped file.
67 Optional<MemoryBufferRef> macho::readFile(StringRef path) {
68   // Open a file.
69   auto mbOrErr = MemoryBuffer::getFile(path);
70   if (auto ec = mbOrErr.getError()) {
71     error("cannot open " + path + ": " + ec.message());
72     return None;
73   }
74 
75   std::unique_ptr<MemoryBuffer> &mb = *mbOrErr;
76   MemoryBufferRef mbref = mb->getMemBufferRef();
77   make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take mb ownership
78 
79   // If this is a regular non-fat file, return it.
80   const char *buf = mbref.getBufferStart();
81   auto *hdr = reinterpret_cast<const MachO::fat_header *>(buf);
82   if (read32be(&hdr->magic) != MachO::FAT_MAGIC)
83     return mbref;
84 
85   // Object files and archive files may be fat files, which contains
86   // multiple real files for different CPU ISAs. Here, we search for a
87   // file that matches with the current link target and returns it as
88   // a MemoryBufferRef.
89   auto *arch = reinterpret_cast<const MachO::fat_arch *>(buf + sizeof(*hdr));
90 
91   for (uint32_t i = 0, n = read32be(&hdr->nfat_arch); i < n; ++i) {
92     if (reinterpret_cast<const char *>(arch + i + 1) >
93         buf + mbref.getBufferSize()) {
94       error(path + ": fat_arch struct extends beyond end of file");
95       return None;
96     }
97 
98     if (read32be(&arch[i].cputype) != target->cpuType ||
99         read32be(&arch[i].cpusubtype) != target->cpuSubtype)
100       continue;
101 
102     uint32_t offset = read32be(&arch[i].offset);
103     uint32_t size = read32be(&arch[i].size);
104     if (offset + size > mbref.getBufferSize())
105       error(path + ": slice extends beyond end of file");
106     return MemoryBufferRef(StringRef(buf + offset, size), path.copy(bAlloc));
107   }
108 
109   error("unable to find matching architecture in " + path);
110   return None;
111 }
112 
113 static const load_command *findCommand(const mach_header_64 *hdr,
114                                        uint32_t type) {
115   const uint8_t *p =
116       reinterpret_cast<const uint8_t *>(hdr) + sizeof(mach_header_64);
117 
118   for (uint32_t i = 0, n = hdr->ncmds; i < n; ++i) {
119     auto *cmd = reinterpret_cast<const load_command *>(p);
120     if (cmd->cmd == type)
121       return cmd;
122     p += cmd->cmdsize;
123   }
124   return nullptr;
125 }
126 
127 std::vector<InputSection *>
128 InputFile::parseSections(ArrayRef<section_64> sections) {
129   std::vector<InputSection *> ret;
130   ret.reserve(sections.size());
131 
132   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
133 
134   for (const section_64 &sec : sections) {
135     InputSection *isec = make<InputSection>();
136     isec->file = this;
137     isec->header = &sec;
138     isec->name = StringRef(sec.sectname, strnlen(sec.sectname, 16));
139     isec->segname = StringRef(sec.segname, strnlen(sec.segname, 16));
140     isec->data = {buf + sec.offset, static_cast<size_t>(sec.size)};
141     if (sec.align >= 32)
142       error("alignment " + std::to_string(sec.align) + " of section " +
143             isec->name + " is too large");
144     else
145       isec->align = 1 << sec.align;
146     isec->flags = sec.flags;
147     ret.push_back(isec);
148   }
149 
150   return ret;
151 }
152 
153 void InputFile::parseRelocations(const section_64 &sec,
154                                  std::vector<Reloc> &relocs) {
155   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
156   ArrayRef<any_relocation_info> relInfos(
157       reinterpret_cast<const any_relocation_info *>(buf + sec.reloff),
158       sec.nreloc);
159 
160   for (const any_relocation_info &anyRel : relInfos) {
161     Reloc r;
162     if (anyRel.r_word0 & R_SCATTERED) {
163       error("TODO: Scattered relocations not supported");
164     } else {
165       auto rel = reinterpret_cast<const relocation_info &>(anyRel);
166       r.type = rel.r_type;
167       r.offset = rel.r_address;
168       r.addend = target->getImplicitAddend(buf + sec.offset + r.offset, r.type);
169       if (rel.r_extern) {
170         r.target = symbols[rel.r_symbolnum];
171       } else {
172         if (rel.r_symbolnum == 0 || rel.r_symbolnum > sections.size())
173           fatal("invalid section index in relocation for offset " +
174                 std::to_string(r.offset) + " in section " + sec.sectname +
175                 " of " + getName());
176         r.target = sections[rel.r_symbolnum - 1];
177       }
178     }
179     relocs.push_back(r);
180   }
181 }
182 
183 ObjFile::ObjFile(MemoryBufferRef mb) : InputFile(ObjKind, mb) {
184   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
185   auto *hdr = reinterpret_cast<const mach_header_64 *>(mb.getBufferStart());
186   ArrayRef<section_64> objSections;
187 
188   if (const load_command *cmd = findCommand(hdr, LC_SEGMENT_64)) {
189     auto *c = reinterpret_cast<const segment_command_64 *>(cmd);
190     objSections = ArrayRef<section_64>{
191         reinterpret_cast<const section_64 *>(c + 1), c->nsects};
192     sections = parseSections(objSections);
193   }
194 
195   // TODO: Error on missing LC_SYMTAB?
196   if (const load_command *cmd = findCommand(hdr, LC_SYMTAB)) {
197     auto *c = reinterpret_cast<const symtab_command *>(cmd);
198     const char *strtab = reinterpret_cast<const char *>(buf) + c->stroff;
199     ArrayRef<const nlist_64> nList(
200         reinterpret_cast<const nlist_64 *>(buf + c->symoff), c->nsyms);
201 
202     symbols.reserve(c->nsyms);
203 
204     for (const nlist_64 &sym : nList) {
205       StringRef name = strtab + sym.n_strx;
206 
207       // Undefined symbol
208       if (!sym.n_sect) {
209         symbols.push_back(symtab->addUndefined(name));
210         continue;
211       }
212 
213       InputSection *isec = sections[sym.n_sect - 1];
214       const section_64 &objSec = objSections[sym.n_sect - 1];
215       uint64_t value = sym.n_value - objSec.addr;
216 
217       // Global defined symbol
218       if (sym.n_type & N_EXT) {
219         symbols.push_back(symtab->addDefined(name, isec, value));
220         continue;
221       }
222 
223       // Local defined symbol
224       symbols.push_back(make<Defined>(name, isec, value));
225     }
226   }
227 
228   // The relocations may refer to the symbols, so we parse them after we have
229   // the symbols loaded.
230   if (!sections.empty()) {
231     auto it = sections.begin();
232     for (const section_64 &sec : objSections) {
233       parseRelocations(sec, (*it)->relocs);
234       ++it;
235     }
236   }
237 }
238 
239 DylibFile::DylibFile(MemoryBufferRef mb) : InputFile(DylibKind, mb) {
240   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
241   auto *hdr = reinterpret_cast<const mach_header_64 *>(mb.getBufferStart());
242 
243   // Initialize dylibName.
244   if (const load_command *cmd = findCommand(hdr, LC_ID_DYLIB)) {
245     auto *c = reinterpret_cast<const dylib_command *>(cmd);
246     dylibName = reinterpret_cast<const char *>(cmd) + read32le(&c->dylib.name);
247   } else {
248     error("dylib " + getName() + " missing LC_ID_DYLIB load command");
249     return;
250   }
251 
252   // Initialize symbols.
253   if (const load_command *cmd = findCommand(hdr, LC_DYLD_INFO_ONLY)) {
254     auto *c = reinterpret_cast<const dyld_info_command *>(cmd);
255     parseTrie(buf + c->export_off, c->export_size,
256               [&](const Twine &name, uint64_t flags) {
257                 symbols.push_back(symtab->addDylib(saver.save(name), this));
258               });
259   } else {
260     error("LC_DYLD_INFO_ONLY not found in " + getName());
261   }
262 }
263 
264 DylibFile::DylibFile() : InputFile(DylibKind, MemoryBufferRef()) {}
265 
266 DylibFile *DylibFile::createLibSystemMock() {
267   auto *file = make<DylibFile>();
268   file->mb = MemoryBufferRef("", "/usr/lib/libSystem.B.dylib");
269   file->dylibName = "/usr/lib/libSystem.B.dylib";
270   file->symbols.push_back(symtab->addDylib("dyld_stub_binder", file));
271   return file;
272 }
273 
274 // Returns "<internal>" or "baz.o".
275 std::string lld::toString(const InputFile *file) {
276   return file ? std::string(file->getName()) : "<internal>";
277 }
278