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