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