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