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