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