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