blob: 69f3f8832add3fb4d98e4a07c6aaa9002c4ed4c2 [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 Clegg93102972018-02-23 05:08:53 +000023#include "llvm/BinaryFormat/Wasm.h"
Nicholas Wilson3e3f5fb2018-03-14 15:58:16 +000024#include "llvm/Object/WasmTraits.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000025#include "llvm/Support/FileOutputBuffer.h"
26#include "llvm/Support/Format.h"
27#include "llvm/Support/FormatVariadic.h"
28#include "llvm/Support/LEB128.h"
29
30#include <cstdarg>
Sam Clegge0f6fcd2018-01-12 22:25:17 +000031#include <map>
Sam Cleggc94d3932017-11-17 18:14:09 +000032
33#define DEBUG_TYPE "lld"
34
35using namespace llvm;
36using namespace llvm::wasm;
37using namespace lld;
38using namespace lld::wasm;
39
40static constexpr int kStackAlignment = 16;
Sam Clegg48bbd632018-01-24 21:37:30 +000041static constexpr int kInitialTableOffset = 1;
Nicholas Wilson874eedd2018-03-27 17:38:51 +000042static constexpr const char *kFunctionTableName = "__indirect_function_table";
Sam Cleggc94d3932017-11-17 18:14:09 +000043
44namespace {
45
Sam Clegg93102972018-02-23 05:08:53 +000046// An init entry to be written to either the synthetic init func or the
47// linking metadata.
48struct WasmInitEntry {
Sam Clegge3f3ccf2018-03-12 19:56:23 +000049 const FunctionSymbol *Sym;
Sam Clegg93102972018-02-23 05:08:53 +000050 uint32_t Priority;
Sam Cleggd3052d52018-01-18 23:40:49 +000051};
52
Sam Cleggc94d3932017-11-17 18:14:09 +000053// The writer writes a SymbolTable result to a file.
54class Writer {
55public:
56 void run();
57
58private:
59 void openFile();
60
Sam Cleggc375e4e2018-01-10 19:18:22 +000061 uint32_t lookupType(const WasmSignature &Sig);
62 uint32_t registerType(const WasmSignature &Sig);
Sam Clegg93102972018-02-23 05:08:53 +000063
Sam Clegg50686852018-01-12 18:35:13 +000064 void createCtorFunction();
65 void calculateInitFunctions();
Sam Clegg8d146bb2018-01-09 23:56:44 +000066 void assignIndexes();
Sam Cleggc94d3932017-11-17 18:14:09 +000067 void calculateImports();
Sam Cleggd3052d52018-01-18 23:40:49 +000068 void calculateExports();
Sam Clegg93102972018-02-23 05:08:53 +000069 void assignSymtab();
Sam Cleggc94d3932017-11-17 18:14:09 +000070 void calculateTypes();
71 void createOutputSegments();
72 void layoutMemory();
73 void createHeader();
74 void createSections();
Nicholas Wilsondbd90bf2018-03-07 13:28:16 +000075 SyntheticSection *createSyntheticSection(uint32_t Type, StringRef Name = "");
Sam Cleggc94d3932017-11-17 18:14:09 +000076
77 // Builtin sections
78 void createTypeSection();
79 void createFunctionSection();
80 void createTableSection();
81 void createGlobalSection();
82 void createExportSection();
83 void createImportSection();
84 void createMemorySection();
85 void createElemSection();
Sam Cleggc94d3932017-11-17 18:14:09 +000086 void createCodeSection();
87 void createDataSection();
88
89 // Custom sections
90 void createRelocSections();
91 void createLinkingSection();
92 void createNameSection();
93
94 void writeHeader();
95 void writeSections();
96
97 uint64_t FileSize = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +000098 uint32_t NumMemoryPages = 0;
Nicholas Wilson2eb39c12018-03-14 13:53:58 +000099 uint32_t MaxMemoryPages = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000100
101 std::vector<const WasmSignature *> Types;
Nicholas Wilson3e3f5fb2018-03-14 15:58:16 +0000102 DenseMap<WasmSignature, int32_t> TypeIndices;
Sam Clegg93102972018-02-23 05:08:53 +0000103 std::vector<const Symbol *> ImportedSymbols;
104 unsigned NumImportedFunctions = 0;
105 unsigned NumImportedGlobals = 0;
106 std::vector<Symbol *> ExportedSymbols;
107 std::vector<const DefinedData *> DefinedFakeGlobals;
108 std::vector<InputGlobal *> InputGlobals;
Sam Clegg9f934222018-02-21 18:29:23 +0000109 std::vector<InputFunction *> InputFunctions;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000110 std::vector<const FunctionSymbol *> IndirectFunctions;
Sam Clegg93102972018-02-23 05:08:53 +0000111 std::vector<const Symbol *> SymtabEntries;
112 std::vector<WasmInitEntry> InitFunctions;
Sam Cleggc94d3932017-11-17 18:14:09 +0000113
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
Sam Cleggc94d3932017-11-17 18:14:09 +0000126void Writer::createImportSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000127 uint32_t NumImports = ImportedSymbols.size();
Sam Cleggc94d3932017-11-17 18:14:09 +0000128 if (Config->ImportMemory)
129 ++NumImports;
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000130 if (Config->Table == ExposeAs::IMPORT)
131 ++NumImports;
Sam Cleggc94d3932017-11-17 18:14:09 +0000132
133 if (NumImports == 0)
134 return;
135
136 SyntheticSection *Section = createSyntheticSection(WASM_SEC_IMPORT);
137 raw_ostream &OS = Section->getStream();
138
139 writeUleb128(OS, NumImports, "import count");
140
Sam Cleggc94d3932017-11-17 18:14:09 +0000141 if (Config->ImportMemory) {
142 WasmImport Import;
143 Import.Module = "env";
144 Import.Field = "memory";
145 Import.Kind = WASM_EXTERNAL_MEMORY;
146 Import.Memory.Flags = 0;
147 Import.Memory.Initial = NumMemoryPages;
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000148 if (MaxMemoryPages != 0) {
149 Import.Memory.Flags |= WASM_LIMITS_FLAG_HAS_MAX;
150 Import.Memory.Maximum = MaxMemoryPages;
151 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000152 writeImport(OS, Import);
153 }
154
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000155 if (Config->Table == ExposeAs::IMPORT) {
156 uint32_t TableSize = kInitialTableOffset + IndirectFunctions.size();
157 WasmImport Import;
158 Import.Module = "env";
159 Import.Field = kFunctionTableName;
160 Import.Kind = WASM_EXTERNAL_TABLE;
161 Import.Table.ElemType = WASM_TYPE_ANYFUNC;
162 Import.Table.Limits = {WASM_LIMITS_FLAG_HAS_MAX, TableSize, TableSize};
163 writeImport(OS, Import);
164 }
165
Sam Clegg93102972018-02-23 05:08:53 +0000166 for (const Symbol *Sym : ImportedSymbols) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000167 WasmImport Import;
168 Import.Module = "env";
169 Import.Field = Sym->getName();
Sam Clegg93102972018-02-23 05:08:53 +0000170 if (auto *FunctionSym = dyn_cast<FunctionSymbol>(Sym)) {
171 Import.Kind = WASM_EXTERNAL_FUNCTION;
172 Import.SigIndex = lookupType(*FunctionSym->getFunctionType());
173 } else {
174 auto *GlobalSym = cast<GlobalSymbol>(Sym);
175 Import.Kind = WASM_EXTERNAL_GLOBAL;
176 Import.Global = *GlobalSym->getGlobalType();
177 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000178 writeImport(OS, Import);
179 }
180}
181
182void Writer::createTypeSection() {
183 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TYPE);
184 raw_ostream &OS = Section->getStream();
185 writeUleb128(OS, Types.size(), "type count");
Sam Cleggd451da12017-12-19 19:56:27 +0000186 for (const WasmSignature *Sig : Types)
Sam Cleggc94d3932017-11-17 18:14:09 +0000187 writeSig(OS, *Sig);
Sam Cleggc94d3932017-11-17 18:14:09 +0000188}
189
190void Writer::createFunctionSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000191 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000192 return;
193
194 SyntheticSection *Section = createSyntheticSection(WASM_SEC_FUNCTION);
195 raw_ostream &OS = Section->getStream();
196
Sam Clegg9f934222018-02-21 18:29:23 +0000197 writeUleb128(OS, InputFunctions.size(), "function count");
198 for (const InputFunction *Func : InputFunctions)
Sam Cleggc375e4e2018-01-10 19:18:22 +0000199 writeUleb128(OS, lookupType(Func->Signature), "sig index");
Sam Cleggc94d3932017-11-17 18:14:09 +0000200}
201
202void Writer::createMemorySection() {
203 if (Config->ImportMemory)
204 return;
205
206 SyntheticSection *Section = createSyntheticSection(WASM_SEC_MEMORY);
207 raw_ostream &OS = Section->getStream();
208
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000209 bool HasMax = MaxMemoryPages != 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000210 writeUleb128(OS, 1, "memory count");
Nicholas Wilsonca5cc202018-03-14 21:43:04 +0000211 writeUleb128(OS, HasMax ? static_cast<unsigned>(WASM_LIMITS_FLAG_HAS_MAX) : 0,
212 "memory limits flags");
Sam Cleggc94d3932017-11-17 18:14:09 +0000213 writeUleb128(OS, NumMemoryPages, "initial pages");
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000214 if (HasMax)
215 writeUleb128(OS, MaxMemoryPages, "max pages");
Sam Cleggc94d3932017-11-17 18:14:09 +0000216}
217
218void Writer::createGlobalSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000219 unsigned NumGlobals = InputGlobals.size() + DefinedFakeGlobals.size();
220 if (NumGlobals == 0)
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000221 return;
222
Sam Cleggc94d3932017-11-17 18:14:09 +0000223 SyntheticSection *Section = createSyntheticSection(WASM_SEC_GLOBAL);
224 raw_ostream &OS = Section->getStream();
225
Sam Clegg93102972018-02-23 05:08:53 +0000226 writeUleb128(OS, NumGlobals, "global count");
227 for (const InputGlobal *G : InputGlobals)
228 writeGlobal(OS, G->Global);
229 for (const DefinedData *Sym : DefinedFakeGlobals) {
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000230 WasmGlobal Global;
Sam Clegg93102972018-02-23 05:08:53 +0000231 Global.Type = {WASM_TYPE_I32, false};
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000232 Global.InitExpr.Opcode = WASM_OPCODE_I32_CONST;
233 Global.InitExpr.Value.Int32 = Sym->getVirtualAddress();
Sam Cleggc94d3932017-11-17 18:14:09 +0000234 writeGlobal(OS, Global);
235 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000236}
237
238void Writer::createTableSection() {
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000239 if (Config->Table == ExposeAs::IMPORT)
240 return;
241
242 // Always output a table section (or table import), even if there are no
243 // indirect calls. There are two reasons for this:
Sam Cleggfc1a9122017-12-11 22:00:56 +0000244 // 1. For executables it is useful to have an empty table slot at 0
245 // which can be filled with a null function call handler.
246 // 2. If we don't do this, any program that contains a call_indirect but
247 // no address-taken function will fail at validation time since it is
248 // a validation error to include a call_indirect instruction if there
249 // is not table.
Sam Clegg48bbd632018-01-24 21:37:30 +0000250 uint32_t TableSize = kInitialTableOffset + IndirectFunctions.size();
Sam Cleggfc1a9122017-12-11 22:00:56 +0000251
Sam Cleggc94d3932017-11-17 18:14:09 +0000252 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TABLE);
253 raw_ostream &OS = Section->getStream();
254
255 writeUleb128(OS, 1, "table count");
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000256 WasmLimits Limits = {WASM_LIMITS_FLAG_HAS_MAX, TableSize, TableSize};
257 writeTableType(OS, WasmTable{WASM_TYPE_ANYFUNC, Limits});
Sam Cleggc94d3932017-11-17 18:14:09 +0000258}
259
260void Writer::createExportSection() {
Sam Cleggc94d3932017-11-17 18:14:09 +0000261 bool ExportMemory = !Config->Relocatable && !Config->ImportMemory;
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000262 bool ExportTable = !Config->Relocatable && Config->Table == ExposeAs::EXPORT;
Sam Cleggc94d3932017-11-17 18:14:09 +0000263
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000264 uint32_t NumExports =
265 (ExportMemory ? 1 : 0) + (ExportTable ? 1 : 0) + ExportedSymbols.size();
Sam Cleggc94d3932017-11-17 18:14:09 +0000266 if (!NumExports)
267 return;
268
269 SyntheticSection *Section = createSyntheticSection(WASM_SEC_EXPORT);
270 raw_ostream &OS = Section->getStream();
271
272 writeUleb128(OS, NumExports, "export count");
273
Rui Ueyama7d696882018-02-28 00:18:34 +0000274 if (ExportMemory)
275 writeExport(OS, {"memory", WASM_EXTERNAL_MEMORY, 0});
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000276 if (ExportTable)
277 writeExport(OS, {kFunctionTableName, WASM_EXTERNAL_TABLE, 0});
Sam Cleggc94d3932017-11-17 18:14:09 +0000278
Sam Clegg93102972018-02-23 05:08:53 +0000279 unsigned FakeGlobalIndex = NumImportedGlobals + InputGlobals.size();
Rui Ueyama7d696882018-02-28 00:18:34 +0000280
Sam Clegg93102972018-02-23 05:08:53 +0000281 for (const Symbol *Sym : ExportedSymbols) {
Rui Ueyama7d696882018-02-28 00:18:34 +0000282 StringRef Name = Sym->getName();
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000283 WasmExport Export;
Rui Ueyama7d696882018-02-28 00:18:34 +0000284 DEBUG(dbgs() << "Export: " << Name << "\n");
285
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000286 if (auto *F = dyn_cast<DefinedFunction>(Sym))
287 Export = {Name, WASM_EXTERNAL_FUNCTION, F->getFunctionIndex()};
288 else if (auto *G = dyn_cast<DefinedGlobal>(Sym))
289 Export = {Name, WASM_EXTERNAL_GLOBAL, G->getGlobalIndex()};
Rui Ueyama7d696882018-02-28 00:18:34 +0000290 else if (isa<DefinedData>(Sym))
291 Export = {Name, WASM_EXTERNAL_GLOBAL, FakeGlobalIndex++};
292 else
Sam Clegg93102972018-02-23 05:08:53 +0000293 llvm_unreachable("unexpected symbol type");
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000294 writeExport(OS, Export);
Sam Cleggc94d3932017-11-17 18:14:09 +0000295 }
296}
297
Sam Cleggc94d3932017-11-17 18:14:09 +0000298void Writer::createElemSection() {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000299 if (IndirectFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000300 return;
301
302 SyntheticSection *Section = createSyntheticSection(WASM_SEC_ELEM);
303 raw_ostream &OS = Section->getStream();
304
305 writeUleb128(OS, 1, "segment count");
306 writeUleb128(OS, 0, "table index");
307 WasmInitExpr InitExpr;
308 InitExpr.Opcode = WASM_OPCODE_I32_CONST;
Sam Clegg48bbd632018-01-24 21:37:30 +0000309 InitExpr.Value.Int32 = kInitialTableOffset;
Sam Cleggc94d3932017-11-17 18:14:09 +0000310 writeInitExpr(OS, InitExpr);
Sam Cleggfc1a9122017-12-11 22:00:56 +0000311 writeUleb128(OS, IndirectFunctions.size(), "elem count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000312
Sam Clegg48bbd632018-01-24 21:37:30 +0000313 uint32_t TableIndex = kInitialTableOffset;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000314 for (const FunctionSymbol *Sym : IndirectFunctions) {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000315 assert(Sym->getTableIndex() == TableIndex);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000316 writeUleb128(OS, Sym->getFunctionIndex(), "function index");
Sam Cleggfc1a9122017-12-11 22:00:56 +0000317 ++TableIndex;
318 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000319}
320
321void Writer::createCodeSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000322 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000323 return;
324
325 log("createCodeSection");
326
Sam Clegg9f934222018-02-21 18:29:23 +0000327 auto Section = make<CodeSection>(InputFunctions);
Sam Cleggc94d3932017-11-17 18:14:09 +0000328 OutputSections.push_back(Section);
329}
330
331void Writer::createDataSection() {
332 if (!Segments.size())
333 return;
334
335 log("createDataSection");
336 auto Section = make<DataSection>(Segments);
337 OutputSections.push_back(Section);
338}
339
Sam Cleggd451da12017-12-19 19:56:27 +0000340// Create relocations sections in the final output.
Sam Cleggc94d3932017-11-17 18:14:09 +0000341// These are only created when relocatable output is requested.
342void Writer::createRelocSections() {
343 log("createRelocSections");
344 // Don't use iterator here since we are adding to OutputSection
345 size_t OrigSize = OutputSections.size();
346 for (size_t i = 0; i < OrigSize; i++) {
Rui Ueyama37254062018-02-28 00:01:31 +0000347 OutputSection *OSec = OutputSections[i];
348 uint32_t Count = OSec->numRelocations();
Sam Cleggc94d3932017-11-17 18:14:09 +0000349 if (!Count)
350 continue;
351
Rui Ueyama37254062018-02-28 00:01:31 +0000352 StringRef Name;
353 if (OSec->Type == WASM_SEC_DATA)
354 Name = "reloc.DATA";
355 else if (OSec->Type == WASM_SEC_CODE)
356 Name = "reloc.CODE";
Sam Cleggc94d3932017-11-17 18:14:09 +0000357 else
Sam Cleggd451da12017-12-19 19:56:27 +0000358 llvm_unreachable("relocations only supported for code and data");
Sam Cleggc94d3932017-11-17 18:14:09 +0000359
Rui Ueyama37254062018-02-28 00:01:31 +0000360 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, Name);
Sam Cleggc94d3932017-11-17 18:14:09 +0000361 raw_ostream &OS = Section->getStream();
Rui Ueyama37254062018-02-28 00:01:31 +0000362 writeUleb128(OS, OSec->Type, "reloc section");
Sam Cleggc94d3932017-11-17 18:14:09 +0000363 writeUleb128(OS, Count, "reloc count");
Rui Ueyama37254062018-02-28 00:01:31 +0000364 OSec->writeRelocations(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000365 }
366}
367
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000368static uint32_t getWasmFlags(const Symbol *Sym) {
369 uint32_t Flags = 0;
370 if (Sym->isLocal())
371 Flags |= WASM_SYMBOL_BINDING_LOCAL;
372 if (Sym->isWeak())
373 Flags |= WASM_SYMBOL_BINDING_WEAK;
374 if (Sym->isHidden())
375 Flags |= WASM_SYMBOL_VISIBILITY_HIDDEN;
376 if (Sym->isUndefined())
377 Flags |= WASM_SYMBOL_UNDEFINED;
378 return Flags;
379}
380
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000381// Some synthetic sections (e.g. "name" and "linking") have subsections.
382// Just like the synthetic sections themselves these need to be created before
383// they can be written out (since they are preceded by their length). This
384// class is used to create subsections and then write them into the stream
385// of the parent section.
386class SubSection {
387public:
388 explicit SubSection(uint32_t Type) : Type(Type) {}
389
390 void writeTo(raw_ostream &To) {
391 OS.flush();
Rui Ueyama67769102018-02-28 03:38:14 +0000392 writeUleb128(To, Type, "subsection type");
393 writeUleb128(To, Body.size(), "subsection size");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000394 To.write(Body.data(), Body.size());
395 }
396
397private:
398 uint32_t Type;
399 std::string Body;
400
401public:
402 raw_string_ostream OS{Body};
403};
404
Sam Clegg49ed9262017-12-01 00:53:21 +0000405// Create the custom "linking" section containing linker metadata.
Sam Cleggc94d3932017-11-17 18:14:09 +0000406// This is only created when relocatable output is requested.
407void Writer::createLinkingSection() {
408 SyntheticSection *Section =
409 createSyntheticSection(WASM_SEC_CUSTOM, "linking");
410 raw_ostream &OS = Section->getStream();
411
Sam Clegg0d0dd392017-12-19 17:09:45 +0000412 if (!Config->Relocatable)
413 return;
414
Sam Clegg93102972018-02-23 05:08:53 +0000415 if (!SymtabEntries.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000416 SubSection Sub(WASM_SYMBOL_TABLE);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000417 writeUleb128(Sub.OS, SymtabEntries.size(), "num symbols");
418
Sam Clegg93102972018-02-23 05:08:53 +0000419 for (const Symbol *Sym : SymtabEntries) {
420 assert(Sym->isDefined() || Sym->isUndefined());
421 WasmSymbolType Kind = Sym->getWasmType();
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000422 uint32_t Flags = getWasmFlags(Sym);
423
Sam Clegg8518e7d2018-03-01 18:06:39 +0000424 writeU8(Sub.OS, Kind, "sym kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000425 writeUleb128(Sub.OS, Flags, "sym flags");
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000426
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000427 if (auto *F = dyn_cast<FunctionSymbol>(Sym)) {
428 writeUleb128(Sub.OS, F->getFunctionIndex(), "index");
Sam Clegg93102972018-02-23 05:08:53 +0000429 if (Sym->isDefined())
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000430 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000431 } else if (auto *G = dyn_cast<GlobalSymbol>(Sym)) {
432 writeUleb128(Sub.OS, G->getGlobalIndex(), "index");
433 if (Sym->isDefined())
434 writeStr(Sub.OS, Sym->getName(), "sym name");
435 } else {
436 assert(isa<DataSymbol>(Sym));
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000437 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegg93102972018-02-23 05:08:53 +0000438 if (auto *DataSym = dyn_cast<DefinedData>(Sym)) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000439 writeUleb128(Sub.OS, DataSym->getOutputSegmentIndex(), "index");
440 writeUleb128(Sub.OS, DataSym->getOutputSegmentOffset(),
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000441 "data offset");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000442 writeUleb128(Sub.OS, DataSym->getSize(), "data size");
Sam Clegg93102972018-02-23 05:08:53 +0000443 }
Sam Clegg93102972018-02-23 05:08:53 +0000444 }
Sam Cleggd3052d52018-01-18 23:40:49 +0000445 }
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000446
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000447 Sub.writeTo(OS);
Sam Cleggd3052d52018-01-18 23:40:49 +0000448 }
449
Sam Clegg0d0dd392017-12-19 17:09:45 +0000450 if (Segments.size()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000451 SubSection Sub(WASM_SEGMENT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000452 writeUleb128(Sub.OS, Segments.size(), "num data segments");
Sam Cleggc94d3932017-11-17 18:14:09 +0000453 for (const OutputSegment *S : Segments) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000454 writeStr(Sub.OS, S->Name, "segment name");
455 writeUleb128(Sub.OS, S->Alignment, "alignment");
456 writeUleb128(Sub.OS, 0, "flags");
Sam Cleggc94d3932017-11-17 18:14:09 +0000457 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000458 Sub.writeTo(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000459 }
Sam Clegg0d0dd392017-12-19 17:09:45 +0000460
Sam Clegg0d0dd392017-12-19 17:09:45 +0000461 if (!InitFunctions.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000462 SubSection Sub(WASM_INIT_FUNCS);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000463 writeUleb128(Sub.OS, InitFunctions.size(), "num init functions");
Sam Clegg93102972018-02-23 05:08:53 +0000464 for (const WasmInitEntry &F : InitFunctions) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000465 writeUleb128(Sub.OS, F.Priority, "priority");
466 writeUleb128(Sub.OS, F.Sym->getOutputSymbolIndex(), "function index");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000467 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000468 Sub.writeTo(OS);
Sam Clegg0d0dd392017-12-19 17:09:45 +0000469 }
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000470
Nicholas Wilsondbd90bf2018-03-07 13:28:16 +0000471 struct ComdatEntry {
472 unsigned Kind;
473 uint32_t Index;
474 };
475 std::map<StringRef, std::vector<ComdatEntry>> Comdats;
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000476
Sam Clegg9f934222018-02-21 18:29:23 +0000477 for (const InputFunction *F : InputFunctions) {
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000478 StringRef Comdat = F->getComdatName();
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000479 if (!Comdat.empty())
480 Comdats[Comdat].emplace_back(
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000481 ComdatEntry{WASM_COMDAT_FUNCTION, F->getFunctionIndex()});
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000482 }
483 for (uint32_t I = 0; I < Segments.size(); ++I) {
Sam Cleggf98bccf2018-01-13 15:57:48 +0000484 const auto &InputSegments = Segments[I]->InputSegments;
485 if (InputSegments.empty())
486 continue;
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000487 StringRef Comdat = InputSegments[0]->getComdatName();
Sam Clegga697df522018-01-13 15:59:53 +0000488#ifndef NDEBUG
Sam Cleggf98bccf2018-01-13 15:57:48 +0000489 for (const InputSegment *IS : InputSegments)
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000490 assert(IS->getComdatName() == Comdat);
Sam Clegga697df522018-01-13 15:59:53 +0000491#endif
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000492 if (!Comdat.empty())
493 Comdats[Comdat].emplace_back(ComdatEntry{WASM_COMDAT_DATA, I});
494 }
495
496 if (!Comdats.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000497 SubSection Sub(WASM_COMDAT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000498 writeUleb128(Sub.OS, Comdats.size(), "num comdats");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000499 for (const auto &C : Comdats) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000500 writeStr(Sub.OS, C.first, "comdat name");
501 writeUleb128(Sub.OS, 0, "comdat flags"); // flags for future use
502 writeUleb128(Sub.OS, C.second.size(), "num entries");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000503 for (const ComdatEntry &Entry : C.second) {
Sam Clegg8518e7d2018-03-01 18:06:39 +0000504 writeU8(Sub.OS, Entry.Kind, "entry kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000505 writeUleb128(Sub.OS, Entry.Index, "entry index");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000506 }
507 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000508 Sub.writeTo(OS);
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000509 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000510}
511
512// Create the custom "name" section containing debug symbol names.
513void Writer::createNameSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000514 unsigned NumNames = NumImportedFunctions;
Sam Clegg9f934222018-02-21 18:29:23 +0000515 for (const InputFunction *F : InputFunctions)
Sam Clegg1963d712018-01-17 20:19:04 +0000516 if (!F->getName().empty())
517 ++NumNames;
Sam Cleggc94d3932017-11-17 18:14:09 +0000518
Sam Clegg1963d712018-01-17 20:19:04 +0000519 if (NumNames == 0)
520 return;
Sam Clegg50686852018-01-12 18:35:13 +0000521
Sam Cleggc94d3932017-11-17 18:14:09 +0000522 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "name");
523
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000524 SubSection Sub(WASM_NAMES_FUNCTION);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000525 writeUleb128(Sub.OS, NumNames, "name count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000526
Sam Clegg93102972018-02-23 05:08:53 +0000527 // Names must appear in function index order. As it happens ImportedSymbols
528 // and InputFunctions are numbered in order with imported functions coming
Sam Clegg1963d712018-01-17 20:19:04 +0000529 // first.
Sam Clegg93102972018-02-23 05:08:53 +0000530 for (const Symbol *S : ImportedSymbols) {
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000531 if (auto *F = dyn_cast<FunctionSymbol>(S)) {
532 writeUleb128(Sub.OS, F->getFunctionIndex(), "func index");
Nicholas Wilson531769b2018-03-13 13:30:04 +0000533 Optional<std::string> Name = demangleItanium(F->getName());
534 writeStr(Sub.OS, Name ? StringRef(*Name) : F->getName(), "symbol name");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000535 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000536 }
Sam Clegg9f934222018-02-21 18:29:23 +0000537 for (const InputFunction *F : InputFunctions) {
Sam Clegg1963d712018-01-17 20:19:04 +0000538 if (!F->getName().empty()) {
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000539 writeUleb128(Sub.OS, F->getFunctionIndex(), "func index");
Nicholas Wilson531769b2018-03-13 13:30:04 +0000540 Optional<std::string> Name = demangleItanium(F->getName());
541 writeStr(Sub.OS, Name ? StringRef(*Name) : F->getName(), "symbol name");
Sam Clegg1963d712018-01-17 20:19:04 +0000542 }
543 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000544
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000545 Sub.writeTo(Section->getStream());
Sam Cleggc94d3932017-11-17 18:14:09 +0000546}
547
548void Writer::writeHeader() {
549 memcpy(Buffer->getBufferStart(), Header.data(), Header.size());
550}
551
552void Writer::writeSections() {
553 uint8_t *Buf = Buffer->getBufferStart();
554 parallelForEach(OutputSections, [Buf](OutputSection *S) { S->writeTo(Buf); });
555}
556
557// Fix the memory layout of the output binary. This assigns memory offsets
Sam Clegg49ed9262017-12-01 00:53:21 +0000558// to each of the input data sections as well as the explicit stack region.
Sam Cleggf0d433d2018-02-02 22:59:56 +0000559// The memory layout is as follows, from low to high.
560// - initialized data (starting at Config->GlobalBase)
561// - BSS data (not currently implemented in llvm)
562// - explicit stack (Config->ZStackSize)
563// - heap start / unallocated
Sam Cleggc94d3932017-11-17 18:14:09 +0000564void Writer::layoutMemory() {
565 uint32_t MemoryPtr = 0;
Sam Clegg99eb42c2018-02-27 23:58:03 +0000566 MemoryPtr = Config->GlobalBase;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000567 log("mem: global base = " + Twine(Config->GlobalBase));
Sam Cleggc94d3932017-11-17 18:14:09 +0000568
569 createOutputSegments();
570
Sam Cleggf0d433d2018-02-02 22:59:56 +0000571 // Arbitrarily set __dso_handle handle to point to the start of the data
572 // segments.
573 if (WasmSym::DsoHandle)
574 WasmSym::DsoHandle->setVirtualAddress(MemoryPtr);
575
Sam Cleggc94d3932017-11-17 18:14:09 +0000576 for (OutputSegment *Seg : Segments) {
577 MemoryPtr = alignTo(MemoryPtr, Seg->Alignment);
578 Seg->StartVA = MemoryPtr;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000579 log(formatv("mem: {0,-15} offset={1,-8} size={2,-8} align={3}", Seg->Name,
580 MemoryPtr, Seg->Size, Seg->Alignment));
Sam Cleggc94d3932017-11-17 18:14:09 +0000581 MemoryPtr += Seg->Size;
582 }
583
Sam Cleggf0d433d2018-02-02 22:59:56 +0000584 // TODO: Add .bss space here.
Sam Clegg37a4a8a2018-02-07 03:04:53 +0000585 if (WasmSym::DataEnd)
586 WasmSym::DataEnd->setVirtualAddress(MemoryPtr);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000587
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000588 log("mem: static data = " + Twine(MemoryPtr - Config->GlobalBase));
Sam Cleggc94d3932017-11-17 18:14:09 +0000589
Sam Cleggf0d433d2018-02-02 22:59:56 +0000590 // Stack comes after static data and bss
Sam Cleggc94d3932017-11-17 18:14:09 +0000591 if (!Config->Relocatable) {
592 MemoryPtr = alignTo(MemoryPtr, kStackAlignment);
593 if (Config->ZStackSize != alignTo(Config->ZStackSize, kStackAlignment))
594 error("stack size must be " + Twine(kStackAlignment) + "-byte aligned");
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000595 log("mem: stack size = " + Twine(Config->ZStackSize));
596 log("mem: stack base = " + Twine(MemoryPtr));
Sam Cleggc94d3932017-11-17 18:14:09 +0000597 MemoryPtr += Config->ZStackSize;
Sam Clegg93102972018-02-23 05:08:53 +0000598 WasmSym::StackPointer->Global->Global.InitExpr.Value.Int32 = MemoryPtr;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000599 log("mem: stack top = " + Twine(MemoryPtr));
Sam Clegg93102972018-02-23 05:08:53 +0000600
Sam Clegg51bcdc22018-01-17 01:34:31 +0000601 // Set `__heap_base` to directly follow the end of the stack. We don't
602 // allocate any heap memory up front, but instead really on the malloc/brk
603 // implementation growing the memory at runtime.
Sam Cleggf0d433d2018-02-02 22:59:56 +0000604 WasmSym::HeapBase->setVirtualAddress(MemoryPtr);
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000605 log("mem: heap base = " + Twine(MemoryPtr));
Sam Cleggc94d3932017-11-17 18:14:09 +0000606 }
607
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000608 if (Config->InitialMemory != 0) {
609 if (Config->InitialMemory != alignTo(Config->InitialMemory, WasmPageSize))
610 error("initial memory must be " + Twine(WasmPageSize) + "-byte aligned");
611 if (MemoryPtr > Config->InitialMemory)
612 error("initial memory too small, " + Twine(MemoryPtr) + " bytes needed");
613 else
614 MemoryPtr = Config->InitialMemory;
615 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000616 uint32_t MemSize = alignTo(MemoryPtr, WasmPageSize);
617 NumMemoryPages = MemSize / WasmPageSize;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000618 log("mem: total pages = " + Twine(NumMemoryPages));
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000619
620 if (Config->MaxMemory != 0) {
621 if (Config->MaxMemory != alignTo(Config->MaxMemory, WasmPageSize))
622 error("maximum memory must be " + Twine(WasmPageSize) + "-byte aligned");
623 if (MemoryPtr > Config->MaxMemory)
624 error("maximum memory too small, " + Twine(MemoryPtr) + " bytes needed");
625 MaxMemoryPages = Config->MaxMemory / WasmPageSize;
626 log("mem: max pages = " + Twine(MaxMemoryPages));
627 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000628}
629
630SyntheticSection *Writer::createSyntheticSection(uint32_t Type,
Sam Cleggc375e4e2018-01-10 19:18:22 +0000631 StringRef Name) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000632 auto Sec = make<SyntheticSection>(Type, Name);
Sam Cleggab2ac292017-12-20 05:14:48 +0000633 log("createSection: " + toString(*Sec));
Sam Cleggc94d3932017-11-17 18:14:09 +0000634 OutputSections.push_back(Sec);
635 return Sec;
636}
637
638void Writer::createSections() {
639 // Known sections
640 createTypeSection();
641 createImportSection();
642 createFunctionSection();
643 createTableSection();
644 createMemorySection();
645 createGlobalSection();
646 createExportSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000647 createElemSection();
648 createCodeSection();
649 createDataSection();
650
651 // Custom sections
Sam Clegg99eb42c2018-02-27 23:58:03 +0000652 if (Config->Relocatable) {
Sam Clegg99eb42c2018-02-27 23:58:03 +0000653 createLinkingSection();
Nicholas Wilson94d3b162018-03-05 12:33:58 +0000654 createRelocSections();
Sam Clegg99eb42c2018-02-27 23:58:03 +0000655 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000656 if (!Config->StripDebug && !Config->StripAll)
657 createNameSection();
658
659 for (OutputSection *S : OutputSections) {
660 S->setOffset(FileSize);
661 S->finalizeContents();
662 FileSize += S->getSize();
663 }
664}
665
Sam Cleggc94d3932017-11-17 18:14:09 +0000666void Writer::calculateImports() {
Sam Clegg574d7ce2017-12-15 19:23:49 +0000667 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000668 if (!Sym->isUndefined())
669 continue;
670 if (isa<DataSymbol>(Sym))
671 continue;
672 if (Sym->isWeak() && !Config->Relocatable)
Sam Clegg574d7ce2017-12-15 19:23:49 +0000673 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000674
Sam Clegg93102972018-02-23 05:08:53 +0000675 DEBUG(dbgs() << "import: " << Sym->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000676 ImportedSymbols.emplace_back(Sym);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000677 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
678 F->setFunctionIndex(NumImportedFunctions++);
Sam Clegg93102972018-02-23 05:08:53 +0000679 else
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000680 cast<GlobalSymbol>(Sym)->setGlobalIndex(NumImportedGlobals++);
Sam Cleggc94d3932017-11-17 18:14:09 +0000681 }
682}
683
Sam Cleggd3052d52018-01-18 23:40:49 +0000684void Writer::calculateExports() {
Sam Clegg93102972018-02-23 05:08:53 +0000685 if (Config->Relocatable)
686 return;
Sam Cleggf0d433d2018-02-02 22:59:56 +0000687
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000688 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000689 if (!Sym->isDefined())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000690 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000691 if (Sym->isHidden() || Sym->isLocal())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000692 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000693 if (!Sym->isLive())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000694 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000695
696 DEBUG(dbgs() << "exporting sym: " << Sym->getName() << "\n");
697
Nicholas Wilsonf2f6d5e2018-03-02 14:51:36 +0000698 if (auto *D = dyn_cast<DefinedData>(Sym))
Sam Clegg93102972018-02-23 05:08:53 +0000699 DefinedFakeGlobals.emplace_back(D);
Sam Clegg93102972018-02-23 05:08:53 +0000700 ExportedSymbols.emplace_back(Sym);
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000701 }
Sam Clegg93102972018-02-23 05:08:53 +0000702}
703
704void Writer::assignSymtab() {
705 if (!Config->Relocatable)
706 return;
707
708 unsigned SymbolIndex = SymtabEntries.size();
Sam Cleggd3052d52018-01-18 23:40:49 +0000709 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg93102972018-02-23 05:08:53 +0000710 DEBUG(dbgs() << "Symtab entries: " << File->getName() << "\n");
Sam Cleggd3052d52018-01-18 23:40:49 +0000711 for (Symbol *Sym : File->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000712 if (Sym->getFile() != File)
Sam Cleggd3052d52018-01-18 23:40:49 +0000713 continue;
Nicholas Wilson06e0d172018-03-07 11:15:47 +0000714 // (Since this is relocatable output, GC is not performed so symbols must
715 // be live.)
716 assert(Sym->isLive());
Sam Clegg93102972018-02-23 05:08:53 +0000717 Sym->setOutputSymbolIndex(SymbolIndex++);
718 SymtabEntries.emplace_back(Sym);
Sam Cleggd3052d52018-01-18 23:40:49 +0000719 }
720 }
721
Sam Clegg93102972018-02-23 05:08:53 +0000722 // For the moment, relocatable output doesn't contain any synthetic functions,
723 // so no need to look through the Symtab for symbols not referenced by
724 // Symtab->ObjectFiles.
Sam Cleggd3052d52018-01-18 23:40:49 +0000725}
726
Sam Cleggc375e4e2018-01-10 19:18:22 +0000727uint32_t Writer::lookupType(const WasmSignature &Sig) {
Sam Clegg8d027d62018-01-10 20:12:26 +0000728 auto It = TypeIndices.find(Sig);
729 if (It == TypeIndices.end()) {
Sam Cleggc375e4e2018-01-10 19:18:22 +0000730 error("type not found: " + toString(Sig));
Sam Clegg8d027d62018-01-10 20:12:26 +0000731 return 0;
732 }
733 return It->second;
Sam Cleggc375e4e2018-01-10 19:18:22 +0000734}
735
736uint32_t Writer::registerType(const WasmSignature &Sig) {
Sam Cleggb8621592017-11-30 01:40:08 +0000737 auto Pair = TypeIndices.insert(std::make_pair(Sig, Types.size()));
Sam Cleggc375e4e2018-01-10 19:18:22 +0000738 if (Pair.second) {
739 DEBUG(dbgs() << "type " << toString(Sig) << "\n");
Sam Cleggb8621592017-11-30 01:40:08 +0000740 Types.push_back(&Sig);
Sam Cleggc375e4e2018-01-10 19:18:22 +0000741 }
Sam Cleggb8621592017-11-30 01:40:08 +0000742 return Pair.first->second;
743}
744
Sam Cleggc94d3932017-11-17 18:14:09 +0000745void Writer::calculateTypes() {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000746 // The output type section is the union of the following sets:
747 // 1. Any signature used in the TYPE relocation
748 // 2. The signatures of all imported functions
749 // 3. The signatures of all defined functions
750
Sam Cleggc94d3932017-11-17 18:14:09 +0000751 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000752 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
753 for (uint32_t I = 0; I < Types.size(); I++)
754 if (File->TypeIsUsed[I])
755 File->TypeMap[I] = registerType(Types[I]);
Sam Cleggc94d3932017-11-17 18:14:09 +0000756 }
Sam Clegg50686852018-01-12 18:35:13 +0000757
Sam Clegg93102972018-02-23 05:08:53 +0000758 for (const Symbol *Sym : ImportedSymbols)
759 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
760 registerType(*F->getFunctionType());
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000761
Sam Clegg9f934222018-02-21 18:29:23 +0000762 for (const InputFunction *F : InputFunctions)
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000763 registerType(F->Signature);
Sam Cleggc94d3932017-11-17 18:14:09 +0000764}
765
Sam Clegg8d146bb2018-01-09 23:56:44 +0000766void Writer::assignIndexes() {
Sam Clegg93102972018-02-23 05:08:53 +0000767 uint32_t FunctionIndex = NumImportedFunctions + InputFunctions.size();
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000768 auto AddDefinedFunction = [&](InputFunction *Func) {
769 if (!Func->Live)
770 return;
771 InputFunctions.emplace_back(Func);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000772 Func->setFunctionIndex(FunctionIndex++);
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000773 };
774
Nicholas Wilson5639da82018-03-12 15:44:07 +0000775 for (InputFunction *Func : Symtab->SyntheticFunctions)
776 AddDefinedFunction(Func);
777
Sam Clegg87e61922018-01-08 23:39:11 +0000778 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8d146bb2018-01-09 23:56:44 +0000779 DEBUG(dbgs() << "Functions: " << File->getName() << "\n");
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000780 for (InputFunction *Func : File->Functions)
781 AddDefinedFunction(Func);
Sam Clegg8d146bb2018-01-09 23:56:44 +0000782 }
783
Sam Clegg93102972018-02-23 05:08:53 +0000784 uint32_t TableIndex = kInitialTableOffset;
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000785 auto HandleRelocs = [&](InputChunk *Chunk) {
786 if (!Chunk->Live)
787 return;
788 ObjFile *File = Chunk->File;
789 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
Sam Clegg93102972018-02-23 05:08:53 +0000790 for (const WasmRelocation &Reloc : Chunk->getRelocations()) {
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000791 if (Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_I32 ||
792 Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_SLEB) {
793 FunctionSymbol *Sym = File->getFunctionSymbol(Reloc.Index);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000794 if (Sym->hasTableIndex() || !Sym->hasFunctionIndex())
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000795 continue;
796 Sym->setTableIndex(TableIndex++);
797 IndirectFunctions.emplace_back(Sym);
798 } else if (Reloc.Type == R_WEBASSEMBLY_TYPE_INDEX_LEB) {
Sam Clegg93102972018-02-23 05:08:53 +0000799 // Mark target type as live
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000800 File->TypeMap[Reloc.Index] = registerType(Types[Reloc.Index]);
801 File->TypeIsUsed[Reloc.Index] = true;
Sam Clegg93102972018-02-23 05:08:53 +0000802 } else if (Reloc.Type == R_WEBASSEMBLY_GLOBAL_INDEX_LEB) {
803 // Mark target global as live
804 GlobalSymbol *Sym = File->getGlobalSymbol(Reloc.Index);
805 if (auto *G = dyn_cast<DefinedGlobal>(Sym)) {
806 DEBUG(dbgs() << "marking global live: " << Sym->getName() << "\n");
807 G->Global->Live = true;
808 }
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000809 }
810 }
811 };
812
Sam Clegg8d146bb2018-01-09 23:56:44 +0000813 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000814 DEBUG(dbgs() << "Handle relocs: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000815 for (InputChunk *Chunk : File->Functions)
816 HandleRelocs(Chunk);
817 for (InputChunk *Chunk : File->Segments)
818 HandleRelocs(Chunk);
819 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000820
Sam Clegg93102972018-02-23 05:08:53 +0000821 uint32_t GlobalIndex = NumImportedGlobals + InputGlobals.size();
822 auto AddDefinedGlobal = [&](InputGlobal *Global) {
823 if (Global->Live) {
824 DEBUG(dbgs() << "AddDefinedGlobal: " << GlobalIndex << "\n");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000825 Global->setGlobalIndex(GlobalIndex++);
Sam Clegg93102972018-02-23 05:08:53 +0000826 InputGlobals.push_back(Global);
827 }
828 };
829
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000830 for (InputGlobal *Global : Symtab->SyntheticGlobals)
831 AddDefinedGlobal(Global);
Sam Clegg93102972018-02-23 05:08:53 +0000832
833 for (ObjFile *File : Symtab->ObjectFiles) {
834 DEBUG(dbgs() << "Globals: " << File->getName() << "\n");
835 for (InputGlobal *Global : File->Globals)
836 AddDefinedGlobal(Global);
Sam Cleggc94d3932017-11-17 18:14:09 +0000837 }
838}
839
840static StringRef getOutputDataSegmentName(StringRef Name) {
841 if (Config->Relocatable)
842 return Name;
Rui Ueyama4764b572018-02-28 00:57:28 +0000843 if (Name.startswith(".text."))
844 return ".text";
845 if (Name.startswith(".data."))
846 return ".data";
847 if (Name.startswith(".bss."))
848 return ".bss";
Sam Cleggc94d3932017-11-17 18:14:09 +0000849 return Name;
850}
851
852void Writer::createOutputSegments() {
853 for (ObjFile *File : Symtab->ObjectFiles) {
854 for (InputSegment *Segment : File->Segments) {
Sam Clegg447ae402018-02-13 20:29:38 +0000855 if (!Segment->Live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000856 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000857 StringRef Name = getOutputDataSegmentName(Segment->getName());
858 OutputSegment *&S = SegmentMap[Name];
859 if (S == nullptr) {
860 DEBUG(dbgs() << "new segment: " << Name << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000861 S = make<OutputSegment>(Name, Segments.size());
Sam Cleggc94d3932017-11-17 18:14:09 +0000862 Segments.push_back(S);
863 }
864 S->addInputSegment(Segment);
865 DEBUG(dbgs() << "added data: " << Name << ": " << S->Size << "\n");
Sam Cleggc94d3932017-11-17 18:14:09 +0000866 }
867 }
868}
869
Sam Clegg50686852018-01-12 18:35:13 +0000870static const int OPCODE_CALL = 0x10;
871static const int OPCODE_END = 0xb;
872
873// Create synthetic "__wasm_call_ctors" function based on ctor functions
874// in input object.
875void Writer::createCtorFunction() {
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000876 // First write the body's contents to a string.
877 std::string BodyContent;
Sam Clegg50686852018-01-12 18:35:13 +0000878 {
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000879 raw_string_ostream OS(BodyContent);
Sam Clegg50686852018-01-12 18:35:13 +0000880 writeUleb128(OS, 0, "num locals");
Sam Clegg93102972018-02-23 05:08:53 +0000881 for (const WasmInitEntry &F : InitFunctions) {
Sam Clegg50686852018-01-12 18:35:13 +0000882 writeU8(OS, OPCODE_CALL, "CALL");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000883 writeUleb128(OS, F.Sym->getFunctionIndex(), "function index");
Sam Clegg50686852018-01-12 18:35:13 +0000884 }
885 writeU8(OS, OPCODE_END, "END");
886 }
887
888 // Once we know the size of the body we can create the final function body
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000889 std::string FunctionBody;
890 {
891 raw_string_ostream OS(FunctionBody);
892 writeUleb128(OS, BodyContent.size(), "function size");
893 OS << BodyContent;
894 }
Rui Ueyama29abfe42018-02-28 17:43:15 +0000895
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000896 ArrayRef<uint8_t> Body = toArrayRef(Saver.save(FunctionBody));
897 cast<SyntheticFunction>(WasmSym::CallCtors->Function)->setBody(Body);
Sam Clegg50686852018-01-12 18:35:13 +0000898}
899
900// Populate InitFunctions vector with init functions from all input objects.
901// This is then used either when creating the output linking section or to
902// synthesize the "__wasm_call_ctors" function.
903void Writer::calculateInitFunctions() {
904 for (ObjFile *File : Symtab->ObjectFiles) {
905 const WasmLinkingData &L = File->getWasmObj()->linkingData();
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +0000906 for (const WasmInitFunc &F : L.InitFunctions) {
907 FunctionSymbol *Sym = File->getFunctionSymbol(F.Symbol);
908 if (*Sym->getFunctionType() != WasmSignature{{}, WASM_TYPE_NORESULT})
909 error("invalid signature for init func: " + toString(*Sym));
910 InitFunctions.emplace_back(WasmInitEntry{Sym, F.Priority});
911 }
Sam Clegg50686852018-01-12 18:35:13 +0000912 }
Rui Ueyamada69b712018-02-28 00:15:59 +0000913
Sam Clegg50686852018-01-12 18:35:13 +0000914 // Sort in order of priority (lowest first) so that they are called
915 // in the correct order.
Sam Clegg29b8feb2018-02-21 00:34:34 +0000916 std::stable_sort(InitFunctions.begin(), InitFunctions.end(),
Sam Clegg93102972018-02-23 05:08:53 +0000917 [](const WasmInitEntry &L, const WasmInitEntry &R) {
Sam Clegg29b8feb2018-02-21 00:34:34 +0000918 return L.Priority < R.Priority;
919 });
Sam Clegg50686852018-01-12 18:35:13 +0000920}
921
Sam Cleggc94d3932017-11-17 18:14:09 +0000922void Writer::run() {
Sam Clegg99eb42c2018-02-27 23:58:03 +0000923 if (Config->Relocatable)
924 Config->GlobalBase = 0;
925
Sam Cleggc94d3932017-11-17 18:14:09 +0000926 log("-- calculateImports");
927 calculateImports();
Sam Clegg8d146bb2018-01-09 23:56:44 +0000928 log("-- assignIndexes");
929 assignIndexes();
Sam Clegg50686852018-01-12 18:35:13 +0000930 log("-- calculateInitFunctions");
931 calculateInitFunctions();
932 if (!Config->Relocatable)
933 createCtorFunction();
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000934 log("-- calculateTypes");
935 calculateTypes();
Sam Clegg93102972018-02-23 05:08:53 +0000936 log("-- layoutMemory");
937 layoutMemory();
938 log("-- calculateExports");
939 calculateExports();
940 log("-- assignSymtab");
941 assignSymtab();
Sam Cleggc94d3932017-11-17 18:14:09 +0000942
943 if (errorHandler().Verbose) {
Sam Clegg9f934222018-02-21 18:29:23 +0000944 log("Defined Functions: " + Twine(InputFunctions.size()));
Sam Clegg93102972018-02-23 05:08:53 +0000945 log("Defined Globals : " + Twine(InputGlobals.size()));
946 log("Function Imports : " + Twine(NumImportedFunctions));
947 log("Global Imports : " + Twine(NumImportedGlobals));
Sam Cleggc94d3932017-11-17 18:14:09 +0000948 for (ObjFile *File : Symtab->ObjectFiles)
949 File->dumpInfo();
950 }
951
Sam Cleggc94d3932017-11-17 18:14:09 +0000952 createHeader();
953 log("-- createSections");
954 createSections();
955
956 log("-- openFile");
957 openFile();
958 if (errorCount())
959 return;
960
961 writeHeader();
962
963 log("-- writeSections");
964 writeSections();
965 if (errorCount())
966 return;
967
968 if (Error E = Buffer->commit())
969 fatal("failed to write the output file: " + toString(std::move(E)));
970}
971
972// Open a result file.
973void Writer::openFile() {
974 log("writing: " + Config->OutputFile);
Sam Cleggc94d3932017-11-17 18:14:09 +0000975
976 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
977 FileOutputBuffer::create(Config->OutputFile, FileSize,
978 FileOutputBuffer::F_executable);
979
980 if (!BufferOrErr)
981 error("failed to open " + Config->OutputFile + ": " +
982 toString(BufferOrErr.takeError()));
983 else
984 Buffer = std::move(*BufferOrErr);
985}
986
987void Writer::createHeader() {
988 raw_string_ostream OS(Header);
989 writeBytes(OS, WasmMagic, sizeof(WasmMagic), "wasm magic");
990 writeU32(OS, WasmVersion, "wasm version");
991 OS.flush();
992 FileSize += Header.size();
993}
994
995void lld::wasm::writeResult() { Writer().run(); }