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