xref: /llvm-project-15.0.7/lld/wasm/Writer.cpp (revision eaebcbc6)
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 "InputEvent.h"
13 #include "InputGlobal.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/Object/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 createInitMemoryFunction();
61   void createApplyRelocationsFunction();
62   void createCallCtorsFunction();
63   void createInitTLSFunction();
64 
65   void assignIndexes();
66   void populateSymtab();
67   void populateProducers();
68   void populateTargetFeatures();
69   void calculateInitFunctions();
70   void calculateImports();
71   void calculateExports();
72   void calculateCustomSections();
73   void calculateTypes();
74   void createOutputSegments();
75   void layoutMemory();
76   void createHeader();
77 
78   void addSection(OutputSection *sec);
79 
80   void addSections();
81 
82   void createCustomSections();
83   void createSyntheticSections();
84   void finalizeSections();
85 
86   // Custom sections
87   void createRelocSections();
88 
89   void writeHeader();
90   void writeSections();
91 
92   uint64_t fileSize = 0;
93 
94   std::vector<WasmInitEntry> initFunctions;
95   llvm::StringMap<std::vector<InputSection *>> customSectionMapping;
96 
97   // Elements that are used to construct the final output
98   std::string header;
99   std::vector<OutputSection *> outputSections;
100 
101   std::unique_ptr<FileOutputBuffer> buffer;
102 
103   std::vector<OutputSegment *> segments;
104   llvm::SmallDenseMap<StringRef, OutputSegment *> segmentMap;
105 };
106 
107 } // anonymous namespace
108 
109 void Writer::calculateCustomSections() {
110   log("calculateCustomSections");
111   bool stripDebug = config->stripDebug || config->stripAll;
112   for (ObjFile *file : symtab->objectFiles) {
113     for (InputSection *section : file->customSections) {
114       StringRef name = section->getName();
115       // These custom sections are known the linker and synthesized rather than
116       // blindly copied.
117       if (name == "linking" || name == "name" || name == "producers" ||
118           name == "target_features" || name.startswith("reloc."))
119         continue;
120       // These custom sections are generated by `clang -fembed-bitcode`.
121       // These are used by the rust toolchain to ship LTO data along with
122       // compiled object code, but they don't want this included in the linker
123       // output.
124       if (name == ".llvmbc" || name == ".llvmcmd")
125         continue;
126       // Strip debug section in that option was specified.
127       if (stripDebug && name.startswith(".debug_"))
128         continue;
129       // Otherwise include custom sections by default and concatenate their
130       // contents.
131       customSectionMapping[name].push_back(section);
132     }
133   }
134 }
135 
136 void Writer::createCustomSections() {
137   log("createCustomSections");
138   for (auto &pair : customSectionMapping) {
139     StringRef name = pair.first();
140     LLVM_DEBUG(dbgs() << "createCustomSection: " << name << "\n");
141 
142     OutputSection *sec = make<CustomSection>(std::string(name), pair.second);
143     if (config->relocatable || config->emitRelocs) {
144       auto *sym = make<OutputSectionSymbol>(sec);
145       out.linkingSec->addToSymtab(sym);
146       sec->sectionSym = sym;
147     }
148     addSection(sec);
149   }
150 }
151 
152 // Create relocations sections in the final output.
153 // These are only created when relocatable output is requested.
154 void Writer::createRelocSections() {
155   log("createRelocSections");
156   // Don't use iterator here since we are adding to OutputSection
157   size_t origSize = outputSections.size();
158   for (size_t i = 0; i < origSize; i++) {
159     LLVM_DEBUG(dbgs() << "check section " << i << "\n");
160     OutputSection *sec = outputSections[i];
161 
162     // Count the number of needed sections.
163     uint32_t count = sec->getNumRelocations();
164     if (!count)
165       continue;
166 
167     StringRef name;
168     if (sec->type == WASM_SEC_DATA)
169       name = "reloc.DATA";
170     else if (sec->type == WASM_SEC_CODE)
171       name = "reloc.CODE";
172     else if (sec->type == WASM_SEC_CUSTOM)
173       name = saver.save("reloc." + sec->name);
174     else
175       llvm_unreachable(
176           "relocations only supported for code, data, or custom sections");
177 
178     addSection(make<RelocSection>(name, sec));
179   }
180 }
181 
182 void Writer::populateProducers() {
183   for (ObjFile *file : symtab->objectFiles) {
184     const WasmProducerInfo &info = file->getWasmObj()->getProducerInfo();
185     out.producersSec->addInfo(info);
186   }
187 }
188 
189 void Writer::writeHeader() {
190   memcpy(buffer->getBufferStart(), header.data(), header.size());
191 }
192 
193 void Writer::writeSections() {
194   uint8_t *buf = buffer->getBufferStart();
195   parallelForEach(outputSections, [buf](OutputSection *s) {
196     assert(s->isNeeded());
197     s->writeTo(buf);
198   });
199 }
200 
201 // Fix the memory layout of the output binary.  This assigns memory offsets
202 // to each of the input data sections as well as the explicit stack region.
203 // The default memory layout is as follows, from low to high.
204 //
205 //  - initialized data (starting at Config->globalBase)
206 //  - BSS data (not currently implemented in llvm)
207 //  - explicit stack (Config->ZStackSize)
208 //  - heap start / unallocated
209 //
210 // The --stack-first option means that stack is placed before any static data.
211 // This can be useful since it means that stack overflow traps immediately
212 // rather than overwriting global data, but also increases code size since all
213 // static data loads and stores requires larger offsets.
214 void Writer::layoutMemory() {
215   uint64_t memoryPtr = 0;
216 
217   auto placeStack = [&]() {
218     if (config->relocatable || config->isPic)
219       return;
220     memoryPtr = alignTo(memoryPtr, stackAlignment);
221     if (config->zStackSize != alignTo(config->zStackSize, stackAlignment))
222       error("stack size must be " + Twine(stackAlignment) + "-byte aligned");
223     log("mem: stack size  = " + Twine(config->zStackSize));
224     log("mem: stack base  = " + Twine(memoryPtr));
225     memoryPtr += config->zStackSize;
226     auto *sp = cast<DefinedGlobal>(WasmSym::stackPointer);
227     sp->global->global.InitExpr.Value.Int32 = memoryPtr;
228     log("mem: stack top   = " + Twine(memoryPtr));
229   };
230 
231   if (config->stackFirst) {
232     placeStack();
233   } else {
234     memoryPtr = config->globalBase;
235     log("mem: global base = " + Twine(config->globalBase));
236   }
237 
238   if (WasmSym::globalBase)
239     WasmSym::globalBase->setVirtualAddress(memoryPtr);
240 
241   uint64_t dataStart = memoryPtr;
242 
243   // Arbitrarily set __dso_handle handle to point to the start of the data
244   // segments.
245   if (WasmSym::dsoHandle)
246     WasmSym::dsoHandle->setVirtualAddress(dataStart);
247 
248   out.dylinkSec->memAlign = 0;
249   for (OutputSegment *seg : segments) {
250     out.dylinkSec->memAlign = std::max(out.dylinkSec->memAlign, seg->alignment);
251     memoryPtr = alignTo(memoryPtr, 1ULL << seg->alignment);
252     seg->startVA = memoryPtr;
253     log(formatv("mem: {0,-15} offset={1,-8} size={2,-8} align={3}", seg->name,
254                 memoryPtr, seg->size, seg->alignment));
255     memoryPtr += seg->size;
256 
257     if (WasmSym::tlsSize && seg->name == ".tdata") {
258       auto *tlsSize = cast<DefinedGlobal>(WasmSym::tlsSize);
259       tlsSize->global->global.InitExpr.Value.Int32 = seg->size;
260 
261       auto *tlsAlign = cast<DefinedGlobal>(WasmSym::tlsAlign);
262       tlsAlign->global->global.InitExpr.Value.Int32 = 1U << seg->alignment;
263     }
264   }
265 
266   // Make space for the memory initialization flag
267   if (WasmSym::initMemoryFlag) {
268     memoryPtr = alignTo(memoryPtr, 4);
269     WasmSym::initMemoryFlag->setVirtualAddress(memoryPtr);
270     log(formatv("mem: {0,-15} offset={1,-8} size={2,-8} align={3}",
271                 "__wasm_init_memory_flag", memoryPtr, 4, 4));
272     memoryPtr += 4;
273   }
274 
275   if (WasmSym::dataEnd)
276     WasmSym::dataEnd->setVirtualAddress(memoryPtr);
277 
278   log("mem: static data = " + Twine(memoryPtr - dataStart));
279 
280   if (config->shared) {
281     out.dylinkSec->memSize = memoryPtr;
282     return;
283   }
284 
285   if (!config->stackFirst)
286     placeStack();
287 
288   // Set `__heap_base` to directly follow the end of the stack or global data.
289   // The fact that this comes last means that a malloc/brk implementation
290   // can grow the heap at runtime.
291   log("mem: heap base   = " + Twine(memoryPtr));
292   if (WasmSym::heapBase)
293     WasmSym::heapBase->setVirtualAddress(memoryPtr);
294 
295   if (config->initialMemory != 0) {
296     if (config->initialMemory != alignTo(config->initialMemory, WasmPageSize))
297       error("initial memory must be " + Twine(WasmPageSize) + "-byte aligned");
298     if (memoryPtr > config->initialMemory)
299       error("initial memory too small, " + Twine(memoryPtr) + " bytes needed");
300     if (config->initialMemory > (1ULL << 32))
301       error("initial memory too large, cannot be greater than 4294967296");
302     memoryPtr = config->initialMemory;
303   }
304   out.dylinkSec->memSize = memoryPtr;
305   out.memorySec->numMemoryPages =
306       alignTo(memoryPtr, WasmPageSize) / WasmPageSize;
307   log("mem: total pages = " + Twine(out.memorySec->numMemoryPages));
308 
309   // Check max if explicitly supplied or required by shared memory
310   if (config->maxMemory != 0 || config->sharedMemory) {
311     if (config->maxMemory != alignTo(config->maxMemory, WasmPageSize))
312       error("maximum memory must be " + Twine(WasmPageSize) + "-byte aligned");
313     if (memoryPtr > config->maxMemory)
314       error("maximum memory too small, " + Twine(memoryPtr) + " bytes needed");
315     if (config->maxMemory > (1ULL << 32))
316       error("maximum memory too large, cannot be greater than 4294967296");
317     out.memorySec->maxMemoryPages = config->maxMemory / WasmPageSize;
318     log("mem: max pages   = " + Twine(out.memorySec->maxMemoryPages));
319   }
320 }
321 
322 void Writer::addSection(OutputSection *sec) {
323   if (!sec->isNeeded())
324     return;
325   log("addSection: " + toString(*sec));
326   sec->sectionIndex = outputSections.size();
327   outputSections.push_back(sec);
328 }
329 
330 // If a section name is valid as a C identifier (which is rare because of
331 // the leading '.'), linkers are expected to define __start_<secname> and
332 // __stop_<secname> symbols. They are at beginning and end of the section,
333 // respectively. This is not requested by the ELF standard, but GNU ld and
334 // gold provide the feature, and used by many programs.
335 static void addStartStopSymbols(const OutputSegment *seg) {
336   StringRef name = seg->name;
337   if (!isValidCIdentifier(name))
338     return;
339   LLVM_DEBUG(dbgs() << "addStartStopSymbols: " << name << "\n");
340   uint32_t start = seg->startVA;
341   uint32_t stop = start + seg->size;
342   symtab->addOptionalDataSymbol(saver.save("__start_" + name), start);
343   symtab->addOptionalDataSymbol(saver.save("__stop_" + name), stop);
344 }
345 
346 void Writer::addSections() {
347   addSection(out.dylinkSec);
348   addSection(out.typeSec);
349   addSection(out.importSec);
350   addSection(out.functionSec);
351   addSection(out.tableSec);
352   addSection(out.memorySec);
353   addSection(out.eventSec);
354   addSection(out.globalSec);
355   addSection(out.exportSec);
356   addSection(out.startSec);
357   addSection(out.elemSec);
358   addSection(out.dataCountSec);
359 
360   addSection(make<CodeSection>(out.functionSec->inputFunctions));
361   addSection(make<DataSection>(segments));
362 
363   createCustomSections();
364 
365   addSection(out.linkingSec);
366   if (config->emitRelocs || config->relocatable) {
367     createRelocSections();
368   }
369 
370   addSection(out.nameSec);
371   addSection(out.producersSec);
372   addSection(out.targetFeaturesSec);
373 }
374 
375 void Writer::finalizeSections() {
376   for (OutputSection *s : outputSections) {
377     s->setOffset(fileSize);
378     s->finalizeContents();
379     fileSize += s->getSize();
380   }
381 }
382 
383 void Writer::populateTargetFeatures() {
384   StringMap<std::string> used;
385   StringMap<std::string> required;
386   StringMap<std::string> disallowed;
387   SmallSet<std::string, 8> &allowed = out.targetFeaturesSec->features;
388   bool tlsUsed = false;
389 
390   // Only infer used features if user did not specify features
391   bool inferFeatures = !config->features.hasValue();
392 
393   if (!inferFeatures) {
394     auto &explicitFeatures = config->features.getValue();
395     allowed.insert(explicitFeatures.begin(), explicitFeatures.end());
396     if (!config->checkFeatures)
397       return;
398   }
399 
400   // Find the sets of used, required, and disallowed features
401   for (ObjFile *file : symtab->objectFiles) {
402     StringRef fileName(file->getName());
403     for (auto &feature : file->getWasmObj()->getTargetFeatures()) {
404       switch (feature.Prefix) {
405       case WASM_FEATURE_PREFIX_USED:
406         used.insert({feature.Name, std::string(fileName)});
407         break;
408       case WASM_FEATURE_PREFIX_REQUIRED:
409         used.insert({feature.Name, std::string(fileName)});
410         required.insert({feature.Name, std::string(fileName)});
411         break;
412       case WASM_FEATURE_PREFIX_DISALLOWED:
413         disallowed.insert({feature.Name, std::string(fileName)});
414         break;
415       default:
416         error("Unrecognized feature policy prefix " +
417               std::to_string(feature.Prefix));
418       }
419     }
420 
421     // Find TLS data segments
422     auto isTLS = [](InputSegment *segment) {
423       StringRef name = segment->getName();
424       return segment->live &&
425              (name.startswith(".tdata") || name.startswith(".tbss"));
426     };
427     tlsUsed = tlsUsed ||
428               std::any_of(file->segments.begin(), file->segments.end(), isTLS);
429   }
430 
431   if (inferFeatures)
432     for (const auto &key : used.keys())
433       allowed.insert(std::string(key));
434 
435   if (!config->relocatable && allowed.count("atomics") &&
436       !config->sharedMemory) {
437     if (inferFeatures)
438       error(Twine("'atomics' feature is used by ") + used["atomics"] +
439             ", so --shared-memory must be used");
440     else
441       error("'atomics' feature is used, so --shared-memory must be used");
442   }
443 
444   if (!config->checkFeatures)
445     return;
446 
447   if (config->sharedMemory) {
448     if (disallowed.count("shared-mem"))
449       error("--shared-memory is disallowed by " + disallowed["shared-mem"] +
450             " because it was not compiled with 'atomics' or 'bulk-memory' "
451             "features.");
452 
453     for (auto feature : {"atomics", "bulk-memory"})
454       if (!allowed.count(feature))
455         error(StringRef("'") + feature +
456               "' feature must be used in order to use shared memory");
457   }
458 
459   if (tlsUsed) {
460     for (auto feature : {"atomics", "bulk-memory"})
461       if (!allowed.count(feature))
462         error(StringRef("'") + feature +
463               "' feature must be used in order to use thread-local storage");
464   }
465 
466   // Validate that used features are allowed in output
467   if (!inferFeatures) {
468     for (auto &feature : used.keys()) {
469       if (!allowed.count(std::string(feature)))
470         error(Twine("Target feature '") + feature + "' used by " +
471               used[feature] + " is not allowed.");
472     }
473   }
474 
475   // Validate the required and disallowed constraints for each file
476   for (ObjFile *file : symtab->objectFiles) {
477     StringRef fileName(file->getName());
478     SmallSet<std::string, 8> objectFeatures;
479     for (auto &feature : file->getWasmObj()->getTargetFeatures()) {
480       if (feature.Prefix == WASM_FEATURE_PREFIX_DISALLOWED)
481         continue;
482       objectFeatures.insert(feature.Name);
483       if (disallowed.count(feature.Name))
484         error(Twine("Target feature '") + feature.Name + "' used in " +
485               fileName + " is disallowed by " + disallowed[feature.Name] +
486               ". Use --no-check-features to suppress.");
487     }
488     for (auto &feature : required.keys()) {
489       if (!objectFeatures.count(std::string(feature)))
490         error(Twine("Missing target feature '") + feature + "' in " + fileName +
491               ", required by " + required[feature] +
492               ". Use --no-check-features to suppress.");
493     }
494   }
495 }
496 
497 void Writer::calculateImports() {
498   for (Symbol *sym : symtab->getSymbols()) {
499     if (!sym->isUndefined())
500       continue;
501     if (sym->isWeak() && !config->relocatable)
502       continue;
503     if (!sym->isLive())
504       continue;
505     if (!sym->isUsedInRegularObj)
506       continue;
507     // We don't generate imports for data symbols. They however can be imported
508     // as GOT entries.
509     if (isa<DataSymbol>(sym))
510       continue;
511 
512     LLVM_DEBUG(dbgs() << "import: " << sym->getName() << "\n");
513     out.importSec->addImport(sym);
514   }
515 }
516 
517 void Writer::calculateExports() {
518   if (config->relocatable)
519     return;
520 
521   if (!config->relocatable && !config->importMemory)
522     out.exportSec->exports.push_back(
523         WasmExport{"memory", WASM_EXTERNAL_MEMORY, 0});
524 
525   if (!config->relocatable && config->exportTable)
526     out.exportSec->exports.push_back(
527         WasmExport{functionTableName, WASM_EXTERNAL_TABLE, 0});
528 
529   unsigned globalIndex =
530       out.importSec->getNumImportedGlobals() + out.globalSec->numGlobals();
531 
532   for (Symbol *sym : symtab->getSymbols()) {
533     if (!sym->isExported())
534       continue;
535     if (!sym->isLive())
536       continue;
537 
538     StringRef name = sym->getName();
539     WasmExport export_;
540     if (auto *f = dyn_cast<DefinedFunction>(sym)) {
541       if (Optional<StringRef> exportName = f->function->getExportName()) {
542         name = *exportName;
543       }
544       export_ = {name, WASM_EXTERNAL_FUNCTION, f->getFunctionIndex()};
545     } else if (auto *g = dyn_cast<DefinedGlobal>(sym)) {
546       // TODO(sbc): Remove this check once to mutable global proposal is
547       // implement in all major browsers.
548       // See: https://github.com/WebAssembly/mutable-global
549       if (g->getGlobalType()->Mutable) {
550         // Only __stack_pointer and __tls_base should ever be create as mutable.
551         assert(g == WasmSym::stackPointer || g == WasmSym::tlsBase);
552         continue;
553       }
554       export_ = {name, WASM_EXTERNAL_GLOBAL, g->getGlobalIndex()};
555     } else if (auto *e = dyn_cast<DefinedEvent>(sym)) {
556       export_ = {name, WASM_EXTERNAL_EVENT, e->getEventIndex()};
557     } else {
558       auto *d = cast<DefinedData>(sym);
559       out.globalSec->dataAddressGlobals.push_back(d);
560       export_ = {name, WASM_EXTERNAL_GLOBAL, globalIndex++};
561     }
562 
563     LLVM_DEBUG(dbgs() << "Export: " << name << "\n");
564     out.exportSec->exports.push_back(export_);
565   }
566 }
567 
568 void Writer::populateSymtab() {
569   if (!config->relocatable && !config->emitRelocs)
570     return;
571 
572   for (Symbol *sym : symtab->getSymbols())
573     if (sym->isUsedInRegularObj && sym->isLive())
574       out.linkingSec->addToSymtab(sym);
575 
576   for (ObjFile *file : symtab->objectFiles) {
577     LLVM_DEBUG(dbgs() << "Local symtab entries: " << file->getName() << "\n");
578     for (Symbol *sym : file->getSymbols())
579       if (sym->isLocal() && !isa<SectionSymbol>(sym) && sym->isLive())
580         out.linkingSec->addToSymtab(sym);
581   }
582 }
583 
584 void Writer::calculateTypes() {
585   // The output type section is the union of the following sets:
586   // 1. Any signature used in the TYPE relocation
587   // 2. The signatures of all imported functions
588   // 3. The signatures of all defined functions
589   // 4. The signatures of all imported events
590   // 5. The signatures of all defined events
591 
592   for (ObjFile *file : symtab->objectFiles) {
593     ArrayRef<WasmSignature> types = file->getWasmObj()->types();
594     for (uint32_t i = 0; i < types.size(); i++)
595       if (file->typeIsUsed[i])
596         file->typeMap[i] = out.typeSec->registerType(types[i]);
597   }
598 
599   for (const Symbol *sym : out.importSec->importedSymbols) {
600     if (auto *f = dyn_cast<FunctionSymbol>(sym))
601       out.typeSec->registerType(*f->signature);
602     else if (auto *e = dyn_cast<EventSymbol>(sym))
603       out.typeSec->registerType(*e->signature);
604   }
605 
606   for (const InputFunction *f : out.functionSec->inputFunctions)
607     out.typeSec->registerType(f->signature);
608 
609   for (const InputEvent *e : out.eventSec->inputEvents)
610     out.typeSec->registerType(e->signature);
611 }
612 
613 static void scanRelocations() {
614   for (ObjFile *file : symtab->objectFiles) {
615     LLVM_DEBUG(dbgs() << "scanRelocations: " << file->getName() << "\n");
616     for (InputChunk *chunk : file->functions)
617       scanRelocations(chunk);
618     for (InputChunk *chunk : file->segments)
619       scanRelocations(chunk);
620     for (auto &p : file->customSections)
621       scanRelocations(p);
622   }
623 }
624 
625 void Writer::assignIndexes() {
626   // Seal the import section, since other index spaces such as function and
627   // global are effected by the number of imports.
628   out.importSec->seal();
629 
630   for (InputFunction *func : symtab->syntheticFunctions)
631     out.functionSec->addFunction(func);
632 
633   for (ObjFile *file : symtab->objectFiles) {
634     LLVM_DEBUG(dbgs() << "Functions: " << file->getName() << "\n");
635     for (InputFunction *func : file->functions)
636       out.functionSec->addFunction(func);
637   }
638 
639   for (InputGlobal *global : symtab->syntheticGlobals)
640     out.globalSec->addGlobal(global);
641 
642   for (ObjFile *file : symtab->objectFiles) {
643     LLVM_DEBUG(dbgs() << "Globals: " << file->getName() << "\n");
644     for (InputGlobal *global : file->globals)
645       out.globalSec->addGlobal(global);
646   }
647 
648   for (ObjFile *file : symtab->objectFiles) {
649     LLVM_DEBUG(dbgs() << "Events: " << file->getName() << "\n");
650     for (InputEvent *event : file->events)
651       out.eventSec->addEvent(event);
652   }
653 
654   out.globalSec->assignIndexes();
655 }
656 
657 static StringRef getOutputDataSegmentName(StringRef name) {
658   // With PIC code we currently only support a single data segment since
659   // we only have a single __memory_base to use as our base address.
660   if (config->isPic)
661     return ".data";
662   // We only support one thread-local segment, so we must merge the segments
663   // despite --no-merge-data-segments.
664   // We also need to merge .tbss into .tdata so they share the same offsets.
665   if (name.startswith(".tdata") || name.startswith(".tbss"))
666     return ".tdata";
667   if (!config->mergeDataSegments)
668     return name;
669   if (name.startswith(".text."))
670     return ".text";
671   if (name.startswith(".data."))
672     return ".data";
673   if (name.startswith(".bss."))
674     return ".bss";
675   if (name.startswith(".rodata."))
676     return ".rodata";
677   return name;
678 }
679 
680 void Writer::createOutputSegments() {
681   for (ObjFile *file : symtab->objectFiles) {
682     for (InputSegment *segment : file->segments) {
683       if (!segment->live)
684         continue;
685       StringRef name = getOutputDataSegmentName(segment->getName());
686       OutputSegment *&s = segmentMap[name];
687       if (s == nullptr) {
688         LLVM_DEBUG(dbgs() << "new segment: " << name << "\n");
689         s = make<OutputSegment>(name);
690         if (config->sharedMemory || name == ".tdata")
691           s->initFlags = WASM_SEGMENT_IS_PASSIVE;
692         // Exported memories are guaranteed to be zero-initialized, so no need
693         // to emit data segments for bss sections.
694         // TODO: consider initializing bss sections with memory.fill
695         // instructions when memory is imported and bulk-memory is available.
696         if (!config->importMemory && !config->relocatable &&
697             name.startswith(".bss"))
698           s->isBss = true;
699         segments.push_back(s);
700       }
701       s->addInputSegment(segment);
702       LLVM_DEBUG(dbgs() << "added data: " << name << ": " << s->size << "\n");
703     }
704   }
705 
706   // Sort segments by type, placing .bss last
707   std::stable_sort(segments.begin(), segments.end(),
708                    [](const OutputSegment *a, const OutputSegment *b) {
709                      auto order = [](StringRef name) {
710                        return StringSwitch<int>(name)
711                            .StartsWith(".rodata", 0)
712                            .StartsWith(".data", 1)
713                            .StartsWith(".tdata", 2)
714                            .StartsWith(".bss", 4)
715                            .Default(3);
716                      };
717                      return order(a->name) < order(b->name);
718                    });
719 
720   for (size_t i = 0; i < segments.size(); ++i)
721     segments[i]->index = i;
722 }
723 
724 static void createFunction(DefinedFunction *func, StringRef bodyContent) {
725   std::string functionBody;
726   {
727     raw_string_ostream os(functionBody);
728     writeUleb128(os, bodyContent.size(), "function size");
729     os << bodyContent;
730   }
731   ArrayRef<uint8_t> body = arrayRefFromStringRef(saver.save(functionBody));
732   cast<SyntheticFunction>(func->function)->setBody(body);
733 }
734 
735 bool Writer::needsPassiveInitialization(const OutputSegment *segment) {
736   return segment->initFlags & WASM_SEGMENT_IS_PASSIVE &&
737          segment->name != ".tdata" && !segment->isBss;
738 }
739 
740 bool Writer::hasPassiveInitializedSegments() {
741   return std::find_if(segments.begin(), segments.end(),
742                       [this](const OutputSegment *s) {
743                         return this->needsPassiveInitialization(s);
744                       }) != segments.end();
745 }
746 
747 void Writer::createInitMemoryFunction() {
748   LLVM_DEBUG(dbgs() << "createInitMemoryFunction\n");
749   assert(WasmSym::initMemoryFlag);
750   uint32_t flagAddress = WasmSym::initMemoryFlag->getVirtualAddress();
751   std::string bodyContent;
752   {
753     raw_string_ostream os(bodyContent);
754     writeUleb128(os, 0, "num locals");
755 
756     if (hasPassiveInitializedSegments()) {
757       // Initialize memory in a thread-safe manner. The thread that successfully
758       // increments the flag from 0 to 1 is is responsible for performing the
759       // memory initialization. Other threads go sleep on the flag until the
760       // first thread finishing initializing memory, increments the flag to 2,
761       // and wakes all the other threads. Once the flag has been set to 2,
762       // subsequently started threads will skip the sleep. All threads
763       // unconditionally drop their passive data segments once memory has been
764       // initialized. The generated code is as follows:
765       //
766       // (func $__wasm_init_memory
767       //  (if
768       //   (i32.atomic.rmw.cmpxchg align=2 offset=0
769       //    (i32.const $__init_memory_flag)
770       //    (i32.const 0)
771       //    (i32.const 1)
772       //   )
773       //   (then
774       //    (drop
775       //     (i32.atomic.wait align=2 offset=0
776       //      (i32.const $__init_memory_flag)
777       //      (i32.const 1)
778       //      (i32.const -1)
779       //     )
780       //    )
781       //   )
782       //   (else
783       //    ( ... initialize data segments ... )
784       //    (i32.atomic.store align=2 offset=0
785       //     (i32.const $__init_memory_flag)
786       //     (i32.const 2)
787       //    )
788       //    (drop
789       //     (i32.atomic.notify align=2 offset=0
790       //      (i32.const $__init_memory_flag)
791       //      (i32.const -1u)
792       //     )
793       //    )
794       //   )
795       //  )
796       //  ( ... drop data segments ... )
797       // )
798 
799       // Atomically check whether this is the main thread.
800       writeI32Const(os, flagAddress, "flag address");
801       writeI32Const(os, 0, "expected flag value");
802       writeI32Const(os, 1, "flag value");
803       writeU8(os, WASM_OPCODE_ATOMICS_PREFIX, "atomics prefix");
804       writeUleb128(os, WASM_OPCODE_I32_RMW_CMPXCHG, "i32.atomic.rmw.cmpxchg");
805       writeMemArg(os, 2, 0);
806       writeU8(os, WASM_OPCODE_IF, "IF");
807       writeU8(os, WASM_TYPE_NORESULT, "blocktype");
808 
809       // Did not increment 0, so wait for main thread to initialize memory
810       writeI32Const(os, flagAddress, "flag address");
811       writeI32Const(os, 1, "expected flag value");
812       writeI64Const(os, -1, "timeout");
813       writeU8(os, WASM_OPCODE_ATOMICS_PREFIX, "atomics prefix");
814       writeUleb128(os, WASM_OPCODE_I32_ATOMIC_WAIT, "i32.atomic.wait");
815       writeMemArg(os, 2, 0);
816       writeU8(os, WASM_OPCODE_DROP, "drop");
817 
818       writeU8(os, WASM_OPCODE_ELSE, "ELSE");
819 
820       // Did increment 0, so conditionally initialize passive data segments
821       for (const OutputSegment *s : segments) {
822         if (needsPassiveInitialization(s)) {
823           // destination address
824           writeI32Const(os, s->startVA, "destination address");
825           // source segment offset
826           writeI32Const(os, 0, "segment offset");
827           // memory region size
828           writeI32Const(os, s->size, "memory region size");
829           // memory.init instruction
830           writeU8(os, WASM_OPCODE_MISC_PREFIX, "bulk-memory prefix");
831           writeUleb128(os, WASM_OPCODE_MEMORY_INIT, "memory.init");
832           writeUleb128(os, s->index, "segment index immediate");
833           writeU8(os, 0, "memory index immediate");
834         }
835       }
836 
837       // Set flag to 2 to mark end of initialization
838       writeI32Const(os, flagAddress, "flag address");
839       writeI32Const(os, 2, "flag value");
840       writeU8(os, WASM_OPCODE_ATOMICS_PREFIX, "atomics prefix");
841       writeUleb128(os, WASM_OPCODE_I32_ATOMIC_STORE, "i32.atomic.store");
842       writeMemArg(os, 2, 0);
843 
844       // Notify any waiters that memory initialization is complete
845       writeI32Const(os, flagAddress, "flag address");
846       writeI32Const(os, -1, "number of waiters");
847       writeU8(os, WASM_OPCODE_ATOMICS_PREFIX, "atomics prefix");
848       writeUleb128(os, WASM_OPCODE_ATOMIC_NOTIFY, "atomic.notify");
849       writeMemArg(os, 2, 0);
850       writeU8(os, WASM_OPCODE_DROP, "drop");
851 
852       writeU8(os, WASM_OPCODE_END, "END");
853 
854       // Unconditionally drop passive data segments
855       for (const OutputSegment *s : segments) {
856         if (needsPassiveInitialization(s)) {
857           // data.drop instruction
858           writeU8(os, WASM_OPCODE_MISC_PREFIX, "bulk-memory prefix");
859           writeUleb128(os, WASM_OPCODE_DATA_DROP, "data.drop");
860           writeUleb128(os, s->index, "segment index immediate");
861         }
862       }
863     }
864     writeU8(os, WASM_OPCODE_END, "END");
865   }
866 
867   createFunction(WasmSym::initMemory, bodyContent);
868 }
869 
870 // For -shared (PIC) output, we create create a synthetic function which will
871 // apply any relocations to the data segments on startup.  This function is
872 // called __wasm_apply_relocs and is added at the beginning of __wasm_call_ctors
873 // before any of the constructors run.
874 void Writer::createApplyRelocationsFunction() {
875   LLVM_DEBUG(dbgs() << "createApplyRelocationsFunction\n");
876   // First write the body's contents to a string.
877   std::string bodyContent;
878   {
879     raw_string_ostream os(bodyContent);
880     writeUleb128(os, 0, "num locals");
881     for (const OutputSegment *seg : segments)
882       for (const InputSegment *inSeg : seg->inputSegments)
883         inSeg->generateRelocationCode(os);
884     writeU8(os, WASM_OPCODE_END, "END");
885   }
886 
887   createFunction(WasmSym::applyRelocs, bodyContent);
888 }
889 
890 // Create synthetic "__wasm_call_ctors" function based on ctor functions
891 // in input object.
892 void Writer::createCallCtorsFunction() {
893   if (!WasmSym::callCtors->isLive())
894     return;
895 
896   // First write the body's contents to a string.
897   std::string bodyContent;
898   {
899     raw_string_ostream os(bodyContent);
900     writeUleb128(os, 0, "num locals");
901 
902     if (config->isPic) {
903       writeU8(os, WASM_OPCODE_CALL, "CALL");
904       writeUleb128(os, WasmSym::applyRelocs->getFunctionIndex(),
905                    "function index");
906     }
907 
908     // Call constructors
909     for (const WasmInitEntry &f : initFunctions) {
910       writeU8(os, WASM_OPCODE_CALL, "CALL");
911       writeUleb128(os, f.sym->getFunctionIndex(), "function index");
912     }
913     writeU8(os, WASM_OPCODE_END, "END");
914   }
915 
916   createFunction(WasmSym::callCtors, bodyContent);
917 }
918 
919 void Writer::createInitTLSFunction() {
920   if (!WasmSym::initTLS->isLive())
921     return;
922 
923   std::string bodyContent;
924   {
925     raw_string_ostream os(bodyContent);
926 
927     OutputSegment *tlsSeg = nullptr;
928     for (auto *seg : segments) {
929       if (seg->name == ".tdata") {
930         tlsSeg = seg;
931         break;
932       }
933     }
934 
935     writeUleb128(os, 0, "num locals");
936     if (tlsSeg) {
937       writeU8(os, WASM_OPCODE_LOCAL_GET, "local.get");
938       writeUleb128(os, 0, "local index");
939 
940       writeU8(os, WASM_OPCODE_GLOBAL_SET, "global.set");
941       writeUleb128(os, WasmSym::tlsBase->getGlobalIndex(), "global index");
942 
943       writeU8(os, WASM_OPCODE_LOCAL_GET, "local.get");
944       writeUleb128(os, 0, "local index");
945 
946       writeI32Const(os, 0, "segment offset");
947 
948       writeI32Const(os, tlsSeg->size, "memory region size");
949 
950       writeU8(os, WASM_OPCODE_MISC_PREFIX, "bulk-memory prefix");
951       writeUleb128(os, WASM_OPCODE_MEMORY_INIT, "MEMORY.INIT");
952       writeUleb128(os, tlsSeg->index, "segment index immediate");
953       writeU8(os, 0, "memory index immediate");
954     }
955     writeU8(os, WASM_OPCODE_END, "end function");
956   }
957 
958   createFunction(WasmSym::initTLS, bodyContent);
959 }
960 
961 // Populate InitFunctions vector with init functions from all input objects.
962 // This is then used either when creating the output linking section or to
963 // synthesize the "__wasm_call_ctors" function.
964 void Writer::calculateInitFunctions() {
965   if (!config->relocatable && !WasmSym::callCtors->isLive())
966     return;
967 
968   for (ObjFile *file : symtab->objectFiles) {
969     const WasmLinkingData &l = file->getWasmObj()->linkingData();
970     for (const WasmInitFunc &f : l.InitFunctions) {
971       FunctionSymbol *sym = file->getFunctionSymbol(f.Symbol);
972       // comdat exclusions can cause init functions be discarded.
973       if (sym->isDiscarded())
974         continue;
975       assert(sym->isLive());
976       if (*sym->signature != WasmSignature{{}, {}})
977         error("invalid signature for init func: " + toString(*sym));
978       LLVM_DEBUG(dbgs() << "initFunctions: " << toString(*sym) << "\n");
979       initFunctions.emplace_back(WasmInitEntry{sym, f.Priority});
980     }
981   }
982 
983   // Sort in order of priority (lowest first) so that they are called
984   // in the correct order.
985   llvm::stable_sort(initFunctions,
986                     [](const WasmInitEntry &l, const WasmInitEntry &r) {
987                       return l.priority < r.priority;
988                     });
989 }
990 
991 void Writer::createSyntheticSections() {
992   out.dylinkSec = make<DylinkSection>();
993   out.typeSec = make<TypeSection>();
994   out.importSec = make<ImportSection>();
995   out.functionSec = make<FunctionSection>();
996   out.tableSec = make<TableSection>();
997   out.memorySec = make<MemorySection>();
998   out.eventSec = make<EventSection>();
999   out.globalSec = make<GlobalSection>();
1000   out.exportSec = make<ExportSection>();
1001   out.startSec = make<StartSection>(hasPassiveInitializedSegments());
1002   out.elemSec = make<ElemSection>();
1003   out.dataCountSec = make<DataCountSection>(segments);
1004   out.linkingSec = make<LinkingSection>(initFunctions, segments);
1005   out.nameSec = make<NameSection>();
1006   out.producersSec = make<ProducersSection>();
1007   out.targetFeaturesSec = make<TargetFeaturesSection>();
1008 }
1009 
1010 void Writer::run() {
1011   if (config->relocatable || config->isPic)
1012     config->globalBase = 0;
1013 
1014   // For PIC code the table base is assigned dynamically by the loader.
1015   // For non-PIC, we start at 1 so that accessing table index 0 always traps.
1016   if (!config->isPic) {
1017     config->tableBase = 1;
1018     if (WasmSym::definedTableBase)
1019       WasmSym::definedTableBase->setVirtualAddress(config->tableBase);
1020   }
1021 
1022   log("-- createOutputSegments");
1023   createOutputSegments();
1024   log("-- createSyntheticSections");
1025   createSyntheticSections();
1026   log("-- populateProducers");
1027   populateProducers();
1028   log("-- populateTargetFeatures");
1029   populateTargetFeatures();
1030   log("-- calculateImports");
1031   calculateImports();
1032   log("-- layoutMemory");
1033   layoutMemory();
1034 
1035   if (!config->relocatable) {
1036     // Create linker synthesized __start_SECNAME/__stop_SECNAME symbols
1037     // This has to be done after memory layout is performed.
1038     for (const OutputSegment *seg : segments)
1039       addStartStopSymbols(seg);
1040   }
1041 
1042   log("-- scanRelocations");
1043   scanRelocations();
1044   log("-- assignIndexes");
1045   assignIndexes();
1046   log("-- calculateInitFunctions");
1047   calculateInitFunctions();
1048 
1049   if (!config->relocatable) {
1050     // Create linker synthesized functions
1051     if (config->sharedMemory)
1052       createInitMemoryFunction();
1053     if (config->isPic)
1054       createApplyRelocationsFunction();
1055     createCallCtorsFunction();
1056   }
1057 
1058   if (!config->relocatable && config->sharedMemory && !config->shared)
1059     createInitTLSFunction();
1060 
1061   if (errorCount())
1062     return;
1063 
1064   log("-- calculateTypes");
1065   calculateTypes();
1066   log("-- calculateExports");
1067   calculateExports();
1068   log("-- calculateCustomSections");
1069   calculateCustomSections();
1070   log("-- populateSymtab");
1071   populateSymtab();
1072   log("-- addSections");
1073   addSections();
1074 
1075   if (errorHandler().verbose) {
1076     log("Defined Functions: " + Twine(out.functionSec->inputFunctions.size()));
1077     log("Defined Globals  : " + Twine(out.globalSec->numGlobals()));
1078     log("Defined Events   : " + Twine(out.eventSec->inputEvents.size()));
1079     log("Function Imports : " +
1080         Twine(out.importSec->getNumImportedFunctions()));
1081     log("Global Imports   : " + Twine(out.importSec->getNumImportedGlobals()));
1082     log("Event Imports    : " + Twine(out.importSec->getNumImportedEvents()));
1083     for (ObjFile *file : symtab->objectFiles)
1084       file->dumpInfo();
1085   }
1086 
1087   createHeader();
1088   log("-- finalizeSections");
1089   finalizeSections();
1090 
1091   log("-- openFile");
1092   openFile();
1093   if (errorCount())
1094     return;
1095 
1096   writeHeader();
1097 
1098   log("-- writeSections");
1099   writeSections();
1100   if (errorCount())
1101     return;
1102 
1103   if (Error e = buffer->commit())
1104     fatal("failed to write the output file: " + toString(std::move(e)));
1105 }
1106 
1107 // Open a result file.
1108 void Writer::openFile() {
1109   log("writing: " + config->outputFile);
1110 
1111   Expected<std::unique_ptr<FileOutputBuffer>> bufferOrErr =
1112       FileOutputBuffer::create(config->outputFile, fileSize,
1113                                FileOutputBuffer::F_executable);
1114 
1115   if (!bufferOrErr)
1116     error("failed to open " + config->outputFile + ": " +
1117           toString(bufferOrErr.takeError()));
1118   else
1119     buffer = std::move(*bufferOrErr);
1120 }
1121 
1122 void Writer::createHeader() {
1123   raw_string_ostream os(header);
1124   writeBytes(os, WasmMagic, sizeof(WasmMagic), "wasm magic");
1125   writeU32(os, WasmVersion, "wasm version");
1126   os.flush();
1127   fileSize += header.size();
1128 }
1129 
1130 void writeResult() { Writer().run(); }
1131 
1132 } // namespace wasm
1133 } // namespace lld
1134