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