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->outputOffset + 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->getVirtualAddress() + 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->outputOffset + 270 (f->function->getFunctionCodeOffset() + reloc.Addend); 271 } 272 case R_WASM_SECTION_OFFSET_I32: 273 return getSectionSymbol(reloc.Index)->section->outputOffset + 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 // Since LLVM 12, we expect that if an input file defines or uses a table, it 312 // declares the tables using symbols and records each use with a relocation. 313 // This way when the linker combines inputs, it can collate the tables used by 314 // the inputs, assigning them distinct table numbers, and renumber all the uses 315 // as appropriate. At the same time, the linker has special logic to build the 316 // indirect function table if it is needed. 317 // 318 // However, object files produced by LLVM 11 and earlier neither write table 319 // symbols nor record relocations, and yet still use tables via call_indirect, 320 // and via function pointer bitcasts. We can detect these object files, as they 321 // declare tables as imports or define them locally, but don't have table 322 // symbols. synthesizeTableSymbols serves as a shim when loading these older 323 // input files, defining the missing symbols to allow the indirect function 324 // table to be built. 325 // 326 // Table uses in these older files won't be relocated, as they have no 327 // relocations. In practice this isn't a problem, as these object files 328 // typically just declare a single table named __indirect_function_table and 329 // having table number 0, so relocation would be idempotent anyway. 330 void ObjFile::synthesizeTableSymbols() { 331 uint32_t tableNumber = 0; 332 const WasmGlobalType *globalType = nullptr; 333 const WasmEventType *eventType = nullptr; 334 const WasmSignature *signature = nullptr; 335 if (wasmObj->getNumImportedTables()) { 336 for (const auto &import : wasmObj->imports()) { 337 if (import.Kind == WASM_EXTERNAL_TABLE) { 338 auto *info = make<WasmSymbolInfo>(); 339 info->Name = import.Field; 340 info->Kind = WASM_SYMBOL_TYPE_TABLE; 341 info->ImportModule = import.Module; 342 info->ImportName = import.Field; 343 info->Flags = WASM_SYMBOL_UNDEFINED; 344 info->Flags |= WASM_SYMBOL_NO_STRIP; 345 info->ElementIndex = tableNumber++; 346 LLVM_DEBUG(dbgs() << "Synthesizing symbol for table import: " 347 << info->Name << "\n"); 348 auto *wasmSym = make<WasmSymbol>(*info, globalType, &import.Table, 349 eventType, signature); 350 symbols.push_back(createUndefined(*wasmSym, false)); 351 // Because there are no TABLE_NUMBER relocs in this case, we can't 352 // compute accurate liveness info; instead, just mark the symbol as 353 // always live. 354 symbols.back()->markLive(); 355 } 356 } 357 } 358 for (const auto &table : tables) { 359 auto *info = make<llvm::wasm::WasmSymbolInfo>(); 360 // Empty name. 361 info->Kind = WASM_SYMBOL_TYPE_TABLE; 362 info->Flags = WASM_SYMBOL_BINDING_LOCAL; 363 info->Flags |= WASM_SYMBOL_VISIBILITY_HIDDEN; 364 info->Flags |= WASM_SYMBOL_NO_STRIP; 365 info->ElementIndex = tableNumber++; 366 LLVM_DEBUG(dbgs() << "Synthesizing symbol for table definition: " 367 << info->Name << "\n"); 368 auto *wasmSym = make<WasmSymbol>(*info, globalType, &table->getType(), 369 eventType, signature); 370 symbols.push_back(createDefined(*wasmSym)); 371 // Mark live, for the same reasons as for imported tables. 372 symbols.back()->markLive(); 373 } 374 } 375 376 void ObjFile::parse(bool ignoreComdats) { 377 // Parse a memory buffer as a wasm file. 378 LLVM_DEBUG(dbgs() << "Parsing object: " << toString(this) << "\n"); 379 std::unique_ptr<Binary> bin = CHECK(createBinary(mb), toString(this)); 380 381 auto *obj = dyn_cast<WasmObjectFile>(bin.get()); 382 if (!obj) 383 fatal(toString(this) + ": not a wasm file"); 384 if (!obj->isRelocatableObject()) 385 fatal(toString(this) + ": not a relocatable wasm file"); 386 387 bin.release(); 388 wasmObj.reset(obj); 389 390 checkArch(obj->getArch()); 391 392 // Build up a map of function indices to table indices for use when 393 // verifying the existing table index relocations 394 uint32_t totalFunctions = 395 wasmObj->getNumImportedFunctions() + wasmObj->functions().size(); 396 tableEntriesRel.resize(totalFunctions); 397 tableEntries.resize(totalFunctions); 398 for (const WasmElemSegment &seg : wasmObj->elements()) { 399 int64_t offset; 400 if (seg.Offset.Opcode == WASM_OPCODE_I32_CONST) 401 offset = seg.Offset.Value.Int32; 402 else if (seg.Offset.Opcode == WASM_OPCODE_I64_CONST) 403 offset = seg.Offset.Value.Int64; 404 else 405 fatal(toString(this) + ": invalid table elements"); 406 for (size_t index = 0; index < seg.Functions.size(); index++) { 407 auto functionIndex = seg.Functions[index]; 408 tableEntriesRel[functionIndex] = index; 409 tableEntries[functionIndex] = offset + index; 410 } 411 } 412 413 ArrayRef<StringRef> comdats = wasmObj->linkingData().Comdats; 414 for (StringRef comdat : comdats) { 415 bool isNew = ignoreComdats || symtab->addComdat(comdat); 416 keptComdats.push_back(isNew); 417 } 418 419 uint32_t sectionIndex = 0; 420 421 // Bool for each symbol, true if called directly. This allows us to implement 422 // a weaker form of signature checking where undefined functions that are not 423 // called directly (i.e. only address taken) don't have to match the defined 424 // function's signature. We cannot do this for directly called functions 425 // because those signatures are checked at validation times. 426 // See https://bugs.llvm.org/show_bug.cgi?id=40412 427 std::vector<bool> isCalledDirectly(wasmObj->getNumberOfSymbols(), false); 428 for (const SectionRef &sec : wasmObj->sections()) { 429 const WasmSection §ion = wasmObj->getWasmSection(sec); 430 // Wasm objects can have at most one code and one data section. 431 if (section.Type == WASM_SEC_CODE) { 432 assert(!codeSection); 433 codeSection = §ion; 434 } else if (section.Type == WASM_SEC_DATA) { 435 assert(!dataSection); 436 dataSection = §ion; 437 } else if (section.Type == WASM_SEC_CUSTOM) { 438 auto *customSec = make<InputSection>(section, this); 439 customSec->discarded = isExcludedByComdat(customSec); 440 customSections.emplace_back(customSec); 441 customSections.back()->setRelocations(section.Relocations); 442 customSectionsByIndex[sectionIndex] = customSections.back(); 443 } 444 sectionIndex++; 445 // Scans relocations to determine if a function symbol is called directly. 446 for (const WasmRelocation &reloc : section.Relocations) 447 if (reloc.Type == R_WASM_FUNCTION_INDEX_LEB) 448 isCalledDirectly[reloc.Index] = true; 449 } 450 451 typeMap.resize(getWasmObj()->types().size()); 452 typeIsUsed.resize(getWasmObj()->types().size(), false); 453 454 455 // Populate `Segments`. 456 for (const WasmSegment &s : wasmObj->dataSegments()) { 457 auto* seg = make<InputSegment>(s, this); 458 seg->discarded = isExcludedByComdat(seg); 459 segments.emplace_back(seg); 460 } 461 setRelocs(segments, dataSection); 462 463 // Populate `Functions`. 464 ArrayRef<WasmFunction> funcs = wasmObj->functions(); 465 ArrayRef<uint32_t> funcTypes = wasmObj->functionTypes(); 466 ArrayRef<WasmSignature> types = wasmObj->types(); 467 functions.reserve(funcs.size()); 468 469 for (size_t i = 0, e = funcs.size(); i != e; ++i) { 470 auto* func = make<InputFunction>(types[funcTypes[i]], &funcs[i], this); 471 func->discarded = isExcludedByComdat(func); 472 functions.emplace_back(func); 473 } 474 setRelocs(functions, codeSection); 475 476 // Populate `Tables`. 477 for (const WasmTable &t : wasmObj->tables()) 478 tables.emplace_back(make<InputTable>(t, this)); 479 480 // Populate `Globals`. 481 for (const WasmGlobal &g : wasmObj->globals()) 482 globals.emplace_back(make<InputGlobal>(g, this)); 483 484 // Populate `Events`. 485 for (const WasmEvent &e : wasmObj->events()) 486 events.emplace_back(make<InputEvent>(types[e.Type.SigIndex], e, this)); 487 488 // Populate `Symbols` based on the symbols in the object. 489 symbols.reserve(wasmObj->getNumberOfSymbols()); 490 bool haveTableSymbol = false; 491 for (const SymbolRef &sym : wasmObj->symbols()) { 492 const WasmSymbol &wasmSym = wasmObj->getWasmSymbol(sym.getRawDataRefImpl()); 493 if (wasmSym.isTypeTable()) 494 haveTableSymbol = true; 495 if (wasmSym.isDefined()) { 496 // createDefined may fail if the symbol is comdat excluded in which case 497 // we fall back to creating an undefined symbol 498 if (Symbol *d = createDefined(wasmSym)) { 499 symbols.push_back(d); 500 continue; 501 } 502 } 503 size_t idx = symbols.size(); 504 symbols.push_back(createUndefined(wasmSym, isCalledDirectly[idx])); 505 } 506 507 // As a stopgap measure while implementing table support, if the object file 508 // has table definitions or imports but no table symbols, synthesize symbols 509 // for those tables. Mark as NO_STRIP to ensure they reach the output file, 510 // even if there are no TABLE_NUMBER relocs against them. 511 if (!haveTableSymbol) 512 synthesizeTableSymbols(); 513 } 514 515 bool ObjFile::isExcludedByComdat(InputChunk *chunk) const { 516 uint32_t c = chunk->getComdat(); 517 if (c == UINT32_MAX) 518 return false; 519 return !keptComdats[c]; 520 } 521 522 FunctionSymbol *ObjFile::getFunctionSymbol(uint32_t index) const { 523 return cast<FunctionSymbol>(symbols[index]); 524 } 525 526 GlobalSymbol *ObjFile::getGlobalSymbol(uint32_t index) const { 527 return cast<GlobalSymbol>(symbols[index]); 528 } 529 530 EventSymbol *ObjFile::getEventSymbol(uint32_t index) const { 531 return cast<EventSymbol>(symbols[index]); 532 } 533 534 TableSymbol *ObjFile::getTableSymbol(uint32_t index) const { 535 return cast<TableSymbol>(symbols[index]); 536 } 537 538 SectionSymbol *ObjFile::getSectionSymbol(uint32_t index) const { 539 return cast<SectionSymbol>(symbols[index]); 540 } 541 542 DataSymbol *ObjFile::getDataSymbol(uint32_t index) const { 543 return cast<DataSymbol>(symbols[index]); 544 } 545 546 Symbol *ObjFile::createDefined(const WasmSymbol &sym) { 547 StringRef name = sym.Info.Name; 548 uint32_t flags = sym.Info.Flags; 549 550 switch (sym.Info.Kind) { 551 case WASM_SYMBOL_TYPE_FUNCTION: { 552 InputFunction *func = 553 functions[sym.Info.ElementIndex - wasmObj->getNumImportedFunctions()]; 554 if (sym.isBindingLocal()) 555 return make<DefinedFunction>(name, flags, this, func); 556 if (func->discarded) 557 return nullptr; 558 return symtab->addDefinedFunction(name, flags, this, func); 559 } 560 case WASM_SYMBOL_TYPE_DATA: { 561 InputSegment *seg = segments[sym.Info.DataRef.Segment]; 562 auto offset = sym.Info.DataRef.Offset; 563 auto size = sym.Info.DataRef.Size; 564 if (sym.isBindingLocal()) 565 return make<DefinedData>(name, flags, this, seg, offset, size); 566 if (seg->discarded) 567 return nullptr; 568 return symtab->addDefinedData(name, flags, this, seg, offset, size); 569 } 570 case WASM_SYMBOL_TYPE_GLOBAL: { 571 InputGlobal *global = 572 globals[sym.Info.ElementIndex - wasmObj->getNumImportedGlobals()]; 573 if (sym.isBindingLocal()) 574 return make<DefinedGlobal>(name, flags, this, global); 575 return symtab->addDefinedGlobal(name, flags, this, global); 576 } 577 case WASM_SYMBOL_TYPE_SECTION: { 578 InputSection *section = customSectionsByIndex[sym.Info.ElementIndex]; 579 assert(sym.isBindingLocal()); 580 // Need to return null if discarded here? data and func only do that when 581 // binding is not local. 582 if (section->discarded) 583 return nullptr; 584 return make<SectionSymbol>(flags, section, this); 585 } 586 case WASM_SYMBOL_TYPE_EVENT: { 587 InputEvent *event = 588 events[sym.Info.ElementIndex - wasmObj->getNumImportedEvents()]; 589 if (sym.isBindingLocal()) 590 return make<DefinedEvent>(name, flags, this, event); 591 return symtab->addDefinedEvent(name, flags, this, event); 592 } 593 case WASM_SYMBOL_TYPE_TABLE: { 594 InputTable *table = 595 tables[sym.Info.ElementIndex - wasmObj->getNumImportedTables()]; 596 if (sym.isBindingLocal()) 597 return make<DefinedTable>(name, flags, this, table); 598 return symtab->addDefinedTable(name, flags, this, table); 599 } 600 } 601 llvm_unreachable("unknown symbol kind"); 602 } 603 604 Symbol *ObjFile::createUndefined(const WasmSymbol &sym, bool isCalledDirectly) { 605 StringRef name = sym.Info.Name; 606 uint32_t flags = sym.Info.Flags | WASM_SYMBOL_UNDEFINED; 607 608 switch (sym.Info.Kind) { 609 case WASM_SYMBOL_TYPE_FUNCTION: 610 if (sym.isBindingLocal()) 611 return make<UndefinedFunction>(name, sym.Info.ImportName, 612 sym.Info.ImportModule, flags, this, 613 sym.Signature, isCalledDirectly); 614 return symtab->addUndefinedFunction(name, sym.Info.ImportName, 615 sym.Info.ImportModule, flags, this, 616 sym.Signature, isCalledDirectly); 617 case WASM_SYMBOL_TYPE_DATA: 618 if (sym.isBindingLocal()) 619 return make<UndefinedData>(name, flags, this); 620 return symtab->addUndefinedData(name, flags, this); 621 case WASM_SYMBOL_TYPE_GLOBAL: 622 if (sym.isBindingLocal()) 623 return make<UndefinedGlobal>(name, sym.Info.ImportName, 624 sym.Info.ImportModule, flags, this, 625 sym.GlobalType); 626 return symtab->addUndefinedGlobal(name, sym.Info.ImportName, 627 sym.Info.ImportModule, flags, this, 628 sym.GlobalType); 629 case WASM_SYMBOL_TYPE_TABLE: 630 if (sym.isBindingLocal()) 631 return make<UndefinedTable>(name, sym.Info.ImportName, 632 sym.Info.ImportModule, flags, this, 633 sym.TableType); 634 return symtab->addUndefinedTable(name, sym.Info.ImportName, 635 sym.Info.ImportModule, flags, this, 636 sym.TableType); 637 case WASM_SYMBOL_TYPE_SECTION: 638 llvm_unreachable("section symbols cannot be undefined"); 639 } 640 llvm_unreachable("unknown symbol kind"); 641 } 642 643 void ArchiveFile::parse() { 644 // Parse a MemoryBufferRef as an archive file. 645 LLVM_DEBUG(dbgs() << "Parsing library: " << toString(this) << "\n"); 646 file = CHECK(Archive::create(mb), toString(this)); 647 648 // Read the symbol table to construct Lazy symbols. 649 int count = 0; 650 for (const Archive::Symbol &sym : file->symbols()) { 651 symtab->addLazy(this, &sym); 652 ++count; 653 } 654 LLVM_DEBUG(dbgs() << "Read " << count << " symbols\n"); 655 } 656 657 void ArchiveFile::addMember(const Archive::Symbol *sym) { 658 const Archive::Child &c = 659 CHECK(sym->getMember(), 660 "could not get the member for symbol " + sym->getName()); 661 662 // Don't try to load the same member twice (this can happen when members 663 // mutually reference each other). 664 if (!seen.insert(c.getChildOffset()).second) 665 return; 666 667 LLVM_DEBUG(dbgs() << "loading lazy: " << sym->getName() << "\n"); 668 LLVM_DEBUG(dbgs() << "from archive: " << toString(this) << "\n"); 669 670 MemoryBufferRef mb = 671 CHECK(c.getMemoryBufferRef(), 672 "could not get the buffer for the member defining symbol " + 673 sym->getName()); 674 675 InputFile *obj = createObjectFile(mb, getName()); 676 symtab->addFile(obj); 677 } 678 679 static uint8_t mapVisibility(GlobalValue::VisibilityTypes gvVisibility) { 680 switch (gvVisibility) { 681 case GlobalValue::DefaultVisibility: 682 return WASM_SYMBOL_VISIBILITY_DEFAULT; 683 case GlobalValue::HiddenVisibility: 684 case GlobalValue::ProtectedVisibility: 685 return WASM_SYMBOL_VISIBILITY_HIDDEN; 686 } 687 llvm_unreachable("unknown visibility"); 688 } 689 690 static Symbol *createBitcodeSymbol(const std::vector<bool> &keptComdats, 691 const lto::InputFile::Symbol &objSym, 692 BitcodeFile &f) { 693 StringRef name = saver.save(objSym.getName()); 694 695 uint32_t flags = objSym.isWeak() ? WASM_SYMBOL_BINDING_WEAK : 0; 696 flags |= mapVisibility(objSym.getVisibility()); 697 698 int c = objSym.getComdatIndex(); 699 bool excludedByComdat = c != -1 && !keptComdats[c]; 700 701 if (objSym.isUndefined() || excludedByComdat) { 702 flags |= WASM_SYMBOL_UNDEFINED; 703 if (objSym.isExecutable()) 704 return symtab->addUndefinedFunction(name, None, None, flags, &f, nullptr, 705 true); 706 return symtab->addUndefinedData(name, flags, &f); 707 } 708 709 if (objSym.isExecutable()) 710 return symtab->addDefinedFunction(name, flags, &f, nullptr); 711 return symtab->addDefinedData(name, flags, &f, nullptr, 0, 0); 712 } 713 714 bool BitcodeFile::doneLTO = false; 715 716 void BitcodeFile::parse() { 717 if (doneLTO) { 718 error(toString(this) + ": attempt to add bitcode file after LTO."); 719 return; 720 } 721 722 obj = check(lto::InputFile::create(MemoryBufferRef( 723 mb.getBuffer(), saver.save(archiveName + mb.getBufferIdentifier())))); 724 Triple t(obj->getTargetTriple()); 725 if (!t.isWasm()) { 726 error(toString(this) + ": machine type must be wasm32 or wasm64"); 727 return; 728 } 729 checkArch(t.getArch()); 730 std::vector<bool> keptComdats; 731 for (StringRef s : obj->getComdatTable()) 732 keptComdats.push_back(symtab->addComdat(s)); 733 734 for (const lto::InputFile::Symbol &objSym : obj->symbols()) 735 symbols.push_back(createBitcodeSymbol(keptComdats, objSym, *this)); 736 } 737 738 } // namespace wasm 739 } // namespace lld 740