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