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