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