blob: 261fbc177eca096fd63e1a80cdd28e265eed1f96 [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();
Rui Ueyamaffa650a2018-04-24 23:09:57 +0000367 for (size_t I = 0; I < OrigSize; I++) {
368 OutputSection *OSec = OutputSections[I];
Rui Ueyama37254062018-02-28 00:01:31 +0000369 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 Ueyamaffa650a2018-04-24 23:09:57 +0000383 writeUleb128(OS, I, "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 Clegg2b8b1792018-04-26 18:17:21 +0000433 writeUleb128(OS, WasmMetadataVersion, "Version");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000434
Sam Clegg93102972018-02-23 05:08:53 +0000435 if (!SymtabEntries.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000436 SubSection Sub(WASM_SYMBOL_TABLE);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000437 writeUleb128(Sub.OS, SymtabEntries.size(), "num symbols");
438
Sam Clegg93102972018-02-23 05:08:53 +0000439 for (const Symbol *Sym : SymtabEntries) {
440 assert(Sym->isDefined() || Sym->isUndefined());
441 WasmSymbolType Kind = Sym->getWasmType();
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000442 uint32_t Flags = getWasmFlags(Sym);
443
Sam Clegg8518e7d2018-03-01 18:06:39 +0000444 writeU8(Sub.OS, Kind, "sym kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000445 writeUleb128(Sub.OS, Flags, "sym flags");
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000446
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000447 if (auto *F = dyn_cast<FunctionSymbol>(Sym)) {
448 writeUleb128(Sub.OS, F->getFunctionIndex(), "index");
Sam Clegg93102972018-02-23 05:08:53 +0000449 if (Sym->isDefined())
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000450 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000451 } else if (auto *G = dyn_cast<GlobalSymbol>(Sym)) {
452 writeUleb128(Sub.OS, G->getGlobalIndex(), "index");
453 if (Sym->isDefined())
454 writeStr(Sub.OS, Sym->getName(), "sym name");
455 } else {
456 assert(isa<DataSymbol>(Sym));
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000457 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegg93102972018-02-23 05:08:53 +0000458 if (auto *DataSym = dyn_cast<DefinedData>(Sym)) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000459 writeUleb128(Sub.OS, DataSym->getOutputSegmentIndex(), "index");
460 writeUleb128(Sub.OS, DataSym->getOutputSegmentOffset(),
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000461 "data offset");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000462 writeUleb128(Sub.OS, DataSym->getSize(), "data size");
Sam Clegg93102972018-02-23 05:08:53 +0000463 }
Sam Clegg93102972018-02-23 05:08:53 +0000464 }
Sam Cleggd3052d52018-01-18 23:40:49 +0000465 }
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000466
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000467 Sub.writeTo(OS);
Sam Cleggd3052d52018-01-18 23:40:49 +0000468 }
469
Sam Clegg0d0dd392017-12-19 17:09:45 +0000470 if (Segments.size()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000471 SubSection Sub(WASM_SEGMENT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000472 writeUleb128(Sub.OS, Segments.size(), "num data segments");
Sam Cleggc94d3932017-11-17 18:14:09 +0000473 for (const OutputSegment *S : Segments) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000474 writeStr(Sub.OS, S->Name, "segment name");
475 writeUleb128(Sub.OS, S->Alignment, "alignment");
476 writeUleb128(Sub.OS, 0, "flags");
Sam Cleggc94d3932017-11-17 18:14:09 +0000477 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000478 Sub.writeTo(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000479 }
Sam Clegg0d0dd392017-12-19 17:09:45 +0000480
Sam Clegg0d0dd392017-12-19 17:09:45 +0000481 if (!InitFunctions.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000482 SubSection Sub(WASM_INIT_FUNCS);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000483 writeUleb128(Sub.OS, InitFunctions.size(), "num init functions");
Sam Clegg93102972018-02-23 05:08:53 +0000484 for (const WasmInitEntry &F : InitFunctions) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000485 writeUleb128(Sub.OS, F.Priority, "priority");
486 writeUleb128(Sub.OS, F.Sym->getOutputSymbolIndex(), "function index");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000487 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000488 Sub.writeTo(OS);
Sam Clegg0d0dd392017-12-19 17:09:45 +0000489 }
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000490
Nicholas Wilsondbd90bf2018-03-07 13:28:16 +0000491 struct ComdatEntry {
492 unsigned Kind;
493 uint32_t Index;
494 };
495 std::map<StringRef, std::vector<ComdatEntry>> Comdats;
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000496
Sam Clegg9f934222018-02-21 18:29:23 +0000497 for (const InputFunction *F : InputFunctions) {
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000498 StringRef Comdat = F->getComdatName();
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000499 if (!Comdat.empty())
500 Comdats[Comdat].emplace_back(
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000501 ComdatEntry{WASM_COMDAT_FUNCTION, F->getFunctionIndex()});
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000502 }
503 for (uint32_t I = 0; I < Segments.size(); ++I) {
Sam Cleggf98bccf2018-01-13 15:57:48 +0000504 const auto &InputSegments = Segments[I]->InputSegments;
505 if (InputSegments.empty())
506 continue;
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000507 StringRef Comdat = InputSegments[0]->getComdatName();
Sam Clegga697df522018-01-13 15:59:53 +0000508#ifndef NDEBUG
Sam Cleggf98bccf2018-01-13 15:57:48 +0000509 for (const InputSegment *IS : InputSegments)
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000510 assert(IS->getComdatName() == Comdat);
Sam Clegga697df522018-01-13 15:59:53 +0000511#endif
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000512 if (!Comdat.empty())
513 Comdats[Comdat].emplace_back(ComdatEntry{WASM_COMDAT_DATA, I});
514 }
515
516 if (!Comdats.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000517 SubSection Sub(WASM_COMDAT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000518 writeUleb128(Sub.OS, Comdats.size(), "num comdats");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000519 for (const auto &C : Comdats) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000520 writeStr(Sub.OS, C.first, "comdat name");
521 writeUleb128(Sub.OS, 0, "comdat flags"); // flags for future use
522 writeUleb128(Sub.OS, C.second.size(), "num entries");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000523 for (const ComdatEntry &Entry : C.second) {
Sam Clegg8518e7d2018-03-01 18:06:39 +0000524 writeU8(Sub.OS, Entry.Kind, "entry kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000525 writeUleb128(Sub.OS, Entry.Index, "entry index");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000526 }
527 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000528 Sub.writeTo(OS);
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000529 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000530}
531
532// Create the custom "name" section containing debug symbol names.
533void Writer::createNameSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000534 unsigned NumNames = NumImportedFunctions;
Sam Clegg9f934222018-02-21 18:29:23 +0000535 for (const InputFunction *F : InputFunctions)
Nicholas Wilson6c7fe302018-04-20 17:09:18 +0000536 if (!F->getName().empty() || !F->getDebugName().empty())
Sam Clegg1963d712018-01-17 20:19:04 +0000537 ++NumNames;
Sam Cleggc94d3932017-11-17 18:14:09 +0000538
Sam Clegg1963d712018-01-17 20:19:04 +0000539 if (NumNames == 0)
540 return;
Sam Clegg50686852018-01-12 18:35:13 +0000541
Sam Cleggc94d3932017-11-17 18:14:09 +0000542 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "name");
543
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000544 SubSection Sub(WASM_NAMES_FUNCTION);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000545 writeUleb128(Sub.OS, NumNames, "name count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000546
Sam Clegg93102972018-02-23 05:08:53 +0000547 // Names must appear in function index order. As it happens ImportedSymbols
548 // and InputFunctions are numbered in order with imported functions coming
Sam Clegg1963d712018-01-17 20:19:04 +0000549 // first.
Sam Clegg93102972018-02-23 05:08:53 +0000550 for (const Symbol *S : ImportedSymbols) {
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000551 if (auto *F = dyn_cast<FunctionSymbol>(S)) {
552 writeUleb128(Sub.OS, F->getFunctionIndex(), "func index");
Nicholas Wilson531769b2018-03-13 13:30:04 +0000553 Optional<std::string> Name = demangleItanium(F->getName());
554 writeStr(Sub.OS, Name ? StringRef(*Name) : F->getName(), "symbol name");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000555 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000556 }
Sam Clegg9f934222018-02-21 18:29:23 +0000557 for (const InputFunction *F : InputFunctions) {
Sam Clegg1963d712018-01-17 20:19:04 +0000558 if (!F->getName().empty()) {
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000559 writeUleb128(Sub.OS, F->getFunctionIndex(), "func index");
Nicholas Wilson6c7fe302018-04-20 17:09:18 +0000560 if (!F->getDebugName().empty()) {
561 writeStr(Sub.OS, F->getDebugName(), "symbol name");
562 } else {
563 Optional<std::string> Name = demangleItanium(F->getName());
564 writeStr(Sub.OS, Name ? StringRef(*Name) : F->getName(), "symbol name");
565 }
Sam Clegg1963d712018-01-17 20:19:04 +0000566 }
567 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000568
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000569 Sub.writeTo(Section->getStream());
Sam Cleggc94d3932017-11-17 18:14:09 +0000570}
571
572void Writer::writeHeader() {
573 memcpy(Buffer->getBufferStart(), Header.data(), Header.size());
574}
575
576void Writer::writeSections() {
577 uint8_t *Buf = Buffer->getBufferStart();
578 parallelForEach(OutputSections, [Buf](OutputSection *S) { S->writeTo(Buf); });
579}
580
581// Fix the memory layout of the output binary. This assigns memory offsets
Sam Clegg49ed9262017-12-01 00:53:21 +0000582// to each of the input data sections as well as the explicit stack region.
Sam Cleggf0d433d2018-02-02 22:59:56 +0000583// The memory layout is as follows, from low to high.
584// - initialized data (starting at Config->GlobalBase)
585// - BSS data (not currently implemented in llvm)
586// - explicit stack (Config->ZStackSize)
587// - heap start / unallocated
Sam Cleggc94d3932017-11-17 18:14:09 +0000588void Writer::layoutMemory() {
589 uint32_t MemoryPtr = 0;
Sam Clegg99eb42c2018-02-27 23:58:03 +0000590 MemoryPtr = Config->GlobalBase;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000591 log("mem: global base = " + Twine(Config->GlobalBase));
Sam Cleggc94d3932017-11-17 18:14:09 +0000592
593 createOutputSegments();
594
Sam Cleggf0d433d2018-02-02 22:59:56 +0000595 // Arbitrarily set __dso_handle handle to point to the start of the data
596 // segments.
597 if (WasmSym::DsoHandle)
598 WasmSym::DsoHandle->setVirtualAddress(MemoryPtr);
599
Sam Cleggc94d3932017-11-17 18:14:09 +0000600 for (OutputSegment *Seg : Segments) {
601 MemoryPtr = alignTo(MemoryPtr, Seg->Alignment);
602 Seg->StartVA = MemoryPtr;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000603 log(formatv("mem: {0,-15} offset={1,-8} size={2,-8} align={3}", Seg->Name,
604 MemoryPtr, Seg->Size, Seg->Alignment));
Sam Cleggc94d3932017-11-17 18:14:09 +0000605 MemoryPtr += Seg->Size;
606 }
607
Sam Cleggf0d433d2018-02-02 22:59:56 +0000608 // TODO: Add .bss space here.
Sam Clegg37a4a8a2018-02-07 03:04:53 +0000609 if (WasmSym::DataEnd)
610 WasmSym::DataEnd->setVirtualAddress(MemoryPtr);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000611
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000612 log("mem: static data = " + Twine(MemoryPtr - Config->GlobalBase));
Sam Cleggc94d3932017-11-17 18:14:09 +0000613
Sam Cleggf0d433d2018-02-02 22:59:56 +0000614 // Stack comes after static data and bss
Sam Cleggc94d3932017-11-17 18:14:09 +0000615 if (!Config->Relocatable) {
616 MemoryPtr = alignTo(MemoryPtr, kStackAlignment);
617 if (Config->ZStackSize != alignTo(Config->ZStackSize, kStackAlignment))
618 error("stack size must be " + Twine(kStackAlignment) + "-byte aligned");
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000619 log("mem: stack size = " + Twine(Config->ZStackSize));
620 log("mem: stack base = " + Twine(MemoryPtr));
Sam Cleggc94d3932017-11-17 18:14:09 +0000621 MemoryPtr += Config->ZStackSize;
Sam Clegg93102972018-02-23 05:08:53 +0000622 WasmSym::StackPointer->Global->Global.InitExpr.Value.Int32 = MemoryPtr;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000623 log("mem: stack top = " + Twine(MemoryPtr));
Sam Clegg93102972018-02-23 05:08:53 +0000624
Sam Clegg51bcdc22018-01-17 01:34:31 +0000625 // Set `__heap_base` to directly follow the end of the stack. We don't
626 // allocate any heap memory up front, but instead really on the malloc/brk
627 // implementation growing the memory at runtime.
Sam Cleggf0d433d2018-02-02 22:59:56 +0000628 WasmSym::HeapBase->setVirtualAddress(MemoryPtr);
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000629 log("mem: heap base = " + Twine(MemoryPtr));
Sam Cleggc94d3932017-11-17 18:14:09 +0000630 }
631
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000632 if (Config->InitialMemory != 0) {
633 if (Config->InitialMemory != alignTo(Config->InitialMemory, WasmPageSize))
634 error("initial memory must be " + Twine(WasmPageSize) + "-byte aligned");
635 if (MemoryPtr > Config->InitialMemory)
636 error("initial memory too small, " + Twine(MemoryPtr) + " bytes needed");
637 else
638 MemoryPtr = Config->InitialMemory;
639 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000640 uint32_t MemSize = alignTo(MemoryPtr, WasmPageSize);
641 NumMemoryPages = MemSize / WasmPageSize;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000642 log("mem: total pages = " + Twine(NumMemoryPages));
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000643
644 if (Config->MaxMemory != 0) {
645 if (Config->MaxMemory != alignTo(Config->MaxMemory, WasmPageSize))
646 error("maximum memory must be " + Twine(WasmPageSize) + "-byte aligned");
647 if (MemoryPtr > Config->MaxMemory)
648 error("maximum memory too small, " + Twine(MemoryPtr) + " bytes needed");
649 MaxMemoryPages = Config->MaxMemory / WasmPageSize;
650 log("mem: max pages = " + Twine(MaxMemoryPages));
651 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000652}
653
654SyntheticSection *Writer::createSyntheticSection(uint32_t Type,
Sam Cleggc375e4e2018-01-10 19:18:22 +0000655 StringRef Name) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000656 auto Sec = make<SyntheticSection>(Type, Name);
Sam Cleggab2ac292017-12-20 05:14:48 +0000657 log("createSection: " + toString(*Sec));
Sam Cleggc94d3932017-11-17 18:14:09 +0000658 OutputSections.push_back(Sec);
659 return Sec;
660}
661
662void Writer::createSections() {
663 // Known sections
664 createTypeSection();
665 createImportSection();
666 createFunctionSection();
667 createTableSection();
668 createMemorySection();
669 createGlobalSection();
670 createExportSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000671 createElemSection();
672 createCodeSection();
673 createDataSection();
Sam Clegg80ba4382018-04-10 16:12:49 +0000674 createCustomSections();
Sam Cleggc94d3932017-11-17 18:14:09 +0000675
676 // Custom sections
Sam Clegg99eb42c2018-02-27 23:58:03 +0000677 if (Config->Relocatable) {
Sam Clegg99eb42c2018-02-27 23:58:03 +0000678 createLinkingSection();
Nicholas Wilson94d3b162018-03-05 12:33:58 +0000679 createRelocSections();
Sam Clegg99eb42c2018-02-27 23:58:03 +0000680 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000681 if (!Config->StripDebug && !Config->StripAll)
682 createNameSection();
683
684 for (OutputSection *S : OutputSections) {
685 S->setOffset(FileSize);
686 S->finalizeContents();
687 FileSize += S->getSize();
688 }
689}
690
Sam Cleggc94d3932017-11-17 18:14:09 +0000691void Writer::calculateImports() {
Sam Clegg574d7ce2017-12-15 19:23:49 +0000692 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000693 if (!Sym->isUndefined())
694 continue;
695 if (isa<DataSymbol>(Sym))
696 continue;
697 if (Sym->isWeak() && !Config->Relocatable)
Sam Clegg574d7ce2017-12-15 19:23:49 +0000698 continue;
Nicholas Wilsona1e299f2018-04-20 17:18:06 +0000699 if (!Sym->isLive())
700 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000701
Sam Clegg93102972018-02-23 05:08:53 +0000702 DEBUG(dbgs() << "import: " << Sym->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000703 ImportedSymbols.emplace_back(Sym);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000704 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
705 F->setFunctionIndex(NumImportedFunctions++);
Sam Clegg93102972018-02-23 05:08:53 +0000706 else
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000707 cast<GlobalSymbol>(Sym)->setGlobalIndex(NumImportedGlobals++);
Sam Cleggc94d3932017-11-17 18:14:09 +0000708 }
709}
710
Sam Cleggd3052d52018-01-18 23:40:49 +0000711void Writer::calculateExports() {
Sam Clegg93102972018-02-23 05:08:53 +0000712 if (Config->Relocatable)
713 return;
Sam Cleggf0d433d2018-02-02 22:59:56 +0000714
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000715 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000716 if (!Sym->isDefined())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000717 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000718 if (Sym->isHidden() || Sym->isLocal())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000719 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000720 if (!Sym->isLive())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000721 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000722
723 DEBUG(dbgs() << "exporting sym: " << Sym->getName() << "\n");
724
Nicholas Wilsonf2f6d5e2018-03-02 14:51:36 +0000725 if (auto *D = dyn_cast<DefinedData>(Sym))
Sam Clegg93102972018-02-23 05:08:53 +0000726 DefinedFakeGlobals.emplace_back(D);
Sam Clegg93102972018-02-23 05:08:53 +0000727 ExportedSymbols.emplace_back(Sym);
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000728 }
Sam Clegg93102972018-02-23 05:08:53 +0000729}
730
731void Writer::assignSymtab() {
732 if (!Config->Relocatable)
733 return;
734
735 unsigned SymbolIndex = SymtabEntries.size();
Sam Cleggd3052d52018-01-18 23:40:49 +0000736 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg93102972018-02-23 05:08:53 +0000737 DEBUG(dbgs() << "Symtab entries: " << File->getName() << "\n");
Sam Cleggd3052d52018-01-18 23:40:49 +0000738 for (Symbol *Sym : File->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000739 if (Sym->getFile() != File)
Sam Cleggd3052d52018-01-18 23:40:49 +0000740 continue;
Nicholas Wilson06e0d172018-03-07 11:15:47 +0000741 // (Since this is relocatable output, GC is not performed so symbols must
742 // be live.)
743 assert(Sym->isLive());
Sam Clegg93102972018-02-23 05:08:53 +0000744 Sym->setOutputSymbolIndex(SymbolIndex++);
745 SymtabEntries.emplace_back(Sym);
Sam Cleggd3052d52018-01-18 23:40:49 +0000746 }
747 }
748
Sam Clegg93102972018-02-23 05:08:53 +0000749 // For the moment, relocatable output doesn't contain any synthetic functions,
750 // so no need to look through the Symtab for symbols not referenced by
751 // Symtab->ObjectFiles.
Sam Cleggd3052d52018-01-18 23:40:49 +0000752}
753
Sam Cleggc375e4e2018-01-10 19:18:22 +0000754uint32_t Writer::lookupType(const WasmSignature &Sig) {
Sam Clegg8d027d62018-01-10 20:12:26 +0000755 auto It = TypeIndices.find(Sig);
756 if (It == TypeIndices.end()) {
Sam Cleggc375e4e2018-01-10 19:18:22 +0000757 error("type not found: " + toString(Sig));
Sam Clegg8d027d62018-01-10 20:12:26 +0000758 return 0;
759 }
760 return It->second;
Sam Cleggc375e4e2018-01-10 19:18:22 +0000761}
762
763uint32_t Writer::registerType(const WasmSignature &Sig) {
Sam Cleggb8621592017-11-30 01:40:08 +0000764 auto Pair = TypeIndices.insert(std::make_pair(Sig, Types.size()));
Sam Cleggc375e4e2018-01-10 19:18:22 +0000765 if (Pair.second) {
766 DEBUG(dbgs() << "type " << toString(Sig) << "\n");
Sam Cleggb8621592017-11-30 01:40:08 +0000767 Types.push_back(&Sig);
Sam Cleggc375e4e2018-01-10 19:18:22 +0000768 }
Sam Cleggb8621592017-11-30 01:40:08 +0000769 return Pair.first->second;
770}
771
Sam Cleggc94d3932017-11-17 18:14:09 +0000772void Writer::calculateTypes() {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000773 // The output type section is the union of the following sets:
774 // 1. Any signature used in the TYPE relocation
775 // 2. The signatures of all imported functions
776 // 3. The signatures of all defined functions
777
Sam Cleggc94d3932017-11-17 18:14:09 +0000778 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000779 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
780 for (uint32_t I = 0; I < Types.size(); I++)
781 if (File->TypeIsUsed[I])
782 File->TypeMap[I] = registerType(Types[I]);
Sam Cleggc94d3932017-11-17 18:14:09 +0000783 }
Sam Clegg50686852018-01-12 18:35:13 +0000784
Sam Clegg93102972018-02-23 05:08:53 +0000785 for (const Symbol *Sym : ImportedSymbols)
786 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
787 registerType(*F->getFunctionType());
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000788
Sam Clegg9f934222018-02-21 18:29:23 +0000789 for (const InputFunction *F : InputFunctions)
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000790 registerType(F->Signature);
Sam Cleggc94d3932017-11-17 18:14:09 +0000791}
792
Sam Clegg8d146bb2018-01-09 23:56:44 +0000793void Writer::assignIndexes() {
Sam Clegg93102972018-02-23 05:08:53 +0000794 uint32_t FunctionIndex = NumImportedFunctions + InputFunctions.size();
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000795 auto AddDefinedFunction = [&](InputFunction *Func) {
796 if (!Func->Live)
797 return;
798 InputFunctions.emplace_back(Func);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000799 Func->setFunctionIndex(FunctionIndex++);
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000800 };
801
Nicholas Wilson5639da82018-03-12 15:44:07 +0000802 for (InputFunction *Func : Symtab->SyntheticFunctions)
803 AddDefinedFunction(Func);
804
Sam Clegg87e61922018-01-08 23:39:11 +0000805 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8d146bb2018-01-09 23:56:44 +0000806 DEBUG(dbgs() << "Functions: " << File->getName() << "\n");
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000807 for (InputFunction *Func : File->Functions)
808 AddDefinedFunction(Func);
Sam Clegg8d146bb2018-01-09 23:56:44 +0000809 }
810
Sam Clegg93102972018-02-23 05:08:53 +0000811 uint32_t TableIndex = kInitialTableOffset;
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000812 auto HandleRelocs = [&](InputChunk *Chunk) {
813 if (!Chunk->Live)
814 return;
815 ObjFile *File = Chunk->File;
816 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
Sam Clegg93102972018-02-23 05:08:53 +0000817 for (const WasmRelocation &Reloc : Chunk->getRelocations()) {
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000818 if (Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_I32 ||
819 Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_SLEB) {
820 FunctionSymbol *Sym = File->getFunctionSymbol(Reloc.Index);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000821 if (Sym->hasTableIndex() || !Sym->hasFunctionIndex())
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000822 continue;
823 Sym->setTableIndex(TableIndex++);
824 IndirectFunctions.emplace_back(Sym);
825 } else if (Reloc.Type == R_WEBASSEMBLY_TYPE_INDEX_LEB) {
Sam Clegg93102972018-02-23 05:08:53 +0000826 // Mark target type as live
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000827 File->TypeMap[Reloc.Index] = registerType(Types[Reloc.Index]);
828 File->TypeIsUsed[Reloc.Index] = true;
829 }
830 }
831 };
832
Sam Clegg8d146bb2018-01-09 23:56:44 +0000833 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000834 DEBUG(dbgs() << "Handle relocs: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000835 for (InputChunk *Chunk : File->Functions)
836 HandleRelocs(Chunk);
837 for (InputChunk *Chunk : File->Segments)
838 HandleRelocs(Chunk);
839 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000840
Sam Clegg93102972018-02-23 05:08:53 +0000841 uint32_t GlobalIndex = NumImportedGlobals + InputGlobals.size();
842 auto AddDefinedGlobal = [&](InputGlobal *Global) {
843 if (Global->Live) {
844 DEBUG(dbgs() << "AddDefinedGlobal: " << GlobalIndex << "\n");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000845 Global->setGlobalIndex(GlobalIndex++);
Sam Clegg93102972018-02-23 05:08:53 +0000846 InputGlobals.push_back(Global);
847 }
848 };
849
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000850 for (InputGlobal *Global : Symtab->SyntheticGlobals)
851 AddDefinedGlobal(Global);
Sam Clegg93102972018-02-23 05:08:53 +0000852
853 for (ObjFile *File : Symtab->ObjectFiles) {
854 DEBUG(dbgs() << "Globals: " << File->getName() << "\n");
855 for (InputGlobal *Global : File->Globals)
856 AddDefinedGlobal(Global);
Sam Cleggc94d3932017-11-17 18:14:09 +0000857 }
858}
859
860static StringRef getOutputDataSegmentName(StringRef Name) {
861 if (Config->Relocatable)
862 return Name;
Rui Ueyama4764b572018-02-28 00:57:28 +0000863 if (Name.startswith(".text."))
864 return ".text";
865 if (Name.startswith(".data."))
866 return ".data";
867 if (Name.startswith(".bss."))
868 return ".bss";
Sam Cleggc94d3932017-11-17 18:14:09 +0000869 return Name;
870}
871
872void Writer::createOutputSegments() {
873 for (ObjFile *File : Symtab->ObjectFiles) {
874 for (InputSegment *Segment : File->Segments) {
Sam Clegg447ae402018-02-13 20:29:38 +0000875 if (!Segment->Live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000876 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000877 StringRef Name = getOutputDataSegmentName(Segment->getName());
878 OutputSegment *&S = SegmentMap[Name];
879 if (S == nullptr) {
880 DEBUG(dbgs() << "new segment: " << Name << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000881 S = make<OutputSegment>(Name, Segments.size());
Sam Cleggc94d3932017-11-17 18:14:09 +0000882 Segments.push_back(S);
883 }
884 S->addInputSegment(Segment);
885 DEBUG(dbgs() << "added data: " << Name << ": " << S->Size << "\n");
Sam Cleggc94d3932017-11-17 18:14:09 +0000886 }
887 }
888}
889
Sam Clegg50686852018-01-12 18:35:13 +0000890static const int OPCODE_CALL = 0x10;
891static const int OPCODE_END = 0xb;
892
893// Create synthetic "__wasm_call_ctors" function based on ctor functions
894// in input object.
895void Writer::createCtorFunction() {
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000896 // First write the body's contents to a string.
897 std::string BodyContent;
Sam Clegg50686852018-01-12 18:35:13 +0000898 {
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000899 raw_string_ostream OS(BodyContent);
Sam Clegg50686852018-01-12 18:35:13 +0000900 writeUleb128(OS, 0, "num locals");
Sam Clegg93102972018-02-23 05:08:53 +0000901 for (const WasmInitEntry &F : InitFunctions) {
Sam Clegg50686852018-01-12 18:35:13 +0000902 writeU8(OS, OPCODE_CALL, "CALL");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000903 writeUleb128(OS, F.Sym->getFunctionIndex(), "function index");
Sam Clegg50686852018-01-12 18:35:13 +0000904 }
905 writeU8(OS, OPCODE_END, "END");
906 }
907
908 // Once we know the size of the body we can create the final function body
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000909 std::string FunctionBody;
910 {
911 raw_string_ostream OS(FunctionBody);
912 writeUleb128(OS, BodyContent.size(), "function size");
913 OS << BodyContent;
914 }
Rui Ueyama29abfe42018-02-28 17:43:15 +0000915
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000916 ArrayRef<uint8_t> Body = toArrayRef(Saver.save(FunctionBody));
917 cast<SyntheticFunction>(WasmSym::CallCtors->Function)->setBody(Body);
Sam Clegg50686852018-01-12 18:35:13 +0000918}
919
920// Populate InitFunctions vector with init functions from all input objects.
921// This is then used either when creating the output linking section or to
922// synthesize the "__wasm_call_ctors" function.
923void Writer::calculateInitFunctions() {
924 for (ObjFile *File : Symtab->ObjectFiles) {
925 const WasmLinkingData &L = File->getWasmObj()->linkingData();
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +0000926 for (const WasmInitFunc &F : L.InitFunctions) {
927 FunctionSymbol *Sym = File->getFunctionSymbol(F.Symbol);
928 if (*Sym->getFunctionType() != WasmSignature{{}, WASM_TYPE_NORESULT})
929 error("invalid signature for init func: " + toString(*Sym));
930 InitFunctions.emplace_back(WasmInitEntry{Sym, F.Priority});
931 }
Sam Clegg50686852018-01-12 18:35:13 +0000932 }
Rui Ueyamada69b712018-02-28 00:15:59 +0000933
Sam Clegg50686852018-01-12 18:35:13 +0000934 // Sort in order of priority (lowest first) so that they are called
935 // in the correct order.
Sam Clegg29b8feb2018-02-21 00:34:34 +0000936 std::stable_sort(InitFunctions.begin(), InitFunctions.end(),
Sam Clegg93102972018-02-23 05:08:53 +0000937 [](const WasmInitEntry &L, const WasmInitEntry &R) {
Sam Clegg29b8feb2018-02-21 00:34:34 +0000938 return L.Priority < R.Priority;
939 });
Sam Clegg50686852018-01-12 18:35:13 +0000940}
941
Sam Cleggc94d3932017-11-17 18:14:09 +0000942void Writer::run() {
Sam Clegg99eb42c2018-02-27 23:58:03 +0000943 if (Config->Relocatable)
944 Config->GlobalBase = 0;
945
Sam Cleggc94d3932017-11-17 18:14:09 +0000946 log("-- calculateImports");
947 calculateImports();
Sam Clegg8d146bb2018-01-09 23:56:44 +0000948 log("-- assignIndexes");
949 assignIndexes();
Sam Clegg50686852018-01-12 18:35:13 +0000950 log("-- calculateInitFunctions");
951 calculateInitFunctions();
952 if (!Config->Relocatable)
953 createCtorFunction();
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000954 log("-- calculateTypes");
955 calculateTypes();
Sam Clegg93102972018-02-23 05:08:53 +0000956 log("-- layoutMemory");
957 layoutMemory();
958 log("-- calculateExports");
959 calculateExports();
960 log("-- assignSymtab");
961 assignSymtab();
Sam Cleggc94d3932017-11-17 18:14:09 +0000962
963 if (errorHandler().Verbose) {
Sam Clegg9f934222018-02-21 18:29:23 +0000964 log("Defined Functions: " + Twine(InputFunctions.size()));
Sam Clegg93102972018-02-23 05:08:53 +0000965 log("Defined Globals : " + Twine(InputGlobals.size()));
966 log("Function Imports : " + Twine(NumImportedFunctions));
967 log("Global Imports : " + Twine(NumImportedGlobals));
Sam Cleggc94d3932017-11-17 18:14:09 +0000968 for (ObjFile *File : Symtab->ObjectFiles)
969 File->dumpInfo();
970 }
971
Sam Cleggc94d3932017-11-17 18:14:09 +0000972 createHeader();
973 log("-- createSections");
974 createSections();
975
976 log("-- openFile");
977 openFile();
978 if (errorCount())
979 return;
980
981 writeHeader();
982
983 log("-- writeSections");
984 writeSections();
985 if (errorCount())
986 return;
987
988 if (Error E = Buffer->commit())
989 fatal("failed to write the output file: " + toString(std::move(E)));
990}
991
992// Open a result file.
993void Writer::openFile() {
994 log("writing: " + Config->OutputFile);
Sam Cleggc94d3932017-11-17 18:14:09 +0000995
996 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
997 FileOutputBuffer::create(Config->OutputFile, FileSize,
998 FileOutputBuffer::F_executable);
999
1000 if (!BufferOrErr)
1001 error("failed to open " + Config->OutputFile + ": " +
1002 toString(BufferOrErr.takeError()));
1003 else
1004 Buffer = std::move(*BufferOrErr);
1005}
1006
1007void Writer::createHeader() {
1008 raw_string_ostream OS(Header);
1009 writeBytes(OS, WasmMagic, sizeof(WasmMagic), "wasm magic");
1010 writeU32(OS, WasmVersion, "wasm version");
1011 OS.flush();
1012 FileSize += Header.size();
1013}
1014
1015void lld::wasm::writeResult() { Writer().run(); }