xref: /llvm-project-15.0.7/lld/wasm/Writer.cpp (revision fa765a09)
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->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.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 = [](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)
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) ||
562       config->unresolvedSymbols == UnresolvedPolicy::ImportFuncs)
563     return true;
564   if (config->allowUndefinedSymbols.count(sym->getName()) != 0)
565     return true;
566   if (auto *g = dyn_cast<UndefinedGlobal>(sym))
567     return g->importName.hasValue();
568   if (auto *f = dyn_cast<UndefinedFunction>(sym))
569     return f->importName.hasValue();
570   if (auto *t = dyn_cast<UndefinedTable>(sym))
571     return t->importName.hasValue();
572 
573   return false;
574 }
575 
576 void Writer::calculateImports() {
577   // Some inputs require that the indirect function table be assigned to table
578   // number 0, so if it is present and is an import, allocate it before any
579   // other tables.
580   if (WasmSym::indirectFunctionTable &&
581       shouldImport(WasmSym::indirectFunctionTable))
582     out.importSec->addImport(WasmSym::indirectFunctionTable);
583 
584   for (Symbol *sym : symtab->getSymbols()) {
585     if (!shouldImport(sym))
586       continue;
587     if (sym == WasmSym::indirectFunctionTable)
588       continue;
589     LLVM_DEBUG(dbgs() << "import: " << sym->getName() << "\n");
590     out.importSec->addImport(sym);
591   }
592 }
593 
594 void Writer::calculateExports() {
595   if (config->relocatable)
596     return;
597 
598   if (!config->relocatable && !config->importMemory)
599     out.exportSec->exports.push_back(
600         WasmExport{"memory", WASM_EXTERNAL_MEMORY, 0});
601 
602   unsigned globalIndex =
603       out.importSec->getNumImportedGlobals() + out.globalSec->numGlobals();
604 
605   for (Symbol *sym : symtab->getSymbols()) {
606     if (!sym->isExported())
607       continue;
608     if (!sym->isLive())
609       continue;
610 
611     StringRef name = sym->getName();
612     WasmExport export_;
613     if (auto *f = dyn_cast<DefinedFunction>(sym)) {
614       if (Optional<StringRef> exportName = f->function->getExportName()) {
615         name = *exportName;
616       }
617       export_ = {name, WASM_EXTERNAL_FUNCTION, f->getFunctionIndex()};
618     } else if (auto *g = dyn_cast<DefinedGlobal>(sym)) {
619       if (g->getGlobalType()->Mutable && !g->getFile() && !g->forceExport) {
620         // Avoid exporting mutable globals are linker synthesized (e.g.
621         // __stack_pointer or __tls_base) unless they are explicitly exported
622         // from the command line.
623         // Without this check `--export-all` would cause any program using the
624         // stack pointer to export a mutable global even if none of the input
625         // files were built with the `mutable-globals` feature.
626         continue;
627       }
628       export_ = {name, WASM_EXTERNAL_GLOBAL, g->getGlobalIndex()};
629     } else if (auto *e = dyn_cast<DefinedEvent>(sym)) {
630       export_ = {name, WASM_EXTERNAL_EVENT, e->getEventIndex()};
631     } else if (auto *d = dyn_cast<DefinedData>(sym)) {
632       if (d->segment && d->segment->isTLS()) {
633         // We can't currenly export TLS data symbols.
634         if (sym->isExportedExplicit())
635           error("TLS symbols cannot yet be exported: `" + toString(*sym) + "`");
636         continue;
637       }
638       out.globalSec->dataAddressGlobals.push_back(d);
639       export_ = {name, WASM_EXTERNAL_GLOBAL, globalIndex++};
640     } else {
641       auto *t = cast<DefinedTable>(sym);
642       export_ = {name, WASM_EXTERNAL_TABLE, t->getTableNumber()};
643     }
644 
645     LLVM_DEBUG(dbgs() << "Export: " << name << "\n");
646     out.exportSec->exports.push_back(export_);
647     out.exportSec->exportedSymbols.push_back(sym);
648   }
649 }
650 
651 void Writer::populateSymtab() {
652   if (!config->relocatable && !config->emitRelocs)
653     return;
654 
655   for (Symbol *sym : symtab->getSymbols())
656     if (sym->isUsedInRegularObj && sym->isLive())
657       out.linkingSec->addToSymtab(sym);
658 
659   for (ObjFile *file : symtab->objectFiles) {
660     LLVM_DEBUG(dbgs() << "Local symtab entries: " << file->getName() << "\n");
661     for (Symbol *sym : file->getSymbols())
662       if (sym->isLocal() && !isa<SectionSymbol>(sym) && sym->isLive())
663         out.linkingSec->addToSymtab(sym);
664   }
665 }
666 
667 void Writer::calculateTypes() {
668   // The output type section is the union of the following sets:
669   // 1. Any signature used in the TYPE relocation
670   // 2. The signatures of all imported functions
671   // 3. The signatures of all defined functions
672   // 4. The signatures of all imported events
673   // 5. The signatures of all defined events
674 
675   for (ObjFile *file : symtab->objectFiles) {
676     ArrayRef<WasmSignature> types = file->getWasmObj()->types();
677     for (uint32_t i = 0; i < types.size(); i++)
678       if (file->typeIsUsed[i])
679         file->typeMap[i] = out.typeSec->registerType(types[i]);
680   }
681 
682   for (const Symbol *sym : out.importSec->importedSymbols) {
683     if (auto *f = dyn_cast<FunctionSymbol>(sym))
684       out.typeSec->registerType(*f->signature);
685     else if (auto *e = dyn_cast<EventSymbol>(sym))
686       out.typeSec->registerType(*e->signature);
687   }
688 
689   for (const InputFunction *f : out.functionSec->inputFunctions)
690     out.typeSec->registerType(f->signature);
691 
692   for (const InputEvent *e : out.eventSec->inputEvents)
693     out.typeSec->registerType(e->signature);
694 }
695 
696 // In a command-style link, create a wrapper for each exported symbol
697 // which calls the constructors and destructors.
698 void Writer::createCommandExportWrappers() {
699   // This logic doesn't currently support Emscripten-style PIC mode.
700   assert(!config->isPic);
701 
702   // If there are no ctors and there's no libc `__wasm_call_dtors` to
703   // call, don't wrap the exports.
704   if (initFunctions.empty() && WasmSym::callDtors == NULL)
705     return;
706 
707   std::vector<DefinedFunction *> toWrap;
708 
709   for (Symbol *sym : symtab->getSymbols())
710     if (sym->isExported())
711       if (auto *f = dyn_cast<DefinedFunction>(sym))
712         toWrap.push_back(f);
713 
714   for (auto *f : toWrap) {
715     auto funcNameStr = (f->getName() + ".command_export").str();
716     commandExportWrapperNames.push_back(funcNameStr);
717     const std::string &funcName = commandExportWrapperNames.back();
718 
719     auto func = make<SyntheticFunction>(*f->getSignature(), funcName);
720     if (f->function->getExportName().hasValue())
721       func->setExportName(f->function->getExportName()->str());
722     else
723       func->setExportName(f->getName().str());
724 
725     DefinedFunction *def =
726         symtab->addSyntheticFunction(funcName, f->flags, func);
727     def->markLive();
728 
729     def->flags |= WASM_SYMBOL_EXPORTED;
730     def->flags &= ~WASM_SYMBOL_VISIBILITY_HIDDEN;
731     def->forceExport = f->forceExport;
732 
733     f->flags |= WASM_SYMBOL_VISIBILITY_HIDDEN;
734     f->flags &= ~WASM_SYMBOL_EXPORTED;
735     f->forceExport = false;
736 
737     out.functionSec->addFunction(func);
738 
739     createCommandExportWrapper(f->getFunctionIndex(), def);
740   }
741 }
742 
743 static void finalizeIndirectFunctionTable() {
744   if (!WasmSym::indirectFunctionTable)
745     return;
746 
747   if (shouldImport(WasmSym::indirectFunctionTable) &&
748       !WasmSym::indirectFunctionTable->hasTableNumber()) {
749     // Processing -Bsymbolic relocations resulted in a late requirement that the
750     // indirect function table be present, and we are running in --import-table
751     // mode.  Add the table now to the imports section.  Otherwise it will be
752     // added to the tables section later in assignIndexes.
753     out.importSec->addImport(WasmSym::indirectFunctionTable);
754   }
755 
756   uint32_t tableSize = config->tableBase + out.elemSec->numEntries();
757   WasmLimits limits = {0, tableSize, 0};
758   if (WasmSym::indirectFunctionTable->isDefined() && !config->growableTable) {
759     limits.Flags |= WASM_LIMITS_FLAG_HAS_MAX;
760     limits.Maximum = limits.Minimum;
761   }
762   WasmSym::indirectFunctionTable->setLimits(limits);
763 }
764 
765 static void scanRelocations() {
766   for (ObjFile *file : symtab->objectFiles) {
767     LLVM_DEBUG(dbgs() << "scanRelocations: " << file->getName() << "\n");
768     for (InputChunk *chunk : file->functions)
769       scanRelocations(chunk);
770     for (InputChunk *chunk : file->segments)
771       scanRelocations(chunk);
772     for (auto &p : file->customSections)
773       scanRelocations(p);
774   }
775 }
776 
777 void Writer::assignIndexes() {
778   // Seal the import section, since other index spaces such as function and
779   // global are effected by the number of imports.
780   out.importSec->seal();
781 
782   for (InputFunction *func : symtab->syntheticFunctions)
783     out.functionSec->addFunction(func);
784 
785   for (ObjFile *file : symtab->objectFiles) {
786     LLVM_DEBUG(dbgs() << "Functions: " << file->getName() << "\n");
787     for (InputFunction *func : file->functions)
788       out.functionSec->addFunction(func);
789   }
790 
791   for (InputGlobal *global : symtab->syntheticGlobals)
792     out.globalSec->addGlobal(global);
793 
794   for (ObjFile *file : symtab->objectFiles) {
795     LLVM_DEBUG(dbgs() << "Globals: " << file->getName() << "\n");
796     for (InputGlobal *global : file->globals)
797       out.globalSec->addGlobal(global);
798   }
799 
800   for (ObjFile *file : symtab->objectFiles) {
801     LLVM_DEBUG(dbgs() << "Events: " << file->getName() << "\n");
802     for (InputEvent *event : file->events)
803       out.eventSec->addEvent(event);
804   }
805 
806   for (ObjFile *file : symtab->objectFiles) {
807     LLVM_DEBUG(dbgs() << "Tables: " << file->getName() << "\n");
808     for (InputTable *table : file->tables)
809       out.tableSec->addTable(table);
810   }
811 
812   for (InputTable *table : symtab->syntheticTables)
813     out.tableSec->addTable(table);
814 
815   out.globalSec->assignIndexes();
816   out.tableSec->assignIndexes();
817 }
818 
819 static StringRef getOutputDataSegmentName(const InputChunk &seg) {
820   // We always merge .tbss and .tdata into a single TLS segment so all TLS
821   // symbols are be relative to single __tls_base.
822   if (seg.isTLS())
823     return ".tdata";
824   StringRef name = seg.getName();
825   if (!config->mergeDataSegments)
826     return name;
827   if (name.startswith(".text."))
828     return ".text";
829   if (name.startswith(".data."))
830     return ".data";
831   if (name.startswith(".bss."))
832     return ".bss";
833   if (name.startswith(".rodata."))
834     return ".rodata";
835   return name;
836 }
837 
838 OutputSegment *Writer::createOutputSegment(StringRef name) {
839   LLVM_DEBUG(dbgs() << "new segment: " << name << "\n");
840   OutputSegment *s = make<OutputSegment>(name);
841   if (config->sharedMemory)
842     s->initFlags = WASM_DATA_SEGMENT_IS_PASSIVE;
843   // Exported memories are guaranteed to be zero-initialized, so no need
844   // to emit data segments for bss sections.
845   // TODO: consider initializing bss sections with memory.fill
846   // instructions when memory is imported and bulk-memory is available.
847   if (!config->importMemory && !config->relocatable && name.startswith(".bss"))
848     s->isBss = true;
849   segments.push_back(s);
850   return s;
851 }
852 
853 void Writer::createOutputSegments() {
854   for (ObjFile *file : symtab->objectFiles) {
855     for (InputChunk *segment : file->segments) {
856       if (!segment->live)
857         continue;
858       StringRef name = getOutputDataSegmentName(*segment);
859       OutputSegment *s = nullptr;
860       // When running in relocatable mode we can't merge segments that are part
861       // of comdat groups since the ultimate linker needs to be able exclude or
862       // include them individually.
863       if (config->relocatable && !segment->getComdatName().empty()) {
864         s = createOutputSegment(name);
865       } else {
866         if (segmentMap.count(name) == 0)
867           segmentMap[name] = createOutputSegment(name);
868         s = segmentMap[name];
869       }
870       s->addInputSegment(segment);
871     }
872   }
873 
874   // Sort segments by type, placing .bss last
875   std::stable_sort(segments.begin(), segments.end(),
876                    [](const OutputSegment *a, const OutputSegment *b) {
877                      auto order = [](StringRef name) {
878                        return StringSwitch<int>(name)
879                            .StartsWith(".tdata", 0)
880                            .StartsWith(".rodata", 1)
881                            .StartsWith(".data", 2)
882                            .StartsWith(".bss", 4)
883                            .Default(3);
884                      };
885                      return order(a->name) < order(b->name);
886                    });
887 
888   for (size_t i = 0; i < segments.size(); ++i)
889     segments[i]->index = i;
890 
891   // Merge MergeInputSections into a single MergeSyntheticSection.
892   LLVM_DEBUG(dbgs() << "-- finalize input semgments\n");
893   for (OutputSegment *seg : segments)
894     seg->finalizeInputSegments();
895 }
896 
897 void Writer::combineOutputSegments() {
898   // With PIC code we currently only support a single data segment since
899   // we only have a single __memory_base to use as our base address.
900   // This pass combines all non-TLS data segments into a single .data
901   // segment.
902   // This restructions can be relaxed once we have extended constant
903   // expressions available:
904   // https://github.com/WebAssembly/extended-const
905   assert(config->isPic);
906   if (segments.size() <= 1)
907     return;
908   OutputSegment *combined = nullptr;
909   std::vector<OutputSegment *> new_segments;
910   for (OutputSegment *s : segments) {
911     if (s->isTLS()) {
912       new_segments.push_back(s);
913     } else {
914       if (!combined) {
915         LLVM_DEBUG(dbgs() << "created combined output segment: .data\n");
916         combined = make<OutputSegment>(".data");
917         combined->startVA = s->startVA;
918         if (config->sharedMemory)
919           combined->initFlags = WASM_DATA_SEGMENT_IS_PASSIVE;
920       }
921       bool first = true;
922       for (InputChunk *inSeg : s->inputSegments) {
923         if (first)
924           inSeg->alignment = std::max(inSeg->alignment, s->alignment);
925         first = false;
926 #ifndef NDEBUG
927         uint64_t oldVA = inSeg->getVA();
928 #endif
929         combined->addInputSegment(inSeg);
930 #ifndef NDEBUG
931         uint64_t newVA = inSeg->getVA();
932         LLVM_DEBUG(dbgs() << "added input segment. name=" << inSeg->getName()
933                           << " oldVA=" << oldVA << " newVA=" << newVA << "\n");
934         assert(oldVA == newVA);
935 #endif
936       }
937     }
938   }
939   if (combined) {
940     new_segments.push_back(combined);
941     segments = new_segments;
942     for (size_t i = 0; i < segments.size(); ++i)
943       segments[i]->index = i;
944   }
945 }
946 
947 static void createFunction(DefinedFunction *func, StringRef bodyContent) {
948   std::string functionBody;
949   {
950     raw_string_ostream os(functionBody);
951     writeUleb128(os, bodyContent.size(), "function size");
952     os << bodyContent;
953   }
954   ArrayRef<uint8_t> body = arrayRefFromStringRef(saver.save(functionBody));
955   cast<SyntheticFunction>(func->function)->setBody(body);
956 }
957 
958 bool Writer::needsPassiveInitialization(const OutputSegment *segment) {
959   return segment->initFlags & WASM_DATA_SEGMENT_IS_PASSIVE &&
960          !segment->isTLS() && !segment->isBss;
961 }
962 
963 bool Writer::hasPassiveInitializedSegments() {
964   return std::find_if(segments.begin(), segments.end(),
965                       [this](const OutputSegment *s) {
966                         return this->needsPassiveInitialization(s);
967                       }) != segments.end();
968 }
969 
970 void Writer::createSyntheticInitFunctions() {
971   if (config->relocatable)
972     return;
973 
974   static WasmSignature nullSignature = {{}, {}};
975 
976   // Passive segments are used to avoid memory being reinitialized on each
977   // thread's instantiation. These passive segments are initialized and
978   // dropped in __wasm_init_memory, which is registered as the start function
979   if (config->sharedMemory && hasPassiveInitializedSegments()) {
980     WasmSym::initMemory = symtab->addSyntheticFunction(
981         "__wasm_init_memory", WASM_SYMBOL_VISIBILITY_HIDDEN,
982         make<SyntheticFunction>(nullSignature, "__wasm_init_memory"));
983     WasmSym::initMemory->markLive();
984   }
985 
986   if (config->isPic) {
987     // For PIC code we create synthetic functions that apply relocations.
988     // These get called from __wasm_call_ctors before the user-level
989     // constructors.
990     WasmSym::applyDataRelocs = symtab->addSyntheticFunction(
991         "__wasm_apply_data_relocs", WASM_SYMBOL_VISIBILITY_HIDDEN,
992         make<SyntheticFunction>(nullSignature, "__wasm_apply_data_relocs"));
993     WasmSym::applyDataRelocs->markLive();
994 
995     if (out.globalSec->needsRelocations()) {
996       WasmSym::applyGlobalRelocs = symtab->addSyntheticFunction(
997           "__wasm_apply_global_relocs", WASM_SYMBOL_VISIBILITY_HIDDEN,
998           make<SyntheticFunction>(nullSignature, "__wasm_apply_global_relocs"));
999       WasmSym::applyGlobalRelocs->markLive();
1000     }
1001   }
1002 
1003   if (WasmSym::applyGlobalRelocs && WasmSym::initMemory) {
1004     WasmSym::startFunction = symtab->addSyntheticFunction(
1005         "__wasm_start", WASM_SYMBOL_VISIBILITY_HIDDEN,
1006         make<SyntheticFunction>(nullSignature, "__wasm_start"));
1007     WasmSym::startFunction->markLive();
1008   }
1009 }
1010 
1011 void Writer::createInitMemoryFunction() {
1012   LLVM_DEBUG(dbgs() << "createInitMemoryFunction\n");
1013   assert(WasmSym::initMemory);
1014   assert(WasmSym::initMemoryFlag);
1015   assert(hasPassiveInitializedSegments());
1016   uint64_t flagAddress = WasmSym::initMemoryFlag->getVA();
1017   bool is64 = config->is64.getValueOr(false);
1018   std::string bodyContent;
1019   {
1020     raw_string_ostream os(bodyContent);
1021     // Initialize memory in a thread-safe manner. The thread that successfully
1022     // increments the flag from 0 to 1 is is responsible for performing the
1023     // memory initialization. Other threads go sleep on the flag until the
1024     // first thread finishing initializing memory, increments the flag to 2,
1025     // and wakes all the other threads. Once the flag has been set to 2,
1026     // subsequently started threads will skip the sleep. All threads
1027     // unconditionally drop their passive data segments once memory has been
1028     // initialized. The generated code is as follows:
1029     //
1030     // (func $__wasm_init_memory
1031     //  (if
1032     //   (i32.atomic.rmw.cmpxchg align=2 offset=0
1033     //    (i32.const $__init_memory_flag)
1034     //    (i32.const 0)
1035     //    (i32.const 1)
1036     //   )
1037     //   (then
1038     //    (drop
1039     //     (i32.atomic.wait align=2 offset=0
1040     //      (i32.const $__init_memory_flag)
1041     //      (i32.const 1)
1042     //      (i32.const -1)
1043     //     )
1044     //    )
1045     //   )
1046     //   (else
1047     //    ( ... initialize data segments ... )
1048     //    (i32.atomic.store align=2 offset=0
1049     //     (i32.const $__init_memory_flag)
1050     //     (i32.const 2)
1051     //    )
1052     //    (drop
1053     //     (i32.atomic.notify align=2 offset=0
1054     //      (i32.const $__init_memory_flag)
1055     //      (i32.const -1u)
1056     //     )
1057     //    )
1058     //   )
1059     //  )
1060     //  ( ... drop data segments ... )
1061     // )
1062     //
1063     // When we are building with PIC, calculate the flag location using:
1064     //
1065     //    (global.get $__memory_base)
1066     //    (i32.const $__init_memory_flag)
1067     //    (i32.const 1)
1068 
1069     // With PIC code we cache the flag address in local 0
1070     if (config->isPic) {
1071       writeUleb128(os, 1, "num local decls");
1072       writeUleb128(os, 1, "local count");
1073       writeU8(os, is64 ? WASM_TYPE_I64 : WASM_TYPE_I32, "address type");
1074       writeU8(os, WASM_OPCODE_GLOBAL_GET, "GLOBAL_GET");
1075       writeUleb128(os, WasmSym::memoryBase->getGlobalIndex(), "memory_base");
1076       writePtrConst(os, flagAddress, is64, "flag address");
1077       writeU8(os, WASM_OPCODE_I32_ADD, "add");
1078       writeU8(os, WASM_OPCODE_LOCAL_SET, "local.set");
1079       writeUleb128(os, 0, "local 0");
1080     } else {
1081       writeUleb128(os, 0, "num locals");
1082     }
1083 
1084     auto writeGetFlagAddress = [&]() {
1085       if (config->isPic) {
1086         writeU8(os, WASM_OPCODE_LOCAL_GET, "local.get");
1087         writeUleb128(os, 0, "local 0");
1088       } else {
1089         writePtrConst(os, flagAddress, is64, "flag address");
1090       }
1091     };
1092 
1093     // Atomically check whether this is the main thread.
1094     writeGetFlagAddress();
1095     writeI32Const(os, 0, "expected flag value");
1096     writeI32Const(os, 1, "flag value");
1097     writeU8(os, WASM_OPCODE_ATOMICS_PREFIX, "atomics prefix");
1098     writeUleb128(os, WASM_OPCODE_I32_RMW_CMPXCHG, "i32.atomic.rmw.cmpxchg");
1099     writeMemArg(os, 2, 0);
1100     writeU8(os, WASM_OPCODE_IF, "IF");
1101     writeU8(os, WASM_TYPE_NORESULT, "blocktype");
1102 
1103     // Did not increment 0, so wait for main thread to initialize memory
1104     writeGetFlagAddress();
1105     writeI32Const(os, 1, "expected flag value");
1106     writeI64Const(os, -1, "timeout");
1107 
1108     writeU8(os, WASM_OPCODE_ATOMICS_PREFIX, "atomics prefix");
1109     writeUleb128(os, WASM_OPCODE_I32_ATOMIC_WAIT, "i32.atomic.wait");
1110     writeMemArg(os, 2, 0);
1111     writeU8(os, WASM_OPCODE_DROP, "drop");
1112 
1113     writeU8(os, WASM_OPCODE_ELSE, "ELSE");
1114 
1115     // Did increment 0, so conditionally initialize passive data segments
1116     for (const OutputSegment *s : segments) {
1117       if (needsPassiveInitialization(s)) {
1118         // destination address
1119         writePtrConst(os, s->startVA, is64, "destination address");
1120         if (config->isPic) {
1121           writeU8(os, WASM_OPCODE_GLOBAL_GET, "GLOBAL_GET");
1122           writeUleb128(os, WasmSym::memoryBase->getGlobalIndex(),
1123                        "memory_base");
1124           writeU8(os, WASM_OPCODE_I32_ADD, "i32.add");
1125         }
1126         // source segment offset
1127         writeI32Const(os, 0, "segment offset");
1128         // memory region size
1129         writeI32Const(os, s->size, "memory region size");
1130         // memory.init instruction
1131         writeU8(os, WASM_OPCODE_MISC_PREFIX, "bulk-memory prefix");
1132         writeUleb128(os, WASM_OPCODE_MEMORY_INIT, "memory.init");
1133         writeUleb128(os, s->index, "segment index immediate");
1134         writeU8(os, 0, "memory index immediate");
1135       }
1136     }
1137 
1138     // Set flag to 2 to mark end of initialization
1139     writeGetFlagAddress();
1140     writeI32Const(os, 2, "flag value");
1141     writeU8(os, WASM_OPCODE_ATOMICS_PREFIX, "atomics prefix");
1142     writeUleb128(os, WASM_OPCODE_I32_ATOMIC_STORE, "i32.atomic.store");
1143     writeMemArg(os, 2, 0);
1144 
1145     // Notify any waiters that memory initialization is complete
1146     writeGetFlagAddress();
1147     writeI32Const(os, -1, "number of waiters");
1148     writeU8(os, WASM_OPCODE_ATOMICS_PREFIX, "atomics prefix");
1149     writeUleb128(os, WASM_OPCODE_ATOMIC_NOTIFY, "atomic.notify");
1150     writeMemArg(os, 2, 0);
1151     writeU8(os, WASM_OPCODE_DROP, "drop");
1152 
1153     writeU8(os, WASM_OPCODE_END, "END");
1154 
1155     // Unconditionally drop passive data segments
1156     for (const OutputSegment *s : segments) {
1157       if (needsPassiveInitialization(s)) {
1158         // data.drop instruction
1159         writeU8(os, WASM_OPCODE_MISC_PREFIX, "bulk-memory prefix");
1160         writeUleb128(os, WASM_OPCODE_DATA_DROP, "data.drop");
1161         writeUleb128(os, s->index, "segment index immediate");
1162       }
1163     }
1164     writeU8(os, WASM_OPCODE_END, "END");
1165   }
1166 
1167   createFunction(WasmSym::initMemory, bodyContent);
1168 }
1169 
1170 void Writer::createStartFunction() {
1171   if (WasmSym::startFunction) {
1172     std::string bodyContent;
1173     {
1174       raw_string_ostream os(bodyContent);
1175       writeUleb128(os, 0, "num locals");
1176       writeU8(os, WASM_OPCODE_CALL, "CALL");
1177       writeUleb128(os, WasmSym::initMemory->getFunctionIndex(),
1178                    "function index");
1179       writeU8(os, WASM_OPCODE_CALL, "CALL");
1180       writeUleb128(os, WasmSym::applyGlobalRelocs->getFunctionIndex(),
1181                    "function index");
1182       writeU8(os, WASM_OPCODE_END, "END");
1183     }
1184     createFunction(WasmSym::startFunction, bodyContent);
1185   } else if (WasmSym::initMemory) {
1186     WasmSym::startFunction = WasmSym::initMemory;
1187   } else if (WasmSym::applyGlobalRelocs) {
1188     WasmSym::startFunction = WasmSym::applyGlobalRelocs;
1189   }
1190 }
1191 
1192 // For -shared (PIC) output, we create create a synthetic function which will
1193 // apply any relocations to the data segments on startup.  This function is
1194 // called `__wasm_apply_data_relocs` and is added at the beginning of
1195 // `__wasm_call_ctors` before any of the constructors run.
1196 void Writer::createApplyDataRelocationsFunction() {
1197   LLVM_DEBUG(dbgs() << "createApplyDataRelocationsFunction\n");
1198   // First write the body's contents to a string.
1199   std::string bodyContent;
1200   {
1201     raw_string_ostream os(bodyContent);
1202     writeUleb128(os, 0, "num locals");
1203     for (const OutputSegment *seg : segments)
1204       for (const InputChunk *inSeg : seg->inputSegments)
1205         inSeg->generateRelocationCode(os);
1206 
1207     writeU8(os, WASM_OPCODE_END, "END");
1208   }
1209 
1210   createFunction(WasmSym::applyDataRelocs, bodyContent);
1211 }
1212 
1213 // Similar to createApplyDataRelocationsFunction but generates relocation code
1214 // fro WebAssembly globals. Because these globals are not shared between threads
1215 // these relocation need to run on every thread.
1216 void Writer::createApplyGlobalRelocationsFunction() {
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     out.globalSec->generateRelocationCode(os);
1223     writeU8(os, WASM_OPCODE_END, "END");
1224   }
1225 
1226   createFunction(WasmSym::applyGlobalRelocs, bodyContent);
1227 }
1228 
1229 // Create synthetic "__wasm_call_ctors" function based on ctor functions
1230 // in input object.
1231 void Writer::createCallCtorsFunction() {
1232   // If __wasm_call_ctors isn't referenced, there aren't any ctors, and we
1233   // aren't calling `__wasm_apply_data_relocs` for Emscripten-style PIC, don't
1234   // define the `__wasm_call_ctors` function.
1235   if (!WasmSym::callCtors->isLive() && !WasmSym::applyDataRelocs &&
1236       initFunctions.empty())
1237     return;
1238 
1239   // First write the body's contents to a string.
1240   std::string bodyContent;
1241   {
1242     raw_string_ostream os(bodyContent);
1243     writeUleb128(os, 0, "num locals");
1244 
1245     if (WasmSym::applyDataRelocs) {
1246       writeU8(os, WASM_OPCODE_CALL, "CALL");
1247       writeUleb128(os, WasmSym::applyDataRelocs->getFunctionIndex(),
1248                    "function index");
1249     }
1250 
1251     // Call constructors
1252     for (const WasmInitEntry &f : initFunctions) {
1253       writeU8(os, WASM_OPCODE_CALL, "CALL");
1254       writeUleb128(os, f.sym->getFunctionIndex(), "function index");
1255       for (size_t i = 0; i < f.sym->signature->Returns.size(); i++) {
1256         writeU8(os, WASM_OPCODE_DROP, "DROP");
1257       }
1258     }
1259 
1260     writeU8(os, WASM_OPCODE_END, "END");
1261   }
1262 
1263   createFunction(WasmSym::callCtors, bodyContent);
1264 }
1265 
1266 // Create a wrapper around a function export which calls the
1267 // static constructors and destructors.
1268 void Writer::createCommandExportWrapper(uint32_t functionIndex,
1269                                         DefinedFunction *f) {
1270   // First write the body's contents to a string.
1271   std::string bodyContent;
1272   {
1273     raw_string_ostream os(bodyContent);
1274     writeUleb128(os, 0, "num locals");
1275 
1276     // Call `__wasm_call_ctors` which call static constructors (and
1277     // applies any runtime relocations in Emscripten-style PIC mode)
1278     if (WasmSym::callCtors->isLive()) {
1279       writeU8(os, WASM_OPCODE_CALL, "CALL");
1280       writeUleb128(os, WasmSym::callCtors->getFunctionIndex(),
1281                    "function index");
1282     }
1283 
1284     // Call the user's code, leaving any return values on the operand stack.
1285     for (size_t i = 0; i < f->signature->Params.size(); ++i) {
1286       writeU8(os, WASM_OPCODE_LOCAL_GET, "local.get");
1287       writeUleb128(os, i, "local index");
1288     }
1289     writeU8(os, WASM_OPCODE_CALL, "CALL");
1290     writeUleb128(os, functionIndex, "function index");
1291 
1292     // Call the function that calls the destructors.
1293     if (DefinedFunction *callDtors = WasmSym::callDtors) {
1294       writeU8(os, WASM_OPCODE_CALL, "CALL");
1295       writeUleb128(os, callDtors->getFunctionIndex(), "function index");
1296     }
1297 
1298     // End the function, returning the return values from the user's code.
1299     writeU8(os, WASM_OPCODE_END, "END");
1300   }
1301 
1302   createFunction(f, bodyContent);
1303 }
1304 
1305 void Writer::createInitTLSFunction() {
1306   std::string bodyContent;
1307   {
1308     raw_string_ostream os(bodyContent);
1309 
1310     OutputSegment *tlsSeg = nullptr;
1311     for (auto *seg : segments) {
1312       if (seg->name == ".tdata") {
1313         tlsSeg = seg;
1314         break;
1315       }
1316     }
1317 
1318     writeUleb128(os, 0, "num locals");
1319     if (tlsSeg) {
1320       writeU8(os, WASM_OPCODE_LOCAL_GET, "local.get");
1321       writeUleb128(os, 0, "local index");
1322 
1323       writeU8(os, WASM_OPCODE_GLOBAL_SET, "global.set");
1324       writeUleb128(os, WasmSym::tlsBase->getGlobalIndex(), "global index");
1325 
1326       // FIXME(wvo): this local needs to be I64 in wasm64, or we need an extend op.
1327       writeU8(os, WASM_OPCODE_LOCAL_GET, "local.get");
1328       writeUleb128(os, 0, "local index");
1329 
1330       writeI32Const(os, 0, "segment offset");
1331 
1332       writeI32Const(os, tlsSeg->size, "memory region size");
1333 
1334       writeU8(os, WASM_OPCODE_MISC_PREFIX, "bulk-memory prefix");
1335       writeUleb128(os, WASM_OPCODE_MEMORY_INIT, "MEMORY.INIT");
1336       writeUleb128(os, tlsSeg->index, "segment index immediate");
1337       writeU8(os, 0, "memory index immediate");
1338     }
1339     writeU8(os, WASM_OPCODE_END, "end function");
1340   }
1341 
1342   createFunction(WasmSym::initTLS, bodyContent);
1343 }
1344 
1345 // Populate InitFunctions vector with init functions from all input objects.
1346 // This is then used either when creating the output linking section or to
1347 // synthesize the "__wasm_call_ctors" function.
1348 void Writer::calculateInitFunctions() {
1349   if (!config->relocatable && !WasmSym::callCtors->isLive())
1350     return;
1351 
1352   for (ObjFile *file : symtab->objectFiles) {
1353     const WasmLinkingData &l = file->getWasmObj()->linkingData();
1354     for (const WasmInitFunc &f : l.InitFunctions) {
1355       FunctionSymbol *sym = file->getFunctionSymbol(f.Symbol);
1356       // comdat exclusions can cause init functions be discarded.
1357       if (sym->isDiscarded() || !sym->isLive())
1358         continue;
1359       if (sym->signature->Params.size() != 0)
1360         error("constructor functions cannot take arguments: " + toString(*sym));
1361       LLVM_DEBUG(dbgs() << "initFunctions: " << toString(*sym) << "\n");
1362       initFunctions.emplace_back(WasmInitEntry{sym, f.Priority});
1363     }
1364   }
1365 
1366   // Sort in order of priority (lowest first) so that they are called
1367   // in the correct order.
1368   llvm::stable_sort(initFunctions,
1369                     [](const WasmInitEntry &l, const WasmInitEntry &r) {
1370                       return l.priority < r.priority;
1371                     });
1372 }
1373 
1374 void Writer::createSyntheticSections() {
1375   out.dylinkSec = make<DylinkSection>();
1376   out.typeSec = make<TypeSection>();
1377   out.importSec = make<ImportSection>();
1378   out.functionSec = make<FunctionSection>();
1379   out.tableSec = make<TableSection>();
1380   out.memorySec = make<MemorySection>();
1381   out.eventSec = make<EventSection>();
1382   out.globalSec = make<GlobalSection>();
1383   out.exportSec = make<ExportSection>();
1384   out.startSec = make<StartSection>();
1385   out.elemSec = make<ElemSection>();
1386   out.producersSec = make<ProducersSection>();
1387   out.targetFeaturesSec = make<TargetFeaturesSection>();
1388 }
1389 
1390 void Writer::createSyntheticSectionsPostLayout() {
1391   out.dataCountSec = make<DataCountSection>(segments);
1392   out.linkingSec = make<LinkingSection>(initFunctions, segments);
1393   out.nameSec = make<NameSection>(segments);
1394 }
1395 
1396 void Writer::run() {
1397   if (config->relocatable || config->isPic)
1398     config->globalBase = 0;
1399 
1400   // For PIC code the table base is assigned dynamically by the loader.
1401   // For non-PIC, we start at 1 so that accessing table index 0 always traps.
1402   if (!config->isPic) {
1403     config->tableBase = 1;
1404     if (WasmSym::definedTableBase)
1405       WasmSym::definedTableBase->setVA(config->tableBase);
1406   }
1407 
1408   log("-- createOutputSegments");
1409   createOutputSegments();
1410   log("-- createSyntheticSections");
1411   createSyntheticSections();
1412   log("-- layoutMemory");
1413   layoutMemory();
1414 
1415   if (!config->relocatable) {
1416     // Create linker synthesized __start_SECNAME/__stop_SECNAME symbols
1417     // This has to be done after memory layout is performed.
1418     for (const OutputSegment *seg : segments) {
1419       addStartStopSymbols(seg);
1420     }
1421   }
1422 
1423   for (auto &pair : config->exportedSymbols) {
1424     Symbol *sym = symtab->find(pair.first());
1425     if (sym && sym->isDefined())
1426       sym->forceExport = true;
1427   }
1428 
1429   // Delay reporting error about explict exports until after addStartStopSymbols
1430   // which can create optional symbols.
1431   for (auto &name : config->requiredExports) {
1432     Symbol *sym = symtab->find(name);
1433     if (!sym || !sym->isDefined()) {
1434       if (config->unresolvedSymbols == UnresolvedPolicy::ReportError)
1435         error(Twine("symbol exported via --export not found: ") + name);
1436       if (config->unresolvedSymbols == UnresolvedPolicy::Warn)
1437         warn(Twine("symbol exported via --export not found: ") + name);
1438     }
1439   }
1440 
1441   if (config->isPic) {
1442     log("-- combineOutputSegments");
1443     combineOutputSegments();
1444   }
1445 
1446   log("-- createSyntheticSectionsPostLayout");
1447   createSyntheticSectionsPostLayout();
1448   log("-- populateProducers");
1449   populateProducers();
1450   log("-- calculateImports");
1451   calculateImports();
1452   log("-- scanRelocations");
1453   scanRelocations();
1454   log("-- finalizeIndirectFunctionTable");
1455   finalizeIndirectFunctionTable();
1456   log("-- createSyntheticInitFunctions");
1457   createSyntheticInitFunctions();
1458   log("-- assignIndexes");
1459   assignIndexes();
1460   log("-- calculateInitFunctions");
1461   calculateInitFunctions();
1462 
1463   if (!config->relocatable) {
1464     // Create linker synthesized functions
1465     if (WasmSym::applyDataRelocs)
1466       createApplyDataRelocationsFunction();
1467     if (WasmSym::applyGlobalRelocs)
1468       createApplyGlobalRelocationsFunction();
1469     if (WasmSym::initMemory)
1470       createInitMemoryFunction();
1471     createStartFunction();
1472 
1473     createCallCtorsFunction();
1474 
1475     // Create export wrappers for commands if needed.
1476     //
1477     // If the input contains a call to `__wasm_call_ctors`, either in one of
1478     // the input objects or an explicit export from the command-line, we
1479     // assume ctors and dtors are taken care of already.
1480     if (!config->relocatable && !config->isPic &&
1481         !WasmSym::callCtors->isUsedInRegularObj &&
1482         !WasmSym::callCtors->isExported()) {
1483       log("-- createCommandExportWrappers");
1484       createCommandExportWrappers();
1485     }
1486   }
1487 
1488   if (WasmSym::initTLS && WasmSym::initTLS->isLive())
1489     createInitTLSFunction();
1490 
1491   if (errorCount())
1492     return;
1493 
1494   log("-- calculateTypes");
1495   calculateTypes();
1496   log("-- calculateExports");
1497   calculateExports();
1498   log("-- calculateCustomSections");
1499   calculateCustomSections();
1500   log("-- populateSymtab");
1501   populateSymtab();
1502   log("-- populateTargetFeatures");
1503   populateTargetFeatures();
1504   log("-- addSections");
1505   addSections();
1506 
1507   if (errorHandler().verbose) {
1508     log("Defined Functions: " + Twine(out.functionSec->inputFunctions.size()));
1509     log("Defined Globals  : " + Twine(out.globalSec->numGlobals()));
1510     log("Defined Events   : " + Twine(out.eventSec->inputEvents.size()));
1511     log("Defined Tables   : " + Twine(out.tableSec->inputTables.size()));
1512     log("Function Imports : " +
1513         Twine(out.importSec->getNumImportedFunctions()));
1514     log("Global Imports   : " + Twine(out.importSec->getNumImportedGlobals()));
1515     log("Event Imports    : " + Twine(out.importSec->getNumImportedEvents()));
1516     log("Table Imports    : " + Twine(out.importSec->getNumImportedTables()));
1517     for (ObjFile *file : symtab->objectFiles)
1518       file->dumpInfo();
1519   }
1520 
1521   createHeader();
1522   log("-- finalizeSections");
1523   finalizeSections();
1524 
1525   log("-- writeMapFile");
1526   writeMapFile(outputSections);
1527 
1528   log("-- openFile");
1529   openFile();
1530   if (errorCount())
1531     return;
1532 
1533   writeHeader();
1534 
1535   log("-- writeSections");
1536   writeSections();
1537   if (errorCount())
1538     return;
1539 
1540   if (Error e = buffer->commit())
1541     fatal("failed to write the output file: " + toString(std::move(e)));
1542 }
1543 
1544 // Open a result file.
1545 void Writer::openFile() {
1546   log("writing: " + config->outputFile);
1547 
1548   Expected<std::unique_ptr<FileOutputBuffer>> bufferOrErr =
1549       FileOutputBuffer::create(config->outputFile, fileSize,
1550                                FileOutputBuffer::F_executable);
1551 
1552   if (!bufferOrErr)
1553     error("failed to open " + config->outputFile + ": " +
1554           toString(bufferOrErr.takeError()));
1555   else
1556     buffer = std::move(*bufferOrErr);
1557 }
1558 
1559 void Writer::createHeader() {
1560   raw_string_ostream os(header);
1561   writeBytes(os, WasmMagic, sizeof(WasmMagic), "wasm magic");
1562   writeU32(os, WasmVersion, "wasm version");
1563   os.flush();
1564   fileSize += header.size();
1565 }
1566 
1567 void writeResult() { Writer().run(); }
1568 
1569 } // namespace wasm
1570 } // namespace lld
1571