xref: /llvm-project-15.0.7/lld/wasm/Writer.cpp (revision 1095870e)
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 "InputElement.h"
13 #include "MapFile.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/CommonLinkerContext.h"
21 #include "lld/Common/Strings.h"
22 #include "llvm/ADT/DenseSet.h"
23 #include "llvm/ADT/SmallSet.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/StringMap.h"
26 #include "llvm/BinaryFormat/Wasm.h"
27 #include "llvm/BinaryFormat/WasmTraits.h"
28 #include "llvm/Support/FileOutputBuffer.h"
29 #include "llvm/Support/Format.h"
30 #include "llvm/Support/FormatVariadic.h"
31 #include "llvm/Support/LEB128.h"
32 #include "llvm/Support/Parallel.h"
33 
34 #include <cstdarg>
35 #include <map>
36 
37 #define DEBUG_TYPE "lld"
38 
39 using namespace llvm;
40 using namespace llvm::wasm;
41 
42 namespace lld {
43 namespace wasm {
44 static constexpr int stackAlignment = 16;
45 static constexpr int heapAlignment = 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   bool needsPassiveInitialization(const OutputSegment *segment);
58   bool hasPassiveInitializedSegments();
59 
60   void createSyntheticInitFunctions();
61   void createInitMemoryFunction();
62   void createStartFunction();
63   void createApplyDataRelocationsFunction();
64   void createApplyGlobalRelocationsFunction();
65   void createApplyGlobalTLSRelocationsFunction();
66   void createCallCtorsFunction();
67   void createInitTLSFunction();
68   void createCommandExportWrappers();
69   void createCommandExportWrapper(uint32_t functionIndex, DefinedFunction *f);
70 
71   void assignIndexes();
72   void populateSymtab();
73   void populateProducers();
74   void populateTargetFeatures();
75   // populateTargetFeatures happens early on so some checks are delayed
76   // until imports and exports are finalized.  There are run unstead
77   // in checkImportExportTargetFeatures
78   void checkImportExportTargetFeatures();
79   void calculateInitFunctions();
80   void calculateImports();
81   void calculateExports();
82   void calculateCustomSections();
83   void calculateTypes();
84   void createOutputSegments();
85   OutputSegment *createOutputSegment(StringRef name);
86   void combineOutputSegments();
87   void layoutMemory();
88   void createHeader();
89 
90   void addSection(OutputSection *sec);
91 
92   void addSections();
93 
94   void createCustomSections();
95   void createSyntheticSections();
96   void createSyntheticSectionsPostLayout();
97   void finalizeSections();
98 
99   // Custom sections
100   void createRelocSections();
101 
102   void writeHeader();
103   void writeSections();
104 
105   uint64_t fileSize = 0;
106 
107   std::vector<WasmInitEntry> initFunctions;
108   llvm::StringMap<std::vector<InputChunk *>> customSectionMapping;
109 
110   // Stable storage for command export wrapper function name strings.
111   std::list<std::string> commandExportWrapperNames;
112 
113   // Elements that are used to construct the final output
114   std::string header;
115   std::vector<OutputSection *> outputSections;
116 
117   std::unique_ptr<FileOutputBuffer> buffer;
118 
119   std::vector<OutputSegment *> segments;
120   llvm::SmallDenseMap<StringRef, OutputSegment *> segmentMap;
121 };
122 
123 } // anonymous namespace
124 
calculateCustomSections()125 void Writer::calculateCustomSections() {
126   log("calculateCustomSections");
127   bool stripDebug = config->stripDebug || config->stripAll;
128   for (ObjFile *file : symtab->objectFiles) {
129     for (InputChunk *section : file->customSections) {
130       // Exclude COMDAT sections that are not selected for inclusion
131       if (section->discarded)
132         continue;
133       StringRef name = section->name;
134       // These custom sections are known the linker and synthesized rather than
135       // blindly copied.
136       if (name == "linking" || name == "name" || name == "producers" ||
137           name == "target_features" || name.startswith("reloc."))
138         continue;
139       // These custom sections are generated by `clang -fembed-bitcode`.
140       // These are used by the rust toolchain to ship LTO data along with
141       // compiled object code, but they don't want this included in the linker
142       // output.
143       if (name == ".llvmbc" || name == ".llvmcmd")
144         continue;
145       // Strip debug section in that option was specified.
146       if (stripDebug && name.startswith(".debug_"))
147         continue;
148       // Otherwise include custom sections by default and concatenate their
149       // contents.
150       customSectionMapping[name].push_back(section);
151     }
152   }
153 }
154 
createCustomSections()155 void Writer::createCustomSections() {
156   log("createCustomSections");
157   for (auto &pair : customSectionMapping) {
158     StringRef name = pair.first();
159     LLVM_DEBUG(dbgs() << "createCustomSection: " << name << "\n");
160 
161     OutputSection *sec = make<CustomSection>(std::string(name), pair.second);
162     if (config->relocatable || config->emitRelocs) {
163       auto *sym = make<OutputSectionSymbol>(sec);
164       out.linkingSec->addToSymtab(sym);
165       sec->sectionSym = sym;
166     }
167     addSection(sec);
168   }
169 }
170 
171 // Create relocations sections in the final output.
172 // These are only created when relocatable output is requested.
createRelocSections()173 void Writer::createRelocSections() {
174   log("createRelocSections");
175   // Don't use iterator here since we are adding to OutputSection
176   size_t origSize = outputSections.size();
177   for (size_t i = 0; i < origSize; i++) {
178     LLVM_DEBUG(dbgs() << "check section " << i << "\n");
179     OutputSection *sec = outputSections[i];
180 
181     // Count the number of needed sections.
182     uint32_t count = sec->getNumRelocations();
183     if (!count)
184       continue;
185 
186     StringRef name;
187     if (sec->type == WASM_SEC_DATA)
188       name = "reloc.DATA";
189     else if (sec->type == WASM_SEC_CODE)
190       name = "reloc.CODE";
191     else if (sec->type == WASM_SEC_CUSTOM)
192       name = saver().save("reloc." + sec->name);
193     else
194       llvm_unreachable(
195           "relocations only supported for code, data, or custom sections");
196 
197     addSection(make<RelocSection>(name, sec));
198   }
199 }
200 
populateProducers()201 void Writer::populateProducers() {
202   for (ObjFile *file : symtab->objectFiles) {
203     const WasmProducerInfo &info = file->getWasmObj()->getProducerInfo();
204     out.producersSec->addInfo(info);
205   }
206 }
207 
writeHeader()208 void Writer::writeHeader() {
209   memcpy(buffer->getBufferStart(), header.data(), header.size());
210 }
211 
writeSections()212 void Writer::writeSections() {
213   uint8_t *buf = buffer->getBufferStart();
214   parallelForEach(outputSections, [buf](OutputSection *s) {
215     assert(s->isNeeded());
216     s->writeTo(buf);
217   });
218 }
219 
setGlobalPtr(DefinedGlobal * g,uint64_t memoryPtr)220 static void setGlobalPtr(DefinedGlobal *g, uint64_t memoryPtr) {
221   LLVM_DEBUG(dbgs() << "setGlobalPtr " << g->getName() << " -> " << memoryPtr << "\n");
222   g->global->setPointerValue(memoryPtr);
223 }
224 
225 // Fix the memory layout of the output binary.  This assigns memory offsets
226 // to each of the input data sections as well as the explicit stack region.
227 // The default memory layout is as follows, from low to high.
228 //
229 //  - initialized data (starting at Config->globalBase)
230 //  - BSS data (not currently implemented in llvm)
231 //  - explicit stack (Config->ZStackSize)
232 //  - heap start / unallocated
233 //
234 // The --stack-first option means that stack is placed before any static data.
235 // This can be useful since it means that stack overflow traps immediately
236 // rather than overwriting global data, but also increases code size since all
237 // static data loads and stores requires larger offsets.
layoutMemory()238 void Writer::layoutMemory() {
239   uint64_t memoryPtr = 0;
240 
241   auto placeStack = [&]() {
242     if (config->relocatable || config->isPic)
243       return;
244     memoryPtr = alignTo(memoryPtr, stackAlignment);
245     if (config->zStackSize != alignTo(config->zStackSize, stackAlignment))
246       error("stack size must be " + Twine(stackAlignment) + "-byte aligned");
247     log("mem: stack size  = " + Twine(config->zStackSize));
248     log("mem: stack base  = " + Twine(memoryPtr));
249     memoryPtr += config->zStackSize;
250     setGlobalPtr(cast<DefinedGlobal>(WasmSym::stackPointer), memoryPtr);
251     log("mem: stack top   = " + Twine(memoryPtr));
252   };
253 
254   if (config->stackFirst) {
255     placeStack();
256   } else {
257     memoryPtr = config->globalBase;
258     log("mem: global base = " + Twine(config->globalBase));
259   }
260 
261   if (WasmSym::globalBase)
262     WasmSym::globalBase->setVA(memoryPtr);
263 
264   uint64_t dataStart = memoryPtr;
265 
266   // Arbitrarily set __dso_handle handle to point to the start of the data
267   // segments.
268   if (WasmSym::dsoHandle)
269     WasmSym::dsoHandle->setVA(dataStart);
270 
271   out.dylinkSec->memAlign = 0;
272   for (OutputSegment *seg : segments) {
273     out.dylinkSec->memAlign = std::max(out.dylinkSec->memAlign, seg->alignment);
274     memoryPtr = alignTo(memoryPtr, 1ULL << seg->alignment);
275     seg->startVA = memoryPtr;
276     log(formatv("mem: {0,-15} offset={1,-8} size={2,-8} align={3}", seg->name,
277                 memoryPtr, seg->size, seg->alignment));
278 
279     if (!config->relocatable && seg->isTLS()) {
280       if (WasmSym::tlsSize) {
281         auto *tlsSize = cast<DefinedGlobal>(WasmSym::tlsSize);
282         setGlobalPtr(tlsSize, seg->size);
283       }
284       if (WasmSym::tlsAlign) {
285         auto *tlsAlign = cast<DefinedGlobal>(WasmSym::tlsAlign);
286         setGlobalPtr(tlsAlign, int64_t{1} << seg->alignment);
287       }
288       if (!config->sharedMemory && WasmSym::tlsBase) {
289         auto *tlsBase = cast<DefinedGlobal>(WasmSym::tlsBase);
290         setGlobalPtr(tlsBase, memoryPtr);
291       }
292     }
293 
294     memoryPtr += seg->size;
295   }
296 
297   // Make space for the memory initialization flag
298   if (config->sharedMemory && hasPassiveInitializedSegments()) {
299     memoryPtr = alignTo(memoryPtr, 4);
300     WasmSym::initMemoryFlag = symtab->addSyntheticDataSymbol(
301         "__wasm_init_memory_flag", WASM_SYMBOL_VISIBILITY_HIDDEN);
302     WasmSym::initMemoryFlag->markLive();
303     WasmSym::initMemoryFlag->setVA(memoryPtr);
304     log(formatv("mem: {0,-15} offset={1,-8} size={2,-8} align={3}",
305                 "__wasm_init_memory_flag", memoryPtr, 4, 4));
306     memoryPtr += 4;
307   }
308 
309   if (WasmSym::dataEnd)
310     WasmSym::dataEnd->setVA(memoryPtr);
311 
312   uint64_t staticDataSize = memoryPtr - dataStart;
313   log("mem: static data = " + Twine(staticDataSize));
314   if (config->isPic)
315     out.dylinkSec->memSize = staticDataSize;
316 
317   if (!config->stackFirst)
318     placeStack();
319 
320   if (WasmSym::heapBase) {
321     // Set `__heap_base` to follow the end of the stack or global data. The
322     // fact that this comes last means that a malloc/brk implementation can
323     // grow the heap at runtime.
324     // We'll align the heap base here because memory allocators might expect
325     // __heap_base to be aligned already.
326     memoryPtr = alignTo(memoryPtr, heapAlignment);
327     log("mem: heap base   = " + Twine(memoryPtr));
328     WasmSym::heapBase->setVA(memoryPtr);
329   }
330 
331   uint64_t maxMemorySetting = 1ULL << (config->is64.value_or(false) ? 48 : 32);
332 
333   if (config->initialMemory != 0) {
334     if (config->initialMemory != alignTo(config->initialMemory, WasmPageSize))
335       error("initial memory must be " + Twine(WasmPageSize) + "-byte aligned");
336     if (memoryPtr > config->initialMemory)
337       error("initial memory too small, " + Twine(memoryPtr) + " bytes needed");
338     if (config->initialMemory > maxMemorySetting)
339       error("initial memory too large, cannot be greater than " +
340             Twine(maxMemorySetting));
341     memoryPtr = config->initialMemory;
342   }
343 
344   memoryPtr = alignTo(memoryPtr, WasmPageSize);
345 
346   out.memorySec->numMemoryPages = memoryPtr / WasmPageSize;
347   log("mem: total pages = " + Twine(out.memorySec->numMemoryPages));
348 
349   if (WasmSym::heapEnd) {
350     // Set `__heap_end` to follow the end of the statically allocated linear
351     // memory. The fact that this comes last means that a malloc/brk
352     // implementation can grow the heap at runtime.
353     log("mem: heap end    = " + Twine(memoryPtr));
354     WasmSym::heapEnd->setVA(memoryPtr);
355   }
356 
357   if (config->maxMemory != 0) {
358     if (config->maxMemory != alignTo(config->maxMemory, WasmPageSize))
359       error("maximum memory must be " + Twine(WasmPageSize) + "-byte aligned");
360     if (memoryPtr > config->maxMemory)
361       error("maximum memory too small, " + Twine(memoryPtr) + " bytes needed");
362     if (config->maxMemory > maxMemorySetting)
363       error("maximum memory too large, cannot be greater than " +
364             Twine(maxMemorySetting));
365   }
366 
367   // Check max if explicitly supplied or required by shared memory
368   if (config->maxMemory != 0 || config->sharedMemory) {
369     uint64_t max = config->maxMemory;
370     if (max == 0) {
371       // If no maxMemory config was supplied but we are building with
372       // shared memory, we need to pick a sensible upper limit.
373       if (config->isPic)
374         max = maxMemorySetting;
375       else
376         max = memoryPtr;
377     }
378     out.memorySec->maxMemoryPages = max / WasmPageSize;
379     log("mem: max pages   = " + Twine(out.memorySec->maxMemoryPages));
380   }
381 }
382 
addSection(OutputSection * sec)383 void Writer::addSection(OutputSection *sec) {
384   if (!sec->isNeeded())
385     return;
386   log("addSection: " + toString(*sec));
387   sec->sectionIndex = outputSections.size();
388   outputSections.push_back(sec);
389 }
390 
391 // If a section name is valid as a C identifier (which is rare because of
392 // the leading '.'), linkers are expected to define __start_<secname> and
393 // __stop_<secname> symbols. They are at beginning and end of the section,
394 // respectively. This is not requested by the ELF standard, but GNU ld and
395 // gold provide the feature, and used by many programs.
addStartStopSymbols(const OutputSegment * seg)396 static void addStartStopSymbols(const OutputSegment *seg) {
397   StringRef name = seg->name;
398   if (!isValidCIdentifier(name))
399     return;
400   LLVM_DEBUG(dbgs() << "addStartStopSymbols: " << name << "\n");
401   uint64_t start = seg->startVA;
402   uint64_t stop = start + seg->size;
403   symtab->addOptionalDataSymbol(saver().save("__start_" + name), start);
404   symtab->addOptionalDataSymbol(saver().save("__stop_" + name), stop);
405 }
406 
addSections()407 void Writer::addSections() {
408   addSection(out.dylinkSec);
409   addSection(out.typeSec);
410   addSection(out.importSec);
411   addSection(out.functionSec);
412   addSection(out.tableSec);
413   addSection(out.memorySec);
414   addSection(out.tagSec);
415   addSection(out.globalSec);
416   addSection(out.exportSec);
417   addSection(out.startSec);
418   addSection(out.elemSec);
419   addSection(out.dataCountSec);
420 
421   addSection(make<CodeSection>(out.functionSec->inputFunctions));
422   addSection(make<DataSection>(segments));
423 
424   createCustomSections();
425 
426   addSection(out.linkingSec);
427   if (config->emitRelocs || config->relocatable) {
428     createRelocSections();
429   }
430 
431   addSection(out.nameSec);
432   addSection(out.producersSec);
433   addSection(out.targetFeaturesSec);
434 }
435 
finalizeSections()436 void Writer::finalizeSections() {
437   for (OutputSection *s : outputSections) {
438     s->setOffset(fileSize);
439     s->finalizeContents();
440     fileSize += s->getSize();
441   }
442 }
443 
populateTargetFeatures()444 void Writer::populateTargetFeatures() {
445   StringMap<std::string> used;
446   StringMap<std::string> required;
447   StringMap<std::string> disallowed;
448   SmallSet<std::string, 8> &allowed = out.targetFeaturesSec->features;
449   bool tlsUsed = false;
450 
451   if (config->isPic) {
452     // This should not be necessary because all PIC objects should
453     // contain the mutable-globals feature.
454     // TODO(https://bugs.llvm.org/show_bug.cgi?id=52339)
455     allowed.insert("mutable-globals");
456   }
457 
458   // Only infer used features if user did not specify features
459   bool inferFeatures = !config->features.has_value();
460 
461   if (!inferFeatures) {
462     auto &explicitFeatures = config->features.value();
463     allowed.insert(explicitFeatures.begin(), explicitFeatures.end());
464     if (!config->checkFeatures)
465       goto done;
466   }
467 
468   // Find the sets of used, required, and disallowed features
469   for (ObjFile *file : symtab->objectFiles) {
470     StringRef fileName(file->getName());
471     for (auto &feature : file->getWasmObj()->getTargetFeatures()) {
472       switch (feature.Prefix) {
473       case WASM_FEATURE_PREFIX_USED:
474         used.insert({feature.Name, std::string(fileName)});
475         break;
476       case WASM_FEATURE_PREFIX_REQUIRED:
477         used.insert({feature.Name, std::string(fileName)});
478         required.insert({feature.Name, std::string(fileName)});
479         break;
480       case WASM_FEATURE_PREFIX_DISALLOWED:
481         disallowed.insert({feature.Name, std::string(fileName)});
482         break;
483       default:
484         error("Unrecognized feature policy prefix " +
485               std::to_string(feature.Prefix));
486       }
487     }
488 
489     // Find TLS data segments
490     auto isTLS = [](InputChunk *segment) {
491       return segment->live && segment->isTLS();
492     };
493     tlsUsed = tlsUsed || llvm::any_of(file->segments, isTLS);
494   }
495 
496   if (inferFeatures)
497     for (const auto &key : used.keys())
498       allowed.insert(std::string(key));
499 
500   if (!config->checkFeatures)
501     goto done;
502 
503   if (config->sharedMemory) {
504     if (disallowed.count("shared-mem"))
505       error("--shared-memory is disallowed by " + disallowed["shared-mem"] +
506             " because it was not compiled with 'atomics' or 'bulk-memory' "
507             "features.");
508 
509     for (auto feature : {"atomics", "bulk-memory"})
510       if (!allowed.count(feature))
511         error(StringRef("'") + feature +
512               "' feature must be used in order to use shared memory");
513   }
514 
515   if (tlsUsed) {
516     for (auto feature : {"atomics", "bulk-memory"})
517       if (!allowed.count(feature))
518         error(StringRef("'") + feature +
519               "' feature must be used in order to use thread-local storage");
520   }
521 
522   // Validate that used features are allowed in output
523   if (!inferFeatures) {
524     for (const auto &feature : used.keys()) {
525       if (!allowed.count(std::string(feature)))
526         error(Twine("Target feature '") + feature + "' used by " +
527               used[feature] + " is not allowed.");
528     }
529   }
530 
531   // Validate the required and disallowed constraints for each file
532   for (ObjFile *file : symtab->objectFiles) {
533     StringRef fileName(file->getName());
534     SmallSet<std::string, 8> objectFeatures;
535     for (const auto &feature : file->getWasmObj()->getTargetFeatures()) {
536       if (feature.Prefix == WASM_FEATURE_PREFIX_DISALLOWED)
537         continue;
538       objectFeatures.insert(feature.Name);
539       if (disallowed.count(feature.Name))
540         error(Twine("Target feature '") + feature.Name + "' used in " +
541               fileName + " is disallowed by " + disallowed[feature.Name] +
542               ". Use --no-check-features to suppress.");
543     }
544     for (const auto &feature : required.keys()) {
545       if (!objectFeatures.count(std::string(feature)))
546         error(Twine("Missing target feature '") + feature + "' in " + fileName +
547               ", required by " + required[feature] +
548               ". Use --no-check-features to suppress.");
549     }
550   }
551 
552 done:
553   // Normally we don't include bss segments in the binary.  In particular if
554   // memory is not being imported then we can assume its zero initialized.
555   // In the case the memory is imported, and we can use the memory.fill
556   // instruction, then we can also avoid including the segments.
557   if (config->importMemory && !allowed.count("bulk-memory"))
558     config->emitBssSegments = true;
559 
560   if (allowed.count("extended-const"))
561     config->extendedConst = true;
562 
563   for (auto &feature : allowed)
564     log("Allowed feature: " + feature);
565 }
566 
checkImportExportTargetFeatures()567 void Writer::checkImportExportTargetFeatures() {
568   if (config->relocatable || !config->checkFeatures)
569     return;
570 
571   if (out.targetFeaturesSec->features.count("mutable-globals") == 0) {
572     for (const Symbol *sym : out.importSec->importedSymbols) {
573       if (auto *global = dyn_cast<GlobalSymbol>(sym)) {
574         if (global->getGlobalType()->Mutable) {
575           error(Twine("mutable global imported but 'mutable-globals' feature "
576                       "not present in inputs: `") +
577                 toString(*sym) + "`. Use --no-check-features to suppress.");
578         }
579       }
580     }
581     for (const Symbol *sym : out.exportSec->exportedSymbols) {
582       if (isa<GlobalSymbol>(sym)) {
583         error(Twine("mutable global exported but 'mutable-globals' feature "
584                     "not present in inputs: `") +
585               toString(*sym) + "`. Use --no-check-features to suppress.");
586       }
587     }
588   }
589 }
590 
shouldImport(Symbol * sym)591 static bool shouldImport(Symbol *sym) {
592   // We don't generate imports for data symbols. They however can be imported
593   // as GOT entries.
594   if (isa<DataSymbol>(sym))
595     return false;
596   if (!sym->isLive())
597     return false;
598   if (!sym->isUsedInRegularObj)
599     return false;
600 
601   // When a symbol is weakly defined in a shared library we need to allow
602   // it to be overridden by another module so need to both import
603   // and export the symbol.
604   if (config->shared && sym->isWeak() && !sym->isUndefined() &&
605       !sym->isHidden())
606     return true;
607   if (!sym->isUndefined())
608     return false;
609   if (sym->isWeak() && !config->relocatable && !config->isPic)
610     return false;
611 
612   // In PIC mode we only need to import functions when they are called directly.
613   // Indirect usage all goes via GOT imports.
614   if (config->isPic) {
615     if (auto *f = dyn_cast<UndefinedFunction>(sym))
616       if (!f->isCalledDirectly)
617         return false;
618   }
619 
620   if (config->isPic || config->relocatable || config->importUndefined ||
621       config->unresolvedSymbols == UnresolvedPolicy::ImportDynamic)
622     return true;
623   if (config->allowUndefinedSymbols.count(sym->getName()) != 0)
624     return true;
625 
626   return sym->importName.has_value();
627 }
628 
calculateImports()629 void Writer::calculateImports() {
630   // Some inputs require that the indirect function table be assigned to table
631   // number 0, so if it is present and is an import, allocate it before any
632   // other tables.
633   if (WasmSym::indirectFunctionTable &&
634       shouldImport(WasmSym::indirectFunctionTable))
635     out.importSec->addImport(WasmSym::indirectFunctionTable);
636 
637   for (Symbol *sym : symtab->getSymbols()) {
638     if (!shouldImport(sym))
639       continue;
640     if (sym == WasmSym::indirectFunctionTable)
641       continue;
642     LLVM_DEBUG(dbgs() << "import: " << sym->getName() << "\n");
643     out.importSec->addImport(sym);
644   }
645 }
646 
calculateExports()647 void Writer::calculateExports() {
648   if (config->relocatable)
649     return;
650 
651   if (!config->relocatable && !config->importMemory)
652     out.exportSec->exports.push_back(
653         WasmExport{"memory", WASM_EXTERNAL_MEMORY, 0});
654 
655   unsigned globalIndex =
656       out.importSec->getNumImportedGlobals() + out.globalSec->numGlobals();
657 
658   for (Symbol *sym : symtab->getSymbols()) {
659     if (!sym->isExported())
660       continue;
661     if (!sym->isLive())
662       continue;
663 
664     StringRef name = sym->getName();
665     WasmExport export_;
666     if (auto *f = dyn_cast<DefinedFunction>(sym)) {
667       if (Optional<StringRef> exportName = f->function->getExportName()) {
668         name = *exportName;
669       }
670       export_ = {name, WASM_EXTERNAL_FUNCTION, f->getExportedFunctionIndex()};
671     } else if (auto *g = dyn_cast<DefinedGlobal>(sym)) {
672       if (g->getGlobalType()->Mutable && !g->getFile() && !g->forceExport) {
673         // Avoid exporting mutable globals are linker synthesized (e.g.
674         // __stack_pointer or __tls_base) unless they are explicitly exported
675         // from the command line.
676         // Without this check `--export-all` would cause any program using the
677         // stack pointer to export a mutable global even if none of the input
678         // files were built with the `mutable-globals` feature.
679         continue;
680       }
681       export_ = {name, WASM_EXTERNAL_GLOBAL, g->getGlobalIndex()};
682     } else if (auto *t = dyn_cast<DefinedTag>(sym)) {
683       export_ = {name, WASM_EXTERNAL_TAG, t->getTagIndex()};
684     } else if (auto *d = dyn_cast<DefinedData>(sym)) {
685       out.globalSec->dataAddressGlobals.push_back(d);
686       export_ = {name, WASM_EXTERNAL_GLOBAL, globalIndex++};
687     } else {
688       auto *t = cast<DefinedTable>(sym);
689       export_ = {name, WASM_EXTERNAL_TABLE, t->getTableNumber()};
690     }
691 
692     LLVM_DEBUG(dbgs() << "Export: " << name << "\n");
693     out.exportSec->exports.push_back(export_);
694     out.exportSec->exportedSymbols.push_back(sym);
695   }
696 }
697 
populateSymtab()698 void Writer::populateSymtab() {
699   if (!config->relocatable && !config->emitRelocs)
700     return;
701 
702   for (Symbol *sym : symtab->getSymbols())
703     if (sym->isUsedInRegularObj && sym->isLive())
704       out.linkingSec->addToSymtab(sym);
705 
706   for (ObjFile *file : symtab->objectFiles) {
707     LLVM_DEBUG(dbgs() << "Local symtab entries: " << file->getName() << "\n");
708     for (Symbol *sym : file->getSymbols())
709       if (sym->isLocal() && !isa<SectionSymbol>(sym) && sym->isLive())
710         out.linkingSec->addToSymtab(sym);
711   }
712 }
713 
calculateTypes()714 void Writer::calculateTypes() {
715   // The output type section is the union of the following sets:
716   // 1. Any signature used in the TYPE relocation
717   // 2. The signatures of all imported functions
718   // 3. The signatures of all defined functions
719   // 4. The signatures of all imported tags
720   // 5. The signatures of all defined tags
721 
722   for (ObjFile *file : symtab->objectFiles) {
723     ArrayRef<WasmSignature> types = file->getWasmObj()->types();
724     for (uint32_t i = 0; i < types.size(); i++)
725       if (file->typeIsUsed[i])
726         file->typeMap[i] = out.typeSec->registerType(types[i]);
727   }
728 
729   for (const Symbol *sym : out.importSec->importedSymbols) {
730     if (auto *f = dyn_cast<FunctionSymbol>(sym))
731       out.typeSec->registerType(*f->signature);
732     else if (auto *t = dyn_cast<TagSymbol>(sym))
733       out.typeSec->registerType(*t->signature);
734   }
735 
736   for (const InputFunction *f : out.functionSec->inputFunctions)
737     out.typeSec->registerType(f->signature);
738 
739   for (const InputTag *t : out.tagSec->inputTags)
740     out.typeSec->registerType(t->signature);
741 }
742 
743 // In a command-style link, create a wrapper for each exported symbol
744 // which calls the constructors and destructors.
createCommandExportWrappers()745 void Writer::createCommandExportWrappers() {
746   // This logic doesn't currently support Emscripten-style PIC mode.
747   assert(!config->isPic);
748 
749   // If there are no ctors and there's no libc `__wasm_call_dtors` to
750   // call, don't wrap the exports.
751   if (initFunctions.empty() && WasmSym::callDtors == nullptr)
752     return;
753 
754   std::vector<DefinedFunction *> toWrap;
755 
756   for (Symbol *sym : symtab->getSymbols())
757     if (sym->isExported())
758       if (auto *f = dyn_cast<DefinedFunction>(sym))
759         toWrap.push_back(f);
760 
761   for (auto *f : toWrap) {
762     auto funcNameStr = (f->getName() + ".command_export").str();
763     commandExportWrapperNames.push_back(funcNameStr);
764     const std::string &funcName = commandExportWrapperNames.back();
765 
766     auto func = make<SyntheticFunction>(*f->getSignature(), funcName);
767     if (f->function->getExportName())
768       func->setExportName(f->function->getExportName()->str());
769     else
770       func->setExportName(f->getName().str());
771 
772     DefinedFunction *def =
773         symtab->addSyntheticFunction(funcName, f->flags, func);
774     def->markLive();
775 
776     def->flags |= WASM_SYMBOL_EXPORTED;
777     def->flags &= ~WASM_SYMBOL_VISIBILITY_HIDDEN;
778     def->forceExport = f->forceExport;
779 
780     f->flags |= WASM_SYMBOL_VISIBILITY_HIDDEN;
781     f->flags &= ~WASM_SYMBOL_EXPORTED;
782     f->forceExport = false;
783 
784     out.functionSec->addFunction(func);
785 
786     createCommandExportWrapper(f->getFunctionIndex(), def);
787   }
788 }
789 
finalizeIndirectFunctionTable()790 static void finalizeIndirectFunctionTable() {
791   if (!WasmSym::indirectFunctionTable)
792     return;
793 
794   if (shouldImport(WasmSym::indirectFunctionTable) &&
795       !WasmSym::indirectFunctionTable->hasTableNumber()) {
796     // Processing -Bsymbolic relocations resulted in a late requirement that the
797     // indirect function table be present, and we are running in --import-table
798     // mode.  Add the table now to the imports section.  Otherwise it will be
799     // added to the tables section later in assignIndexes.
800     out.importSec->addImport(WasmSym::indirectFunctionTable);
801   }
802 
803   uint32_t tableSize = config->tableBase + out.elemSec->numEntries();
804   WasmLimits limits = {0, tableSize, 0};
805   if (WasmSym::indirectFunctionTable->isDefined() && !config->growableTable) {
806     limits.Flags |= WASM_LIMITS_FLAG_HAS_MAX;
807     limits.Maximum = limits.Minimum;
808   }
809   WasmSym::indirectFunctionTable->setLimits(limits);
810 }
811 
scanRelocations()812 static void scanRelocations() {
813   for (ObjFile *file : symtab->objectFiles) {
814     LLVM_DEBUG(dbgs() << "scanRelocations: " << file->getName() << "\n");
815     for (InputChunk *chunk : file->functions)
816       scanRelocations(chunk);
817     for (InputChunk *chunk : file->segments)
818       scanRelocations(chunk);
819     for (auto &p : file->customSections)
820       scanRelocations(p);
821   }
822 }
823 
assignIndexes()824 void Writer::assignIndexes() {
825   // Seal the import section, since other index spaces such as function and
826   // global are effected by the number of imports.
827   out.importSec->seal();
828 
829   for (InputFunction *func : symtab->syntheticFunctions)
830     out.functionSec->addFunction(func);
831 
832   for (ObjFile *file : symtab->objectFiles) {
833     LLVM_DEBUG(dbgs() << "Functions: " << file->getName() << "\n");
834     for (InputFunction *func : file->functions)
835       out.functionSec->addFunction(func);
836   }
837 
838   for (InputGlobal *global : symtab->syntheticGlobals)
839     out.globalSec->addGlobal(global);
840 
841   for (ObjFile *file : symtab->objectFiles) {
842     LLVM_DEBUG(dbgs() << "Globals: " << file->getName() << "\n");
843     for (InputGlobal *global : file->globals)
844       out.globalSec->addGlobal(global);
845   }
846 
847   for (ObjFile *file : symtab->objectFiles) {
848     LLVM_DEBUG(dbgs() << "Tags: " << file->getName() << "\n");
849     for (InputTag *tag : file->tags)
850       out.tagSec->addTag(tag);
851   }
852 
853   for (ObjFile *file : symtab->objectFiles) {
854     LLVM_DEBUG(dbgs() << "Tables: " << file->getName() << "\n");
855     for (InputTable *table : file->tables)
856       out.tableSec->addTable(table);
857   }
858 
859   for (InputTable *table : symtab->syntheticTables)
860     out.tableSec->addTable(table);
861 
862   out.globalSec->assignIndexes();
863   out.tableSec->assignIndexes();
864 }
865 
getOutputDataSegmentName(const InputChunk & seg)866 static StringRef getOutputDataSegmentName(const InputChunk &seg) {
867   // We always merge .tbss and .tdata into a single TLS segment so all TLS
868   // symbols are be relative to single __tls_base.
869   if (seg.isTLS())
870     return ".tdata";
871   if (!config->mergeDataSegments)
872     return seg.name;
873   if (seg.name.startswith(".text."))
874     return ".text";
875   if (seg.name.startswith(".data."))
876     return ".data";
877   if (seg.name.startswith(".bss."))
878     return ".bss";
879   if (seg.name.startswith(".rodata."))
880     return ".rodata";
881   return seg.name;
882 }
883 
createOutputSegment(StringRef name)884 OutputSegment *Writer::createOutputSegment(StringRef name) {
885   LLVM_DEBUG(dbgs() << "new segment: " << name << "\n");
886   OutputSegment *s = make<OutputSegment>(name);
887   if (config->sharedMemory)
888     s->initFlags = WASM_DATA_SEGMENT_IS_PASSIVE;
889   if (!config->relocatable && name.startswith(".bss"))
890     s->isBss = true;
891   segments.push_back(s);
892   return s;
893 }
894 
createOutputSegments()895 void Writer::createOutputSegments() {
896   for (ObjFile *file : symtab->objectFiles) {
897     for (InputChunk *segment : file->segments) {
898       if (!segment->live)
899         continue;
900       StringRef name = getOutputDataSegmentName(*segment);
901       OutputSegment *s = nullptr;
902       // When running in relocatable mode we can't merge segments that are part
903       // of comdat groups since the ultimate linker needs to be able exclude or
904       // include them individually.
905       if (config->relocatable && !segment->getComdatName().empty()) {
906         s = createOutputSegment(name);
907       } else {
908         if (segmentMap.count(name) == 0)
909           segmentMap[name] = createOutputSegment(name);
910         s = segmentMap[name];
911       }
912       s->addInputSegment(segment);
913     }
914   }
915 
916   // Sort segments by type, placing .bss last
917   std::stable_sort(segments.begin(), segments.end(),
918                    [](const OutputSegment *a, const OutputSegment *b) {
919                      auto order = [](StringRef name) {
920                        return StringSwitch<int>(name)
921                            .StartsWith(".tdata", 0)
922                            .StartsWith(".rodata", 1)
923                            .StartsWith(".data", 2)
924                            .StartsWith(".bss", 4)
925                            .Default(3);
926                      };
927                      return order(a->name) < order(b->name);
928                    });
929 
930   for (size_t i = 0; i < segments.size(); ++i)
931     segments[i]->index = i;
932 
933   // Merge MergeInputSections into a single MergeSyntheticSection.
934   LLVM_DEBUG(dbgs() << "-- finalize input semgments\n");
935   for (OutputSegment *seg : segments)
936     seg->finalizeInputSegments();
937 }
938 
combineOutputSegments()939 void Writer::combineOutputSegments() {
940   // With PIC code we currently only support a single active data segment since
941   // we only have a single __memory_base to use as our base address.  This pass
942   // combines all data segments into a single .data segment.
943   // This restriction does not apply when the extended const extension is
944   // available: https://github.com/WebAssembly/extended-const
945   assert(!config->extendedConst);
946   assert(config->isPic && !config->sharedMemory);
947   if (segments.size() <= 1)
948     return;
949   OutputSegment *combined = make<OutputSegment>(".data");
950   combined->startVA = segments[0]->startVA;
951   for (OutputSegment *s : segments) {
952     bool first = true;
953     for (InputChunk *inSeg : s->inputSegments) {
954       if (first)
955         inSeg->alignment = std::max(inSeg->alignment, s->alignment);
956       first = false;
957 #ifndef NDEBUG
958       uint64_t oldVA = inSeg->getVA();
959 #endif
960       combined->addInputSegment(inSeg);
961 #ifndef NDEBUG
962       uint64_t newVA = inSeg->getVA();
963       LLVM_DEBUG(dbgs() << "added input segment. name=" << inSeg->name
964                         << " oldVA=" << oldVA << " newVA=" << newVA << "\n");
965       assert(oldVA == newVA);
966 #endif
967     }
968   }
969 
970   segments = {combined};
971 }
972 
createFunction(DefinedFunction * func,StringRef bodyContent)973 static void createFunction(DefinedFunction *func, StringRef bodyContent) {
974   std::string functionBody;
975   {
976     raw_string_ostream os(functionBody);
977     writeUleb128(os, bodyContent.size(), "function size");
978     os << bodyContent;
979   }
980   ArrayRef<uint8_t> body = arrayRefFromStringRef(saver().save(functionBody));
981   cast<SyntheticFunction>(func->function)->setBody(body);
982 }
983 
needsPassiveInitialization(const OutputSegment * segment)984 bool Writer::needsPassiveInitialization(const OutputSegment *segment) {
985   // If bulk memory features is supported then we can perform bss initialization
986   // (via memory.fill) during `__wasm_init_memory`.
987   if (config->importMemory && !segment->requiredInBinary())
988     return true;
989   return segment->initFlags & WASM_DATA_SEGMENT_IS_PASSIVE;
990 }
991 
hasPassiveInitializedSegments()992 bool Writer::hasPassiveInitializedSegments() {
993   return llvm::any_of(segments, [this](const OutputSegment *s) {
994     return this->needsPassiveInitialization(s);
995   });
996 }
997 
createSyntheticInitFunctions()998 void Writer::createSyntheticInitFunctions() {
999   if (config->relocatable)
1000     return;
1001 
1002   static WasmSignature nullSignature = {{}, {}};
1003 
1004   // Passive segments are used to avoid memory being reinitialized on each
1005   // thread's instantiation. These passive segments are initialized and
1006   // dropped in __wasm_init_memory, which is registered as the start function
1007   // We also initialize bss segments (using memory.fill) as part of this
1008   // function.
1009   if (hasPassiveInitializedSegments()) {
1010     WasmSym::initMemory = symtab->addSyntheticFunction(
1011         "__wasm_init_memory", WASM_SYMBOL_VISIBILITY_HIDDEN,
1012         make<SyntheticFunction>(nullSignature, "__wasm_init_memory"));
1013     WasmSym::initMemory->markLive();
1014     if (config->sharedMemory) {
1015       // This global is assigned during  __wasm_init_memory in the shared memory
1016       // case.
1017       WasmSym::tlsBase->markLive();
1018     }
1019   }
1020 
1021   if (config->sharedMemory && out.globalSec->needsTLSRelocations()) {
1022     WasmSym::applyGlobalTLSRelocs = symtab->addSyntheticFunction(
1023         "__wasm_apply_global_tls_relocs", WASM_SYMBOL_VISIBILITY_HIDDEN,
1024         make<SyntheticFunction>(nullSignature,
1025                                 "__wasm_apply_global_tls_relocs"));
1026     WasmSym::applyGlobalTLSRelocs->markLive();
1027     // TLS relocations depend on  the __tls_base symbols
1028     WasmSym::tlsBase->markLive();
1029   }
1030 
1031   if (config->isPic && out.globalSec->needsRelocations()) {
1032     WasmSym::applyGlobalRelocs = symtab->addSyntheticFunction(
1033         "__wasm_apply_global_relocs", WASM_SYMBOL_VISIBILITY_HIDDEN,
1034         make<SyntheticFunction>(nullSignature, "__wasm_apply_global_relocs"));
1035     WasmSym::applyGlobalRelocs->markLive();
1036   }
1037 
1038   // If there is only one start function we can just use that function
1039   // itself as the Wasm start function, otherwise we need to synthesize
1040   // a new function to call them in sequence.
1041   if (WasmSym::applyGlobalRelocs && WasmSym::initMemory) {
1042     WasmSym::startFunction = symtab->addSyntheticFunction(
1043         "__wasm_start", WASM_SYMBOL_VISIBILITY_HIDDEN,
1044         make<SyntheticFunction>(nullSignature, "__wasm_start"));
1045     WasmSym::startFunction->markLive();
1046   }
1047 }
1048 
createInitMemoryFunction()1049 void Writer::createInitMemoryFunction() {
1050   LLVM_DEBUG(dbgs() << "createInitMemoryFunction\n");
1051   assert(WasmSym::initMemory);
1052   assert(hasPassiveInitializedSegments());
1053   uint64_t flagAddress;
1054   if (config->sharedMemory) {
1055     assert(WasmSym::initMemoryFlag);
1056     flagAddress = WasmSym::initMemoryFlag->getVA();
1057   }
1058   bool is64 = config->is64.value_or(false);
1059   std::string bodyContent;
1060   {
1061     raw_string_ostream os(bodyContent);
1062     // Initialize memory in a thread-safe manner. The thread that successfully
1063     // increments the flag from 0 to 1 is is responsible for performing the
1064     // memory initialization. Other threads go sleep on the flag until the
1065     // first thread finishing initializing memory, increments the flag to 2,
1066     // and wakes all the other threads. Once the flag has been set to 2,
1067     // subsequently started threads will skip the sleep. All threads
1068     // unconditionally drop their passive data segments once memory has been
1069     // initialized. The generated code is as follows:
1070     //
1071     // (func $__wasm_init_memory
1072     //  (block $drop
1073     //   (block $wait
1074     //    (block $init
1075     //     (br_table $init $wait $drop
1076     //      (i32.atomic.rmw.cmpxchg align=2 offset=0
1077     //       (i32.const $__init_memory_flag)
1078     //       (i32.const 0)
1079     //       (i32.const 1)
1080     //      )
1081     //     )
1082     //    ) ;; $init
1083     //    ( ... initialize data segments ... )
1084     //    (i32.atomic.store align=2 offset=0
1085     //     (i32.const $__init_memory_flag)
1086     //     (i32.const 2)
1087     //    )
1088     //    (drop
1089     //     (i32.atomic.notify align=2 offset=0
1090     //      (i32.const $__init_memory_flag)
1091     //      (i32.const -1u)
1092     //     )
1093     //    )
1094     //    (br $drop)
1095     //   ) ;; $wait
1096     //   (drop
1097     //    (i32.atomic.wait align=2 offset=0
1098     //     (i32.const $__init_memory_flag)
1099     //     (i32.const 1)
1100     //     (i32.const -1)
1101     //    )
1102     //   )
1103     //  ) ;; $drop
1104     //  ( ... drop data segments ... )
1105     // )
1106     //
1107     // When we are building with PIC, calculate the flag location using:
1108     //
1109     //    (global.get $__memory_base)
1110     //    (i32.const $__init_memory_flag)
1111     //    (i32.const 1)
1112 
1113     auto writeGetFlagAddress = [&]() {
1114       if (config->isPic) {
1115         writeU8(os, WASM_OPCODE_LOCAL_GET, "local.get");
1116         writeUleb128(os, 0, "local 0");
1117       } else {
1118         writePtrConst(os, flagAddress, is64, "flag address");
1119       }
1120     };
1121 
1122     if (config->sharedMemory) {
1123       // With PIC code we cache the flag address in local 0
1124       if (config->isPic) {
1125         writeUleb128(os, 1, "num local decls");
1126         writeUleb128(os, 2, "local count");
1127         writeU8(os, is64 ? WASM_TYPE_I64 : WASM_TYPE_I32, "address type");
1128         writeU8(os, WASM_OPCODE_GLOBAL_GET, "GLOBAL_GET");
1129         writeUleb128(os, WasmSym::memoryBase->getGlobalIndex(), "memory_base");
1130         writePtrConst(os, flagAddress, is64, "flag address");
1131         writeU8(os, is64 ? WASM_OPCODE_I64_ADD : WASM_OPCODE_I32_ADD, "add");
1132         writeU8(os, WASM_OPCODE_LOCAL_SET, "local.set");
1133         writeUleb128(os, 0, "local 0");
1134       } else {
1135         writeUleb128(os, 0, "num locals");
1136       }
1137 
1138       // Set up destination blocks
1139       writeU8(os, WASM_OPCODE_BLOCK, "block $drop");
1140       writeU8(os, WASM_TYPE_NORESULT, "block type");
1141       writeU8(os, WASM_OPCODE_BLOCK, "block $wait");
1142       writeU8(os, WASM_TYPE_NORESULT, "block type");
1143       writeU8(os, WASM_OPCODE_BLOCK, "block $init");
1144       writeU8(os, WASM_TYPE_NORESULT, "block type");
1145 
1146       // Atomically check whether we win the race.
1147       writeGetFlagAddress();
1148       writeI32Const(os, 0, "expected flag value");
1149       writeI32Const(os, 1, "new flag value");
1150       writeU8(os, WASM_OPCODE_ATOMICS_PREFIX, "atomics prefix");
1151       writeUleb128(os, WASM_OPCODE_I32_RMW_CMPXCHG, "i32.atomic.rmw.cmpxchg");
1152       writeMemArg(os, 2, 0);
1153 
1154       // Based on the value, decide what to do next.
1155       writeU8(os, WASM_OPCODE_BR_TABLE, "br_table");
1156       writeUleb128(os, 2, "label vector length");
1157       writeUleb128(os, 0, "label $init");
1158       writeUleb128(os, 1, "label $wait");
1159       writeUleb128(os, 2, "default label $drop");
1160 
1161       // Initialize passive data segments
1162       writeU8(os, WASM_OPCODE_END, "end $init");
1163     } else {
1164       writeUleb128(os, 0, "num local decls");
1165     }
1166 
1167     for (const OutputSegment *s : segments) {
1168       if (needsPassiveInitialization(s)) {
1169         // For passive BSS segments we can simple issue a memory.fill(0).
1170         // For non-BSS segments we do a memory.init.  Both these
1171         // instructions take as their first argument the destination
1172         // address.
1173         writePtrConst(os, s->startVA, is64, "destination address");
1174         if (config->isPic) {
1175           writeU8(os, WASM_OPCODE_GLOBAL_GET, "GLOBAL_GET");
1176           writeUleb128(os, WasmSym::memoryBase->getGlobalIndex(),
1177                        "__memory_base");
1178           writeU8(os, is64 ? WASM_OPCODE_I64_ADD : WASM_OPCODE_I32_ADD,
1179                   "i32.add");
1180         }
1181 
1182         // When we initialize the TLS segment we also set the `__tls_base`
1183         // global.  This allows the runtime to use this static copy of the
1184         // TLS data for the first/main thread.
1185         if (config->sharedMemory && s->isTLS()) {
1186           if (config->isPic) {
1187             // Cache the result of the addionion in local 0
1188             writeU8(os, WASM_OPCODE_LOCAL_TEE, "local.tee");
1189             writeUleb128(os, 1, "local 1");
1190           } else {
1191             writePtrConst(os, s->startVA, is64, "destination address");
1192           }
1193           writeU8(os, WASM_OPCODE_GLOBAL_SET, "GLOBAL_SET");
1194           writeUleb128(os, WasmSym::tlsBase->getGlobalIndex(),
1195                        "__tls_base");
1196           if (config->isPic) {
1197             writeU8(os, WASM_OPCODE_LOCAL_GET, "local.tee");
1198             writeUleb128(os, 1, "local 1");
1199           }
1200         }
1201 
1202         if (s->isBss) {
1203           writeI32Const(os, 0, "fill value");
1204           writeI32Const(os, s->size, "memory region size");
1205           writeU8(os, WASM_OPCODE_MISC_PREFIX, "bulk-memory prefix");
1206           writeUleb128(os, WASM_OPCODE_MEMORY_FILL, "memory.fill");
1207           writeU8(os, 0, "memory index immediate");
1208         } else {
1209           writeI32Const(os, 0, "source segment offset");
1210           writeI32Const(os, s->size, "memory region size");
1211           writeU8(os, WASM_OPCODE_MISC_PREFIX, "bulk-memory prefix");
1212           writeUleb128(os, WASM_OPCODE_MEMORY_INIT, "memory.init");
1213           writeUleb128(os, s->index, "segment index immediate");
1214           writeU8(os, 0, "memory index immediate");
1215         }
1216       }
1217     }
1218 
1219     if (config->sharedMemory) {
1220       // Set flag to 2 to mark end of initialization
1221       writeGetFlagAddress();
1222       writeI32Const(os, 2, "flag value");
1223       writeU8(os, WASM_OPCODE_ATOMICS_PREFIX, "atomics prefix");
1224       writeUleb128(os, WASM_OPCODE_I32_ATOMIC_STORE, "i32.atomic.store");
1225       writeMemArg(os, 2, 0);
1226 
1227       // Notify any waiters that memory initialization is complete
1228       writeGetFlagAddress();
1229       writeI32Const(os, -1, "number of waiters");
1230       writeU8(os, WASM_OPCODE_ATOMICS_PREFIX, "atomics prefix");
1231       writeUleb128(os, WASM_OPCODE_ATOMIC_NOTIFY, "atomic.notify");
1232       writeMemArg(os, 2, 0);
1233       writeU8(os, WASM_OPCODE_DROP, "drop");
1234 
1235       // Branch to drop the segments
1236       writeU8(os, WASM_OPCODE_BR, "br");
1237       writeUleb128(os, 1, "label $drop");
1238 
1239       // Wait for the winning thread to initialize memory
1240       writeU8(os, WASM_OPCODE_END, "end $wait");
1241       writeGetFlagAddress();
1242       writeI32Const(os, 1, "expected flag value");
1243       writeI64Const(os, -1, "timeout");
1244 
1245       writeU8(os, WASM_OPCODE_ATOMICS_PREFIX, "atomics prefix");
1246       writeUleb128(os, WASM_OPCODE_I32_ATOMIC_WAIT, "i32.atomic.wait");
1247       writeMemArg(os, 2, 0);
1248       writeU8(os, WASM_OPCODE_DROP, "drop");
1249 
1250       // Unconditionally drop passive data segments
1251       writeU8(os, WASM_OPCODE_END, "end $drop");
1252     }
1253 
1254     for (const OutputSegment *s : segments) {
1255       if (needsPassiveInitialization(s) && !s->isBss) {
1256         // The TLS region should not be dropped since its is needed
1257         // during the initialization of each thread (__wasm_init_tls).
1258         if (config->sharedMemory && s->isTLS())
1259           continue;
1260         // data.drop instruction
1261         writeU8(os, WASM_OPCODE_MISC_PREFIX, "bulk-memory prefix");
1262         writeUleb128(os, WASM_OPCODE_DATA_DROP, "data.drop");
1263         writeUleb128(os, s->index, "segment index immediate");
1264       }
1265     }
1266 
1267     // End the function
1268     writeU8(os, WASM_OPCODE_END, "END");
1269   }
1270 
1271   createFunction(WasmSym::initMemory, bodyContent);
1272 }
1273 
createStartFunction()1274 void Writer::createStartFunction() {
1275   // If the start function exists when we have more than one function to call.
1276   if (WasmSym::initMemory && WasmSym::applyGlobalRelocs) {
1277     assert(WasmSym::startFunction);
1278     std::string bodyContent;
1279     {
1280       raw_string_ostream os(bodyContent);
1281       writeUleb128(os, 0, "num locals");
1282       writeU8(os, WASM_OPCODE_CALL, "CALL");
1283       writeUleb128(os, WasmSym::applyGlobalRelocs->getFunctionIndex(),
1284                    "function index");
1285       writeU8(os, WASM_OPCODE_CALL, "CALL");
1286       writeUleb128(os, WasmSym::initMemory->getFunctionIndex(),
1287                    "function index");
1288       writeU8(os, WASM_OPCODE_END, "END");
1289     }
1290     createFunction(WasmSym::startFunction, bodyContent);
1291   } else if (WasmSym::initMemory) {
1292     WasmSym::startFunction = WasmSym::initMemory;
1293   } else if (WasmSym::applyGlobalRelocs) {
1294     WasmSym::startFunction = WasmSym::applyGlobalRelocs;
1295   }
1296 }
1297 
1298 // For -shared (PIC) output, we create create a synthetic function which will
1299 // apply any relocations to the data segments on startup.  This function is
1300 // called `__wasm_apply_data_relocs` and is expected to be called before
1301 // any user code (i.e. before `__wasm_call_ctors`).
createApplyDataRelocationsFunction()1302 void Writer::createApplyDataRelocationsFunction() {
1303   LLVM_DEBUG(dbgs() << "createApplyDataRelocationsFunction\n");
1304   // First write the body's contents to a string.
1305   std::string bodyContent;
1306   {
1307     raw_string_ostream os(bodyContent);
1308     writeUleb128(os, 0, "num locals");
1309     for (const OutputSegment *seg : segments)
1310       for (const InputChunk *inSeg : seg->inputSegments)
1311         inSeg->generateRelocationCode(os);
1312 
1313     writeU8(os, WASM_OPCODE_END, "END");
1314   }
1315 
1316   createFunction(WasmSym::applyDataRelocs, bodyContent);
1317 }
1318 
1319 // Similar to createApplyDataRelocationsFunction but generates relocation code
1320 // for WebAssembly globals. Because these globals are not shared between threads
1321 // these relocation need to run on every thread.
createApplyGlobalRelocationsFunction()1322 void Writer::createApplyGlobalRelocationsFunction() {
1323   // First write the body's contents to a string.
1324   std::string bodyContent;
1325   {
1326     raw_string_ostream os(bodyContent);
1327     writeUleb128(os, 0, "num locals");
1328     out.globalSec->generateRelocationCode(os, false);
1329     writeU8(os, WASM_OPCODE_END, "END");
1330   }
1331 
1332   createFunction(WasmSym::applyGlobalRelocs, bodyContent);
1333 }
1334 
1335 // Similar to createApplyGlobalRelocationsFunction but for
1336 // TLS symbols.  This cannot be run during the start function
1337 // but must be delayed until __wasm_init_tls is called.
createApplyGlobalTLSRelocationsFunction()1338 void Writer::createApplyGlobalTLSRelocationsFunction() {
1339   // First write the body's contents to a string.
1340   std::string bodyContent;
1341   {
1342     raw_string_ostream os(bodyContent);
1343     writeUleb128(os, 0, "num locals");
1344     out.globalSec->generateRelocationCode(os, true);
1345     writeU8(os, WASM_OPCODE_END, "END");
1346   }
1347 
1348   createFunction(WasmSym::applyGlobalTLSRelocs, bodyContent);
1349 }
1350 
1351 // Create synthetic "__wasm_call_ctors" function based on ctor functions
1352 // in input object.
createCallCtorsFunction()1353 void Writer::createCallCtorsFunction() {
1354   // If __wasm_call_ctors isn't referenced, there aren't any ctors, don't
1355   // define the `__wasm_call_ctors` function.
1356   if (!WasmSym::callCtors->isLive() && initFunctions.empty())
1357     return;
1358 
1359   // First write the body's contents to a string.
1360   std::string bodyContent;
1361   {
1362     raw_string_ostream os(bodyContent);
1363     writeUleb128(os, 0, "num locals");
1364 
1365     // Call constructors
1366     for (const WasmInitEntry &f : initFunctions) {
1367       writeU8(os, WASM_OPCODE_CALL, "CALL");
1368       writeUleb128(os, f.sym->getFunctionIndex(), "function index");
1369       for (size_t i = 0; i < f.sym->signature->Returns.size(); i++) {
1370         writeU8(os, WASM_OPCODE_DROP, "DROP");
1371       }
1372     }
1373 
1374     writeU8(os, WASM_OPCODE_END, "END");
1375   }
1376 
1377   createFunction(WasmSym::callCtors, bodyContent);
1378 }
1379 
1380 // Create a wrapper around a function export which calls the
1381 // static constructors and destructors.
createCommandExportWrapper(uint32_t functionIndex,DefinedFunction * f)1382 void Writer::createCommandExportWrapper(uint32_t functionIndex,
1383                                         DefinedFunction *f) {
1384   // First write the body's contents to a string.
1385   std::string bodyContent;
1386   {
1387     raw_string_ostream os(bodyContent);
1388     writeUleb128(os, 0, "num locals");
1389 
1390     // Call `__wasm_call_ctors` which call static constructors (and
1391     // applies any runtime relocations in Emscripten-style PIC mode)
1392     if (WasmSym::callCtors->isLive()) {
1393       writeU8(os, WASM_OPCODE_CALL, "CALL");
1394       writeUleb128(os, WasmSym::callCtors->getFunctionIndex(),
1395                    "function index");
1396     }
1397 
1398     // Call the user's code, leaving any return values on the operand stack.
1399     for (size_t i = 0; i < f->signature->Params.size(); ++i) {
1400       writeU8(os, WASM_OPCODE_LOCAL_GET, "local.get");
1401       writeUleb128(os, i, "local index");
1402     }
1403     writeU8(os, WASM_OPCODE_CALL, "CALL");
1404     writeUleb128(os, functionIndex, "function index");
1405 
1406     // Call the function that calls the destructors.
1407     if (DefinedFunction *callDtors = WasmSym::callDtors) {
1408       writeU8(os, WASM_OPCODE_CALL, "CALL");
1409       writeUleb128(os, callDtors->getFunctionIndex(), "function index");
1410     }
1411 
1412     // End the function, returning the return values from the user's code.
1413     writeU8(os, WASM_OPCODE_END, "END");
1414   }
1415 
1416   createFunction(f, bodyContent);
1417 }
1418 
createInitTLSFunction()1419 void Writer::createInitTLSFunction() {
1420   std::string bodyContent;
1421   {
1422     raw_string_ostream os(bodyContent);
1423 
1424     OutputSegment *tlsSeg = nullptr;
1425     for (auto *seg : segments) {
1426       if (seg->name == ".tdata") {
1427         tlsSeg = seg;
1428         break;
1429       }
1430     }
1431 
1432     writeUleb128(os, 0, "num locals");
1433     if (tlsSeg) {
1434       writeU8(os, WASM_OPCODE_LOCAL_GET, "local.get");
1435       writeUleb128(os, 0, "local index");
1436 
1437       writeU8(os, WASM_OPCODE_GLOBAL_SET, "global.set");
1438       writeUleb128(os, WasmSym::tlsBase->getGlobalIndex(), "global index");
1439 
1440       // FIXME(wvo): this local needs to be I64 in wasm64, or we need an extend op.
1441       writeU8(os, WASM_OPCODE_LOCAL_GET, "local.get");
1442       writeUleb128(os, 0, "local index");
1443 
1444       writeI32Const(os, 0, "segment offset");
1445 
1446       writeI32Const(os, tlsSeg->size, "memory region size");
1447 
1448       writeU8(os, WASM_OPCODE_MISC_PREFIX, "bulk-memory prefix");
1449       writeUleb128(os, WASM_OPCODE_MEMORY_INIT, "MEMORY.INIT");
1450       writeUleb128(os, tlsSeg->index, "segment index immediate");
1451       writeU8(os, 0, "memory index immediate");
1452     }
1453 
1454     if (WasmSym::applyGlobalTLSRelocs) {
1455       writeU8(os, WASM_OPCODE_CALL, "CALL");
1456       writeUleb128(os, WasmSym::applyGlobalTLSRelocs->getFunctionIndex(),
1457                    "function index");
1458     }
1459     writeU8(os, WASM_OPCODE_END, "end function");
1460   }
1461 
1462   createFunction(WasmSym::initTLS, bodyContent);
1463 }
1464 
1465 // Populate InitFunctions vector with init functions from all input objects.
1466 // This is then used either when creating the output linking section or to
1467 // synthesize the "__wasm_call_ctors" function.
calculateInitFunctions()1468 void Writer::calculateInitFunctions() {
1469   if (!config->relocatable && !WasmSym::callCtors->isLive())
1470     return;
1471 
1472   for (ObjFile *file : symtab->objectFiles) {
1473     const WasmLinkingData &l = file->getWasmObj()->linkingData();
1474     for (const WasmInitFunc &f : l.InitFunctions) {
1475       FunctionSymbol *sym = file->getFunctionSymbol(f.Symbol);
1476       // comdat exclusions can cause init functions be discarded.
1477       if (sym->isDiscarded() || !sym->isLive())
1478         continue;
1479       if (sym->signature->Params.size() != 0)
1480         error("constructor functions cannot take arguments: " + toString(*sym));
1481       LLVM_DEBUG(dbgs() << "initFunctions: " << toString(*sym) << "\n");
1482       initFunctions.emplace_back(WasmInitEntry{sym, f.Priority});
1483     }
1484   }
1485 
1486   // Sort in order of priority (lowest first) so that they are called
1487   // in the correct order.
1488   llvm::stable_sort(initFunctions,
1489                     [](const WasmInitEntry &l, const WasmInitEntry &r) {
1490                       return l.priority < r.priority;
1491                     });
1492 }
1493 
createSyntheticSections()1494 void Writer::createSyntheticSections() {
1495   out.dylinkSec = make<DylinkSection>();
1496   out.typeSec = make<TypeSection>();
1497   out.importSec = make<ImportSection>();
1498   out.functionSec = make<FunctionSection>();
1499   out.tableSec = make<TableSection>();
1500   out.memorySec = make<MemorySection>();
1501   out.tagSec = make<TagSection>();
1502   out.globalSec = make<GlobalSection>();
1503   out.exportSec = make<ExportSection>();
1504   out.startSec = make<StartSection>();
1505   out.elemSec = make<ElemSection>();
1506   out.producersSec = make<ProducersSection>();
1507   out.targetFeaturesSec = make<TargetFeaturesSection>();
1508 }
1509 
createSyntheticSectionsPostLayout()1510 void Writer::createSyntheticSectionsPostLayout() {
1511   out.dataCountSec = make<DataCountSection>(segments);
1512   out.linkingSec = make<LinkingSection>(initFunctions, segments);
1513   out.nameSec = make<NameSection>(segments);
1514 }
1515 
run()1516 void Writer::run() {
1517   if (config->relocatable || config->isPic)
1518     config->globalBase = 0;
1519 
1520   // For PIC code the table base is assigned dynamically by the loader.
1521   // For non-PIC, we start at 1 so that accessing table index 0 always traps.
1522   if (!config->isPic) {
1523     config->tableBase = 1;
1524     if (WasmSym::definedTableBase)
1525       WasmSym::definedTableBase->setVA(config->tableBase);
1526     if (WasmSym::definedTableBase32)
1527       WasmSym::definedTableBase32->setVA(config->tableBase);
1528   }
1529 
1530   log("-- createOutputSegments");
1531   createOutputSegments();
1532   log("-- createSyntheticSections");
1533   createSyntheticSections();
1534   log("-- layoutMemory");
1535   layoutMemory();
1536 
1537   if (!config->relocatable) {
1538     // Create linker synthesized __start_SECNAME/__stop_SECNAME symbols
1539     // This has to be done after memory layout is performed.
1540     for (const OutputSegment *seg : segments) {
1541       addStartStopSymbols(seg);
1542     }
1543   }
1544 
1545   for (auto &pair : config->exportedSymbols) {
1546     Symbol *sym = symtab->find(pair.first());
1547     if (sym && sym->isDefined())
1548       sym->forceExport = true;
1549   }
1550 
1551   // Delay reporting error about explicit exports until after
1552   // addStartStopSymbols which can create optional symbols.
1553   for (auto &name : config->requiredExports) {
1554     Symbol *sym = symtab->find(name);
1555     if (!sym || !sym->isDefined()) {
1556       if (config->unresolvedSymbols == UnresolvedPolicy::ReportError)
1557         error(Twine("symbol exported via --export not found: ") + name);
1558       if (config->unresolvedSymbols == UnresolvedPolicy::Warn)
1559         warn(Twine("symbol exported via --export not found: ") + name);
1560     }
1561   }
1562 
1563   log("-- populateTargetFeatures");
1564   populateTargetFeatures();
1565 
1566   // When outputting PIC code each segment lives at at fixes offset from the
1567   // `__memory_base` import.  Unless we support the extended const expression we
1568   // can't do addition inside the constant expression, so we much combine the
1569   // segments into a single one that can live at `__memory_base`.
1570   if (config->isPic && !config->extendedConst && !config->sharedMemory) {
1571     // In shared memory mode all data segments are passive and initialized
1572     // via __wasm_init_memory.
1573     log("-- combineOutputSegments");
1574     combineOutputSegments();
1575   }
1576 
1577   log("-- createSyntheticSectionsPostLayout");
1578   createSyntheticSectionsPostLayout();
1579   log("-- populateProducers");
1580   populateProducers();
1581   log("-- calculateImports");
1582   calculateImports();
1583   log("-- scanRelocations");
1584   scanRelocations();
1585   log("-- finalizeIndirectFunctionTable");
1586   finalizeIndirectFunctionTable();
1587   log("-- createSyntheticInitFunctions");
1588   createSyntheticInitFunctions();
1589   log("-- assignIndexes");
1590   assignIndexes();
1591   log("-- calculateInitFunctions");
1592   calculateInitFunctions();
1593 
1594   if (!config->relocatable) {
1595     // Create linker synthesized functions
1596     if (WasmSym::applyDataRelocs)
1597       createApplyDataRelocationsFunction();
1598     if (WasmSym::applyGlobalRelocs)
1599       createApplyGlobalRelocationsFunction();
1600     if (WasmSym::applyGlobalTLSRelocs)
1601       createApplyGlobalTLSRelocationsFunction();
1602     if (WasmSym::initMemory)
1603       createInitMemoryFunction();
1604     createStartFunction();
1605 
1606     createCallCtorsFunction();
1607 
1608     // Create export wrappers for commands if needed.
1609     //
1610     // If the input contains a call to `__wasm_call_ctors`, either in one of
1611     // the input objects or an explicit export from the command-line, we
1612     // assume ctors and dtors are taken care of already.
1613     if (!config->relocatable && !config->isPic &&
1614         !WasmSym::callCtors->isUsedInRegularObj &&
1615         !WasmSym::callCtors->isExported()) {
1616       log("-- createCommandExportWrappers");
1617       createCommandExportWrappers();
1618     }
1619   }
1620 
1621   if (WasmSym::initTLS && WasmSym::initTLS->isLive()) {
1622     log("-- createInitTLSFunction");
1623     createInitTLSFunction();
1624   }
1625 
1626   if (errorCount())
1627     return;
1628 
1629   log("-- calculateTypes");
1630   calculateTypes();
1631   log("-- calculateExports");
1632   calculateExports();
1633   log("-- calculateCustomSections");
1634   calculateCustomSections();
1635   log("-- populateSymtab");
1636   populateSymtab();
1637   log("-- checkImportExportTargetFeatures");
1638   checkImportExportTargetFeatures();
1639   log("-- addSections");
1640   addSections();
1641 
1642   if (errorHandler().verbose) {
1643     log("Defined Functions: " + Twine(out.functionSec->inputFunctions.size()));
1644     log("Defined Globals  : " + Twine(out.globalSec->numGlobals()));
1645     log("Defined Tags     : " + Twine(out.tagSec->inputTags.size()));
1646     log("Defined Tables   : " + Twine(out.tableSec->inputTables.size()));
1647     log("Function Imports : " +
1648         Twine(out.importSec->getNumImportedFunctions()));
1649     log("Global Imports   : " + Twine(out.importSec->getNumImportedGlobals()));
1650     log("Tag Imports      : " + Twine(out.importSec->getNumImportedTags()));
1651     log("Table Imports    : " + Twine(out.importSec->getNumImportedTables()));
1652   }
1653 
1654   createHeader();
1655   log("-- finalizeSections");
1656   finalizeSections();
1657 
1658   log("-- writeMapFile");
1659   writeMapFile(outputSections);
1660 
1661   log("-- openFile");
1662   openFile();
1663   if (errorCount())
1664     return;
1665 
1666   writeHeader();
1667 
1668   log("-- writeSections");
1669   writeSections();
1670   if (errorCount())
1671     return;
1672 
1673   if (Error e = buffer->commit())
1674     fatal("failed to write the output file: " + toString(std::move(e)));
1675 }
1676 
1677 // Open a result file.
openFile()1678 void Writer::openFile() {
1679   log("writing: " + config->outputFile);
1680 
1681   Expected<std::unique_ptr<FileOutputBuffer>> bufferOrErr =
1682       FileOutputBuffer::create(config->outputFile, fileSize,
1683                                FileOutputBuffer::F_executable);
1684 
1685   if (!bufferOrErr)
1686     error("failed to open " + config->outputFile + ": " +
1687           toString(bufferOrErr.takeError()));
1688   else
1689     buffer = std::move(*bufferOrErr);
1690 }
1691 
createHeader()1692 void Writer::createHeader() {
1693   raw_string_ostream os(header);
1694   writeBytes(os, WasmMagic, sizeof(WasmMagic), "wasm magic");
1695   writeU32(os, WasmVersion, "wasm version");
1696   os.flush();
1697   fileSize += header.size();
1698 }
1699 
writeResult()1700 void writeResult() { Writer().run(); }
1701 
1702 } // namespace wasm
1703 } // namespace lld
1704