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