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