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 "InputTable.h" 15 #include "OutputSegment.h" 16 #include "SymbolTable.h" 17 #include "lld/Common/ErrorHandler.h" 18 #include "lld/Common/Memory.h" 19 #include "lld/Common/Reproduce.h" 20 #include "llvm/Object/Binary.h" 21 #include "llvm/Object/Wasm.h" 22 #include "llvm/Support/TarWriter.h" 23 #include "llvm/Support/raw_ostream.h" 24 25 #define DEBUG_TYPE "lld" 26 27 using namespace llvm; 28 using namespace llvm::object; 29 using namespace llvm::wasm; 30 31 namespace lld { 32 33 // Returns a string in the format of "foo.o" or "foo.a(bar.o)". 34 std::string toString(const wasm::InputFile *file) { 35 if (!file) 36 return "<internal>"; 37 38 if (file->archiveName.empty()) 39 return std::string(file->getName()); 40 41 return (file->archiveName + "(" + file->getName() + ")").str(); 42 } 43 44 namespace wasm { 45 46 void InputFile::checkArch(Triple::ArchType arch) const { 47 bool is64 = arch == Triple::wasm64; 48 if (is64 && !config->is64.hasValue()) { 49 fatal(toString(this) + 50 ": must specify -mwasm64 to process wasm64 object files"); 51 } else if (config->is64.getValueOr(false) != is64) { 52 fatal(toString(this) + 53 ": wasm32 object file can't be linked in wasm64 mode"); 54 } 55 } 56 57 std::unique_ptr<llvm::TarWriter> tar; 58 59 Optional<MemoryBufferRef> readFile(StringRef path) { 60 log("Loading: " + path); 61 62 auto mbOrErr = MemoryBuffer::getFile(path); 63 if (auto ec = mbOrErr.getError()) { 64 error("cannot open " + path + ": " + ec.message()); 65 return None; 66 } 67 std::unique_ptr<MemoryBuffer> &mb = *mbOrErr; 68 MemoryBufferRef mbref = mb->getMemBufferRef(); 69 make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take MB ownership 70 71 if (tar) 72 tar->append(relativeToRoot(path), mbref.getBuffer()); 73 return mbref; 74 } 75 76 InputFile *createObjectFile(MemoryBufferRef mb, StringRef archiveName) { 77 file_magic magic = identify_magic(mb.getBuffer()); 78 if (magic == file_magic::wasm_object) { 79 std::unique_ptr<Binary> bin = 80 CHECK(createBinary(mb), mb.getBufferIdentifier()); 81 auto *obj = cast<WasmObjectFile>(bin.get()); 82 if (obj->isSharedObject()) 83 return make<SharedFile>(mb); 84 return make<ObjFile>(mb, archiveName); 85 } 86 87 if (magic == file_magic::bitcode) 88 return make<BitcodeFile>(mb, archiveName); 89 90 fatal("unknown file type: " + mb.getBufferIdentifier()); 91 } 92 93 void ObjFile::dumpInfo() const { 94 log("info for: " + toString(this) + 95 "\n Symbols : " + Twine(symbols.size()) + 96 "\n Function Imports : " + Twine(wasmObj->getNumImportedFunctions()) + 97 "\n Global Imports : " + Twine(wasmObj->getNumImportedGlobals()) + 98 "\n Event Imports : " + Twine(wasmObj->getNumImportedEvents()) + 99 "\n Table Imports : " + Twine(wasmObj->getNumImportedTables())); 100 } 101 102 // Relocations contain either symbol or type indices. This function takes a 103 // relocation and returns relocated index (i.e. translates from the input 104 // symbol/type space to the output symbol/type space). 105 uint32_t ObjFile::calcNewIndex(const WasmRelocation &reloc) const { 106 if (reloc.Type == R_WASM_TYPE_INDEX_LEB) { 107 assert(typeIsUsed[reloc.Index]); 108 return typeMap[reloc.Index]; 109 } 110 const Symbol *sym = symbols[reloc.Index]; 111 if (auto *ss = dyn_cast<SectionSymbol>(sym)) 112 sym = ss->getOutputSectionSymbol(); 113 return sym->getOutputSymbolIndex(); 114 } 115 116 // Relocations can contain addend for combined sections. This function takes a 117 // relocation and returns updated addend by offset in the output section. 118 uint64_t ObjFile::calcNewAddend(const WasmRelocation &reloc) const { 119 switch (reloc.Type) { 120 case R_WASM_MEMORY_ADDR_LEB: 121 case R_WASM_MEMORY_ADDR_LEB64: 122 case R_WASM_MEMORY_ADDR_SLEB64: 123 case R_WASM_MEMORY_ADDR_SLEB: 124 case R_WASM_MEMORY_ADDR_REL_SLEB: 125 case R_WASM_MEMORY_ADDR_REL_SLEB64: 126 case R_WASM_MEMORY_ADDR_I32: 127 case R_WASM_MEMORY_ADDR_I64: 128 case R_WASM_MEMORY_ADDR_TLS_SLEB: 129 case R_WASM_FUNCTION_OFFSET_I32: 130 case R_WASM_FUNCTION_OFFSET_I64: 131 return reloc.Addend; 132 case R_WASM_SECTION_OFFSET_I32: 133 return getSectionSymbol(reloc.Index)->section->outputOffset + reloc.Addend; 134 default: 135 llvm_unreachable("unexpected relocation type"); 136 } 137 } 138 139 // Calculate the value we expect to find at the relocation location. 140 // This is used as a sanity check before applying a relocation to a given 141 // location. It is useful for catching bugs in the compiler and linker. 142 uint64_t ObjFile::calcExpectedValue(const WasmRelocation &reloc) const { 143 switch (reloc.Type) { 144 case R_WASM_TABLE_INDEX_I32: 145 case R_WASM_TABLE_INDEX_I64: 146 case R_WASM_TABLE_INDEX_SLEB: 147 case R_WASM_TABLE_INDEX_SLEB64: { 148 const WasmSymbol &sym = wasmObj->syms()[reloc.Index]; 149 return tableEntries[sym.Info.ElementIndex]; 150 } 151 case R_WASM_TABLE_INDEX_REL_SLEB: { 152 const WasmSymbol &sym = wasmObj->syms()[reloc.Index]; 153 return tableEntriesRel[sym.Info.ElementIndex]; 154 } 155 case R_WASM_MEMORY_ADDR_LEB: 156 case R_WASM_MEMORY_ADDR_LEB64: 157 case R_WASM_MEMORY_ADDR_SLEB: 158 case R_WASM_MEMORY_ADDR_SLEB64: 159 case R_WASM_MEMORY_ADDR_REL_SLEB: 160 case R_WASM_MEMORY_ADDR_REL_SLEB64: 161 case R_WASM_MEMORY_ADDR_I32: 162 case R_WASM_MEMORY_ADDR_I64: 163 case R_WASM_MEMORY_ADDR_TLS_SLEB: { 164 const WasmSymbol &sym = wasmObj->syms()[reloc.Index]; 165 if (sym.isUndefined()) 166 return 0; 167 const WasmSegment &segment = 168 wasmObj->dataSegments()[sym.Info.DataRef.Segment]; 169 if (segment.Data.Offset.Opcode == WASM_OPCODE_I32_CONST) 170 return segment.Data.Offset.Value.Int32 + sym.Info.DataRef.Offset + 171 reloc.Addend; 172 else if (segment.Data.Offset.Opcode == WASM_OPCODE_I64_CONST) 173 return segment.Data.Offset.Value.Int64 + sym.Info.DataRef.Offset + 174 reloc.Addend; 175 else 176 llvm_unreachable("unknown init expr opcode"); 177 } 178 case R_WASM_FUNCTION_OFFSET_I32: 179 case R_WASM_FUNCTION_OFFSET_I64: { 180 const WasmSymbol &sym = wasmObj->syms()[reloc.Index]; 181 InputFunction *f = 182 functions[sym.Info.ElementIndex - wasmObj->getNumImportedFunctions()]; 183 return f->getFunctionInputOffset() + f->getFunctionCodeOffset() + 184 reloc.Addend; 185 } 186 case R_WASM_SECTION_OFFSET_I32: 187 return reloc.Addend; 188 case R_WASM_TYPE_INDEX_LEB: 189 return reloc.Index; 190 case R_WASM_FUNCTION_INDEX_LEB: 191 case R_WASM_GLOBAL_INDEX_LEB: 192 case R_WASM_GLOBAL_INDEX_I32: 193 case R_WASM_EVENT_INDEX_LEB: 194 case R_WASM_TABLE_NUMBER_LEB: { 195 const WasmSymbol &sym = wasmObj->syms()[reloc.Index]; 196 return sym.Info.ElementIndex; 197 } 198 default: 199 llvm_unreachable("unknown relocation type"); 200 } 201 } 202 203 // Translate from the relocation's index into the final linked output value. 204 uint64_t ObjFile::calcNewValue(const WasmRelocation &reloc, uint64_t tombstone) const { 205 const Symbol* sym = nullptr; 206 if (reloc.Type != R_WASM_TYPE_INDEX_LEB) { 207 sym = symbols[reloc.Index]; 208 209 // We can end up with relocations against non-live symbols. For example 210 // in debug sections. We return a tombstone value in debug symbol sections 211 // so this will not produce a valid range conflicting with ranges of actual 212 // code. In other sections we return reloc.Addend. 213 214 if ((isa<FunctionSymbol>(sym) || isa<DataSymbol>(sym)) && !sym->isLive()) 215 return tombstone ? tombstone : reloc.Addend; 216 } 217 218 switch (reloc.Type) { 219 case R_WASM_TABLE_INDEX_I32: 220 case R_WASM_TABLE_INDEX_I64: 221 case R_WASM_TABLE_INDEX_SLEB: 222 case R_WASM_TABLE_INDEX_SLEB64: 223 case R_WASM_TABLE_INDEX_REL_SLEB: { 224 if (!getFunctionSymbol(reloc.Index)->hasTableIndex()) 225 return 0; 226 uint32_t index = getFunctionSymbol(reloc.Index)->getTableIndex(); 227 if (reloc.Type == R_WASM_TABLE_INDEX_REL_SLEB) 228 index -= config->tableBase; 229 return index; 230 231 } 232 case R_WASM_MEMORY_ADDR_LEB: 233 case R_WASM_MEMORY_ADDR_LEB64: 234 case R_WASM_MEMORY_ADDR_SLEB: 235 case R_WASM_MEMORY_ADDR_SLEB64: 236 case R_WASM_MEMORY_ADDR_REL_SLEB: 237 case R_WASM_MEMORY_ADDR_REL_SLEB64: 238 case R_WASM_MEMORY_ADDR_I32: 239 case R_WASM_MEMORY_ADDR_I64: { 240 if (isa<UndefinedData>(sym) || sym->isUndefWeak()) 241 return 0; 242 auto D = cast<DefinedData>(sym); 243 // Treat non-TLS relocation against symbols that live in the TLS segment 244 // like TLS relocations. This beaviour exists to support older object 245 // files created before we introduced TLS relocations. 246 // TODO(sbc): Remove this legacy behaviour one day. This will break 247 // backward compat with old object files built with `-fPIC`. 248 if (D->segment && D->segment->outputSeg->name == ".tdata") 249 return D->getOutputSegmentOffset() + reloc.Addend; 250 return D->getVirtualAddress() + reloc.Addend; 251 } 252 case R_WASM_MEMORY_ADDR_TLS_SLEB: 253 if (isa<UndefinedData>(sym) || sym->isUndefWeak()) 254 return 0; 255 // TLS relocations are relative to the start of the TLS output segment 256 return cast<DefinedData>(sym)->getOutputSegmentOffset() + reloc.Addend; 257 case R_WASM_TYPE_INDEX_LEB: 258 return typeMap[reloc.Index]; 259 case R_WASM_FUNCTION_INDEX_LEB: 260 return getFunctionSymbol(reloc.Index)->getFunctionIndex(); 261 case R_WASM_GLOBAL_INDEX_LEB: 262 case R_WASM_GLOBAL_INDEX_I32: 263 if (auto gs = dyn_cast<GlobalSymbol>(sym)) 264 return gs->getGlobalIndex(); 265 return sym->getGOTIndex(); 266 case R_WASM_EVENT_INDEX_LEB: 267 return getEventSymbol(reloc.Index)->getEventIndex(); 268 case R_WASM_FUNCTION_OFFSET_I32: 269 case R_WASM_FUNCTION_OFFSET_I64: { 270 auto *f = cast<DefinedFunction>(sym); 271 return f->function->outputOffset + 272 (f->function->getFunctionCodeOffset() + reloc.Addend); 273 } 274 case R_WASM_SECTION_OFFSET_I32: 275 return getSectionSymbol(reloc.Index)->section->outputOffset + reloc.Addend; 276 case R_WASM_TABLE_NUMBER_LEB: 277 return getTableSymbol(reloc.Index)->getTableNumber(); 278 default: 279 llvm_unreachable("unknown relocation type"); 280 } 281 } 282 283 template <class T> 284 static void setRelocs(const std::vector<T *> &chunks, 285 const WasmSection *section) { 286 if (!section) 287 return; 288 289 ArrayRef<WasmRelocation> relocs = section->Relocations; 290 assert(llvm::is_sorted( 291 relocs, [](const WasmRelocation &r1, const WasmRelocation &r2) { 292 return r1.Offset < r2.Offset; 293 })); 294 assert(llvm::is_sorted(chunks, [](InputChunk *c1, InputChunk *c2) { 295 return c1->getInputSectionOffset() < c2->getInputSectionOffset(); 296 })); 297 298 auto relocsNext = relocs.begin(); 299 auto relocsEnd = relocs.end(); 300 auto relocLess = [](const WasmRelocation &r, uint32_t val) { 301 return r.Offset < val; 302 }; 303 for (InputChunk *c : chunks) { 304 auto relocsStart = std::lower_bound(relocsNext, relocsEnd, 305 c->getInputSectionOffset(), relocLess); 306 relocsNext = std::lower_bound( 307 relocsStart, relocsEnd, c->getInputSectionOffset() + c->getInputSize(), 308 relocLess); 309 c->setRelocations(ArrayRef<WasmRelocation>(relocsStart, relocsNext)); 310 } 311 } 312 313 // Since LLVM 12, we expect that if an input file defines or uses a table, it 314 // declares the tables using symbols and records each use with a relocation. 315 // This way when the linker combines inputs, it can collate the tables used by 316 // the inputs, assigning them distinct table numbers, and renumber all the uses 317 // as appropriate. At the same time, the linker has special logic to build the 318 // indirect function table if it is needed. 319 // 320 // However, object files produced by LLVM 11 and earlier neither write table 321 // symbols nor record relocations, and yet still use tables via call_indirect, 322 // and via function pointer bitcasts. We can detect these object files, as they 323 // declare tables as imports or define them locally, but don't have table 324 // symbols. synthesizeTableSymbols serves as a shim when loading these older 325 // input files, defining the missing symbols to allow the indirect function 326 // table to be built. 327 // 328 // Table uses in these older files won't be relocated, as they have no 329 // relocations. In practice this isn't a problem, as these object files 330 // typically just declare a single table named __indirect_function_table and 331 // having table number 0, so relocation would be idempotent anyway. 332 void ObjFile::synthesizeTableSymbols() { 333 uint32_t tableNumber = 0; 334 const WasmGlobalType *globalType = nullptr; 335 const WasmEventType *eventType = nullptr; 336 const WasmSignature *signature = nullptr; 337 if (wasmObj->getNumImportedTables()) { 338 for (const auto &import : wasmObj->imports()) { 339 if (import.Kind == WASM_EXTERNAL_TABLE) { 340 auto *info = make<WasmSymbolInfo>(); 341 info->Name = import.Field; 342 info->Kind = WASM_SYMBOL_TYPE_TABLE; 343 info->ImportModule = import.Module; 344 info->ImportName = import.Field; 345 info->Flags = WASM_SYMBOL_UNDEFINED; 346 info->Flags |= WASM_SYMBOL_NO_STRIP; 347 info->ElementIndex = tableNumber++; 348 LLVM_DEBUG(dbgs() << "Synthesizing symbol for table import: " 349 << info->Name << "\n"); 350 auto *wasmSym = make<WasmSymbol>(*info, globalType, &import.Table, 351 eventType, signature); 352 symbols.push_back(createUndefined(*wasmSym, false)); 353 // Because there are no TABLE_NUMBER relocs in this case, we can't 354 // compute accurate liveness info; instead, just mark the symbol as 355 // always live. 356 symbols.back()->markLive(); 357 } 358 } 359 } 360 for (const auto &table : tables) { 361 auto *info = make<llvm::wasm::WasmSymbolInfo>(); 362 // Empty name. 363 info->Kind = WASM_SYMBOL_TYPE_TABLE; 364 info->Flags = WASM_SYMBOL_BINDING_LOCAL; 365 info->Flags |= WASM_SYMBOL_VISIBILITY_HIDDEN; 366 info->Flags |= WASM_SYMBOL_NO_STRIP; 367 info->ElementIndex = tableNumber++; 368 LLVM_DEBUG(dbgs() << "Synthesizing symbol for table definition: " 369 << info->Name << "\n"); 370 auto *wasmSym = make<WasmSymbol>(*info, globalType, &table->getType(), 371 eventType, signature); 372 symbols.push_back(createDefined(*wasmSym)); 373 // Mark live, for the same reasons as for imported tables. 374 symbols.back()->markLive(); 375 } 376 } 377 378 void ObjFile::parse(bool ignoreComdats) { 379 // Parse a memory buffer as a wasm file. 380 LLVM_DEBUG(dbgs() << "Parsing object: " << toString(this) << "\n"); 381 std::unique_ptr<Binary> bin = CHECK(createBinary(mb), toString(this)); 382 383 auto *obj = dyn_cast<WasmObjectFile>(bin.get()); 384 if (!obj) 385 fatal(toString(this) + ": not a wasm file"); 386 if (!obj->isRelocatableObject()) 387 fatal(toString(this) + ": not a relocatable wasm file"); 388 389 bin.release(); 390 wasmObj.reset(obj); 391 392 checkArch(obj->getArch()); 393 394 // Build up a map of function indices to table indices for use when 395 // verifying the existing table index relocations 396 uint32_t totalFunctions = 397 wasmObj->getNumImportedFunctions() + wasmObj->functions().size(); 398 tableEntriesRel.resize(totalFunctions); 399 tableEntries.resize(totalFunctions); 400 for (const WasmElemSegment &seg : wasmObj->elements()) { 401 int64_t offset; 402 if (seg.Offset.Opcode == WASM_OPCODE_I32_CONST) 403 offset = seg.Offset.Value.Int32; 404 else if (seg.Offset.Opcode == WASM_OPCODE_I64_CONST) 405 offset = seg.Offset.Value.Int64; 406 else 407 fatal(toString(this) + ": invalid table elements"); 408 for (size_t index = 0; index < seg.Functions.size(); index++) { 409 auto functionIndex = seg.Functions[index]; 410 tableEntriesRel[functionIndex] = index; 411 tableEntries[functionIndex] = offset + index; 412 } 413 } 414 415 ArrayRef<StringRef> comdats = wasmObj->linkingData().Comdats; 416 for (StringRef comdat : comdats) { 417 bool isNew = ignoreComdats || symtab->addComdat(comdat); 418 keptComdats.push_back(isNew); 419 } 420 421 uint32_t sectionIndex = 0; 422 423 // Bool for each symbol, true if called directly. This allows us to implement 424 // a weaker form of signature checking where undefined functions that are not 425 // called directly (i.e. only address taken) don't have to match the defined 426 // function's signature. We cannot do this for directly called functions 427 // because those signatures are checked at validation times. 428 // See https://bugs.llvm.org/show_bug.cgi?id=40412 429 std::vector<bool> isCalledDirectly(wasmObj->getNumberOfSymbols(), false); 430 for (const SectionRef &sec : wasmObj->sections()) { 431 const WasmSection §ion = wasmObj->getWasmSection(sec); 432 // Wasm objects can have at most one code and one data section. 433 if (section.Type == WASM_SEC_CODE) { 434 assert(!codeSection); 435 codeSection = §ion; 436 } else if (section.Type == WASM_SEC_DATA) { 437 assert(!dataSection); 438 dataSection = §ion; 439 } else if (section.Type == WASM_SEC_CUSTOM) { 440 auto *customSec = make<InputSection>(section, this); 441 customSec->discarded = isExcludedByComdat(customSec); 442 customSections.emplace_back(customSec); 443 customSections.back()->setRelocations(section.Relocations); 444 customSectionsByIndex[sectionIndex] = customSections.back(); 445 } 446 sectionIndex++; 447 // Scans relocations to determine if a function symbol is called directly. 448 for (const WasmRelocation &reloc : section.Relocations) 449 if (reloc.Type == R_WASM_FUNCTION_INDEX_LEB) 450 isCalledDirectly[reloc.Index] = true; 451 } 452 453 typeMap.resize(getWasmObj()->types().size()); 454 typeIsUsed.resize(getWasmObj()->types().size(), false); 455 456 457 // Populate `Segments`. 458 for (const WasmSegment &s : wasmObj->dataSegments()) { 459 auto* seg = make<InputSegment>(s, this); 460 seg->discarded = isExcludedByComdat(seg); 461 segments.emplace_back(seg); 462 } 463 setRelocs(segments, dataSection); 464 465 // Populate `Functions`. 466 ArrayRef<WasmFunction> funcs = wasmObj->functions(); 467 ArrayRef<uint32_t> funcTypes = wasmObj->functionTypes(); 468 ArrayRef<WasmSignature> types = wasmObj->types(); 469 functions.reserve(funcs.size()); 470 471 for (size_t i = 0, e = funcs.size(); i != e; ++i) { 472 auto* func = make<InputFunction>(types[funcTypes[i]], &funcs[i], this); 473 func->discarded = isExcludedByComdat(func); 474 functions.emplace_back(func); 475 } 476 setRelocs(functions, codeSection); 477 478 // Populate `Tables`. 479 for (const WasmTable &t : wasmObj->tables()) 480 tables.emplace_back(make<InputTable>(t, this)); 481 482 // Populate `Globals`. 483 for (const WasmGlobal &g : wasmObj->globals()) 484 globals.emplace_back(make<InputGlobal>(g, this)); 485 486 // Populate `Events`. 487 for (const WasmEvent &e : wasmObj->events()) 488 events.emplace_back(make<InputEvent>(types[e.Type.SigIndex], e, this)); 489 490 // Populate `Symbols` based on the symbols in the object. 491 symbols.reserve(wasmObj->getNumberOfSymbols()); 492 bool haveTableSymbol = false; 493 for (const SymbolRef &sym : wasmObj->symbols()) { 494 const WasmSymbol &wasmSym = wasmObj->getWasmSymbol(sym.getRawDataRefImpl()); 495 if (wasmSym.isTypeTable()) 496 haveTableSymbol = true; 497 if (wasmSym.isDefined()) { 498 // createDefined may fail if the symbol is comdat excluded in which case 499 // we fall back to creating an undefined symbol 500 if (Symbol *d = createDefined(wasmSym)) { 501 symbols.push_back(d); 502 continue; 503 } 504 } 505 size_t idx = symbols.size(); 506 symbols.push_back(createUndefined(wasmSym, isCalledDirectly[idx])); 507 } 508 509 // As a stopgap measure while implementing table support, if the object file 510 // has table definitions or imports but no table symbols, synthesize symbols 511 // for those tables. Mark as NO_STRIP to ensure they reach the output file, 512 // even if there are no TABLE_NUMBER relocs against them. 513 if (!haveTableSymbol) 514 synthesizeTableSymbols(); 515 } 516 517 bool ObjFile::isExcludedByComdat(InputChunk *chunk) const { 518 uint32_t c = chunk->getComdat(); 519 if (c == UINT32_MAX) 520 return false; 521 return !keptComdats[c]; 522 } 523 524 FunctionSymbol *ObjFile::getFunctionSymbol(uint32_t index) const { 525 return cast<FunctionSymbol>(symbols[index]); 526 } 527 528 GlobalSymbol *ObjFile::getGlobalSymbol(uint32_t index) const { 529 return cast<GlobalSymbol>(symbols[index]); 530 } 531 532 EventSymbol *ObjFile::getEventSymbol(uint32_t index) const { 533 return cast<EventSymbol>(symbols[index]); 534 } 535 536 TableSymbol *ObjFile::getTableSymbol(uint32_t index) const { 537 return cast<TableSymbol>(symbols[index]); 538 } 539 540 SectionSymbol *ObjFile::getSectionSymbol(uint32_t index) const { 541 return cast<SectionSymbol>(symbols[index]); 542 } 543 544 DataSymbol *ObjFile::getDataSymbol(uint32_t index) const { 545 return cast<DataSymbol>(symbols[index]); 546 } 547 548 Symbol *ObjFile::createDefined(const WasmSymbol &sym) { 549 StringRef name = sym.Info.Name; 550 uint32_t flags = sym.Info.Flags; 551 552 switch (sym.Info.Kind) { 553 case WASM_SYMBOL_TYPE_FUNCTION: { 554 InputFunction *func = 555 functions[sym.Info.ElementIndex - wasmObj->getNumImportedFunctions()]; 556 if (sym.isBindingLocal()) 557 return make<DefinedFunction>(name, flags, this, func); 558 if (func->discarded) 559 return nullptr; 560 return symtab->addDefinedFunction(name, flags, this, func); 561 } 562 case WASM_SYMBOL_TYPE_DATA: { 563 InputSegment *seg = segments[sym.Info.DataRef.Segment]; 564 auto offset = sym.Info.DataRef.Offset; 565 auto size = sym.Info.DataRef.Size; 566 if (sym.isBindingLocal()) 567 return make<DefinedData>(name, flags, this, seg, offset, size); 568 if (seg->discarded) 569 return nullptr; 570 return symtab->addDefinedData(name, flags, this, seg, offset, size); 571 } 572 case WASM_SYMBOL_TYPE_GLOBAL: { 573 InputGlobal *global = 574 globals[sym.Info.ElementIndex - wasmObj->getNumImportedGlobals()]; 575 if (sym.isBindingLocal()) 576 return make<DefinedGlobal>(name, flags, this, global); 577 return symtab->addDefinedGlobal(name, flags, this, global); 578 } 579 case WASM_SYMBOL_TYPE_SECTION: { 580 InputSection *section = customSectionsByIndex[sym.Info.ElementIndex]; 581 assert(sym.isBindingLocal()); 582 // Need to return null if discarded here? data and func only do that when 583 // binding is not local. 584 if (section->discarded) 585 return nullptr; 586 return make<SectionSymbol>(flags, section, this); 587 } 588 case WASM_SYMBOL_TYPE_EVENT: { 589 InputEvent *event = 590 events[sym.Info.ElementIndex - wasmObj->getNumImportedEvents()]; 591 if (sym.isBindingLocal()) 592 return make<DefinedEvent>(name, flags, this, event); 593 return symtab->addDefinedEvent(name, flags, this, event); 594 } 595 case WASM_SYMBOL_TYPE_TABLE: { 596 InputTable *table = 597 tables[sym.Info.ElementIndex - wasmObj->getNumImportedTables()]; 598 if (sym.isBindingLocal()) 599 return make<DefinedTable>(name, flags, this, table); 600 return symtab->addDefinedTable(name, flags, this, table); 601 } 602 } 603 llvm_unreachable("unknown symbol kind"); 604 } 605 606 Symbol *ObjFile::createUndefined(const WasmSymbol &sym, bool isCalledDirectly) { 607 StringRef name = sym.Info.Name; 608 uint32_t flags = sym.Info.Flags | WASM_SYMBOL_UNDEFINED; 609 610 switch (sym.Info.Kind) { 611 case WASM_SYMBOL_TYPE_FUNCTION: 612 if (sym.isBindingLocal()) 613 return make<UndefinedFunction>(name, sym.Info.ImportName, 614 sym.Info.ImportModule, flags, this, 615 sym.Signature, isCalledDirectly); 616 return symtab->addUndefinedFunction(name, sym.Info.ImportName, 617 sym.Info.ImportModule, flags, this, 618 sym.Signature, isCalledDirectly); 619 case WASM_SYMBOL_TYPE_DATA: 620 if (sym.isBindingLocal()) 621 return make<UndefinedData>(name, flags, this); 622 return symtab->addUndefinedData(name, flags, this); 623 case WASM_SYMBOL_TYPE_GLOBAL: 624 if (sym.isBindingLocal()) 625 return make<UndefinedGlobal>(name, sym.Info.ImportName, 626 sym.Info.ImportModule, flags, this, 627 sym.GlobalType); 628 return symtab->addUndefinedGlobal(name, sym.Info.ImportName, 629 sym.Info.ImportModule, flags, this, 630 sym.GlobalType); 631 case WASM_SYMBOL_TYPE_TABLE: 632 if (sym.isBindingLocal()) 633 return make<UndefinedTable>(name, sym.Info.ImportName, 634 sym.Info.ImportModule, flags, this, 635 sym.TableType); 636 return symtab->addUndefinedTable(name, sym.Info.ImportName, 637 sym.Info.ImportModule, flags, this, 638 sym.TableType); 639 case WASM_SYMBOL_TYPE_SECTION: 640 llvm_unreachable("section symbols cannot be undefined"); 641 } 642 llvm_unreachable("unknown symbol kind"); 643 } 644 645 void ArchiveFile::parse() { 646 // Parse a MemoryBufferRef as an archive file. 647 LLVM_DEBUG(dbgs() << "Parsing library: " << toString(this) << "\n"); 648 file = CHECK(Archive::create(mb), toString(this)); 649 650 // Read the symbol table to construct Lazy symbols. 651 int count = 0; 652 for (const Archive::Symbol &sym : file->symbols()) { 653 symtab->addLazy(this, &sym); 654 ++count; 655 } 656 LLVM_DEBUG(dbgs() << "Read " << count << " symbols\n"); 657 } 658 659 void ArchiveFile::addMember(const Archive::Symbol *sym) { 660 const Archive::Child &c = 661 CHECK(sym->getMember(), 662 "could not get the member for symbol " + sym->getName()); 663 664 // Don't try to load the same member twice (this can happen when members 665 // mutually reference each other). 666 if (!seen.insert(c.getChildOffset()).second) 667 return; 668 669 LLVM_DEBUG(dbgs() << "loading lazy: " << sym->getName() << "\n"); 670 LLVM_DEBUG(dbgs() << "from archive: " << toString(this) << "\n"); 671 672 MemoryBufferRef mb = 673 CHECK(c.getMemoryBufferRef(), 674 "could not get the buffer for the member defining symbol " + 675 sym->getName()); 676 677 InputFile *obj = createObjectFile(mb, getName()); 678 symtab->addFile(obj); 679 } 680 681 static uint8_t mapVisibility(GlobalValue::VisibilityTypes gvVisibility) { 682 switch (gvVisibility) { 683 case GlobalValue::DefaultVisibility: 684 return WASM_SYMBOL_VISIBILITY_DEFAULT; 685 case GlobalValue::HiddenVisibility: 686 case GlobalValue::ProtectedVisibility: 687 return WASM_SYMBOL_VISIBILITY_HIDDEN; 688 } 689 llvm_unreachable("unknown visibility"); 690 } 691 692 static Symbol *createBitcodeSymbol(const std::vector<bool> &keptComdats, 693 const lto::InputFile::Symbol &objSym, 694 BitcodeFile &f) { 695 StringRef name = saver.save(objSym.getName()); 696 697 uint32_t flags = objSym.isWeak() ? WASM_SYMBOL_BINDING_WEAK : 0; 698 flags |= mapVisibility(objSym.getVisibility()); 699 700 int c = objSym.getComdatIndex(); 701 bool excludedByComdat = c != -1 && !keptComdats[c]; 702 703 if (objSym.isUndefined() || excludedByComdat) { 704 flags |= WASM_SYMBOL_UNDEFINED; 705 if (objSym.isExecutable()) 706 return symtab->addUndefinedFunction(name, None, None, flags, &f, nullptr, 707 true); 708 return symtab->addUndefinedData(name, flags, &f); 709 } 710 711 if (objSym.isExecutable()) 712 return symtab->addDefinedFunction(name, flags, &f, nullptr); 713 return symtab->addDefinedData(name, flags, &f, nullptr, 0, 0); 714 } 715 716 bool BitcodeFile::doneLTO = false; 717 718 void BitcodeFile::parse() { 719 if (doneLTO) { 720 error(toString(this) + ": attempt to add bitcode file after LTO."); 721 return; 722 } 723 724 obj = check(lto::InputFile::create(MemoryBufferRef( 725 mb.getBuffer(), saver.save(archiveName + mb.getBufferIdentifier())))); 726 Triple t(obj->getTargetTriple()); 727 if (!t.isWasm()) { 728 error(toString(this) + ": machine type must be wasm32 or wasm64"); 729 return; 730 } 731 checkArch(t.getArch()); 732 std::vector<bool> keptComdats; 733 for (StringRef s : obj->getComdatTable()) 734 keptComdats.push_back(symtab->addComdat(s)); 735 736 for (const lto::InputFile::Symbol &objSym : obj->symbols()) 737 symbols.push_back(createBitcodeSymbol(keptComdats, objSym, *this)); 738 } 739 740 } // namespace wasm 741 } // namespace lld 742