blob: 5bce63f0e08c760e5925b8ba368ee58773a2b8ca [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;
Sam Cleggc94d3932017-11-17 18:14:09 +0000120
121 std::vector<const WasmSignature *> Types;
122 DenseMap<WasmSignature, int32_t, WasmSignatureDenseMapInfo> TypeIndices;
Sam Clegg93102972018-02-23 05:08:53 +0000123 std::vector<const Symbol *> ImportedSymbols;
124 unsigned NumImportedFunctions = 0;
125 unsigned NumImportedGlobals = 0;
126 std::vector<Symbol *> ExportedSymbols;
127 std::vector<const DefinedData *> DefinedFakeGlobals;
128 std::vector<InputGlobal *> InputGlobals;
Sam Clegg9f934222018-02-21 18:29:23 +0000129 std::vector<InputFunction *> InputFunctions;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000130 std::vector<const FunctionSymbol *> IndirectFunctions;
Sam Clegg93102972018-02-23 05:08:53 +0000131 std::vector<const Symbol *> SymtabEntries;
132 std::vector<WasmInitEntry> InitFunctions;
Sam Cleggc94d3932017-11-17 18:14:09 +0000133
134 // Elements that are used to construct the final output
135 std::string Header;
136 std::vector<OutputSection *> OutputSections;
137
138 std::unique_ptr<FileOutputBuffer> Buffer;
139
140 std::vector<OutputSegment *> Segments;
141 llvm::SmallDenseMap<StringRef, OutputSegment *> SegmentMap;
142};
143
144} // anonymous namespace
145
Sam Cleggc94d3932017-11-17 18:14:09 +0000146void Writer::createImportSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000147 uint32_t NumImports = ImportedSymbols.size();
Sam Cleggc94d3932017-11-17 18:14:09 +0000148 if (Config->ImportMemory)
149 ++NumImports;
150
151 if (NumImports == 0)
152 return;
153
154 SyntheticSection *Section = createSyntheticSection(WASM_SEC_IMPORT);
155 raw_ostream &OS = Section->getStream();
156
157 writeUleb128(OS, NumImports, "import count");
158
Sam Cleggc94d3932017-11-17 18:14:09 +0000159 if (Config->ImportMemory) {
160 WasmImport Import;
161 Import.Module = "env";
162 Import.Field = "memory";
163 Import.Kind = WASM_EXTERNAL_MEMORY;
164 Import.Memory.Flags = 0;
165 Import.Memory.Initial = NumMemoryPages;
166 writeImport(OS, Import);
167 }
168
Sam Clegg93102972018-02-23 05:08:53 +0000169 for (const Symbol *Sym : ImportedSymbols) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000170 WasmImport Import;
171 Import.Module = "env";
172 Import.Field = Sym->getName();
Sam Clegg93102972018-02-23 05:08:53 +0000173 if (auto *FunctionSym = dyn_cast<FunctionSymbol>(Sym)) {
174 Import.Kind = WASM_EXTERNAL_FUNCTION;
175 Import.SigIndex = lookupType(*FunctionSym->getFunctionType());
176 } else {
177 auto *GlobalSym = cast<GlobalSymbol>(Sym);
178 Import.Kind = WASM_EXTERNAL_GLOBAL;
179 Import.Global = *GlobalSym->getGlobalType();
180 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000181 writeImport(OS, Import);
182 }
183}
184
185void Writer::createTypeSection() {
186 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TYPE);
187 raw_ostream &OS = Section->getStream();
188 writeUleb128(OS, Types.size(), "type count");
Sam Cleggd451da12017-12-19 19:56:27 +0000189 for (const WasmSignature *Sig : Types)
Sam Cleggc94d3932017-11-17 18:14:09 +0000190 writeSig(OS, *Sig);
Sam Cleggc94d3932017-11-17 18:14:09 +0000191}
192
193void Writer::createFunctionSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000194 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000195 return;
196
197 SyntheticSection *Section = createSyntheticSection(WASM_SEC_FUNCTION);
198 raw_ostream &OS = Section->getStream();
199
Sam Clegg9f934222018-02-21 18:29:23 +0000200 writeUleb128(OS, InputFunctions.size(), "function count");
201 for (const InputFunction *Func : InputFunctions)
Sam Cleggc375e4e2018-01-10 19:18:22 +0000202 writeUleb128(OS, lookupType(Func->Signature), "sig index");
Sam Cleggc94d3932017-11-17 18:14:09 +0000203}
204
205void Writer::createMemorySection() {
206 if (Config->ImportMemory)
207 return;
208
209 SyntheticSection *Section = createSyntheticSection(WASM_SEC_MEMORY);
210 raw_ostream &OS = Section->getStream();
211
212 writeUleb128(OS, 1, "memory count");
213 writeUleb128(OS, 0, "memory limits flags");
214 writeUleb128(OS, NumMemoryPages, "initial pages");
215}
216
217void Writer::createGlobalSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000218 unsigned NumGlobals = InputGlobals.size() + DefinedFakeGlobals.size();
219 if (NumGlobals == 0)
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000220 return;
221
Sam Cleggc94d3932017-11-17 18:14:09 +0000222 SyntheticSection *Section = createSyntheticSection(WASM_SEC_GLOBAL);
223 raw_ostream &OS = Section->getStream();
224
Sam Clegg93102972018-02-23 05:08:53 +0000225 writeUleb128(OS, NumGlobals, "global count");
226 for (const InputGlobal *G : InputGlobals)
227 writeGlobal(OS, G->Global);
228 for (const DefinedData *Sym : DefinedFakeGlobals) {
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000229 WasmGlobal Global;
Sam Clegg93102972018-02-23 05:08:53 +0000230 Global.Type = {WASM_TYPE_I32, false};
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000231 Global.InitExpr.Opcode = WASM_OPCODE_I32_CONST;
232 Global.InitExpr.Value.Int32 = Sym->getVirtualAddress();
Sam Cleggc94d3932017-11-17 18:14:09 +0000233 writeGlobal(OS, Global);
234 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000235}
236
237void Writer::createTableSection() {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000238 // Always output a table section, even if there are no indirect calls.
239 // There are two reasons for this:
240 // 1. For executables it is useful to have an empty table slot at 0
241 // which can be filled with a null function call handler.
242 // 2. If we don't do this, any program that contains a call_indirect but
243 // no address-taken function will fail at validation time since it is
244 // a validation error to include a call_indirect instruction if there
245 // is not table.
Sam Clegg48bbd632018-01-24 21:37:30 +0000246 uint32_t TableSize = kInitialTableOffset + IndirectFunctions.size();
Sam Cleggfc1a9122017-12-11 22:00:56 +0000247
Sam Cleggc94d3932017-11-17 18:14:09 +0000248 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TABLE);
249 raw_ostream &OS = Section->getStream();
250
251 writeUleb128(OS, 1, "table count");
Sam Clegg8518e7d2018-03-01 18:06:39 +0000252 writeU8(OS, WASM_TYPE_ANYFUNC, "table type");
Sam Cleggc94d3932017-11-17 18:14:09 +0000253 writeUleb128(OS, WASM_LIMITS_FLAG_HAS_MAX, "table flags");
Sam Cleggfc1a9122017-12-11 22:00:56 +0000254 writeUleb128(OS, TableSize, "table initial size");
255 writeUleb128(OS, TableSize, "table max size");
Sam Cleggc94d3932017-11-17 18:14:09 +0000256}
257
258void Writer::createExportSection() {
Sam Cleggc94d3932017-11-17 18:14:09 +0000259 bool ExportMemory = !Config->Relocatable && !Config->ImportMemory;
Sam Cleggc94d3932017-11-17 18:14:09 +0000260
Sam Cleggd3052d52018-01-18 23:40:49 +0000261 uint32_t NumExports = (ExportMemory ? 1 : 0) + ExportedSymbols.size();
Sam Cleggc94d3932017-11-17 18:14:09 +0000262 if (!NumExports)
263 return;
264
265 SyntheticSection *Section = createSyntheticSection(WASM_SEC_EXPORT);
266 raw_ostream &OS = Section->getStream();
267
268 writeUleb128(OS, NumExports, "export count");
269
Rui Ueyama7d696882018-02-28 00:18:34 +0000270 if (ExportMemory)
271 writeExport(OS, {"memory", WASM_EXTERNAL_MEMORY, 0});
Sam Cleggc94d3932017-11-17 18:14:09 +0000272
Sam Clegg93102972018-02-23 05:08:53 +0000273 unsigned FakeGlobalIndex = NumImportedGlobals + InputGlobals.size();
Rui Ueyama7d696882018-02-28 00:18:34 +0000274
Sam Clegg93102972018-02-23 05:08:53 +0000275 for (const Symbol *Sym : ExportedSymbols) {
Rui Ueyama7d696882018-02-28 00:18:34 +0000276 StringRef Name = Sym->getName();
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000277 WasmExport Export;
Rui Ueyama7d696882018-02-28 00:18:34 +0000278 DEBUG(dbgs() << "Export: " << Name << "\n");
279
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000280 if (auto *F = dyn_cast<DefinedFunction>(Sym))
281 Export = {Name, WASM_EXTERNAL_FUNCTION, F->getFunctionIndex()};
282 else if (auto *G = dyn_cast<DefinedGlobal>(Sym))
283 Export = {Name, WASM_EXTERNAL_GLOBAL, G->getGlobalIndex()};
Rui Ueyama7d696882018-02-28 00:18:34 +0000284 else if (isa<DefinedData>(Sym))
285 Export = {Name, WASM_EXTERNAL_GLOBAL, FakeGlobalIndex++};
286 else
Sam Clegg93102972018-02-23 05:08:53 +0000287 llvm_unreachable("unexpected symbol type");
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000288 writeExport(OS, Export);
Sam Cleggc94d3932017-11-17 18:14:09 +0000289 }
290}
291
Sam Cleggc94d3932017-11-17 18:14:09 +0000292void Writer::createElemSection() {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000293 if (IndirectFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000294 return;
295
296 SyntheticSection *Section = createSyntheticSection(WASM_SEC_ELEM);
297 raw_ostream &OS = Section->getStream();
298
299 writeUleb128(OS, 1, "segment count");
300 writeUleb128(OS, 0, "table index");
301 WasmInitExpr InitExpr;
302 InitExpr.Opcode = WASM_OPCODE_I32_CONST;
Sam Clegg48bbd632018-01-24 21:37:30 +0000303 InitExpr.Value.Int32 = kInitialTableOffset;
Sam Cleggc94d3932017-11-17 18:14:09 +0000304 writeInitExpr(OS, InitExpr);
Sam Cleggfc1a9122017-12-11 22:00:56 +0000305 writeUleb128(OS, IndirectFunctions.size(), "elem count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000306
Sam Clegg48bbd632018-01-24 21:37:30 +0000307 uint32_t TableIndex = kInitialTableOffset;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000308 for (const FunctionSymbol *Sym : IndirectFunctions) {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000309 assert(Sym->getTableIndex() == TableIndex);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000310 writeUleb128(OS, Sym->getFunctionIndex(), "function index");
Sam Cleggfc1a9122017-12-11 22:00:56 +0000311 ++TableIndex;
312 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000313}
314
315void Writer::createCodeSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000316 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000317 return;
318
319 log("createCodeSection");
320
Sam Clegg9f934222018-02-21 18:29:23 +0000321 auto Section = make<CodeSection>(InputFunctions);
Sam Cleggc94d3932017-11-17 18:14:09 +0000322 OutputSections.push_back(Section);
323}
324
325void Writer::createDataSection() {
326 if (!Segments.size())
327 return;
328
329 log("createDataSection");
330 auto Section = make<DataSection>(Segments);
331 OutputSections.push_back(Section);
332}
333
Sam Cleggd451da12017-12-19 19:56:27 +0000334// Create relocations sections in the final output.
Sam Cleggc94d3932017-11-17 18:14:09 +0000335// These are only created when relocatable output is requested.
336void Writer::createRelocSections() {
337 log("createRelocSections");
338 // Don't use iterator here since we are adding to OutputSection
339 size_t OrigSize = OutputSections.size();
340 for (size_t i = 0; i < OrigSize; i++) {
Rui Ueyama37254062018-02-28 00:01:31 +0000341 OutputSection *OSec = OutputSections[i];
342 uint32_t Count = OSec->numRelocations();
Sam Cleggc94d3932017-11-17 18:14:09 +0000343 if (!Count)
344 continue;
345
Rui Ueyama37254062018-02-28 00:01:31 +0000346 StringRef Name;
347 if (OSec->Type == WASM_SEC_DATA)
348 Name = "reloc.DATA";
349 else if (OSec->Type == WASM_SEC_CODE)
350 Name = "reloc.CODE";
Sam Cleggc94d3932017-11-17 18:14:09 +0000351 else
Sam Cleggd451da12017-12-19 19:56:27 +0000352 llvm_unreachable("relocations only supported for code and data");
Sam Cleggc94d3932017-11-17 18:14:09 +0000353
Rui Ueyama37254062018-02-28 00:01:31 +0000354 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, Name);
Sam Cleggc94d3932017-11-17 18:14:09 +0000355 raw_ostream &OS = Section->getStream();
Rui Ueyama37254062018-02-28 00:01:31 +0000356 writeUleb128(OS, OSec->Type, "reloc section");
Sam Cleggc94d3932017-11-17 18:14:09 +0000357 writeUleb128(OS, Count, "reloc count");
Rui Ueyama37254062018-02-28 00:01:31 +0000358 OSec->writeRelocations(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000359 }
360}
361
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000362static uint32_t getWasmFlags(const Symbol *Sym) {
363 uint32_t Flags = 0;
364 if (Sym->isLocal())
365 Flags |= WASM_SYMBOL_BINDING_LOCAL;
366 if (Sym->isWeak())
367 Flags |= WASM_SYMBOL_BINDING_WEAK;
368 if (Sym->isHidden())
369 Flags |= WASM_SYMBOL_VISIBILITY_HIDDEN;
370 if (Sym->isUndefined())
371 Flags |= WASM_SYMBOL_UNDEFINED;
372 return Flags;
373}
374
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000375// Some synthetic sections (e.g. "name" and "linking") have subsections.
376// Just like the synthetic sections themselves these need to be created before
377// they can be written out (since they are preceded by their length). This
378// class is used to create subsections and then write them into the stream
379// of the parent section.
380class SubSection {
381public:
382 explicit SubSection(uint32_t Type) : Type(Type) {}
383
384 void writeTo(raw_ostream &To) {
385 OS.flush();
Rui Ueyama67769102018-02-28 03:38:14 +0000386 writeUleb128(To, Type, "subsection type");
387 writeUleb128(To, Body.size(), "subsection size");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000388 To.write(Body.data(), Body.size());
389 }
390
391private:
392 uint32_t Type;
393 std::string Body;
394
395public:
396 raw_string_ostream OS{Body};
397};
398
Sam Clegg49ed9262017-12-01 00:53:21 +0000399// Create the custom "linking" section containing linker metadata.
Sam Cleggc94d3932017-11-17 18:14:09 +0000400// This is only created when relocatable output is requested.
401void Writer::createLinkingSection() {
402 SyntheticSection *Section =
403 createSyntheticSection(WASM_SEC_CUSTOM, "linking");
404 raw_ostream &OS = Section->getStream();
405
Sam Clegg0d0dd392017-12-19 17:09:45 +0000406 if (!Config->Relocatable)
407 return;
408
Sam Clegg93102972018-02-23 05:08:53 +0000409 if (!SymtabEntries.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000410 SubSection Sub(WASM_SYMBOL_TABLE);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000411 writeUleb128(Sub.OS, SymtabEntries.size(), "num symbols");
412
Sam Clegg93102972018-02-23 05:08:53 +0000413 for (const Symbol *Sym : SymtabEntries) {
414 assert(Sym->isDefined() || Sym->isUndefined());
415 WasmSymbolType Kind = Sym->getWasmType();
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000416 uint32_t Flags = getWasmFlags(Sym);
417
Sam Clegg8518e7d2018-03-01 18:06:39 +0000418 writeU8(Sub.OS, Kind, "sym kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000419 writeUleb128(Sub.OS, Flags, "sym flags");
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000420
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000421 if (auto *F = dyn_cast<FunctionSymbol>(Sym)) {
422 writeUleb128(Sub.OS, F->getFunctionIndex(), "index");
Sam Clegg93102972018-02-23 05:08:53 +0000423 if (Sym->isDefined())
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000424 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000425 } else if (auto *G = dyn_cast<GlobalSymbol>(Sym)) {
426 writeUleb128(Sub.OS, G->getGlobalIndex(), "index");
427 if (Sym->isDefined())
428 writeStr(Sub.OS, Sym->getName(), "sym name");
429 } else {
430 assert(isa<DataSymbol>(Sym));
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000431 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegg93102972018-02-23 05:08:53 +0000432 if (auto *DataSym = dyn_cast<DefinedData>(Sym)) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000433 writeUleb128(Sub.OS, DataSym->getOutputSegmentIndex(), "index");
434 writeUleb128(Sub.OS, DataSym->getOutputSegmentOffset(),
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000435 "data offset");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000436 writeUleb128(Sub.OS, DataSym->getSize(), "data size");
Sam Clegg93102972018-02-23 05:08:53 +0000437 }
Sam Clegg93102972018-02-23 05:08:53 +0000438 }
Sam Cleggd3052d52018-01-18 23:40:49 +0000439 }
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000440
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000441 Sub.writeTo(OS);
Sam Cleggd3052d52018-01-18 23:40:49 +0000442 }
443
Sam Clegg0d0dd392017-12-19 17:09:45 +0000444 if (Segments.size()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000445 SubSection Sub(WASM_SEGMENT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000446 writeUleb128(Sub.OS, Segments.size(), "num data segments");
Sam Cleggc94d3932017-11-17 18:14:09 +0000447 for (const OutputSegment *S : Segments) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000448 writeStr(Sub.OS, S->Name, "segment name");
449 writeUleb128(Sub.OS, S->Alignment, "alignment");
450 writeUleb128(Sub.OS, 0, "flags");
Sam Cleggc94d3932017-11-17 18:14:09 +0000451 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000452 Sub.writeTo(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000453 }
Sam Clegg0d0dd392017-12-19 17:09:45 +0000454
Sam Clegg0d0dd392017-12-19 17:09:45 +0000455 if (!InitFunctions.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000456 SubSection Sub(WASM_INIT_FUNCS);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000457 writeUleb128(Sub.OS, InitFunctions.size(), "num init functions");
Sam Clegg93102972018-02-23 05:08:53 +0000458 for (const WasmInitEntry &F : InitFunctions) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000459 writeUleb128(Sub.OS, F.Priority, "priority");
460 writeUleb128(Sub.OS, F.Sym->getOutputSymbolIndex(), "function index");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000461 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000462 Sub.writeTo(OS);
Sam Clegg0d0dd392017-12-19 17:09:45 +0000463 }
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000464
Nicholas Wilsondbd90bf2018-03-07 13:28:16 +0000465 struct ComdatEntry {
466 unsigned Kind;
467 uint32_t Index;
468 };
469 std::map<StringRef, std::vector<ComdatEntry>> Comdats;
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000470
Sam Clegg9f934222018-02-21 18:29:23 +0000471 for (const InputFunction *F : InputFunctions) {
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000472 StringRef Comdat = F->getComdat();
473 if (!Comdat.empty())
474 Comdats[Comdat].emplace_back(
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000475 ComdatEntry{WASM_COMDAT_FUNCTION, F->getFunctionIndex()});
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000476 }
477 for (uint32_t I = 0; I < Segments.size(); ++I) {
Sam Cleggf98bccf2018-01-13 15:57:48 +0000478 const auto &InputSegments = Segments[I]->InputSegments;
479 if (InputSegments.empty())
480 continue;
481 StringRef Comdat = InputSegments[0]->getComdat();
Sam Clegga697df522018-01-13 15:59:53 +0000482#ifndef NDEBUG
Sam Cleggf98bccf2018-01-13 15:57:48 +0000483 for (const InputSegment *IS : InputSegments)
484 assert(IS->getComdat() == Comdat);
Sam Clegga697df522018-01-13 15:59:53 +0000485#endif
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000486 if (!Comdat.empty())
487 Comdats[Comdat].emplace_back(ComdatEntry{WASM_COMDAT_DATA, I});
488 }
489
490 if (!Comdats.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000491 SubSection Sub(WASM_COMDAT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000492 writeUleb128(Sub.OS, Comdats.size(), "num comdats");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000493 for (const auto &C : Comdats) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000494 writeStr(Sub.OS, C.first, "comdat name");
495 writeUleb128(Sub.OS, 0, "comdat flags"); // flags for future use
496 writeUleb128(Sub.OS, C.second.size(), "num entries");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000497 for (const ComdatEntry &Entry : C.second) {
Sam Clegg8518e7d2018-03-01 18:06:39 +0000498 writeU8(Sub.OS, Entry.Kind, "entry kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000499 writeUleb128(Sub.OS, Entry.Index, "entry index");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000500 }
501 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000502 Sub.writeTo(OS);
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000503 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000504}
505
506// Create the custom "name" section containing debug symbol names.
507void Writer::createNameSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000508 unsigned NumNames = NumImportedFunctions;
Sam Clegg9f934222018-02-21 18:29:23 +0000509 for (const InputFunction *F : InputFunctions)
Sam Clegg1963d712018-01-17 20:19:04 +0000510 if (!F->getName().empty())
511 ++NumNames;
Sam Cleggc94d3932017-11-17 18:14:09 +0000512
Sam Clegg1963d712018-01-17 20:19:04 +0000513 if (NumNames == 0)
514 return;
Sam Clegg50686852018-01-12 18:35:13 +0000515
Sam Cleggc94d3932017-11-17 18:14:09 +0000516 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "name");
517
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000518 SubSection Sub(WASM_NAMES_FUNCTION);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000519 writeUleb128(Sub.OS, NumNames, "name count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000520
Sam Clegg93102972018-02-23 05:08:53 +0000521 // Names must appear in function index order. As it happens ImportedSymbols
522 // and InputFunctions are numbered in order with imported functions coming
Sam Clegg1963d712018-01-17 20:19:04 +0000523 // first.
Sam Clegg93102972018-02-23 05:08:53 +0000524 for (const Symbol *S : ImportedSymbols) {
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000525 if (auto *F = dyn_cast<FunctionSymbol>(S)) {
526 writeUleb128(Sub.OS, F->getFunctionIndex(), "func index");
Nicholas Wilson531769b2018-03-13 13:30:04 +0000527 Optional<std::string> Name = demangleItanium(F->getName());
528 writeStr(Sub.OS, Name ? StringRef(*Name) : F->getName(), "symbol name");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000529 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000530 }
Sam Clegg9f934222018-02-21 18:29:23 +0000531 for (const InputFunction *F : InputFunctions) {
Sam Clegg1963d712018-01-17 20:19:04 +0000532 if (!F->getName().empty()) {
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000533 writeUleb128(Sub.OS, F->getFunctionIndex(), "func index");
Nicholas Wilson531769b2018-03-13 13:30:04 +0000534 Optional<std::string> Name = demangleItanium(F->getName());
535 writeStr(Sub.OS, Name ? StringRef(*Name) : F->getName(), "symbol name");
Sam Clegg1963d712018-01-17 20:19:04 +0000536 }
537 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000538
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000539 Sub.writeTo(Section->getStream());
Sam Cleggc94d3932017-11-17 18:14:09 +0000540}
541
542void Writer::writeHeader() {
543 memcpy(Buffer->getBufferStart(), Header.data(), Header.size());
544}
545
546void Writer::writeSections() {
547 uint8_t *Buf = Buffer->getBufferStart();
548 parallelForEach(OutputSections, [Buf](OutputSection *S) { S->writeTo(Buf); });
549}
550
551// Fix the memory layout of the output binary. This assigns memory offsets
Sam Clegg49ed9262017-12-01 00:53:21 +0000552// to each of the input data sections as well as the explicit stack region.
Sam Cleggf0d433d2018-02-02 22:59:56 +0000553// The memory layout is as follows, from low to high.
554// - initialized data (starting at Config->GlobalBase)
555// - BSS data (not currently implemented in llvm)
556// - explicit stack (Config->ZStackSize)
557// - heap start / unallocated
Sam Cleggc94d3932017-11-17 18:14:09 +0000558void Writer::layoutMemory() {
559 uint32_t MemoryPtr = 0;
Sam Clegg99eb42c2018-02-27 23:58:03 +0000560 MemoryPtr = Config->GlobalBase;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000561 log("mem: global base = " + Twine(Config->GlobalBase));
Sam Cleggc94d3932017-11-17 18:14:09 +0000562
563 createOutputSegments();
564
Sam Cleggf0d433d2018-02-02 22:59:56 +0000565 // Arbitrarily set __dso_handle handle to point to the start of the data
566 // segments.
567 if (WasmSym::DsoHandle)
568 WasmSym::DsoHandle->setVirtualAddress(MemoryPtr);
569
Sam Cleggc94d3932017-11-17 18:14:09 +0000570 for (OutputSegment *Seg : Segments) {
571 MemoryPtr = alignTo(MemoryPtr, Seg->Alignment);
572 Seg->StartVA = MemoryPtr;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000573 log(formatv("mem: {0,-15} offset={1,-8} size={2,-8} align={3}", Seg->Name,
574 MemoryPtr, Seg->Size, Seg->Alignment));
Sam Cleggc94d3932017-11-17 18:14:09 +0000575 MemoryPtr += Seg->Size;
576 }
577
Sam Cleggf0d433d2018-02-02 22:59:56 +0000578 // TODO: Add .bss space here.
Sam Clegg37a4a8a2018-02-07 03:04:53 +0000579 if (WasmSym::DataEnd)
580 WasmSym::DataEnd->setVirtualAddress(MemoryPtr);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000581
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000582 log("mem: static data = " + Twine(MemoryPtr - Config->GlobalBase));
Sam Cleggc94d3932017-11-17 18:14:09 +0000583
Sam Cleggf0d433d2018-02-02 22:59:56 +0000584 // Stack comes after static data and bss
Sam Cleggc94d3932017-11-17 18:14:09 +0000585 if (!Config->Relocatable) {
586 MemoryPtr = alignTo(MemoryPtr, kStackAlignment);
587 if (Config->ZStackSize != alignTo(Config->ZStackSize, kStackAlignment))
588 error("stack size must be " + Twine(kStackAlignment) + "-byte aligned");
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000589 log("mem: stack size = " + Twine(Config->ZStackSize));
590 log("mem: stack base = " + Twine(MemoryPtr));
Sam Cleggc94d3932017-11-17 18:14:09 +0000591 MemoryPtr += Config->ZStackSize;
Sam Clegg93102972018-02-23 05:08:53 +0000592 WasmSym::StackPointer->Global->Global.InitExpr.Value.Int32 = MemoryPtr;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000593 log("mem: stack top = " + Twine(MemoryPtr));
Sam Clegg93102972018-02-23 05:08:53 +0000594
Sam Clegg51bcdc22018-01-17 01:34:31 +0000595 // Set `__heap_base` to directly follow the end of the stack. We don't
596 // allocate any heap memory up front, but instead really on the malloc/brk
597 // implementation growing the memory at runtime.
Sam Cleggf0d433d2018-02-02 22:59:56 +0000598 WasmSym::HeapBase->setVirtualAddress(MemoryPtr);
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000599 log("mem: heap base = " + Twine(MemoryPtr));
Sam Cleggc94d3932017-11-17 18:14:09 +0000600 }
601
602 uint32_t MemSize = alignTo(MemoryPtr, WasmPageSize);
603 NumMemoryPages = MemSize / WasmPageSize;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000604 log("mem: total pages = " + Twine(NumMemoryPages));
Sam Cleggc94d3932017-11-17 18:14:09 +0000605}
606
607SyntheticSection *Writer::createSyntheticSection(uint32_t Type,
Sam Cleggc375e4e2018-01-10 19:18:22 +0000608 StringRef Name) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000609 auto Sec = make<SyntheticSection>(Type, Name);
Sam Cleggab2ac292017-12-20 05:14:48 +0000610 log("createSection: " + toString(*Sec));
Sam Cleggc94d3932017-11-17 18:14:09 +0000611 OutputSections.push_back(Sec);
612 return Sec;
613}
614
615void Writer::createSections() {
616 // Known sections
617 createTypeSection();
618 createImportSection();
619 createFunctionSection();
620 createTableSection();
621 createMemorySection();
622 createGlobalSection();
623 createExportSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000624 createElemSection();
625 createCodeSection();
626 createDataSection();
627
628 // Custom sections
Sam Clegg99eb42c2018-02-27 23:58:03 +0000629 if (Config->Relocatable) {
Sam Clegg99eb42c2018-02-27 23:58:03 +0000630 createLinkingSection();
Nicholas Wilson94d3b162018-03-05 12:33:58 +0000631 createRelocSections();
Sam Clegg99eb42c2018-02-27 23:58:03 +0000632 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000633 if (!Config->StripDebug && !Config->StripAll)
634 createNameSection();
635
636 for (OutputSection *S : OutputSections) {
637 S->setOffset(FileSize);
638 S->finalizeContents();
639 FileSize += S->getSize();
640 }
641}
642
Sam Cleggc94d3932017-11-17 18:14:09 +0000643void Writer::calculateImports() {
Sam Clegg574d7ce2017-12-15 19:23:49 +0000644 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000645 if (!Sym->isUndefined())
646 continue;
647 if (isa<DataSymbol>(Sym))
648 continue;
649 if (Sym->isWeak() && !Config->Relocatable)
Sam Clegg574d7ce2017-12-15 19:23:49 +0000650 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000651
Sam Clegg93102972018-02-23 05:08:53 +0000652 DEBUG(dbgs() << "import: " << Sym->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000653 ImportedSymbols.emplace_back(Sym);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000654 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
655 F->setFunctionIndex(NumImportedFunctions++);
Sam Clegg93102972018-02-23 05:08:53 +0000656 else
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000657 cast<GlobalSymbol>(Sym)->setGlobalIndex(NumImportedGlobals++);
Sam Cleggc94d3932017-11-17 18:14:09 +0000658 }
659}
660
Sam Cleggd3052d52018-01-18 23:40:49 +0000661void Writer::calculateExports() {
Sam Clegg93102972018-02-23 05:08:53 +0000662 if (Config->Relocatable)
663 return;
Sam Cleggf0d433d2018-02-02 22:59:56 +0000664
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000665 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000666 if (!Sym->isDefined())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000667 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000668 if (Sym->isHidden() || Sym->isLocal())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000669 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000670 if (!Sym->isLive())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000671 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000672
673 DEBUG(dbgs() << "exporting sym: " << Sym->getName() << "\n");
674
Nicholas Wilsonf2f6d5e2018-03-02 14:51:36 +0000675 if (auto *D = dyn_cast<DefinedData>(Sym))
Sam Clegg93102972018-02-23 05:08:53 +0000676 DefinedFakeGlobals.emplace_back(D);
Sam Clegg93102972018-02-23 05:08:53 +0000677 ExportedSymbols.emplace_back(Sym);
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000678 }
Sam Clegg93102972018-02-23 05:08:53 +0000679}
680
681void Writer::assignSymtab() {
682 if (!Config->Relocatable)
683 return;
684
685 unsigned SymbolIndex = SymtabEntries.size();
Sam Cleggd3052d52018-01-18 23:40:49 +0000686 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg93102972018-02-23 05:08:53 +0000687 DEBUG(dbgs() << "Symtab entries: " << File->getName() << "\n");
Sam Cleggd3052d52018-01-18 23:40:49 +0000688 for (Symbol *Sym : File->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000689 if (Sym->getFile() != File)
Sam Cleggd3052d52018-01-18 23:40:49 +0000690 continue;
Nicholas Wilson06e0d172018-03-07 11:15:47 +0000691 // (Since this is relocatable output, GC is not performed so symbols must
692 // be live.)
693 assert(Sym->isLive());
Sam Clegg93102972018-02-23 05:08:53 +0000694 Sym->setOutputSymbolIndex(SymbolIndex++);
695 SymtabEntries.emplace_back(Sym);
Sam Cleggd3052d52018-01-18 23:40:49 +0000696 }
697 }
698
Sam Clegg93102972018-02-23 05:08:53 +0000699 // For the moment, relocatable output doesn't contain any synthetic functions,
700 // so no need to look through the Symtab for symbols not referenced by
701 // Symtab->ObjectFiles.
Sam Cleggd3052d52018-01-18 23:40:49 +0000702}
703
Sam Cleggc375e4e2018-01-10 19:18:22 +0000704uint32_t Writer::lookupType(const WasmSignature &Sig) {
Sam Clegg8d027d62018-01-10 20:12:26 +0000705 auto It = TypeIndices.find(Sig);
706 if (It == TypeIndices.end()) {
Sam Cleggc375e4e2018-01-10 19:18:22 +0000707 error("type not found: " + toString(Sig));
Sam Clegg8d027d62018-01-10 20:12:26 +0000708 return 0;
709 }
710 return It->second;
Sam Cleggc375e4e2018-01-10 19:18:22 +0000711}
712
713uint32_t Writer::registerType(const WasmSignature &Sig) {
Sam Cleggb8621592017-11-30 01:40:08 +0000714 auto Pair = TypeIndices.insert(std::make_pair(Sig, Types.size()));
Sam Cleggc375e4e2018-01-10 19:18:22 +0000715 if (Pair.second) {
716 DEBUG(dbgs() << "type " << toString(Sig) << "\n");
Sam Cleggb8621592017-11-30 01:40:08 +0000717 Types.push_back(&Sig);
Sam Cleggc375e4e2018-01-10 19:18:22 +0000718 }
Sam Cleggb8621592017-11-30 01:40:08 +0000719 return Pair.first->second;
720}
721
Sam Cleggc94d3932017-11-17 18:14:09 +0000722void Writer::calculateTypes() {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000723 // The output type section is the union of the following sets:
724 // 1. Any signature used in the TYPE relocation
725 // 2. The signatures of all imported functions
726 // 3. The signatures of all defined functions
727
Sam Cleggc94d3932017-11-17 18:14:09 +0000728 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000729 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
730 for (uint32_t I = 0; I < Types.size(); I++)
731 if (File->TypeIsUsed[I])
732 File->TypeMap[I] = registerType(Types[I]);
Sam Cleggc94d3932017-11-17 18:14:09 +0000733 }
Sam Clegg50686852018-01-12 18:35:13 +0000734
Sam Clegg93102972018-02-23 05:08:53 +0000735 for (const Symbol *Sym : ImportedSymbols)
736 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
737 registerType(*F->getFunctionType());
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000738
Sam Clegg9f934222018-02-21 18:29:23 +0000739 for (const InputFunction *F : InputFunctions)
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000740 registerType(F->Signature);
Sam Cleggc94d3932017-11-17 18:14:09 +0000741}
742
Sam Clegg8d146bb2018-01-09 23:56:44 +0000743void Writer::assignIndexes() {
Sam Clegg93102972018-02-23 05:08:53 +0000744 uint32_t FunctionIndex = NumImportedFunctions + InputFunctions.size();
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000745 auto AddDefinedFunction = [&](InputFunction *Func) {
746 if (!Func->Live)
747 return;
748 InputFunctions.emplace_back(Func);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000749 Func->setFunctionIndex(FunctionIndex++);
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000750 };
751
Nicholas Wilson5639da82018-03-12 15:44:07 +0000752 for (InputFunction *Func : Symtab->SyntheticFunctions)
753 AddDefinedFunction(Func);
754
Sam Clegg87e61922018-01-08 23:39:11 +0000755 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8d146bb2018-01-09 23:56:44 +0000756 DEBUG(dbgs() << "Functions: " << File->getName() << "\n");
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000757 for (InputFunction *Func : File->Functions)
758 AddDefinedFunction(Func);
Sam Clegg8d146bb2018-01-09 23:56:44 +0000759 }
760
Sam Clegg93102972018-02-23 05:08:53 +0000761 uint32_t TableIndex = kInitialTableOffset;
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000762 auto HandleRelocs = [&](InputChunk *Chunk) {
763 if (!Chunk->Live)
764 return;
765 ObjFile *File = Chunk->File;
766 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
Sam Clegg93102972018-02-23 05:08:53 +0000767 for (const WasmRelocation &Reloc : Chunk->getRelocations()) {
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000768 if (Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_I32 ||
769 Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_SLEB) {
770 FunctionSymbol *Sym = File->getFunctionSymbol(Reloc.Index);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000771 if (Sym->hasTableIndex() || !Sym->hasFunctionIndex())
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000772 continue;
773 Sym->setTableIndex(TableIndex++);
774 IndirectFunctions.emplace_back(Sym);
775 } else if (Reloc.Type == R_WEBASSEMBLY_TYPE_INDEX_LEB) {
Sam Clegg93102972018-02-23 05:08:53 +0000776 // Mark target type as live
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000777 File->TypeMap[Reloc.Index] = registerType(Types[Reloc.Index]);
778 File->TypeIsUsed[Reloc.Index] = true;
Sam Clegg93102972018-02-23 05:08:53 +0000779 } else if (Reloc.Type == R_WEBASSEMBLY_GLOBAL_INDEX_LEB) {
780 // Mark target global as live
781 GlobalSymbol *Sym = File->getGlobalSymbol(Reloc.Index);
782 if (auto *G = dyn_cast<DefinedGlobal>(Sym)) {
783 DEBUG(dbgs() << "marking global live: " << Sym->getName() << "\n");
784 G->Global->Live = true;
785 }
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000786 }
787 }
788 };
789
Sam Clegg8d146bb2018-01-09 23:56:44 +0000790 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000791 DEBUG(dbgs() << "Handle relocs: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000792 for (InputChunk *Chunk : File->Functions)
793 HandleRelocs(Chunk);
794 for (InputChunk *Chunk : File->Segments)
795 HandleRelocs(Chunk);
796 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000797
Sam Clegg93102972018-02-23 05:08:53 +0000798 uint32_t GlobalIndex = NumImportedGlobals + InputGlobals.size();
799 auto AddDefinedGlobal = [&](InputGlobal *Global) {
800 if (Global->Live) {
801 DEBUG(dbgs() << "AddDefinedGlobal: " << GlobalIndex << "\n");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000802 Global->setGlobalIndex(GlobalIndex++);
Sam Clegg93102972018-02-23 05:08:53 +0000803 InputGlobals.push_back(Global);
804 }
805 };
806
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000807 for (InputGlobal *Global : Symtab->SyntheticGlobals)
808 AddDefinedGlobal(Global);
Sam Clegg93102972018-02-23 05:08:53 +0000809
810 for (ObjFile *File : Symtab->ObjectFiles) {
811 DEBUG(dbgs() << "Globals: " << File->getName() << "\n");
812 for (InputGlobal *Global : File->Globals)
813 AddDefinedGlobal(Global);
Sam Cleggc94d3932017-11-17 18:14:09 +0000814 }
815}
816
817static StringRef getOutputDataSegmentName(StringRef Name) {
818 if (Config->Relocatable)
819 return Name;
Rui Ueyama4764b572018-02-28 00:57:28 +0000820 if (Name.startswith(".text."))
821 return ".text";
822 if (Name.startswith(".data."))
823 return ".data";
824 if (Name.startswith(".bss."))
825 return ".bss";
Sam Cleggc94d3932017-11-17 18:14:09 +0000826 return Name;
827}
828
829void Writer::createOutputSegments() {
830 for (ObjFile *File : Symtab->ObjectFiles) {
831 for (InputSegment *Segment : File->Segments) {
Sam Clegg447ae402018-02-13 20:29:38 +0000832 if (!Segment->Live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000833 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000834 StringRef Name = getOutputDataSegmentName(Segment->getName());
835 OutputSegment *&S = SegmentMap[Name];
836 if (S == nullptr) {
837 DEBUG(dbgs() << "new segment: " << Name << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000838 S = make<OutputSegment>(Name, Segments.size());
Sam Cleggc94d3932017-11-17 18:14:09 +0000839 Segments.push_back(S);
840 }
841 S->addInputSegment(Segment);
842 DEBUG(dbgs() << "added data: " << Name << ": " << S->Size << "\n");
Sam Cleggc94d3932017-11-17 18:14:09 +0000843 }
844 }
845}
846
Sam Clegg50686852018-01-12 18:35:13 +0000847static const int OPCODE_CALL = 0x10;
848static const int OPCODE_END = 0xb;
849
850// Create synthetic "__wasm_call_ctors" function based on ctor functions
851// in input object.
852void Writer::createCtorFunction() {
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000853 // First write the body's contents to a string.
854 std::string BodyContent;
Sam Clegg50686852018-01-12 18:35:13 +0000855 {
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000856 raw_string_ostream OS(BodyContent);
Sam Clegg50686852018-01-12 18:35:13 +0000857 writeUleb128(OS, 0, "num locals");
Sam Clegg93102972018-02-23 05:08:53 +0000858 for (const WasmInitEntry &F : InitFunctions) {
Sam Clegg50686852018-01-12 18:35:13 +0000859 writeU8(OS, OPCODE_CALL, "CALL");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000860 writeUleb128(OS, F.Sym->getFunctionIndex(), "function index");
Sam Clegg50686852018-01-12 18:35:13 +0000861 }
862 writeU8(OS, OPCODE_END, "END");
863 }
864
865 // Once we know the size of the body we can create the final function body
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000866 std::string FunctionBody;
867 {
868 raw_string_ostream OS(FunctionBody);
869 writeUleb128(OS, BodyContent.size(), "function size");
870 OS << BodyContent;
871 }
Rui Ueyama29abfe42018-02-28 17:43:15 +0000872
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000873 ArrayRef<uint8_t> Body = toArrayRef(Saver.save(FunctionBody));
874 cast<SyntheticFunction>(WasmSym::CallCtors->Function)->setBody(Body);
Sam Clegg50686852018-01-12 18:35:13 +0000875}
876
877// Populate InitFunctions vector with init functions from all input objects.
878// This is then used either when creating the output linking section or to
879// synthesize the "__wasm_call_ctors" function.
880void Writer::calculateInitFunctions() {
881 for (ObjFile *File : Symtab->ObjectFiles) {
882 const WasmLinkingData &L = File->getWasmObj()->linkingData();
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +0000883 for (const WasmInitFunc &F : L.InitFunctions) {
884 FunctionSymbol *Sym = File->getFunctionSymbol(F.Symbol);
885 if (*Sym->getFunctionType() != WasmSignature{{}, WASM_TYPE_NORESULT})
886 error("invalid signature for init func: " + toString(*Sym));
887 InitFunctions.emplace_back(WasmInitEntry{Sym, F.Priority});
888 }
Sam Clegg50686852018-01-12 18:35:13 +0000889 }
Rui Ueyamada69b712018-02-28 00:15:59 +0000890
Sam Clegg50686852018-01-12 18:35:13 +0000891 // Sort in order of priority (lowest first) so that they are called
892 // in the correct order.
Sam Clegg29b8feb2018-02-21 00:34:34 +0000893 std::stable_sort(InitFunctions.begin(), InitFunctions.end(),
Sam Clegg93102972018-02-23 05:08:53 +0000894 [](const WasmInitEntry &L, const WasmInitEntry &R) {
Sam Clegg29b8feb2018-02-21 00:34:34 +0000895 return L.Priority < R.Priority;
896 });
Sam Clegg50686852018-01-12 18:35:13 +0000897}
898
Sam Cleggc94d3932017-11-17 18:14:09 +0000899void Writer::run() {
Sam Clegg99eb42c2018-02-27 23:58:03 +0000900 if (Config->Relocatable)
901 Config->GlobalBase = 0;
902
Sam Cleggc94d3932017-11-17 18:14:09 +0000903 log("-- calculateImports");
904 calculateImports();
Sam Clegg8d146bb2018-01-09 23:56:44 +0000905 log("-- assignIndexes");
906 assignIndexes();
Sam Clegg50686852018-01-12 18:35:13 +0000907 log("-- calculateInitFunctions");
908 calculateInitFunctions();
909 if (!Config->Relocatable)
910 createCtorFunction();
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000911 log("-- calculateTypes");
912 calculateTypes();
Sam Clegg93102972018-02-23 05:08:53 +0000913 log("-- layoutMemory");
914 layoutMemory();
915 log("-- calculateExports");
916 calculateExports();
917 log("-- assignSymtab");
918 assignSymtab();
Sam Cleggc94d3932017-11-17 18:14:09 +0000919
920 if (errorHandler().Verbose) {
Sam Clegg9f934222018-02-21 18:29:23 +0000921 log("Defined Functions: " + Twine(InputFunctions.size()));
Sam Clegg93102972018-02-23 05:08:53 +0000922 log("Defined Globals : " + Twine(InputGlobals.size()));
923 log("Function Imports : " + Twine(NumImportedFunctions));
924 log("Global Imports : " + Twine(NumImportedGlobals));
Sam Cleggc94d3932017-11-17 18:14:09 +0000925 for (ObjFile *File : Symtab->ObjectFiles)
926 File->dumpInfo();
927 }
928
Sam Cleggc94d3932017-11-17 18:14:09 +0000929 createHeader();
930 log("-- createSections");
931 createSections();
932
933 log("-- openFile");
934 openFile();
935 if (errorCount())
936 return;
937
938 writeHeader();
939
940 log("-- writeSections");
941 writeSections();
942 if (errorCount())
943 return;
944
945 if (Error E = Buffer->commit())
946 fatal("failed to write the output file: " + toString(std::move(E)));
947}
948
949// Open a result file.
950void Writer::openFile() {
951 log("writing: " + Config->OutputFile);
Sam Cleggc94d3932017-11-17 18:14:09 +0000952
953 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
954 FileOutputBuffer::create(Config->OutputFile, FileSize,
955 FileOutputBuffer::F_executable);
956
957 if (!BufferOrErr)
958 error("failed to open " + Config->OutputFile + ": " +
959 toString(BufferOrErr.takeError()));
960 else
961 Buffer = std::move(*BufferOrErr);
962}
963
964void Writer::createHeader() {
965 raw_string_ostream OS(Header);
966 writeBytes(OS, WasmMagic, sizeof(WasmMagic), "wasm magic");
967 writeU32(OS, WasmVersion, "wasm version");
968 OS.flush();
969 FileSize += Header.size();
970}
971
972void lld::wasm::writeResult() { Writer().run(); }