blob: 4a52b526ae30afd8abb7745bd359cce5c827fe6f [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 Clegg80ba4382018-04-10 16:12:49 +000023#include "llvm/ADT/StringMap.h"
Sam Clegg93102972018-02-23 05:08:53 +000024#include "llvm/BinaryFormat/Wasm.h"
Nicholas Wilson3e3f5fb2018-03-14 15:58:16 +000025#include "llvm/Object/WasmTraits.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000026#include "llvm/Support/FileOutputBuffer.h"
27#include "llvm/Support/Format.h"
28#include "llvm/Support/FormatVariadic.h"
29#include "llvm/Support/LEB128.h"
30
31#include <cstdarg>
Sam Clegge0f6fcd2018-01-12 22:25:17 +000032#include <map>
Sam Cleggc94d3932017-11-17 18:14:09 +000033
34#define DEBUG_TYPE "lld"
35
36using namespace llvm;
37using namespace llvm::wasm;
38using namespace lld;
39using namespace lld::wasm;
40
41static constexpr int kStackAlignment = 16;
Sam Clegg48bbd632018-01-24 21:37:30 +000042static constexpr int kInitialTableOffset = 1;
Nicholas Wilson874eedd2018-03-27 17:38:51 +000043static constexpr const char *kFunctionTableName = "__indirect_function_table";
Sam Cleggc94d3932017-11-17 18:14:09 +000044
45namespace {
46
Sam Clegg93102972018-02-23 05:08:53 +000047// An init entry to be written to either the synthetic init func or the
48// linking metadata.
49struct WasmInitEntry {
Sam Clegge3f3ccf2018-03-12 19:56:23 +000050 const FunctionSymbol *Sym;
Sam Clegg93102972018-02-23 05:08:53 +000051 uint32_t Priority;
Sam Cleggd3052d52018-01-18 23:40:49 +000052};
53
Sam Cleggc94d3932017-11-17 18:14:09 +000054// The writer writes a SymbolTable result to a file.
55class Writer {
56public:
57 void run();
58
59private:
60 void openFile();
61
Sam Cleggc375e4e2018-01-10 19:18:22 +000062 uint32_t lookupType(const WasmSignature &Sig);
63 uint32_t registerType(const WasmSignature &Sig);
Sam Clegg93102972018-02-23 05:08:53 +000064
Sam Clegg50686852018-01-12 18:35:13 +000065 void createCtorFunction();
66 void calculateInitFunctions();
Sam Clegg8d146bb2018-01-09 23:56:44 +000067 void assignIndexes();
Sam Cleggc94d3932017-11-17 18:14:09 +000068 void calculateImports();
Sam Cleggd3052d52018-01-18 23:40:49 +000069 void calculateExports();
Sam Clegg93102972018-02-23 05:08:53 +000070 void assignSymtab();
Sam Cleggc94d3932017-11-17 18:14:09 +000071 void calculateTypes();
72 void createOutputSegments();
73 void layoutMemory();
74 void createHeader();
75 void createSections();
Nicholas Wilsondbd90bf2018-03-07 13:28:16 +000076 SyntheticSection *createSyntheticSection(uint32_t Type, StringRef Name = "");
Sam Cleggc94d3932017-11-17 18:14:09 +000077
78 // Builtin sections
79 void createTypeSection();
80 void createFunctionSection();
81 void createTableSection();
82 void createGlobalSection();
83 void createExportSection();
84 void createImportSection();
85 void createMemorySection();
86 void createElemSection();
Sam Cleggc94d3932017-11-17 18:14:09 +000087 void createCodeSection();
88 void createDataSection();
Sam Clegg80ba4382018-04-10 16:12:49 +000089 void createCustomSections();
Sam Cleggc94d3932017-11-17 18:14:09 +000090
91 // Custom sections
92 void createRelocSections();
93 void createLinkingSection();
94 void createNameSection();
95
96 void writeHeader();
97 void writeSections();
98
99 uint64_t FileSize = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000100 uint32_t NumMemoryPages = 0;
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000101 uint32_t MaxMemoryPages = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000102
103 std::vector<const WasmSignature *> Types;
Nicholas Wilson3e3f5fb2018-03-14 15:58:16 +0000104 DenseMap<WasmSignature, int32_t> TypeIndices;
Sam Clegg93102972018-02-23 05:08:53 +0000105 std::vector<const Symbol *> ImportedSymbols;
106 unsigned NumImportedFunctions = 0;
107 unsigned NumImportedGlobals = 0;
108 std::vector<Symbol *> ExportedSymbols;
109 std::vector<const DefinedData *> DefinedFakeGlobals;
110 std::vector<InputGlobal *> InputGlobals;
Sam Clegg9f934222018-02-21 18:29:23 +0000111 std::vector<InputFunction *> InputFunctions;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000112 std::vector<const FunctionSymbol *> IndirectFunctions;
Sam Clegg93102972018-02-23 05:08:53 +0000113 std::vector<const Symbol *> SymtabEntries;
114 std::vector<WasmInitEntry> InitFunctions;
Sam Cleggc94d3932017-11-17 18:14:09 +0000115
Sam Clegg80ba4382018-04-10 16:12:49 +0000116 llvm::StringMap<std::vector<InputSection *>> CustomSectionMapping;
117
Sam Cleggc94d3932017-11-17 18:14:09 +0000118 // Elements that are used to construct the final output
119 std::string Header;
120 std::vector<OutputSection *> OutputSections;
121
122 std::unique_ptr<FileOutputBuffer> Buffer;
123
124 std::vector<OutputSegment *> Segments;
125 llvm::SmallDenseMap<StringRef, OutputSegment *> SegmentMap;
126};
127
128} // anonymous namespace
129
Sam Cleggc94d3932017-11-17 18:14:09 +0000130void Writer::createImportSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000131 uint32_t NumImports = ImportedSymbols.size();
Sam Cleggc94d3932017-11-17 18:14:09 +0000132 if (Config->ImportMemory)
133 ++NumImports;
Nicholas Wilsonfc90b302018-03-28 12:53:29 +0000134 if (Config->ImportTable)
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000135 ++NumImports;
Sam Cleggc94d3932017-11-17 18:14:09 +0000136
137 if (NumImports == 0)
138 return;
139
140 SyntheticSection *Section = createSyntheticSection(WASM_SEC_IMPORT);
141 raw_ostream &OS = Section->getStream();
142
143 writeUleb128(OS, NumImports, "import count");
144
Sam Cleggc94d3932017-11-17 18:14:09 +0000145 if (Config->ImportMemory) {
146 WasmImport Import;
147 Import.Module = "env";
148 Import.Field = "memory";
149 Import.Kind = WASM_EXTERNAL_MEMORY;
150 Import.Memory.Flags = 0;
151 Import.Memory.Initial = NumMemoryPages;
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000152 if (MaxMemoryPages != 0) {
153 Import.Memory.Flags |= WASM_LIMITS_FLAG_HAS_MAX;
154 Import.Memory.Maximum = MaxMemoryPages;
155 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000156 writeImport(OS, Import);
157 }
158
Nicholas Wilsonfc90b302018-03-28 12:53:29 +0000159 if (Config->ImportTable) {
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000160 uint32_t TableSize = kInitialTableOffset + IndirectFunctions.size();
161 WasmImport Import;
162 Import.Module = "env";
163 Import.Field = kFunctionTableName;
164 Import.Kind = WASM_EXTERNAL_TABLE;
165 Import.Table.ElemType = WASM_TYPE_ANYFUNC;
166 Import.Table.Limits = {WASM_LIMITS_FLAG_HAS_MAX, TableSize, TableSize};
167 writeImport(OS, Import);
168 }
169
Sam Clegg93102972018-02-23 05:08:53 +0000170 for (const Symbol *Sym : ImportedSymbols) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000171 WasmImport Import;
172 Import.Module = "env";
173 Import.Field = Sym->getName();
Sam Clegg93102972018-02-23 05:08:53 +0000174 if (auto *FunctionSym = dyn_cast<FunctionSymbol>(Sym)) {
175 Import.Kind = WASM_EXTERNAL_FUNCTION;
176 Import.SigIndex = lookupType(*FunctionSym->getFunctionType());
177 } else {
178 auto *GlobalSym = cast<GlobalSymbol>(Sym);
179 Import.Kind = WASM_EXTERNAL_GLOBAL;
180 Import.Global = *GlobalSym->getGlobalType();
181 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000182 writeImport(OS, Import);
183 }
184}
185
186void Writer::createTypeSection() {
187 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TYPE);
188 raw_ostream &OS = Section->getStream();
189 writeUleb128(OS, Types.size(), "type count");
Sam Cleggd451da12017-12-19 19:56:27 +0000190 for (const WasmSignature *Sig : Types)
Sam Cleggc94d3932017-11-17 18:14:09 +0000191 writeSig(OS, *Sig);
Sam Cleggc94d3932017-11-17 18:14:09 +0000192}
193
194void Writer::createFunctionSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000195 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000196 return;
197
198 SyntheticSection *Section = createSyntheticSection(WASM_SEC_FUNCTION);
199 raw_ostream &OS = Section->getStream();
200
Sam Clegg9f934222018-02-21 18:29:23 +0000201 writeUleb128(OS, InputFunctions.size(), "function count");
202 for (const InputFunction *Func : InputFunctions)
Sam Cleggc375e4e2018-01-10 19:18:22 +0000203 writeUleb128(OS, lookupType(Func->Signature), "sig index");
Sam Cleggc94d3932017-11-17 18:14:09 +0000204}
205
206void Writer::createMemorySection() {
207 if (Config->ImportMemory)
208 return;
209
210 SyntheticSection *Section = createSyntheticSection(WASM_SEC_MEMORY);
211 raw_ostream &OS = Section->getStream();
212
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000213 bool HasMax = MaxMemoryPages != 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000214 writeUleb128(OS, 1, "memory count");
Nicholas Wilsonca5cc202018-03-14 21:43:04 +0000215 writeUleb128(OS, HasMax ? static_cast<unsigned>(WASM_LIMITS_FLAG_HAS_MAX) : 0,
216 "memory limits flags");
Sam Cleggc94d3932017-11-17 18:14:09 +0000217 writeUleb128(OS, NumMemoryPages, "initial pages");
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000218 if (HasMax)
219 writeUleb128(OS, MaxMemoryPages, "max pages");
Sam Cleggc94d3932017-11-17 18:14:09 +0000220}
221
222void Writer::createGlobalSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000223 unsigned NumGlobals = InputGlobals.size() + DefinedFakeGlobals.size();
224 if (NumGlobals == 0)
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000225 return;
226
Sam Cleggc94d3932017-11-17 18:14:09 +0000227 SyntheticSection *Section = createSyntheticSection(WASM_SEC_GLOBAL);
228 raw_ostream &OS = Section->getStream();
229
Sam Clegg93102972018-02-23 05:08:53 +0000230 writeUleb128(OS, NumGlobals, "global count");
231 for (const InputGlobal *G : InputGlobals)
232 writeGlobal(OS, G->Global);
233 for (const DefinedData *Sym : DefinedFakeGlobals) {
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000234 WasmGlobal Global;
Sam Clegg93102972018-02-23 05:08:53 +0000235 Global.Type = {WASM_TYPE_I32, false};
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000236 Global.InitExpr.Opcode = WASM_OPCODE_I32_CONST;
237 Global.InitExpr.Value.Int32 = Sym->getVirtualAddress();
Sam Cleggc94d3932017-11-17 18:14:09 +0000238 writeGlobal(OS, Global);
239 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000240}
241
242void Writer::createTableSection() {
Nicholas Wilsonfc90b302018-03-28 12:53:29 +0000243 if (Config->ImportTable)
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000244 return;
245
246 // Always output a table section (or table import), even if there are no
247 // indirect calls. There are two reasons for this:
Sam Cleggfc1a9122017-12-11 22:00:56 +0000248 // 1. For executables it is useful to have an empty table slot at 0
249 // which can be filled with a null function call handler.
250 // 2. If we don't do this, any program that contains a call_indirect but
251 // no address-taken function will fail at validation time since it is
252 // a validation error to include a call_indirect instruction if there
253 // is not table.
Sam Clegg48bbd632018-01-24 21:37:30 +0000254 uint32_t TableSize = kInitialTableOffset + IndirectFunctions.size();
Sam Cleggfc1a9122017-12-11 22:00:56 +0000255
Sam Cleggc94d3932017-11-17 18:14:09 +0000256 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TABLE);
257 raw_ostream &OS = Section->getStream();
258
259 writeUleb128(OS, 1, "table count");
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000260 WasmLimits Limits = {WASM_LIMITS_FLAG_HAS_MAX, TableSize, TableSize};
261 writeTableType(OS, WasmTable{WASM_TYPE_ANYFUNC, Limits});
Sam Cleggc94d3932017-11-17 18:14:09 +0000262}
263
264void Writer::createExportSection() {
Sam Cleggc94d3932017-11-17 18:14:09 +0000265 bool ExportMemory = !Config->Relocatable && !Config->ImportMemory;
Nicholas Wilsonfc90b302018-03-28 12:53:29 +0000266 bool ExportTable = !Config->Relocatable && Config->ExportTable;
Sam Cleggc94d3932017-11-17 18:14:09 +0000267
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000268 uint32_t NumExports =
269 (ExportMemory ? 1 : 0) + (ExportTable ? 1 : 0) + ExportedSymbols.size();
Sam Cleggc94d3932017-11-17 18:14:09 +0000270 if (!NumExports)
271 return;
272
273 SyntheticSection *Section = createSyntheticSection(WASM_SEC_EXPORT);
274 raw_ostream &OS = Section->getStream();
275
276 writeUleb128(OS, NumExports, "export count");
277
Rui Ueyama7d696882018-02-28 00:18:34 +0000278 if (ExportMemory)
279 writeExport(OS, {"memory", WASM_EXTERNAL_MEMORY, 0});
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000280 if (ExportTable)
281 writeExport(OS, {kFunctionTableName, WASM_EXTERNAL_TABLE, 0});
Sam Cleggc94d3932017-11-17 18:14:09 +0000282
Sam Clegg93102972018-02-23 05:08:53 +0000283 unsigned FakeGlobalIndex = NumImportedGlobals + InputGlobals.size();
Rui Ueyama7d696882018-02-28 00:18:34 +0000284
Sam Clegg93102972018-02-23 05:08:53 +0000285 for (const Symbol *Sym : ExportedSymbols) {
Rui Ueyama7d696882018-02-28 00:18:34 +0000286 StringRef Name = Sym->getName();
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000287 WasmExport Export;
Rui Ueyama7d696882018-02-28 00:18:34 +0000288 DEBUG(dbgs() << "Export: " << Name << "\n");
289
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000290 if (auto *F = dyn_cast<DefinedFunction>(Sym))
291 Export = {Name, WASM_EXTERNAL_FUNCTION, F->getFunctionIndex()};
292 else if (auto *G = dyn_cast<DefinedGlobal>(Sym))
293 Export = {Name, WASM_EXTERNAL_GLOBAL, G->getGlobalIndex()};
Rui Ueyama7d696882018-02-28 00:18:34 +0000294 else if (isa<DefinedData>(Sym))
295 Export = {Name, WASM_EXTERNAL_GLOBAL, FakeGlobalIndex++};
296 else
Sam Clegg93102972018-02-23 05:08:53 +0000297 llvm_unreachable("unexpected symbol type");
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000298 writeExport(OS, Export);
Sam Cleggc94d3932017-11-17 18:14:09 +0000299 }
300}
301
Sam Clegg80ba4382018-04-10 16:12:49 +0000302void Writer::createCustomSections() {
303 log("createCustomSections");
304 for (ObjFile *File : Symtab->ObjectFiles)
305 for (InputSection *Section : File->CustomSections)
306 CustomSectionMapping[Section->getName()].push_back(Section);
307
308 for (auto &Pair : CustomSectionMapping) {
309 StringRef Name = Pair.first();
310 // These custom sections are known the linker and synthesized rather than
311 // blindly copied
312 if (Name == "linking" || Name == "name" || Name.startswith("reloc."))
313 continue;
314 DEBUG(dbgs() << "createCustomSection: " << Name << "\n");
315 OutputSections.push_back(make<CustomSection>(Name, Pair.second));
316 }
317}
318
Sam Cleggc94d3932017-11-17 18:14:09 +0000319void Writer::createElemSection() {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000320 if (IndirectFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000321 return;
322
323 SyntheticSection *Section = createSyntheticSection(WASM_SEC_ELEM);
324 raw_ostream &OS = Section->getStream();
325
326 writeUleb128(OS, 1, "segment count");
327 writeUleb128(OS, 0, "table index");
328 WasmInitExpr InitExpr;
329 InitExpr.Opcode = WASM_OPCODE_I32_CONST;
Sam Clegg48bbd632018-01-24 21:37:30 +0000330 InitExpr.Value.Int32 = kInitialTableOffset;
Sam Cleggc94d3932017-11-17 18:14:09 +0000331 writeInitExpr(OS, InitExpr);
Sam Cleggfc1a9122017-12-11 22:00:56 +0000332 writeUleb128(OS, IndirectFunctions.size(), "elem count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000333
Sam Clegg48bbd632018-01-24 21:37:30 +0000334 uint32_t TableIndex = kInitialTableOffset;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000335 for (const FunctionSymbol *Sym : IndirectFunctions) {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000336 assert(Sym->getTableIndex() == TableIndex);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000337 writeUleb128(OS, Sym->getFunctionIndex(), "function index");
Sam Cleggfc1a9122017-12-11 22:00:56 +0000338 ++TableIndex;
339 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000340}
341
342void Writer::createCodeSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000343 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000344 return;
345
346 log("createCodeSection");
347
Sam Clegg9f934222018-02-21 18:29:23 +0000348 auto Section = make<CodeSection>(InputFunctions);
Sam Cleggc94d3932017-11-17 18:14:09 +0000349 OutputSections.push_back(Section);
350}
351
352void Writer::createDataSection() {
353 if (!Segments.size())
354 return;
355
356 log("createDataSection");
357 auto Section = make<DataSection>(Segments);
358 OutputSections.push_back(Section);
359}
360
Sam Cleggd451da12017-12-19 19:56:27 +0000361// Create relocations sections in the final output.
Sam Cleggc94d3932017-11-17 18:14:09 +0000362// These are only created when relocatable output is requested.
363void Writer::createRelocSections() {
364 log("createRelocSections");
365 // Don't use iterator here since we are adding to OutputSection
366 size_t OrigSize = OutputSections.size();
367 for (size_t i = 0; i < OrigSize; i++) {
Rui Ueyama37254062018-02-28 00:01:31 +0000368 OutputSection *OSec = OutputSections[i];
369 uint32_t Count = OSec->numRelocations();
Sam Cleggc94d3932017-11-17 18:14:09 +0000370 if (!Count)
371 continue;
372
Rui Ueyama37254062018-02-28 00:01:31 +0000373 StringRef Name;
374 if (OSec->Type == WASM_SEC_DATA)
375 Name = "reloc.DATA";
376 else if (OSec->Type == WASM_SEC_CODE)
377 Name = "reloc.CODE";
Sam Cleggc94d3932017-11-17 18:14:09 +0000378 else
Sam Cleggd451da12017-12-19 19:56:27 +0000379 llvm_unreachable("relocations only supported for code and data");
Sam Cleggc94d3932017-11-17 18:14:09 +0000380
Rui Ueyama37254062018-02-28 00:01:31 +0000381 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, Name);
Sam Cleggc94d3932017-11-17 18:14:09 +0000382 raw_ostream &OS = Section->getStream();
Rui Ueyama37254062018-02-28 00:01:31 +0000383 writeUleb128(OS, OSec->Type, "reloc section");
Sam Cleggc94d3932017-11-17 18:14:09 +0000384 writeUleb128(OS, Count, "reloc count");
Rui Ueyama37254062018-02-28 00:01:31 +0000385 OSec->writeRelocations(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000386 }
387}
388
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000389static uint32_t getWasmFlags(const Symbol *Sym) {
390 uint32_t Flags = 0;
391 if (Sym->isLocal())
392 Flags |= WASM_SYMBOL_BINDING_LOCAL;
393 if (Sym->isWeak())
394 Flags |= WASM_SYMBOL_BINDING_WEAK;
395 if (Sym->isHidden())
396 Flags |= WASM_SYMBOL_VISIBILITY_HIDDEN;
397 if (Sym->isUndefined())
398 Flags |= WASM_SYMBOL_UNDEFINED;
399 return Flags;
400}
401
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000402// Some synthetic sections (e.g. "name" and "linking") have subsections.
403// Just like the synthetic sections themselves these need to be created before
404// they can be written out (since they are preceded by their length). This
405// class is used to create subsections and then write them into the stream
406// of the parent section.
407class SubSection {
408public:
409 explicit SubSection(uint32_t Type) : Type(Type) {}
410
411 void writeTo(raw_ostream &To) {
412 OS.flush();
Rui Ueyama67769102018-02-28 03:38:14 +0000413 writeUleb128(To, Type, "subsection type");
414 writeUleb128(To, Body.size(), "subsection size");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000415 To.write(Body.data(), Body.size());
416 }
417
418private:
419 uint32_t Type;
420 std::string Body;
421
422public:
423 raw_string_ostream OS{Body};
424};
425
Sam Clegg49ed9262017-12-01 00:53:21 +0000426// Create the custom "linking" section containing linker metadata.
Sam Cleggc94d3932017-11-17 18:14:09 +0000427// This is only created when relocatable output is requested.
428void Writer::createLinkingSection() {
429 SyntheticSection *Section =
430 createSyntheticSection(WASM_SEC_CUSTOM, "linking");
431 raw_ostream &OS = Section->getStream();
432
Sam Clegg0d0dd392017-12-19 17:09:45 +0000433 if (!Config->Relocatable)
434 return;
435
Sam Clegg93102972018-02-23 05:08:53 +0000436 if (!SymtabEntries.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000437 SubSection Sub(WASM_SYMBOL_TABLE);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000438 writeUleb128(Sub.OS, SymtabEntries.size(), "num symbols");
439
Sam Clegg93102972018-02-23 05:08:53 +0000440 for (const Symbol *Sym : SymtabEntries) {
441 assert(Sym->isDefined() || Sym->isUndefined());
442 WasmSymbolType Kind = Sym->getWasmType();
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000443 uint32_t Flags = getWasmFlags(Sym);
444
Sam Clegg8518e7d2018-03-01 18:06:39 +0000445 writeU8(Sub.OS, Kind, "sym kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000446 writeUleb128(Sub.OS, Flags, "sym flags");
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000447
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000448 if (auto *F = dyn_cast<FunctionSymbol>(Sym)) {
449 writeUleb128(Sub.OS, F->getFunctionIndex(), "index");
Sam Clegg93102972018-02-23 05:08:53 +0000450 if (Sym->isDefined())
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000451 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000452 } else if (auto *G = dyn_cast<GlobalSymbol>(Sym)) {
453 writeUleb128(Sub.OS, G->getGlobalIndex(), "index");
454 if (Sym->isDefined())
455 writeStr(Sub.OS, Sym->getName(), "sym name");
456 } else {
457 assert(isa<DataSymbol>(Sym));
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000458 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegg93102972018-02-23 05:08:53 +0000459 if (auto *DataSym = dyn_cast<DefinedData>(Sym)) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000460 writeUleb128(Sub.OS, DataSym->getOutputSegmentIndex(), "index");
461 writeUleb128(Sub.OS, DataSym->getOutputSegmentOffset(),
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000462 "data offset");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000463 writeUleb128(Sub.OS, DataSym->getSize(), "data size");
Sam Clegg93102972018-02-23 05:08:53 +0000464 }
Sam Clegg93102972018-02-23 05:08:53 +0000465 }
Sam Cleggd3052d52018-01-18 23:40:49 +0000466 }
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000467
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000468 Sub.writeTo(OS);
Sam Cleggd3052d52018-01-18 23:40:49 +0000469 }
470
Sam Clegg0d0dd392017-12-19 17:09:45 +0000471 if (Segments.size()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000472 SubSection Sub(WASM_SEGMENT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000473 writeUleb128(Sub.OS, Segments.size(), "num data segments");
Sam Cleggc94d3932017-11-17 18:14:09 +0000474 for (const OutputSegment *S : Segments) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000475 writeStr(Sub.OS, S->Name, "segment name");
476 writeUleb128(Sub.OS, S->Alignment, "alignment");
477 writeUleb128(Sub.OS, 0, "flags");
Sam Cleggc94d3932017-11-17 18:14:09 +0000478 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000479 Sub.writeTo(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000480 }
Sam Clegg0d0dd392017-12-19 17:09:45 +0000481
Sam Clegg0d0dd392017-12-19 17:09:45 +0000482 if (!InitFunctions.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000483 SubSection Sub(WASM_INIT_FUNCS);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000484 writeUleb128(Sub.OS, InitFunctions.size(), "num init functions");
Sam Clegg93102972018-02-23 05:08:53 +0000485 for (const WasmInitEntry &F : InitFunctions) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000486 writeUleb128(Sub.OS, F.Priority, "priority");
487 writeUleb128(Sub.OS, F.Sym->getOutputSymbolIndex(), "function index");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000488 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000489 Sub.writeTo(OS);
Sam Clegg0d0dd392017-12-19 17:09:45 +0000490 }
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000491
Nicholas Wilsondbd90bf2018-03-07 13:28:16 +0000492 struct ComdatEntry {
493 unsigned Kind;
494 uint32_t Index;
495 };
496 std::map<StringRef, std::vector<ComdatEntry>> Comdats;
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000497
Sam Clegg9f934222018-02-21 18:29:23 +0000498 for (const InputFunction *F : InputFunctions) {
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000499 StringRef Comdat = F->getComdatName();
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000500 if (!Comdat.empty())
501 Comdats[Comdat].emplace_back(
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000502 ComdatEntry{WASM_COMDAT_FUNCTION, F->getFunctionIndex()});
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000503 }
504 for (uint32_t I = 0; I < Segments.size(); ++I) {
Sam Cleggf98bccf2018-01-13 15:57:48 +0000505 const auto &InputSegments = Segments[I]->InputSegments;
506 if (InputSegments.empty())
507 continue;
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000508 StringRef Comdat = InputSegments[0]->getComdatName();
Sam Clegga697df522018-01-13 15:59:53 +0000509#ifndef NDEBUG
Sam Cleggf98bccf2018-01-13 15:57:48 +0000510 for (const InputSegment *IS : InputSegments)
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000511 assert(IS->getComdatName() == Comdat);
Sam Clegga697df522018-01-13 15:59:53 +0000512#endif
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000513 if (!Comdat.empty())
514 Comdats[Comdat].emplace_back(ComdatEntry{WASM_COMDAT_DATA, I});
515 }
516
517 if (!Comdats.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000518 SubSection Sub(WASM_COMDAT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000519 writeUleb128(Sub.OS, Comdats.size(), "num comdats");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000520 for (const auto &C : Comdats) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000521 writeStr(Sub.OS, C.first, "comdat name");
522 writeUleb128(Sub.OS, 0, "comdat flags"); // flags for future use
523 writeUleb128(Sub.OS, C.second.size(), "num entries");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000524 for (const ComdatEntry &Entry : C.second) {
Sam Clegg8518e7d2018-03-01 18:06:39 +0000525 writeU8(Sub.OS, Entry.Kind, "entry kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000526 writeUleb128(Sub.OS, Entry.Index, "entry index");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000527 }
528 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000529 Sub.writeTo(OS);
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000530 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000531}
532
533// Create the custom "name" section containing debug symbol names.
534void Writer::createNameSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000535 unsigned NumNames = NumImportedFunctions;
Sam Clegg9f934222018-02-21 18:29:23 +0000536 for (const InputFunction *F : InputFunctions)
Nicholas Wilson6c7fe302018-04-20 17:09:18 +0000537 if (!F->getName().empty() || !F->getDebugName().empty())
Sam Clegg1963d712018-01-17 20:19:04 +0000538 ++NumNames;
Sam Cleggc94d3932017-11-17 18:14:09 +0000539
Sam Clegg1963d712018-01-17 20:19:04 +0000540 if (NumNames == 0)
541 return;
Sam Clegg50686852018-01-12 18:35:13 +0000542
Sam Cleggc94d3932017-11-17 18:14:09 +0000543 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "name");
544
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000545 SubSection Sub(WASM_NAMES_FUNCTION);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000546 writeUleb128(Sub.OS, NumNames, "name count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000547
Sam Clegg93102972018-02-23 05:08:53 +0000548 // Names must appear in function index order. As it happens ImportedSymbols
549 // and InputFunctions are numbered in order with imported functions coming
Sam Clegg1963d712018-01-17 20:19:04 +0000550 // first.
Sam Clegg93102972018-02-23 05:08:53 +0000551 for (const Symbol *S : ImportedSymbols) {
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000552 if (auto *F = dyn_cast<FunctionSymbol>(S)) {
553 writeUleb128(Sub.OS, F->getFunctionIndex(), "func index");
Nicholas Wilson531769b2018-03-13 13:30:04 +0000554 Optional<std::string> Name = demangleItanium(F->getName());
555 writeStr(Sub.OS, Name ? StringRef(*Name) : F->getName(), "symbol name");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000556 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000557 }
Sam Clegg9f934222018-02-21 18:29:23 +0000558 for (const InputFunction *F : InputFunctions) {
Sam Clegg1963d712018-01-17 20:19:04 +0000559 if (!F->getName().empty()) {
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000560 writeUleb128(Sub.OS, F->getFunctionIndex(), "func index");
Nicholas Wilson6c7fe302018-04-20 17:09:18 +0000561 if (!F->getDebugName().empty()) {
562 writeStr(Sub.OS, F->getDebugName(), "symbol name");
563 } else {
564 Optional<std::string> Name = demangleItanium(F->getName());
565 writeStr(Sub.OS, Name ? StringRef(*Name) : F->getName(), "symbol name");
566 }
Sam Clegg1963d712018-01-17 20:19:04 +0000567 }
568 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000569
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000570 Sub.writeTo(Section->getStream());
Sam Cleggc94d3932017-11-17 18:14:09 +0000571}
572
573void Writer::writeHeader() {
574 memcpy(Buffer->getBufferStart(), Header.data(), Header.size());
575}
576
577void Writer::writeSections() {
578 uint8_t *Buf = Buffer->getBufferStart();
579 parallelForEach(OutputSections, [Buf](OutputSection *S) { S->writeTo(Buf); });
580}
581
582// Fix the memory layout of the output binary. This assigns memory offsets
Sam Clegg49ed9262017-12-01 00:53:21 +0000583// to each of the input data sections as well as the explicit stack region.
Sam Cleggf0d433d2018-02-02 22:59:56 +0000584// The memory layout is as follows, from low to high.
585// - initialized data (starting at Config->GlobalBase)
586// - BSS data (not currently implemented in llvm)
587// - explicit stack (Config->ZStackSize)
588// - heap start / unallocated
Sam Cleggc94d3932017-11-17 18:14:09 +0000589void Writer::layoutMemory() {
590 uint32_t MemoryPtr = 0;
Sam Clegg99eb42c2018-02-27 23:58:03 +0000591 MemoryPtr = Config->GlobalBase;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000592 log("mem: global base = " + Twine(Config->GlobalBase));
Sam Cleggc94d3932017-11-17 18:14:09 +0000593
594 createOutputSegments();
595
Sam Cleggf0d433d2018-02-02 22:59:56 +0000596 // Arbitrarily set __dso_handle handle to point to the start of the data
597 // segments.
598 if (WasmSym::DsoHandle)
599 WasmSym::DsoHandle->setVirtualAddress(MemoryPtr);
600
Sam Cleggc94d3932017-11-17 18:14:09 +0000601 for (OutputSegment *Seg : Segments) {
602 MemoryPtr = alignTo(MemoryPtr, Seg->Alignment);
603 Seg->StartVA = MemoryPtr;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000604 log(formatv("mem: {0,-15} offset={1,-8} size={2,-8} align={3}", Seg->Name,
605 MemoryPtr, Seg->Size, Seg->Alignment));
Sam Cleggc94d3932017-11-17 18:14:09 +0000606 MemoryPtr += Seg->Size;
607 }
608
Sam Cleggf0d433d2018-02-02 22:59:56 +0000609 // TODO: Add .bss space here.
Sam Clegg37a4a8a2018-02-07 03:04:53 +0000610 if (WasmSym::DataEnd)
611 WasmSym::DataEnd->setVirtualAddress(MemoryPtr);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000612
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000613 log("mem: static data = " + Twine(MemoryPtr - Config->GlobalBase));
Sam Cleggc94d3932017-11-17 18:14:09 +0000614
Sam Cleggf0d433d2018-02-02 22:59:56 +0000615 // Stack comes after static data and bss
Sam Cleggc94d3932017-11-17 18:14:09 +0000616 if (!Config->Relocatable) {
617 MemoryPtr = alignTo(MemoryPtr, kStackAlignment);
618 if (Config->ZStackSize != alignTo(Config->ZStackSize, kStackAlignment))
619 error("stack size must be " + Twine(kStackAlignment) + "-byte aligned");
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000620 log("mem: stack size = " + Twine(Config->ZStackSize));
621 log("mem: stack base = " + Twine(MemoryPtr));
Sam Cleggc94d3932017-11-17 18:14:09 +0000622 MemoryPtr += Config->ZStackSize;
Sam Clegg93102972018-02-23 05:08:53 +0000623 WasmSym::StackPointer->Global->Global.InitExpr.Value.Int32 = MemoryPtr;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000624 log("mem: stack top = " + Twine(MemoryPtr));
Sam Clegg93102972018-02-23 05:08:53 +0000625
Sam Clegg51bcdc22018-01-17 01:34:31 +0000626 // Set `__heap_base` to directly follow the end of the stack. We don't
627 // allocate any heap memory up front, but instead really on the malloc/brk
628 // implementation growing the memory at runtime.
Sam Cleggf0d433d2018-02-02 22:59:56 +0000629 WasmSym::HeapBase->setVirtualAddress(MemoryPtr);
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000630 log("mem: heap base = " + Twine(MemoryPtr));
Sam Cleggc94d3932017-11-17 18:14:09 +0000631 }
632
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000633 if (Config->InitialMemory != 0) {
634 if (Config->InitialMemory != alignTo(Config->InitialMemory, WasmPageSize))
635 error("initial memory must be " + Twine(WasmPageSize) + "-byte aligned");
636 if (MemoryPtr > Config->InitialMemory)
637 error("initial memory too small, " + Twine(MemoryPtr) + " bytes needed");
638 else
639 MemoryPtr = Config->InitialMemory;
640 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000641 uint32_t MemSize = alignTo(MemoryPtr, WasmPageSize);
642 NumMemoryPages = MemSize / WasmPageSize;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000643 log("mem: total pages = " + Twine(NumMemoryPages));
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000644
645 if (Config->MaxMemory != 0) {
646 if (Config->MaxMemory != alignTo(Config->MaxMemory, WasmPageSize))
647 error("maximum memory must be " + Twine(WasmPageSize) + "-byte aligned");
648 if (MemoryPtr > Config->MaxMemory)
649 error("maximum memory too small, " + Twine(MemoryPtr) + " bytes needed");
650 MaxMemoryPages = Config->MaxMemory / WasmPageSize;
651 log("mem: max pages = " + Twine(MaxMemoryPages));
652 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000653}
654
655SyntheticSection *Writer::createSyntheticSection(uint32_t Type,
Sam Cleggc375e4e2018-01-10 19:18:22 +0000656 StringRef Name) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000657 auto Sec = make<SyntheticSection>(Type, Name);
Sam Cleggab2ac292017-12-20 05:14:48 +0000658 log("createSection: " + toString(*Sec));
Sam Cleggc94d3932017-11-17 18:14:09 +0000659 OutputSections.push_back(Sec);
660 return Sec;
661}
662
663void Writer::createSections() {
664 // Known sections
665 createTypeSection();
666 createImportSection();
667 createFunctionSection();
668 createTableSection();
669 createMemorySection();
670 createGlobalSection();
671 createExportSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000672 createElemSection();
673 createCodeSection();
674 createDataSection();
Sam Clegg80ba4382018-04-10 16:12:49 +0000675 createCustomSections();
Sam Cleggc94d3932017-11-17 18:14:09 +0000676
677 // Custom sections
Sam Clegg99eb42c2018-02-27 23:58:03 +0000678 if (Config->Relocatable) {
Sam Clegg99eb42c2018-02-27 23:58:03 +0000679 createLinkingSection();
Nicholas Wilson94d3b162018-03-05 12:33:58 +0000680 createRelocSections();
Sam Clegg99eb42c2018-02-27 23:58:03 +0000681 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000682 if (!Config->StripDebug && !Config->StripAll)
683 createNameSection();
684
685 for (OutputSection *S : OutputSections) {
686 S->setOffset(FileSize);
687 S->finalizeContents();
688 FileSize += S->getSize();
689 }
690}
691
Sam Cleggc94d3932017-11-17 18:14:09 +0000692void Writer::calculateImports() {
Sam Clegg574d7ce2017-12-15 19:23:49 +0000693 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000694 if (!Sym->isUndefined())
695 continue;
696 if (isa<DataSymbol>(Sym))
697 continue;
698 if (Sym->isWeak() && !Config->Relocatable)
Sam Clegg574d7ce2017-12-15 19:23:49 +0000699 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000700
Sam Clegg93102972018-02-23 05:08:53 +0000701 DEBUG(dbgs() << "import: " << Sym->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000702 ImportedSymbols.emplace_back(Sym);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000703 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
704 F->setFunctionIndex(NumImportedFunctions++);
Sam Clegg93102972018-02-23 05:08:53 +0000705 else
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000706 cast<GlobalSymbol>(Sym)->setGlobalIndex(NumImportedGlobals++);
Sam Cleggc94d3932017-11-17 18:14:09 +0000707 }
708}
709
Sam Cleggd3052d52018-01-18 23:40:49 +0000710void Writer::calculateExports() {
Sam Clegg93102972018-02-23 05:08:53 +0000711 if (Config->Relocatable)
712 return;
Sam Cleggf0d433d2018-02-02 22:59:56 +0000713
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000714 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000715 if (!Sym->isDefined())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000716 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000717 if (Sym->isHidden() || Sym->isLocal())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000718 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000719 if (!Sym->isLive())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000720 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000721
722 DEBUG(dbgs() << "exporting sym: " << Sym->getName() << "\n");
723
Nicholas Wilsonf2f6d5e2018-03-02 14:51:36 +0000724 if (auto *D = dyn_cast<DefinedData>(Sym))
Sam Clegg93102972018-02-23 05:08:53 +0000725 DefinedFakeGlobals.emplace_back(D);
Sam Clegg93102972018-02-23 05:08:53 +0000726 ExportedSymbols.emplace_back(Sym);
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000727 }
Sam Clegg93102972018-02-23 05:08:53 +0000728}
729
730void Writer::assignSymtab() {
731 if (!Config->Relocatable)
732 return;
733
734 unsigned SymbolIndex = SymtabEntries.size();
Sam Cleggd3052d52018-01-18 23:40:49 +0000735 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg93102972018-02-23 05:08:53 +0000736 DEBUG(dbgs() << "Symtab entries: " << File->getName() << "\n");
Sam Cleggd3052d52018-01-18 23:40:49 +0000737 for (Symbol *Sym : File->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000738 if (Sym->getFile() != File)
Sam Cleggd3052d52018-01-18 23:40:49 +0000739 continue;
Nicholas Wilson06e0d172018-03-07 11:15:47 +0000740 // (Since this is relocatable output, GC is not performed so symbols must
741 // be live.)
742 assert(Sym->isLive());
Sam Clegg93102972018-02-23 05:08:53 +0000743 Sym->setOutputSymbolIndex(SymbolIndex++);
744 SymtabEntries.emplace_back(Sym);
Sam Cleggd3052d52018-01-18 23:40:49 +0000745 }
746 }
747
Sam Clegg93102972018-02-23 05:08:53 +0000748 // For the moment, relocatable output doesn't contain any synthetic functions,
749 // so no need to look through the Symtab for symbols not referenced by
750 // Symtab->ObjectFiles.
Sam Cleggd3052d52018-01-18 23:40:49 +0000751}
752
Sam Cleggc375e4e2018-01-10 19:18:22 +0000753uint32_t Writer::lookupType(const WasmSignature &Sig) {
Sam Clegg8d027d62018-01-10 20:12:26 +0000754 auto It = TypeIndices.find(Sig);
755 if (It == TypeIndices.end()) {
Sam Cleggc375e4e2018-01-10 19:18:22 +0000756 error("type not found: " + toString(Sig));
Sam Clegg8d027d62018-01-10 20:12:26 +0000757 return 0;
758 }
759 return It->second;
Sam Cleggc375e4e2018-01-10 19:18:22 +0000760}
761
762uint32_t Writer::registerType(const WasmSignature &Sig) {
Sam Cleggb8621592017-11-30 01:40:08 +0000763 auto Pair = TypeIndices.insert(std::make_pair(Sig, Types.size()));
Sam Cleggc375e4e2018-01-10 19:18:22 +0000764 if (Pair.second) {
765 DEBUG(dbgs() << "type " << toString(Sig) << "\n");
Sam Cleggb8621592017-11-30 01:40:08 +0000766 Types.push_back(&Sig);
Sam Cleggc375e4e2018-01-10 19:18:22 +0000767 }
Sam Cleggb8621592017-11-30 01:40:08 +0000768 return Pair.first->second;
769}
770
Sam Cleggc94d3932017-11-17 18:14:09 +0000771void Writer::calculateTypes() {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000772 // The output type section is the union of the following sets:
773 // 1. Any signature used in the TYPE relocation
774 // 2. The signatures of all imported functions
775 // 3. The signatures of all defined functions
776
Sam Cleggc94d3932017-11-17 18:14:09 +0000777 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000778 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
779 for (uint32_t I = 0; I < Types.size(); I++)
780 if (File->TypeIsUsed[I])
781 File->TypeMap[I] = registerType(Types[I]);
Sam Cleggc94d3932017-11-17 18:14:09 +0000782 }
Sam Clegg50686852018-01-12 18:35:13 +0000783
Sam Clegg93102972018-02-23 05:08:53 +0000784 for (const Symbol *Sym : ImportedSymbols)
785 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
786 registerType(*F->getFunctionType());
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000787
Sam Clegg9f934222018-02-21 18:29:23 +0000788 for (const InputFunction *F : InputFunctions)
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000789 registerType(F->Signature);
Sam Cleggc94d3932017-11-17 18:14:09 +0000790}
791
Sam Clegg8d146bb2018-01-09 23:56:44 +0000792void Writer::assignIndexes() {
Sam Clegg93102972018-02-23 05:08:53 +0000793 uint32_t FunctionIndex = NumImportedFunctions + InputFunctions.size();
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000794 auto AddDefinedFunction = [&](InputFunction *Func) {
795 if (!Func->Live)
796 return;
797 InputFunctions.emplace_back(Func);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000798 Func->setFunctionIndex(FunctionIndex++);
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000799 };
800
Nicholas Wilson5639da82018-03-12 15:44:07 +0000801 for (InputFunction *Func : Symtab->SyntheticFunctions)
802 AddDefinedFunction(Func);
803
Sam Clegg87e61922018-01-08 23:39:11 +0000804 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8d146bb2018-01-09 23:56:44 +0000805 DEBUG(dbgs() << "Functions: " << File->getName() << "\n");
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000806 for (InputFunction *Func : File->Functions)
807 AddDefinedFunction(Func);
Sam Clegg8d146bb2018-01-09 23:56:44 +0000808 }
809
Sam Clegg93102972018-02-23 05:08:53 +0000810 uint32_t TableIndex = kInitialTableOffset;
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000811 auto HandleRelocs = [&](InputChunk *Chunk) {
812 if (!Chunk->Live)
813 return;
814 ObjFile *File = Chunk->File;
815 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
Sam Clegg93102972018-02-23 05:08:53 +0000816 for (const WasmRelocation &Reloc : Chunk->getRelocations()) {
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000817 if (Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_I32 ||
818 Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_SLEB) {
819 FunctionSymbol *Sym = File->getFunctionSymbol(Reloc.Index);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000820 if (Sym->hasTableIndex() || !Sym->hasFunctionIndex())
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000821 continue;
822 Sym->setTableIndex(TableIndex++);
823 IndirectFunctions.emplace_back(Sym);
824 } else if (Reloc.Type == R_WEBASSEMBLY_TYPE_INDEX_LEB) {
Sam Clegg93102972018-02-23 05:08:53 +0000825 // Mark target type as live
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000826 File->TypeMap[Reloc.Index] = registerType(Types[Reloc.Index]);
827 File->TypeIsUsed[Reloc.Index] = true;
Sam Clegg93102972018-02-23 05:08:53 +0000828 } else if (Reloc.Type == R_WEBASSEMBLY_GLOBAL_INDEX_LEB) {
829 // Mark target global as live
830 GlobalSymbol *Sym = File->getGlobalSymbol(Reloc.Index);
831 if (auto *G = dyn_cast<DefinedGlobal>(Sym)) {
832 DEBUG(dbgs() << "marking global live: " << Sym->getName() << "\n");
833 G->Global->Live = true;
834 }
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000835 }
836 }
837 };
838
Sam Clegg8d146bb2018-01-09 23:56:44 +0000839 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000840 DEBUG(dbgs() << "Handle relocs: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000841 for (InputChunk *Chunk : File->Functions)
842 HandleRelocs(Chunk);
843 for (InputChunk *Chunk : File->Segments)
844 HandleRelocs(Chunk);
845 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000846
Sam Clegg93102972018-02-23 05:08:53 +0000847 uint32_t GlobalIndex = NumImportedGlobals + InputGlobals.size();
848 auto AddDefinedGlobal = [&](InputGlobal *Global) {
849 if (Global->Live) {
850 DEBUG(dbgs() << "AddDefinedGlobal: " << GlobalIndex << "\n");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000851 Global->setGlobalIndex(GlobalIndex++);
Sam Clegg93102972018-02-23 05:08:53 +0000852 InputGlobals.push_back(Global);
853 }
854 };
855
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000856 for (InputGlobal *Global : Symtab->SyntheticGlobals)
857 AddDefinedGlobal(Global);
Sam Clegg93102972018-02-23 05:08:53 +0000858
859 for (ObjFile *File : Symtab->ObjectFiles) {
860 DEBUG(dbgs() << "Globals: " << File->getName() << "\n");
861 for (InputGlobal *Global : File->Globals)
862 AddDefinedGlobal(Global);
Sam Cleggc94d3932017-11-17 18:14:09 +0000863 }
864}
865
866static StringRef getOutputDataSegmentName(StringRef Name) {
867 if (Config->Relocatable)
868 return Name;
Rui Ueyama4764b572018-02-28 00:57:28 +0000869 if (Name.startswith(".text."))
870 return ".text";
871 if (Name.startswith(".data."))
872 return ".data";
873 if (Name.startswith(".bss."))
874 return ".bss";
Sam Cleggc94d3932017-11-17 18:14:09 +0000875 return Name;
876}
877
878void Writer::createOutputSegments() {
879 for (ObjFile *File : Symtab->ObjectFiles) {
880 for (InputSegment *Segment : File->Segments) {
Sam Clegg447ae402018-02-13 20:29:38 +0000881 if (!Segment->Live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000882 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000883 StringRef Name = getOutputDataSegmentName(Segment->getName());
884 OutputSegment *&S = SegmentMap[Name];
885 if (S == nullptr) {
886 DEBUG(dbgs() << "new segment: " << Name << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000887 S = make<OutputSegment>(Name, Segments.size());
Sam Cleggc94d3932017-11-17 18:14:09 +0000888 Segments.push_back(S);
889 }
890 S->addInputSegment(Segment);
891 DEBUG(dbgs() << "added data: " << Name << ": " << S->Size << "\n");
Sam Cleggc94d3932017-11-17 18:14:09 +0000892 }
893 }
894}
895
Sam Clegg50686852018-01-12 18:35:13 +0000896static const int OPCODE_CALL = 0x10;
897static const int OPCODE_END = 0xb;
898
899// Create synthetic "__wasm_call_ctors" function based on ctor functions
900// in input object.
901void Writer::createCtorFunction() {
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000902 // First write the body's contents to a string.
903 std::string BodyContent;
Sam Clegg50686852018-01-12 18:35:13 +0000904 {
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000905 raw_string_ostream OS(BodyContent);
Sam Clegg50686852018-01-12 18:35:13 +0000906 writeUleb128(OS, 0, "num locals");
Sam Clegg93102972018-02-23 05:08:53 +0000907 for (const WasmInitEntry &F : InitFunctions) {
Sam Clegg50686852018-01-12 18:35:13 +0000908 writeU8(OS, OPCODE_CALL, "CALL");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000909 writeUleb128(OS, F.Sym->getFunctionIndex(), "function index");
Sam Clegg50686852018-01-12 18:35:13 +0000910 }
911 writeU8(OS, OPCODE_END, "END");
912 }
913
914 // Once we know the size of the body we can create the final function body
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000915 std::string FunctionBody;
916 {
917 raw_string_ostream OS(FunctionBody);
918 writeUleb128(OS, BodyContent.size(), "function size");
919 OS << BodyContent;
920 }
Rui Ueyama29abfe42018-02-28 17:43:15 +0000921
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000922 ArrayRef<uint8_t> Body = toArrayRef(Saver.save(FunctionBody));
923 cast<SyntheticFunction>(WasmSym::CallCtors->Function)->setBody(Body);
Sam Clegg50686852018-01-12 18:35:13 +0000924}
925
926// Populate InitFunctions vector with init functions from all input objects.
927// This is then used either when creating the output linking section or to
928// synthesize the "__wasm_call_ctors" function.
929void Writer::calculateInitFunctions() {
930 for (ObjFile *File : Symtab->ObjectFiles) {
931 const WasmLinkingData &L = File->getWasmObj()->linkingData();
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +0000932 for (const WasmInitFunc &F : L.InitFunctions) {
933 FunctionSymbol *Sym = File->getFunctionSymbol(F.Symbol);
934 if (*Sym->getFunctionType() != WasmSignature{{}, WASM_TYPE_NORESULT})
935 error("invalid signature for init func: " + toString(*Sym));
936 InitFunctions.emplace_back(WasmInitEntry{Sym, F.Priority});
937 }
Sam Clegg50686852018-01-12 18:35:13 +0000938 }
Rui Ueyamada69b712018-02-28 00:15:59 +0000939
Sam Clegg50686852018-01-12 18:35:13 +0000940 // Sort in order of priority (lowest first) so that they are called
941 // in the correct order.
Sam Clegg29b8feb2018-02-21 00:34:34 +0000942 std::stable_sort(InitFunctions.begin(), InitFunctions.end(),
Sam Clegg93102972018-02-23 05:08:53 +0000943 [](const WasmInitEntry &L, const WasmInitEntry &R) {
Sam Clegg29b8feb2018-02-21 00:34:34 +0000944 return L.Priority < R.Priority;
945 });
Sam Clegg50686852018-01-12 18:35:13 +0000946}
947
Sam Cleggc94d3932017-11-17 18:14:09 +0000948void Writer::run() {
Sam Clegg99eb42c2018-02-27 23:58:03 +0000949 if (Config->Relocatable)
950 Config->GlobalBase = 0;
951
Sam Cleggc94d3932017-11-17 18:14:09 +0000952 log("-- calculateImports");
953 calculateImports();
Sam Clegg8d146bb2018-01-09 23:56:44 +0000954 log("-- assignIndexes");
955 assignIndexes();
Sam Clegg50686852018-01-12 18:35:13 +0000956 log("-- calculateInitFunctions");
957 calculateInitFunctions();
958 if (!Config->Relocatable)
959 createCtorFunction();
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000960 log("-- calculateTypes");
961 calculateTypes();
Sam Clegg93102972018-02-23 05:08:53 +0000962 log("-- layoutMemory");
963 layoutMemory();
964 log("-- calculateExports");
965 calculateExports();
966 log("-- assignSymtab");
967 assignSymtab();
Sam Cleggc94d3932017-11-17 18:14:09 +0000968
969 if (errorHandler().Verbose) {
Sam Clegg9f934222018-02-21 18:29:23 +0000970 log("Defined Functions: " + Twine(InputFunctions.size()));
Sam Clegg93102972018-02-23 05:08:53 +0000971 log("Defined Globals : " + Twine(InputGlobals.size()));
972 log("Function Imports : " + Twine(NumImportedFunctions));
973 log("Global Imports : " + Twine(NumImportedGlobals));
Sam Cleggc94d3932017-11-17 18:14:09 +0000974 for (ObjFile *File : Symtab->ObjectFiles)
975 File->dumpInfo();
976 }
977
Sam Cleggc94d3932017-11-17 18:14:09 +0000978 createHeader();
979 log("-- createSections");
980 createSections();
981
982 log("-- openFile");
983 openFile();
984 if (errorCount())
985 return;
986
987 writeHeader();
988
989 log("-- writeSections");
990 writeSections();
991 if (errorCount())
992 return;
993
994 if (Error E = Buffer->commit())
995 fatal("failed to write the output file: " + toString(std::move(E)));
996}
997
998// Open a result file.
999void Writer::openFile() {
1000 log("writing: " + Config->OutputFile);
Sam Cleggc94d3932017-11-17 18:14:09 +00001001
1002 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
1003 FileOutputBuffer::create(Config->OutputFile, FileSize,
1004 FileOutputBuffer::F_executable);
1005
1006 if (!BufferOrErr)
1007 error("failed to open " + Config->OutputFile + ": " +
1008 toString(BufferOrErr.takeError()));
1009 else
1010 Buffer = std::move(*BufferOrErr);
1011}
1012
1013void Writer::createHeader() {
1014 raw_string_ostream OS(Header);
1015 writeBytes(OS, WasmMagic, sizeof(WasmMagic), "wasm magic");
1016 writeU32(OS, WasmVersion, "wasm version");
1017 OS.flush();
1018 FileSize += Header.size();
1019}
1020
1021void lld::wasm::writeResult() { Writer().run(); }