1 //===- InputFiles.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 "InputFiles.h" 10 #include "Config.h" 11 #include "InputChunks.h" 12 #include "InputEvent.h" 13 #include "InputGlobal.h" 14 #include "SymbolTable.h" 15 #include "lld/Common/ErrorHandler.h" 16 #include "lld/Common/Memory.h" 17 #include "lld/Common/Reproduce.h" 18 #include "llvm/Object/Binary.h" 19 #include "llvm/Object/Wasm.h" 20 #include "llvm/Support/TarWriter.h" 21 #include "llvm/Support/raw_ostream.h" 22 23 #define DEBUG_TYPE "lld" 24 25 using namespace llvm; 26 using namespace llvm::object; 27 using namespace llvm::wasm; 28 29 namespace lld { 30 31 // Returns a string in the format of "foo.o" or "foo.a(bar.o)". 32 std::string toString(const wasm::InputFile *file) { 33 if (!file) 34 return "<internal>"; 35 36 if (file->archiveName.empty()) 37 return file->getName(); 38 39 return (file->archiveName + "(" + file->getName() + ")").str(); 40 } 41 42 namespace wasm { 43 std::unique_ptr<llvm::TarWriter> tar; 44 45 Optional<MemoryBufferRef> readFile(StringRef path) { 46 log("Loading: " + path); 47 48 auto mbOrErr = MemoryBuffer::getFile(path); 49 if (auto ec = mbOrErr.getError()) { 50 error("cannot open " + path + ": " + ec.message()); 51 return None; 52 } 53 std::unique_ptr<MemoryBuffer> &mb = *mbOrErr; 54 MemoryBufferRef mbref = mb->getMemBufferRef(); 55 make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take MB ownership 56 57 if (tar) 58 tar->append(relativeToRoot(path), mbref.getBuffer()); 59 return mbref; 60 } 61 62 InputFile *createObjectFile(MemoryBufferRef mb, 63 StringRef archiveName) { 64 file_magic magic = identify_magic(mb.getBuffer()); 65 if (magic == file_magic::wasm_object) { 66 std::unique_ptr<Binary> bin = 67 CHECK(createBinary(mb), mb.getBufferIdentifier()); 68 auto *obj = cast<WasmObjectFile>(bin.get()); 69 if (obj->isSharedObject()) 70 return make<SharedFile>(mb); 71 return make<ObjFile>(mb, archiveName); 72 } 73 74 if (magic == file_magic::bitcode) 75 return make<BitcodeFile>(mb, archiveName); 76 77 fatal("unknown file type: " + mb.getBufferIdentifier()); 78 } 79 80 void ObjFile::dumpInfo() const { 81 log("info for: " + toString(this) + 82 "\n Symbols : " + Twine(symbols.size()) + 83 "\n Function Imports : " + Twine(wasmObj->getNumImportedFunctions()) + 84 "\n Global Imports : " + Twine(wasmObj->getNumImportedGlobals()) + 85 "\n Event Imports : " + Twine(wasmObj->getNumImportedEvents())); 86 } 87 88 // Relocations contain either symbol or type indices. This function takes a 89 // relocation and returns relocated index (i.e. translates from the input 90 // symbol/type space to the output symbol/type space). 91 uint32_t ObjFile::calcNewIndex(const WasmRelocation &reloc) const { 92 if (reloc.Type == R_WASM_TYPE_INDEX_LEB) { 93 assert(typeIsUsed[reloc.Index]); 94 return typeMap[reloc.Index]; 95 } 96 const Symbol *sym = symbols[reloc.Index]; 97 if (auto *ss = dyn_cast<SectionSymbol>(sym)) 98 sym = ss->getOutputSectionSymbol(); 99 return sym->getOutputSymbolIndex(); 100 } 101 102 // Relocations can contain addend for combined sections. This function takes a 103 // relocation and returns updated addend by offset in the output section. 104 uint32_t ObjFile::calcNewAddend(const WasmRelocation &reloc) const { 105 switch (reloc.Type) { 106 case R_WASM_MEMORY_ADDR_LEB: 107 case R_WASM_MEMORY_ADDR_SLEB: 108 case R_WASM_MEMORY_ADDR_REL_SLEB: 109 case R_WASM_MEMORY_ADDR_I32: 110 case R_WASM_FUNCTION_OFFSET_I32: 111 return reloc.Addend; 112 case R_WASM_SECTION_OFFSET_I32: 113 return getSectionSymbol(reloc.Index)->section->outputOffset + reloc.Addend; 114 default: 115 llvm_unreachable("unexpected relocation type"); 116 } 117 } 118 119 // Calculate the value we expect to find at the relocation location. 120 // This is used as a sanity check before applying a relocation to a given 121 // location. It is useful for catching bugs in the compiler and linker. 122 uint32_t ObjFile::calcExpectedValue(const WasmRelocation &reloc) const { 123 switch (reloc.Type) { 124 case R_WASM_TABLE_INDEX_I32: 125 case R_WASM_TABLE_INDEX_SLEB: 126 case R_WASM_TABLE_INDEX_REL_SLEB: { 127 const WasmSymbol &sym = wasmObj->syms()[reloc.Index]; 128 return tableEntries[sym.Info.ElementIndex]; 129 } 130 case R_WASM_MEMORY_ADDR_SLEB: 131 case R_WASM_MEMORY_ADDR_I32: 132 case R_WASM_MEMORY_ADDR_LEB: 133 case R_WASM_MEMORY_ADDR_REL_SLEB: { 134 const WasmSymbol &sym = wasmObj->syms()[reloc.Index]; 135 if (sym.isUndefined()) 136 return 0; 137 const WasmSegment &segment = 138 wasmObj->dataSegments()[sym.Info.DataRef.Segment]; 139 return segment.Data.Offset.Value.Int32 + sym.Info.DataRef.Offset + 140 reloc.Addend; 141 } 142 case R_WASM_FUNCTION_OFFSET_I32: { 143 const WasmSymbol &sym = wasmObj->syms()[reloc.Index]; 144 InputFunction *f = 145 functions[sym.Info.ElementIndex - wasmObj->getNumImportedFunctions()]; 146 return f->getFunctionInputOffset() + f->getFunctionCodeOffset() + 147 reloc.Addend; 148 } 149 case R_WASM_SECTION_OFFSET_I32: 150 return reloc.Addend; 151 case R_WASM_TYPE_INDEX_LEB: 152 return reloc.Index; 153 case R_WASM_FUNCTION_INDEX_LEB: 154 case R_WASM_GLOBAL_INDEX_LEB: 155 case R_WASM_EVENT_INDEX_LEB: { 156 const WasmSymbol &sym = wasmObj->syms()[reloc.Index]; 157 return sym.Info.ElementIndex; 158 } 159 default: 160 llvm_unreachable("unknown relocation type"); 161 } 162 } 163 164 // Translate from the relocation's index into the final linked output value. 165 uint32_t ObjFile::calcNewValue(const WasmRelocation &reloc) const { 166 const Symbol* sym = nullptr; 167 if (reloc.Type != R_WASM_TYPE_INDEX_LEB) { 168 sym = symbols[reloc.Index]; 169 170 // We can end up with relocations against non-live symbols. For example 171 // in debug sections. 172 if ((isa<FunctionSymbol>(sym) || isa<DataSymbol>(sym)) && !sym->isLive()) 173 return 0; 174 } 175 176 switch (reloc.Type) { 177 case R_WASM_TABLE_INDEX_I32: 178 case R_WASM_TABLE_INDEX_SLEB: 179 case R_WASM_TABLE_INDEX_REL_SLEB: { 180 if (!getFunctionSymbol(reloc.Index)->hasTableIndex()) 181 return 0; 182 uint32_t index = getFunctionSymbol(reloc.Index)->getTableIndex(); 183 if (reloc.Type == R_WASM_TABLE_INDEX_REL_SLEB) 184 index -= config->tableBase; 185 return index; 186 187 } 188 case R_WASM_MEMORY_ADDR_SLEB: 189 case R_WASM_MEMORY_ADDR_I32: 190 case R_WASM_MEMORY_ADDR_LEB: 191 case R_WASM_MEMORY_ADDR_REL_SLEB: 192 if (isa<UndefinedData>(sym) || sym->isUndefWeak()) 193 return 0; 194 return cast<DefinedData>(sym)->getVirtualAddress() + reloc.Addend; 195 case R_WASM_TYPE_INDEX_LEB: 196 return typeMap[reloc.Index]; 197 case R_WASM_FUNCTION_INDEX_LEB: 198 return getFunctionSymbol(reloc.Index)->getFunctionIndex(); 199 case R_WASM_GLOBAL_INDEX_LEB: 200 if (auto gs = dyn_cast<GlobalSymbol>(sym)) 201 return gs->getGlobalIndex(); 202 return sym->getGOTIndex(); 203 case R_WASM_EVENT_INDEX_LEB: 204 return getEventSymbol(reloc.Index)->getEventIndex(); 205 case R_WASM_FUNCTION_OFFSET_I32: { 206 auto *f = cast<DefinedFunction>(sym); 207 return f->function->outputOffset + f->function->getFunctionCodeOffset() + 208 reloc.Addend; 209 } 210 case R_WASM_SECTION_OFFSET_I32: 211 return getSectionSymbol(reloc.Index)->section->outputOffset + reloc.Addend; 212 default: 213 llvm_unreachable("unknown relocation type"); 214 } 215 } 216 217 template <class T> 218 static void setRelocs(const std::vector<T *> &chunks, 219 const WasmSection *section) { 220 if (!section) 221 return; 222 223 ArrayRef<WasmRelocation> relocs = section->Relocations; 224 assert(std::is_sorted(relocs.begin(), relocs.end(), 225 [](const WasmRelocation &r1, const WasmRelocation &r2) { 226 return r1.Offset < r2.Offset; 227 })); 228 assert(std::is_sorted( 229 chunks.begin(), chunks.end(), [](InputChunk *c1, InputChunk *c2) { 230 return c1->getInputSectionOffset() < c2->getInputSectionOffset(); 231 })); 232 233 auto relocsNext = relocs.begin(); 234 auto relocsEnd = relocs.end(); 235 auto relocLess = [](const WasmRelocation &r, uint32_t val) { 236 return r.Offset < val; 237 }; 238 for (InputChunk *c : chunks) { 239 auto relocsStart = std::lower_bound(relocsNext, relocsEnd, 240 c->getInputSectionOffset(), relocLess); 241 relocsNext = std::lower_bound( 242 relocsStart, relocsEnd, c->getInputSectionOffset() + c->getInputSize(), 243 relocLess); 244 c->setRelocations(ArrayRef<WasmRelocation>(relocsStart, relocsNext)); 245 } 246 } 247 248 void ObjFile::parse(bool ignoreComdats) { 249 // Parse a memory buffer as a wasm file. 250 LLVM_DEBUG(dbgs() << "Parsing object: " << toString(this) << "\n"); 251 std::unique_ptr<Binary> bin = CHECK(createBinary(mb), toString(this)); 252 253 auto *obj = dyn_cast<WasmObjectFile>(bin.get()); 254 if (!obj) 255 fatal(toString(this) + ": not a wasm file"); 256 if (!obj->isRelocatableObject()) 257 fatal(toString(this) + ": not a relocatable wasm file"); 258 259 bin.release(); 260 wasmObj.reset(obj); 261 262 // Build up a map of function indices to table indices for use when 263 // verifying the existing table index relocations 264 uint32_t totalFunctions = 265 wasmObj->getNumImportedFunctions() + wasmObj->functions().size(); 266 tableEntries.resize(totalFunctions); 267 for (const WasmElemSegment &seg : wasmObj->elements()) { 268 if (seg.Offset.Opcode != WASM_OPCODE_I32_CONST) 269 fatal(toString(this) + ": invalid table elements"); 270 uint32_t offset = seg.Offset.Value.Int32; 271 for (uint32_t index = 0; index < seg.Functions.size(); index++) { 272 273 uint32_t functionIndex = seg.Functions[index]; 274 tableEntries[functionIndex] = offset + index; 275 } 276 } 277 278 uint32_t sectionIndex = 0; 279 280 // Bool for each symbol, true if called directly. This allows us to implement 281 // a weaker form of signature checking where undefined functions that are not 282 // called directly (i.e. only address taken) don't have to match the defined 283 // function's signature. We cannot do this for directly called functions 284 // because those signatures are checked at validation times. 285 // See https://bugs.llvm.org/show_bug.cgi?id=40412 286 std::vector<bool> isCalledDirectly(wasmObj->getNumberOfSymbols(), false); 287 for (const SectionRef &sec : wasmObj->sections()) { 288 const WasmSection §ion = wasmObj->getWasmSection(sec); 289 // Wasm objects can have at most one code and one data section. 290 if (section.Type == WASM_SEC_CODE) { 291 assert(!codeSection); 292 codeSection = §ion; 293 } else if (section.Type == WASM_SEC_DATA) { 294 assert(!dataSection); 295 dataSection = §ion; 296 } else if (section.Type == WASM_SEC_CUSTOM) { 297 customSections.emplace_back(make<InputSection>(section, this)); 298 customSections.back()->setRelocations(section.Relocations); 299 customSectionsByIndex[sectionIndex] = customSections.back(); 300 } 301 sectionIndex++; 302 // Scans relocations to dermine determine if a function symbol is called 303 // directly 304 for (const WasmRelocation &reloc : section.Relocations) 305 if (reloc.Type == R_WASM_FUNCTION_INDEX_LEB) 306 isCalledDirectly[reloc.Index] = true; 307 } 308 309 typeMap.resize(getWasmObj()->types().size()); 310 typeIsUsed.resize(getWasmObj()->types().size(), false); 311 312 ArrayRef<StringRef> comdats = wasmObj->linkingData().Comdats; 313 for (StringRef comdat : comdats) { 314 bool isNew = ignoreComdats || symtab->addComdat(comdat); 315 keptComdats.push_back(isNew); 316 } 317 318 // Populate `Segments`. 319 for (const WasmSegment &s : wasmObj->dataSegments()) { 320 auto* seg = make<InputSegment>(s, this); 321 seg->discarded = isExcludedByComdat(seg); 322 segments.emplace_back(seg); 323 } 324 setRelocs(segments, dataSection); 325 326 // Populate `Functions`. 327 ArrayRef<WasmFunction> funcs = wasmObj->functions(); 328 ArrayRef<uint32_t> funcTypes = wasmObj->functionTypes(); 329 ArrayRef<WasmSignature> types = wasmObj->types(); 330 functions.reserve(funcs.size()); 331 332 for (size_t i = 0, e = funcs.size(); i != e; ++i) { 333 auto* func = make<InputFunction>(types[funcTypes[i]], &funcs[i], this); 334 func->discarded = isExcludedByComdat(func); 335 functions.emplace_back(func); 336 } 337 setRelocs(functions, codeSection); 338 339 // Populate `Globals`. 340 for (const WasmGlobal &g : wasmObj->globals()) 341 globals.emplace_back(make<InputGlobal>(g, this)); 342 343 // Populate `Events`. 344 for (const WasmEvent &e : wasmObj->events()) 345 events.emplace_back(make<InputEvent>(types[e.Type.SigIndex], e, this)); 346 347 // Populate `Symbols` based on the symbols in the object. 348 symbols.reserve(wasmObj->getNumberOfSymbols()); 349 for (const SymbolRef &sym : wasmObj->symbols()) { 350 const WasmSymbol &wasmSym = wasmObj->getWasmSymbol(sym.getRawDataRefImpl()); 351 if (wasmSym.isDefined()) { 352 // createDefined may fail if the symbol is comdat excluded in which case 353 // we fall back to creating an undefined symbol 354 if (Symbol *d = createDefined(wasmSym)) { 355 symbols.push_back(d); 356 continue; 357 } 358 } 359 size_t idx = symbols.size(); 360 symbols.push_back(createUndefined(wasmSym, isCalledDirectly[idx])); 361 } 362 } 363 364 bool ObjFile::isExcludedByComdat(InputChunk *chunk) const { 365 uint32_t c = chunk->getComdat(); 366 if (c == UINT32_MAX) 367 return false; 368 return !keptComdats[c]; 369 } 370 371 FunctionSymbol *ObjFile::getFunctionSymbol(uint32_t index) const { 372 return cast<FunctionSymbol>(symbols[index]); 373 } 374 375 GlobalSymbol *ObjFile::getGlobalSymbol(uint32_t index) const { 376 return cast<GlobalSymbol>(symbols[index]); 377 } 378 379 EventSymbol *ObjFile::getEventSymbol(uint32_t index) const { 380 return cast<EventSymbol>(symbols[index]); 381 } 382 383 SectionSymbol *ObjFile::getSectionSymbol(uint32_t index) const { 384 return cast<SectionSymbol>(symbols[index]); 385 } 386 387 DataSymbol *ObjFile::getDataSymbol(uint32_t index) const { 388 return cast<DataSymbol>(symbols[index]); 389 } 390 391 Symbol *ObjFile::createDefined(const WasmSymbol &sym) { 392 StringRef name = sym.Info.Name; 393 uint32_t flags = sym.Info.Flags; 394 395 switch (sym.Info.Kind) { 396 case WASM_SYMBOL_TYPE_FUNCTION: { 397 InputFunction *func = 398 functions[sym.Info.ElementIndex - wasmObj->getNumImportedFunctions()]; 399 if (sym.isBindingLocal()) 400 return make<DefinedFunction>(name, flags, this, func); 401 if (func->discarded) 402 return nullptr; 403 return symtab->addDefinedFunction(name, flags, this, func); 404 } 405 case WASM_SYMBOL_TYPE_DATA: { 406 InputSegment *seg = segments[sym.Info.DataRef.Segment]; 407 uint32_t offset = sym.Info.DataRef.Offset; 408 uint32_t size = sym.Info.DataRef.Size; 409 if (sym.isBindingLocal()) 410 return make<DefinedData>(name, flags, this, seg, offset, size); 411 if (seg->discarded) 412 return nullptr; 413 return symtab->addDefinedData(name, flags, this, seg, offset, size); 414 } 415 case WASM_SYMBOL_TYPE_GLOBAL: { 416 InputGlobal *global = 417 globals[sym.Info.ElementIndex - wasmObj->getNumImportedGlobals()]; 418 if (sym.isBindingLocal()) 419 return make<DefinedGlobal>(name, flags, this, global); 420 return symtab->addDefinedGlobal(name, flags, this, global); 421 } 422 case WASM_SYMBOL_TYPE_SECTION: { 423 InputSection *section = customSectionsByIndex[sym.Info.ElementIndex]; 424 assert(sym.isBindingLocal()); 425 return make<SectionSymbol>(flags, section, this); 426 } 427 case WASM_SYMBOL_TYPE_EVENT: { 428 InputEvent *event = 429 events[sym.Info.ElementIndex - wasmObj->getNumImportedEvents()]; 430 if (sym.isBindingLocal()) 431 return make<DefinedEvent>(name, flags, this, event); 432 return symtab->addDefinedEvent(name, flags, this, event); 433 } 434 } 435 llvm_unreachable("unknown symbol kind"); 436 } 437 438 Symbol *ObjFile::createUndefined(const WasmSymbol &sym, bool isCalledDirectly) { 439 StringRef name = sym.Info.Name; 440 uint32_t flags = sym.Info.Flags | WASM_SYMBOL_UNDEFINED; 441 442 switch (sym.Info.Kind) { 443 case WASM_SYMBOL_TYPE_FUNCTION: 444 if (sym.isBindingLocal()) 445 return make<UndefinedFunction>(name, sym.Info.ImportName, 446 sym.Info.ImportModule, flags, this, 447 sym.Signature, isCalledDirectly); 448 return symtab->addUndefinedFunction(name, sym.Info.ImportName, 449 sym.Info.ImportModule, flags, this, 450 sym.Signature, isCalledDirectly); 451 case WASM_SYMBOL_TYPE_DATA: 452 if (sym.isBindingLocal()) 453 return make<UndefinedData>(name, flags, this); 454 return symtab->addUndefinedData(name, flags, this); 455 case WASM_SYMBOL_TYPE_GLOBAL: 456 if (sym.isBindingLocal()) 457 return make<UndefinedGlobal>(name, sym.Info.ImportName, 458 sym.Info.ImportModule, flags, this, 459 sym.GlobalType); 460 return symtab->addUndefinedGlobal(name, sym.Info.ImportName, 461 sym.Info.ImportModule, flags, this, 462 sym.GlobalType); 463 case WASM_SYMBOL_TYPE_SECTION: 464 llvm_unreachable("section symbols cannot be undefined"); 465 } 466 llvm_unreachable("unknown symbol kind"); 467 } 468 469 void ArchiveFile::parse() { 470 // Parse a MemoryBufferRef as an archive file. 471 LLVM_DEBUG(dbgs() << "Parsing library: " << toString(this) << "\n"); 472 file = CHECK(Archive::create(mb), toString(this)); 473 474 // Read the symbol table to construct Lazy symbols. 475 int count = 0; 476 for (const Archive::Symbol &sym : file->symbols()) { 477 symtab->addLazy(this, &sym); 478 ++count; 479 } 480 LLVM_DEBUG(dbgs() << "Read " << count << " symbols\n"); 481 } 482 483 void ArchiveFile::addMember(const Archive::Symbol *sym) { 484 const Archive::Child &c = 485 CHECK(sym->getMember(), 486 "could not get the member for symbol " + sym->getName()); 487 488 // Don't try to load the same member twice (this can happen when members 489 // mutually reference each other). 490 if (!seen.insert(c.getChildOffset()).second) 491 return; 492 493 LLVM_DEBUG(dbgs() << "loading lazy: " << sym->getName() << "\n"); 494 LLVM_DEBUG(dbgs() << "from archive: " << toString(this) << "\n"); 495 496 MemoryBufferRef mb = 497 CHECK(c.getMemoryBufferRef(), 498 "could not get the buffer for the member defining symbol " + 499 sym->getName()); 500 501 InputFile *obj = createObjectFile(mb, getName()); 502 symtab->addFile(obj); 503 } 504 505 static uint8_t mapVisibility(GlobalValue::VisibilityTypes gvVisibility) { 506 switch (gvVisibility) { 507 case GlobalValue::DefaultVisibility: 508 return WASM_SYMBOL_VISIBILITY_DEFAULT; 509 case GlobalValue::HiddenVisibility: 510 case GlobalValue::ProtectedVisibility: 511 return WASM_SYMBOL_VISIBILITY_HIDDEN; 512 } 513 llvm_unreachable("unknown visibility"); 514 } 515 516 static Symbol *createBitcodeSymbol(const std::vector<bool> &keptComdats, 517 const lto::InputFile::Symbol &objSym, 518 BitcodeFile &f) { 519 StringRef name = saver.save(objSym.getName()); 520 521 uint32_t flags = objSym.isWeak() ? WASM_SYMBOL_BINDING_WEAK : 0; 522 flags |= mapVisibility(objSym.getVisibility()); 523 524 int c = objSym.getComdatIndex(); 525 bool excludedByComdat = c != -1 && !keptComdats[c]; 526 527 if (objSym.isUndefined() || excludedByComdat) { 528 flags |= WASM_SYMBOL_UNDEFINED; 529 if (objSym.isExecutable()) 530 return symtab->addUndefinedFunction(name, "", "", flags, &f, nullptr, 531 true); 532 return symtab->addUndefinedData(name, flags, &f); 533 } 534 535 if (objSym.isExecutable()) 536 return symtab->addDefinedFunction(name, flags, &f, nullptr); 537 return symtab->addDefinedData(name, flags, &f, nullptr, 0, 0); 538 } 539 540 void BitcodeFile::parse() { 541 obj = check(lto::InputFile::create(MemoryBufferRef( 542 mb.getBuffer(), saver.save(archiveName + mb.getBufferIdentifier())))); 543 Triple t(obj->getTargetTriple()); 544 if (t.getArch() != Triple::wasm32) { 545 error(toString(mb.getBufferIdentifier()) + ": machine type must be wasm32"); 546 return; 547 } 548 std::vector<bool> keptComdats; 549 for (StringRef s : obj->getComdatTable()) 550 keptComdats.push_back(symtab->addComdat(s)); 551 552 for (const lto::InputFile::Symbol &objSym : obj->symbols()) 553 symbols.push_back(createBitcodeSymbol(keptComdats, objSym, *this)); 554 } 555 556 } // namespace wasm 557 } // namespace lld 558