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