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 "InputEvent.h" 13 #include "InputGlobal.h" 14 #include "OutputSegment.h" 15 #include "SymbolTable.h" 16 #include "lld/Common/ErrorHandler.h" 17 #include "lld/Common/Memory.h" 18 #include "lld/Common/Reproduce.h" 19 #include "llvm/Object/Binary.h" 20 #include "llvm/Object/Wasm.h" 21 #include "llvm/Support/TarWriter.h" 22 #include "llvm/Support/raw_ostream.h" 23 24 #define DEBUG_TYPE "lld" 25 26 using namespace llvm; 27 using namespace llvm::object; 28 using namespace llvm::wasm; 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 file_magic magic = identify_magic(mb.getBuffer()); 77 if (magic == file_magic::wasm_object) { 78 std::unique_ptr<Binary> bin = 79 CHECK(createBinary(mb), mb.getBufferIdentifier()); 80 auto *obj = cast<WasmObjectFile>(bin.get()); 81 if (obj->isSharedObject()) 82 return make<SharedFile>(mb); 83 return make<ObjFile>(mb, archiveName); 84 } 85 86 if (magic == file_magic::bitcode) 87 return make<BitcodeFile>(mb, archiveName); 88 89 fatal("unknown file type: " + mb.getBufferIdentifier()); 90 } 91 92 void ObjFile::dumpInfo() const { 93 log("info for: " + toString(this) + 94 "\n Symbols : " + Twine(symbols.size()) + 95 "\n Function Imports : " + Twine(wasmObj->getNumImportedFunctions()) + 96 "\n Global Imports : " + Twine(wasmObj->getNumImportedGlobals()) + 97 "\n Event Imports : " + Twine(wasmObj->getNumImportedEvents())); 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_FUNCTION_OFFSET_I32: 127 case R_WASM_FUNCTION_OFFSET_I64: 128 return reloc.Addend; 129 case R_WASM_SECTION_OFFSET_I32: 130 return getSectionSymbol(reloc.Index)->section->outputOffset + reloc.Addend; 131 default: 132 llvm_unreachable("unexpected relocation type"); 133 } 134 } 135 136 // Calculate the value we expect to find at the relocation location. 137 // This is used as a sanity check before applying a relocation to a given 138 // location. It is useful for catching bugs in the compiler and linker. 139 uint64_t ObjFile::calcExpectedValue(const WasmRelocation &reloc) const { 140 switch (reloc.Type) { 141 case R_WASM_TABLE_INDEX_I32: 142 case R_WASM_TABLE_INDEX_I64: 143 case R_WASM_TABLE_INDEX_SLEB: 144 case R_WASM_TABLE_INDEX_SLEB64: { 145 const WasmSymbol &sym = wasmObj->syms()[reloc.Index]; 146 return tableEntries[sym.Info.ElementIndex]; 147 } 148 case R_WASM_TABLE_INDEX_REL_SLEB: { 149 const WasmSymbol &sym = wasmObj->syms()[reloc.Index]; 150 return tableEntriesRel[sym.Info.ElementIndex]; 151 } 152 case R_WASM_MEMORY_ADDR_LEB: 153 case R_WASM_MEMORY_ADDR_LEB64: 154 case R_WASM_MEMORY_ADDR_SLEB: 155 case R_WASM_MEMORY_ADDR_SLEB64: 156 case R_WASM_MEMORY_ADDR_REL_SLEB: 157 case R_WASM_MEMORY_ADDR_REL_SLEB64: 158 case R_WASM_MEMORY_ADDR_I32: 159 case R_WASM_MEMORY_ADDR_I64: 160 case R_WASM_MEMORY_ADDR_TLS_SLEB: { 161 const WasmSymbol &sym = wasmObj->syms()[reloc.Index]; 162 if (sym.isUndefined()) 163 return 0; 164 const WasmSegment &segment = 165 wasmObj->dataSegments()[sym.Info.DataRef.Segment]; 166 if (segment.Data.Offset.Opcode == WASM_OPCODE_I32_CONST) 167 return segment.Data.Offset.Value.Int32 + sym.Info.DataRef.Offset + 168 reloc.Addend; 169 else if (segment.Data.Offset.Opcode == WASM_OPCODE_I64_CONST) 170 return segment.Data.Offset.Value.Int64 + sym.Info.DataRef.Offset + 171 reloc.Addend; 172 else 173 llvm_unreachable("unknown init expr opcode"); 174 } 175 case R_WASM_FUNCTION_OFFSET_I32: 176 case R_WASM_FUNCTION_OFFSET_I64: { 177 const WasmSymbol &sym = wasmObj->syms()[reloc.Index]; 178 InputFunction *f = 179 functions[sym.Info.ElementIndex - wasmObj->getNumImportedFunctions()]; 180 return f->getFunctionInputOffset() + f->getFunctionCodeOffset() + 181 reloc.Addend; 182 } 183 case R_WASM_SECTION_OFFSET_I32: 184 return reloc.Addend; 185 case R_WASM_TYPE_INDEX_LEB: 186 return reloc.Index; 187 case R_WASM_FUNCTION_INDEX_LEB: 188 case R_WASM_GLOBAL_INDEX_LEB: 189 case R_WASM_GLOBAL_INDEX_I32: 190 case R_WASM_EVENT_INDEX_LEB: { 191 const WasmSymbol &sym = wasmObj->syms()[reloc.Index]; 192 return sym.Info.ElementIndex; 193 } 194 default: 195 llvm_unreachable("unknown relocation type"); 196 } 197 } 198 199 // Translate from the relocation's index into the final linked output value. 200 uint64_t ObjFile::calcNewValue(const WasmRelocation &reloc, uint64_t tombstone) const { 201 const Symbol* sym = nullptr; 202 if (reloc.Type != R_WASM_TYPE_INDEX_LEB) { 203 sym = symbols[reloc.Index]; 204 205 // We can end up with relocations against non-live symbols. For example 206 // in debug sections. We return a tombstone value in debug symbol sections 207 // so this will not produce a valid range conflicting with ranges of actual 208 // code. In other sections we return reloc.Addend. 209 210 if ((isa<FunctionSymbol>(sym) || isa<DataSymbol>(sym)) && !sym->isLive()) 211 return tombstone ? tombstone : reloc.Addend; 212 } 213 214 switch (reloc.Type) { 215 case R_WASM_TABLE_INDEX_I32: 216 case R_WASM_TABLE_INDEX_I64: 217 case R_WASM_TABLE_INDEX_SLEB: 218 case R_WASM_TABLE_INDEX_SLEB64: 219 case R_WASM_TABLE_INDEX_REL_SLEB: { 220 if (!getFunctionSymbol(reloc.Index)->hasTableIndex()) 221 return 0; 222 uint32_t index = getFunctionSymbol(reloc.Index)->getTableIndex(); 223 if (reloc.Type == R_WASM_TABLE_INDEX_REL_SLEB) 224 index -= config->tableBase; 225 return index; 226 227 } 228 case R_WASM_MEMORY_ADDR_LEB: 229 case R_WASM_MEMORY_ADDR_LEB64: 230 case R_WASM_MEMORY_ADDR_SLEB: 231 case R_WASM_MEMORY_ADDR_SLEB64: 232 case R_WASM_MEMORY_ADDR_REL_SLEB: 233 case R_WASM_MEMORY_ADDR_REL_SLEB64: 234 case R_WASM_MEMORY_ADDR_I32: 235 case R_WASM_MEMORY_ADDR_I64: { 236 if (isa<UndefinedData>(sym) || sym->isUndefWeak()) 237 return 0; 238 auto D = cast<DefinedData>(sym); 239 // Treat non-TLS relocation against symbols that live in the TLS segment 240 // like TLS relocations. This beaviour exists to support older object 241 // files created before we introduced TLS relocations. 242 // TODO(sbc): Remove this legacy behaviour one day. This will break 243 // backward compat with old object files built with `-fPIC`. 244 if (D->segment && D->segment->outputSeg->name == ".tdata") 245 return D->getOutputSegmentOffset() + reloc.Addend; 246 return D->getVirtualAddress() + reloc.Addend; 247 } 248 case R_WASM_MEMORY_ADDR_TLS_SLEB: 249 if (isa<UndefinedData>(sym) || sym->isUndefWeak()) 250 return 0; 251 // TLS relocations are relative to the start of the TLS output segment 252 return cast<DefinedData>(sym)->getOutputSegmentOffset() + reloc.Addend; 253 case R_WASM_TYPE_INDEX_LEB: 254 return typeMap[reloc.Index]; 255 case R_WASM_FUNCTION_INDEX_LEB: 256 return getFunctionSymbol(reloc.Index)->getFunctionIndex(); 257 case R_WASM_GLOBAL_INDEX_LEB: 258 case R_WASM_GLOBAL_INDEX_I32: 259 if (auto gs = dyn_cast<GlobalSymbol>(sym)) 260 return gs->getGlobalIndex(); 261 return sym->getGOTIndex(); 262 case R_WASM_EVENT_INDEX_LEB: 263 return getEventSymbol(reloc.Index)->getEventIndex(); 264 case R_WASM_FUNCTION_OFFSET_I32: 265 case R_WASM_FUNCTION_OFFSET_I64: { 266 auto *f = cast<DefinedFunction>(sym); 267 return f->function->outputOffset + 268 (f->function->getFunctionCodeOffset() + reloc.Addend); 269 } 270 case R_WASM_SECTION_OFFSET_I32: 271 return getSectionSymbol(reloc.Index)->section->outputOffset + reloc.Addend; 272 default: 273 llvm_unreachable("unknown relocation type"); 274 } 275 } 276 277 template <class T> 278 static void setRelocs(const std::vector<T *> &chunks, 279 const WasmSection *section) { 280 if (!section) 281 return; 282 283 ArrayRef<WasmRelocation> relocs = section->Relocations; 284 assert(llvm::is_sorted( 285 relocs, [](const WasmRelocation &r1, const WasmRelocation &r2) { 286 return r1.Offset < r2.Offset; 287 })); 288 assert(llvm::is_sorted(chunks, [](InputChunk *c1, InputChunk *c2) { 289 return c1->getInputSectionOffset() < c2->getInputSectionOffset(); 290 })); 291 292 auto relocsNext = relocs.begin(); 293 auto relocsEnd = relocs.end(); 294 auto relocLess = [](const WasmRelocation &r, uint32_t val) { 295 return r.Offset < val; 296 }; 297 for (InputChunk *c : chunks) { 298 auto relocsStart = std::lower_bound(relocsNext, relocsEnd, 299 c->getInputSectionOffset(), relocLess); 300 relocsNext = std::lower_bound( 301 relocsStart, relocsEnd, c->getInputSectionOffset() + c->getInputSize(), 302 relocLess); 303 c->setRelocations(ArrayRef<WasmRelocation>(relocsStart, relocsNext)); 304 } 305 } 306 307 void ObjFile::parse(bool ignoreComdats) { 308 // Parse a memory buffer as a wasm file. 309 LLVM_DEBUG(dbgs() << "Parsing object: " << toString(this) << "\n"); 310 std::unique_ptr<Binary> bin = CHECK(createBinary(mb), toString(this)); 311 312 auto *obj = dyn_cast<WasmObjectFile>(bin.get()); 313 if (!obj) 314 fatal(toString(this) + ": not a wasm file"); 315 if (!obj->isRelocatableObject()) 316 fatal(toString(this) + ": not a relocatable wasm file"); 317 318 bin.release(); 319 wasmObj.reset(obj); 320 321 checkArch(obj->getArch()); 322 323 // Build up a map of function indices to table indices for use when 324 // verifying the existing table index relocations 325 uint32_t totalFunctions = 326 wasmObj->getNumImportedFunctions() + wasmObj->functions().size(); 327 tableEntriesRel.resize(totalFunctions); 328 tableEntries.resize(totalFunctions); 329 for (const WasmElemSegment &seg : wasmObj->elements()) { 330 int64_t offset; 331 if (seg.Offset.Opcode == WASM_OPCODE_I32_CONST) 332 offset = seg.Offset.Value.Int32; 333 else if (seg.Offset.Opcode == WASM_OPCODE_I64_CONST) 334 offset = seg.Offset.Value.Int64; 335 else 336 fatal(toString(this) + ": invalid table elements"); 337 for (size_t index = 0; index < seg.Functions.size(); index++) { 338 auto functionIndex = seg.Functions[index]; 339 tableEntriesRel[functionIndex] = index; 340 tableEntries[functionIndex] = offset + index; 341 } 342 } 343 344 ArrayRef<StringRef> comdats = wasmObj->linkingData().Comdats; 345 for (StringRef comdat : comdats) { 346 bool isNew = ignoreComdats || symtab->addComdat(comdat); 347 keptComdats.push_back(isNew); 348 } 349 350 uint32_t sectionIndex = 0; 351 352 // Bool for each symbol, true if called directly. This allows us to implement 353 // a weaker form of signature checking where undefined functions that are not 354 // called directly (i.e. only address taken) don't have to match the defined 355 // function's signature. We cannot do this for directly called functions 356 // because those signatures are checked at validation times. 357 // See https://bugs.llvm.org/show_bug.cgi?id=40412 358 std::vector<bool> isCalledDirectly(wasmObj->getNumberOfSymbols(), false); 359 for (const SectionRef &sec : wasmObj->sections()) { 360 const WasmSection §ion = wasmObj->getWasmSection(sec); 361 // Wasm objects can have at most one code and one data section. 362 if (section.Type == WASM_SEC_CODE) { 363 assert(!codeSection); 364 codeSection = §ion; 365 } else if (section.Type == WASM_SEC_DATA) { 366 assert(!dataSection); 367 dataSection = §ion; 368 } else if (section.Type == WASM_SEC_CUSTOM) { 369 auto *customSec = make<InputSection>(section, this); 370 customSec->discarded = isExcludedByComdat(customSec); 371 customSections.emplace_back(customSec); 372 customSections.back()->setRelocations(section.Relocations); 373 customSectionsByIndex[sectionIndex] = customSections.back(); 374 } 375 sectionIndex++; 376 // Scans relocations to determine if a function symbol is called directly. 377 for (const WasmRelocation &reloc : section.Relocations) 378 if (reloc.Type == R_WASM_FUNCTION_INDEX_LEB) 379 isCalledDirectly[reloc.Index] = true; 380 } 381 382 typeMap.resize(getWasmObj()->types().size()); 383 typeIsUsed.resize(getWasmObj()->types().size(), false); 384 385 386 // Populate `Segments`. 387 for (const WasmSegment &s : wasmObj->dataSegments()) { 388 auto* seg = make<InputSegment>(s, this); 389 seg->discarded = isExcludedByComdat(seg); 390 segments.emplace_back(seg); 391 } 392 setRelocs(segments, dataSection); 393 394 // Populate `Functions`. 395 ArrayRef<WasmFunction> funcs = wasmObj->functions(); 396 ArrayRef<uint32_t> funcTypes = wasmObj->functionTypes(); 397 ArrayRef<WasmSignature> types = wasmObj->types(); 398 functions.reserve(funcs.size()); 399 400 for (size_t i = 0, e = funcs.size(); i != e; ++i) { 401 auto* func = make<InputFunction>(types[funcTypes[i]], &funcs[i], this); 402 func->discarded = isExcludedByComdat(func); 403 functions.emplace_back(func); 404 } 405 setRelocs(functions, codeSection); 406 407 // Populate `Globals`. 408 for (const WasmGlobal &g : wasmObj->globals()) 409 globals.emplace_back(make<InputGlobal>(g, this)); 410 411 // Populate `Events`. 412 for (const WasmEvent &e : wasmObj->events()) 413 events.emplace_back(make<InputEvent>(types[e.Type.SigIndex], e, this)); 414 415 // Populate `Symbols` based on the symbols in the object. 416 symbols.reserve(wasmObj->getNumberOfSymbols()); 417 for (const SymbolRef &sym : wasmObj->symbols()) { 418 const WasmSymbol &wasmSym = wasmObj->getWasmSymbol(sym.getRawDataRefImpl()); 419 if (wasmSym.isDefined()) { 420 // createDefined may fail if the symbol is comdat excluded in which case 421 // we fall back to creating an undefined symbol 422 if (Symbol *d = createDefined(wasmSym)) { 423 symbols.push_back(d); 424 continue; 425 } 426 } 427 size_t idx = symbols.size(); 428 symbols.push_back(createUndefined(wasmSym, isCalledDirectly[idx])); 429 } 430 } 431 432 bool ObjFile::isExcludedByComdat(InputChunk *chunk) const { 433 uint32_t c = chunk->getComdat(); 434 if (c == UINT32_MAX) 435 return false; 436 return !keptComdats[c]; 437 } 438 439 FunctionSymbol *ObjFile::getFunctionSymbol(uint32_t index) const { 440 return cast<FunctionSymbol>(symbols[index]); 441 } 442 443 GlobalSymbol *ObjFile::getGlobalSymbol(uint32_t index) const { 444 return cast<GlobalSymbol>(symbols[index]); 445 } 446 447 EventSymbol *ObjFile::getEventSymbol(uint32_t index) const { 448 return cast<EventSymbol>(symbols[index]); 449 } 450 451 SectionSymbol *ObjFile::getSectionSymbol(uint32_t index) const { 452 return cast<SectionSymbol>(symbols[index]); 453 } 454 455 DataSymbol *ObjFile::getDataSymbol(uint32_t index) const { 456 return cast<DataSymbol>(symbols[index]); 457 } 458 459 Symbol *ObjFile::createDefined(const WasmSymbol &sym) { 460 StringRef name = sym.Info.Name; 461 uint32_t flags = sym.Info.Flags; 462 463 switch (sym.Info.Kind) { 464 case WASM_SYMBOL_TYPE_FUNCTION: { 465 InputFunction *func = 466 functions[sym.Info.ElementIndex - wasmObj->getNumImportedFunctions()]; 467 if (sym.isBindingLocal()) 468 return make<DefinedFunction>(name, flags, this, func); 469 if (func->discarded) 470 return nullptr; 471 return symtab->addDefinedFunction(name, flags, this, func); 472 } 473 case WASM_SYMBOL_TYPE_DATA: { 474 InputSegment *seg = segments[sym.Info.DataRef.Segment]; 475 auto offset = sym.Info.DataRef.Offset; 476 auto size = sym.Info.DataRef.Size; 477 if (sym.isBindingLocal()) 478 return make<DefinedData>(name, flags, this, seg, offset, size); 479 if (seg->discarded) 480 return nullptr; 481 return symtab->addDefinedData(name, flags, this, seg, offset, size); 482 } 483 case WASM_SYMBOL_TYPE_GLOBAL: { 484 InputGlobal *global = 485 globals[sym.Info.ElementIndex - wasmObj->getNumImportedGlobals()]; 486 if (sym.isBindingLocal()) 487 return make<DefinedGlobal>(name, flags, this, global); 488 return symtab->addDefinedGlobal(name, flags, this, global); 489 } 490 case WASM_SYMBOL_TYPE_SECTION: { 491 InputSection *section = customSectionsByIndex[sym.Info.ElementIndex]; 492 assert(sym.isBindingLocal()); 493 // Need to return null if discarded here? data and func only do that when 494 // binding is not local. 495 if (section->discarded) 496 return nullptr; 497 return make<SectionSymbol>(flags, section, this); 498 } 499 case WASM_SYMBOL_TYPE_EVENT: { 500 InputEvent *event = 501 events[sym.Info.ElementIndex - wasmObj->getNumImportedEvents()]; 502 if (sym.isBindingLocal()) 503 return make<DefinedEvent>(name, flags, this, event); 504 return symtab->addDefinedEvent(name, flags, this, event); 505 } 506 } 507 llvm_unreachable("unknown symbol kind"); 508 } 509 510 Symbol *ObjFile::createUndefined(const WasmSymbol &sym, bool isCalledDirectly) { 511 StringRef name = sym.Info.Name; 512 uint32_t flags = sym.Info.Flags | WASM_SYMBOL_UNDEFINED; 513 514 switch (sym.Info.Kind) { 515 case WASM_SYMBOL_TYPE_FUNCTION: 516 if (sym.isBindingLocal()) 517 return make<UndefinedFunction>(name, sym.Info.ImportName, 518 sym.Info.ImportModule, flags, this, 519 sym.Signature, isCalledDirectly); 520 return symtab->addUndefinedFunction(name, sym.Info.ImportName, 521 sym.Info.ImportModule, flags, this, 522 sym.Signature, isCalledDirectly); 523 case WASM_SYMBOL_TYPE_DATA: 524 if (sym.isBindingLocal()) 525 return make<UndefinedData>(name, flags, this); 526 return symtab->addUndefinedData(name, flags, this); 527 case WASM_SYMBOL_TYPE_GLOBAL: 528 if (sym.isBindingLocal()) 529 return make<UndefinedGlobal>(name, sym.Info.ImportName, 530 sym.Info.ImportModule, flags, this, 531 sym.GlobalType); 532 return symtab->addUndefinedGlobal(name, sym.Info.ImportName, 533 sym.Info.ImportModule, flags, this, 534 sym.GlobalType); 535 case WASM_SYMBOL_TYPE_SECTION: 536 llvm_unreachable("section symbols cannot be undefined"); 537 } 538 llvm_unreachable("unknown symbol kind"); 539 } 540 541 void ArchiveFile::parse() { 542 // Parse a MemoryBufferRef as an archive file. 543 LLVM_DEBUG(dbgs() << "Parsing library: " << toString(this) << "\n"); 544 file = CHECK(Archive::create(mb), toString(this)); 545 546 // Read the symbol table to construct Lazy symbols. 547 int count = 0; 548 for (const Archive::Symbol &sym : file->symbols()) { 549 symtab->addLazy(this, &sym); 550 ++count; 551 } 552 LLVM_DEBUG(dbgs() << "Read " << count << " symbols\n"); 553 } 554 555 void ArchiveFile::addMember(const Archive::Symbol *sym) { 556 const Archive::Child &c = 557 CHECK(sym->getMember(), 558 "could not get the member for symbol " + sym->getName()); 559 560 // Don't try to load the same member twice (this can happen when members 561 // mutually reference each other). 562 if (!seen.insert(c.getChildOffset()).second) 563 return; 564 565 LLVM_DEBUG(dbgs() << "loading lazy: " << sym->getName() << "\n"); 566 LLVM_DEBUG(dbgs() << "from archive: " << toString(this) << "\n"); 567 568 MemoryBufferRef mb = 569 CHECK(c.getMemoryBufferRef(), 570 "could not get the buffer for the member defining symbol " + 571 sym->getName()); 572 573 InputFile *obj = createObjectFile(mb, getName()); 574 symtab->addFile(obj); 575 } 576 577 static uint8_t mapVisibility(GlobalValue::VisibilityTypes gvVisibility) { 578 switch (gvVisibility) { 579 case GlobalValue::DefaultVisibility: 580 return WASM_SYMBOL_VISIBILITY_DEFAULT; 581 case GlobalValue::HiddenVisibility: 582 case GlobalValue::ProtectedVisibility: 583 return WASM_SYMBOL_VISIBILITY_HIDDEN; 584 } 585 llvm_unreachable("unknown visibility"); 586 } 587 588 static Symbol *createBitcodeSymbol(const std::vector<bool> &keptComdats, 589 const lto::InputFile::Symbol &objSym, 590 BitcodeFile &f) { 591 StringRef name = saver.save(objSym.getName()); 592 593 uint32_t flags = objSym.isWeak() ? WASM_SYMBOL_BINDING_WEAK : 0; 594 flags |= mapVisibility(objSym.getVisibility()); 595 596 int c = objSym.getComdatIndex(); 597 bool excludedByComdat = c != -1 && !keptComdats[c]; 598 599 if (objSym.isUndefined() || excludedByComdat) { 600 flags |= WASM_SYMBOL_UNDEFINED; 601 if (objSym.isExecutable()) 602 return symtab->addUndefinedFunction(name, None, None, flags, &f, nullptr, 603 true); 604 return symtab->addUndefinedData(name, flags, &f); 605 } 606 607 if (objSym.isExecutable()) 608 return symtab->addDefinedFunction(name, flags, &f, nullptr); 609 return symtab->addDefinedData(name, flags, &f, nullptr, 0, 0); 610 } 611 612 bool BitcodeFile::doneLTO = false; 613 614 void BitcodeFile::parse() { 615 if (doneLTO) { 616 error(toString(this) + ": attempt to add bitcode file after LTO."); 617 return; 618 } 619 620 obj = check(lto::InputFile::create(MemoryBufferRef( 621 mb.getBuffer(), saver.save(archiveName + mb.getBufferIdentifier())))); 622 Triple t(obj->getTargetTriple()); 623 if (!t.isWasm()) { 624 error(toString(this) + ": machine type must be wasm32 or wasm64"); 625 return; 626 } 627 checkArch(t.getArch()); 628 std::vector<bool> keptComdats; 629 for (StringRef s : obj->getComdatTable()) 630 keptComdats.push_back(symtab->addComdat(s)); 631 632 for (const lto::InputFile::Symbol &objSym : obj->symbols()) 633 symbols.push_back(createBitcodeSymbol(keptComdats, objSym, *this)); 634 } 635 636 } // namespace wasm 637 } // namespace lld 638