1 //===- Writer.cpp ---------------------------------------------------------===//
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
12 #include "InputChunks.h"
13 #include "InputGlobal.h"
14 #include "OutputSections.h"
15 #include "OutputSegment.h"
16 #include "SymbolTable.h"
17 #include "WriterUtils.h"
18 #include "lld/Common/ErrorHandler.h"
19 #include "lld/Common/Memory.h"
20 #include "lld/Common/Strings.h"
21 #include "lld/Common/Threads.h"
22 #include "llvm/ADT/DenseSet.h"
23 #include "llvm/ADT/StringMap.h"
24 #include "llvm/BinaryFormat/Wasm.h"
25 #include "llvm/Object/WasmTraits.h"
26 #include "llvm/Support/FileOutputBuffer.h"
27 #include "llvm/Support/Format.h"
28 #include "llvm/Support/FormatVariadic.h"
29 #include "llvm/Support/LEB128.h"
34 #define DEBUG_TYPE "lld"
37 using namespace llvm::wasm;
39 using namespace lld::wasm;
41 static constexpr int kStackAlignment = 16;
42 static constexpr int kInitialTableOffset = 1;
43 static constexpr const char *kFunctionTableName = "__indirect_function_table";
47 // An init entry to be written to either the synthetic init func or the
49 struct WasmInitEntry {
50 const FunctionSymbol *Sym;
54 // The writer writes a SymbolTable result to a file.
62 uint32_t lookupType(const WasmSignature &Sig);
63 uint32_t registerType(const WasmSignature &Sig);
65 void createCtorFunction();
66 void calculateInitFunctions();
68 void calculateImports();
69 void calculateExports();
70 void calculateCustomSections();
72 void calculateTypes();
73 void createOutputSegments();
76 void createSections();
77 SyntheticSection *createSyntheticSection(uint32_t Type, StringRef Name = "");
80 void createTypeSection();
81 void createFunctionSection();
82 void createTableSection();
83 void createGlobalSection();
84 void createExportSection();
85 void createImportSection();
86 void createMemorySection();
87 void createElemSection();
88 void createCodeSection();
89 void createDataSection();
90 void createCustomSections();
93 void createRelocSections();
94 void createLinkingSection();
95 void createNameSection();
100 uint64_t FileSize = 0;
101 uint32_t NumMemoryPages = 0;
102 uint32_t MaxMemoryPages = 0;
104 std::vector<const WasmSignature *> Types;
105 DenseMap<WasmSignature, int32_t> TypeIndices;
106 std::vector<const Symbol *> ImportedSymbols;
107 unsigned NumImportedFunctions = 0;
108 unsigned NumImportedGlobals = 0;
109 std::vector<WasmExport> Exports;
110 std::vector<const DefinedData *> DefinedFakeGlobals;
111 std::vector<InputGlobal *> InputGlobals;
112 std::vector<InputFunction *> InputFunctions;
113 std::vector<const FunctionSymbol *> IndirectFunctions;
114 std::vector<const Symbol *> SymtabEntries;
115 std::vector<WasmInitEntry> InitFunctions;
117 llvm::StringMap<std::vector<InputSection *>> CustomSectionMapping;
118 llvm::StringMap<SectionSymbol *> CustomSectionSymbols;
120 // Elements that are used to construct the final output
122 std::vector<OutputSection *> OutputSections;
124 std::unique_ptr<FileOutputBuffer> Buffer;
126 std::vector<OutputSegment *> Segments;
127 llvm::SmallDenseMap<StringRef, OutputSegment *> SegmentMap;
130 } // anonymous namespace
132 void Writer::createImportSection() {
133 uint32_t NumImports = ImportedSymbols.size();
134 if (Config->ImportMemory)
136 if (Config->ImportTable)
142 SyntheticSection *Section = createSyntheticSection(WASM_SEC_IMPORT);
143 raw_ostream &OS = Section->getStream();
145 writeUleb128(OS, NumImports, "import count");
147 if (Config->ImportMemory) {
149 Import.Module = "env";
150 Import.Field = "memory";
151 Import.Kind = WASM_EXTERNAL_MEMORY;
152 Import.Memory.Flags = 0;
153 Import.Memory.Initial = NumMemoryPages;
154 if (MaxMemoryPages != 0) {
155 Import.Memory.Flags |= WASM_LIMITS_FLAG_HAS_MAX;
156 Import.Memory.Maximum = MaxMemoryPages;
158 writeImport(OS, Import);
161 if (Config->ImportTable) {
162 uint32_t TableSize = kInitialTableOffset + IndirectFunctions.size();
164 Import.Module = "env";
165 Import.Field = kFunctionTableName;
166 Import.Kind = WASM_EXTERNAL_TABLE;
167 Import.Table.ElemType = WASM_TYPE_ANYFUNC;
168 Import.Table.Limits = {WASM_LIMITS_FLAG_HAS_MAX, TableSize, TableSize};
169 writeImport(OS, Import);
172 for (const Symbol *Sym : ImportedSymbols) {
174 Import.Module = "env";
175 Import.Field = Sym->getName();
176 if (auto *FunctionSym = dyn_cast<FunctionSymbol>(Sym)) {
177 Import.Kind = WASM_EXTERNAL_FUNCTION;
178 Import.SigIndex = lookupType(*FunctionSym->FunctionType);
180 auto *GlobalSym = cast<GlobalSymbol>(Sym);
181 Import.Kind = WASM_EXTERNAL_GLOBAL;
182 Import.Global = *GlobalSym->getGlobalType();
184 writeImport(OS, Import);
188 void Writer::createTypeSection() {
189 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TYPE);
190 raw_ostream &OS = Section->getStream();
191 writeUleb128(OS, Types.size(), "type count");
192 for (const WasmSignature *Sig : Types)
196 void Writer::createFunctionSection() {
197 if (InputFunctions.empty())
200 SyntheticSection *Section = createSyntheticSection(WASM_SEC_FUNCTION);
201 raw_ostream &OS = Section->getStream();
203 writeUleb128(OS, InputFunctions.size(), "function count");
204 for (const InputFunction *Func : InputFunctions)
205 writeUleb128(OS, lookupType(Func->Signature), "sig index");
208 void Writer::createMemorySection() {
209 if (Config->ImportMemory)
212 SyntheticSection *Section = createSyntheticSection(WASM_SEC_MEMORY);
213 raw_ostream &OS = Section->getStream();
215 bool HasMax = MaxMemoryPages != 0;
216 writeUleb128(OS, 1, "memory count");
217 writeUleb128(OS, HasMax ? static_cast<unsigned>(WASM_LIMITS_FLAG_HAS_MAX) : 0,
218 "memory limits flags");
219 writeUleb128(OS, NumMemoryPages, "initial pages");
221 writeUleb128(OS, MaxMemoryPages, "max pages");
224 void Writer::createGlobalSection() {
225 unsigned NumGlobals = InputGlobals.size() + DefinedFakeGlobals.size();
229 SyntheticSection *Section = createSyntheticSection(WASM_SEC_GLOBAL);
230 raw_ostream &OS = Section->getStream();
232 writeUleb128(OS, NumGlobals, "global count");
233 for (const InputGlobal *G : InputGlobals)
234 writeGlobal(OS, G->Global);
235 for (const DefinedData *Sym : DefinedFakeGlobals) {
237 Global.Type = {WASM_TYPE_I32, false};
238 Global.InitExpr.Opcode = WASM_OPCODE_I32_CONST;
239 Global.InitExpr.Value.Int32 = Sym->getVirtualAddress();
240 writeGlobal(OS, Global);
244 void Writer::createTableSection() {
245 if (Config->ImportTable)
248 // Always output a table section (or table import), even if there are no
249 // indirect calls. There are two reasons for this:
250 // 1. For executables it is useful to have an empty table slot at 0
251 // which can be filled with a null function call handler.
252 // 2. If we don't do this, any program that contains a call_indirect but
253 // no address-taken function will fail at validation time since it is
254 // a validation error to include a call_indirect instruction if there
256 uint32_t TableSize = kInitialTableOffset + IndirectFunctions.size();
258 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TABLE);
259 raw_ostream &OS = Section->getStream();
261 writeUleb128(OS, 1, "table count");
262 WasmLimits Limits = {WASM_LIMITS_FLAG_HAS_MAX, TableSize, TableSize};
263 writeTableType(OS, WasmTable{WASM_TYPE_ANYFUNC, Limits});
266 void Writer::createExportSection() {
270 SyntheticSection *Section = createSyntheticSection(WASM_SEC_EXPORT);
271 raw_ostream &OS = Section->getStream();
273 writeUleb128(OS, Exports.size(), "export count");
274 for (const WasmExport &Export : Exports)
275 writeExport(OS, Export);
278 void Writer::calculateCustomSections() {
279 log("calculateCustomSections");
280 bool StripDebug = Config->StripDebug || Config->StripAll;
281 for (ObjFile *File : Symtab->ObjectFiles) {
282 for (InputSection *Section : File->CustomSections) {
283 StringRef Name = Section->getName();
284 // These custom sections are known the linker and synthesized rather than
286 if (Name == "linking" || Name == "name" || Name.startswith("reloc."))
288 // .. or it is a debug section
289 if (StripDebug && Name.startswith(".debug_"))
291 CustomSectionMapping[Name].push_back(Section);
296 void Writer::createCustomSections() {
297 log("createCustomSections");
298 for (auto &Pair : CustomSectionMapping) {
299 StringRef Name = Pair.first();
301 auto P = CustomSectionSymbols.find(Name);
302 if (P != CustomSectionSymbols.end()) {
303 uint32_t SectionIndex = OutputSections.size();
304 P->second->setOutputSectionIndex(SectionIndex);
307 LLVM_DEBUG(dbgs() << "createCustomSection: " << Name << "\n");
308 OutputSections.push_back(make<CustomSection>(Name, Pair.second));
312 void Writer::createElemSection() {
313 if (IndirectFunctions.empty())
316 SyntheticSection *Section = createSyntheticSection(WASM_SEC_ELEM);
317 raw_ostream &OS = Section->getStream();
319 writeUleb128(OS, 1, "segment count");
320 writeUleb128(OS, 0, "table index");
321 WasmInitExpr InitExpr;
322 InitExpr.Opcode = WASM_OPCODE_I32_CONST;
323 InitExpr.Value.Int32 = kInitialTableOffset;
324 writeInitExpr(OS, InitExpr);
325 writeUleb128(OS, IndirectFunctions.size(), "elem count");
327 uint32_t TableIndex = kInitialTableOffset;
328 for (const FunctionSymbol *Sym : IndirectFunctions) {
329 assert(Sym->getTableIndex() == TableIndex);
330 writeUleb128(OS, Sym->getFunctionIndex(), "function index");
335 void Writer::createCodeSection() {
336 if (InputFunctions.empty())
339 log("createCodeSection");
341 auto Section = make<CodeSection>(InputFunctions);
342 OutputSections.push_back(Section);
345 void Writer::createDataSection() {
346 if (!Segments.size())
349 log("createDataSection");
350 auto Section = make<DataSection>(Segments);
351 OutputSections.push_back(Section);
354 // Create relocations sections in the final output.
355 // These are only created when relocatable output is requested.
356 void Writer::createRelocSections() {
357 log("createRelocSections");
358 // Don't use iterator here since we are adding to OutputSection
359 size_t OrigSize = OutputSections.size();
360 for (size_t I = 0; I < OrigSize; I++) {
361 OutputSection *OSec = OutputSections[I];
362 uint32_t Count = OSec->numRelocations();
367 if (OSec->Type == WASM_SEC_DATA)
369 else if (OSec->Type == WASM_SEC_CODE)
371 else if (OSec->Type == WASM_SEC_CUSTOM)
372 Name = Saver.save("reloc." + OSec->Name);
375 "relocations only supported for code, data, or custom sections");
377 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, Name);
378 raw_ostream &OS = Section->getStream();
379 writeUleb128(OS, I, "reloc section");
380 writeUleb128(OS, Count, "reloc count");
381 OSec->writeRelocations(OS);
385 static uint32_t getWasmFlags(const Symbol *Sym) {
388 Flags |= WASM_SYMBOL_BINDING_LOCAL;
390 Flags |= WASM_SYMBOL_BINDING_WEAK;
392 Flags |= WASM_SYMBOL_VISIBILITY_HIDDEN;
393 if (Sym->isUndefined())
394 Flags |= WASM_SYMBOL_UNDEFINED;
398 // Some synthetic sections (e.g. "name" and "linking") have subsections.
399 // Just like the synthetic sections themselves these need to be created before
400 // they can be written out (since they are preceded by their length). This
401 // class is used to create subsections and then write them into the stream
402 // of the parent section.
405 explicit SubSection(uint32_t Type) : Type(Type) {}
407 void writeTo(raw_ostream &To) {
409 writeUleb128(To, Type, "subsection type");
410 writeUleb128(To, Body.size(), "subsection size");
411 To.write(Body.data(), Body.size());
419 raw_string_ostream OS{Body};
422 // Create the custom "linking" section containing linker metadata.
423 // This is only created when relocatable output is requested.
424 void Writer::createLinkingSection() {
425 SyntheticSection *Section =
426 createSyntheticSection(WASM_SEC_CUSTOM, "linking");
427 raw_ostream &OS = Section->getStream();
429 writeUleb128(OS, WasmMetadataVersion, "Version");
431 if (!SymtabEntries.empty()) {
432 SubSection Sub(WASM_SYMBOL_TABLE);
433 writeUleb128(Sub.OS, SymtabEntries.size(), "num symbols");
435 for (const Symbol *Sym : SymtabEntries) {
436 assert(Sym->isDefined() || Sym->isUndefined());
437 WasmSymbolType Kind = Sym->getWasmType();
438 uint32_t Flags = getWasmFlags(Sym);
440 writeU8(Sub.OS, Kind, "sym kind");
441 writeUleb128(Sub.OS, Flags, "sym flags");
443 if (auto *F = dyn_cast<FunctionSymbol>(Sym)) {
444 writeUleb128(Sub.OS, F->getFunctionIndex(), "index");
445 if (Sym->isDefined())
446 writeStr(Sub.OS, Sym->getName(), "sym name");
447 } else if (auto *G = dyn_cast<GlobalSymbol>(Sym)) {
448 writeUleb128(Sub.OS, G->getGlobalIndex(), "index");
449 if (Sym->isDefined())
450 writeStr(Sub.OS, Sym->getName(), "sym name");
451 } else if (isa<DataSymbol>(Sym)) {
452 writeStr(Sub.OS, Sym->getName(), "sym name");
453 if (auto *DataSym = dyn_cast<DefinedData>(Sym)) {
454 writeUleb128(Sub.OS, DataSym->getOutputSegmentIndex(), "index");
455 writeUleb128(Sub.OS, DataSym->getOutputSegmentOffset(),
457 writeUleb128(Sub.OS, DataSym->getSize(), "data size");
460 auto *S = cast<SectionSymbol>(Sym);
461 writeUleb128(Sub.OS, S->getOutputSectionIndex(), "sym section index");
468 if (Segments.size()) {
469 SubSection Sub(WASM_SEGMENT_INFO);
470 writeUleb128(Sub.OS, Segments.size(), "num data segments");
471 for (const OutputSegment *S : Segments) {
472 writeStr(Sub.OS, S->Name, "segment name");
473 writeUleb128(Sub.OS, S->Alignment, "alignment");
474 writeUleb128(Sub.OS, 0, "flags");
479 if (!InitFunctions.empty()) {
480 SubSection Sub(WASM_INIT_FUNCS);
481 writeUleb128(Sub.OS, InitFunctions.size(), "num init functions");
482 for (const WasmInitEntry &F : InitFunctions) {
483 writeUleb128(Sub.OS, F.Priority, "priority");
484 writeUleb128(Sub.OS, F.Sym->getOutputSymbolIndex(), "function index");
493 std::map<StringRef, std::vector<ComdatEntry>> Comdats;
495 for (const InputFunction *F : InputFunctions) {
496 StringRef Comdat = F->getComdatName();
498 Comdats[Comdat].emplace_back(
499 ComdatEntry{WASM_COMDAT_FUNCTION, F->getFunctionIndex()});
501 for (uint32_t I = 0; I < Segments.size(); ++I) {
502 const auto &InputSegments = Segments[I]->InputSegments;
503 if (InputSegments.empty())
505 StringRef Comdat = InputSegments[0]->getComdatName();
507 for (const InputSegment *IS : InputSegments)
508 assert(IS->getComdatName() == Comdat);
511 Comdats[Comdat].emplace_back(ComdatEntry{WASM_COMDAT_DATA, I});
514 if (!Comdats.empty()) {
515 SubSection Sub(WASM_COMDAT_INFO);
516 writeUleb128(Sub.OS, Comdats.size(), "num comdats");
517 for (const auto &C : Comdats) {
518 writeStr(Sub.OS, C.first, "comdat name");
519 writeUleb128(Sub.OS, 0, "comdat flags"); // flags for future use
520 writeUleb128(Sub.OS, C.second.size(), "num entries");
521 for (const ComdatEntry &Entry : C.second) {
522 writeU8(Sub.OS, Entry.Kind, "entry kind");
523 writeUleb128(Sub.OS, Entry.Index, "entry index");
530 // Create the custom "name" section containing debug symbol names.
531 void Writer::createNameSection() {
532 unsigned NumNames = NumImportedFunctions;
533 for (const InputFunction *F : InputFunctions)
534 if (!F->getName().empty() || !F->getDebugName().empty())
540 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "name");
542 SubSection Sub(WASM_NAMES_FUNCTION);
543 writeUleb128(Sub.OS, NumNames, "name count");
545 // Names must appear in function index order. As it happens ImportedSymbols
546 // and InputFunctions are numbered in order with imported functions coming
548 for (const Symbol *S : ImportedSymbols) {
549 if (auto *F = dyn_cast<FunctionSymbol>(S)) {
550 writeUleb128(Sub.OS, F->getFunctionIndex(), "func index");
551 Optional<std::string> Name = demangleItanium(F->getName());
552 writeStr(Sub.OS, Name ? StringRef(*Name) : F->getName(), "symbol name");
555 for (const InputFunction *F : InputFunctions) {
556 if (!F->getName().empty()) {
557 writeUleb128(Sub.OS, F->getFunctionIndex(), "func index");
558 if (!F->getDebugName().empty()) {
559 writeStr(Sub.OS, F->getDebugName(), "symbol name");
561 Optional<std::string> Name = demangleItanium(F->getName());
562 writeStr(Sub.OS, Name ? StringRef(*Name) : F->getName(), "symbol name");
567 Sub.writeTo(Section->getStream());
570 void Writer::writeHeader() {
571 memcpy(Buffer->getBufferStart(), Header.data(), Header.size());
574 void Writer::writeSections() {
575 uint8_t *Buf = Buffer->getBufferStart();
576 parallelForEach(OutputSections, [Buf](OutputSection *S) { S->writeTo(Buf); });
579 // Fix the memory layout of the output binary. This assigns memory offsets
580 // to each of the input data sections as well as the explicit stack region.
581 // The default memory layout is as follows, from low to high.
583 // - initialized data (starting at Config->GlobalBase)
584 // - BSS data (not currently implemented in llvm)
585 // - explicit stack (Config->ZStackSize)
586 // - heap start / unallocated
588 // The --stack-first option means that stack is placed before any static data.
589 // This can be useful since it means that stack overflow traps immediately rather
590 // than overwriting global data, but also increases code size since all static
591 // data loads and stores requires larger offsets.
592 void Writer::layoutMemory() {
593 createOutputSegments();
595 uint32_t MemoryPtr = 0;
597 auto PlaceStack = [&]() {
598 if (Config->Relocatable)
600 MemoryPtr = alignTo(MemoryPtr, kStackAlignment);
601 if (Config->ZStackSize != alignTo(Config->ZStackSize, kStackAlignment))
602 error("stack size must be " + Twine(kStackAlignment) + "-byte aligned");
603 log("mem: stack size = " + Twine(Config->ZStackSize));
604 log("mem: stack base = " + Twine(MemoryPtr));
605 MemoryPtr += Config->ZStackSize;
606 WasmSym::StackPointer->Global->Global.InitExpr.Value.Int32 = MemoryPtr;
607 log("mem: stack top = " + Twine(MemoryPtr));
610 if (Config->StackFirst) {
613 MemoryPtr = Config->GlobalBase;
614 log("mem: global base = " + Twine(Config->GlobalBase));
617 uint32_t DataStart = MemoryPtr;
619 // Arbitrarily set __dso_handle handle to point to the start of the data
621 if (WasmSym::DsoHandle)
622 WasmSym::DsoHandle->setVirtualAddress(DataStart);
624 for (OutputSegment *Seg : Segments) {
625 MemoryPtr = alignTo(MemoryPtr, Seg->Alignment);
626 Seg->StartVA = MemoryPtr;
627 log(formatv("mem: {0,-15} offset={1,-8} size={2,-8} align={3}", Seg->Name,
628 MemoryPtr, Seg->Size, Seg->Alignment));
629 MemoryPtr += Seg->Size;
632 // TODO: Add .bss space here.
633 if (WasmSym::DataEnd)
634 WasmSym::DataEnd->setVirtualAddress(MemoryPtr);
636 log("mem: static data = " + Twine(MemoryPtr - DataStart));
638 if (!Config->StackFirst)
641 // Set `__heap_base` to directly follow the end of the stack or global data.
642 // The fact that this comes last means that a malloc/brk implementation
643 // can grow the heap at runtime.
644 if (!Config->Relocatable) {
645 WasmSym::HeapBase->setVirtualAddress(MemoryPtr);
646 log("mem: heap base = " + Twine(MemoryPtr));
649 if (Config->InitialMemory != 0) {
650 if (Config->InitialMemory != alignTo(Config->InitialMemory, WasmPageSize))
651 error("initial memory must be " + Twine(WasmPageSize) + "-byte aligned");
652 if (MemoryPtr > Config->InitialMemory)
653 error("initial memory too small, " + Twine(MemoryPtr) + " bytes needed");
655 MemoryPtr = Config->InitialMemory;
657 uint32_t MemSize = alignTo(MemoryPtr, WasmPageSize);
658 NumMemoryPages = MemSize / WasmPageSize;
659 log("mem: total pages = " + Twine(NumMemoryPages));
661 if (Config->MaxMemory != 0) {
662 if (Config->MaxMemory != alignTo(Config->MaxMemory, WasmPageSize))
663 error("maximum memory must be " + Twine(WasmPageSize) + "-byte aligned");
664 if (MemoryPtr > Config->MaxMemory)
665 error("maximum memory too small, " + Twine(MemoryPtr) + " bytes needed");
666 MaxMemoryPages = Config->MaxMemory / WasmPageSize;
667 log("mem: max pages = " + Twine(MaxMemoryPages));
671 SyntheticSection *Writer::createSyntheticSection(uint32_t Type,
673 auto Sec = make<SyntheticSection>(Type, Name);
674 log("createSection: " + toString(*Sec));
675 OutputSections.push_back(Sec);
679 void Writer::createSections() {
682 createImportSection();
683 createFunctionSection();
684 createTableSection();
685 createMemorySection();
686 createGlobalSection();
687 createExportSection();
691 createCustomSections();
694 if (Config->Relocatable) {
695 createLinkingSection();
696 createRelocSections();
698 if (!Config->StripDebug && !Config->StripAll)
701 for (OutputSection *S : OutputSections) {
702 S->setOffset(FileSize);
703 S->finalizeContents();
704 FileSize += S->getSize();
708 void Writer::calculateImports() {
709 for (Symbol *Sym : Symtab->getSymbols()) {
710 if (!Sym->isUndefined())
712 if (isa<DataSymbol>(Sym))
714 if (Sym->isWeak() && !Config->Relocatable)
718 if (!Sym->IsUsedInRegularObj)
721 LLVM_DEBUG(dbgs() << "import: " << Sym->getName() << "\n");
722 ImportedSymbols.emplace_back(Sym);
723 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
724 F->setFunctionIndex(NumImportedFunctions++);
726 cast<GlobalSymbol>(Sym)->setGlobalIndex(NumImportedGlobals++);
730 void Writer::calculateExports() {
731 if (Config->Relocatable)
734 if (!Config->Relocatable && !Config->ImportMemory)
735 Exports.push_back(WasmExport{"memory", WASM_EXTERNAL_MEMORY, 0});
737 if (!Config->Relocatable && Config->ExportTable)
738 Exports.push_back(WasmExport{kFunctionTableName, WASM_EXTERNAL_TABLE, 0});
740 unsigned FakeGlobalIndex = NumImportedGlobals + InputGlobals.size();
742 for (Symbol *Sym : Symtab->getSymbols()) {
743 if (!Sym->isExported())
748 StringRef Name = Sym->getName();
750 if (auto *F = dyn_cast<DefinedFunction>(Sym)) {
751 Export = {Name, WASM_EXTERNAL_FUNCTION, F->getFunctionIndex()};
752 } else if (auto *G = dyn_cast<DefinedGlobal>(Sym)) {
753 // TODO(sbc): Remove this check once to mutable global proposal is
754 // implement in all major browsers.
755 // See: https://github.com/WebAssembly/mutable-global
756 if (G->getGlobalType()->Mutable) {
757 // Only the __stack_pointer should ever be create as mutable.
758 assert(G == WasmSym::StackPointer);
761 Export = {Name, WASM_EXTERNAL_GLOBAL, G->getGlobalIndex()};
763 auto *D = cast<DefinedData>(Sym);
764 DefinedFakeGlobals.emplace_back(D);
765 Export = {Name, WASM_EXTERNAL_GLOBAL, FakeGlobalIndex++};
768 LLVM_DEBUG(dbgs() << "Export: " << Name << "\n");
769 Exports.push_back(Export);
773 void Writer::assignSymtab() {
774 if (!Config->Relocatable)
777 StringMap<uint32_t> SectionSymbolIndices;
779 unsigned SymbolIndex = SymtabEntries.size();
780 for (ObjFile *File : Symtab->ObjectFiles) {
781 LLVM_DEBUG(dbgs() << "Symtab entries: " << File->getName() << "\n");
782 for (Symbol *Sym : File->getSymbols()) {
783 if (Sym->getFile() != File)
786 if (auto *S = dyn_cast<SectionSymbol>(Sym)) {
787 StringRef Name = S->getName();
788 if (CustomSectionMapping.count(Name) == 0)
791 auto SSI = SectionSymbolIndices.find(Name);
792 if (SSI != SectionSymbolIndices.end()) {
793 Sym->setOutputSymbolIndex(SSI->second);
797 SectionSymbolIndices[Name] = SymbolIndex;
798 CustomSectionSymbols[Name] = cast<SectionSymbol>(Sym);
803 // (Since this is relocatable output, GC is not performed so symbols must
805 assert(Sym->isLive());
806 Sym->setOutputSymbolIndex(SymbolIndex++);
807 SymtabEntries.emplace_back(Sym);
811 // For the moment, relocatable output doesn't contain any synthetic functions,
812 // so no need to look through the Symtab for symbols not referenced by
813 // Symtab->ObjectFiles.
816 uint32_t Writer::lookupType(const WasmSignature &Sig) {
817 auto It = TypeIndices.find(Sig);
818 if (It == TypeIndices.end()) {
819 error("type not found: " + toString(Sig));
825 uint32_t Writer::registerType(const WasmSignature &Sig) {
826 auto Pair = TypeIndices.insert(std::make_pair(Sig, Types.size()));
828 LLVM_DEBUG(dbgs() << "type " << toString(Sig) << "\n");
829 Types.push_back(&Sig);
831 return Pair.first->second;
834 void Writer::calculateTypes() {
835 // The output type section is the union of the following sets:
836 // 1. Any signature used in the TYPE relocation
837 // 2. The signatures of all imported functions
838 // 3. The signatures of all defined functions
840 for (ObjFile *File : Symtab->ObjectFiles) {
841 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
842 for (uint32_t I = 0; I < Types.size(); I++)
843 if (File->TypeIsUsed[I])
844 File->TypeMap[I] = registerType(Types[I]);
847 for (const Symbol *Sym : ImportedSymbols)
848 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
849 registerType(*F->FunctionType);
851 for (const InputFunction *F : InputFunctions)
852 registerType(F->Signature);
855 void Writer::assignIndexes() {
856 uint32_t FunctionIndex = NumImportedFunctions + InputFunctions.size();
857 auto AddDefinedFunction = [&](InputFunction *Func) {
860 InputFunctions.emplace_back(Func);
861 Func->setFunctionIndex(FunctionIndex++);
864 for (InputFunction *Func : Symtab->SyntheticFunctions)
865 AddDefinedFunction(Func);
867 for (ObjFile *File : Symtab->ObjectFiles) {
868 LLVM_DEBUG(dbgs() << "Functions: " << File->getName() << "\n");
869 for (InputFunction *Func : File->Functions)
870 AddDefinedFunction(Func);
873 uint32_t TableIndex = kInitialTableOffset;
874 auto HandleRelocs = [&](InputChunk *Chunk) {
877 ObjFile *File = Chunk->File;
878 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
879 for (const WasmRelocation &Reloc : Chunk->getRelocations()) {
880 if (Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_I32 ||
881 Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_SLEB) {
882 FunctionSymbol *Sym = File->getFunctionSymbol(Reloc.Index);
883 if (Sym->hasTableIndex() || !Sym->hasFunctionIndex())
885 Sym->setTableIndex(TableIndex++);
886 IndirectFunctions.emplace_back(Sym);
887 } else if (Reloc.Type == R_WEBASSEMBLY_TYPE_INDEX_LEB) {
888 // Mark target type as live
889 File->TypeMap[Reloc.Index] = registerType(Types[Reloc.Index]);
890 File->TypeIsUsed[Reloc.Index] = true;
895 for (ObjFile *File : Symtab->ObjectFiles) {
896 LLVM_DEBUG(dbgs() << "Handle relocs: " << File->getName() << "\n");
897 for (InputChunk *Chunk : File->Functions)
899 for (InputChunk *Chunk : File->Segments)
901 for (auto &P : File->CustomSections)
905 uint32_t GlobalIndex = NumImportedGlobals + InputGlobals.size();
906 auto AddDefinedGlobal = [&](InputGlobal *Global) {
908 LLVM_DEBUG(dbgs() << "AddDefinedGlobal: " << GlobalIndex << "\n");
909 Global->setGlobalIndex(GlobalIndex++);
910 InputGlobals.push_back(Global);
914 for (InputGlobal *Global : Symtab->SyntheticGlobals)
915 AddDefinedGlobal(Global);
917 for (ObjFile *File : Symtab->ObjectFiles) {
918 LLVM_DEBUG(dbgs() << "Globals: " << File->getName() << "\n");
919 for (InputGlobal *Global : File->Globals)
920 AddDefinedGlobal(Global);
924 static StringRef getOutputDataSegmentName(StringRef Name) {
925 if (!Config->MergeDataSegments)
927 if (Name.startswith(".text."))
929 if (Name.startswith(".data."))
931 if (Name.startswith(".bss."))
936 void Writer::createOutputSegments() {
937 for (ObjFile *File : Symtab->ObjectFiles) {
938 for (InputSegment *Segment : File->Segments) {
941 StringRef Name = getOutputDataSegmentName(Segment->getName());
942 OutputSegment *&S = SegmentMap[Name];
944 LLVM_DEBUG(dbgs() << "new segment: " << Name << "\n");
945 S = make<OutputSegment>(Name, Segments.size());
946 Segments.push_back(S);
948 S->addInputSegment(Segment);
949 LLVM_DEBUG(dbgs() << "added data: " << Name << ": " << S->Size << "\n");
954 static const int OPCODE_CALL = 0x10;
955 static const int OPCODE_END = 0xb;
957 // Create synthetic "__wasm_call_ctors" function based on ctor functions
959 void Writer::createCtorFunction() {
960 // First write the body's contents to a string.
961 std::string BodyContent;
963 raw_string_ostream OS(BodyContent);
964 writeUleb128(OS, 0, "num locals");
965 for (const WasmInitEntry &F : InitFunctions) {
966 writeU8(OS, OPCODE_CALL, "CALL");
967 writeUleb128(OS, F.Sym->getFunctionIndex(), "function index");
969 writeU8(OS, OPCODE_END, "END");
972 // Once we know the size of the body we can create the final function body
973 std::string FunctionBody;
975 raw_string_ostream OS(FunctionBody);
976 writeUleb128(OS, BodyContent.size(), "function size");
980 ArrayRef<uint8_t> Body = toArrayRef(Saver.save(FunctionBody));
981 cast<SyntheticFunction>(WasmSym::CallCtors->Function)->setBody(Body);
984 // Populate InitFunctions vector with init functions from all input objects.
985 // This is then used either when creating the output linking section or to
986 // synthesize the "__wasm_call_ctors" function.
987 void Writer::calculateInitFunctions() {
988 for (ObjFile *File : Symtab->ObjectFiles) {
989 const WasmLinkingData &L = File->getWasmObj()->linkingData();
990 for (const WasmInitFunc &F : L.InitFunctions) {
991 FunctionSymbol *Sym = File->getFunctionSymbol(F.Symbol);
992 if (*Sym->FunctionType != WasmSignature{{}, WASM_TYPE_NORESULT})
993 error("invalid signature for init func: " + toString(*Sym));
994 InitFunctions.emplace_back(WasmInitEntry{Sym, F.Priority});
998 // Sort in order of priority (lowest first) so that they are called
999 // in the correct order.
1000 std::stable_sort(InitFunctions.begin(), InitFunctions.end(),
1001 [](const WasmInitEntry &L, const WasmInitEntry &R) {
1002 return L.Priority < R.Priority;
1006 void Writer::run() {
1007 if (Config->Relocatable)
1008 Config->GlobalBase = 0;
1010 log("-- calculateImports");
1012 log("-- assignIndexes");
1014 log("-- calculateInitFunctions");
1015 calculateInitFunctions();
1016 if (!Config->Relocatable)
1017 createCtorFunction();
1018 log("-- calculateTypes");
1020 log("-- layoutMemory");
1022 log("-- calculateExports");
1024 log("-- calculateCustomSections");
1025 calculateCustomSections();
1026 log("-- assignSymtab");
1029 if (errorHandler().Verbose) {
1030 log("Defined Functions: " + Twine(InputFunctions.size()));
1031 log("Defined Globals : " + Twine(InputGlobals.size()));
1032 log("Function Imports : " + Twine(NumImportedFunctions));
1033 log("Global Imports : " + Twine(NumImportedGlobals));
1034 for (ObjFile *File : Symtab->ObjectFiles)
1039 log("-- createSections");
1049 log("-- writeSections");
1054 if (Error E = Buffer->commit())
1055 fatal("failed to write the output file: " + toString(std::move(E)));
1058 // Open a result file.
1059 void Writer::openFile() {
1060 log("writing: " + Config->OutputFile);
1062 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
1063 FileOutputBuffer::create(Config->OutputFile, FileSize,
1064 FileOutputBuffer::F_executable);
1067 error("failed to open " + Config->OutputFile + ": " +
1068 toString(BufferOrErr.takeError()));
1070 Buffer = std::move(*BufferOrErr);
1073 void Writer::createHeader() {
1074 raw_string_ostream OS(Header);
1075 writeBytes(OS, WasmMagic, sizeof(WasmMagic), "wasm magic");
1076 writeU32(OS, WasmVersion, "wasm version");
1078 FileSize += Header.size();
1081 void lld::wasm::writeResult() { Writer().run(); }