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