xref: /llvm-project-15.0.7/lld/wasm/Writer.cpp (revision e5a82b45)
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 void Writer::calculateImports() {
543   for (Symbol *sym : symtab->getSymbols()) {
544     if (!sym->isUndefined())
545       continue;
546     if (sym->isWeak() && !config->relocatable)
547       continue;
548     if (!sym->isLive())
549       continue;
550     if (!sym->isUsedInRegularObj)
551       continue;
552     // We don't generate imports for data symbols. They however can be imported
553     // as GOT entries.
554     if (isa<DataSymbol>(sym))
555       continue;
556 
557     LLVM_DEBUG(dbgs() << "import: " << sym->getName() << "\n");
558     out.importSec->addImport(sym);
559   }
560 }
561 
562 void Writer::calculateExports() {
563   if (config->relocatable)
564     return;
565 
566   if (!config->relocatable && !config->importMemory)
567     out.exportSec->exports.push_back(
568         WasmExport{"memory", WASM_EXTERNAL_MEMORY, 0});
569 
570   if (!config->relocatable && config->exportTable)
571     out.exportSec->exports.push_back(
572         WasmExport{functionTableName, WASM_EXTERNAL_TABLE, 0});
573 
574   unsigned globalIndex =
575       out.importSec->getNumImportedGlobals() + out.globalSec->numGlobals();
576 
577   for (Symbol *sym : symtab->getSymbols()) {
578     if (!sym->isExported())
579       continue;
580     if (!sym->isLive())
581       continue;
582 
583     StringRef name = sym->getName();
584     WasmExport export_;
585     if (auto *f = dyn_cast<DefinedFunction>(sym)) {
586       if (Optional<StringRef> exportName = f->function->getExportName()) {
587         name = *exportName;
588       }
589       export_ = {name, WASM_EXTERNAL_FUNCTION, f->getFunctionIndex()};
590     } else if (auto *g = dyn_cast<DefinedGlobal>(sym)) {
591       if (g->getGlobalType()->Mutable && !g->getFile() && !g->forceExport) {
592         // Avoid exporting mutable globals are linker synthesized (e.g.
593         // __stack_pointer or __tls_base) unless they are explicitly exported
594         // from the command line.
595         // Without this check `--export-all` would cause any program using the
596         // stack pointer to export a mutable global even if none of the input
597         // files were built with the `mutable-globals` feature.
598         continue;
599       }
600       export_ = {name, WASM_EXTERNAL_GLOBAL, g->getGlobalIndex()};
601     } else if (auto *e = dyn_cast<DefinedEvent>(sym)) {
602       export_ = {name, WASM_EXTERNAL_EVENT, e->getEventIndex()};
603     } else {
604       auto *d = cast<DefinedData>(sym);
605       out.globalSec->dataAddressGlobals.push_back(d);
606       export_ = {name, WASM_EXTERNAL_GLOBAL, globalIndex++};
607     }
608 
609     LLVM_DEBUG(dbgs() << "Export: " << name << "\n");
610     out.exportSec->exports.push_back(export_);
611     out.exportSec->exportedSymbols.push_back(sym);
612   }
613 }
614 
615 void Writer::populateSymtab() {
616   if (!config->relocatable && !config->emitRelocs)
617     return;
618 
619   for (Symbol *sym : symtab->getSymbols())
620     if (sym->isUsedInRegularObj && sym->isLive())
621       out.linkingSec->addToSymtab(sym);
622 
623   for (ObjFile *file : symtab->objectFiles) {
624     LLVM_DEBUG(dbgs() << "Local symtab entries: " << file->getName() << "\n");
625     for (Symbol *sym : file->getSymbols())
626       if (sym->isLocal() && !isa<SectionSymbol>(sym) && sym->isLive())
627         out.linkingSec->addToSymtab(sym);
628   }
629 }
630 
631 void Writer::calculateTypes() {
632   // The output type section is the union of the following sets:
633   // 1. Any signature used in the TYPE relocation
634   // 2. The signatures of all imported functions
635   // 3. The signatures of all defined functions
636   // 4. The signatures of all imported events
637   // 5. The signatures of all defined events
638 
639   for (ObjFile *file : symtab->objectFiles) {
640     ArrayRef<WasmSignature> types = file->getWasmObj()->types();
641     for (uint32_t i = 0; i < types.size(); i++)
642       if (file->typeIsUsed[i])
643         file->typeMap[i] = out.typeSec->registerType(types[i]);
644   }
645 
646   for (const Symbol *sym : out.importSec->importedSymbols) {
647     if (auto *f = dyn_cast<FunctionSymbol>(sym))
648       out.typeSec->registerType(*f->signature);
649     else if (auto *e = dyn_cast<EventSymbol>(sym))
650       out.typeSec->registerType(*e->signature);
651   }
652 
653   for (const InputFunction *f : out.functionSec->inputFunctions)
654     out.typeSec->registerType(f->signature);
655 
656   for (const InputEvent *e : out.eventSec->inputEvents)
657     out.typeSec->registerType(e->signature);
658 }
659 
660 // In a command-style link, create a wrapper for each exported symbol
661 // which calls the constructors and destructors.
662 void Writer::createCommandExportWrappers() {
663   // This logic doesn't currently support Emscripten-style PIC mode.
664   assert(!config->isPic);
665 
666   // If there are no ctors and there's no libc `__wasm_call_dtors` to
667   // call, don't wrap the exports.
668   if (initFunctions.empty() && WasmSym::callDtors == NULL)
669     return;
670 
671   std::vector<DefinedFunction *> toWrap;
672 
673   for (Symbol *sym : symtab->getSymbols())
674     if (sym->isExported())
675       if (auto *f = dyn_cast<DefinedFunction>(sym))
676         toWrap.push_back(f);
677 
678   for (auto *f : toWrap) {
679     auto funcNameStr = (f->getName() + ".command_export").str();
680     commandExportWrapperNames.push_back(funcNameStr);
681     const std::string &funcName = commandExportWrapperNames.back();
682 
683     auto func = make<SyntheticFunction>(*f->getSignature(), funcName);
684     if (f->function->getExportName().hasValue())
685       func->setExportName(f->function->getExportName()->str());
686     else
687       func->setExportName(f->getName().str());
688 
689     DefinedFunction *def =
690         symtab->addSyntheticFunction(funcName, f->flags, func);
691     def->markLive();
692 
693     def->flags |= WASM_SYMBOL_EXPORTED;
694     def->flags &= ~WASM_SYMBOL_VISIBILITY_HIDDEN;
695     def->forceExport = f->forceExport;
696 
697     f->flags |= WASM_SYMBOL_VISIBILITY_HIDDEN;
698     f->flags &= ~WASM_SYMBOL_EXPORTED;
699     f->forceExport = false;
700 
701     out.functionSec->addFunction(func);
702 
703     createCommandExportWrapper(f->getFunctionIndex(), def);
704   }
705 }
706 
707 static void scanRelocations() {
708   for (ObjFile *file : symtab->objectFiles) {
709     LLVM_DEBUG(dbgs() << "scanRelocations: " << file->getName() << "\n");
710     for (InputChunk *chunk : file->functions)
711       scanRelocations(chunk);
712     for (InputChunk *chunk : file->segments)
713       scanRelocations(chunk);
714     for (auto &p : file->customSections)
715       scanRelocations(p);
716   }
717 }
718 
719 void Writer::assignIndexes() {
720   // Seal the import section, since other index spaces such as function and
721   // global are effected by the number of imports.
722   out.importSec->seal();
723 
724   for (InputFunction *func : symtab->syntheticFunctions)
725     out.functionSec->addFunction(func);
726 
727   for (ObjFile *file : symtab->objectFiles) {
728     LLVM_DEBUG(dbgs() << "Functions: " << file->getName() << "\n");
729     for (InputFunction *func : file->functions)
730       out.functionSec->addFunction(func);
731   }
732 
733   for (InputGlobal *global : symtab->syntheticGlobals)
734     out.globalSec->addGlobal(global);
735 
736   for (ObjFile *file : symtab->objectFiles) {
737     LLVM_DEBUG(dbgs() << "Globals: " << file->getName() << "\n");
738     for (InputGlobal *global : file->globals)
739       out.globalSec->addGlobal(global);
740   }
741 
742   for (ObjFile *file : symtab->objectFiles) {
743     LLVM_DEBUG(dbgs() << "Events: " << file->getName() << "\n");
744     for (InputEvent *event : file->events)
745       out.eventSec->addEvent(event);
746   }
747 
748   out.globalSec->assignIndexes();
749 }
750 
751 static StringRef getOutputDataSegmentName(StringRef name) {
752   // We only support one thread-local segment, so we must merge the segments
753   // despite --no-merge-data-segments.
754   // We also need to merge .tbss into .tdata so they share the same offsets.
755   if (name.startswith(".tdata") || name.startswith(".tbss"))
756     return ".tdata";
757   // With PIC code we currently only support a single data segment since
758   // we only have a single __memory_base to use as our base address.
759   if (config->isPic)
760     return ".data";
761   if (!config->mergeDataSegments)
762     return name;
763   if (name.startswith(".text."))
764     return ".text";
765   if (name.startswith(".data."))
766     return ".data";
767   if (name.startswith(".bss."))
768     return ".bss";
769   if (name.startswith(".rodata."))
770     return ".rodata";
771   return name;
772 }
773 
774 void Writer::createOutputSegments() {
775   for (ObjFile *file : symtab->objectFiles) {
776     for (InputSegment *segment : file->segments) {
777       if (!segment->live)
778         continue;
779       StringRef name = getOutputDataSegmentName(segment->getName());
780       OutputSegment *&s = segmentMap[name];
781       if (s == nullptr) {
782         LLVM_DEBUG(dbgs() << "new segment: " << name << "\n");
783         s = make<OutputSegment>(name);
784         if (config->sharedMemory)
785           s->initFlags = WASM_SEGMENT_IS_PASSIVE;
786         // Exported memories are guaranteed to be zero-initialized, so no need
787         // to emit data segments for bss sections.
788         // TODO: consider initializing bss sections with memory.fill
789         // instructions when memory is imported and bulk-memory is available.
790         if (!config->importMemory && !config->relocatable &&
791             name.startswith(".bss"))
792           s->isBss = true;
793         segments.push_back(s);
794       }
795       s->addInputSegment(segment);
796       LLVM_DEBUG(dbgs() << "added data: " << name << ": " << s->size << "\n");
797     }
798   }
799 
800   // Sort segments by type, placing .bss last
801   std::stable_sort(segments.begin(), segments.end(),
802                    [](const OutputSegment *a, const OutputSegment *b) {
803                      auto order = [](StringRef name) {
804                        return StringSwitch<int>(name)
805                            .StartsWith(".rodata", 0)
806                            .StartsWith(".data", 1)
807                            .StartsWith(".tdata", 2)
808                            .StartsWith(".bss", 4)
809                            .Default(3);
810                      };
811                      return order(a->name) < order(b->name);
812                    });
813 
814   for (size_t i = 0; i < segments.size(); ++i)
815     segments[i]->index = i;
816 }
817 
818 static void createFunction(DefinedFunction *func, StringRef bodyContent) {
819   std::string functionBody;
820   {
821     raw_string_ostream os(functionBody);
822     writeUleb128(os, bodyContent.size(), "function size");
823     os << bodyContent;
824   }
825   ArrayRef<uint8_t> body = arrayRefFromStringRef(saver.save(functionBody));
826   cast<SyntheticFunction>(func->function)->setBody(body);
827 }
828 
829 bool Writer::needsPassiveInitialization(const OutputSegment *segment) {
830   return segment->initFlags & WASM_SEGMENT_IS_PASSIVE &&
831          segment->name != ".tdata" && !segment->isBss;
832 }
833 
834 bool Writer::hasPassiveInitializedSegments() {
835   return std::find_if(segments.begin(), segments.end(),
836                       [this](const OutputSegment *s) {
837                         return this->needsPassiveInitialization(s);
838                       }) != segments.end();
839 }
840 
841 void Writer::createInitMemoryFunction() {
842   LLVM_DEBUG(dbgs() << "createInitMemoryFunction\n");
843   assert(WasmSym::initMemoryFlag);
844   uint32_t flagAddress = WasmSym::initMemoryFlag->getVirtualAddress();
845   std::string bodyContent;
846   {
847     raw_string_ostream os(bodyContent);
848     writeUleb128(os, 0, "num locals");
849 
850     if (hasPassiveInitializedSegments()) {
851       // Initialize memory in a thread-safe manner. The thread that successfully
852       // increments the flag from 0 to 1 is is responsible for performing the
853       // memory initialization. Other threads go sleep on the flag until the
854       // first thread finishing initializing memory, increments the flag to 2,
855       // and wakes all the other threads. Once the flag has been set to 2,
856       // subsequently started threads will skip the sleep. All threads
857       // unconditionally drop their passive data segments once memory has been
858       // initialized. The generated code is as follows:
859       //
860       // (func $__wasm_init_memory
861       //  (if
862       //   (i32.atomic.rmw.cmpxchg align=2 offset=0
863       //    (i32.const $__init_memory_flag)
864       //    (i32.const 0)
865       //    (i32.const 1)
866       //   )
867       //   (then
868       //    (drop
869       //     (i32.atomic.wait align=2 offset=0
870       //      (i32.const $__init_memory_flag)
871       //      (i32.const 1)
872       //      (i32.const -1)
873       //     )
874       //    )
875       //   )
876       //   (else
877       //    ( ... initialize data segments ... )
878       //    (i32.atomic.store align=2 offset=0
879       //     (i32.const $__init_memory_flag)
880       //     (i32.const 2)
881       //    )
882       //    (drop
883       //     (i32.atomic.notify align=2 offset=0
884       //      (i32.const $__init_memory_flag)
885       //      (i32.const -1u)
886       //     )
887       //    )
888       //   )
889       //  )
890       //  ( ... drop data segments ... )
891       // )
892 
893       // Atomically check whether this is the main thread.
894       writeI32Const(os, flagAddress, "flag address");
895       writeI32Const(os, 0, "expected flag value");
896       writeI32Const(os, 1, "flag value");
897       writeU8(os, WASM_OPCODE_ATOMICS_PREFIX, "atomics prefix");
898       writeUleb128(os, WASM_OPCODE_I32_RMW_CMPXCHG, "i32.atomic.rmw.cmpxchg");
899       writeMemArg(os, 2, 0);
900       writeU8(os, WASM_OPCODE_IF, "IF");
901       writeU8(os, WASM_TYPE_NORESULT, "blocktype");
902 
903       // Did not increment 0, so wait for main thread to initialize memory
904       writeI32Const(os, flagAddress, "flag address");
905       writeI32Const(os, 1, "expected flag value");
906       writeI64Const(os, -1, "timeout");
907       writeU8(os, WASM_OPCODE_ATOMICS_PREFIX, "atomics prefix");
908       writeUleb128(os, WASM_OPCODE_I32_ATOMIC_WAIT, "i32.atomic.wait");
909       writeMemArg(os, 2, 0);
910       writeU8(os, WASM_OPCODE_DROP, "drop");
911 
912       writeU8(os, WASM_OPCODE_ELSE, "ELSE");
913 
914       // Did increment 0, so conditionally initialize passive data segments
915       for (const OutputSegment *s : segments) {
916         if (needsPassiveInitialization(s)) {
917           // destination address
918           if (config->is64.getValueOr(false)) {
919             writeI64Const(os, s->startVA, "destination address");
920           } else {
921             writeI32Const(os, static_cast<int32_t>(s->startVA),
922                           "destination address");
923           }
924           // source segment offset
925           writeI32Const(os, 0, "segment offset");
926           // memory region size
927           writeI32Const(os, s->size, "memory region size");
928           // memory.init instruction
929           writeU8(os, WASM_OPCODE_MISC_PREFIX, "bulk-memory prefix");
930           writeUleb128(os, WASM_OPCODE_MEMORY_INIT, "memory.init");
931           writeUleb128(os, s->index, "segment index immediate");
932           writeU8(os, 0, "memory index immediate");
933         }
934       }
935 
936       // Set flag to 2 to mark end of initialization
937       writeI32Const(os, flagAddress, "flag address");
938       writeI32Const(os, 2, "flag value");
939       writeU8(os, WASM_OPCODE_ATOMICS_PREFIX, "atomics prefix");
940       writeUleb128(os, WASM_OPCODE_I32_ATOMIC_STORE, "i32.atomic.store");
941       writeMemArg(os, 2, 0);
942 
943       // Notify any waiters that memory initialization is complete
944       writeI32Const(os, flagAddress, "flag address");
945       writeI32Const(os, -1, "number of waiters");
946       writeU8(os, WASM_OPCODE_ATOMICS_PREFIX, "atomics prefix");
947       writeUleb128(os, WASM_OPCODE_ATOMIC_NOTIFY, "atomic.notify");
948       writeMemArg(os, 2, 0);
949       writeU8(os, WASM_OPCODE_DROP, "drop");
950 
951       writeU8(os, WASM_OPCODE_END, "END");
952 
953       // Unconditionally drop passive data segments
954       for (const OutputSegment *s : segments) {
955         if (needsPassiveInitialization(s)) {
956           // data.drop instruction
957           writeU8(os, WASM_OPCODE_MISC_PREFIX, "bulk-memory prefix");
958           writeUleb128(os, WASM_OPCODE_DATA_DROP, "data.drop");
959           writeUleb128(os, s->index, "segment index immediate");
960         }
961       }
962     }
963     writeU8(os, WASM_OPCODE_END, "END");
964   }
965 
966   createFunction(WasmSym::initMemory, bodyContent);
967 }
968 
969 // For -shared (PIC) output, we create create a synthetic function which will
970 // apply any relocations to the data segments on startup.  This function is
971 // called __wasm_apply_relocs and is added at the beginning of __wasm_call_ctors
972 // before any of the constructors run.
973 void Writer::createApplyRelocationsFunction() {
974   LLVM_DEBUG(dbgs() << "createApplyRelocationsFunction\n");
975   // First write the body's contents to a string.
976   std::string bodyContent;
977   {
978     raw_string_ostream os(bodyContent);
979     writeUleb128(os, 0, "num locals");
980 
981     // First apply relocations to any internalized GOT entries.  These
982     // are the result of relaxation when building with -Bsymbolic.
983     out.globalSec->generateRelocationCode(os);
984 
985     // Next apply any realocation to the data section by reading GOT entry
986     // globals.
987     for (const OutputSegment *seg : segments)
988       for (const InputSegment *inSeg : seg->inputSegments)
989         inSeg->generateRelocationCode(os);
990 
991     writeU8(os, WASM_OPCODE_END, "END");
992   }
993 
994   createFunction(WasmSym::applyRelocs, bodyContent);
995 }
996 
997 // Create synthetic "__wasm_call_ctors" function based on ctor functions
998 // in input object.
999 void Writer::createCallCtorsFunction() {
1000   // If __wasm_call_ctors isn't referenced, there aren't any ctors, and we
1001   // aren't calling `__wasm_apply_relocs` for Emscripten-style PIC, don't
1002   // define the `__wasm_call_ctors` function.
1003   if (!WasmSym::callCtors->isLive() && initFunctions.empty() && !config->isPic)
1004     return;
1005 
1006   // First write the body's contents to a string.
1007   std::string bodyContent;
1008   {
1009     raw_string_ostream os(bodyContent);
1010     writeUleb128(os, 0, "num locals");
1011 
1012     if (config->isPic) {
1013       writeU8(os, WASM_OPCODE_CALL, "CALL");
1014       writeUleb128(os, WasmSym::applyRelocs->getFunctionIndex(),
1015                    "function index");
1016     }
1017 
1018     // Call constructors
1019     for (const WasmInitEntry &f : initFunctions) {
1020       writeU8(os, WASM_OPCODE_CALL, "CALL");
1021       writeUleb128(os, f.sym->getFunctionIndex(), "function index");
1022       for (size_t i = 0; i < f.sym->signature->Returns.size(); i++) {
1023         writeU8(os, WASM_OPCODE_DROP, "DROP");
1024       }
1025     }
1026     writeU8(os, WASM_OPCODE_END, "END");
1027   }
1028 
1029   createFunction(WasmSym::callCtors, bodyContent);
1030 }
1031 
1032 // Create a wrapper around a function export which calls the
1033 // static constructors and destructors.
1034 void Writer::createCommandExportWrapper(uint32_t functionIndex,
1035                                         DefinedFunction *f) {
1036   // First write the body's contents to a string.
1037   std::string bodyContent;
1038   {
1039     raw_string_ostream os(bodyContent);
1040     writeUleb128(os, 0, "num locals");
1041 
1042     // If we have any ctors, or we're calling `__wasm_apply_relocs` for
1043     // Emscripten-style PIC, call `__wasm_call_ctors` which performs those
1044     // calls.
1045     if (!initFunctions.empty() || config->isPic) {
1046       writeU8(os, WASM_OPCODE_CALL, "CALL");
1047       writeUleb128(os, WasmSym::callCtors->getFunctionIndex(),
1048                    "function index");
1049     }
1050 
1051     // Call the user's code, leaving any return values on the operand stack.
1052     for (size_t i = 0; i < f->signature->Params.size(); ++i) {
1053       writeU8(os, WASM_OPCODE_LOCAL_GET, "local.get");
1054       writeUleb128(os, i, "local index");
1055     }
1056     writeU8(os, WASM_OPCODE_CALL, "CALL");
1057     writeUleb128(os, functionIndex, "function index");
1058 
1059     // Call the function that calls the destructors.
1060     if (DefinedFunction *callDtors = WasmSym::callDtors) {
1061       writeU8(os, WASM_OPCODE_CALL, "CALL");
1062       writeUleb128(os, callDtors->getFunctionIndex(), "function index");
1063     }
1064 
1065     // End the function, returning the return values from the user's code.
1066     writeU8(os, WASM_OPCODE_END, "END");
1067   }
1068 
1069   createFunction(f, bodyContent);
1070 }
1071 
1072 void Writer::createInitTLSFunction() {
1073   if (!WasmSym::initTLS->isLive())
1074     return;
1075 
1076   std::string bodyContent;
1077   {
1078     raw_string_ostream os(bodyContent);
1079 
1080     OutputSegment *tlsSeg = nullptr;
1081     for (auto *seg : segments) {
1082       if (seg->name == ".tdata") {
1083         tlsSeg = seg;
1084         break;
1085       }
1086     }
1087 
1088     writeUleb128(os, 0, "num locals");
1089     if (tlsSeg) {
1090       writeU8(os, WASM_OPCODE_LOCAL_GET, "local.get");
1091       writeUleb128(os, 0, "local index");
1092 
1093       writeU8(os, WASM_OPCODE_GLOBAL_SET, "global.set");
1094       writeUleb128(os, WasmSym::tlsBase->getGlobalIndex(), "global index");
1095 
1096       // FIXME(wvo): this local needs to be I64 in wasm64, or we need an extend op.
1097       writeU8(os, WASM_OPCODE_LOCAL_GET, "local.get");
1098       writeUleb128(os, 0, "local index");
1099 
1100       writeI32Const(os, 0, "segment offset");
1101 
1102       writeI32Const(os, tlsSeg->size, "memory region size");
1103 
1104       writeU8(os, WASM_OPCODE_MISC_PREFIX, "bulk-memory prefix");
1105       writeUleb128(os, WASM_OPCODE_MEMORY_INIT, "MEMORY.INIT");
1106       writeUleb128(os, tlsSeg->index, "segment index immediate");
1107       writeU8(os, 0, "memory index immediate");
1108     }
1109     writeU8(os, WASM_OPCODE_END, "end function");
1110   }
1111 
1112   createFunction(WasmSym::initTLS, bodyContent);
1113 }
1114 
1115 // Populate InitFunctions vector with init functions from all input objects.
1116 // This is then used either when creating the output linking section or to
1117 // synthesize the "__wasm_call_ctors" function.
1118 void Writer::calculateInitFunctions() {
1119   if (!config->relocatable && !WasmSym::callCtors->isLive())
1120     return;
1121 
1122   for (ObjFile *file : symtab->objectFiles) {
1123     const WasmLinkingData &l = file->getWasmObj()->linkingData();
1124     for (const WasmInitFunc &f : l.InitFunctions) {
1125       FunctionSymbol *sym = file->getFunctionSymbol(f.Symbol);
1126       // comdat exclusions can cause init functions be discarded.
1127       if (sym->isDiscarded() || !sym->isLive())
1128         continue;
1129       if (sym->signature->Params.size() != 0)
1130         error("constructor functions cannot take arguments: " + toString(*sym));
1131       LLVM_DEBUG(dbgs() << "initFunctions: " << toString(*sym) << "\n");
1132       initFunctions.emplace_back(WasmInitEntry{sym, f.Priority});
1133     }
1134   }
1135 
1136   // Sort in order of priority (lowest first) so that they are called
1137   // in the correct order.
1138   llvm::stable_sort(initFunctions,
1139                     [](const WasmInitEntry &l, const WasmInitEntry &r) {
1140                       return l.priority < r.priority;
1141                     });
1142 }
1143 
1144 void Writer::createSyntheticSections() {
1145   out.dylinkSec = make<DylinkSection>();
1146   out.typeSec = make<TypeSection>();
1147   out.importSec = make<ImportSection>();
1148   out.functionSec = make<FunctionSection>();
1149   out.tableSec = make<TableSection>();
1150   out.memorySec = make<MemorySection>();
1151   out.eventSec = make<EventSection>();
1152   out.globalSec = make<GlobalSection>();
1153   out.exportSec = make<ExportSection>();
1154   out.startSec = make<StartSection>(hasPassiveInitializedSegments());
1155   out.elemSec = make<ElemSection>();
1156   out.dataCountSec = make<DataCountSection>(segments);
1157   out.linkingSec = make<LinkingSection>(initFunctions, segments);
1158   out.nameSec = make<NameSection>();
1159   out.producersSec = make<ProducersSection>();
1160   out.targetFeaturesSec = make<TargetFeaturesSection>();
1161 }
1162 
1163 void Writer::run() {
1164   if (config->relocatable || config->isPic)
1165     config->globalBase = 0;
1166 
1167   // For PIC code the table base is assigned dynamically by the loader.
1168   // For non-PIC, we start at 1 so that accessing table index 0 always traps.
1169   if (!config->isPic) {
1170     config->tableBase = 1;
1171     if (WasmSym::definedTableBase)
1172       WasmSym::definedTableBase->setVirtualAddress(config->tableBase);
1173   }
1174 
1175   log("-- createOutputSegments");
1176   createOutputSegments();
1177   log("-- createSyntheticSections");
1178   createSyntheticSections();
1179   log("-- populateProducers");
1180   populateProducers();
1181   log("-- calculateImports");
1182   calculateImports();
1183   log("-- layoutMemory");
1184   layoutMemory();
1185 
1186   if (!config->relocatable) {
1187     // Create linker synthesized __start_SECNAME/__stop_SECNAME symbols
1188     // This has to be done after memory layout is performed.
1189     for (const OutputSegment *seg : segments)
1190       addStartStopSymbols(seg);
1191   }
1192 
1193   log("-- scanRelocations");
1194   scanRelocations();
1195   log("-- assignIndexes");
1196   assignIndexes();
1197   log("-- calculateInitFunctions");
1198   calculateInitFunctions();
1199 
1200   if (!config->relocatable) {
1201     // Create linker synthesized functions
1202     if (config->isPic)
1203       createApplyRelocationsFunction();
1204     else if (config->sharedMemory)
1205       createInitMemoryFunction();
1206     createCallCtorsFunction();
1207 
1208     // Create export wrappers for commands if needed.
1209     //
1210     // If the input contains a call to `__wasm_call_ctors`, either in one of
1211     // the input objects or an explicit export from the command-line, we
1212     // assume ctors and dtors are taken care of already.
1213     if (!config->relocatable && !config->isPic &&
1214         !WasmSym::callCtors->isUsedInRegularObj &&
1215         !WasmSym::callCtors->isExported()) {
1216       log("-- createCommandExportWrappers");
1217       createCommandExportWrappers();
1218     }
1219   }
1220 
1221   if (!config->relocatable && config->sharedMemory && !config->shared)
1222     createInitTLSFunction();
1223 
1224   if (errorCount())
1225     return;
1226 
1227   log("-- calculateTypes");
1228   calculateTypes();
1229   log("-- calculateExports");
1230   calculateExports();
1231   log("-- calculateCustomSections");
1232   calculateCustomSections();
1233   log("-- populateSymtab");
1234   populateSymtab();
1235   log("-- populateTargetFeatures");
1236   populateTargetFeatures();
1237   log("-- addSections");
1238   addSections();
1239 
1240   if (errorHandler().verbose) {
1241     log("Defined Functions: " + Twine(out.functionSec->inputFunctions.size()));
1242     log("Defined Globals  : " + Twine(out.globalSec->numGlobals()));
1243     log("Defined Events   : " + Twine(out.eventSec->inputEvents.size()));
1244     log("Function Imports : " +
1245         Twine(out.importSec->getNumImportedFunctions()));
1246     log("Global Imports   : " + Twine(out.importSec->getNumImportedGlobals()));
1247     log("Event Imports    : " + Twine(out.importSec->getNumImportedEvents()));
1248     for (ObjFile *file : symtab->objectFiles)
1249       file->dumpInfo();
1250   }
1251 
1252   createHeader();
1253   log("-- finalizeSections");
1254   finalizeSections();
1255 
1256   log("-- writeMapFile");
1257   writeMapFile(outputSections);
1258 
1259   log("-- openFile");
1260   openFile();
1261   if (errorCount())
1262     return;
1263 
1264   writeHeader();
1265 
1266   log("-- writeSections");
1267   writeSections();
1268   if (errorCount())
1269     return;
1270 
1271   if (Error e = buffer->commit())
1272     fatal("failed to write the output file: " + toString(std::move(e)));
1273 }
1274 
1275 // Open a result file.
1276 void Writer::openFile() {
1277   log("writing: " + config->outputFile);
1278 
1279   Expected<std::unique_ptr<FileOutputBuffer>> bufferOrErr =
1280       FileOutputBuffer::create(config->outputFile, fileSize,
1281                                FileOutputBuffer::F_executable);
1282 
1283   if (!bufferOrErr)
1284     error("failed to open " + config->outputFile + ": " +
1285           toString(bufferOrErr.takeError()));
1286   else
1287     buffer = std::move(*bufferOrErr);
1288 }
1289 
1290 void Writer::createHeader() {
1291   raw_string_ostream os(header);
1292   writeBytes(os, WasmMagic, sizeof(WasmMagic), "wasm magic");
1293   writeU32(os, WasmVersion, "wasm version");
1294   os.flush();
1295   fileSize += header.size();
1296 }
1297 
1298 void writeResult() { Writer().run(); }
1299 
1300 } // namespace wasm
1301 } // namespace lld
1302