xref: /llvm-project-15.0.7/lld/wasm/Writer.cpp (revision 5aa5eba1)
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.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 active data segment since
899   // we only have a single __memory_base to use as our base address.  This pass
900   // combines all data segments into a single .data segment.
901   // This restructions can be relaxed once we have extended constant
902   // expressions available:
903   // https://github.com/WebAssembly/extended-const
904   assert(config->isPic && !config->sharedMemory);
905   if (segments.size() <= 1)
906     return;
907   OutputSegment *combined = make<OutputSegment>(".data");
908   combined->startVA = segments[0]->startVA;
909   for (OutputSegment *s : segments) {
910     bool first = true;
911     for (InputChunk *inSeg : s->inputSegments) {
912       if (first)
913         inSeg->alignment = std::max(inSeg->alignment, s->alignment);
914       first = false;
915 #ifndef NDEBUG
916       uint64_t oldVA = inSeg->getVA();
917 #endif
918       combined->addInputSegment(inSeg);
919 #ifndef NDEBUG
920       uint64_t newVA = inSeg->getVA();
921       LLVM_DEBUG(dbgs() << "added input segment. name=" << inSeg->getName()
922                         << " oldVA=" << oldVA << " newVA=" << newVA << "\n");
923       assert(oldVA == newVA);
924 #endif
925     }
926   }
927 
928   segments = {combined};
929 }
930 
931 static void createFunction(DefinedFunction *func, StringRef bodyContent) {
932   std::string functionBody;
933   {
934     raw_string_ostream os(functionBody);
935     writeUleb128(os, bodyContent.size(), "function size");
936     os << bodyContent;
937   }
938   ArrayRef<uint8_t> body = arrayRefFromStringRef(saver.save(functionBody));
939   cast<SyntheticFunction>(func->function)->setBody(body);
940 }
941 
942 bool Writer::needsPassiveInitialization(const OutputSegment *segment) {
943   return segment->initFlags & WASM_DATA_SEGMENT_IS_PASSIVE &&
944          !segment->isTLS() && !segment->isBss;
945 }
946 
947 bool Writer::hasPassiveInitializedSegments() {
948   return std::find_if(segments.begin(), segments.end(),
949                       [this](const OutputSegment *s) {
950                         return this->needsPassiveInitialization(s);
951                       }) != segments.end();
952 }
953 
954 void Writer::createSyntheticInitFunctions() {
955   if (config->relocatable)
956     return;
957 
958   static WasmSignature nullSignature = {{}, {}};
959 
960   // Passive segments are used to avoid memory being reinitialized on each
961   // thread's instantiation. These passive segments are initialized and
962   // dropped in __wasm_init_memory, which is registered as the start function
963   if (config->sharedMemory && hasPassiveInitializedSegments()) {
964     WasmSym::initMemory = symtab->addSyntheticFunction(
965         "__wasm_init_memory", WASM_SYMBOL_VISIBILITY_HIDDEN,
966         make<SyntheticFunction>(nullSignature, "__wasm_init_memory"));
967     WasmSym::initMemory->markLive();
968   }
969 
970   if (config->isPic) {
971     // For PIC code we create synthetic functions that apply relocations.
972     // These get called from __wasm_call_ctors before the user-level
973     // constructors.
974     WasmSym::applyDataRelocs = symtab->addSyntheticFunction(
975         "__wasm_apply_data_relocs", WASM_SYMBOL_VISIBILITY_HIDDEN,
976         make<SyntheticFunction>(nullSignature, "__wasm_apply_data_relocs"));
977     WasmSym::applyDataRelocs->markLive();
978 
979     if (out.globalSec->needsRelocations()) {
980       WasmSym::applyGlobalRelocs = symtab->addSyntheticFunction(
981           "__wasm_apply_global_relocs", WASM_SYMBOL_VISIBILITY_HIDDEN,
982           make<SyntheticFunction>(nullSignature, "__wasm_apply_global_relocs"));
983       WasmSym::applyGlobalRelocs->markLive();
984     }
985   }
986 
987   if (WasmSym::applyGlobalRelocs && WasmSym::initMemory) {
988     WasmSym::startFunction = symtab->addSyntheticFunction(
989         "__wasm_start", WASM_SYMBOL_VISIBILITY_HIDDEN,
990         make<SyntheticFunction>(nullSignature, "__wasm_start"));
991     WasmSym::startFunction->markLive();
992   }
993 }
994 
995 void Writer::createInitMemoryFunction() {
996   LLVM_DEBUG(dbgs() << "createInitMemoryFunction\n");
997   assert(WasmSym::initMemory);
998   assert(WasmSym::initMemoryFlag);
999   assert(hasPassiveInitializedSegments());
1000   uint64_t flagAddress = WasmSym::initMemoryFlag->getVA();
1001   bool is64 = config->is64.getValueOr(false);
1002   std::string bodyContent;
1003   {
1004     raw_string_ostream os(bodyContent);
1005     // Initialize memory in a thread-safe manner. The thread that successfully
1006     // increments the flag from 0 to 1 is is responsible for performing the
1007     // memory initialization. Other threads go sleep on the flag until the
1008     // first thread finishing initializing memory, increments the flag to 2,
1009     // and wakes all the other threads. Once the flag has been set to 2,
1010     // subsequently started threads will skip the sleep. All threads
1011     // unconditionally drop their passive data segments once memory has been
1012     // initialized. The generated code is as follows:
1013     //
1014     // (func $__wasm_init_memory
1015     //  (if
1016     //   (i32.atomic.rmw.cmpxchg align=2 offset=0
1017     //    (i32.const $__init_memory_flag)
1018     //    (i32.const 0)
1019     //    (i32.const 1)
1020     //   )
1021     //   (then
1022     //    (drop
1023     //     (i32.atomic.wait align=2 offset=0
1024     //      (i32.const $__init_memory_flag)
1025     //      (i32.const 1)
1026     //      (i32.const -1)
1027     //     )
1028     //    )
1029     //   )
1030     //   (else
1031     //    ( ... initialize data segments ... )
1032     //    (i32.atomic.store align=2 offset=0
1033     //     (i32.const $__init_memory_flag)
1034     //     (i32.const 2)
1035     //    )
1036     //    (drop
1037     //     (i32.atomic.notify align=2 offset=0
1038     //      (i32.const $__init_memory_flag)
1039     //      (i32.const -1u)
1040     //     )
1041     //    )
1042     //   )
1043     //  )
1044     //  ( ... drop data segments ... )
1045     // )
1046     //
1047     // When we are building with PIC, calculate the flag location using:
1048     //
1049     //    (global.get $__memory_base)
1050     //    (i32.const $__init_memory_flag)
1051     //    (i32.const 1)
1052 
1053     // With PIC code we cache the flag address in local 0
1054     if (config->isPic) {
1055       writeUleb128(os, 1, "num local decls");
1056       writeUleb128(os, 1, "local count");
1057       writeU8(os, is64 ? WASM_TYPE_I64 : WASM_TYPE_I32, "address type");
1058       writeU8(os, WASM_OPCODE_GLOBAL_GET, "GLOBAL_GET");
1059       writeUleb128(os, WasmSym::memoryBase->getGlobalIndex(), "memory_base");
1060       writePtrConst(os, flagAddress, is64, "flag address");
1061       writeU8(os, WASM_OPCODE_I32_ADD, "add");
1062       writeU8(os, WASM_OPCODE_LOCAL_SET, "local.set");
1063       writeUleb128(os, 0, "local 0");
1064     } else {
1065       writeUleb128(os, 0, "num locals");
1066     }
1067 
1068     auto writeGetFlagAddress = [&]() {
1069       if (config->isPic) {
1070         writeU8(os, WASM_OPCODE_LOCAL_GET, "local.get");
1071         writeUleb128(os, 0, "local 0");
1072       } else {
1073         writePtrConst(os, flagAddress, is64, "flag address");
1074       }
1075     };
1076 
1077     // Atomically check whether this is the main thread.
1078     writeGetFlagAddress();
1079     writeI32Const(os, 0, "expected flag value");
1080     writeI32Const(os, 1, "flag value");
1081     writeU8(os, WASM_OPCODE_ATOMICS_PREFIX, "atomics prefix");
1082     writeUleb128(os, WASM_OPCODE_I32_RMW_CMPXCHG, "i32.atomic.rmw.cmpxchg");
1083     writeMemArg(os, 2, 0);
1084     writeU8(os, WASM_OPCODE_IF, "IF");
1085     writeU8(os, WASM_TYPE_NORESULT, "blocktype");
1086 
1087     // Did not increment 0, so wait for main thread to initialize memory
1088     writeGetFlagAddress();
1089     writeI32Const(os, 1, "expected flag value");
1090     writeI64Const(os, -1, "timeout");
1091 
1092     writeU8(os, WASM_OPCODE_ATOMICS_PREFIX, "atomics prefix");
1093     writeUleb128(os, WASM_OPCODE_I32_ATOMIC_WAIT, "i32.atomic.wait");
1094     writeMemArg(os, 2, 0);
1095     writeU8(os, WASM_OPCODE_DROP, "drop");
1096 
1097     writeU8(os, WASM_OPCODE_ELSE, "ELSE");
1098 
1099     // Did increment 0, so conditionally initialize passive data segments
1100     for (const OutputSegment *s : segments) {
1101       if (needsPassiveInitialization(s)) {
1102         // destination address
1103         writePtrConst(os, s->startVA, is64, "destination address");
1104         if (config->isPic) {
1105           writeU8(os, WASM_OPCODE_GLOBAL_GET, "GLOBAL_GET");
1106           writeUleb128(os, WasmSym::memoryBase->getGlobalIndex(),
1107                        "memory_base");
1108           writeU8(os, WASM_OPCODE_I32_ADD, "i32.add");
1109         }
1110         // source segment offset
1111         writeI32Const(os, 0, "segment offset");
1112         // memory region size
1113         writeI32Const(os, s->size, "memory region size");
1114         // memory.init instruction
1115         writeU8(os, WASM_OPCODE_MISC_PREFIX, "bulk-memory prefix");
1116         writeUleb128(os, WASM_OPCODE_MEMORY_INIT, "memory.init");
1117         writeUleb128(os, s->index, "segment index immediate");
1118         writeU8(os, 0, "memory index immediate");
1119       }
1120     }
1121 
1122     // Set flag to 2 to mark end of initialization
1123     writeGetFlagAddress();
1124     writeI32Const(os, 2, "flag value");
1125     writeU8(os, WASM_OPCODE_ATOMICS_PREFIX, "atomics prefix");
1126     writeUleb128(os, WASM_OPCODE_I32_ATOMIC_STORE, "i32.atomic.store");
1127     writeMemArg(os, 2, 0);
1128 
1129     // Notify any waiters that memory initialization is complete
1130     writeGetFlagAddress();
1131     writeI32Const(os, -1, "number of waiters");
1132     writeU8(os, WASM_OPCODE_ATOMICS_PREFIX, "atomics prefix");
1133     writeUleb128(os, WASM_OPCODE_ATOMIC_NOTIFY, "atomic.notify");
1134     writeMemArg(os, 2, 0);
1135     writeU8(os, WASM_OPCODE_DROP, "drop");
1136 
1137     writeU8(os, WASM_OPCODE_END, "END");
1138 
1139     // Unconditionally drop passive data segments
1140     for (const OutputSegment *s : segments) {
1141       if (needsPassiveInitialization(s)) {
1142         // data.drop instruction
1143         writeU8(os, WASM_OPCODE_MISC_PREFIX, "bulk-memory prefix");
1144         writeUleb128(os, WASM_OPCODE_DATA_DROP, "data.drop");
1145         writeUleb128(os, s->index, "segment index immediate");
1146       }
1147     }
1148     writeU8(os, WASM_OPCODE_END, "END");
1149   }
1150 
1151   createFunction(WasmSym::initMemory, bodyContent);
1152 }
1153 
1154 void Writer::createStartFunction() {
1155   if (WasmSym::startFunction) {
1156     std::string bodyContent;
1157     {
1158       raw_string_ostream os(bodyContent);
1159       writeUleb128(os, 0, "num locals");
1160       writeU8(os, WASM_OPCODE_CALL, "CALL");
1161       writeUleb128(os, WasmSym::initMemory->getFunctionIndex(),
1162                    "function index");
1163       writeU8(os, WASM_OPCODE_CALL, "CALL");
1164       writeUleb128(os, WasmSym::applyGlobalRelocs->getFunctionIndex(),
1165                    "function index");
1166       writeU8(os, WASM_OPCODE_END, "END");
1167     }
1168     createFunction(WasmSym::startFunction, bodyContent);
1169   } else if (WasmSym::initMemory) {
1170     WasmSym::startFunction = WasmSym::initMemory;
1171   } else if (WasmSym::applyGlobalRelocs) {
1172     WasmSym::startFunction = WasmSym::applyGlobalRelocs;
1173   }
1174 }
1175 
1176 // For -shared (PIC) output, we create create a synthetic function which will
1177 // apply any relocations to the data segments on startup.  This function is
1178 // called `__wasm_apply_data_relocs` and is added at the beginning of
1179 // `__wasm_call_ctors` before any of the constructors run.
1180 void Writer::createApplyDataRelocationsFunction() {
1181   LLVM_DEBUG(dbgs() << "createApplyDataRelocationsFunction\n");
1182   // First write the body's contents to a string.
1183   std::string bodyContent;
1184   {
1185     raw_string_ostream os(bodyContent);
1186     writeUleb128(os, 0, "num locals");
1187     for (const OutputSegment *seg : segments)
1188       for (const InputChunk *inSeg : seg->inputSegments)
1189         inSeg->generateRelocationCode(os);
1190 
1191     writeU8(os, WASM_OPCODE_END, "END");
1192   }
1193 
1194   createFunction(WasmSym::applyDataRelocs, bodyContent);
1195 }
1196 
1197 // Similar to createApplyDataRelocationsFunction but generates relocation code
1198 // fro WebAssembly globals. Because these globals are not shared between threads
1199 // these relocation need to run on every thread.
1200 void Writer::createApplyGlobalRelocationsFunction() {
1201   // First write the body's contents to a string.
1202   std::string bodyContent;
1203   {
1204     raw_string_ostream os(bodyContent);
1205     writeUleb128(os, 0, "num locals");
1206     out.globalSec->generateRelocationCode(os);
1207     writeU8(os, WASM_OPCODE_END, "END");
1208   }
1209 
1210   createFunction(WasmSym::applyGlobalRelocs, bodyContent);
1211 }
1212 
1213 // Create synthetic "__wasm_call_ctors" function based on ctor functions
1214 // in input object.
1215 void Writer::createCallCtorsFunction() {
1216   // If __wasm_call_ctors isn't referenced, there aren't any ctors, and we
1217   // aren't calling `__wasm_apply_data_relocs` for Emscripten-style PIC, don't
1218   // define the `__wasm_call_ctors` function.
1219   if (!WasmSym::callCtors->isLive() && !WasmSym::applyDataRelocs &&
1220       initFunctions.empty())
1221     return;
1222 
1223   // First write the body's contents to a string.
1224   std::string bodyContent;
1225   {
1226     raw_string_ostream os(bodyContent);
1227     writeUleb128(os, 0, "num locals");
1228 
1229     if (WasmSym::applyDataRelocs) {
1230       writeU8(os, WASM_OPCODE_CALL, "CALL");
1231       writeUleb128(os, WasmSym::applyDataRelocs->getFunctionIndex(),
1232                    "function index");
1233     }
1234 
1235     // Call constructors
1236     for (const WasmInitEntry &f : initFunctions) {
1237       writeU8(os, WASM_OPCODE_CALL, "CALL");
1238       writeUleb128(os, f.sym->getFunctionIndex(), "function index");
1239       for (size_t i = 0; i < f.sym->signature->Returns.size(); i++) {
1240         writeU8(os, WASM_OPCODE_DROP, "DROP");
1241       }
1242     }
1243 
1244     writeU8(os, WASM_OPCODE_END, "END");
1245   }
1246 
1247   createFunction(WasmSym::callCtors, bodyContent);
1248 }
1249 
1250 // Create a wrapper around a function export which calls the
1251 // static constructors and destructors.
1252 void Writer::createCommandExportWrapper(uint32_t functionIndex,
1253                                         DefinedFunction *f) {
1254   // First write the body's contents to a string.
1255   std::string bodyContent;
1256   {
1257     raw_string_ostream os(bodyContent);
1258     writeUleb128(os, 0, "num locals");
1259 
1260     // Call `__wasm_call_ctors` which call static constructors (and
1261     // applies any runtime relocations in Emscripten-style PIC mode)
1262     if (WasmSym::callCtors->isLive()) {
1263       writeU8(os, WASM_OPCODE_CALL, "CALL");
1264       writeUleb128(os, WasmSym::callCtors->getFunctionIndex(),
1265                    "function index");
1266     }
1267 
1268     // Call the user's code, leaving any return values on the operand stack.
1269     for (size_t i = 0; i < f->signature->Params.size(); ++i) {
1270       writeU8(os, WASM_OPCODE_LOCAL_GET, "local.get");
1271       writeUleb128(os, i, "local index");
1272     }
1273     writeU8(os, WASM_OPCODE_CALL, "CALL");
1274     writeUleb128(os, functionIndex, "function index");
1275 
1276     // Call the function that calls the destructors.
1277     if (DefinedFunction *callDtors = WasmSym::callDtors) {
1278       writeU8(os, WASM_OPCODE_CALL, "CALL");
1279       writeUleb128(os, callDtors->getFunctionIndex(), "function index");
1280     }
1281 
1282     // End the function, returning the return values from the user's code.
1283     writeU8(os, WASM_OPCODE_END, "END");
1284   }
1285 
1286   createFunction(f, bodyContent);
1287 }
1288 
1289 void Writer::createInitTLSFunction() {
1290   std::string bodyContent;
1291   {
1292     raw_string_ostream os(bodyContent);
1293 
1294     OutputSegment *tlsSeg = nullptr;
1295     for (auto *seg : segments) {
1296       if (seg->name == ".tdata") {
1297         tlsSeg = seg;
1298         break;
1299       }
1300     }
1301 
1302     writeUleb128(os, 0, "num locals");
1303     if (tlsSeg) {
1304       writeU8(os, WASM_OPCODE_LOCAL_GET, "local.get");
1305       writeUleb128(os, 0, "local index");
1306 
1307       writeU8(os, WASM_OPCODE_GLOBAL_SET, "global.set");
1308       writeUleb128(os, WasmSym::tlsBase->getGlobalIndex(), "global index");
1309 
1310       // FIXME(wvo): this local needs to be I64 in wasm64, or we need an extend op.
1311       writeU8(os, WASM_OPCODE_LOCAL_GET, "local.get");
1312       writeUleb128(os, 0, "local index");
1313 
1314       writeI32Const(os, 0, "segment offset");
1315 
1316       writeI32Const(os, tlsSeg->size, "memory region size");
1317 
1318       writeU8(os, WASM_OPCODE_MISC_PREFIX, "bulk-memory prefix");
1319       writeUleb128(os, WASM_OPCODE_MEMORY_INIT, "MEMORY.INIT");
1320       writeUleb128(os, tlsSeg->index, "segment index immediate");
1321       writeU8(os, 0, "memory index immediate");
1322     }
1323     writeU8(os, WASM_OPCODE_END, "end function");
1324   }
1325 
1326   createFunction(WasmSym::initTLS, bodyContent);
1327 }
1328 
1329 // Populate InitFunctions vector with init functions from all input objects.
1330 // This is then used either when creating the output linking section or to
1331 // synthesize the "__wasm_call_ctors" function.
1332 void Writer::calculateInitFunctions() {
1333   if (!config->relocatable && !WasmSym::callCtors->isLive())
1334     return;
1335 
1336   for (ObjFile *file : symtab->objectFiles) {
1337     const WasmLinkingData &l = file->getWasmObj()->linkingData();
1338     for (const WasmInitFunc &f : l.InitFunctions) {
1339       FunctionSymbol *sym = file->getFunctionSymbol(f.Symbol);
1340       // comdat exclusions can cause init functions be discarded.
1341       if (sym->isDiscarded() || !sym->isLive())
1342         continue;
1343       if (sym->signature->Params.size() != 0)
1344         error("constructor functions cannot take arguments: " + toString(*sym));
1345       LLVM_DEBUG(dbgs() << "initFunctions: " << toString(*sym) << "\n");
1346       initFunctions.emplace_back(WasmInitEntry{sym, f.Priority});
1347     }
1348   }
1349 
1350   // Sort in order of priority (lowest first) so that they are called
1351   // in the correct order.
1352   llvm::stable_sort(initFunctions,
1353                     [](const WasmInitEntry &l, const WasmInitEntry &r) {
1354                       return l.priority < r.priority;
1355                     });
1356 }
1357 
1358 void Writer::createSyntheticSections() {
1359   out.dylinkSec = make<DylinkSection>();
1360   out.typeSec = make<TypeSection>();
1361   out.importSec = make<ImportSection>();
1362   out.functionSec = make<FunctionSection>();
1363   out.tableSec = make<TableSection>();
1364   out.memorySec = make<MemorySection>();
1365   out.eventSec = make<EventSection>();
1366   out.globalSec = make<GlobalSection>();
1367   out.exportSec = make<ExportSection>();
1368   out.startSec = make<StartSection>();
1369   out.elemSec = make<ElemSection>();
1370   out.producersSec = make<ProducersSection>();
1371   out.targetFeaturesSec = make<TargetFeaturesSection>();
1372 }
1373 
1374 void Writer::createSyntheticSectionsPostLayout() {
1375   out.dataCountSec = make<DataCountSection>(segments);
1376   out.linkingSec = make<LinkingSection>(initFunctions, segments);
1377   out.nameSec = make<NameSection>(segments);
1378 }
1379 
1380 void Writer::run() {
1381   if (config->relocatable || config->isPic)
1382     config->globalBase = 0;
1383 
1384   // For PIC code the table base is assigned dynamically by the loader.
1385   // For non-PIC, we start at 1 so that accessing table index 0 always traps.
1386   if (!config->isPic) {
1387     config->tableBase = 1;
1388     if (WasmSym::definedTableBase)
1389       WasmSym::definedTableBase->setVA(config->tableBase);
1390     if (WasmSym::definedTableBase32)
1391       WasmSym::definedTableBase32->setVA(config->tableBase);
1392   }
1393 
1394   log("-- createOutputSegments");
1395   createOutputSegments();
1396   log("-- createSyntheticSections");
1397   createSyntheticSections();
1398   log("-- layoutMemory");
1399   layoutMemory();
1400 
1401   if (!config->relocatable) {
1402     // Create linker synthesized __start_SECNAME/__stop_SECNAME symbols
1403     // This has to be done after memory layout is performed.
1404     for (const OutputSegment *seg : segments) {
1405       addStartStopSymbols(seg);
1406     }
1407   }
1408 
1409   for (auto &pair : config->exportedSymbols) {
1410     Symbol *sym = symtab->find(pair.first());
1411     if (sym && sym->isDefined())
1412       sym->forceExport = true;
1413   }
1414 
1415   // Delay reporting error about explict exports until after addStartStopSymbols
1416   // which can create optional symbols.
1417   for (auto &name : config->requiredExports) {
1418     Symbol *sym = symtab->find(name);
1419     if (!sym || !sym->isDefined()) {
1420       if (config->unresolvedSymbols == UnresolvedPolicy::ReportError)
1421         error(Twine("symbol exported via --export not found: ") + name);
1422       if (config->unresolvedSymbols == UnresolvedPolicy::Warn)
1423         warn(Twine("symbol exported via --export not found: ") + name);
1424     }
1425   }
1426 
1427   if (config->isPic && !config->sharedMemory) {
1428     // In shared memory mode all data segments are passive and initilized
1429     // via __wasm_init_memory.
1430     log("-- combineOutputSegments");
1431     combineOutputSegments();
1432   }
1433 
1434   log("-- createSyntheticSectionsPostLayout");
1435   createSyntheticSectionsPostLayout();
1436   log("-- populateProducers");
1437   populateProducers();
1438   log("-- calculateImports");
1439   calculateImports();
1440   log("-- scanRelocations");
1441   scanRelocations();
1442   log("-- finalizeIndirectFunctionTable");
1443   finalizeIndirectFunctionTable();
1444   log("-- createSyntheticInitFunctions");
1445   createSyntheticInitFunctions();
1446   log("-- assignIndexes");
1447   assignIndexes();
1448   log("-- calculateInitFunctions");
1449   calculateInitFunctions();
1450 
1451   if (!config->relocatable) {
1452     // Create linker synthesized functions
1453     if (WasmSym::applyDataRelocs)
1454       createApplyDataRelocationsFunction();
1455     if (WasmSym::applyGlobalRelocs)
1456       createApplyGlobalRelocationsFunction();
1457     if (WasmSym::initMemory)
1458       createInitMemoryFunction();
1459     createStartFunction();
1460 
1461     createCallCtorsFunction();
1462 
1463     // Create export wrappers for commands if needed.
1464     //
1465     // If the input contains a call to `__wasm_call_ctors`, either in one of
1466     // the input objects or an explicit export from the command-line, we
1467     // assume ctors and dtors are taken care of already.
1468     if (!config->relocatable && !config->isPic &&
1469         !WasmSym::callCtors->isUsedInRegularObj &&
1470         !WasmSym::callCtors->isExported()) {
1471       log("-- createCommandExportWrappers");
1472       createCommandExportWrappers();
1473     }
1474   }
1475 
1476   if (WasmSym::initTLS && WasmSym::initTLS->isLive())
1477     createInitTLSFunction();
1478 
1479   if (errorCount())
1480     return;
1481 
1482   log("-- calculateTypes");
1483   calculateTypes();
1484   log("-- calculateExports");
1485   calculateExports();
1486   log("-- calculateCustomSections");
1487   calculateCustomSections();
1488   log("-- populateSymtab");
1489   populateSymtab();
1490   log("-- populateTargetFeatures");
1491   populateTargetFeatures();
1492   log("-- addSections");
1493   addSections();
1494 
1495   if (errorHandler().verbose) {
1496     log("Defined Functions: " + Twine(out.functionSec->inputFunctions.size()));
1497     log("Defined Globals  : " + Twine(out.globalSec->numGlobals()));
1498     log("Defined Events   : " + Twine(out.eventSec->inputEvents.size()));
1499     log("Defined Tables   : " + Twine(out.tableSec->inputTables.size()));
1500     log("Function Imports : " +
1501         Twine(out.importSec->getNumImportedFunctions()));
1502     log("Global Imports   : " + Twine(out.importSec->getNumImportedGlobals()));
1503     log("Event Imports    : " + Twine(out.importSec->getNumImportedEvents()));
1504     log("Table Imports    : " + Twine(out.importSec->getNumImportedTables()));
1505     for (ObjFile *file : symtab->objectFiles)
1506       file->dumpInfo();
1507   }
1508 
1509   createHeader();
1510   log("-- finalizeSections");
1511   finalizeSections();
1512 
1513   log("-- writeMapFile");
1514   writeMapFile(outputSections);
1515 
1516   log("-- openFile");
1517   openFile();
1518   if (errorCount())
1519     return;
1520 
1521   writeHeader();
1522 
1523   log("-- writeSections");
1524   writeSections();
1525   if (errorCount())
1526     return;
1527 
1528   if (Error e = buffer->commit())
1529     fatal("failed to write the output file: " + toString(std::move(e)));
1530 }
1531 
1532 // Open a result file.
1533 void Writer::openFile() {
1534   log("writing: " + config->outputFile);
1535 
1536   Expected<std::unique_ptr<FileOutputBuffer>> bufferOrErr =
1537       FileOutputBuffer::create(config->outputFile, fileSize,
1538                                FileOutputBuffer::F_executable);
1539 
1540   if (!bufferOrErr)
1541     error("failed to open " + config->outputFile + ": " +
1542           toString(bufferOrErr.takeError()));
1543   else
1544     buffer = std::move(*bufferOrErr);
1545 }
1546 
1547 void Writer::createHeader() {
1548   raw_string_ostream os(header);
1549   writeBytes(os, WasmMagic, sizeof(WasmMagic), "wasm magic");
1550   writeU32(os, WasmVersion, "wasm version");
1551   os.flush();
1552   fileSize += header.size();
1553 }
1554 
1555 void writeResult() { Writer().run(); }
1556 
1557 } // namespace wasm
1558 } // namespace lld
1559