xref: /openbsd-src/gnu/llvm/lld/wasm/Writer.cpp (revision dfe94b169149f14cc1aee2cf6dad58a8d9a1860c)
1ece8a530Spatrick //===- Writer.cpp ---------------------------------------------------------===//
2ece8a530Spatrick //
3ece8a530Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4ece8a530Spatrick // See https://llvm.org/LICENSE.txt for license information.
5ece8a530Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6ece8a530Spatrick //
7ece8a530Spatrick //===----------------------------------------------------------------------===//
8ece8a530Spatrick 
9ece8a530Spatrick #include "Writer.h"
10ece8a530Spatrick #include "Config.h"
11ece8a530Spatrick #include "InputChunks.h"
121cf9926bSpatrick #include "InputElement.h"
131cf9926bSpatrick #include "MapFile.h"
14ece8a530Spatrick #include "OutputSections.h"
15ece8a530Spatrick #include "OutputSegment.h"
16ece8a530Spatrick #include "Relocations.h"
17ece8a530Spatrick #include "SymbolTable.h"
18ece8a530Spatrick #include "SyntheticSections.h"
19ece8a530Spatrick #include "WriterUtils.h"
20*dfe94b16Srobert #include "lld/Common/CommonLinkerContext.h"
21ece8a530Spatrick #include "lld/Common/Strings.h"
22ece8a530Spatrick #include "llvm/ADT/DenseSet.h"
23ece8a530Spatrick #include "llvm/ADT/SmallSet.h"
24ece8a530Spatrick #include "llvm/ADT/SmallVector.h"
25ece8a530Spatrick #include "llvm/ADT/StringMap.h"
26ece8a530Spatrick #include "llvm/BinaryFormat/Wasm.h"
271cf9926bSpatrick #include "llvm/BinaryFormat/WasmTraits.h"
28ece8a530Spatrick #include "llvm/Support/FileOutputBuffer.h"
29ece8a530Spatrick #include "llvm/Support/Format.h"
30ece8a530Spatrick #include "llvm/Support/FormatVariadic.h"
31ece8a530Spatrick #include "llvm/Support/LEB128.h"
32bb684c34Spatrick #include "llvm/Support/Parallel.h"
33ece8a530Spatrick 
34ece8a530Spatrick #include <cstdarg>
35ece8a530Spatrick #include <map>
36*dfe94b16Srobert #include <optional>
37ece8a530Spatrick 
38ece8a530Spatrick #define DEBUG_TYPE "lld"
39ece8a530Spatrick 
40ece8a530Spatrick using namespace llvm;
41ece8a530Spatrick using namespace llvm::wasm;
42ece8a530Spatrick 
43ece8a530Spatrick namespace lld {
44ece8a530Spatrick namespace wasm {
45ece8a530Spatrick static constexpr int stackAlignment = 16;
461cf9926bSpatrick static constexpr int heapAlignment = 16;
47ece8a530Spatrick 
48ece8a530Spatrick namespace {
49ece8a530Spatrick 
50ece8a530Spatrick // The writer writes a SymbolTable result to a file.
51ece8a530Spatrick class Writer {
52ece8a530Spatrick public:
53ece8a530Spatrick   void run();
54ece8a530Spatrick 
55ece8a530Spatrick private:
56ece8a530Spatrick   void openFile();
57ece8a530Spatrick 
58bb684c34Spatrick   bool needsPassiveInitialization(const OutputSegment *segment);
59bb684c34Spatrick   bool hasPassiveInitializedSegments();
60bb684c34Spatrick 
611cf9926bSpatrick   void createSyntheticInitFunctions();
62ece8a530Spatrick   void createInitMemoryFunction();
631cf9926bSpatrick   void createStartFunction();
641cf9926bSpatrick   void createApplyDataRelocationsFunction();
651cf9926bSpatrick   void createApplyGlobalRelocationsFunction();
66*dfe94b16Srobert   void createApplyGlobalTLSRelocationsFunction();
67ece8a530Spatrick   void createCallCtorsFunction();
68ece8a530Spatrick   void createInitTLSFunction();
691cf9926bSpatrick   void createCommandExportWrappers();
701cf9926bSpatrick   void createCommandExportWrapper(uint32_t functionIndex, DefinedFunction *f);
71ece8a530Spatrick 
72ece8a530Spatrick   void assignIndexes();
73ece8a530Spatrick   void populateSymtab();
74ece8a530Spatrick   void populateProducers();
75ece8a530Spatrick   void populateTargetFeatures();
76*dfe94b16Srobert   // populateTargetFeatures happens early on so some checks are delayed
77*dfe94b16Srobert   // until imports and exports are finalized.  There are run unstead
78*dfe94b16Srobert   // in checkImportExportTargetFeatures
79*dfe94b16Srobert   void checkImportExportTargetFeatures();
80ece8a530Spatrick   void calculateInitFunctions();
81ece8a530Spatrick   void calculateImports();
82ece8a530Spatrick   void calculateExports();
83ece8a530Spatrick   void calculateCustomSections();
84ece8a530Spatrick   void calculateTypes();
85ece8a530Spatrick   void createOutputSegments();
861cf9926bSpatrick   OutputSegment *createOutputSegment(StringRef name);
871cf9926bSpatrick   void combineOutputSegments();
88ece8a530Spatrick   void layoutMemory();
89ece8a530Spatrick   void createHeader();
90ece8a530Spatrick 
91ece8a530Spatrick   void addSection(OutputSection *sec);
92ece8a530Spatrick 
93ece8a530Spatrick   void addSections();
94ece8a530Spatrick 
95ece8a530Spatrick   void createCustomSections();
96ece8a530Spatrick   void createSyntheticSections();
971cf9926bSpatrick   void createSyntheticSectionsPostLayout();
98ece8a530Spatrick   void finalizeSections();
99ece8a530Spatrick 
100ece8a530Spatrick   // Custom sections
101ece8a530Spatrick   void createRelocSections();
102ece8a530Spatrick 
103ece8a530Spatrick   void writeHeader();
104ece8a530Spatrick   void writeSections();
105ece8a530Spatrick 
106ece8a530Spatrick   uint64_t fileSize = 0;
107ece8a530Spatrick 
108ece8a530Spatrick   std::vector<WasmInitEntry> initFunctions;
1091cf9926bSpatrick   llvm::StringMap<std::vector<InputChunk *>> customSectionMapping;
1101cf9926bSpatrick 
1111cf9926bSpatrick   // Stable storage for command export wrapper function name strings.
1121cf9926bSpatrick   std::list<std::string> commandExportWrapperNames;
113ece8a530Spatrick 
114ece8a530Spatrick   // Elements that are used to construct the final output
115ece8a530Spatrick   std::string header;
116ece8a530Spatrick   std::vector<OutputSection *> outputSections;
117ece8a530Spatrick 
118ece8a530Spatrick   std::unique_ptr<FileOutputBuffer> buffer;
119ece8a530Spatrick 
120ece8a530Spatrick   std::vector<OutputSegment *> segments;
121ece8a530Spatrick   llvm::SmallDenseMap<StringRef, OutputSegment *> segmentMap;
122ece8a530Spatrick };
123ece8a530Spatrick 
124ece8a530Spatrick } // anonymous namespace
125ece8a530Spatrick 
calculateCustomSections()126ece8a530Spatrick void Writer::calculateCustomSections() {
127ece8a530Spatrick   log("calculateCustomSections");
128ece8a530Spatrick   bool stripDebug = config->stripDebug || config->stripAll;
129ece8a530Spatrick   for (ObjFile *file : symtab->objectFiles) {
1301cf9926bSpatrick     for (InputChunk *section : file->customSections) {
1311cf9926bSpatrick       // Exclude COMDAT sections that are not selected for inclusion
1321cf9926bSpatrick       if (section->discarded)
1331cf9926bSpatrick         continue;
134*dfe94b16Srobert       StringRef name = section->name;
135ece8a530Spatrick       // These custom sections are known the linker and synthesized rather than
136bb684c34Spatrick       // blindly copied.
137ece8a530Spatrick       if (name == "linking" || name == "name" || name == "producers" ||
138ece8a530Spatrick           name == "target_features" || name.startswith("reloc."))
139ece8a530Spatrick         continue;
140bb684c34Spatrick       // These custom sections are generated by `clang -fembed-bitcode`.
141bb684c34Spatrick       // These are used by the rust toolchain to ship LTO data along with
142bb684c34Spatrick       // compiled object code, but they don't want this included in the linker
143bb684c34Spatrick       // output.
144bb684c34Spatrick       if (name == ".llvmbc" || name == ".llvmcmd")
145bb684c34Spatrick         continue;
146bb684c34Spatrick       // Strip debug section in that option was specified.
147ece8a530Spatrick       if (stripDebug && name.startswith(".debug_"))
148ece8a530Spatrick         continue;
149bb684c34Spatrick       // Otherwise include custom sections by default and concatenate their
150bb684c34Spatrick       // contents.
151ece8a530Spatrick       customSectionMapping[name].push_back(section);
152ece8a530Spatrick     }
153ece8a530Spatrick   }
154ece8a530Spatrick }
155ece8a530Spatrick 
createCustomSections()156ece8a530Spatrick void Writer::createCustomSections() {
157ece8a530Spatrick   log("createCustomSections");
158ece8a530Spatrick   for (auto &pair : customSectionMapping) {
159ece8a530Spatrick     StringRef name = pair.first();
160ece8a530Spatrick     LLVM_DEBUG(dbgs() << "createCustomSection: " << name << "\n");
161ece8a530Spatrick 
162bb684c34Spatrick     OutputSection *sec = make<CustomSection>(std::string(name), pair.second);
163ece8a530Spatrick     if (config->relocatable || config->emitRelocs) {
164ece8a530Spatrick       auto *sym = make<OutputSectionSymbol>(sec);
165ece8a530Spatrick       out.linkingSec->addToSymtab(sym);
166ece8a530Spatrick       sec->sectionSym = sym;
167ece8a530Spatrick     }
168ece8a530Spatrick     addSection(sec);
169ece8a530Spatrick   }
170ece8a530Spatrick }
171ece8a530Spatrick 
172ece8a530Spatrick // Create relocations sections in the final output.
173ece8a530Spatrick // These are only created when relocatable output is requested.
createRelocSections()174ece8a530Spatrick void Writer::createRelocSections() {
175ece8a530Spatrick   log("createRelocSections");
176ece8a530Spatrick   // Don't use iterator here since we are adding to OutputSection
177ece8a530Spatrick   size_t origSize = outputSections.size();
178ece8a530Spatrick   for (size_t i = 0; i < origSize; i++) {
179ece8a530Spatrick     LLVM_DEBUG(dbgs() << "check section " << i << "\n");
180ece8a530Spatrick     OutputSection *sec = outputSections[i];
181ece8a530Spatrick 
182ece8a530Spatrick     // Count the number of needed sections.
183ece8a530Spatrick     uint32_t count = sec->getNumRelocations();
184ece8a530Spatrick     if (!count)
185ece8a530Spatrick       continue;
186ece8a530Spatrick 
187ece8a530Spatrick     StringRef name;
188ece8a530Spatrick     if (sec->type == WASM_SEC_DATA)
189ece8a530Spatrick       name = "reloc.DATA";
190ece8a530Spatrick     else if (sec->type == WASM_SEC_CODE)
191ece8a530Spatrick       name = "reloc.CODE";
192ece8a530Spatrick     else if (sec->type == WASM_SEC_CUSTOM)
193*dfe94b16Srobert       name = saver().save("reloc." + sec->name);
194ece8a530Spatrick     else
195ece8a530Spatrick       llvm_unreachable(
196ece8a530Spatrick           "relocations only supported for code, data, or custom sections");
197ece8a530Spatrick 
198ece8a530Spatrick     addSection(make<RelocSection>(name, sec));
199ece8a530Spatrick   }
200ece8a530Spatrick }
201ece8a530Spatrick 
populateProducers()202ece8a530Spatrick void Writer::populateProducers() {
203ece8a530Spatrick   for (ObjFile *file : symtab->objectFiles) {
204ece8a530Spatrick     const WasmProducerInfo &info = file->getWasmObj()->getProducerInfo();
205ece8a530Spatrick     out.producersSec->addInfo(info);
206ece8a530Spatrick   }
207ece8a530Spatrick }
208ece8a530Spatrick 
writeHeader()209ece8a530Spatrick void Writer::writeHeader() {
210ece8a530Spatrick   memcpy(buffer->getBufferStart(), header.data(), header.size());
211ece8a530Spatrick }
212ece8a530Spatrick 
writeSections()213ece8a530Spatrick void Writer::writeSections() {
214ece8a530Spatrick   uint8_t *buf = buffer->getBufferStart();
215ece8a530Spatrick   parallelForEach(outputSections, [buf](OutputSection *s) {
216ece8a530Spatrick     assert(s->isNeeded());
217ece8a530Spatrick     s->writeTo(buf);
218ece8a530Spatrick   });
219ece8a530Spatrick }
220ece8a530Spatrick 
setGlobalPtr(DefinedGlobal * g,uint64_t memoryPtr)2211cf9926bSpatrick static void setGlobalPtr(DefinedGlobal *g, uint64_t memoryPtr) {
222*dfe94b16Srobert   LLVM_DEBUG(dbgs() << "setGlobalPtr " << g->getName() << " -> " << memoryPtr << "\n");
2231cf9926bSpatrick   g->global->setPointerValue(memoryPtr);
2241cf9926bSpatrick }
2251cf9926bSpatrick 
226ece8a530Spatrick // Fix the memory layout of the output binary.  This assigns memory offsets
227ece8a530Spatrick // to each of the input data sections as well as the explicit stack region.
228ece8a530Spatrick // The default memory layout is as follows, from low to high.
229ece8a530Spatrick //
230*dfe94b16Srobert //  - initialized data (starting at config->globalBase)
231ece8a530Spatrick //  - BSS data (not currently implemented in llvm)
232*dfe94b16Srobert //  - explicit stack (config->ZStackSize)
233ece8a530Spatrick //  - heap start / unallocated
234ece8a530Spatrick //
235ece8a530Spatrick // The --stack-first option means that stack is placed before any static data.
236ece8a530Spatrick // This can be useful since it means that stack overflow traps immediately
237ece8a530Spatrick // rather than overwriting global data, but also increases code size since all
238ece8a530Spatrick // static data loads and stores requires larger offsets.
layoutMemory()239ece8a530Spatrick void Writer::layoutMemory() {
240bb684c34Spatrick   uint64_t memoryPtr = 0;
241ece8a530Spatrick 
242ece8a530Spatrick   auto placeStack = [&]() {
243ece8a530Spatrick     if (config->relocatable || config->isPic)
244ece8a530Spatrick       return;
245ece8a530Spatrick     memoryPtr = alignTo(memoryPtr, stackAlignment);
246*dfe94b16Srobert     if (WasmSym::stackLow)
247*dfe94b16Srobert       WasmSym::stackLow->setVA(memoryPtr);
248ece8a530Spatrick     if (config->zStackSize != alignTo(config->zStackSize, stackAlignment))
249ece8a530Spatrick       error("stack size must be " + Twine(stackAlignment) + "-byte aligned");
250ece8a530Spatrick     log("mem: stack size  = " + Twine(config->zStackSize));
251ece8a530Spatrick     log("mem: stack base  = " + Twine(memoryPtr));
252ece8a530Spatrick     memoryPtr += config->zStackSize;
2531cf9926bSpatrick     setGlobalPtr(cast<DefinedGlobal>(WasmSym::stackPointer), memoryPtr);
254*dfe94b16Srobert     if (WasmSym::stackHigh)
255*dfe94b16Srobert       WasmSym::stackHigh->setVA(memoryPtr);
256ece8a530Spatrick     log("mem: stack top   = " + Twine(memoryPtr));
257ece8a530Spatrick   };
258ece8a530Spatrick 
259ece8a530Spatrick   if (config->stackFirst) {
260ece8a530Spatrick     placeStack();
261*dfe94b16Srobert     if (config->globalBase) {
262*dfe94b16Srobert       if (config->globalBase < memoryPtr) {
263*dfe94b16Srobert         error("--global-base cannot be less than stack size when --stack-first is used");
264*dfe94b16Srobert         return;
265*dfe94b16Srobert       }
266ece8a530Spatrick       memoryPtr = config->globalBase;
267*dfe94b16Srobert     }
268*dfe94b16Srobert   } else {
269*dfe94b16Srobert     if (!config->globalBase && !config->relocatable && !config->isPic) {
270*dfe94b16Srobert       // The default offset for static/global data, for when --global-base is
271*dfe94b16Srobert       // not specified on the command line.  The precise value of 1024 is
272*dfe94b16Srobert       // somewhat arbitrary, and pre-dates wasm-ld (Its the value that
273*dfe94b16Srobert       // emscripten used prior to wasm-ld).
274*dfe94b16Srobert       config->globalBase = 1024;
275*dfe94b16Srobert     }
276*dfe94b16Srobert     memoryPtr = config->globalBase;
277ece8a530Spatrick   }
278ece8a530Spatrick 
279*dfe94b16Srobert   log("mem: global base = " + Twine(memoryPtr));
280ece8a530Spatrick   if (WasmSym::globalBase)
2811cf9926bSpatrick     WasmSym::globalBase->setVA(memoryPtr);
282ece8a530Spatrick 
283bb684c34Spatrick   uint64_t dataStart = memoryPtr;
284ece8a530Spatrick 
285ece8a530Spatrick   // Arbitrarily set __dso_handle handle to point to the start of the data
286ece8a530Spatrick   // segments.
287ece8a530Spatrick   if (WasmSym::dsoHandle)
2881cf9926bSpatrick     WasmSym::dsoHandle->setVA(dataStart);
289ece8a530Spatrick 
290ece8a530Spatrick   out.dylinkSec->memAlign = 0;
291ece8a530Spatrick   for (OutputSegment *seg : segments) {
292ece8a530Spatrick     out.dylinkSec->memAlign = std::max(out.dylinkSec->memAlign, seg->alignment);
293ece8a530Spatrick     memoryPtr = alignTo(memoryPtr, 1ULL << seg->alignment);
294ece8a530Spatrick     seg->startVA = memoryPtr;
295ece8a530Spatrick     log(formatv("mem: {0,-15} offset={1,-8} size={2,-8} align={3}", seg->name,
296ece8a530Spatrick                 memoryPtr, seg->size, seg->alignment));
297ece8a530Spatrick 
2981cf9926bSpatrick     if (!config->relocatable && seg->isTLS()) {
299*dfe94b16Srobert       if (WasmSym::tlsSize) {
300ece8a530Spatrick         auto *tlsSize = cast<DefinedGlobal>(WasmSym::tlsSize);
3011cf9926bSpatrick         setGlobalPtr(tlsSize, seg->size);
302*dfe94b16Srobert       }
303*dfe94b16Srobert       if (WasmSym::tlsAlign) {
304ece8a530Spatrick         auto *tlsAlign = cast<DefinedGlobal>(WasmSym::tlsAlign);
3051cf9926bSpatrick         setGlobalPtr(tlsAlign, int64_t{1} << seg->alignment);
306*dfe94b16Srobert       }
307*dfe94b16Srobert       if (!config->sharedMemory && WasmSym::tlsBase) {
3081cf9926bSpatrick         auto *tlsBase = cast<DefinedGlobal>(WasmSym::tlsBase);
3091cf9926bSpatrick         setGlobalPtr(tlsBase, memoryPtr);
310ece8a530Spatrick       }
311ece8a530Spatrick     }
312ece8a530Spatrick 
3131cf9926bSpatrick     memoryPtr += seg->size;
3141cf9926bSpatrick   }
3151cf9926bSpatrick 
316ece8a530Spatrick   // Make space for the memory initialization flag
3171cf9926bSpatrick   if (config->sharedMemory && hasPassiveInitializedSegments()) {
318ece8a530Spatrick     memoryPtr = alignTo(memoryPtr, 4);
3191cf9926bSpatrick     WasmSym::initMemoryFlag = symtab->addSyntheticDataSymbol(
3201cf9926bSpatrick         "__wasm_init_memory_flag", WASM_SYMBOL_VISIBILITY_HIDDEN);
3211cf9926bSpatrick     WasmSym::initMemoryFlag->markLive();
3221cf9926bSpatrick     WasmSym::initMemoryFlag->setVA(memoryPtr);
323ece8a530Spatrick     log(formatv("mem: {0,-15} offset={1,-8} size={2,-8} align={3}",
324ece8a530Spatrick                 "__wasm_init_memory_flag", memoryPtr, 4, 4));
325ece8a530Spatrick     memoryPtr += 4;
326ece8a530Spatrick   }
327ece8a530Spatrick 
328ece8a530Spatrick   if (WasmSym::dataEnd)
3291cf9926bSpatrick     WasmSym::dataEnd->setVA(memoryPtr);
330ece8a530Spatrick 
3311cf9926bSpatrick   uint64_t staticDataSize = memoryPtr - dataStart;
3321cf9926bSpatrick   log("mem: static data = " + Twine(staticDataSize));
3331cf9926bSpatrick   if (config->isPic)
3341cf9926bSpatrick     out.dylinkSec->memSize = staticDataSize;
335ece8a530Spatrick 
336ece8a530Spatrick   if (!config->stackFirst)
337ece8a530Spatrick     placeStack();
338ece8a530Spatrick 
3391cf9926bSpatrick   if (WasmSym::heapBase) {
3401cf9926bSpatrick     // Set `__heap_base` to follow the end of the stack or global data. The
3411cf9926bSpatrick     // fact that this comes last means that a malloc/brk implementation can
3421cf9926bSpatrick     // grow the heap at runtime.
3431cf9926bSpatrick     // We'll align the heap base here because memory allocators might expect
3441cf9926bSpatrick     // __heap_base to be aligned already.
3451cf9926bSpatrick     memoryPtr = alignTo(memoryPtr, heapAlignment);
346ece8a530Spatrick     log("mem: heap base   = " + Twine(memoryPtr));
3471cf9926bSpatrick     WasmSym::heapBase->setVA(memoryPtr);
3481cf9926bSpatrick   }
349ece8a530Spatrick 
350*dfe94b16Srobert   uint64_t maxMemorySetting = 1ULL << (config->is64.value_or(false) ? 48 : 32);
351bb684c34Spatrick 
352ece8a530Spatrick   if (config->initialMemory != 0) {
353ece8a530Spatrick     if (config->initialMemory != alignTo(config->initialMemory, WasmPageSize))
354ece8a530Spatrick       error("initial memory must be " + Twine(WasmPageSize) + "-byte aligned");
355ece8a530Spatrick     if (memoryPtr > config->initialMemory)
356ece8a530Spatrick       error("initial memory too small, " + Twine(memoryPtr) + " bytes needed");
357bb684c34Spatrick     if (config->initialMemory > maxMemorySetting)
358bb684c34Spatrick       error("initial memory too large, cannot be greater than " +
359bb684c34Spatrick             Twine(maxMemorySetting));
360ece8a530Spatrick     memoryPtr = config->initialMemory;
361ece8a530Spatrick   }
362*dfe94b16Srobert 
363*dfe94b16Srobert   memoryPtr = alignTo(memoryPtr, WasmPageSize);
364*dfe94b16Srobert 
365*dfe94b16Srobert   out.memorySec->numMemoryPages = memoryPtr / WasmPageSize;
366ece8a530Spatrick   log("mem: total pages = " + Twine(out.memorySec->numMemoryPages));
367ece8a530Spatrick 
368*dfe94b16Srobert   if (WasmSym::heapEnd) {
369*dfe94b16Srobert     // Set `__heap_end` to follow the end of the statically allocated linear
370*dfe94b16Srobert     // memory. The fact that this comes last means that a malloc/brk
371*dfe94b16Srobert     // implementation can grow the heap at runtime.
372*dfe94b16Srobert     log("mem: heap end    = " + Twine(memoryPtr));
373*dfe94b16Srobert     WasmSym::heapEnd->setVA(memoryPtr);
374*dfe94b16Srobert   }
375*dfe94b16Srobert 
3761cf9926bSpatrick   if (config->maxMemory != 0) {
377ece8a530Spatrick     if (config->maxMemory != alignTo(config->maxMemory, WasmPageSize))
378ece8a530Spatrick       error("maximum memory must be " + Twine(WasmPageSize) + "-byte aligned");
379ece8a530Spatrick     if (memoryPtr > config->maxMemory)
380ece8a530Spatrick       error("maximum memory too small, " + Twine(memoryPtr) + " bytes needed");
381bb684c34Spatrick     if (config->maxMemory > maxMemorySetting)
382bb684c34Spatrick       error("maximum memory too large, cannot be greater than " +
383bb684c34Spatrick             Twine(maxMemorySetting));
3841cf9926bSpatrick   }
3851cf9926bSpatrick 
3861cf9926bSpatrick   // Check max if explicitly supplied or required by shared memory
3871cf9926bSpatrick   if (config->maxMemory != 0 || config->sharedMemory) {
3881cf9926bSpatrick     uint64_t max = config->maxMemory;
3891cf9926bSpatrick     if (max == 0) {
3901cf9926bSpatrick       // If no maxMemory config was supplied but we are building with
3911cf9926bSpatrick       // shared memory, we need to pick a sensible upper limit.
3921cf9926bSpatrick       if (config->isPic)
3931cf9926bSpatrick         max = maxMemorySetting;
3941cf9926bSpatrick       else
395*dfe94b16Srobert         max = memoryPtr;
3961cf9926bSpatrick     }
3971cf9926bSpatrick     out.memorySec->maxMemoryPages = max / WasmPageSize;
398ece8a530Spatrick     log("mem: max pages   = " + Twine(out.memorySec->maxMemoryPages));
399ece8a530Spatrick   }
400ece8a530Spatrick }
401ece8a530Spatrick 
addSection(OutputSection * sec)402ece8a530Spatrick void Writer::addSection(OutputSection *sec) {
403ece8a530Spatrick   if (!sec->isNeeded())
404ece8a530Spatrick     return;
405ece8a530Spatrick   log("addSection: " + toString(*sec));
406ece8a530Spatrick   sec->sectionIndex = outputSections.size();
407ece8a530Spatrick   outputSections.push_back(sec);
408ece8a530Spatrick }
409ece8a530Spatrick 
410ece8a530Spatrick // If a section name is valid as a C identifier (which is rare because of
411ece8a530Spatrick // the leading '.'), linkers are expected to define __start_<secname> and
412ece8a530Spatrick // __stop_<secname> symbols. They are at beginning and end of the section,
413ece8a530Spatrick // respectively. This is not requested by the ELF standard, but GNU ld and
414ece8a530Spatrick // gold provide the feature, and used by many programs.
addStartStopSymbols(const OutputSegment * seg)415ece8a530Spatrick static void addStartStopSymbols(const OutputSegment *seg) {
416ece8a530Spatrick   StringRef name = seg->name;
417ece8a530Spatrick   if (!isValidCIdentifier(name))
418ece8a530Spatrick     return;
419ece8a530Spatrick   LLVM_DEBUG(dbgs() << "addStartStopSymbols: " << name << "\n");
4201cf9926bSpatrick   uint64_t start = seg->startVA;
4211cf9926bSpatrick   uint64_t stop = start + seg->size;
422*dfe94b16Srobert   symtab->addOptionalDataSymbol(saver().save("__start_" + name), start);
423*dfe94b16Srobert   symtab->addOptionalDataSymbol(saver().save("__stop_" + name), stop);
424ece8a530Spatrick }
425ece8a530Spatrick 
addSections()426ece8a530Spatrick void Writer::addSections() {
427ece8a530Spatrick   addSection(out.dylinkSec);
428ece8a530Spatrick   addSection(out.typeSec);
429ece8a530Spatrick   addSection(out.importSec);
430ece8a530Spatrick   addSection(out.functionSec);
431ece8a530Spatrick   addSection(out.tableSec);
432ece8a530Spatrick   addSection(out.memorySec);
4331cf9926bSpatrick   addSection(out.tagSec);
434bb684c34Spatrick   addSection(out.globalSec);
435ece8a530Spatrick   addSection(out.exportSec);
436ece8a530Spatrick   addSection(out.startSec);
437ece8a530Spatrick   addSection(out.elemSec);
438ece8a530Spatrick   addSection(out.dataCountSec);
439ece8a530Spatrick 
440ece8a530Spatrick   addSection(make<CodeSection>(out.functionSec->inputFunctions));
441ece8a530Spatrick   addSection(make<DataSection>(segments));
442ece8a530Spatrick 
443ece8a530Spatrick   createCustomSections();
444ece8a530Spatrick 
445ece8a530Spatrick   addSection(out.linkingSec);
446ece8a530Spatrick   if (config->emitRelocs || config->relocatable) {
447ece8a530Spatrick     createRelocSections();
448ece8a530Spatrick   }
449ece8a530Spatrick 
450ece8a530Spatrick   addSection(out.nameSec);
451ece8a530Spatrick   addSection(out.producersSec);
452ece8a530Spatrick   addSection(out.targetFeaturesSec);
453ece8a530Spatrick }
454ece8a530Spatrick 
finalizeSections()455ece8a530Spatrick void Writer::finalizeSections() {
456ece8a530Spatrick   for (OutputSection *s : outputSections) {
457ece8a530Spatrick     s->setOffset(fileSize);
458ece8a530Spatrick     s->finalizeContents();
459ece8a530Spatrick     fileSize += s->getSize();
460ece8a530Spatrick   }
461ece8a530Spatrick }
462ece8a530Spatrick 
populateTargetFeatures()463ece8a530Spatrick void Writer::populateTargetFeatures() {
464ece8a530Spatrick   StringMap<std::string> used;
465ece8a530Spatrick   StringMap<std::string> required;
466ece8a530Spatrick   StringMap<std::string> disallowed;
467ece8a530Spatrick   SmallSet<std::string, 8> &allowed = out.targetFeaturesSec->features;
468ece8a530Spatrick   bool tlsUsed = false;
469ece8a530Spatrick 
470*dfe94b16Srobert   if (config->isPic) {
471*dfe94b16Srobert     // This should not be necessary because all PIC objects should
472*dfe94b16Srobert     // contain the mutable-globals feature.
473*dfe94b16Srobert     // TODO(https://bugs.llvm.org/show_bug.cgi?id=52339)
474*dfe94b16Srobert     allowed.insert("mutable-globals");
475*dfe94b16Srobert   }
476*dfe94b16Srobert 
477*dfe94b16Srobert   if (config->extraFeatures.has_value()) {
478*dfe94b16Srobert     auto &extraFeatures = *config->extraFeatures;
479*dfe94b16Srobert     allowed.insert(extraFeatures.begin(), extraFeatures.end());
480*dfe94b16Srobert   }
481*dfe94b16Srobert 
482ece8a530Spatrick   // Only infer used features if user did not specify features
483*dfe94b16Srobert   bool inferFeatures = !config->features.has_value();
484ece8a530Spatrick 
485ece8a530Spatrick   if (!inferFeatures) {
486*dfe94b16Srobert     auto &explicitFeatures = *config->features;
487ece8a530Spatrick     allowed.insert(explicitFeatures.begin(), explicitFeatures.end());
488ece8a530Spatrick     if (!config->checkFeatures)
489*dfe94b16Srobert       goto done;
490ece8a530Spatrick   }
491ece8a530Spatrick 
492ece8a530Spatrick   // Find the sets of used, required, and disallowed features
493ece8a530Spatrick   for (ObjFile *file : symtab->objectFiles) {
494ece8a530Spatrick     StringRef fileName(file->getName());
495ece8a530Spatrick     for (auto &feature : file->getWasmObj()->getTargetFeatures()) {
496ece8a530Spatrick       switch (feature.Prefix) {
497ece8a530Spatrick       case WASM_FEATURE_PREFIX_USED:
498bb684c34Spatrick         used.insert({feature.Name, std::string(fileName)});
499ece8a530Spatrick         break;
500ece8a530Spatrick       case WASM_FEATURE_PREFIX_REQUIRED:
501bb684c34Spatrick         used.insert({feature.Name, std::string(fileName)});
502bb684c34Spatrick         required.insert({feature.Name, std::string(fileName)});
503ece8a530Spatrick         break;
504ece8a530Spatrick       case WASM_FEATURE_PREFIX_DISALLOWED:
505bb684c34Spatrick         disallowed.insert({feature.Name, std::string(fileName)});
506ece8a530Spatrick         break;
507ece8a530Spatrick       default:
508ece8a530Spatrick         error("Unrecognized feature policy prefix " +
509ece8a530Spatrick               std::to_string(feature.Prefix));
510ece8a530Spatrick       }
511ece8a530Spatrick     }
512ece8a530Spatrick 
513ece8a530Spatrick     // Find TLS data segments
5141cf9926bSpatrick     auto isTLS = [](InputChunk *segment) {
5151cf9926bSpatrick       return segment->live && segment->isTLS();
516ece8a530Spatrick     };
517*dfe94b16Srobert     tlsUsed = tlsUsed || llvm::any_of(file->segments, isTLS);
518ece8a530Spatrick   }
519ece8a530Spatrick 
520ece8a530Spatrick   if (inferFeatures)
521bb684c34Spatrick     for (const auto &key : used.keys())
522bb684c34Spatrick       allowed.insert(std::string(key));
523ece8a530Spatrick 
524ece8a530Spatrick   if (!config->checkFeatures)
525*dfe94b16Srobert     goto done;
5261cf9926bSpatrick 
527bb684c34Spatrick   if (config->sharedMemory) {
528bb684c34Spatrick     if (disallowed.count("shared-mem"))
529bb684c34Spatrick       error("--shared-memory is disallowed by " + disallowed["shared-mem"] +
530bb684c34Spatrick             " because it was not compiled with 'atomics' or 'bulk-memory' "
531bb684c34Spatrick             "features.");
532ece8a530Spatrick 
533bb684c34Spatrick     for (auto feature : {"atomics", "bulk-memory"})
534bb684c34Spatrick       if (!allowed.count(feature))
535bb684c34Spatrick         error(StringRef("'") + feature +
536bb684c34Spatrick               "' feature must be used in order to use shared memory");
537bb684c34Spatrick   }
538ece8a530Spatrick 
539bb684c34Spatrick   if (tlsUsed) {
540bb684c34Spatrick     for (auto feature : {"atomics", "bulk-memory"})
541bb684c34Spatrick       if (!allowed.count(feature))
542bb684c34Spatrick         error(StringRef("'") + feature +
543bb684c34Spatrick               "' feature must be used in order to use thread-local storage");
544bb684c34Spatrick   }
545ece8a530Spatrick 
546ece8a530Spatrick   // Validate that used features are allowed in output
547ece8a530Spatrick   if (!inferFeatures) {
548*dfe94b16Srobert     for (const auto &feature : used.keys()) {
549bb684c34Spatrick       if (!allowed.count(std::string(feature)))
550ece8a530Spatrick         error(Twine("Target feature '") + feature + "' used by " +
551ece8a530Spatrick               used[feature] + " is not allowed.");
552ece8a530Spatrick     }
553ece8a530Spatrick   }
554ece8a530Spatrick 
555ece8a530Spatrick   // Validate the required and disallowed constraints for each file
556ece8a530Spatrick   for (ObjFile *file : symtab->objectFiles) {
557ece8a530Spatrick     StringRef fileName(file->getName());
558ece8a530Spatrick     SmallSet<std::string, 8> objectFeatures;
559*dfe94b16Srobert     for (const auto &feature : file->getWasmObj()->getTargetFeatures()) {
560ece8a530Spatrick       if (feature.Prefix == WASM_FEATURE_PREFIX_DISALLOWED)
561ece8a530Spatrick         continue;
562ece8a530Spatrick       objectFeatures.insert(feature.Name);
563ece8a530Spatrick       if (disallowed.count(feature.Name))
564ece8a530Spatrick         error(Twine("Target feature '") + feature.Name + "' used in " +
565ece8a530Spatrick               fileName + " is disallowed by " + disallowed[feature.Name] +
566ece8a530Spatrick               ". Use --no-check-features to suppress.");
567ece8a530Spatrick     }
568*dfe94b16Srobert     for (const auto &feature : required.keys()) {
569bb684c34Spatrick       if (!objectFeatures.count(std::string(feature)))
570ece8a530Spatrick         error(Twine("Missing target feature '") + feature + "' in " + fileName +
571ece8a530Spatrick               ", required by " + required[feature] +
572ece8a530Spatrick               ". Use --no-check-features to suppress.");
573ece8a530Spatrick     }
574ece8a530Spatrick   }
575*dfe94b16Srobert 
576*dfe94b16Srobert done:
577*dfe94b16Srobert   // Normally we don't include bss segments in the binary.  In particular if
578*dfe94b16Srobert   // memory is not being imported then we can assume its zero initialized.
579*dfe94b16Srobert   // In the case the memory is imported, and we can use the memory.fill
580*dfe94b16Srobert   // instruction, then we can also avoid including the segments.
581*dfe94b16Srobert   if (config->memoryImport.has_value() && !allowed.count("bulk-memory"))
582*dfe94b16Srobert     config->emitBssSegments = true;
583*dfe94b16Srobert 
584*dfe94b16Srobert   if (allowed.count("extended-const"))
585*dfe94b16Srobert     config->extendedConst = true;
586*dfe94b16Srobert 
587*dfe94b16Srobert   for (auto &feature : allowed)
588*dfe94b16Srobert     log("Allowed feature: " + feature);
589*dfe94b16Srobert }
590*dfe94b16Srobert 
checkImportExportTargetFeatures()591*dfe94b16Srobert void Writer::checkImportExportTargetFeatures() {
592*dfe94b16Srobert   if (config->relocatable || !config->checkFeatures)
593*dfe94b16Srobert     return;
594*dfe94b16Srobert 
595*dfe94b16Srobert   if (out.targetFeaturesSec->features.count("mutable-globals") == 0) {
596*dfe94b16Srobert     for (const Symbol *sym : out.importSec->importedSymbols) {
597*dfe94b16Srobert       if (auto *global = dyn_cast<GlobalSymbol>(sym)) {
598*dfe94b16Srobert         if (global->getGlobalType()->Mutable) {
599*dfe94b16Srobert           error(Twine("mutable global imported but 'mutable-globals' feature "
600*dfe94b16Srobert                       "not present in inputs: `") +
601*dfe94b16Srobert                 toString(*sym) + "`. Use --no-check-features to suppress.");
602*dfe94b16Srobert         }
603*dfe94b16Srobert       }
604*dfe94b16Srobert     }
605*dfe94b16Srobert     for (const Symbol *sym : out.exportSec->exportedSymbols) {
606*dfe94b16Srobert       if (isa<GlobalSymbol>(sym)) {
607*dfe94b16Srobert         error(Twine("mutable global exported but 'mutable-globals' feature "
608*dfe94b16Srobert                     "not present in inputs: `") +
609*dfe94b16Srobert               toString(*sym) + "`. Use --no-check-features to suppress.");
610*dfe94b16Srobert       }
611*dfe94b16Srobert     }
612*dfe94b16Srobert   }
613ece8a530Spatrick }
614ece8a530Spatrick 
shouldImport(Symbol * sym)6151cf9926bSpatrick static bool shouldImport(Symbol *sym) {
616*dfe94b16Srobert   // We don't generate imports for data symbols. They however can be imported
617*dfe94b16Srobert   // as GOT entries.
618*dfe94b16Srobert   if (isa<DataSymbol>(sym))
6191cf9926bSpatrick     return false;
620ece8a530Spatrick   if (!sym->isLive())
6211cf9926bSpatrick     return false;
622ece8a530Spatrick   if (!sym->isUsedInRegularObj)
6231cf9926bSpatrick     return false;
6241cf9926bSpatrick 
625*dfe94b16Srobert   // When a symbol is weakly defined in a shared library we need to allow
626*dfe94b16Srobert   // it to be overridden by another module so need to both import
627*dfe94b16Srobert   // and export the symbol.
628*dfe94b16Srobert   if (config->shared && sym->isWeak() && !sym->isUndefined() &&
629*dfe94b16Srobert       !sym->isHidden())
630*dfe94b16Srobert     return true;
631*dfe94b16Srobert   if (!sym->isUndefined())
632*dfe94b16Srobert     return false;
633*dfe94b16Srobert   if (sym->isWeak() && !config->relocatable && !config->isPic)
6341cf9926bSpatrick     return false;
635ece8a530Spatrick 
636*dfe94b16Srobert   // In PIC mode we only need to import functions when they are called directly.
637*dfe94b16Srobert   // Indirect usage all goes via GOT imports.
638*dfe94b16Srobert   if (config->isPic) {
639*dfe94b16Srobert     if (auto *f = dyn_cast<UndefinedFunction>(sym))
640*dfe94b16Srobert       if (!f->isCalledDirectly)
641*dfe94b16Srobert         return false;
642*dfe94b16Srobert   }
643*dfe94b16Srobert 
644*dfe94b16Srobert   if (config->isPic || config->relocatable || config->importUndefined ||
645*dfe94b16Srobert       config->unresolvedSymbols == UnresolvedPolicy::ImportDynamic)
6461cf9926bSpatrick     return true;
6471cf9926bSpatrick   if (config->allowUndefinedSymbols.count(sym->getName()) != 0)
6481cf9926bSpatrick     return true;
6491cf9926bSpatrick 
650*dfe94b16Srobert   return sym->isImported();
6511cf9926bSpatrick }
6521cf9926bSpatrick 
calculateImports()6531cf9926bSpatrick void Writer::calculateImports() {
6541cf9926bSpatrick   // Some inputs require that the indirect function table be assigned to table
6551cf9926bSpatrick   // number 0, so if it is present and is an import, allocate it before any
6561cf9926bSpatrick   // other tables.
6571cf9926bSpatrick   if (WasmSym::indirectFunctionTable &&
6581cf9926bSpatrick       shouldImport(WasmSym::indirectFunctionTable))
6591cf9926bSpatrick     out.importSec->addImport(WasmSym::indirectFunctionTable);
6601cf9926bSpatrick 
661*dfe94b16Srobert   for (Symbol *sym : symtab->symbols()) {
6621cf9926bSpatrick     if (!shouldImport(sym))
6631cf9926bSpatrick       continue;
6641cf9926bSpatrick     if (sym == WasmSym::indirectFunctionTable)
6651cf9926bSpatrick       continue;
666ece8a530Spatrick     LLVM_DEBUG(dbgs() << "import: " << sym->getName() << "\n");
667ece8a530Spatrick     out.importSec->addImport(sym);
668ece8a530Spatrick   }
669ece8a530Spatrick }
670ece8a530Spatrick 
calculateExports()671ece8a530Spatrick void Writer::calculateExports() {
672ece8a530Spatrick   if (config->relocatable)
673ece8a530Spatrick     return;
674ece8a530Spatrick 
675*dfe94b16Srobert   if (!config->relocatable && config->memoryExport.has_value()) {
676ece8a530Spatrick     out.exportSec->exports.push_back(
677*dfe94b16Srobert         WasmExport{*config->memoryExport, WASM_EXTERNAL_MEMORY, 0});
678*dfe94b16Srobert   }
679ece8a530Spatrick 
680ece8a530Spatrick   unsigned globalIndex =
681ece8a530Spatrick       out.importSec->getNumImportedGlobals() + out.globalSec->numGlobals();
682ece8a530Spatrick 
683*dfe94b16Srobert   for (Symbol *sym : symtab->symbols()) {
684ece8a530Spatrick     if (!sym->isExported())
685ece8a530Spatrick       continue;
686ece8a530Spatrick     if (!sym->isLive())
687ece8a530Spatrick       continue;
688ece8a530Spatrick 
689ece8a530Spatrick     StringRef name = sym->getName();
690ece8a530Spatrick     WasmExport export_;
691ece8a530Spatrick     if (auto *f = dyn_cast<DefinedFunction>(sym)) {
692*dfe94b16Srobert       if (std::optional<StringRef> exportName = f->function->getExportName()) {
693bb684c34Spatrick         name = *exportName;
694ece8a530Spatrick       }
695*dfe94b16Srobert       export_ = {name, WASM_EXTERNAL_FUNCTION, f->getExportedFunctionIndex()};
696ece8a530Spatrick     } else if (auto *g = dyn_cast<DefinedGlobal>(sym)) {
6971cf9926bSpatrick       if (g->getGlobalType()->Mutable && !g->getFile() && !g->forceExport) {
6981cf9926bSpatrick         // Avoid exporting mutable globals are linker synthesized (e.g.
6991cf9926bSpatrick         // __stack_pointer or __tls_base) unless they are explicitly exported
7001cf9926bSpatrick         // from the command line.
7011cf9926bSpatrick         // Without this check `--export-all` would cause any program using the
7021cf9926bSpatrick         // stack pointer to export a mutable global even if none of the input
7031cf9926bSpatrick         // files were built with the `mutable-globals` feature.
704ece8a530Spatrick         continue;
705ece8a530Spatrick       }
706ece8a530Spatrick       export_ = {name, WASM_EXTERNAL_GLOBAL, g->getGlobalIndex()};
7071cf9926bSpatrick     } else if (auto *t = dyn_cast<DefinedTag>(sym)) {
7081cf9926bSpatrick       export_ = {name, WASM_EXTERNAL_TAG, t->getTagIndex()};
7091cf9926bSpatrick     } else if (auto *d = dyn_cast<DefinedData>(sym)) {
710ece8a530Spatrick       out.globalSec->dataAddressGlobals.push_back(d);
711ece8a530Spatrick       export_ = {name, WASM_EXTERNAL_GLOBAL, globalIndex++};
7121cf9926bSpatrick     } else {
7131cf9926bSpatrick       auto *t = cast<DefinedTable>(sym);
7141cf9926bSpatrick       export_ = {name, WASM_EXTERNAL_TABLE, t->getTableNumber()};
715ece8a530Spatrick     }
716ece8a530Spatrick 
717ece8a530Spatrick     LLVM_DEBUG(dbgs() << "Export: " << name << "\n");
718ece8a530Spatrick     out.exportSec->exports.push_back(export_);
7191cf9926bSpatrick     out.exportSec->exportedSymbols.push_back(sym);
720ece8a530Spatrick   }
721ece8a530Spatrick }
722ece8a530Spatrick 
populateSymtab()723ece8a530Spatrick void Writer::populateSymtab() {
724ece8a530Spatrick   if (!config->relocatable && !config->emitRelocs)
725ece8a530Spatrick     return;
726ece8a530Spatrick 
727*dfe94b16Srobert   for (Symbol *sym : symtab->symbols())
728ece8a530Spatrick     if (sym->isUsedInRegularObj && sym->isLive())
729ece8a530Spatrick       out.linkingSec->addToSymtab(sym);
730ece8a530Spatrick 
731ece8a530Spatrick   for (ObjFile *file : symtab->objectFiles) {
732ece8a530Spatrick     LLVM_DEBUG(dbgs() << "Local symtab entries: " << file->getName() << "\n");
733ece8a530Spatrick     for (Symbol *sym : file->getSymbols())
734ece8a530Spatrick       if (sym->isLocal() && !isa<SectionSymbol>(sym) && sym->isLive())
735ece8a530Spatrick         out.linkingSec->addToSymtab(sym);
736ece8a530Spatrick   }
737ece8a530Spatrick }
738ece8a530Spatrick 
calculateTypes()739ece8a530Spatrick void Writer::calculateTypes() {
740ece8a530Spatrick   // The output type section is the union of the following sets:
741ece8a530Spatrick   // 1. Any signature used in the TYPE relocation
742ece8a530Spatrick   // 2. The signatures of all imported functions
743ece8a530Spatrick   // 3. The signatures of all defined functions
7441cf9926bSpatrick   // 4. The signatures of all imported tags
7451cf9926bSpatrick   // 5. The signatures of all defined tags
746ece8a530Spatrick 
747ece8a530Spatrick   for (ObjFile *file : symtab->objectFiles) {
748ece8a530Spatrick     ArrayRef<WasmSignature> types = file->getWasmObj()->types();
749ece8a530Spatrick     for (uint32_t i = 0; i < types.size(); i++)
750ece8a530Spatrick       if (file->typeIsUsed[i])
751ece8a530Spatrick         file->typeMap[i] = out.typeSec->registerType(types[i]);
752ece8a530Spatrick   }
753ece8a530Spatrick 
754ece8a530Spatrick   for (const Symbol *sym : out.importSec->importedSymbols) {
755ece8a530Spatrick     if (auto *f = dyn_cast<FunctionSymbol>(sym))
756ece8a530Spatrick       out.typeSec->registerType(*f->signature);
7571cf9926bSpatrick     else if (auto *t = dyn_cast<TagSymbol>(sym))
7581cf9926bSpatrick       out.typeSec->registerType(*t->signature);
759ece8a530Spatrick   }
760ece8a530Spatrick 
761ece8a530Spatrick   for (const InputFunction *f : out.functionSec->inputFunctions)
762ece8a530Spatrick     out.typeSec->registerType(f->signature);
763ece8a530Spatrick 
7641cf9926bSpatrick   for (const InputTag *t : out.tagSec->inputTags)
7651cf9926bSpatrick     out.typeSec->registerType(t->signature);
7661cf9926bSpatrick }
7671cf9926bSpatrick 
7681cf9926bSpatrick // In a command-style link, create a wrapper for each exported symbol
7691cf9926bSpatrick // which calls the constructors and destructors.
createCommandExportWrappers()7701cf9926bSpatrick void Writer::createCommandExportWrappers() {
7711cf9926bSpatrick   // This logic doesn't currently support Emscripten-style PIC mode.
7721cf9926bSpatrick   assert(!config->isPic);
7731cf9926bSpatrick 
7741cf9926bSpatrick   // If there are no ctors and there's no libc `__wasm_call_dtors` to
7751cf9926bSpatrick   // call, don't wrap the exports.
776*dfe94b16Srobert   if (initFunctions.empty() && WasmSym::callDtors == nullptr)
7771cf9926bSpatrick     return;
7781cf9926bSpatrick 
7791cf9926bSpatrick   std::vector<DefinedFunction *> toWrap;
7801cf9926bSpatrick 
781*dfe94b16Srobert   for (Symbol *sym : symtab->symbols())
7821cf9926bSpatrick     if (sym->isExported())
7831cf9926bSpatrick       if (auto *f = dyn_cast<DefinedFunction>(sym))
7841cf9926bSpatrick         toWrap.push_back(f);
7851cf9926bSpatrick 
7861cf9926bSpatrick   for (auto *f : toWrap) {
7871cf9926bSpatrick     auto funcNameStr = (f->getName() + ".command_export").str();
7881cf9926bSpatrick     commandExportWrapperNames.push_back(funcNameStr);
7891cf9926bSpatrick     const std::string &funcName = commandExportWrapperNames.back();
7901cf9926bSpatrick 
7911cf9926bSpatrick     auto func = make<SyntheticFunction>(*f->getSignature(), funcName);
792*dfe94b16Srobert     if (f->function->getExportName())
7931cf9926bSpatrick       func->setExportName(f->function->getExportName()->str());
7941cf9926bSpatrick     else
7951cf9926bSpatrick       func->setExportName(f->getName().str());
7961cf9926bSpatrick 
7971cf9926bSpatrick     DefinedFunction *def =
7981cf9926bSpatrick         symtab->addSyntheticFunction(funcName, f->flags, func);
7991cf9926bSpatrick     def->markLive();
8001cf9926bSpatrick 
8011cf9926bSpatrick     def->flags |= WASM_SYMBOL_EXPORTED;
8021cf9926bSpatrick     def->flags &= ~WASM_SYMBOL_VISIBILITY_HIDDEN;
8031cf9926bSpatrick     def->forceExport = f->forceExport;
8041cf9926bSpatrick 
8051cf9926bSpatrick     f->flags |= WASM_SYMBOL_VISIBILITY_HIDDEN;
8061cf9926bSpatrick     f->flags &= ~WASM_SYMBOL_EXPORTED;
8071cf9926bSpatrick     f->forceExport = false;
8081cf9926bSpatrick 
8091cf9926bSpatrick     out.functionSec->addFunction(func);
8101cf9926bSpatrick 
8111cf9926bSpatrick     createCommandExportWrapper(f->getFunctionIndex(), def);
8121cf9926bSpatrick   }
8131cf9926bSpatrick }
8141cf9926bSpatrick 
finalizeIndirectFunctionTable()8151cf9926bSpatrick static void finalizeIndirectFunctionTable() {
8161cf9926bSpatrick   if (!WasmSym::indirectFunctionTable)
8171cf9926bSpatrick     return;
8181cf9926bSpatrick 
8191cf9926bSpatrick   if (shouldImport(WasmSym::indirectFunctionTable) &&
8201cf9926bSpatrick       !WasmSym::indirectFunctionTable->hasTableNumber()) {
8211cf9926bSpatrick     // Processing -Bsymbolic relocations resulted in a late requirement that the
8221cf9926bSpatrick     // indirect function table be present, and we are running in --import-table
8231cf9926bSpatrick     // mode.  Add the table now to the imports section.  Otherwise it will be
8241cf9926bSpatrick     // added to the tables section later in assignIndexes.
8251cf9926bSpatrick     out.importSec->addImport(WasmSym::indirectFunctionTable);
8261cf9926bSpatrick   }
8271cf9926bSpatrick 
8281cf9926bSpatrick   uint32_t tableSize = config->tableBase + out.elemSec->numEntries();
8291cf9926bSpatrick   WasmLimits limits = {0, tableSize, 0};
8301cf9926bSpatrick   if (WasmSym::indirectFunctionTable->isDefined() && !config->growableTable) {
8311cf9926bSpatrick     limits.Flags |= WASM_LIMITS_FLAG_HAS_MAX;
8321cf9926bSpatrick     limits.Maximum = limits.Minimum;
8331cf9926bSpatrick   }
8341cf9926bSpatrick   WasmSym::indirectFunctionTable->setLimits(limits);
835ece8a530Spatrick }
836ece8a530Spatrick 
scanRelocations()837ece8a530Spatrick static void scanRelocations() {
838ece8a530Spatrick   for (ObjFile *file : symtab->objectFiles) {
839ece8a530Spatrick     LLVM_DEBUG(dbgs() << "scanRelocations: " << file->getName() << "\n");
840ece8a530Spatrick     for (InputChunk *chunk : file->functions)
841ece8a530Spatrick       scanRelocations(chunk);
842ece8a530Spatrick     for (InputChunk *chunk : file->segments)
843ece8a530Spatrick       scanRelocations(chunk);
844ece8a530Spatrick     for (auto &p : file->customSections)
845ece8a530Spatrick       scanRelocations(p);
846ece8a530Spatrick   }
847ece8a530Spatrick }
848ece8a530Spatrick 
assignIndexes()849ece8a530Spatrick void Writer::assignIndexes() {
850ece8a530Spatrick   // Seal the import section, since other index spaces such as function and
851ece8a530Spatrick   // global are effected by the number of imports.
852ece8a530Spatrick   out.importSec->seal();
853ece8a530Spatrick 
854ece8a530Spatrick   for (InputFunction *func : symtab->syntheticFunctions)
855ece8a530Spatrick     out.functionSec->addFunction(func);
856ece8a530Spatrick 
857ece8a530Spatrick   for (ObjFile *file : symtab->objectFiles) {
858ece8a530Spatrick     LLVM_DEBUG(dbgs() << "Functions: " << file->getName() << "\n");
859ece8a530Spatrick     for (InputFunction *func : file->functions)
860ece8a530Spatrick       out.functionSec->addFunction(func);
861ece8a530Spatrick   }
862ece8a530Spatrick 
863ece8a530Spatrick   for (InputGlobal *global : symtab->syntheticGlobals)
864ece8a530Spatrick     out.globalSec->addGlobal(global);
865ece8a530Spatrick 
866ece8a530Spatrick   for (ObjFile *file : symtab->objectFiles) {
867ece8a530Spatrick     LLVM_DEBUG(dbgs() << "Globals: " << file->getName() << "\n");
868ece8a530Spatrick     for (InputGlobal *global : file->globals)
869ece8a530Spatrick       out.globalSec->addGlobal(global);
870ece8a530Spatrick   }
871ece8a530Spatrick 
872ece8a530Spatrick   for (ObjFile *file : symtab->objectFiles) {
8731cf9926bSpatrick     LLVM_DEBUG(dbgs() << "Tags: " << file->getName() << "\n");
8741cf9926bSpatrick     for (InputTag *tag : file->tags)
8751cf9926bSpatrick       out.tagSec->addTag(tag);
876ece8a530Spatrick   }
877ece8a530Spatrick 
8781cf9926bSpatrick   for (ObjFile *file : symtab->objectFiles) {
8791cf9926bSpatrick     LLVM_DEBUG(dbgs() << "Tables: " << file->getName() << "\n");
8801cf9926bSpatrick     for (InputTable *table : file->tables)
8811cf9926bSpatrick       out.tableSec->addTable(table);
8821cf9926bSpatrick   }
8831cf9926bSpatrick 
8841cf9926bSpatrick   for (InputTable *table : symtab->syntheticTables)
8851cf9926bSpatrick     out.tableSec->addTable(table);
8861cf9926bSpatrick 
887ece8a530Spatrick   out.globalSec->assignIndexes();
8881cf9926bSpatrick   out.tableSec->assignIndexes();
889ece8a530Spatrick }
890ece8a530Spatrick 
getOutputDataSegmentName(const InputChunk & seg)8911cf9926bSpatrick static StringRef getOutputDataSegmentName(const InputChunk &seg) {
8921cf9926bSpatrick   // We always merge .tbss and .tdata into a single TLS segment so all TLS
8931cf9926bSpatrick   // symbols are be relative to single __tls_base.
8941cf9926bSpatrick   if (seg.isTLS())
895ece8a530Spatrick     return ".tdata";
896ece8a530Spatrick   if (!config->mergeDataSegments)
897*dfe94b16Srobert     return seg.name;
898*dfe94b16Srobert   if (seg.name.startswith(".text."))
899ece8a530Spatrick     return ".text";
900*dfe94b16Srobert   if (seg.name.startswith(".data."))
901ece8a530Spatrick     return ".data";
902*dfe94b16Srobert   if (seg.name.startswith(".bss."))
903ece8a530Spatrick     return ".bss";
904*dfe94b16Srobert   if (seg.name.startswith(".rodata."))
905ece8a530Spatrick     return ".rodata";
906*dfe94b16Srobert   return seg.name;
907ece8a530Spatrick }
908ece8a530Spatrick 
createOutputSegment(StringRef name)9091cf9926bSpatrick OutputSegment *Writer::createOutputSegment(StringRef name) {
910ece8a530Spatrick   LLVM_DEBUG(dbgs() << "new segment: " << name << "\n");
9111cf9926bSpatrick   OutputSegment *s = make<OutputSegment>(name);
9121cf9926bSpatrick   if (config->sharedMemory)
9131cf9926bSpatrick     s->initFlags = WASM_DATA_SEGMENT_IS_PASSIVE;
914*dfe94b16Srobert   if (!config->relocatable && name.startswith(".bss"))
915ece8a530Spatrick     s->isBss = true;
916ece8a530Spatrick   segments.push_back(s);
9171cf9926bSpatrick   return s;
9181cf9926bSpatrick }
9191cf9926bSpatrick 
createOutputSegments()9201cf9926bSpatrick void Writer::createOutputSegments() {
9211cf9926bSpatrick   for (ObjFile *file : symtab->objectFiles) {
9221cf9926bSpatrick     for (InputChunk *segment : file->segments) {
9231cf9926bSpatrick       if (!segment->live)
9241cf9926bSpatrick         continue;
9251cf9926bSpatrick       StringRef name = getOutputDataSegmentName(*segment);
9261cf9926bSpatrick       OutputSegment *s = nullptr;
9271cf9926bSpatrick       // When running in relocatable mode we can't merge segments that are part
9281cf9926bSpatrick       // of comdat groups since the ultimate linker needs to be able exclude or
9291cf9926bSpatrick       // include them individually.
9301cf9926bSpatrick       if (config->relocatable && !segment->getComdatName().empty()) {
9311cf9926bSpatrick         s = createOutputSegment(name);
9321cf9926bSpatrick       } else {
9331cf9926bSpatrick         if (segmentMap.count(name) == 0)
9341cf9926bSpatrick           segmentMap[name] = createOutputSegment(name);
9351cf9926bSpatrick         s = segmentMap[name];
936ece8a530Spatrick       }
937ece8a530Spatrick       s->addInputSegment(segment);
938ece8a530Spatrick     }
939ece8a530Spatrick   }
940ece8a530Spatrick 
941ece8a530Spatrick   // Sort segments by type, placing .bss last
942ece8a530Spatrick   std::stable_sort(segments.begin(), segments.end(),
943ece8a530Spatrick                    [](const OutputSegment *a, const OutputSegment *b) {
944ece8a530Spatrick                      auto order = [](StringRef name) {
945ece8a530Spatrick                        return StringSwitch<int>(name)
9461cf9926bSpatrick                            .StartsWith(".tdata", 0)
9471cf9926bSpatrick                            .StartsWith(".rodata", 1)
9481cf9926bSpatrick                            .StartsWith(".data", 2)
949ece8a530Spatrick                            .StartsWith(".bss", 4)
950ece8a530Spatrick                            .Default(3);
951ece8a530Spatrick                      };
952ece8a530Spatrick                      return order(a->name) < order(b->name);
953ece8a530Spatrick                    });
954ece8a530Spatrick 
955ece8a530Spatrick   for (size_t i = 0; i < segments.size(); ++i)
956ece8a530Spatrick     segments[i]->index = i;
9571cf9926bSpatrick 
9581cf9926bSpatrick   // Merge MergeInputSections into a single MergeSyntheticSection.
9591cf9926bSpatrick   LLVM_DEBUG(dbgs() << "-- finalize input semgments\n");
9601cf9926bSpatrick   for (OutputSegment *seg : segments)
9611cf9926bSpatrick     seg->finalizeInputSegments();
9621cf9926bSpatrick }
9631cf9926bSpatrick 
combineOutputSegments()9641cf9926bSpatrick void Writer::combineOutputSegments() {
9651cf9926bSpatrick   // With PIC code we currently only support a single active data segment since
9661cf9926bSpatrick   // we only have a single __memory_base to use as our base address.  This pass
9671cf9926bSpatrick   // combines all data segments into a single .data segment.
968*dfe94b16Srobert   // This restriction does not apply when the extended const extension is
969*dfe94b16Srobert   // available: https://github.com/WebAssembly/extended-const
970*dfe94b16Srobert   assert(!config->extendedConst);
9711cf9926bSpatrick   assert(config->isPic && !config->sharedMemory);
9721cf9926bSpatrick   if (segments.size() <= 1)
9731cf9926bSpatrick     return;
9741cf9926bSpatrick   OutputSegment *combined = make<OutputSegment>(".data");
9751cf9926bSpatrick   combined->startVA = segments[0]->startVA;
9761cf9926bSpatrick   for (OutputSegment *s : segments) {
9771cf9926bSpatrick     bool first = true;
9781cf9926bSpatrick     for (InputChunk *inSeg : s->inputSegments) {
9791cf9926bSpatrick       if (first)
9801cf9926bSpatrick         inSeg->alignment = std::max(inSeg->alignment, s->alignment);
9811cf9926bSpatrick       first = false;
9821cf9926bSpatrick #ifndef NDEBUG
9831cf9926bSpatrick       uint64_t oldVA = inSeg->getVA();
9841cf9926bSpatrick #endif
9851cf9926bSpatrick       combined->addInputSegment(inSeg);
9861cf9926bSpatrick #ifndef NDEBUG
9871cf9926bSpatrick       uint64_t newVA = inSeg->getVA();
988*dfe94b16Srobert       LLVM_DEBUG(dbgs() << "added input segment. name=" << inSeg->name
9891cf9926bSpatrick                         << " oldVA=" << oldVA << " newVA=" << newVA << "\n");
9901cf9926bSpatrick       assert(oldVA == newVA);
9911cf9926bSpatrick #endif
9921cf9926bSpatrick     }
9931cf9926bSpatrick   }
9941cf9926bSpatrick 
9951cf9926bSpatrick   segments = {combined};
996ece8a530Spatrick }
997ece8a530Spatrick 
createFunction(DefinedFunction * func,StringRef bodyContent)998ece8a530Spatrick static void createFunction(DefinedFunction *func, StringRef bodyContent) {
999ece8a530Spatrick   std::string functionBody;
1000ece8a530Spatrick   {
1001ece8a530Spatrick     raw_string_ostream os(functionBody);
1002ece8a530Spatrick     writeUleb128(os, bodyContent.size(), "function size");
1003ece8a530Spatrick     os << bodyContent;
1004ece8a530Spatrick   }
1005*dfe94b16Srobert   ArrayRef<uint8_t> body = arrayRefFromStringRef(saver().save(functionBody));
1006ece8a530Spatrick   cast<SyntheticFunction>(func->function)->setBody(body);
1007ece8a530Spatrick }
1008ece8a530Spatrick 
needsPassiveInitialization(const OutputSegment * segment)1009bb684c34Spatrick bool Writer::needsPassiveInitialization(const OutputSegment *segment) {
1010*dfe94b16Srobert   // If bulk memory features is supported then we can perform bss initialization
1011*dfe94b16Srobert   // (via memory.fill) during `__wasm_init_memory`.
1012*dfe94b16Srobert   if (config->memoryImport.has_value() && !segment->requiredInBinary())
1013*dfe94b16Srobert     return true;
1014*dfe94b16Srobert   return segment->initFlags & WASM_DATA_SEGMENT_IS_PASSIVE;
1015bb684c34Spatrick }
1016bb684c34Spatrick 
hasPassiveInitializedSegments()1017bb684c34Spatrick bool Writer::hasPassiveInitializedSegments() {
1018*dfe94b16Srobert   return llvm::any_of(segments, [this](const OutputSegment *s) {
1019bb684c34Spatrick     return this->needsPassiveInitialization(s);
1020*dfe94b16Srobert   });
1021bb684c34Spatrick }
1022bb684c34Spatrick 
createSyntheticInitFunctions()10231cf9926bSpatrick void Writer::createSyntheticInitFunctions() {
10241cf9926bSpatrick   if (config->relocatable)
10251cf9926bSpatrick     return;
10261cf9926bSpatrick 
10271cf9926bSpatrick   static WasmSignature nullSignature = {{}, {}};
10281cf9926bSpatrick 
10291cf9926bSpatrick   // Passive segments are used to avoid memory being reinitialized on each
10301cf9926bSpatrick   // thread's instantiation. These passive segments are initialized and
10311cf9926bSpatrick   // dropped in __wasm_init_memory, which is registered as the start function
1032*dfe94b16Srobert   // We also initialize bss segments (using memory.fill) as part of this
1033*dfe94b16Srobert   // function.
1034*dfe94b16Srobert   if (hasPassiveInitializedSegments()) {
10351cf9926bSpatrick     WasmSym::initMemory = symtab->addSyntheticFunction(
10361cf9926bSpatrick         "__wasm_init_memory", WASM_SYMBOL_VISIBILITY_HIDDEN,
10371cf9926bSpatrick         make<SyntheticFunction>(nullSignature, "__wasm_init_memory"));
10381cf9926bSpatrick     WasmSym::initMemory->markLive();
1039*dfe94b16Srobert     if (config->sharedMemory) {
1040*dfe94b16Srobert       // This global is assigned during  __wasm_init_memory in the shared memory
1041*dfe94b16Srobert       // case.
1042*dfe94b16Srobert       WasmSym::tlsBase->markLive();
1043*dfe94b16Srobert     }
10441cf9926bSpatrick   }
10451cf9926bSpatrick 
1046*dfe94b16Srobert   if (config->sharedMemory && out.globalSec->needsTLSRelocations()) {
1047*dfe94b16Srobert     WasmSym::applyGlobalTLSRelocs = symtab->addSyntheticFunction(
1048*dfe94b16Srobert         "__wasm_apply_global_tls_relocs", WASM_SYMBOL_VISIBILITY_HIDDEN,
1049*dfe94b16Srobert         make<SyntheticFunction>(nullSignature,
1050*dfe94b16Srobert                                 "__wasm_apply_global_tls_relocs"));
1051*dfe94b16Srobert     WasmSym::applyGlobalTLSRelocs->markLive();
1052*dfe94b16Srobert     // TLS relocations depend on  the __tls_base symbols
1053*dfe94b16Srobert     WasmSym::tlsBase->markLive();
1054*dfe94b16Srobert   }
10551cf9926bSpatrick 
1056*dfe94b16Srobert   if (config->isPic && out.globalSec->needsRelocations()) {
10571cf9926bSpatrick     WasmSym::applyGlobalRelocs = symtab->addSyntheticFunction(
10581cf9926bSpatrick         "__wasm_apply_global_relocs", WASM_SYMBOL_VISIBILITY_HIDDEN,
10591cf9926bSpatrick         make<SyntheticFunction>(nullSignature, "__wasm_apply_global_relocs"));
10601cf9926bSpatrick     WasmSym::applyGlobalRelocs->markLive();
10611cf9926bSpatrick   }
10621cf9926bSpatrick 
1063*dfe94b16Srobert   // If there is only one start function we can just use that function
1064*dfe94b16Srobert   // itself as the Wasm start function, otherwise we need to synthesize
1065*dfe94b16Srobert   // a new function to call them in sequence.
10661cf9926bSpatrick   if (WasmSym::applyGlobalRelocs && WasmSym::initMemory) {
10671cf9926bSpatrick     WasmSym::startFunction = symtab->addSyntheticFunction(
10681cf9926bSpatrick         "__wasm_start", WASM_SYMBOL_VISIBILITY_HIDDEN,
10691cf9926bSpatrick         make<SyntheticFunction>(nullSignature, "__wasm_start"));
10701cf9926bSpatrick     WasmSym::startFunction->markLive();
10711cf9926bSpatrick   }
10721cf9926bSpatrick }
10731cf9926bSpatrick 
createInitMemoryFunction()1074ece8a530Spatrick void Writer::createInitMemoryFunction() {
1075ece8a530Spatrick   LLVM_DEBUG(dbgs() << "createInitMemoryFunction\n");
10761cf9926bSpatrick   assert(WasmSym::initMemory);
10771cf9926bSpatrick   assert(hasPassiveInitializedSegments());
1078*dfe94b16Srobert   uint64_t flagAddress;
1079*dfe94b16Srobert   if (config->sharedMemory) {
1080*dfe94b16Srobert     assert(WasmSym::initMemoryFlag);
1081*dfe94b16Srobert     flagAddress = WasmSym::initMemoryFlag->getVA();
1082*dfe94b16Srobert   }
1083*dfe94b16Srobert   bool is64 = config->is64.value_or(false);
1084ece8a530Spatrick   std::string bodyContent;
1085ece8a530Spatrick   {
1086ece8a530Spatrick     raw_string_ostream os(bodyContent);
1087ece8a530Spatrick     // Initialize memory in a thread-safe manner. The thread that successfully
1088*dfe94b16Srobert     // increments the flag from 0 to 1 is responsible for performing the memory
1089*dfe94b16Srobert     // initialization. Other threads go sleep on the flag until the first thread
1090*dfe94b16Srobert     // finishing initializing memory, increments the flag to 2, and wakes all
1091*dfe94b16Srobert     // the other threads. Once the flag has been set to 2, subsequently started
1092*dfe94b16Srobert     // threads will skip the sleep. All threads unconditionally drop their
1093*dfe94b16Srobert     // passive data segments once memory has been initialized. The generated
1094*dfe94b16Srobert     // code is as follows:
1095ece8a530Spatrick     //
1096ece8a530Spatrick     // (func $__wasm_init_memory
1097*dfe94b16Srobert     //  (block $drop
1098*dfe94b16Srobert     //   (block $wait
1099*dfe94b16Srobert     //    (block $init
1100*dfe94b16Srobert     //     (br_table $init $wait $drop
1101ece8a530Spatrick     //      (i32.atomic.rmw.cmpxchg align=2 offset=0
1102ece8a530Spatrick     //       (i32.const $__init_memory_flag)
1103ece8a530Spatrick     //       (i32.const 0)
1104ece8a530Spatrick     //       (i32.const 1)
1105ece8a530Spatrick     //      )
1106ece8a530Spatrick     //     )
1107*dfe94b16Srobert     //    ) ;; $init
1108ece8a530Spatrick     //    ( ... initialize data segments ... )
1109ece8a530Spatrick     //    (i32.atomic.store align=2 offset=0
1110ece8a530Spatrick     //     (i32.const $__init_memory_flag)
1111ece8a530Spatrick     //     (i32.const 2)
1112ece8a530Spatrick     //    )
1113ece8a530Spatrick     //    (drop
1114ece8a530Spatrick     //     (i32.atomic.notify align=2 offset=0
1115ece8a530Spatrick     //      (i32.const $__init_memory_flag)
1116ece8a530Spatrick     //      (i32.const -1u)
1117ece8a530Spatrick     //     )
1118ece8a530Spatrick     //    )
1119*dfe94b16Srobert     //    (br $drop)
1120*dfe94b16Srobert     //   ) ;; $wait
1121*dfe94b16Srobert     //   (drop
1122*dfe94b16Srobert     //    (i32.atomic.wait align=2 offset=0
1123*dfe94b16Srobert     //     (i32.const $__init_memory_flag)
1124*dfe94b16Srobert     //     (i32.const 1)
1125*dfe94b16Srobert     //     (i32.const -1)
1126ece8a530Spatrick     //    )
1127ece8a530Spatrick     //   )
1128*dfe94b16Srobert     //  ) ;; $drop
1129ece8a530Spatrick     //  ( ... drop data segments ... )
1130ece8a530Spatrick     // )
11311cf9926bSpatrick     //
11321cf9926bSpatrick     // When we are building with PIC, calculate the flag location using:
11331cf9926bSpatrick     //
11341cf9926bSpatrick     //    (global.get $__memory_base)
11351cf9926bSpatrick     //    (i32.const $__init_memory_flag)
11361cf9926bSpatrick     //    (i32.const 1)
11371cf9926bSpatrick 
1138*dfe94b16Srobert     auto writeGetFlagAddress = [&]() {
1139*dfe94b16Srobert       if (config->isPic) {
1140*dfe94b16Srobert         writeU8(os, WASM_OPCODE_LOCAL_GET, "local.get");
1141*dfe94b16Srobert         writeUleb128(os, 0, "local 0");
1142*dfe94b16Srobert       } else {
1143*dfe94b16Srobert         writePtrConst(os, flagAddress, is64, "flag address");
1144*dfe94b16Srobert       }
1145*dfe94b16Srobert     };
1146*dfe94b16Srobert 
1147*dfe94b16Srobert     if (config->sharedMemory) {
11481cf9926bSpatrick       // With PIC code we cache the flag address in local 0
11491cf9926bSpatrick       if (config->isPic) {
11501cf9926bSpatrick         writeUleb128(os, 1, "num local decls");
1151*dfe94b16Srobert         writeUleb128(os, 2, "local count");
11521cf9926bSpatrick         writeU8(os, is64 ? WASM_TYPE_I64 : WASM_TYPE_I32, "address type");
11531cf9926bSpatrick         writeU8(os, WASM_OPCODE_GLOBAL_GET, "GLOBAL_GET");
11541cf9926bSpatrick         writeUleb128(os, WasmSym::memoryBase->getGlobalIndex(), "memory_base");
11551cf9926bSpatrick         writePtrConst(os, flagAddress, is64, "flag address");
11561cf9926bSpatrick         writeU8(os, is64 ? WASM_OPCODE_I64_ADD : WASM_OPCODE_I32_ADD, "add");
11571cf9926bSpatrick         writeU8(os, WASM_OPCODE_LOCAL_SET, "local.set");
11581cf9926bSpatrick         writeUleb128(os, 0, "local 0");
11591cf9926bSpatrick       } else {
11601cf9926bSpatrick         writeUleb128(os, 0, "num locals");
11611cf9926bSpatrick       }
11621cf9926bSpatrick 
1163*dfe94b16Srobert       // Set up destination blocks
1164*dfe94b16Srobert       writeU8(os, WASM_OPCODE_BLOCK, "block $drop");
1165*dfe94b16Srobert       writeU8(os, WASM_TYPE_NORESULT, "block type");
1166*dfe94b16Srobert       writeU8(os, WASM_OPCODE_BLOCK, "block $wait");
1167*dfe94b16Srobert       writeU8(os, WASM_TYPE_NORESULT, "block type");
1168*dfe94b16Srobert       writeU8(os, WASM_OPCODE_BLOCK, "block $init");
1169*dfe94b16Srobert       writeU8(os, WASM_TYPE_NORESULT, "block type");
1170ece8a530Spatrick 
1171*dfe94b16Srobert       // Atomically check whether we win the race.
11721cf9926bSpatrick       writeGetFlagAddress();
1173ece8a530Spatrick       writeI32Const(os, 0, "expected flag value");
1174*dfe94b16Srobert       writeI32Const(os, 1, "new flag value");
1175ece8a530Spatrick       writeU8(os, WASM_OPCODE_ATOMICS_PREFIX, "atomics prefix");
1176ece8a530Spatrick       writeUleb128(os, WASM_OPCODE_I32_RMW_CMPXCHG, "i32.atomic.rmw.cmpxchg");
1177ece8a530Spatrick       writeMemArg(os, 2, 0);
1178ece8a530Spatrick 
1179*dfe94b16Srobert       // Based on the value, decide what to do next.
1180*dfe94b16Srobert       writeU8(os, WASM_OPCODE_BR_TABLE, "br_table");
1181*dfe94b16Srobert       writeUleb128(os, 2, "label vector length");
1182*dfe94b16Srobert       writeUleb128(os, 0, "label $init");
1183*dfe94b16Srobert       writeUleb128(os, 1, "label $wait");
1184*dfe94b16Srobert       writeUleb128(os, 2, "default label $drop");
11851cf9926bSpatrick 
1186*dfe94b16Srobert       // Initialize passive data segments
1187*dfe94b16Srobert       writeU8(os, WASM_OPCODE_END, "end $init");
1188*dfe94b16Srobert     } else {
1189*dfe94b16Srobert       writeUleb128(os, 0, "num local decls");
1190*dfe94b16Srobert     }
1191ece8a530Spatrick 
1192ece8a530Spatrick     for (const OutputSegment *s : segments) {
1193bb684c34Spatrick       if (needsPassiveInitialization(s)) {
1194*dfe94b16Srobert         // For passive BSS segments we can simple issue a memory.fill(0).
1195*dfe94b16Srobert         // For non-BSS segments we do a memory.init.  Both these
1196*dfe94b16Srobert         // instructions take as their first argument the destination
1197*dfe94b16Srobert         // address.
11981cf9926bSpatrick         writePtrConst(os, s->startVA, is64, "destination address");
11991cf9926bSpatrick         if (config->isPic) {
12001cf9926bSpatrick           writeU8(os, WASM_OPCODE_GLOBAL_GET, "GLOBAL_GET");
12011cf9926bSpatrick           writeUleb128(os, WasmSym::memoryBase->getGlobalIndex(),
1202*dfe94b16Srobert                        "__memory_base");
12031cf9926bSpatrick           writeU8(os, is64 ? WASM_OPCODE_I64_ADD : WASM_OPCODE_I32_ADD,
12041cf9926bSpatrick                   "i32.add");
12051cf9926bSpatrick         }
1206*dfe94b16Srobert 
1207*dfe94b16Srobert         // When we initialize the TLS segment we also set the `__tls_base`
1208*dfe94b16Srobert         // global.  This allows the runtime to use this static copy of the
1209*dfe94b16Srobert         // TLS data for the first/main thread.
1210*dfe94b16Srobert         if (config->sharedMemory && s->isTLS()) {
1211*dfe94b16Srobert           if (config->isPic) {
1212*dfe94b16Srobert             // Cache the result of the addionion in local 0
1213*dfe94b16Srobert             writeU8(os, WASM_OPCODE_LOCAL_TEE, "local.tee");
1214*dfe94b16Srobert             writeUleb128(os, 1, "local 1");
1215*dfe94b16Srobert           } else {
1216*dfe94b16Srobert             writePtrConst(os, s->startVA, is64, "destination address");
1217*dfe94b16Srobert           }
1218*dfe94b16Srobert           writeU8(os, WASM_OPCODE_GLOBAL_SET, "GLOBAL_SET");
1219*dfe94b16Srobert           writeUleb128(os, WasmSym::tlsBase->getGlobalIndex(),
1220*dfe94b16Srobert                        "__tls_base");
1221*dfe94b16Srobert           if (config->isPic) {
1222*dfe94b16Srobert             writeU8(os, WASM_OPCODE_LOCAL_GET, "local.tee");
1223*dfe94b16Srobert             writeUleb128(os, 1, "local 1");
1224*dfe94b16Srobert           }
1225*dfe94b16Srobert         }
1226*dfe94b16Srobert 
1227*dfe94b16Srobert         if (s->isBss) {
1228*dfe94b16Srobert           writeI32Const(os, 0, "fill value");
1229*dfe94b16Srobert           writePtrConst(os, s->size, is64, "memory region size");
1230*dfe94b16Srobert           writeU8(os, WASM_OPCODE_MISC_PREFIX, "bulk-memory prefix");
1231*dfe94b16Srobert           writeUleb128(os, WASM_OPCODE_MEMORY_FILL, "memory.fill");
1232*dfe94b16Srobert           writeU8(os, 0, "memory index immediate");
1233*dfe94b16Srobert         } else {
1234*dfe94b16Srobert           writeI32Const(os, 0, "source segment offset");
1235ece8a530Spatrick           writeI32Const(os, s->size, "memory region size");
1236ece8a530Spatrick           writeU8(os, WASM_OPCODE_MISC_PREFIX, "bulk-memory prefix");
1237ece8a530Spatrick           writeUleb128(os, WASM_OPCODE_MEMORY_INIT, "memory.init");
1238ece8a530Spatrick           writeUleb128(os, s->index, "segment index immediate");
1239ece8a530Spatrick           writeU8(os, 0, "memory index immediate");
1240ece8a530Spatrick         }
1241ece8a530Spatrick       }
1242*dfe94b16Srobert     }
1243ece8a530Spatrick 
1244*dfe94b16Srobert     if (config->sharedMemory) {
1245ece8a530Spatrick       // Set flag to 2 to mark end of initialization
12461cf9926bSpatrick       writeGetFlagAddress();
1247ece8a530Spatrick       writeI32Const(os, 2, "flag value");
1248ece8a530Spatrick       writeU8(os, WASM_OPCODE_ATOMICS_PREFIX, "atomics prefix");
1249ece8a530Spatrick       writeUleb128(os, WASM_OPCODE_I32_ATOMIC_STORE, "i32.atomic.store");
1250ece8a530Spatrick       writeMemArg(os, 2, 0);
1251ece8a530Spatrick 
1252ece8a530Spatrick       // Notify any waiters that memory initialization is complete
12531cf9926bSpatrick       writeGetFlagAddress();
1254ece8a530Spatrick       writeI32Const(os, -1, "number of waiters");
1255ece8a530Spatrick       writeU8(os, WASM_OPCODE_ATOMICS_PREFIX, "atomics prefix");
1256ece8a530Spatrick       writeUleb128(os, WASM_OPCODE_ATOMIC_NOTIFY, "atomic.notify");
1257ece8a530Spatrick       writeMemArg(os, 2, 0);
1258ece8a530Spatrick       writeU8(os, WASM_OPCODE_DROP, "drop");
1259ece8a530Spatrick 
1260*dfe94b16Srobert       // Branch to drop the segments
1261*dfe94b16Srobert       writeU8(os, WASM_OPCODE_BR, "br");
1262*dfe94b16Srobert       writeUleb128(os, 1, "label $drop");
1263*dfe94b16Srobert 
1264*dfe94b16Srobert       // Wait for the winning thread to initialize memory
1265*dfe94b16Srobert       writeU8(os, WASM_OPCODE_END, "end $wait");
1266*dfe94b16Srobert       writeGetFlagAddress();
1267*dfe94b16Srobert       writeI32Const(os, 1, "expected flag value");
1268*dfe94b16Srobert       writeI64Const(os, -1, "timeout");
1269*dfe94b16Srobert 
1270*dfe94b16Srobert       writeU8(os, WASM_OPCODE_ATOMICS_PREFIX, "atomics prefix");
1271*dfe94b16Srobert       writeUleb128(os, WASM_OPCODE_I32_ATOMIC_WAIT, "i32.atomic.wait");
1272*dfe94b16Srobert       writeMemArg(os, 2, 0);
1273*dfe94b16Srobert       writeU8(os, WASM_OPCODE_DROP, "drop");
1274ece8a530Spatrick 
1275ece8a530Spatrick       // Unconditionally drop passive data segments
1276*dfe94b16Srobert       writeU8(os, WASM_OPCODE_END, "end $drop");
1277*dfe94b16Srobert     }
1278*dfe94b16Srobert 
1279ece8a530Spatrick     for (const OutputSegment *s : segments) {
1280*dfe94b16Srobert       if (needsPassiveInitialization(s) && !s->isBss) {
1281*dfe94b16Srobert         // The TLS region should not be dropped since its is needed
1282*dfe94b16Srobert         // during the initialization of each thread (__wasm_init_tls).
1283*dfe94b16Srobert         if (config->sharedMemory && s->isTLS())
1284*dfe94b16Srobert           continue;
1285ece8a530Spatrick         // data.drop instruction
1286ece8a530Spatrick         writeU8(os, WASM_OPCODE_MISC_PREFIX, "bulk-memory prefix");
1287ece8a530Spatrick         writeUleb128(os, WASM_OPCODE_DATA_DROP, "data.drop");
1288ece8a530Spatrick         writeUleb128(os, s->index, "segment index immediate");
1289ece8a530Spatrick       }
1290ece8a530Spatrick     }
1291*dfe94b16Srobert 
1292*dfe94b16Srobert     // End the function
1293ece8a530Spatrick     writeU8(os, WASM_OPCODE_END, "END");
1294ece8a530Spatrick   }
1295ece8a530Spatrick 
1296ece8a530Spatrick   createFunction(WasmSym::initMemory, bodyContent);
1297ece8a530Spatrick }
1298ece8a530Spatrick 
createStartFunction()12991cf9926bSpatrick void Writer::createStartFunction() {
1300*dfe94b16Srobert   // If the start function exists when we have more than one function to call.
1301*dfe94b16Srobert   if (WasmSym::initMemory && WasmSym::applyGlobalRelocs) {
1302*dfe94b16Srobert     assert(WasmSym::startFunction);
13031cf9926bSpatrick     std::string bodyContent;
13041cf9926bSpatrick     {
13051cf9926bSpatrick       raw_string_ostream os(bodyContent);
13061cf9926bSpatrick       writeUleb128(os, 0, "num locals");
13071cf9926bSpatrick       writeU8(os, WASM_OPCODE_CALL, "CALL");
1308*dfe94b16Srobert       writeUleb128(os, WasmSym::applyGlobalRelocs->getFunctionIndex(),
13091cf9926bSpatrick                    "function index");
13101cf9926bSpatrick       writeU8(os, WASM_OPCODE_CALL, "CALL");
1311*dfe94b16Srobert       writeUleb128(os, WasmSym::initMemory->getFunctionIndex(),
13121cf9926bSpatrick                    "function index");
13131cf9926bSpatrick       writeU8(os, WASM_OPCODE_END, "END");
13141cf9926bSpatrick     }
13151cf9926bSpatrick     createFunction(WasmSym::startFunction, bodyContent);
13161cf9926bSpatrick   } else if (WasmSym::initMemory) {
13171cf9926bSpatrick     WasmSym::startFunction = WasmSym::initMemory;
13181cf9926bSpatrick   } else if (WasmSym::applyGlobalRelocs) {
13191cf9926bSpatrick     WasmSym::startFunction = WasmSym::applyGlobalRelocs;
13201cf9926bSpatrick   }
13211cf9926bSpatrick }
13221cf9926bSpatrick 
1323ece8a530Spatrick // For -shared (PIC) output, we create create a synthetic function which will
1324ece8a530Spatrick // apply any relocations to the data segments on startup.  This function is
1325*dfe94b16Srobert // called `__wasm_apply_data_relocs` and is expected to be called before
1326*dfe94b16Srobert // any user code (i.e. before `__wasm_call_ctors`).
createApplyDataRelocationsFunction()13271cf9926bSpatrick void Writer::createApplyDataRelocationsFunction() {
13281cf9926bSpatrick   LLVM_DEBUG(dbgs() << "createApplyDataRelocationsFunction\n");
1329ece8a530Spatrick   // First write the body's contents to a string.
1330ece8a530Spatrick   std::string bodyContent;
1331ece8a530Spatrick   {
1332ece8a530Spatrick     raw_string_ostream os(bodyContent);
1333ece8a530Spatrick     writeUleb128(os, 0, "num locals");
1334ece8a530Spatrick     for (const OutputSegment *seg : segments)
13351cf9926bSpatrick       for (const InputChunk *inSeg : seg->inputSegments)
1336ece8a530Spatrick         inSeg->generateRelocationCode(os);
13371cf9926bSpatrick 
1338ece8a530Spatrick     writeU8(os, WASM_OPCODE_END, "END");
1339ece8a530Spatrick   }
1340ece8a530Spatrick 
13411cf9926bSpatrick   createFunction(WasmSym::applyDataRelocs, bodyContent);
13421cf9926bSpatrick }
13431cf9926bSpatrick 
13441cf9926bSpatrick // Similar to createApplyDataRelocationsFunction but generates relocation code
1345*dfe94b16Srobert // for WebAssembly globals. Because these globals are not shared between threads
13461cf9926bSpatrick // these relocation need to run on every thread.
createApplyGlobalRelocationsFunction()13471cf9926bSpatrick void Writer::createApplyGlobalRelocationsFunction() {
13481cf9926bSpatrick   // First write the body's contents to a string.
13491cf9926bSpatrick   std::string bodyContent;
13501cf9926bSpatrick   {
13511cf9926bSpatrick     raw_string_ostream os(bodyContent);
13521cf9926bSpatrick     writeUleb128(os, 0, "num locals");
1353*dfe94b16Srobert     out.globalSec->generateRelocationCode(os, false);
13541cf9926bSpatrick     writeU8(os, WASM_OPCODE_END, "END");
13551cf9926bSpatrick   }
13561cf9926bSpatrick 
13571cf9926bSpatrick   createFunction(WasmSym::applyGlobalRelocs, bodyContent);
1358ece8a530Spatrick }
1359ece8a530Spatrick 
1360*dfe94b16Srobert // Similar to createApplyGlobalRelocationsFunction but for
1361*dfe94b16Srobert // TLS symbols.  This cannot be run during the start function
1362*dfe94b16Srobert // but must be delayed until __wasm_init_tls is called.
createApplyGlobalTLSRelocationsFunction()1363*dfe94b16Srobert void Writer::createApplyGlobalTLSRelocationsFunction() {
1364*dfe94b16Srobert   // First write the body's contents to a string.
1365*dfe94b16Srobert   std::string bodyContent;
1366*dfe94b16Srobert   {
1367*dfe94b16Srobert     raw_string_ostream os(bodyContent);
1368*dfe94b16Srobert     writeUleb128(os, 0, "num locals");
1369*dfe94b16Srobert     out.globalSec->generateRelocationCode(os, true);
1370*dfe94b16Srobert     writeU8(os, WASM_OPCODE_END, "END");
1371*dfe94b16Srobert   }
1372*dfe94b16Srobert 
1373*dfe94b16Srobert   createFunction(WasmSym::applyGlobalTLSRelocs, bodyContent);
1374*dfe94b16Srobert }
1375*dfe94b16Srobert 
1376ece8a530Spatrick // Create synthetic "__wasm_call_ctors" function based on ctor functions
1377ece8a530Spatrick // in input object.
createCallCtorsFunction()1378ece8a530Spatrick void Writer::createCallCtorsFunction() {
1379*dfe94b16Srobert   // If __wasm_call_ctors isn't referenced, there aren't any ctors, don't
13801cf9926bSpatrick   // define the `__wasm_call_ctors` function.
1381*dfe94b16Srobert   if (!WasmSym::callCtors->isLive() && initFunctions.empty())
1382ece8a530Spatrick     return;
1383ece8a530Spatrick 
1384ece8a530Spatrick   // First write the body's contents to a string.
1385ece8a530Spatrick   std::string bodyContent;
1386ece8a530Spatrick   {
1387ece8a530Spatrick     raw_string_ostream os(bodyContent);
1388ece8a530Spatrick     writeUleb128(os, 0, "num locals");
1389ece8a530Spatrick 
1390ece8a530Spatrick     // Call constructors
1391ece8a530Spatrick     for (const WasmInitEntry &f : initFunctions) {
1392ece8a530Spatrick       writeU8(os, WASM_OPCODE_CALL, "CALL");
1393ece8a530Spatrick       writeUleb128(os, f.sym->getFunctionIndex(), "function index");
1394bb684c34Spatrick       for (size_t i = 0; i < f.sym->signature->Returns.size(); i++) {
1395bb684c34Spatrick         writeU8(os, WASM_OPCODE_DROP, "DROP");
1396bb684c34Spatrick       }
1397ece8a530Spatrick     }
13981cf9926bSpatrick 
1399ece8a530Spatrick     writeU8(os, WASM_OPCODE_END, "END");
1400ece8a530Spatrick   }
1401ece8a530Spatrick 
1402ece8a530Spatrick   createFunction(WasmSym::callCtors, bodyContent);
1403ece8a530Spatrick }
1404ece8a530Spatrick 
14051cf9926bSpatrick // Create a wrapper around a function export which calls the
14061cf9926bSpatrick // static constructors and destructors.
createCommandExportWrapper(uint32_t functionIndex,DefinedFunction * f)14071cf9926bSpatrick void Writer::createCommandExportWrapper(uint32_t functionIndex,
14081cf9926bSpatrick                                         DefinedFunction *f) {
14091cf9926bSpatrick   // First write the body's contents to a string.
14101cf9926bSpatrick   std::string bodyContent;
14111cf9926bSpatrick   {
14121cf9926bSpatrick     raw_string_ostream os(bodyContent);
14131cf9926bSpatrick     writeUleb128(os, 0, "num locals");
1414ece8a530Spatrick 
14151cf9926bSpatrick     // Call `__wasm_call_ctors` which call static constructors (and
14161cf9926bSpatrick     // applies any runtime relocations in Emscripten-style PIC mode)
14171cf9926bSpatrick     if (WasmSym::callCtors->isLive()) {
14181cf9926bSpatrick       writeU8(os, WASM_OPCODE_CALL, "CALL");
14191cf9926bSpatrick       writeUleb128(os, WasmSym::callCtors->getFunctionIndex(),
14201cf9926bSpatrick                    "function index");
14211cf9926bSpatrick     }
14221cf9926bSpatrick 
14231cf9926bSpatrick     // Call the user's code, leaving any return values on the operand stack.
14241cf9926bSpatrick     for (size_t i = 0; i < f->signature->Params.size(); ++i) {
14251cf9926bSpatrick       writeU8(os, WASM_OPCODE_LOCAL_GET, "local.get");
14261cf9926bSpatrick       writeUleb128(os, i, "local index");
14271cf9926bSpatrick     }
14281cf9926bSpatrick     writeU8(os, WASM_OPCODE_CALL, "CALL");
14291cf9926bSpatrick     writeUleb128(os, functionIndex, "function index");
14301cf9926bSpatrick 
14311cf9926bSpatrick     // Call the function that calls the destructors.
14321cf9926bSpatrick     if (DefinedFunction *callDtors = WasmSym::callDtors) {
14331cf9926bSpatrick       writeU8(os, WASM_OPCODE_CALL, "CALL");
14341cf9926bSpatrick       writeUleb128(os, callDtors->getFunctionIndex(), "function index");
14351cf9926bSpatrick     }
14361cf9926bSpatrick 
14371cf9926bSpatrick     // End the function, returning the return values from the user's code.
14381cf9926bSpatrick     writeU8(os, WASM_OPCODE_END, "END");
14391cf9926bSpatrick   }
14401cf9926bSpatrick 
14411cf9926bSpatrick   createFunction(f, bodyContent);
14421cf9926bSpatrick }
14431cf9926bSpatrick 
createInitTLSFunction()14441cf9926bSpatrick void Writer::createInitTLSFunction() {
1445ece8a530Spatrick   std::string bodyContent;
1446ece8a530Spatrick   {
1447ece8a530Spatrick     raw_string_ostream os(bodyContent);
1448ece8a530Spatrick 
1449ece8a530Spatrick     OutputSegment *tlsSeg = nullptr;
1450ece8a530Spatrick     for (auto *seg : segments) {
1451ece8a530Spatrick       if (seg->name == ".tdata") {
1452ece8a530Spatrick         tlsSeg = seg;
1453ece8a530Spatrick         break;
1454ece8a530Spatrick       }
1455ece8a530Spatrick     }
1456ece8a530Spatrick 
1457ece8a530Spatrick     writeUleb128(os, 0, "num locals");
1458ece8a530Spatrick     if (tlsSeg) {
1459ece8a530Spatrick       writeU8(os, WASM_OPCODE_LOCAL_GET, "local.get");
1460ece8a530Spatrick       writeUleb128(os, 0, "local index");
1461ece8a530Spatrick 
1462ece8a530Spatrick       writeU8(os, WASM_OPCODE_GLOBAL_SET, "global.set");
1463ece8a530Spatrick       writeUleb128(os, WasmSym::tlsBase->getGlobalIndex(), "global index");
1464ece8a530Spatrick 
14651cf9926bSpatrick       // FIXME(wvo): this local needs to be I64 in wasm64, or we need an extend op.
1466ece8a530Spatrick       writeU8(os, WASM_OPCODE_LOCAL_GET, "local.get");
1467ece8a530Spatrick       writeUleb128(os, 0, "local index");
1468ece8a530Spatrick 
1469ece8a530Spatrick       writeI32Const(os, 0, "segment offset");
1470ece8a530Spatrick 
1471ece8a530Spatrick       writeI32Const(os, tlsSeg->size, "memory region size");
1472ece8a530Spatrick 
1473ece8a530Spatrick       writeU8(os, WASM_OPCODE_MISC_PREFIX, "bulk-memory prefix");
1474ece8a530Spatrick       writeUleb128(os, WASM_OPCODE_MEMORY_INIT, "MEMORY.INIT");
1475ece8a530Spatrick       writeUleb128(os, tlsSeg->index, "segment index immediate");
1476ece8a530Spatrick       writeU8(os, 0, "memory index immediate");
1477ece8a530Spatrick     }
1478*dfe94b16Srobert 
1479*dfe94b16Srobert     if (WasmSym::applyGlobalTLSRelocs) {
1480*dfe94b16Srobert       writeU8(os, WASM_OPCODE_CALL, "CALL");
1481*dfe94b16Srobert       writeUleb128(os, WasmSym::applyGlobalTLSRelocs->getFunctionIndex(),
1482*dfe94b16Srobert                    "function index");
1483*dfe94b16Srobert     }
1484ece8a530Spatrick     writeU8(os, WASM_OPCODE_END, "end function");
1485ece8a530Spatrick   }
1486ece8a530Spatrick 
1487ece8a530Spatrick   createFunction(WasmSym::initTLS, bodyContent);
1488ece8a530Spatrick }
1489ece8a530Spatrick 
1490ece8a530Spatrick // Populate InitFunctions vector with init functions from all input objects.
1491ece8a530Spatrick // This is then used either when creating the output linking section or to
1492ece8a530Spatrick // synthesize the "__wasm_call_ctors" function.
calculateInitFunctions()1493ece8a530Spatrick void Writer::calculateInitFunctions() {
1494ece8a530Spatrick   if (!config->relocatable && !WasmSym::callCtors->isLive())
1495ece8a530Spatrick     return;
1496ece8a530Spatrick 
1497ece8a530Spatrick   for (ObjFile *file : symtab->objectFiles) {
1498ece8a530Spatrick     const WasmLinkingData &l = file->getWasmObj()->linkingData();
1499ece8a530Spatrick     for (const WasmInitFunc &f : l.InitFunctions) {
1500ece8a530Spatrick       FunctionSymbol *sym = file->getFunctionSymbol(f.Symbol);
1501ece8a530Spatrick       // comdat exclusions can cause init functions be discarded.
15021cf9926bSpatrick       if (sym->isDiscarded() || !sym->isLive())
1503ece8a530Spatrick         continue;
1504bb684c34Spatrick       if (sym->signature->Params.size() != 0)
1505bb684c34Spatrick         error("constructor functions cannot take arguments: " + toString(*sym));
1506ece8a530Spatrick       LLVM_DEBUG(dbgs() << "initFunctions: " << toString(*sym) << "\n");
1507ece8a530Spatrick       initFunctions.emplace_back(WasmInitEntry{sym, f.Priority});
1508ece8a530Spatrick     }
1509ece8a530Spatrick   }
1510ece8a530Spatrick 
1511ece8a530Spatrick   // Sort in order of priority (lowest first) so that they are called
1512ece8a530Spatrick   // in the correct order.
1513ece8a530Spatrick   llvm::stable_sort(initFunctions,
1514ece8a530Spatrick                     [](const WasmInitEntry &l, const WasmInitEntry &r) {
1515ece8a530Spatrick                       return l.priority < r.priority;
1516ece8a530Spatrick                     });
1517ece8a530Spatrick }
1518ece8a530Spatrick 
createSyntheticSections()1519ece8a530Spatrick void Writer::createSyntheticSections() {
1520ece8a530Spatrick   out.dylinkSec = make<DylinkSection>();
1521ece8a530Spatrick   out.typeSec = make<TypeSection>();
1522ece8a530Spatrick   out.importSec = make<ImportSection>();
1523ece8a530Spatrick   out.functionSec = make<FunctionSection>();
1524ece8a530Spatrick   out.tableSec = make<TableSection>();
1525ece8a530Spatrick   out.memorySec = make<MemorySection>();
15261cf9926bSpatrick   out.tagSec = make<TagSection>();
1527bb684c34Spatrick   out.globalSec = make<GlobalSection>();
1528ece8a530Spatrick   out.exportSec = make<ExportSection>();
15291cf9926bSpatrick   out.startSec = make<StartSection>();
1530ece8a530Spatrick   out.elemSec = make<ElemSection>();
1531ece8a530Spatrick   out.producersSec = make<ProducersSection>();
1532ece8a530Spatrick   out.targetFeaturesSec = make<TargetFeaturesSection>();
1533ece8a530Spatrick }
1534ece8a530Spatrick 
createSyntheticSectionsPostLayout()15351cf9926bSpatrick void Writer::createSyntheticSectionsPostLayout() {
15361cf9926bSpatrick   out.dataCountSec = make<DataCountSection>(segments);
15371cf9926bSpatrick   out.linkingSec = make<LinkingSection>(initFunctions, segments);
15381cf9926bSpatrick   out.nameSec = make<NameSection>(segments);
15391cf9926bSpatrick }
15401cf9926bSpatrick 
run()1541ece8a530Spatrick void Writer::run() {
1542ece8a530Spatrick   // For PIC code the table base is assigned dynamically by the loader.
1543ece8a530Spatrick   // For non-PIC, we start at 1 so that accessing table index 0 always traps.
1544ece8a530Spatrick   if (!config->isPic) {
1545ece8a530Spatrick     config->tableBase = 1;
1546ece8a530Spatrick     if (WasmSym::definedTableBase)
15471cf9926bSpatrick       WasmSym::definedTableBase->setVA(config->tableBase);
15481cf9926bSpatrick     if (WasmSym::definedTableBase32)
15491cf9926bSpatrick       WasmSym::definedTableBase32->setVA(config->tableBase);
1550ece8a530Spatrick   }
1551ece8a530Spatrick 
1552ece8a530Spatrick   log("-- createOutputSegments");
1553ece8a530Spatrick   createOutputSegments();
1554ece8a530Spatrick   log("-- createSyntheticSections");
1555ece8a530Spatrick   createSyntheticSections();
1556ece8a530Spatrick   log("-- layoutMemory");
1557ece8a530Spatrick   layoutMemory();
1558ece8a530Spatrick 
1559ece8a530Spatrick   if (!config->relocatable) {
1560ece8a530Spatrick     // Create linker synthesized __start_SECNAME/__stop_SECNAME symbols
1561ece8a530Spatrick     // This has to be done after memory layout is performed.
15621cf9926bSpatrick     for (const OutputSegment *seg : segments) {
1563ece8a530Spatrick       addStartStopSymbols(seg);
1564ece8a530Spatrick     }
15651cf9926bSpatrick   }
1566ece8a530Spatrick 
15671cf9926bSpatrick   for (auto &pair : config->exportedSymbols) {
15681cf9926bSpatrick     Symbol *sym = symtab->find(pair.first());
15691cf9926bSpatrick     if (sym && sym->isDefined())
15701cf9926bSpatrick       sym->forceExport = true;
15711cf9926bSpatrick   }
15721cf9926bSpatrick 
1573*dfe94b16Srobert   // Delay reporting errors about explicit exports until after
1574*dfe94b16Srobert   // addStartStopSymbols which can create optional symbols.
15751cf9926bSpatrick   for (auto &name : config->requiredExports) {
15761cf9926bSpatrick     Symbol *sym = symtab->find(name);
15771cf9926bSpatrick     if (!sym || !sym->isDefined()) {
15781cf9926bSpatrick       if (config->unresolvedSymbols == UnresolvedPolicy::ReportError)
15791cf9926bSpatrick         error(Twine("symbol exported via --export not found: ") + name);
15801cf9926bSpatrick       if (config->unresolvedSymbols == UnresolvedPolicy::Warn)
15811cf9926bSpatrick         warn(Twine("symbol exported via --export not found: ") + name);
15821cf9926bSpatrick     }
15831cf9926bSpatrick   }
15841cf9926bSpatrick 
1585*dfe94b16Srobert   log("-- populateTargetFeatures");
1586*dfe94b16Srobert   populateTargetFeatures();
1587*dfe94b16Srobert 
1588*dfe94b16Srobert   // When outputting PIC code each segment lives at at fixes offset from the
1589*dfe94b16Srobert   // `__memory_base` import.  Unless we support the extended const expression we
1590*dfe94b16Srobert   // can't do addition inside the constant expression, so we much combine the
1591*dfe94b16Srobert   // segments into a single one that can live at `__memory_base`.
1592*dfe94b16Srobert   if (config->isPic && !config->extendedConst && !config->sharedMemory) {
1593*dfe94b16Srobert     // In shared memory mode all data segments are passive and initialized
15941cf9926bSpatrick     // via __wasm_init_memory.
15951cf9926bSpatrick     log("-- combineOutputSegments");
15961cf9926bSpatrick     combineOutputSegments();
15971cf9926bSpatrick   }
15981cf9926bSpatrick 
15991cf9926bSpatrick   log("-- createSyntheticSectionsPostLayout");
16001cf9926bSpatrick   createSyntheticSectionsPostLayout();
16011cf9926bSpatrick   log("-- populateProducers");
16021cf9926bSpatrick   populateProducers();
16031cf9926bSpatrick   log("-- calculateImports");
16041cf9926bSpatrick   calculateImports();
1605ece8a530Spatrick   log("-- scanRelocations");
1606ece8a530Spatrick   scanRelocations();
16071cf9926bSpatrick   log("-- finalizeIndirectFunctionTable");
16081cf9926bSpatrick   finalizeIndirectFunctionTable();
16091cf9926bSpatrick   log("-- createSyntheticInitFunctions");
16101cf9926bSpatrick   createSyntheticInitFunctions();
1611ece8a530Spatrick   log("-- assignIndexes");
1612ece8a530Spatrick   assignIndexes();
1613ece8a530Spatrick   log("-- calculateInitFunctions");
1614ece8a530Spatrick   calculateInitFunctions();
1615ece8a530Spatrick 
1616ece8a530Spatrick   if (!config->relocatable) {
1617ece8a530Spatrick     // Create linker synthesized functions
16181cf9926bSpatrick     if (WasmSym::applyDataRelocs)
16191cf9926bSpatrick       createApplyDataRelocationsFunction();
16201cf9926bSpatrick     if (WasmSym::applyGlobalRelocs)
16211cf9926bSpatrick       createApplyGlobalRelocationsFunction();
1622*dfe94b16Srobert     if (WasmSym::applyGlobalTLSRelocs)
1623*dfe94b16Srobert       createApplyGlobalTLSRelocationsFunction();
16241cf9926bSpatrick     if (WasmSym::initMemory)
1625ece8a530Spatrick       createInitMemoryFunction();
16261cf9926bSpatrick     createStartFunction();
16271cf9926bSpatrick 
1628ece8a530Spatrick     createCallCtorsFunction();
16291cf9926bSpatrick 
16301cf9926bSpatrick     // Create export wrappers for commands if needed.
16311cf9926bSpatrick     //
16321cf9926bSpatrick     // If the input contains a call to `__wasm_call_ctors`, either in one of
16331cf9926bSpatrick     // the input objects or an explicit export from the command-line, we
16341cf9926bSpatrick     // assume ctors and dtors are taken care of already.
16351cf9926bSpatrick     if (!config->relocatable && !config->isPic &&
16361cf9926bSpatrick         !WasmSym::callCtors->isUsedInRegularObj &&
16371cf9926bSpatrick         !WasmSym::callCtors->isExported()) {
16381cf9926bSpatrick       log("-- createCommandExportWrappers");
16391cf9926bSpatrick       createCommandExportWrappers();
16401cf9926bSpatrick     }
1641ece8a530Spatrick   }
1642ece8a530Spatrick 
1643*dfe94b16Srobert   if (WasmSym::initTLS && WasmSym::initTLS->isLive()) {
1644*dfe94b16Srobert     log("-- createInitTLSFunction");
1645ece8a530Spatrick     createInitTLSFunction();
1646*dfe94b16Srobert   }
1647ece8a530Spatrick 
1648ece8a530Spatrick   if (errorCount())
1649ece8a530Spatrick     return;
1650ece8a530Spatrick 
1651ece8a530Spatrick   log("-- calculateTypes");
1652ece8a530Spatrick   calculateTypes();
1653ece8a530Spatrick   log("-- calculateExports");
1654ece8a530Spatrick   calculateExports();
1655ece8a530Spatrick   log("-- calculateCustomSections");
1656ece8a530Spatrick   calculateCustomSections();
1657ece8a530Spatrick   log("-- populateSymtab");
1658ece8a530Spatrick   populateSymtab();
1659*dfe94b16Srobert   log("-- checkImportExportTargetFeatures");
1660*dfe94b16Srobert   checkImportExportTargetFeatures();
1661ece8a530Spatrick   log("-- addSections");
1662ece8a530Spatrick   addSections();
1663ece8a530Spatrick 
1664ece8a530Spatrick   if (errorHandler().verbose) {
1665ece8a530Spatrick     log("Defined Functions: " + Twine(out.functionSec->inputFunctions.size()));
1666ece8a530Spatrick     log("Defined Globals  : " + Twine(out.globalSec->numGlobals()));
16671cf9926bSpatrick     log("Defined Tags     : " + Twine(out.tagSec->inputTags.size()));
16681cf9926bSpatrick     log("Defined Tables   : " + Twine(out.tableSec->inputTables.size()));
1669ece8a530Spatrick     log("Function Imports : " +
1670ece8a530Spatrick         Twine(out.importSec->getNumImportedFunctions()));
1671ece8a530Spatrick     log("Global Imports   : " + Twine(out.importSec->getNumImportedGlobals()));
16721cf9926bSpatrick     log("Tag Imports      : " + Twine(out.importSec->getNumImportedTags()));
16731cf9926bSpatrick     log("Table Imports    : " + Twine(out.importSec->getNumImportedTables()));
1674ece8a530Spatrick   }
1675ece8a530Spatrick 
1676ece8a530Spatrick   createHeader();
1677ece8a530Spatrick   log("-- finalizeSections");
1678ece8a530Spatrick   finalizeSections();
1679ece8a530Spatrick 
16801cf9926bSpatrick   log("-- writeMapFile");
16811cf9926bSpatrick   writeMapFile(outputSections);
16821cf9926bSpatrick 
1683ece8a530Spatrick   log("-- openFile");
1684ece8a530Spatrick   openFile();
1685ece8a530Spatrick   if (errorCount())
1686ece8a530Spatrick     return;
1687ece8a530Spatrick 
1688ece8a530Spatrick   writeHeader();
1689ece8a530Spatrick 
1690ece8a530Spatrick   log("-- writeSections");
1691ece8a530Spatrick   writeSections();
1692ece8a530Spatrick   if (errorCount())
1693ece8a530Spatrick     return;
1694ece8a530Spatrick 
1695ece8a530Spatrick   if (Error e = buffer->commit())
1696*dfe94b16Srobert     fatal("failed to write output '" + buffer->getPath() +
1697*dfe94b16Srobert           "': " + toString(std::move(e)));
1698ece8a530Spatrick }
1699ece8a530Spatrick 
1700ece8a530Spatrick // Open a result file.
openFile()1701ece8a530Spatrick void Writer::openFile() {
1702ece8a530Spatrick   log("writing: " + config->outputFile);
1703ece8a530Spatrick 
1704ece8a530Spatrick   Expected<std::unique_ptr<FileOutputBuffer>> bufferOrErr =
1705ece8a530Spatrick       FileOutputBuffer::create(config->outputFile, fileSize,
1706ece8a530Spatrick                                FileOutputBuffer::F_executable);
1707ece8a530Spatrick 
1708ece8a530Spatrick   if (!bufferOrErr)
1709ece8a530Spatrick     error("failed to open " + config->outputFile + ": " +
1710ece8a530Spatrick           toString(bufferOrErr.takeError()));
1711ece8a530Spatrick   else
1712ece8a530Spatrick     buffer = std::move(*bufferOrErr);
1713ece8a530Spatrick }
1714ece8a530Spatrick 
createHeader()1715ece8a530Spatrick void Writer::createHeader() {
1716ece8a530Spatrick   raw_string_ostream os(header);
1717ece8a530Spatrick   writeBytes(os, WasmMagic, sizeof(WasmMagic), "wasm magic");
1718ece8a530Spatrick   writeU32(os, WasmVersion, "wasm version");
1719ece8a530Spatrick   os.flush();
1720ece8a530Spatrick   fileSize += header.size();
1721ece8a530Spatrick }
1722ece8a530Spatrick 
writeResult()1723ece8a530Spatrick void writeResult() { Writer().run(); }
1724ece8a530Spatrick 
1725ece8a530Spatrick } // namespace wasm
1726ece8a530Spatrick } // namespace lld
1727