blob: 5043ebdef0df0ab16d19c806ea1d733930c1d267 [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"
Nicholas Wilson3e3f5fb2018-03-14 15:58:16 +000024#include "llvm/Object/WasmTraits.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000025#include "llvm/Support/FileOutputBuffer.h"
26#include "llvm/Support/Format.h"
27#include "llvm/Support/FormatVariadic.h"
28#include "llvm/Support/LEB128.h"
29
30#include <cstdarg>
Sam Clegge0f6fcd2018-01-12 22:25:17 +000031#include <map>
Sam Cleggc94d3932017-11-17 18:14:09 +000032
33#define DEBUG_TYPE "lld"
34
35using namespace llvm;
36using namespace llvm::wasm;
37using namespace lld;
38using namespace lld::wasm;
39
40static constexpr int kStackAlignment = 16;
Sam Clegg48bbd632018-01-24 21:37:30 +000041static constexpr int kInitialTableOffset = 1;
Sam Cleggc94d3932017-11-17 18:14:09 +000042
43namespace {
44
Sam Clegg93102972018-02-23 05:08:53 +000045// An init entry to be written to either the synthetic init func or the
46// linking metadata.
47struct WasmInitEntry {
Sam Clegge3f3ccf2018-03-12 19:56:23 +000048 const FunctionSymbol *Sym;
Sam Clegg93102972018-02-23 05:08:53 +000049 uint32_t Priority;
Sam Cleggd3052d52018-01-18 23:40:49 +000050};
51
Sam Cleggc94d3932017-11-17 18:14:09 +000052// The writer writes a SymbolTable result to a file.
53class Writer {
54public:
55 void run();
56
57private:
58 void openFile();
59
Sam Cleggc375e4e2018-01-10 19:18:22 +000060 uint32_t lookupType(const WasmSignature &Sig);
61 uint32_t registerType(const WasmSignature &Sig);
Sam Clegg93102972018-02-23 05:08:53 +000062
Sam Clegg50686852018-01-12 18:35:13 +000063 void createCtorFunction();
64 void calculateInitFunctions();
Sam Clegg8d146bb2018-01-09 23:56:44 +000065 void assignIndexes();
Sam Cleggc94d3932017-11-17 18:14:09 +000066 void calculateImports();
Sam Cleggd3052d52018-01-18 23:40:49 +000067 void calculateExports();
Sam Clegg93102972018-02-23 05:08:53 +000068 void assignSymtab();
Sam Cleggc94d3932017-11-17 18:14:09 +000069 void calculateTypes();
70 void createOutputSegments();
71 void layoutMemory();
72 void createHeader();
73 void createSections();
Nicholas Wilsondbd90bf2018-03-07 13:28:16 +000074 SyntheticSection *createSyntheticSection(uint32_t Type, StringRef Name = "");
Sam Cleggc94d3932017-11-17 18:14:09 +000075
76 // Builtin sections
77 void createTypeSection();
78 void createFunctionSection();
79 void createTableSection();
80 void createGlobalSection();
81 void createExportSection();
82 void createImportSection();
83 void createMemorySection();
84 void createElemSection();
Sam Cleggc94d3932017-11-17 18:14:09 +000085 void createCodeSection();
86 void createDataSection();
87
88 // Custom sections
89 void createRelocSections();
90 void createLinkingSection();
91 void createNameSection();
92
93 void writeHeader();
94 void writeSections();
95
96 uint64_t FileSize = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +000097 uint32_t NumMemoryPages = 0;
Nicholas Wilson2eb39c12018-03-14 13:53:58 +000098 uint32_t MaxMemoryPages = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +000099
100 std::vector<const WasmSignature *> Types;
Nicholas Wilson3e3f5fb2018-03-14 15:58:16 +0000101 DenseMap<WasmSignature, int32_t> TypeIndices;
Sam Clegg93102972018-02-23 05:08:53 +0000102 std::vector<const Symbol *> ImportedSymbols;
103 unsigned NumImportedFunctions = 0;
104 unsigned NumImportedGlobals = 0;
105 std::vector<Symbol *> ExportedSymbols;
106 std::vector<const DefinedData *> DefinedFakeGlobals;
107 std::vector<InputGlobal *> InputGlobals;
Sam Clegg9f934222018-02-21 18:29:23 +0000108 std::vector<InputFunction *> InputFunctions;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000109 std::vector<const FunctionSymbol *> IndirectFunctions;
Sam Clegg93102972018-02-23 05:08:53 +0000110 std::vector<const Symbol *> SymtabEntries;
111 std::vector<WasmInitEntry> InitFunctions;
Sam Cleggc94d3932017-11-17 18:14:09 +0000112
113 // Elements that are used to construct the final output
114 std::string Header;
115 std::vector<OutputSection *> OutputSections;
116
117 std::unique_ptr<FileOutputBuffer> Buffer;
118
119 std::vector<OutputSegment *> Segments;
120 llvm::SmallDenseMap<StringRef, OutputSegment *> SegmentMap;
121};
122
123} // anonymous namespace
124
Sam Cleggc94d3932017-11-17 18:14:09 +0000125void Writer::createImportSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000126 uint32_t NumImports = ImportedSymbols.size();
Sam Cleggc94d3932017-11-17 18:14:09 +0000127 if (Config->ImportMemory)
128 ++NumImports;
129
130 if (NumImports == 0)
131 return;
132
133 SyntheticSection *Section = createSyntheticSection(WASM_SEC_IMPORT);
134 raw_ostream &OS = Section->getStream();
135
136 writeUleb128(OS, NumImports, "import count");
137
Sam Cleggc94d3932017-11-17 18:14:09 +0000138 if (Config->ImportMemory) {
139 WasmImport Import;
140 Import.Module = "env";
141 Import.Field = "memory";
142 Import.Kind = WASM_EXTERNAL_MEMORY;
143 Import.Memory.Flags = 0;
144 Import.Memory.Initial = NumMemoryPages;
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000145 if (MaxMemoryPages != 0) {
146 Import.Memory.Flags |= WASM_LIMITS_FLAG_HAS_MAX;
147 Import.Memory.Maximum = MaxMemoryPages;
148 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000149 writeImport(OS, Import);
150 }
151
Sam Clegg93102972018-02-23 05:08:53 +0000152 for (const Symbol *Sym : ImportedSymbols) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000153 WasmImport Import;
154 Import.Module = "env";
155 Import.Field = Sym->getName();
Sam Clegg93102972018-02-23 05:08:53 +0000156 if (auto *FunctionSym = dyn_cast<FunctionSymbol>(Sym)) {
157 Import.Kind = WASM_EXTERNAL_FUNCTION;
158 Import.SigIndex = lookupType(*FunctionSym->getFunctionType());
159 } else {
160 auto *GlobalSym = cast<GlobalSymbol>(Sym);
161 Import.Kind = WASM_EXTERNAL_GLOBAL;
162 Import.Global = *GlobalSym->getGlobalType();
163 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000164 writeImport(OS, Import);
165 }
166}
167
168void Writer::createTypeSection() {
169 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TYPE);
170 raw_ostream &OS = Section->getStream();
171 writeUleb128(OS, Types.size(), "type count");
Sam Cleggd451da12017-12-19 19:56:27 +0000172 for (const WasmSignature *Sig : Types)
Sam Cleggc94d3932017-11-17 18:14:09 +0000173 writeSig(OS, *Sig);
Sam Cleggc94d3932017-11-17 18:14:09 +0000174}
175
176void Writer::createFunctionSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000177 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000178 return;
179
180 SyntheticSection *Section = createSyntheticSection(WASM_SEC_FUNCTION);
181 raw_ostream &OS = Section->getStream();
182
Sam Clegg9f934222018-02-21 18:29:23 +0000183 writeUleb128(OS, InputFunctions.size(), "function count");
184 for (const InputFunction *Func : InputFunctions)
Sam Cleggc375e4e2018-01-10 19:18:22 +0000185 writeUleb128(OS, lookupType(Func->Signature), "sig index");
Sam Cleggc94d3932017-11-17 18:14:09 +0000186}
187
188void Writer::createMemorySection() {
189 if (Config->ImportMemory)
190 return;
191
192 SyntheticSection *Section = createSyntheticSection(WASM_SEC_MEMORY);
193 raw_ostream &OS = Section->getStream();
194
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000195 bool HasMax = MaxMemoryPages != 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000196 writeUleb128(OS, 1, "memory count");
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000197 writeUleb128(OS, HasMax ? WASM_LIMITS_FLAG_HAS_MAX : 0, "memory limits flags");
Sam Cleggc94d3932017-11-17 18:14:09 +0000198 writeUleb128(OS, NumMemoryPages, "initial pages");
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000199 if (HasMax)
200 writeUleb128(OS, MaxMemoryPages, "max pages");
Sam Cleggc94d3932017-11-17 18:14:09 +0000201}
202
203void Writer::createGlobalSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000204 unsigned NumGlobals = InputGlobals.size() + DefinedFakeGlobals.size();
205 if (NumGlobals == 0)
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000206 return;
207
Sam Cleggc94d3932017-11-17 18:14:09 +0000208 SyntheticSection *Section = createSyntheticSection(WASM_SEC_GLOBAL);
209 raw_ostream &OS = Section->getStream();
210
Sam Clegg93102972018-02-23 05:08:53 +0000211 writeUleb128(OS, NumGlobals, "global count");
212 for (const InputGlobal *G : InputGlobals)
213 writeGlobal(OS, G->Global);
214 for (const DefinedData *Sym : DefinedFakeGlobals) {
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000215 WasmGlobal Global;
Sam Clegg93102972018-02-23 05:08:53 +0000216 Global.Type = {WASM_TYPE_I32, false};
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000217 Global.InitExpr.Opcode = WASM_OPCODE_I32_CONST;
218 Global.InitExpr.Value.Int32 = Sym->getVirtualAddress();
Sam Cleggc94d3932017-11-17 18:14:09 +0000219 writeGlobal(OS, Global);
220 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000221}
222
223void Writer::createTableSection() {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000224 // Always output a table section, even if there are no indirect calls.
225 // There are two reasons for this:
226 // 1. For executables it is useful to have an empty table slot at 0
227 // which can be filled with a null function call handler.
228 // 2. If we don't do this, any program that contains a call_indirect but
229 // no address-taken function will fail at validation time since it is
230 // a validation error to include a call_indirect instruction if there
231 // is not table.
Sam Clegg48bbd632018-01-24 21:37:30 +0000232 uint32_t TableSize = kInitialTableOffset + IndirectFunctions.size();
Sam Cleggfc1a9122017-12-11 22:00:56 +0000233
Sam Cleggc94d3932017-11-17 18:14:09 +0000234 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TABLE);
235 raw_ostream &OS = Section->getStream();
236
237 writeUleb128(OS, 1, "table count");
Sam Clegg8518e7d2018-03-01 18:06:39 +0000238 writeU8(OS, WASM_TYPE_ANYFUNC, "table type");
Sam Cleggc94d3932017-11-17 18:14:09 +0000239 writeUleb128(OS, WASM_LIMITS_FLAG_HAS_MAX, "table flags");
Sam Cleggfc1a9122017-12-11 22:00:56 +0000240 writeUleb128(OS, TableSize, "table initial size");
241 writeUleb128(OS, TableSize, "table max size");
Sam Cleggc94d3932017-11-17 18:14:09 +0000242}
243
244void Writer::createExportSection() {
Sam Cleggc94d3932017-11-17 18:14:09 +0000245 bool ExportMemory = !Config->Relocatable && !Config->ImportMemory;
Sam Cleggc94d3932017-11-17 18:14:09 +0000246
Sam Cleggd3052d52018-01-18 23:40:49 +0000247 uint32_t NumExports = (ExportMemory ? 1 : 0) + ExportedSymbols.size();
Sam Cleggc94d3932017-11-17 18:14:09 +0000248 if (!NumExports)
249 return;
250
251 SyntheticSection *Section = createSyntheticSection(WASM_SEC_EXPORT);
252 raw_ostream &OS = Section->getStream();
253
254 writeUleb128(OS, NumExports, "export count");
255
Rui Ueyama7d696882018-02-28 00:18:34 +0000256 if (ExportMemory)
257 writeExport(OS, {"memory", WASM_EXTERNAL_MEMORY, 0});
Sam Cleggc94d3932017-11-17 18:14:09 +0000258
Sam Clegg93102972018-02-23 05:08:53 +0000259 unsigned FakeGlobalIndex = NumImportedGlobals + InputGlobals.size();
Rui Ueyama7d696882018-02-28 00:18:34 +0000260
Sam Clegg93102972018-02-23 05:08:53 +0000261 for (const Symbol *Sym : ExportedSymbols) {
Rui Ueyama7d696882018-02-28 00:18:34 +0000262 StringRef Name = Sym->getName();
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000263 WasmExport Export;
Rui Ueyama7d696882018-02-28 00:18:34 +0000264 DEBUG(dbgs() << "Export: " << Name << "\n");
265
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000266 if (auto *F = dyn_cast<DefinedFunction>(Sym))
267 Export = {Name, WASM_EXTERNAL_FUNCTION, F->getFunctionIndex()};
268 else if (auto *G = dyn_cast<DefinedGlobal>(Sym))
269 Export = {Name, WASM_EXTERNAL_GLOBAL, G->getGlobalIndex()};
Rui Ueyama7d696882018-02-28 00:18:34 +0000270 else if (isa<DefinedData>(Sym))
271 Export = {Name, WASM_EXTERNAL_GLOBAL, FakeGlobalIndex++};
272 else
Sam Clegg93102972018-02-23 05:08:53 +0000273 llvm_unreachable("unexpected symbol type");
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000274 writeExport(OS, Export);
Sam Cleggc94d3932017-11-17 18:14:09 +0000275 }
276}
277
Sam Cleggc94d3932017-11-17 18:14:09 +0000278void Writer::createElemSection() {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000279 if (IndirectFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000280 return;
281
282 SyntheticSection *Section = createSyntheticSection(WASM_SEC_ELEM);
283 raw_ostream &OS = Section->getStream();
284
285 writeUleb128(OS, 1, "segment count");
286 writeUleb128(OS, 0, "table index");
287 WasmInitExpr InitExpr;
288 InitExpr.Opcode = WASM_OPCODE_I32_CONST;
Sam Clegg48bbd632018-01-24 21:37:30 +0000289 InitExpr.Value.Int32 = kInitialTableOffset;
Sam Cleggc94d3932017-11-17 18:14:09 +0000290 writeInitExpr(OS, InitExpr);
Sam Cleggfc1a9122017-12-11 22:00:56 +0000291 writeUleb128(OS, IndirectFunctions.size(), "elem count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000292
Sam Clegg48bbd632018-01-24 21:37:30 +0000293 uint32_t TableIndex = kInitialTableOffset;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000294 for (const FunctionSymbol *Sym : IndirectFunctions) {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000295 assert(Sym->getTableIndex() == TableIndex);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000296 writeUleb128(OS, Sym->getFunctionIndex(), "function index");
Sam Cleggfc1a9122017-12-11 22:00:56 +0000297 ++TableIndex;
298 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000299}
300
301void Writer::createCodeSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000302 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000303 return;
304
305 log("createCodeSection");
306
Sam Clegg9f934222018-02-21 18:29:23 +0000307 auto Section = make<CodeSection>(InputFunctions);
Sam Cleggc94d3932017-11-17 18:14:09 +0000308 OutputSections.push_back(Section);
309}
310
311void Writer::createDataSection() {
312 if (!Segments.size())
313 return;
314
315 log("createDataSection");
316 auto Section = make<DataSection>(Segments);
317 OutputSections.push_back(Section);
318}
319
Sam Cleggd451da12017-12-19 19:56:27 +0000320// Create relocations sections in the final output.
Sam Cleggc94d3932017-11-17 18:14:09 +0000321// These are only created when relocatable output is requested.
322void Writer::createRelocSections() {
323 log("createRelocSections");
324 // Don't use iterator here since we are adding to OutputSection
325 size_t OrigSize = OutputSections.size();
326 for (size_t i = 0; i < OrigSize; i++) {
Rui Ueyama37254062018-02-28 00:01:31 +0000327 OutputSection *OSec = OutputSections[i];
328 uint32_t Count = OSec->numRelocations();
Sam Cleggc94d3932017-11-17 18:14:09 +0000329 if (!Count)
330 continue;
331
Rui Ueyama37254062018-02-28 00:01:31 +0000332 StringRef Name;
333 if (OSec->Type == WASM_SEC_DATA)
334 Name = "reloc.DATA";
335 else if (OSec->Type == WASM_SEC_CODE)
336 Name = "reloc.CODE";
Sam Cleggc94d3932017-11-17 18:14:09 +0000337 else
Sam Cleggd451da12017-12-19 19:56:27 +0000338 llvm_unreachable("relocations only supported for code and data");
Sam Cleggc94d3932017-11-17 18:14:09 +0000339
Rui Ueyama37254062018-02-28 00:01:31 +0000340 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, Name);
Sam Cleggc94d3932017-11-17 18:14:09 +0000341 raw_ostream &OS = Section->getStream();
Rui Ueyama37254062018-02-28 00:01:31 +0000342 writeUleb128(OS, OSec->Type, "reloc section");
Sam Cleggc94d3932017-11-17 18:14:09 +0000343 writeUleb128(OS, Count, "reloc count");
Rui Ueyama37254062018-02-28 00:01:31 +0000344 OSec->writeRelocations(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000345 }
346}
347
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000348static uint32_t getWasmFlags(const Symbol *Sym) {
349 uint32_t Flags = 0;
350 if (Sym->isLocal())
351 Flags |= WASM_SYMBOL_BINDING_LOCAL;
352 if (Sym->isWeak())
353 Flags |= WASM_SYMBOL_BINDING_WEAK;
354 if (Sym->isHidden())
355 Flags |= WASM_SYMBOL_VISIBILITY_HIDDEN;
356 if (Sym->isUndefined())
357 Flags |= WASM_SYMBOL_UNDEFINED;
358 return Flags;
359}
360
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000361// Some synthetic sections (e.g. "name" and "linking") have subsections.
362// Just like the synthetic sections themselves these need to be created before
363// they can be written out (since they are preceded by their length). This
364// class is used to create subsections and then write them into the stream
365// of the parent section.
366class SubSection {
367public:
368 explicit SubSection(uint32_t Type) : Type(Type) {}
369
370 void writeTo(raw_ostream &To) {
371 OS.flush();
Rui Ueyama67769102018-02-28 03:38:14 +0000372 writeUleb128(To, Type, "subsection type");
373 writeUleb128(To, Body.size(), "subsection size");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000374 To.write(Body.data(), Body.size());
375 }
376
377private:
378 uint32_t Type;
379 std::string Body;
380
381public:
382 raw_string_ostream OS{Body};
383};
384
Sam Clegg49ed9262017-12-01 00:53:21 +0000385// Create the custom "linking" section containing linker metadata.
Sam Cleggc94d3932017-11-17 18:14:09 +0000386// This is only created when relocatable output is requested.
387void Writer::createLinkingSection() {
388 SyntheticSection *Section =
389 createSyntheticSection(WASM_SEC_CUSTOM, "linking");
390 raw_ostream &OS = Section->getStream();
391
Sam Clegg0d0dd392017-12-19 17:09:45 +0000392 if (!Config->Relocatable)
393 return;
394
Sam Clegg93102972018-02-23 05:08:53 +0000395 if (!SymtabEntries.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000396 SubSection Sub(WASM_SYMBOL_TABLE);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000397 writeUleb128(Sub.OS, SymtabEntries.size(), "num symbols");
398
Sam Clegg93102972018-02-23 05:08:53 +0000399 for (const Symbol *Sym : SymtabEntries) {
400 assert(Sym->isDefined() || Sym->isUndefined());
401 WasmSymbolType Kind = Sym->getWasmType();
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000402 uint32_t Flags = getWasmFlags(Sym);
403
Sam Clegg8518e7d2018-03-01 18:06:39 +0000404 writeU8(Sub.OS, Kind, "sym kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000405 writeUleb128(Sub.OS, Flags, "sym flags");
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000406
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000407 if (auto *F = dyn_cast<FunctionSymbol>(Sym)) {
408 writeUleb128(Sub.OS, F->getFunctionIndex(), "index");
Sam Clegg93102972018-02-23 05:08:53 +0000409 if (Sym->isDefined())
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000410 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000411 } else if (auto *G = dyn_cast<GlobalSymbol>(Sym)) {
412 writeUleb128(Sub.OS, G->getGlobalIndex(), "index");
413 if (Sym->isDefined())
414 writeStr(Sub.OS, Sym->getName(), "sym name");
415 } else {
416 assert(isa<DataSymbol>(Sym));
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000417 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegg93102972018-02-23 05:08:53 +0000418 if (auto *DataSym = dyn_cast<DefinedData>(Sym)) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000419 writeUleb128(Sub.OS, DataSym->getOutputSegmentIndex(), "index");
420 writeUleb128(Sub.OS, DataSym->getOutputSegmentOffset(),
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000421 "data offset");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000422 writeUleb128(Sub.OS, DataSym->getSize(), "data size");
Sam Clegg93102972018-02-23 05:08:53 +0000423 }
Sam Clegg93102972018-02-23 05:08:53 +0000424 }
Sam Cleggd3052d52018-01-18 23:40:49 +0000425 }
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000426
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000427 Sub.writeTo(OS);
Sam Cleggd3052d52018-01-18 23:40:49 +0000428 }
429
Sam Clegg0d0dd392017-12-19 17:09:45 +0000430 if (Segments.size()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000431 SubSection Sub(WASM_SEGMENT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000432 writeUleb128(Sub.OS, Segments.size(), "num data segments");
Sam Cleggc94d3932017-11-17 18:14:09 +0000433 for (const OutputSegment *S : Segments) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000434 writeStr(Sub.OS, S->Name, "segment name");
435 writeUleb128(Sub.OS, S->Alignment, "alignment");
436 writeUleb128(Sub.OS, 0, "flags");
Sam Cleggc94d3932017-11-17 18:14:09 +0000437 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000438 Sub.writeTo(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000439 }
Sam Clegg0d0dd392017-12-19 17:09:45 +0000440
Sam Clegg0d0dd392017-12-19 17:09:45 +0000441 if (!InitFunctions.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000442 SubSection Sub(WASM_INIT_FUNCS);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000443 writeUleb128(Sub.OS, InitFunctions.size(), "num init functions");
Sam Clegg93102972018-02-23 05:08:53 +0000444 for (const WasmInitEntry &F : InitFunctions) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000445 writeUleb128(Sub.OS, F.Priority, "priority");
446 writeUleb128(Sub.OS, F.Sym->getOutputSymbolIndex(), "function index");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000447 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000448 Sub.writeTo(OS);
Sam Clegg0d0dd392017-12-19 17:09:45 +0000449 }
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000450
Nicholas Wilsondbd90bf2018-03-07 13:28:16 +0000451 struct ComdatEntry {
452 unsigned Kind;
453 uint32_t Index;
454 };
455 std::map<StringRef, std::vector<ComdatEntry>> Comdats;
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000456
Sam Clegg9f934222018-02-21 18:29:23 +0000457 for (const InputFunction *F : InputFunctions) {
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000458 StringRef Comdat = F->getComdatName();
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000459 if (!Comdat.empty())
460 Comdats[Comdat].emplace_back(
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000461 ComdatEntry{WASM_COMDAT_FUNCTION, F->getFunctionIndex()});
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000462 }
463 for (uint32_t I = 0; I < Segments.size(); ++I) {
Sam Cleggf98bccf2018-01-13 15:57:48 +0000464 const auto &InputSegments = Segments[I]->InputSegments;
465 if (InputSegments.empty())
466 continue;
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000467 StringRef Comdat = InputSegments[0]->getComdatName();
Sam Clegga697df522018-01-13 15:59:53 +0000468#ifndef NDEBUG
Sam Cleggf98bccf2018-01-13 15:57:48 +0000469 for (const InputSegment *IS : InputSegments)
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000470 assert(IS->getComdatName() == Comdat);
Sam Clegga697df522018-01-13 15:59:53 +0000471#endif
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000472 if (!Comdat.empty())
473 Comdats[Comdat].emplace_back(ComdatEntry{WASM_COMDAT_DATA, I});
474 }
475
476 if (!Comdats.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000477 SubSection Sub(WASM_COMDAT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000478 writeUleb128(Sub.OS, Comdats.size(), "num comdats");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000479 for (const auto &C : Comdats) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000480 writeStr(Sub.OS, C.first, "comdat name");
481 writeUleb128(Sub.OS, 0, "comdat flags"); // flags for future use
482 writeUleb128(Sub.OS, C.second.size(), "num entries");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000483 for (const ComdatEntry &Entry : C.second) {
Sam Clegg8518e7d2018-03-01 18:06:39 +0000484 writeU8(Sub.OS, Entry.Kind, "entry kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000485 writeUleb128(Sub.OS, Entry.Index, "entry index");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000486 }
487 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000488 Sub.writeTo(OS);
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000489 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000490}
491
492// Create the custom "name" section containing debug symbol names.
493void Writer::createNameSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000494 unsigned NumNames = NumImportedFunctions;
Sam Clegg9f934222018-02-21 18:29:23 +0000495 for (const InputFunction *F : InputFunctions)
Sam Clegg1963d712018-01-17 20:19:04 +0000496 if (!F->getName().empty())
497 ++NumNames;
Sam Cleggc94d3932017-11-17 18:14:09 +0000498
Sam Clegg1963d712018-01-17 20:19:04 +0000499 if (NumNames == 0)
500 return;
Sam Clegg50686852018-01-12 18:35:13 +0000501
Sam Cleggc94d3932017-11-17 18:14:09 +0000502 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "name");
503
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000504 SubSection Sub(WASM_NAMES_FUNCTION);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000505 writeUleb128(Sub.OS, NumNames, "name count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000506
Sam Clegg93102972018-02-23 05:08:53 +0000507 // Names must appear in function index order. As it happens ImportedSymbols
508 // and InputFunctions are numbered in order with imported functions coming
Sam Clegg1963d712018-01-17 20:19:04 +0000509 // first.
Sam Clegg93102972018-02-23 05:08:53 +0000510 for (const Symbol *S : ImportedSymbols) {
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000511 if (auto *F = dyn_cast<FunctionSymbol>(S)) {
512 writeUleb128(Sub.OS, F->getFunctionIndex(), "func index");
Nicholas Wilson531769b2018-03-13 13:30:04 +0000513 Optional<std::string> Name = demangleItanium(F->getName());
514 writeStr(Sub.OS, Name ? StringRef(*Name) : F->getName(), "symbol name");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000515 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000516 }
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()) {
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000519 writeUleb128(Sub.OS, F->getFunctionIndex(), "func index");
Nicholas Wilson531769b2018-03-13 13:30:04 +0000520 Optional<std::string> Name = demangleItanium(F->getName());
521 writeStr(Sub.OS, Name ? StringRef(*Name) : F->getName(), "symbol name");
Sam Clegg1963d712018-01-17 20:19:04 +0000522 }
523 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000524
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000525 Sub.writeTo(Section->getStream());
Sam Cleggc94d3932017-11-17 18:14:09 +0000526}
527
528void Writer::writeHeader() {
529 memcpy(Buffer->getBufferStart(), Header.data(), Header.size());
530}
531
532void Writer::writeSections() {
533 uint8_t *Buf = Buffer->getBufferStart();
534 parallelForEach(OutputSections, [Buf](OutputSection *S) { S->writeTo(Buf); });
535}
536
537// Fix the memory layout of the output binary. This assigns memory offsets
Sam Clegg49ed9262017-12-01 00:53:21 +0000538// to each of the input data sections as well as the explicit stack region.
Sam Cleggf0d433d2018-02-02 22:59:56 +0000539// The memory layout is as follows, from low to high.
540// - initialized data (starting at Config->GlobalBase)
541// - BSS data (not currently implemented in llvm)
542// - explicit stack (Config->ZStackSize)
543// - heap start / unallocated
Sam Cleggc94d3932017-11-17 18:14:09 +0000544void Writer::layoutMemory() {
545 uint32_t MemoryPtr = 0;
Sam Clegg99eb42c2018-02-27 23:58:03 +0000546 MemoryPtr = Config->GlobalBase;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000547 log("mem: global base = " + Twine(Config->GlobalBase));
Sam Cleggc94d3932017-11-17 18:14:09 +0000548
549 createOutputSegments();
550
Sam Cleggf0d433d2018-02-02 22:59:56 +0000551 // Arbitrarily set __dso_handle handle to point to the start of the data
552 // segments.
553 if (WasmSym::DsoHandle)
554 WasmSym::DsoHandle->setVirtualAddress(MemoryPtr);
555
Sam Cleggc94d3932017-11-17 18:14:09 +0000556 for (OutputSegment *Seg : Segments) {
557 MemoryPtr = alignTo(MemoryPtr, Seg->Alignment);
558 Seg->StartVA = MemoryPtr;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000559 log(formatv("mem: {0,-15} offset={1,-8} size={2,-8} align={3}", Seg->Name,
560 MemoryPtr, Seg->Size, Seg->Alignment));
Sam Cleggc94d3932017-11-17 18:14:09 +0000561 MemoryPtr += Seg->Size;
562 }
563
Sam Cleggf0d433d2018-02-02 22:59:56 +0000564 // TODO: Add .bss space here.
Sam Clegg37a4a8a2018-02-07 03:04:53 +0000565 if (WasmSym::DataEnd)
566 WasmSym::DataEnd->setVirtualAddress(MemoryPtr);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000567
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000568 log("mem: static data = " + Twine(MemoryPtr - Config->GlobalBase));
Sam Cleggc94d3932017-11-17 18:14:09 +0000569
Sam Cleggf0d433d2018-02-02 22:59:56 +0000570 // Stack comes after static data and bss
Sam Cleggc94d3932017-11-17 18:14:09 +0000571 if (!Config->Relocatable) {
572 MemoryPtr = alignTo(MemoryPtr, kStackAlignment);
573 if (Config->ZStackSize != alignTo(Config->ZStackSize, kStackAlignment))
574 error("stack size must be " + Twine(kStackAlignment) + "-byte aligned");
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000575 log("mem: stack size = " + Twine(Config->ZStackSize));
576 log("mem: stack base = " + Twine(MemoryPtr));
Sam Cleggc94d3932017-11-17 18:14:09 +0000577 MemoryPtr += Config->ZStackSize;
Sam Clegg93102972018-02-23 05:08:53 +0000578 WasmSym::StackPointer->Global->Global.InitExpr.Value.Int32 = MemoryPtr;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000579 log("mem: stack top = " + Twine(MemoryPtr));
Sam Clegg93102972018-02-23 05:08:53 +0000580
Sam Clegg51bcdc22018-01-17 01:34:31 +0000581 // Set `__heap_base` to directly follow the end of the stack. We don't
582 // allocate any heap memory up front, but instead really on the malloc/brk
583 // implementation growing the memory at runtime.
Sam Cleggf0d433d2018-02-02 22:59:56 +0000584 WasmSym::HeapBase->setVirtualAddress(MemoryPtr);
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000585 log("mem: heap base = " + Twine(MemoryPtr));
Sam Cleggc94d3932017-11-17 18:14:09 +0000586 }
587
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000588 if (Config->InitialMemory != 0) {
589 if (Config->InitialMemory != alignTo(Config->InitialMemory, WasmPageSize))
590 error("initial memory must be " + Twine(WasmPageSize) + "-byte aligned");
591 if (MemoryPtr > Config->InitialMemory)
592 error("initial memory too small, " + Twine(MemoryPtr) + " bytes needed");
593 else
594 MemoryPtr = Config->InitialMemory;
595 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000596 uint32_t MemSize = alignTo(MemoryPtr, WasmPageSize);
597 NumMemoryPages = MemSize / WasmPageSize;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000598 log("mem: total pages = " + Twine(NumMemoryPages));
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000599
600 if (Config->MaxMemory != 0) {
601 if (Config->MaxMemory != alignTo(Config->MaxMemory, WasmPageSize))
602 error("maximum memory must be " + Twine(WasmPageSize) + "-byte aligned");
603 if (MemoryPtr > Config->MaxMemory)
604 error("maximum memory too small, " + Twine(MemoryPtr) + " bytes needed");
605 MaxMemoryPages = Config->MaxMemory / WasmPageSize;
606 log("mem: max pages = " + Twine(MaxMemoryPages));
607 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000608}
609
610SyntheticSection *Writer::createSyntheticSection(uint32_t Type,
Sam Cleggc375e4e2018-01-10 19:18:22 +0000611 StringRef Name) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000612 auto Sec = make<SyntheticSection>(Type, Name);
Sam Cleggab2ac292017-12-20 05:14:48 +0000613 log("createSection: " + toString(*Sec));
Sam Cleggc94d3932017-11-17 18:14:09 +0000614 OutputSections.push_back(Sec);
615 return Sec;
616}
617
618void Writer::createSections() {
619 // Known sections
620 createTypeSection();
621 createImportSection();
622 createFunctionSection();
623 createTableSection();
624 createMemorySection();
625 createGlobalSection();
626 createExportSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000627 createElemSection();
628 createCodeSection();
629 createDataSection();
630
631 // Custom sections
Sam Clegg99eb42c2018-02-27 23:58:03 +0000632 if (Config->Relocatable) {
Sam Clegg99eb42c2018-02-27 23:58:03 +0000633 createLinkingSection();
Nicholas Wilson94d3b162018-03-05 12:33:58 +0000634 createRelocSections();
Sam Clegg99eb42c2018-02-27 23:58:03 +0000635 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000636 if (!Config->StripDebug && !Config->StripAll)
637 createNameSection();
638
639 for (OutputSection *S : OutputSections) {
640 S->setOffset(FileSize);
641 S->finalizeContents();
642 FileSize += S->getSize();
643 }
644}
645
Sam Cleggc94d3932017-11-17 18:14:09 +0000646void Writer::calculateImports() {
Sam Clegg574d7ce2017-12-15 19:23:49 +0000647 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000648 if (!Sym->isUndefined())
649 continue;
650 if (isa<DataSymbol>(Sym))
651 continue;
652 if (Sym->isWeak() && !Config->Relocatable)
Sam Clegg574d7ce2017-12-15 19:23:49 +0000653 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000654
Sam Clegg93102972018-02-23 05:08:53 +0000655 DEBUG(dbgs() << "import: " << Sym->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000656 ImportedSymbols.emplace_back(Sym);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000657 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
658 F->setFunctionIndex(NumImportedFunctions++);
Sam Clegg93102972018-02-23 05:08:53 +0000659 else
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000660 cast<GlobalSymbol>(Sym)->setGlobalIndex(NumImportedGlobals++);
Sam Cleggc94d3932017-11-17 18:14:09 +0000661 }
662}
663
Sam Cleggd3052d52018-01-18 23:40:49 +0000664void Writer::calculateExports() {
Sam Clegg93102972018-02-23 05:08:53 +0000665 if (Config->Relocatable)
666 return;
Sam Cleggf0d433d2018-02-02 22:59:56 +0000667
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000668 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000669 if (!Sym->isDefined())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000670 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000671 if (Sym->isHidden() || Sym->isLocal())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000672 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000673 if (!Sym->isLive())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000674 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000675
676 DEBUG(dbgs() << "exporting sym: " << Sym->getName() << "\n");
677
Nicholas Wilsonf2f6d5e2018-03-02 14:51:36 +0000678 if (auto *D = dyn_cast<DefinedData>(Sym))
Sam Clegg93102972018-02-23 05:08:53 +0000679 DefinedFakeGlobals.emplace_back(D);
Sam Clegg93102972018-02-23 05:08:53 +0000680 ExportedSymbols.emplace_back(Sym);
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000681 }
Sam Clegg93102972018-02-23 05:08:53 +0000682}
683
684void Writer::assignSymtab() {
685 if (!Config->Relocatable)
686 return;
687
688 unsigned SymbolIndex = SymtabEntries.size();
Sam Cleggd3052d52018-01-18 23:40:49 +0000689 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg93102972018-02-23 05:08:53 +0000690 DEBUG(dbgs() << "Symtab entries: " << File->getName() << "\n");
Sam Cleggd3052d52018-01-18 23:40:49 +0000691 for (Symbol *Sym : File->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000692 if (Sym->getFile() != File)
Sam Cleggd3052d52018-01-18 23:40:49 +0000693 continue;
Nicholas Wilson06e0d172018-03-07 11:15:47 +0000694 // (Since this is relocatable output, GC is not performed so symbols must
695 // be live.)
696 assert(Sym->isLive());
Sam Clegg93102972018-02-23 05:08:53 +0000697 Sym->setOutputSymbolIndex(SymbolIndex++);
698 SymtabEntries.emplace_back(Sym);
Sam Cleggd3052d52018-01-18 23:40:49 +0000699 }
700 }
701
Sam Clegg93102972018-02-23 05:08:53 +0000702 // For the moment, relocatable output doesn't contain any synthetic functions,
703 // so no need to look through the Symtab for symbols not referenced by
704 // Symtab->ObjectFiles.
Sam Cleggd3052d52018-01-18 23:40:49 +0000705}
706
Sam Cleggc375e4e2018-01-10 19:18:22 +0000707uint32_t Writer::lookupType(const WasmSignature &Sig) {
Sam Clegg8d027d62018-01-10 20:12:26 +0000708 auto It = TypeIndices.find(Sig);
709 if (It == TypeIndices.end()) {
Sam Cleggc375e4e2018-01-10 19:18:22 +0000710 error("type not found: " + toString(Sig));
Sam Clegg8d027d62018-01-10 20:12:26 +0000711 return 0;
712 }
713 return It->second;
Sam Cleggc375e4e2018-01-10 19:18:22 +0000714}
715
716uint32_t Writer::registerType(const WasmSignature &Sig) {
Sam Cleggb8621592017-11-30 01:40:08 +0000717 auto Pair = TypeIndices.insert(std::make_pair(Sig, Types.size()));
Sam Cleggc375e4e2018-01-10 19:18:22 +0000718 if (Pair.second) {
719 DEBUG(dbgs() << "type " << toString(Sig) << "\n");
Sam Cleggb8621592017-11-30 01:40:08 +0000720 Types.push_back(&Sig);
Sam Cleggc375e4e2018-01-10 19:18:22 +0000721 }
Sam Cleggb8621592017-11-30 01:40:08 +0000722 return Pair.first->second;
723}
724
Sam Cleggc94d3932017-11-17 18:14:09 +0000725void Writer::calculateTypes() {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000726 // The output type section is the union of the following sets:
727 // 1. Any signature used in the TYPE relocation
728 // 2. The signatures of all imported functions
729 // 3. The signatures of all defined functions
730
Sam Cleggc94d3932017-11-17 18:14:09 +0000731 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000732 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
733 for (uint32_t I = 0; I < Types.size(); I++)
734 if (File->TypeIsUsed[I])
735 File->TypeMap[I] = registerType(Types[I]);
Sam Cleggc94d3932017-11-17 18:14:09 +0000736 }
Sam Clegg50686852018-01-12 18:35:13 +0000737
Sam Clegg93102972018-02-23 05:08:53 +0000738 for (const Symbol *Sym : ImportedSymbols)
739 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
740 registerType(*F->getFunctionType());
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000741
Sam Clegg9f934222018-02-21 18:29:23 +0000742 for (const InputFunction *F : InputFunctions)
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000743 registerType(F->Signature);
Sam Cleggc94d3932017-11-17 18:14:09 +0000744}
745
Sam Clegg8d146bb2018-01-09 23:56:44 +0000746void Writer::assignIndexes() {
Sam Clegg93102972018-02-23 05:08:53 +0000747 uint32_t FunctionIndex = NumImportedFunctions + InputFunctions.size();
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000748 auto AddDefinedFunction = [&](InputFunction *Func) {
749 if (!Func->Live)
750 return;
751 InputFunctions.emplace_back(Func);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000752 Func->setFunctionIndex(FunctionIndex++);
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000753 };
754
Nicholas Wilson5639da82018-03-12 15:44:07 +0000755 for (InputFunction *Func : Symtab->SyntheticFunctions)
756 AddDefinedFunction(Func);
757
Sam Clegg87e61922018-01-08 23:39:11 +0000758 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8d146bb2018-01-09 23:56:44 +0000759 DEBUG(dbgs() << "Functions: " << File->getName() << "\n");
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000760 for (InputFunction *Func : File->Functions)
761 AddDefinedFunction(Func);
Sam Clegg8d146bb2018-01-09 23:56:44 +0000762 }
763
Sam Clegg93102972018-02-23 05:08:53 +0000764 uint32_t TableIndex = kInitialTableOffset;
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000765 auto HandleRelocs = [&](InputChunk *Chunk) {
766 if (!Chunk->Live)
767 return;
768 ObjFile *File = Chunk->File;
769 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
Sam Clegg93102972018-02-23 05:08:53 +0000770 for (const WasmRelocation &Reloc : Chunk->getRelocations()) {
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000771 if (Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_I32 ||
772 Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_SLEB) {
773 FunctionSymbol *Sym = File->getFunctionSymbol(Reloc.Index);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000774 if (Sym->hasTableIndex() || !Sym->hasFunctionIndex())
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000775 continue;
776 Sym->setTableIndex(TableIndex++);
777 IndirectFunctions.emplace_back(Sym);
778 } else if (Reloc.Type == R_WEBASSEMBLY_TYPE_INDEX_LEB) {
Sam Clegg93102972018-02-23 05:08:53 +0000779 // Mark target type as live
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000780 File->TypeMap[Reloc.Index] = registerType(Types[Reloc.Index]);
781 File->TypeIsUsed[Reloc.Index] = true;
Sam Clegg93102972018-02-23 05:08:53 +0000782 } else if (Reloc.Type == R_WEBASSEMBLY_GLOBAL_INDEX_LEB) {
783 // Mark target global as live
784 GlobalSymbol *Sym = File->getGlobalSymbol(Reloc.Index);
785 if (auto *G = dyn_cast<DefinedGlobal>(Sym)) {
786 DEBUG(dbgs() << "marking global live: " << Sym->getName() << "\n");
787 G->Global->Live = true;
788 }
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000789 }
790 }
791 };
792
Sam Clegg8d146bb2018-01-09 23:56:44 +0000793 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000794 DEBUG(dbgs() << "Handle relocs: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000795 for (InputChunk *Chunk : File->Functions)
796 HandleRelocs(Chunk);
797 for (InputChunk *Chunk : File->Segments)
798 HandleRelocs(Chunk);
799 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000800
Sam Clegg93102972018-02-23 05:08:53 +0000801 uint32_t GlobalIndex = NumImportedGlobals + InputGlobals.size();
802 auto AddDefinedGlobal = [&](InputGlobal *Global) {
803 if (Global->Live) {
804 DEBUG(dbgs() << "AddDefinedGlobal: " << GlobalIndex << "\n");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000805 Global->setGlobalIndex(GlobalIndex++);
Sam Clegg93102972018-02-23 05:08:53 +0000806 InputGlobals.push_back(Global);
807 }
808 };
809
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000810 for (InputGlobal *Global : Symtab->SyntheticGlobals)
811 AddDefinedGlobal(Global);
Sam Clegg93102972018-02-23 05:08:53 +0000812
813 for (ObjFile *File : Symtab->ObjectFiles) {
814 DEBUG(dbgs() << "Globals: " << File->getName() << "\n");
815 for (InputGlobal *Global : File->Globals)
816 AddDefinedGlobal(Global);
Sam Cleggc94d3932017-11-17 18:14:09 +0000817 }
818}
819
820static StringRef getOutputDataSegmentName(StringRef Name) {
821 if (Config->Relocatable)
822 return Name;
Rui Ueyama4764b572018-02-28 00:57:28 +0000823 if (Name.startswith(".text."))
824 return ".text";
825 if (Name.startswith(".data."))
826 return ".data";
827 if (Name.startswith(".bss."))
828 return ".bss";
Sam Cleggc94d3932017-11-17 18:14:09 +0000829 return Name;
830}
831
832void Writer::createOutputSegments() {
833 for (ObjFile *File : Symtab->ObjectFiles) {
834 for (InputSegment *Segment : File->Segments) {
Sam Clegg447ae402018-02-13 20:29:38 +0000835 if (!Segment->Live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000836 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000837 StringRef Name = getOutputDataSegmentName(Segment->getName());
838 OutputSegment *&S = SegmentMap[Name];
839 if (S == nullptr) {
840 DEBUG(dbgs() << "new segment: " << Name << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000841 S = make<OutputSegment>(Name, Segments.size());
Sam Cleggc94d3932017-11-17 18:14:09 +0000842 Segments.push_back(S);
843 }
844 S->addInputSegment(Segment);
845 DEBUG(dbgs() << "added data: " << Name << ": " << S->Size << "\n");
Sam Cleggc94d3932017-11-17 18:14:09 +0000846 }
847 }
848}
849
Sam Clegg50686852018-01-12 18:35:13 +0000850static const int OPCODE_CALL = 0x10;
851static const int OPCODE_END = 0xb;
852
853// Create synthetic "__wasm_call_ctors" function based on ctor functions
854// in input object.
855void Writer::createCtorFunction() {
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000856 // First write the body's contents to a string.
857 std::string BodyContent;
Sam Clegg50686852018-01-12 18:35:13 +0000858 {
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000859 raw_string_ostream OS(BodyContent);
Sam Clegg50686852018-01-12 18:35:13 +0000860 writeUleb128(OS, 0, "num locals");
Sam Clegg93102972018-02-23 05:08:53 +0000861 for (const WasmInitEntry &F : InitFunctions) {
Sam Clegg50686852018-01-12 18:35:13 +0000862 writeU8(OS, OPCODE_CALL, "CALL");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000863 writeUleb128(OS, F.Sym->getFunctionIndex(), "function index");
Sam Clegg50686852018-01-12 18:35:13 +0000864 }
865 writeU8(OS, OPCODE_END, "END");
866 }
867
868 // Once we know the size of the body we can create the final function body
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000869 std::string FunctionBody;
870 {
871 raw_string_ostream OS(FunctionBody);
872 writeUleb128(OS, BodyContent.size(), "function size");
873 OS << BodyContent;
874 }
Rui Ueyama29abfe42018-02-28 17:43:15 +0000875
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000876 ArrayRef<uint8_t> Body = toArrayRef(Saver.save(FunctionBody));
877 cast<SyntheticFunction>(WasmSym::CallCtors->Function)->setBody(Body);
Sam Clegg50686852018-01-12 18:35:13 +0000878}
879
880// Populate InitFunctions vector with init functions from all input objects.
881// This is then used either when creating the output linking section or to
882// synthesize the "__wasm_call_ctors" function.
883void Writer::calculateInitFunctions() {
884 for (ObjFile *File : Symtab->ObjectFiles) {
885 const WasmLinkingData &L = File->getWasmObj()->linkingData();
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +0000886 for (const WasmInitFunc &F : L.InitFunctions) {
887 FunctionSymbol *Sym = File->getFunctionSymbol(F.Symbol);
888 if (*Sym->getFunctionType() != WasmSignature{{}, WASM_TYPE_NORESULT})
889 error("invalid signature for init func: " + toString(*Sym));
890 InitFunctions.emplace_back(WasmInitEntry{Sym, F.Priority});
891 }
Sam Clegg50686852018-01-12 18:35:13 +0000892 }
Rui Ueyamada69b712018-02-28 00:15:59 +0000893
Sam Clegg50686852018-01-12 18:35:13 +0000894 // Sort in order of priority (lowest first) so that they are called
895 // in the correct order.
Sam Clegg29b8feb2018-02-21 00:34:34 +0000896 std::stable_sort(InitFunctions.begin(), InitFunctions.end(),
Sam Clegg93102972018-02-23 05:08:53 +0000897 [](const WasmInitEntry &L, const WasmInitEntry &R) {
Sam Clegg29b8feb2018-02-21 00:34:34 +0000898 return L.Priority < R.Priority;
899 });
Sam Clegg50686852018-01-12 18:35:13 +0000900}
901
Sam Cleggc94d3932017-11-17 18:14:09 +0000902void Writer::run() {
Sam Clegg99eb42c2018-02-27 23:58:03 +0000903 if (Config->Relocatable)
904 Config->GlobalBase = 0;
905
Sam Cleggc94d3932017-11-17 18:14:09 +0000906 log("-- calculateImports");
907 calculateImports();
Sam Clegg8d146bb2018-01-09 23:56:44 +0000908 log("-- assignIndexes");
909 assignIndexes();
Sam Clegg50686852018-01-12 18:35:13 +0000910 log("-- calculateInitFunctions");
911 calculateInitFunctions();
912 if (!Config->Relocatable)
913 createCtorFunction();
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000914 log("-- calculateTypes");
915 calculateTypes();
Sam Clegg93102972018-02-23 05:08:53 +0000916 log("-- layoutMemory");
917 layoutMemory();
918 log("-- calculateExports");
919 calculateExports();
920 log("-- assignSymtab");
921 assignSymtab();
Sam Cleggc94d3932017-11-17 18:14:09 +0000922
923 if (errorHandler().Verbose) {
Sam Clegg9f934222018-02-21 18:29:23 +0000924 log("Defined Functions: " + Twine(InputFunctions.size()));
Sam Clegg93102972018-02-23 05:08:53 +0000925 log("Defined Globals : " + Twine(InputGlobals.size()));
926 log("Function Imports : " + Twine(NumImportedFunctions));
927 log("Global Imports : " + Twine(NumImportedGlobals));
Sam Cleggc94d3932017-11-17 18:14:09 +0000928 for (ObjFile *File : Symtab->ObjectFiles)
929 File->dumpInfo();
930 }
931
Sam Cleggc94d3932017-11-17 18:14:09 +0000932 createHeader();
933 log("-- createSections");
934 createSections();
935
936 log("-- openFile");
937 openFile();
938 if (errorCount())
939 return;
940
941 writeHeader();
942
943 log("-- writeSections");
944 writeSections();
945 if (errorCount())
946 return;
947
948 if (Error E = Buffer->commit())
949 fatal("failed to write the output file: " + toString(std::move(E)));
950}
951
952// Open a result file.
953void Writer::openFile() {
954 log("writing: " + Config->OutputFile);
Sam Cleggc94d3932017-11-17 18:14:09 +0000955
956 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
957 FileOutputBuffer::create(Config->OutputFile, FileSize,
958 FileOutputBuffer::F_executable);
959
960 if (!BufferOrErr)
961 error("failed to open " + Config->OutputFile + ": " +
962 toString(BufferOrErr.takeError()));
963 else
964 Buffer = std::move(*BufferOrErr);
965}
966
967void Writer::createHeader() {
968 raw_string_ostream OS(Header);
969 writeBytes(OS, WasmMagic, sizeof(WasmMagic), "wasm magic");
970 writeU32(OS, WasmVersion, "wasm version");
971 OS.flush();
972 FileSize += Header.size();
973}
974
975void lld::wasm::writeResult() { Writer().run(); }