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