blob: 8bf8834726dc3c45c2710a2485effbc9bcd8bf2c [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
146static void debugPrint(const char *fmt, ...) {
147 if (!errorHandler().Verbose)
148 return;
149 fprintf(stderr, "lld: ");
150 va_list ap;
151 va_start(ap, fmt);
152 vfprintf(stderr, fmt, ap);
153 va_end(ap);
154}
155
156void Writer::createImportSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000157 uint32_t NumImports = ImportedSymbols.size();
Sam Cleggc94d3932017-11-17 18:14:09 +0000158 if (Config->ImportMemory)
159 ++NumImports;
160
161 if (NumImports == 0)
162 return;
163
164 SyntheticSection *Section = createSyntheticSection(WASM_SEC_IMPORT);
165 raw_ostream &OS = Section->getStream();
166
167 writeUleb128(OS, NumImports, "import count");
168
Sam Cleggc94d3932017-11-17 18:14:09 +0000169 if (Config->ImportMemory) {
170 WasmImport Import;
171 Import.Module = "env";
172 Import.Field = "memory";
173 Import.Kind = WASM_EXTERNAL_MEMORY;
174 Import.Memory.Flags = 0;
175 Import.Memory.Initial = NumMemoryPages;
176 writeImport(OS, Import);
177 }
178
Sam Clegg93102972018-02-23 05:08:53 +0000179 for (const Symbol *Sym : ImportedSymbols) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000180 WasmImport Import;
181 Import.Module = "env";
182 Import.Field = Sym->getName();
Sam Clegg93102972018-02-23 05:08:53 +0000183 if (auto *FunctionSym = dyn_cast<FunctionSymbol>(Sym)) {
184 Import.Kind = WASM_EXTERNAL_FUNCTION;
185 Import.SigIndex = lookupType(*FunctionSym->getFunctionType());
186 } else {
187 auto *GlobalSym = cast<GlobalSymbol>(Sym);
188 Import.Kind = WASM_EXTERNAL_GLOBAL;
189 Import.Global = *GlobalSym->getGlobalType();
190 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000191 writeImport(OS, Import);
192 }
193}
194
195void Writer::createTypeSection() {
196 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TYPE);
197 raw_ostream &OS = Section->getStream();
198 writeUleb128(OS, Types.size(), "type count");
Sam Cleggd451da12017-12-19 19:56:27 +0000199 for (const WasmSignature *Sig : Types)
Sam Cleggc94d3932017-11-17 18:14:09 +0000200 writeSig(OS, *Sig);
Sam Cleggc94d3932017-11-17 18:14:09 +0000201}
202
203void Writer::createFunctionSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000204 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000205 return;
206
207 SyntheticSection *Section = createSyntheticSection(WASM_SEC_FUNCTION);
208 raw_ostream &OS = Section->getStream();
209
Sam Clegg9f934222018-02-21 18:29:23 +0000210 writeUleb128(OS, InputFunctions.size(), "function count");
211 for (const InputFunction *Func : InputFunctions)
Sam Cleggc375e4e2018-01-10 19:18:22 +0000212 writeUleb128(OS, lookupType(Func->Signature), "sig index");
Sam Cleggc94d3932017-11-17 18:14:09 +0000213}
214
215void Writer::createMemorySection() {
216 if (Config->ImportMemory)
217 return;
218
219 SyntheticSection *Section = createSyntheticSection(WASM_SEC_MEMORY);
220 raw_ostream &OS = Section->getStream();
221
222 writeUleb128(OS, 1, "memory count");
223 writeUleb128(OS, 0, "memory limits flags");
224 writeUleb128(OS, NumMemoryPages, "initial pages");
225}
226
227void Writer::createGlobalSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000228 unsigned NumGlobals = InputGlobals.size() + DefinedFakeGlobals.size();
229 if (NumGlobals == 0)
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000230 return;
231
Sam Cleggc94d3932017-11-17 18:14:09 +0000232 SyntheticSection *Section = createSyntheticSection(WASM_SEC_GLOBAL);
233 raw_ostream &OS = Section->getStream();
234
Sam Clegg93102972018-02-23 05:08:53 +0000235 writeUleb128(OS, NumGlobals, "global count");
236 for (const InputGlobal *G : InputGlobals)
237 writeGlobal(OS, G->Global);
238 for (const DefinedData *Sym : DefinedFakeGlobals) {
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000239 WasmGlobal Global;
Sam Clegg93102972018-02-23 05:08:53 +0000240 Global.Type = {WASM_TYPE_I32, false};
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000241 Global.InitExpr.Opcode = WASM_OPCODE_I32_CONST;
242 Global.InitExpr.Value.Int32 = Sym->getVirtualAddress();
Sam Cleggc94d3932017-11-17 18:14:09 +0000243 writeGlobal(OS, Global);
244 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000245}
246
247void Writer::createTableSection() {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000248 // Always output a table section, even if there are no indirect calls.
249 // There are two reasons for this:
250 // 1. For executables it is useful to have an empty table slot at 0
251 // which can be filled with a null function call handler.
252 // 2. If we don't do this, any program that contains a call_indirect but
253 // no address-taken function will fail at validation time since it is
254 // a validation error to include a call_indirect instruction if there
255 // is not table.
Sam Clegg48bbd632018-01-24 21:37:30 +0000256 uint32_t TableSize = kInitialTableOffset + IndirectFunctions.size();
Sam Cleggfc1a9122017-12-11 22:00:56 +0000257
Sam Cleggc94d3932017-11-17 18:14:09 +0000258 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TABLE);
259 raw_ostream &OS = Section->getStream();
260
261 writeUleb128(OS, 1, "table count");
Sam Clegg8518e7d2018-03-01 18:06:39 +0000262 writeU8(OS, WASM_TYPE_ANYFUNC, "table type");
Sam Cleggc94d3932017-11-17 18:14:09 +0000263 writeUleb128(OS, WASM_LIMITS_FLAG_HAS_MAX, "table flags");
Sam Cleggfc1a9122017-12-11 22:00:56 +0000264 writeUleb128(OS, TableSize, "table initial size");
265 writeUleb128(OS, TableSize, "table max size");
Sam Cleggc94d3932017-11-17 18:14:09 +0000266}
267
268void Writer::createExportSection() {
Sam Cleggc94d3932017-11-17 18:14:09 +0000269 bool ExportMemory = !Config->Relocatable && !Config->ImportMemory;
Sam Cleggc94d3932017-11-17 18:14:09 +0000270
Sam Cleggd3052d52018-01-18 23:40:49 +0000271 uint32_t NumExports = (ExportMemory ? 1 : 0) + ExportedSymbols.size();
Sam Cleggc94d3932017-11-17 18:14:09 +0000272 if (!NumExports)
273 return;
274
275 SyntheticSection *Section = createSyntheticSection(WASM_SEC_EXPORT);
276 raw_ostream &OS = Section->getStream();
277
278 writeUleb128(OS, NumExports, "export count");
279
Rui Ueyama7d696882018-02-28 00:18:34 +0000280 if (ExportMemory)
281 writeExport(OS, {"memory", WASM_EXTERNAL_MEMORY, 0});
Sam Cleggc94d3932017-11-17 18:14:09 +0000282
Sam Clegg93102972018-02-23 05:08:53 +0000283 unsigned FakeGlobalIndex = NumImportedGlobals + InputGlobals.size();
Rui Ueyama7d696882018-02-28 00:18:34 +0000284
Sam Clegg93102972018-02-23 05:08:53 +0000285 for (const Symbol *Sym : ExportedSymbols) {
Rui Ueyama7d696882018-02-28 00:18:34 +0000286 StringRef Name = Sym->getName();
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000287 WasmExport Export;
Rui Ueyama7d696882018-02-28 00:18:34 +0000288 DEBUG(dbgs() << "Export: " << Name << "\n");
289
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000290 if (auto *F = dyn_cast<DefinedFunction>(Sym))
291 Export = {Name, WASM_EXTERNAL_FUNCTION, F->getFunctionIndex()};
292 else if (auto *G = dyn_cast<DefinedGlobal>(Sym))
293 Export = {Name, WASM_EXTERNAL_GLOBAL, G->getGlobalIndex()};
Rui Ueyama7d696882018-02-28 00:18:34 +0000294 else if (isa<DefinedData>(Sym))
295 Export = {Name, WASM_EXTERNAL_GLOBAL, FakeGlobalIndex++};
296 else
Sam Clegg93102972018-02-23 05:08:53 +0000297 llvm_unreachable("unexpected symbol type");
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000298 writeExport(OS, Export);
Sam Cleggc94d3932017-11-17 18:14:09 +0000299 }
300}
301
Sam Cleggc94d3932017-11-17 18:14:09 +0000302void Writer::createElemSection() {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000303 if (IndirectFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000304 return;
305
306 SyntheticSection *Section = createSyntheticSection(WASM_SEC_ELEM);
307 raw_ostream &OS = Section->getStream();
308
309 writeUleb128(OS, 1, "segment count");
310 writeUleb128(OS, 0, "table index");
311 WasmInitExpr InitExpr;
312 InitExpr.Opcode = WASM_OPCODE_I32_CONST;
Sam Clegg48bbd632018-01-24 21:37:30 +0000313 InitExpr.Value.Int32 = kInitialTableOffset;
Sam Cleggc94d3932017-11-17 18:14:09 +0000314 writeInitExpr(OS, InitExpr);
Sam Cleggfc1a9122017-12-11 22:00:56 +0000315 writeUleb128(OS, IndirectFunctions.size(), "elem count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000316
Sam Clegg48bbd632018-01-24 21:37:30 +0000317 uint32_t TableIndex = kInitialTableOffset;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000318 for (const FunctionSymbol *Sym : IndirectFunctions) {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000319 assert(Sym->getTableIndex() == TableIndex);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000320 writeUleb128(OS, Sym->getFunctionIndex(), "function index");
Sam Cleggfc1a9122017-12-11 22:00:56 +0000321 ++TableIndex;
322 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000323}
324
325void Writer::createCodeSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000326 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000327 return;
328
329 log("createCodeSection");
330
Sam Clegg9f934222018-02-21 18:29:23 +0000331 auto Section = make<CodeSection>(InputFunctions);
Sam Cleggc94d3932017-11-17 18:14:09 +0000332 OutputSections.push_back(Section);
333}
334
335void Writer::createDataSection() {
336 if (!Segments.size())
337 return;
338
339 log("createDataSection");
340 auto Section = make<DataSection>(Segments);
341 OutputSections.push_back(Section);
342}
343
Sam Cleggd451da12017-12-19 19:56:27 +0000344// Create relocations sections in the final output.
Sam Cleggc94d3932017-11-17 18:14:09 +0000345// These are only created when relocatable output is requested.
346void Writer::createRelocSections() {
347 log("createRelocSections");
348 // Don't use iterator here since we are adding to OutputSection
349 size_t OrigSize = OutputSections.size();
350 for (size_t i = 0; i < OrigSize; i++) {
Rui Ueyama37254062018-02-28 00:01:31 +0000351 OutputSection *OSec = OutputSections[i];
352 uint32_t Count = OSec->numRelocations();
Sam Cleggc94d3932017-11-17 18:14:09 +0000353 if (!Count)
354 continue;
355
Rui Ueyama37254062018-02-28 00:01:31 +0000356 StringRef Name;
357 if (OSec->Type == WASM_SEC_DATA)
358 Name = "reloc.DATA";
359 else if (OSec->Type == WASM_SEC_CODE)
360 Name = "reloc.CODE";
Sam Cleggc94d3932017-11-17 18:14:09 +0000361 else
Sam Cleggd451da12017-12-19 19:56:27 +0000362 llvm_unreachable("relocations only supported for code and data");
Sam Cleggc94d3932017-11-17 18:14:09 +0000363
Rui Ueyama37254062018-02-28 00:01:31 +0000364 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, Name);
Sam Cleggc94d3932017-11-17 18:14:09 +0000365 raw_ostream &OS = Section->getStream();
Rui Ueyama37254062018-02-28 00:01:31 +0000366 writeUleb128(OS, OSec->Type, "reloc section");
Sam Cleggc94d3932017-11-17 18:14:09 +0000367 writeUleb128(OS, Count, "reloc count");
Rui Ueyama37254062018-02-28 00:01:31 +0000368 OSec->writeRelocations(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000369 }
370}
371
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000372static uint32_t getWasmFlags(const Symbol *Sym) {
373 uint32_t Flags = 0;
374 if (Sym->isLocal())
375 Flags |= WASM_SYMBOL_BINDING_LOCAL;
376 if (Sym->isWeak())
377 Flags |= WASM_SYMBOL_BINDING_WEAK;
378 if (Sym->isHidden())
379 Flags |= WASM_SYMBOL_VISIBILITY_HIDDEN;
380 if (Sym->isUndefined())
381 Flags |= WASM_SYMBOL_UNDEFINED;
382 return Flags;
383}
384
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000385// Some synthetic sections (e.g. "name" and "linking") have subsections.
386// Just like the synthetic sections themselves these need to be created before
387// they can be written out (since they are preceded by their length). This
388// class is used to create subsections and then write them into the stream
389// of the parent section.
390class SubSection {
391public:
392 explicit SubSection(uint32_t Type) : Type(Type) {}
393
394 void writeTo(raw_ostream &To) {
395 OS.flush();
Rui Ueyama67769102018-02-28 03:38:14 +0000396 writeUleb128(To, Type, "subsection type");
397 writeUleb128(To, Body.size(), "subsection size");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000398 To.write(Body.data(), Body.size());
399 }
400
401private:
402 uint32_t Type;
403 std::string Body;
404
405public:
406 raw_string_ostream OS{Body};
407};
408
Sam Clegg49ed9262017-12-01 00:53:21 +0000409// Create the custom "linking" section containing linker metadata.
Sam Cleggc94d3932017-11-17 18:14:09 +0000410// This is only created when relocatable output is requested.
411void Writer::createLinkingSection() {
412 SyntheticSection *Section =
413 createSyntheticSection(WASM_SEC_CUSTOM, "linking");
414 raw_ostream &OS = Section->getStream();
415
Sam Clegg0d0dd392017-12-19 17:09:45 +0000416 if (!Config->Relocatable)
417 return;
418
Sam Clegg93102972018-02-23 05:08:53 +0000419 if (!SymtabEntries.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000420 SubSection Sub(WASM_SYMBOL_TABLE);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000421 writeUleb128(Sub.OS, SymtabEntries.size(), "num symbols");
422
Sam Clegg93102972018-02-23 05:08:53 +0000423 for (const Symbol *Sym : SymtabEntries) {
424 assert(Sym->isDefined() || Sym->isUndefined());
425 WasmSymbolType Kind = Sym->getWasmType();
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000426 uint32_t Flags = getWasmFlags(Sym);
427
Sam Clegg8518e7d2018-03-01 18:06:39 +0000428 writeU8(Sub.OS, Kind, "sym kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000429 writeUleb128(Sub.OS, Flags, "sym flags");
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000430
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000431 if (auto *F = dyn_cast<FunctionSymbol>(Sym)) {
432 writeUleb128(Sub.OS, F->getFunctionIndex(), "index");
Sam Clegg93102972018-02-23 05:08:53 +0000433 if (Sym->isDefined())
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000434 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000435 } else if (auto *G = dyn_cast<GlobalSymbol>(Sym)) {
436 writeUleb128(Sub.OS, G->getGlobalIndex(), "index");
437 if (Sym->isDefined())
438 writeStr(Sub.OS, Sym->getName(), "sym name");
439 } else {
440 assert(isa<DataSymbol>(Sym));
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000441 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegg93102972018-02-23 05:08:53 +0000442 if (auto *DataSym = dyn_cast<DefinedData>(Sym)) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000443 writeUleb128(Sub.OS, DataSym->getOutputSegmentIndex(), "index");
444 writeUleb128(Sub.OS, DataSym->getOutputSegmentOffset(),
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000445 "data offset");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000446 writeUleb128(Sub.OS, DataSym->getSize(), "data size");
Sam Clegg93102972018-02-23 05:08:53 +0000447 }
Sam Clegg93102972018-02-23 05:08:53 +0000448 }
Sam Cleggd3052d52018-01-18 23:40:49 +0000449 }
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000450
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000451 Sub.writeTo(OS);
Sam Cleggd3052d52018-01-18 23:40:49 +0000452 }
453
Sam Clegg0d0dd392017-12-19 17:09:45 +0000454 if (Segments.size()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000455 SubSection Sub(WASM_SEGMENT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000456 writeUleb128(Sub.OS, Segments.size(), "num data segments");
Sam Cleggc94d3932017-11-17 18:14:09 +0000457 for (const OutputSegment *S : Segments) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000458 writeStr(Sub.OS, S->Name, "segment name");
459 writeUleb128(Sub.OS, S->Alignment, "alignment");
460 writeUleb128(Sub.OS, 0, "flags");
Sam Cleggc94d3932017-11-17 18:14:09 +0000461 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000462 Sub.writeTo(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000463 }
Sam Clegg0d0dd392017-12-19 17:09:45 +0000464
Sam Clegg0d0dd392017-12-19 17:09:45 +0000465 if (!InitFunctions.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000466 SubSection Sub(WASM_INIT_FUNCS);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000467 writeUleb128(Sub.OS, InitFunctions.size(), "num init functions");
Sam Clegg93102972018-02-23 05:08:53 +0000468 for (const WasmInitEntry &F : InitFunctions) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000469 writeUleb128(Sub.OS, F.Priority, "priority");
470 writeUleb128(Sub.OS, F.Sym->getOutputSymbolIndex(), "function index");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000471 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000472 Sub.writeTo(OS);
Sam Clegg0d0dd392017-12-19 17:09:45 +0000473 }
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000474
Nicholas Wilsondbd90bf2018-03-07 13:28:16 +0000475 struct ComdatEntry {
476 unsigned Kind;
477 uint32_t Index;
478 };
479 std::map<StringRef, std::vector<ComdatEntry>> Comdats;
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000480
Sam Clegg9f934222018-02-21 18:29:23 +0000481 for (const InputFunction *F : InputFunctions) {
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000482 StringRef Comdat = F->getComdat();
483 if (!Comdat.empty())
484 Comdats[Comdat].emplace_back(
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000485 ComdatEntry{WASM_COMDAT_FUNCTION, F->getFunctionIndex()});
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000486 }
487 for (uint32_t I = 0; I < Segments.size(); ++I) {
Sam Cleggf98bccf2018-01-13 15:57:48 +0000488 const auto &InputSegments = Segments[I]->InputSegments;
489 if (InputSegments.empty())
490 continue;
491 StringRef Comdat = InputSegments[0]->getComdat();
Sam Clegga697df522018-01-13 15:59:53 +0000492#ifndef NDEBUG
Sam Cleggf98bccf2018-01-13 15:57:48 +0000493 for (const InputSegment *IS : InputSegments)
494 assert(IS->getComdat() == Comdat);
Sam Clegga697df522018-01-13 15:59:53 +0000495#endif
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000496 if (!Comdat.empty())
497 Comdats[Comdat].emplace_back(ComdatEntry{WASM_COMDAT_DATA, I});
498 }
499
500 if (!Comdats.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000501 SubSection Sub(WASM_COMDAT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000502 writeUleb128(Sub.OS, Comdats.size(), "num comdats");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000503 for (const auto &C : Comdats) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000504 writeStr(Sub.OS, C.first, "comdat name");
505 writeUleb128(Sub.OS, 0, "comdat flags"); // flags for future use
506 writeUleb128(Sub.OS, C.second.size(), "num entries");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000507 for (const ComdatEntry &Entry : C.second) {
Sam Clegg8518e7d2018-03-01 18:06:39 +0000508 writeU8(Sub.OS, Entry.Kind, "entry kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000509 writeUleb128(Sub.OS, Entry.Index, "entry index");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000510 }
511 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000512 Sub.writeTo(OS);
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000513 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000514}
515
516// Create the custom "name" section containing debug symbol names.
517void Writer::createNameSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000518 unsigned NumNames = NumImportedFunctions;
Sam Clegg9f934222018-02-21 18:29:23 +0000519 for (const InputFunction *F : InputFunctions)
Sam Clegg1963d712018-01-17 20:19:04 +0000520 if (!F->getName().empty())
521 ++NumNames;
Sam Cleggc94d3932017-11-17 18:14:09 +0000522
Sam Clegg1963d712018-01-17 20:19:04 +0000523 if (NumNames == 0)
524 return;
Sam Clegg50686852018-01-12 18:35:13 +0000525
Sam Cleggc94d3932017-11-17 18:14:09 +0000526 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "name");
527
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000528 SubSection Sub(WASM_NAMES_FUNCTION);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000529 writeUleb128(Sub.OS, NumNames, "name count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000530
Sam Clegg93102972018-02-23 05:08:53 +0000531 // Names must appear in function index order. As it happens ImportedSymbols
532 // and InputFunctions are numbered in order with imported functions coming
Sam Clegg1963d712018-01-17 20:19:04 +0000533 // first.
Sam Clegg93102972018-02-23 05:08:53 +0000534 for (const Symbol *S : ImportedSymbols) {
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000535 if (auto *F = dyn_cast<FunctionSymbol>(S)) {
536 writeUleb128(Sub.OS, F->getFunctionIndex(), "func index");
Nicholas Wilson531769b2018-03-13 13:30:04 +0000537 Optional<std::string> Name = demangleItanium(F->getName());
538 writeStr(Sub.OS, Name ? StringRef(*Name) : F->getName(), "symbol name");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000539 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000540 }
Sam Clegg9f934222018-02-21 18:29:23 +0000541 for (const InputFunction *F : InputFunctions) {
Sam Clegg1963d712018-01-17 20:19:04 +0000542 if (!F->getName().empty()) {
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000543 writeUleb128(Sub.OS, F->getFunctionIndex(), "func index");
Nicholas Wilson531769b2018-03-13 13:30:04 +0000544 Optional<std::string> Name = demangleItanium(F->getName());
545 writeStr(Sub.OS, Name ? StringRef(*Name) : F->getName(), "symbol name");
Sam Clegg1963d712018-01-17 20:19:04 +0000546 }
547 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000548
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000549 Sub.writeTo(Section->getStream());
Sam Cleggc94d3932017-11-17 18:14:09 +0000550}
551
552void Writer::writeHeader() {
553 memcpy(Buffer->getBufferStart(), Header.data(), Header.size());
554}
555
556void Writer::writeSections() {
557 uint8_t *Buf = Buffer->getBufferStart();
558 parallelForEach(OutputSections, [Buf](OutputSection *S) { S->writeTo(Buf); });
559}
560
561// Fix the memory layout of the output binary. This assigns memory offsets
Sam Clegg49ed9262017-12-01 00:53:21 +0000562// to each of the input data sections as well as the explicit stack region.
Sam Cleggf0d433d2018-02-02 22:59:56 +0000563// The memory layout is as follows, from low to high.
564// - initialized data (starting at Config->GlobalBase)
565// - BSS data (not currently implemented in llvm)
566// - explicit stack (Config->ZStackSize)
567// - heap start / unallocated
Sam Cleggc94d3932017-11-17 18:14:09 +0000568void Writer::layoutMemory() {
569 uint32_t MemoryPtr = 0;
Sam Clegg99eb42c2018-02-27 23:58:03 +0000570 MemoryPtr = Config->GlobalBase;
571 debugPrint("mem: global base = %d\n", Config->GlobalBase);
Sam Cleggc94d3932017-11-17 18:14:09 +0000572
573 createOutputSegments();
574
Sam Cleggf0d433d2018-02-02 22:59:56 +0000575 // Arbitrarily set __dso_handle handle to point to the start of the data
576 // segments.
577 if (WasmSym::DsoHandle)
578 WasmSym::DsoHandle->setVirtualAddress(MemoryPtr);
579
Sam Cleggc94d3932017-11-17 18:14:09 +0000580 for (OutputSegment *Seg : Segments) {
581 MemoryPtr = alignTo(MemoryPtr, Seg->Alignment);
582 Seg->StartVA = MemoryPtr;
Sam Clegg7ed293e2018-01-12 00:34:04 +0000583 debugPrint("mem: %-15s offset=%-8d size=%-8d align=%d\n",
Sam Cleggc94d3932017-11-17 18:14:09 +0000584 Seg->Name.str().c_str(), MemoryPtr, Seg->Size, Seg->Alignment);
585 MemoryPtr += Seg->Size;
586 }
587
Sam Cleggf0d433d2018-02-02 22:59:56 +0000588 // TODO: Add .bss space here.
Sam Clegg37a4a8a2018-02-07 03:04:53 +0000589 if (WasmSym::DataEnd)
590 WasmSym::DataEnd->setVirtualAddress(MemoryPtr);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000591
Sam Clegg99eb42c2018-02-27 23:58:03 +0000592 debugPrint("mem: static data = %d\n", MemoryPtr - Config->GlobalBase);
Sam Cleggc94d3932017-11-17 18:14:09 +0000593
Sam Cleggf0d433d2018-02-02 22:59:56 +0000594 // Stack comes after static data and bss
Sam Cleggc94d3932017-11-17 18:14:09 +0000595 if (!Config->Relocatable) {
596 MemoryPtr = alignTo(MemoryPtr, kStackAlignment);
597 if (Config->ZStackSize != alignTo(Config->ZStackSize, kStackAlignment))
598 error("stack size must be " + Twine(kStackAlignment) + "-byte aligned");
599 debugPrint("mem: stack size = %d\n", Config->ZStackSize);
600 debugPrint("mem: stack base = %d\n", MemoryPtr);
601 MemoryPtr += Config->ZStackSize;
Sam Clegg93102972018-02-23 05:08:53 +0000602 WasmSym::StackPointer->Global->Global.InitExpr.Value.Int32 = MemoryPtr;
Sam Cleggc94d3932017-11-17 18:14:09 +0000603 debugPrint("mem: stack top = %d\n", MemoryPtr);
Sam Clegg93102972018-02-23 05:08:53 +0000604
Sam Clegg51bcdc22018-01-17 01:34:31 +0000605 // Set `__heap_base` to directly follow the end of the stack. We don't
606 // allocate any heap memory up front, but instead really on the malloc/brk
607 // implementation growing the memory at runtime.
Sam Cleggf0d433d2018-02-02 22:59:56 +0000608 WasmSym::HeapBase->setVirtualAddress(MemoryPtr);
Sam Clegg51bcdc22018-01-17 01:34:31 +0000609 debugPrint("mem: heap base = %d\n", MemoryPtr);
Sam Cleggc94d3932017-11-17 18:14:09 +0000610 }
611
612 uint32_t MemSize = alignTo(MemoryPtr, WasmPageSize);
613 NumMemoryPages = MemSize / WasmPageSize;
614 debugPrint("mem: total pages = %d\n", NumMemoryPages);
615}
616
617SyntheticSection *Writer::createSyntheticSection(uint32_t Type,
Sam Cleggc375e4e2018-01-10 19:18:22 +0000618 StringRef Name) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000619 auto Sec = make<SyntheticSection>(Type, Name);
Sam Cleggab2ac292017-12-20 05:14:48 +0000620 log("createSection: " + toString(*Sec));
Sam Cleggc94d3932017-11-17 18:14:09 +0000621 OutputSections.push_back(Sec);
622 return Sec;
623}
624
625void Writer::createSections() {
626 // Known sections
627 createTypeSection();
628 createImportSection();
629 createFunctionSection();
630 createTableSection();
631 createMemorySection();
632 createGlobalSection();
633 createExportSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000634 createElemSection();
635 createCodeSection();
636 createDataSection();
637
638 // Custom sections
Sam Clegg99eb42c2018-02-27 23:58:03 +0000639 if (Config->Relocatable) {
Sam Clegg99eb42c2018-02-27 23:58:03 +0000640 createLinkingSection();
Nicholas Wilson94d3b162018-03-05 12:33:58 +0000641 createRelocSections();
Sam Clegg99eb42c2018-02-27 23:58:03 +0000642 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000643 if (!Config->StripDebug && !Config->StripAll)
644 createNameSection();
645
646 for (OutputSection *S : OutputSections) {
647 S->setOffset(FileSize);
648 S->finalizeContents();
649 FileSize += S->getSize();
650 }
651}
652
Sam Cleggc94d3932017-11-17 18:14:09 +0000653void Writer::calculateImports() {
Sam Clegg574d7ce2017-12-15 19:23:49 +0000654 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000655 if (!Sym->isUndefined())
656 continue;
657 if (isa<DataSymbol>(Sym))
658 continue;
659 if (Sym->isWeak() && !Config->Relocatable)
Sam Clegg574d7ce2017-12-15 19:23:49 +0000660 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000661
Sam Clegg93102972018-02-23 05:08:53 +0000662 DEBUG(dbgs() << "import: " << Sym->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000663 ImportedSymbols.emplace_back(Sym);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000664 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
665 F->setFunctionIndex(NumImportedFunctions++);
Sam Clegg93102972018-02-23 05:08:53 +0000666 else
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000667 cast<GlobalSymbol>(Sym)->setGlobalIndex(NumImportedGlobals++);
Sam Cleggc94d3932017-11-17 18:14:09 +0000668 }
669}
670
Sam Cleggd3052d52018-01-18 23:40:49 +0000671void Writer::calculateExports() {
Sam Clegg93102972018-02-23 05:08:53 +0000672 if (Config->Relocatable)
673 return;
Sam Cleggf0d433d2018-02-02 22:59:56 +0000674
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000675 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000676 if (!Sym->isDefined())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000677 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000678 if (Sym->isHidden() || Sym->isLocal())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000679 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000680 if (!Sym->isLive())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000681 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000682
683 DEBUG(dbgs() << "exporting sym: " << Sym->getName() << "\n");
684
Nicholas Wilsonf2f6d5e2018-03-02 14:51:36 +0000685 if (auto *D = dyn_cast<DefinedData>(Sym))
Sam Clegg93102972018-02-23 05:08:53 +0000686 DefinedFakeGlobals.emplace_back(D);
Sam Clegg93102972018-02-23 05:08:53 +0000687 ExportedSymbols.emplace_back(Sym);
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000688 }
Sam Clegg93102972018-02-23 05:08:53 +0000689}
690
691void Writer::assignSymtab() {
692 if (!Config->Relocatable)
693 return;
694
695 unsigned SymbolIndex = SymtabEntries.size();
Sam Cleggd3052d52018-01-18 23:40:49 +0000696 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg93102972018-02-23 05:08:53 +0000697 DEBUG(dbgs() << "Symtab entries: " << File->getName() << "\n");
Sam Cleggd3052d52018-01-18 23:40:49 +0000698 for (Symbol *Sym : File->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000699 if (Sym->getFile() != File)
Sam Cleggd3052d52018-01-18 23:40:49 +0000700 continue;
Nicholas Wilson06e0d172018-03-07 11:15:47 +0000701 // (Since this is relocatable output, GC is not performed so symbols must
702 // be live.)
703 assert(Sym->isLive());
Sam Clegg93102972018-02-23 05:08:53 +0000704 Sym->setOutputSymbolIndex(SymbolIndex++);
705 SymtabEntries.emplace_back(Sym);
Sam Cleggd3052d52018-01-18 23:40:49 +0000706 }
707 }
708
Sam Clegg93102972018-02-23 05:08:53 +0000709 // For the moment, relocatable output doesn't contain any synthetic functions,
710 // so no need to look through the Symtab for symbols not referenced by
711 // Symtab->ObjectFiles.
Sam Cleggd3052d52018-01-18 23:40:49 +0000712}
713
Sam Cleggc375e4e2018-01-10 19:18:22 +0000714uint32_t Writer::lookupType(const WasmSignature &Sig) {
Sam Clegg8d027d62018-01-10 20:12:26 +0000715 auto It = TypeIndices.find(Sig);
716 if (It == TypeIndices.end()) {
Sam Cleggc375e4e2018-01-10 19:18:22 +0000717 error("type not found: " + toString(Sig));
Sam Clegg8d027d62018-01-10 20:12:26 +0000718 return 0;
719 }
720 return It->second;
Sam Cleggc375e4e2018-01-10 19:18:22 +0000721}
722
723uint32_t Writer::registerType(const WasmSignature &Sig) {
Sam Cleggb8621592017-11-30 01:40:08 +0000724 auto Pair = TypeIndices.insert(std::make_pair(Sig, Types.size()));
Sam Cleggc375e4e2018-01-10 19:18:22 +0000725 if (Pair.second) {
726 DEBUG(dbgs() << "type " << toString(Sig) << "\n");
Sam Cleggb8621592017-11-30 01:40:08 +0000727 Types.push_back(&Sig);
Sam Cleggc375e4e2018-01-10 19:18:22 +0000728 }
Sam Cleggb8621592017-11-30 01:40:08 +0000729 return Pair.first->second;
730}
731
Sam Cleggc94d3932017-11-17 18:14:09 +0000732void Writer::calculateTypes() {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000733 // The output type section is the union of the following sets:
734 // 1. Any signature used in the TYPE relocation
735 // 2. The signatures of all imported functions
736 // 3. The signatures of all defined functions
737
Sam Cleggc94d3932017-11-17 18:14:09 +0000738 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000739 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
740 for (uint32_t I = 0; I < Types.size(); I++)
741 if (File->TypeIsUsed[I])
742 File->TypeMap[I] = registerType(Types[I]);
Sam Cleggc94d3932017-11-17 18:14:09 +0000743 }
Sam Clegg50686852018-01-12 18:35:13 +0000744
Sam Clegg93102972018-02-23 05:08:53 +0000745 for (const Symbol *Sym : ImportedSymbols)
746 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
747 registerType(*F->getFunctionType());
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000748
Sam Clegg9f934222018-02-21 18:29:23 +0000749 for (const InputFunction *F : InputFunctions)
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000750 registerType(F->Signature);
Sam Cleggc94d3932017-11-17 18:14:09 +0000751}
752
Sam Clegg8d146bb2018-01-09 23:56:44 +0000753void Writer::assignIndexes() {
Sam Clegg93102972018-02-23 05:08:53 +0000754 uint32_t FunctionIndex = NumImportedFunctions + InputFunctions.size();
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000755 auto AddDefinedFunction = [&](InputFunction *Func) {
756 if (!Func->Live)
757 return;
758 InputFunctions.emplace_back(Func);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000759 Func->setFunctionIndex(FunctionIndex++);
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000760 };
761
Nicholas Wilson5639da82018-03-12 15:44:07 +0000762 for (InputFunction *Func : Symtab->SyntheticFunctions)
763 AddDefinedFunction(Func);
764
Sam Clegg87e61922018-01-08 23:39:11 +0000765 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8d146bb2018-01-09 23:56:44 +0000766 DEBUG(dbgs() << "Functions: " << File->getName() << "\n");
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000767 for (InputFunction *Func : File->Functions)
768 AddDefinedFunction(Func);
Sam Clegg8d146bb2018-01-09 23:56:44 +0000769 }
770
Sam Clegg93102972018-02-23 05:08:53 +0000771 uint32_t TableIndex = kInitialTableOffset;
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000772 auto HandleRelocs = [&](InputChunk *Chunk) {
773 if (!Chunk->Live)
774 return;
775 ObjFile *File = Chunk->File;
776 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
Sam Clegg93102972018-02-23 05:08:53 +0000777 for (const WasmRelocation &Reloc : Chunk->getRelocations()) {
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000778 if (Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_I32 ||
779 Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_SLEB) {
780 FunctionSymbol *Sym = File->getFunctionSymbol(Reloc.Index);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000781 if (Sym->hasTableIndex() || !Sym->hasFunctionIndex())
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000782 continue;
783 Sym->setTableIndex(TableIndex++);
784 IndirectFunctions.emplace_back(Sym);
785 } else if (Reloc.Type == R_WEBASSEMBLY_TYPE_INDEX_LEB) {
Sam Clegg93102972018-02-23 05:08:53 +0000786 // Mark target type as live
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000787 File->TypeMap[Reloc.Index] = registerType(Types[Reloc.Index]);
788 File->TypeIsUsed[Reloc.Index] = true;
Sam Clegg93102972018-02-23 05:08:53 +0000789 } else if (Reloc.Type == R_WEBASSEMBLY_GLOBAL_INDEX_LEB) {
790 // Mark target global as live
791 GlobalSymbol *Sym = File->getGlobalSymbol(Reloc.Index);
792 if (auto *G = dyn_cast<DefinedGlobal>(Sym)) {
793 DEBUG(dbgs() << "marking global live: " << Sym->getName() << "\n");
794 G->Global->Live = true;
795 }
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000796 }
797 }
798 };
799
Sam Clegg8d146bb2018-01-09 23:56:44 +0000800 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000801 DEBUG(dbgs() << "Handle relocs: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000802 for (InputChunk *Chunk : File->Functions)
803 HandleRelocs(Chunk);
804 for (InputChunk *Chunk : File->Segments)
805 HandleRelocs(Chunk);
806 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000807
Sam Clegg93102972018-02-23 05:08:53 +0000808 uint32_t GlobalIndex = NumImportedGlobals + InputGlobals.size();
809 auto AddDefinedGlobal = [&](InputGlobal *Global) {
810 if (Global->Live) {
811 DEBUG(dbgs() << "AddDefinedGlobal: " << GlobalIndex << "\n");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000812 Global->setGlobalIndex(GlobalIndex++);
Sam Clegg93102972018-02-23 05:08:53 +0000813 InputGlobals.push_back(Global);
814 }
815 };
816
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000817 for (InputGlobal *Global : Symtab->SyntheticGlobals)
818 AddDefinedGlobal(Global);
Sam Clegg93102972018-02-23 05:08:53 +0000819
820 for (ObjFile *File : Symtab->ObjectFiles) {
821 DEBUG(dbgs() << "Globals: " << File->getName() << "\n");
822 for (InputGlobal *Global : File->Globals)
823 AddDefinedGlobal(Global);
Sam Cleggc94d3932017-11-17 18:14:09 +0000824 }
825}
826
827static StringRef getOutputDataSegmentName(StringRef Name) {
828 if (Config->Relocatable)
829 return Name;
Rui Ueyama4764b572018-02-28 00:57:28 +0000830 if (Name.startswith(".text."))
831 return ".text";
832 if (Name.startswith(".data."))
833 return ".data";
834 if (Name.startswith(".bss."))
835 return ".bss";
Sam Cleggc94d3932017-11-17 18:14:09 +0000836 return Name;
837}
838
839void Writer::createOutputSegments() {
840 for (ObjFile *File : Symtab->ObjectFiles) {
841 for (InputSegment *Segment : File->Segments) {
Sam Clegg447ae402018-02-13 20:29:38 +0000842 if (!Segment->Live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000843 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000844 StringRef Name = getOutputDataSegmentName(Segment->getName());
845 OutputSegment *&S = SegmentMap[Name];
846 if (S == nullptr) {
847 DEBUG(dbgs() << "new segment: " << Name << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000848 S = make<OutputSegment>(Name, Segments.size());
Sam Cleggc94d3932017-11-17 18:14:09 +0000849 Segments.push_back(S);
850 }
851 S->addInputSegment(Segment);
852 DEBUG(dbgs() << "added data: " << Name << ": " << S->Size << "\n");
Sam Cleggc94d3932017-11-17 18:14:09 +0000853 }
854 }
855}
856
Sam Clegg50686852018-01-12 18:35:13 +0000857static const int OPCODE_CALL = 0x10;
858static const int OPCODE_END = 0xb;
859
860// Create synthetic "__wasm_call_ctors" function based on ctor functions
861// in input object.
862void Writer::createCtorFunction() {
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000863 // First write the body's contents to a string.
864 std::string BodyContent;
Sam Clegg50686852018-01-12 18:35:13 +0000865 {
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000866 raw_string_ostream OS(BodyContent);
Sam Clegg50686852018-01-12 18:35:13 +0000867 writeUleb128(OS, 0, "num locals");
Sam Clegg93102972018-02-23 05:08:53 +0000868 for (const WasmInitEntry &F : InitFunctions) {
Sam Clegg50686852018-01-12 18:35:13 +0000869 writeU8(OS, OPCODE_CALL, "CALL");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000870 writeUleb128(OS, F.Sym->getFunctionIndex(), "function index");
Sam Clegg50686852018-01-12 18:35:13 +0000871 }
872 writeU8(OS, OPCODE_END, "END");
873 }
874
875 // Once we know the size of the body we can create the final function body
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000876 std::string FunctionBody;
877 {
878 raw_string_ostream OS(FunctionBody);
879 writeUleb128(OS, BodyContent.size(), "function size");
880 OS << BodyContent;
881 }
Rui Ueyama29abfe42018-02-28 17:43:15 +0000882
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000883 ArrayRef<uint8_t> Body = toArrayRef(Saver.save(FunctionBody));
884 cast<SyntheticFunction>(WasmSym::CallCtors->Function)->setBody(Body);
Sam Clegg50686852018-01-12 18:35:13 +0000885}
886
887// Populate InitFunctions vector with init functions from all input objects.
888// This is then used either when creating the output linking section or to
889// synthesize the "__wasm_call_ctors" function.
890void Writer::calculateInitFunctions() {
891 for (ObjFile *File : Symtab->ObjectFiles) {
892 const WasmLinkingData &L = File->getWasmObj()->linkingData();
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +0000893 for (const WasmInitFunc &F : L.InitFunctions) {
894 FunctionSymbol *Sym = File->getFunctionSymbol(F.Symbol);
895 if (*Sym->getFunctionType() != WasmSignature{{}, WASM_TYPE_NORESULT})
896 error("invalid signature for init func: " + toString(*Sym));
897 InitFunctions.emplace_back(WasmInitEntry{Sym, F.Priority});
898 }
Sam Clegg50686852018-01-12 18:35:13 +0000899 }
Rui Ueyamada69b712018-02-28 00:15:59 +0000900
Sam Clegg50686852018-01-12 18:35:13 +0000901 // Sort in order of priority (lowest first) so that they are called
902 // in the correct order.
Sam Clegg29b8feb2018-02-21 00:34:34 +0000903 std::stable_sort(InitFunctions.begin(), InitFunctions.end(),
Sam Clegg93102972018-02-23 05:08:53 +0000904 [](const WasmInitEntry &L, const WasmInitEntry &R) {
Sam Clegg29b8feb2018-02-21 00:34:34 +0000905 return L.Priority < R.Priority;
906 });
Sam Clegg50686852018-01-12 18:35:13 +0000907}
908
Sam Cleggc94d3932017-11-17 18:14:09 +0000909void Writer::run() {
Sam Clegg99eb42c2018-02-27 23:58:03 +0000910 if (Config->Relocatable)
911 Config->GlobalBase = 0;
912
Sam Cleggc94d3932017-11-17 18:14:09 +0000913 log("-- calculateImports");
914 calculateImports();
Sam Clegg8d146bb2018-01-09 23:56:44 +0000915 log("-- assignIndexes");
916 assignIndexes();
Sam Clegg50686852018-01-12 18:35:13 +0000917 log("-- calculateInitFunctions");
918 calculateInitFunctions();
919 if (!Config->Relocatable)
920 createCtorFunction();
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000921 log("-- calculateTypes");
922 calculateTypes();
Sam Clegg93102972018-02-23 05:08:53 +0000923 log("-- layoutMemory");
924 layoutMemory();
925 log("-- calculateExports");
926 calculateExports();
927 log("-- assignSymtab");
928 assignSymtab();
Sam Cleggc94d3932017-11-17 18:14:09 +0000929
930 if (errorHandler().Verbose) {
Sam Clegg9f934222018-02-21 18:29:23 +0000931 log("Defined Functions: " + Twine(InputFunctions.size()));
Sam Clegg93102972018-02-23 05:08:53 +0000932 log("Defined Globals : " + Twine(InputGlobals.size()));
933 log("Function Imports : " + Twine(NumImportedFunctions));
934 log("Global Imports : " + Twine(NumImportedGlobals));
Sam Cleggc94d3932017-11-17 18:14:09 +0000935 for (ObjFile *File : Symtab->ObjectFiles)
936 File->dumpInfo();
937 }
938
Sam Cleggc94d3932017-11-17 18:14:09 +0000939 createHeader();
940 log("-- createSections");
941 createSections();
942
943 log("-- openFile");
944 openFile();
945 if (errorCount())
946 return;
947
948 writeHeader();
949
950 log("-- writeSections");
951 writeSections();
952 if (errorCount())
953 return;
954
955 if (Error E = Buffer->commit())
956 fatal("failed to write the output file: " + toString(std::move(E)));
957}
958
959// Open a result file.
960void Writer::openFile() {
961 log("writing: " + Config->OutputFile);
Sam Cleggc94d3932017-11-17 18:14:09 +0000962
963 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
964 FileOutputBuffer::create(Config->OutputFile, FileSize,
965 FileOutputBuffer::F_executable);
966
967 if (!BufferOrErr)
968 error("failed to open " + Config->OutputFile + ": " +
969 toString(BufferOrErr.takeError()));
970 else
971 Buffer = std::move(*BufferOrErr);
972}
973
974void Writer::createHeader() {
975 raw_string_ostream OS(Header);
976 writeBytes(OS, WasmMagic, sizeof(WasmMagic), "wasm magic");
977 writeU32(OS, WasmVersion, "wasm version");
978 OS.flush();
979 FileSize += Header.size();
980}
981
982void lld::wasm::writeResult() { Writer().run(); }