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