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