1 //===- InputChunks.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 "InputChunks.h" 10 #include "Config.h" 11 #include "OutputSegment.h" 12 #include "WriterUtils.h" 13 #include "lld/Common/ErrorHandler.h" 14 #include "lld/Common/LLVM.h" 15 #include "llvm/Support/LEB128.h" 16 17 #define DEBUG_TYPE "lld" 18 19 using namespace llvm; 20 using namespace llvm::wasm; 21 using namespace llvm::support::endian; 22 23 namespace lld { 24 StringRef relocTypeToString(uint8_t relocType) { 25 switch (relocType) { 26 #define WASM_RELOC(NAME, REL) \ 27 case REL: \ 28 return #NAME; 29 #include "llvm/BinaryFormat/WasmRelocs.def" 30 #undef WASM_RELOC 31 } 32 llvm_unreachable("unknown reloc type"); 33 } 34 35 bool relocIs64(uint8_t relocType) { 36 switch (relocType) { 37 case R_WASM_MEMORY_ADDR_LEB64: 38 case R_WASM_MEMORY_ADDR_SLEB64: 39 case R_WASM_MEMORY_ADDR_REL_SLEB64: 40 case R_WASM_MEMORY_ADDR_I64: 41 return true; 42 default: 43 return false; 44 } 45 } 46 47 std::string toString(const wasm::InputChunk *c) { 48 return (toString(c->file) + ":(" + c->getName() + ")").str(); 49 } 50 51 namespace wasm { 52 StringRef InputChunk::getComdatName() const { 53 uint32_t index = getComdat(); 54 if (index == UINT32_MAX) 55 return StringRef(); 56 return file->getWasmObj()->linkingData().Comdats[index]; 57 } 58 59 void InputChunk::verifyRelocTargets() const { 60 for (const WasmRelocation &rel : relocations) { 61 uint64_t existingValue; 62 unsigned bytesRead = 0; 63 unsigned paddedLEBWidth = 5; 64 auto offset = rel.Offset - getInputSectionOffset(); 65 const uint8_t *loc = data().data() + offset; 66 switch (rel.Type) { 67 case R_WASM_TYPE_INDEX_LEB: 68 case R_WASM_FUNCTION_INDEX_LEB: 69 case R_WASM_GLOBAL_INDEX_LEB: 70 case R_WASM_EVENT_INDEX_LEB: 71 case R_WASM_MEMORY_ADDR_LEB: 72 existingValue = decodeULEB128(loc, &bytesRead); 73 break; 74 case R_WASM_MEMORY_ADDR_LEB64: 75 existingValue = decodeULEB128(loc, &bytesRead); 76 paddedLEBWidth = 10; 77 break; 78 case R_WASM_TABLE_INDEX_SLEB: 79 case R_WASM_TABLE_INDEX_REL_SLEB: 80 case R_WASM_MEMORY_ADDR_SLEB: 81 case R_WASM_MEMORY_ADDR_REL_SLEB: 82 case R_WASM_MEMORY_ADDR_TLS_SLEB: 83 existingValue = static_cast<uint64_t>(decodeSLEB128(loc, &bytesRead)); 84 break; 85 case R_WASM_TABLE_INDEX_SLEB64: 86 case R_WASM_MEMORY_ADDR_SLEB64: 87 case R_WASM_MEMORY_ADDR_REL_SLEB64: 88 existingValue = static_cast<uint64_t>(decodeSLEB128(loc, &bytesRead)); 89 paddedLEBWidth = 10; 90 break; 91 case R_WASM_TABLE_INDEX_I32: 92 case R_WASM_MEMORY_ADDR_I32: 93 case R_WASM_FUNCTION_OFFSET_I32: 94 case R_WASM_SECTION_OFFSET_I32: 95 case R_WASM_GLOBAL_INDEX_I32: 96 existingValue = read32le(loc); 97 break; 98 case R_WASM_TABLE_INDEX_I64: 99 case R_WASM_MEMORY_ADDR_I64: 100 existingValue = read64le(loc); 101 break; 102 default: 103 llvm_unreachable("unknown relocation type"); 104 } 105 106 if (bytesRead && bytesRead != paddedLEBWidth) 107 warn("expected LEB at relocation site be 5/10-byte padded"); 108 109 if (rel.Type != R_WASM_GLOBAL_INDEX_LEB && 110 rel.Type != R_WASM_GLOBAL_INDEX_I32) { 111 auto expectedValue = file->calcExpectedValue(rel); 112 if (expectedValue != existingValue) 113 warn(toString(this) + ": unexpected existing value for " + 114 relocTypeToString(rel.Type) + ": existing=" + 115 Twine(existingValue) + " expected=" + Twine(expectedValue)); 116 } 117 } 118 } 119 120 // Copy this input chunk to an mmap'ed output file and apply relocations. 121 void InputChunk::writeTo(uint8_t *buf) const { 122 // Copy contents 123 memcpy(buf + outputOffset, data().data(), data().size()); 124 125 // Apply relocations 126 if (relocations.empty()) 127 return; 128 129 #ifndef NDEBUG 130 verifyRelocTargets(); 131 #endif 132 133 LLVM_DEBUG(dbgs() << "applying relocations: " << toString(this) 134 << " count=" << relocations.size() << "\n"); 135 int32_t off = outputOffset - getInputSectionOffset(); 136 137 for (const WasmRelocation &rel : relocations) { 138 uint8_t *loc = buf + rel.Offset + off; 139 auto value = file->calcNewValue(rel); 140 LLVM_DEBUG(dbgs() << "apply reloc: type=" << relocTypeToString(rel.Type)); 141 if (rel.Type != R_WASM_TYPE_INDEX_LEB) 142 LLVM_DEBUG(dbgs() << " sym=" << file->getSymbols()[rel.Index]->getName()); 143 LLVM_DEBUG(dbgs() << " addend=" << rel.Addend << " index=" << rel.Index 144 << " value=" << value << " offset=" << rel.Offset 145 << "\n"); 146 147 switch (rel.Type) { 148 case R_WASM_TYPE_INDEX_LEB: 149 case R_WASM_FUNCTION_INDEX_LEB: 150 case R_WASM_GLOBAL_INDEX_LEB: 151 case R_WASM_EVENT_INDEX_LEB: 152 case R_WASM_MEMORY_ADDR_LEB: 153 encodeULEB128(value, loc, 5); 154 break; 155 case R_WASM_MEMORY_ADDR_LEB64: 156 encodeULEB128(value, loc, 10); 157 break; 158 case R_WASM_TABLE_INDEX_SLEB: 159 case R_WASM_TABLE_INDEX_REL_SLEB: 160 case R_WASM_MEMORY_ADDR_SLEB: 161 case R_WASM_MEMORY_ADDR_REL_SLEB: 162 case R_WASM_MEMORY_ADDR_TLS_SLEB: 163 encodeSLEB128(static_cast<int32_t>(value), loc, 5); 164 break; 165 case R_WASM_TABLE_INDEX_SLEB64: 166 case R_WASM_MEMORY_ADDR_SLEB64: 167 case R_WASM_MEMORY_ADDR_REL_SLEB64: 168 encodeSLEB128(static_cast<int64_t>(value), loc, 10); 169 break; 170 case R_WASM_TABLE_INDEX_I32: 171 case R_WASM_MEMORY_ADDR_I32: 172 case R_WASM_FUNCTION_OFFSET_I32: 173 case R_WASM_SECTION_OFFSET_I32: 174 case R_WASM_GLOBAL_INDEX_I32: 175 write32le(loc, value); 176 break; 177 case R_WASM_TABLE_INDEX_I64: 178 case R_WASM_MEMORY_ADDR_I64: 179 write64le(loc, value); 180 break; 181 default: 182 llvm_unreachable("unknown relocation type"); 183 } 184 } 185 } 186 187 // Copy relocation entries to a given output stream. 188 // This function is used only when a user passes "-r". For a regular link, 189 // we consume relocations instead of copying them to an output file. 190 void InputChunk::writeRelocations(raw_ostream &os) const { 191 if (relocations.empty()) 192 return; 193 194 int32_t off = outputOffset - getInputSectionOffset(); 195 LLVM_DEBUG(dbgs() << "writeRelocations: " << file->getName() 196 << " offset=" << Twine(off) << "\n"); 197 198 for (const WasmRelocation &rel : relocations) { 199 writeUleb128(os, rel.Type, "reloc type"); 200 writeUleb128(os, rel.Offset + off, "reloc offset"); 201 writeUleb128(os, file->calcNewIndex(rel), "reloc index"); 202 203 if (relocTypeHasAddend(rel.Type)) 204 writeSleb128(os, file->calcNewAddend(rel), "reloc addend"); 205 } 206 } 207 208 void InputFunction::setFunctionIndex(uint32_t index) { 209 LLVM_DEBUG(dbgs() << "InputFunction::setFunctionIndex: " << getName() 210 << " -> " << index << "\n"); 211 assert(!hasFunctionIndex()); 212 functionIndex = index; 213 } 214 215 void InputFunction::setTableIndex(uint32_t index) { 216 LLVM_DEBUG(dbgs() << "InputFunction::setTableIndex: " << getName() << " -> " 217 << index << "\n"); 218 assert(!hasTableIndex()); 219 tableIndex = index; 220 } 221 222 // Write a relocation value without padding and return the number of bytes 223 // witten. 224 static unsigned writeCompressedReloc(uint8_t *buf, const WasmRelocation &rel, 225 uint64_t value) { 226 switch (rel.Type) { 227 case R_WASM_TYPE_INDEX_LEB: 228 case R_WASM_FUNCTION_INDEX_LEB: 229 case R_WASM_GLOBAL_INDEX_LEB: 230 case R_WASM_EVENT_INDEX_LEB: 231 case R_WASM_MEMORY_ADDR_LEB: 232 case R_WASM_MEMORY_ADDR_LEB64: 233 return encodeULEB128(value, buf); 234 case R_WASM_TABLE_INDEX_SLEB: 235 case R_WASM_TABLE_INDEX_SLEB64: 236 case R_WASM_MEMORY_ADDR_SLEB: 237 case R_WASM_MEMORY_ADDR_SLEB64: 238 return encodeSLEB128(static_cast<int64_t>(value), buf); 239 default: 240 llvm_unreachable("unexpected relocation type"); 241 } 242 } 243 244 static unsigned getRelocWidthPadded(const WasmRelocation &rel) { 245 switch (rel.Type) { 246 case R_WASM_TYPE_INDEX_LEB: 247 case R_WASM_FUNCTION_INDEX_LEB: 248 case R_WASM_GLOBAL_INDEX_LEB: 249 case R_WASM_EVENT_INDEX_LEB: 250 case R_WASM_MEMORY_ADDR_LEB: 251 case R_WASM_TABLE_INDEX_SLEB: 252 case R_WASM_MEMORY_ADDR_SLEB: 253 return 5; 254 case R_WASM_TABLE_INDEX_SLEB64: 255 case R_WASM_MEMORY_ADDR_LEB64: 256 case R_WASM_MEMORY_ADDR_SLEB64: 257 return 10; 258 default: 259 llvm_unreachable("unexpected relocation type"); 260 } 261 } 262 263 static unsigned getRelocWidth(const WasmRelocation &rel, uint64_t value) { 264 uint8_t buf[10]; 265 return writeCompressedReloc(buf, rel, value); 266 } 267 268 // Relocations of type LEB and SLEB in the code section are padded to 5 bytes 269 // so that a fast linker can blindly overwrite them without needing to worry 270 // about the number of bytes needed to encode the values. 271 // However, for optimal output the code section can be compressed to remove 272 // the padding then outputting non-relocatable files. 273 // In this case we need to perform a size calculation based on the value at each 274 // relocation. At best we end up saving 4 bytes for each relocation entry. 275 // 276 // This function only computes the final output size. It must be called 277 // before getSize() is used to calculate of layout of the code section. 278 void InputFunction::calculateSize() { 279 if (!file || !config->compressRelocations) 280 return; 281 282 LLVM_DEBUG(dbgs() << "calculateSize: " << getName() << "\n"); 283 284 const uint8_t *secStart = file->codeSection->Content.data(); 285 const uint8_t *funcStart = secStart + getInputSectionOffset(); 286 uint32_t functionSizeLength; 287 decodeULEB128(funcStart, &functionSizeLength); 288 289 uint32_t start = getInputSectionOffset(); 290 uint32_t end = start + function->Size; 291 292 uint32_t lastRelocEnd = start + functionSizeLength; 293 for (const WasmRelocation &rel : relocations) { 294 LLVM_DEBUG(dbgs() << " region: " << (rel.Offset - lastRelocEnd) << "\n"); 295 compressedFuncSize += rel.Offset - lastRelocEnd; 296 compressedFuncSize += getRelocWidth(rel, file->calcNewValue(rel)); 297 lastRelocEnd = rel.Offset + getRelocWidthPadded(rel); 298 } 299 LLVM_DEBUG(dbgs() << " final region: " << (end - lastRelocEnd) << "\n"); 300 compressedFuncSize += end - lastRelocEnd; 301 302 // Now we know how long the resulting function is we can add the encoding 303 // of its length 304 uint8_t buf[5]; 305 compressedSize = compressedFuncSize + encodeULEB128(compressedFuncSize, buf); 306 307 LLVM_DEBUG(dbgs() << " calculateSize orig: " << function->Size << "\n"); 308 LLVM_DEBUG(dbgs() << " calculateSize new: " << compressedSize << "\n"); 309 } 310 311 // Override the default writeTo method so that we can (optionally) write the 312 // compressed version of the function. 313 void InputFunction::writeTo(uint8_t *buf) const { 314 if (!file || !config->compressRelocations) 315 return InputChunk::writeTo(buf); 316 317 buf += outputOffset; 318 uint8_t *orig = buf; 319 (void)orig; 320 321 const uint8_t *secStart = file->codeSection->Content.data(); 322 const uint8_t *funcStart = secStart + getInputSectionOffset(); 323 const uint8_t *end = funcStart + function->Size; 324 uint32_t count; 325 decodeULEB128(funcStart, &count); 326 funcStart += count; 327 328 LLVM_DEBUG(dbgs() << "write func: " << getName() << "\n"); 329 buf += encodeULEB128(compressedFuncSize, buf); 330 const uint8_t *lastRelocEnd = funcStart; 331 for (const WasmRelocation &rel : relocations) { 332 unsigned chunkSize = (secStart + rel.Offset) - lastRelocEnd; 333 LLVM_DEBUG(dbgs() << " write chunk: " << chunkSize << "\n"); 334 memcpy(buf, lastRelocEnd, chunkSize); 335 buf += chunkSize; 336 buf += writeCompressedReloc(buf, rel, file->calcNewValue(rel)); 337 lastRelocEnd = secStart + rel.Offset + getRelocWidthPadded(rel); 338 } 339 340 unsigned chunkSize = end - lastRelocEnd; 341 LLVM_DEBUG(dbgs() << " write final chunk: " << chunkSize << "\n"); 342 memcpy(buf, lastRelocEnd, chunkSize); 343 LLVM_DEBUG(dbgs() << " total: " << (buf + chunkSize - orig) << "\n"); 344 } 345 346 // Generate code to apply relocations to the data section at runtime. 347 // This is only called when generating shared libaries (PIC) where address are 348 // not known at static link time. 349 void InputSegment::generateRelocationCode(raw_ostream &os) const { 350 LLVM_DEBUG(dbgs() << "generating runtime relocations: " << getName() 351 << " count=" << relocations.size() << "\n"); 352 353 unsigned opcode_ptr_const = config->is64.getValueOr(false) 354 ? WASM_OPCODE_I64_CONST 355 : WASM_OPCODE_I32_CONST; 356 unsigned opcode_ptr_add = config->is64.getValueOr(false) 357 ? WASM_OPCODE_I64_ADD 358 : WASM_OPCODE_I32_ADD; 359 360 // TODO(sbc): Encode the relocations in the data section and write a loop 361 // here to apply them. 362 uint64_t segmentVA = outputSeg->startVA + outputSegmentOffset; 363 for (const WasmRelocation &rel : relocations) { 364 uint64_t offset = rel.Offset - getInputSectionOffset(); 365 uint64_t outputOffset = segmentVA + offset; 366 367 LLVM_DEBUG(dbgs() << "gen reloc: type=" << relocTypeToString(rel.Type) 368 << " addend=" << rel.Addend << " index=" << rel.Index 369 << " output offset=" << outputOffset << "\n"); 370 371 // Get __memory_base 372 writeU8(os, WASM_OPCODE_GLOBAL_GET, "GLOBAL_GET"); 373 writeUleb128(os, WasmSym::memoryBase->getGlobalIndex(), "memory_base"); 374 375 // Add the offset of the relocation 376 writeU8(os, opcode_ptr_const, "CONST"); 377 writeSleb128(os, outputOffset, "offset"); 378 writeU8(os, opcode_ptr_add, "ADD"); 379 380 bool is64 = relocIs64(rel.Type); 381 unsigned opcode_reloc_const = 382 is64 ? WASM_OPCODE_I64_CONST : WASM_OPCODE_I32_CONST; 383 unsigned opcode_reloc_add = 384 is64 ? WASM_OPCODE_I64_ADD : WASM_OPCODE_I32_ADD; 385 unsigned opcode_reloc_store = 386 is64 ? WASM_OPCODE_I64_STORE : WASM_OPCODE_I32_STORE; 387 388 Symbol *sym = file->getSymbol(rel); 389 // Now figure out what we want to store 390 if (sym->hasGOTIndex()) { 391 writeU8(os, WASM_OPCODE_GLOBAL_GET, "GLOBAL_GET"); 392 writeUleb128(os, sym->getGOTIndex(), "global index"); 393 if (rel.Addend) { 394 writeU8(os, opcode_reloc_const, "CONST"); 395 writeSleb128(os, rel.Addend, "addend"); 396 writeU8(os, opcode_reloc_add, "ADD"); 397 } 398 } else { 399 const GlobalSymbol* baseSymbol = WasmSym::memoryBase; 400 if (rel.Type == R_WASM_TABLE_INDEX_I32 || 401 rel.Type == R_WASM_TABLE_INDEX_I64) 402 baseSymbol = WasmSym::tableBase; 403 writeU8(os, WASM_OPCODE_GLOBAL_GET, "GLOBAL_GET"); 404 writeUleb128(os, baseSymbol->getGlobalIndex(), "base"); 405 writeU8(os, opcode_reloc_const, "CONST"); 406 writeSleb128(os, file->calcNewValue(rel), "offset"); 407 writeU8(os, opcode_reloc_add, "ADD"); 408 } 409 410 // Store that value at the virtual address 411 writeU8(os, opcode_reloc_store, "I32_STORE"); 412 writeUleb128(os, 2, "align"); 413 writeUleb128(os, 0, "offset"); 414 } 415 } 416 417 } // namespace wasm 418 } // namespace lld 419