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