Revert "[libc] Use best-fit binary trie to make malloc logarithmic" (#117065)
[llvm-project.git] / lld / wasm / SyntheticSections.cpp
blob1454c3324af989d8bd995847451431d22e6cfd13
1 //===- SyntheticSections.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 // This file contains linker-synthesized sections.
11 //===----------------------------------------------------------------------===//
13 #include "SyntheticSections.h"
15 #include "InputChunks.h"
16 #include "InputElement.h"
17 #include "OutputSegment.h"
18 #include "SymbolTable.h"
19 #include "llvm/Support/Path.h"
20 #include <optional>
22 using namespace llvm;
23 using namespace llvm::wasm;
25 namespace lld::wasm {
27 OutStruct out;
29 namespace {
31 // Some synthetic sections (e.g. "name" and "linking") have subsections.
32 // Just like the synthetic sections themselves these need to be created before
33 // they can be written out (since they are preceded by their length). This
34 // class is used to create subsections and then write them into the stream
35 // of the parent section.
36 class SubSection {
37 public:
38 explicit SubSection(uint32_t type) : type(type) {}
40 void writeTo(raw_ostream &to) {
41 writeUleb128(to, type, "subsection type");
42 writeUleb128(to, body.size(), "subsection size");
43 to.write(body.data(), body.size());
46 private:
47 uint32_t type;
48 std::string body;
50 public:
51 raw_string_ostream os{body};
54 } // namespace
56 bool DylinkSection::isNeeded() const {
57 return ctx.isPic ||
58 config->unresolvedSymbols == UnresolvedPolicy::ImportDynamic ||
59 !ctx.sharedFiles.empty();
62 void DylinkSection::writeBody() {
63 raw_ostream &os = bodyOutputStream;
66 SubSection sub(WASM_DYLINK_MEM_INFO);
67 writeUleb128(sub.os, memSize, "MemSize");
68 writeUleb128(sub.os, memAlign, "MemAlign");
69 writeUleb128(sub.os, out.elemSec->numEntries(), "TableSize");
70 writeUleb128(sub.os, 0, "TableAlign");
71 sub.writeTo(os);
74 if (ctx.sharedFiles.size()) {
75 SubSection sub(WASM_DYLINK_NEEDED);
76 writeUleb128(sub.os, ctx.sharedFiles.size(), "Needed");
77 for (auto *so : ctx.sharedFiles)
78 writeStr(sub.os, llvm::sys::path::filename(so->getName()), "so name");
79 sub.writeTo(os);
82 // Under certain circumstances we need to include extra information about our
83 // exports and/or imports to the dynamic linker.
84 // For exports we need to notify the linker when an export is TLS since the
85 // exported value is relative to __tls_base rather than __memory_base.
86 // For imports we need to notify the dynamic linker when an import is weak
87 // so that knows not to report an error for such symbols.
88 std::vector<const Symbol *> importInfo;
89 std::vector<const Symbol *> exportInfo;
90 for (const Symbol *sym : symtab->symbols()) {
91 if (sym->isLive()) {
92 if (sym->isExported() && sym->isTLS() && isa<DefinedData>(sym)) {
93 exportInfo.push_back(sym);
95 if (sym->isUndefWeak()) {
96 importInfo.push_back(sym);
101 if (!exportInfo.empty()) {
102 SubSection sub(WASM_DYLINK_EXPORT_INFO);
103 writeUleb128(sub.os, exportInfo.size(), "num exports");
105 for (const Symbol *sym : exportInfo) {
106 LLVM_DEBUG(llvm::dbgs() << "export info: " << toString(*sym) << "\n");
107 StringRef name = sym->getName();
108 if (auto *f = dyn_cast<DefinedFunction>(sym)) {
109 if (std::optional<StringRef> exportName =
110 f->function->getExportName()) {
111 name = *exportName;
114 writeStr(sub.os, name, "sym name");
115 writeUleb128(sub.os, sym->flags, "sym flags");
118 sub.writeTo(os);
121 if (!importInfo.empty()) {
122 SubSection sub(WASM_DYLINK_IMPORT_INFO);
123 writeUleb128(sub.os, importInfo.size(), "num imports");
125 for (const Symbol *sym : importInfo) {
126 LLVM_DEBUG(llvm::dbgs() << "imports info: " << toString(*sym) << "\n");
127 StringRef module = sym->importModule.value_or(defaultModule);
128 StringRef name = sym->importName.value_or(sym->getName());
129 writeStr(sub.os, module, "import module");
130 writeStr(sub.os, name, "import name");
131 writeUleb128(sub.os, sym->flags, "sym flags");
134 sub.writeTo(os);
138 uint32_t TypeSection::registerType(const WasmSignature &sig) {
139 auto pair = typeIndices.insert(std::make_pair(sig, types.size()));
140 if (pair.second) {
141 LLVM_DEBUG(llvm::dbgs() << "registerType " << toString(sig) << "\n");
142 types.push_back(&sig);
144 return pair.first->second;
147 uint32_t TypeSection::lookupType(const WasmSignature &sig) {
148 auto it = typeIndices.find(sig);
149 if (it == typeIndices.end()) {
150 error("type not found: " + toString(sig));
151 return 0;
153 return it->second;
156 void TypeSection::writeBody() {
157 writeUleb128(bodyOutputStream, types.size(), "type count");
158 for (const WasmSignature *sig : types)
159 writeSig(bodyOutputStream, *sig);
162 uint32_t ImportSection::getNumImports() const {
163 assert(isSealed);
164 uint32_t numImports = importedSymbols.size() + gotSymbols.size();
165 if (config->memoryImport.has_value())
166 ++numImports;
167 return numImports;
170 void ImportSection::addGOTEntry(Symbol *sym) {
171 assert(!isSealed);
172 if (sym->hasGOTIndex())
173 return;
174 LLVM_DEBUG(dbgs() << "addGOTEntry: " << toString(*sym) << "\n");
175 sym->setGOTIndex(numImportedGlobals++);
176 if (ctx.isPic) {
177 // Any symbol that is assigned an normal GOT entry must be exported
178 // otherwise the dynamic linker won't be able create the entry that contains
179 // it.
180 sym->forceExport = true;
182 gotSymbols.push_back(sym);
185 void ImportSection::addImport(Symbol *sym) {
186 assert(!isSealed);
187 StringRef module = sym->importModule.value_or(defaultModule);
188 StringRef name = sym->importName.value_or(sym->getName());
189 if (auto *f = dyn_cast<FunctionSymbol>(sym)) {
190 ImportKey<WasmSignature> key(*(f->getSignature()), module, name);
191 auto entry = importedFunctions.try_emplace(key, numImportedFunctions);
192 if (entry.second) {
193 importedSymbols.emplace_back(sym);
194 f->setFunctionIndex(numImportedFunctions++);
195 } else {
196 f->setFunctionIndex(entry.first->second);
198 } else if (auto *g = dyn_cast<GlobalSymbol>(sym)) {
199 ImportKey<WasmGlobalType> key(*(g->getGlobalType()), module, name);
200 auto entry = importedGlobals.try_emplace(key, numImportedGlobals);
201 if (entry.second) {
202 importedSymbols.emplace_back(sym);
203 g->setGlobalIndex(numImportedGlobals++);
204 } else {
205 g->setGlobalIndex(entry.first->second);
207 } else if (auto *t = dyn_cast<TagSymbol>(sym)) {
208 ImportKey<WasmSignature> key(*(t->getSignature()), module, name);
209 auto entry = importedTags.try_emplace(key, numImportedTags);
210 if (entry.second) {
211 importedSymbols.emplace_back(sym);
212 t->setTagIndex(numImportedTags++);
213 } else {
214 t->setTagIndex(entry.first->second);
216 } else {
217 assert(TableSymbol::classof(sym));
218 auto *table = cast<TableSymbol>(sym);
219 ImportKey<WasmTableType> key(*(table->getTableType()), module, name);
220 auto entry = importedTables.try_emplace(key, numImportedTables);
221 if (entry.second) {
222 importedSymbols.emplace_back(sym);
223 table->setTableNumber(numImportedTables++);
224 } else {
225 table->setTableNumber(entry.first->second);
230 void ImportSection::writeBody() {
231 raw_ostream &os = bodyOutputStream;
233 writeUleb128(os, getNumImports(), "import count");
235 bool is64 = config->is64.value_or(false);
237 if (config->memoryImport) {
238 WasmImport import;
239 import.Module = config->memoryImport->first;
240 import.Field = config->memoryImport->second;
241 import.Kind = WASM_EXTERNAL_MEMORY;
242 import.Memory.Flags = 0;
243 import.Memory.Minimum = out.memorySec->numMemoryPages;
244 if (out.memorySec->maxMemoryPages != 0 || config->sharedMemory) {
245 import.Memory.Flags |= WASM_LIMITS_FLAG_HAS_MAX;
246 import.Memory.Maximum = out.memorySec->maxMemoryPages;
248 if (config->sharedMemory)
249 import.Memory.Flags |= WASM_LIMITS_FLAG_IS_SHARED;
250 if (is64)
251 import.Memory.Flags |= WASM_LIMITS_FLAG_IS_64;
252 writeImport(os, import);
255 for (const Symbol *sym : importedSymbols) {
256 WasmImport import;
257 import.Field = sym->importName.value_or(sym->getName());
258 import.Module = sym->importModule.value_or(defaultModule);
260 if (auto *functionSym = dyn_cast<FunctionSymbol>(sym)) {
261 import.Kind = WASM_EXTERNAL_FUNCTION;
262 import.SigIndex = out.typeSec->lookupType(*functionSym->signature);
263 } else if (auto *globalSym = dyn_cast<GlobalSymbol>(sym)) {
264 import.Kind = WASM_EXTERNAL_GLOBAL;
265 import.Global = *globalSym->getGlobalType();
266 } else if (auto *tagSym = dyn_cast<TagSymbol>(sym)) {
267 import.Kind = WASM_EXTERNAL_TAG;
268 import.SigIndex = out.typeSec->lookupType(*tagSym->signature);
269 } else {
270 auto *tableSym = cast<TableSymbol>(sym);
271 import.Kind = WASM_EXTERNAL_TABLE;
272 import.Table = *tableSym->getTableType();
274 writeImport(os, import);
277 for (const Symbol *sym : gotSymbols) {
278 WasmImport import;
279 import.Kind = WASM_EXTERNAL_GLOBAL;
280 auto ptrType = is64 ? WASM_TYPE_I64 : WASM_TYPE_I32;
281 import.Global = {static_cast<uint8_t>(ptrType), true};
282 if (isa<DataSymbol>(sym))
283 import.Module = "GOT.mem";
284 else
285 import.Module = "GOT.func";
286 import.Field = sym->getName();
287 writeImport(os, import);
291 void FunctionSection::writeBody() {
292 raw_ostream &os = bodyOutputStream;
294 writeUleb128(os, inputFunctions.size(), "function count");
295 for (const InputFunction *func : inputFunctions)
296 writeUleb128(os, out.typeSec->lookupType(func->signature), "sig index");
299 void FunctionSection::addFunction(InputFunction *func) {
300 if (!func->live)
301 return;
302 uint32_t functionIndex =
303 out.importSec->getNumImportedFunctions() + inputFunctions.size();
304 inputFunctions.emplace_back(func);
305 func->setFunctionIndex(functionIndex);
308 void TableSection::writeBody() {
309 raw_ostream &os = bodyOutputStream;
311 writeUleb128(os, inputTables.size(), "table count");
312 for (const InputTable *table : inputTables)
313 writeTableType(os, table->getType());
316 void TableSection::addTable(InputTable *table) {
317 if (!table->live)
318 return;
319 // Some inputs require that the indirect function table be assigned to table
320 // number 0.
321 if (ctx.legacyFunctionTable &&
322 isa<DefinedTable>(WasmSym::indirectFunctionTable) &&
323 cast<DefinedTable>(WasmSym::indirectFunctionTable)->table == table) {
324 if (out.importSec->getNumImportedTables()) {
325 // Alack! Some other input imported a table, meaning that we are unable
326 // to assign table number 0 to the indirect function table.
327 for (const auto *culprit : out.importSec->importedSymbols) {
328 if (isa<UndefinedTable>(culprit)) {
329 error("object file not built with 'reference-types' feature "
330 "conflicts with import of table " +
331 culprit->getName() + " by file " +
332 toString(culprit->getFile()));
333 return;
336 llvm_unreachable("failed to find conflicting table import");
338 inputTables.insert(inputTables.begin(), table);
339 return;
341 inputTables.push_back(table);
344 void TableSection::assignIndexes() {
345 uint32_t tableNumber = out.importSec->getNumImportedTables();
346 for (InputTable *t : inputTables)
347 t->assignIndex(tableNumber++);
350 void MemorySection::writeBody() {
351 raw_ostream &os = bodyOutputStream;
353 bool hasMax = maxMemoryPages != 0 || config->sharedMemory;
354 writeUleb128(os, 1, "memory count");
355 unsigned flags = 0;
356 if (hasMax)
357 flags |= WASM_LIMITS_FLAG_HAS_MAX;
358 if (config->sharedMemory)
359 flags |= WASM_LIMITS_FLAG_IS_SHARED;
360 if (config->is64.value_or(false))
361 flags |= WASM_LIMITS_FLAG_IS_64;
362 writeUleb128(os, flags, "memory limits flags");
363 writeUleb128(os, numMemoryPages, "initial pages");
364 if (hasMax)
365 writeUleb128(os, maxMemoryPages, "max pages");
368 void TagSection::writeBody() {
369 raw_ostream &os = bodyOutputStream;
371 writeUleb128(os, inputTags.size(), "tag count");
372 for (InputTag *t : inputTags) {
373 writeUleb128(os, 0, "tag attribute"); // Reserved "attribute" field
374 writeUleb128(os, out.typeSec->lookupType(t->signature), "sig index");
378 void TagSection::addTag(InputTag *tag) {
379 if (!tag->live)
380 return;
381 uint32_t tagIndex = out.importSec->getNumImportedTags() + inputTags.size();
382 LLVM_DEBUG(dbgs() << "addTag: " << tagIndex << "\n");
383 tag->assignIndex(tagIndex);
384 inputTags.push_back(tag);
387 void GlobalSection::assignIndexes() {
388 uint32_t globalIndex = out.importSec->getNumImportedGlobals();
389 for (InputGlobal *g : inputGlobals)
390 g->assignIndex(globalIndex++);
391 for (Symbol *sym : internalGotSymbols)
392 sym->setGOTIndex(globalIndex++);
393 isSealed = true;
396 static void ensureIndirectFunctionTable() {
397 if (!WasmSym::indirectFunctionTable)
398 WasmSym::indirectFunctionTable =
399 symtab->resolveIndirectFunctionTable(/*required =*/true);
402 void GlobalSection::addInternalGOTEntry(Symbol *sym) {
403 assert(!isSealed);
404 if (sym->requiresGOT)
405 return;
406 LLVM_DEBUG(dbgs() << "addInternalGOTEntry: " << sym->getName() << " "
407 << toString(sym->kind()) << "\n");
408 sym->requiresGOT = true;
409 if (auto *F = dyn_cast<FunctionSymbol>(sym)) {
410 ensureIndirectFunctionTable();
411 out.elemSec->addEntry(F);
413 internalGotSymbols.push_back(sym);
416 void GlobalSection::generateRelocationCode(raw_ostream &os, bool TLS) const {
417 assert(!config->extendedConst);
418 bool is64 = config->is64.value_or(false);
419 unsigned opcode_ptr_const = is64 ? WASM_OPCODE_I64_CONST
420 : WASM_OPCODE_I32_CONST;
421 unsigned opcode_ptr_add = is64 ? WASM_OPCODE_I64_ADD
422 : WASM_OPCODE_I32_ADD;
424 for (const Symbol *sym : internalGotSymbols) {
425 if (TLS != sym->isTLS())
426 continue;
428 if (auto *d = dyn_cast<DefinedData>(sym)) {
429 // Get __memory_base
430 writeU8(os, WASM_OPCODE_GLOBAL_GET, "GLOBAL_GET");
431 if (sym->isTLS())
432 writeUleb128(os, WasmSym::tlsBase->getGlobalIndex(), "__tls_base");
433 else
434 writeUleb128(os, WasmSym::memoryBase->getGlobalIndex(),
435 "__memory_base");
437 // Add the virtual address of the data symbol
438 writeU8(os, opcode_ptr_const, "CONST");
439 writeSleb128(os, d->getVA(), "offset");
440 } else if (auto *f = dyn_cast<FunctionSymbol>(sym)) {
441 if (f->isStub)
442 continue;
443 // Get __table_base
444 writeU8(os, WASM_OPCODE_GLOBAL_GET, "GLOBAL_GET");
445 writeUleb128(os, WasmSym::tableBase->getGlobalIndex(), "__table_base");
447 // Add the table index to __table_base
448 writeU8(os, opcode_ptr_const, "CONST");
449 writeSleb128(os, f->getTableIndex(), "offset");
450 } else {
451 assert(isa<UndefinedData>(sym) || isa<SharedData>(sym));
452 continue;
454 writeU8(os, opcode_ptr_add, "ADD");
455 writeU8(os, WASM_OPCODE_GLOBAL_SET, "GLOBAL_SET");
456 writeUleb128(os, sym->getGOTIndex(), "got_entry");
460 void GlobalSection::writeBody() {
461 raw_ostream &os = bodyOutputStream;
463 writeUleb128(os, numGlobals(), "global count");
464 for (InputGlobal *g : inputGlobals) {
465 writeGlobalType(os, g->getType());
466 writeInitExpr(os, g->getInitExpr());
468 bool is64 = config->is64.value_or(false);
469 uint8_t itype = is64 ? WASM_TYPE_I64 : WASM_TYPE_I32;
470 for (const Symbol *sym : internalGotSymbols) {
471 bool mutable_ = false;
472 if (!sym->isStub) {
473 // In the case of dynamic linking, unless we have 'extended-const'
474 // available, these global must to be mutable since they get updated to
475 // the correct runtime value during `__wasm_apply_global_relocs`.
476 if (!config->extendedConst && ctx.isPic && !sym->isTLS())
477 mutable_ = true;
478 // With multi-theadeding any TLS globals must be mutable since they get
479 // set during `__wasm_apply_global_tls_relocs`
480 if (config->sharedMemory && sym->isTLS())
481 mutable_ = true;
483 WasmGlobalType type{itype, mutable_};
484 writeGlobalType(os, type);
486 bool useExtendedConst = false;
487 uint32_t globalIdx;
488 int64_t offset;
489 if (config->extendedConst && ctx.isPic) {
490 if (auto *d = dyn_cast<DefinedData>(sym)) {
491 if (!sym->isTLS()) {
492 globalIdx = WasmSym::memoryBase->getGlobalIndex();
493 offset = d->getVA();
494 useExtendedConst = true;
496 } else if (auto *f = dyn_cast<FunctionSymbol>(sym)) {
497 if (!sym->isStub) {
498 globalIdx = WasmSym::tableBase->getGlobalIndex();
499 offset = f->getTableIndex();
500 useExtendedConst = true;
504 if (useExtendedConst) {
505 // We can use an extended init expression to add a constant
506 // offset of __memory_base/__table_base.
507 writeU8(os, WASM_OPCODE_GLOBAL_GET, "global get");
508 writeUleb128(os, globalIdx, "literal (global index)");
509 if (offset) {
510 writePtrConst(os, offset, is64, "offset");
511 writeU8(os, is64 ? WASM_OPCODE_I64_ADD : WASM_OPCODE_I32_ADD, "add");
513 writeU8(os, WASM_OPCODE_END, "opcode:end");
514 } else {
515 WasmInitExpr initExpr;
516 if (auto *d = dyn_cast<DefinedData>(sym))
517 // In the sharedMemory case TLS globals are set during
518 // `__wasm_apply_global_tls_relocs`, but in the non-shared case
519 // we know the absolute value at link time.
520 initExpr = intConst(d->getVA(/*absolute=*/!config->sharedMemory), is64);
521 else if (auto *f = dyn_cast<FunctionSymbol>(sym))
522 initExpr = intConst(f->isStub ? 0 : f->getTableIndex(), is64);
523 else {
524 assert(isa<UndefinedData>(sym) || isa<SharedData>(sym));
525 initExpr = intConst(0, is64);
527 writeInitExpr(os, initExpr);
530 for (const DefinedData *sym : dataAddressGlobals) {
531 WasmGlobalType type{itype, false};
532 writeGlobalType(os, type);
533 writeInitExpr(os, intConst(sym->getVA(), is64));
537 void GlobalSection::addGlobal(InputGlobal *global) {
538 assert(!isSealed);
539 if (!global->live)
540 return;
541 inputGlobals.push_back(global);
544 void ExportSection::writeBody() {
545 raw_ostream &os = bodyOutputStream;
547 writeUleb128(os, exports.size(), "export count");
548 for (const WasmExport &export_ : exports)
549 writeExport(os, export_);
552 bool StartSection::isNeeded() const {
553 return WasmSym::startFunction != nullptr;
556 void StartSection::writeBody() {
557 raw_ostream &os = bodyOutputStream;
558 writeUleb128(os, WasmSym::startFunction->getFunctionIndex(),
559 "function index");
562 void ElemSection::addEntry(FunctionSymbol *sym) {
563 // Don't add stub functions to the wasm table. The address of all stub
564 // functions should be zero and they should they don't appear in the table.
565 // They only exist so that the calls to missing functions can validate.
566 if (sym->hasTableIndex() || sym->isStub)
567 return;
568 sym->setTableIndex(config->tableBase + indirectFunctions.size());
569 indirectFunctions.emplace_back(sym);
572 void ElemSection::writeBody() {
573 raw_ostream &os = bodyOutputStream;
575 assert(WasmSym::indirectFunctionTable);
576 writeUleb128(os, 1, "segment count");
577 uint32_t tableNumber = WasmSym::indirectFunctionTable->getTableNumber();
578 uint32_t flags = 0;
579 if (tableNumber)
580 flags |= WASM_ELEM_SEGMENT_HAS_TABLE_NUMBER;
581 writeUleb128(os, flags, "elem segment flags");
582 if (flags & WASM_ELEM_SEGMENT_HAS_TABLE_NUMBER)
583 writeUleb128(os, tableNumber, "table number");
585 WasmInitExpr initExpr;
586 initExpr.Extended = false;
587 if (ctx.isPic) {
588 initExpr.Inst.Opcode = WASM_OPCODE_GLOBAL_GET;
589 initExpr.Inst.Value.Global = WasmSym::tableBase->getGlobalIndex();
590 } else {
591 bool is64 = config->is64.value_or(false);
592 initExpr = intConst(config->tableBase, is64);
594 writeInitExpr(os, initExpr);
596 if (flags & WASM_ELEM_SEGMENT_MASK_HAS_ELEM_KIND) {
597 // We only write active function table initializers, for which the elem kind
598 // is specified to be written as 0x00 and interpreted to mean "funcref".
599 const uint8_t elemKind = 0;
600 writeU8(os, elemKind, "elem kind");
603 writeUleb128(os, indirectFunctions.size(), "elem count");
604 uint32_t tableIndex = config->tableBase;
605 for (const FunctionSymbol *sym : indirectFunctions) {
606 assert(sym->getTableIndex() == tableIndex);
607 (void) tableIndex;
608 writeUleb128(os, sym->getFunctionIndex(), "function index");
609 ++tableIndex;
613 DataCountSection::DataCountSection(ArrayRef<OutputSegment *> segments)
614 : SyntheticSection(llvm::wasm::WASM_SEC_DATACOUNT),
615 numSegments(llvm::count_if(segments, [](OutputSegment *const segment) {
616 return segment->requiredInBinary();
617 })) {}
619 void DataCountSection::writeBody() {
620 writeUleb128(bodyOutputStream, numSegments, "data count");
623 bool DataCountSection::isNeeded() const {
624 return numSegments && config->sharedMemory;
627 void LinkingSection::writeBody() {
628 raw_ostream &os = bodyOutputStream;
630 writeUleb128(os, WasmMetadataVersion, "Version");
632 if (!symtabEntries.empty()) {
633 SubSection sub(WASM_SYMBOL_TABLE);
634 writeUleb128(sub.os, symtabEntries.size(), "num symbols");
636 for (const Symbol *sym : symtabEntries) {
637 assert(sym->isDefined() || sym->isUndefined());
638 WasmSymbolType kind = sym->getWasmType();
639 uint32_t flags = sym->flags;
641 writeU8(sub.os, kind, "sym kind");
642 writeUleb128(sub.os, flags, "sym flags");
644 if (auto *f = dyn_cast<FunctionSymbol>(sym)) {
645 if (auto *d = dyn_cast<DefinedFunction>(sym)) {
646 writeUleb128(sub.os, d->getExportedFunctionIndex(), "index");
647 } else {
648 writeUleb128(sub.os, f->getFunctionIndex(), "index");
650 if (sym->isDefined() || (flags & WASM_SYMBOL_EXPLICIT_NAME) != 0)
651 writeStr(sub.os, sym->getName(), "sym name");
652 } else if (auto *g = dyn_cast<GlobalSymbol>(sym)) {
653 writeUleb128(sub.os, g->getGlobalIndex(), "index");
654 if (sym->isDefined() || (flags & WASM_SYMBOL_EXPLICIT_NAME) != 0)
655 writeStr(sub.os, sym->getName(), "sym name");
656 } else if (auto *t = dyn_cast<TagSymbol>(sym)) {
657 writeUleb128(sub.os, t->getTagIndex(), "index");
658 if (sym->isDefined() || (flags & WASM_SYMBOL_EXPLICIT_NAME) != 0)
659 writeStr(sub.os, sym->getName(), "sym name");
660 } else if (auto *t = dyn_cast<TableSymbol>(sym)) {
661 writeUleb128(sub.os, t->getTableNumber(), "table number");
662 if (sym->isDefined() || (flags & WASM_SYMBOL_EXPLICIT_NAME) != 0)
663 writeStr(sub.os, sym->getName(), "sym name");
664 } else if (isa<DataSymbol>(sym)) {
665 writeStr(sub.os, sym->getName(), "sym name");
666 if (auto *dataSym = dyn_cast<DefinedData>(sym)) {
667 if (dataSym->segment) {
668 writeUleb128(sub.os, dataSym->getOutputSegmentIndex(), "index");
669 writeUleb128(sub.os, dataSym->getOutputSegmentOffset(),
670 "data offset");
671 } else {
672 writeUleb128(sub.os, 0, "index");
673 writeUleb128(sub.os, dataSym->getVA(), "data offset");
675 writeUleb128(sub.os, dataSym->getSize(), "data size");
677 } else {
678 auto *s = cast<OutputSectionSymbol>(sym);
679 writeUleb128(sub.os, s->section->sectionIndex, "sym section index");
683 sub.writeTo(os);
686 if (dataSegments.size()) {
687 SubSection sub(WASM_SEGMENT_INFO);
688 writeUleb128(sub.os, dataSegments.size(), "num data segments");
689 for (const OutputSegment *s : dataSegments) {
690 writeStr(sub.os, s->name, "segment name");
691 writeUleb128(sub.os, s->alignment, "alignment");
692 writeUleb128(sub.os, s->linkingFlags, "flags");
694 sub.writeTo(os);
697 if (!initFunctions.empty()) {
698 SubSection sub(WASM_INIT_FUNCS);
699 writeUleb128(sub.os, initFunctions.size(), "num init functions");
700 for (const WasmInitEntry &f : initFunctions) {
701 writeUleb128(sub.os, f.priority, "priority");
702 writeUleb128(sub.os, f.sym->getOutputSymbolIndex(), "function index");
704 sub.writeTo(os);
707 struct ComdatEntry {
708 unsigned kind;
709 uint32_t index;
711 std::map<StringRef, std::vector<ComdatEntry>> comdats;
713 for (const InputFunction *f : out.functionSec->inputFunctions) {
714 StringRef comdat = f->getComdatName();
715 if (!comdat.empty())
716 comdats[comdat].emplace_back(
717 ComdatEntry{WASM_COMDAT_FUNCTION, f->getFunctionIndex()});
719 for (uint32_t i = 0; i < dataSegments.size(); ++i) {
720 const auto &inputSegments = dataSegments[i]->inputSegments;
721 if (inputSegments.empty())
722 continue;
723 StringRef comdat = inputSegments[0]->getComdatName();
724 #ifndef NDEBUG
725 for (const InputChunk *isec : inputSegments)
726 assert(isec->getComdatName() == comdat);
727 #endif
728 if (!comdat.empty())
729 comdats[comdat].emplace_back(ComdatEntry{WASM_COMDAT_DATA, i});
732 if (!comdats.empty()) {
733 SubSection sub(WASM_COMDAT_INFO);
734 writeUleb128(sub.os, comdats.size(), "num comdats");
735 for (const auto &c : comdats) {
736 writeStr(sub.os, c.first, "comdat name");
737 writeUleb128(sub.os, 0, "comdat flags"); // flags for future use
738 writeUleb128(sub.os, c.second.size(), "num entries");
739 for (const ComdatEntry &entry : c.second) {
740 writeU8(sub.os, entry.kind, "entry kind");
741 writeUleb128(sub.os, entry.index, "entry index");
744 sub.writeTo(os);
748 void LinkingSection::addToSymtab(Symbol *sym) {
749 sym->setOutputSymbolIndex(symtabEntries.size());
750 symtabEntries.emplace_back(sym);
753 unsigned NameSection::numNamedFunctions() const {
754 unsigned numNames = out.importSec->getNumImportedFunctions();
756 for (const InputFunction *f : out.functionSec->inputFunctions)
757 if (!f->name.empty() || !f->debugName.empty())
758 ++numNames;
760 return numNames;
763 unsigned NameSection::numNamedGlobals() const {
764 unsigned numNames = out.importSec->getNumImportedGlobals();
766 for (const InputGlobal *g : out.globalSec->inputGlobals)
767 if (!g->getName().empty())
768 ++numNames;
770 numNames += out.globalSec->internalGotSymbols.size();
771 return numNames;
774 unsigned NameSection::numNamedDataSegments() const {
775 unsigned numNames = 0;
777 for (const OutputSegment *s : segments)
778 if (!s->name.empty() && s->requiredInBinary())
779 ++numNames;
781 return numNames;
784 // Create the custom "name" section containing debug symbol names.
785 void NameSection::writeBody() {
787 SubSection sub(WASM_NAMES_MODULE);
788 StringRef moduleName = config->soName;
789 if (config->soName.empty())
790 moduleName = llvm::sys::path::filename(config->outputFile);
791 writeStr(sub.os, moduleName, "module name");
792 sub.writeTo(bodyOutputStream);
795 unsigned count = numNamedFunctions();
796 if (count) {
797 SubSection sub(WASM_NAMES_FUNCTION);
798 writeUleb128(sub.os, count, "name count");
800 // Function names appear in function index order. As it happens
801 // importedSymbols and inputFunctions are numbered in order with imported
802 // functions coming first.
803 for (const Symbol *s : out.importSec->importedSymbols) {
804 if (auto *f = dyn_cast<FunctionSymbol>(s)) {
805 writeUleb128(sub.os, f->getFunctionIndex(), "func index");
806 writeStr(sub.os, toString(*s), "symbol name");
809 for (const InputFunction *f : out.functionSec->inputFunctions) {
810 if (!f->name.empty()) {
811 writeUleb128(sub.os, f->getFunctionIndex(), "func index");
812 if (!f->debugName.empty()) {
813 writeStr(sub.os, f->debugName, "symbol name");
814 } else {
815 writeStr(sub.os, maybeDemangleSymbol(f->name), "symbol name");
819 sub.writeTo(bodyOutputStream);
822 count = numNamedGlobals();
823 if (count) {
824 SubSection sub(WASM_NAMES_GLOBAL);
825 writeUleb128(sub.os, count, "name count");
827 for (const Symbol *s : out.importSec->importedSymbols) {
828 if (auto *g = dyn_cast<GlobalSymbol>(s)) {
829 writeUleb128(sub.os, g->getGlobalIndex(), "global index");
830 writeStr(sub.os, toString(*s), "symbol name");
833 for (const Symbol *s : out.importSec->gotSymbols) {
834 writeUleb128(sub.os, s->getGOTIndex(), "global index");
835 writeStr(sub.os, toString(*s), "symbol name");
837 for (const InputGlobal *g : out.globalSec->inputGlobals) {
838 if (!g->getName().empty()) {
839 writeUleb128(sub.os, g->getAssignedIndex(), "global index");
840 writeStr(sub.os, maybeDemangleSymbol(g->getName()), "symbol name");
843 for (Symbol *s : out.globalSec->internalGotSymbols) {
844 writeUleb128(sub.os, s->getGOTIndex(), "global index");
845 if (isa<FunctionSymbol>(s))
846 writeStr(sub.os, "GOT.func.internal." + toString(*s), "symbol name");
847 else
848 writeStr(sub.os, "GOT.data.internal." + toString(*s), "symbol name");
851 sub.writeTo(bodyOutputStream);
854 count = numNamedDataSegments();
855 if (count) {
856 SubSection sub(WASM_NAMES_DATA_SEGMENT);
857 writeUleb128(sub.os, count, "name count");
859 for (OutputSegment *s : segments) {
860 if (!s->name.empty() && s->requiredInBinary()) {
861 writeUleb128(sub.os, s->index, "global index");
862 writeStr(sub.os, s->name, "segment name");
866 sub.writeTo(bodyOutputStream);
870 void ProducersSection::addInfo(const WasmProducerInfo &info) {
871 for (auto &producers :
872 {std::make_pair(&info.Languages, &languages),
873 std::make_pair(&info.Tools, &tools), std::make_pair(&info.SDKs, &sDKs)})
874 for (auto &producer : *producers.first)
875 if (llvm::none_of(*producers.second,
876 [&](std::pair<std::string, std::string> seen) {
877 return seen.first == producer.first;
879 producers.second->push_back(producer);
882 void ProducersSection::writeBody() {
883 auto &os = bodyOutputStream;
884 writeUleb128(os, fieldCount(), "field count");
885 for (auto &field :
886 {std::make_pair("language", languages),
887 std::make_pair("processed-by", tools), std::make_pair("sdk", sDKs)}) {
888 if (field.second.empty())
889 continue;
890 writeStr(os, field.first, "field name");
891 writeUleb128(os, field.second.size(), "number of entries");
892 for (auto &entry : field.second) {
893 writeStr(os, entry.first, "producer name");
894 writeStr(os, entry.second, "producer version");
899 void TargetFeaturesSection::writeBody() {
900 SmallVector<std::string, 8> emitted(features.begin(), features.end());
901 llvm::sort(emitted);
902 auto &os = bodyOutputStream;
903 writeUleb128(os, emitted.size(), "feature count");
904 for (auto &feature : emitted) {
905 writeU8(os, WASM_FEATURE_PREFIX_USED, "feature used prefix");
906 writeStr(os, feature, "feature name");
910 void RelocSection::writeBody() {
911 uint32_t count = sec->getNumRelocations();
912 assert(sec->sectionIndex != UINT32_MAX);
913 writeUleb128(bodyOutputStream, sec->sectionIndex, "reloc section");
914 writeUleb128(bodyOutputStream, count, "reloc count");
915 sec->writeRelocations(bodyOutputStream);
918 static size_t getHashSize() {
919 switch (config->buildId) {
920 case BuildIdKind::Fast:
921 case BuildIdKind::Uuid:
922 return 16;
923 case BuildIdKind::Sha1:
924 return 20;
925 case BuildIdKind::Hexstring:
926 return config->buildIdVector.size();
927 case BuildIdKind::None:
928 return 0;
930 llvm_unreachable("build id kind not implemented");
933 BuildIdSection::BuildIdSection()
934 : SyntheticSection(llvm::wasm::WASM_SEC_CUSTOM, buildIdSectionName),
935 hashSize(getHashSize()) {}
937 void BuildIdSection::writeBody() {
938 LLVM_DEBUG(llvm::dbgs() << "BuildId writebody\n");
939 // Write hash size
940 auto &os = bodyOutputStream;
941 writeUleb128(os, hashSize, "build id size");
942 writeBytes(os, std::vector<char>(hashSize, ' ').data(), hashSize,
943 "placeholder");
946 void BuildIdSection::writeBuildId(llvm::ArrayRef<uint8_t> buf) {
947 assert(buf.size() == hashSize);
948 LLVM_DEBUG(dbgs() << "buildid write " << buf.size() << " "
949 << hashPlaceholderPtr << '\n');
950 memcpy(hashPlaceholderPtr, buf.data(), hashSize);
953 } // namespace wasm::lld