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