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/CommonLinkerContext.h" 16 #include "lld/Common/Reproduce.h" 17 #include "llvm/Object/Binary.h" 18 #include "llvm/Object/Wasm.h" 19 #include "llvm/Support/Path.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 using namespace llvm::sys; 29 30 namespace lld { 31 32 // Returns a string in the format of "foo.o" or "foo.a(bar.o)". 33 std::string toString(const wasm::InputFile *file) { 34 if (!file) 35 return "<internal>"; 36 37 if (file->archiveName.empty()) 38 return std::string(file->getName()); 39 40 return (file->archiveName + "(" + file->getName() + ")").str(); 41 } 42 43 namespace wasm { 44 45 void InputFile::checkArch(Triple::ArchType arch) const { 46 bool is64 = arch == Triple::wasm64; 47 if (is64 && !config->is64.hasValue()) { 48 fatal(toString(this) + 49 ": must specify -mwasm64 to process wasm64 object files"); 50 } else if (config->is64.getValueOr(false) != is64) { 51 fatal(toString(this) + 52 ": wasm32 object file can't be linked in wasm64 mode"); 53 } 54 } 55 56 std::unique_ptr<llvm::TarWriter> tar; 57 58 Optional<MemoryBufferRef> readFile(StringRef path) { 59 log("Loading: " + path); 60 61 auto mbOrErr = MemoryBuffer::getFile(path); 62 if (auto ec = mbOrErr.getError()) { 63 error("cannot open " + path + ": " + ec.message()); 64 return None; 65 } 66 std::unique_ptr<MemoryBuffer> &mb = *mbOrErr; 67 MemoryBufferRef mbref = mb->getMemBufferRef(); 68 make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take MB ownership 69 70 if (tar) 71 tar->append(relativeToRoot(path), mbref.getBuffer()); 72 return mbref; 73 } 74 75 InputFile *createObjectFile(MemoryBufferRef mb, StringRef archiveName, 76 uint64_t offsetInArchive) { 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, offsetInArchive); 89 90 std::string name = mb.getBufferIdentifier().str(); 91 if (!archiveName.empty()) { 92 name = archiveName.str() + "(" + name + ")"; 93 } 94 95 fatal("unknown file type: " + name); 96 } 97 98 // Relocations contain either symbol or type indices. This function takes a 99 // relocation and returns relocated index (i.e. translates from the input 100 // symbol/type space to the output symbol/type space). 101 uint32_t ObjFile::calcNewIndex(const WasmRelocation &reloc) const { 102 if (reloc.Type == R_WASM_TYPE_INDEX_LEB) { 103 assert(typeIsUsed[reloc.Index]); 104 return typeMap[reloc.Index]; 105 } 106 const Symbol *sym = symbols[reloc.Index]; 107 if (auto *ss = dyn_cast<SectionSymbol>(sym)) 108 sym = ss->getOutputSectionSymbol(); 109 return sym->getOutputSymbolIndex(); 110 } 111 112 // Relocations can contain addend for combined sections. This function takes a 113 // relocation and returns updated addend by offset in the output section. 114 int64_t ObjFile::calcNewAddend(const WasmRelocation &reloc) const { 115 switch (reloc.Type) { 116 case R_WASM_MEMORY_ADDR_LEB: 117 case R_WASM_MEMORY_ADDR_LEB64: 118 case R_WASM_MEMORY_ADDR_SLEB64: 119 case R_WASM_MEMORY_ADDR_SLEB: 120 case R_WASM_MEMORY_ADDR_REL_SLEB: 121 case R_WASM_MEMORY_ADDR_REL_SLEB64: 122 case R_WASM_MEMORY_ADDR_I32: 123 case R_WASM_MEMORY_ADDR_I64: 124 case R_WASM_MEMORY_ADDR_TLS_SLEB: 125 case R_WASM_MEMORY_ADDR_TLS_SLEB64: 126 case R_WASM_FUNCTION_OFFSET_I32: 127 case R_WASM_FUNCTION_OFFSET_I64: 128 case R_WASM_MEMORY_ADDR_LOCREL_I32: 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 // Translate from the relocation's index into the final linked output value. 138 uint64_t ObjFile::calcNewValue(const WasmRelocation &reloc, uint64_t tombstone, 139 const InputChunk *chunk) const { 140 const Symbol* sym = nullptr; 141 if (reloc.Type != R_WASM_TYPE_INDEX_LEB) { 142 sym = symbols[reloc.Index]; 143 144 // We can end up with relocations against non-live symbols. For example 145 // in debug sections. We return a tombstone value in debug symbol sections 146 // so this will not produce a valid range conflicting with ranges of actual 147 // code. In other sections we return reloc.Addend. 148 149 if (!isa<SectionSymbol>(sym) && !sym->isLive()) 150 return tombstone ? tombstone : reloc.Addend; 151 } 152 153 switch (reloc.Type) { 154 case R_WASM_TABLE_INDEX_I32: 155 case R_WASM_TABLE_INDEX_I64: 156 case R_WASM_TABLE_INDEX_SLEB: 157 case R_WASM_TABLE_INDEX_SLEB64: 158 case R_WASM_TABLE_INDEX_REL_SLEB: 159 case R_WASM_TABLE_INDEX_REL_SLEB64: { 160 if (!getFunctionSymbol(reloc.Index)->hasTableIndex()) 161 return 0; 162 uint32_t index = getFunctionSymbol(reloc.Index)->getTableIndex(); 163 if (reloc.Type == R_WASM_TABLE_INDEX_REL_SLEB || 164 reloc.Type == R_WASM_TABLE_INDEX_REL_SLEB64) 165 index -= config->tableBase; 166 return index; 167 } 168 case R_WASM_MEMORY_ADDR_LEB: 169 case R_WASM_MEMORY_ADDR_LEB64: 170 case R_WASM_MEMORY_ADDR_SLEB: 171 case R_WASM_MEMORY_ADDR_SLEB64: 172 case R_WASM_MEMORY_ADDR_REL_SLEB: 173 case R_WASM_MEMORY_ADDR_REL_SLEB64: 174 case R_WASM_MEMORY_ADDR_I32: 175 case R_WASM_MEMORY_ADDR_I64: 176 case R_WASM_MEMORY_ADDR_TLS_SLEB: 177 case R_WASM_MEMORY_ADDR_TLS_SLEB64: 178 case R_WASM_MEMORY_ADDR_LOCREL_I32: { 179 if (isa<UndefinedData>(sym) || sym->isUndefWeak()) 180 return 0; 181 auto D = cast<DefinedData>(sym); 182 uint64_t value = D->getVA() + reloc.Addend; 183 if (reloc.Type == R_WASM_MEMORY_ADDR_LOCREL_I32) { 184 const auto *segment = cast<InputSegment>(chunk); 185 uint64_t p = segment->outputSeg->startVA + segment->outputSegmentOffset + 186 reloc.Offset - segment->getInputSectionOffset(); 187 value -= p; 188 } 189 return value; 190 } 191 case R_WASM_TYPE_INDEX_LEB: 192 return typeMap[reloc.Index]; 193 case R_WASM_FUNCTION_INDEX_LEB: 194 return getFunctionSymbol(reloc.Index)->getFunctionIndex(); 195 case R_WASM_GLOBAL_INDEX_LEB: 196 case R_WASM_GLOBAL_INDEX_I32: 197 if (auto gs = dyn_cast<GlobalSymbol>(sym)) 198 return gs->getGlobalIndex(); 199 return sym->getGOTIndex(); 200 case R_WASM_TAG_INDEX_LEB: 201 return getTagSymbol(reloc.Index)->getTagIndex(); 202 case R_WASM_FUNCTION_OFFSET_I32: 203 case R_WASM_FUNCTION_OFFSET_I64: { 204 if (isa<UndefinedFunction>(sym)) { 205 return tombstone ? tombstone : reloc.Addend; 206 } 207 auto *f = cast<DefinedFunction>(sym); 208 return f->function->getOffset(f->function->getFunctionCodeOffset() + 209 reloc.Addend); 210 } 211 case R_WASM_SECTION_OFFSET_I32: 212 return getSectionSymbol(reloc.Index)->section->getOffset(reloc.Addend); 213 case R_WASM_TABLE_NUMBER_LEB: 214 return getTableSymbol(reloc.Index)->getTableNumber(); 215 default: 216 llvm_unreachable("unknown relocation type"); 217 } 218 } 219 220 template <class T> 221 static void setRelocs(const std::vector<T *> &chunks, 222 const WasmSection *section) { 223 if (!section) 224 return; 225 226 ArrayRef<WasmRelocation> relocs = section->Relocations; 227 assert(llvm::is_sorted( 228 relocs, [](const WasmRelocation &r1, const WasmRelocation &r2) { 229 return r1.Offset < r2.Offset; 230 })); 231 assert(llvm::is_sorted(chunks, [](InputChunk *c1, InputChunk *c2) { 232 return c1->getInputSectionOffset() < c2->getInputSectionOffset(); 233 })); 234 235 auto relocsNext = relocs.begin(); 236 auto relocsEnd = relocs.end(); 237 auto relocLess = [](const WasmRelocation &r, uint32_t val) { 238 return r.Offset < val; 239 }; 240 for (InputChunk *c : chunks) { 241 auto relocsStart = std::lower_bound(relocsNext, relocsEnd, 242 c->getInputSectionOffset(), relocLess); 243 relocsNext = std::lower_bound( 244 relocsStart, relocsEnd, c->getInputSectionOffset() + c->getInputSize(), 245 relocLess); 246 c->setRelocations(ArrayRef<WasmRelocation>(relocsStart, relocsNext)); 247 } 248 } 249 250 // An object file can have two approaches to tables. With the reference-types 251 // feature enabled, input files that define or use tables declare the tables 252 // using symbols, and record each use with a relocation. This way when the 253 // linker combines inputs, it can collate the tables used by the inputs, 254 // assigning them distinct table numbers, and renumber all the uses as 255 // appropriate. At the same time, the linker has special logic to build the 256 // indirect function table if it is needed. 257 // 258 // However, MVP object files (those that target WebAssembly 1.0, the "minimum 259 // viable product" version of WebAssembly) neither write table symbols nor 260 // record relocations. These files can have at most one table, the indirect 261 // function table used by call_indirect and which is the address space for 262 // function pointers. If this table is present, it is always an import. If we 263 // have a file with a table import but no table symbols, it is an MVP object 264 // file. synthesizeMVPIndirectFunctionTableSymbolIfNeeded serves as a shim when 265 // loading these input files, defining the missing symbol to allow the indirect 266 // function table to be built. 267 // 268 // As indirect function table table usage in MVP objects cannot be relocated, 269 // the linker must ensure that this table gets assigned index zero. 270 void ObjFile::addLegacyIndirectFunctionTableIfNeeded( 271 uint32_t tableSymbolCount) { 272 uint32_t tableCount = wasmObj->getNumImportedTables() + tables.size(); 273 274 // If there are symbols for all tables, then all is good. 275 if (tableCount == tableSymbolCount) 276 return; 277 278 // It's possible for an input to define tables and also use the indirect 279 // function table, but forget to compile with -mattr=+reference-types. 280 // For these newer files, we require symbols for all tables, and 281 // relocations for all of their uses. 282 if (tableSymbolCount != 0) { 283 error(toString(this) + 284 ": expected one symbol table entry for each of the " + 285 Twine(tableCount) + " table(s) present, but got " + 286 Twine(tableSymbolCount) + " symbol(s) instead."); 287 return; 288 } 289 290 // An MVP object file can have up to one table import, for the indirect 291 // function table, but will have no table definitions. 292 if (tables.size()) { 293 error(toString(this) + 294 ": unexpected table definition(s) without corresponding " 295 "symbol-table entries."); 296 return; 297 } 298 299 // An MVP object file can have only one table import. 300 if (tableCount != 1) { 301 error(toString(this) + 302 ": multiple table imports, but no corresponding symbol-table " 303 "entries."); 304 return; 305 } 306 307 const WasmImport *tableImport = nullptr; 308 for (const auto &import : wasmObj->imports()) { 309 if (import.Kind == WASM_EXTERNAL_TABLE) { 310 assert(!tableImport); 311 tableImport = &import; 312 } 313 } 314 assert(tableImport); 315 316 // We can only synthesize a symtab entry for the indirect function table; if 317 // it has an unexpected name or type, assume that it's not actually the 318 // indirect function table. 319 if (tableImport->Field != functionTableName || 320 tableImport->Table.ElemType != uint8_t(ValType::FUNCREF)) { 321 error(toString(this) + ": table import " + Twine(tableImport->Field) + 322 " is missing a symbol table entry."); 323 return; 324 } 325 326 auto *info = make<WasmSymbolInfo>(); 327 info->Name = tableImport->Field; 328 info->Kind = WASM_SYMBOL_TYPE_TABLE; 329 info->ImportModule = tableImport->Module; 330 info->ImportName = tableImport->Field; 331 info->Flags = WASM_SYMBOL_UNDEFINED; 332 info->Flags |= WASM_SYMBOL_NO_STRIP; 333 info->ElementIndex = 0; 334 LLVM_DEBUG(dbgs() << "Synthesizing symbol for table import: " << info->Name 335 << "\n"); 336 const WasmGlobalType *globalType = nullptr; 337 const WasmSignature *signature = nullptr; 338 auto *wasmSym = 339 make<WasmSymbol>(*info, globalType, &tableImport->Table, signature); 340 Symbol *sym = createUndefined(*wasmSym, false); 341 // We're only sure it's a TableSymbol if the createUndefined succeeded. 342 if (errorCount()) 343 return; 344 symbols.push_back(sym); 345 // Because there are no TABLE_NUMBER relocs, we can't compute accurate 346 // liveness info; instead, just mark the symbol as always live. 347 sym->markLive(); 348 349 // We assume that this compilation unit has unrelocatable references to 350 // this table. 351 config->legacyFunctionTable = true; 352 } 353 354 static bool shouldMerge(const WasmSection &sec) { 355 if (config->optimize == 0) 356 return false; 357 // Sadly we don't have section attributes yet for custom sections, so we 358 // currently go by the name alone. 359 // TODO(sbc): Add ability for wasm sections to carry flags so we don't 360 // need to use names here. 361 // For now, keep in sync with uses of wasm::WASM_SEG_FLAG_STRINGS in 362 // MCObjectFileInfo::initWasmMCObjectFileInfo which creates these custom 363 // sections. 364 return sec.Name == ".debug_str" || sec.Name == ".debug_str.dwo" || 365 sec.Name == ".debug_line_str"; 366 } 367 368 static bool shouldMerge(const WasmSegment &seg) { 369 // As of now we only support merging strings, and only with single byte 370 // alignment (2^0). 371 if (!(seg.Data.LinkingFlags & WASM_SEG_FLAG_STRINGS) || 372 (seg.Data.Alignment != 0)) 373 return false; 374 375 // On a regular link we don't merge sections if -O0 (default is -O1). This 376 // sometimes makes the linker significantly faster, although the output will 377 // be bigger. 378 if (config->optimize == 0) 379 return false; 380 381 // A mergeable section with size 0 is useless because they don't have 382 // any data to merge. A mergeable string section with size 0 can be 383 // argued as invalid because it doesn't end with a null character. 384 // We'll avoid a mess by handling them as if they were non-mergeable. 385 if (seg.Data.Content.size() == 0) 386 return false; 387 388 return true; 389 } 390 391 void ObjFile::parse(bool ignoreComdats) { 392 // Parse a memory buffer as a wasm file. 393 LLVM_DEBUG(dbgs() << "Parsing object: " << toString(this) << "\n"); 394 std::unique_ptr<Binary> bin = CHECK(createBinary(mb), toString(this)); 395 396 auto *obj = dyn_cast<WasmObjectFile>(bin.get()); 397 if (!obj) 398 fatal(toString(this) + ": not a wasm file"); 399 if (!obj->isRelocatableObject()) 400 fatal(toString(this) + ": not a relocatable wasm file"); 401 402 bin.release(); 403 wasmObj.reset(obj); 404 405 checkArch(obj->getArch()); 406 407 // Build up a map of function indices to table indices for use when 408 // verifying the existing table index relocations 409 uint32_t totalFunctions = 410 wasmObj->getNumImportedFunctions() + wasmObj->functions().size(); 411 tableEntriesRel.resize(totalFunctions); 412 tableEntries.resize(totalFunctions); 413 for (const WasmElemSegment &seg : wasmObj->elements()) { 414 int64_t offset; 415 if (seg.Offset.Opcode == WASM_OPCODE_I32_CONST) 416 offset = seg.Offset.Value.Int32; 417 else if (seg.Offset.Opcode == WASM_OPCODE_I64_CONST) 418 offset = seg.Offset.Value.Int64; 419 else 420 fatal(toString(this) + ": invalid table elements"); 421 for (size_t index = 0; index < seg.Functions.size(); index++) { 422 auto functionIndex = seg.Functions[index]; 423 tableEntriesRel[functionIndex] = index; 424 tableEntries[functionIndex] = offset + index; 425 } 426 } 427 428 ArrayRef<StringRef> comdats = wasmObj->linkingData().Comdats; 429 for (StringRef comdat : comdats) { 430 bool isNew = ignoreComdats || symtab->addComdat(comdat); 431 keptComdats.push_back(isNew); 432 } 433 434 uint32_t sectionIndex = 0; 435 436 // Bool for each symbol, true if called directly. This allows us to implement 437 // a weaker form of signature checking where undefined functions that are not 438 // called directly (i.e. only address taken) don't have to match the defined 439 // function's signature. We cannot do this for directly called functions 440 // because those signatures are checked at validation times. 441 // See https://bugs.llvm.org/show_bug.cgi?id=40412 442 std::vector<bool> isCalledDirectly(wasmObj->getNumberOfSymbols(), false); 443 for (const SectionRef &sec : wasmObj->sections()) { 444 const WasmSection §ion = wasmObj->getWasmSection(sec); 445 // Wasm objects can have at most one code and one data section. 446 if (section.Type == WASM_SEC_CODE) { 447 assert(!codeSection); 448 codeSection = §ion; 449 } else if (section.Type == WASM_SEC_DATA) { 450 assert(!dataSection); 451 dataSection = §ion; 452 } else if (section.Type == WASM_SEC_CUSTOM) { 453 InputChunk *customSec; 454 if (shouldMerge(section)) 455 customSec = make<MergeInputChunk>(section, this); 456 else 457 customSec = make<InputSection>(section, this); 458 customSec->discarded = isExcludedByComdat(customSec); 459 customSections.emplace_back(customSec); 460 customSections.back()->setRelocations(section.Relocations); 461 customSectionsByIndex[sectionIndex] = customSections.back(); 462 } 463 sectionIndex++; 464 // Scans relocations to determine if a function symbol is called directly. 465 for (const WasmRelocation &reloc : section.Relocations) 466 if (reloc.Type == R_WASM_FUNCTION_INDEX_LEB) 467 isCalledDirectly[reloc.Index] = true; 468 } 469 470 typeMap.resize(getWasmObj()->types().size()); 471 typeIsUsed.resize(getWasmObj()->types().size(), false); 472 473 474 // Populate `Segments`. 475 for (const WasmSegment &s : wasmObj->dataSegments()) { 476 InputChunk *seg; 477 if (shouldMerge(s)) 478 seg = make<MergeInputChunk>(s, this); 479 else 480 seg = make<InputSegment>(s, this); 481 seg->discarded = isExcludedByComdat(seg); 482 // Older object files did not include WASM_SEG_FLAG_TLS and instead 483 // relied on the naming convention. To maintain compat with such objects 484 // we still imply the TLS flag based on the name of the segment. 485 if (!seg->isTLS() && 486 (seg->name.startswith(".tdata") || seg->name.startswith(".tbss"))) 487 seg->flags |= WASM_SEG_FLAG_TLS; 488 segments.emplace_back(seg); 489 } 490 setRelocs(segments, dataSection); 491 492 // Populate `Functions`. 493 ArrayRef<WasmFunction> funcs = wasmObj->functions(); 494 ArrayRef<WasmSignature> types = wasmObj->types(); 495 functions.reserve(funcs.size()); 496 497 for (auto &f : funcs) { 498 auto *func = make<InputFunction>(types[f.SigIndex], &f, this); 499 func->discarded = isExcludedByComdat(func); 500 functions.emplace_back(func); 501 } 502 setRelocs(functions, codeSection); 503 504 // Populate `Tables`. 505 for (const WasmTable &t : wasmObj->tables()) 506 tables.emplace_back(make<InputTable>(t, this)); 507 508 // Populate `Globals`. 509 for (const WasmGlobal &g : wasmObj->globals()) 510 globals.emplace_back(make<InputGlobal>(g, this)); 511 512 // Populate `Tags`. 513 for (const WasmTag &t : wasmObj->tags()) 514 tags.emplace_back(make<InputTag>(types[t.SigIndex], t, this)); 515 516 // Populate `Symbols` based on the symbols in the object. 517 symbols.reserve(wasmObj->getNumberOfSymbols()); 518 uint32_t tableSymbolCount = 0; 519 for (const SymbolRef &sym : wasmObj->symbols()) { 520 const WasmSymbol &wasmSym = wasmObj->getWasmSymbol(sym.getRawDataRefImpl()); 521 if (wasmSym.isTypeTable()) 522 tableSymbolCount++; 523 if (wasmSym.isDefined()) { 524 // createDefined may fail if the symbol is comdat excluded in which case 525 // we fall back to creating an undefined symbol 526 if (Symbol *d = createDefined(wasmSym)) { 527 symbols.push_back(d); 528 continue; 529 } 530 } 531 size_t idx = symbols.size(); 532 symbols.push_back(createUndefined(wasmSym, isCalledDirectly[idx])); 533 } 534 535 addLegacyIndirectFunctionTableIfNeeded(tableSymbolCount); 536 } 537 538 bool ObjFile::isExcludedByComdat(const InputChunk *chunk) const { 539 uint32_t c = chunk->getComdat(); 540 if (c == UINT32_MAX) 541 return false; 542 return !keptComdats[c]; 543 } 544 545 FunctionSymbol *ObjFile::getFunctionSymbol(uint32_t index) const { 546 return cast<FunctionSymbol>(symbols[index]); 547 } 548 549 GlobalSymbol *ObjFile::getGlobalSymbol(uint32_t index) const { 550 return cast<GlobalSymbol>(symbols[index]); 551 } 552 553 TagSymbol *ObjFile::getTagSymbol(uint32_t index) const { 554 return cast<TagSymbol>(symbols[index]); 555 } 556 557 TableSymbol *ObjFile::getTableSymbol(uint32_t index) const { 558 return cast<TableSymbol>(symbols[index]); 559 } 560 561 SectionSymbol *ObjFile::getSectionSymbol(uint32_t index) const { 562 return cast<SectionSymbol>(symbols[index]); 563 } 564 565 DataSymbol *ObjFile::getDataSymbol(uint32_t index) const { 566 return cast<DataSymbol>(symbols[index]); 567 } 568 569 Symbol *ObjFile::createDefined(const WasmSymbol &sym) { 570 StringRef name = sym.Info.Name; 571 uint32_t flags = sym.Info.Flags; 572 573 switch (sym.Info.Kind) { 574 case WASM_SYMBOL_TYPE_FUNCTION: { 575 InputFunction *func = 576 functions[sym.Info.ElementIndex - wasmObj->getNumImportedFunctions()]; 577 if (sym.isBindingLocal()) 578 return make<DefinedFunction>(name, flags, this, func); 579 if (func->discarded) 580 return nullptr; 581 return symtab->addDefinedFunction(name, flags, this, func); 582 } 583 case WASM_SYMBOL_TYPE_DATA: { 584 InputChunk *seg = segments[sym.Info.DataRef.Segment]; 585 auto offset = sym.Info.DataRef.Offset; 586 auto size = sym.Info.DataRef.Size; 587 // Support older (e.g. llvm 13) object files that pre-date the per-symbol 588 // TLS flag, and symbols were assumed to be TLS by being defined in a TLS 589 // segment. 590 if (!(flags & WASM_SYMBOL_TLS) && seg->isTLS()) 591 flags |= WASM_SYMBOL_TLS; 592 if (sym.isBindingLocal()) 593 return make<DefinedData>(name, flags, this, seg, offset, size); 594 if (seg->discarded) 595 return nullptr; 596 return symtab->addDefinedData(name, flags, this, seg, offset, size); 597 } 598 case WASM_SYMBOL_TYPE_GLOBAL: { 599 InputGlobal *global = 600 globals[sym.Info.ElementIndex - wasmObj->getNumImportedGlobals()]; 601 if (sym.isBindingLocal()) 602 return make<DefinedGlobal>(name, flags, this, global); 603 return symtab->addDefinedGlobal(name, flags, this, global); 604 } 605 case WASM_SYMBOL_TYPE_SECTION: { 606 InputChunk *section = customSectionsByIndex[sym.Info.ElementIndex]; 607 assert(sym.isBindingLocal()); 608 // Need to return null if discarded here? data and func only do that when 609 // binding is not local. 610 if (section->discarded) 611 return nullptr; 612 return make<SectionSymbol>(flags, section, this); 613 } 614 case WASM_SYMBOL_TYPE_TAG: { 615 InputTag *tag = tags[sym.Info.ElementIndex - wasmObj->getNumImportedTags()]; 616 if (sym.isBindingLocal()) 617 return make<DefinedTag>(name, flags, this, tag); 618 return symtab->addDefinedTag(name, flags, this, tag); 619 } 620 case WASM_SYMBOL_TYPE_TABLE: { 621 InputTable *table = 622 tables[sym.Info.ElementIndex - wasmObj->getNumImportedTables()]; 623 if (sym.isBindingLocal()) 624 return make<DefinedTable>(name, flags, this, table); 625 return symtab->addDefinedTable(name, flags, this, table); 626 } 627 } 628 llvm_unreachable("unknown symbol kind"); 629 } 630 631 Symbol *ObjFile::createUndefined(const WasmSymbol &sym, bool isCalledDirectly) { 632 StringRef name = sym.Info.Name; 633 uint32_t flags = sym.Info.Flags | WASM_SYMBOL_UNDEFINED; 634 635 switch (sym.Info.Kind) { 636 case WASM_SYMBOL_TYPE_FUNCTION: 637 if (sym.isBindingLocal()) 638 return make<UndefinedFunction>(name, sym.Info.ImportName, 639 sym.Info.ImportModule, flags, this, 640 sym.Signature, isCalledDirectly); 641 return symtab->addUndefinedFunction(name, sym.Info.ImportName, 642 sym.Info.ImportModule, flags, this, 643 sym.Signature, isCalledDirectly); 644 case WASM_SYMBOL_TYPE_DATA: 645 if (sym.isBindingLocal()) 646 return make<UndefinedData>(name, flags, this); 647 return symtab->addUndefinedData(name, flags, this); 648 case WASM_SYMBOL_TYPE_GLOBAL: 649 if (sym.isBindingLocal()) 650 return make<UndefinedGlobal>(name, sym.Info.ImportName, 651 sym.Info.ImportModule, flags, this, 652 sym.GlobalType); 653 return symtab->addUndefinedGlobal(name, sym.Info.ImportName, 654 sym.Info.ImportModule, flags, this, 655 sym.GlobalType); 656 case WASM_SYMBOL_TYPE_TABLE: 657 if (sym.isBindingLocal()) 658 return make<UndefinedTable>(name, sym.Info.ImportName, 659 sym.Info.ImportModule, flags, this, 660 sym.TableType); 661 return symtab->addUndefinedTable(name, sym.Info.ImportName, 662 sym.Info.ImportModule, flags, this, 663 sym.TableType); 664 case WASM_SYMBOL_TYPE_TAG: 665 if (sym.isBindingLocal()) 666 return make<UndefinedTag>(name, sym.Info.ImportName, 667 sym.Info.ImportModule, flags, this, 668 sym.Signature); 669 return symtab->addUndefinedTag(name, sym.Info.ImportName, 670 sym.Info.ImportModule, flags, this, 671 sym.Signature); 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(), c.getChildOffset()); 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 BitcodeFile::BitcodeFile(MemoryBufferRef m, StringRef archiveName, 750 uint64_t offsetInArchive) 751 : InputFile(BitcodeKind, m) { 752 this->archiveName = std::string(archiveName); 753 754 std::string path = mb.getBufferIdentifier().str(); 755 756 // ThinLTO assumes that all MemoryBufferRefs given to it have a unique 757 // name. If two archives define two members with the same name, this 758 // causes a collision which result in only one of the objects being taken 759 // into consideration at LTO time (which very likely causes undefined 760 // symbols later in the link stage). So we append file offset to make 761 // filename unique. 762 StringRef name = archiveName.empty() 763 ? saver().save(path) 764 : saver().save(archiveName + "(" + path::filename(path) + 765 " at " + utostr(offsetInArchive) + ")"); 766 MemoryBufferRef mbref(mb.getBuffer(), name); 767 768 obj = check(lto::InputFile::create(mbref)); 769 770 // If this isn't part of an archive, it's eagerly linked, so mark it live. 771 if (archiveName.empty()) 772 markLive(); 773 } 774 775 bool BitcodeFile::doneLTO = false; 776 777 void BitcodeFile::parse() { 778 if (doneLTO) { 779 error(toString(this) + ": attempt to add bitcode file after LTO."); 780 return; 781 } 782 783 Triple t(obj->getTargetTriple()); 784 if (!t.isWasm()) { 785 error(toString(this) + ": machine type must be wasm32 or wasm64"); 786 return; 787 } 788 checkArch(t.getArch()); 789 std::vector<bool> keptComdats; 790 // TODO Support nodeduplicate https://bugs.llvm.org/show_bug.cgi?id=50531 791 for (std::pair<StringRef, Comdat::SelectionKind> s : obj->getComdatTable()) 792 keptComdats.push_back(symtab->addComdat(s.first)); 793 794 for (const lto::InputFile::Symbol &objSym : obj->symbols()) 795 symbols.push_back(createBitcodeSymbol(keptComdats, objSym, *this)); 796 } 797 798 } // namespace wasm 799 } // namespace lld 800