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 unsigned globalIndex = 610 out.importSec->getNumImportedGlobals() + out.globalSec->numGlobals(); 611 612 for (Symbol *sym : symtab->getSymbols()) { 613 if (!sym->isExported()) 614 continue; 615 if (!sym->isLive()) 616 continue; 617 618 StringRef name = sym->getName(); 619 WasmExport export_; 620 if (auto *f = dyn_cast<DefinedFunction>(sym)) { 621 if (Optional<StringRef> exportName = f->function->getExportName()) { 622 name = *exportName; 623 } 624 export_ = {name, WASM_EXTERNAL_FUNCTION, f->getFunctionIndex()}; 625 } else if (auto *g = dyn_cast<DefinedGlobal>(sym)) { 626 if (g->getGlobalType()->Mutable && !g->getFile() && !g->forceExport) { 627 // Avoid exporting mutable globals are linker synthesized (e.g. 628 // __stack_pointer or __tls_base) unless they are explicitly exported 629 // from the command line. 630 // Without this check `--export-all` would cause any program using the 631 // stack pointer to export a mutable global even if none of the input 632 // files were built with the `mutable-globals` feature. 633 continue; 634 } 635 export_ = {name, WASM_EXTERNAL_GLOBAL, g->getGlobalIndex()}; 636 } else if (auto *e = dyn_cast<DefinedEvent>(sym)) { 637 export_ = {name, WASM_EXTERNAL_EVENT, e->getEventIndex()}; 638 } else if (auto *d = dyn_cast<DefinedData>(sym)) { 639 out.globalSec->dataAddressGlobals.push_back(d); 640 export_ = {name, WASM_EXTERNAL_GLOBAL, globalIndex++}; 641 } else { 642 auto *t = cast<DefinedTable>(sym); 643 export_ = {name, WASM_EXTERNAL_TABLE, t->getTableNumber()}; 644 } 645 646 LLVM_DEBUG(dbgs() << "Export: " << name << "\n"); 647 out.exportSec->exports.push_back(export_); 648 out.exportSec->exportedSymbols.push_back(sym); 649 } 650 } 651 652 void Writer::populateSymtab() { 653 if (!config->relocatable && !config->emitRelocs) 654 return; 655 656 for (Symbol *sym : symtab->getSymbols()) 657 if (sym->isUsedInRegularObj && sym->isLive()) 658 out.linkingSec->addToSymtab(sym); 659 660 for (ObjFile *file : symtab->objectFiles) { 661 LLVM_DEBUG(dbgs() << "Local symtab entries: " << file->getName() << "\n"); 662 for (Symbol *sym : file->getSymbols()) 663 if (sym->isLocal() && !isa<SectionSymbol>(sym) && sym->isLive()) 664 out.linkingSec->addToSymtab(sym); 665 } 666 } 667 668 void Writer::calculateTypes() { 669 // The output type section is the union of the following sets: 670 // 1. Any signature used in the TYPE relocation 671 // 2. The signatures of all imported functions 672 // 3. The signatures of all defined functions 673 // 4. The signatures of all imported events 674 // 5. The signatures of all defined events 675 676 for (ObjFile *file : symtab->objectFiles) { 677 ArrayRef<WasmSignature> types = file->getWasmObj()->types(); 678 for (uint32_t i = 0; i < types.size(); i++) 679 if (file->typeIsUsed[i]) 680 file->typeMap[i] = out.typeSec->registerType(types[i]); 681 } 682 683 for (const Symbol *sym : out.importSec->importedSymbols) { 684 if (auto *f = dyn_cast<FunctionSymbol>(sym)) 685 out.typeSec->registerType(*f->signature); 686 else if (auto *e = dyn_cast<EventSymbol>(sym)) 687 out.typeSec->registerType(*e->signature); 688 } 689 690 for (const InputFunction *f : out.functionSec->inputFunctions) 691 out.typeSec->registerType(f->signature); 692 693 for (const InputEvent *e : out.eventSec->inputEvents) 694 out.typeSec->registerType(e->signature); 695 } 696 697 // In a command-style link, create a wrapper for each exported symbol 698 // which calls the constructors and destructors. 699 void Writer::createCommandExportWrappers() { 700 // This logic doesn't currently support Emscripten-style PIC mode. 701 assert(!config->isPic); 702 703 // If there are no ctors and there's no libc `__wasm_call_dtors` to 704 // call, don't wrap the exports. 705 if (initFunctions.empty() && WasmSym::callDtors == NULL) 706 return; 707 708 std::vector<DefinedFunction *> toWrap; 709 710 for (Symbol *sym : symtab->getSymbols()) 711 if (sym->isExported()) 712 if (auto *f = dyn_cast<DefinedFunction>(sym)) 713 toWrap.push_back(f); 714 715 for (auto *f : toWrap) { 716 auto funcNameStr = (f->getName() + ".command_export").str(); 717 commandExportWrapperNames.push_back(funcNameStr); 718 const std::string &funcName = commandExportWrapperNames.back(); 719 720 auto func = make<SyntheticFunction>(*f->getSignature(), funcName); 721 if (f->function->getExportName().hasValue()) 722 func->setExportName(f->function->getExportName()->str()); 723 else 724 func->setExportName(f->getName().str()); 725 726 DefinedFunction *def = 727 symtab->addSyntheticFunction(funcName, f->flags, func); 728 def->markLive(); 729 730 def->flags |= WASM_SYMBOL_EXPORTED; 731 def->flags &= ~WASM_SYMBOL_VISIBILITY_HIDDEN; 732 def->forceExport = f->forceExport; 733 734 f->flags |= WASM_SYMBOL_VISIBILITY_HIDDEN; 735 f->flags &= ~WASM_SYMBOL_EXPORTED; 736 f->forceExport = false; 737 738 out.functionSec->addFunction(func); 739 740 createCommandExportWrapper(f->getFunctionIndex(), def); 741 } 742 } 743 744 static void finalizeIndirectFunctionTable() { 745 if (!WasmSym::indirectFunctionTable) 746 return; 747 748 uint32_t tableSize = config->tableBase + out.elemSec->numEntries(); 749 WasmLimits limits = {0, tableSize, 0}; 750 if (WasmSym::indirectFunctionTable->isDefined() && !config->growableTable) { 751 limits.Flags |= WASM_LIMITS_FLAG_HAS_MAX; 752 limits.Maximum = limits.Initial; 753 } 754 WasmSym::indirectFunctionTable->setLimits(limits); 755 } 756 757 static void scanRelocations() { 758 for (ObjFile *file : symtab->objectFiles) { 759 LLVM_DEBUG(dbgs() << "scanRelocations: " << file->getName() << "\n"); 760 for (InputChunk *chunk : file->functions) 761 scanRelocations(chunk); 762 for (InputChunk *chunk : file->segments) 763 scanRelocations(chunk); 764 for (auto &p : file->customSections) 765 scanRelocations(p); 766 } 767 } 768 769 void Writer::assignIndexes() { 770 // Seal the import section, since other index spaces such as function and 771 // global are effected by the number of imports. 772 out.importSec->seal(); 773 774 for (InputFunction *func : symtab->syntheticFunctions) 775 out.functionSec->addFunction(func); 776 777 for (ObjFile *file : symtab->objectFiles) { 778 LLVM_DEBUG(dbgs() << "Functions: " << file->getName() << "\n"); 779 for (InputFunction *func : file->functions) 780 out.functionSec->addFunction(func); 781 } 782 783 for (InputGlobal *global : symtab->syntheticGlobals) 784 out.globalSec->addGlobal(global); 785 786 for (ObjFile *file : symtab->objectFiles) { 787 LLVM_DEBUG(dbgs() << "Globals: " << file->getName() << "\n"); 788 for (InputGlobal *global : file->globals) 789 out.globalSec->addGlobal(global); 790 } 791 792 for (ObjFile *file : symtab->objectFiles) { 793 LLVM_DEBUG(dbgs() << "Events: " << file->getName() << "\n"); 794 for (InputEvent *event : file->events) 795 out.eventSec->addEvent(event); 796 } 797 798 for (ObjFile *file : symtab->objectFiles) { 799 LLVM_DEBUG(dbgs() << "Tables: " << file->getName() << "\n"); 800 for (InputTable *table : file->tables) 801 out.tableSec->addTable(table); 802 } 803 804 for (InputTable *table : symtab->syntheticTables) 805 out.tableSec->addTable(table); 806 807 out.globalSec->assignIndexes(); 808 } 809 810 static StringRef getOutputDataSegmentName(StringRef name) { 811 // We only support one thread-local segment, so we must merge the segments 812 // despite --no-merge-data-segments. 813 // We also need to merge .tbss into .tdata so they share the same offsets. 814 if (name.startswith(".tdata") || name.startswith(".tbss")) 815 return ".tdata"; 816 // With PIC code we currently only support a single data segment since 817 // we only have a single __memory_base to use as our base address. 818 if (config->isPic) 819 return ".data"; 820 if (!config->mergeDataSegments) 821 return name; 822 if (name.startswith(".text.")) 823 return ".text"; 824 if (name.startswith(".data.")) 825 return ".data"; 826 if (name.startswith(".bss.")) 827 return ".bss"; 828 if (name.startswith(".rodata.")) 829 return ".rodata"; 830 return name; 831 } 832 833 void Writer::createOutputSegments() { 834 for (ObjFile *file : symtab->objectFiles) { 835 for (InputSegment *segment : file->segments) { 836 if (!segment->live) 837 continue; 838 StringRef name = getOutputDataSegmentName(segment->getName()); 839 OutputSegment *&s = segmentMap[name]; 840 if (s == nullptr) { 841 LLVM_DEBUG(dbgs() << "new segment: " << name << "\n"); 842 s = make<OutputSegment>(name); 843 if (config->sharedMemory) 844 s->initFlags = WASM_DATA_SEGMENT_IS_PASSIVE; 845 // Exported memories are guaranteed to be zero-initialized, so no need 846 // to emit data segments for bss sections. 847 // TODO: consider initializing bss sections with memory.fill 848 // instructions when memory is imported and bulk-memory is available. 849 if (!config->importMemory && !config->relocatable && 850 name.startswith(".bss")) 851 s->isBss = true; 852 segments.push_back(s); 853 } 854 s->addInputSegment(segment); 855 LLVM_DEBUG(dbgs() << "added data: " << name << ": " << s->size << "\n"); 856 } 857 } 858 859 // Sort segments by type, placing .bss last 860 std::stable_sort(segments.begin(), segments.end(), 861 [](const OutputSegment *a, const OutputSegment *b) { 862 auto order = [](StringRef name) { 863 return StringSwitch<int>(name) 864 .StartsWith(".rodata", 0) 865 .StartsWith(".data", 1) 866 .StartsWith(".tdata", 2) 867 .StartsWith(".bss", 4) 868 .Default(3); 869 }; 870 return order(a->name) < order(b->name); 871 }); 872 873 for (size_t i = 0; i < segments.size(); ++i) 874 segments[i]->index = i; 875 } 876 877 static void createFunction(DefinedFunction *func, StringRef bodyContent) { 878 std::string functionBody; 879 { 880 raw_string_ostream os(functionBody); 881 writeUleb128(os, bodyContent.size(), "function size"); 882 os << bodyContent; 883 } 884 ArrayRef<uint8_t> body = arrayRefFromStringRef(saver.save(functionBody)); 885 cast<SyntheticFunction>(func->function)->setBody(body); 886 } 887 888 bool Writer::needsPassiveInitialization(const OutputSegment *segment) { 889 return segment->initFlags & WASM_DATA_SEGMENT_IS_PASSIVE && 890 segment->name != ".tdata" && !segment->isBss; 891 } 892 893 bool Writer::hasPassiveInitializedSegments() { 894 return std::find_if(segments.begin(), segments.end(), 895 [this](const OutputSegment *s) { 896 return this->needsPassiveInitialization(s); 897 }) != segments.end(); 898 } 899 900 void Writer::createSyntheticInitFunctions() { 901 if (config->relocatable) 902 return; 903 904 static WasmSignature nullSignature = {{}, {}}; 905 906 // Passive segments are used to avoid memory being reinitialized on each 907 // thread's instantiation. These passive segments are initialized and 908 // dropped in __wasm_init_memory, which is registered as the start function 909 if (config->sharedMemory && hasPassiveInitializedSegments()) { 910 WasmSym::initMemory = symtab->addSyntheticFunction( 911 "__wasm_init_memory", WASM_SYMBOL_VISIBILITY_HIDDEN, 912 make<SyntheticFunction>(nullSignature, "__wasm_init_memory")); 913 WasmSym::initMemory->markLive(); 914 } 915 916 if (config->isPic) { 917 // For PIC code we create synthetic functions that apply relocations. 918 // These get called from __wasm_call_ctors before the user-level 919 // constructors. 920 WasmSym::applyDataRelocs = symtab->addSyntheticFunction( 921 "__wasm_apply_data_relocs", WASM_SYMBOL_VISIBILITY_HIDDEN, 922 make<SyntheticFunction>(nullSignature, "__wasm_apply_data_relocs")); 923 WasmSym::applyDataRelocs->markLive(); 924 925 if (out.globalSec->needsRelocations()) { 926 WasmSym::applyGlobalRelocs = symtab->addSyntheticFunction( 927 "__wasm_apply_global_relocs", WASM_SYMBOL_VISIBILITY_HIDDEN, 928 make<SyntheticFunction>(nullSignature, "__wasm_apply_global_relocs")); 929 WasmSym::applyGlobalRelocs->markLive(); 930 } 931 } 932 933 if (WasmSym::applyGlobalRelocs && WasmSym::initMemory) { 934 WasmSym::startFunction = symtab->addSyntheticFunction( 935 "__wasm_start", WASM_SYMBOL_VISIBILITY_HIDDEN, 936 make<SyntheticFunction>(nullSignature, "__wasm_start")); 937 WasmSym::startFunction->markLive(); 938 } 939 } 940 941 void Writer::createInitMemoryFunction() { 942 LLVM_DEBUG(dbgs() << "createInitMemoryFunction\n"); 943 assert(WasmSym::initMemory); 944 assert(WasmSym::initMemoryFlag); 945 assert(hasPassiveInitializedSegments()); 946 uint64_t flagAddress = WasmSym::initMemoryFlag->getVirtualAddress(); 947 bool is64 = config->is64.getValueOr(false); 948 std::string bodyContent; 949 { 950 raw_string_ostream os(bodyContent); 951 // Initialize memory in a thread-safe manner. The thread that successfully 952 // increments the flag from 0 to 1 is is responsible for performing the 953 // memory initialization. Other threads go sleep on the flag until the 954 // first thread finishing initializing memory, increments the flag to 2, 955 // and wakes all the other threads. Once the flag has been set to 2, 956 // subsequently started threads will skip the sleep. All threads 957 // unconditionally drop their passive data segments once memory has been 958 // initialized. The generated code is as follows: 959 // 960 // (func $__wasm_init_memory 961 // (if 962 // (i32.atomic.rmw.cmpxchg align=2 offset=0 963 // (i32.const $__init_memory_flag) 964 // (i32.const 0) 965 // (i32.const 1) 966 // ) 967 // (then 968 // (drop 969 // (i32.atomic.wait align=2 offset=0 970 // (i32.const $__init_memory_flag) 971 // (i32.const 1) 972 // (i32.const -1) 973 // ) 974 // ) 975 // ) 976 // (else 977 // ( ... initialize data segments ... ) 978 // (i32.atomic.store align=2 offset=0 979 // (i32.const $__init_memory_flag) 980 // (i32.const 2) 981 // ) 982 // (drop 983 // (i32.atomic.notify align=2 offset=0 984 // (i32.const $__init_memory_flag) 985 // (i32.const -1u) 986 // ) 987 // ) 988 // ) 989 // ) 990 // ( ... drop data segments ... ) 991 // ) 992 // 993 // When we are building with PIC, calculate the flag location using: 994 // 995 // (global.get $__memory_base) 996 // (i32.const $__init_memory_flag) 997 // (i32.const 1) 998 999 // With PIC code we cache the flag address in local 0 1000 if (config->isPic) { 1001 writeUleb128(os, 1, "num local decls"); 1002 writeUleb128(os, 1, "local count"); 1003 writeU8(os, is64 ? WASM_TYPE_I64 : WASM_TYPE_I32, "address type"); 1004 writeU8(os, WASM_OPCODE_GLOBAL_GET, "GLOBAL_GET"); 1005 writeUleb128(os, WasmSym::memoryBase->getGlobalIndex(), "memory_base"); 1006 writePtrConst(os, flagAddress, is64, "flag address"); 1007 writeU8(os, WASM_OPCODE_I32_ADD, "add"); 1008 writeU8(os, WASM_OPCODE_LOCAL_SET, "local.set"); 1009 writeUleb128(os, 0, "local 0"); 1010 } else { 1011 writeUleb128(os, 0, "num locals"); 1012 } 1013 1014 auto writeGetFlagAddress = [&]() { 1015 if (config->isPic) { 1016 writeU8(os, WASM_OPCODE_LOCAL_GET, "local.get"); 1017 writeUleb128(os, 0, "local 0"); 1018 } else { 1019 writePtrConst(os, flagAddress, is64, "flag address"); 1020 } 1021 }; 1022 1023 // Atomically check whether this is the main thread. 1024 writeGetFlagAddress(); 1025 writeI32Const(os, 0, "expected flag value"); 1026 writeI32Const(os, 1, "flag value"); 1027 writeU8(os, WASM_OPCODE_ATOMICS_PREFIX, "atomics prefix"); 1028 writeUleb128(os, WASM_OPCODE_I32_RMW_CMPXCHG, "i32.atomic.rmw.cmpxchg"); 1029 writeMemArg(os, 2, 0); 1030 writeU8(os, WASM_OPCODE_IF, "IF"); 1031 writeU8(os, WASM_TYPE_NORESULT, "blocktype"); 1032 1033 // Did not increment 0, so wait for main thread to initialize memory 1034 writeGetFlagAddress(); 1035 writeI32Const(os, 1, "expected flag value"); 1036 writeI64Const(os, -1, "timeout"); 1037 1038 writeU8(os, WASM_OPCODE_ATOMICS_PREFIX, "atomics prefix"); 1039 writeUleb128(os, WASM_OPCODE_I32_ATOMIC_WAIT, "i32.atomic.wait"); 1040 writeMemArg(os, 2, 0); 1041 writeU8(os, WASM_OPCODE_DROP, "drop"); 1042 1043 writeU8(os, WASM_OPCODE_ELSE, "ELSE"); 1044 1045 // Did increment 0, so conditionally initialize passive data segments 1046 for (const OutputSegment *s : segments) { 1047 if (needsPassiveInitialization(s)) { 1048 // destination address 1049 writePtrConst(os, s->startVA, is64, "destination address"); 1050 if (config->isPic) { 1051 writeU8(os, WASM_OPCODE_GLOBAL_GET, "GLOBAL_GET"); 1052 writeUleb128(os, WasmSym::memoryBase->getGlobalIndex(), 1053 "memory_base"); 1054 writeU8(os, WASM_OPCODE_I32_ADD, "i32.add"); 1055 } 1056 // source segment offset 1057 writeI32Const(os, 0, "segment offset"); 1058 // memory region size 1059 writeI32Const(os, s->size, "memory region size"); 1060 // memory.init instruction 1061 writeU8(os, WASM_OPCODE_MISC_PREFIX, "bulk-memory prefix"); 1062 writeUleb128(os, WASM_OPCODE_MEMORY_INIT, "memory.init"); 1063 writeUleb128(os, s->index, "segment index immediate"); 1064 writeU8(os, 0, "memory index immediate"); 1065 } 1066 } 1067 1068 // Set flag to 2 to mark end of initialization 1069 writeGetFlagAddress(); 1070 writeI32Const(os, 2, "flag value"); 1071 writeU8(os, WASM_OPCODE_ATOMICS_PREFIX, "atomics prefix"); 1072 writeUleb128(os, WASM_OPCODE_I32_ATOMIC_STORE, "i32.atomic.store"); 1073 writeMemArg(os, 2, 0); 1074 1075 // Notify any waiters that memory initialization is complete 1076 writeGetFlagAddress(); 1077 writeI32Const(os, -1, "number of waiters"); 1078 writeU8(os, WASM_OPCODE_ATOMICS_PREFIX, "atomics prefix"); 1079 writeUleb128(os, WASM_OPCODE_ATOMIC_NOTIFY, "atomic.notify"); 1080 writeMemArg(os, 2, 0); 1081 writeU8(os, WASM_OPCODE_DROP, "drop"); 1082 1083 writeU8(os, WASM_OPCODE_END, "END"); 1084 1085 // Unconditionally drop passive data segments 1086 for (const OutputSegment *s : segments) { 1087 if (needsPassiveInitialization(s)) { 1088 // data.drop instruction 1089 writeU8(os, WASM_OPCODE_MISC_PREFIX, "bulk-memory prefix"); 1090 writeUleb128(os, WASM_OPCODE_DATA_DROP, "data.drop"); 1091 writeUleb128(os, s->index, "segment index immediate"); 1092 } 1093 } 1094 writeU8(os, WASM_OPCODE_END, "END"); 1095 } 1096 1097 createFunction(WasmSym::initMemory, bodyContent); 1098 } 1099 1100 void Writer::createStartFunction() { 1101 if (WasmSym::startFunction) { 1102 std::string bodyContent; 1103 { 1104 raw_string_ostream os(bodyContent); 1105 writeUleb128(os, 0, "num locals"); 1106 writeU8(os, WASM_OPCODE_CALL, "CALL"); 1107 writeUleb128(os, WasmSym::initMemory->getFunctionIndex(), 1108 "function index"); 1109 writeU8(os, WASM_OPCODE_CALL, "CALL"); 1110 writeUleb128(os, WasmSym::applyGlobalRelocs->getFunctionIndex(), 1111 "function index"); 1112 writeU8(os, WASM_OPCODE_END, "END"); 1113 } 1114 createFunction(WasmSym::startFunction, bodyContent); 1115 } else if (WasmSym::initMemory) { 1116 WasmSym::startFunction = WasmSym::initMemory; 1117 } else if (WasmSym::applyGlobalRelocs) { 1118 WasmSym::startFunction = WasmSym::applyGlobalRelocs; 1119 } 1120 } 1121 1122 // For -shared (PIC) output, we create create a synthetic function which will 1123 // apply any relocations to the data segments on startup. This function is 1124 // called __wasm_apply_relocs and is added at the beginning of __wasm_call_ctors 1125 // before any of the constructors run. 1126 void Writer::createApplyDataRelocationsFunction() { 1127 LLVM_DEBUG(dbgs() << "createApplyDataRelocationsFunction\n"); 1128 // First write the body's contents to a string. 1129 std::string bodyContent; 1130 { 1131 raw_string_ostream os(bodyContent); 1132 writeUleb128(os, 0, "num locals"); 1133 for (const OutputSegment *seg : segments) 1134 for (const InputSegment *inSeg : seg->inputSegments) 1135 inSeg->generateRelocationCode(os); 1136 1137 writeU8(os, WASM_OPCODE_END, "END"); 1138 } 1139 1140 createFunction(WasmSym::applyDataRelocs, bodyContent); 1141 } 1142 1143 // Similar to createApplyDataRelocationsFunction but generates relocation code 1144 // fro WebAssembly globals. Because these globals are not shared between threads 1145 // these relocation need to run on every thread. 1146 void Writer::createApplyGlobalRelocationsFunction() { 1147 // First write the body's contents to a string. 1148 std::string bodyContent; 1149 { 1150 raw_string_ostream os(bodyContent); 1151 writeUleb128(os, 0, "num locals"); 1152 out.globalSec->generateRelocationCode(os); 1153 writeU8(os, WASM_OPCODE_END, "END"); 1154 } 1155 1156 createFunction(WasmSym::applyGlobalRelocs, bodyContent); 1157 } 1158 1159 // Create synthetic "__wasm_call_ctors" function based on ctor functions 1160 // in input object. 1161 void Writer::createCallCtorsFunction() { 1162 // If __wasm_call_ctors isn't referenced, there aren't any ctors, and we 1163 // aren't calling `__wasm_apply_relocs` for Emscripten-style PIC, don't 1164 // define the `__wasm_call_ctors` function. 1165 if (!WasmSym::callCtors->isLive() && !WasmSym::applyDataRelocs && 1166 initFunctions.empty()) 1167 return; 1168 1169 // First write the body's contents to a string. 1170 std::string bodyContent; 1171 { 1172 raw_string_ostream os(bodyContent); 1173 writeUleb128(os, 0, "num locals"); 1174 1175 if (WasmSym::applyDataRelocs) { 1176 writeU8(os, WASM_OPCODE_CALL, "CALL"); 1177 writeUleb128(os, WasmSym::applyDataRelocs->getFunctionIndex(), 1178 "function index"); 1179 } 1180 1181 // Call constructors 1182 for (const WasmInitEntry &f : initFunctions) { 1183 writeU8(os, WASM_OPCODE_CALL, "CALL"); 1184 writeUleb128(os, f.sym->getFunctionIndex(), "function index"); 1185 for (size_t i = 0; i < f.sym->signature->Returns.size(); i++) { 1186 writeU8(os, WASM_OPCODE_DROP, "DROP"); 1187 } 1188 } 1189 1190 writeU8(os, WASM_OPCODE_END, "END"); 1191 } 1192 1193 createFunction(WasmSym::callCtors, bodyContent); 1194 } 1195 1196 // Create a wrapper around a function export which calls the 1197 // static constructors and destructors. 1198 void Writer::createCommandExportWrapper(uint32_t functionIndex, 1199 DefinedFunction *f) { 1200 // First write the body's contents to a string. 1201 std::string bodyContent; 1202 { 1203 raw_string_ostream os(bodyContent); 1204 writeUleb128(os, 0, "num locals"); 1205 1206 // If we have any ctors, or we're calling `__wasm_apply_relocs` for 1207 // Emscripten-style PIC, call `__wasm_call_ctors` which performs those 1208 // calls. 1209 if (WasmSym::callCtors->isLive()) { 1210 writeU8(os, WASM_OPCODE_CALL, "CALL"); 1211 writeUleb128(os, WasmSym::callCtors->getFunctionIndex(), 1212 "function index"); 1213 } 1214 1215 // Call the user's code, leaving any return values on the operand stack. 1216 for (size_t i = 0; i < f->signature->Params.size(); ++i) { 1217 writeU8(os, WASM_OPCODE_LOCAL_GET, "local.get"); 1218 writeUleb128(os, i, "local index"); 1219 } 1220 writeU8(os, WASM_OPCODE_CALL, "CALL"); 1221 writeUleb128(os, functionIndex, "function index"); 1222 1223 // Call the function that calls the destructors. 1224 if (DefinedFunction *callDtors = WasmSym::callDtors) { 1225 writeU8(os, WASM_OPCODE_CALL, "CALL"); 1226 writeUleb128(os, callDtors->getFunctionIndex(), "function index"); 1227 } 1228 1229 // End the function, returning the return values from the user's code. 1230 writeU8(os, WASM_OPCODE_END, "END"); 1231 } 1232 1233 createFunction(f, bodyContent); 1234 } 1235 1236 void Writer::createInitTLSFunction() { 1237 std::string bodyContent; 1238 { 1239 raw_string_ostream os(bodyContent); 1240 1241 OutputSegment *tlsSeg = nullptr; 1242 for (auto *seg : segments) { 1243 if (seg->name == ".tdata") { 1244 tlsSeg = seg; 1245 break; 1246 } 1247 } 1248 1249 writeUleb128(os, 0, "num locals"); 1250 if (tlsSeg) { 1251 writeU8(os, WASM_OPCODE_LOCAL_GET, "local.get"); 1252 writeUleb128(os, 0, "local index"); 1253 1254 writeU8(os, WASM_OPCODE_GLOBAL_SET, "global.set"); 1255 writeUleb128(os, WasmSym::tlsBase->getGlobalIndex(), "global index"); 1256 1257 // FIXME(wvo): this local needs to be I64 in wasm64, or we need an extend op. 1258 writeU8(os, WASM_OPCODE_LOCAL_GET, "local.get"); 1259 writeUleb128(os, 0, "local index"); 1260 1261 writeI32Const(os, 0, "segment offset"); 1262 1263 writeI32Const(os, tlsSeg->size, "memory region size"); 1264 1265 writeU8(os, WASM_OPCODE_MISC_PREFIX, "bulk-memory prefix"); 1266 writeUleb128(os, WASM_OPCODE_MEMORY_INIT, "MEMORY.INIT"); 1267 writeUleb128(os, tlsSeg->index, "segment index immediate"); 1268 writeU8(os, 0, "memory index immediate"); 1269 } 1270 writeU8(os, WASM_OPCODE_END, "end function"); 1271 } 1272 1273 createFunction(WasmSym::initTLS, bodyContent); 1274 } 1275 1276 // Populate InitFunctions vector with init functions from all input objects. 1277 // This is then used either when creating the output linking section or to 1278 // synthesize the "__wasm_call_ctors" function. 1279 void Writer::calculateInitFunctions() { 1280 if (!config->relocatable && !WasmSym::callCtors->isLive()) 1281 return; 1282 1283 for (ObjFile *file : symtab->objectFiles) { 1284 const WasmLinkingData &l = file->getWasmObj()->linkingData(); 1285 for (const WasmInitFunc &f : l.InitFunctions) { 1286 FunctionSymbol *sym = file->getFunctionSymbol(f.Symbol); 1287 // comdat exclusions can cause init functions be discarded. 1288 if (sym->isDiscarded() || !sym->isLive()) 1289 continue; 1290 if (sym->signature->Params.size() != 0) 1291 error("constructor functions cannot take arguments: " + toString(*sym)); 1292 LLVM_DEBUG(dbgs() << "initFunctions: " << toString(*sym) << "\n"); 1293 initFunctions.emplace_back(WasmInitEntry{sym, f.Priority}); 1294 } 1295 } 1296 1297 // Sort in order of priority (lowest first) so that they are called 1298 // in the correct order. 1299 llvm::stable_sort(initFunctions, 1300 [](const WasmInitEntry &l, const WasmInitEntry &r) { 1301 return l.priority < r.priority; 1302 }); 1303 } 1304 1305 void Writer::createSyntheticSections() { 1306 out.dylinkSec = make<DylinkSection>(); 1307 out.typeSec = make<TypeSection>(); 1308 out.importSec = make<ImportSection>(); 1309 out.functionSec = make<FunctionSection>(); 1310 out.tableSec = make<TableSection>(); 1311 out.memorySec = make<MemorySection>(); 1312 out.eventSec = make<EventSection>(); 1313 out.globalSec = make<GlobalSection>(); 1314 out.exportSec = make<ExportSection>(); 1315 out.startSec = make<StartSection>(); 1316 out.elemSec = make<ElemSection>(); 1317 out.dataCountSec = make<DataCountSection>(segments); 1318 out.linkingSec = make<LinkingSection>(initFunctions, segments); 1319 out.nameSec = make<NameSection>(segments); 1320 out.producersSec = make<ProducersSection>(); 1321 out.targetFeaturesSec = make<TargetFeaturesSection>(); 1322 } 1323 1324 void Writer::run() { 1325 if (config->relocatable || config->isPic) 1326 config->globalBase = 0; 1327 1328 // For PIC code the table base is assigned dynamically by the loader. 1329 // For non-PIC, we start at 1 so that accessing table index 0 always traps. 1330 if (!config->isPic) { 1331 config->tableBase = 1; 1332 if (WasmSym::definedTableBase) 1333 WasmSym::definedTableBase->setVirtualAddress(config->tableBase); 1334 } 1335 1336 log("-- createOutputSegments"); 1337 createOutputSegments(); 1338 log("-- createSyntheticSections"); 1339 createSyntheticSections(); 1340 log("-- populateProducers"); 1341 populateProducers(); 1342 log("-- calculateImports"); 1343 calculateImports(); 1344 log("-- layoutMemory"); 1345 layoutMemory(); 1346 1347 if (!config->relocatable) { 1348 // Create linker synthesized __start_SECNAME/__stop_SECNAME symbols 1349 // This has to be done after memory layout is performed. 1350 for (const OutputSegment *seg : segments) 1351 addStartStopSymbols(seg); 1352 } 1353 1354 log("-- scanRelocations"); 1355 scanRelocations(); 1356 log("-- finalizeIndirectFunctionTable"); 1357 finalizeIndirectFunctionTable(); 1358 log("-- createSyntheticInitFunctions"); 1359 createSyntheticInitFunctions(); 1360 log("-- assignIndexes"); 1361 assignIndexes(); 1362 log("-- calculateInitFunctions"); 1363 calculateInitFunctions(); 1364 1365 if (!config->relocatable) { 1366 // Create linker synthesized functions 1367 if (WasmSym::applyDataRelocs) 1368 createApplyDataRelocationsFunction(); 1369 if (WasmSym::applyGlobalRelocs) 1370 createApplyGlobalRelocationsFunction(); 1371 if (WasmSym::initMemory) 1372 createInitMemoryFunction(); 1373 createStartFunction(); 1374 1375 createCallCtorsFunction(); 1376 1377 // Create export wrappers for commands if needed. 1378 // 1379 // If the input contains a call to `__wasm_call_ctors`, either in one of 1380 // the input objects or an explicit export from the command-line, we 1381 // assume ctors and dtors are taken care of already. 1382 if (!config->relocatable && !config->isPic && 1383 !WasmSym::callCtors->isUsedInRegularObj && 1384 !WasmSym::callCtors->isExported()) { 1385 log("-- createCommandExportWrappers"); 1386 createCommandExportWrappers(); 1387 } 1388 } 1389 1390 if (WasmSym::initTLS && WasmSym::initTLS->isLive()) 1391 createInitTLSFunction(); 1392 1393 if (errorCount()) 1394 return; 1395 1396 log("-- calculateTypes"); 1397 calculateTypes(); 1398 log("-- calculateExports"); 1399 calculateExports(); 1400 log("-- calculateCustomSections"); 1401 calculateCustomSections(); 1402 log("-- populateSymtab"); 1403 populateSymtab(); 1404 log("-- populateTargetFeatures"); 1405 populateTargetFeatures(); 1406 log("-- addSections"); 1407 addSections(); 1408 1409 if (errorHandler().verbose) { 1410 log("Defined Functions: " + Twine(out.functionSec->inputFunctions.size())); 1411 log("Defined Globals : " + Twine(out.globalSec->numGlobals())); 1412 log("Defined Events : " + Twine(out.eventSec->inputEvents.size())); 1413 log("Defined Tables : " + Twine(out.tableSec->inputTables.size())); 1414 log("Function Imports : " + 1415 Twine(out.importSec->getNumImportedFunctions())); 1416 log("Global Imports : " + Twine(out.importSec->getNumImportedGlobals())); 1417 log("Event Imports : " + Twine(out.importSec->getNumImportedEvents())); 1418 log("Table Imports : " + Twine(out.importSec->getNumImportedTables())); 1419 for (ObjFile *file : symtab->objectFiles) 1420 file->dumpInfo(); 1421 } 1422 1423 createHeader(); 1424 log("-- finalizeSections"); 1425 finalizeSections(); 1426 1427 log("-- writeMapFile"); 1428 writeMapFile(outputSections); 1429 1430 log("-- openFile"); 1431 openFile(); 1432 if (errorCount()) 1433 return; 1434 1435 writeHeader(); 1436 1437 log("-- writeSections"); 1438 writeSections(); 1439 if (errorCount()) 1440 return; 1441 1442 if (Error e = buffer->commit()) 1443 fatal("failed to write the output file: " + toString(std::move(e))); 1444 } 1445 1446 // Open a result file. 1447 void Writer::openFile() { 1448 log("writing: " + config->outputFile); 1449 1450 Expected<std::unique_ptr<FileOutputBuffer>> bufferOrErr = 1451 FileOutputBuffer::create(config->outputFile, fileSize, 1452 FileOutputBuffer::F_executable); 1453 1454 if (!bufferOrErr) 1455 error("failed to open " + config->outputFile + ": " + 1456 toString(bufferOrErr.takeError())); 1457 else 1458 buffer = std::move(*bufferOrErr); 1459 } 1460 1461 void Writer::createHeader() { 1462 raw_string_ostream os(header); 1463 writeBytes(os, WasmMagic, sizeof(WasmMagic), "wasm magic"); 1464 writeU32(os, WasmVersion, "wasm version"); 1465 os.flush(); 1466 fileSize += header.size(); 1467 } 1468 1469 void writeResult() { Writer().run(); } 1470 1471 } // namespace wasm 1472 } // namespace lld 1473