blob: 45abb3e8dcaa2c6f08e75b1c96747db21ed0bc04 [file] [log] [blame]
Sam Cleggc94d3932017-11-17 18:14:09 +00001//===- Writer.cpp ---------------------------------------------------------===//
2//
3// The LLVM Linker
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "Writer.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000011#include "Config.h"
Sam Clegg5fa274b2018-01-10 01:13:34 +000012#include "InputChunks.h"
Sam Clegg93102972018-02-23 05:08:53 +000013#include "InputGlobal.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000014#include "OutputSections.h"
15#include "OutputSegment.h"
16#include "SymbolTable.h"
17#include "WriterUtils.h"
18#include "lld/Common/ErrorHandler.h"
Rui Ueyama2017d522017-11-28 20:39:17 +000019#include "lld/Common/Memory.h"
Nicholas Wilson8269f372018-03-07 10:37:50 +000020#include "lld/Common/Strings.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000021#include "lld/Common/Threads.h"
Sam Clegg3141ddc2018-02-20 21:53:18 +000022#include "llvm/ADT/DenseSet.h"
Sam Clegg80ba4382018-04-10 16:12:49 +000023#include "llvm/ADT/StringMap.h"
Sam Clegg93102972018-02-23 05:08:53 +000024#include "llvm/BinaryFormat/Wasm.h"
Nicholas Wilson3e3f5fb2018-03-14 15:58:16 +000025#include "llvm/Object/WasmTraits.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000026#include "llvm/Support/FileOutputBuffer.h"
27#include "llvm/Support/Format.h"
28#include "llvm/Support/FormatVariadic.h"
29#include "llvm/Support/LEB128.h"
30
31#include <cstdarg>
Sam Clegge0f6fcd2018-01-12 22:25:17 +000032#include <map>
Sam Cleggc94d3932017-11-17 18:14:09 +000033
34#define DEBUG_TYPE "lld"
35
36using namespace llvm;
37using namespace llvm::wasm;
38using namespace lld;
39using namespace lld::wasm;
40
41static constexpr int kStackAlignment = 16;
Sam Clegg48bbd632018-01-24 21:37:30 +000042static constexpr int kInitialTableOffset = 1;
Nicholas Wilson874eedd2018-03-27 17:38:51 +000043static constexpr const char *kFunctionTableName = "__indirect_function_table";
Sam Cleggc94d3932017-11-17 18:14:09 +000044
45namespace {
46
Sam Clegg93102972018-02-23 05:08:53 +000047// An init entry to be written to either the synthetic init func or the
48// linking metadata.
49struct WasmInitEntry {
Sam Clegge3f3ccf2018-03-12 19:56:23 +000050 const FunctionSymbol *Sym;
Sam Clegg93102972018-02-23 05:08:53 +000051 uint32_t Priority;
Sam Cleggd3052d52018-01-18 23:40:49 +000052};
53
Sam Cleggc94d3932017-11-17 18:14:09 +000054// The writer writes a SymbolTable result to a file.
55class Writer {
56public:
57 void run();
58
59private:
60 void openFile();
61
Sam Cleggc375e4e2018-01-10 19:18:22 +000062 uint32_t lookupType(const WasmSignature &Sig);
63 uint32_t registerType(const WasmSignature &Sig);
Sam Clegg93102972018-02-23 05:08:53 +000064
Sam Clegg50686852018-01-12 18:35:13 +000065 void createCtorFunction();
66 void calculateInitFunctions();
Sam Clegg8d146bb2018-01-09 23:56:44 +000067 void assignIndexes();
Sam Cleggc94d3932017-11-17 18:14:09 +000068 void calculateImports();
Sam Cleggd3052d52018-01-18 23:40:49 +000069 void calculateExports();
Sam Clegg93102972018-02-23 05:08:53 +000070 void assignSymtab();
Sam Cleggc94d3932017-11-17 18:14:09 +000071 void calculateTypes();
72 void createOutputSegments();
73 void layoutMemory();
74 void createHeader();
75 void createSections();
Nicholas Wilsondbd90bf2018-03-07 13:28:16 +000076 SyntheticSection *createSyntheticSection(uint32_t Type, StringRef Name = "");
Sam Cleggc94d3932017-11-17 18:14:09 +000077
78 // Builtin sections
79 void createTypeSection();
80 void createFunctionSection();
81 void createTableSection();
82 void createGlobalSection();
83 void createExportSection();
84 void createImportSection();
85 void createMemorySection();
86 void createElemSection();
Sam Cleggc94d3932017-11-17 18:14:09 +000087 void createCodeSection();
88 void createDataSection();
Sam Clegg80ba4382018-04-10 16:12:49 +000089 void createCustomSections();
Sam Cleggc94d3932017-11-17 18:14:09 +000090
91 // Custom sections
92 void createRelocSections();
93 void createLinkingSection();
94 void createNameSection();
95
96 void writeHeader();
97 void writeSections();
98
99 uint64_t FileSize = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000100 uint32_t NumMemoryPages = 0;
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000101 uint32_t MaxMemoryPages = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000102
103 std::vector<const WasmSignature *> Types;
Nicholas Wilson3e3f5fb2018-03-14 15:58:16 +0000104 DenseMap<WasmSignature, int32_t> TypeIndices;
Sam Clegg93102972018-02-23 05:08:53 +0000105 std::vector<const Symbol *> ImportedSymbols;
106 unsigned NumImportedFunctions = 0;
107 unsigned NumImportedGlobals = 0;
108 std::vector<Symbol *> ExportedSymbols;
109 std::vector<const DefinedData *> DefinedFakeGlobals;
110 std::vector<InputGlobal *> InputGlobals;
Sam Clegg9f934222018-02-21 18:29:23 +0000111 std::vector<InputFunction *> InputFunctions;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000112 std::vector<const FunctionSymbol *> IndirectFunctions;
Sam Clegg93102972018-02-23 05:08:53 +0000113 std::vector<const Symbol *> SymtabEntries;
114 std::vector<WasmInitEntry> InitFunctions;
Sam Cleggc94d3932017-11-17 18:14:09 +0000115
Sam Clegg80ba4382018-04-10 16:12:49 +0000116 llvm::StringMap<std::vector<InputSection *>> CustomSectionMapping;
117
Sam Cleggc94d3932017-11-17 18:14:09 +0000118 // Elements that are used to construct the final output
119 std::string Header;
120 std::vector<OutputSection *> OutputSections;
121
122 std::unique_ptr<FileOutputBuffer> Buffer;
123
124 std::vector<OutputSegment *> Segments;
125 llvm::SmallDenseMap<StringRef, OutputSegment *> SegmentMap;
126};
127
128} // anonymous namespace
129
Sam Cleggc94d3932017-11-17 18:14:09 +0000130void Writer::createImportSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000131 uint32_t NumImports = ImportedSymbols.size();
Sam Cleggc94d3932017-11-17 18:14:09 +0000132 if (Config->ImportMemory)
133 ++NumImports;
Nicholas Wilsonfc90b302018-03-28 12:53:29 +0000134 if (Config->ImportTable)
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000135 ++NumImports;
Sam Cleggc94d3932017-11-17 18:14:09 +0000136
137 if (NumImports == 0)
138 return;
139
140 SyntheticSection *Section = createSyntheticSection(WASM_SEC_IMPORT);
141 raw_ostream &OS = Section->getStream();
142
143 writeUleb128(OS, NumImports, "import count");
144
Sam Cleggc94d3932017-11-17 18:14:09 +0000145 if (Config->ImportMemory) {
146 WasmImport Import;
147 Import.Module = "env";
148 Import.Field = "memory";
149 Import.Kind = WASM_EXTERNAL_MEMORY;
150 Import.Memory.Flags = 0;
151 Import.Memory.Initial = NumMemoryPages;
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000152 if (MaxMemoryPages != 0) {
153 Import.Memory.Flags |= WASM_LIMITS_FLAG_HAS_MAX;
154 Import.Memory.Maximum = MaxMemoryPages;
155 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000156 writeImport(OS, Import);
157 }
158
Nicholas Wilsonfc90b302018-03-28 12:53:29 +0000159 if (Config->ImportTable) {
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000160 uint32_t TableSize = kInitialTableOffset + IndirectFunctions.size();
161 WasmImport Import;
162 Import.Module = "env";
163 Import.Field = kFunctionTableName;
164 Import.Kind = WASM_EXTERNAL_TABLE;
165 Import.Table.ElemType = WASM_TYPE_ANYFUNC;
166 Import.Table.Limits = {WASM_LIMITS_FLAG_HAS_MAX, TableSize, TableSize};
167 writeImport(OS, Import);
168 }
169
Sam Clegg93102972018-02-23 05:08:53 +0000170 for (const Symbol *Sym : ImportedSymbols) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000171 WasmImport Import;
172 Import.Module = "env";
173 Import.Field = Sym->getName();
Sam Clegg93102972018-02-23 05:08:53 +0000174 if (auto *FunctionSym = dyn_cast<FunctionSymbol>(Sym)) {
175 Import.Kind = WASM_EXTERNAL_FUNCTION;
176 Import.SigIndex = lookupType(*FunctionSym->getFunctionType());
177 } else {
178 auto *GlobalSym = cast<GlobalSymbol>(Sym);
179 Import.Kind = WASM_EXTERNAL_GLOBAL;
180 Import.Global = *GlobalSym->getGlobalType();
181 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000182 writeImport(OS, Import);
183 }
184}
185
186void Writer::createTypeSection() {
187 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TYPE);
188 raw_ostream &OS = Section->getStream();
189 writeUleb128(OS, Types.size(), "type count");
Sam Cleggd451da12017-12-19 19:56:27 +0000190 for (const WasmSignature *Sig : Types)
Sam Cleggc94d3932017-11-17 18:14:09 +0000191 writeSig(OS, *Sig);
Sam Cleggc94d3932017-11-17 18:14:09 +0000192}
193
194void Writer::createFunctionSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000195 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000196 return;
197
198 SyntheticSection *Section = createSyntheticSection(WASM_SEC_FUNCTION);
199 raw_ostream &OS = Section->getStream();
200
Sam Clegg9f934222018-02-21 18:29:23 +0000201 writeUleb128(OS, InputFunctions.size(), "function count");
202 for (const InputFunction *Func : InputFunctions)
Sam Cleggc375e4e2018-01-10 19:18:22 +0000203 writeUleb128(OS, lookupType(Func->Signature), "sig index");
Sam Cleggc94d3932017-11-17 18:14:09 +0000204}
205
206void Writer::createMemorySection() {
207 if (Config->ImportMemory)
208 return;
209
210 SyntheticSection *Section = createSyntheticSection(WASM_SEC_MEMORY);
211 raw_ostream &OS = Section->getStream();
212
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000213 bool HasMax = MaxMemoryPages != 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000214 writeUleb128(OS, 1, "memory count");
Nicholas Wilsonca5cc202018-03-14 21:43:04 +0000215 writeUleb128(OS, HasMax ? static_cast<unsigned>(WASM_LIMITS_FLAG_HAS_MAX) : 0,
216 "memory limits flags");
Sam Cleggc94d3932017-11-17 18:14:09 +0000217 writeUleb128(OS, NumMemoryPages, "initial pages");
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000218 if (HasMax)
219 writeUleb128(OS, MaxMemoryPages, "max pages");
Sam Cleggc94d3932017-11-17 18:14:09 +0000220}
221
222void Writer::createGlobalSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000223 unsigned NumGlobals = InputGlobals.size() + DefinedFakeGlobals.size();
224 if (NumGlobals == 0)
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000225 return;
226
Sam Cleggc94d3932017-11-17 18:14:09 +0000227 SyntheticSection *Section = createSyntheticSection(WASM_SEC_GLOBAL);
228 raw_ostream &OS = Section->getStream();
229
Sam Clegg93102972018-02-23 05:08:53 +0000230 writeUleb128(OS, NumGlobals, "global count");
231 for (const InputGlobal *G : InputGlobals)
232 writeGlobal(OS, G->Global);
233 for (const DefinedData *Sym : DefinedFakeGlobals) {
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000234 WasmGlobal Global;
Sam Clegg93102972018-02-23 05:08:53 +0000235 Global.Type = {WASM_TYPE_I32, false};
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000236 Global.InitExpr.Opcode = WASM_OPCODE_I32_CONST;
237 Global.InitExpr.Value.Int32 = Sym->getVirtualAddress();
Sam Cleggc94d3932017-11-17 18:14:09 +0000238 writeGlobal(OS, Global);
239 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000240}
241
242void Writer::createTableSection() {
Nicholas Wilsonfc90b302018-03-28 12:53:29 +0000243 if (Config->ImportTable)
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000244 return;
245
246 // Always output a table section (or table import), even if there are no
247 // indirect calls. There are two reasons for this:
Sam Cleggfc1a9122017-12-11 22:00:56 +0000248 // 1. For executables it is useful to have an empty table slot at 0
249 // which can be filled with a null function call handler.
250 // 2. If we don't do this, any program that contains a call_indirect but
251 // no address-taken function will fail at validation time since it is
252 // a validation error to include a call_indirect instruction if there
253 // is not table.
Sam Clegg48bbd632018-01-24 21:37:30 +0000254 uint32_t TableSize = kInitialTableOffset + IndirectFunctions.size();
Sam Cleggfc1a9122017-12-11 22:00:56 +0000255
Sam Cleggc94d3932017-11-17 18:14:09 +0000256 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TABLE);
257 raw_ostream &OS = Section->getStream();
258
259 writeUleb128(OS, 1, "table count");
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000260 WasmLimits Limits = {WASM_LIMITS_FLAG_HAS_MAX, TableSize, TableSize};
261 writeTableType(OS, WasmTable{WASM_TYPE_ANYFUNC, Limits});
Sam Cleggc94d3932017-11-17 18:14:09 +0000262}
263
264void Writer::createExportSection() {
Sam Cleggc94d3932017-11-17 18:14:09 +0000265 bool ExportMemory = !Config->Relocatable && !Config->ImportMemory;
Nicholas Wilsonfc90b302018-03-28 12:53:29 +0000266 bool ExportTable = !Config->Relocatable && Config->ExportTable;
Sam Cleggc94d3932017-11-17 18:14:09 +0000267
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000268 uint32_t NumExports =
269 (ExportMemory ? 1 : 0) + (ExportTable ? 1 : 0) + ExportedSymbols.size();
Sam Cleggc94d3932017-11-17 18:14:09 +0000270 if (!NumExports)
271 return;
272
273 SyntheticSection *Section = createSyntheticSection(WASM_SEC_EXPORT);
274 raw_ostream &OS = Section->getStream();
275
276 writeUleb128(OS, NumExports, "export count");
277
Rui Ueyama7d696882018-02-28 00:18:34 +0000278 if (ExportMemory)
279 writeExport(OS, {"memory", WASM_EXTERNAL_MEMORY, 0});
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000280 if (ExportTable)
281 writeExport(OS, {kFunctionTableName, WASM_EXTERNAL_TABLE, 0});
Sam Cleggc94d3932017-11-17 18:14:09 +0000282
Sam Clegg93102972018-02-23 05:08:53 +0000283 unsigned FakeGlobalIndex = NumImportedGlobals + InputGlobals.size();
Rui Ueyama7d696882018-02-28 00:18:34 +0000284
Sam Clegg93102972018-02-23 05:08:53 +0000285 for (const Symbol *Sym : ExportedSymbols) {
Rui Ueyama7d696882018-02-28 00:18:34 +0000286 StringRef Name = Sym->getName();
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000287 WasmExport Export;
Rui Ueyama7d696882018-02-28 00:18:34 +0000288 DEBUG(dbgs() << "Export: " << Name << "\n");
289
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000290 if (auto *F = dyn_cast<DefinedFunction>(Sym))
291 Export = {Name, WASM_EXTERNAL_FUNCTION, F->getFunctionIndex()};
292 else if (auto *G = dyn_cast<DefinedGlobal>(Sym))
293 Export = {Name, WASM_EXTERNAL_GLOBAL, G->getGlobalIndex()};
Rui Ueyama7d696882018-02-28 00:18:34 +0000294 else if (isa<DefinedData>(Sym))
295 Export = {Name, WASM_EXTERNAL_GLOBAL, FakeGlobalIndex++};
296 else
Sam Clegg93102972018-02-23 05:08:53 +0000297 llvm_unreachable("unexpected symbol type");
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000298 writeExport(OS, Export);
Sam Cleggc94d3932017-11-17 18:14:09 +0000299 }
300}
301
Sam Clegg80ba4382018-04-10 16:12:49 +0000302void Writer::createCustomSections() {
303 log("createCustomSections");
304 for (ObjFile *File : Symtab->ObjectFiles)
305 for (InputSection *Section : File->CustomSections)
306 CustomSectionMapping[Section->getName()].push_back(Section);
307
308 for (auto &Pair : CustomSectionMapping) {
309 StringRef Name = Pair.first();
310 // These custom sections are known the linker and synthesized rather than
311 // blindly copied
312 if (Name == "linking" || Name == "name" || Name.startswith("reloc."))
313 continue;
314 DEBUG(dbgs() << "createCustomSection: " << Name << "\n");
315 OutputSections.push_back(make<CustomSection>(Name, Pair.second));
316 }
317}
318
Sam Cleggc94d3932017-11-17 18:14:09 +0000319void Writer::createElemSection() {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000320 if (IndirectFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000321 return;
322
323 SyntheticSection *Section = createSyntheticSection(WASM_SEC_ELEM);
324 raw_ostream &OS = Section->getStream();
325
326 writeUleb128(OS, 1, "segment count");
327 writeUleb128(OS, 0, "table index");
328 WasmInitExpr InitExpr;
329 InitExpr.Opcode = WASM_OPCODE_I32_CONST;
Sam Clegg48bbd632018-01-24 21:37:30 +0000330 InitExpr.Value.Int32 = kInitialTableOffset;
Sam Cleggc94d3932017-11-17 18:14:09 +0000331 writeInitExpr(OS, InitExpr);
Sam Cleggfc1a9122017-12-11 22:00:56 +0000332 writeUleb128(OS, IndirectFunctions.size(), "elem count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000333
Sam Clegg48bbd632018-01-24 21:37:30 +0000334 uint32_t TableIndex = kInitialTableOffset;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000335 for (const FunctionSymbol *Sym : IndirectFunctions) {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000336 assert(Sym->getTableIndex() == TableIndex);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000337 writeUleb128(OS, Sym->getFunctionIndex(), "function index");
Sam Cleggfc1a9122017-12-11 22:00:56 +0000338 ++TableIndex;
339 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000340}
341
342void Writer::createCodeSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000343 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000344 return;
345
346 log("createCodeSection");
347
Sam Clegg9f934222018-02-21 18:29:23 +0000348 auto Section = make<CodeSection>(InputFunctions);
Sam Cleggc94d3932017-11-17 18:14:09 +0000349 OutputSections.push_back(Section);
350}
351
352void Writer::createDataSection() {
353 if (!Segments.size())
354 return;
355
356 log("createDataSection");
357 auto Section = make<DataSection>(Segments);
358 OutputSections.push_back(Section);
359}
360
Sam Cleggd451da12017-12-19 19:56:27 +0000361// Create relocations sections in the final output.
Sam Cleggc94d3932017-11-17 18:14:09 +0000362// These are only created when relocatable output is requested.
363void Writer::createRelocSections() {
364 log("createRelocSections");
365 // Don't use iterator here since we are adding to OutputSection
366 size_t OrigSize = OutputSections.size();
Rui Ueyamaffa650a2018-04-24 23:09:57 +0000367 for (size_t I = 0; I < OrigSize; I++) {
368 OutputSection *OSec = OutputSections[I];
Rui Ueyama37254062018-02-28 00:01:31 +0000369 uint32_t Count = OSec->numRelocations();
Sam Cleggc94d3932017-11-17 18:14:09 +0000370 if (!Count)
371 continue;
372
Rui Ueyama37254062018-02-28 00:01:31 +0000373 StringRef Name;
374 if (OSec->Type == WASM_SEC_DATA)
375 Name = "reloc.DATA";
376 else if (OSec->Type == WASM_SEC_CODE)
377 Name = "reloc.CODE";
Sam Cleggc94d3932017-11-17 18:14:09 +0000378 else
Sam Cleggd451da12017-12-19 19:56:27 +0000379 llvm_unreachable("relocations only supported for code and data");
Sam Cleggc94d3932017-11-17 18:14:09 +0000380
Rui Ueyama37254062018-02-28 00:01:31 +0000381 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, Name);
Sam Cleggc94d3932017-11-17 18:14:09 +0000382 raw_ostream &OS = Section->getStream();
Rui Ueyamaffa650a2018-04-24 23:09:57 +0000383 writeUleb128(OS, I, "reloc section");
Sam Cleggc94d3932017-11-17 18:14:09 +0000384 writeUleb128(OS, Count, "reloc count");
Rui Ueyama37254062018-02-28 00:01:31 +0000385 OSec->writeRelocations(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000386 }
387}
388
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000389static uint32_t getWasmFlags(const Symbol *Sym) {
390 uint32_t Flags = 0;
391 if (Sym->isLocal())
392 Flags |= WASM_SYMBOL_BINDING_LOCAL;
393 if (Sym->isWeak())
394 Flags |= WASM_SYMBOL_BINDING_WEAK;
395 if (Sym->isHidden())
396 Flags |= WASM_SYMBOL_VISIBILITY_HIDDEN;
397 if (Sym->isUndefined())
398 Flags |= WASM_SYMBOL_UNDEFINED;
399 return Flags;
400}
401
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000402// Some synthetic sections (e.g. "name" and "linking") have subsections.
403// Just like the synthetic sections themselves these need to be created before
404// they can be written out (since they are preceded by their length). This
405// class is used to create subsections and then write them into the stream
406// of the parent section.
407class SubSection {
408public:
409 explicit SubSection(uint32_t Type) : Type(Type) {}
410
411 void writeTo(raw_ostream &To) {
412 OS.flush();
Rui Ueyama67769102018-02-28 03:38:14 +0000413 writeUleb128(To, Type, "subsection type");
414 writeUleb128(To, Body.size(), "subsection size");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000415 To.write(Body.data(), Body.size());
416 }
417
418private:
419 uint32_t Type;
420 std::string Body;
421
422public:
423 raw_string_ostream OS{Body};
424};
425
Sam Clegg49ed9262017-12-01 00:53:21 +0000426// Create the custom "linking" section containing linker metadata.
Sam Cleggc94d3932017-11-17 18:14:09 +0000427// This is only created when relocatable output is requested.
428void Writer::createLinkingSection() {
429 SyntheticSection *Section =
430 createSyntheticSection(WASM_SEC_CUSTOM, "linking");
431 raw_ostream &OS = Section->getStream();
432
Sam Clegg2b8b1792018-04-26 18:17:21 +0000433 writeUleb128(OS, WasmMetadataVersion, "Version");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000434
Sam Clegg93102972018-02-23 05:08:53 +0000435 if (!SymtabEntries.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000436 SubSection Sub(WASM_SYMBOL_TABLE);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000437 writeUleb128(Sub.OS, SymtabEntries.size(), "num symbols");
438
Sam Clegg93102972018-02-23 05:08:53 +0000439 for (const Symbol *Sym : SymtabEntries) {
440 assert(Sym->isDefined() || Sym->isUndefined());
441 WasmSymbolType Kind = Sym->getWasmType();
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000442 uint32_t Flags = getWasmFlags(Sym);
443
Sam Clegg8518e7d2018-03-01 18:06:39 +0000444 writeU8(Sub.OS, Kind, "sym kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000445 writeUleb128(Sub.OS, Flags, "sym flags");
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000446
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000447 if (auto *F = dyn_cast<FunctionSymbol>(Sym)) {
448 writeUleb128(Sub.OS, F->getFunctionIndex(), "index");
Sam Clegg93102972018-02-23 05:08:53 +0000449 if (Sym->isDefined())
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000450 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000451 } else if (auto *G = dyn_cast<GlobalSymbol>(Sym)) {
452 writeUleb128(Sub.OS, G->getGlobalIndex(), "index");
453 if (Sym->isDefined())
454 writeStr(Sub.OS, Sym->getName(), "sym name");
455 } else {
456 assert(isa<DataSymbol>(Sym));
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000457 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegg93102972018-02-23 05:08:53 +0000458 if (auto *DataSym = dyn_cast<DefinedData>(Sym)) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000459 writeUleb128(Sub.OS, DataSym->getOutputSegmentIndex(), "index");
460 writeUleb128(Sub.OS, DataSym->getOutputSegmentOffset(),
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000461 "data offset");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000462 writeUleb128(Sub.OS, DataSym->getSize(), "data size");
Sam Clegg93102972018-02-23 05:08:53 +0000463 }
Sam Clegg93102972018-02-23 05:08:53 +0000464 }
Sam Cleggd3052d52018-01-18 23:40:49 +0000465 }
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000466
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000467 Sub.writeTo(OS);
Sam Cleggd3052d52018-01-18 23:40:49 +0000468 }
469
Sam Clegg0d0dd392017-12-19 17:09:45 +0000470 if (Segments.size()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000471 SubSection Sub(WASM_SEGMENT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000472 writeUleb128(Sub.OS, Segments.size(), "num data segments");
Sam Cleggc94d3932017-11-17 18:14:09 +0000473 for (const OutputSegment *S : Segments) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000474 writeStr(Sub.OS, S->Name, "segment name");
475 writeUleb128(Sub.OS, S->Alignment, "alignment");
476 writeUleb128(Sub.OS, 0, "flags");
Sam Cleggc94d3932017-11-17 18:14:09 +0000477 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000478 Sub.writeTo(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000479 }
Sam Clegg0d0dd392017-12-19 17:09:45 +0000480
Sam Clegg0d0dd392017-12-19 17:09:45 +0000481 if (!InitFunctions.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000482 SubSection Sub(WASM_INIT_FUNCS);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000483 writeUleb128(Sub.OS, InitFunctions.size(), "num init functions");
Sam Clegg93102972018-02-23 05:08:53 +0000484 for (const WasmInitEntry &F : InitFunctions) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000485 writeUleb128(Sub.OS, F.Priority, "priority");
486 writeUleb128(Sub.OS, F.Sym->getOutputSymbolIndex(), "function index");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000487 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000488 Sub.writeTo(OS);
Sam Clegg0d0dd392017-12-19 17:09:45 +0000489 }
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000490
Nicholas Wilsondbd90bf2018-03-07 13:28:16 +0000491 struct ComdatEntry {
492 unsigned Kind;
493 uint32_t Index;
494 };
495 std::map<StringRef, std::vector<ComdatEntry>> Comdats;
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000496
Sam Clegg9f934222018-02-21 18:29:23 +0000497 for (const InputFunction *F : InputFunctions) {
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000498 StringRef Comdat = F->getComdatName();
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000499 if (!Comdat.empty())
500 Comdats[Comdat].emplace_back(
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000501 ComdatEntry{WASM_COMDAT_FUNCTION, F->getFunctionIndex()});
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000502 }
503 for (uint32_t I = 0; I < Segments.size(); ++I) {
Sam Cleggf98bccf2018-01-13 15:57:48 +0000504 const auto &InputSegments = Segments[I]->InputSegments;
505 if (InputSegments.empty())
506 continue;
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000507 StringRef Comdat = InputSegments[0]->getComdatName();
Sam Clegga697df522018-01-13 15:59:53 +0000508#ifndef NDEBUG
Sam Cleggf98bccf2018-01-13 15:57:48 +0000509 for (const InputSegment *IS : InputSegments)
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000510 assert(IS->getComdatName() == Comdat);
Sam Clegga697df522018-01-13 15:59:53 +0000511#endif
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000512 if (!Comdat.empty())
513 Comdats[Comdat].emplace_back(ComdatEntry{WASM_COMDAT_DATA, I});
514 }
515
516 if (!Comdats.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000517 SubSection Sub(WASM_COMDAT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000518 writeUleb128(Sub.OS, Comdats.size(), "num comdats");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000519 for (const auto &C : Comdats) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000520 writeStr(Sub.OS, C.first, "comdat name");
521 writeUleb128(Sub.OS, 0, "comdat flags"); // flags for future use
522 writeUleb128(Sub.OS, C.second.size(), "num entries");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000523 for (const ComdatEntry &Entry : C.second) {
Sam Clegg8518e7d2018-03-01 18:06:39 +0000524 writeU8(Sub.OS, Entry.Kind, "entry kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000525 writeUleb128(Sub.OS, Entry.Index, "entry index");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000526 }
527 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000528 Sub.writeTo(OS);
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000529 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000530}
531
532// Create the custom "name" section containing debug symbol names.
533void Writer::createNameSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000534 unsigned NumNames = NumImportedFunctions;
Sam Clegg9f934222018-02-21 18:29:23 +0000535 for (const InputFunction *F : InputFunctions)
Nicholas Wilson6c7fe302018-04-20 17:09:18 +0000536 if (!F->getName().empty() || !F->getDebugName().empty())
Sam Clegg1963d712018-01-17 20:19:04 +0000537 ++NumNames;
Sam Cleggc94d3932017-11-17 18:14:09 +0000538
Sam Clegg1963d712018-01-17 20:19:04 +0000539 if (NumNames == 0)
540 return;
Sam Clegg50686852018-01-12 18:35:13 +0000541
Sam Cleggc94d3932017-11-17 18:14:09 +0000542 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "name");
543
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000544 SubSection Sub(WASM_NAMES_FUNCTION);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000545 writeUleb128(Sub.OS, NumNames, "name count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000546
Sam Clegg93102972018-02-23 05:08:53 +0000547 // Names must appear in function index order. As it happens ImportedSymbols
548 // and InputFunctions are numbered in order with imported functions coming
Sam Clegg1963d712018-01-17 20:19:04 +0000549 // first.
Sam Clegg93102972018-02-23 05:08:53 +0000550 for (const Symbol *S : ImportedSymbols) {
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000551 if (auto *F = dyn_cast<FunctionSymbol>(S)) {
552 writeUleb128(Sub.OS, F->getFunctionIndex(), "func index");
Nicholas Wilson531769b2018-03-13 13:30:04 +0000553 Optional<std::string> Name = demangleItanium(F->getName());
554 writeStr(Sub.OS, Name ? StringRef(*Name) : F->getName(), "symbol name");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000555 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000556 }
Sam Clegg9f934222018-02-21 18:29:23 +0000557 for (const InputFunction *F : InputFunctions) {
Sam Clegg1963d712018-01-17 20:19:04 +0000558 if (!F->getName().empty()) {
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000559 writeUleb128(Sub.OS, F->getFunctionIndex(), "func index");
Nicholas Wilson6c7fe302018-04-20 17:09:18 +0000560 if (!F->getDebugName().empty()) {
561 writeStr(Sub.OS, F->getDebugName(), "symbol name");
562 } else {
563 Optional<std::string> Name = demangleItanium(F->getName());
564 writeStr(Sub.OS, Name ? StringRef(*Name) : F->getName(), "symbol name");
565 }
Sam Clegg1963d712018-01-17 20:19:04 +0000566 }
567 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000568
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000569 Sub.writeTo(Section->getStream());
Sam Cleggc94d3932017-11-17 18:14:09 +0000570}
571
572void Writer::writeHeader() {
573 memcpy(Buffer->getBufferStart(), Header.data(), Header.size());
574}
575
576void Writer::writeSections() {
577 uint8_t *Buf = Buffer->getBufferStart();
578 parallelForEach(OutputSections, [Buf](OutputSection *S) { S->writeTo(Buf); });
579}
580
581// Fix the memory layout of the output binary. This assigns memory offsets
Sam Clegg49ed9262017-12-01 00:53:21 +0000582// to each of the input data sections as well as the explicit stack region.
Sam Clegga0f095e2018-05-03 17:21:53 +0000583// The default memory layout is as follows, from low to high.
584//
Sam Cleggf0d433d2018-02-02 22:59:56 +0000585// - initialized data (starting at Config->GlobalBase)
586// - BSS data (not currently implemented in llvm)
587// - explicit stack (Config->ZStackSize)
588// - heap start / unallocated
Sam Clegga0f095e2018-05-03 17:21:53 +0000589//
590// The --stack-first option means that stack is placed before any static data.
591// This can be useful since it means that stack overflow traps immediately rather
592// than overwriting global data, but also increases code size since all static
593// data loads and stores requires larger offsets.
Sam Cleggc94d3932017-11-17 18:14:09 +0000594void Writer::layoutMemory() {
Sam Cleggc94d3932017-11-17 18:14:09 +0000595 createOutputSegments();
596
Sam Clegga0f095e2018-05-03 17:21:53 +0000597 uint32_t MemoryPtr = 0;
598
599 auto PlaceStack = [&]() {
600 if (Config->Relocatable)
601 return;
602 MemoryPtr = alignTo(MemoryPtr, kStackAlignment);
603 if (Config->ZStackSize != alignTo(Config->ZStackSize, kStackAlignment))
604 error("stack size must be " + Twine(kStackAlignment) + "-byte aligned");
605 log("mem: stack size = " + Twine(Config->ZStackSize));
606 log("mem: stack base = " + Twine(MemoryPtr));
607 MemoryPtr += Config->ZStackSize;
608 WasmSym::StackPointer->Global->Global.InitExpr.Value.Int32 = MemoryPtr;
609 log("mem: stack top = " + Twine(MemoryPtr));
610 };
611
612 if (Config->StackFirst) {
613 PlaceStack();
614 } else {
615 MemoryPtr = Config->GlobalBase;
616 log("mem: global base = " + Twine(Config->GlobalBase));
617 }
618
619 uint32_t DataStart = MemoryPtr;
620
Sam Cleggf0d433d2018-02-02 22:59:56 +0000621 // Arbitrarily set __dso_handle handle to point to the start of the data
622 // segments.
623 if (WasmSym::DsoHandle)
Sam Clegga0f095e2018-05-03 17:21:53 +0000624 WasmSym::DsoHandle->setVirtualAddress(DataStart);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000625
Sam Cleggc94d3932017-11-17 18:14:09 +0000626 for (OutputSegment *Seg : Segments) {
627 MemoryPtr = alignTo(MemoryPtr, Seg->Alignment);
628 Seg->StartVA = MemoryPtr;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000629 log(formatv("mem: {0,-15} offset={1,-8} size={2,-8} align={3}", Seg->Name,
630 MemoryPtr, Seg->Size, Seg->Alignment));
Sam Cleggc94d3932017-11-17 18:14:09 +0000631 MemoryPtr += Seg->Size;
632 }
633
Sam Cleggf0d433d2018-02-02 22:59:56 +0000634 // TODO: Add .bss space here.
Sam Clegg37a4a8a2018-02-07 03:04:53 +0000635 if (WasmSym::DataEnd)
636 WasmSym::DataEnd->setVirtualAddress(MemoryPtr);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000637
Sam Clegga0f095e2018-05-03 17:21:53 +0000638 log("mem: static data = " + Twine(MemoryPtr - DataStart));
Sam Cleggc94d3932017-11-17 18:14:09 +0000639
Sam Clegga0f095e2018-05-03 17:21:53 +0000640 if (!Config->StackFirst)
641 PlaceStack();
642
643 // Set `__heap_base` to directly follow the end of the stack or global data.
644 // The fact that this comes last means that a malloc/brk implementation
645 // can grow the heap at runtime.
Sam Cleggc94d3932017-11-17 18:14:09 +0000646 if (!Config->Relocatable) {
Sam Cleggf0d433d2018-02-02 22:59:56 +0000647 WasmSym::HeapBase->setVirtualAddress(MemoryPtr);
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000648 log("mem: heap base = " + Twine(MemoryPtr));
Sam Cleggc94d3932017-11-17 18:14:09 +0000649 }
650
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000651 if (Config->InitialMemory != 0) {
652 if (Config->InitialMemory != alignTo(Config->InitialMemory, WasmPageSize))
653 error("initial memory must be " + Twine(WasmPageSize) + "-byte aligned");
654 if (MemoryPtr > Config->InitialMemory)
655 error("initial memory too small, " + Twine(MemoryPtr) + " bytes needed");
656 else
657 MemoryPtr = Config->InitialMemory;
658 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000659 uint32_t MemSize = alignTo(MemoryPtr, WasmPageSize);
660 NumMemoryPages = MemSize / WasmPageSize;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000661 log("mem: total pages = " + Twine(NumMemoryPages));
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000662
663 if (Config->MaxMemory != 0) {
664 if (Config->MaxMemory != alignTo(Config->MaxMemory, WasmPageSize))
665 error("maximum memory must be " + Twine(WasmPageSize) + "-byte aligned");
666 if (MemoryPtr > Config->MaxMemory)
667 error("maximum memory too small, " + Twine(MemoryPtr) + " bytes needed");
668 MaxMemoryPages = Config->MaxMemory / WasmPageSize;
669 log("mem: max pages = " + Twine(MaxMemoryPages));
670 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000671}
672
673SyntheticSection *Writer::createSyntheticSection(uint32_t Type,
Sam Cleggc375e4e2018-01-10 19:18:22 +0000674 StringRef Name) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000675 auto Sec = make<SyntheticSection>(Type, Name);
Sam Cleggab2ac292017-12-20 05:14:48 +0000676 log("createSection: " + toString(*Sec));
Sam Cleggc94d3932017-11-17 18:14:09 +0000677 OutputSections.push_back(Sec);
678 return Sec;
679}
680
681void Writer::createSections() {
682 // Known sections
683 createTypeSection();
684 createImportSection();
685 createFunctionSection();
686 createTableSection();
687 createMemorySection();
688 createGlobalSection();
689 createExportSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000690 createElemSection();
691 createCodeSection();
692 createDataSection();
Sam Clegg80ba4382018-04-10 16:12:49 +0000693 createCustomSections();
Sam Cleggc94d3932017-11-17 18:14:09 +0000694
695 // Custom sections
Sam Clegg99eb42c2018-02-27 23:58:03 +0000696 if (Config->Relocatable) {
Sam Clegg99eb42c2018-02-27 23:58:03 +0000697 createLinkingSection();
Nicholas Wilson94d3b162018-03-05 12:33:58 +0000698 createRelocSections();
Sam Clegg99eb42c2018-02-27 23:58:03 +0000699 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000700 if (!Config->StripDebug && !Config->StripAll)
701 createNameSection();
702
703 for (OutputSection *S : OutputSections) {
704 S->setOffset(FileSize);
705 S->finalizeContents();
706 FileSize += S->getSize();
707 }
708}
709
Sam Cleggc94d3932017-11-17 18:14:09 +0000710void Writer::calculateImports() {
Sam Clegg574d7ce2017-12-15 19:23:49 +0000711 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000712 if (!Sym->isUndefined())
713 continue;
714 if (isa<DataSymbol>(Sym))
715 continue;
716 if (Sym->isWeak() && !Config->Relocatable)
Sam Clegg574d7ce2017-12-15 19:23:49 +0000717 continue;
Nicholas Wilsona1e299f2018-04-20 17:18:06 +0000718 if (!Sym->isLive())
719 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000720
Sam Clegg93102972018-02-23 05:08:53 +0000721 DEBUG(dbgs() << "import: " << Sym->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000722 ImportedSymbols.emplace_back(Sym);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000723 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
724 F->setFunctionIndex(NumImportedFunctions++);
Sam Clegg93102972018-02-23 05:08:53 +0000725 else
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000726 cast<GlobalSymbol>(Sym)->setGlobalIndex(NumImportedGlobals++);
Sam Cleggc94d3932017-11-17 18:14:09 +0000727 }
728}
729
Sam Cleggd3052d52018-01-18 23:40:49 +0000730void Writer::calculateExports() {
Sam Clegg93102972018-02-23 05:08:53 +0000731 if (Config->Relocatable)
732 return;
Sam Cleggf0d433d2018-02-02 22:59:56 +0000733
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000734 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000735 if (!Sym->isDefined())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000736 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000737 if (Sym->isHidden() || Sym->isLocal())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000738 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000739 if (!Sym->isLive())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000740 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000741
742 DEBUG(dbgs() << "exporting sym: " << Sym->getName() << "\n");
743
Nicholas Wilsonf2f6d5e2018-03-02 14:51:36 +0000744 if (auto *D = dyn_cast<DefinedData>(Sym))
Sam Clegg93102972018-02-23 05:08:53 +0000745 DefinedFakeGlobals.emplace_back(D);
Sam Clegg93102972018-02-23 05:08:53 +0000746 ExportedSymbols.emplace_back(Sym);
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000747 }
Sam Clegg93102972018-02-23 05:08:53 +0000748}
749
750void Writer::assignSymtab() {
751 if (!Config->Relocatable)
752 return;
753
754 unsigned SymbolIndex = SymtabEntries.size();
Sam Cleggd3052d52018-01-18 23:40:49 +0000755 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg93102972018-02-23 05:08:53 +0000756 DEBUG(dbgs() << "Symtab entries: " << File->getName() << "\n");
Sam Cleggd3052d52018-01-18 23:40:49 +0000757 for (Symbol *Sym : File->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000758 if (Sym->getFile() != File)
Sam Cleggd3052d52018-01-18 23:40:49 +0000759 continue;
Nicholas Wilson06e0d172018-03-07 11:15:47 +0000760 // (Since this is relocatable output, GC is not performed so symbols must
761 // be live.)
762 assert(Sym->isLive());
Sam Clegg93102972018-02-23 05:08:53 +0000763 Sym->setOutputSymbolIndex(SymbolIndex++);
764 SymtabEntries.emplace_back(Sym);
Sam Cleggd3052d52018-01-18 23:40:49 +0000765 }
766 }
767
Sam Clegg93102972018-02-23 05:08:53 +0000768 // For the moment, relocatable output doesn't contain any synthetic functions,
769 // so no need to look through the Symtab for symbols not referenced by
770 // Symtab->ObjectFiles.
Sam Cleggd3052d52018-01-18 23:40:49 +0000771}
772
Sam Cleggc375e4e2018-01-10 19:18:22 +0000773uint32_t Writer::lookupType(const WasmSignature &Sig) {
Sam Clegg8d027d62018-01-10 20:12:26 +0000774 auto It = TypeIndices.find(Sig);
775 if (It == TypeIndices.end()) {
Sam Cleggc375e4e2018-01-10 19:18:22 +0000776 error("type not found: " + toString(Sig));
Sam Clegg8d027d62018-01-10 20:12:26 +0000777 return 0;
778 }
779 return It->second;
Sam Cleggc375e4e2018-01-10 19:18:22 +0000780}
781
782uint32_t Writer::registerType(const WasmSignature &Sig) {
Sam Cleggb8621592017-11-30 01:40:08 +0000783 auto Pair = TypeIndices.insert(std::make_pair(Sig, Types.size()));
Sam Cleggc375e4e2018-01-10 19:18:22 +0000784 if (Pair.second) {
785 DEBUG(dbgs() << "type " << toString(Sig) << "\n");
Sam Cleggb8621592017-11-30 01:40:08 +0000786 Types.push_back(&Sig);
Sam Cleggc375e4e2018-01-10 19:18:22 +0000787 }
Sam Cleggb8621592017-11-30 01:40:08 +0000788 return Pair.first->second;
789}
790
Sam Cleggc94d3932017-11-17 18:14:09 +0000791void Writer::calculateTypes() {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000792 // The output type section is the union of the following sets:
793 // 1. Any signature used in the TYPE relocation
794 // 2. The signatures of all imported functions
795 // 3. The signatures of all defined functions
796
Sam Cleggc94d3932017-11-17 18:14:09 +0000797 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000798 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
799 for (uint32_t I = 0; I < Types.size(); I++)
800 if (File->TypeIsUsed[I])
801 File->TypeMap[I] = registerType(Types[I]);
Sam Cleggc94d3932017-11-17 18:14:09 +0000802 }
Sam Clegg50686852018-01-12 18:35:13 +0000803
Sam Clegg93102972018-02-23 05:08:53 +0000804 for (const Symbol *Sym : ImportedSymbols)
805 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
806 registerType(*F->getFunctionType());
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000807
Sam Clegg9f934222018-02-21 18:29:23 +0000808 for (const InputFunction *F : InputFunctions)
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000809 registerType(F->Signature);
Sam Cleggc94d3932017-11-17 18:14:09 +0000810}
811
Sam Clegg8d146bb2018-01-09 23:56:44 +0000812void Writer::assignIndexes() {
Sam Clegg93102972018-02-23 05:08:53 +0000813 uint32_t FunctionIndex = NumImportedFunctions + InputFunctions.size();
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000814 auto AddDefinedFunction = [&](InputFunction *Func) {
815 if (!Func->Live)
816 return;
817 InputFunctions.emplace_back(Func);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000818 Func->setFunctionIndex(FunctionIndex++);
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000819 };
820
Nicholas Wilson5639da82018-03-12 15:44:07 +0000821 for (InputFunction *Func : Symtab->SyntheticFunctions)
822 AddDefinedFunction(Func);
823
Sam Clegg87e61922018-01-08 23:39:11 +0000824 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8d146bb2018-01-09 23:56:44 +0000825 DEBUG(dbgs() << "Functions: " << File->getName() << "\n");
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000826 for (InputFunction *Func : File->Functions)
827 AddDefinedFunction(Func);
Sam Clegg8d146bb2018-01-09 23:56:44 +0000828 }
829
Sam Clegg93102972018-02-23 05:08:53 +0000830 uint32_t TableIndex = kInitialTableOffset;
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000831 auto HandleRelocs = [&](InputChunk *Chunk) {
832 if (!Chunk->Live)
833 return;
834 ObjFile *File = Chunk->File;
835 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
Sam Clegg93102972018-02-23 05:08:53 +0000836 for (const WasmRelocation &Reloc : Chunk->getRelocations()) {
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000837 if (Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_I32 ||
838 Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_SLEB) {
839 FunctionSymbol *Sym = File->getFunctionSymbol(Reloc.Index);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000840 if (Sym->hasTableIndex() || !Sym->hasFunctionIndex())
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000841 continue;
842 Sym->setTableIndex(TableIndex++);
843 IndirectFunctions.emplace_back(Sym);
844 } else if (Reloc.Type == R_WEBASSEMBLY_TYPE_INDEX_LEB) {
Sam Clegg93102972018-02-23 05:08:53 +0000845 // Mark target type as live
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000846 File->TypeMap[Reloc.Index] = registerType(Types[Reloc.Index]);
847 File->TypeIsUsed[Reloc.Index] = true;
848 }
849 }
850 };
851
Sam Clegg8d146bb2018-01-09 23:56:44 +0000852 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000853 DEBUG(dbgs() << "Handle relocs: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000854 for (InputChunk *Chunk : File->Functions)
855 HandleRelocs(Chunk);
856 for (InputChunk *Chunk : File->Segments)
857 HandleRelocs(Chunk);
858 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000859
Sam Clegg93102972018-02-23 05:08:53 +0000860 uint32_t GlobalIndex = NumImportedGlobals + InputGlobals.size();
861 auto AddDefinedGlobal = [&](InputGlobal *Global) {
862 if (Global->Live) {
863 DEBUG(dbgs() << "AddDefinedGlobal: " << GlobalIndex << "\n");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000864 Global->setGlobalIndex(GlobalIndex++);
Sam Clegg93102972018-02-23 05:08:53 +0000865 InputGlobals.push_back(Global);
866 }
867 };
868
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000869 for (InputGlobal *Global : Symtab->SyntheticGlobals)
870 AddDefinedGlobal(Global);
Sam Clegg93102972018-02-23 05:08:53 +0000871
872 for (ObjFile *File : Symtab->ObjectFiles) {
873 DEBUG(dbgs() << "Globals: " << File->getName() << "\n");
874 for (InputGlobal *Global : File->Globals)
875 AddDefinedGlobal(Global);
Sam Cleggc94d3932017-11-17 18:14:09 +0000876 }
877}
878
879static StringRef getOutputDataSegmentName(StringRef Name) {
880 if (Config->Relocatable)
881 return Name;
Rui Ueyama4764b572018-02-28 00:57:28 +0000882 if (Name.startswith(".text."))
883 return ".text";
884 if (Name.startswith(".data."))
885 return ".data";
886 if (Name.startswith(".bss."))
887 return ".bss";
Sam Cleggc94d3932017-11-17 18:14:09 +0000888 return Name;
889}
890
891void Writer::createOutputSegments() {
892 for (ObjFile *File : Symtab->ObjectFiles) {
893 for (InputSegment *Segment : File->Segments) {
Sam Clegg447ae402018-02-13 20:29:38 +0000894 if (!Segment->Live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000895 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000896 StringRef Name = getOutputDataSegmentName(Segment->getName());
897 OutputSegment *&S = SegmentMap[Name];
898 if (S == nullptr) {
899 DEBUG(dbgs() << "new segment: " << Name << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000900 S = make<OutputSegment>(Name, Segments.size());
Sam Cleggc94d3932017-11-17 18:14:09 +0000901 Segments.push_back(S);
902 }
903 S->addInputSegment(Segment);
904 DEBUG(dbgs() << "added data: " << Name << ": " << S->Size << "\n");
Sam Cleggc94d3932017-11-17 18:14:09 +0000905 }
906 }
907}
908
Sam Clegg50686852018-01-12 18:35:13 +0000909static const int OPCODE_CALL = 0x10;
910static const int OPCODE_END = 0xb;
911
912// Create synthetic "__wasm_call_ctors" function based on ctor functions
913// in input object.
914void Writer::createCtorFunction() {
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000915 // First write the body's contents to a string.
916 std::string BodyContent;
Sam Clegg50686852018-01-12 18:35:13 +0000917 {
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000918 raw_string_ostream OS(BodyContent);
Sam Clegg50686852018-01-12 18:35:13 +0000919 writeUleb128(OS, 0, "num locals");
Sam Clegg93102972018-02-23 05:08:53 +0000920 for (const WasmInitEntry &F : InitFunctions) {
Sam Clegg50686852018-01-12 18:35:13 +0000921 writeU8(OS, OPCODE_CALL, "CALL");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000922 writeUleb128(OS, F.Sym->getFunctionIndex(), "function index");
Sam Clegg50686852018-01-12 18:35:13 +0000923 }
924 writeU8(OS, OPCODE_END, "END");
925 }
926
927 // Once we know the size of the body we can create the final function body
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000928 std::string FunctionBody;
929 {
930 raw_string_ostream OS(FunctionBody);
931 writeUleb128(OS, BodyContent.size(), "function size");
932 OS << BodyContent;
933 }
Rui Ueyama29abfe42018-02-28 17:43:15 +0000934
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000935 ArrayRef<uint8_t> Body = toArrayRef(Saver.save(FunctionBody));
936 cast<SyntheticFunction>(WasmSym::CallCtors->Function)->setBody(Body);
Sam Clegg50686852018-01-12 18:35:13 +0000937}
938
939// Populate InitFunctions vector with init functions from all input objects.
940// This is then used either when creating the output linking section or to
941// synthesize the "__wasm_call_ctors" function.
942void Writer::calculateInitFunctions() {
943 for (ObjFile *File : Symtab->ObjectFiles) {
944 const WasmLinkingData &L = File->getWasmObj()->linkingData();
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +0000945 for (const WasmInitFunc &F : L.InitFunctions) {
946 FunctionSymbol *Sym = File->getFunctionSymbol(F.Symbol);
947 if (*Sym->getFunctionType() != WasmSignature{{}, WASM_TYPE_NORESULT})
948 error("invalid signature for init func: " + toString(*Sym));
949 InitFunctions.emplace_back(WasmInitEntry{Sym, F.Priority});
950 }
Sam Clegg50686852018-01-12 18:35:13 +0000951 }
Rui Ueyamada69b712018-02-28 00:15:59 +0000952
Sam Clegg50686852018-01-12 18:35:13 +0000953 // Sort in order of priority (lowest first) so that they are called
954 // in the correct order.
Sam Clegg29b8feb2018-02-21 00:34:34 +0000955 std::stable_sort(InitFunctions.begin(), InitFunctions.end(),
Sam Clegg93102972018-02-23 05:08:53 +0000956 [](const WasmInitEntry &L, const WasmInitEntry &R) {
Sam Clegg29b8feb2018-02-21 00:34:34 +0000957 return L.Priority < R.Priority;
958 });
Sam Clegg50686852018-01-12 18:35:13 +0000959}
960
Sam Cleggc94d3932017-11-17 18:14:09 +0000961void Writer::run() {
Sam Clegg99eb42c2018-02-27 23:58:03 +0000962 if (Config->Relocatable)
963 Config->GlobalBase = 0;
964
Sam Cleggc94d3932017-11-17 18:14:09 +0000965 log("-- calculateImports");
966 calculateImports();
Sam Clegg8d146bb2018-01-09 23:56:44 +0000967 log("-- assignIndexes");
968 assignIndexes();
Sam Clegg50686852018-01-12 18:35:13 +0000969 log("-- calculateInitFunctions");
970 calculateInitFunctions();
971 if (!Config->Relocatable)
972 createCtorFunction();
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000973 log("-- calculateTypes");
974 calculateTypes();
Sam Clegg93102972018-02-23 05:08:53 +0000975 log("-- layoutMemory");
976 layoutMemory();
977 log("-- calculateExports");
978 calculateExports();
979 log("-- assignSymtab");
980 assignSymtab();
Sam Cleggc94d3932017-11-17 18:14:09 +0000981
982 if (errorHandler().Verbose) {
Sam Clegg9f934222018-02-21 18:29:23 +0000983 log("Defined Functions: " + Twine(InputFunctions.size()));
Sam Clegg93102972018-02-23 05:08:53 +0000984 log("Defined Globals : " + Twine(InputGlobals.size()));
985 log("Function Imports : " + Twine(NumImportedFunctions));
986 log("Global Imports : " + Twine(NumImportedGlobals));
Sam Cleggc94d3932017-11-17 18:14:09 +0000987 for (ObjFile *File : Symtab->ObjectFiles)
988 File->dumpInfo();
989 }
990
Sam Cleggc94d3932017-11-17 18:14:09 +0000991 createHeader();
992 log("-- createSections");
993 createSections();
994
995 log("-- openFile");
996 openFile();
997 if (errorCount())
998 return;
999
1000 writeHeader();
1001
1002 log("-- writeSections");
1003 writeSections();
1004 if (errorCount())
1005 return;
1006
1007 if (Error E = Buffer->commit())
1008 fatal("failed to write the output file: " + toString(std::move(E)));
1009}
1010
1011// Open a result file.
1012void Writer::openFile() {
1013 log("writing: " + Config->OutputFile);
Sam Cleggc94d3932017-11-17 18:14:09 +00001014
1015 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
1016 FileOutputBuffer::create(Config->OutputFile, FileSize,
1017 FileOutputBuffer::F_executable);
1018
1019 if (!BufferOrErr)
1020 error("failed to open " + Config->OutputFile + ": " +
1021 toString(BufferOrErr.takeError()));
1022 else
1023 Buffer = std::move(*BufferOrErr);
1024}
1025
1026void Writer::createHeader() {
1027 raw_string_ostream OS(Header);
1028 writeBytes(OS, WasmMagic, sizeof(WasmMagic), "wasm magic");
1029 writeU32(OS, WasmVersion, "wasm version");
1030 OS.flush();
1031 FileSize += Header.size();
1032}
1033
1034void lld::wasm::writeResult() { Writer().run(); }