1 //===- Writer.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 "Writer.h" 10 #include "Config.h" 11 #include "InputChunks.h" 12 #include "InputElement.h" 13 #include "MapFile.h" 14 #include "OutputSections.h" 15 #include "OutputSegment.h" 16 #include "Relocations.h" 17 #include "SymbolTable.h" 18 #include "SyntheticSections.h" 19 #include "WriterUtils.h" 20 #include "lld/Common/ErrorHandler.h" 21 #include "lld/Common/Memory.h" 22 #include "lld/Common/Strings.h" 23 #include "llvm/ADT/DenseSet.h" 24 #include "llvm/ADT/SmallSet.h" 25 #include "llvm/ADT/SmallVector.h" 26 #include "llvm/ADT/StringMap.h" 27 #include "llvm/BinaryFormat/Wasm.h" 28 #include "llvm/BinaryFormat/WasmTraits.h" 29 #include "llvm/Support/FileOutputBuffer.h" 30 #include "llvm/Support/Format.h" 31 #include "llvm/Support/FormatVariadic.h" 32 #include "llvm/Support/LEB128.h" 33 #include "llvm/Support/Parallel.h" 34 35 #include <cstdarg> 36 #include <map> 37 38 #define DEBUG_TYPE "lld" 39 40 using namespace llvm; 41 using namespace llvm::wasm; 42 43 namespace lld { 44 namespace wasm { 45 static constexpr int stackAlignment = 16; 46 static constexpr int heapAlignment = 16; 47 48 namespace { 49 50 // The writer writes a SymbolTable result to a file. 51 class Writer { 52 public: 53 void run(); 54 55 private: 56 void openFile(); 57 58 bool needsPassiveInitialization(const OutputSegment *segment); 59 bool hasPassiveInitializedSegments(); 60 61 void createSyntheticInitFunctions(); 62 void createInitMemoryFunction(); 63 void createStartFunction(); 64 void createApplyDataRelocationsFunction(); 65 void createApplyGlobalRelocationsFunction(); 66 void createApplyGlobalTLSRelocationsFunction(); 67 void createCallCtorsFunction(); 68 void createInitTLSFunction(); 69 void createCommandExportWrappers(); 70 void createCommandExportWrapper(uint32_t functionIndex, DefinedFunction *f); 71 72 void assignIndexes(); 73 void populateSymtab(); 74 void populateProducers(); 75 void populateTargetFeatures(); 76 void calculateInitFunctions(); 77 void calculateImports(); 78 void calculateExports(); 79 void calculateCustomSections(); 80 void calculateTypes(); 81 void createOutputSegments(); 82 OutputSegment *createOutputSegment(StringRef name); 83 void combineOutputSegments(); 84 void layoutMemory(); 85 void createHeader(); 86 87 void addSection(OutputSection *sec); 88 89 void addSections(); 90 91 void createCustomSections(); 92 void createSyntheticSections(); 93 void createSyntheticSectionsPostLayout(); 94 void finalizeSections(); 95 96 // Custom sections 97 void createRelocSections(); 98 99 void writeHeader(); 100 void writeSections(); 101 102 uint64_t fileSize = 0; 103 104 std::vector<WasmInitEntry> initFunctions; 105 llvm::StringMap<std::vector<InputChunk *>> customSectionMapping; 106 107 // Stable storage for command export wrapper function name strings. 108 std::list<std::string> commandExportWrapperNames; 109 110 // Elements that are used to construct the final output 111 std::string header; 112 std::vector<OutputSection *> outputSections; 113 114 std::unique_ptr<FileOutputBuffer> buffer; 115 116 std::vector<OutputSegment *> segments; 117 llvm::SmallDenseMap<StringRef, OutputSegment *> segmentMap; 118 }; 119 120 } // anonymous namespace 121 122 void Writer::calculateCustomSections() { 123 log("calculateCustomSections"); 124 bool stripDebug = config->stripDebug || config->stripAll; 125 for (ObjFile *file : symtab->objectFiles) { 126 for (InputChunk *section : file->customSections) { 127 // Exclude COMDAT sections that are not selected for inclusion 128 if (section->discarded) 129 continue; 130 StringRef name = section->getName(); 131 // These custom sections are known the linker and synthesized rather than 132 // blindly copied. 133 if (name == "linking" || name == "name" || name == "producers" || 134 name == "target_features" || name.startswith("reloc.")) 135 continue; 136 // These custom sections are generated by `clang -fembed-bitcode`. 137 // These are used by the rust toolchain to ship LTO data along with 138 // compiled object code, but they don't want this included in the linker 139 // output. 140 if (name == ".llvmbc" || name == ".llvmcmd") 141 continue; 142 // Strip debug section in that option was specified. 143 if (stripDebug && name.startswith(".debug_")) 144 continue; 145 // Otherwise include custom sections by default and concatenate their 146 // contents. 147 customSectionMapping[name].push_back(section); 148 } 149 } 150 } 151 152 void Writer::createCustomSections() { 153 log("createCustomSections"); 154 for (auto &pair : customSectionMapping) { 155 StringRef name = pair.first(); 156 LLVM_DEBUG(dbgs() << "createCustomSection: " << name << "\n"); 157 158 OutputSection *sec = make<CustomSection>(std::string(name), pair.second); 159 if (config->relocatable || config->emitRelocs) { 160 auto *sym = make<OutputSectionSymbol>(sec); 161 out.linkingSec->addToSymtab(sym); 162 sec->sectionSym = sym; 163 } 164 addSection(sec); 165 } 166 } 167 168 // Create relocations sections in the final output. 169 // These are only created when relocatable output is requested. 170 void Writer::createRelocSections() { 171 log("createRelocSections"); 172 // Don't use iterator here since we are adding to OutputSection 173 size_t origSize = outputSections.size(); 174 for (size_t i = 0; i < origSize; i++) { 175 LLVM_DEBUG(dbgs() << "check section " << i << "\n"); 176 OutputSection *sec = outputSections[i]; 177 178 // Count the number of needed sections. 179 uint32_t count = sec->getNumRelocations(); 180 if (!count) 181 continue; 182 183 StringRef name; 184 if (sec->type == WASM_SEC_DATA) 185 name = "reloc.DATA"; 186 else if (sec->type == WASM_SEC_CODE) 187 name = "reloc.CODE"; 188 else if (sec->type == WASM_SEC_CUSTOM) 189 name = saver.save("reloc." + sec->name); 190 else 191 llvm_unreachable( 192 "relocations only supported for code, data, or custom sections"); 193 194 addSection(make<RelocSection>(name, sec)); 195 } 196 } 197 198 void Writer::populateProducers() { 199 for (ObjFile *file : symtab->objectFiles) { 200 const WasmProducerInfo &info = file->getWasmObj()->getProducerInfo(); 201 out.producersSec->addInfo(info); 202 } 203 } 204 205 void Writer::writeHeader() { 206 memcpy(buffer->getBufferStart(), header.data(), header.size()); 207 } 208 209 void Writer::writeSections() { 210 uint8_t *buf = buffer->getBufferStart(); 211 parallelForEach(outputSections, [buf](OutputSection *s) { 212 assert(s->isNeeded()); 213 s->writeTo(buf); 214 }); 215 } 216 217 static void setGlobalPtr(DefinedGlobal *g, uint64_t memoryPtr) { 218 g->global->setPointerValue(memoryPtr); 219 } 220 221 // Fix the memory layout of the output binary. This assigns memory offsets 222 // to each of the input data sections as well as the explicit stack region. 223 // The default memory layout is as follows, from low to high. 224 // 225 // - initialized data (starting at Config->globalBase) 226 // - BSS data (not currently implemented in llvm) 227 // - explicit stack (Config->ZStackSize) 228 // - heap start / unallocated 229 // 230 // The --stack-first option means that stack is placed before any static data. 231 // This can be useful since it means that stack overflow traps immediately 232 // rather than overwriting global data, but also increases code size since all 233 // static data loads and stores requires larger offsets. 234 void Writer::layoutMemory() { 235 uint64_t memoryPtr = 0; 236 237 auto placeStack = [&]() { 238 if (config->relocatable || config->isPic) 239 return; 240 memoryPtr = alignTo(memoryPtr, stackAlignment); 241 if (config->zStackSize != alignTo(config->zStackSize, stackAlignment)) 242 error("stack size must be " + Twine(stackAlignment) + "-byte aligned"); 243 log("mem: stack size = " + Twine(config->zStackSize)); 244 log("mem: stack base = " + Twine(memoryPtr)); 245 memoryPtr += config->zStackSize; 246 setGlobalPtr(cast<DefinedGlobal>(WasmSym::stackPointer), memoryPtr); 247 log("mem: stack top = " + Twine(memoryPtr)); 248 }; 249 250 if (config->stackFirst) { 251 placeStack(); 252 } else { 253 memoryPtr = config->globalBase; 254 log("mem: global base = " + Twine(config->globalBase)); 255 } 256 257 if (WasmSym::globalBase) 258 WasmSym::globalBase->setVA(memoryPtr); 259 260 uint64_t dataStart = memoryPtr; 261 262 // Arbitrarily set __dso_handle handle to point to the start of the data 263 // segments. 264 if (WasmSym::dsoHandle) 265 WasmSym::dsoHandle->setVA(dataStart); 266 267 out.dylinkSec->memAlign = 0; 268 for (OutputSegment *seg : segments) { 269 out.dylinkSec->memAlign = std::max(out.dylinkSec->memAlign, seg->alignment); 270 memoryPtr = alignTo(memoryPtr, 1ULL << seg->alignment); 271 seg->startVA = memoryPtr; 272 log(formatv("mem: {0,-15} offset={1,-8} size={2,-8} align={3}", seg->name, 273 memoryPtr, seg->size, seg->alignment)); 274 275 if (!config->relocatable && seg->isTLS()) { 276 if (config->sharedMemory) { 277 auto *tlsSize = cast<DefinedGlobal>(WasmSym::tlsSize); 278 setGlobalPtr(tlsSize, seg->size); 279 280 auto *tlsAlign = cast<DefinedGlobal>(WasmSym::tlsAlign); 281 setGlobalPtr(tlsAlign, int64_t{1} << seg->alignment); 282 } else if (WasmSym::tlsBase) { 283 auto *tlsBase = cast<DefinedGlobal>(WasmSym::tlsBase); 284 setGlobalPtr(tlsBase, memoryPtr); 285 } 286 } 287 288 memoryPtr += seg->size; 289 } 290 291 // Make space for the memory initialization flag 292 if (config->sharedMemory && hasPassiveInitializedSegments()) { 293 memoryPtr = alignTo(memoryPtr, 4); 294 WasmSym::initMemoryFlag = symtab->addSyntheticDataSymbol( 295 "__wasm_init_memory_flag", WASM_SYMBOL_VISIBILITY_HIDDEN); 296 WasmSym::initMemoryFlag->markLive(); 297 WasmSym::initMemoryFlag->setVA(memoryPtr); 298 log(formatv("mem: {0,-15} offset={1,-8} size={2,-8} align={3}", 299 "__wasm_init_memory_flag", memoryPtr, 4, 4)); 300 memoryPtr += 4; 301 } 302 303 if (WasmSym::dataEnd) 304 WasmSym::dataEnd->setVA(memoryPtr); 305 306 uint64_t staticDataSize = memoryPtr - dataStart; 307 log("mem: static data = " + Twine(staticDataSize)); 308 if (config->isPic) 309 out.dylinkSec->memSize = staticDataSize; 310 311 if (!config->stackFirst) 312 placeStack(); 313 314 if (WasmSym::heapBase) { 315 // Set `__heap_base` to follow the end of the stack or global data. The 316 // fact that this comes last means that a malloc/brk implementation can 317 // grow the heap at runtime. 318 // We'll align the heap base here because memory allocators might expect 319 // __heap_base to be aligned already. 320 memoryPtr = alignTo(memoryPtr, heapAlignment); 321 log("mem: heap base = " + Twine(memoryPtr)); 322 WasmSym::heapBase->setVA(memoryPtr); 323 } 324 325 uint64_t maxMemorySetting = 1ULL 326 << (config->is64.getValueOr(false) ? 48 : 32); 327 328 if (config->initialMemory != 0) { 329 if (config->initialMemory != alignTo(config->initialMemory, WasmPageSize)) 330 error("initial memory must be " + Twine(WasmPageSize) + "-byte aligned"); 331 if (memoryPtr > config->initialMemory) 332 error("initial memory too small, " + Twine(memoryPtr) + " bytes needed"); 333 if (config->initialMemory > maxMemorySetting) 334 error("initial memory too large, cannot be greater than " + 335 Twine(maxMemorySetting)); 336 memoryPtr = config->initialMemory; 337 } 338 out.memorySec->numMemoryPages = 339 alignTo(memoryPtr, WasmPageSize) / WasmPageSize; 340 log("mem: total pages = " + Twine(out.memorySec->numMemoryPages)); 341 342 if (config->maxMemory != 0) { 343 if (config->maxMemory != alignTo(config->maxMemory, WasmPageSize)) 344 error("maximum memory must be " + Twine(WasmPageSize) + "-byte aligned"); 345 if (memoryPtr > config->maxMemory) 346 error("maximum memory too small, " + Twine(memoryPtr) + " bytes needed"); 347 if (config->maxMemory > maxMemorySetting) 348 error("maximum memory too large, cannot be greater than " + 349 Twine(maxMemorySetting)); 350 } 351 352 // Check max if explicitly supplied or required by shared memory 353 if (config->maxMemory != 0 || config->sharedMemory) { 354 uint64_t max = config->maxMemory; 355 if (max == 0) { 356 // If no maxMemory config was supplied but we are building with 357 // shared memory, we need to pick a sensible upper limit. 358 if (config->isPic) 359 max = maxMemorySetting; 360 else 361 max = alignTo(memoryPtr, WasmPageSize); 362 } 363 out.memorySec->maxMemoryPages = max / WasmPageSize; 364 log("mem: max pages = " + Twine(out.memorySec->maxMemoryPages)); 365 } 366 } 367 368 void Writer::addSection(OutputSection *sec) { 369 if (!sec->isNeeded()) 370 return; 371 log("addSection: " + toString(*sec)); 372 sec->sectionIndex = outputSections.size(); 373 outputSections.push_back(sec); 374 } 375 376 // If a section name is valid as a C identifier (which is rare because of 377 // the leading '.'), linkers are expected to define __start_<secname> and 378 // __stop_<secname> symbols. They are at beginning and end of the section, 379 // respectively. This is not requested by the ELF standard, but GNU ld and 380 // gold provide the feature, and used by many programs. 381 static void addStartStopSymbols(const OutputSegment *seg) { 382 StringRef name = seg->name; 383 if (!isValidCIdentifier(name)) 384 return; 385 LLVM_DEBUG(dbgs() << "addStartStopSymbols: " << name << "\n"); 386 uint64_t start = seg->startVA; 387 uint64_t stop = start + seg->size; 388 symtab->addOptionalDataSymbol(saver.save("__start_" + name), start); 389 symtab->addOptionalDataSymbol(saver.save("__stop_" + name), stop); 390 } 391 392 void Writer::addSections() { 393 addSection(out.dylinkSec); 394 addSection(out.typeSec); 395 addSection(out.importSec); 396 addSection(out.functionSec); 397 addSection(out.tableSec); 398 addSection(out.memorySec); 399 addSection(out.tagSec); 400 addSection(out.globalSec); 401 addSection(out.exportSec); 402 addSection(out.startSec); 403 addSection(out.elemSec); 404 addSection(out.dataCountSec); 405 406 addSection(make<CodeSection>(out.functionSec->inputFunctions)); 407 addSection(make<DataSection>(segments)); 408 409 createCustomSections(); 410 411 addSection(out.linkingSec); 412 if (config->emitRelocs || config->relocatable) { 413 createRelocSections(); 414 } 415 416 addSection(out.nameSec); 417 addSection(out.producersSec); 418 addSection(out.targetFeaturesSec); 419 } 420 421 void Writer::finalizeSections() { 422 for (OutputSection *s : outputSections) { 423 s->setOffset(fileSize); 424 s->finalizeContents(); 425 fileSize += s->getSize(); 426 } 427 } 428 429 void Writer::populateTargetFeatures() { 430 StringMap<std::string> used; 431 StringMap<std::string> required; 432 StringMap<std::string> disallowed; 433 SmallSet<std::string, 8> &allowed = out.targetFeaturesSec->features; 434 bool tlsUsed = false; 435 436 // Only infer used features if user did not specify features 437 bool inferFeatures = !config->features.hasValue(); 438 439 if (!inferFeatures) { 440 auto &explicitFeatures = config->features.getValue(); 441 allowed.insert(explicitFeatures.begin(), explicitFeatures.end()); 442 if (!config->checkFeatures) 443 return; 444 } 445 446 // Find the sets of used, required, and disallowed features 447 for (ObjFile *file : symtab->objectFiles) { 448 StringRef fileName(file->getName()); 449 for (auto &feature : file->getWasmObj()->getTargetFeatures()) { 450 switch (feature.Prefix) { 451 case WASM_FEATURE_PREFIX_USED: 452 used.insert({feature.Name, std::string(fileName)}); 453 break; 454 case WASM_FEATURE_PREFIX_REQUIRED: 455 used.insert({feature.Name, std::string(fileName)}); 456 required.insert({feature.Name, std::string(fileName)}); 457 break; 458 case WASM_FEATURE_PREFIX_DISALLOWED: 459 disallowed.insert({feature.Name, std::string(fileName)}); 460 break; 461 default: 462 error("Unrecognized feature policy prefix " + 463 std::to_string(feature.Prefix)); 464 } 465 } 466 467 // Find TLS data segments 468 auto isTLS = [](InputChunk *segment) { 469 return segment->live && segment->isTLS(); 470 }; 471 tlsUsed = tlsUsed || 472 std::any_of(file->segments.begin(), file->segments.end(), isTLS); 473 } 474 475 if (inferFeatures) 476 for (const auto &key : used.keys()) 477 allowed.insert(std::string(key)); 478 479 if (!config->checkFeatures) 480 return; 481 482 if (!config->relocatable && allowed.count("mutable-globals") == 0) { 483 for (const Symbol *sym : out.importSec->importedSymbols) { 484 if (auto *global = dyn_cast<GlobalSymbol>(sym)) { 485 if (global->getGlobalType()->Mutable) { 486 error(Twine("mutable global imported but 'mutable-globals' feature " 487 "not present in inputs: `") + 488 toString(*sym) + "`. Use --no-check-features to suppress."); 489 } 490 } 491 } 492 for (const Symbol *sym : out.exportSec->exportedSymbols) { 493 if (isa<GlobalSymbol>(sym)) { 494 error(Twine("mutable global exported but 'mutable-globals' feature " 495 "not present in inputs: `") + 496 toString(*sym) + "`. Use --no-check-features to suppress."); 497 } 498 } 499 } 500 501 if (config->sharedMemory) { 502 if (disallowed.count("shared-mem")) 503 error("--shared-memory is disallowed by " + disallowed["shared-mem"] + 504 " because it was not compiled with 'atomics' or 'bulk-memory' " 505 "features."); 506 507 for (auto feature : {"atomics", "bulk-memory"}) 508 if (!allowed.count(feature)) 509 error(StringRef("'") + feature + 510 "' feature must be used in order to use shared memory"); 511 } 512 513 if (tlsUsed) { 514 for (auto feature : {"atomics", "bulk-memory"}) 515 if (!allowed.count(feature)) 516 error(StringRef("'") + feature + 517 "' feature must be used in order to use thread-local storage"); 518 } 519 520 // Validate that used features are allowed in output 521 if (!inferFeatures) { 522 for (const auto &feature : used.keys()) { 523 if (!allowed.count(std::string(feature))) 524 error(Twine("Target feature '") + feature + "' used by " + 525 used[feature] + " is not allowed."); 526 } 527 } 528 529 // Validate the required and disallowed constraints for each file 530 for (ObjFile *file : symtab->objectFiles) { 531 StringRef fileName(file->getName()); 532 SmallSet<std::string, 8> objectFeatures; 533 for (const auto &feature : file->getWasmObj()->getTargetFeatures()) { 534 if (feature.Prefix == WASM_FEATURE_PREFIX_DISALLOWED) 535 continue; 536 objectFeatures.insert(feature.Name); 537 if (disallowed.count(feature.Name)) 538 error(Twine("Target feature '") + feature.Name + "' used in " + 539 fileName + " is disallowed by " + disallowed[feature.Name] + 540 ". Use --no-check-features to suppress."); 541 } 542 for (const auto &feature : required.keys()) { 543 if (!objectFeatures.count(std::string(feature))) 544 error(Twine("Missing target feature '") + feature + "' in " + fileName + 545 ", required by " + required[feature] + 546 ". Use --no-check-features to suppress."); 547 } 548 } 549 } 550 551 static bool shouldImport(Symbol *sym) { 552 // We don't generate imports for data symbols. They however can be imported 553 // as GOT entries. 554 if (isa<DataSymbol>(sym)) 555 return false; 556 if (!sym->isLive()) 557 return false; 558 if (!sym->isUsedInRegularObj) 559 return false; 560 561 // When a symbol is weakly defined in a shared library we need to allow 562 // it to be overridden by another module so need to both import 563 // and export the symbol. 564 if (config->shared && sym->isDefined() && sym->isWeak()) 565 return true; 566 if (!sym->isUndefined()) 567 return false; 568 if (sym->isWeak() && !config->relocatable && !config->isPic) 569 return false; 570 571 // In PIC mode we only need to import functions when they are called directly. 572 // Indirect usage all goes via GOT imports. 573 if (config->isPic) { 574 if (auto *f = dyn_cast<UndefinedFunction>(sym)) 575 if (!f->isCalledDirectly) 576 return false; 577 } 578 579 if (config->isPic || config->relocatable || config->importUndefined) 580 return true; 581 if (config->allowUndefinedSymbols.count(sym->getName()) != 0) 582 return true; 583 584 return sym->importName.hasValue(); 585 } 586 587 void Writer::calculateImports() { 588 // Some inputs require that the indirect function table be assigned to table 589 // number 0, so if it is present and is an import, allocate it before any 590 // other tables. 591 if (WasmSym::indirectFunctionTable && 592 shouldImport(WasmSym::indirectFunctionTable)) 593 out.importSec->addImport(WasmSym::indirectFunctionTable); 594 595 for (Symbol *sym : symtab->getSymbols()) { 596 if (!shouldImport(sym)) 597 continue; 598 if (sym == WasmSym::indirectFunctionTable) 599 continue; 600 LLVM_DEBUG(dbgs() << "import: " << sym->getName() << "\n"); 601 out.importSec->addImport(sym); 602 } 603 } 604 605 void Writer::calculateExports() { 606 if (config->relocatable) 607 return; 608 609 if (!config->relocatable && !config->importMemory) 610 out.exportSec->exports.push_back( 611 WasmExport{"memory", WASM_EXTERNAL_MEMORY, 0}); 612 613 unsigned globalIndex = 614 out.importSec->getNumImportedGlobals() + out.globalSec->numGlobals(); 615 616 for (Symbol *sym : symtab->getSymbols()) { 617 if (!sym->isExported()) 618 continue; 619 if (!sym->isLive()) 620 continue; 621 622 StringRef name = sym->getName(); 623 WasmExport export_; 624 if (auto *f = dyn_cast<DefinedFunction>(sym)) { 625 if (Optional<StringRef> exportName = f->function->getExportName()) { 626 name = *exportName; 627 } 628 export_ = {name, WASM_EXTERNAL_FUNCTION, f->getExportedFunctionIndex()}; 629 } else if (auto *g = dyn_cast<DefinedGlobal>(sym)) { 630 if (g->getGlobalType()->Mutable && !g->getFile() && !g->forceExport) { 631 // Avoid exporting mutable globals are linker synthesized (e.g. 632 // __stack_pointer or __tls_base) unless they are explicitly exported 633 // from the command line. 634 // Without this check `--export-all` would cause any program using the 635 // stack pointer to export a mutable global even if none of the input 636 // files were built with the `mutable-globals` feature. 637 continue; 638 } 639 export_ = {name, WASM_EXTERNAL_GLOBAL, g->getGlobalIndex()}; 640 } else if (auto *t = dyn_cast<DefinedTag>(sym)) { 641 export_ = {name, WASM_EXTERNAL_TAG, t->getTagIndex()}; 642 } else if (auto *d = dyn_cast<DefinedData>(sym)) { 643 out.globalSec->dataAddressGlobals.push_back(d); 644 export_ = {name, WASM_EXTERNAL_GLOBAL, globalIndex++}; 645 } else { 646 auto *t = cast<DefinedTable>(sym); 647 export_ = {name, WASM_EXTERNAL_TABLE, t->getTableNumber()}; 648 } 649 650 LLVM_DEBUG(dbgs() << "Export: " << name << "\n"); 651 out.exportSec->exports.push_back(export_); 652 out.exportSec->exportedSymbols.push_back(sym); 653 } 654 } 655 656 void Writer::populateSymtab() { 657 if (!config->relocatable && !config->emitRelocs) 658 return; 659 660 for (Symbol *sym : symtab->getSymbols()) 661 if (sym->isUsedInRegularObj && sym->isLive()) 662 out.linkingSec->addToSymtab(sym); 663 664 for (ObjFile *file : symtab->objectFiles) { 665 LLVM_DEBUG(dbgs() << "Local symtab entries: " << file->getName() << "\n"); 666 for (Symbol *sym : file->getSymbols()) 667 if (sym->isLocal() && !isa<SectionSymbol>(sym) && sym->isLive()) 668 out.linkingSec->addToSymtab(sym); 669 } 670 } 671 672 void Writer::calculateTypes() { 673 // The output type section is the union of the following sets: 674 // 1. Any signature used in the TYPE relocation 675 // 2. The signatures of all imported functions 676 // 3. The signatures of all defined functions 677 // 4. The signatures of all imported tags 678 // 5. The signatures of all defined tags 679 680 for (ObjFile *file : symtab->objectFiles) { 681 ArrayRef<WasmSignature> types = file->getWasmObj()->types(); 682 for (uint32_t i = 0; i < types.size(); i++) 683 if (file->typeIsUsed[i]) 684 file->typeMap[i] = out.typeSec->registerType(types[i]); 685 } 686 687 for (const Symbol *sym : out.importSec->importedSymbols) { 688 if (auto *f = dyn_cast<FunctionSymbol>(sym)) 689 out.typeSec->registerType(*f->signature); 690 else if (auto *t = dyn_cast<TagSymbol>(sym)) 691 out.typeSec->registerType(*t->signature); 692 } 693 694 for (const InputFunction *f : out.functionSec->inputFunctions) 695 out.typeSec->registerType(f->signature); 696 697 for (const InputTag *t : out.tagSec->inputTags) 698 out.typeSec->registerType(t->signature); 699 } 700 701 // In a command-style link, create a wrapper for each exported symbol 702 // which calls the constructors and destructors. 703 void Writer::createCommandExportWrappers() { 704 // This logic doesn't currently support Emscripten-style PIC mode. 705 assert(!config->isPic); 706 707 // If there are no ctors and there's no libc `__wasm_call_dtors` to 708 // call, don't wrap the exports. 709 if (initFunctions.empty() && WasmSym::callDtors == NULL) 710 return; 711 712 std::vector<DefinedFunction *> toWrap; 713 714 for (Symbol *sym : symtab->getSymbols()) 715 if (sym->isExported()) 716 if (auto *f = dyn_cast<DefinedFunction>(sym)) 717 toWrap.push_back(f); 718 719 for (auto *f : toWrap) { 720 auto funcNameStr = (f->getName() + ".command_export").str(); 721 commandExportWrapperNames.push_back(funcNameStr); 722 const std::string &funcName = commandExportWrapperNames.back(); 723 724 auto func = make<SyntheticFunction>(*f->getSignature(), funcName); 725 if (f->function->getExportName().hasValue()) 726 func->setExportName(f->function->getExportName()->str()); 727 else 728 func->setExportName(f->getName().str()); 729 730 DefinedFunction *def = 731 symtab->addSyntheticFunction(funcName, f->flags, func); 732 def->markLive(); 733 734 def->flags |= WASM_SYMBOL_EXPORTED; 735 def->flags &= ~WASM_SYMBOL_VISIBILITY_HIDDEN; 736 def->forceExport = f->forceExport; 737 738 f->flags |= WASM_SYMBOL_VISIBILITY_HIDDEN; 739 f->flags &= ~WASM_SYMBOL_EXPORTED; 740 f->forceExport = false; 741 742 out.functionSec->addFunction(func); 743 744 createCommandExportWrapper(f->getFunctionIndex(), def); 745 } 746 } 747 748 static void finalizeIndirectFunctionTable() { 749 if (!WasmSym::indirectFunctionTable) 750 return; 751 752 if (shouldImport(WasmSym::indirectFunctionTable) && 753 !WasmSym::indirectFunctionTable->hasTableNumber()) { 754 // Processing -Bsymbolic relocations resulted in a late requirement that the 755 // indirect function table be present, and we are running in --import-table 756 // mode. Add the table now to the imports section. Otherwise it will be 757 // added to the tables section later in assignIndexes. 758 out.importSec->addImport(WasmSym::indirectFunctionTable); 759 } 760 761 uint32_t tableSize = config->tableBase + out.elemSec->numEntries(); 762 WasmLimits limits = {0, tableSize, 0}; 763 if (WasmSym::indirectFunctionTable->isDefined() && !config->growableTable) { 764 limits.Flags |= WASM_LIMITS_FLAG_HAS_MAX; 765 limits.Maximum = limits.Minimum; 766 } 767 WasmSym::indirectFunctionTable->setLimits(limits); 768 } 769 770 static void scanRelocations() { 771 for (ObjFile *file : symtab->objectFiles) { 772 LLVM_DEBUG(dbgs() << "scanRelocations: " << file->getName() << "\n"); 773 for (InputChunk *chunk : file->functions) 774 scanRelocations(chunk); 775 for (InputChunk *chunk : file->segments) 776 scanRelocations(chunk); 777 for (auto &p : file->customSections) 778 scanRelocations(p); 779 } 780 } 781 782 void Writer::assignIndexes() { 783 // Seal the import section, since other index spaces such as function and 784 // global are effected by the number of imports. 785 out.importSec->seal(); 786 787 for (InputFunction *func : symtab->syntheticFunctions) 788 out.functionSec->addFunction(func); 789 790 for (ObjFile *file : symtab->objectFiles) { 791 LLVM_DEBUG(dbgs() << "Functions: " << file->getName() << "\n"); 792 for (InputFunction *func : file->functions) 793 out.functionSec->addFunction(func); 794 } 795 796 for (InputGlobal *global : symtab->syntheticGlobals) 797 out.globalSec->addGlobal(global); 798 799 for (ObjFile *file : symtab->objectFiles) { 800 LLVM_DEBUG(dbgs() << "Globals: " << file->getName() << "\n"); 801 for (InputGlobal *global : file->globals) 802 out.globalSec->addGlobal(global); 803 } 804 805 for (ObjFile *file : symtab->objectFiles) { 806 LLVM_DEBUG(dbgs() << "Tags: " << file->getName() << "\n"); 807 for (InputTag *tag : file->tags) 808 out.tagSec->addTag(tag); 809 } 810 811 for (ObjFile *file : symtab->objectFiles) { 812 LLVM_DEBUG(dbgs() << "Tables: " << file->getName() << "\n"); 813 for (InputTable *table : file->tables) 814 out.tableSec->addTable(table); 815 } 816 817 for (InputTable *table : symtab->syntheticTables) 818 out.tableSec->addTable(table); 819 820 out.globalSec->assignIndexes(); 821 out.tableSec->assignIndexes(); 822 } 823 824 static StringRef getOutputDataSegmentName(const InputChunk &seg) { 825 // We always merge .tbss and .tdata into a single TLS segment so all TLS 826 // symbols are be relative to single __tls_base. 827 if (seg.isTLS()) 828 return ".tdata"; 829 StringRef name = seg.getName(); 830 if (!config->mergeDataSegments) 831 return name; 832 if (name.startswith(".text.")) 833 return ".text"; 834 if (name.startswith(".data.")) 835 return ".data"; 836 if (name.startswith(".bss.")) 837 return ".bss"; 838 if (name.startswith(".rodata.")) 839 return ".rodata"; 840 return name; 841 } 842 843 OutputSegment *Writer::createOutputSegment(StringRef name) { 844 LLVM_DEBUG(dbgs() << "new segment: " << name << "\n"); 845 OutputSegment *s = make<OutputSegment>(name); 846 if (config->sharedMemory) 847 s->initFlags = WASM_DATA_SEGMENT_IS_PASSIVE; 848 // Exported memories are guaranteed to be zero-initialized, so no need 849 // to emit data segments for bss sections. 850 // TODO: consider initializing bss sections with memory.fill 851 // instructions when memory is imported and bulk-memory is available. 852 if (!config->importMemory && !config->relocatable && name.startswith(".bss")) 853 s->isBss = true; 854 segments.push_back(s); 855 return s; 856 } 857 858 void Writer::createOutputSegments() { 859 for (ObjFile *file : symtab->objectFiles) { 860 for (InputChunk *segment : file->segments) { 861 if (!segment->live) 862 continue; 863 StringRef name = getOutputDataSegmentName(*segment); 864 OutputSegment *s = nullptr; 865 // When running in relocatable mode we can't merge segments that are part 866 // of comdat groups since the ultimate linker needs to be able exclude or 867 // include them individually. 868 if (config->relocatable && !segment->getComdatName().empty()) { 869 s = createOutputSegment(name); 870 } else { 871 if (segmentMap.count(name) == 0) 872 segmentMap[name] = createOutputSegment(name); 873 s = segmentMap[name]; 874 } 875 s->addInputSegment(segment); 876 } 877 } 878 879 // Sort segments by type, placing .bss last 880 std::stable_sort(segments.begin(), segments.end(), 881 [](const OutputSegment *a, const OutputSegment *b) { 882 auto order = [](StringRef name) { 883 return StringSwitch<int>(name) 884 .StartsWith(".tdata", 0) 885 .StartsWith(".rodata", 1) 886 .StartsWith(".data", 2) 887 .StartsWith(".bss", 4) 888 .Default(3); 889 }; 890 return order(a->name) < order(b->name); 891 }); 892 893 for (size_t i = 0; i < segments.size(); ++i) 894 segments[i]->index = i; 895 896 // Merge MergeInputSections into a single MergeSyntheticSection. 897 LLVM_DEBUG(dbgs() << "-- finalize input semgments\n"); 898 for (OutputSegment *seg : segments) 899 seg->finalizeInputSegments(); 900 } 901 902 void Writer::combineOutputSegments() { 903 // With PIC code we currently only support a single active data segment since 904 // we only have a single __memory_base to use as our base address. This pass 905 // combines all data segments into a single .data segment. 906 // This restructions can be relaxed once we have extended constant 907 // expressions available: 908 // https://github.com/WebAssembly/extended-const 909 assert(config->isPic && !config->sharedMemory); 910 if (segments.size() <= 1) 911 return; 912 OutputSegment *combined = make<OutputSegment>(".data"); 913 combined->startVA = segments[0]->startVA; 914 for (OutputSegment *s : segments) { 915 bool first = true; 916 for (InputChunk *inSeg : s->inputSegments) { 917 if (first) 918 inSeg->alignment = std::max(inSeg->alignment, s->alignment); 919 first = false; 920 #ifndef NDEBUG 921 uint64_t oldVA = inSeg->getVA(); 922 #endif 923 combined->addInputSegment(inSeg); 924 #ifndef NDEBUG 925 uint64_t newVA = inSeg->getVA(); 926 LLVM_DEBUG(dbgs() << "added input segment. name=" << inSeg->getName() 927 << " oldVA=" << oldVA << " newVA=" << newVA << "\n"); 928 assert(oldVA == newVA); 929 #endif 930 } 931 } 932 933 segments = {combined}; 934 } 935 936 static void createFunction(DefinedFunction *func, StringRef bodyContent) { 937 std::string functionBody; 938 { 939 raw_string_ostream os(functionBody); 940 writeUleb128(os, bodyContent.size(), "function size"); 941 os << bodyContent; 942 } 943 ArrayRef<uint8_t> body = arrayRefFromStringRef(saver.save(functionBody)); 944 cast<SyntheticFunction>(func->function)->setBody(body); 945 } 946 947 bool Writer::needsPassiveInitialization(const OutputSegment *segment) { 948 return segment->initFlags & WASM_DATA_SEGMENT_IS_PASSIVE && 949 !segment->isTLS() && !segment->isBss; 950 } 951 952 bool Writer::hasPassiveInitializedSegments() { 953 return std::find_if(segments.begin(), segments.end(), 954 [this](const OutputSegment *s) { 955 return this->needsPassiveInitialization(s); 956 }) != segments.end(); 957 } 958 959 void Writer::createSyntheticInitFunctions() { 960 if (config->relocatable) 961 return; 962 963 static WasmSignature nullSignature = {{}, {}}; 964 965 // Passive segments are used to avoid memory being reinitialized on each 966 // thread's instantiation. These passive segments are initialized and 967 // dropped in __wasm_init_memory, which is registered as the start function 968 if (config->sharedMemory && hasPassiveInitializedSegments()) { 969 WasmSym::initMemory = symtab->addSyntheticFunction( 970 "__wasm_init_memory", WASM_SYMBOL_VISIBILITY_HIDDEN, 971 make<SyntheticFunction>(nullSignature, "__wasm_init_memory")); 972 WasmSym::initMemory->markLive(); 973 } 974 975 if (config->isPic) { 976 // For PIC code we create synthetic functions that apply relocations. 977 // These get called from __wasm_call_ctors before the user-level 978 // constructors. 979 WasmSym::applyDataRelocs = symtab->addSyntheticFunction( 980 "__wasm_apply_data_relocs", WASM_SYMBOL_VISIBILITY_HIDDEN, 981 make<SyntheticFunction>(nullSignature, "__wasm_apply_data_relocs")); 982 WasmSym::applyDataRelocs->markLive(); 983 984 if (out.globalSec->needsRelocations()) { 985 WasmSym::applyGlobalRelocs = symtab->addSyntheticFunction( 986 "__wasm_apply_global_relocs", WASM_SYMBOL_VISIBILITY_HIDDEN, 987 make<SyntheticFunction>(nullSignature, "__wasm_apply_global_relocs")); 988 WasmSym::applyGlobalRelocs->markLive(); 989 if (config->sharedMemory) { 990 WasmSym::applyGlobalTLSRelocs = symtab->addSyntheticFunction( 991 "__wasm_apply_global_tls_relocs", WASM_SYMBOL_VISIBILITY_HIDDEN, 992 make<SyntheticFunction>(nullSignature, 993 "__wasm_apply_global_tls_relocs")); 994 WasmSym::applyGlobalTLSRelocs->markLive(); 995 } 996 } 997 } 998 999 if (WasmSym::applyGlobalRelocs && WasmSym::initMemory) { 1000 WasmSym::startFunction = symtab->addSyntheticFunction( 1001 "__wasm_start", WASM_SYMBOL_VISIBILITY_HIDDEN, 1002 make<SyntheticFunction>(nullSignature, "__wasm_start")); 1003 WasmSym::startFunction->markLive(); 1004 } 1005 } 1006 1007 void Writer::createInitMemoryFunction() { 1008 LLVM_DEBUG(dbgs() << "createInitMemoryFunction\n"); 1009 assert(WasmSym::initMemory); 1010 assert(WasmSym::initMemoryFlag); 1011 assert(hasPassiveInitializedSegments()); 1012 uint64_t flagAddress = WasmSym::initMemoryFlag->getVA(); 1013 bool is64 = config->is64.getValueOr(false); 1014 std::string bodyContent; 1015 { 1016 raw_string_ostream os(bodyContent); 1017 // Initialize memory in a thread-safe manner. The thread that successfully 1018 // increments the flag from 0 to 1 is is responsible for performing the 1019 // memory initialization. Other threads go sleep on the flag until the 1020 // first thread finishing initializing memory, increments the flag to 2, 1021 // and wakes all the other threads. Once the flag has been set to 2, 1022 // subsequently started threads will skip the sleep. All threads 1023 // unconditionally drop their passive data segments once memory has been 1024 // initialized. The generated code is as follows: 1025 // 1026 // (func $__wasm_init_memory 1027 // (block $drop 1028 // (block $wait 1029 // (block $init 1030 // (br_table $init $wait $drop 1031 // (i32.atomic.rmw.cmpxchg align=2 offset=0 1032 // (i32.const $__init_memory_flag) 1033 // (i32.const 0) 1034 // (i32.const 1) 1035 // ) 1036 // ) 1037 // ) ;; $init 1038 // ( ... initialize data segments ... ) 1039 // (i32.atomic.store align=2 offset=0 1040 // (i32.const $__init_memory_flag) 1041 // (i32.const 2) 1042 // ) 1043 // (drop 1044 // (i32.atomic.notify align=2 offset=0 1045 // (i32.const $__init_memory_flag) 1046 // (i32.const -1u) 1047 // ) 1048 // ) 1049 // (br $drop) 1050 // ) ;; $wait 1051 // (drop 1052 // (i32.atomic.wait align=2 offset=0 1053 // (i32.const $__init_memory_flag) 1054 // (i32.const 1) 1055 // (i32.const -1) 1056 // ) 1057 // ) 1058 // ) ;; $drop 1059 // ( ... drop data segments ... ) 1060 // ) 1061 // 1062 // When we are building with PIC, calculate the flag location using: 1063 // 1064 // (global.get $__memory_base) 1065 // (i32.const $__init_memory_flag) 1066 // (i32.const 1) 1067 1068 // With PIC code we cache the flag address in local 0 1069 if (config->isPic) { 1070 writeUleb128(os, 1, "num local decls"); 1071 writeUleb128(os, 1, "local count"); 1072 writeU8(os, is64 ? WASM_TYPE_I64 : WASM_TYPE_I32, "address type"); 1073 writeU8(os, WASM_OPCODE_GLOBAL_GET, "GLOBAL_GET"); 1074 writeUleb128(os, WasmSym::memoryBase->getGlobalIndex(), "memory_base"); 1075 writePtrConst(os, flagAddress, is64, "flag address"); 1076 writeU8(os, is64 ? WASM_OPCODE_I64_ADD : WASM_OPCODE_I32_ADD, "add"); 1077 writeU8(os, WASM_OPCODE_LOCAL_SET, "local.set"); 1078 writeUleb128(os, 0, "local 0"); 1079 } else { 1080 writeUleb128(os, 0, "num locals"); 1081 } 1082 1083 auto writeGetFlagAddress = [&]() { 1084 if (config->isPic) { 1085 writeU8(os, WASM_OPCODE_LOCAL_GET, "local.get"); 1086 writeUleb128(os, 0, "local 0"); 1087 } else { 1088 writePtrConst(os, flagAddress, is64, "flag address"); 1089 } 1090 }; 1091 1092 // Set up destination blocks 1093 writeU8(os, WASM_OPCODE_BLOCK, "block $drop"); 1094 writeU8(os, WASM_TYPE_NORESULT, "block type"); 1095 writeU8(os, WASM_OPCODE_BLOCK, "block $wait"); 1096 writeU8(os, WASM_TYPE_NORESULT, "block type"); 1097 writeU8(os, WASM_OPCODE_BLOCK, "block $init"); 1098 writeU8(os, WASM_TYPE_NORESULT, "block type"); 1099 1100 // Atomically check whether we win the race. 1101 writeGetFlagAddress(); 1102 writeI32Const(os, 0, "expected flag value"); 1103 writeI32Const(os, 1, "new flag value"); 1104 writeU8(os, WASM_OPCODE_ATOMICS_PREFIX, "atomics prefix"); 1105 writeUleb128(os, WASM_OPCODE_I32_RMW_CMPXCHG, "i32.atomic.rmw.cmpxchg"); 1106 writeMemArg(os, 2, 0); 1107 1108 // Based on the value, decide what to do next. 1109 writeU8(os, WASM_OPCODE_BR_TABLE, "br_table"); 1110 writeUleb128(os, 2, "label vector length"); 1111 writeUleb128(os, 0, "label $init"); 1112 writeUleb128(os, 1, "label $wait"); 1113 writeUleb128(os, 2, "default label $drop"); 1114 1115 // Initialize passive data segments 1116 writeU8(os, WASM_OPCODE_END, "end $init"); 1117 for (const OutputSegment *s : segments) { 1118 if (needsPassiveInitialization(s)) { 1119 // destination address 1120 writePtrConst(os, s->startVA, is64, "destination address"); 1121 if (config->isPic) { 1122 writeU8(os, WASM_OPCODE_GLOBAL_GET, "GLOBAL_GET"); 1123 writeUleb128(os, WasmSym::memoryBase->getGlobalIndex(), 1124 "memory_base"); 1125 writeU8(os, is64 ? WASM_OPCODE_I64_ADD : WASM_OPCODE_I32_ADD, 1126 "i32.add"); 1127 } 1128 // source segment offset 1129 writeI32Const(os, 0, "segment offset"); 1130 // memory region size 1131 writeI32Const(os, s->size, "memory region size"); 1132 // memory.init instruction 1133 writeU8(os, WASM_OPCODE_MISC_PREFIX, "bulk-memory prefix"); 1134 writeUleb128(os, WASM_OPCODE_MEMORY_INIT, "memory.init"); 1135 writeUleb128(os, s->index, "segment index immediate"); 1136 writeU8(os, 0, "memory index immediate"); 1137 } 1138 } 1139 1140 // Set flag to 2 to mark end of initialization 1141 writeGetFlagAddress(); 1142 writeI32Const(os, 2, "flag value"); 1143 writeU8(os, WASM_OPCODE_ATOMICS_PREFIX, "atomics prefix"); 1144 writeUleb128(os, WASM_OPCODE_I32_ATOMIC_STORE, "i32.atomic.store"); 1145 writeMemArg(os, 2, 0); 1146 1147 // Notify any waiters that memory initialization is complete 1148 writeGetFlagAddress(); 1149 writeI32Const(os, -1, "number of waiters"); 1150 writeU8(os, WASM_OPCODE_ATOMICS_PREFIX, "atomics prefix"); 1151 writeUleb128(os, WASM_OPCODE_ATOMIC_NOTIFY, "atomic.notify"); 1152 writeMemArg(os, 2, 0); 1153 writeU8(os, WASM_OPCODE_DROP, "drop"); 1154 1155 // Branch to drop the segments 1156 writeU8(os, WASM_OPCODE_BR, "br"); 1157 writeUleb128(os, 1, "label $drop"); 1158 1159 // Wait for the winning thread to initialize memory 1160 writeU8(os, WASM_OPCODE_END, "end $wait"); 1161 writeGetFlagAddress(); 1162 writeI32Const(os, 1, "expected flag value"); 1163 writeI64Const(os, -1, "timeout"); 1164 1165 writeU8(os, WASM_OPCODE_ATOMICS_PREFIX, "atomics prefix"); 1166 writeUleb128(os, WASM_OPCODE_I32_ATOMIC_WAIT, "i32.atomic.wait"); 1167 writeMemArg(os, 2, 0); 1168 writeU8(os, WASM_OPCODE_DROP, "drop"); 1169 1170 // Unconditionally drop passive data segments 1171 writeU8(os, WASM_OPCODE_END, "end $drop"); 1172 for (const OutputSegment *s : segments) { 1173 if (needsPassiveInitialization(s)) { 1174 // data.drop instruction 1175 writeU8(os, WASM_OPCODE_MISC_PREFIX, "bulk-memory prefix"); 1176 writeUleb128(os, WASM_OPCODE_DATA_DROP, "data.drop"); 1177 writeUleb128(os, s->index, "segment index immediate"); 1178 } 1179 } 1180 1181 // End the function 1182 writeU8(os, WASM_OPCODE_END, "END"); 1183 } 1184 1185 createFunction(WasmSym::initMemory, bodyContent); 1186 } 1187 1188 void Writer::createStartFunction() { 1189 if (WasmSym::startFunction) { 1190 std::string bodyContent; 1191 { 1192 raw_string_ostream os(bodyContent); 1193 writeUleb128(os, 0, "num locals"); 1194 writeU8(os, WASM_OPCODE_CALL, "CALL"); 1195 writeUleb128(os, WasmSym::initMemory->getFunctionIndex(), 1196 "function index"); 1197 writeU8(os, WASM_OPCODE_CALL, "CALL"); 1198 writeUleb128(os, WasmSym::applyGlobalRelocs->getFunctionIndex(), 1199 "function index"); 1200 writeU8(os, WASM_OPCODE_END, "END"); 1201 } 1202 createFunction(WasmSym::startFunction, bodyContent); 1203 } else if (WasmSym::initMemory) { 1204 WasmSym::startFunction = WasmSym::initMemory; 1205 } else if (WasmSym::applyGlobalRelocs) { 1206 WasmSym::startFunction = WasmSym::applyGlobalRelocs; 1207 } 1208 } 1209 1210 // For -shared (PIC) output, we create create a synthetic function which will 1211 // apply any relocations to the data segments on startup. This function is 1212 // called `__wasm_apply_data_relocs` and is added at the beginning of 1213 // `__wasm_call_ctors` before any of the constructors run. 1214 void Writer::createApplyDataRelocationsFunction() { 1215 LLVM_DEBUG(dbgs() << "createApplyDataRelocationsFunction\n"); 1216 // First write the body's contents to a string. 1217 std::string bodyContent; 1218 { 1219 raw_string_ostream os(bodyContent); 1220 writeUleb128(os, 0, "num locals"); 1221 for (const OutputSegment *seg : segments) 1222 for (const InputChunk *inSeg : seg->inputSegments) 1223 inSeg->generateRelocationCode(os); 1224 1225 writeU8(os, WASM_OPCODE_END, "END"); 1226 } 1227 1228 createFunction(WasmSym::applyDataRelocs, bodyContent); 1229 } 1230 1231 // Similar to createApplyDataRelocationsFunction but generates relocation code 1232 // fro WebAssembly globals. Because these globals are not shared between threads 1233 // these relocation need to run on every thread. 1234 void Writer::createApplyGlobalRelocationsFunction() { 1235 // First write the body's contents to a string. 1236 std::string bodyContent; 1237 { 1238 raw_string_ostream os(bodyContent); 1239 writeUleb128(os, 0, "num locals"); 1240 out.globalSec->generateRelocationCode(os, false); 1241 writeU8(os, WASM_OPCODE_END, "END"); 1242 } 1243 1244 createFunction(WasmSym::applyGlobalRelocs, bodyContent); 1245 } 1246 1247 // Similar to createApplyGlobalRelocationsFunction but for 1248 // TLS symbols. This cannot be run during the start function 1249 // but must be delayed until __wasm_init_tls is called. 1250 void Writer::createApplyGlobalTLSRelocationsFunction() { 1251 // First write the body's contents to a string. 1252 std::string bodyContent; 1253 { 1254 raw_string_ostream os(bodyContent); 1255 writeUleb128(os, 0, "num locals"); 1256 out.globalSec->generateRelocationCode(os, true); 1257 writeU8(os, WASM_OPCODE_END, "END"); 1258 } 1259 1260 createFunction(WasmSym::applyGlobalTLSRelocs, bodyContent); 1261 } 1262 1263 // Create synthetic "__wasm_call_ctors" function based on ctor functions 1264 // in input object. 1265 void Writer::createCallCtorsFunction() { 1266 // If __wasm_call_ctors isn't referenced, there aren't any ctors, and we 1267 // aren't calling `__wasm_apply_data_relocs` for Emscripten-style PIC, don't 1268 // define the `__wasm_call_ctors` function. 1269 if (!WasmSym::callCtors->isLive() && !WasmSym::applyDataRelocs && 1270 initFunctions.empty()) 1271 return; 1272 1273 // First write the body's contents to a string. 1274 std::string bodyContent; 1275 { 1276 raw_string_ostream os(bodyContent); 1277 writeUleb128(os, 0, "num locals"); 1278 1279 if (WasmSym::applyDataRelocs) { 1280 writeU8(os, WASM_OPCODE_CALL, "CALL"); 1281 writeUleb128(os, WasmSym::applyDataRelocs->getFunctionIndex(), 1282 "function index"); 1283 } 1284 1285 // Call constructors 1286 for (const WasmInitEntry &f : initFunctions) { 1287 writeU8(os, WASM_OPCODE_CALL, "CALL"); 1288 writeUleb128(os, f.sym->getFunctionIndex(), "function index"); 1289 for (size_t i = 0; i < f.sym->signature->Returns.size(); i++) { 1290 writeU8(os, WASM_OPCODE_DROP, "DROP"); 1291 } 1292 } 1293 1294 writeU8(os, WASM_OPCODE_END, "END"); 1295 } 1296 1297 createFunction(WasmSym::callCtors, bodyContent); 1298 } 1299 1300 // Create a wrapper around a function export which calls the 1301 // static constructors and destructors. 1302 void Writer::createCommandExportWrapper(uint32_t functionIndex, 1303 DefinedFunction *f) { 1304 // First write the body's contents to a string. 1305 std::string bodyContent; 1306 { 1307 raw_string_ostream os(bodyContent); 1308 writeUleb128(os, 0, "num locals"); 1309 1310 // Call `__wasm_call_ctors` which call static constructors (and 1311 // applies any runtime relocations in Emscripten-style PIC mode) 1312 if (WasmSym::callCtors->isLive()) { 1313 writeU8(os, WASM_OPCODE_CALL, "CALL"); 1314 writeUleb128(os, WasmSym::callCtors->getFunctionIndex(), 1315 "function index"); 1316 } 1317 1318 // Call the user's code, leaving any return values on the operand stack. 1319 for (size_t i = 0; i < f->signature->Params.size(); ++i) { 1320 writeU8(os, WASM_OPCODE_LOCAL_GET, "local.get"); 1321 writeUleb128(os, i, "local index"); 1322 } 1323 writeU8(os, WASM_OPCODE_CALL, "CALL"); 1324 writeUleb128(os, functionIndex, "function index"); 1325 1326 // Call the function that calls the destructors. 1327 if (DefinedFunction *callDtors = WasmSym::callDtors) { 1328 writeU8(os, WASM_OPCODE_CALL, "CALL"); 1329 writeUleb128(os, callDtors->getFunctionIndex(), "function index"); 1330 } 1331 1332 // End the function, returning the return values from the user's code. 1333 writeU8(os, WASM_OPCODE_END, "END"); 1334 } 1335 1336 createFunction(f, bodyContent); 1337 } 1338 1339 void Writer::createInitTLSFunction() { 1340 std::string bodyContent; 1341 { 1342 raw_string_ostream os(bodyContent); 1343 1344 OutputSegment *tlsSeg = nullptr; 1345 for (auto *seg : segments) { 1346 if (seg->name == ".tdata") { 1347 tlsSeg = seg; 1348 break; 1349 } 1350 } 1351 1352 writeUleb128(os, 0, "num locals"); 1353 if (tlsSeg) { 1354 writeU8(os, WASM_OPCODE_LOCAL_GET, "local.get"); 1355 writeUleb128(os, 0, "local index"); 1356 1357 writeU8(os, WASM_OPCODE_GLOBAL_SET, "global.set"); 1358 writeUleb128(os, WasmSym::tlsBase->getGlobalIndex(), "global index"); 1359 1360 // FIXME(wvo): this local needs to be I64 in wasm64, or we need an extend op. 1361 writeU8(os, WASM_OPCODE_LOCAL_GET, "local.get"); 1362 writeUleb128(os, 0, "local index"); 1363 1364 writeI32Const(os, 0, "segment offset"); 1365 1366 writeI32Const(os, tlsSeg->size, "memory region size"); 1367 1368 writeU8(os, WASM_OPCODE_MISC_PREFIX, "bulk-memory prefix"); 1369 writeUleb128(os, WASM_OPCODE_MEMORY_INIT, "MEMORY.INIT"); 1370 writeUleb128(os, tlsSeg->index, "segment index immediate"); 1371 writeU8(os, 0, "memory index immediate"); 1372 } 1373 1374 if (WasmSym::applyGlobalTLSRelocs) { 1375 writeU8(os, WASM_OPCODE_CALL, "CALL"); 1376 writeUleb128(os, WasmSym::applyGlobalTLSRelocs->getFunctionIndex(), 1377 "function index"); 1378 } 1379 writeU8(os, WASM_OPCODE_END, "end function"); 1380 } 1381 1382 createFunction(WasmSym::initTLS, bodyContent); 1383 } 1384 1385 // Populate InitFunctions vector with init functions from all input objects. 1386 // This is then used either when creating the output linking section or to 1387 // synthesize the "__wasm_call_ctors" function. 1388 void Writer::calculateInitFunctions() { 1389 if (!config->relocatable && !WasmSym::callCtors->isLive()) 1390 return; 1391 1392 for (ObjFile *file : symtab->objectFiles) { 1393 const WasmLinkingData &l = file->getWasmObj()->linkingData(); 1394 for (const WasmInitFunc &f : l.InitFunctions) { 1395 FunctionSymbol *sym = file->getFunctionSymbol(f.Symbol); 1396 // comdat exclusions can cause init functions be discarded. 1397 if (sym->isDiscarded() || !sym->isLive()) 1398 continue; 1399 if (sym->signature->Params.size() != 0) 1400 error("constructor functions cannot take arguments: " + toString(*sym)); 1401 LLVM_DEBUG(dbgs() << "initFunctions: " << toString(*sym) << "\n"); 1402 initFunctions.emplace_back(WasmInitEntry{sym, f.Priority}); 1403 } 1404 } 1405 1406 // Sort in order of priority (lowest first) so that they are called 1407 // in the correct order. 1408 llvm::stable_sort(initFunctions, 1409 [](const WasmInitEntry &l, const WasmInitEntry &r) { 1410 return l.priority < r.priority; 1411 }); 1412 } 1413 1414 void Writer::createSyntheticSections() { 1415 out.dylinkSec = make<DylinkSection>(); 1416 out.typeSec = make<TypeSection>(); 1417 out.importSec = make<ImportSection>(); 1418 out.functionSec = make<FunctionSection>(); 1419 out.tableSec = make<TableSection>(); 1420 out.memorySec = make<MemorySection>(); 1421 out.tagSec = make<TagSection>(); 1422 out.globalSec = make<GlobalSection>(); 1423 out.exportSec = make<ExportSection>(); 1424 out.startSec = make<StartSection>(); 1425 out.elemSec = make<ElemSection>(); 1426 out.producersSec = make<ProducersSection>(); 1427 out.targetFeaturesSec = make<TargetFeaturesSection>(); 1428 } 1429 1430 void Writer::createSyntheticSectionsPostLayout() { 1431 out.dataCountSec = make<DataCountSection>(segments); 1432 out.linkingSec = make<LinkingSection>(initFunctions, segments); 1433 out.nameSec = make<NameSection>(segments); 1434 } 1435 1436 void Writer::run() { 1437 if (config->relocatable || config->isPic) 1438 config->globalBase = 0; 1439 1440 // For PIC code the table base is assigned dynamically by the loader. 1441 // For non-PIC, we start at 1 so that accessing table index 0 always traps. 1442 if (!config->isPic) { 1443 config->tableBase = 1; 1444 if (WasmSym::definedTableBase) 1445 WasmSym::definedTableBase->setVA(config->tableBase); 1446 if (WasmSym::definedTableBase32) 1447 WasmSym::definedTableBase32->setVA(config->tableBase); 1448 } 1449 1450 log("-- createOutputSegments"); 1451 createOutputSegments(); 1452 log("-- createSyntheticSections"); 1453 createSyntheticSections(); 1454 log("-- layoutMemory"); 1455 layoutMemory(); 1456 1457 if (!config->relocatable) { 1458 // Create linker synthesized __start_SECNAME/__stop_SECNAME symbols 1459 // This has to be done after memory layout is performed. 1460 for (const OutputSegment *seg : segments) { 1461 addStartStopSymbols(seg); 1462 } 1463 } 1464 1465 for (auto &pair : config->exportedSymbols) { 1466 Symbol *sym = symtab->find(pair.first()); 1467 if (sym && sym->isDefined()) 1468 sym->forceExport = true; 1469 } 1470 1471 // Delay reporting error about explict exports until after addStartStopSymbols 1472 // which can create optional symbols. 1473 for (auto &name : config->requiredExports) { 1474 Symbol *sym = symtab->find(name); 1475 if (!sym || !sym->isDefined()) { 1476 if (config->unresolvedSymbols == UnresolvedPolicy::ReportError) 1477 error(Twine("symbol exported via --export not found: ") + name); 1478 if (config->unresolvedSymbols == UnresolvedPolicy::Warn) 1479 warn(Twine("symbol exported via --export not found: ") + name); 1480 } 1481 } 1482 1483 if (config->isPic && !config->sharedMemory) { 1484 // In shared memory mode all data segments are passive and initilized 1485 // via __wasm_init_memory. 1486 log("-- combineOutputSegments"); 1487 combineOutputSegments(); 1488 } 1489 1490 log("-- createSyntheticSectionsPostLayout"); 1491 createSyntheticSectionsPostLayout(); 1492 log("-- populateProducers"); 1493 populateProducers(); 1494 log("-- calculateImports"); 1495 calculateImports(); 1496 log("-- scanRelocations"); 1497 scanRelocations(); 1498 log("-- finalizeIndirectFunctionTable"); 1499 finalizeIndirectFunctionTable(); 1500 log("-- createSyntheticInitFunctions"); 1501 createSyntheticInitFunctions(); 1502 log("-- assignIndexes"); 1503 assignIndexes(); 1504 log("-- calculateInitFunctions"); 1505 calculateInitFunctions(); 1506 1507 if (!config->relocatable) { 1508 // Create linker synthesized functions 1509 if (WasmSym::applyDataRelocs) 1510 createApplyDataRelocationsFunction(); 1511 if (WasmSym::applyGlobalRelocs) 1512 createApplyGlobalRelocationsFunction(); 1513 if (WasmSym::applyGlobalTLSRelocs) 1514 createApplyGlobalTLSRelocationsFunction(); 1515 if (WasmSym::initMemory) 1516 createInitMemoryFunction(); 1517 createStartFunction(); 1518 1519 createCallCtorsFunction(); 1520 1521 // Create export wrappers for commands if needed. 1522 // 1523 // If the input contains a call to `__wasm_call_ctors`, either in one of 1524 // the input objects or an explicit export from the command-line, we 1525 // assume ctors and dtors are taken care of already. 1526 if (!config->relocatable && !config->isPic && 1527 !WasmSym::callCtors->isUsedInRegularObj && 1528 !WasmSym::callCtors->isExported()) { 1529 log("-- createCommandExportWrappers"); 1530 createCommandExportWrappers(); 1531 } 1532 } 1533 1534 if (WasmSym::initTLS && WasmSym::initTLS->isLive()) 1535 createInitTLSFunction(); 1536 1537 if (errorCount()) 1538 return; 1539 1540 log("-- calculateTypes"); 1541 calculateTypes(); 1542 log("-- calculateExports"); 1543 calculateExports(); 1544 log("-- calculateCustomSections"); 1545 calculateCustomSections(); 1546 log("-- populateSymtab"); 1547 populateSymtab(); 1548 log("-- populateTargetFeatures"); 1549 populateTargetFeatures(); 1550 log("-- addSections"); 1551 addSections(); 1552 1553 if (errorHandler().verbose) { 1554 log("Defined Functions: " + Twine(out.functionSec->inputFunctions.size())); 1555 log("Defined Globals : " + Twine(out.globalSec->numGlobals())); 1556 log("Defined Tags : " + Twine(out.tagSec->inputTags.size())); 1557 log("Defined Tables : " + Twine(out.tableSec->inputTables.size())); 1558 log("Function Imports : " + 1559 Twine(out.importSec->getNumImportedFunctions())); 1560 log("Global Imports : " + Twine(out.importSec->getNumImportedGlobals())); 1561 log("Tag Imports : " + Twine(out.importSec->getNumImportedTags())); 1562 log("Table Imports : " + Twine(out.importSec->getNumImportedTables())); 1563 } 1564 1565 createHeader(); 1566 log("-- finalizeSections"); 1567 finalizeSections(); 1568 1569 log("-- writeMapFile"); 1570 writeMapFile(outputSections); 1571 1572 log("-- openFile"); 1573 openFile(); 1574 if (errorCount()) 1575 return; 1576 1577 writeHeader(); 1578 1579 log("-- writeSections"); 1580 writeSections(); 1581 if (errorCount()) 1582 return; 1583 1584 if (Error e = buffer->commit()) 1585 fatal("failed to write the output file: " + toString(std::move(e))); 1586 } 1587 1588 // Open a result file. 1589 void Writer::openFile() { 1590 log("writing: " + config->outputFile); 1591 1592 Expected<std::unique_ptr<FileOutputBuffer>> bufferOrErr = 1593 FileOutputBuffer::create(config->outputFile, fileSize, 1594 FileOutputBuffer::F_executable); 1595 1596 if (!bufferOrErr) 1597 error("failed to open " + config->outputFile + ": " + 1598 toString(bufferOrErr.takeError())); 1599 else 1600 buffer = std::move(*bufferOrErr); 1601 } 1602 1603 void Writer::createHeader() { 1604 raw_string_ostream os(header); 1605 writeBytes(os, WasmMagic, sizeof(WasmMagic), "wasm magic"); 1606 writeU32(os, WasmVersion, "wasm version"); 1607 os.flush(); 1608 fileSize += header.size(); 1609 } 1610 1611 void writeResult() { Writer().run(); } 1612 1613 } // namespace wasm 1614 } // namespace lld 1615