blob: dc2210b1146ae05b69b145712e9c5df08de9415a [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 Clegg811236c2018-01-19 03:31:07 +000070 const Symbol *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
290 if (isa<DefinedFunction>(Sym))
291 Export = {Name, WASM_EXTERNAL_FUNCTION, Sym->getOutputIndex()};
292 else if (isa<DefinedGlobal>(Sym))
293 Export = {Name, WASM_EXTERNAL_GLOBAL, Sym->getOutputIndex()};
294 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);
320 writeUleb128(OS, Sym->getOutputIndex(), "function index");
321 ++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 Clegg93102972018-02-23 05:08:53 +0000431 switch (Kind) {
432 case llvm::wasm::WASM_SYMBOL_TYPE_FUNCTION:
433 case llvm::wasm::WASM_SYMBOL_TYPE_GLOBAL:
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000434 writeUleb128(Sub.OS, Sym->getOutputIndex(), "index");
Sam Clegg93102972018-02-23 05:08:53 +0000435 if (Sym->isDefined())
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000436 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegg93102972018-02-23 05:08:53 +0000437 break;
438 case llvm::wasm::WASM_SYMBOL_TYPE_DATA:
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000439 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegg93102972018-02-23 05:08:53 +0000440 if (auto *DataSym = dyn_cast<DefinedData>(Sym)) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000441 writeUleb128(Sub.OS, DataSym->getOutputSegmentIndex(), "index");
442 writeUleb128(Sub.OS, DataSym->getOutputSegmentOffset(),
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000443 "data offset");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000444 writeUleb128(Sub.OS, DataSym->getSize(), "data size");
Sam Clegg93102972018-02-23 05:08:53 +0000445 }
446 break;
447 }
Sam Cleggd3052d52018-01-18 23:40:49 +0000448 }
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000449
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000450 Sub.writeTo(OS);
Sam Cleggd3052d52018-01-18 23:40:49 +0000451 }
452
Sam Clegg0d0dd392017-12-19 17:09:45 +0000453 if (Segments.size()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000454 SubSection Sub(WASM_SEGMENT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000455 writeUleb128(Sub.OS, Segments.size(), "num data segments");
Sam Cleggc94d3932017-11-17 18:14:09 +0000456 for (const OutputSegment *S : Segments) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000457 writeStr(Sub.OS, S->Name, "segment name");
458 writeUleb128(Sub.OS, S->Alignment, "alignment");
459 writeUleb128(Sub.OS, 0, "flags");
Sam Cleggc94d3932017-11-17 18:14:09 +0000460 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000461 Sub.writeTo(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000462 }
Sam Clegg0d0dd392017-12-19 17:09:45 +0000463
Sam Clegg0d0dd392017-12-19 17:09:45 +0000464 if (!InitFunctions.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000465 SubSection Sub(WASM_INIT_FUNCS);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000466 writeUleb128(Sub.OS, InitFunctions.size(), "num init functions");
Sam Clegg93102972018-02-23 05:08:53 +0000467 for (const WasmInitEntry &F : InitFunctions) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000468 writeUleb128(Sub.OS, F.Priority, "priority");
469 writeUleb128(Sub.OS, F.Sym->getOutputSymbolIndex(), "function index");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000470 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000471 Sub.writeTo(OS);
Sam Clegg0d0dd392017-12-19 17:09:45 +0000472 }
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000473
Nicholas Wilsondbd90bf2018-03-07 13:28:16 +0000474 struct ComdatEntry {
475 unsigned Kind;
476 uint32_t Index;
477 };
478 std::map<StringRef, std::vector<ComdatEntry>> Comdats;
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000479
Sam Clegg9f934222018-02-21 18:29:23 +0000480 for (const InputFunction *F : InputFunctions) {
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000481 StringRef Comdat = F->getComdat();
482 if (!Comdat.empty())
483 Comdats[Comdat].emplace_back(
484 ComdatEntry{WASM_COMDAT_FUNCTION, F->getOutputIndex()});
485 }
486 for (uint32_t I = 0; I < Segments.size(); ++I) {
Sam Cleggf98bccf2018-01-13 15:57:48 +0000487 const auto &InputSegments = Segments[I]->InputSegments;
488 if (InputSegments.empty())
489 continue;
490 StringRef Comdat = InputSegments[0]->getComdat();
Sam Clegga697df522018-01-13 15:59:53 +0000491#ifndef NDEBUG
Sam Cleggf98bccf2018-01-13 15:57:48 +0000492 for (const InputSegment *IS : InputSegments)
493 assert(IS->getComdat() == Comdat);
Sam Clegga697df522018-01-13 15:59:53 +0000494#endif
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000495 if (!Comdat.empty())
496 Comdats[Comdat].emplace_back(ComdatEntry{WASM_COMDAT_DATA, I});
497 }
498
499 if (!Comdats.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000500 SubSection Sub(WASM_COMDAT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000501 writeUleb128(Sub.OS, Comdats.size(), "num comdats");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000502 for (const auto &C : Comdats) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000503 writeStr(Sub.OS, C.first, "comdat name");
504 writeUleb128(Sub.OS, 0, "comdat flags"); // flags for future use
505 writeUleb128(Sub.OS, C.second.size(), "num entries");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000506 for (const ComdatEntry &Entry : C.second) {
Sam Clegg8518e7d2018-03-01 18:06:39 +0000507 writeU8(Sub.OS, Entry.Kind, "entry kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000508 writeUleb128(Sub.OS, Entry.Index, "entry index");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000509 }
510 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000511 Sub.writeTo(OS);
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000512 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000513}
514
515// Create the custom "name" section containing debug symbol names.
516void Writer::createNameSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000517 unsigned NumNames = NumImportedFunctions;
Sam Clegg9f934222018-02-21 18:29:23 +0000518 for (const InputFunction *F : InputFunctions)
Sam Clegg1963d712018-01-17 20:19:04 +0000519 if (!F->getName().empty())
520 ++NumNames;
Sam Cleggc94d3932017-11-17 18:14:09 +0000521
Sam Clegg1963d712018-01-17 20:19:04 +0000522 if (NumNames == 0)
523 return;
Sam Clegg50686852018-01-12 18:35:13 +0000524
Sam Cleggc94d3932017-11-17 18:14:09 +0000525 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "name");
526
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000527 SubSection Sub(WASM_NAMES_FUNCTION);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000528 writeUleb128(Sub.OS, NumNames, "name count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000529
Sam Clegg93102972018-02-23 05:08:53 +0000530 // Names must appear in function index order. As it happens ImportedSymbols
531 // and InputFunctions are numbered in order with imported functions coming
Sam Clegg1963d712018-01-17 20:19:04 +0000532 // first.
Sam Clegg93102972018-02-23 05:08:53 +0000533 for (const Symbol *S : ImportedSymbols) {
534 if (!isa<FunctionSymbol>(S))
535 continue;
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000536 writeUleb128(Sub.OS, S->getOutputIndex(), "import index");
537 writeStr(Sub.OS, S->getName(), "symbol name");
Sam Cleggc94d3932017-11-17 18:14:09 +0000538 }
Sam Clegg9f934222018-02-21 18:29:23 +0000539 for (const InputFunction *F : InputFunctions) {
Sam Clegg1963d712018-01-17 20:19:04 +0000540 if (!F->getName().empty()) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000541 writeUleb128(Sub.OS, F->getOutputIndex(), "func index");
542 writeStr(Sub.OS, F->getName(), "symbol name");
Sam Clegg1963d712018-01-17 20:19:04 +0000543 }
544 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000545
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000546 Sub.writeTo(Section->getStream());
Sam Cleggc94d3932017-11-17 18:14:09 +0000547}
548
549void Writer::writeHeader() {
550 memcpy(Buffer->getBufferStart(), Header.data(), Header.size());
551}
552
553void Writer::writeSections() {
554 uint8_t *Buf = Buffer->getBufferStart();
555 parallelForEach(OutputSections, [Buf](OutputSection *S) { S->writeTo(Buf); });
556}
557
558// Fix the memory layout of the output binary. This assigns memory offsets
Sam Clegg49ed9262017-12-01 00:53:21 +0000559// to each of the input data sections as well as the explicit stack region.
Sam Cleggf0d433d2018-02-02 22:59:56 +0000560// The memory layout is as follows, from low to high.
561// - initialized data (starting at Config->GlobalBase)
562// - BSS data (not currently implemented in llvm)
563// - explicit stack (Config->ZStackSize)
564// - heap start / unallocated
Sam Cleggc94d3932017-11-17 18:14:09 +0000565void Writer::layoutMemory() {
566 uint32_t MemoryPtr = 0;
Sam Clegg99eb42c2018-02-27 23:58:03 +0000567 MemoryPtr = Config->GlobalBase;
568 debugPrint("mem: global base = %d\n", Config->GlobalBase);
Sam Cleggc94d3932017-11-17 18:14:09 +0000569
570 createOutputSegments();
571
Sam Cleggf0d433d2018-02-02 22:59:56 +0000572 // Arbitrarily set __dso_handle handle to point to the start of the data
573 // segments.
574 if (WasmSym::DsoHandle)
575 WasmSym::DsoHandle->setVirtualAddress(MemoryPtr);
576
Sam Cleggc94d3932017-11-17 18:14:09 +0000577 for (OutputSegment *Seg : Segments) {
578 MemoryPtr = alignTo(MemoryPtr, Seg->Alignment);
579 Seg->StartVA = MemoryPtr;
Sam Clegg7ed293e2018-01-12 00:34:04 +0000580 debugPrint("mem: %-15s offset=%-8d size=%-8d align=%d\n",
Sam Cleggc94d3932017-11-17 18:14:09 +0000581 Seg->Name.str().c_str(), MemoryPtr, Seg->Size, Seg->Alignment);
582 MemoryPtr += Seg->Size;
583 }
584
Sam Cleggf0d433d2018-02-02 22:59:56 +0000585 // TODO: Add .bss space here.
Sam Clegg37a4a8a2018-02-07 03:04:53 +0000586 if (WasmSym::DataEnd)
587 WasmSym::DataEnd->setVirtualAddress(MemoryPtr);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000588
Sam Clegg99eb42c2018-02-27 23:58:03 +0000589 debugPrint("mem: static data = %d\n", MemoryPtr - Config->GlobalBase);
Sam Cleggc94d3932017-11-17 18:14:09 +0000590
Sam Cleggf0d433d2018-02-02 22:59:56 +0000591 // Stack comes after static data and bss
Sam Cleggc94d3932017-11-17 18:14:09 +0000592 if (!Config->Relocatable) {
593 MemoryPtr = alignTo(MemoryPtr, kStackAlignment);
594 if (Config->ZStackSize != alignTo(Config->ZStackSize, kStackAlignment))
595 error("stack size must be " + Twine(kStackAlignment) + "-byte aligned");
596 debugPrint("mem: stack size = %d\n", Config->ZStackSize);
597 debugPrint("mem: stack base = %d\n", MemoryPtr);
598 MemoryPtr += Config->ZStackSize;
Sam Clegg93102972018-02-23 05:08:53 +0000599 WasmSym::StackPointer->Global->Global.InitExpr.Value.Int32 = MemoryPtr;
Sam Cleggc94d3932017-11-17 18:14:09 +0000600 debugPrint("mem: stack top = %d\n", MemoryPtr);
Sam Clegg93102972018-02-23 05:08:53 +0000601
Sam Clegg51bcdc22018-01-17 01:34:31 +0000602 // Set `__heap_base` to directly follow the end of the stack. We don't
603 // allocate any heap memory up front, but instead really on the malloc/brk
604 // implementation growing the memory at runtime.
Sam Cleggf0d433d2018-02-02 22:59:56 +0000605 WasmSym::HeapBase->setVirtualAddress(MemoryPtr);
Sam Clegg51bcdc22018-01-17 01:34:31 +0000606 debugPrint("mem: heap base = %d\n", MemoryPtr);
Sam Cleggc94d3932017-11-17 18:14:09 +0000607 }
608
609 uint32_t MemSize = alignTo(MemoryPtr, WasmPageSize);
610 NumMemoryPages = MemSize / WasmPageSize;
611 debugPrint("mem: total pages = %d\n", NumMemoryPages);
612}
613
614SyntheticSection *Writer::createSyntheticSection(uint32_t Type,
Sam Cleggc375e4e2018-01-10 19:18:22 +0000615 StringRef Name) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000616 auto Sec = make<SyntheticSection>(Type, Name);
Sam Cleggab2ac292017-12-20 05:14:48 +0000617 log("createSection: " + toString(*Sec));
Sam Cleggc94d3932017-11-17 18:14:09 +0000618 OutputSections.push_back(Sec);
619 return Sec;
620}
621
622void Writer::createSections() {
623 // Known sections
624 createTypeSection();
625 createImportSection();
626 createFunctionSection();
627 createTableSection();
628 createMemorySection();
629 createGlobalSection();
630 createExportSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000631 createElemSection();
632 createCodeSection();
633 createDataSection();
634
635 // Custom sections
Sam Clegg99eb42c2018-02-27 23:58:03 +0000636 if (Config->Relocatable) {
Sam Clegg99eb42c2018-02-27 23:58:03 +0000637 createLinkingSection();
Nicholas Wilson94d3b162018-03-05 12:33:58 +0000638 createRelocSections();
Sam Clegg99eb42c2018-02-27 23:58:03 +0000639 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000640 if (!Config->StripDebug && !Config->StripAll)
641 createNameSection();
642
643 for (OutputSection *S : OutputSections) {
644 S->setOffset(FileSize);
645 S->finalizeContents();
646 FileSize += S->getSize();
647 }
648}
649
Sam Cleggc94d3932017-11-17 18:14:09 +0000650void Writer::calculateImports() {
Sam Clegg574d7ce2017-12-15 19:23:49 +0000651 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000652 if (!Sym->isUndefined())
653 continue;
654 if (isa<DataSymbol>(Sym))
655 continue;
656 if (Sym->isWeak() && !Config->Relocatable)
Sam Clegg574d7ce2017-12-15 19:23:49 +0000657 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000658
Sam Clegg93102972018-02-23 05:08:53 +0000659 DEBUG(dbgs() << "import: " << Sym->getName() << "\n");
660 Sym->setOutputIndex(ImportedSymbols.size());
661 ImportedSymbols.emplace_back(Sym);
662 if (isa<FunctionSymbol>(Sym))
663 ++NumImportedFunctions;
664 else
665 ++NumImportedGlobals;
Sam Cleggc94d3932017-11-17 18:14:09 +0000666 }
667}
668
Sam Cleggd3052d52018-01-18 23:40:49 +0000669void Writer::calculateExports() {
Sam Clegg93102972018-02-23 05:08:53 +0000670 if (Config->Relocatable)
671 return;
Sam Cleggf0d433d2018-02-02 22:59:56 +0000672
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000673 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000674 if (!Sym->isDefined())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000675 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000676 if (Sym->isHidden() || Sym->isLocal())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000677 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000678 if (!Sym->isLive())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000679 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000680
681 DEBUG(dbgs() << "exporting sym: " << Sym->getName() << "\n");
682
Nicholas Wilsonf2f6d5e2018-03-02 14:51:36 +0000683 if (auto *D = dyn_cast<DefinedData>(Sym))
Sam Clegg93102972018-02-23 05:08:53 +0000684 DefinedFakeGlobals.emplace_back(D);
Sam Clegg93102972018-02-23 05:08:53 +0000685 ExportedSymbols.emplace_back(Sym);
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000686 }
Sam Clegg93102972018-02-23 05:08:53 +0000687}
688
689void Writer::assignSymtab() {
690 if (!Config->Relocatable)
691 return;
692
693 unsigned SymbolIndex = SymtabEntries.size();
Sam Cleggd3052d52018-01-18 23:40:49 +0000694 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg93102972018-02-23 05:08:53 +0000695 DEBUG(dbgs() << "Symtab entries: " << File->getName() << "\n");
Sam Cleggd3052d52018-01-18 23:40:49 +0000696 for (Symbol *Sym : File->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000697 if (Sym->getFile() != File)
Sam Cleggd3052d52018-01-18 23:40:49 +0000698 continue;
Nicholas Wilson06e0d172018-03-07 11:15:47 +0000699 // (Since this is relocatable output, GC is not performed so symbols must
700 // be live.)
701 assert(Sym->isLive());
Sam Clegg93102972018-02-23 05:08:53 +0000702 Sym->setOutputSymbolIndex(SymbolIndex++);
703 SymtabEntries.emplace_back(Sym);
Sam Cleggd3052d52018-01-18 23:40:49 +0000704 }
705 }
706
Sam Clegg93102972018-02-23 05:08:53 +0000707 // For the moment, relocatable output doesn't contain any synthetic functions,
708 // so no need to look through the Symtab for symbols not referenced by
709 // Symtab->ObjectFiles.
Sam Cleggd3052d52018-01-18 23:40:49 +0000710}
711
Sam Cleggc375e4e2018-01-10 19:18:22 +0000712uint32_t Writer::lookupType(const WasmSignature &Sig) {
Sam Clegg8d027d62018-01-10 20:12:26 +0000713 auto It = TypeIndices.find(Sig);
714 if (It == TypeIndices.end()) {
Sam Cleggc375e4e2018-01-10 19:18:22 +0000715 error("type not found: " + toString(Sig));
Sam Clegg8d027d62018-01-10 20:12:26 +0000716 return 0;
717 }
718 return It->second;
Sam Cleggc375e4e2018-01-10 19:18:22 +0000719}
720
721uint32_t Writer::registerType(const WasmSignature &Sig) {
Sam Cleggb8621592017-11-30 01:40:08 +0000722 auto Pair = TypeIndices.insert(std::make_pair(Sig, Types.size()));
Sam Cleggc375e4e2018-01-10 19:18:22 +0000723 if (Pair.second) {
724 DEBUG(dbgs() << "type " << toString(Sig) << "\n");
Sam Cleggb8621592017-11-30 01:40:08 +0000725 Types.push_back(&Sig);
Sam Cleggc375e4e2018-01-10 19:18:22 +0000726 }
Sam Cleggb8621592017-11-30 01:40:08 +0000727 return Pair.first->second;
728}
729
Sam Cleggc94d3932017-11-17 18:14:09 +0000730void Writer::calculateTypes() {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000731 // The output type section is the union of the following sets:
732 // 1. Any signature used in the TYPE relocation
733 // 2. The signatures of all imported functions
734 // 3. The signatures of all defined functions
735
Sam Cleggc94d3932017-11-17 18:14:09 +0000736 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000737 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
738 for (uint32_t I = 0; I < Types.size(); I++)
739 if (File->TypeIsUsed[I])
740 File->TypeMap[I] = registerType(Types[I]);
Sam Cleggc94d3932017-11-17 18:14:09 +0000741 }
Sam Clegg50686852018-01-12 18:35:13 +0000742
Sam Clegg93102972018-02-23 05:08:53 +0000743 for (const Symbol *Sym : ImportedSymbols)
744 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
745 registerType(*F->getFunctionType());
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000746
Sam Clegg9f934222018-02-21 18:29:23 +0000747 for (const InputFunction *F : InputFunctions)
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000748 registerType(F->Signature);
Sam Cleggc94d3932017-11-17 18:14:09 +0000749}
750
Sam Clegg8d146bb2018-01-09 23:56:44 +0000751void Writer::assignIndexes() {
Sam Clegg93102972018-02-23 05:08:53 +0000752 uint32_t FunctionIndex = NumImportedFunctions + InputFunctions.size();
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000753 auto AddDefinedFunction = [&](InputFunction *Func) {
754 if (!Func->Live)
755 return;
756 InputFunctions.emplace_back(Func);
757 Func->setOutputIndex(FunctionIndex++);
758 };
759
Nicholas Wilson5639da82018-03-12 15:44:07 +0000760 for (InputFunction *Func : Symtab->SyntheticFunctions)
761 AddDefinedFunction(Func);
762
Sam Clegg87e61922018-01-08 23:39:11 +0000763 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8d146bb2018-01-09 23:56:44 +0000764 DEBUG(dbgs() << "Functions: " << File->getName() << "\n");
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000765 for (InputFunction *Func : File->Functions)
766 AddDefinedFunction(Func);
Sam Clegg8d146bb2018-01-09 23:56:44 +0000767 }
768
Sam Clegg93102972018-02-23 05:08:53 +0000769 uint32_t TableIndex = kInitialTableOffset;
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000770 auto HandleRelocs = [&](InputChunk *Chunk) {
771 if (!Chunk->Live)
772 return;
773 ObjFile *File = Chunk->File;
774 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
Sam Clegg93102972018-02-23 05:08:53 +0000775 for (const WasmRelocation &Reloc : Chunk->getRelocations()) {
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000776 if (Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_I32 ||
777 Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_SLEB) {
778 FunctionSymbol *Sym = File->getFunctionSymbol(Reloc.Index);
779 if (Sym->hasTableIndex() || !Sym->hasOutputIndex())
780 continue;
781 Sym->setTableIndex(TableIndex++);
782 IndirectFunctions.emplace_back(Sym);
783 } else if (Reloc.Type == R_WEBASSEMBLY_TYPE_INDEX_LEB) {
Sam Clegg93102972018-02-23 05:08:53 +0000784 // Mark target type as live
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000785 File->TypeMap[Reloc.Index] = registerType(Types[Reloc.Index]);
786 File->TypeIsUsed[Reloc.Index] = true;
Sam Clegg93102972018-02-23 05:08:53 +0000787 } else if (Reloc.Type == R_WEBASSEMBLY_GLOBAL_INDEX_LEB) {
788 // Mark target global as live
789 GlobalSymbol *Sym = File->getGlobalSymbol(Reloc.Index);
790 if (auto *G = dyn_cast<DefinedGlobal>(Sym)) {
791 DEBUG(dbgs() << "marking global live: " << Sym->getName() << "\n");
792 G->Global->Live = true;
793 }
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000794 }
795 }
796 };
797
Sam Clegg8d146bb2018-01-09 23:56:44 +0000798 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000799 DEBUG(dbgs() << "Handle relocs: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000800 for (InputChunk *Chunk : File->Functions)
801 HandleRelocs(Chunk);
802 for (InputChunk *Chunk : File->Segments)
803 HandleRelocs(Chunk);
804 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000805
Sam Clegg93102972018-02-23 05:08:53 +0000806 uint32_t GlobalIndex = NumImportedGlobals + InputGlobals.size();
807 auto AddDefinedGlobal = [&](InputGlobal *Global) {
808 if (Global->Live) {
809 DEBUG(dbgs() << "AddDefinedGlobal: " << GlobalIndex << "\n");
810 Global->setOutputIndex(GlobalIndex++);
811 InputGlobals.push_back(Global);
812 }
813 };
814
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000815 for (InputGlobal *Global : Symtab->SyntheticGlobals)
816 AddDefinedGlobal(Global);
Sam Clegg93102972018-02-23 05:08:53 +0000817
818 for (ObjFile *File : Symtab->ObjectFiles) {
819 DEBUG(dbgs() << "Globals: " << File->getName() << "\n");
820 for (InputGlobal *Global : File->Globals)
821 AddDefinedGlobal(Global);
Sam Cleggc94d3932017-11-17 18:14:09 +0000822 }
823}
824
825static StringRef getOutputDataSegmentName(StringRef Name) {
826 if (Config->Relocatable)
827 return Name;
Rui Ueyama4764b572018-02-28 00:57:28 +0000828 if (Name.startswith(".text."))
829 return ".text";
830 if (Name.startswith(".data."))
831 return ".data";
832 if (Name.startswith(".bss."))
833 return ".bss";
Sam Cleggc94d3932017-11-17 18:14:09 +0000834 return Name;
835}
836
837void Writer::createOutputSegments() {
838 for (ObjFile *File : Symtab->ObjectFiles) {
839 for (InputSegment *Segment : File->Segments) {
Sam Clegg447ae402018-02-13 20:29:38 +0000840 if (!Segment->Live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000841 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000842 StringRef Name = getOutputDataSegmentName(Segment->getName());
843 OutputSegment *&S = SegmentMap[Name];
844 if (S == nullptr) {
845 DEBUG(dbgs() << "new segment: " << Name << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000846 S = make<OutputSegment>(Name, Segments.size());
Sam Cleggc94d3932017-11-17 18:14:09 +0000847 Segments.push_back(S);
848 }
849 S->addInputSegment(Segment);
850 DEBUG(dbgs() << "added data: " << Name << ": " << S->Size << "\n");
Sam Cleggc94d3932017-11-17 18:14:09 +0000851 }
852 }
853}
854
Sam Clegg50686852018-01-12 18:35:13 +0000855static const int OPCODE_CALL = 0x10;
856static const int OPCODE_END = 0xb;
857
858// Create synthetic "__wasm_call_ctors" function based on ctor functions
859// in input object.
860void Writer::createCtorFunction() {
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000861 // First write the body's contents to a string.
862 std::string BodyContent;
Sam Clegg50686852018-01-12 18:35:13 +0000863 {
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000864 raw_string_ostream OS(BodyContent);
Sam Clegg50686852018-01-12 18:35:13 +0000865 writeUleb128(OS, 0, "num locals");
Sam Clegg93102972018-02-23 05:08:53 +0000866 for (const WasmInitEntry &F : InitFunctions) {
Sam Clegg50686852018-01-12 18:35:13 +0000867 writeU8(OS, OPCODE_CALL, "CALL");
Sam Clegg93102972018-02-23 05:08:53 +0000868 writeUleb128(OS, F.Sym->getOutputIndex(), "function index");
Sam Clegg50686852018-01-12 18:35:13 +0000869 }
870 writeU8(OS, OPCODE_END, "END");
871 }
872
873 // Once we know the size of the body we can create the final function body
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000874 std::string FunctionBody;
875 {
876 raw_string_ostream OS(FunctionBody);
877 writeUleb128(OS, BodyContent.size(), "function size");
878 OS << BodyContent;
879 }
Rui Ueyama29abfe42018-02-28 17:43:15 +0000880
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000881 ArrayRef<uint8_t> Body = toArrayRef(Saver.save(FunctionBody));
882 cast<SyntheticFunction>(WasmSym::CallCtors->Function)->setBody(Body);
Sam Clegg50686852018-01-12 18:35:13 +0000883}
884
885// Populate InitFunctions vector with init functions from all input objects.
886// This is then used either when creating the output linking section or to
887// synthesize the "__wasm_call_ctors" function.
888void Writer::calculateInitFunctions() {
889 for (ObjFile *File : Symtab->ObjectFiles) {
890 const WasmLinkingData &L = File->getWasmObj()->linkingData();
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +0000891 for (const WasmInitFunc &F : L.InitFunctions) {
892 FunctionSymbol *Sym = File->getFunctionSymbol(F.Symbol);
893 if (*Sym->getFunctionType() != WasmSignature{{}, WASM_TYPE_NORESULT})
894 error("invalid signature for init func: " + toString(*Sym));
895 InitFunctions.emplace_back(WasmInitEntry{Sym, F.Priority});
896 }
Sam Clegg50686852018-01-12 18:35:13 +0000897 }
Rui Ueyamada69b712018-02-28 00:15:59 +0000898
Sam Clegg50686852018-01-12 18:35:13 +0000899 // Sort in order of priority (lowest first) so that they are called
900 // in the correct order.
Sam Clegg29b8feb2018-02-21 00:34:34 +0000901 std::stable_sort(InitFunctions.begin(), InitFunctions.end(),
Sam Clegg93102972018-02-23 05:08:53 +0000902 [](const WasmInitEntry &L, const WasmInitEntry &R) {
Sam Clegg29b8feb2018-02-21 00:34:34 +0000903 return L.Priority < R.Priority;
904 });
Sam Clegg50686852018-01-12 18:35:13 +0000905}
906
Sam Cleggc94d3932017-11-17 18:14:09 +0000907void Writer::run() {
Sam Clegg99eb42c2018-02-27 23:58:03 +0000908 if (Config->Relocatable)
909 Config->GlobalBase = 0;
910
Sam Cleggc94d3932017-11-17 18:14:09 +0000911 log("-- calculateImports");
912 calculateImports();
Sam Clegg8d146bb2018-01-09 23:56:44 +0000913 log("-- assignIndexes");
914 assignIndexes();
Sam Clegg50686852018-01-12 18:35:13 +0000915 log("-- calculateInitFunctions");
916 calculateInitFunctions();
917 if (!Config->Relocatable)
918 createCtorFunction();
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000919 log("-- calculateTypes");
920 calculateTypes();
Sam Clegg93102972018-02-23 05:08:53 +0000921 log("-- layoutMemory");
922 layoutMemory();
923 log("-- calculateExports");
924 calculateExports();
925 log("-- assignSymtab");
926 assignSymtab();
Sam Cleggc94d3932017-11-17 18:14:09 +0000927
928 if (errorHandler().Verbose) {
Sam Clegg9f934222018-02-21 18:29:23 +0000929 log("Defined Functions: " + Twine(InputFunctions.size()));
Sam Clegg93102972018-02-23 05:08:53 +0000930 log("Defined Globals : " + Twine(InputGlobals.size()));
931 log("Function Imports : " + Twine(NumImportedFunctions));
932 log("Global Imports : " + Twine(NumImportedGlobals));
Sam Cleggc94d3932017-11-17 18:14:09 +0000933 for (ObjFile *File : Symtab->ObjectFiles)
934 File->dumpInfo();
935 }
936
Sam Cleggc94d3932017-11-17 18:14:09 +0000937 createHeader();
938 log("-- createSections");
939 createSections();
940
941 log("-- openFile");
942 openFile();
943 if (errorCount())
944 return;
945
946 writeHeader();
947
948 log("-- writeSections");
949 writeSections();
950 if (errorCount())
951 return;
952
953 if (Error E = Buffer->commit())
954 fatal("failed to write the output file: " + toString(std::move(E)));
955}
956
957// Open a result file.
958void Writer::openFile() {
959 log("writing: " + Config->OutputFile);
Sam Cleggc94d3932017-11-17 18:14:09 +0000960
961 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
962 FileOutputBuffer::create(Config->OutputFile, FileSize,
963 FileOutputBuffer::F_executable);
964
965 if (!BufferOrErr)
966 error("failed to open " + Config->OutputFile + ": " +
967 toString(BufferOrErr.takeError()));
968 else
969 Buffer = std::move(*BufferOrErr);
970}
971
972void Writer::createHeader() {
973 raw_string_ostream OS(Header);
974 writeBytes(OS, WasmMagic, sizeof(WasmMagic), "wasm magic");
975 writeU32(OS, WasmVersion, "wasm version");
976 OS.flush();
977 FileSize += Header.size();
978}
979
980void lld::wasm::writeResult() { Writer().run(); }