blob: 3c6a90bf1bbf301e38ba4bca150b11e2a8ec8520 [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"
Sam Cleggc94d3932017-11-17 18:14:09 +000024#include "llvm/Support/FileOutputBuffer.h"
25#include "llvm/Support/Format.h"
26#include "llvm/Support/FormatVariadic.h"
27#include "llvm/Support/LEB128.h"
28
29#include <cstdarg>
Sam Clegge0f6fcd2018-01-12 22:25:17 +000030#include <map>
Sam Cleggc94d3932017-11-17 18:14:09 +000031
32#define DEBUG_TYPE "lld"
33
34using namespace llvm;
35using namespace llvm::wasm;
36using namespace lld;
37using namespace lld::wasm;
38
39static constexpr int kStackAlignment = 16;
Sam Clegg48bbd632018-01-24 21:37:30 +000040static constexpr int kInitialTableOffset = 1;
Sam Cleggc94d3932017-11-17 18:14:09 +000041
42namespace {
43
Sam Cleggc94d3932017-11-17 18:14:09 +000044// Traits for using WasmSignature in a DenseMap.
45struct WasmSignatureDenseMapInfo {
46 static WasmSignature getEmptyKey() {
47 WasmSignature Sig;
48 Sig.ReturnType = 1;
49 return Sig;
50 }
51 static WasmSignature getTombstoneKey() {
52 WasmSignature Sig;
53 Sig.ReturnType = 2;
54 return Sig;
55 }
56 static unsigned getHashValue(const WasmSignature &Sig) {
Rui Ueyamaba16bac2018-02-28 17:32:50 +000057 unsigned H = hash_value(Sig.ReturnType);
Sam Cleggc94d3932017-11-17 18:14:09 +000058 for (int32_t Param : Sig.ParamTypes)
Rui Ueyamaba16bac2018-02-28 17:32:50 +000059 H = hash_combine(H, Param);
60 return H;
Sam Cleggc94d3932017-11-17 18:14:09 +000061 }
62 static bool isEqual(const WasmSignature &LHS, const WasmSignature &RHS) {
63 return LHS == RHS;
64 }
65};
66
Sam Clegg93102972018-02-23 05:08:53 +000067// An init entry to be written to either the synthetic init func or the
68// linking metadata.
69struct WasmInitEntry {
Sam Clegge3f3ccf2018-03-12 19:56:23 +000070 const FunctionSymbol *Sym;
Sam Clegg93102972018-02-23 05:08:53 +000071 uint32_t Priority;
Sam Cleggd3052d52018-01-18 23:40:49 +000072};
73
Sam Cleggc94d3932017-11-17 18:14:09 +000074// The writer writes a SymbolTable result to a file.
75class Writer {
76public:
77 void run();
78
79private:
80 void openFile();
81
Sam Cleggc375e4e2018-01-10 19:18:22 +000082 uint32_t lookupType(const WasmSignature &Sig);
83 uint32_t registerType(const WasmSignature &Sig);
Sam Clegg93102972018-02-23 05:08:53 +000084
Sam Clegg50686852018-01-12 18:35:13 +000085 void createCtorFunction();
86 void calculateInitFunctions();
Sam Clegg8d146bb2018-01-09 23:56:44 +000087 void assignIndexes();
Sam Cleggc94d3932017-11-17 18:14:09 +000088 void calculateImports();
Sam Cleggd3052d52018-01-18 23:40:49 +000089 void calculateExports();
Sam Clegg93102972018-02-23 05:08:53 +000090 void assignSymtab();
Sam Cleggc94d3932017-11-17 18:14:09 +000091 void calculateTypes();
92 void createOutputSegments();
93 void layoutMemory();
94 void createHeader();
95 void createSections();
Nicholas Wilsondbd90bf2018-03-07 13:28:16 +000096 SyntheticSection *createSyntheticSection(uint32_t Type, StringRef Name = "");
Sam Cleggc94d3932017-11-17 18:14:09 +000097
98 // Builtin sections
99 void createTypeSection();
100 void createFunctionSection();
101 void createTableSection();
102 void createGlobalSection();
103 void createExportSection();
104 void createImportSection();
105 void createMemorySection();
106 void createElemSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000107 void createCodeSection();
108 void createDataSection();
109
110 // Custom sections
111 void createRelocSections();
112 void createLinkingSection();
113 void createNameSection();
114
115 void writeHeader();
116 void writeSections();
117
118 uint64_t FileSize = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000119 uint32_t NumMemoryPages = 0;
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000120 uint32_t MaxMemoryPages = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000121
122 std::vector<const WasmSignature *> Types;
123 DenseMap<WasmSignature, int32_t, WasmSignatureDenseMapInfo> TypeIndices;
Sam Clegg93102972018-02-23 05:08:53 +0000124 std::vector<const Symbol *> ImportedSymbols;
125 unsigned NumImportedFunctions = 0;
126 unsigned NumImportedGlobals = 0;
127 std::vector<Symbol *> ExportedSymbols;
128 std::vector<const DefinedData *> DefinedFakeGlobals;
129 std::vector<InputGlobal *> InputGlobals;
Sam Clegg9f934222018-02-21 18:29:23 +0000130 std::vector<InputFunction *> InputFunctions;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000131 std::vector<const FunctionSymbol *> IndirectFunctions;
Sam Clegg93102972018-02-23 05:08:53 +0000132 std::vector<const Symbol *> SymtabEntries;
133 std::vector<WasmInitEntry> InitFunctions;
Sam Cleggc94d3932017-11-17 18:14:09 +0000134
135 // Elements that are used to construct the final output
136 std::string Header;
137 std::vector<OutputSection *> OutputSections;
138
139 std::unique_ptr<FileOutputBuffer> Buffer;
140
141 std::vector<OutputSegment *> Segments;
142 llvm::SmallDenseMap<StringRef, OutputSegment *> SegmentMap;
143};
144
145} // anonymous namespace
146
Sam Cleggc94d3932017-11-17 18:14:09 +0000147void Writer::createImportSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000148 uint32_t NumImports = ImportedSymbols.size();
Sam Cleggc94d3932017-11-17 18:14:09 +0000149 if (Config->ImportMemory)
150 ++NumImports;
151
152 if (NumImports == 0)
153 return;
154
155 SyntheticSection *Section = createSyntheticSection(WASM_SEC_IMPORT);
156 raw_ostream &OS = Section->getStream();
157
158 writeUleb128(OS, NumImports, "import count");
159
Sam Cleggc94d3932017-11-17 18:14:09 +0000160 if (Config->ImportMemory) {
161 WasmImport Import;
162 Import.Module = "env";
163 Import.Field = "memory";
164 Import.Kind = WASM_EXTERNAL_MEMORY;
165 Import.Memory.Flags = 0;
166 Import.Memory.Initial = NumMemoryPages;
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000167 if (MaxMemoryPages != 0) {
168 Import.Memory.Flags |= WASM_LIMITS_FLAG_HAS_MAX;
169 Import.Memory.Maximum = MaxMemoryPages;
170 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000171 writeImport(OS, Import);
172 }
173
Sam Clegg93102972018-02-23 05:08:53 +0000174 for (const Symbol *Sym : ImportedSymbols) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000175 WasmImport Import;
176 Import.Module = "env";
177 Import.Field = Sym->getName();
Sam Clegg93102972018-02-23 05:08:53 +0000178 if (auto *FunctionSym = dyn_cast<FunctionSymbol>(Sym)) {
179 Import.Kind = WASM_EXTERNAL_FUNCTION;
180 Import.SigIndex = lookupType(*FunctionSym->getFunctionType());
181 } else {
182 auto *GlobalSym = cast<GlobalSymbol>(Sym);
183 Import.Kind = WASM_EXTERNAL_GLOBAL;
184 Import.Global = *GlobalSym->getGlobalType();
185 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000186 writeImport(OS, Import);
187 }
188}
189
190void Writer::createTypeSection() {
191 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TYPE);
192 raw_ostream &OS = Section->getStream();
193 writeUleb128(OS, Types.size(), "type count");
Sam Cleggd451da12017-12-19 19:56:27 +0000194 for (const WasmSignature *Sig : Types)
Sam Cleggc94d3932017-11-17 18:14:09 +0000195 writeSig(OS, *Sig);
Sam Cleggc94d3932017-11-17 18:14:09 +0000196}
197
198void Writer::createFunctionSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000199 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000200 return;
201
202 SyntheticSection *Section = createSyntheticSection(WASM_SEC_FUNCTION);
203 raw_ostream &OS = Section->getStream();
204
Sam Clegg9f934222018-02-21 18:29:23 +0000205 writeUleb128(OS, InputFunctions.size(), "function count");
206 for (const InputFunction *Func : InputFunctions)
Sam Cleggc375e4e2018-01-10 19:18:22 +0000207 writeUleb128(OS, lookupType(Func->Signature), "sig index");
Sam Cleggc94d3932017-11-17 18:14:09 +0000208}
209
210void Writer::createMemorySection() {
211 if (Config->ImportMemory)
212 return;
213
214 SyntheticSection *Section = createSyntheticSection(WASM_SEC_MEMORY);
215 raw_ostream &OS = Section->getStream();
216
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000217 bool HasMax = MaxMemoryPages != 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000218 writeUleb128(OS, 1, "memory count");
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000219 writeUleb128(OS, HasMax ? WASM_LIMITS_FLAG_HAS_MAX : 0, "memory limits flags");
Sam Cleggc94d3932017-11-17 18:14:09 +0000220 writeUleb128(OS, NumMemoryPages, "initial pages");
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000221 if (HasMax)
222 writeUleb128(OS, MaxMemoryPages, "max pages");
Sam Cleggc94d3932017-11-17 18:14:09 +0000223}
224
225void Writer::createGlobalSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000226 unsigned NumGlobals = InputGlobals.size() + DefinedFakeGlobals.size();
227 if (NumGlobals == 0)
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000228 return;
229
Sam Cleggc94d3932017-11-17 18:14:09 +0000230 SyntheticSection *Section = createSyntheticSection(WASM_SEC_GLOBAL);
231 raw_ostream &OS = Section->getStream();
232
Sam Clegg93102972018-02-23 05:08:53 +0000233 writeUleb128(OS, NumGlobals, "global count");
234 for (const InputGlobal *G : InputGlobals)
235 writeGlobal(OS, G->Global);
236 for (const DefinedData *Sym : DefinedFakeGlobals) {
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000237 WasmGlobal Global;
Sam Clegg93102972018-02-23 05:08:53 +0000238 Global.Type = {WASM_TYPE_I32, false};
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000239 Global.InitExpr.Opcode = WASM_OPCODE_I32_CONST;
240 Global.InitExpr.Value.Int32 = Sym->getVirtualAddress();
Sam Cleggc94d3932017-11-17 18:14:09 +0000241 writeGlobal(OS, Global);
242 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000243}
244
245void Writer::createTableSection() {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000246 // Always output a table section, even if there are no indirect calls.
247 // There are two reasons for this:
248 // 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");
Sam Clegg8518e7d2018-03-01 18:06:39 +0000260 writeU8(OS, WASM_TYPE_ANYFUNC, "table type");
Sam Cleggc94d3932017-11-17 18:14:09 +0000261 writeUleb128(OS, WASM_LIMITS_FLAG_HAS_MAX, "table flags");
Sam Cleggfc1a9122017-12-11 22:00:56 +0000262 writeUleb128(OS, TableSize, "table initial size");
263 writeUleb128(OS, TableSize, "table max size");
Sam Cleggc94d3932017-11-17 18:14:09 +0000264}
265
266void Writer::createExportSection() {
Sam Cleggc94d3932017-11-17 18:14:09 +0000267 bool ExportMemory = !Config->Relocatable && !Config->ImportMemory;
Sam Cleggc94d3932017-11-17 18:14:09 +0000268
Sam Cleggd3052d52018-01-18 23:40:49 +0000269 uint32_t NumExports = (ExportMemory ? 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});
Sam Cleggc94d3932017-11-17 18:14:09 +0000280
Sam Clegg93102972018-02-23 05:08:53 +0000281 unsigned FakeGlobalIndex = NumImportedGlobals + InputGlobals.size();
Rui Ueyama7d696882018-02-28 00:18:34 +0000282
Sam Clegg93102972018-02-23 05:08:53 +0000283 for (const Symbol *Sym : ExportedSymbols) {
Rui Ueyama7d696882018-02-28 00:18:34 +0000284 StringRef Name = Sym->getName();
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000285 WasmExport Export;
Rui Ueyama7d696882018-02-28 00:18:34 +0000286 DEBUG(dbgs() << "Export: " << Name << "\n");
287
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000288 if (auto *F = dyn_cast<DefinedFunction>(Sym))
289 Export = {Name, WASM_EXTERNAL_FUNCTION, F->getFunctionIndex()};
290 else if (auto *G = dyn_cast<DefinedGlobal>(Sym))
291 Export = {Name, WASM_EXTERNAL_GLOBAL, G->getGlobalIndex()};
Rui Ueyama7d696882018-02-28 00:18:34 +0000292 else if (isa<DefinedData>(Sym))
293 Export = {Name, WASM_EXTERNAL_GLOBAL, FakeGlobalIndex++};
294 else
Sam Clegg93102972018-02-23 05:08:53 +0000295 llvm_unreachable("unexpected symbol type");
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000296 writeExport(OS, Export);
Sam Cleggc94d3932017-11-17 18:14:09 +0000297 }
298}
299
Sam Cleggc94d3932017-11-17 18:14:09 +0000300void Writer::createElemSection() {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000301 if (IndirectFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000302 return;
303
304 SyntheticSection *Section = createSyntheticSection(WASM_SEC_ELEM);
305 raw_ostream &OS = Section->getStream();
306
307 writeUleb128(OS, 1, "segment count");
308 writeUleb128(OS, 0, "table index");
309 WasmInitExpr InitExpr;
310 InitExpr.Opcode = WASM_OPCODE_I32_CONST;
Sam Clegg48bbd632018-01-24 21:37:30 +0000311 InitExpr.Value.Int32 = kInitialTableOffset;
Sam Cleggc94d3932017-11-17 18:14:09 +0000312 writeInitExpr(OS, InitExpr);
Sam Cleggfc1a9122017-12-11 22:00:56 +0000313 writeUleb128(OS, IndirectFunctions.size(), "elem count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000314
Sam Clegg48bbd632018-01-24 21:37:30 +0000315 uint32_t TableIndex = kInitialTableOffset;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000316 for (const FunctionSymbol *Sym : IndirectFunctions) {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000317 assert(Sym->getTableIndex() == TableIndex);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000318 writeUleb128(OS, Sym->getFunctionIndex(), "function index");
Sam Cleggfc1a9122017-12-11 22:00:56 +0000319 ++TableIndex;
320 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000321}
322
323void Writer::createCodeSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000324 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000325 return;
326
327 log("createCodeSection");
328
Sam Clegg9f934222018-02-21 18:29:23 +0000329 auto Section = make<CodeSection>(InputFunctions);
Sam Cleggc94d3932017-11-17 18:14:09 +0000330 OutputSections.push_back(Section);
331}
332
333void Writer::createDataSection() {
334 if (!Segments.size())
335 return;
336
337 log("createDataSection");
338 auto Section = make<DataSection>(Segments);
339 OutputSections.push_back(Section);
340}
341
Sam Cleggd451da12017-12-19 19:56:27 +0000342// Create relocations sections in the final output.
Sam Cleggc94d3932017-11-17 18:14:09 +0000343// These are only created when relocatable output is requested.
344void Writer::createRelocSections() {
345 log("createRelocSections");
346 // Don't use iterator here since we are adding to OutputSection
347 size_t OrigSize = OutputSections.size();
348 for (size_t i = 0; i < OrigSize; i++) {
Rui Ueyama37254062018-02-28 00:01:31 +0000349 OutputSection *OSec = OutputSections[i];
350 uint32_t Count = OSec->numRelocations();
Sam Cleggc94d3932017-11-17 18:14:09 +0000351 if (!Count)
352 continue;
353
Rui Ueyama37254062018-02-28 00:01:31 +0000354 StringRef Name;
355 if (OSec->Type == WASM_SEC_DATA)
356 Name = "reloc.DATA";
357 else if (OSec->Type == WASM_SEC_CODE)
358 Name = "reloc.CODE";
Sam Cleggc94d3932017-11-17 18:14:09 +0000359 else
Sam Cleggd451da12017-12-19 19:56:27 +0000360 llvm_unreachable("relocations only supported for code and data");
Sam Cleggc94d3932017-11-17 18:14:09 +0000361
Rui Ueyama37254062018-02-28 00:01:31 +0000362 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, Name);
Sam Cleggc94d3932017-11-17 18:14:09 +0000363 raw_ostream &OS = Section->getStream();
Rui Ueyama37254062018-02-28 00:01:31 +0000364 writeUleb128(OS, OSec->Type, "reloc section");
Sam Cleggc94d3932017-11-17 18:14:09 +0000365 writeUleb128(OS, Count, "reloc count");
Rui Ueyama37254062018-02-28 00:01:31 +0000366 OSec->writeRelocations(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000367 }
368}
369
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000370static uint32_t getWasmFlags(const Symbol *Sym) {
371 uint32_t Flags = 0;
372 if (Sym->isLocal())
373 Flags |= WASM_SYMBOL_BINDING_LOCAL;
374 if (Sym->isWeak())
375 Flags |= WASM_SYMBOL_BINDING_WEAK;
376 if (Sym->isHidden())
377 Flags |= WASM_SYMBOL_VISIBILITY_HIDDEN;
378 if (Sym->isUndefined())
379 Flags |= WASM_SYMBOL_UNDEFINED;
380 return Flags;
381}
382
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000383// Some synthetic sections (e.g. "name" and "linking") have subsections.
384// Just like the synthetic sections themselves these need to be created before
385// they can be written out (since they are preceded by their length). This
386// class is used to create subsections and then write them into the stream
387// of the parent section.
388class SubSection {
389public:
390 explicit SubSection(uint32_t Type) : Type(Type) {}
391
392 void writeTo(raw_ostream &To) {
393 OS.flush();
Rui Ueyama67769102018-02-28 03:38:14 +0000394 writeUleb128(To, Type, "subsection type");
395 writeUleb128(To, Body.size(), "subsection size");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000396 To.write(Body.data(), Body.size());
397 }
398
399private:
400 uint32_t Type;
401 std::string Body;
402
403public:
404 raw_string_ostream OS{Body};
405};
406
Sam Clegg49ed9262017-12-01 00:53:21 +0000407// Create the custom "linking" section containing linker metadata.
Sam Cleggc94d3932017-11-17 18:14:09 +0000408// This is only created when relocatable output is requested.
409void Writer::createLinkingSection() {
410 SyntheticSection *Section =
411 createSyntheticSection(WASM_SEC_CUSTOM, "linking");
412 raw_ostream &OS = Section->getStream();
413
Sam Clegg0d0dd392017-12-19 17:09:45 +0000414 if (!Config->Relocatable)
415 return;
416
Sam Clegg93102972018-02-23 05:08:53 +0000417 if (!SymtabEntries.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000418 SubSection Sub(WASM_SYMBOL_TABLE);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000419 writeUleb128(Sub.OS, SymtabEntries.size(), "num symbols");
420
Sam Clegg93102972018-02-23 05:08:53 +0000421 for (const Symbol *Sym : SymtabEntries) {
422 assert(Sym->isDefined() || Sym->isUndefined());
423 WasmSymbolType Kind = Sym->getWasmType();
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000424 uint32_t Flags = getWasmFlags(Sym);
425
Sam Clegg8518e7d2018-03-01 18:06:39 +0000426 writeU8(Sub.OS, Kind, "sym kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000427 writeUleb128(Sub.OS, Flags, "sym flags");
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000428
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000429 if (auto *F = dyn_cast<FunctionSymbol>(Sym)) {
430 writeUleb128(Sub.OS, F->getFunctionIndex(), "index");
Sam Clegg93102972018-02-23 05:08:53 +0000431 if (Sym->isDefined())
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000432 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000433 } else if (auto *G = dyn_cast<GlobalSymbol>(Sym)) {
434 writeUleb128(Sub.OS, G->getGlobalIndex(), "index");
435 if (Sym->isDefined())
436 writeStr(Sub.OS, Sym->getName(), "sym name");
437 } else {
438 assert(isa<DataSymbol>(Sym));
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000439 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegg93102972018-02-23 05:08:53 +0000440 if (auto *DataSym = dyn_cast<DefinedData>(Sym)) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000441 writeUleb128(Sub.OS, DataSym->getOutputSegmentIndex(), "index");
442 writeUleb128(Sub.OS, DataSym->getOutputSegmentOffset(),
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000443 "data offset");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000444 writeUleb128(Sub.OS, DataSym->getSize(), "data size");
Sam Clegg93102972018-02-23 05:08:53 +0000445 }
Sam Clegg93102972018-02-23 05:08:53 +0000446 }
Sam Cleggd3052d52018-01-18 23:40:49 +0000447 }
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000448
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000449 Sub.writeTo(OS);
Sam Cleggd3052d52018-01-18 23:40:49 +0000450 }
451
Sam Clegg0d0dd392017-12-19 17:09:45 +0000452 if (Segments.size()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000453 SubSection Sub(WASM_SEGMENT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000454 writeUleb128(Sub.OS, Segments.size(), "num data segments");
Sam Cleggc94d3932017-11-17 18:14:09 +0000455 for (const OutputSegment *S : Segments) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000456 writeStr(Sub.OS, S->Name, "segment name");
457 writeUleb128(Sub.OS, S->Alignment, "alignment");
458 writeUleb128(Sub.OS, 0, "flags");
Sam Cleggc94d3932017-11-17 18:14:09 +0000459 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000460 Sub.writeTo(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000461 }
Sam Clegg0d0dd392017-12-19 17:09:45 +0000462
Sam Clegg0d0dd392017-12-19 17:09:45 +0000463 if (!InitFunctions.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000464 SubSection Sub(WASM_INIT_FUNCS);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000465 writeUleb128(Sub.OS, InitFunctions.size(), "num init functions");
Sam Clegg93102972018-02-23 05:08:53 +0000466 for (const WasmInitEntry &F : InitFunctions) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000467 writeUleb128(Sub.OS, F.Priority, "priority");
468 writeUleb128(Sub.OS, F.Sym->getOutputSymbolIndex(), "function index");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000469 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000470 Sub.writeTo(OS);
Sam Clegg0d0dd392017-12-19 17:09:45 +0000471 }
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000472
Nicholas Wilsondbd90bf2018-03-07 13:28:16 +0000473 struct ComdatEntry {
474 unsigned Kind;
475 uint32_t Index;
476 };
477 std::map<StringRef, std::vector<ComdatEntry>> Comdats;
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000478
Sam Clegg9f934222018-02-21 18:29:23 +0000479 for (const InputFunction *F : InputFunctions) {
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000480 StringRef Comdat = F->getComdatName();
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000481 if (!Comdat.empty())
482 Comdats[Comdat].emplace_back(
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000483 ComdatEntry{WASM_COMDAT_FUNCTION, F->getFunctionIndex()});
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000484 }
485 for (uint32_t I = 0; I < Segments.size(); ++I) {
Sam Cleggf98bccf2018-01-13 15:57:48 +0000486 const auto &InputSegments = Segments[I]->InputSegments;
487 if (InputSegments.empty())
488 continue;
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000489 StringRef Comdat = InputSegments[0]->getComdatName();
Sam Clegga697df522018-01-13 15:59:53 +0000490#ifndef NDEBUG
Sam Cleggf98bccf2018-01-13 15:57:48 +0000491 for (const InputSegment *IS : InputSegments)
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000492 assert(IS->getComdatName() == Comdat);
Sam Clegga697df522018-01-13 15:59:53 +0000493#endif
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000494 if (!Comdat.empty())
495 Comdats[Comdat].emplace_back(ComdatEntry{WASM_COMDAT_DATA, I});
496 }
497
498 if (!Comdats.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000499 SubSection Sub(WASM_COMDAT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000500 writeUleb128(Sub.OS, Comdats.size(), "num comdats");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000501 for (const auto &C : Comdats) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000502 writeStr(Sub.OS, C.first, "comdat name");
503 writeUleb128(Sub.OS, 0, "comdat flags"); // flags for future use
504 writeUleb128(Sub.OS, C.second.size(), "num entries");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000505 for (const ComdatEntry &Entry : C.second) {
Sam Clegg8518e7d2018-03-01 18:06:39 +0000506 writeU8(Sub.OS, Entry.Kind, "entry kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000507 writeUleb128(Sub.OS, Entry.Index, "entry index");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000508 }
509 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000510 Sub.writeTo(OS);
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000511 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000512}
513
514// Create the custom "name" section containing debug symbol names.
515void Writer::createNameSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000516 unsigned NumNames = NumImportedFunctions;
Sam Clegg9f934222018-02-21 18:29:23 +0000517 for (const InputFunction *F : InputFunctions)
Sam Clegg1963d712018-01-17 20:19:04 +0000518 if (!F->getName().empty())
519 ++NumNames;
Sam Cleggc94d3932017-11-17 18:14:09 +0000520
Sam Clegg1963d712018-01-17 20:19:04 +0000521 if (NumNames == 0)
522 return;
Sam Clegg50686852018-01-12 18:35:13 +0000523
Sam Cleggc94d3932017-11-17 18:14:09 +0000524 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "name");
525
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000526 SubSection Sub(WASM_NAMES_FUNCTION);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000527 writeUleb128(Sub.OS, NumNames, "name count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000528
Sam Clegg93102972018-02-23 05:08:53 +0000529 // Names must appear in function index order. As it happens ImportedSymbols
530 // and InputFunctions are numbered in order with imported functions coming
Sam Clegg1963d712018-01-17 20:19:04 +0000531 // first.
Sam Clegg93102972018-02-23 05:08:53 +0000532 for (const Symbol *S : ImportedSymbols) {
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000533 if (auto *F = dyn_cast<FunctionSymbol>(S)) {
534 writeUleb128(Sub.OS, F->getFunctionIndex(), "func index");
Nicholas Wilson531769b2018-03-13 13:30:04 +0000535 Optional<std::string> Name = demangleItanium(F->getName());
536 writeStr(Sub.OS, Name ? StringRef(*Name) : F->getName(), "symbol name");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000537 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000538 }
Sam Clegg9f934222018-02-21 18:29:23 +0000539 for (const InputFunction *F : InputFunctions) {
Sam Clegg1963d712018-01-17 20:19:04 +0000540 if (!F->getName().empty()) {
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000541 writeUleb128(Sub.OS, F->getFunctionIndex(), "func index");
Nicholas Wilson531769b2018-03-13 13:30:04 +0000542 Optional<std::string> Name = demangleItanium(F->getName());
543 writeStr(Sub.OS, Name ? StringRef(*Name) : F->getName(), "symbol name");
Sam Clegg1963d712018-01-17 20:19:04 +0000544 }
545 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000546
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000547 Sub.writeTo(Section->getStream());
Sam Cleggc94d3932017-11-17 18:14:09 +0000548}
549
550void Writer::writeHeader() {
551 memcpy(Buffer->getBufferStart(), Header.data(), Header.size());
552}
553
554void Writer::writeSections() {
555 uint8_t *Buf = Buffer->getBufferStart();
556 parallelForEach(OutputSections, [Buf](OutputSection *S) { S->writeTo(Buf); });
557}
558
559// Fix the memory layout of the output binary. This assigns memory offsets
Sam Clegg49ed9262017-12-01 00:53:21 +0000560// to each of the input data sections as well as the explicit stack region.
Sam Cleggf0d433d2018-02-02 22:59:56 +0000561// The memory layout is as follows, from low to high.
562// - initialized data (starting at Config->GlobalBase)
563// - BSS data (not currently implemented in llvm)
564// - explicit stack (Config->ZStackSize)
565// - heap start / unallocated
Sam Cleggc94d3932017-11-17 18:14:09 +0000566void Writer::layoutMemory() {
567 uint32_t MemoryPtr = 0;
Sam Clegg99eb42c2018-02-27 23:58:03 +0000568 MemoryPtr = Config->GlobalBase;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000569 log("mem: global base = " + Twine(Config->GlobalBase));
Sam Cleggc94d3932017-11-17 18:14:09 +0000570
571 createOutputSegments();
572
Sam Cleggf0d433d2018-02-02 22:59:56 +0000573 // Arbitrarily set __dso_handle handle to point to the start of the data
574 // segments.
575 if (WasmSym::DsoHandle)
576 WasmSym::DsoHandle->setVirtualAddress(MemoryPtr);
577
Sam Cleggc94d3932017-11-17 18:14:09 +0000578 for (OutputSegment *Seg : Segments) {
579 MemoryPtr = alignTo(MemoryPtr, Seg->Alignment);
580 Seg->StartVA = MemoryPtr;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000581 log(formatv("mem: {0,-15} offset={1,-8} size={2,-8} align={3}", Seg->Name,
582 MemoryPtr, Seg->Size, Seg->Alignment));
Sam Cleggc94d3932017-11-17 18:14:09 +0000583 MemoryPtr += Seg->Size;
584 }
585
Sam Cleggf0d433d2018-02-02 22:59:56 +0000586 // TODO: Add .bss space here.
Sam Clegg37a4a8a2018-02-07 03:04:53 +0000587 if (WasmSym::DataEnd)
588 WasmSym::DataEnd->setVirtualAddress(MemoryPtr);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000589
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000590 log("mem: static data = " + Twine(MemoryPtr - Config->GlobalBase));
Sam Cleggc94d3932017-11-17 18:14:09 +0000591
Sam Cleggf0d433d2018-02-02 22:59:56 +0000592 // Stack comes after static data and bss
Sam Cleggc94d3932017-11-17 18:14:09 +0000593 if (!Config->Relocatable) {
594 MemoryPtr = alignTo(MemoryPtr, kStackAlignment);
595 if (Config->ZStackSize != alignTo(Config->ZStackSize, kStackAlignment))
596 error("stack size must be " + Twine(kStackAlignment) + "-byte aligned");
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000597 log("mem: stack size = " + Twine(Config->ZStackSize));
598 log("mem: stack base = " + Twine(MemoryPtr));
Sam Cleggc94d3932017-11-17 18:14:09 +0000599 MemoryPtr += Config->ZStackSize;
Sam Clegg93102972018-02-23 05:08:53 +0000600 WasmSym::StackPointer->Global->Global.InitExpr.Value.Int32 = MemoryPtr;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000601 log("mem: stack top = " + Twine(MemoryPtr));
Sam Clegg93102972018-02-23 05:08:53 +0000602
Sam Clegg51bcdc22018-01-17 01:34:31 +0000603 // Set `__heap_base` to directly follow the end of the stack. We don't
604 // allocate any heap memory up front, but instead really on the malloc/brk
605 // implementation growing the memory at runtime.
Sam Cleggf0d433d2018-02-02 22:59:56 +0000606 WasmSym::HeapBase->setVirtualAddress(MemoryPtr);
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000607 log("mem: heap base = " + Twine(MemoryPtr));
Sam Cleggc94d3932017-11-17 18:14:09 +0000608 }
609
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000610 if (Config->InitialMemory != 0) {
611 if (Config->InitialMemory != alignTo(Config->InitialMemory, WasmPageSize))
612 error("initial memory must be " + Twine(WasmPageSize) + "-byte aligned");
613 if (MemoryPtr > Config->InitialMemory)
614 error("initial memory too small, " + Twine(MemoryPtr) + " bytes needed");
615 else
616 MemoryPtr = Config->InitialMemory;
617 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000618 uint32_t MemSize = alignTo(MemoryPtr, WasmPageSize);
619 NumMemoryPages = MemSize / WasmPageSize;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000620 log("mem: total pages = " + Twine(NumMemoryPages));
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000621
622 if (Config->MaxMemory != 0) {
623 if (Config->MaxMemory != alignTo(Config->MaxMemory, WasmPageSize))
624 error("maximum memory must be " + Twine(WasmPageSize) + "-byte aligned");
625 if (MemoryPtr > Config->MaxMemory)
626 error("maximum memory too small, " + Twine(MemoryPtr) + " bytes needed");
627 MaxMemoryPages = Config->MaxMemory / WasmPageSize;
628 log("mem: max pages = " + Twine(MaxMemoryPages));
629 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000630}
631
632SyntheticSection *Writer::createSyntheticSection(uint32_t Type,
Sam Cleggc375e4e2018-01-10 19:18:22 +0000633 StringRef Name) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000634 auto Sec = make<SyntheticSection>(Type, Name);
Sam Cleggab2ac292017-12-20 05:14:48 +0000635 log("createSection: " + toString(*Sec));
Sam Cleggc94d3932017-11-17 18:14:09 +0000636 OutputSections.push_back(Sec);
637 return Sec;
638}
639
640void Writer::createSections() {
641 // Known sections
642 createTypeSection();
643 createImportSection();
644 createFunctionSection();
645 createTableSection();
646 createMemorySection();
647 createGlobalSection();
648 createExportSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000649 createElemSection();
650 createCodeSection();
651 createDataSection();
652
653 // Custom sections
Sam Clegg99eb42c2018-02-27 23:58:03 +0000654 if (Config->Relocatable) {
Sam Clegg99eb42c2018-02-27 23:58:03 +0000655 createLinkingSection();
Nicholas Wilson94d3b162018-03-05 12:33:58 +0000656 createRelocSections();
Sam Clegg99eb42c2018-02-27 23:58:03 +0000657 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000658 if (!Config->StripDebug && !Config->StripAll)
659 createNameSection();
660
661 for (OutputSection *S : OutputSections) {
662 S->setOffset(FileSize);
663 S->finalizeContents();
664 FileSize += S->getSize();
665 }
666}
667
Sam Cleggc94d3932017-11-17 18:14:09 +0000668void Writer::calculateImports() {
Sam Clegg574d7ce2017-12-15 19:23:49 +0000669 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000670 if (!Sym->isUndefined())
671 continue;
672 if (isa<DataSymbol>(Sym))
673 continue;
674 if (Sym->isWeak() && !Config->Relocatable)
Sam Clegg574d7ce2017-12-15 19:23:49 +0000675 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000676
Sam Clegg93102972018-02-23 05:08:53 +0000677 DEBUG(dbgs() << "import: " << Sym->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000678 ImportedSymbols.emplace_back(Sym);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000679 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
680 F->setFunctionIndex(NumImportedFunctions++);
Sam Clegg93102972018-02-23 05:08:53 +0000681 else
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000682 cast<GlobalSymbol>(Sym)->setGlobalIndex(NumImportedGlobals++);
Sam Cleggc94d3932017-11-17 18:14:09 +0000683 }
684}
685
Sam Cleggd3052d52018-01-18 23:40:49 +0000686void Writer::calculateExports() {
Sam Clegg93102972018-02-23 05:08:53 +0000687 if (Config->Relocatable)
688 return;
Sam Cleggf0d433d2018-02-02 22:59:56 +0000689
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000690 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000691 if (!Sym->isDefined())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000692 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000693 if (Sym->isHidden() || Sym->isLocal())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000694 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000695 if (!Sym->isLive())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000696 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000697
698 DEBUG(dbgs() << "exporting sym: " << Sym->getName() << "\n");
699
Nicholas Wilsonf2f6d5e2018-03-02 14:51:36 +0000700 if (auto *D = dyn_cast<DefinedData>(Sym))
Sam Clegg93102972018-02-23 05:08:53 +0000701 DefinedFakeGlobals.emplace_back(D);
Sam Clegg93102972018-02-23 05:08:53 +0000702 ExportedSymbols.emplace_back(Sym);
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000703 }
Sam Clegg93102972018-02-23 05:08:53 +0000704}
705
706void Writer::assignSymtab() {
707 if (!Config->Relocatable)
708 return;
709
710 unsigned SymbolIndex = SymtabEntries.size();
Sam Cleggd3052d52018-01-18 23:40:49 +0000711 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg93102972018-02-23 05:08:53 +0000712 DEBUG(dbgs() << "Symtab entries: " << File->getName() << "\n");
Sam Cleggd3052d52018-01-18 23:40:49 +0000713 for (Symbol *Sym : File->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000714 if (Sym->getFile() != File)
Sam Cleggd3052d52018-01-18 23:40:49 +0000715 continue;
Nicholas Wilson06e0d172018-03-07 11:15:47 +0000716 // (Since this is relocatable output, GC is not performed so symbols must
717 // be live.)
718 assert(Sym->isLive());
Sam Clegg93102972018-02-23 05:08:53 +0000719 Sym->setOutputSymbolIndex(SymbolIndex++);
720 SymtabEntries.emplace_back(Sym);
Sam Cleggd3052d52018-01-18 23:40:49 +0000721 }
722 }
723
Sam Clegg93102972018-02-23 05:08:53 +0000724 // For the moment, relocatable output doesn't contain any synthetic functions,
725 // so no need to look through the Symtab for symbols not referenced by
726 // Symtab->ObjectFiles.
Sam Cleggd3052d52018-01-18 23:40:49 +0000727}
728
Sam Cleggc375e4e2018-01-10 19:18:22 +0000729uint32_t Writer::lookupType(const WasmSignature &Sig) {
Sam Clegg8d027d62018-01-10 20:12:26 +0000730 auto It = TypeIndices.find(Sig);
731 if (It == TypeIndices.end()) {
Sam Cleggc375e4e2018-01-10 19:18:22 +0000732 error("type not found: " + toString(Sig));
Sam Clegg8d027d62018-01-10 20:12:26 +0000733 return 0;
734 }
735 return It->second;
Sam Cleggc375e4e2018-01-10 19:18:22 +0000736}
737
738uint32_t Writer::registerType(const WasmSignature &Sig) {
Sam Cleggb8621592017-11-30 01:40:08 +0000739 auto Pair = TypeIndices.insert(std::make_pair(Sig, Types.size()));
Sam Cleggc375e4e2018-01-10 19:18:22 +0000740 if (Pair.second) {
741 DEBUG(dbgs() << "type " << toString(Sig) << "\n");
Sam Cleggb8621592017-11-30 01:40:08 +0000742 Types.push_back(&Sig);
Sam Cleggc375e4e2018-01-10 19:18:22 +0000743 }
Sam Cleggb8621592017-11-30 01:40:08 +0000744 return Pair.first->second;
745}
746
Sam Cleggc94d3932017-11-17 18:14:09 +0000747void Writer::calculateTypes() {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000748 // The output type section is the union of the following sets:
749 // 1. Any signature used in the TYPE relocation
750 // 2. The signatures of all imported functions
751 // 3. The signatures of all defined functions
752
Sam Cleggc94d3932017-11-17 18:14:09 +0000753 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000754 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
755 for (uint32_t I = 0; I < Types.size(); I++)
756 if (File->TypeIsUsed[I])
757 File->TypeMap[I] = registerType(Types[I]);
Sam Cleggc94d3932017-11-17 18:14:09 +0000758 }
Sam Clegg50686852018-01-12 18:35:13 +0000759
Sam Clegg93102972018-02-23 05:08:53 +0000760 for (const Symbol *Sym : ImportedSymbols)
761 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
762 registerType(*F->getFunctionType());
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000763
Sam Clegg9f934222018-02-21 18:29:23 +0000764 for (const InputFunction *F : InputFunctions)
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000765 registerType(F->Signature);
Sam Cleggc94d3932017-11-17 18:14:09 +0000766}
767
Sam Clegg8d146bb2018-01-09 23:56:44 +0000768void Writer::assignIndexes() {
Sam Clegg93102972018-02-23 05:08:53 +0000769 uint32_t FunctionIndex = NumImportedFunctions + InputFunctions.size();
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000770 auto AddDefinedFunction = [&](InputFunction *Func) {
771 if (!Func->Live)
772 return;
773 InputFunctions.emplace_back(Func);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000774 Func->setFunctionIndex(FunctionIndex++);
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000775 };
776
Nicholas Wilson5639da82018-03-12 15:44:07 +0000777 for (InputFunction *Func : Symtab->SyntheticFunctions)
778 AddDefinedFunction(Func);
779
Sam Clegg87e61922018-01-08 23:39:11 +0000780 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8d146bb2018-01-09 23:56:44 +0000781 DEBUG(dbgs() << "Functions: " << File->getName() << "\n");
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000782 for (InputFunction *Func : File->Functions)
783 AddDefinedFunction(Func);
Sam Clegg8d146bb2018-01-09 23:56:44 +0000784 }
785
Sam Clegg93102972018-02-23 05:08:53 +0000786 uint32_t TableIndex = kInitialTableOffset;
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000787 auto HandleRelocs = [&](InputChunk *Chunk) {
788 if (!Chunk->Live)
789 return;
790 ObjFile *File = Chunk->File;
791 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
Sam Clegg93102972018-02-23 05:08:53 +0000792 for (const WasmRelocation &Reloc : Chunk->getRelocations()) {
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000793 if (Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_I32 ||
794 Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_SLEB) {
795 FunctionSymbol *Sym = File->getFunctionSymbol(Reloc.Index);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000796 if (Sym->hasTableIndex() || !Sym->hasFunctionIndex())
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000797 continue;
798 Sym->setTableIndex(TableIndex++);
799 IndirectFunctions.emplace_back(Sym);
800 } else if (Reloc.Type == R_WEBASSEMBLY_TYPE_INDEX_LEB) {
Sam Clegg93102972018-02-23 05:08:53 +0000801 // Mark target type as live
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000802 File->TypeMap[Reloc.Index] = registerType(Types[Reloc.Index]);
803 File->TypeIsUsed[Reloc.Index] = true;
Sam Clegg93102972018-02-23 05:08:53 +0000804 } else if (Reloc.Type == R_WEBASSEMBLY_GLOBAL_INDEX_LEB) {
805 // Mark target global as live
806 GlobalSymbol *Sym = File->getGlobalSymbol(Reloc.Index);
807 if (auto *G = dyn_cast<DefinedGlobal>(Sym)) {
808 DEBUG(dbgs() << "marking global live: " << Sym->getName() << "\n");
809 G->Global->Live = true;
810 }
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000811 }
812 }
813 };
814
Sam Clegg8d146bb2018-01-09 23:56:44 +0000815 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000816 DEBUG(dbgs() << "Handle relocs: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000817 for (InputChunk *Chunk : File->Functions)
818 HandleRelocs(Chunk);
819 for (InputChunk *Chunk : File->Segments)
820 HandleRelocs(Chunk);
821 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000822
Sam Clegg93102972018-02-23 05:08:53 +0000823 uint32_t GlobalIndex = NumImportedGlobals + InputGlobals.size();
824 auto AddDefinedGlobal = [&](InputGlobal *Global) {
825 if (Global->Live) {
826 DEBUG(dbgs() << "AddDefinedGlobal: " << GlobalIndex << "\n");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000827 Global->setGlobalIndex(GlobalIndex++);
Sam Clegg93102972018-02-23 05:08:53 +0000828 InputGlobals.push_back(Global);
829 }
830 };
831
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000832 for (InputGlobal *Global : Symtab->SyntheticGlobals)
833 AddDefinedGlobal(Global);
Sam Clegg93102972018-02-23 05:08:53 +0000834
835 for (ObjFile *File : Symtab->ObjectFiles) {
836 DEBUG(dbgs() << "Globals: " << File->getName() << "\n");
837 for (InputGlobal *Global : File->Globals)
838 AddDefinedGlobal(Global);
Sam Cleggc94d3932017-11-17 18:14:09 +0000839 }
840}
841
842static StringRef getOutputDataSegmentName(StringRef Name) {
843 if (Config->Relocatable)
844 return Name;
Rui Ueyama4764b572018-02-28 00:57:28 +0000845 if (Name.startswith(".text."))
846 return ".text";
847 if (Name.startswith(".data."))
848 return ".data";
849 if (Name.startswith(".bss."))
850 return ".bss";
Sam Cleggc94d3932017-11-17 18:14:09 +0000851 return Name;
852}
853
854void Writer::createOutputSegments() {
855 for (ObjFile *File : Symtab->ObjectFiles) {
856 for (InputSegment *Segment : File->Segments) {
Sam Clegg447ae402018-02-13 20:29:38 +0000857 if (!Segment->Live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000858 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000859 StringRef Name = getOutputDataSegmentName(Segment->getName());
860 OutputSegment *&S = SegmentMap[Name];
861 if (S == nullptr) {
862 DEBUG(dbgs() << "new segment: " << Name << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000863 S = make<OutputSegment>(Name, Segments.size());
Sam Cleggc94d3932017-11-17 18:14:09 +0000864 Segments.push_back(S);
865 }
866 S->addInputSegment(Segment);
867 DEBUG(dbgs() << "added data: " << Name << ": " << S->Size << "\n");
Sam Cleggc94d3932017-11-17 18:14:09 +0000868 }
869 }
870}
871
Sam Clegg50686852018-01-12 18:35:13 +0000872static const int OPCODE_CALL = 0x10;
873static const int OPCODE_END = 0xb;
874
875// Create synthetic "__wasm_call_ctors" function based on ctor functions
876// in input object.
877void Writer::createCtorFunction() {
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000878 // First write the body's contents to a string.
879 std::string BodyContent;
Sam Clegg50686852018-01-12 18:35:13 +0000880 {
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000881 raw_string_ostream OS(BodyContent);
Sam Clegg50686852018-01-12 18:35:13 +0000882 writeUleb128(OS, 0, "num locals");
Sam Clegg93102972018-02-23 05:08:53 +0000883 for (const WasmInitEntry &F : InitFunctions) {
Sam Clegg50686852018-01-12 18:35:13 +0000884 writeU8(OS, OPCODE_CALL, "CALL");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000885 writeUleb128(OS, F.Sym->getFunctionIndex(), "function index");
Sam Clegg50686852018-01-12 18:35:13 +0000886 }
887 writeU8(OS, OPCODE_END, "END");
888 }
889
890 // Once we know the size of the body we can create the final function body
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000891 std::string FunctionBody;
892 {
893 raw_string_ostream OS(FunctionBody);
894 writeUleb128(OS, BodyContent.size(), "function size");
895 OS << BodyContent;
896 }
Rui Ueyama29abfe42018-02-28 17:43:15 +0000897
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000898 ArrayRef<uint8_t> Body = toArrayRef(Saver.save(FunctionBody));
899 cast<SyntheticFunction>(WasmSym::CallCtors->Function)->setBody(Body);
Sam Clegg50686852018-01-12 18:35:13 +0000900}
901
902// Populate InitFunctions vector with init functions from all input objects.
903// This is then used either when creating the output linking section or to
904// synthesize the "__wasm_call_ctors" function.
905void Writer::calculateInitFunctions() {
906 for (ObjFile *File : Symtab->ObjectFiles) {
907 const WasmLinkingData &L = File->getWasmObj()->linkingData();
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +0000908 for (const WasmInitFunc &F : L.InitFunctions) {
909 FunctionSymbol *Sym = File->getFunctionSymbol(F.Symbol);
910 if (*Sym->getFunctionType() != WasmSignature{{}, WASM_TYPE_NORESULT})
911 error("invalid signature for init func: " + toString(*Sym));
912 InitFunctions.emplace_back(WasmInitEntry{Sym, F.Priority});
913 }
Sam Clegg50686852018-01-12 18:35:13 +0000914 }
Rui Ueyamada69b712018-02-28 00:15:59 +0000915
Sam Clegg50686852018-01-12 18:35:13 +0000916 // Sort in order of priority (lowest first) so that they are called
917 // in the correct order.
Sam Clegg29b8feb2018-02-21 00:34:34 +0000918 std::stable_sort(InitFunctions.begin(), InitFunctions.end(),
Sam Clegg93102972018-02-23 05:08:53 +0000919 [](const WasmInitEntry &L, const WasmInitEntry &R) {
Sam Clegg29b8feb2018-02-21 00:34:34 +0000920 return L.Priority < R.Priority;
921 });
Sam Clegg50686852018-01-12 18:35:13 +0000922}
923
Sam Cleggc94d3932017-11-17 18:14:09 +0000924void Writer::run() {
Sam Clegg99eb42c2018-02-27 23:58:03 +0000925 if (Config->Relocatable)
926 Config->GlobalBase = 0;
927
Sam Cleggc94d3932017-11-17 18:14:09 +0000928 log("-- calculateImports");
929 calculateImports();
Sam Clegg8d146bb2018-01-09 23:56:44 +0000930 log("-- assignIndexes");
931 assignIndexes();
Sam Clegg50686852018-01-12 18:35:13 +0000932 log("-- calculateInitFunctions");
933 calculateInitFunctions();
934 if (!Config->Relocatable)
935 createCtorFunction();
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000936 log("-- calculateTypes");
937 calculateTypes();
Sam Clegg93102972018-02-23 05:08:53 +0000938 log("-- layoutMemory");
939 layoutMemory();
940 log("-- calculateExports");
941 calculateExports();
942 log("-- assignSymtab");
943 assignSymtab();
Sam Cleggc94d3932017-11-17 18:14:09 +0000944
945 if (errorHandler().Verbose) {
Sam Clegg9f934222018-02-21 18:29:23 +0000946 log("Defined Functions: " + Twine(InputFunctions.size()));
Sam Clegg93102972018-02-23 05:08:53 +0000947 log("Defined Globals : " + Twine(InputGlobals.size()));
948 log("Function Imports : " + Twine(NumImportedFunctions));
949 log("Global Imports : " + Twine(NumImportedGlobals));
Sam Cleggc94d3932017-11-17 18:14:09 +0000950 for (ObjFile *File : Symtab->ObjectFiles)
951 File->dumpInfo();
952 }
953
Sam Cleggc94d3932017-11-17 18:14:09 +0000954 createHeader();
955 log("-- createSections");
956 createSections();
957
958 log("-- openFile");
959 openFile();
960 if (errorCount())
961 return;
962
963 writeHeader();
964
965 log("-- writeSections");
966 writeSections();
967 if (errorCount())
968 return;
969
970 if (Error E = Buffer->commit())
971 fatal("failed to write the output file: " + toString(std::move(E)));
972}
973
974// Open a result file.
975void Writer::openFile() {
976 log("writing: " + Config->OutputFile);
Sam Cleggc94d3932017-11-17 18:14:09 +0000977
978 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
979 FileOutputBuffer::create(Config->OutputFile, FileSize,
980 FileOutputBuffer::F_executable);
981
982 if (!BufferOrErr)
983 error("failed to open " + Config->OutputFile + ": " +
984 toString(BufferOrErr.takeError()));
985 else
986 Buffer = std::move(*BufferOrErr);
987}
988
989void Writer::createHeader() {
990 raw_string_ostream OS(Header);
991 writeBytes(OS, WasmMagic, sizeof(WasmMagic), "wasm magic");
992 writeU32(OS, WasmVersion, "wasm version");
993 OS.flush();
994 FileSize += Header.size();
995}
996
997void lld::wasm::writeResult() { Writer().run(); }