blob: e263c97b116a688385b2e5f2b34cf382f7826d0b [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();
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;
140
141 std::vector<OutputSegment *> Segments;
142 llvm::SmallDenseMap<StringRef, OutputSegment *> SegmentMap;
143};
144
145} // anonymous namespace
146
147static void debugPrint(const char *fmt, ...) {
148 if (!errorHandler().Verbose)
149 return;
150 fprintf(stderr, "lld: ");
151 va_list ap;
152 va_start(ap, fmt);
153 vfprintf(stderr, fmt, ap);
154 va_end(ap);
155}
156
157void Writer::createImportSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000158 uint32_t NumImports = ImportedSymbols.size();
Sam Cleggc94d3932017-11-17 18:14:09 +0000159 if (Config->ImportMemory)
160 ++NumImports;
161
162 if (NumImports == 0)
163 return;
164
165 SyntheticSection *Section = createSyntheticSection(WASM_SEC_IMPORT);
166 raw_ostream &OS = Section->getStream();
167
168 writeUleb128(OS, NumImports, "import count");
169
Sam Cleggc94d3932017-11-17 18:14:09 +0000170 if (Config->ImportMemory) {
171 WasmImport Import;
172 Import.Module = "env";
173 Import.Field = "memory";
174 Import.Kind = WASM_EXTERNAL_MEMORY;
175 Import.Memory.Flags = 0;
176 Import.Memory.Initial = NumMemoryPages;
177 writeImport(OS, Import);
178 }
179
Sam Clegg93102972018-02-23 05:08:53 +0000180 for (const Symbol *Sym : ImportedSymbols) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000181 WasmImport Import;
182 Import.Module = "env";
183 Import.Field = Sym->getName();
Sam Clegg93102972018-02-23 05:08:53 +0000184 if (auto *FunctionSym = dyn_cast<FunctionSymbol>(Sym)) {
185 Import.Kind = WASM_EXTERNAL_FUNCTION;
186 Import.SigIndex = lookupType(*FunctionSym->getFunctionType());
187 } else {
188 auto *GlobalSym = cast<GlobalSymbol>(Sym);
189 Import.Kind = WASM_EXTERNAL_GLOBAL;
190 Import.Global = *GlobalSym->getGlobalType();
191 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000192 writeImport(OS, Import);
193 }
194}
195
196void Writer::createTypeSection() {
197 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TYPE);
198 raw_ostream &OS = Section->getStream();
199 writeUleb128(OS, Types.size(), "type count");
Sam Cleggd451da12017-12-19 19:56:27 +0000200 for (const WasmSignature *Sig : Types)
Sam Cleggc94d3932017-11-17 18:14:09 +0000201 writeSig(OS, *Sig);
Sam Cleggc94d3932017-11-17 18:14:09 +0000202}
203
204void Writer::createFunctionSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000205 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000206 return;
207
208 SyntheticSection *Section = createSyntheticSection(WASM_SEC_FUNCTION);
209 raw_ostream &OS = Section->getStream();
210
Sam Clegg9f934222018-02-21 18:29:23 +0000211 writeUleb128(OS, InputFunctions.size(), "function count");
212 for (const InputFunction *Func : InputFunctions)
Sam Cleggc375e4e2018-01-10 19:18:22 +0000213 writeUleb128(OS, lookupType(Func->Signature), "sig index");
Sam Cleggc94d3932017-11-17 18:14:09 +0000214}
215
216void Writer::createMemorySection() {
217 if (Config->ImportMemory)
218 return;
219
220 SyntheticSection *Section = createSyntheticSection(WASM_SEC_MEMORY);
221 raw_ostream &OS = Section->getStream();
222
223 writeUleb128(OS, 1, "memory count");
224 writeUleb128(OS, 0, "memory limits flags");
225 writeUleb128(OS, NumMemoryPages, "initial pages");
226}
227
228void Writer::createGlobalSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000229 unsigned NumGlobals = InputGlobals.size() + DefinedFakeGlobals.size();
230 if (NumGlobals == 0)
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000231 return;
232
Sam Cleggc94d3932017-11-17 18:14:09 +0000233 SyntheticSection *Section = createSyntheticSection(WASM_SEC_GLOBAL);
234 raw_ostream &OS = Section->getStream();
235
Sam Clegg93102972018-02-23 05:08:53 +0000236 writeUleb128(OS, NumGlobals, "global count");
237 for (const InputGlobal *G : InputGlobals)
238 writeGlobal(OS, G->Global);
239 for (const DefinedData *Sym : DefinedFakeGlobals) {
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000240 WasmGlobal Global;
Sam Clegg93102972018-02-23 05:08:53 +0000241 Global.Type = {WASM_TYPE_I32, false};
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000242 Global.InitExpr.Opcode = WASM_OPCODE_I32_CONST;
243 Global.InitExpr.Value.Int32 = Sym->getVirtualAddress();
Sam Cleggc94d3932017-11-17 18:14:09 +0000244 writeGlobal(OS, Global);
245 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000246}
247
248void Writer::createTableSection() {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000249 // Always output a table section, even if there are no indirect calls.
250 // There are two reasons for this:
251 // 1. For executables it is useful to have an empty table slot at 0
252 // which can be filled with a null function call handler.
253 // 2. If we don't do this, any program that contains a call_indirect but
254 // no address-taken function will fail at validation time since it is
255 // a validation error to include a call_indirect instruction if there
256 // is not table.
Sam Clegg48bbd632018-01-24 21:37:30 +0000257 uint32_t TableSize = kInitialTableOffset + IndirectFunctions.size();
Sam Cleggfc1a9122017-12-11 22:00:56 +0000258
Sam Cleggc94d3932017-11-17 18:14:09 +0000259 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TABLE);
260 raw_ostream &OS = Section->getStream();
261
262 writeUleb128(OS, 1, "table count");
Sam Clegg8518e7d2018-03-01 18:06:39 +0000263 writeU8(OS, WASM_TYPE_ANYFUNC, "table type");
Sam Cleggc94d3932017-11-17 18:14:09 +0000264 writeUleb128(OS, WASM_LIMITS_FLAG_HAS_MAX, "table flags");
Sam Cleggfc1a9122017-12-11 22:00:56 +0000265 writeUleb128(OS, TableSize, "table initial size");
266 writeUleb128(OS, TableSize, "table max size");
Sam Cleggc94d3932017-11-17 18:14:09 +0000267}
268
269void Writer::createExportSection() {
Sam Cleggc94d3932017-11-17 18:14:09 +0000270 bool ExportMemory = !Config->Relocatable && !Config->ImportMemory;
Sam Cleggc94d3932017-11-17 18:14:09 +0000271
Sam Cleggd3052d52018-01-18 23:40:49 +0000272 uint32_t NumExports = (ExportMemory ? 1 : 0) + ExportedSymbols.size();
Sam Cleggc94d3932017-11-17 18:14:09 +0000273 if (!NumExports)
274 return;
275
276 SyntheticSection *Section = createSyntheticSection(WASM_SEC_EXPORT);
277 raw_ostream &OS = Section->getStream();
278
279 writeUleb128(OS, NumExports, "export count");
280
Rui Ueyama7d696882018-02-28 00:18:34 +0000281 if (ExportMemory)
282 writeExport(OS, {"memory", WASM_EXTERNAL_MEMORY, 0});
Sam Cleggc94d3932017-11-17 18:14:09 +0000283
Sam Clegg93102972018-02-23 05:08:53 +0000284 unsigned FakeGlobalIndex = NumImportedGlobals + InputGlobals.size();
Rui Ueyama7d696882018-02-28 00:18:34 +0000285
Sam Clegg93102972018-02-23 05:08:53 +0000286 for (const Symbol *Sym : ExportedSymbols) {
Rui Ueyama7d696882018-02-28 00:18:34 +0000287 StringRef Name = Sym->getName();
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000288 WasmExport Export;
Rui Ueyama7d696882018-02-28 00:18:34 +0000289 DEBUG(dbgs() << "Export: " << Name << "\n");
290
291 if (isa<DefinedFunction>(Sym))
292 Export = {Name, WASM_EXTERNAL_FUNCTION, Sym->getOutputIndex()};
293 else if (isa<DefinedGlobal>(Sym))
294 Export = {Name, WASM_EXTERNAL_GLOBAL, Sym->getOutputIndex()};
295 else if (isa<DefinedData>(Sym))
296 Export = {Name, WASM_EXTERNAL_GLOBAL, FakeGlobalIndex++};
297 else
Sam Clegg93102972018-02-23 05:08:53 +0000298 llvm_unreachable("unexpected symbol type");
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000299 writeExport(OS, Export);
Sam Cleggc94d3932017-11-17 18:14:09 +0000300 }
301}
302
Sam Cleggc94d3932017-11-17 18:14:09 +0000303void Writer::createElemSection() {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000304 if (IndirectFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000305 return;
306
307 SyntheticSection *Section = createSyntheticSection(WASM_SEC_ELEM);
308 raw_ostream &OS = Section->getStream();
309
310 writeUleb128(OS, 1, "segment count");
311 writeUleb128(OS, 0, "table index");
312 WasmInitExpr InitExpr;
313 InitExpr.Opcode = WASM_OPCODE_I32_CONST;
Sam Clegg48bbd632018-01-24 21:37:30 +0000314 InitExpr.Value.Int32 = kInitialTableOffset;
Sam Cleggc94d3932017-11-17 18:14:09 +0000315 writeInitExpr(OS, InitExpr);
Sam Cleggfc1a9122017-12-11 22:00:56 +0000316 writeUleb128(OS, IndirectFunctions.size(), "elem count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000317
Sam Clegg48bbd632018-01-24 21:37:30 +0000318 uint32_t TableIndex = kInitialTableOffset;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000319 for (const FunctionSymbol *Sym : IndirectFunctions) {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000320 assert(Sym->getTableIndex() == TableIndex);
321 writeUleb128(OS, Sym->getOutputIndex(), "function index");
322 ++TableIndex;
323 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000324}
325
326void Writer::createCodeSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000327 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000328 return;
329
330 log("createCodeSection");
331
Sam Clegg9f934222018-02-21 18:29:23 +0000332 auto Section = make<CodeSection>(InputFunctions);
Sam Cleggc94d3932017-11-17 18:14:09 +0000333 OutputSections.push_back(Section);
334}
335
336void Writer::createDataSection() {
337 if (!Segments.size())
338 return;
339
340 log("createDataSection");
341 auto Section = make<DataSection>(Segments);
342 OutputSections.push_back(Section);
343}
344
Sam Cleggd451da12017-12-19 19:56:27 +0000345// Create relocations sections in the final output.
Sam Cleggc94d3932017-11-17 18:14:09 +0000346// These are only created when relocatable output is requested.
347void Writer::createRelocSections() {
348 log("createRelocSections");
349 // Don't use iterator here since we are adding to OutputSection
350 size_t OrigSize = OutputSections.size();
351 for (size_t i = 0; i < OrigSize; i++) {
Rui Ueyama37254062018-02-28 00:01:31 +0000352 OutputSection *OSec = OutputSections[i];
353 uint32_t Count = OSec->numRelocations();
Sam Cleggc94d3932017-11-17 18:14:09 +0000354 if (!Count)
355 continue;
356
Rui Ueyama37254062018-02-28 00:01:31 +0000357 StringRef Name;
358 if (OSec->Type == WASM_SEC_DATA)
359 Name = "reloc.DATA";
360 else if (OSec->Type == WASM_SEC_CODE)
361 Name = "reloc.CODE";
Sam Cleggc94d3932017-11-17 18:14:09 +0000362 else
Sam Cleggd451da12017-12-19 19:56:27 +0000363 llvm_unreachable("relocations only supported for code and data");
Sam Cleggc94d3932017-11-17 18:14:09 +0000364
Rui Ueyama37254062018-02-28 00:01:31 +0000365 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, Name);
Sam Cleggc94d3932017-11-17 18:14:09 +0000366 raw_ostream &OS = Section->getStream();
Rui Ueyama37254062018-02-28 00:01:31 +0000367 writeUleb128(OS, OSec->Type, "reloc section");
Sam Cleggc94d3932017-11-17 18:14:09 +0000368 writeUleb128(OS, Count, "reloc count");
Rui Ueyama37254062018-02-28 00:01:31 +0000369 OSec->writeRelocations(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000370 }
371}
372
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000373static uint32_t getWasmFlags(const Symbol *Sym) {
374 uint32_t Flags = 0;
375 if (Sym->isLocal())
376 Flags |= WASM_SYMBOL_BINDING_LOCAL;
377 if (Sym->isWeak())
378 Flags |= WASM_SYMBOL_BINDING_WEAK;
379 if (Sym->isHidden())
380 Flags |= WASM_SYMBOL_VISIBILITY_HIDDEN;
381 if (Sym->isUndefined())
382 Flags |= WASM_SYMBOL_UNDEFINED;
383 return Flags;
384}
385
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000386// Some synthetic sections (e.g. "name" and "linking") have subsections.
387// Just like the synthetic sections themselves these need to be created before
388// they can be written out (since they are preceded by their length). This
389// class is used to create subsections and then write them into the stream
390// of the parent section.
391class SubSection {
392public:
393 explicit SubSection(uint32_t Type) : Type(Type) {}
394
395 void writeTo(raw_ostream &To) {
396 OS.flush();
Rui Ueyama67769102018-02-28 03:38:14 +0000397 writeUleb128(To, Type, "subsection type");
398 writeUleb128(To, Body.size(), "subsection size");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000399 To.write(Body.data(), Body.size());
400 }
401
402private:
403 uint32_t Type;
404 std::string Body;
405
406public:
407 raw_string_ostream OS{Body};
408};
409
Sam Clegg49ed9262017-12-01 00:53:21 +0000410// Create the custom "linking" section containing linker metadata.
Sam Cleggc94d3932017-11-17 18:14:09 +0000411// This is only created when relocatable output is requested.
412void Writer::createLinkingSection() {
413 SyntheticSection *Section =
414 createSyntheticSection(WASM_SEC_CUSTOM, "linking");
415 raw_ostream &OS = Section->getStream();
416
Sam Clegg0d0dd392017-12-19 17:09:45 +0000417 if (!Config->Relocatable)
418 return;
419
Sam Clegg93102972018-02-23 05:08:53 +0000420 if (!SymtabEntries.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000421 SubSection Sub(WASM_SYMBOL_TABLE);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000422 writeUleb128(Sub.OS, SymtabEntries.size(), "num symbols");
423
Sam Clegg93102972018-02-23 05:08:53 +0000424 for (const Symbol *Sym : SymtabEntries) {
425 assert(Sym->isDefined() || Sym->isUndefined());
426 WasmSymbolType Kind = Sym->getWasmType();
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000427 uint32_t Flags = getWasmFlags(Sym);
428
Sam Clegg8518e7d2018-03-01 18:06:39 +0000429 writeU8(Sub.OS, Kind, "sym kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000430 writeUleb128(Sub.OS, Flags, "sym flags");
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000431
Sam Clegg93102972018-02-23 05:08:53 +0000432 switch (Kind) {
433 case llvm::wasm::WASM_SYMBOL_TYPE_FUNCTION:
434 case llvm::wasm::WASM_SYMBOL_TYPE_GLOBAL:
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000435 writeUleb128(Sub.OS, Sym->getOutputIndex(), "index");
Sam Clegg93102972018-02-23 05:08:53 +0000436 if (Sym->isDefined())
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000437 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegg93102972018-02-23 05:08:53 +0000438 break;
439 case llvm::wasm::WASM_SYMBOL_TYPE_DATA:
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000440 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegg93102972018-02-23 05:08:53 +0000441 if (auto *DataSym = dyn_cast<DefinedData>(Sym)) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000442 writeUleb128(Sub.OS, DataSym->getOutputSegmentIndex(), "index");
443 writeUleb128(Sub.OS, DataSym->getOutputSegmentOffset(),
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000444 "data offset");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000445 writeUleb128(Sub.OS, DataSym->getSize(), "data size");
Sam Clegg93102972018-02-23 05:08:53 +0000446 }
447 break;
448 }
Sam Cleggd3052d52018-01-18 23:40:49 +0000449 }
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000450
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000451 Sub.writeTo(OS);
Sam Cleggd3052d52018-01-18 23:40:49 +0000452 }
453
Sam Clegg0d0dd392017-12-19 17:09:45 +0000454 if (Segments.size()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000455 SubSection Sub(WASM_SEGMENT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000456 writeUleb128(Sub.OS, Segments.size(), "num data segments");
Sam Cleggc94d3932017-11-17 18:14:09 +0000457 for (const OutputSegment *S : Segments) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000458 writeStr(Sub.OS, S->Name, "segment name");
459 writeUleb128(Sub.OS, S->Alignment, "alignment");
460 writeUleb128(Sub.OS, 0, "flags");
Sam Cleggc94d3932017-11-17 18:14:09 +0000461 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000462 Sub.writeTo(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000463 }
Sam Clegg0d0dd392017-12-19 17:09:45 +0000464
Sam Clegg0d0dd392017-12-19 17:09:45 +0000465 if (!InitFunctions.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000466 SubSection Sub(WASM_INIT_FUNCS);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000467 writeUleb128(Sub.OS, InitFunctions.size(), "num init functions");
Sam Clegg93102972018-02-23 05:08:53 +0000468 for (const WasmInitEntry &F : InitFunctions) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000469 writeUleb128(Sub.OS, F.Priority, "priority");
470 writeUleb128(Sub.OS, F.Sym->getOutputSymbolIndex(), "function index");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000471 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000472 Sub.writeTo(OS);
Sam Clegg0d0dd392017-12-19 17:09:45 +0000473 }
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000474
475 struct ComdatEntry { unsigned Kind; uint32_t Index; };
476 std::map<StringRef,std::vector<ComdatEntry>> Comdats;
477
Sam Clegg9f934222018-02-21 18:29:23 +0000478 for (const InputFunction *F : InputFunctions) {
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000479 StringRef Comdat = F->getComdat();
480 if (!Comdat.empty())
481 Comdats[Comdat].emplace_back(
482 ComdatEntry{WASM_COMDAT_FUNCTION, F->getOutputIndex()});
483 }
484 for (uint32_t I = 0; I < Segments.size(); ++I) {
Sam Cleggf98bccf2018-01-13 15:57:48 +0000485 const auto &InputSegments = Segments[I]->InputSegments;
486 if (InputSegments.empty())
487 continue;
488 StringRef Comdat = InputSegments[0]->getComdat();
Sam Clegga697df522018-01-13 15:59:53 +0000489#ifndef NDEBUG
Sam Cleggf98bccf2018-01-13 15:57:48 +0000490 for (const InputSegment *IS : InputSegments)
491 assert(IS->getComdat() == Comdat);
Sam Clegga697df522018-01-13 15:59:53 +0000492#endif
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000493 if (!Comdat.empty())
494 Comdats[Comdat].emplace_back(ComdatEntry{WASM_COMDAT_DATA, I});
495 }
496
497 if (!Comdats.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000498 SubSection Sub(WASM_COMDAT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000499 writeUleb128(Sub.OS, Comdats.size(), "num comdats");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000500 for (const auto &C : Comdats) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000501 writeStr(Sub.OS, C.first, "comdat name");
502 writeUleb128(Sub.OS, 0, "comdat flags"); // flags for future use
503 writeUleb128(Sub.OS, C.second.size(), "num entries");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000504 for (const ComdatEntry &Entry : C.second) {
Sam Clegg8518e7d2018-03-01 18:06:39 +0000505 writeU8(Sub.OS, Entry.Kind, "entry kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000506 writeUleb128(Sub.OS, Entry.Index, "entry index");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000507 }
508 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000509 Sub.writeTo(OS);
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000510 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000511}
512
513// Create the custom "name" section containing debug symbol names.
514void Writer::createNameSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000515 unsigned NumNames = NumImportedFunctions;
Sam Clegg9f934222018-02-21 18:29:23 +0000516 for (const InputFunction *F : InputFunctions)
Sam Clegg1963d712018-01-17 20:19:04 +0000517 if (!F->getName().empty())
518 ++NumNames;
Sam Cleggc94d3932017-11-17 18:14:09 +0000519
Sam Clegg1963d712018-01-17 20:19:04 +0000520 if (NumNames == 0)
521 return;
Sam Clegg50686852018-01-12 18:35:13 +0000522
Sam Cleggc94d3932017-11-17 18:14:09 +0000523 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "name");
524
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000525 SubSection Sub(WASM_NAMES_FUNCTION);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000526 writeUleb128(Sub.OS, NumNames, "name count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000527
Sam Clegg93102972018-02-23 05:08:53 +0000528 // Names must appear in function index order. As it happens ImportedSymbols
529 // and InputFunctions are numbered in order with imported functions coming
Sam Clegg1963d712018-01-17 20:19:04 +0000530 // first.
Sam Clegg93102972018-02-23 05:08:53 +0000531 for (const Symbol *S : ImportedSymbols) {
532 if (!isa<FunctionSymbol>(S))
533 continue;
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000534 writeUleb128(Sub.OS, S->getOutputIndex(), "import index");
535 writeStr(Sub.OS, S->getName(), "symbol name");
Sam Cleggc94d3932017-11-17 18:14:09 +0000536 }
Sam Clegg9f934222018-02-21 18:29:23 +0000537 for (const InputFunction *F : InputFunctions) {
Sam Clegg1963d712018-01-17 20:19:04 +0000538 if (!F->getName().empty()) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000539 writeUleb128(Sub.OS, F->getOutputIndex(), "func index");
540 writeStr(Sub.OS, F->getName(), "symbol name");
Sam Clegg1963d712018-01-17 20:19:04 +0000541 }
542 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000543
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000544 Sub.writeTo(Section->getStream());
Sam Cleggc94d3932017-11-17 18:14:09 +0000545}
546
547void Writer::writeHeader() {
548 memcpy(Buffer->getBufferStart(), Header.data(), Header.size());
549}
550
551void Writer::writeSections() {
552 uint8_t *Buf = Buffer->getBufferStart();
553 parallelForEach(OutputSections, [Buf](OutputSection *S) { S->writeTo(Buf); });
554}
555
556// Fix the memory layout of the output binary. This assigns memory offsets
Sam Clegg49ed9262017-12-01 00:53:21 +0000557// to each of the input data sections as well as the explicit stack region.
Sam Cleggf0d433d2018-02-02 22:59:56 +0000558// The memory layout is as follows, from low to high.
559// - initialized data (starting at Config->GlobalBase)
560// - BSS data (not currently implemented in llvm)
561// - explicit stack (Config->ZStackSize)
562// - heap start / unallocated
Sam Cleggc94d3932017-11-17 18:14:09 +0000563void Writer::layoutMemory() {
564 uint32_t MemoryPtr = 0;
Sam Clegg99eb42c2018-02-27 23:58:03 +0000565 MemoryPtr = Config->GlobalBase;
566 debugPrint("mem: global base = %d\n", Config->GlobalBase);
Sam Cleggc94d3932017-11-17 18:14:09 +0000567
568 createOutputSegments();
569
Sam Cleggf0d433d2018-02-02 22:59:56 +0000570 // Arbitrarily set __dso_handle handle to point to the start of the data
571 // segments.
572 if (WasmSym::DsoHandle)
573 WasmSym::DsoHandle->setVirtualAddress(MemoryPtr);
574
Sam Cleggc94d3932017-11-17 18:14:09 +0000575 for (OutputSegment *Seg : Segments) {
576 MemoryPtr = alignTo(MemoryPtr, Seg->Alignment);
577 Seg->StartVA = MemoryPtr;
Sam Clegg7ed293e2018-01-12 00:34:04 +0000578 debugPrint("mem: %-15s offset=%-8d size=%-8d align=%d\n",
Sam Cleggc94d3932017-11-17 18:14:09 +0000579 Seg->Name.str().c_str(), MemoryPtr, Seg->Size, Seg->Alignment);
580 MemoryPtr += Seg->Size;
581 }
582
Sam Cleggf0d433d2018-02-02 22:59:56 +0000583 // TODO: Add .bss space here.
Sam Clegg37a4a8a2018-02-07 03:04:53 +0000584 if (WasmSym::DataEnd)
585 WasmSym::DataEnd->setVirtualAddress(MemoryPtr);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000586
Sam Clegg99eb42c2018-02-27 23:58:03 +0000587 debugPrint("mem: static data = %d\n", MemoryPtr - Config->GlobalBase);
Sam Cleggc94d3932017-11-17 18:14:09 +0000588
Sam Cleggf0d433d2018-02-02 22:59:56 +0000589 // Stack comes after static data and bss
Sam Cleggc94d3932017-11-17 18:14:09 +0000590 if (!Config->Relocatable) {
591 MemoryPtr = alignTo(MemoryPtr, kStackAlignment);
592 if (Config->ZStackSize != alignTo(Config->ZStackSize, kStackAlignment))
593 error("stack size must be " + Twine(kStackAlignment) + "-byte aligned");
594 debugPrint("mem: stack size = %d\n", Config->ZStackSize);
595 debugPrint("mem: stack base = %d\n", MemoryPtr);
596 MemoryPtr += Config->ZStackSize;
Sam Clegg93102972018-02-23 05:08:53 +0000597 WasmSym::StackPointer->Global->Global.InitExpr.Value.Int32 = MemoryPtr;
Sam Cleggc94d3932017-11-17 18:14:09 +0000598 debugPrint("mem: stack top = %d\n", MemoryPtr);
Sam Clegg93102972018-02-23 05:08:53 +0000599
Sam Clegg51bcdc22018-01-17 01:34:31 +0000600 // Set `__heap_base` to directly follow the end of the stack. We don't
601 // allocate any heap memory up front, but instead really on the malloc/brk
602 // implementation growing the memory at runtime.
Sam Cleggf0d433d2018-02-02 22:59:56 +0000603 WasmSym::HeapBase->setVirtualAddress(MemoryPtr);
Sam Clegg51bcdc22018-01-17 01:34:31 +0000604 debugPrint("mem: heap base = %d\n", MemoryPtr);
Sam Cleggc94d3932017-11-17 18:14:09 +0000605 }
606
607 uint32_t MemSize = alignTo(MemoryPtr, WasmPageSize);
608 NumMemoryPages = MemSize / WasmPageSize;
609 debugPrint("mem: total pages = %d\n", NumMemoryPages);
610}
611
612SyntheticSection *Writer::createSyntheticSection(uint32_t Type,
Sam Cleggc375e4e2018-01-10 19:18:22 +0000613 StringRef Name) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000614 auto Sec = make<SyntheticSection>(Type, Name);
Sam Cleggab2ac292017-12-20 05:14:48 +0000615 log("createSection: " + toString(*Sec));
Sam Cleggc94d3932017-11-17 18:14:09 +0000616 OutputSections.push_back(Sec);
617 return Sec;
618}
619
620void Writer::createSections() {
621 // Known sections
622 createTypeSection();
623 createImportSection();
624 createFunctionSection();
625 createTableSection();
626 createMemorySection();
627 createGlobalSection();
628 createExportSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000629 createElemSection();
630 createCodeSection();
631 createDataSection();
632
633 // Custom sections
Sam Clegg99eb42c2018-02-27 23:58:03 +0000634 if (Config->Relocatable) {
Sam Clegg99eb42c2018-02-27 23:58:03 +0000635 createLinkingSection();
Nicholas Wilson94d3b162018-03-05 12:33:58 +0000636 createRelocSections();
Sam Clegg99eb42c2018-02-27 23:58:03 +0000637 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000638 if (!Config->StripDebug && !Config->StripAll)
639 createNameSection();
640
641 for (OutputSection *S : OutputSections) {
642 S->setOffset(FileSize);
643 S->finalizeContents();
644 FileSize += S->getSize();
645 }
646}
647
Sam Cleggc94d3932017-11-17 18:14:09 +0000648void Writer::calculateImports() {
Sam Clegg574d7ce2017-12-15 19:23:49 +0000649 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000650 if (!Sym->isUndefined())
651 continue;
652 if (isa<DataSymbol>(Sym))
653 continue;
654 if (Sym->isWeak() && !Config->Relocatable)
Sam Clegg574d7ce2017-12-15 19:23:49 +0000655 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000656
Sam Clegg93102972018-02-23 05:08:53 +0000657 DEBUG(dbgs() << "import: " << Sym->getName() << "\n");
658 Sym->setOutputIndex(ImportedSymbols.size());
659 ImportedSymbols.emplace_back(Sym);
660 if (isa<FunctionSymbol>(Sym))
661 ++NumImportedFunctions;
662 else
663 ++NumImportedGlobals;
Sam Cleggc94d3932017-11-17 18:14:09 +0000664 }
665}
666
Sam Cleggd3052d52018-01-18 23:40:49 +0000667void Writer::calculateExports() {
Sam Clegg93102972018-02-23 05:08:53 +0000668 if (Config->Relocatable)
669 return;
Sam Cleggf0d433d2018-02-02 22:59:56 +0000670
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000671 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000672 if (!Sym->isDefined())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000673 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000674 if (Sym->isHidden() || Sym->isLocal())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000675 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000676 if (!Sym->isLive())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000677 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000678
679 DEBUG(dbgs() << "exporting sym: " << Sym->getName() << "\n");
680
Nicholas Wilsonf2f6d5e2018-03-02 14:51:36 +0000681 if (auto *D = dyn_cast<DefinedData>(Sym))
Sam Clegg93102972018-02-23 05:08:53 +0000682 DefinedFakeGlobals.emplace_back(D);
Sam Clegg93102972018-02-23 05:08:53 +0000683 ExportedSymbols.emplace_back(Sym);
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000684 }
Sam Clegg93102972018-02-23 05:08:53 +0000685}
686
687void Writer::assignSymtab() {
688 if (!Config->Relocatable)
689 return;
690
691 unsigned SymbolIndex = SymtabEntries.size();
Sam Cleggd3052d52018-01-18 23:40:49 +0000692 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg93102972018-02-23 05:08:53 +0000693 DEBUG(dbgs() << "Symtab entries: " << File->getName() << "\n");
Sam Cleggd3052d52018-01-18 23:40:49 +0000694 for (Symbol *Sym : File->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000695 if (Sym->getFile() != File)
Sam Cleggd3052d52018-01-18 23:40:49 +0000696 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000697 if (!Sym->isLive())
698 return;
699 Sym->setOutputSymbolIndex(SymbolIndex++);
700 SymtabEntries.emplace_back(Sym);
Sam Cleggd3052d52018-01-18 23:40:49 +0000701 }
702 }
703
Sam Clegg93102972018-02-23 05:08:53 +0000704 // For the moment, relocatable output doesn't contain any synthetic functions,
705 // so no need to look through the Symtab for symbols not referenced by
706 // Symtab->ObjectFiles.
Sam Cleggd3052d52018-01-18 23:40:49 +0000707}
708
Sam Cleggc375e4e2018-01-10 19:18:22 +0000709uint32_t Writer::lookupType(const WasmSignature &Sig) {
Sam Clegg8d027d62018-01-10 20:12:26 +0000710 auto It = TypeIndices.find(Sig);
711 if (It == TypeIndices.end()) {
Sam Cleggc375e4e2018-01-10 19:18:22 +0000712 error("type not found: " + toString(Sig));
Sam Clegg8d027d62018-01-10 20:12:26 +0000713 return 0;
714 }
715 return It->second;
Sam Cleggc375e4e2018-01-10 19:18:22 +0000716}
717
718uint32_t Writer::registerType(const WasmSignature &Sig) {
Sam Cleggb8621592017-11-30 01:40:08 +0000719 auto Pair = TypeIndices.insert(std::make_pair(Sig, Types.size()));
Sam Cleggc375e4e2018-01-10 19:18:22 +0000720 if (Pair.second) {
721 DEBUG(dbgs() << "type " << toString(Sig) << "\n");
Sam Cleggb8621592017-11-30 01:40:08 +0000722 Types.push_back(&Sig);
Sam Cleggc375e4e2018-01-10 19:18:22 +0000723 }
Sam Cleggb8621592017-11-30 01:40:08 +0000724 return Pair.first->second;
725}
726
Sam Cleggc94d3932017-11-17 18:14:09 +0000727void Writer::calculateTypes() {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000728 // The output type section is the union of the following sets:
729 // 1. Any signature used in the TYPE relocation
730 // 2. The signatures of all imported functions
731 // 3. The signatures of all defined functions
732
Sam Cleggc94d3932017-11-17 18:14:09 +0000733 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000734 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
735 for (uint32_t I = 0; I < Types.size(); I++)
736 if (File->TypeIsUsed[I])
737 File->TypeMap[I] = registerType(Types[I]);
Sam Cleggc94d3932017-11-17 18:14:09 +0000738 }
Sam Clegg50686852018-01-12 18:35:13 +0000739
Sam Clegg93102972018-02-23 05:08:53 +0000740 for (const Symbol *Sym : ImportedSymbols)
741 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
742 registerType(*F->getFunctionType());
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000743
Sam Clegg9f934222018-02-21 18:29:23 +0000744 for (const InputFunction *F : InputFunctions)
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000745 registerType(F->Signature);
Sam Cleggc94d3932017-11-17 18:14:09 +0000746}
747
Sam Clegg8d146bb2018-01-09 23:56:44 +0000748void Writer::assignIndexes() {
Sam Clegg93102972018-02-23 05:08:53 +0000749 uint32_t FunctionIndex = NumImportedFunctions + InputFunctions.size();
Sam Clegg87e61922018-01-08 23:39:11 +0000750 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8d146bb2018-01-09 23:56:44 +0000751 DEBUG(dbgs() << "Functions: " << File->getName() << "\n");
752 for (InputFunction *Func : File->Functions) {
Sam Clegg447ae402018-02-13 20:29:38 +0000753 if (!Func->Live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000754 continue;
Sam Clegg9f934222018-02-21 18:29:23 +0000755 InputFunctions.emplace_back(Func);
Sam Clegg8d146bb2018-01-09 23:56:44 +0000756 Func->setOutputIndex(FunctionIndex++);
757 }
758 }
759
Sam Clegg93102972018-02-23 05:08:53 +0000760 uint32_t TableIndex = kInitialTableOffset;
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000761 auto HandleRelocs = [&](InputChunk *Chunk) {
762 if (!Chunk->Live)
763 return;
764 ObjFile *File = Chunk->File;
765 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
Sam Clegg93102972018-02-23 05:08:53 +0000766 for (const WasmRelocation &Reloc : Chunk->getRelocations()) {
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000767 if (Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_I32 ||
768 Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_SLEB) {
769 FunctionSymbol *Sym = File->getFunctionSymbol(Reloc.Index);
770 if (Sym->hasTableIndex() || !Sym->hasOutputIndex())
771 continue;
772 Sym->setTableIndex(TableIndex++);
773 IndirectFunctions.emplace_back(Sym);
774 } else if (Reloc.Type == R_WEBASSEMBLY_TYPE_INDEX_LEB) {
Sam Clegg93102972018-02-23 05:08:53 +0000775 // Mark target type as live
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000776 File->TypeMap[Reloc.Index] = registerType(Types[Reloc.Index]);
777 File->TypeIsUsed[Reloc.Index] = true;
Sam Clegg93102972018-02-23 05:08:53 +0000778 } else if (Reloc.Type == R_WEBASSEMBLY_GLOBAL_INDEX_LEB) {
779 // Mark target global as live
780 GlobalSymbol *Sym = File->getGlobalSymbol(Reloc.Index);
781 if (auto *G = dyn_cast<DefinedGlobal>(Sym)) {
782 DEBUG(dbgs() << "marking global live: " << Sym->getName() << "\n");
783 G->Global->Live = true;
784 }
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000785 }
786 }
787 };
788
Sam Clegg8d146bb2018-01-09 23:56:44 +0000789 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000790 DEBUG(dbgs() << "Handle relocs: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000791 for (InputChunk *Chunk : File->Functions)
792 HandleRelocs(Chunk);
793 for (InputChunk *Chunk : File->Segments)
794 HandleRelocs(Chunk);
795 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000796
Sam Clegg93102972018-02-23 05:08:53 +0000797 uint32_t GlobalIndex = NumImportedGlobals + InputGlobals.size();
798 auto AddDefinedGlobal = [&](InputGlobal *Global) {
799 if (Global->Live) {
800 DEBUG(dbgs() << "AddDefinedGlobal: " << GlobalIndex << "\n");
801 Global->setOutputIndex(GlobalIndex++);
802 InputGlobals.push_back(Global);
803 }
804 };
805
806 if (WasmSym::StackPointer)
807 AddDefinedGlobal(WasmSym::StackPointer->Global);
808
809 for (ObjFile *File : Symtab->ObjectFiles) {
810 DEBUG(dbgs() << "Globals: " << File->getName() << "\n");
811 for (InputGlobal *Global : File->Globals)
812 AddDefinedGlobal(Global);
Sam Cleggc94d3932017-11-17 18:14:09 +0000813 }
814}
815
816static StringRef getOutputDataSegmentName(StringRef Name) {
817 if (Config->Relocatable)
818 return Name;
Rui Ueyama4764b572018-02-28 00:57:28 +0000819 if (Name.startswith(".text."))
820 return ".text";
821 if (Name.startswith(".data."))
822 return ".data";
823 if (Name.startswith(".bss."))
824 return ".bss";
Sam Cleggc94d3932017-11-17 18:14:09 +0000825 return Name;
826}
827
828void Writer::createOutputSegments() {
829 for (ObjFile *File : Symtab->ObjectFiles) {
830 for (InputSegment *Segment : File->Segments) {
Sam Clegg447ae402018-02-13 20:29:38 +0000831 if (!Segment->Live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000832 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000833 StringRef Name = getOutputDataSegmentName(Segment->getName());
834 OutputSegment *&S = SegmentMap[Name];
835 if (S == nullptr) {
836 DEBUG(dbgs() << "new segment: " << Name << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000837 S = make<OutputSegment>(Name, Segments.size());
Sam Cleggc94d3932017-11-17 18:14:09 +0000838 Segments.push_back(S);
839 }
840 S->addInputSegment(Segment);
841 DEBUG(dbgs() << "added data: " << Name << ": " << S->Size << "\n");
Sam Cleggc94d3932017-11-17 18:14:09 +0000842 }
843 }
844}
845
Sam Clegg50686852018-01-12 18:35:13 +0000846static const int OPCODE_CALL = 0x10;
847static const int OPCODE_END = 0xb;
848
849// Create synthetic "__wasm_call_ctors" function based on ctor functions
850// in input object.
851void Writer::createCtorFunction() {
Sam Clegg93102972018-02-23 05:08:53 +0000852 uint32_t FunctionIndex = NumImportedFunctions + InputFunctions.size();
Sam Cleggf0d433d2018-02-02 22:59:56 +0000853 WasmSym::CallCtors->setOutputIndex(FunctionIndex);
Sam Clegg50686852018-01-12 18:35:13 +0000854
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000855 // First write the body's contents to a string.
856 std::string BodyContent;
Sam Clegg50686852018-01-12 18:35:13 +0000857 {
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000858 raw_string_ostream OS(BodyContent);
Sam Clegg50686852018-01-12 18:35:13 +0000859 writeUleb128(OS, 0, "num locals");
Sam Clegg93102972018-02-23 05:08:53 +0000860 for (const WasmInitEntry &F : InitFunctions) {
Sam Clegg50686852018-01-12 18:35:13 +0000861 writeU8(OS, OPCODE_CALL, "CALL");
Sam Clegg93102972018-02-23 05:08:53 +0000862 writeUleb128(OS, F.Sym->getOutputIndex(), "function index");
Sam Clegg50686852018-01-12 18:35:13 +0000863 }
864 writeU8(OS, OPCODE_END, "END");
865 }
866
867 // Once we know the size of the body we can create the final function body
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000868 std::string FunctionBody;
869 {
870 raw_string_ostream OS(FunctionBody);
871 writeUleb128(OS, BodyContent.size(), "function size");
872 OS << BodyContent;
873 }
Rui Ueyama29abfe42018-02-28 17:43:15 +0000874
875 const WasmSignature *Sig = WasmSym::CallCtors->getFunctionType();
876 SyntheticFunction *F = make<SyntheticFunction>(
Nicholas Wilson8269f372018-03-07 10:37:50 +0000877 *Sig, toArrayRef(Saver.save(FunctionBody)),
878 WasmSym::CallCtors->getName());
Rui Ueyama29abfe42018-02-28 17:43:15 +0000879
Sam Clegg011dce22018-02-21 18:37:44 +0000880 F->setOutputIndex(FunctionIndex);
Sam Clegg93102972018-02-23 05:08:53 +0000881 F->Live = true;
882 WasmSym::CallCtors->Function = F;
Sam Clegg011dce22018-02-21 18:37:44 +0000883 InputFunctions.emplace_back(F);
Sam Clegg50686852018-01-12 18:35:13 +0000884}
885
886// Populate InitFunctions vector with init functions from all input objects.
887// This is then used either when creating the output linking section or to
888// synthesize the "__wasm_call_ctors" function.
889void Writer::calculateInitFunctions() {
890 for (ObjFile *File : Symtab->ObjectFiles) {
891 const WasmLinkingData &L = File->getWasmObj()->linkingData();
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +0000892 for (const WasmInitFunc &F : L.InitFunctions) {
893 FunctionSymbol *Sym = File->getFunctionSymbol(F.Symbol);
894 if (*Sym->getFunctionType() != WasmSignature{{}, WASM_TYPE_NORESULT})
895 error("invalid signature for init func: " + toString(*Sym));
896 InitFunctions.emplace_back(WasmInitEntry{Sym, F.Priority});
897 }
Sam Clegg50686852018-01-12 18:35:13 +0000898 }
Rui Ueyamada69b712018-02-28 00:15:59 +0000899
Sam Clegg50686852018-01-12 18:35:13 +0000900 // Sort in order of priority (lowest first) so that they are called
901 // in the correct order.
Sam Clegg29b8feb2018-02-21 00:34:34 +0000902 std::stable_sort(InitFunctions.begin(), InitFunctions.end(),
Sam Clegg93102972018-02-23 05:08:53 +0000903 [](const WasmInitEntry &L, const WasmInitEntry &R) {
Sam Clegg29b8feb2018-02-21 00:34:34 +0000904 return L.Priority < R.Priority;
905 });
Sam Clegg50686852018-01-12 18:35:13 +0000906}
907
Sam Cleggc94d3932017-11-17 18:14:09 +0000908void Writer::run() {
Sam Clegg99eb42c2018-02-27 23:58:03 +0000909 if (Config->Relocatable)
910 Config->GlobalBase = 0;
911
Sam Cleggc94d3932017-11-17 18:14:09 +0000912 log("-- calculateImports");
913 calculateImports();
Sam Clegg8d146bb2018-01-09 23:56:44 +0000914 log("-- assignIndexes");
915 assignIndexes();
Sam Clegg50686852018-01-12 18:35:13 +0000916 log("-- calculateInitFunctions");
917 calculateInitFunctions();
918 if (!Config->Relocatable)
919 createCtorFunction();
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000920 log("-- calculateTypes");
921 calculateTypes();
Sam Clegg93102972018-02-23 05:08:53 +0000922 log("-- layoutMemory");
923 layoutMemory();
924 log("-- calculateExports");
925 calculateExports();
926 log("-- assignSymtab");
927 assignSymtab();
Sam Cleggc94d3932017-11-17 18:14:09 +0000928
929 if (errorHandler().Verbose) {
Sam Clegg9f934222018-02-21 18:29:23 +0000930 log("Defined Functions: " + Twine(InputFunctions.size()));
Sam Clegg93102972018-02-23 05:08:53 +0000931 log("Defined Globals : " + Twine(InputGlobals.size()));
932 log("Function Imports : " + Twine(NumImportedFunctions));
933 log("Global Imports : " + Twine(NumImportedGlobals));
Sam Cleggc94d3932017-11-17 18:14:09 +0000934 for (ObjFile *File : Symtab->ObjectFiles)
935 File->dumpInfo();
936 }
937
Sam Cleggc94d3932017-11-17 18:14:09 +0000938 createHeader();
939 log("-- createSections");
940 createSections();
941
942 log("-- openFile");
943 openFile();
944 if (errorCount())
945 return;
946
947 writeHeader();
948
949 log("-- writeSections");
950 writeSections();
951 if (errorCount())
952 return;
953
954 if (Error E = Buffer->commit())
955 fatal("failed to write the output file: " + toString(std::move(E)));
956}
957
958// Open a result file.
959void Writer::openFile() {
960 log("writing: " + Config->OutputFile);
Sam Cleggc94d3932017-11-17 18:14:09 +0000961
962 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
963 FileOutputBuffer::create(Config->OutputFile, FileSize,
964 FileOutputBuffer::F_executable);
965
966 if (!BufferOrErr)
967 error("failed to open " + Config->OutputFile + ": " +
968 toString(BufferOrErr.takeError()));
969 else
970 Buffer = std::move(*BufferOrErr);
971}
972
973void Writer::createHeader() {
974 raw_string_ostream OS(Header);
975 writeBytes(OS, WasmMagic, sizeof(WasmMagic), "wasm magic");
976 writeU32(OS, WasmVersion, "wasm version");
977 OS.flush();
978 FileSize += Header.size();
979}
980
981void lld::wasm::writeResult() { Writer().run(); }