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 "InputFiles.h" 12 #include "Writer.h" 13 #include "llvm/ADT/Hashing.h" 14 #include "llvm/ADT/STLExtras.h" 15 #include "llvm/Object/COFF.h" 16 #include "llvm/Support/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 27 namespace lld { 28 namespace coff { 29 30 SectionChunk::SectionChunk(ObjectFile *F, const coff_section *H) 31 : Chunk(SectionKind), Ptr(this), File(F), Header(H), 32 Relocs(File->getCOFFObj()->getRelocations(Header)), 33 NumRelocs(std::distance(Relocs.begin(), Relocs.end())) { 34 // Initialize SectionName. 35 File->getCOFFObj()->getSectionName(Header, SectionName); 36 37 // Bit [20:24] contains section alignment. Both 0 and 1 mean alignment 1. 38 unsigned Shift = (Header->Characteristics >> 20) & 0xF; 39 if (Shift > 0) 40 Align = uint32_t(1) << (Shift - 1); 41 42 // COMDAT sections are not GC root. Non-text sections are not 43 // subject of garbage collection (thus they are root). 44 Root = !isCOMDAT() && !(Header->Characteristics & IMAGE_SCN_CNT_CODE); 45 } 46 47 static void add16(uint8_t *P, int16_t V) { write16le(P, read16le(P) + V); } 48 static void add32(uint8_t *P, int32_t V) { write32le(P, read32le(P) + V); } 49 static void add64(uint8_t *P, int64_t V) { write64le(P, read64le(P) + V); } 50 51 void SectionChunk::applyRelX64(uint8_t *Off, uint16_t Type, uint64_t S, 52 uint64_t P) { 53 switch (Type) { 54 case IMAGE_REL_AMD64_ADDR32: add32(Off, S + Config->ImageBase); break; 55 case IMAGE_REL_AMD64_ADDR64: add64(Off, S + Config->ImageBase); break; 56 case IMAGE_REL_AMD64_ADDR32NB: add32(Off, S); break; 57 case IMAGE_REL_AMD64_REL32: add32(Off, S - P - 4); break; 58 case IMAGE_REL_AMD64_REL32_1: add32(Off, S - P - 5); break; 59 case IMAGE_REL_AMD64_REL32_2: add32(Off, S - P - 6); break; 60 case IMAGE_REL_AMD64_REL32_3: add32(Off, S - P - 7); break; 61 case IMAGE_REL_AMD64_REL32_4: add32(Off, S - P - 8); break; 62 case IMAGE_REL_AMD64_REL32_5: add32(Off, S - P - 9); break; 63 case IMAGE_REL_AMD64_SECTION: add16(Off, Out->SectionIndex); break; 64 case IMAGE_REL_AMD64_SECREL: add32(Off, S - Out->getRVA()); break; 65 default: 66 llvm::report_fatal_error("Unsupported relocation type"); 67 } 68 } 69 70 void SectionChunk::applyRelX86(uint8_t *Off, uint16_t Type, uint64_t S, 71 uint64_t P) { 72 switch (Type) { 73 case IMAGE_REL_I386_ABSOLUTE: break; 74 case IMAGE_REL_I386_DIR32: add32(Off, S + Config->ImageBase); break; 75 case IMAGE_REL_I386_DIR32NB: add32(Off, S); break; 76 case IMAGE_REL_I386_REL32: add32(Off, S - P - 4); break; 77 case IMAGE_REL_I386_SECTION: add16(Off, Out->SectionIndex); break; 78 case IMAGE_REL_I386_SECREL: add32(Off, S - Out->getRVA()); break; 79 default: 80 llvm::report_fatal_error("Unsupported relocation type"); 81 } 82 } 83 84 void SectionChunk::writeTo(uint8_t *Buf) { 85 if (!hasData()) 86 return; 87 // Copy section contents from source object file to output file. 88 ArrayRef<uint8_t> A = getContents(); 89 memcpy(Buf + FileOff, A.data(), A.size()); 90 91 // Apply relocations. 92 for (const coff_relocation &Rel : Relocs) { 93 uint8_t *Off = Buf + FileOff + Rel.VirtualAddress; 94 SymbolBody *Body = File->getSymbolBody(Rel.SymbolTableIndex)->repl(); 95 uint64_t S = cast<Defined>(Body)->getRVA(); 96 uint64_t P = RVA + Rel.VirtualAddress; 97 switch (Config->MachineType) { 98 case IMAGE_FILE_MACHINE_AMD64: 99 applyRelX64(Off, Rel.Type, S, P); 100 break; 101 case IMAGE_FILE_MACHINE_I386: 102 applyRelX86(Off, Rel.Type, S, P); 103 break; 104 default: 105 llvm_unreachable("unknown machine type"); 106 } 107 } 108 } 109 110 void SectionChunk::addAssociative(SectionChunk *Child) { 111 AssocChildren.push_back(Child); 112 // Associative sections are live if their parent COMDATs are live, 113 // and vice versa, so they are not considered live by themselves. 114 Child->Root = false; 115 } 116 117 static bool isAbs(const coff_relocation &Rel) { 118 switch (Config->MachineType) { 119 case IMAGE_FILE_MACHINE_AMD64: 120 return Rel.Type == IMAGE_REL_AMD64_ADDR64; 121 case IMAGE_FILE_MACHINE_I386: 122 return Rel.Type == IMAGE_REL_I386_DIR32; 123 default: 124 llvm_unreachable("unknown machine type"); 125 } 126 } 127 128 // Windows-specific. 129 // Collect all locations that contain absolute addresses, which need to be 130 // fixed by the loader if load-time relocation is needed. 131 // Only called when base relocation is enabled. 132 void SectionChunk::getBaserels(std::vector<uint32_t> *Res, Defined *ImageBase) { 133 for (const coff_relocation &Rel : Relocs) { 134 // Symbol __ImageBase is special -- it's an absolute symbol, but its 135 // address never changes even if image is relocated. 136 if (!isAbs(Rel)) 137 continue; 138 SymbolBody *Body = File->getSymbolBody(Rel.SymbolTableIndex)->repl(); 139 if (Body == ImageBase) 140 continue; 141 Res->push_back(RVA + Rel.VirtualAddress); 142 } 143 } 144 145 bool SectionChunk::hasData() const { 146 return !(Header->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA); 147 } 148 149 uint32_t SectionChunk::getPermissions() const { 150 return Header->Characteristics & PermMask; 151 } 152 153 bool SectionChunk::isCOMDAT() const { 154 return Header->Characteristics & IMAGE_SCN_LNK_COMDAT; 155 } 156 157 void SectionChunk::printDiscardedMessage() const { 158 if (this == Ptr) { 159 // Removed by dead-stripping. 160 llvm::dbgs() << "Discarded " << Sym->getName() << "\n"; 161 } else { 162 // Removed by ICF. 163 llvm::dbgs() << "Replaced " << Sym->getName() << "\n"; 164 } 165 } 166 167 StringRef SectionChunk::getDebugName() { 168 return Sym->getName(); 169 } 170 171 uint64_t SectionChunk::getHash() const { 172 ArrayRef<uint8_t> A = getContents(); 173 return hash_combine(getPermissions(), 174 llvm::hash_value(SectionName), 175 NumRelocs, 176 uint32_t(Header->SizeOfRawData), 177 std::distance(Relocs.end(), Relocs.begin()), 178 hash_combine_range(A.data(), A.data() + A.size())); 179 } 180 181 // Returns true if this and a given chunk are identical COMDAT sections. 182 bool SectionChunk::equals(const SectionChunk *X) const { 183 // Compare headers 184 if (getPermissions() != X->getPermissions()) 185 return false; 186 if (SectionName != X->SectionName) 187 return false; 188 if (Header->SizeOfRawData != X->Header->SizeOfRawData) 189 return false; 190 if (NumRelocs != X->NumRelocs) 191 return false; 192 193 // Compare data 194 if (getContents() != X->getContents()) 195 return false; 196 197 // Compare associative sections 198 if (AssocChildren.size() != X->AssocChildren.size()) 199 return false; 200 for (size_t I = 0, E = AssocChildren.size(); I != E; ++I) 201 if (AssocChildren[I]->Ptr != X->AssocChildren[I]->Ptr) 202 return false; 203 204 // Compare relocations 205 auto Eq = [&](const coff_relocation &R1, const coff_relocation &R2) { 206 if (R1.Type != R2.Type) 207 return false; 208 if (R1.VirtualAddress != R2.VirtualAddress) 209 return false; 210 SymbolBody *B1 = File->getSymbolBody(R1.SymbolTableIndex)->repl(); 211 SymbolBody *B2 = X->File->getSymbolBody(R2.SymbolTableIndex)->repl(); 212 if (B1 == B2) 213 return true; 214 auto *D1 = dyn_cast<DefinedRegular>(B1); 215 auto *D2 = dyn_cast<DefinedRegular>(B2); 216 return (D1 && D2 && 217 D1->getValue() == D2->getValue() && 218 D1->getChunk() == D2->getChunk()); 219 }; 220 return std::equal(Relocs.begin(), Relocs.end(), X->Relocs.begin(), Eq); 221 } 222 223 ArrayRef<uint8_t> SectionChunk::getContents() const { 224 ArrayRef<uint8_t> A; 225 File->getCOFFObj()->getSectionContents(Header, A); 226 return A; 227 } 228 229 void SectionChunk::replaceWith(SectionChunk *Other) { 230 Ptr = Other->Ptr; 231 Live = false; 232 } 233 234 CommonChunk::CommonChunk(const COFFSymbolRef S) : Sym(S) { 235 // Common symbols are aligned on natural boundaries up to 32 bytes. 236 // This is what MSVC link.exe does. 237 Align = std::min(uint64_t(32), NextPowerOf2(Sym.getValue())); 238 } 239 240 uint32_t CommonChunk::getPermissions() const { 241 return IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_READ | 242 IMAGE_SCN_MEM_WRITE; 243 } 244 245 void StringChunk::writeTo(uint8_t *Buf) { 246 memcpy(Buf + FileOff, Str.data(), Str.size()); 247 } 248 249 ImportThunkChunk::ImportThunkChunk(Defined *S) : ImpSymbol(S) { 250 // Intel Optimization Manual says that all branch targets 251 // should be 16-byte aligned. MSVC linker does this too. 252 Align = 16; 253 } 254 255 void ImportThunkChunk::getBaserels(std::vector<uint32_t> *Res, 256 Defined *ImageBase) { 257 if (!Config->is64()) 258 Res->push_back(getRVA() + 2); 259 } 260 261 void ImportThunkChunk::writeTo(uint8_t *Buf) { 262 memcpy(Buf + FileOff, ImportThunkData, sizeof(ImportThunkData)); 263 // The first two bytes is a JMP instruction. Fill its operand. 264 uint32_t Operand = Config->is64() 265 ? ImpSymbol->getRVA() - RVA - getSize() 266 : ImpSymbol->getRVA() + Config->ImageBase; 267 write32le(Buf + FileOff + 2, Operand); 268 } 269 270 void LocalImportChunk::getBaserels(std::vector<uint32_t> *Res, 271 Defined *ImageBase) { 272 Res->push_back(getRVA()); 273 } 274 275 size_t LocalImportChunk::getSize() const { 276 return Config->is64() ? 8 : 4; 277 } 278 279 void LocalImportChunk::writeTo(uint8_t *Buf) { 280 if (Config->is64()) { 281 write64le(Buf + FileOff, Sym->getRVA() + Config->ImageBase); 282 } else { 283 write32le(Buf + FileOff, Sym->getRVA() + Config->ImageBase); 284 } 285 } 286 287 // Windows-specific. 288 // This class represents a block in .reloc section. 289 BaserelChunk::BaserelChunk(uint32_t Page, uint32_t *Begin, uint32_t *End) { 290 // Block header consists of 4 byte page RVA and 4 byte block size. 291 // Each entry is 2 byte. Last entry may be padding. 292 Data.resize(RoundUpToAlignment((End - Begin) * 2 + 8, 4)); 293 uint8_t *P = Data.data(); 294 write32le(P, Page); 295 write32le(P + 4, Data.size()); 296 P += 8; 297 for (uint32_t *I = Begin; I != End; ++I) { 298 write16le(P, (IMAGE_REL_BASED_DIR64 << 12) | (*I - Page)); 299 P += 2; 300 } 301 } 302 303 void BaserelChunk::writeTo(uint8_t *Buf) { 304 memcpy(Buf + FileOff, Data.data(), Data.size()); 305 } 306 307 } // namespace coff 308 } // namespace lld 309