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