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