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