blob: 9d7684c5110a93a098a103d4e061a196e7716c37 [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;
Sam Cleggc94d3932017-11-17 18:14:09 +000042
43namespace {
44
Sam Clegg93102972018-02-23 05:08:53 +000045// An init entry to be written to either the synthetic init func or the
46// linking metadata.
47struct WasmInitEntry {
Sam Clegge3f3ccf2018-03-12 19:56:23 +000048 const FunctionSymbol *Sym;
Sam Clegg93102972018-02-23 05:08:53 +000049 uint32_t Priority;
Sam Cleggd3052d52018-01-18 23:40:49 +000050};
51
Sam Cleggc94d3932017-11-17 18:14:09 +000052// The writer writes a SymbolTable result to a file.
53class Writer {
54public:
55 void run();
56
57private:
58 void openFile();
59
Sam Cleggc375e4e2018-01-10 19:18:22 +000060 uint32_t lookupType(const WasmSignature &Sig);
61 uint32_t registerType(const WasmSignature &Sig);
Sam Clegg93102972018-02-23 05:08:53 +000062
Sam Clegg50686852018-01-12 18:35:13 +000063 void createCtorFunction();
64 void calculateInitFunctions();
Sam Clegg8d146bb2018-01-09 23:56:44 +000065 void assignIndexes();
Sam Cleggc94d3932017-11-17 18:14:09 +000066 void calculateImports();
Sam Cleggd3052d52018-01-18 23:40:49 +000067 void calculateExports();
Sam Clegg93102972018-02-23 05:08:53 +000068 void assignSymtab();
Sam Cleggc94d3932017-11-17 18:14:09 +000069 void calculateTypes();
70 void createOutputSegments();
71 void layoutMemory();
72 void createHeader();
73 void createSections();
Nicholas Wilsondbd90bf2018-03-07 13:28:16 +000074 SyntheticSection *createSyntheticSection(uint32_t Type, StringRef Name = "");
Sam Cleggc94d3932017-11-17 18:14:09 +000075
76 // Builtin sections
77 void createTypeSection();
78 void createFunctionSection();
79 void createTableSection();
80 void createGlobalSection();
81 void createExportSection();
82 void createImportSection();
83 void createMemorySection();
84 void createElemSection();
Sam Cleggc94d3932017-11-17 18:14:09 +000085 void createCodeSection();
86 void createDataSection();
87
88 // Custom sections
89 void createRelocSections();
90 void createLinkingSection();
91 void createNameSection();
92
93 void writeHeader();
94 void writeSections();
95
96 uint64_t FileSize = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +000097 uint32_t NumMemoryPages = 0;
Nicholas Wilson2eb39c12018-03-14 13:53:58 +000098 uint32_t MaxMemoryPages = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +000099
100 std::vector<const WasmSignature *> Types;
Nicholas Wilson3e3f5fb2018-03-14 15:58:16 +0000101 DenseMap<WasmSignature, int32_t> TypeIndices;
Sam Clegg93102972018-02-23 05:08:53 +0000102 std::vector<const Symbol *> ImportedSymbols;
103 unsigned NumImportedFunctions = 0;
104 unsigned NumImportedGlobals = 0;
105 std::vector<Symbol *> ExportedSymbols;
106 std::vector<const DefinedData *> DefinedFakeGlobals;
107 std::vector<InputGlobal *> InputGlobals;
Sam Clegg9f934222018-02-21 18:29:23 +0000108 std::vector<InputFunction *> InputFunctions;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000109 std::vector<const FunctionSymbol *> IndirectFunctions;
Sam Clegg93102972018-02-23 05:08:53 +0000110 std::vector<const Symbol *> SymtabEntries;
111 std::vector<WasmInitEntry> InitFunctions;
Sam Cleggc94d3932017-11-17 18:14:09 +0000112
113 // Elements that are used to construct the final output
114 std::string Header;
115 std::vector<OutputSection *> OutputSections;
116
117 std::unique_ptr<FileOutputBuffer> Buffer;
118
119 std::vector<OutputSegment *> Segments;
120 llvm::SmallDenseMap<StringRef, OutputSegment *> SegmentMap;
121};
122
123} // anonymous namespace
124
Sam Cleggc94d3932017-11-17 18:14:09 +0000125void Writer::createImportSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000126 uint32_t NumImports = ImportedSymbols.size();
Sam Cleggc94d3932017-11-17 18:14:09 +0000127 if (Config->ImportMemory)
128 ++NumImports;
129
130 if (NumImports == 0)
131 return;
132
133 SyntheticSection *Section = createSyntheticSection(WASM_SEC_IMPORT);
134 raw_ostream &OS = Section->getStream();
135
136 writeUleb128(OS, NumImports, "import count");
137
Sam Cleggc94d3932017-11-17 18:14:09 +0000138 if (Config->ImportMemory) {
139 WasmImport Import;
140 Import.Module = "env";
141 Import.Field = "memory";
142 Import.Kind = WASM_EXTERNAL_MEMORY;
143 Import.Memory.Flags = 0;
144 Import.Memory.Initial = NumMemoryPages;
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000145 if (MaxMemoryPages != 0) {
146 Import.Memory.Flags |= WASM_LIMITS_FLAG_HAS_MAX;
147 Import.Memory.Maximum = MaxMemoryPages;
148 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000149 writeImport(OS, Import);
150 }
151
Sam Clegg93102972018-02-23 05:08:53 +0000152 for (const Symbol *Sym : ImportedSymbols) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000153 WasmImport Import;
154 Import.Module = "env";
155 Import.Field = Sym->getName();
Sam Clegg93102972018-02-23 05:08:53 +0000156 if (auto *FunctionSym = dyn_cast<FunctionSymbol>(Sym)) {
157 Import.Kind = WASM_EXTERNAL_FUNCTION;
158 Import.SigIndex = lookupType(*FunctionSym->getFunctionType());
159 } else {
160 auto *GlobalSym = cast<GlobalSymbol>(Sym);
161 Import.Kind = WASM_EXTERNAL_GLOBAL;
162 Import.Global = *GlobalSym->getGlobalType();
163 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000164 writeImport(OS, Import);
165 }
166}
167
168void Writer::createTypeSection() {
169 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TYPE);
170 raw_ostream &OS = Section->getStream();
171 writeUleb128(OS, Types.size(), "type count");
Sam Cleggd451da12017-12-19 19:56:27 +0000172 for (const WasmSignature *Sig : Types)
Sam Cleggc94d3932017-11-17 18:14:09 +0000173 writeSig(OS, *Sig);
Sam Cleggc94d3932017-11-17 18:14:09 +0000174}
175
176void Writer::createFunctionSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000177 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000178 return;
179
180 SyntheticSection *Section = createSyntheticSection(WASM_SEC_FUNCTION);
181 raw_ostream &OS = Section->getStream();
182
Sam Clegg9f934222018-02-21 18:29:23 +0000183 writeUleb128(OS, InputFunctions.size(), "function count");
184 for (const InputFunction *Func : InputFunctions)
Sam Cleggc375e4e2018-01-10 19:18:22 +0000185 writeUleb128(OS, lookupType(Func->Signature), "sig index");
Sam Cleggc94d3932017-11-17 18:14:09 +0000186}
187
188void Writer::createMemorySection() {
189 if (Config->ImportMemory)
190 return;
191
192 SyntheticSection *Section = createSyntheticSection(WASM_SEC_MEMORY);
193 raw_ostream &OS = Section->getStream();
194
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000195 bool HasMax = MaxMemoryPages != 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000196 writeUleb128(OS, 1, "memory count");
Nicholas Wilsonca5cc202018-03-14 21:43:04 +0000197 writeUleb128(OS, HasMax ? static_cast<unsigned>(WASM_LIMITS_FLAG_HAS_MAX) : 0,
198 "memory limits flags");
Sam Cleggc94d3932017-11-17 18:14:09 +0000199 writeUleb128(OS, NumMemoryPages, "initial pages");
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000200 if (HasMax)
201 writeUleb128(OS, MaxMemoryPages, "max pages");
Sam Cleggc94d3932017-11-17 18:14:09 +0000202}
203
204void Writer::createGlobalSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000205 unsigned NumGlobals = InputGlobals.size() + DefinedFakeGlobals.size();
206 if (NumGlobals == 0)
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000207 return;
208
Sam Cleggc94d3932017-11-17 18:14:09 +0000209 SyntheticSection *Section = createSyntheticSection(WASM_SEC_GLOBAL);
210 raw_ostream &OS = Section->getStream();
211
Sam Clegg93102972018-02-23 05:08:53 +0000212 writeUleb128(OS, NumGlobals, "global count");
213 for (const InputGlobal *G : InputGlobals)
214 writeGlobal(OS, G->Global);
215 for (const DefinedData *Sym : DefinedFakeGlobals) {
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000216 WasmGlobal Global;
Sam Clegg93102972018-02-23 05:08:53 +0000217 Global.Type = {WASM_TYPE_I32, false};
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000218 Global.InitExpr.Opcode = WASM_OPCODE_I32_CONST;
219 Global.InitExpr.Value.Int32 = Sym->getVirtualAddress();
Sam Cleggc94d3932017-11-17 18:14:09 +0000220 writeGlobal(OS, Global);
221 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000222}
223
224void Writer::createTableSection() {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000225 // Always output a table section, even if there are no indirect calls.
226 // There are two reasons for this:
227 // 1. For executables it is useful to have an empty table slot at 0
228 // which can be filled with a null function call handler.
229 // 2. If we don't do this, any program that contains a call_indirect but
230 // no address-taken function will fail at validation time since it is
231 // a validation error to include a call_indirect instruction if there
232 // is not table.
Sam Clegg48bbd632018-01-24 21:37:30 +0000233 uint32_t TableSize = kInitialTableOffset + IndirectFunctions.size();
Sam Cleggfc1a9122017-12-11 22:00:56 +0000234
Sam Cleggc94d3932017-11-17 18:14:09 +0000235 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TABLE);
236 raw_ostream &OS = Section->getStream();
237
238 writeUleb128(OS, 1, "table count");
Sam Clegg8518e7d2018-03-01 18:06:39 +0000239 writeU8(OS, WASM_TYPE_ANYFUNC, "table type");
Sam Cleggc94d3932017-11-17 18:14:09 +0000240 writeUleb128(OS, WASM_LIMITS_FLAG_HAS_MAX, "table flags");
Sam Cleggfc1a9122017-12-11 22:00:56 +0000241 writeUleb128(OS, TableSize, "table initial size");
242 writeUleb128(OS, TableSize, "table max size");
Sam Cleggc94d3932017-11-17 18:14:09 +0000243}
244
245void Writer::createExportSection() {
Sam Cleggc94d3932017-11-17 18:14:09 +0000246 bool ExportMemory = !Config->Relocatable && !Config->ImportMemory;
Sam Cleggc94d3932017-11-17 18:14:09 +0000247
Sam Cleggd3052d52018-01-18 23:40:49 +0000248 uint32_t NumExports = (ExportMemory ? 1 : 0) + ExportedSymbols.size();
Sam Cleggc94d3932017-11-17 18:14:09 +0000249 if (!NumExports)
250 return;
251
252 SyntheticSection *Section = createSyntheticSection(WASM_SEC_EXPORT);
253 raw_ostream &OS = Section->getStream();
254
255 writeUleb128(OS, NumExports, "export count");
256
Rui Ueyama7d696882018-02-28 00:18:34 +0000257 if (ExportMemory)
258 writeExport(OS, {"memory", WASM_EXTERNAL_MEMORY, 0});
Sam Cleggc94d3932017-11-17 18:14:09 +0000259
Sam Clegg93102972018-02-23 05:08:53 +0000260 unsigned FakeGlobalIndex = NumImportedGlobals + InputGlobals.size();
Rui Ueyama7d696882018-02-28 00:18:34 +0000261
Sam Clegg93102972018-02-23 05:08:53 +0000262 for (const Symbol *Sym : ExportedSymbols) {
Rui Ueyama7d696882018-02-28 00:18:34 +0000263 StringRef Name = Sym->getName();
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000264 WasmExport Export;
Rui Ueyama7d696882018-02-28 00:18:34 +0000265 DEBUG(dbgs() << "Export: " << Name << "\n");
266
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000267 if (auto *F = dyn_cast<DefinedFunction>(Sym))
268 Export = {Name, WASM_EXTERNAL_FUNCTION, F->getFunctionIndex()};
269 else if (auto *G = dyn_cast<DefinedGlobal>(Sym))
270 Export = {Name, WASM_EXTERNAL_GLOBAL, G->getGlobalIndex()};
Rui Ueyama7d696882018-02-28 00:18:34 +0000271 else if (isa<DefinedData>(Sym))
272 Export = {Name, WASM_EXTERNAL_GLOBAL, FakeGlobalIndex++};
273 else
Sam Clegg93102972018-02-23 05:08:53 +0000274 llvm_unreachable("unexpected symbol type");
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000275 writeExport(OS, Export);
Sam Cleggc94d3932017-11-17 18:14:09 +0000276 }
277}
278
Sam Cleggc94d3932017-11-17 18:14:09 +0000279void Writer::createElemSection() {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000280 if (IndirectFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000281 return;
282
283 SyntheticSection *Section = createSyntheticSection(WASM_SEC_ELEM);
284 raw_ostream &OS = Section->getStream();
285
286 writeUleb128(OS, 1, "segment count");
287 writeUleb128(OS, 0, "table index");
288 WasmInitExpr InitExpr;
289 InitExpr.Opcode = WASM_OPCODE_I32_CONST;
Sam Clegg48bbd632018-01-24 21:37:30 +0000290 InitExpr.Value.Int32 = kInitialTableOffset;
Sam Cleggc94d3932017-11-17 18:14:09 +0000291 writeInitExpr(OS, InitExpr);
Sam Cleggfc1a9122017-12-11 22:00:56 +0000292 writeUleb128(OS, IndirectFunctions.size(), "elem count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000293
Sam Clegg48bbd632018-01-24 21:37:30 +0000294 uint32_t TableIndex = kInitialTableOffset;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000295 for (const FunctionSymbol *Sym : IndirectFunctions) {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000296 assert(Sym->getTableIndex() == TableIndex);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000297 writeUleb128(OS, Sym->getFunctionIndex(), "function index");
Sam Cleggfc1a9122017-12-11 22:00:56 +0000298 ++TableIndex;
299 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000300}
301
302void Writer::createCodeSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000303 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000304 return;
305
306 log("createCodeSection");
307
Sam Clegg9f934222018-02-21 18:29:23 +0000308 auto Section = make<CodeSection>(InputFunctions);
Sam Cleggc94d3932017-11-17 18:14:09 +0000309 OutputSections.push_back(Section);
310}
311
312void Writer::createDataSection() {
313 if (!Segments.size())
314 return;
315
316 log("createDataSection");
317 auto Section = make<DataSection>(Segments);
318 OutputSections.push_back(Section);
319}
320
Sam Cleggd451da12017-12-19 19:56:27 +0000321// Create relocations sections in the final output.
Sam Cleggc94d3932017-11-17 18:14:09 +0000322// These are only created when relocatable output is requested.
323void Writer::createRelocSections() {
324 log("createRelocSections");
325 // Don't use iterator here since we are adding to OutputSection
326 size_t OrigSize = OutputSections.size();
327 for (size_t i = 0; i < OrigSize; i++) {
Rui Ueyama37254062018-02-28 00:01:31 +0000328 OutputSection *OSec = OutputSections[i];
329 uint32_t Count = OSec->numRelocations();
Sam Cleggc94d3932017-11-17 18:14:09 +0000330 if (!Count)
331 continue;
332
Rui Ueyama37254062018-02-28 00:01:31 +0000333 StringRef Name;
334 if (OSec->Type == WASM_SEC_DATA)
335 Name = "reloc.DATA";
336 else if (OSec->Type == WASM_SEC_CODE)
337 Name = "reloc.CODE";
Sam Cleggc94d3932017-11-17 18:14:09 +0000338 else
Sam Cleggd451da12017-12-19 19:56:27 +0000339 llvm_unreachable("relocations only supported for code and data");
Sam Cleggc94d3932017-11-17 18:14:09 +0000340
Rui Ueyama37254062018-02-28 00:01:31 +0000341 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, Name);
Sam Cleggc94d3932017-11-17 18:14:09 +0000342 raw_ostream &OS = Section->getStream();
Rui Ueyama37254062018-02-28 00:01:31 +0000343 writeUleb128(OS, OSec->Type, "reloc section");
Sam Cleggc94d3932017-11-17 18:14:09 +0000344 writeUleb128(OS, Count, "reloc count");
Rui Ueyama37254062018-02-28 00:01:31 +0000345 OSec->writeRelocations(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000346 }
347}
348
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000349static uint32_t getWasmFlags(const Symbol *Sym) {
350 uint32_t Flags = 0;
351 if (Sym->isLocal())
352 Flags |= WASM_SYMBOL_BINDING_LOCAL;
353 if (Sym->isWeak())
354 Flags |= WASM_SYMBOL_BINDING_WEAK;
355 if (Sym->isHidden())
356 Flags |= WASM_SYMBOL_VISIBILITY_HIDDEN;
357 if (Sym->isUndefined())
358 Flags |= WASM_SYMBOL_UNDEFINED;
359 return Flags;
360}
361
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000362// Some synthetic sections (e.g. "name" and "linking") have subsections.
363// Just like the synthetic sections themselves these need to be created before
364// they can be written out (since they are preceded by their length). This
365// class is used to create subsections and then write them into the stream
366// of the parent section.
367class SubSection {
368public:
369 explicit SubSection(uint32_t Type) : Type(Type) {}
370
371 void writeTo(raw_ostream &To) {
372 OS.flush();
Rui Ueyama67769102018-02-28 03:38:14 +0000373 writeUleb128(To, Type, "subsection type");
374 writeUleb128(To, Body.size(), "subsection size");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000375 To.write(Body.data(), Body.size());
376 }
377
378private:
379 uint32_t Type;
380 std::string Body;
381
382public:
383 raw_string_ostream OS{Body};
384};
385
Sam Clegg49ed9262017-12-01 00:53:21 +0000386// Create the custom "linking" section containing linker metadata.
Sam Cleggc94d3932017-11-17 18:14:09 +0000387// This is only created when relocatable output is requested.
388void Writer::createLinkingSection() {
389 SyntheticSection *Section =
390 createSyntheticSection(WASM_SEC_CUSTOM, "linking");
391 raw_ostream &OS = Section->getStream();
392
Sam Clegg0d0dd392017-12-19 17:09:45 +0000393 if (!Config->Relocatable)
394 return;
395
Sam Clegg93102972018-02-23 05:08:53 +0000396 if (!SymtabEntries.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000397 SubSection Sub(WASM_SYMBOL_TABLE);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000398 writeUleb128(Sub.OS, SymtabEntries.size(), "num symbols");
399
Sam Clegg93102972018-02-23 05:08:53 +0000400 for (const Symbol *Sym : SymtabEntries) {
401 assert(Sym->isDefined() || Sym->isUndefined());
402 WasmSymbolType Kind = Sym->getWasmType();
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000403 uint32_t Flags = getWasmFlags(Sym);
404
Sam Clegg8518e7d2018-03-01 18:06:39 +0000405 writeU8(Sub.OS, Kind, "sym kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000406 writeUleb128(Sub.OS, Flags, "sym flags");
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000407
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000408 if (auto *F = dyn_cast<FunctionSymbol>(Sym)) {
409 writeUleb128(Sub.OS, F->getFunctionIndex(), "index");
Sam Clegg93102972018-02-23 05:08:53 +0000410 if (Sym->isDefined())
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000411 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000412 } else if (auto *G = dyn_cast<GlobalSymbol>(Sym)) {
413 writeUleb128(Sub.OS, G->getGlobalIndex(), "index");
414 if (Sym->isDefined())
415 writeStr(Sub.OS, Sym->getName(), "sym name");
416 } else {
417 assert(isa<DataSymbol>(Sym));
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000418 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegg93102972018-02-23 05:08:53 +0000419 if (auto *DataSym = dyn_cast<DefinedData>(Sym)) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000420 writeUleb128(Sub.OS, DataSym->getOutputSegmentIndex(), "index");
421 writeUleb128(Sub.OS, DataSym->getOutputSegmentOffset(),
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000422 "data offset");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000423 writeUleb128(Sub.OS, DataSym->getSize(), "data size");
Sam Clegg93102972018-02-23 05:08:53 +0000424 }
Sam Clegg93102972018-02-23 05:08:53 +0000425 }
Sam Cleggd3052d52018-01-18 23:40:49 +0000426 }
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000427
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000428 Sub.writeTo(OS);
Sam Cleggd3052d52018-01-18 23:40:49 +0000429 }
430
Sam Clegg0d0dd392017-12-19 17:09:45 +0000431 if (Segments.size()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000432 SubSection Sub(WASM_SEGMENT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000433 writeUleb128(Sub.OS, Segments.size(), "num data segments");
Sam Cleggc94d3932017-11-17 18:14:09 +0000434 for (const OutputSegment *S : Segments) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000435 writeStr(Sub.OS, S->Name, "segment name");
436 writeUleb128(Sub.OS, S->Alignment, "alignment");
437 writeUleb128(Sub.OS, 0, "flags");
Sam Cleggc94d3932017-11-17 18:14:09 +0000438 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000439 Sub.writeTo(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000440 }
Sam Clegg0d0dd392017-12-19 17:09:45 +0000441
Sam Clegg0d0dd392017-12-19 17:09:45 +0000442 if (!InitFunctions.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000443 SubSection Sub(WASM_INIT_FUNCS);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000444 writeUleb128(Sub.OS, InitFunctions.size(), "num init functions");
Sam Clegg93102972018-02-23 05:08:53 +0000445 for (const WasmInitEntry &F : InitFunctions) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000446 writeUleb128(Sub.OS, F.Priority, "priority");
447 writeUleb128(Sub.OS, F.Sym->getOutputSymbolIndex(), "function index");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000448 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000449 Sub.writeTo(OS);
Sam Clegg0d0dd392017-12-19 17:09:45 +0000450 }
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000451
Nicholas Wilsondbd90bf2018-03-07 13:28:16 +0000452 struct ComdatEntry {
453 unsigned Kind;
454 uint32_t Index;
455 };
456 std::map<StringRef, std::vector<ComdatEntry>> Comdats;
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000457
Sam Clegg9f934222018-02-21 18:29:23 +0000458 for (const InputFunction *F : InputFunctions) {
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000459 StringRef Comdat = F->getComdatName();
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000460 if (!Comdat.empty())
461 Comdats[Comdat].emplace_back(
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000462 ComdatEntry{WASM_COMDAT_FUNCTION, F->getFunctionIndex()});
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000463 }
464 for (uint32_t I = 0; I < Segments.size(); ++I) {
Sam Cleggf98bccf2018-01-13 15:57:48 +0000465 const auto &InputSegments = Segments[I]->InputSegments;
466 if (InputSegments.empty())
467 continue;
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000468 StringRef Comdat = InputSegments[0]->getComdatName();
Sam Clegga697df522018-01-13 15:59:53 +0000469#ifndef NDEBUG
Sam Cleggf98bccf2018-01-13 15:57:48 +0000470 for (const InputSegment *IS : InputSegments)
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000471 assert(IS->getComdatName() == Comdat);
Sam Clegga697df522018-01-13 15:59:53 +0000472#endif
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000473 if (!Comdat.empty())
474 Comdats[Comdat].emplace_back(ComdatEntry{WASM_COMDAT_DATA, I});
475 }
476
477 if (!Comdats.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000478 SubSection Sub(WASM_COMDAT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000479 writeUleb128(Sub.OS, Comdats.size(), "num comdats");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000480 for (const auto &C : Comdats) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000481 writeStr(Sub.OS, C.first, "comdat name");
482 writeUleb128(Sub.OS, 0, "comdat flags"); // flags for future use
483 writeUleb128(Sub.OS, C.second.size(), "num entries");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000484 for (const ComdatEntry &Entry : C.second) {
Sam Clegg8518e7d2018-03-01 18:06:39 +0000485 writeU8(Sub.OS, Entry.Kind, "entry kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000486 writeUleb128(Sub.OS, Entry.Index, "entry index");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000487 }
488 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000489 Sub.writeTo(OS);
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000490 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000491}
492
493// Create the custom "name" section containing debug symbol names.
494void Writer::createNameSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000495 unsigned NumNames = NumImportedFunctions;
Sam Clegg9f934222018-02-21 18:29:23 +0000496 for (const InputFunction *F : InputFunctions)
Sam Clegg1963d712018-01-17 20:19:04 +0000497 if (!F->getName().empty())
498 ++NumNames;
Sam Cleggc94d3932017-11-17 18:14:09 +0000499
Sam Clegg1963d712018-01-17 20:19:04 +0000500 if (NumNames == 0)
501 return;
Sam Clegg50686852018-01-12 18:35:13 +0000502
Sam Cleggc94d3932017-11-17 18:14:09 +0000503 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "name");
504
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000505 SubSection Sub(WASM_NAMES_FUNCTION);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000506 writeUleb128(Sub.OS, NumNames, "name count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000507
Sam Clegg93102972018-02-23 05:08:53 +0000508 // Names must appear in function index order. As it happens ImportedSymbols
509 // and InputFunctions are numbered in order with imported functions coming
Sam Clegg1963d712018-01-17 20:19:04 +0000510 // first.
Sam Clegg93102972018-02-23 05:08:53 +0000511 for (const Symbol *S : ImportedSymbols) {
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000512 if (auto *F = dyn_cast<FunctionSymbol>(S)) {
513 writeUleb128(Sub.OS, F->getFunctionIndex(), "func index");
Nicholas Wilson531769b2018-03-13 13:30:04 +0000514 Optional<std::string> Name = demangleItanium(F->getName());
515 writeStr(Sub.OS, Name ? StringRef(*Name) : F->getName(), "symbol name");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000516 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000517 }
Sam Clegg9f934222018-02-21 18:29:23 +0000518 for (const InputFunction *F : InputFunctions) {
Sam Clegg1963d712018-01-17 20:19:04 +0000519 if (!F->getName().empty()) {
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000520 writeUleb128(Sub.OS, F->getFunctionIndex(), "func index");
Nicholas Wilson531769b2018-03-13 13:30:04 +0000521 Optional<std::string> Name = demangleItanium(F->getName());
522 writeStr(Sub.OS, Name ? StringRef(*Name) : F->getName(), "symbol name");
Sam Clegg1963d712018-01-17 20:19:04 +0000523 }
524 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000525
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000526 Sub.writeTo(Section->getStream());
Sam Cleggc94d3932017-11-17 18:14:09 +0000527}
528
529void Writer::writeHeader() {
530 memcpy(Buffer->getBufferStart(), Header.data(), Header.size());
531}
532
533void Writer::writeSections() {
534 uint8_t *Buf = Buffer->getBufferStart();
535 parallelForEach(OutputSections, [Buf](OutputSection *S) { S->writeTo(Buf); });
536}
537
538// Fix the memory layout of the output binary. This assigns memory offsets
Sam Clegg49ed9262017-12-01 00:53:21 +0000539// to each of the input data sections as well as the explicit stack region.
Sam Cleggf0d433d2018-02-02 22:59:56 +0000540// The memory layout is as follows, from low to high.
541// - initialized data (starting at Config->GlobalBase)
542// - BSS data (not currently implemented in llvm)
543// - explicit stack (Config->ZStackSize)
544// - heap start / unallocated
Sam Cleggc94d3932017-11-17 18:14:09 +0000545void Writer::layoutMemory() {
546 uint32_t MemoryPtr = 0;
Sam Clegg99eb42c2018-02-27 23:58:03 +0000547 MemoryPtr = Config->GlobalBase;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000548 log("mem: global base = " + Twine(Config->GlobalBase));
Sam Cleggc94d3932017-11-17 18:14:09 +0000549
550 createOutputSegments();
551
Sam Cleggf0d433d2018-02-02 22:59:56 +0000552 // Arbitrarily set __dso_handle handle to point to the start of the data
553 // segments.
554 if (WasmSym::DsoHandle)
555 WasmSym::DsoHandle->setVirtualAddress(MemoryPtr);
556
Sam Cleggc94d3932017-11-17 18:14:09 +0000557 for (OutputSegment *Seg : Segments) {
558 MemoryPtr = alignTo(MemoryPtr, Seg->Alignment);
559 Seg->StartVA = MemoryPtr;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000560 log(formatv("mem: {0,-15} offset={1,-8} size={2,-8} align={3}", Seg->Name,
561 MemoryPtr, Seg->Size, Seg->Alignment));
Sam Cleggc94d3932017-11-17 18:14:09 +0000562 MemoryPtr += Seg->Size;
563 }
564
Sam Cleggf0d433d2018-02-02 22:59:56 +0000565 // TODO: Add .bss space here.
Sam Clegg37a4a8a2018-02-07 03:04:53 +0000566 if (WasmSym::DataEnd)
567 WasmSym::DataEnd->setVirtualAddress(MemoryPtr);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000568
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000569 log("mem: static data = " + Twine(MemoryPtr - Config->GlobalBase));
Sam Cleggc94d3932017-11-17 18:14:09 +0000570
Sam Cleggf0d433d2018-02-02 22:59:56 +0000571 // Stack comes after static data and bss
Sam Cleggc94d3932017-11-17 18:14:09 +0000572 if (!Config->Relocatable) {
573 MemoryPtr = alignTo(MemoryPtr, kStackAlignment);
574 if (Config->ZStackSize != alignTo(Config->ZStackSize, kStackAlignment))
575 error("stack size must be " + Twine(kStackAlignment) + "-byte aligned");
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000576 log("mem: stack size = " + Twine(Config->ZStackSize));
577 log("mem: stack base = " + Twine(MemoryPtr));
Sam Cleggc94d3932017-11-17 18:14:09 +0000578 MemoryPtr += Config->ZStackSize;
Sam Clegg93102972018-02-23 05:08:53 +0000579 WasmSym::StackPointer->Global->Global.InitExpr.Value.Int32 = MemoryPtr;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000580 log("mem: stack top = " + Twine(MemoryPtr));
Sam Clegg93102972018-02-23 05:08:53 +0000581
Sam Clegg51bcdc22018-01-17 01:34:31 +0000582 // Set `__heap_base` to directly follow the end of the stack. We don't
583 // allocate any heap memory up front, but instead really on the malloc/brk
584 // implementation growing the memory at runtime.
Sam Cleggf0d433d2018-02-02 22:59:56 +0000585 WasmSym::HeapBase->setVirtualAddress(MemoryPtr);
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000586 log("mem: heap base = " + Twine(MemoryPtr));
Sam Cleggc94d3932017-11-17 18:14:09 +0000587 }
588
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000589 if (Config->InitialMemory != 0) {
590 if (Config->InitialMemory != alignTo(Config->InitialMemory, WasmPageSize))
591 error("initial memory must be " + Twine(WasmPageSize) + "-byte aligned");
592 if (MemoryPtr > Config->InitialMemory)
593 error("initial memory too small, " + Twine(MemoryPtr) + " bytes needed");
594 else
595 MemoryPtr = Config->InitialMemory;
596 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000597 uint32_t MemSize = alignTo(MemoryPtr, WasmPageSize);
598 NumMemoryPages = MemSize / WasmPageSize;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000599 log("mem: total pages = " + Twine(NumMemoryPages));
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000600
601 if (Config->MaxMemory != 0) {
602 if (Config->MaxMemory != alignTo(Config->MaxMemory, WasmPageSize))
603 error("maximum memory must be " + Twine(WasmPageSize) + "-byte aligned");
604 if (MemoryPtr > Config->MaxMemory)
605 error("maximum memory too small, " + Twine(MemoryPtr) + " bytes needed");
606 MaxMemoryPages = Config->MaxMemory / WasmPageSize;
607 log("mem: max pages = " + Twine(MaxMemoryPages));
608 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000609}
610
611SyntheticSection *Writer::createSyntheticSection(uint32_t Type,
Sam Cleggc375e4e2018-01-10 19:18:22 +0000612 StringRef Name) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000613 auto Sec = make<SyntheticSection>(Type, Name);
Sam Cleggab2ac292017-12-20 05:14:48 +0000614 log("createSection: " + toString(*Sec));
Sam Cleggc94d3932017-11-17 18:14:09 +0000615 OutputSections.push_back(Sec);
616 return Sec;
617}
618
619void Writer::createSections() {
620 // Known sections
621 createTypeSection();
622 createImportSection();
623 createFunctionSection();
624 createTableSection();
625 createMemorySection();
626 createGlobalSection();
627 createExportSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000628 createElemSection();
629 createCodeSection();
630 createDataSection();
631
632 // Custom sections
Sam Clegg99eb42c2018-02-27 23:58:03 +0000633 if (Config->Relocatable) {
Sam Clegg99eb42c2018-02-27 23:58:03 +0000634 createLinkingSection();
Nicholas Wilson94d3b162018-03-05 12:33:58 +0000635 createRelocSections();
Sam Clegg99eb42c2018-02-27 23:58:03 +0000636 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000637 if (!Config->StripDebug && !Config->StripAll)
638 createNameSection();
639
640 for (OutputSection *S : OutputSections) {
641 S->setOffset(FileSize);
642 S->finalizeContents();
643 FileSize += S->getSize();
644 }
645}
646
Sam Cleggc94d3932017-11-17 18:14:09 +0000647void Writer::calculateImports() {
Sam Clegg574d7ce2017-12-15 19:23:49 +0000648 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000649 if (!Sym->isUndefined())
650 continue;
651 if (isa<DataSymbol>(Sym))
652 continue;
653 if (Sym->isWeak() && !Config->Relocatable)
Sam Clegg574d7ce2017-12-15 19:23:49 +0000654 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000655
Sam Clegg93102972018-02-23 05:08:53 +0000656 DEBUG(dbgs() << "import: " << Sym->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000657 ImportedSymbols.emplace_back(Sym);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000658 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
659 F->setFunctionIndex(NumImportedFunctions++);
Sam Clegg93102972018-02-23 05:08:53 +0000660 else
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000661 cast<GlobalSymbol>(Sym)->setGlobalIndex(NumImportedGlobals++);
Sam Cleggc94d3932017-11-17 18:14:09 +0000662 }
663}
664
Sam Cleggd3052d52018-01-18 23:40:49 +0000665void Writer::calculateExports() {
Sam Clegg93102972018-02-23 05:08:53 +0000666 if (Config->Relocatable)
667 return;
Sam Cleggf0d433d2018-02-02 22:59:56 +0000668
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000669 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000670 if (!Sym->isDefined())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000671 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000672 if (Sym->isHidden() || Sym->isLocal())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000673 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000674 if (!Sym->isLive())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000675 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000676
677 DEBUG(dbgs() << "exporting sym: " << Sym->getName() << "\n");
678
Nicholas Wilsonf2f6d5e2018-03-02 14:51:36 +0000679 if (auto *D = dyn_cast<DefinedData>(Sym))
Sam Clegg93102972018-02-23 05:08:53 +0000680 DefinedFakeGlobals.emplace_back(D);
Sam Clegg93102972018-02-23 05:08:53 +0000681 ExportedSymbols.emplace_back(Sym);
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000682 }
Sam Clegg93102972018-02-23 05:08:53 +0000683}
684
685void Writer::assignSymtab() {
686 if (!Config->Relocatable)
687 return;
688
689 unsigned SymbolIndex = SymtabEntries.size();
Sam Cleggd3052d52018-01-18 23:40:49 +0000690 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg93102972018-02-23 05:08:53 +0000691 DEBUG(dbgs() << "Symtab entries: " << File->getName() << "\n");
Sam Cleggd3052d52018-01-18 23:40:49 +0000692 for (Symbol *Sym : File->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000693 if (Sym->getFile() != File)
Sam Cleggd3052d52018-01-18 23:40:49 +0000694 continue;
Nicholas Wilson06e0d172018-03-07 11:15:47 +0000695 // (Since this is relocatable output, GC is not performed so symbols must
696 // be live.)
697 assert(Sym->isLive());
Sam Clegg93102972018-02-23 05:08:53 +0000698 Sym->setOutputSymbolIndex(SymbolIndex++);
699 SymtabEntries.emplace_back(Sym);
Sam Cleggd3052d52018-01-18 23:40:49 +0000700 }
701 }
702
Sam Clegg93102972018-02-23 05:08:53 +0000703 // For the moment, relocatable output doesn't contain any synthetic functions,
704 // so no need to look through the Symtab for symbols not referenced by
705 // Symtab->ObjectFiles.
Sam Cleggd3052d52018-01-18 23:40:49 +0000706}
707
Sam Cleggc375e4e2018-01-10 19:18:22 +0000708uint32_t Writer::lookupType(const WasmSignature &Sig) {
Sam Clegg8d027d62018-01-10 20:12:26 +0000709 auto It = TypeIndices.find(Sig);
710 if (It == TypeIndices.end()) {
Sam Cleggc375e4e2018-01-10 19:18:22 +0000711 error("type not found: " + toString(Sig));
Sam Clegg8d027d62018-01-10 20:12:26 +0000712 return 0;
713 }
714 return It->second;
Sam Cleggc375e4e2018-01-10 19:18:22 +0000715}
716
717uint32_t Writer::registerType(const WasmSignature &Sig) {
Sam Cleggb8621592017-11-30 01:40:08 +0000718 auto Pair = TypeIndices.insert(std::make_pair(Sig, Types.size()));
Sam Cleggc375e4e2018-01-10 19:18:22 +0000719 if (Pair.second) {
720 DEBUG(dbgs() << "type " << toString(Sig) << "\n");
Sam Cleggb8621592017-11-30 01:40:08 +0000721 Types.push_back(&Sig);
Sam Cleggc375e4e2018-01-10 19:18:22 +0000722 }
Sam Cleggb8621592017-11-30 01:40:08 +0000723 return Pair.first->second;
724}
725
Sam Cleggc94d3932017-11-17 18:14:09 +0000726void Writer::calculateTypes() {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000727 // The output type section is the union of the following sets:
728 // 1. Any signature used in the TYPE relocation
729 // 2. The signatures of all imported functions
730 // 3. The signatures of all defined functions
731
Sam Cleggc94d3932017-11-17 18:14:09 +0000732 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000733 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
734 for (uint32_t I = 0; I < Types.size(); I++)
735 if (File->TypeIsUsed[I])
736 File->TypeMap[I] = registerType(Types[I]);
Sam Cleggc94d3932017-11-17 18:14:09 +0000737 }
Sam Clegg50686852018-01-12 18:35:13 +0000738
Sam Clegg93102972018-02-23 05:08:53 +0000739 for (const Symbol *Sym : ImportedSymbols)
740 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
741 registerType(*F->getFunctionType());
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000742
Sam Clegg9f934222018-02-21 18:29:23 +0000743 for (const InputFunction *F : InputFunctions)
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000744 registerType(F->Signature);
Sam Cleggc94d3932017-11-17 18:14:09 +0000745}
746
Sam Clegg8d146bb2018-01-09 23:56:44 +0000747void Writer::assignIndexes() {
Sam Clegg93102972018-02-23 05:08:53 +0000748 uint32_t FunctionIndex = NumImportedFunctions + InputFunctions.size();
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000749 auto AddDefinedFunction = [&](InputFunction *Func) {
750 if (!Func->Live)
751 return;
752 InputFunctions.emplace_back(Func);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000753 Func->setFunctionIndex(FunctionIndex++);
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000754 };
755
Nicholas Wilson5639da82018-03-12 15:44:07 +0000756 for (InputFunction *Func : Symtab->SyntheticFunctions)
757 AddDefinedFunction(Func);
758
Sam Clegg87e61922018-01-08 23:39:11 +0000759 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8d146bb2018-01-09 23:56:44 +0000760 DEBUG(dbgs() << "Functions: " << File->getName() << "\n");
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000761 for (InputFunction *Func : File->Functions)
762 AddDefinedFunction(Func);
Sam Clegg8d146bb2018-01-09 23:56:44 +0000763 }
764
Sam Clegg93102972018-02-23 05:08:53 +0000765 uint32_t TableIndex = kInitialTableOffset;
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000766 auto HandleRelocs = [&](InputChunk *Chunk) {
767 if (!Chunk->Live)
768 return;
769 ObjFile *File = Chunk->File;
770 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
Sam Clegg93102972018-02-23 05:08:53 +0000771 for (const WasmRelocation &Reloc : Chunk->getRelocations()) {
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000772 if (Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_I32 ||
773 Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_SLEB) {
774 FunctionSymbol *Sym = File->getFunctionSymbol(Reloc.Index);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000775 if (Sym->hasTableIndex() || !Sym->hasFunctionIndex())
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000776 continue;
777 Sym->setTableIndex(TableIndex++);
778 IndirectFunctions.emplace_back(Sym);
779 } else if (Reloc.Type == R_WEBASSEMBLY_TYPE_INDEX_LEB) {
Sam Clegg93102972018-02-23 05:08:53 +0000780 // Mark target type as live
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000781 File->TypeMap[Reloc.Index] = registerType(Types[Reloc.Index]);
782 File->TypeIsUsed[Reloc.Index] = true;
Sam Clegg93102972018-02-23 05:08:53 +0000783 } else if (Reloc.Type == R_WEBASSEMBLY_GLOBAL_INDEX_LEB) {
784 // Mark target global as live
785 GlobalSymbol *Sym = File->getGlobalSymbol(Reloc.Index);
786 if (auto *G = dyn_cast<DefinedGlobal>(Sym)) {
787 DEBUG(dbgs() << "marking global live: " << Sym->getName() << "\n");
788 G->Global->Live = true;
789 }
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000790 }
791 }
792 };
793
Sam Clegg8d146bb2018-01-09 23:56:44 +0000794 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000795 DEBUG(dbgs() << "Handle relocs: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000796 for (InputChunk *Chunk : File->Functions)
797 HandleRelocs(Chunk);
798 for (InputChunk *Chunk : File->Segments)
799 HandleRelocs(Chunk);
800 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000801
Sam Clegg93102972018-02-23 05:08:53 +0000802 uint32_t GlobalIndex = NumImportedGlobals + InputGlobals.size();
803 auto AddDefinedGlobal = [&](InputGlobal *Global) {
804 if (Global->Live) {
805 DEBUG(dbgs() << "AddDefinedGlobal: " << GlobalIndex << "\n");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000806 Global->setGlobalIndex(GlobalIndex++);
Sam Clegg93102972018-02-23 05:08:53 +0000807 InputGlobals.push_back(Global);
808 }
809 };
810
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000811 for (InputGlobal *Global : Symtab->SyntheticGlobals)
812 AddDefinedGlobal(Global);
Sam Clegg93102972018-02-23 05:08:53 +0000813
814 for (ObjFile *File : Symtab->ObjectFiles) {
815 DEBUG(dbgs() << "Globals: " << File->getName() << "\n");
816 for (InputGlobal *Global : File->Globals)
817 AddDefinedGlobal(Global);
Sam Cleggc94d3932017-11-17 18:14:09 +0000818 }
819}
820
821static StringRef getOutputDataSegmentName(StringRef Name) {
822 if (Config->Relocatable)
823 return Name;
Rui Ueyama4764b572018-02-28 00:57:28 +0000824 if (Name.startswith(".text."))
825 return ".text";
826 if (Name.startswith(".data."))
827 return ".data";
828 if (Name.startswith(".bss."))
829 return ".bss";
Sam Cleggc94d3932017-11-17 18:14:09 +0000830 return Name;
831}
832
833void Writer::createOutputSegments() {
834 for (ObjFile *File : Symtab->ObjectFiles) {
835 for (InputSegment *Segment : File->Segments) {
Sam Clegg447ae402018-02-13 20:29:38 +0000836 if (!Segment->Live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000837 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000838 StringRef Name = getOutputDataSegmentName(Segment->getName());
839 OutputSegment *&S = SegmentMap[Name];
840 if (S == nullptr) {
841 DEBUG(dbgs() << "new segment: " << Name << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000842 S = make<OutputSegment>(Name, Segments.size());
Sam Cleggc94d3932017-11-17 18:14:09 +0000843 Segments.push_back(S);
844 }
845 S->addInputSegment(Segment);
846 DEBUG(dbgs() << "added data: " << Name << ": " << S->Size << "\n");
Sam Cleggc94d3932017-11-17 18:14:09 +0000847 }
848 }
849}
850
Sam Clegg50686852018-01-12 18:35:13 +0000851static const int OPCODE_CALL = 0x10;
852static const int OPCODE_END = 0xb;
853
854// Create synthetic "__wasm_call_ctors" function based on ctor functions
855// in input object.
856void Writer::createCtorFunction() {
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000857 // First write the body's contents to a string.
858 std::string BodyContent;
Sam Clegg50686852018-01-12 18:35:13 +0000859 {
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000860 raw_string_ostream OS(BodyContent);
Sam Clegg50686852018-01-12 18:35:13 +0000861 writeUleb128(OS, 0, "num locals");
Sam Clegg93102972018-02-23 05:08:53 +0000862 for (const WasmInitEntry &F : InitFunctions) {
Sam Clegg50686852018-01-12 18:35:13 +0000863 writeU8(OS, OPCODE_CALL, "CALL");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000864 writeUleb128(OS, F.Sym->getFunctionIndex(), "function index");
Sam Clegg50686852018-01-12 18:35:13 +0000865 }
866 writeU8(OS, OPCODE_END, "END");
867 }
868
869 // Once we know the size of the body we can create the final function body
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000870 std::string FunctionBody;
871 {
872 raw_string_ostream OS(FunctionBody);
873 writeUleb128(OS, BodyContent.size(), "function size");
874 OS << BodyContent;
875 }
Rui Ueyama29abfe42018-02-28 17:43:15 +0000876
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000877 ArrayRef<uint8_t> Body = toArrayRef(Saver.save(FunctionBody));
878 cast<SyntheticFunction>(WasmSym::CallCtors->Function)->setBody(Body);
Sam Clegg50686852018-01-12 18:35:13 +0000879}
880
881// Populate InitFunctions vector with init functions from all input objects.
882// This is then used either when creating the output linking section or to
883// synthesize the "__wasm_call_ctors" function.
884void Writer::calculateInitFunctions() {
885 for (ObjFile *File : Symtab->ObjectFiles) {
886 const WasmLinkingData &L = File->getWasmObj()->linkingData();
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +0000887 for (const WasmInitFunc &F : L.InitFunctions) {
888 FunctionSymbol *Sym = File->getFunctionSymbol(F.Symbol);
889 if (*Sym->getFunctionType() != WasmSignature{{}, WASM_TYPE_NORESULT})
890 error("invalid signature for init func: " + toString(*Sym));
891 InitFunctions.emplace_back(WasmInitEntry{Sym, F.Priority});
892 }
Sam Clegg50686852018-01-12 18:35:13 +0000893 }
Rui Ueyamada69b712018-02-28 00:15:59 +0000894
Sam Clegg50686852018-01-12 18:35:13 +0000895 // Sort in order of priority (lowest first) so that they are called
896 // in the correct order.
Sam Clegg29b8feb2018-02-21 00:34:34 +0000897 std::stable_sort(InitFunctions.begin(), InitFunctions.end(),
Sam Clegg93102972018-02-23 05:08:53 +0000898 [](const WasmInitEntry &L, const WasmInitEntry &R) {
Sam Clegg29b8feb2018-02-21 00:34:34 +0000899 return L.Priority < R.Priority;
900 });
Sam Clegg50686852018-01-12 18:35:13 +0000901}
902
Sam Cleggc94d3932017-11-17 18:14:09 +0000903void Writer::run() {
Sam Clegg99eb42c2018-02-27 23:58:03 +0000904 if (Config->Relocatable)
905 Config->GlobalBase = 0;
906
Sam Cleggc94d3932017-11-17 18:14:09 +0000907 log("-- calculateImports");
908 calculateImports();
Sam Clegg8d146bb2018-01-09 23:56:44 +0000909 log("-- assignIndexes");
910 assignIndexes();
Sam Clegg50686852018-01-12 18:35:13 +0000911 log("-- calculateInitFunctions");
912 calculateInitFunctions();
913 if (!Config->Relocatable)
914 createCtorFunction();
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000915 log("-- calculateTypes");
916 calculateTypes();
Sam Clegg93102972018-02-23 05:08:53 +0000917 log("-- layoutMemory");
918 layoutMemory();
919 log("-- calculateExports");
920 calculateExports();
921 log("-- assignSymtab");
922 assignSymtab();
Sam Cleggc94d3932017-11-17 18:14:09 +0000923
924 if (errorHandler().Verbose) {
Sam Clegg9f934222018-02-21 18:29:23 +0000925 log("Defined Functions: " + Twine(InputFunctions.size()));
Sam Clegg93102972018-02-23 05:08:53 +0000926 log("Defined Globals : " + Twine(InputGlobals.size()));
927 log("Function Imports : " + Twine(NumImportedFunctions));
928 log("Global Imports : " + Twine(NumImportedGlobals));
Sam Cleggc94d3932017-11-17 18:14:09 +0000929 for (ObjFile *File : Symtab->ObjectFiles)
930 File->dumpInfo();
931 }
932
Sam Cleggc94d3932017-11-17 18:14:09 +0000933 createHeader();
934 log("-- createSections");
935 createSections();
936
937 log("-- openFile");
938 openFile();
939 if (errorCount())
940 return;
941
942 writeHeader();
943
944 log("-- writeSections");
945 writeSections();
946 if (errorCount())
947 return;
948
949 if (Error E = Buffer->commit())
950 fatal("failed to write the output file: " + toString(std::move(E)));
951}
952
953// Open a result file.
954void Writer::openFile() {
955 log("writing: " + Config->OutputFile);
Sam Cleggc94d3932017-11-17 18:14:09 +0000956
957 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
958 FileOutputBuffer::create(Config->OutputFile, FileSize,
959 FileOutputBuffer::F_executable);
960
961 if (!BufferOrErr)
962 error("failed to open " + Config->OutputFile + ": " +
963 toString(BufferOrErr.takeError()));
964 else
965 Buffer = std::move(*BufferOrErr);
966}
967
968void Writer::createHeader() {
969 raw_string_ostream OS(Header);
970 writeBytes(OS, WasmMagic, sizeof(WasmMagic), "wasm magic");
971 writeU32(OS, WasmVersion, "wasm version");
972 OS.flush();
973 FileSize += Header.size();
974}
975
976void lld::wasm::writeResult() { Writer().run(); }