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