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