blob: cb413de67babb77eb619488a9e1ace6abc7e21e3 [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 Cleggd177ab22018-05-04 23:14:42 +000070 void calculateCustomSections();
Sam Clegg93102972018-02-23 05:08:53 +000071 void assignSymtab();
Sam Cleggc94d3932017-11-17 18:14:09 +000072 void calculateTypes();
73 void createOutputSegments();
74 void layoutMemory();
75 void createHeader();
76 void createSections();
Nicholas Wilsondbd90bf2018-03-07 13:28:16 +000077 SyntheticSection *createSyntheticSection(uint32_t Type, StringRef Name = "");
Sam Cleggc94d3932017-11-17 18:14:09 +000078
79 // Builtin sections
80 void createTypeSection();
81 void createFunctionSection();
82 void createTableSection();
83 void createGlobalSection();
84 void createExportSection();
85 void createImportSection();
86 void createMemorySection();
87 void createElemSection();
Sam Cleggc94d3932017-11-17 18:14:09 +000088 void createCodeSection();
89 void createDataSection();
Sam Clegg80ba4382018-04-10 16:12:49 +000090 void createCustomSections();
Sam Cleggc94d3932017-11-17 18:14:09 +000091
92 // Custom sections
93 void createRelocSections();
94 void createLinkingSection();
95 void createNameSection();
96
97 void writeHeader();
98 void writeSections();
99
100 uint64_t FileSize = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000101 uint32_t NumMemoryPages = 0;
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000102 uint32_t MaxMemoryPages = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000103
104 std::vector<const WasmSignature *> Types;
Nicholas Wilson3e3f5fb2018-03-14 15:58:16 +0000105 DenseMap<WasmSignature, int32_t> TypeIndices;
Sam Clegg93102972018-02-23 05:08:53 +0000106 std::vector<const Symbol *> ImportedSymbols;
107 unsigned NumImportedFunctions = 0;
108 unsigned NumImportedGlobals = 0;
Sam Cleggd6beb322018-05-10 18:10:34 +0000109 std::vector<WasmExport> Exports;
Sam Clegg93102972018-02-23 05:08:53 +0000110 std::vector<const DefinedData *> DefinedFakeGlobals;
111 std::vector<InputGlobal *> InputGlobals;
Sam Clegg9f934222018-02-21 18:29:23 +0000112 std::vector<InputFunction *> InputFunctions;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000113 std::vector<const FunctionSymbol *> IndirectFunctions;
Sam Clegg93102972018-02-23 05:08:53 +0000114 std::vector<const Symbol *> SymtabEntries;
115 std::vector<WasmInitEntry> InitFunctions;
Sam Cleggc94d3932017-11-17 18:14:09 +0000116
Sam Clegg80ba4382018-04-10 16:12:49 +0000117 llvm::StringMap<std::vector<InputSection *>> CustomSectionMapping;
Sam Cleggd177ab22018-05-04 23:14:42 +0000118 llvm::StringMap<SectionSymbol *> CustomSectionSymbols;
Sam Clegg80ba4382018-04-10 16:12:49 +0000119
Sam Cleggc94d3932017-11-17 18:14:09 +0000120 // Elements that are used to construct the final output
121 std::string Header;
122 std::vector<OutputSection *> OutputSections;
123
124 std::unique_ptr<FileOutputBuffer> Buffer;
125
126 std::vector<OutputSegment *> Segments;
127 llvm::SmallDenseMap<StringRef, OutputSegment *> SegmentMap;
128};
129
130} // anonymous namespace
131
Sam Cleggc94d3932017-11-17 18:14:09 +0000132void Writer::createImportSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000133 uint32_t NumImports = ImportedSymbols.size();
Sam Cleggc94d3932017-11-17 18:14:09 +0000134 if (Config->ImportMemory)
135 ++NumImports;
Nicholas Wilsonfc90b302018-03-28 12:53:29 +0000136 if (Config->ImportTable)
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000137 ++NumImports;
Sam Cleggc94d3932017-11-17 18:14:09 +0000138
139 if (NumImports == 0)
140 return;
141
142 SyntheticSection *Section = createSyntheticSection(WASM_SEC_IMPORT);
143 raw_ostream &OS = Section->getStream();
144
145 writeUleb128(OS, NumImports, "import count");
146
Sam Cleggc94d3932017-11-17 18:14:09 +0000147 if (Config->ImportMemory) {
148 WasmImport Import;
149 Import.Module = "env";
150 Import.Field = "memory";
151 Import.Kind = WASM_EXTERNAL_MEMORY;
152 Import.Memory.Flags = 0;
153 Import.Memory.Initial = NumMemoryPages;
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000154 if (MaxMemoryPages != 0) {
155 Import.Memory.Flags |= WASM_LIMITS_FLAG_HAS_MAX;
156 Import.Memory.Maximum = MaxMemoryPages;
157 }
Derek Schuff786760a2018-11-06 18:02:39 +0000158 if (Config->SharedMemory)
Derek Schuff3bea8bc2018-11-06 17:59:32 +0000159 Import.Memory.Flags |= WASM_LIMITS_FLAG_IS_SHARED;
Sam Cleggc94d3932017-11-17 18:14:09 +0000160 writeImport(OS, Import);
161 }
162
Nicholas Wilsonfc90b302018-03-28 12:53:29 +0000163 if (Config->ImportTable) {
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000164 uint32_t TableSize = kInitialTableOffset + IndirectFunctions.size();
165 WasmImport Import;
166 Import.Module = "env";
167 Import.Field = kFunctionTableName;
168 Import.Kind = WASM_EXTERNAL_TABLE;
169 Import.Table.ElemType = WASM_TYPE_ANYFUNC;
170 Import.Table.Limits = {WASM_LIMITS_FLAG_HAS_MAX, TableSize, TableSize};
171 writeImport(OS, Import);
172 }
173
Sam Clegg93102972018-02-23 05:08:53 +0000174 for (const Symbol *Sym : ImportedSymbols) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000175 WasmImport Import;
176 Import.Module = "env";
177 Import.Field = Sym->getName();
Sam Clegg93102972018-02-23 05:08:53 +0000178 if (auto *FunctionSym = dyn_cast<FunctionSymbol>(Sym)) {
179 Import.Kind = WASM_EXTERNAL_FUNCTION;
Sam Cleggcefbf9a2018-06-28 16:53:53 +0000180 Import.SigIndex = lookupType(*FunctionSym->FunctionType);
Sam Clegg93102972018-02-23 05:08:53 +0000181 } else {
182 auto *GlobalSym = cast<GlobalSymbol>(Sym);
183 Import.Kind = WASM_EXTERNAL_GLOBAL;
184 Import.Global = *GlobalSym->getGlobalType();
185 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000186 writeImport(OS, Import);
187 }
188}
189
190void Writer::createTypeSection() {
191 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TYPE);
192 raw_ostream &OS = Section->getStream();
193 writeUleb128(OS, Types.size(), "type count");
Sam Cleggd451da12017-12-19 19:56:27 +0000194 for (const WasmSignature *Sig : Types)
Sam Cleggc94d3932017-11-17 18:14:09 +0000195 writeSig(OS, *Sig);
Sam Cleggc94d3932017-11-17 18:14:09 +0000196}
197
198void Writer::createFunctionSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000199 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000200 return;
201
202 SyntheticSection *Section = createSyntheticSection(WASM_SEC_FUNCTION);
203 raw_ostream &OS = Section->getStream();
204
Sam Clegg9f934222018-02-21 18:29:23 +0000205 writeUleb128(OS, InputFunctions.size(), "function count");
206 for (const InputFunction *Func : InputFunctions)
Sam Cleggc375e4e2018-01-10 19:18:22 +0000207 writeUleb128(OS, lookupType(Func->Signature), "sig index");
Sam Cleggc94d3932017-11-17 18:14:09 +0000208}
209
210void Writer::createMemorySection() {
211 if (Config->ImportMemory)
212 return;
213
214 SyntheticSection *Section = createSyntheticSection(WASM_SEC_MEMORY);
215 raw_ostream &OS = Section->getStream();
216
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000217 bool HasMax = MaxMemoryPages != 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000218 writeUleb128(OS, 1, "memory count");
Derek Schuff786760a2018-11-06 18:02:39 +0000219 unsigned Flags = 0;
220 if (HasMax)
221 Flags |= WASM_LIMITS_FLAG_HAS_MAX;
Derek Schuff3bea8bc2018-11-06 17:59:32 +0000222 if (Config->SharedMemory)
223 Flags |= WASM_LIMITS_FLAG_IS_SHARED;
224 writeUleb128(OS, Flags, "memory limits flags");
Sam Cleggc94d3932017-11-17 18:14:09 +0000225 writeUleb128(OS, NumMemoryPages, "initial pages");
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000226 if (HasMax)
227 writeUleb128(OS, MaxMemoryPages, "max pages");
Sam Cleggc94d3932017-11-17 18:14:09 +0000228}
229
230void Writer::createGlobalSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000231 unsigned NumGlobals = InputGlobals.size() + DefinedFakeGlobals.size();
232 if (NumGlobals == 0)
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000233 return;
234
Sam Cleggc94d3932017-11-17 18:14:09 +0000235 SyntheticSection *Section = createSyntheticSection(WASM_SEC_GLOBAL);
236 raw_ostream &OS = Section->getStream();
237
Sam Clegg93102972018-02-23 05:08:53 +0000238 writeUleb128(OS, NumGlobals, "global count");
239 for (const InputGlobal *G : InputGlobals)
240 writeGlobal(OS, G->Global);
241 for (const DefinedData *Sym : DefinedFakeGlobals) {
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000242 WasmGlobal Global;
Sam Clegg93102972018-02-23 05:08:53 +0000243 Global.Type = {WASM_TYPE_I32, false};
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000244 Global.InitExpr.Opcode = WASM_OPCODE_I32_CONST;
245 Global.InitExpr.Value.Int32 = Sym->getVirtualAddress();
Sam Cleggc94d3932017-11-17 18:14:09 +0000246 writeGlobal(OS, Global);
247 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000248}
249
250void Writer::createTableSection() {
Nicholas Wilsonfc90b302018-03-28 12:53:29 +0000251 if (Config->ImportTable)
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000252 return;
253
254 // Always output a table section (or table import), even if there are no
255 // indirect calls. There are two reasons for this:
Sam Cleggfc1a9122017-12-11 22:00:56 +0000256 // 1. For executables it is useful to have an empty table slot at 0
257 // which can be filled with a null function call handler.
258 // 2. If we don't do this, any program that contains a call_indirect but
259 // no address-taken function will fail at validation time since it is
260 // a validation error to include a call_indirect instruction if there
261 // is not table.
Sam Clegg48bbd632018-01-24 21:37:30 +0000262 uint32_t TableSize = kInitialTableOffset + IndirectFunctions.size();
Sam Cleggfc1a9122017-12-11 22:00:56 +0000263
Sam Cleggc94d3932017-11-17 18:14:09 +0000264 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TABLE);
265 raw_ostream &OS = Section->getStream();
266
267 writeUleb128(OS, 1, "table count");
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000268 WasmLimits Limits = {WASM_LIMITS_FLAG_HAS_MAX, TableSize, TableSize};
269 writeTableType(OS, WasmTable{WASM_TYPE_ANYFUNC, Limits});
Sam Cleggc94d3932017-11-17 18:14:09 +0000270}
271
272void Writer::createExportSection() {
Sam Cleggd6beb322018-05-10 18:10:34 +0000273 if (!Exports.size())
Sam Cleggc94d3932017-11-17 18:14:09 +0000274 return;
275
276 SyntheticSection *Section = createSyntheticSection(WASM_SEC_EXPORT);
277 raw_ostream &OS = Section->getStream();
278
Sam Cleggd6beb322018-05-10 18:10:34 +0000279 writeUleb128(OS, Exports.size(), "export count");
280 for (const WasmExport &Export : Exports)
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000281 writeExport(OS, Export);
Sam Cleggc94d3932017-11-17 18:14:09 +0000282}
283
Sam Cleggd177ab22018-05-04 23:14:42 +0000284void Writer::calculateCustomSections() {
285 log("calculateCustomSections");
286 bool StripDebug = Config->StripDebug || Config->StripAll;
287 for (ObjFile *File : Symtab->ObjectFiles) {
288 for (InputSection *Section : File->CustomSections) {
289 StringRef Name = Section->getName();
290 // These custom sections are known the linker and synthesized rather than
291 // blindly copied
292 if (Name == "linking" || Name == "name" || Name.startswith("reloc."))
293 continue;
294 // .. or it is a debug section
295 if (StripDebug && Name.startswith(".debug_"))
296 continue;
297 CustomSectionMapping[Name].push_back(Section);
298 }
299 }
300}
301
Sam Clegg80ba4382018-04-10 16:12:49 +0000302void Writer::createCustomSections() {
303 log("createCustomSections");
Sam Clegg80ba4382018-04-10 16:12:49 +0000304 for (auto &Pair : CustomSectionMapping) {
305 StringRef Name = Pair.first();
Sam Cleggd177ab22018-05-04 23:14:42 +0000306
307 auto P = CustomSectionSymbols.find(Name);
308 if (P != CustomSectionSymbols.end()) {
309 uint32_t SectionIndex = OutputSections.size();
310 P->second->setOutputSectionIndex(SectionIndex);
311 }
312
Nicola Zaghene7245b42018-05-15 13:36:20 +0000313 LLVM_DEBUG(dbgs() << "createCustomSection: " << Name << "\n");
Sam Clegg80ba4382018-04-10 16:12:49 +0000314 OutputSections.push_back(make<CustomSection>(Name, Pair.second));
315 }
316}
317
Sam Cleggc94d3932017-11-17 18:14:09 +0000318void Writer::createElemSection() {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000319 if (IndirectFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000320 return;
321
322 SyntheticSection *Section = createSyntheticSection(WASM_SEC_ELEM);
323 raw_ostream &OS = Section->getStream();
324
325 writeUleb128(OS, 1, "segment count");
326 writeUleb128(OS, 0, "table index");
327 WasmInitExpr InitExpr;
328 InitExpr.Opcode = WASM_OPCODE_I32_CONST;
Sam Clegg48bbd632018-01-24 21:37:30 +0000329 InitExpr.Value.Int32 = kInitialTableOffset;
Sam Cleggc94d3932017-11-17 18:14:09 +0000330 writeInitExpr(OS, InitExpr);
Sam Cleggfc1a9122017-12-11 22:00:56 +0000331 writeUleb128(OS, IndirectFunctions.size(), "elem count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000332
Sam Clegg48bbd632018-01-24 21:37:30 +0000333 uint32_t TableIndex = kInitialTableOffset;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000334 for (const FunctionSymbol *Sym : IndirectFunctions) {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000335 assert(Sym->getTableIndex() == TableIndex);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000336 writeUleb128(OS, Sym->getFunctionIndex(), "function index");
Sam Cleggfc1a9122017-12-11 22:00:56 +0000337 ++TableIndex;
338 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000339}
340
341void Writer::createCodeSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000342 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000343 return;
344
345 log("createCodeSection");
346
Sam Clegg9f934222018-02-21 18:29:23 +0000347 auto Section = make<CodeSection>(InputFunctions);
Sam Cleggc94d3932017-11-17 18:14:09 +0000348 OutputSections.push_back(Section);
349}
350
351void Writer::createDataSection() {
352 if (!Segments.size())
353 return;
354
355 log("createDataSection");
356 auto Section = make<DataSection>(Segments);
357 OutputSections.push_back(Section);
358}
359
Sam Cleggd451da12017-12-19 19:56:27 +0000360// Create relocations sections in the final output.
Sam Cleggc94d3932017-11-17 18:14:09 +0000361// These are only created when relocatable output is requested.
362void Writer::createRelocSections() {
363 log("createRelocSections");
364 // Don't use iterator here since we are adding to OutputSection
365 size_t OrigSize = OutputSections.size();
Rui Ueyamaffa650a2018-04-24 23:09:57 +0000366 for (size_t I = 0; I < OrigSize; I++) {
367 OutputSection *OSec = OutputSections[I];
Rui Ueyama37254062018-02-28 00:01:31 +0000368 uint32_t Count = OSec->numRelocations();
Sam Cleggc94d3932017-11-17 18:14:09 +0000369 if (!Count)
370 continue;
371
Rui Ueyama37254062018-02-28 00:01:31 +0000372 StringRef Name;
373 if (OSec->Type == WASM_SEC_DATA)
374 Name = "reloc.DATA";
375 else if (OSec->Type == WASM_SEC_CODE)
376 Name = "reloc.CODE";
Sam Cleggd177ab22018-05-04 23:14:42 +0000377 else if (OSec->Type == WASM_SEC_CUSTOM)
378 Name = Saver.save("reloc." + OSec->Name);
Sam Cleggc94d3932017-11-17 18:14:09 +0000379 else
Sam Cleggd177ab22018-05-04 23:14:42 +0000380 llvm_unreachable(
381 "relocations only supported for code, data, or custom sections");
Sam Cleggc94d3932017-11-17 18:14:09 +0000382
Rui Ueyama37254062018-02-28 00:01:31 +0000383 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, Name);
Sam Cleggc94d3932017-11-17 18:14:09 +0000384 raw_ostream &OS = Section->getStream();
Rui Ueyamaffa650a2018-04-24 23:09:57 +0000385 writeUleb128(OS, I, "reloc section");
Sam Cleggc94d3932017-11-17 18:14:09 +0000386 writeUleb128(OS, Count, "reloc count");
Rui Ueyama37254062018-02-28 00:01:31 +0000387 OSec->writeRelocations(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000388 }
389}
390
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000391static uint32_t getWasmFlags(const Symbol *Sym) {
392 uint32_t Flags = 0;
393 if (Sym->isLocal())
394 Flags |= WASM_SYMBOL_BINDING_LOCAL;
395 if (Sym->isWeak())
396 Flags |= WASM_SYMBOL_BINDING_WEAK;
397 if (Sym->isHidden())
398 Flags |= WASM_SYMBOL_VISIBILITY_HIDDEN;
399 if (Sym->isUndefined())
400 Flags |= WASM_SYMBOL_UNDEFINED;
401 return Flags;
402}
403
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000404// Some synthetic sections (e.g. "name" and "linking") have subsections.
405// Just like the synthetic sections themselves these need to be created before
406// they can be written out (since they are preceded by their length). This
407// class is used to create subsections and then write them into the stream
408// of the parent section.
409class SubSection {
410public:
411 explicit SubSection(uint32_t Type) : Type(Type) {}
412
413 void writeTo(raw_ostream &To) {
414 OS.flush();
Rui Ueyama67769102018-02-28 03:38:14 +0000415 writeUleb128(To, Type, "subsection type");
416 writeUleb128(To, Body.size(), "subsection size");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000417 To.write(Body.data(), Body.size());
418 }
419
420private:
421 uint32_t Type;
422 std::string Body;
423
424public:
425 raw_string_ostream OS{Body};
426};
427
Sam Clegg49ed9262017-12-01 00:53:21 +0000428// Create the custom "linking" section containing linker metadata.
Sam Cleggc94d3932017-11-17 18:14:09 +0000429// This is only created when relocatable output is requested.
430void Writer::createLinkingSection() {
431 SyntheticSection *Section =
432 createSyntheticSection(WASM_SEC_CUSTOM, "linking");
433 raw_ostream &OS = Section->getStream();
434
Sam Clegg2b8b1792018-04-26 18:17:21 +0000435 writeUleb128(OS, WasmMetadataVersion, "Version");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000436
Sam Clegg93102972018-02-23 05:08:53 +0000437 if (!SymtabEntries.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000438 SubSection Sub(WASM_SYMBOL_TABLE);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000439 writeUleb128(Sub.OS, SymtabEntries.size(), "num symbols");
440
Sam Clegg93102972018-02-23 05:08:53 +0000441 for (const Symbol *Sym : SymtabEntries) {
442 assert(Sym->isDefined() || Sym->isUndefined());
443 WasmSymbolType Kind = Sym->getWasmType();
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000444 uint32_t Flags = getWasmFlags(Sym);
445
Sam Clegg8518e7d2018-03-01 18:06:39 +0000446 writeU8(Sub.OS, Kind, "sym kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000447 writeUleb128(Sub.OS, Flags, "sym flags");
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000448
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000449 if (auto *F = dyn_cast<FunctionSymbol>(Sym)) {
450 writeUleb128(Sub.OS, F->getFunctionIndex(), "index");
Sam Clegg93102972018-02-23 05:08:53 +0000451 if (Sym->isDefined())
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000452 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000453 } else if (auto *G = dyn_cast<GlobalSymbol>(Sym)) {
454 writeUleb128(Sub.OS, G->getGlobalIndex(), "index");
455 if (Sym->isDefined())
456 writeStr(Sub.OS, Sym->getName(), "sym name");
Andrea Di Biagio25c1a2f2018-05-05 10:53:31 +0000457 } else if (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 Cleggd177ab22018-05-04 23:14:42 +0000465 } else {
466 auto *S = cast<SectionSymbol>(Sym);
467 writeUleb128(Sub.OS, S->getOutputSectionIndex(), "sym section index");
Sam Clegg93102972018-02-23 05:08:53 +0000468 }
Sam Cleggd3052d52018-01-18 23:40:49 +0000469 }
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000470
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000471 Sub.writeTo(OS);
Sam Cleggd3052d52018-01-18 23:40:49 +0000472 }
473
Sam Clegg0d0dd392017-12-19 17:09:45 +0000474 if (Segments.size()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000475 SubSection Sub(WASM_SEGMENT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000476 writeUleb128(Sub.OS, Segments.size(), "num data segments");
Sam Cleggc94d3932017-11-17 18:14:09 +0000477 for (const OutputSegment *S : Segments) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000478 writeStr(Sub.OS, S->Name, "segment name");
479 writeUleb128(Sub.OS, S->Alignment, "alignment");
480 writeUleb128(Sub.OS, 0, "flags");
Sam Cleggc94d3932017-11-17 18:14:09 +0000481 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000482 Sub.writeTo(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000483 }
Sam Clegg0d0dd392017-12-19 17:09:45 +0000484
Sam Clegg0d0dd392017-12-19 17:09:45 +0000485 if (!InitFunctions.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000486 SubSection Sub(WASM_INIT_FUNCS);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000487 writeUleb128(Sub.OS, InitFunctions.size(), "num init functions");
Sam Clegg93102972018-02-23 05:08:53 +0000488 for (const WasmInitEntry &F : InitFunctions) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000489 writeUleb128(Sub.OS, F.Priority, "priority");
490 writeUleb128(Sub.OS, F.Sym->getOutputSymbolIndex(), "function index");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000491 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000492 Sub.writeTo(OS);
Sam Clegg0d0dd392017-12-19 17:09:45 +0000493 }
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000494
Nicholas Wilsondbd90bf2018-03-07 13:28:16 +0000495 struct ComdatEntry {
496 unsigned Kind;
497 uint32_t Index;
498 };
499 std::map<StringRef, std::vector<ComdatEntry>> Comdats;
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000500
Sam Clegg9f934222018-02-21 18:29:23 +0000501 for (const InputFunction *F : InputFunctions) {
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000502 StringRef Comdat = F->getComdatName();
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000503 if (!Comdat.empty())
504 Comdats[Comdat].emplace_back(
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000505 ComdatEntry{WASM_COMDAT_FUNCTION, F->getFunctionIndex()});
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000506 }
507 for (uint32_t I = 0; I < Segments.size(); ++I) {
Sam Cleggf98bccf2018-01-13 15:57:48 +0000508 const auto &InputSegments = Segments[I]->InputSegments;
509 if (InputSegments.empty())
510 continue;
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000511 StringRef Comdat = InputSegments[0]->getComdatName();
Sam Clegga697df522018-01-13 15:59:53 +0000512#ifndef NDEBUG
Sam Cleggf98bccf2018-01-13 15:57:48 +0000513 for (const InputSegment *IS : InputSegments)
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000514 assert(IS->getComdatName() == Comdat);
Sam Clegga697df522018-01-13 15:59:53 +0000515#endif
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000516 if (!Comdat.empty())
517 Comdats[Comdat].emplace_back(ComdatEntry{WASM_COMDAT_DATA, I});
518 }
519
520 if (!Comdats.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000521 SubSection Sub(WASM_COMDAT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000522 writeUleb128(Sub.OS, Comdats.size(), "num comdats");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000523 for (const auto &C : Comdats) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000524 writeStr(Sub.OS, C.first, "comdat name");
525 writeUleb128(Sub.OS, 0, "comdat flags"); // flags for future use
526 writeUleb128(Sub.OS, C.second.size(), "num entries");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000527 for (const ComdatEntry &Entry : C.second) {
Sam Clegg8518e7d2018-03-01 18:06:39 +0000528 writeU8(Sub.OS, Entry.Kind, "entry kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000529 writeUleb128(Sub.OS, Entry.Index, "entry index");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000530 }
531 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000532 Sub.writeTo(OS);
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000533 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000534}
535
536// Create the custom "name" section containing debug symbol names.
537void Writer::createNameSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000538 unsigned NumNames = NumImportedFunctions;
Sam Clegg9f934222018-02-21 18:29:23 +0000539 for (const InputFunction *F : InputFunctions)
Nicholas Wilson6c7fe302018-04-20 17:09:18 +0000540 if (!F->getName().empty() || !F->getDebugName().empty())
Sam Clegg1963d712018-01-17 20:19:04 +0000541 ++NumNames;
Sam Cleggc94d3932017-11-17 18:14:09 +0000542
Sam Clegg1963d712018-01-17 20:19:04 +0000543 if (NumNames == 0)
544 return;
Sam Clegg50686852018-01-12 18:35:13 +0000545
Sam Cleggc94d3932017-11-17 18:14:09 +0000546 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "name");
547
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000548 SubSection Sub(WASM_NAMES_FUNCTION);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000549 writeUleb128(Sub.OS, NumNames, "name count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000550
Sam Clegg93102972018-02-23 05:08:53 +0000551 // Names must appear in function index order. As it happens ImportedSymbols
552 // and InputFunctions are numbered in order with imported functions coming
Sam Clegg1963d712018-01-17 20:19:04 +0000553 // first.
Sam Clegg93102972018-02-23 05:08:53 +0000554 for (const Symbol *S : ImportedSymbols) {
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000555 if (auto *F = dyn_cast<FunctionSymbol>(S)) {
556 writeUleb128(Sub.OS, F->getFunctionIndex(), "func index");
Sam Clegg37125f02018-11-09 16:57:41 +0000557 writeStr(Sub.OS, toString(*S), "symbol name");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000558 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000559 }
Sam Clegg9f934222018-02-21 18:29:23 +0000560 for (const InputFunction *F : InputFunctions) {
Sam Clegg1963d712018-01-17 20:19:04 +0000561 if (!F->getName().empty()) {
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000562 writeUleb128(Sub.OS, F->getFunctionIndex(), "func index");
Nicholas Wilson6c7fe302018-04-20 17:09:18 +0000563 if (!F->getDebugName().empty()) {
564 writeStr(Sub.OS, F->getDebugName(), "symbol name");
565 } else {
Sam Clegg37125f02018-11-09 16:57:41 +0000566 writeStr(Sub.OS, maybeDemangleSymbol(F->getName()), "symbol name");
Nicholas Wilson6c7fe302018-04-20 17:09:18 +0000567 }
Sam Clegg1963d712018-01-17 20:19:04 +0000568 }
569 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000570
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000571 Sub.writeTo(Section->getStream());
Sam Cleggc94d3932017-11-17 18:14:09 +0000572}
573
574void Writer::writeHeader() {
575 memcpy(Buffer->getBufferStart(), Header.data(), Header.size());
576}
577
578void Writer::writeSections() {
579 uint8_t *Buf = Buffer->getBufferStart();
580 parallelForEach(OutputSections, [Buf](OutputSection *S) { S->writeTo(Buf); });
581}
582
583// Fix the memory layout of the output binary. This assigns memory offsets
Sam Clegg49ed9262017-12-01 00:53:21 +0000584// to each of the input data sections as well as the explicit stack region.
Sam Clegga0f095e2018-05-03 17:21:53 +0000585// The default memory layout is as follows, from low to high.
586//
Sam Cleggf0d433d2018-02-02 22:59:56 +0000587// - initialized data (starting at Config->GlobalBase)
588// - BSS data (not currently implemented in llvm)
589// - explicit stack (Config->ZStackSize)
590// - heap start / unallocated
Sam Clegga0f095e2018-05-03 17:21:53 +0000591//
592// The --stack-first option means that stack is placed before any static data.
Heejin Ahn4821ebf2018-08-29 21:03:16 +0000593// This can be useful since it means that stack overflow traps immediately
594// rather than overwriting global data, but also increases code size since all
595// static data loads and stores requires larger offsets.
Sam Cleggc94d3932017-11-17 18:14:09 +0000596void Writer::layoutMemory() {
Sam Cleggc94d3932017-11-17 18:14:09 +0000597 createOutputSegments();
598
Sam Clegga0f095e2018-05-03 17:21:53 +0000599 uint32_t MemoryPtr = 0;
600
601 auto PlaceStack = [&]() {
602 if (Config->Relocatable)
603 return;
604 MemoryPtr = alignTo(MemoryPtr, kStackAlignment);
605 if (Config->ZStackSize != alignTo(Config->ZStackSize, kStackAlignment))
606 error("stack size must be " + Twine(kStackAlignment) + "-byte aligned");
607 log("mem: stack size = " + Twine(Config->ZStackSize));
608 log("mem: stack base = " + Twine(MemoryPtr));
609 MemoryPtr += Config->ZStackSize;
610 WasmSym::StackPointer->Global->Global.InitExpr.Value.Int32 = MemoryPtr;
611 log("mem: stack top = " + Twine(MemoryPtr));
612 };
613
614 if (Config->StackFirst) {
615 PlaceStack();
616 } else {
617 MemoryPtr = Config->GlobalBase;
618 log("mem: global base = " + Twine(Config->GlobalBase));
619 }
620
621 uint32_t DataStart = MemoryPtr;
622
Sam Cleggf0d433d2018-02-02 22:59:56 +0000623 // Arbitrarily set __dso_handle handle to point to the start of the data
624 // segments.
625 if (WasmSym::DsoHandle)
Sam Clegga0f095e2018-05-03 17:21:53 +0000626 WasmSym::DsoHandle->setVirtualAddress(DataStart);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000627
Sam Cleggc94d3932017-11-17 18:14:09 +0000628 for (OutputSegment *Seg : Segments) {
629 MemoryPtr = alignTo(MemoryPtr, Seg->Alignment);
630 Seg->StartVA = MemoryPtr;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000631 log(formatv("mem: {0,-15} offset={1,-8} size={2,-8} align={3}", Seg->Name,
632 MemoryPtr, Seg->Size, Seg->Alignment));
Sam Cleggc94d3932017-11-17 18:14:09 +0000633 MemoryPtr += Seg->Size;
634 }
635
Sam Cleggf0d433d2018-02-02 22:59:56 +0000636 // TODO: Add .bss space here.
Sam Clegg37a4a8a2018-02-07 03:04:53 +0000637 if (WasmSym::DataEnd)
638 WasmSym::DataEnd->setVirtualAddress(MemoryPtr);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000639
Sam Clegga0f095e2018-05-03 17:21:53 +0000640 log("mem: static data = " + Twine(MemoryPtr - DataStart));
Sam Cleggc94d3932017-11-17 18:14:09 +0000641
Sam Clegga0f095e2018-05-03 17:21:53 +0000642 if (!Config->StackFirst)
643 PlaceStack();
644
645 // Set `__heap_base` to directly follow the end of the stack or global data.
646 // The fact that this comes last means that a malloc/brk implementation
647 // can grow the heap at runtime.
Sam Cleggc94d3932017-11-17 18:14:09 +0000648 if (!Config->Relocatable) {
Sam Cleggf0d433d2018-02-02 22:59:56 +0000649 WasmSym::HeapBase->setVirtualAddress(MemoryPtr);
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000650 log("mem: heap base = " + Twine(MemoryPtr));
Sam Cleggc94d3932017-11-17 18:14:09 +0000651 }
652
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000653 if (Config->InitialMemory != 0) {
654 if (Config->InitialMemory != alignTo(Config->InitialMemory, WasmPageSize))
655 error("initial memory must be " + Twine(WasmPageSize) + "-byte aligned");
656 if (MemoryPtr > Config->InitialMemory)
657 error("initial memory too small, " + Twine(MemoryPtr) + " bytes needed");
658 else
659 MemoryPtr = Config->InitialMemory;
660 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000661 uint32_t MemSize = alignTo(MemoryPtr, WasmPageSize);
662 NumMemoryPages = MemSize / WasmPageSize;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000663 log("mem: total pages = " + Twine(NumMemoryPages));
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000664
665 if (Config->MaxMemory != 0) {
666 if (Config->MaxMemory != alignTo(Config->MaxMemory, WasmPageSize))
667 error("maximum memory must be " + Twine(WasmPageSize) + "-byte aligned");
668 if (MemoryPtr > Config->MaxMemory)
669 error("maximum memory too small, " + Twine(MemoryPtr) + " bytes needed");
670 MaxMemoryPages = Config->MaxMemory / WasmPageSize;
671 log("mem: max pages = " + Twine(MaxMemoryPages));
672 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000673}
674
675SyntheticSection *Writer::createSyntheticSection(uint32_t Type,
Sam Cleggc375e4e2018-01-10 19:18:22 +0000676 StringRef Name) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000677 auto Sec = make<SyntheticSection>(Type, Name);
Sam Cleggab2ac292017-12-20 05:14:48 +0000678 log("createSection: " + toString(*Sec));
Sam Cleggc94d3932017-11-17 18:14:09 +0000679 OutputSections.push_back(Sec);
680 return Sec;
681}
682
683void Writer::createSections() {
684 // Known sections
685 createTypeSection();
686 createImportSection();
687 createFunctionSection();
688 createTableSection();
689 createMemorySection();
690 createGlobalSection();
691 createExportSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000692 createElemSection();
693 createCodeSection();
694 createDataSection();
Sam Clegg80ba4382018-04-10 16:12:49 +0000695 createCustomSections();
Sam Cleggc94d3932017-11-17 18:14:09 +0000696
697 // Custom sections
Sam Clegg99eb42c2018-02-27 23:58:03 +0000698 if (Config->Relocatable) {
Sam Clegg99eb42c2018-02-27 23:58:03 +0000699 createLinkingSection();
Nicholas Wilson94d3b162018-03-05 12:33:58 +0000700 createRelocSections();
Sam Clegg99eb42c2018-02-27 23:58:03 +0000701 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000702 if (!Config->StripDebug && !Config->StripAll)
703 createNameSection();
704
705 for (OutputSection *S : OutputSections) {
706 S->setOffset(FileSize);
707 S->finalizeContents();
708 FileSize += S->getSize();
709 }
710}
711
Sam Cleggc94d3932017-11-17 18:14:09 +0000712void Writer::calculateImports() {
Sam Clegg574d7ce2017-12-15 19:23:49 +0000713 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000714 if (!Sym->isUndefined())
715 continue;
716 if (isa<DataSymbol>(Sym))
717 continue;
718 if (Sym->isWeak() && !Config->Relocatable)
Sam Clegg574d7ce2017-12-15 19:23:49 +0000719 continue;
Nicholas Wilsona1e299f2018-04-20 17:18:06 +0000720 if (!Sym->isLive())
721 continue;
Sam Cleggc729c1b2018-05-30 18:07:52 +0000722 if (!Sym->IsUsedInRegularObj)
723 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000724
Nicola Zaghene7245b42018-05-15 13:36:20 +0000725 LLVM_DEBUG(dbgs() << "import: " << Sym->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000726 ImportedSymbols.emplace_back(Sym);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000727 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
728 F->setFunctionIndex(NumImportedFunctions++);
Sam Clegg93102972018-02-23 05:08:53 +0000729 else
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000730 cast<GlobalSymbol>(Sym)->setGlobalIndex(NumImportedGlobals++);
Sam Cleggc94d3932017-11-17 18:14:09 +0000731 }
732}
733
Sam Cleggd3052d52018-01-18 23:40:49 +0000734void Writer::calculateExports() {
Sam Clegg93102972018-02-23 05:08:53 +0000735 if (Config->Relocatable)
736 return;
Sam Cleggf0d433d2018-02-02 22:59:56 +0000737
Sam Cleggd6beb322018-05-10 18:10:34 +0000738 if (!Config->Relocatable && !Config->ImportMemory)
739 Exports.push_back(WasmExport{"memory", WASM_EXTERNAL_MEMORY, 0});
740
741 if (!Config->Relocatable && Config->ExportTable)
742 Exports.push_back(WasmExport{kFunctionTableName, WASM_EXTERNAL_TABLE, 0});
743
744 unsigned FakeGlobalIndex = NumImportedGlobals + InputGlobals.size();
745
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000746 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Cleggce004bf2018-06-28 17:04:58 +0000747 if (!Sym->isExported())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000748 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000749 if (!Sym->isLive())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000750 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000751
Sam Cleggd6beb322018-05-10 18:10:34 +0000752 StringRef Name = Sym->getName();
753 WasmExport Export;
754 if (auto *F = dyn_cast<DefinedFunction>(Sym)) {
755 Export = {Name, WASM_EXTERNAL_FUNCTION, F->getFunctionIndex()};
756 } else if (auto *G = dyn_cast<DefinedGlobal>(Sym)) {
Sam Clegg177b4582018-06-07 01:27:07 +0000757 // TODO(sbc): Remove this check once to mutable global proposal is
758 // implement in all major browsers.
759 // See: https://github.com/WebAssembly/mutable-global
760 if (G->getGlobalType()->Mutable) {
761 // Only the __stack_pointer should ever be create as mutable.
762 assert(G == WasmSym::StackPointer);
763 continue;
764 }
Sam Cleggd6beb322018-05-10 18:10:34 +0000765 Export = {Name, WASM_EXTERNAL_GLOBAL, G->getGlobalIndex()};
766 } else {
767 auto *D = cast<DefinedData>(Sym);
Sam Clegg93102972018-02-23 05:08:53 +0000768 DefinedFakeGlobals.emplace_back(D);
Sam Cleggd6beb322018-05-10 18:10:34 +0000769 Export = {Name, WASM_EXTERNAL_GLOBAL, FakeGlobalIndex++};
770 }
771
Nicola Zaghene7245b42018-05-15 13:36:20 +0000772 LLVM_DEBUG(dbgs() << "Export: " << Name << "\n");
Sam Cleggd6beb322018-05-10 18:10:34 +0000773 Exports.push_back(Export);
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000774 }
Sam Clegg93102972018-02-23 05:08:53 +0000775}
776
777void Writer::assignSymtab() {
778 if (!Config->Relocatable)
779 return;
780
Sam Cleggd177ab22018-05-04 23:14:42 +0000781 StringMap<uint32_t> SectionSymbolIndices;
782
Sam Clegg93102972018-02-23 05:08:53 +0000783 unsigned SymbolIndex = SymtabEntries.size();
Sam Cleggd3052d52018-01-18 23:40:49 +0000784 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000785 LLVM_DEBUG(dbgs() << "Symtab entries: " << File->getName() << "\n");
Sam Cleggd3052d52018-01-18 23:40:49 +0000786 for (Symbol *Sym : File->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000787 if (Sym->getFile() != File)
Sam Cleggd3052d52018-01-18 23:40:49 +0000788 continue;
Sam Cleggd177ab22018-05-04 23:14:42 +0000789
790 if (auto *S = dyn_cast<SectionSymbol>(Sym)) {
791 StringRef Name = S->getName();
792 if (CustomSectionMapping.count(Name) == 0)
793 continue;
794
795 auto SSI = SectionSymbolIndices.find(Name);
796 if (SSI != SectionSymbolIndices.end()) {
797 Sym->setOutputSymbolIndex(SSI->second);
798 continue;
799 }
800
801 SectionSymbolIndices[Name] = SymbolIndex;
802 CustomSectionSymbols[Name] = cast<SectionSymbol>(Sym);
803
804 Sym->markLive();
805 }
806
Nicholas Wilson06e0d172018-03-07 11:15:47 +0000807 // (Since this is relocatable output, GC is not performed so symbols must
808 // be live.)
809 assert(Sym->isLive());
Sam Clegg93102972018-02-23 05:08:53 +0000810 Sym->setOutputSymbolIndex(SymbolIndex++);
811 SymtabEntries.emplace_back(Sym);
Sam Cleggd3052d52018-01-18 23:40:49 +0000812 }
813 }
814
Sam Clegg93102972018-02-23 05:08:53 +0000815 // For the moment, relocatable output doesn't contain any synthetic functions,
816 // so no need to look through the Symtab for symbols not referenced by
817 // Symtab->ObjectFiles.
Sam Cleggd3052d52018-01-18 23:40:49 +0000818}
819
Sam Cleggc375e4e2018-01-10 19:18:22 +0000820uint32_t Writer::lookupType(const WasmSignature &Sig) {
Sam Clegg8d027d62018-01-10 20:12:26 +0000821 auto It = TypeIndices.find(Sig);
822 if (It == TypeIndices.end()) {
Sam Cleggc375e4e2018-01-10 19:18:22 +0000823 error("type not found: " + toString(Sig));
Sam Clegg8d027d62018-01-10 20:12:26 +0000824 return 0;
825 }
826 return It->second;
Sam Cleggc375e4e2018-01-10 19:18:22 +0000827}
828
829uint32_t Writer::registerType(const WasmSignature &Sig) {
Sam Cleggb8621592017-11-30 01:40:08 +0000830 auto Pair = TypeIndices.insert(std::make_pair(Sig, Types.size()));
Sam Cleggc375e4e2018-01-10 19:18:22 +0000831 if (Pair.second) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000832 LLVM_DEBUG(dbgs() << "type " << toString(Sig) << "\n");
Sam Cleggb8621592017-11-30 01:40:08 +0000833 Types.push_back(&Sig);
Sam Cleggc375e4e2018-01-10 19:18:22 +0000834 }
Sam Cleggb8621592017-11-30 01:40:08 +0000835 return Pair.first->second;
836}
837
Sam Cleggc94d3932017-11-17 18:14:09 +0000838void Writer::calculateTypes() {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000839 // The output type section is the union of the following sets:
840 // 1. Any signature used in the TYPE relocation
841 // 2. The signatures of all imported functions
842 // 3. The signatures of all defined functions
843
Sam Cleggc94d3932017-11-17 18:14:09 +0000844 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000845 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
846 for (uint32_t I = 0; I < Types.size(); I++)
847 if (File->TypeIsUsed[I])
848 File->TypeMap[I] = registerType(Types[I]);
Sam Cleggc94d3932017-11-17 18:14:09 +0000849 }
Sam Clegg50686852018-01-12 18:35:13 +0000850
Sam Clegg93102972018-02-23 05:08:53 +0000851 for (const Symbol *Sym : ImportedSymbols)
852 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
Sam Cleggcefbf9a2018-06-28 16:53:53 +0000853 registerType(*F->FunctionType);
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000854
Sam Clegg9f934222018-02-21 18:29:23 +0000855 for (const InputFunction *F : InputFunctions)
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000856 registerType(F->Signature);
Sam Cleggc94d3932017-11-17 18:14:09 +0000857}
858
Sam Clegg8d146bb2018-01-09 23:56:44 +0000859void Writer::assignIndexes() {
Sam Clegg93102972018-02-23 05:08:53 +0000860 uint32_t FunctionIndex = NumImportedFunctions + InputFunctions.size();
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000861 auto AddDefinedFunction = [&](InputFunction *Func) {
862 if (!Func->Live)
863 return;
864 InputFunctions.emplace_back(Func);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000865 Func->setFunctionIndex(FunctionIndex++);
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000866 };
867
Nicholas Wilson5639da82018-03-12 15:44:07 +0000868 for (InputFunction *Func : Symtab->SyntheticFunctions)
869 AddDefinedFunction(Func);
870
Sam Clegg87e61922018-01-08 23:39:11 +0000871 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000872 LLVM_DEBUG(dbgs() << "Functions: " << File->getName() << "\n");
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000873 for (InputFunction *Func : File->Functions)
874 AddDefinedFunction(Func);
Sam Clegg8d146bb2018-01-09 23:56:44 +0000875 }
876
Sam Clegg93102972018-02-23 05:08:53 +0000877 uint32_t TableIndex = kInitialTableOffset;
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000878 auto HandleRelocs = [&](InputChunk *Chunk) {
879 if (!Chunk->Live)
880 return;
881 ObjFile *File = Chunk->File;
882 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
Sam Clegg93102972018-02-23 05:08:53 +0000883 for (const WasmRelocation &Reloc : Chunk->getRelocations()) {
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000884 if (Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_I32 ||
885 Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_SLEB) {
886 FunctionSymbol *Sym = File->getFunctionSymbol(Reloc.Index);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000887 if (Sym->hasTableIndex() || !Sym->hasFunctionIndex())
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000888 continue;
889 Sym->setTableIndex(TableIndex++);
890 IndirectFunctions.emplace_back(Sym);
891 } else if (Reloc.Type == R_WEBASSEMBLY_TYPE_INDEX_LEB) {
Sam Clegg93102972018-02-23 05:08:53 +0000892 // Mark target type as live
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000893 File->TypeMap[Reloc.Index] = registerType(Types[Reloc.Index]);
894 File->TypeIsUsed[Reloc.Index] = true;
895 }
896 }
897 };
898
Sam Clegg8d146bb2018-01-09 23:56:44 +0000899 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000900 LLVM_DEBUG(dbgs() << "Handle relocs: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000901 for (InputChunk *Chunk : File->Functions)
902 HandleRelocs(Chunk);
903 for (InputChunk *Chunk : File->Segments)
904 HandleRelocs(Chunk);
Sam Cleggd177ab22018-05-04 23:14:42 +0000905 for (auto &P : File->CustomSections)
906 HandleRelocs(P);
Sam Clegg93102972018-02-23 05:08:53 +0000907 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000908
Sam Clegg93102972018-02-23 05:08:53 +0000909 uint32_t GlobalIndex = NumImportedGlobals + InputGlobals.size();
910 auto AddDefinedGlobal = [&](InputGlobal *Global) {
911 if (Global->Live) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000912 LLVM_DEBUG(dbgs() << "AddDefinedGlobal: " << GlobalIndex << "\n");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000913 Global->setGlobalIndex(GlobalIndex++);
Sam Clegg93102972018-02-23 05:08:53 +0000914 InputGlobals.push_back(Global);
915 }
916 };
917
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000918 for (InputGlobal *Global : Symtab->SyntheticGlobals)
919 AddDefinedGlobal(Global);
Sam Clegg93102972018-02-23 05:08:53 +0000920
921 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000922 LLVM_DEBUG(dbgs() << "Globals: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000923 for (InputGlobal *Global : File->Globals)
924 AddDefinedGlobal(Global);
Sam Cleggc94d3932017-11-17 18:14:09 +0000925 }
926}
927
928static StringRef getOutputDataSegmentName(StringRef Name) {
Sam Clegg66844762018-05-10 18:23:51 +0000929 if (!Config->MergeDataSegments)
Sam Cleggc94d3932017-11-17 18:14:09 +0000930 return Name;
Rui Ueyama4764b572018-02-28 00:57:28 +0000931 if (Name.startswith(".text."))
932 return ".text";
933 if (Name.startswith(".data."))
934 return ".data";
935 if (Name.startswith(".bss."))
936 return ".bss";
Sam Clegg57694c52018-08-08 18:02:55 +0000937 if (Name.startswith(".rodata."))
938 return ".rodata";
Sam Cleggc94d3932017-11-17 18:14:09 +0000939 return Name;
940}
941
942void Writer::createOutputSegments() {
943 for (ObjFile *File : Symtab->ObjectFiles) {
944 for (InputSegment *Segment : File->Segments) {
Sam Clegg447ae402018-02-13 20:29:38 +0000945 if (!Segment->Live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000946 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000947 StringRef Name = getOutputDataSegmentName(Segment->getName());
948 OutputSegment *&S = SegmentMap[Name];
949 if (S == nullptr) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000950 LLVM_DEBUG(dbgs() << "new segment: " << Name << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000951 S = make<OutputSegment>(Name, Segments.size());
Sam Cleggc94d3932017-11-17 18:14:09 +0000952 Segments.push_back(S);
953 }
954 S->addInputSegment(Segment);
Nicola Zaghene7245b42018-05-15 13:36:20 +0000955 LLVM_DEBUG(dbgs() << "added data: " << Name << ": " << S->Size << "\n");
Sam Cleggc94d3932017-11-17 18:14:09 +0000956 }
957 }
958}
959
Sam Clegg50686852018-01-12 18:35:13 +0000960static const int OPCODE_CALL = 0x10;
961static const int OPCODE_END = 0xb;
962
963// Create synthetic "__wasm_call_ctors" function based on ctor functions
964// in input object.
965void Writer::createCtorFunction() {
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000966 // First write the body's contents to a string.
967 std::string BodyContent;
Sam Clegg50686852018-01-12 18:35:13 +0000968 {
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000969 raw_string_ostream OS(BodyContent);
Sam Clegg50686852018-01-12 18:35:13 +0000970 writeUleb128(OS, 0, "num locals");
Sam Clegg93102972018-02-23 05:08:53 +0000971 for (const WasmInitEntry &F : InitFunctions) {
Sam Clegg50686852018-01-12 18:35:13 +0000972 writeU8(OS, OPCODE_CALL, "CALL");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000973 writeUleb128(OS, F.Sym->getFunctionIndex(), "function index");
Sam Clegg50686852018-01-12 18:35:13 +0000974 }
975 writeU8(OS, OPCODE_END, "END");
976 }
977
978 // Once we know the size of the body we can create the final function body
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000979 std::string FunctionBody;
980 {
981 raw_string_ostream OS(FunctionBody);
982 writeUleb128(OS, BodyContent.size(), "function size");
983 OS << BodyContent;
984 }
Rui Ueyama29abfe42018-02-28 17:43:15 +0000985
Sam Cleggea656472018-10-22 08:35:39 +0000986 ArrayRef<uint8_t> Body = arrayRefFromStringRef(Saver.save(FunctionBody));
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000987 cast<SyntheticFunction>(WasmSym::CallCtors->Function)->setBody(Body);
Sam Clegg50686852018-01-12 18:35:13 +0000988}
989
990// Populate InitFunctions vector with init functions from all input objects.
991// This is then used either when creating the output linking section or to
992// synthesize the "__wasm_call_ctors" function.
993void Writer::calculateInitFunctions() {
994 for (ObjFile *File : Symtab->ObjectFiles) {
995 const WasmLinkingData &L = File->getWasmObj()->linkingData();
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +0000996 for (const WasmInitFunc &F : L.InitFunctions) {
997 FunctionSymbol *Sym = File->getFunctionSymbol(F.Symbol);
Derek Schuff371842b2018-10-03 22:25:32 +0000998 if (*Sym->FunctionType != WasmSignature{{}, {}})
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +0000999 error("invalid signature for init func: " + toString(*Sym));
1000 InitFunctions.emplace_back(WasmInitEntry{Sym, F.Priority});
1001 }
Sam Clegg50686852018-01-12 18:35:13 +00001002 }
Rui Ueyamada69b712018-02-28 00:15:59 +00001003
Sam Clegg50686852018-01-12 18:35:13 +00001004 // Sort in order of priority (lowest first) so that they are called
1005 // in the correct order.
Sam Clegg29b8feb2018-02-21 00:34:34 +00001006 std::stable_sort(InitFunctions.begin(), InitFunctions.end(),
Sam Clegg93102972018-02-23 05:08:53 +00001007 [](const WasmInitEntry &L, const WasmInitEntry &R) {
Sam Clegg29b8feb2018-02-21 00:34:34 +00001008 return L.Priority < R.Priority;
1009 });
Sam Clegg50686852018-01-12 18:35:13 +00001010}
1011
Sam Cleggc94d3932017-11-17 18:14:09 +00001012void Writer::run() {
Sam Clegg99eb42c2018-02-27 23:58:03 +00001013 if (Config->Relocatable)
1014 Config->GlobalBase = 0;
1015
Sam Cleggc94d3932017-11-17 18:14:09 +00001016 log("-- calculateImports");
1017 calculateImports();
Sam Clegg8d146bb2018-01-09 23:56:44 +00001018 log("-- assignIndexes");
1019 assignIndexes();
Sam Clegg50686852018-01-12 18:35:13 +00001020 log("-- calculateInitFunctions");
1021 calculateInitFunctions();
1022 if (!Config->Relocatable)
1023 createCtorFunction();
Sam Clegg8f6d2de2018-01-31 23:48:14 +00001024 log("-- calculateTypes");
1025 calculateTypes();
Sam Clegg93102972018-02-23 05:08:53 +00001026 log("-- layoutMemory");
1027 layoutMemory();
1028 log("-- calculateExports");
1029 calculateExports();
Sam Cleggd177ab22018-05-04 23:14:42 +00001030 log("-- calculateCustomSections");
1031 calculateCustomSections();
Sam Clegg93102972018-02-23 05:08:53 +00001032 log("-- assignSymtab");
1033 assignSymtab();
Sam Cleggc94d3932017-11-17 18:14:09 +00001034
1035 if (errorHandler().Verbose) {
Sam Clegg9f934222018-02-21 18:29:23 +00001036 log("Defined Functions: " + Twine(InputFunctions.size()));
Sam Clegg93102972018-02-23 05:08:53 +00001037 log("Defined Globals : " + Twine(InputGlobals.size()));
1038 log("Function Imports : " + Twine(NumImportedFunctions));
1039 log("Global Imports : " + Twine(NumImportedGlobals));
Sam Cleggc94d3932017-11-17 18:14:09 +00001040 for (ObjFile *File : Symtab->ObjectFiles)
1041 File->dumpInfo();
1042 }
1043
Sam Cleggc94d3932017-11-17 18:14:09 +00001044 createHeader();
1045 log("-- createSections");
1046 createSections();
1047
1048 log("-- openFile");
1049 openFile();
1050 if (errorCount())
1051 return;
1052
1053 writeHeader();
1054
1055 log("-- writeSections");
1056 writeSections();
1057 if (errorCount())
1058 return;
1059
1060 if (Error E = Buffer->commit())
1061 fatal("failed to write the output file: " + toString(std::move(E)));
1062}
1063
1064// Open a result file.
1065void Writer::openFile() {
1066 log("writing: " + Config->OutputFile);
Sam Cleggc94d3932017-11-17 18:14:09 +00001067
1068 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
1069 FileOutputBuffer::create(Config->OutputFile, FileSize,
1070 FileOutputBuffer::F_executable);
1071
1072 if (!BufferOrErr)
1073 error("failed to open " + Config->OutputFile + ": " +
1074 toString(BufferOrErr.takeError()));
1075 else
1076 Buffer = std::move(*BufferOrErr);
1077}
1078
1079void Writer::createHeader() {
1080 raw_string_ostream OS(Header);
1081 writeBytes(OS, WasmMagic, sizeof(WasmMagic), "wasm magic");
1082 writeU32(OS, WasmVersion, "wasm version");
1083 OS.flush();
1084 FileSize += Header.size();
1085}
1086
1087void lld::wasm::writeResult() { Writer().run(); }