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