1 //===- Chunks.cpp ---------------------------------------------------------===// 2 // 3 // The LLVM Linker 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #include "Chunks.h" 11 #include "Error.h" 12 #include "InputFiles.h" 13 #include "Symbols.h" 14 #include "Writer.h" 15 #include "llvm/ADT/Twine.h" 16 #include "llvm/BinaryFormat/COFF.h" 17 #include "llvm/Object/COFF.h" 18 #include "llvm/Support/Debug.h" 19 #include "llvm/Support/Endian.h" 20 #include "llvm/Support/raw_ostream.h" 21 #include <algorithm> 22 23 using namespace llvm; 24 using namespace llvm::object; 25 using namespace llvm::support::endian; 26 using namespace llvm::COFF; 27 using llvm::support::ulittle32_t; 28 29 namespace lld { 30 namespace coff { 31 32 SectionChunk::SectionChunk(ObjectFile *F, const coff_section *H) 33 : Chunk(SectionKind), Repl(this), Header(H), File(F), 34 Relocs(File->getCOFFObj()->getRelocations(Header)), 35 NumRelocs(std::distance(Relocs.begin(), Relocs.end())) { 36 // Initialize SectionName. 37 File->getCOFFObj()->getSectionName(Header, SectionName); 38 39 Align = Header->getAlignment(); 40 41 // Chunks may be discarded during comdat merging. 42 Discarded = false; 43 44 // If linker GC is disabled, every chunk starts out alive. If linker GC is 45 // enabled, treat non-comdat sections as roots. Generally optimized object 46 // files will be built with -ffunction-sections or /Gy, so most things worth 47 // stripping will be in a comdat. 48 Live = !Config->DoGC || !isCOMDAT(); 49 } 50 51 static void add16(uint8_t *P, int16_t V) { write16le(P, read16le(P) + V); } 52 static void add32(uint8_t *P, int32_t V) { write32le(P, read32le(P) + V); } 53 static void add64(uint8_t *P, int64_t V) { write64le(P, read64le(P) + V); } 54 static void or16(uint8_t *P, uint16_t V) { write16le(P, read16le(P) | V); } 55 static void or32(uint8_t *P, uint32_t V) { write32le(P, read32le(P) | V); } 56 57 static void applySecRel(const SectionChunk *Sec, uint8_t *Off, 58 OutputSection *OS, uint64_t S) { 59 if (!OS) { 60 if (Sec->isCodeView()) 61 return; 62 fatal("SECREL relocation cannot be applied to absolute symbols"); 63 } 64 uint64_t SecRel = S - OS->getRVA(); 65 assert(SecRel < INT32_MAX && "overflow in SECREL relocation"); 66 add32(Off, SecRel); 67 } 68 69 static void applySecIdx(uint8_t *Off, OutputSection *OS) { 70 // If we have no output section, this must be an absolute symbol. Use the 71 // sentinel absolute symbol section index. 72 uint16_t SecIdx = OS ? OS->SectionIndex : DefinedAbsolute::OutputSectionIndex; 73 add16(Off, SecIdx); 74 } 75 76 void SectionChunk::applyRelX64(uint8_t *Off, uint16_t Type, OutputSection *OS, 77 uint64_t S, uint64_t P) const { 78 switch (Type) { 79 case IMAGE_REL_AMD64_ADDR32: add32(Off, S + Config->ImageBase); break; 80 case IMAGE_REL_AMD64_ADDR64: add64(Off, S + Config->ImageBase); break; 81 case IMAGE_REL_AMD64_ADDR32NB: add32(Off, S); break; 82 case IMAGE_REL_AMD64_REL32: add32(Off, S - P - 4); break; 83 case IMAGE_REL_AMD64_REL32_1: add32(Off, S - P - 5); break; 84 case IMAGE_REL_AMD64_REL32_2: add32(Off, S - P - 6); break; 85 case IMAGE_REL_AMD64_REL32_3: add32(Off, S - P - 7); break; 86 case IMAGE_REL_AMD64_REL32_4: add32(Off, S - P - 8); break; 87 case IMAGE_REL_AMD64_REL32_5: add32(Off, S - P - 9); break; 88 case IMAGE_REL_AMD64_SECTION: applySecIdx(Off, OS); break; 89 case IMAGE_REL_AMD64_SECREL: applySecRel(this, Off, OS, S); break; 90 default: 91 fatal("unsupported relocation type 0x" + Twine::utohexstr(Type)); 92 } 93 } 94 95 void SectionChunk::applyRelX86(uint8_t *Off, uint16_t Type, OutputSection *OS, 96 uint64_t S, uint64_t P) const { 97 switch (Type) { 98 case IMAGE_REL_I386_ABSOLUTE: break; 99 case IMAGE_REL_I386_DIR32: add32(Off, S + Config->ImageBase); break; 100 case IMAGE_REL_I386_DIR32NB: add32(Off, S); break; 101 case IMAGE_REL_I386_REL32: add32(Off, S - P - 4); break; 102 case IMAGE_REL_I386_SECTION: applySecIdx(Off, OS); break; 103 case IMAGE_REL_I386_SECREL: applySecRel(this, Off, OS, S); break; 104 default: 105 fatal("unsupported relocation type 0x" + Twine::utohexstr(Type)); 106 } 107 } 108 109 static void applyMOV(uint8_t *Off, uint16_t V) { 110 write16le(Off, (read16le(Off) & 0xfbf0) | ((V & 0x800) >> 1) | ((V >> 12) & 0xf)); 111 write16le(Off + 2, (read16le(Off + 2) & 0x8f00) | ((V & 0x700) << 4) | (V & 0xff)); 112 } 113 114 static uint16_t readMOV(uint8_t *Off) { 115 uint16_t Opcode1 = read16le(Off); 116 uint16_t Opcode2 = read16le(Off + 2); 117 uint16_t Imm = (Opcode2 & 0x00ff) | ((Opcode2 >> 4) & 0x0700); 118 Imm |= ((Opcode1 << 1) & 0x0800) | ((Opcode1 & 0x000f) << 12); 119 return Imm; 120 } 121 122 static void applyMOV32T(uint8_t *Off, uint32_t V) { 123 uint16_t ImmW = readMOV(Off); // read MOVW operand 124 uint16_t ImmT = readMOV(Off + 4); // read MOVT operand 125 uint32_t Imm = ImmW | (ImmT << 16); 126 V += Imm; // add the immediate offset 127 applyMOV(Off, V); // set MOVW operand 128 applyMOV(Off + 4, V >> 16); // set MOVT operand 129 } 130 131 static void applyBranch20T(uint8_t *Off, int32_t V) { 132 uint32_t S = V < 0 ? 1 : 0; 133 uint32_t J1 = (V >> 19) & 1; 134 uint32_t J2 = (V >> 18) & 1; 135 or16(Off, (S << 10) | ((V >> 12) & 0x3f)); 136 or16(Off + 2, (J1 << 13) | (J2 << 11) | ((V >> 1) & 0x7ff)); 137 } 138 139 static void applyBranch24T(uint8_t *Off, int32_t V) { 140 if (!isInt<25>(V)) 141 fatal("relocation out of range"); 142 uint32_t S = V < 0 ? 1 : 0; 143 uint32_t J1 = ((~V >> 23) & 1) ^ S; 144 uint32_t J2 = ((~V >> 22) & 1) ^ S; 145 or16(Off, (S << 10) | ((V >> 12) & 0x3ff)); 146 // Clear out the J1 and J2 bits which may be set. 147 write16le(Off + 2, (read16le(Off + 2) & 0xd000) | (J1 << 13) | (J2 << 11) | ((V >> 1) & 0x7ff)); 148 } 149 150 void SectionChunk::applyRelARM(uint8_t *Off, uint16_t Type, OutputSection *OS, 151 uint64_t S, uint64_t P) const { 152 // Pointer to thumb code must have the LSB set. 153 uint64_t SX = S; 154 if (OS && (OS->getPermissions() & IMAGE_SCN_MEM_EXECUTE)) 155 SX |= 1; 156 switch (Type) { 157 case IMAGE_REL_ARM_ADDR32: add32(Off, SX + Config->ImageBase); break; 158 case IMAGE_REL_ARM_ADDR32NB: add32(Off, SX); break; 159 case IMAGE_REL_ARM_MOV32T: applyMOV32T(Off, SX + Config->ImageBase); break; 160 case IMAGE_REL_ARM_BRANCH20T: applyBranch20T(Off, SX - P - 4); break; 161 case IMAGE_REL_ARM_BRANCH24T: applyBranch24T(Off, SX - P - 4); break; 162 case IMAGE_REL_ARM_BLX23T: applyBranch24T(Off, SX - P - 4); break; 163 case IMAGE_REL_ARM_SECTION: applySecIdx(Off, OS); break; 164 case IMAGE_REL_ARM_SECREL: applySecRel(this, Off, OS, S); break; 165 default: 166 fatal("unsupported relocation type 0x" + Twine::utohexstr(Type)); 167 } 168 } 169 170 static void applyArm64Addr(uint8_t *Off, uint64_t Imm) { 171 uint32_t ImmLo = (Imm & 0x3) << 29; 172 uint32_t ImmHi = (Imm & 0x1FFFFC) << 3; 173 uint64_t Mask = (0x3 << 29) | (0x1FFFFC << 3); 174 write32le(Off, (read32le(Off) & ~Mask) | ImmLo | ImmHi); 175 } 176 177 // Update the immediate field in a AARCH64 ldr, str, and add instruction. 178 static void applyArm64Imm(uint8_t *Off, uint64_t Imm) { 179 uint32_t Orig = read32le(Off); 180 Imm += (Orig >> 10) & 0xFFF; 181 Orig &= ~(0xFFF << 10); 182 write32le(Off, Orig | ((Imm & 0xFFF) << 10)); 183 } 184 185 static void applyArm64Ldr(uint8_t *Off, uint64_t Imm) { 186 int Size = read32le(Off) >> 30; 187 Imm >>= Size; 188 applyArm64Imm(Off, Imm); 189 } 190 191 void SectionChunk::applyRelARM64(uint8_t *Off, uint16_t Type, OutputSection *OS, 192 uint64_t S, uint64_t P) const { 193 switch (Type) { 194 case IMAGE_REL_ARM64_PAGEBASE_REL21: applyArm64Addr(Off, (S >> 12) - (P >> 12)); break; 195 case IMAGE_REL_ARM64_PAGEOFFSET_12A: applyArm64Imm(Off, S & 0xfff); break; 196 case IMAGE_REL_ARM64_PAGEOFFSET_12L: applyArm64Ldr(Off, S & 0xfff); break; 197 case IMAGE_REL_ARM64_BRANCH26: or32(Off, ((S - P) & 0x0FFFFFFC) >> 2); break; 198 case IMAGE_REL_ARM64_ADDR32: add32(Off, S + Config->ImageBase); break; 199 case IMAGE_REL_ARM64_ADDR64: add64(Off, S + Config->ImageBase); break; 200 default: 201 fatal("unsupported relocation type 0x" + Twine::utohexstr(Type)); 202 } 203 } 204 205 void SectionChunk::writeTo(uint8_t *Buf) const { 206 if (!hasData()) 207 return; 208 // Copy section contents from source object file to output file. 209 ArrayRef<uint8_t> A = getContents(); 210 memcpy(Buf + OutputSectionOff, A.data(), A.size()); 211 212 // Apply relocations. 213 size_t InputSize = getSize(); 214 for (const coff_relocation &Rel : Relocs) { 215 // Check for an invalid relocation offset. This check isn't perfect, because 216 // we don't have the relocation size, which is only known after checking the 217 // machine and relocation type. As a result, a relocation may overwrite the 218 // beginning of the following input section. 219 if (Rel.VirtualAddress >= InputSize) 220 fatal("relocation points beyond the end of its parent section"); 221 222 uint8_t *Off = Buf + OutputSectionOff + Rel.VirtualAddress; 223 224 // Get the output section of the symbol for this relocation. The output 225 // section is needed to compute SECREL and SECTION relocations used in debug 226 // info. 227 SymbolBody *Body = File->getSymbolBody(Rel.SymbolTableIndex); 228 Defined *Sym = cast<Defined>(Body); 229 Chunk *C = Sym->getChunk(); 230 OutputSection *OS = C ? C->getOutputSection() : nullptr; 231 232 // Only absolute and __ImageBase symbols lack an output section. For any 233 // other symbol, this indicates that the chunk was discarded. Normally 234 // relocations against discarded sections are an error. However, debug info 235 // sections are not GC roots and can end up with these kinds of relocations. 236 // Skip these relocations. 237 if (!OS && !isa<DefinedAbsolute>(Sym) && !isa<DefinedSynthetic>(Sym)) { 238 if (isCodeView() || isDWARF()) 239 continue; 240 fatal("relocation against symbol in discarded section: " + 241 Sym->getName()); 242 } 243 uint64_t S = Sym->getRVA(); 244 245 // Compute the RVA of the relocation for relative relocations. 246 uint64_t P = RVA + Rel.VirtualAddress; 247 switch (Config->Machine) { 248 case AMD64: 249 applyRelX64(Off, Rel.Type, OS, S, P); 250 break; 251 case I386: 252 applyRelX86(Off, Rel.Type, OS, S, P); 253 break; 254 case ARMNT: 255 applyRelARM(Off, Rel.Type, OS, S, P); 256 break; 257 case ARM64: 258 applyRelARM64(Off, Rel.Type, OS, S, P); 259 break; 260 default: 261 llvm_unreachable("unknown machine type"); 262 } 263 } 264 } 265 266 void SectionChunk::addAssociative(SectionChunk *Child) { 267 AssocChildren.push_back(Child); 268 } 269 270 static uint8_t getBaserelType(const coff_relocation &Rel) { 271 switch (Config->Machine) { 272 case AMD64: 273 if (Rel.Type == IMAGE_REL_AMD64_ADDR64) 274 return IMAGE_REL_BASED_DIR64; 275 return IMAGE_REL_BASED_ABSOLUTE; 276 case I386: 277 if (Rel.Type == IMAGE_REL_I386_DIR32) 278 return IMAGE_REL_BASED_HIGHLOW; 279 return IMAGE_REL_BASED_ABSOLUTE; 280 case ARMNT: 281 if (Rel.Type == IMAGE_REL_ARM_ADDR32) 282 return IMAGE_REL_BASED_HIGHLOW; 283 if (Rel.Type == IMAGE_REL_ARM_MOV32T) 284 return IMAGE_REL_BASED_ARM_MOV32T; 285 return IMAGE_REL_BASED_ABSOLUTE; 286 case ARM64: 287 if (Rel.Type == IMAGE_REL_ARM64_ADDR64) 288 return IMAGE_REL_BASED_DIR64; 289 return IMAGE_REL_BASED_ABSOLUTE; 290 default: 291 llvm_unreachable("unknown machine type"); 292 } 293 } 294 295 // Windows-specific. 296 // Collect all locations that contain absolute addresses, which need to be 297 // fixed by the loader if load-time relocation is needed. 298 // Only called when base relocation is enabled. 299 void SectionChunk::getBaserels(std::vector<Baserel> *Res) { 300 for (const coff_relocation &Rel : Relocs) { 301 uint8_t Ty = getBaserelType(Rel); 302 if (Ty == IMAGE_REL_BASED_ABSOLUTE) 303 continue; 304 SymbolBody *Body = File->getSymbolBody(Rel.SymbolTableIndex); 305 if (isa<DefinedAbsolute>(Body)) 306 continue; 307 Res->emplace_back(RVA + Rel.VirtualAddress, Ty); 308 } 309 } 310 311 bool SectionChunk::hasData() const { 312 return !(Header->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA); 313 } 314 315 uint32_t SectionChunk::getPermissions() const { 316 return Header->Characteristics & PermMask; 317 } 318 319 bool SectionChunk::isCOMDAT() const { 320 return Header->Characteristics & IMAGE_SCN_LNK_COMDAT; 321 } 322 323 void SectionChunk::printDiscardedMessage() const { 324 // Removed by dead-stripping. If it's removed by ICF, ICF already 325 // printed out the name, so don't repeat that here. 326 if (Sym && this == Repl) { 327 if (Discarded) 328 message("Discarded comdat symbol " + Sym->getName()); 329 else if (!Live) 330 message("Discarded " + Sym->getName()); 331 } 332 } 333 334 StringRef SectionChunk::getDebugName() { 335 if (Sym) 336 return Sym->getName(); 337 return ""; 338 } 339 340 ArrayRef<uint8_t> SectionChunk::getContents() const { 341 ArrayRef<uint8_t> A; 342 File->getCOFFObj()->getSectionContents(Header, A); 343 return A; 344 } 345 346 void SectionChunk::replace(SectionChunk *Other) { 347 Other->Repl = Repl; 348 Other->Live = false; 349 } 350 351 CommonChunk::CommonChunk(const COFFSymbolRef S) : Sym(S) { 352 // Common symbols are aligned on natural boundaries up to 32 bytes. 353 // This is what MSVC link.exe does. 354 Align = std::min(uint64_t(32), PowerOf2Ceil(Sym.getValue())); 355 } 356 357 uint32_t CommonChunk::getPermissions() const { 358 return IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_READ | 359 IMAGE_SCN_MEM_WRITE; 360 } 361 362 void StringChunk::writeTo(uint8_t *Buf) const { 363 memcpy(Buf + OutputSectionOff, Str.data(), Str.size()); 364 } 365 366 ImportThunkChunkX64::ImportThunkChunkX64(Defined *S) : ImpSymbol(S) { 367 // Intel Optimization Manual says that all branch targets 368 // should be 16-byte aligned. MSVC linker does this too. 369 Align = 16; 370 } 371 372 void ImportThunkChunkX64::writeTo(uint8_t *Buf) const { 373 memcpy(Buf + OutputSectionOff, ImportThunkX86, sizeof(ImportThunkX86)); 374 // The first two bytes is a JMP instruction. Fill its operand. 375 write32le(Buf + OutputSectionOff + 2, ImpSymbol->getRVA() - RVA - getSize()); 376 } 377 378 void ImportThunkChunkX86::getBaserels(std::vector<Baserel> *Res) { 379 Res->emplace_back(getRVA() + 2); 380 } 381 382 void ImportThunkChunkX86::writeTo(uint8_t *Buf) const { 383 memcpy(Buf + OutputSectionOff, ImportThunkX86, sizeof(ImportThunkX86)); 384 // The first two bytes is a JMP instruction. Fill its operand. 385 write32le(Buf + OutputSectionOff + 2, 386 ImpSymbol->getRVA() + Config->ImageBase); 387 } 388 389 void ImportThunkChunkARM::getBaserels(std::vector<Baserel> *Res) { 390 Res->emplace_back(getRVA(), IMAGE_REL_BASED_ARM_MOV32T); 391 } 392 393 void ImportThunkChunkARM::writeTo(uint8_t *Buf) const { 394 memcpy(Buf + OutputSectionOff, ImportThunkARM, sizeof(ImportThunkARM)); 395 // Fix mov.w and mov.t operands. 396 applyMOV32T(Buf + OutputSectionOff, ImpSymbol->getRVA() + Config->ImageBase); 397 } 398 399 void ImportThunkChunkARM64::writeTo(uint8_t *Buf) const { 400 int64_t PageOff = (ImpSymbol->getRVA() >> 12) - (RVA >> 12); 401 int64_t Off = ImpSymbol->getRVA() & 0xfff; 402 memcpy(Buf + OutputSectionOff, ImportThunkARM64, sizeof(ImportThunkARM64)); 403 applyArm64Addr(Buf + OutputSectionOff, PageOff); 404 applyArm64Ldr(Buf + OutputSectionOff + 4, Off); 405 } 406 407 void LocalImportChunk::getBaserels(std::vector<Baserel> *Res) { 408 Res->emplace_back(getRVA()); 409 } 410 411 size_t LocalImportChunk::getSize() const { 412 return Config->is64() ? 8 : 4; 413 } 414 415 void LocalImportChunk::writeTo(uint8_t *Buf) const { 416 if (Config->is64()) { 417 write64le(Buf + OutputSectionOff, Sym->getRVA() + Config->ImageBase); 418 } else { 419 write32le(Buf + OutputSectionOff, Sym->getRVA() + Config->ImageBase); 420 } 421 } 422 423 void SEHTableChunk::writeTo(uint8_t *Buf) const { 424 ulittle32_t *Begin = reinterpret_cast<ulittle32_t *>(Buf + OutputSectionOff); 425 size_t Cnt = 0; 426 for (Defined *D : Syms) 427 Begin[Cnt++] = D->getRVA(); 428 std::sort(Begin, Begin + Cnt); 429 } 430 431 // Windows-specific. This class represents a block in .reloc section. 432 // The format is described here. 433 // 434 // On Windows, each DLL is linked against a fixed base address and 435 // usually loaded to that address. However, if there's already another 436 // DLL that overlaps, the loader has to relocate it. To do that, DLLs 437 // contain .reloc sections which contain offsets that need to be fixed 438 // up at runtime. If the loader finds that a DLL cannot be loaded to its 439 // desired base address, it loads it to somewhere else, and add <actual 440 // base address> - <desired base address> to each offset that is 441 // specified by the .reloc section. In ELF terms, .reloc sections 442 // contain relative relocations in REL format (as opposed to RELA.) 443 // 444 // This already significantly reduces the size of relocations compared 445 // to ELF .rel.dyn, but Windows does more to reduce it (probably because 446 // it was invented for PCs in the late '80s or early '90s.) Offsets in 447 // .reloc are grouped by page where the page size is 12 bits, and 448 // offsets sharing the same page address are stored consecutively to 449 // represent them with less space. This is very similar to the page 450 // table which is grouped by (multiple stages of) pages. 451 // 452 // For example, let's say we have 0x00030, 0x00500, 0x00700, 0x00A00, 453 // 0x20004, and 0x20008 in a .reloc section for x64. The uppermost 4 454 // bits have a type IMAGE_REL_BASED_DIR64 or 0xA. In the section, they 455 // are represented like this: 456 // 457 // 0x00000 -- page address (4 bytes) 458 // 16 -- size of this block (4 bytes) 459 // 0xA030 -- entries (2 bytes each) 460 // 0xA500 461 // 0xA700 462 // 0xAA00 463 // 0x20000 -- page address (4 bytes) 464 // 12 -- size of this block (4 bytes) 465 // 0xA004 -- entries (2 bytes each) 466 // 0xA008 467 // 468 // Usually we have a lot of relocations for each page, so the number of 469 // bytes for one .reloc entry is close to 2 bytes on average. 470 BaserelChunk::BaserelChunk(uint32_t Page, Baserel *Begin, Baserel *End) { 471 // Block header consists of 4 byte page RVA and 4 byte block size. 472 // Each entry is 2 byte. Last entry may be padding. 473 Data.resize(alignTo((End - Begin) * 2 + 8, 4)); 474 uint8_t *P = Data.data(); 475 write32le(P, Page); 476 write32le(P + 4, Data.size()); 477 P += 8; 478 for (Baserel *I = Begin; I != End; ++I) { 479 write16le(P, (I->Type << 12) | (I->RVA - Page)); 480 P += 2; 481 } 482 } 483 484 void BaserelChunk::writeTo(uint8_t *Buf) const { 485 memcpy(Buf + OutputSectionOff, Data.data(), Data.size()); 486 } 487 488 uint8_t Baserel::getDefaultType() { 489 switch (Config->Machine) { 490 case AMD64: 491 return IMAGE_REL_BASED_DIR64; 492 case I386: 493 return IMAGE_REL_BASED_HIGHLOW; 494 default: 495 llvm_unreachable("unknown machine type"); 496 } 497 } 498 499 } // namespace coff 500 } // namespace lld 501