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