blob: dad2c5fa2df402ec10a817a2e20b33d4ef845aee [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"
Rui Ueyama29abfe42018-02-28 17:43:15 +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();
96 SyntheticSection *createSyntheticSection(uint32_t Type,
Sam Cleggc375e4e2018-01-10 19:18:22 +000097 StringRef Name = "");
Sam Cleggc94d3932017-11-17 18:14:09 +000098
99 // Builtin sections
100 void createTypeSection();
101 void createFunctionSection();
102 void createTableSection();
103 void createGlobalSection();
104 void createExportSection();
105 void createImportSection();
106 void createMemorySection();
107 void createElemSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000108 void createCodeSection();
109 void createDataSection();
110
111 // Custom sections
112 void createRelocSections();
113 void createLinkingSection();
114 void createNameSection();
115
116 void writeHeader();
117 void writeSections();
118
119 uint64_t FileSize = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000120 uint32_t NumMemoryPages = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000121
122 std::vector<const WasmSignature *> Types;
123 DenseMap<WasmSignature, int32_t, WasmSignatureDenseMapInfo> TypeIndices;
Sam Clegg93102972018-02-23 05:08:53 +0000124 std::vector<const Symbol *> ImportedSymbols;
125 unsigned NumImportedFunctions = 0;
126 unsigned NumImportedGlobals = 0;
127 std::vector<Symbol *> ExportedSymbols;
128 std::vector<const DefinedData *> DefinedFakeGlobals;
129 std::vector<InputGlobal *> InputGlobals;
Sam Clegg9f934222018-02-21 18:29:23 +0000130 std::vector<InputFunction *> InputFunctions;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000131 std::vector<const FunctionSymbol *> IndirectFunctions;
Sam Clegg93102972018-02-23 05:08:53 +0000132 std::vector<const Symbol *> SymtabEntries;
133 std::vector<WasmInitEntry> InitFunctions;
Sam Cleggc94d3932017-11-17 18:14:09 +0000134
135 // Elements that are used to construct the final output
136 std::string Header;
137 std::vector<OutputSection *> OutputSections;
138
139 std::unique_ptr<FileOutputBuffer> Buffer;
Sam Clegg50686852018-01-12 18:35:13 +0000140 std::string CtorFunctionBody;
Sam Cleggc94d3932017-11-17 18:14:09 +0000141
142 std::vector<OutputSegment *> Segments;
143 llvm::SmallDenseMap<StringRef, OutputSegment *> SegmentMap;
144};
145
146} // anonymous namespace
147
148static void debugPrint(const char *fmt, ...) {
149 if (!errorHandler().Verbose)
150 return;
151 fprintf(stderr, "lld: ");
152 va_list ap;
153 va_start(ap, fmt);
154 vfprintf(stderr, fmt, ap);
155 va_end(ap);
156}
157
158void Writer::createImportSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000159 uint32_t NumImports = ImportedSymbols.size();
Sam Cleggc94d3932017-11-17 18:14:09 +0000160 if (Config->ImportMemory)
161 ++NumImports;
162
163 if (NumImports == 0)
164 return;
165
166 SyntheticSection *Section = createSyntheticSection(WASM_SEC_IMPORT);
167 raw_ostream &OS = Section->getStream();
168
169 writeUleb128(OS, NumImports, "import count");
170
Sam Cleggc94d3932017-11-17 18:14:09 +0000171 if (Config->ImportMemory) {
172 WasmImport Import;
173 Import.Module = "env";
174 Import.Field = "memory";
175 Import.Kind = WASM_EXTERNAL_MEMORY;
176 Import.Memory.Flags = 0;
177 Import.Memory.Initial = NumMemoryPages;
178 writeImport(OS, Import);
179 }
180
Sam Clegg93102972018-02-23 05:08:53 +0000181 for (const Symbol *Sym : ImportedSymbols) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000182 WasmImport Import;
183 Import.Module = "env";
184 Import.Field = Sym->getName();
Sam Clegg93102972018-02-23 05:08:53 +0000185 if (auto *FunctionSym = dyn_cast<FunctionSymbol>(Sym)) {
186 Import.Kind = WASM_EXTERNAL_FUNCTION;
187 Import.SigIndex = lookupType(*FunctionSym->getFunctionType());
188 } else {
189 auto *GlobalSym = cast<GlobalSymbol>(Sym);
190 Import.Kind = WASM_EXTERNAL_GLOBAL;
191 Import.Global = *GlobalSym->getGlobalType();
192 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000193 writeImport(OS, Import);
194 }
195}
196
197void Writer::createTypeSection() {
198 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TYPE);
199 raw_ostream &OS = Section->getStream();
200 writeUleb128(OS, Types.size(), "type count");
Sam Cleggd451da12017-12-19 19:56:27 +0000201 for (const WasmSignature *Sig : Types)
Sam Cleggc94d3932017-11-17 18:14:09 +0000202 writeSig(OS, *Sig);
Sam Cleggc94d3932017-11-17 18:14:09 +0000203}
204
205void Writer::createFunctionSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000206 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000207 return;
208
209 SyntheticSection *Section = createSyntheticSection(WASM_SEC_FUNCTION);
210 raw_ostream &OS = Section->getStream();
211
Sam Clegg9f934222018-02-21 18:29:23 +0000212 writeUleb128(OS, InputFunctions.size(), "function count");
213 for (const InputFunction *Func : InputFunctions)
Sam Cleggc375e4e2018-01-10 19:18:22 +0000214 writeUleb128(OS, lookupType(Func->Signature), "sig index");
Sam Cleggc94d3932017-11-17 18:14:09 +0000215}
216
217void Writer::createMemorySection() {
218 if (Config->ImportMemory)
219 return;
220
221 SyntheticSection *Section = createSyntheticSection(WASM_SEC_MEMORY);
222 raw_ostream &OS = Section->getStream();
223
224 writeUleb128(OS, 1, "memory count");
225 writeUleb128(OS, 0, "memory limits flags");
226 writeUleb128(OS, NumMemoryPages, "initial pages");
227}
228
229void Writer::createGlobalSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000230 unsigned NumGlobals = InputGlobals.size() + DefinedFakeGlobals.size();
231 if (NumGlobals == 0)
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000232 return;
233
Sam Cleggc94d3932017-11-17 18:14:09 +0000234 SyntheticSection *Section = createSyntheticSection(WASM_SEC_GLOBAL);
235 raw_ostream &OS = Section->getStream();
236
Sam Clegg93102972018-02-23 05:08:53 +0000237 writeUleb128(OS, NumGlobals, "global count");
238 for (const InputGlobal *G : InputGlobals)
239 writeGlobal(OS, G->Global);
240 for (const DefinedData *Sym : DefinedFakeGlobals) {
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000241 WasmGlobal Global;
Sam Clegg93102972018-02-23 05:08:53 +0000242 Global.Type = {WASM_TYPE_I32, false};
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000243 Global.InitExpr.Opcode = WASM_OPCODE_I32_CONST;
244 Global.InitExpr.Value.Int32 = Sym->getVirtualAddress();
Sam Cleggc94d3932017-11-17 18:14:09 +0000245 writeGlobal(OS, Global);
246 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000247}
248
249void Writer::createTableSection() {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000250 // Always output a table section, even if there are no indirect calls.
251 // There are two reasons for this:
252 // 1. For executables it is useful to have an empty table slot at 0
253 // which can be filled with a null function call handler.
254 // 2. If we don't do this, any program that contains a call_indirect but
255 // no address-taken function will fail at validation time since it is
256 // a validation error to include a call_indirect instruction if there
257 // is not table.
Sam Clegg48bbd632018-01-24 21:37:30 +0000258 uint32_t TableSize = kInitialTableOffset + IndirectFunctions.size();
Sam Cleggfc1a9122017-12-11 22:00:56 +0000259
Sam Cleggc94d3932017-11-17 18:14:09 +0000260 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TABLE);
261 raw_ostream &OS = Section->getStream();
262
263 writeUleb128(OS, 1, "table count");
Sam Clegg8518e7d2018-03-01 18:06:39 +0000264 writeU8(OS, WASM_TYPE_ANYFUNC, "table type");
Sam Cleggc94d3932017-11-17 18:14:09 +0000265 writeUleb128(OS, WASM_LIMITS_FLAG_HAS_MAX, "table flags");
Sam Cleggfc1a9122017-12-11 22:00:56 +0000266 writeUleb128(OS, TableSize, "table initial size");
267 writeUleb128(OS, TableSize, "table max size");
Sam Cleggc94d3932017-11-17 18:14:09 +0000268}
269
270void Writer::createExportSection() {
Sam Cleggc94d3932017-11-17 18:14:09 +0000271 bool ExportMemory = !Config->Relocatable && !Config->ImportMemory;
Sam Cleggc94d3932017-11-17 18:14:09 +0000272
Sam Cleggd3052d52018-01-18 23:40:49 +0000273 uint32_t NumExports = (ExportMemory ? 1 : 0) + ExportedSymbols.size();
Sam Cleggc94d3932017-11-17 18:14:09 +0000274 if (!NumExports)
275 return;
276
277 SyntheticSection *Section = createSyntheticSection(WASM_SEC_EXPORT);
278 raw_ostream &OS = Section->getStream();
279
280 writeUleb128(OS, NumExports, "export count");
281
Rui Ueyama7d696882018-02-28 00:18:34 +0000282 if (ExportMemory)
283 writeExport(OS, {"memory", WASM_EXTERNAL_MEMORY, 0});
Sam Cleggc94d3932017-11-17 18:14:09 +0000284
Sam Clegg93102972018-02-23 05:08:53 +0000285 unsigned FakeGlobalIndex = NumImportedGlobals + InputGlobals.size();
Rui Ueyama7d696882018-02-28 00:18:34 +0000286
Sam Clegg93102972018-02-23 05:08:53 +0000287 for (const Symbol *Sym : ExportedSymbols) {
Rui Ueyama7d696882018-02-28 00:18:34 +0000288 StringRef Name = Sym->getName();
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000289 WasmExport Export;
Rui Ueyama7d696882018-02-28 00:18:34 +0000290 DEBUG(dbgs() << "Export: " << Name << "\n");
291
292 if (isa<DefinedFunction>(Sym))
293 Export = {Name, WASM_EXTERNAL_FUNCTION, Sym->getOutputIndex()};
294 else if (isa<DefinedGlobal>(Sym))
295 Export = {Name, WASM_EXTERNAL_GLOBAL, Sym->getOutputIndex()};
296 else if (isa<DefinedData>(Sym))
297 Export = {Name, WASM_EXTERNAL_GLOBAL, FakeGlobalIndex++};
298 else
Sam Clegg93102972018-02-23 05:08:53 +0000299 llvm_unreachable("unexpected symbol type");
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000300 writeExport(OS, Export);
Sam Cleggc94d3932017-11-17 18:14:09 +0000301 }
302}
303
Sam Cleggc94d3932017-11-17 18:14:09 +0000304void Writer::createElemSection() {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000305 if (IndirectFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000306 return;
307
308 SyntheticSection *Section = createSyntheticSection(WASM_SEC_ELEM);
309 raw_ostream &OS = Section->getStream();
310
311 writeUleb128(OS, 1, "segment count");
312 writeUleb128(OS, 0, "table index");
313 WasmInitExpr InitExpr;
314 InitExpr.Opcode = WASM_OPCODE_I32_CONST;
Sam Clegg48bbd632018-01-24 21:37:30 +0000315 InitExpr.Value.Int32 = kInitialTableOffset;
Sam Cleggc94d3932017-11-17 18:14:09 +0000316 writeInitExpr(OS, InitExpr);
Sam Cleggfc1a9122017-12-11 22:00:56 +0000317 writeUleb128(OS, IndirectFunctions.size(), "elem count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000318
Sam Clegg48bbd632018-01-24 21:37:30 +0000319 uint32_t TableIndex = kInitialTableOffset;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000320 for (const FunctionSymbol *Sym : IndirectFunctions) {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000321 assert(Sym->getTableIndex() == TableIndex);
322 writeUleb128(OS, Sym->getOutputIndex(), "function index");
323 ++TableIndex;
324 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000325}
326
327void Writer::createCodeSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000328 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000329 return;
330
331 log("createCodeSection");
332
Sam Clegg9f934222018-02-21 18:29:23 +0000333 auto Section = make<CodeSection>(InputFunctions);
Sam Cleggc94d3932017-11-17 18:14:09 +0000334 OutputSections.push_back(Section);
335}
336
337void Writer::createDataSection() {
338 if (!Segments.size())
339 return;
340
341 log("createDataSection");
342 auto Section = make<DataSection>(Segments);
343 OutputSections.push_back(Section);
344}
345
Sam Cleggd451da12017-12-19 19:56:27 +0000346// Create relocations sections in the final output.
Sam Cleggc94d3932017-11-17 18:14:09 +0000347// These are only created when relocatable output is requested.
348void Writer::createRelocSections() {
349 log("createRelocSections");
350 // Don't use iterator here since we are adding to OutputSection
351 size_t OrigSize = OutputSections.size();
352 for (size_t i = 0; i < OrigSize; i++) {
Rui Ueyama37254062018-02-28 00:01:31 +0000353 OutputSection *OSec = OutputSections[i];
354 uint32_t Count = OSec->numRelocations();
Sam Cleggc94d3932017-11-17 18:14:09 +0000355 if (!Count)
356 continue;
357
Rui Ueyama37254062018-02-28 00:01:31 +0000358 StringRef Name;
359 if (OSec->Type == WASM_SEC_DATA)
360 Name = "reloc.DATA";
361 else if (OSec->Type == WASM_SEC_CODE)
362 Name = "reloc.CODE";
Sam Cleggc94d3932017-11-17 18:14:09 +0000363 else
Sam Cleggd451da12017-12-19 19:56:27 +0000364 llvm_unreachable("relocations only supported for code and data");
Sam Cleggc94d3932017-11-17 18:14:09 +0000365
Rui Ueyama37254062018-02-28 00:01:31 +0000366 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, Name);
Sam Cleggc94d3932017-11-17 18:14:09 +0000367 raw_ostream &OS = Section->getStream();
Rui Ueyama37254062018-02-28 00:01:31 +0000368 writeUleb128(OS, OSec->Type, "reloc section");
Sam Cleggc94d3932017-11-17 18:14:09 +0000369 writeUleb128(OS, Count, "reloc count");
Rui Ueyama37254062018-02-28 00:01:31 +0000370 OSec->writeRelocations(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000371 }
372}
373
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000374static uint32_t getWasmFlags(const Symbol *Sym) {
375 uint32_t Flags = 0;
376 if (Sym->isLocal())
377 Flags |= WASM_SYMBOL_BINDING_LOCAL;
378 if (Sym->isWeak())
379 Flags |= WASM_SYMBOL_BINDING_WEAK;
380 if (Sym->isHidden())
381 Flags |= WASM_SYMBOL_VISIBILITY_HIDDEN;
382 if (Sym->isUndefined())
383 Flags |= WASM_SYMBOL_UNDEFINED;
384 return Flags;
385}
386
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000387// Some synthetic sections (e.g. "name" and "linking") have subsections.
388// Just like the synthetic sections themselves these need to be created before
389// they can be written out (since they are preceded by their length). This
390// class is used to create subsections and then write them into the stream
391// of the parent section.
392class SubSection {
393public:
394 explicit SubSection(uint32_t Type) : Type(Type) {}
395
396 void writeTo(raw_ostream &To) {
397 OS.flush();
Rui Ueyama67769102018-02-28 03:38:14 +0000398 writeUleb128(To, Type, "subsection type");
399 writeUleb128(To, Body.size(), "subsection size");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000400 To.write(Body.data(), Body.size());
401 }
402
403private:
404 uint32_t Type;
405 std::string Body;
406
407public:
408 raw_string_ostream OS{Body};
409};
410
Sam Clegg49ed9262017-12-01 00:53:21 +0000411// Create the custom "linking" section containing linker metadata.
Sam Cleggc94d3932017-11-17 18:14:09 +0000412// This is only created when relocatable output is requested.
413void Writer::createLinkingSection() {
414 SyntheticSection *Section =
415 createSyntheticSection(WASM_SEC_CUSTOM, "linking");
416 raw_ostream &OS = Section->getStream();
417
Sam Clegg0d0dd392017-12-19 17:09:45 +0000418 if (!Config->Relocatable)
419 return;
420
Sam Clegg93102972018-02-23 05:08:53 +0000421 if (!SymtabEntries.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000422 SubSection Sub(WASM_SYMBOL_TABLE);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000423 writeUleb128(Sub.OS, SymtabEntries.size(), "num symbols");
424
Sam Clegg93102972018-02-23 05:08:53 +0000425 for (const Symbol *Sym : SymtabEntries) {
426 assert(Sym->isDefined() || Sym->isUndefined());
427 WasmSymbolType Kind = Sym->getWasmType();
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000428 uint32_t Flags = getWasmFlags(Sym);
429
Sam Clegg8518e7d2018-03-01 18:06:39 +0000430 writeU8(Sub.OS, Kind, "sym kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000431 writeUleb128(Sub.OS, Flags, "sym flags");
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000432
Sam Clegg93102972018-02-23 05:08:53 +0000433 switch (Kind) {
434 case llvm::wasm::WASM_SYMBOL_TYPE_FUNCTION:
435 case llvm::wasm::WASM_SYMBOL_TYPE_GLOBAL:
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000436 writeUleb128(Sub.OS, Sym->getOutputIndex(), "index");
Sam Clegg93102972018-02-23 05:08:53 +0000437 if (Sym->isDefined())
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000438 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegg93102972018-02-23 05:08:53 +0000439 break;
440 case llvm::wasm::WASM_SYMBOL_TYPE_DATA:
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 }
448 break;
449 }
Sam Cleggd3052d52018-01-18 23:40:49 +0000450 }
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000451
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000452 Sub.writeTo(OS);
Sam Cleggd3052d52018-01-18 23:40:49 +0000453 }
454
Sam Clegg0d0dd392017-12-19 17:09:45 +0000455 if (Segments.size()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000456 SubSection Sub(WASM_SEGMENT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000457 writeUleb128(Sub.OS, Segments.size(), "num data segments");
Sam Cleggc94d3932017-11-17 18:14:09 +0000458 for (const OutputSegment *S : Segments) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000459 writeStr(Sub.OS, S->Name, "segment name");
460 writeUleb128(Sub.OS, S->Alignment, "alignment");
461 writeUleb128(Sub.OS, 0, "flags");
Sam Cleggc94d3932017-11-17 18:14:09 +0000462 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000463 Sub.writeTo(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000464 }
Sam Clegg0d0dd392017-12-19 17:09:45 +0000465
Sam Clegg0d0dd392017-12-19 17:09:45 +0000466 if (!InitFunctions.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000467 SubSection Sub(WASM_INIT_FUNCS);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000468 writeUleb128(Sub.OS, InitFunctions.size(), "num init functions");
Sam Clegg93102972018-02-23 05:08:53 +0000469 for (const WasmInitEntry &F : InitFunctions) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000470 writeUleb128(Sub.OS, F.Priority, "priority");
471 writeUleb128(Sub.OS, F.Sym->getOutputSymbolIndex(), "function index");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000472 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000473 Sub.writeTo(OS);
Sam Clegg0d0dd392017-12-19 17:09:45 +0000474 }
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000475
476 struct ComdatEntry { unsigned Kind; uint32_t Index; };
477 std::map<StringRef,std::vector<ComdatEntry>> Comdats;
478
Sam Clegg9f934222018-02-21 18:29:23 +0000479 for (const InputFunction *F : InputFunctions) {
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000480 StringRef Comdat = F->getComdat();
481 if (!Comdat.empty())
482 Comdats[Comdat].emplace_back(
483 ComdatEntry{WASM_COMDAT_FUNCTION, F->getOutputIndex()});
484 }
485 for (uint32_t I = 0; I < Segments.size(); ++I) {
Sam Cleggf98bccf2018-01-13 15:57:48 +0000486 const auto &InputSegments = Segments[I]->InputSegments;
487 if (InputSegments.empty())
488 continue;
489 StringRef Comdat = InputSegments[0]->getComdat();
Sam Clegga697df522018-01-13 15:59:53 +0000490#ifndef NDEBUG
Sam Cleggf98bccf2018-01-13 15:57:48 +0000491 for (const InputSegment *IS : InputSegments)
492 assert(IS->getComdat() == Comdat);
Sam Clegga697df522018-01-13 15:59:53 +0000493#endif
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000494 if (!Comdat.empty())
495 Comdats[Comdat].emplace_back(ComdatEntry{WASM_COMDAT_DATA, I});
496 }
497
498 if (!Comdats.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000499 SubSection Sub(WASM_COMDAT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000500 writeUleb128(Sub.OS, Comdats.size(), "num comdats");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000501 for (const auto &C : Comdats) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000502 writeStr(Sub.OS, C.first, "comdat name");
503 writeUleb128(Sub.OS, 0, "comdat flags"); // flags for future use
504 writeUleb128(Sub.OS, C.second.size(), "num entries");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000505 for (const ComdatEntry &Entry : C.second) {
Sam Clegg8518e7d2018-03-01 18:06:39 +0000506 writeU8(Sub.OS, Entry.Kind, "entry kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000507 writeUleb128(Sub.OS, Entry.Index, "entry index");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000508 }
509 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000510 Sub.writeTo(OS);
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000511 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000512}
513
514// Create the custom "name" section containing debug symbol names.
515void Writer::createNameSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000516 unsigned NumNames = NumImportedFunctions;
Sam Clegg9f934222018-02-21 18:29:23 +0000517 for (const InputFunction *F : InputFunctions)
Sam Clegg1963d712018-01-17 20:19:04 +0000518 if (!F->getName().empty())
519 ++NumNames;
Sam Cleggc94d3932017-11-17 18:14:09 +0000520
Sam Clegg1963d712018-01-17 20:19:04 +0000521 if (NumNames == 0)
522 return;
Sam Clegg50686852018-01-12 18:35:13 +0000523
Sam Cleggc94d3932017-11-17 18:14:09 +0000524 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "name");
525
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000526 SubSection Sub(WASM_NAMES_FUNCTION);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000527 writeUleb128(Sub.OS, NumNames, "name count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000528
Sam Clegg93102972018-02-23 05:08:53 +0000529 // Names must appear in function index order. As it happens ImportedSymbols
530 // and InputFunctions are numbered in order with imported functions coming
Sam Clegg1963d712018-01-17 20:19:04 +0000531 // first.
Sam Clegg93102972018-02-23 05:08:53 +0000532 for (const Symbol *S : ImportedSymbols) {
533 if (!isa<FunctionSymbol>(S))
534 continue;
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000535 writeUleb128(Sub.OS, S->getOutputIndex(), "import index");
536 writeStr(Sub.OS, S->getName(), "symbol name");
Sam Cleggc94d3932017-11-17 18:14:09 +0000537 }
Sam Clegg9f934222018-02-21 18:29:23 +0000538 for (const InputFunction *F : InputFunctions) {
Sam Clegg1963d712018-01-17 20:19:04 +0000539 if (!F->getName().empty()) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000540 writeUleb128(Sub.OS, F->getOutputIndex(), "func index");
541 writeStr(Sub.OS, F->getName(), "symbol name");
Sam Clegg1963d712018-01-17 20:19:04 +0000542 }
543 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000544
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000545 Sub.writeTo(Section->getStream());
Sam Cleggc94d3932017-11-17 18:14:09 +0000546}
547
548void Writer::writeHeader() {
549 memcpy(Buffer->getBufferStart(), Header.data(), Header.size());
550}
551
552void Writer::writeSections() {
553 uint8_t *Buf = Buffer->getBufferStart();
554 parallelForEach(OutputSections, [Buf](OutputSection *S) { S->writeTo(Buf); });
555}
556
557// Fix the memory layout of the output binary. This assigns memory offsets
Sam Clegg49ed9262017-12-01 00:53:21 +0000558// to each of the input data sections as well as the explicit stack region.
Sam Cleggf0d433d2018-02-02 22:59:56 +0000559// The memory layout is as follows, from low to high.
560// - initialized data (starting at Config->GlobalBase)
561// - BSS data (not currently implemented in llvm)
562// - explicit stack (Config->ZStackSize)
563// - heap start / unallocated
Sam Cleggc94d3932017-11-17 18:14:09 +0000564void Writer::layoutMemory() {
565 uint32_t MemoryPtr = 0;
Sam Clegg99eb42c2018-02-27 23:58:03 +0000566 MemoryPtr = Config->GlobalBase;
567 debugPrint("mem: global base = %d\n", Config->GlobalBase);
Sam Cleggc94d3932017-11-17 18:14:09 +0000568
569 createOutputSegments();
570
Sam Cleggf0d433d2018-02-02 22:59:56 +0000571 // Arbitrarily set __dso_handle handle to point to the start of the data
572 // segments.
573 if (WasmSym::DsoHandle)
574 WasmSym::DsoHandle->setVirtualAddress(MemoryPtr);
575
Sam Cleggc94d3932017-11-17 18:14:09 +0000576 for (OutputSegment *Seg : Segments) {
577 MemoryPtr = alignTo(MemoryPtr, Seg->Alignment);
578 Seg->StartVA = MemoryPtr;
Sam Clegg7ed293e2018-01-12 00:34:04 +0000579 debugPrint("mem: %-15s offset=%-8d size=%-8d align=%d\n",
Sam Cleggc94d3932017-11-17 18:14:09 +0000580 Seg->Name.str().c_str(), MemoryPtr, Seg->Size, Seg->Alignment);
581 MemoryPtr += Seg->Size;
582 }
583
Sam Cleggf0d433d2018-02-02 22:59:56 +0000584 // TODO: Add .bss space here.
Sam Clegg37a4a8a2018-02-07 03:04:53 +0000585 if (WasmSym::DataEnd)
586 WasmSym::DataEnd->setVirtualAddress(MemoryPtr);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000587
Sam Clegg99eb42c2018-02-27 23:58:03 +0000588 debugPrint("mem: static data = %d\n", MemoryPtr - Config->GlobalBase);
Sam Cleggc94d3932017-11-17 18:14:09 +0000589
Sam Cleggf0d433d2018-02-02 22:59:56 +0000590 // Stack comes after static data and bss
Sam Cleggc94d3932017-11-17 18:14:09 +0000591 if (!Config->Relocatable) {
592 MemoryPtr = alignTo(MemoryPtr, kStackAlignment);
593 if (Config->ZStackSize != alignTo(Config->ZStackSize, kStackAlignment))
594 error("stack size must be " + Twine(kStackAlignment) + "-byte aligned");
595 debugPrint("mem: stack size = %d\n", Config->ZStackSize);
596 debugPrint("mem: stack base = %d\n", MemoryPtr);
597 MemoryPtr += Config->ZStackSize;
Sam Clegg93102972018-02-23 05:08:53 +0000598 WasmSym::StackPointer->Global->Global.InitExpr.Value.Int32 = MemoryPtr;
Sam Cleggc94d3932017-11-17 18:14:09 +0000599 debugPrint("mem: stack top = %d\n", MemoryPtr);
Sam Clegg93102972018-02-23 05:08:53 +0000600
Sam Clegg51bcdc22018-01-17 01:34:31 +0000601 // Set `__heap_base` to directly follow the end of the stack. We don't
602 // allocate any heap memory up front, but instead really on the malloc/brk
603 // implementation growing the memory at runtime.
Sam Cleggf0d433d2018-02-02 22:59:56 +0000604 WasmSym::HeapBase->setVirtualAddress(MemoryPtr);
Sam Clegg51bcdc22018-01-17 01:34:31 +0000605 debugPrint("mem: heap base = %d\n", MemoryPtr);
Sam Cleggc94d3932017-11-17 18:14:09 +0000606 }
607
608 uint32_t MemSize = alignTo(MemoryPtr, WasmPageSize);
609 NumMemoryPages = MemSize / WasmPageSize;
610 debugPrint("mem: total pages = %d\n", NumMemoryPages);
611}
612
613SyntheticSection *Writer::createSyntheticSection(uint32_t Type,
Sam Cleggc375e4e2018-01-10 19:18:22 +0000614 StringRef Name) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000615 auto Sec = make<SyntheticSection>(Type, Name);
Sam Cleggab2ac292017-12-20 05:14:48 +0000616 log("createSection: " + toString(*Sec));
Sam Cleggc94d3932017-11-17 18:14:09 +0000617 OutputSections.push_back(Sec);
618 return Sec;
619}
620
621void Writer::createSections() {
622 // Known sections
623 createTypeSection();
624 createImportSection();
625 createFunctionSection();
626 createTableSection();
627 createMemorySection();
628 createGlobalSection();
629 createExportSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000630 createElemSection();
631 createCodeSection();
632 createDataSection();
633
634 // Custom sections
Sam Clegg99eb42c2018-02-27 23:58:03 +0000635 if (Config->Relocatable) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000636 createRelocSections();
Sam Clegg99eb42c2018-02-27 23:58:03 +0000637 createLinkingSection();
638 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000639 if (!Config->StripDebug && !Config->StripAll)
640 createNameSection();
641
642 for (OutputSection *S : OutputSections) {
643 S->setOffset(FileSize);
644 S->finalizeContents();
645 FileSize += S->getSize();
646 }
647}
648
Sam Cleggc94d3932017-11-17 18:14:09 +0000649void Writer::calculateImports() {
Sam Clegg574d7ce2017-12-15 19:23:49 +0000650 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000651 if (!Sym->isUndefined())
652 continue;
653 if (isa<DataSymbol>(Sym))
654 continue;
655 if (Sym->isWeak() && !Config->Relocatable)
Sam Clegg574d7ce2017-12-15 19:23:49 +0000656 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000657
Sam Clegg93102972018-02-23 05:08:53 +0000658 DEBUG(dbgs() << "import: " << Sym->getName() << "\n");
659 Sym->setOutputIndex(ImportedSymbols.size());
660 ImportedSymbols.emplace_back(Sym);
661 if (isa<FunctionSymbol>(Sym))
662 ++NumImportedFunctions;
663 else
664 ++NumImportedGlobals;
Sam Cleggc94d3932017-11-17 18:14:09 +0000665 }
666}
667
Sam Cleggd3052d52018-01-18 23:40:49 +0000668void Writer::calculateExports() {
Sam Clegg93102972018-02-23 05:08:53 +0000669 if (Config->Relocatable)
670 return;
Sam Cleggf0d433d2018-02-02 22:59:56 +0000671
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000672 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000673 if (!Sym->isDefined())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000674 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000675 if (Sym->isHidden() || Sym->isLocal())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000676 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000677 if (!Sym->isLive())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000678 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000679
680 DEBUG(dbgs() << "exporting sym: " << Sym->getName() << "\n");
681
682 if (auto *D = dyn_cast<DefinedData>(Sym)) {
683 // TODO Remove this check here; for non-relocatable output we actually
684 // used only to create fake-global exports for the synthetic symbols. Fix
685 // this in a future commit
686 if (Sym != WasmSym::DataEnd && Sym != WasmSym::HeapBase)
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000687 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000688 DefinedFakeGlobals.emplace_back(D);
Sam Cleggd3052d52018-01-18 23:40:49 +0000689 }
Sam Clegg93102972018-02-23 05:08:53 +0000690 ExportedSymbols.emplace_back(Sym);
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000691 }
Sam Clegg93102972018-02-23 05:08:53 +0000692}
693
694void Writer::assignSymtab() {
695 if (!Config->Relocatable)
696 return;
697
698 unsigned SymbolIndex = SymtabEntries.size();
Sam Cleggd3052d52018-01-18 23:40:49 +0000699 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg93102972018-02-23 05:08:53 +0000700 DEBUG(dbgs() << "Symtab entries: " << File->getName() << "\n");
Sam Cleggd3052d52018-01-18 23:40:49 +0000701 for (Symbol *Sym : File->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000702 if (Sym->getFile() != File)
Sam Cleggd3052d52018-01-18 23:40:49 +0000703 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000704 if (!Sym->isLive())
705 return;
706 Sym->setOutputSymbolIndex(SymbolIndex++);
707 SymtabEntries.emplace_back(Sym);
Sam Cleggd3052d52018-01-18 23:40:49 +0000708 }
709 }
710
Sam Clegg93102972018-02-23 05:08:53 +0000711 // For the moment, relocatable output doesn't contain any synthetic functions,
712 // so no need to look through the Symtab for symbols not referenced by
713 // Symtab->ObjectFiles.
Sam Cleggd3052d52018-01-18 23:40:49 +0000714}
715
Sam Cleggc375e4e2018-01-10 19:18:22 +0000716uint32_t Writer::lookupType(const WasmSignature &Sig) {
Sam Clegg8d027d62018-01-10 20:12:26 +0000717 auto It = TypeIndices.find(Sig);
718 if (It == TypeIndices.end()) {
Sam Cleggc375e4e2018-01-10 19:18:22 +0000719 error("type not found: " + toString(Sig));
Sam Clegg8d027d62018-01-10 20:12:26 +0000720 return 0;
721 }
722 return It->second;
Sam Cleggc375e4e2018-01-10 19:18:22 +0000723}
724
725uint32_t Writer::registerType(const WasmSignature &Sig) {
Sam Cleggb8621592017-11-30 01:40:08 +0000726 auto Pair = TypeIndices.insert(std::make_pair(Sig, Types.size()));
Sam Cleggc375e4e2018-01-10 19:18:22 +0000727 if (Pair.second) {
728 DEBUG(dbgs() << "type " << toString(Sig) << "\n");
Sam Cleggb8621592017-11-30 01:40:08 +0000729 Types.push_back(&Sig);
Sam Cleggc375e4e2018-01-10 19:18:22 +0000730 }
Sam Cleggb8621592017-11-30 01:40:08 +0000731 return Pair.first->second;
732}
733
Sam Cleggc94d3932017-11-17 18:14:09 +0000734void Writer::calculateTypes() {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000735 // The output type section is the union of the following sets:
736 // 1. Any signature used in the TYPE relocation
737 // 2. The signatures of all imported functions
738 // 3. The signatures of all defined functions
739
Sam Cleggc94d3932017-11-17 18:14:09 +0000740 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000741 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
742 for (uint32_t I = 0; I < Types.size(); I++)
743 if (File->TypeIsUsed[I])
744 File->TypeMap[I] = registerType(Types[I]);
Sam Cleggc94d3932017-11-17 18:14:09 +0000745 }
Sam Clegg50686852018-01-12 18:35:13 +0000746
Sam Clegg93102972018-02-23 05:08:53 +0000747 for (const Symbol *Sym : ImportedSymbols)
748 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
749 registerType(*F->getFunctionType());
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000750
Sam Clegg9f934222018-02-21 18:29:23 +0000751 for (const InputFunction *F : InputFunctions)
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000752 registerType(F->Signature);
Sam Cleggc94d3932017-11-17 18:14:09 +0000753}
754
Sam Clegg8d146bb2018-01-09 23:56:44 +0000755void Writer::assignIndexes() {
Sam Clegg93102972018-02-23 05:08:53 +0000756 uint32_t FunctionIndex = NumImportedFunctions + InputFunctions.size();
Sam Clegg87e61922018-01-08 23:39:11 +0000757 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8d146bb2018-01-09 23:56:44 +0000758 DEBUG(dbgs() << "Functions: " << File->getName() << "\n");
759 for (InputFunction *Func : File->Functions) {
Sam Clegg447ae402018-02-13 20:29:38 +0000760 if (!Func->Live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000761 continue;
Sam Clegg9f934222018-02-21 18:29:23 +0000762 InputFunctions.emplace_back(Func);
Sam Clegg8d146bb2018-01-09 23:56:44 +0000763 Func->setOutputIndex(FunctionIndex++);
764 }
765 }
766
Sam Clegg93102972018-02-23 05:08:53 +0000767 uint32_t TableIndex = kInitialTableOffset;
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000768 auto HandleRelocs = [&](InputChunk *Chunk) {
769 if (!Chunk->Live)
770 return;
771 ObjFile *File = Chunk->File;
772 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
Sam Clegg93102972018-02-23 05:08:53 +0000773 for (const WasmRelocation &Reloc : Chunk->getRelocations()) {
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000774 if (Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_I32 ||
775 Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_SLEB) {
776 FunctionSymbol *Sym = File->getFunctionSymbol(Reloc.Index);
777 if (Sym->hasTableIndex() || !Sym->hasOutputIndex())
778 continue;
779 Sym->setTableIndex(TableIndex++);
780 IndirectFunctions.emplace_back(Sym);
781 } else if (Reloc.Type == R_WEBASSEMBLY_TYPE_INDEX_LEB) {
Sam Clegg93102972018-02-23 05:08:53 +0000782 // Mark target type as live
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000783 File->TypeMap[Reloc.Index] = registerType(Types[Reloc.Index]);
784 File->TypeIsUsed[Reloc.Index] = true;
Sam Clegg93102972018-02-23 05:08:53 +0000785 } else if (Reloc.Type == R_WEBASSEMBLY_GLOBAL_INDEX_LEB) {
786 // Mark target global as live
787 GlobalSymbol *Sym = File->getGlobalSymbol(Reloc.Index);
788 if (auto *G = dyn_cast<DefinedGlobal>(Sym)) {
789 DEBUG(dbgs() << "marking global live: " << Sym->getName() << "\n");
790 G->Global->Live = true;
791 }
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000792 }
793 }
794 };
795
Sam Clegg8d146bb2018-01-09 23:56:44 +0000796 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000797 DEBUG(dbgs() << "Handle relocs: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000798 for (InputChunk *Chunk : File->Functions)
799 HandleRelocs(Chunk);
800 for (InputChunk *Chunk : File->Segments)
801 HandleRelocs(Chunk);
802 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000803
Sam Clegg93102972018-02-23 05:08:53 +0000804 uint32_t GlobalIndex = NumImportedGlobals + InputGlobals.size();
805 auto AddDefinedGlobal = [&](InputGlobal *Global) {
806 if (Global->Live) {
807 DEBUG(dbgs() << "AddDefinedGlobal: " << GlobalIndex << "\n");
808 Global->setOutputIndex(GlobalIndex++);
809 InputGlobals.push_back(Global);
810 }
811 };
812
813 if (WasmSym::StackPointer)
814 AddDefinedGlobal(WasmSym::StackPointer->Global);
815
816 for (ObjFile *File : Symtab->ObjectFiles) {
817 DEBUG(dbgs() << "Globals: " << File->getName() << "\n");
818 for (InputGlobal *Global : File->Globals)
819 AddDefinedGlobal(Global);
Sam Cleggc94d3932017-11-17 18:14:09 +0000820 }
821}
822
823static StringRef getOutputDataSegmentName(StringRef Name) {
824 if (Config->Relocatable)
825 return Name;
Rui Ueyama4764b572018-02-28 00:57:28 +0000826 if (Name.startswith(".text."))
827 return ".text";
828 if (Name.startswith(".data."))
829 return ".data";
830 if (Name.startswith(".bss."))
831 return ".bss";
Sam Cleggc94d3932017-11-17 18:14:09 +0000832 return Name;
833}
834
835void Writer::createOutputSegments() {
836 for (ObjFile *File : Symtab->ObjectFiles) {
837 for (InputSegment *Segment : File->Segments) {
Sam Clegg447ae402018-02-13 20:29:38 +0000838 if (!Segment->Live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000839 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000840 StringRef Name = getOutputDataSegmentName(Segment->getName());
841 OutputSegment *&S = SegmentMap[Name];
842 if (S == nullptr) {
843 DEBUG(dbgs() << "new segment: " << Name << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000844 S = make<OutputSegment>(Name, Segments.size());
Sam Cleggc94d3932017-11-17 18:14:09 +0000845 Segments.push_back(S);
846 }
847 S->addInputSegment(Segment);
848 DEBUG(dbgs() << "added data: " << Name << ": " << S->Size << "\n");
Sam Cleggc94d3932017-11-17 18:14:09 +0000849 }
850 }
851}
852
Sam Clegg50686852018-01-12 18:35:13 +0000853static const int OPCODE_CALL = 0x10;
854static const int OPCODE_END = 0xb;
855
856// Create synthetic "__wasm_call_ctors" function based on ctor functions
857// in input object.
858void Writer::createCtorFunction() {
Sam Clegg93102972018-02-23 05:08:53 +0000859 uint32_t FunctionIndex = NumImportedFunctions + InputFunctions.size();
Sam Cleggf0d433d2018-02-02 22:59:56 +0000860 WasmSym::CallCtors->setOutputIndex(FunctionIndex);
Sam Clegg50686852018-01-12 18:35:13 +0000861
862 // First write the body bytes to a string.
863 std::string FunctionBody;
Sam Clegg50686852018-01-12 18:35:13 +0000864 {
865 raw_string_ostream OS(FunctionBody);
866 writeUleb128(OS, 0, "num locals");
Sam Clegg93102972018-02-23 05:08:53 +0000867 for (const WasmInitEntry &F : InitFunctions) {
Sam Clegg50686852018-01-12 18:35:13 +0000868 writeU8(OS, OPCODE_CALL, "CALL");
Sam Clegg93102972018-02-23 05:08:53 +0000869 writeUleb128(OS, F.Sym->getOutputIndex(), "function index");
Sam Clegg50686852018-01-12 18:35:13 +0000870 }
871 writeU8(OS, OPCODE_END, "END");
872 }
873
874 // Once we know the size of the body we can create the final function body
875 raw_string_ostream OS(CtorFunctionBody);
876 writeUleb128(OS, FunctionBody.size(), "function size");
877 OS.flush();
878 CtorFunctionBody += FunctionBody;
Rui Ueyama29abfe42018-02-28 17:43:15 +0000879
880 const WasmSignature *Sig = WasmSym::CallCtors->getFunctionType();
881 SyntheticFunction *F = make<SyntheticFunction>(
882 *Sig, toArrayRef(CtorFunctionBody), WasmSym::CallCtors->getName());
883
Sam Clegg011dce22018-02-21 18:37:44 +0000884 F->setOutputIndex(FunctionIndex);
Sam Clegg93102972018-02-23 05:08:53 +0000885 F->Live = true;
886 WasmSym::CallCtors->Function = F;
Sam Clegg011dce22018-02-21 18:37:44 +0000887 InputFunctions.emplace_back(F);
Sam Clegg50686852018-01-12 18:35:13 +0000888}
889
890// Populate InitFunctions vector with init functions from all input objects.
891// This is then used either when creating the output linking section or to
892// synthesize the "__wasm_call_ctors" function.
893void Writer::calculateInitFunctions() {
894 for (ObjFile *File : Symtab->ObjectFiles) {
895 const WasmLinkingData &L = File->getWasmObj()->linkingData();
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +0000896 for (const WasmInitFunc &F : L.InitFunctions) {
897 FunctionSymbol *Sym = File->getFunctionSymbol(F.Symbol);
898 if (*Sym->getFunctionType() != WasmSignature{{}, WASM_TYPE_NORESULT})
899 error("invalid signature for init func: " + toString(*Sym));
900 InitFunctions.emplace_back(WasmInitEntry{Sym, F.Priority});
901 }
Sam Clegg50686852018-01-12 18:35:13 +0000902 }
Rui Ueyamada69b712018-02-28 00:15:59 +0000903
Sam Clegg50686852018-01-12 18:35:13 +0000904 // Sort in order of priority (lowest first) so that they are called
905 // in the correct order.
Sam Clegg29b8feb2018-02-21 00:34:34 +0000906 std::stable_sort(InitFunctions.begin(), InitFunctions.end(),
Sam Clegg93102972018-02-23 05:08:53 +0000907 [](const WasmInitEntry &L, const WasmInitEntry &R) {
Sam Clegg29b8feb2018-02-21 00:34:34 +0000908 return L.Priority < R.Priority;
909 });
Sam Clegg50686852018-01-12 18:35:13 +0000910}
911
Sam Cleggc94d3932017-11-17 18:14:09 +0000912void Writer::run() {
Sam Clegg99eb42c2018-02-27 23:58:03 +0000913 if (Config->Relocatable)
914 Config->GlobalBase = 0;
915
Sam Cleggc94d3932017-11-17 18:14:09 +0000916 log("-- calculateImports");
917 calculateImports();
Sam Clegg8d146bb2018-01-09 23:56:44 +0000918 log("-- assignIndexes");
919 assignIndexes();
Sam Clegg50686852018-01-12 18:35:13 +0000920 log("-- calculateInitFunctions");
921 calculateInitFunctions();
922 if (!Config->Relocatable)
923 createCtorFunction();
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000924 log("-- calculateTypes");
925 calculateTypes();
Sam Clegg93102972018-02-23 05:08:53 +0000926 log("-- layoutMemory");
927 layoutMemory();
928 log("-- calculateExports");
929 calculateExports();
930 log("-- assignSymtab");
931 assignSymtab();
Sam Cleggc94d3932017-11-17 18:14:09 +0000932
933 if (errorHandler().Verbose) {
Sam Clegg9f934222018-02-21 18:29:23 +0000934 log("Defined Functions: " + Twine(InputFunctions.size()));
Sam Clegg93102972018-02-23 05:08:53 +0000935 log("Defined Globals : " + Twine(InputGlobals.size()));
936 log("Function Imports : " + Twine(NumImportedFunctions));
937 log("Global Imports : " + Twine(NumImportedGlobals));
Sam Cleggc94d3932017-11-17 18:14:09 +0000938 for (ObjFile *File : Symtab->ObjectFiles)
939 File->dumpInfo();
940 }
941
Sam Cleggc94d3932017-11-17 18:14:09 +0000942 createHeader();
943 log("-- createSections");
944 createSections();
945
946 log("-- openFile");
947 openFile();
948 if (errorCount())
949 return;
950
951 writeHeader();
952
953 log("-- writeSections");
954 writeSections();
955 if (errorCount())
956 return;
957
958 if (Error E = Buffer->commit())
959 fatal("failed to write the output file: " + toString(std::move(E)));
960}
961
962// Open a result file.
963void Writer::openFile() {
964 log("writing: " + Config->OutputFile);
Sam Cleggc94d3932017-11-17 18:14:09 +0000965
966 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
967 FileOutputBuffer::create(Config->OutputFile, FileSize,
968 FileOutputBuffer::F_executable);
969
970 if (!BufferOrErr)
971 error("failed to open " + Config->OutputFile + ": " +
972 toString(BufferOrErr.takeError()));
973 else
974 Buffer = std::move(*BufferOrErr);
975}
976
977void Writer::createHeader() {
978 raw_string_ostream OS(Header);
979 writeBytes(OS, WasmMagic, sizeof(WasmMagic), "wasm magic");
980 writeU32(OS, WasmVersion, "wasm version");
981 OS.flush();
982 FileSize += Header.size();
983}
984
985void lld::wasm::writeResult() { Writer().run(); }