blob: c26ae53311b5d5a93ca855a0d89c34a0eb44ecf5 [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");
Nicholas Wilson531769b2018-03-13 13:30:04 +0000557 Optional<std::string> Name = demangleItanium(F->getName());
558 writeStr(Sub.OS, Name ? StringRef(*Name) : F->getName(), "symbol name");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000559 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000560 }
Sam Clegg9f934222018-02-21 18:29:23 +0000561 for (const InputFunction *F : InputFunctions) {
Sam Clegg1963d712018-01-17 20:19:04 +0000562 if (!F->getName().empty()) {
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000563 writeUleb128(Sub.OS, F->getFunctionIndex(), "func index");
Nicholas Wilson6c7fe302018-04-20 17:09:18 +0000564 if (!F->getDebugName().empty()) {
565 writeStr(Sub.OS, F->getDebugName(), "symbol name");
566 } else {
567 Optional<std::string> Name = demangleItanium(F->getName());
568 writeStr(Sub.OS, Name ? StringRef(*Name) : F->getName(), "symbol name");
569 }
Sam Clegg1963d712018-01-17 20:19:04 +0000570 }
571 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000572
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000573 Sub.writeTo(Section->getStream());
Sam Cleggc94d3932017-11-17 18:14:09 +0000574}
575
576void Writer::writeHeader() {
577 memcpy(Buffer->getBufferStart(), Header.data(), Header.size());
578}
579
580void Writer::writeSections() {
581 uint8_t *Buf = Buffer->getBufferStart();
582 parallelForEach(OutputSections, [Buf](OutputSection *S) { S->writeTo(Buf); });
583}
584
585// Fix the memory layout of the output binary. This assigns memory offsets
Sam Clegg49ed9262017-12-01 00:53:21 +0000586// to each of the input data sections as well as the explicit stack region.
Sam Clegga0f095e2018-05-03 17:21:53 +0000587// The default memory layout is as follows, from low to high.
588//
Sam Cleggf0d433d2018-02-02 22:59:56 +0000589// - initialized data (starting at Config->GlobalBase)
590// - BSS data (not currently implemented in llvm)
591// - explicit stack (Config->ZStackSize)
592// - heap start / unallocated
Sam Clegga0f095e2018-05-03 17:21:53 +0000593//
594// The --stack-first option means that stack is placed before any static data.
Heejin Ahn4821ebf2018-08-29 21:03:16 +0000595// This can be useful since it means that stack overflow traps immediately
596// rather than overwriting global data, but also increases code size since all
597// static data loads and stores requires larger offsets.
Sam Cleggc94d3932017-11-17 18:14:09 +0000598void Writer::layoutMemory() {
Sam Cleggc94d3932017-11-17 18:14:09 +0000599 createOutputSegments();
600
Sam Clegga0f095e2018-05-03 17:21:53 +0000601 uint32_t MemoryPtr = 0;
602
603 auto PlaceStack = [&]() {
604 if (Config->Relocatable)
605 return;
606 MemoryPtr = alignTo(MemoryPtr, kStackAlignment);
607 if (Config->ZStackSize != alignTo(Config->ZStackSize, kStackAlignment))
608 error("stack size must be " + Twine(kStackAlignment) + "-byte aligned");
609 log("mem: stack size = " + Twine(Config->ZStackSize));
610 log("mem: stack base = " + Twine(MemoryPtr));
611 MemoryPtr += Config->ZStackSize;
612 WasmSym::StackPointer->Global->Global.InitExpr.Value.Int32 = MemoryPtr;
613 log("mem: stack top = " + Twine(MemoryPtr));
614 };
615
616 if (Config->StackFirst) {
617 PlaceStack();
618 } else {
619 MemoryPtr = Config->GlobalBase;
620 log("mem: global base = " + Twine(Config->GlobalBase));
621 }
622
623 uint32_t DataStart = MemoryPtr;
624
Sam Cleggf0d433d2018-02-02 22:59:56 +0000625 // Arbitrarily set __dso_handle handle to point to the start of the data
626 // segments.
627 if (WasmSym::DsoHandle)
Sam Clegga0f095e2018-05-03 17:21:53 +0000628 WasmSym::DsoHandle->setVirtualAddress(DataStart);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000629
Sam Cleggc94d3932017-11-17 18:14:09 +0000630 for (OutputSegment *Seg : Segments) {
631 MemoryPtr = alignTo(MemoryPtr, Seg->Alignment);
632 Seg->StartVA = MemoryPtr;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000633 log(formatv("mem: {0,-15} offset={1,-8} size={2,-8} align={3}", Seg->Name,
634 MemoryPtr, Seg->Size, Seg->Alignment));
Sam Cleggc94d3932017-11-17 18:14:09 +0000635 MemoryPtr += Seg->Size;
636 }
637
Sam Cleggf0d433d2018-02-02 22:59:56 +0000638 // TODO: Add .bss space here.
Sam Clegg37a4a8a2018-02-07 03:04:53 +0000639 if (WasmSym::DataEnd)
640 WasmSym::DataEnd->setVirtualAddress(MemoryPtr);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000641
Sam Clegga0f095e2018-05-03 17:21:53 +0000642 log("mem: static data = " + Twine(MemoryPtr - DataStart));
Sam Cleggc94d3932017-11-17 18:14:09 +0000643
Sam Clegga0f095e2018-05-03 17:21:53 +0000644 if (!Config->StackFirst)
645 PlaceStack();
646
647 // Set `__heap_base` to directly follow the end of the stack or global data.
648 // The fact that this comes last means that a malloc/brk implementation
649 // can grow the heap at runtime.
Sam Cleggc94d3932017-11-17 18:14:09 +0000650 if (!Config->Relocatable) {
Sam Cleggf0d433d2018-02-02 22:59:56 +0000651 WasmSym::HeapBase->setVirtualAddress(MemoryPtr);
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000652 log("mem: heap base = " + Twine(MemoryPtr));
Sam Cleggc94d3932017-11-17 18:14:09 +0000653 }
654
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000655 if (Config->InitialMemory != 0) {
656 if (Config->InitialMemory != alignTo(Config->InitialMemory, WasmPageSize))
657 error("initial memory must be " + Twine(WasmPageSize) + "-byte aligned");
658 if (MemoryPtr > Config->InitialMemory)
659 error("initial memory too small, " + Twine(MemoryPtr) + " bytes needed");
660 else
661 MemoryPtr = Config->InitialMemory;
662 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000663 uint32_t MemSize = alignTo(MemoryPtr, WasmPageSize);
664 NumMemoryPages = MemSize / WasmPageSize;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000665 log("mem: total pages = " + Twine(NumMemoryPages));
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000666
667 if (Config->MaxMemory != 0) {
668 if (Config->MaxMemory != alignTo(Config->MaxMemory, WasmPageSize))
669 error("maximum memory must be " + Twine(WasmPageSize) + "-byte aligned");
670 if (MemoryPtr > Config->MaxMemory)
671 error("maximum memory too small, " + Twine(MemoryPtr) + " bytes needed");
672 MaxMemoryPages = Config->MaxMemory / WasmPageSize;
673 log("mem: max pages = " + Twine(MaxMemoryPages));
674 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000675}
676
677SyntheticSection *Writer::createSyntheticSection(uint32_t Type,
Sam Cleggc375e4e2018-01-10 19:18:22 +0000678 StringRef Name) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000679 auto Sec = make<SyntheticSection>(Type, Name);
Sam Cleggab2ac292017-12-20 05:14:48 +0000680 log("createSection: " + toString(*Sec));
Sam Cleggc94d3932017-11-17 18:14:09 +0000681 OutputSections.push_back(Sec);
682 return Sec;
683}
684
685void Writer::createSections() {
686 // Known sections
687 createTypeSection();
688 createImportSection();
689 createFunctionSection();
690 createTableSection();
691 createMemorySection();
692 createGlobalSection();
693 createExportSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000694 createElemSection();
695 createCodeSection();
696 createDataSection();
Sam Clegg80ba4382018-04-10 16:12:49 +0000697 createCustomSections();
Sam Cleggc94d3932017-11-17 18:14:09 +0000698
699 // Custom sections
Sam Clegg99eb42c2018-02-27 23:58:03 +0000700 if (Config->Relocatable) {
Sam Clegg99eb42c2018-02-27 23:58:03 +0000701 createLinkingSection();
Nicholas Wilson94d3b162018-03-05 12:33:58 +0000702 createRelocSections();
Sam Clegg99eb42c2018-02-27 23:58:03 +0000703 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000704 if (!Config->StripDebug && !Config->StripAll)
705 createNameSection();
706
707 for (OutputSection *S : OutputSections) {
708 S->setOffset(FileSize);
709 S->finalizeContents();
710 FileSize += S->getSize();
711 }
712}
713
Sam Cleggc94d3932017-11-17 18:14:09 +0000714void Writer::calculateImports() {
Sam Clegg574d7ce2017-12-15 19:23:49 +0000715 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000716 if (!Sym->isUndefined())
717 continue;
718 if (isa<DataSymbol>(Sym))
719 continue;
720 if (Sym->isWeak() && !Config->Relocatable)
Sam Clegg574d7ce2017-12-15 19:23:49 +0000721 continue;
Nicholas Wilsona1e299f2018-04-20 17:18:06 +0000722 if (!Sym->isLive())
723 continue;
Sam Cleggc729c1b2018-05-30 18:07:52 +0000724 if (!Sym->IsUsedInRegularObj)
725 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000726
Nicola Zaghene7245b42018-05-15 13:36:20 +0000727 LLVM_DEBUG(dbgs() << "import: " << Sym->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000728 ImportedSymbols.emplace_back(Sym);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000729 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
730 F->setFunctionIndex(NumImportedFunctions++);
Sam Clegg93102972018-02-23 05:08:53 +0000731 else
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000732 cast<GlobalSymbol>(Sym)->setGlobalIndex(NumImportedGlobals++);
Sam Cleggc94d3932017-11-17 18:14:09 +0000733 }
734}
735
Sam Cleggd3052d52018-01-18 23:40:49 +0000736void Writer::calculateExports() {
Sam Clegg93102972018-02-23 05:08:53 +0000737 if (Config->Relocatable)
738 return;
Sam Cleggf0d433d2018-02-02 22:59:56 +0000739
Sam Cleggd6beb322018-05-10 18:10:34 +0000740 if (!Config->Relocatable && !Config->ImportMemory)
741 Exports.push_back(WasmExport{"memory", WASM_EXTERNAL_MEMORY, 0});
742
743 if (!Config->Relocatable && Config->ExportTable)
744 Exports.push_back(WasmExport{kFunctionTableName, WASM_EXTERNAL_TABLE, 0});
745
746 unsigned FakeGlobalIndex = NumImportedGlobals + InputGlobals.size();
747
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000748 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Cleggce004bf2018-06-28 17:04:58 +0000749 if (!Sym->isExported())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000750 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000751 if (!Sym->isLive())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000752 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000753
Sam Cleggd6beb322018-05-10 18:10:34 +0000754 StringRef Name = Sym->getName();
755 WasmExport Export;
756 if (auto *F = dyn_cast<DefinedFunction>(Sym)) {
757 Export = {Name, WASM_EXTERNAL_FUNCTION, F->getFunctionIndex()};
758 } else if (auto *G = dyn_cast<DefinedGlobal>(Sym)) {
Sam Clegg177b4582018-06-07 01:27:07 +0000759 // TODO(sbc): Remove this check once to mutable global proposal is
760 // implement in all major browsers.
761 // See: https://github.com/WebAssembly/mutable-global
762 if (G->getGlobalType()->Mutable) {
763 // Only the __stack_pointer should ever be create as mutable.
764 assert(G == WasmSym::StackPointer);
765 continue;
766 }
Sam Cleggd6beb322018-05-10 18:10:34 +0000767 Export = {Name, WASM_EXTERNAL_GLOBAL, G->getGlobalIndex()};
768 } else {
769 auto *D = cast<DefinedData>(Sym);
Sam Clegg93102972018-02-23 05:08:53 +0000770 DefinedFakeGlobals.emplace_back(D);
Sam Cleggd6beb322018-05-10 18:10:34 +0000771 Export = {Name, WASM_EXTERNAL_GLOBAL, FakeGlobalIndex++};
772 }
773
Nicola Zaghene7245b42018-05-15 13:36:20 +0000774 LLVM_DEBUG(dbgs() << "Export: " << Name << "\n");
Sam Cleggd6beb322018-05-10 18:10:34 +0000775 Exports.push_back(Export);
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000776 }
Sam Clegg93102972018-02-23 05:08:53 +0000777}
778
779void Writer::assignSymtab() {
780 if (!Config->Relocatable)
781 return;
782
Sam Cleggd177ab22018-05-04 23:14:42 +0000783 StringMap<uint32_t> SectionSymbolIndices;
784
Sam Clegg93102972018-02-23 05:08:53 +0000785 unsigned SymbolIndex = SymtabEntries.size();
Sam Cleggd3052d52018-01-18 23:40:49 +0000786 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000787 LLVM_DEBUG(dbgs() << "Symtab entries: " << File->getName() << "\n");
Sam Cleggd3052d52018-01-18 23:40:49 +0000788 for (Symbol *Sym : File->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000789 if (Sym->getFile() != File)
Sam Cleggd3052d52018-01-18 23:40:49 +0000790 continue;
Sam Cleggd177ab22018-05-04 23:14:42 +0000791
792 if (auto *S = dyn_cast<SectionSymbol>(Sym)) {
793 StringRef Name = S->getName();
794 if (CustomSectionMapping.count(Name) == 0)
795 continue;
796
797 auto SSI = SectionSymbolIndices.find(Name);
798 if (SSI != SectionSymbolIndices.end()) {
799 Sym->setOutputSymbolIndex(SSI->second);
800 continue;
801 }
802
803 SectionSymbolIndices[Name] = SymbolIndex;
804 CustomSectionSymbols[Name] = cast<SectionSymbol>(Sym);
805
806 Sym->markLive();
807 }
808
Nicholas Wilson06e0d172018-03-07 11:15:47 +0000809 // (Since this is relocatable output, GC is not performed so symbols must
810 // be live.)
811 assert(Sym->isLive());
Sam Clegg93102972018-02-23 05:08:53 +0000812 Sym->setOutputSymbolIndex(SymbolIndex++);
813 SymtabEntries.emplace_back(Sym);
Sam Cleggd3052d52018-01-18 23:40:49 +0000814 }
815 }
816
Sam Clegg93102972018-02-23 05:08:53 +0000817 // For the moment, relocatable output doesn't contain any synthetic functions,
818 // so no need to look through the Symtab for symbols not referenced by
819 // Symtab->ObjectFiles.
Sam Cleggd3052d52018-01-18 23:40:49 +0000820}
821
Sam Cleggc375e4e2018-01-10 19:18:22 +0000822uint32_t Writer::lookupType(const WasmSignature &Sig) {
Sam Clegg8d027d62018-01-10 20:12:26 +0000823 auto It = TypeIndices.find(Sig);
824 if (It == TypeIndices.end()) {
Sam Cleggc375e4e2018-01-10 19:18:22 +0000825 error("type not found: " + toString(Sig));
Sam Clegg8d027d62018-01-10 20:12:26 +0000826 return 0;
827 }
828 return It->second;
Sam Cleggc375e4e2018-01-10 19:18:22 +0000829}
830
831uint32_t Writer::registerType(const WasmSignature &Sig) {
Sam Cleggb8621592017-11-30 01:40:08 +0000832 auto Pair = TypeIndices.insert(std::make_pair(Sig, Types.size()));
Sam Cleggc375e4e2018-01-10 19:18:22 +0000833 if (Pair.second) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000834 LLVM_DEBUG(dbgs() << "type " << toString(Sig) << "\n");
Sam Cleggb8621592017-11-30 01:40:08 +0000835 Types.push_back(&Sig);
Sam Cleggc375e4e2018-01-10 19:18:22 +0000836 }
Sam Cleggb8621592017-11-30 01:40:08 +0000837 return Pair.first->second;
838}
839
Sam Cleggc94d3932017-11-17 18:14:09 +0000840void Writer::calculateTypes() {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000841 // The output type section is the union of the following sets:
842 // 1. Any signature used in the TYPE relocation
843 // 2. The signatures of all imported functions
844 // 3. The signatures of all defined functions
845
Sam Cleggc94d3932017-11-17 18:14:09 +0000846 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000847 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
848 for (uint32_t I = 0; I < Types.size(); I++)
849 if (File->TypeIsUsed[I])
850 File->TypeMap[I] = registerType(Types[I]);
Sam Cleggc94d3932017-11-17 18:14:09 +0000851 }
Sam Clegg50686852018-01-12 18:35:13 +0000852
Sam Clegg93102972018-02-23 05:08:53 +0000853 for (const Symbol *Sym : ImportedSymbols)
854 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
Sam Cleggcefbf9a2018-06-28 16:53:53 +0000855 registerType(*F->FunctionType);
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000856
Sam Clegg9f934222018-02-21 18:29:23 +0000857 for (const InputFunction *F : InputFunctions)
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000858 registerType(F->Signature);
Sam Cleggc94d3932017-11-17 18:14:09 +0000859}
860
Sam Clegg8d146bb2018-01-09 23:56:44 +0000861void Writer::assignIndexes() {
Sam Clegg93102972018-02-23 05:08:53 +0000862 uint32_t FunctionIndex = NumImportedFunctions + InputFunctions.size();
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000863 auto AddDefinedFunction = [&](InputFunction *Func) {
864 if (!Func->Live)
865 return;
866 InputFunctions.emplace_back(Func);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000867 Func->setFunctionIndex(FunctionIndex++);
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000868 };
869
Nicholas Wilson5639da82018-03-12 15:44:07 +0000870 for (InputFunction *Func : Symtab->SyntheticFunctions)
871 AddDefinedFunction(Func);
872
Sam Clegg87e61922018-01-08 23:39:11 +0000873 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000874 LLVM_DEBUG(dbgs() << "Functions: " << File->getName() << "\n");
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000875 for (InputFunction *Func : File->Functions)
876 AddDefinedFunction(Func);
Sam Clegg8d146bb2018-01-09 23:56:44 +0000877 }
878
Sam Clegg93102972018-02-23 05:08:53 +0000879 uint32_t TableIndex = kInitialTableOffset;
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000880 auto HandleRelocs = [&](InputChunk *Chunk) {
881 if (!Chunk->Live)
882 return;
883 ObjFile *File = Chunk->File;
884 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
Sam Clegg93102972018-02-23 05:08:53 +0000885 for (const WasmRelocation &Reloc : Chunk->getRelocations()) {
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000886 if (Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_I32 ||
887 Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_SLEB) {
888 FunctionSymbol *Sym = File->getFunctionSymbol(Reloc.Index);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000889 if (Sym->hasTableIndex() || !Sym->hasFunctionIndex())
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000890 continue;
891 Sym->setTableIndex(TableIndex++);
892 IndirectFunctions.emplace_back(Sym);
893 } else if (Reloc.Type == R_WEBASSEMBLY_TYPE_INDEX_LEB) {
Sam Clegg93102972018-02-23 05:08:53 +0000894 // Mark target type as live
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000895 File->TypeMap[Reloc.Index] = registerType(Types[Reloc.Index]);
896 File->TypeIsUsed[Reloc.Index] = true;
897 }
898 }
899 };
900
Sam Clegg8d146bb2018-01-09 23:56:44 +0000901 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000902 LLVM_DEBUG(dbgs() << "Handle relocs: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000903 for (InputChunk *Chunk : File->Functions)
904 HandleRelocs(Chunk);
905 for (InputChunk *Chunk : File->Segments)
906 HandleRelocs(Chunk);
Sam Cleggd177ab22018-05-04 23:14:42 +0000907 for (auto &P : File->CustomSections)
908 HandleRelocs(P);
Sam Clegg93102972018-02-23 05:08:53 +0000909 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000910
Sam Clegg93102972018-02-23 05:08:53 +0000911 uint32_t GlobalIndex = NumImportedGlobals + InputGlobals.size();
912 auto AddDefinedGlobal = [&](InputGlobal *Global) {
913 if (Global->Live) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000914 LLVM_DEBUG(dbgs() << "AddDefinedGlobal: " << GlobalIndex << "\n");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000915 Global->setGlobalIndex(GlobalIndex++);
Sam Clegg93102972018-02-23 05:08:53 +0000916 InputGlobals.push_back(Global);
917 }
918 };
919
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000920 for (InputGlobal *Global : Symtab->SyntheticGlobals)
921 AddDefinedGlobal(Global);
Sam Clegg93102972018-02-23 05:08:53 +0000922
923 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000924 LLVM_DEBUG(dbgs() << "Globals: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000925 for (InputGlobal *Global : File->Globals)
926 AddDefinedGlobal(Global);
Sam Cleggc94d3932017-11-17 18:14:09 +0000927 }
928}
929
930static StringRef getOutputDataSegmentName(StringRef Name) {
Sam Clegg66844762018-05-10 18:23:51 +0000931 if (!Config->MergeDataSegments)
Sam Cleggc94d3932017-11-17 18:14:09 +0000932 return Name;
Rui Ueyama4764b572018-02-28 00:57:28 +0000933 if (Name.startswith(".text."))
934 return ".text";
935 if (Name.startswith(".data."))
936 return ".data";
937 if (Name.startswith(".bss."))
938 return ".bss";
Sam Clegg57694c52018-08-08 18:02:55 +0000939 if (Name.startswith(".rodata."))
940 return ".rodata";
Sam Cleggc94d3932017-11-17 18:14:09 +0000941 return Name;
942}
943
944void Writer::createOutputSegments() {
945 for (ObjFile *File : Symtab->ObjectFiles) {
946 for (InputSegment *Segment : File->Segments) {
Sam Clegg447ae402018-02-13 20:29:38 +0000947 if (!Segment->Live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000948 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000949 StringRef Name = getOutputDataSegmentName(Segment->getName());
950 OutputSegment *&S = SegmentMap[Name];
951 if (S == nullptr) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000952 LLVM_DEBUG(dbgs() << "new segment: " << Name << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000953 S = make<OutputSegment>(Name, Segments.size());
Sam Cleggc94d3932017-11-17 18:14:09 +0000954 Segments.push_back(S);
955 }
956 S->addInputSegment(Segment);
Nicola Zaghene7245b42018-05-15 13:36:20 +0000957 LLVM_DEBUG(dbgs() << "added data: " << Name << ": " << S->Size << "\n");
Sam Cleggc94d3932017-11-17 18:14:09 +0000958 }
959 }
960}
961
Sam Clegg50686852018-01-12 18:35:13 +0000962static const int OPCODE_CALL = 0x10;
963static const int OPCODE_END = 0xb;
964
965// Create synthetic "__wasm_call_ctors" function based on ctor functions
966// in input object.
967void Writer::createCtorFunction() {
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000968 // First write the body's contents to a string.
969 std::string BodyContent;
Sam Clegg50686852018-01-12 18:35:13 +0000970 {
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000971 raw_string_ostream OS(BodyContent);
Sam Clegg50686852018-01-12 18:35:13 +0000972 writeUleb128(OS, 0, "num locals");
Sam Clegg93102972018-02-23 05:08:53 +0000973 for (const WasmInitEntry &F : InitFunctions) {
Sam Clegg50686852018-01-12 18:35:13 +0000974 writeU8(OS, OPCODE_CALL, "CALL");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000975 writeUleb128(OS, F.Sym->getFunctionIndex(), "function index");
Sam Clegg50686852018-01-12 18:35:13 +0000976 }
977 writeU8(OS, OPCODE_END, "END");
978 }
979
980 // Once we know the size of the body we can create the final function body
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000981 std::string FunctionBody;
982 {
983 raw_string_ostream OS(FunctionBody);
984 writeUleb128(OS, BodyContent.size(), "function size");
985 OS << BodyContent;
986 }
Rui Ueyama29abfe42018-02-28 17:43:15 +0000987
Sam Cleggea656472018-10-22 08:35:39 +0000988 ArrayRef<uint8_t> Body = arrayRefFromStringRef(Saver.save(FunctionBody));
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000989 cast<SyntheticFunction>(WasmSym::CallCtors->Function)->setBody(Body);
Sam Clegg50686852018-01-12 18:35:13 +0000990}
991
992// Populate InitFunctions vector with init functions from all input objects.
993// This is then used either when creating the output linking section or to
994// synthesize the "__wasm_call_ctors" function.
995void Writer::calculateInitFunctions() {
996 for (ObjFile *File : Symtab->ObjectFiles) {
997 const WasmLinkingData &L = File->getWasmObj()->linkingData();
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +0000998 for (const WasmInitFunc &F : L.InitFunctions) {
999 FunctionSymbol *Sym = File->getFunctionSymbol(F.Symbol);
Derek Schuff371842b2018-10-03 22:25:32 +00001000 if (*Sym->FunctionType != WasmSignature{{}, {}})
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +00001001 error("invalid signature for init func: " + toString(*Sym));
1002 InitFunctions.emplace_back(WasmInitEntry{Sym, F.Priority});
1003 }
Sam Clegg50686852018-01-12 18:35:13 +00001004 }
Rui Ueyamada69b712018-02-28 00:15:59 +00001005
Sam Clegg50686852018-01-12 18:35:13 +00001006 // Sort in order of priority (lowest first) so that they are called
1007 // in the correct order.
Sam Clegg29b8feb2018-02-21 00:34:34 +00001008 std::stable_sort(InitFunctions.begin(), InitFunctions.end(),
Sam Clegg93102972018-02-23 05:08:53 +00001009 [](const WasmInitEntry &L, const WasmInitEntry &R) {
Sam Clegg29b8feb2018-02-21 00:34:34 +00001010 return L.Priority < R.Priority;
1011 });
Sam Clegg50686852018-01-12 18:35:13 +00001012}
1013
Sam Cleggc94d3932017-11-17 18:14:09 +00001014void Writer::run() {
Sam Clegg99eb42c2018-02-27 23:58:03 +00001015 if (Config->Relocatable)
1016 Config->GlobalBase = 0;
1017
Sam Cleggc94d3932017-11-17 18:14:09 +00001018 log("-- calculateImports");
1019 calculateImports();
Sam Clegg8d146bb2018-01-09 23:56:44 +00001020 log("-- assignIndexes");
1021 assignIndexes();
Sam Clegg50686852018-01-12 18:35:13 +00001022 log("-- calculateInitFunctions");
1023 calculateInitFunctions();
1024 if (!Config->Relocatable)
1025 createCtorFunction();
Sam Clegg8f6d2de2018-01-31 23:48:14 +00001026 log("-- calculateTypes");
1027 calculateTypes();
Sam Clegg93102972018-02-23 05:08:53 +00001028 log("-- layoutMemory");
1029 layoutMemory();
1030 log("-- calculateExports");
1031 calculateExports();
Sam Cleggd177ab22018-05-04 23:14:42 +00001032 log("-- calculateCustomSections");
1033 calculateCustomSections();
Sam Clegg93102972018-02-23 05:08:53 +00001034 log("-- assignSymtab");
1035 assignSymtab();
Sam Cleggc94d3932017-11-17 18:14:09 +00001036
1037 if (errorHandler().Verbose) {
Sam Clegg9f934222018-02-21 18:29:23 +00001038 log("Defined Functions: " + Twine(InputFunctions.size()));
Sam Clegg93102972018-02-23 05:08:53 +00001039 log("Defined Globals : " + Twine(InputGlobals.size()));
1040 log("Function Imports : " + Twine(NumImportedFunctions));
1041 log("Global Imports : " + Twine(NumImportedGlobals));
Sam Cleggc94d3932017-11-17 18:14:09 +00001042 for (ObjFile *File : Symtab->ObjectFiles)
1043 File->dumpInfo();
1044 }
1045
Sam Cleggc94d3932017-11-17 18:14:09 +00001046 createHeader();
1047 log("-- createSections");
1048 createSections();
1049
1050 log("-- openFile");
1051 openFile();
1052 if (errorCount())
1053 return;
1054
1055 writeHeader();
1056
1057 log("-- writeSections");
1058 writeSections();
1059 if (errorCount())
1060 return;
1061
1062 if (Error E = Buffer->commit())
1063 fatal("failed to write the output file: " + toString(std::move(E)));
1064}
1065
1066// Open a result file.
1067void Writer::openFile() {
1068 log("writing: " + Config->OutputFile);
Sam Cleggc94d3932017-11-17 18:14:09 +00001069
1070 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
1071 FileOutputBuffer::create(Config->OutputFile, FileSize,
1072 FileOutputBuffer::F_executable);
1073
1074 if (!BufferOrErr)
1075 error("failed to open " + Config->OutputFile + ": " +
1076 toString(BufferOrErr.takeError()));
1077 else
1078 Buffer = std::move(*BufferOrErr);
1079}
1080
1081void Writer::createHeader() {
1082 raw_string_ostream OS(Header);
1083 writeBytes(OS, WasmMagic, sizeof(WasmMagic), "wasm magic");
1084 writeU32(OS, WasmVersion, "wasm version");
1085 OS.flush();
1086 FileSize += Header.size();
1087}
1088
1089void lld::wasm::writeResult() { Writer().run(); }