1 //===- SyntheticSections.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 #include "SyntheticSections.h" 10 #include "Config.h" 11 #include "ExportTrie.h" 12 #include "InputFiles.h" 13 #include "MachOStructs.h" 14 #include "OutputSegment.h" 15 #include "SymbolTable.h" 16 #include "Symbols.h" 17 #include "Writer.h" 18 19 #include "lld/Common/ErrorHandler.h" 20 #include "llvm/Support/EndianStream.h" 21 #include "llvm/Support/LEB128.h" 22 23 using namespace llvm; 24 using namespace llvm::MachO; 25 using namespace llvm::support; 26 using namespace llvm::support::endian; 27 28 namespace lld { 29 namespace macho { 30 31 SyntheticSection::SyntheticSection(const char *segname, const char *name) 32 : OutputSection(SyntheticKind, name) { 33 // Synthetic sections always know which segment they belong to so hook 34 // them up when they're made 35 getOrCreateOutputSegment(segname)->addOutputSection(this); 36 } 37 38 // dyld3's MachOLoaded::getSlide() assumes that the __TEXT segment starts 39 // from the beginning of the file (i.e. the header). 40 MachHeaderSection::MachHeaderSection() 41 : SyntheticSection(segment_names::text, section_names::header) {} 42 43 void MachHeaderSection::addLoadCommand(LoadCommand *lc) { 44 loadCommands.push_back(lc); 45 sizeOfCmds += lc->getSize(); 46 } 47 48 size_t MachHeaderSection::getSize() const { 49 return sizeof(mach_header_64) + sizeOfCmds; 50 } 51 52 void MachHeaderSection::writeTo(uint8_t *buf) const { 53 auto *hdr = reinterpret_cast<mach_header_64 *>(buf); 54 hdr->magic = MH_MAGIC_64; 55 hdr->cputype = CPU_TYPE_X86_64; 56 hdr->cpusubtype = CPU_SUBTYPE_X86_64_ALL | CPU_SUBTYPE_LIB64; 57 hdr->filetype = config->outputType; 58 hdr->ncmds = loadCommands.size(); 59 hdr->sizeofcmds = sizeOfCmds; 60 hdr->flags = MH_NOUNDEFS | MH_DYLDLINK | MH_TWOLEVEL; 61 if (config->outputType == MH_DYLIB && !config->hasReexports) 62 hdr->flags |= MH_NO_REEXPORTED_DYLIBS; 63 64 uint8_t *p = reinterpret_cast<uint8_t *>(hdr + 1); 65 for (LoadCommand *lc : loadCommands) { 66 lc->writeTo(p); 67 p += lc->getSize(); 68 } 69 } 70 71 PageZeroSection::PageZeroSection() 72 : SyntheticSection(segment_names::pageZero, section_names::pageZero) {} 73 74 GotSection::GotSection() 75 : SyntheticSection(segment_names::dataConst, section_names::got) { 76 align = 8; 77 flags = S_NON_LAZY_SYMBOL_POINTERS; 78 79 // TODO: section_64::reserved1 should be an index into the indirect symbol 80 // table, which we do not currently emit 81 } 82 83 void GotSection::addEntry(DylibSymbol &sym) { 84 if (entries.insert(&sym)) { 85 sym.gotIndex = entries.size() - 1; 86 } 87 } 88 89 BindingSection::BindingSection() 90 : SyntheticSection(segment_names::linkEdit, section_names::binding) {} 91 92 bool BindingSection::isNeeded() const { return in.got->isNeeded(); } 93 94 // Emit bind opcodes, which are a stream of byte-sized opcodes that dyld 95 // interprets to update a record with the following fields: 96 // * segment index (of the segment to write the symbol addresses to, typically 97 // the __DATA_CONST segment which contains the GOT) 98 // * offset within the segment, indicating the next location to write a binding 99 // * symbol type 100 // * symbol library ordinal (the index of its library's LC_LOAD_DYLIB command) 101 // * symbol name 102 // * addend 103 // When dyld sees BIND_OPCODE_DO_BIND, it uses the current record state to bind 104 // a symbol in the GOT, and increments the segment offset to point to the next 105 // entry. It does *not* clear the record state after doing the bind, so 106 // subsequent opcodes only need to encode the differences between bindings. 107 void BindingSection::finalizeContents() { 108 if (!isNeeded()) 109 return; 110 111 raw_svector_ostream os{contents}; 112 os << static_cast<uint8_t>(BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB | 113 in.got->parent->index); 114 encodeULEB128(in.got->getSegmentOffset(), os); 115 for (const DylibSymbol *sym : in.got->getEntries()) { 116 // TODO: Implement compact encoding -- we only need to encode the 117 // differences between consecutive symbol entries. 118 if (sym->file->ordinal <= BIND_IMMEDIATE_MASK) { 119 os << static_cast<uint8_t>(BIND_OPCODE_SET_DYLIB_ORDINAL_IMM | 120 sym->file->ordinal); 121 } else { 122 error("TODO: Support larger dylib symbol ordinals"); 123 continue; 124 } 125 os << static_cast<uint8_t>(BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM) 126 << sym->getName() << '\0' 127 << static_cast<uint8_t>(BIND_OPCODE_SET_TYPE_IMM | BIND_TYPE_POINTER) 128 << static_cast<uint8_t>(BIND_OPCODE_DO_BIND); 129 } 130 131 os << static_cast<uint8_t>(BIND_OPCODE_DONE); 132 } 133 134 void BindingSection::writeTo(uint8_t *buf) const { 135 memcpy(buf, contents.data(), contents.size()); 136 } 137 138 StubsSection::StubsSection() 139 : SyntheticSection(segment_names::text, "__stubs") {} 140 141 size_t StubsSection::getSize() const { 142 return entries.size() * target->stubSize; 143 } 144 145 void StubsSection::writeTo(uint8_t *buf) const { 146 size_t off = 0; 147 for (const DylibSymbol *sym : in.stubs->getEntries()) { 148 target->writeStub(buf + off, *sym); 149 off += target->stubSize; 150 } 151 } 152 153 void StubsSection::addEntry(DylibSymbol &sym) { 154 if (entries.insert(&sym)) 155 sym.stubsIndex = entries.size() - 1; 156 } 157 158 StubHelperSection::StubHelperSection() 159 : SyntheticSection(segment_names::text, "__stub_helper") {} 160 161 size_t StubHelperSection::getSize() const { 162 return target->stubHelperHeaderSize + 163 in.stubs->getEntries().size() * target->stubHelperEntrySize; 164 } 165 166 bool StubHelperSection::isNeeded() const { 167 return !in.stubs->getEntries().empty(); 168 } 169 170 void StubHelperSection::writeTo(uint8_t *buf) const { 171 target->writeStubHelperHeader(buf); 172 size_t off = target->stubHelperHeaderSize; 173 for (const DylibSymbol *sym : in.stubs->getEntries()) { 174 target->writeStubHelperEntry(buf + off, *sym, addr + off); 175 off += target->stubHelperEntrySize; 176 } 177 } 178 179 void StubHelperSection::setup() { 180 stubBinder = dyn_cast_or_null<DylibSymbol>(symtab->find("dyld_stub_binder")); 181 if (stubBinder == nullptr) { 182 error("symbol dyld_stub_binder not found (normally in libSystem.dylib). " 183 "Needed to perform lazy binding."); 184 return; 185 } 186 in.got->addEntry(*stubBinder); 187 188 inputSections.push_back(in.imageLoaderCache); 189 symtab->addDefined("__dyld_private", in.imageLoaderCache, 0); 190 } 191 192 ImageLoaderCacheSection::ImageLoaderCacheSection() { 193 segname = segment_names::data; 194 name = "__data"; 195 } 196 197 LazyPointerSection::LazyPointerSection() 198 : SyntheticSection(segment_names::data, "__la_symbol_ptr") { 199 align = 8; 200 flags = S_LAZY_SYMBOL_POINTERS; 201 } 202 203 size_t LazyPointerSection::getSize() const { 204 return in.stubs->getEntries().size() * WordSize; 205 } 206 207 bool LazyPointerSection::isNeeded() const { 208 return !in.stubs->getEntries().empty(); 209 } 210 211 void LazyPointerSection::writeTo(uint8_t *buf) const { 212 size_t off = 0; 213 for (const DylibSymbol *sym : in.stubs->getEntries()) { 214 uint64_t stubHelperOffset = target->stubHelperHeaderSize + 215 sym->stubsIndex * target->stubHelperEntrySize; 216 write64le(buf + off, in.stubHelper->addr + stubHelperOffset); 217 off += WordSize; 218 } 219 } 220 221 LazyBindingSection::LazyBindingSection() 222 : SyntheticSection(segment_names::linkEdit, section_names::lazyBinding) {} 223 224 bool LazyBindingSection::isNeeded() const { return in.stubs->isNeeded(); } 225 226 void LazyBindingSection::finalizeContents() { 227 // TODO: Just precompute output size here instead of writing to a temporary 228 // buffer 229 for (DylibSymbol *sym : in.stubs->getEntries()) 230 sym->lazyBindOffset = encode(*sym); 231 } 232 233 void LazyBindingSection::writeTo(uint8_t *buf) const { 234 memcpy(buf, contents.data(), contents.size()); 235 } 236 237 // Unlike the non-lazy binding section, the bind opcodes in this section aren't 238 // interpreted all at once. Rather, dyld will start interpreting opcodes at a 239 // given offset, typically only binding a single symbol before it finds a 240 // BIND_OPCODE_DONE terminator. As such, unlike in the non-lazy-binding case, 241 // we cannot encode just the differences between symbols; we have to emit the 242 // complete bind information for each symbol. 243 uint32_t LazyBindingSection::encode(const DylibSymbol &sym) { 244 uint32_t opstreamOffset = contents.size(); 245 OutputSegment *dataSeg = in.lazyPointers->parent; 246 os << static_cast<uint8_t>(BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB | 247 dataSeg->index); 248 uint64_t offset = in.lazyPointers->addr - dataSeg->firstSection()->addr + 249 sym.stubsIndex * WordSize; 250 encodeULEB128(offset, os); 251 if (sym.file->ordinal <= BIND_IMMEDIATE_MASK) 252 os << static_cast<uint8_t>(BIND_OPCODE_SET_DYLIB_ORDINAL_IMM | 253 sym.file->ordinal); 254 else 255 fatal("TODO: Support larger dylib symbol ordinals"); 256 257 os << static_cast<uint8_t>(BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM) 258 << sym.getName() << '\0' << static_cast<uint8_t>(BIND_OPCODE_DO_BIND) 259 << static_cast<uint8_t>(BIND_OPCODE_DONE); 260 return opstreamOffset; 261 } 262 263 ExportSection::ExportSection() 264 : SyntheticSection(segment_names::linkEdit, section_names::export_) {} 265 266 void ExportSection::finalizeContents() { 267 // TODO: We should check symbol visibility. 268 for (const Symbol *sym : symtab->getSymbols()) 269 if (auto *defined = dyn_cast<Defined>(sym)) 270 trieBuilder.addSymbol(*defined); 271 size = trieBuilder.build(); 272 } 273 274 void ExportSection::writeTo(uint8_t *buf) const { trieBuilder.writeTo(buf); } 275 276 SymtabSection::SymtabSection(StringTableSection &stringTableSection) 277 : SyntheticSection(segment_names::linkEdit, section_names::symbolTable), 278 stringTableSection(stringTableSection) { 279 // TODO: When we introduce the SyntheticSections superclass, we should make 280 // all synthetic sections aligned to WordSize by default. 281 align = WordSize; 282 } 283 284 size_t SymtabSection::getSize() const { 285 return symbols.size() * sizeof(structs::nlist_64); 286 } 287 288 void SymtabSection::finalizeContents() { 289 // TODO support other symbol types 290 for (Symbol *sym : symtab->getSymbols()) 291 if (isa<Defined>(sym)) 292 symbols.push_back({sym, stringTableSection.addString(sym->getName())}); 293 } 294 295 void SymtabSection::writeTo(uint8_t *buf) const { 296 auto *nList = reinterpret_cast<structs::nlist_64 *>(buf); 297 for (const SymtabEntry &entry : symbols) { 298 nList->n_strx = entry.strx; 299 // TODO support other symbol types 300 // TODO populate n_desc 301 if (auto *defined = dyn_cast<Defined>(entry.sym)) { 302 nList->n_type = N_EXT | N_SECT; 303 nList->n_sect = defined->isec->parent->index; 304 // For the N_SECT symbol type, n_value is the address of the symbol 305 nList->n_value = defined->value + defined->isec->getVA(); 306 } 307 ++nList; 308 } 309 } 310 311 StringTableSection::StringTableSection() 312 : SyntheticSection(segment_names::linkEdit, section_names::stringTable) {} 313 314 uint32_t StringTableSection::addString(StringRef str) { 315 uint32_t strx = size; 316 strings.push_back(str); 317 size += str.size() + 1; // account for null terminator 318 return strx; 319 } 320 321 void StringTableSection::writeTo(uint8_t *buf) const { 322 uint32_t off = 0; 323 for (StringRef str : strings) { 324 memcpy(buf + off, str.data(), str.size()); 325 off += str.size() + 1; // account for null terminator 326 } 327 } 328 329 InStruct in; 330 331 } // namespace macho 332 } // namespace lld 333