blob: 18d5d4a8d520a802de250bc424c40db754044aaf [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)
Sam Clegg1963d712018-01-17 20:19:04 +0000537 if (!F->getName().empty())
538 ++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 Wilson531769b2018-03-13 13:30:04 +0000561 Optional<std::string> Name = demangleItanium(F->getName());
562 writeStr(Sub.OS, Name ? StringRef(*Name) : F->getName(), "symbol name");
Sam Clegg1963d712018-01-17 20:19:04 +0000563 }
564 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000565
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000566 Sub.writeTo(Section->getStream());
Sam Cleggc94d3932017-11-17 18:14:09 +0000567}
568
569void Writer::writeHeader() {
570 memcpy(Buffer->getBufferStart(), Header.data(), Header.size());
571}
572
573void Writer::writeSections() {
574 uint8_t *Buf = Buffer->getBufferStart();
575 parallelForEach(OutputSections, [Buf](OutputSection *S) { S->writeTo(Buf); });
576}
577
578// Fix the memory layout of the output binary. This assigns memory offsets
Sam Clegg49ed9262017-12-01 00:53:21 +0000579// to each of the input data sections as well as the explicit stack region.
Sam Cleggf0d433d2018-02-02 22:59:56 +0000580// The memory layout is as follows, from low to high.
581// - initialized data (starting at Config->GlobalBase)
582// - BSS data (not currently implemented in llvm)
583// - explicit stack (Config->ZStackSize)
584// - heap start / unallocated
Sam Cleggc94d3932017-11-17 18:14:09 +0000585void Writer::layoutMemory() {
586 uint32_t MemoryPtr = 0;
Sam Clegg99eb42c2018-02-27 23:58:03 +0000587 MemoryPtr = Config->GlobalBase;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000588 log("mem: global base = " + Twine(Config->GlobalBase));
Sam Cleggc94d3932017-11-17 18:14:09 +0000589
590 createOutputSegments();
591
Sam Cleggf0d433d2018-02-02 22:59:56 +0000592 // Arbitrarily set __dso_handle handle to point to the start of the data
593 // segments.
594 if (WasmSym::DsoHandle)
595 WasmSym::DsoHandle->setVirtualAddress(MemoryPtr);
596
Sam Cleggc94d3932017-11-17 18:14:09 +0000597 for (OutputSegment *Seg : Segments) {
598 MemoryPtr = alignTo(MemoryPtr, Seg->Alignment);
599 Seg->StartVA = MemoryPtr;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000600 log(formatv("mem: {0,-15} offset={1,-8} size={2,-8} align={3}", Seg->Name,
601 MemoryPtr, Seg->Size, Seg->Alignment));
Sam Cleggc94d3932017-11-17 18:14:09 +0000602 MemoryPtr += Seg->Size;
603 }
604
Sam Cleggf0d433d2018-02-02 22:59:56 +0000605 // TODO: Add .bss space here.
Sam Clegg37a4a8a2018-02-07 03:04:53 +0000606 if (WasmSym::DataEnd)
607 WasmSym::DataEnd->setVirtualAddress(MemoryPtr);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000608
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000609 log("mem: static data = " + Twine(MemoryPtr - Config->GlobalBase));
Sam Cleggc94d3932017-11-17 18:14:09 +0000610
Sam Cleggf0d433d2018-02-02 22:59:56 +0000611 // Stack comes after static data and bss
Sam Cleggc94d3932017-11-17 18:14:09 +0000612 if (!Config->Relocatable) {
613 MemoryPtr = alignTo(MemoryPtr, kStackAlignment);
614 if (Config->ZStackSize != alignTo(Config->ZStackSize, kStackAlignment))
615 error("stack size must be " + Twine(kStackAlignment) + "-byte aligned");
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000616 log("mem: stack size = " + Twine(Config->ZStackSize));
617 log("mem: stack base = " + Twine(MemoryPtr));
Sam Cleggc94d3932017-11-17 18:14:09 +0000618 MemoryPtr += Config->ZStackSize;
Sam Clegg93102972018-02-23 05:08:53 +0000619 WasmSym::StackPointer->Global->Global.InitExpr.Value.Int32 = MemoryPtr;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000620 log("mem: stack top = " + Twine(MemoryPtr));
Sam Clegg93102972018-02-23 05:08:53 +0000621
Sam Clegg51bcdc22018-01-17 01:34:31 +0000622 // Set `__heap_base` to directly follow the end of the stack. We don't
623 // allocate any heap memory up front, but instead really on the malloc/brk
624 // implementation growing the memory at runtime.
Sam Cleggf0d433d2018-02-02 22:59:56 +0000625 WasmSym::HeapBase->setVirtualAddress(MemoryPtr);
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000626 log("mem: heap base = " + Twine(MemoryPtr));
Sam Cleggc94d3932017-11-17 18:14:09 +0000627 }
628
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000629 if (Config->InitialMemory != 0) {
630 if (Config->InitialMemory != alignTo(Config->InitialMemory, WasmPageSize))
631 error("initial memory must be " + Twine(WasmPageSize) + "-byte aligned");
632 if (MemoryPtr > Config->InitialMemory)
633 error("initial memory too small, " + Twine(MemoryPtr) + " bytes needed");
634 else
635 MemoryPtr = Config->InitialMemory;
636 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000637 uint32_t MemSize = alignTo(MemoryPtr, WasmPageSize);
638 NumMemoryPages = MemSize / WasmPageSize;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000639 log("mem: total pages = " + Twine(NumMemoryPages));
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000640
641 if (Config->MaxMemory != 0) {
642 if (Config->MaxMemory != alignTo(Config->MaxMemory, WasmPageSize))
643 error("maximum memory must be " + Twine(WasmPageSize) + "-byte aligned");
644 if (MemoryPtr > Config->MaxMemory)
645 error("maximum memory too small, " + Twine(MemoryPtr) + " bytes needed");
646 MaxMemoryPages = Config->MaxMemory / WasmPageSize;
647 log("mem: max pages = " + Twine(MaxMemoryPages));
648 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000649}
650
651SyntheticSection *Writer::createSyntheticSection(uint32_t Type,
Sam Cleggc375e4e2018-01-10 19:18:22 +0000652 StringRef Name) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000653 auto Sec = make<SyntheticSection>(Type, Name);
Sam Cleggab2ac292017-12-20 05:14:48 +0000654 log("createSection: " + toString(*Sec));
Sam Cleggc94d3932017-11-17 18:14:09 +0000655 OutputSections.push_back(Sec);
656 return Sec;
657}
658
659void Writer::createSections() {
660 // Known sections
661 createTypeSection();
662 createImportSection();
663 createFunctionSection();
664 createTableSection();
665 createMemorySection();
666 createGlobalSection();
667 createExportSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000668 createElemSection();
669 createCodeSection();
670 createDataSection();
Sam Clegg80ba4382018-04-10 16:12:49 +0000671 createCustomSections();
Sam Cleggc94d3932017-11-17 18:14:09 +0000672
673 // Custom sections
Sam Clegg99eb42c2018-02-27 23:58:03 +0000674 if (Config->Relocatable) {
Sam Clegg99eb42c2018-02-27 23:58:03 +0000675 createLinkingSection();
Nicholas Wilson94d3b162018-03-05 12:33:58 +0000676 createRelocSections();
Sam Clegg99eb42c2018-02-27 23:58:03 +0000677 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000678 if (!Config->StripDebug && !Config->StripAll)
679 createNameSection();
680
681 for (OutputSection *S : OutputSections) {
682 S->setOffset(FileSize);
683 S->finalizeContents();
684 FileSize += S->getSize();
685 }
686}
687
Sam Cleggc94d3932017-11-17 18:14:09 +0000688void Writer::calculateImports() {
Sam Clegg574d7ce2017-12-15 19:23:49 +0000689 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000690 if (!Sym->isUndefined())
691 continue;
692 if (isa<DataSymbol>(Sym))
693 continue;
694 if (Sym->isWeak() && !Config->Relocatable)
Sam Clegg574d7ce2017-12-15 19:23:49 +0000695 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000696
Sam Clegg93102972018-02-23 05:08:53 +0000697 DEBUG(dbgs() << "import: " << Sym->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000698 ImportedSymbols.emplace_back(Sym);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000699 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
700 F->setFunctionIndex(NumImportedFunctions++);
Sam Clegg93102972018-02-23 05:08:53 +0000701 else
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000702 cast<GlobalSymbol>(Sym)->setGlobalIndex(NumImportedGlobals++);
Sam Cleggc94d3932017-11-17 18:14:09 +0000703 }
704}
705
Sam Cleggd3052d52018-01-18 23:40:49 +0000706void Writer::calculateExports() {
Sam Clegg93102972018-02-23 05:08:53 +0000707 if (Config->Relocatable)
708 return;
Sam Cleggf0d433d2018-02-02 22:59:56 +0000709
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000710 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000711 if (!Sym->isDefined())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000712 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000713 if (Sym->isHidden() || Sym->isLocal())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000714 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000715 if (!Sym->isLive())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000716 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000717
718 DEBUG(dbgs() << "exporting sym: " << Sym->getName() << "\n");
719
Nicholas Wilsonf2f6d5e2018-03-02 14:51:36 +0000720 if (auto *D = dyn_cast<DefinedData>(Sym))
Sam Clegg93102972018-02-23 05:08:53 +0000721 DefinedFakeGlobals.emplace_back(D);
Sam Clegg93102972018-02-23 05:08:53 +0000722 ExportedSymbols.emplace_back(Sym);
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000723 }
Sam Clegg93102972018-02-23 05:08:53 +0000724}
725
726void Writer::assignSymtab() {
727 if (!Config->Relocatable)
728 return;
729
730 unsigned SymbolIndex = SymtabEntries.size();
Sam Cleggd3052d52018-01-18 23:40:49 +0000731 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg93102972018-02-23 05:08:53 +0000732 DEBUG(dbgs() << "Symtab entries: " << File->getName() << "\n");
Sam Cleggd3052d52018-01-18 23:40:49 +0000733 for (Symbol *Sym : File->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000734 if (Sym->getFile() != File)
Sam Cleggd3052d52018-01-18 23:40:49 +0000735 continue;
Nicholas Wilson06e0d172018-03-07 11:15:47 +0000736 // (Since this is relocatable output, GC is not performed so symbols must
737 // be live.)
738 assert(Sym->isLive());
Sam Clegg93102972018-02-23 05:08:53 +0000739 Sym->setOutputSymbolIndex(SymbolIndex++);
740 SymtabEntries.emplace_back(Sym);
Sam Cleggd3052d52018-01-18 23:40:49 +0000741 }
742 }
743
Sam Clegg93102972018-02-23 05:08:53 +0000744 // For the moment, relocatable output doesn't contain any synthetic functions,
745 // so no need to look through the Symtab for symbols not referenced by
746 // Symtab->ObjectFiles.
Sam Cleggd3052d52018-01-18 23:40:49 +0000747}
748
Sam Cleggc375e4e2018-01-10 19:18:22 +0000749uint32_t Writer::lookupType(const WasmSignature &Sig) {
Sam Clegg8d027d62018-01-10 20:12:26 +0000750 auto It = TypeIndices.find(Sig);
751 if (It == TypeIndices.end()) {
Sam Cleggc375e4e2018-01-10 19:18:22 +0000752 error("type not found: " + toString(Sig));
Sam Clegg8d027d62018-01-10 20:12:26 +0000753 return 0;
754 }
755 return It->second;
Sam Cleggc375e4e2018-01-10 19:18:22 +0000756}
757
758uint32_t Writer::registerType(const WasmSignature &Sig) {
Sam Cleggb8621592017-11-30 01:40:08 +0000759 auto Pair = TypeIndices.insert(std::make_pair(Sig, Types.size()));
Sam Cleggc375e4e2018-01-10 19:18:22 +0000760 if (Pair.second) {
761 DEBUG(dbgs() << "type " << toString(Sig) << "\n");
Sam Cleggb8621592017-11-30 01:40:08 +0000762 Types.push_back(&Sig);
Sam Cleggc375e4e2018-01-10 19:18:22 +0000763 }
Sam Cleggb8621592017-11-30 01:40:08 +0000764 return Pair.first->second;
765}
766
Sam Cleggc94d3932017-11-17 18:14:09 +0000767void Writer::calculateTypes() {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000768 // The output type section is the union of the following sets:
769 // 1. Any signature used in the TYPE relocation
770 // 2. The signatures of all imported functions
771 // 3. The signatures of all defined functions
772
Sam Cleggc94d3932017-11-17 18:14:09 +0000773 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000774 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
775 for (uint32_t I = 0; I < Types.size(); I++)
776 if (File->TypeIsUsed[I])
777 File->TypeMap[I] = registerType(Types[I]);
Sam Cleggc94d3932017-11-17 18:14:09 +0000778 }
Sam Clegg50686852018-01-12 18:35:13 +0000779
Sam Clegg93102972018-02-23 05:08:53 +0000780 for (const Symbol *Sym : ImportedSymbols)
781 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
782 registerType(*F->getFunctionType());
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000783
Sam Clegg9f934222018-02-21 18:29:23 +0000784 for (const InputFunction *F : InputFunctions)
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000785 registerType(F->Signature);
Sam Cleggc94d3932017-11-17 18:14:09 +0000786}
787
Sam Clegg8d146bb2018-01-09 23:56:44 +0000788void Writer::assignIndexes() {
Sam Clegg93102972018-02-23 05:08:53 +0000789 uint32_t FunctionIndex = NumImportedFunctions + InputFunctions.size();
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000790 auto AddDefinedFunction = [&](InputFunction *Func) {
791 if (!Func->Live)
792 return;
793 InputFunctions.emplace_back(Func);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000794 Func->setFunctionIndex(FunctionIndex++);
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000795 };
796
Nicholas Wilson5639da82018-03-12 15:44:07 +0000797 for (InputFunction *Func : Symtab->SyntheticFunctions)
798 AddDefinedFunction(Func);
799
Sam Clegg87e61922018-01-08 23:39:11 +0000800 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8d146bb2018-01-09 23:56:44 +0000801 DEBUG(dbgs() << "Functions: " << File->getName() << "\n");
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000802 for (InputFunction *Func : File->Functions)
803 AddDefinedFunction(Func);
Sam Clegg8d146bb2018-01-09 23:56:44 +0000804 }
805
Sam Clegg93102972018-02-23 05:08:53 +0000806 uint32_t TableIndex = kInitialTableOffset;
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000807 auto HandleRelocs = [&](InputChunk *Chunk) {
808 if (!Chunk->Live)
809 return;
810 ObjFile *File = Chunk->File;
811 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
Sam Clegg93102972018-02-23 05:08:53 +0000812 for (const WasmRelocation &Reloc : Chunk->getRelocations()) {
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000813 if (Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_I32 ||
814 Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_SLEB) {
815 FunctionSymbol *Sym = File->getFunctionSymbol(Reloc.Index);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000816 if (Sym->hasTableIndex() || !Sym->hasFunctionIndex())
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000817 continue;
818 Sym->setTableIndex(TableIndex++);
819 IndirectFunctions.emplace_back(Sym);
820 } else if (Reloc.Type == R_WEBASSEMBLY_TYPE_INDEX_LEB) {
Sam Clegg93102972018-02-23 05:08:53 +0000821 // Mark target type as live
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000822 File->TypeMap[Reloc.Index] = registerType(Types[Reloc.Index]);
823 File->TypeIsUsed[Reloc.Index] = true;
Sam Clegg93102972018-02-23 05:08:53 +0000824 } else if (Reloc.Type == R_WEBASSEMBLY_GLOBAL_INDEX_LEB) {
825 // Mark target global as live
826 GlobalSymbol *Sym = File->getGlobalSymbol(Reloc.Index);
827 if (auto *G = dyn_cast<DefinedGlobal>(Sym)) {
828 DEBUG(dbgs() << "marking global live: " << Sym->getName() << "\n");
829 G->Global->Live = true;
830 }
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000831 }
832 }
833 };
834
Sam Clegg8d146bb2018-01-09 23:56:44 +0000835 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000836 DEBUG(dbgs() << "Handle relocs: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000837 for (InputChunk *Chunk : File->Functions)
838 HandleRelocs(Chunk);
839 for (InputChunk *Chunk : File->Segments)
840 HandleRelocs(Chunk);
841 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000842
Sam Clegg93102972018-02-23 05:08:53 +0000843 uint32_t GlobalIndex = NumImportedGlobals + InputGlobals.size();
844 auto AddDefinedGlobal = [&](InputGlobal *Global) {
845 if (Global->Live) {
846 DEBUG(dbgs() << "AddDefinedGlobal: " << GlobalIndex << "\n");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000847 Global->setGlobalIndex(GlobalIndex++);
Sam Clegg93102972018-02-23 05:08:53 +0000848 InputGlobals.push_back(Global);
849 }
850 };
851
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000852 for (InputGlobal *Global : Symtab->SyntheticGlobals)
853 AddDefinedGlobal(Global);
Sam Clegg93102972018-02-23 05:08:53 +0000854
855 for (ObjFile *File : Symtab->ObjectFiles) {
856 DEBUG(dbgs() << "Globals: " << File->getName() << "\n");
857 for (InputGlobal *Global : File->Globals)
858 AddDefinedGlobal(Global);
Sam Cleggc94d3932017-11-17 18:14:09 +0000859 }
860}
861
862static StringRef getOutputDataSegmentName(StringRef Name) {
863 if (Config->Relocatable)
864 return Name;
Rui Ueyama4764b572018-02-28 00:57:28 +0000865 if (Name.startswith(".text."))
866 return ".text";
867 if (Name.startswith(".data."))
868 return ".data";
869 if (Name.startswith(".bss."))
870 return ".bss";
Sam Cleggc94d3932017-11-17 18:14:09 +0000871 return Name;
872}
873
874void Writer::createOutputSegments() {
875 for (ObjFile *File : Symtab->ObjectFiles) {
876 for (InputSegment *Segment : File->Segments) {
Sam Clegg447ae402018-02-13 20:29:38 +0000877 if (!Segment->Live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000878 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000879 StringRef Name = getOutputDataSegmentName(Segment->getName());
880 OutputSegment *&S = SegmentMap[Name];
881 if (S == nullptr) {
882 DEBUG(dbgs() << "new segment: " << Name << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000883 S = make<OutputSegment>(Name, Segments.size());
Sam Cleggc94d3932017-11-17 18:14:09 +0000884 Segments.push_back(S);
885 }
886 S->addInputSegment(Segment);
887 DEBUG(dbgs() << "added data: " << Name << ": " << S->Size << "\n");
Sam Cleggc94d3932017-11-17 18:14:09 +0000888 }
889 }
890}
891
Sam Clegg50686852018-01-12 18:35:13 +0000892static const int OPCODE_CALL = 0x10;
893static const int OPCODE_END = 0xb;
894
895// Create synthetic "__wasm_call_ctors" function based on ctor functions
896// in input object.
897void Writer::createCtorFunction() {
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000898 // First write the body's contents to a string.
899 std::string BodyContent;
Sam Clegg50686852018-01-12 18:35:13 +0000900 {
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000901 raw_string_ostream OS(BodyContent);
Sam Clegg50686852018-01-12 18:35:13 +0000902 writeUleb128(OS, 0, "num locals");
Sam Clegg93102972018-02-23 05:08:53 +0000903 for (const WasmInitEntry &F : InitFunctions) {
Sam Clegg50686852018-01-12 18:35:13 +0000904 writeU8(OS, OPCODE_CALL, "CALL");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000905 writeUleb128(OS, F.Sym->getFunctionIndex(), "function index");
Sam Clegg50686852018-01-12 18:35:13 +0000906 }
907 writeU8(OS, OPCODE_END, "END");
908 }
909
910 // Once we know the size of the body we can create the final function body
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000911 std::string FunctionBody;
912 {
913 raw_string_ostream OS(FunctionBody);
914 writeUleb128(OS, BodyContent.size(), "function size");
915 OS << BodyContent;
916 }
Rui Ueyama29abfe42018-02-28 17:43:15 +0000917
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000918 ArrayRef<uint8_t> Body = toArrayRef(Saver.save(FunctionBody));
919 cast<SyntheticFunction>(WasmSym::CallCtors->Function)->setBody(Body);
Sam Clegg50686852018-01-12 18:35:13 +0000920}
921
922// Populate InitFunctions vector with init functions from all input objects.
923// This is then used either when creating the output linking section or to
924// synthesize the "__wasm_call_ctors" function.
925void Writer::calculateInitFunctions() {
926 for (ObjFile *File : Symtab->ObjectFiles) {
927 const WasmLinkingData &L = File->getWasmObj()->linkingData();
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +0000928 for (const WasmInitFunc &F : L.InitFunctions) {
929 FunctionSymbol *Sym = File->getFunctionSymbol(F.Symbol);
930 if (*Sym->getFunctionType() != WasmSignature{{}, WASM_TYPE_NORESULT})
931 error("invalid signature for init func: " + toString(*Sym));
932 InitFunctions.emplace_back(WasmInitEntry{Sym, F.Priority});
933 }
Sam Clegg50686852018-01-12 18:35:13 +0000934 }
Rui Ueyamada69b712018-02-28 00:15:59 +0000935
Sam Clegg50686852018-01-12 18:35:13 +0000936 // Sort in order of priority (lowest first) so that they are called
937 // in the correct order.
Sam Clegg29b8feb2018-02-21 00:34:34 +0000938 std::stable_sort(InitFunctions.begin(), InitFunctions.end(),
Sam Clegg93102972018-02-23 05:08:53 +0000939 [](const WasmInitEntry &L, const WasmInitEntry &R) {
Sam Clegg29b8feb2018-02-21 00:34:34 +0000940 return L.Priority < R.Priority;
941 });
Sam Clegg50686852018-01-12 18:35:13 +0000942}
943
Sam Cleggc94d3932017-11-17 18:14:09 +0000944void Writer::run() {
Sam Clegg99eb42c2018-02-27 23:58:03 +0000945 if (Config->Relocatable)
946 Config->GlobalBase = 0;
947
Sam Cleggc94d3932017-11-17 18:14:09 +0000948 log("-- calculateImports");
949 calculateImports();
Sam Clegg8d146bb2018-01-09 23:56:44 +0000950 log("-- assignIndexes");
951 assignIndexes();
Sam Clegg50686852018-01-12 18:35:13 +0000952 log("-- calculateInitFunctions");
953 calculateInitFunctions();
954 if (!Config->Relocatable)
955 createCtorFunction();
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000956 log("-- calculateTypes");
957 calculateTypes();
Sam Clegg93102972018-02-23 05:08:53 +0000958 log("-- layoutMemory");
959 layoutMemory();
960 log("-- calculateExports");
961 calculateExports();
962 log("-- assignSymtab");
963 assignSymtab();
Sam Cleggc94d3932017-11-17 18:14:09 +0000964
965 if (errorHandler().Verbose) {
Sam Clegg9f934222018-02-21 18:29:23 +0000966 log("Defined Functions: " + Twine(InputFunctions.size()));
Sam Clegg93102972018-02-23 05:08:53 +0000967 log("Defined Globals : " + Twine(InputGlobals.size()));
968 log("Function Imports : " + Twine(NumImportedFunctions));
969 log("Global Imports : " + Twine(NumImportedGlobals));
Sam Cleggc94d3932017-11-17 18:14:09 +0000970 for (ObjFile *File : Symtab->ObjectFiles)
971 File->dumpInfo();
972 }
973
Sam Cleggc94d3932017-11-17 18:14:09 +0000974 createHeader();
975 log("-- createSections");
976 createSections();
977
978 log("-- openFile");
979 openFile();
980 if (errorCount())
981 return;
982
983 writeHeader();
984
985 log("-- writeSections");
986 writeSections();
987 if (errorCount())
988 return;
989
990 if (Error E = Buffer->commit())
991 fatal("failed to write the output file: " + toString(std::move(E)));
992}
993
994// Open a result file.
995void Writer::openFile() {
996 log("writing: " + Config->OutputFile);
Sam Cleggc94d3932017-11-17 18:14:09 +0000997
998 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
999 FileOutputBuffer::create(Config->OutputFile, FileSize,
1000 FileOutputBuffer::F_executable);
1001
1002 if (!BufferOrErr)
1003 error("failed to open " + Config->OutputFile + ": " +
1004 toString(BufferOrErr.takeError()));
1005 else
1006 Buffer = std::move(*BufferOrErr);
1007}
1008
1009void Writer::createHeader() {
1010 raw_string_ostream OS(Header);
1011 writeBytes(OS, WasmMagic, sizeof(WasmMagic), "wasm magic");
1012 writeU32(OS, WasmVersion, "wasm version");
1013 OS.flush();
1014 FileSize += Header.size();
1015}
1016
1017void lld::wasm::writeResult() { Writer().run(); }