blob: 53b9ff5b4ba4f2185c8dc79c321c8f164e6de0b2 [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 Schuff3bea8bc2018-11-06 17:59:32 +0000158 if (Config->SharedMemory) {
159 Import.Memory.Flags |= WASM_LIMITS_FLAG_IS_SHARED;
160 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000161 writeImport(OS, Import);
162 }
163
Nicholas Wilsonfc90b302018-03-28 12:53:29 +0000164 if (Config->ImportTable) {
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000165 uint32_t TableSize = kInitialTableOffset + IndirectFunctions.size();
166 WasmImport Import;
167 Import.Module = "env";
168 Import.Field = kFunctionTableName;
169 Import.Kind = WASM_EXTERNAL_TABLE;
170 Import.Table.ElemType = WASM_TYPE_ANYFUNC;
171 Import.Table.Limits = {WASM_LIMITS_FLAG_HAS_MAX, TableSize, TableSize};
172 writeImport(OS, Import);
173 }
174
Sam Clegg93102972018-02-23 05:08:53 +0000175 for (const Symbol *Sym : ImportedSymbols) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000176 WasmImport Import;
177 Import.Module = "env";
178 Import.Field = Sym->getName();
Sam Clegg93102972018-02-23 05:08:53 +0000179 if (auto *FunctionSym = dyn_cast<FunctionSymbol>(Sym)) {
180 Import.Kind = WASM_EXTERNAL_FUNCTION;
Sam Cleggcefbf9a2018-06-28 16:53:53 +0000181 Import.SigIndex = lookupType(*FunctionSym->FunctionType);
Sam Clegg93102972018-02-23 05:08:53 +0000182 } else {
183 auto *GlobalSym = cast<GlobalSymbol>(Sym);
184 Import.Kind = WASM_EXTERNAL_GLOBAL;
185 Import.Global = *GlobalSym->getGlobalType();
186 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000187 writeImport(OS, Import);
188 }
189}
190
191void Writer::createTypeSection() {
192 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TYPE);
193 raw_ostream &OS = Section->getStream();
194 writeUleb128(OS, Types.size(), "type count");
Sam Cleggd451da12017-12-19 19:56:27 +0000195 for (const WasmSignature *Sig : Types)
Sam Cleggc94d3932017-11-17 18:14:09 +0000196 writeSig(OS, *Sig);
Sam Cleggc94d3932017-11-17 18:14:09 +0000197}
198
199void Writer::createFunctionSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000200 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000201 return;
202
203 SyntheticSection *Section = createSyntheticSection(WASM_SEC_FUNCTION);
204 raw_ostream &OS = Section->getStream();
205
Sam Clegg9f934222018-02-21 18:29:23 +0000206 writeUleb128(OS, InputFunctions.size(), "function count");
207 for (const InputFunction *Func : InputFunctions)
Sam Cleggc375e4e2018-01-10 19:18:22 +0000208 writeUleb128(OS, lookupType(Func->Signature), "sig index");
Sam Cleggc94d3932017-11-17 18:14:09 +0000209}
210
211void Writer::createMemorySection() {
212 if (Config->ImportMemory)
213 return;
214
215 SyntheticSection *Section = createSyntheticSection(WASM_SEC_MEMORY);
216 raw_ostream &OS = Section->getStream();
217
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000218 bool HasMax = MaxMemoryPages != 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000219 writeUleb128(OS, 1, "memory count");
Derek Schuff3bea8bc2018-11-06 17:59:32 +0000220 unsigned Flags = HasMax ? static_cast<unsigned>(WASM_LIMITS_FLAG_HAS_MAX) : 0;
221 if (Config->SharedMemory)
222 Flags |= WASM_LIMITS_FLAG_IS_SHARED;
223 writeUleb128(OS, Flags, "memory limits flags");
Sam Cleggc94d3932017-11-17 18:14:09 +0000224 writeUleb128(OS, NumMemoryPages, "initial pages");
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000225 if (HasMax)
226 writeUleb128(OS, MaxMemoryPages, "max pages");
Sam Cleggc94d3932017-11-17 18:14:09 +0000227}
228
229void Writer::createGlobalSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000230 unsigned NumGlobals = InputGlobals.size() + DefinedFakeGlobals.size();
231 if (NumGlobals == 0)
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000232 return;
233
Sam Cleggc94d3932017-11-17 18:14:09 +0000234 SyntheticSection *Section = createSyntheticSection(WASM_SEC_GLOBAL);
235 raw_ostream &OS = Section->getStream();
236
Sam Clegg93102972018-02-23 05:08:53 +0000237 writeUleb128(OS, NumGlobals, "global count");
238 for (const InputGlobal *G : InputGlobals)
239 writeGlobal(OS, G->Global);
240 for (const DefinedData *Sym : DefinedFakeGlobals) {
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000241 WasmGlobal Global;
Sam Clegg93102972018-02-23 05:08:53 +0000242 Global.Type = {WASM_TYPE_I32, false};
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000243 Global.InitExpr.Opcode = WASM_OPCODE_I32_CONST;
244 Global.InitExpr.Value.Int32 = Sym->getVirtualAddress();
Sam Cleggc94d3932017-11-17 18:14:09 +0000245 writeGlobal(OS, Global);
246 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000247}
248
249void Writer::createTableSection() {
Nicholas Wilsonfc90b302018-03-28 12:53:29 +0000250 if (Config->ImportTable)
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000251 return;
252
253 // Always output a table section (or table import), even if there are no
254 // indirect calls. There are two reasons for this:
Sam Cleggfc1a9122017-12-11 22:00:56 +0000255 // 1. For executables it is useful to have an empty table slot at 0
256 // which can be filled with a null function call handler.
257 // 2. If we don't do this, any program that contains a call_indirect but
258 // no address-taken function will fail at validation time since it is
259 // a validation error to include a call_indirect instruction if there
260 // is not table.
Sam Clegg48bbd632018-01-24 21:37:30 +0000261 uint32_t TableSize = kInitialTableOffset + IndirectFunctions.size();
Sam Cleggfc1a9122017-12-11 22:00:56 +0000262
Sam Cleggc94d3932017-11-17 18:14:09 +0000263 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TABLE);
264 raw_ostream &OS = Section->getStream();
265
266 writeUleb128(OS, 1, "table count");
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000267 WasmLimits Limits = {WASM_LIMITS_FLAG_HAS_MAX, TableSize, TableSize};
268 writeTableType(OS, WasmTable{WASM_TYPE_ANYFUNC, Limits});
Sam Cleggc94d3932017-11-17 18:14:09 +0000269}
270
271void Writer::createExportSection() {
Sam Cleggd6beb322018-05-10 18:10:34 +0000272 if (!Exports.size())
Sam Cleggc94d3932017-11-17 18:14:09 +0000273 return;
274
275 SyntheticSection *Section = createSyntheticSection(WASM_SEC_EXPORT);
276 raw_ostream &OS = Section->getStream();
277
Sam Cleggd6beb322018-05-10 18:10:34 +0000278 writeUleb128(OS, Exports.size(), "export count");
279 for (const WasmExport &Export : Exports)
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000280 writeExport(OS, Export);
Sam Cleggc94d3932017-11-17 18:14:09 +0000281}
282
Sam Cleggd177ab22018-05-04 23:14:42 +0000283void Writer::calculateCustomSections() {
284 log("calculateCustomSections");
285 bool StripDebug = Config->StripDebug || Config->StripAll;
286 for (ObjFile *File : Symtab->ObjectFiles) {
287 for (InputSection *Section : File->CustomSections) {
288 StringRef Name = Section->getName();
289 // These custom sections are known the linker and synthesized rather than
290 // blindly copied
291 if (Name == "linking" || Name == "name" || Name.startswith("reloc."))
292 continue;
293 // .. or it is a debug section
294 if (StripDebug && Name.startswith(".debug_"))
295 continue;
296 CustomSectionMapping[Name].push_back(Section);
297 }
298 }
299}
300
Sam Clegg80ba4382018-04-10 16:12:49 +0000301void Writer::createCustomSections() {
302 log("createCustomSections");
Sam Clegg80ba4382018-04-10 16:12:49 +0000303 for (auto &Pair : CustomSectionMapping) {
304 StringRef Name = Pair.first();
Sam Cleggd177ab22018-05-04 23:14:42 +0000305
306 auto P = CustomSectionSymbols.find(Name);
307 if (P != CustomSectionSymbols.end()) {
308 uint32_t SectionIndex = OutputSections.size();
309 P->second->setOutputSectionIndex(SectionIndex);
310 }
311
Nicola Zaghene7245b42018-05-15 13:36:20 +0000312 LLVM_DEBUG(dbgs() << "createCustomSection: " << Name << "\n");
Sam Clegg80ba4382018-04-10 16:12:49 +0000313 OutputSections.push_back(make<CustomSection>(Name, Pair.second));
314 }
315}
316
Sam Cleggc94d3932017-11-17 18:14:09 +0000317void Writer::createElemSection() {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000318 if (IndirectFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000319 return;
320
321 SyntheticSection *Section = createSyntheticSection(WASM_SEC_ELEM);
322 raw_ostream &OS = Section->getStream();
323
324 writeUleb128(OS, 1, "segment count");
325 writeUleb128(OS, 0, "table index");
326 WasmInitExpr InitExpr;
327 InitExpr.Opcode = WASM_OPCODE_I32_CONST;
Sam Clegg48bbd632018-01-24 21:37:30 +0000328 InitExpr.Value.Int32 = kInitialTableOffset;
Sam Cleggc94d3932017-11-17 18:14:09 +0000329 writeInitExpr(OS, InitExpr);
Sam Cleggfc1a9122017-12-11 22:00:56 +0000330 writeUleb128(OS, IndirectFunctions.size(), "elem count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000331
Sam Clegg48bbd632018-01-24 21:37:30 +0000332 uint32_t TableIndex = kInitialTableOffset;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000333 for (const FunctionSymbol *Sym : IndirectFunctions) {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000334 assert(Sym->getTableIndex() == TableIndex);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000335 writeUleb128(OS, Sym->getFunctionIndex(), "function index");
Sam Cleggfc1a9122017-12-11 22:00:56 +0000336 ++TableIndex;
337 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000338}
339
340void Writer::createCodeSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000341 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000342 return;
343
344 log("createCodeSection");
345
Sam Clegg9f934222018-02-21 18:29:23 +0000346 auto Section = make<CodeSection>(InputFunctions);
Sam Cleggc94d3932017-11-17 18:14:09 +0000347 OutputSections.push_back(Section);
348}
349
350void Writer::createDataSection() {
351 if (!Segments.size())
352 return;
353
354 log("createDataSection");
355 auto Section = make<DataSection>(Segments);
356 OutputSections.push_back(Section);
357}
358
Sam Cleggd451da12017-12-19 19:56:27 +0000359// Create relocations sections in the final output.
Sam Cleggc94d3932017-11-17 18:14:09 +0000360// These are only created when relocatable output is requested.
361void Writer::createRelocSections() {
362 log("createRelocSections");
363 // Don't use iterator here since we are adding to OutputSection
364 size_t OrigSize = OutputSections.size();
Rui Ueyamaffa650a2018-04-24 23:09:57 +0000365 for (size_t I = 0; I < OrigSize; I++) {
366 OutputSection *OSec = OutputSections[I];
Rui Ueyama37254062018-02-28 00:01:31 +0000367 uint32_t Count = OSec->numRelocations();
Sam Cleggc94d3932017-11-17 18:14:09 +0000368 if (!Count)
369 continue;
370
Rui Ueyama37254062018-02-28 00:01:31 +0000371 StringRef Name;
372 if (OSec->Type == WASM_SEC_DATA)
373 Name = "reloc.DATA";
374 else if (OSec->Type == WASM_SEC_CODE)
375 Name = "reloc.CODE";
Sam Cleggd177ab22018-05-04 23:14:42 +0000376 else if (OSec->Type == WASM_SEC_CUSTOM)
377 Name = Saver.save("reloc." + OSec->Name);
Sam Cleggc94d3932017-11-17 18:14:09 +0000378 else
Sam Cleggd177ab22018-05-04 23:14:42 +0000379 llvm_unreachable(
380 "relocations only supported for code, data, or custom sections");
Sam Cleggc94d3932017-11-17 18:14:09 +0000381
Rui Ueyama37254062018-02-28 00:01:31 +0000382 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, Name);
Sam Cleggc94d3932017-11-17 18:14:09 +0000383 raw_ostream &OS = Section->getStream();
Rui Ueyamaffa650a2018-04-24 23:09:57 +0000384 writeUleb128(OS, I, "reloc section");
Sam Cleggc94d3932017-11-17 18:14:09 +0000385 writeUleb128(OS, Count, "reloc count");
Rui Ueyama37254062018-02-28 00:01:31 +0000386 OSec->writeRelocations(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000387 }
388}
389
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000390static uint32_t getWasmFlags(const Symbol *Sym) {
391 uint32_t Flags = 0;
392 if (Sym->isLocal())
393 Flags |= WASM_SYMBOL_BINDING_LOCAL;
394 if (Sym->isWeak())
395 Flags |= WASM_SYMBOL_BINDING_WEAK;
396 if (Sym->isHidden())
397 Flags |= WASM_SYMBOL_VISIBILITY_HIDDEN;
398 if (Sym->isUndefined())
399 Flags |= WASM_SYMBOL_UNDEFINED;
400 return Flags;
401}
402
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000403// Some synthetic sections (e.g. "name" and "linking") have subsections.
404// Just like the synthetic sections themselves these need to be created before
405// they can be written out (since they are preceded by their length). This
406// class is used to create subsections and then write them into the stream
407// of the parent section.
408class SubSection {
409public:
410 explicit SubSection(uint32_t Type) : Type(Type) {}
411
412 void writeTo(raw_ostream &To) {
413 OS.flush();
Rui Ueyama67769102018-02-28 03:38:14 +0000414 writeUleb128(To, Type, "subsection type");
415 writeUleb128(To, Body.size(), "subsection size");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000416 To.write(Body.data(), Body.size());
417 }
418
419private:
420 uint32_t Type;
421 std::string Body;
422
423public:
424 raw_string_ostream OS{Body};
425};
426
Sam Clegg49ed9262017-12-01 00:53:21 +0000427// Create the custom "linking" section containing linker metadata.
Sam Cleggc94d3932017-11-17 18:14:09 +0000428// This is only created when relocatable output is requested.
429void Writer::createLinkingSection() {
430 SyntheticSection *Section =
431 createSyntheticSection(WASM_SEC_CUSTOM, "linking");
432 raw_ostream &OS = Section->getStream();
433
Sam Clegg2b8b1792018-04-26 18:17:21 +0000434 writeUleb128(OS, WasmMetadataVersion, "Version");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000435
Sam Clegg93102972018-02-23 05:08:53 +0000436 if (!SymtabEntries.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000437 SubSection Sub(WASM_SYMBOL_TABLE);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000438 writeUleb128(Sub.OS, SymtabEntries.size(), "num symbols");
439
Sam Clegg93102972018-02-23 05:08:53 +0000440 for (const Symbol *Sym : SymtabEntries) {
441 assert(Sym->isDefined() || Sym->isUndefined());
442 WasmSymbolType Kind = Sym->getWasmType();
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000443 uint32_t Flags = getWasmFlags(Sym);
444
Sam Clegg8518e7d2018-03-01 18:06:39 +0000445 writeU8(Sub.OS, Kind, "sym kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000446 writeUleb128(Sub.OS, Flags, "sym flags");
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000447
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000448 if (auto *F = dyn_cast<FunctionSymbol>(Sym)) {
449 writeUleb128(Sub.OS, F->getFunctionIndex(), "index");
Sam Clegg93102972018-02-23 05:08:53 +0000450 if (Sym->isDefined())
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000451 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000452 } else if (auto *G = dyn_cast<GlobalSymbol>(Sym)) {
453 writeUleb128(Sub.OS, G->getGlobalIndex(), "index");
454 if (Sym->isDefined())
455 writeStr(Sub.OS, Sym->getName(), "sym name");
Andrea Di Biagio25c1a2f2018-05-05 10:53:31 +0000456 } else if (isa<DataSymbol>(Sym)) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000457 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegg93102972018-02-23 05:08:53 +0000458 if (auto *DataSym = dyn_cast<DefinedData>(Sym)) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000459 writeUleb128(Sub.OS, DataSym->getOutputSegmentIndex(), "index");
460 writeUleb128(Sub.OS, DataSym->getOutputSegmentOffset(),
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000461 "data offset");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000462 writeUleb128(Sub.OS, DataSym->getSize(), "data size");
Sam Clegg93102972018-02-23 05:08:53 +0000463 }
Sam Cleggd177ab22018-05-04 23:14:42 +0000464 } else {
465 auto *S = cast<SectionSymbol>(Sym);
466 writeUleb128(Sub.OS, S->getOutputSectionIndex(), "sym section index");
Sam Clegg93102972018-02-23 05:08:53 +0000467 }
Sam Cleggd3052d52018-01-18 23:40:49 +0000468 }
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000469
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000470 Sub.writeTo(OS);
Sam Cleggd3052d52018-01-18 23:40:49 +0000471 }
472
Sam Clegg0d0dd392017-12-19 17:09:45 +0000473 if (Segments.size()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000474 SubSection Sub(WASM_SEGMENT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000475 writeUleb128(Sub.OS, Segments.size(), "num data segments");
Sam Cleggc94d3932017-11-17 18:14:09 +0000476 for (const OutputSegment *S : Segments) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000477 writeStr(Sub.OS, S->Name, "segment name");
478 writeUleb128(Sub.OS, S->Alignment, "alignment");
479 writeUleb128(Sub.OS, 0, "flags");
Sam Cleggc94d3932017-11-17 18:14:09 +0000480 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000481 Sub.writeTo(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000482 }
Sam Clegg0d0dd392017-12-19 17:09:45 +0000483
Sam Clegg0d0dd392017-12-19 17:09:45 +0000484 if (!InitFunctions.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000485 SubSection Sub(WASM_INIT_FUNCS);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000486 writeUleb128(Sub.OS, InitFunctions.size(), "num init functions");
Sam Clegg93102972018-02-23 05:08:53 +0000487 for (const WasmInitEntry &F : InitFunctions) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000488 writeUleb128(Sub.OS, F.Priority, "priority");
489 writeUleb128(Sub.OS, F.Sym->getOutputSymbolIndex(), "function index");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000490 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000491 Sub.writeTo(OS);
Sam Clegg0d0dd392017-12-19 17:09:45 +0000492 }
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000493
Nicholas Wilsondbd90bf2018-03-07 13:28:16 +0000494 struct ComdatEntry {
495 unsigned Kind;
496 uint32_t Index;
497 };
498 std::map<StringRef, std::vector<ComdatEntry>> Comdats;
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000499
Sam Clegg9f934222018-02-21 18:29:23 +0000500 for (const InputFunction *F : InputFunctions) {
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000501 StringRef Comdat = F->getComdatName();
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000502 if (!Comdat.empty())
503 Comdats[Comdat].emplace_back(
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000504 ComdatEntry{WASM_COMDAT_FUNCTION, F->getFunctionIndex()});
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000505 }
506 for (uint32_t I = 0; I < Segments.size(); ++I) {
Sam Cleggf98bccf2018-01-13 15:57:48 +0000507 const auto &InputSegments = Segments[I]->InputSegments;
508 if (InputSegments.empty())
509 continue;
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000510 StringRef Comdat = InputSegments[0]->getComdatName();
Sam Clegga697df522018-01-13 15:59:53 +0000511#ifndef NDEBUG
Sam Cleggf98bccf2018-01-13 15:57:48 +0000512 for (const InputSegment *IS : InputSegments)
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000513 assert(IS->getComdatName() == Comdat);
Sam Clegga697df522018-01-13 15:59:53 +0000514#endif
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000515 if (!Comdat.empty())
516 Comdats[Comdat].emplace_back(ComdatEntry{WASM_COMDAT_DATA, I});
517 }
518
519 if (!Comdats.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000520 SubSection Sub(WASM_COMDAT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000521 writeUleb128(Sub.OS, Comdats.size(), "num comdats");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000522 for (const auto &C : Comdats) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000523 writeStr(Sub.OS, C.first, "comdat name");
524 writeUleb128(Sub.OS, 0, "comdat flags"); // flags for future use
525 writeUleb128(Sub.OS, C.second.size(), "num entries");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000526 for (const ComdatEntry &Entry : C.second) {
Sam Clegg8518e7d2018-03-01 18:06:39 +0000527 writeU8(Sub.OS, Entry.Kind, "entry kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000528 writeUleb128(Sub.OS, Entry.Index, "entry index");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000529 }
530 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000531 Sub.writeTo(OS);
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000532 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000533}
534
535// Create the custom "name" section containing debug symbol names.
536void Writer::createNameSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000537 unsigned NumNames = NumImportedFunctions;
Sam Clegg9f934222018-02-21 18:29:23 +0000538 for (const InputFunction *F : InputFunctions)
Nicholas Wilson6c7fe302018-04-20 17:09:18 +0000539 if (!F->getName().empty() || !F->getDebugName().empty())
Sam Clegg1963d712018-01-17 20:19:04 +0000540 ++NumNames;
Sam Cleggc94d3932017-11-17 18:14:09 +0000541
Sam Clegg1963d712018-01-17 20:19:04 +0000542 if (NumNames == 0)
543 return;
Sam Clegg50686852018-01-12 18:35:13 +0000544
Sam Cleggc94d3932017-11-17 18:14:09 +0000545 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "name");
546
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000547 SubSection Sub(WASM_NAMES_FUNCTION);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000548 writeUleb128(Sub.OS, NumNames, "name count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000549
Sam Clegg93102972018-02-23 05:08:53 +0000550 // Names must appear in function index order. As it happens ImportedSymbols
551 // and InputFunctions are numbered in order with imported functions coming
Sam Clegg1963d712018-01-17 20:19:04 +0000552 // first.
Sam Clegg93102972018-02-23 05:08:53 +0000553 for (const Symbol *S : ImportedSymbols) {
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000554 if (auto *F = dyn_cast<FunctionSymbol>(S)) {
555 writeUleb128(Sub.OS, F->getFunctionIndex(), "func index");
Nicholas Wilson531769b2018-03-13 13:30:04 +0000556 Optional<std::string> Name = demangleItanium(F->getName());
557 writeStr(Sub.OS, Name ? StringRef(*Name) : F->getName(), "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 {
566 Optional<std::string> Name = demangleItanium(F->getName());
567 writeStr(Sub.OS, Name ? StringRef(*Name) : F->getName(), "symbol name");
568 }
Sam Clegg1963d712018-01-17 20:19:04 +0000569 }
570 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000571
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000572 Sub.writeTo(Section->getStream());
Sam Cleggc94d3932017-11-17 18:14:09 +0000573}
574
575void Writer::writeHeader() {
576 memcpy(Buffer->getBufferStart(), Header.data(), Header.size());
577}
578
579void Writer::writeSections() {
580 uint8_t *Buf = Buffer->getBufferStart();
581 parallelForEach(OutputSections, [Buf](OutputSection *S) { S->writeTo(Buf); });
582}
583
584// Fix the memory layout of the output binary. This assigns memory offsets
Sam Clegg49ed9262017-12-01 00:53:21 +0000585// to each of the input data sections as well as the explicit stack region.
Sam Clegga0f095e2018-05-03 17:21:53 +0000586// The default memory layout is as follows, from low to high.
587//
Sam Cleggf0d433d2018-02-02 22:59:56 +0000588// - initialized data (starting at Config->GlobalBase)
589// - BSS data (not currently implemented in llvm)
590// - explicit stack (Config->ZStackSize)
591// - heap start / unallocated
Sam Clegga0f095e2018-05-03 17:21:53 +0000592//
593// The --stack-first option means that stack is placed before any static data.
Heejin Ahn4821ebf2018-08-29 21:03:16 +0000594// This can be useful since it means that stack overflow traps immediately
595// rather than overwriting global data, but also increases code size since all
596// static data loads and stores requires larger offsets.
Sam Cleggc94d3932017-11-17 18:14:09 +0000597void Writer::layoutMemory() {
Sam Cleggc94d3932017-11-17 18:14:09 +0000598 createOutputSegments();
599
Sam Clegga0f095e2018-05-03 17:21:53 +0000600 uint32_t MemoryPtr = 0;
601
602 auto PlaceStack = [&]() {
603 if (Config->Relocatable)
604 return;
605 MemoryPtr = alignTo(MemoryPtr, kStackAlignment);
606 if (Config->ZStackSize != alignTo(Config->ZStackSize, kStackAlignment))
607 error("stack size must be " + Twine(kStackAlignment) + "-byte aligned");
608 log("mem: stack size = " + Twine(Config->ZStackSize));
609 log("mem: stack base = " + Twine(MemoryPtr));
610 MemoryPtr += Config->ZStackSize;
611 WasmSym::StackPointer->Global->Global.InitExpr.Value.Int32 = MemoryPtr;
612 log("mem: stack top = " + Twine(MemoryPtr));
613 };
614
615 if (Config->StackFirst) {
616 PlaceStack();
617 } else {
618 MemoryPtr = Config->GlobalBase;
619 log("mem: global base = " + Twine(Config->GlobalBase));
620 }
621
622 uint32_t DataStart = MemoryPtr;
623
Sam Cleggf0d433d2018-02-02 22:59:56 +0000624 // Arbitrarily set __dso_handle handle to point to the start of the data
625 // segments.
626 if (WasmSym::DsoHandle)
Sam Clegga0f095e2018-05-03 17:21:53 +0000627 WasmSym::DsoHandle->setVirtualAddress(DataStart);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000628
Sam Cleggc94d3932017-11-17 18:14:09 +0000629 for (OutputSegment *Seg : Segments) {
630 MemoryPtr = alignTo(MemoryPtr, Seg->Alignment);
631 Seg->StartVA = MemoryPtr;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000632 log(formatv("mem: {0,-15} offset={1,-8} size={2,-8} align={3}", Seg->Name,
633 MemoryPtr, Seg->Size, Seg->Alignment));
Sam Cleggc94d3932017-11-17 18:14:09 +0000634 MemoryPtr += Seg->Size;
635 }
636
Sam Cleggf0d433d2018-02-02 22:59:56 +0000637 // TODO: Add .bss space here.
Sam Clegg37a4a8a2018-02-07 03:04:53 +0000638 if (WasmSym::DataEnd)
639 WasmSym::DataEnd->setVirtualAddress(MemoryPtr);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000640
Sam Clegga0f095e2018-05-03 17:21:53 +0000641 log("mem: static data = " + Twine(MemoryPtr - DataStart));
Sam Cleggc94d3932017-11-17 18:14:09 +0000642
Sam Clegga0f095e2018-05-03 17:21:53 +0000643 if (!Config->StackFirst)
644 PlaceStack();
645
646 // Set `__heap_base` to directly follow the end of the stack or global data.
647 // The fact that this comes last means that a malloc/brk implementation
648 // can grow the heap at runtime.
Sam Cleggc94d3932017-11-17 18:14:09 +0000649 if (!Config->Relocatable) {
Sam Cleggf0d433d2018-02-02 22:59:56 +0000650 WasmSym::HeapBase->setVirtualAddress(MemoryPtr);
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000651 log("mem: heap base = " + Twine(MemoryPtr));
Sam Cleggc94d3932017-11-17 18:14:09 +0000652 }
653
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000654 if (Config->InitialMemory != 0) {
655 if (Config->InitialMemory != alignTo(Config->InitialMemory, WasmPageSize))
656 error("initial memory must be " + Twine(WasmPageSize) + "-byte aligned");
657 if (MemoryPtr > Config->InitialMemory)
658 error("initial memory too small, " + Twine(MemoryPtr) + " bytes needed");
659 else
660 MemoryPtr = Config->InitialMemory;
661 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000662 uint32_t MemSize = alignTo(MemoryPtr, WasmPageSize);
663 NumMemoryPages = MemSize / WasmPageSize;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000664 log("mem: total pages = " + Twine(NumMemoryPages));
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000665
666 if (Config->MaxMemory != 0) {
667 if (Config->MaxMemory != alignTo(Config->MaxMemory, WasmPageSize))
668 error("maximum memory must be " + Twine(WasmPageSize) + "-byte aligned");
669 if (MemoryPtr > Config->MaxMemory)
670 error("maximum memory too small, " + Twine(MemoryPtr) + " bytes needed");
671 MaxMemoryPages = Config->MaxMemory / WasmPageSize;
672 log("mem: max pages = " + Twine(MaxMemoryPages));
673 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000674}
675
676SyntheticSection *Writer::createSyntheticSection(uint32_t Type,
Sam Cleggc375e4e2018-01-10 19:18:22 +0000677 StringRef Name) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000678 auto Sec = make<SyntheticSection>(Type, Name);
Sam Cleggab2ac292017-12-20 05:14:48 +0000679 log("createSection: " + toString(*Sec));
Sam Cleggc94d3932017-11-17 18:14:09 +0000680 OutputSections.push_back(Sec);
681 return Sec;
682}
683
684void Writer::createSections() {
685 // Known sections
686 createTypeSection();
687 createImportSection();
688 createFunctionSection();
689 createTableSection();
690 createMemorySection();
691 createGlobalSection();
692 createExportSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000693 createElemSection();
694 createCodeSection();
695 createDataSection();
Sam Clegg80ba4382018-04-10 16:12:49 +0000696 createCustomSections();
Sam Cleggc94d3932017-11-17 18:14:09 +0000697
698 // Custom sections
Sam Clegg99eb42c2018-02-27 23:58:03 +0000699 if (Config->Relocatable) {
Sam Clegg99eb42c2018-02-27 23:58:03 +0000700 createLinkingSection();
Nicholas Wilson94d3b162018-03-05 12:33:58 +0000701 createRelocSections();
Sam Clegg99eb42c2018-02-27 23:58:03 +0000702 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000703 if (!Config->StripDebug && !Config->StripAll)
704 createNameSection();
705
706 for (OutputSection *S : OutputSections) {
707 S->setOffset(FileSize);
708 S->finalizeContents();
709 FileSize += S->getSize();
710 }
711}
712
Sam Cleggc94d3932017-11-17 18:14:09 +0000713void Writer::calculateImports() {
Sam Clegg574d7ce2017-12-15 19:23:49 +0000714 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000715 if (!Sym->isUndefined())
716 continue;
717 if (isa<DataSymbol>(Sym))
718 continue;
719 if (Sym->isWeak() && !Config->Relocatable)
Sam Clegg574d7ce2017-12-15 19:23:49 +0000720 continue;
Nicholas Wilsona1e299f2018-04-20 17:18:06 +0000721 if (!Sym->isLive())
722 continue;
Sam Cleggc729c1b2018-05-30 18:07:52 +0000723 if (!Sym->IsUsedInRegularObj)
724 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000725
Nicola Zaghene7245b42018-05-15 13:36:20 +0000726 LLVM_DEBUG(dbgs() << "import: " << Sym->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000727 ImportedSymbols.emplace_back(Sym);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000728 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
729 F->setFunctionIndex(NumImportedFunctions++);
Sam Clegg93102972018-02-23 05:08:53 +0000730 else
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000731 cast<GlobalSymbol>(Sym)->setGlobalIndex(NumImportedGlobals++);
Sam Cleggc94d3932017-11-17 18:14:09 +0000732 }
733}
734
Sam Cleggd3052d52018-01-18 23:40:49 +0000735void Writer::calculateExports() {
Sam Clegg93102972018-02-23 05:08:53 +0000736 if (Config->Relocatable)
737 return;
Sam Cleggf0d433d2018-02-02 22:59:56 +0000738
Sam Cleggd6beb322018-05-10 18:10:34 +0000739 if (!Config->Relocatable && !Config->ImportMemory)
740 Exports.push_back(WasmExport{"memory", WASM_EXTERNAL_MEMORY, 0});
741
742 if (!Config->Relocatable && Config->ExportTable)
743 Exports.push_back(WasmExport{kFunctionTableName, WASM_EXTERNAL_TABLE, 0});
744
745 unsigned FakeGlobalIndex = NumImportedGlobals + InputGlobals.size();
746
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000747 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Cleggce004bf2018-06-28 17:04:58 +0000748 if (!Sym->isExported())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000749 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000750 if (!Sym->isLive())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000751 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000752
Sam Cleggd6beb322018-05-10 18:10:34 +0000753 StringRef Name = Sym->getName();
754 WasmExport Export;
755 if (auto *F = dyn_cast<DefinedFunction>(Sym)) {
756 Export = {Name, WASM_EXTERNAL_FUNCTION, F->getFunctionIndex()};
757 } else if (auto *G = dyn_cast<DefinedGlobal>(Sym)) {
Sam Clegg177b4582018-06-07 01:27:07 +0000758 // TODO(sbc): Remove this check once to mutable global proposal is
759 // implement in all major browsers.
760 // See: https://github.com/WebAssembly/mutable-global
761 if (G->getGlobalType()->Mutable) {
762 // Only the __stack_pointer should ever be create as mutable.
763 assert(G == WasmSym::StackPointer);
764 continue;
765 }
Sam Cleggd6beb322018-05-10 18:10:34 +0000766 Export = {Name, WASM_EXTERNAL_GLOBAL, G->getGlobalIndex()};
767 } else {
768 auto *D = cast<DefinedData>(Sym);
Sam Clegg93102972018-02-23 05:08:53 +0000769 DefinedFakeGlobals.emplace_back(D);
Sam Cleggd6beb322018-05-10 18:10:34 +0000770 Export = {Name, WASM_EXTERNAL_GLOBAL, FakeGlobalIndex++};
771 }
772
Nicola Zaghene7245b42018-05-15 13:36:20 +0000773 LLVM_DEBUG(dbgs() << "Export: " << Name << "\n");
Sam Cleggd6beb322018-05-10 18:10:34 +0000774 Exports.push_back(Export);
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000775 }
Sam Clegg93102972018-02-23 05:08:53 +0000776}
777
778void Writer::assignSymtab() {
779 if (!Config->Relocatable)
780 return;
781
Sam Cleggd177ab22018-05-04 23:14:42 +0000782 StringMap<uint32_t> SectionSymbolIndices;
783
Sam Clegg93102972018-02-23 05:08:53 +0000784 unsigned SymbolIndex = SymtabEntries.size();
Sam Cleggd3052d52018-01-18 23:40:49 +0000785 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000786 LLVM_DEBUG(dbgs() << "Symtab entries: " << File->getName() << "\n");
Sam Cleggd3052d52018-01-18 23:40:49 +0000787 for (Symbol *Sym : File->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000788 if (Sym->getFile() != File)
Sam Cleggd3052d52018-01-18 23:40:49 +0000789 continue;
Sam Cleggd177ab22018-05-04 23:14:42 +0000790
791 if (auto *S = dyn_cast<SectionSymbol>(Sym)) {
792 StringRef Name = S->getName();
793 if (CustomSectionMapping.count(Name) == 0)
794 continue;
795
796 auto SSI = SectionSymbolIndices.find(Name);
797 if (SSI != SectionSymbolIndices.end()) {
798 Sym->setOutputSymbolIndex(SSI->second);
799 continue;
800 }
801
802 SectionSymbolIndices[Name] = SymbolIndex;
803 CustomSectionSymbols[Name] = cast<SectionSymbol>(Sym);
804
805 Sym->markLive();
806 }
807
Nicholas Wilson06e0d172018-03-07 11:15:47 +0000808 // (Since this is relocatable output, GC is not performed so symbols must
809 // be live.)
810 assert(Sym->isLive());
Sam Clegg93102972018-02-23 05:08:53 +0000811 Sym->setOutputSymbolIndex(SymbolIndex++);
812 SymtabEntries.emplace_back(Sym);
Sam Cleggd3052d52018-01-18 23:40:49 +0000813 }
814 }
815
Sam Clegg93102972018-02-23 05:08:53 +0000816 // For the moment, relocatable output doesn't contain any synthetic functions,
817 // so no need to look through the Symtab for symbols not referenced by
818 // Symtab->ObjectFiles.
Sam Cleggd3052d52018-01-18 23:40:49 +0000819}
820
Sam Cleggc375e4e2018-01-10 19:18:22 +0000821uint32_t Writer::lookupType(const WasmSignature &Sig) {
Sam Clegg8d027d62018-01-10 20:12:26 +0000822 auto It = TypeIndices.find(Sig);
823 if (It == TypeIndices.end()) {
Sam Cleggc375e4e2018-01-10 19:18:22 +0000824 error("type not found: " + toString(Sig));
Sam Clegg8d027d62018-01-10 20:12:26 +0000825 return 0;
826 }
827 return It->second;
Sam Cleggc375e4e2018-01-10 19:18:22 +0000828}
829
830uint32_t Writer::registerType(const WasmSignature &Sig) {
Sam Cleggb8621592017-11-30 01:40:08 +0000831 auto Pair = TypeIndices.insert(std::make_pair(Sig, Types.size()));
Sam Cleggc375e4e2018-01-10 19:18:22 +0000832 if (Pair.second) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000833 LLVM_DEBUG(dbgs() << "type " << toString(Sig) << "\n");
Sam Cleggb8621592017-11-30 01:40:08 +0000834 Types.push_back(&Sig);
Sam Cleggc375e4e2018-01-10 19:18:22 +0000835 }
Sam Cleggb8621592017-11-30 01:40:08 +0000836 return Pair.first->second;
837}
838
Sam Cleggc94d3932017-11-17 18:14:09 +0000839void Writer::calculateTypes() {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000840 // The output type section is the union of the following sets:
841 // 1. Any signature used in the TYPE relocation
842 // 2. The signatures of all imported functions
843 // 3. The signatures of all defined functions
844
Sam Cleggc94d3932017-11-17 18:14:09 +0000845 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000846 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
847 for (uint32_t I = 0; I < Types.size(); I++)
848 if (File->TypeIsUsed[I])
849 File->TypeMap[I] = registerType(Types[I]);
Sam Cleggc94d3932017-11-17 18:14:09 +0000850 }
Sam Clegg50686852018-01-12 18:35:13 +0000851
Sam Clegg93102972018-02-23 05:08:53 +0000852 for (const Symbol *Sym : ImportedSymbols)
853 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
Sam Cleggcefbf9a2018-06-28 16:53:53 +0000854 registerType(*F->FunctionType);
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000855
Sam Clegg9f934222018-02-21 18:29:23 +0000856 for (const InputFunction *F : InputFunctions)
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000857 registerType(F->Signature);
Sam Cleggc94d3932017-11-17 18:14:09 +0000858}
859
Sam Clegg8d146bb2018-01-09 23:56:44 +0000860void Writer::assignIndexes() {
Sam Clegg93102972018-02-23 05:08:53 +0000861 uint32_t FunctionIndex = NumImportedFunctions + InputFunctions.size();
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000862 auto AddDefinedFunction = [&](InputFunction *Func) {
863 if (!Func->Live)
864 return;
865 InputFunctions.emplace_back(Func);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000866 Func->setFunctionIndex(FunctionIndex++);
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000867 };
868
Nicholas Wilson5639da82018-03-12 15:44:07 +0000869 for (InputFunction *Func : Symtab->SyntheticFunctions)
870 AddDefinedFunction(Func);
871
Sam Clegg87e61922018-01-08 23:39:11 +0000872 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000873 LLVM_DEBUG(dbgs() << "Functions: " << File->getName() << "\n");
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000874 for (InputFunction *Func : File->Functions)
875 AddDefinedFunction(Func);
Sam Clegg8d146bb2018-01-09 23:56:44 +0000876 }
877
Sam Clegg93102972018-02-23 05:08:53 +0000878 uint32_t TableIndex = kInitialTableOffset;
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000879 auto HandleRelocs = [&](InputChunk *Chunk) {
880 if (!Chunk->Live)
881 return;
882 ObjFile *File = Chunk->File;
883 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
Sam Clegg93102972018-02-23 05:08:53 +0000884 for (const WasmRelocation &Reloc : Chunk->getRelocations()) {
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000885 if (Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_I32 ||
886 Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_SLEB) {
887 FunctionSymbol *Sym = File->getFunctionSymbol(Reloc.Index);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000888 if (Sym->hasTableIndex() || !Sym->hasFunctionIndex())
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000889 continue;
890 Sym->setTableIndex(TableIndex++);
891 IndirectFunctions.emplace_back(Sym);
892 } else if (Reloc.Type == R_WEBASSEMBLY_TYPE_INDEX_LEB) {
Sam Clegg93102972018-02-23 05:08:53 +0000893 // Mark target type as live
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000894 File->TypeMap[Reloc.Index] = registerType(Types[Reloc.Index]);
895 File->TypeIsUsed[Reloc.Index] = true;
896 }
897 }
898 };
899
Sam Clegg8d146bb2018-01-09 23:56:44 +0000900 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000901 LLVM_DEBUG(dbgs() << "Handle relocs: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000902 for (InputChunk *Chunk : File->Functions)
903 HandleRelocs(Chunk);
904 for (InputChunk *Chunk : File->Segments)
905 HandleRelocs(Chunk);
Sam Cleggd177ab22018-05-04 23:14:42 +0000906 for (auto &P : File->CustomSections)
907 HandleRelocs(P);
Sam Clegg93102972018-02-23 05:08:53 +0000908 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000909
Sam Clegg93102972018-02-23 05:08:53 +0000910 uint32_t GlobalIndex = NumImportedGlobals + InputGlobals.size();
911 auto AddDefinedGlobal = [&](InputGlobal *Global) {
912 if (Global->Live) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000913 LLVM_DEBUG(dbgs() << "AddDefinedGlobal: " << GlobalIndex << "\n");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000914 Global->setGlobalIndex(GlobalIndex++);
Sam Clegg93102972018-02-23 05:08:53 +0000915 InputGlobals.push_back(Global);
916 }
917 };
918
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000919 for (InputGlobal *Global : Symtab->SyntheticGlobals)
920 AddDefinedGlobal(Global);
Sam Clegg93102972018-02-23 05:08:53 +0000921
922 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000923 LLVM_DEBUG(dbgs() << "Globals: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000924 for (InputGlobal *Global : File->Globals)
925 AddDefinedGlobal(Global);
Sam Cleggc94d3932017-11-17 18:14:09 +0000926 }
927}
928
929static StringRef getOutputDataSegmentName(StringRef Name) {
Sam Clegg66844762018-05-10 18:23:51 +0000930 if (!Config->MergeDataSegments)
Sam Cleggc94d3932017-11-17 18:14:09 +0000931 return Name;
Rui Ueyama4764b572018-02-28 00:57:28 +0000932 if (Name.startswith(".text."))
933 return ".text";
934 if (Name.startswith(".data."))
935 return ".data";
936 if (Name.startswith(".bss."))
937 return ".bss";
Sam Clegg57694c52018-08-08 18:02:55 +0000938 if (Name.startswith(".rodata."))
939 return ".rodata";
Sam Cleggc94d3932017-11-17 18:14:09 +0000940 return Name;
941}
942
943void Writer::createOutputSegments() {
944 for (ObjFile *File : Symtab->ObjectFiles) {
945 for (InputSegment *Segment : File->Segments) {
Sam Clegg447ae402018-02-13 20:29:38 +0000946 if (!Segment->Live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000947 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000948 StringRef Name = getOutputDataSegmentName(Segment->getName());
949 OutputSegment *&S = SegmentMap[Name];
950 if (S == nullptr) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000951 LLVM_DEBUG(dbgs() << "new segment: " << Name << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000952 S = make<OutputSegment>(Name, Segments.size());
Sam Cleggc94d3932017-11-17 18:14:09 +0000953 Segments.push_back(S);
954 }
955 S->addInputSegment(Segment);
Nicola Zaghene7245b42018-05-15 13:36:20 +0000956 LLVM_DEBUG(dbgs() << "added data: " << Name << ": " << S->Size << "\n");
Sam Cleggc94d3932017-11-17 18:14:09 +0000957 }
958 }
959}
960
Sam Clegg50686852018-01-12 18:35:13 +0000961static const int OPCODE_CALL = 0x10;
962static const int OPCODE_END = 0xb;
963
964// Create synthetic "__wasm_call_ctors" function based on ctor functions
965// in input object.
966void Writer::createCtorFunction() {
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000967 // First write the body's contents to a string.
968 std::string BodyContent;
Sam Clegg50686852018-01-12 18:35:13 +0000969 {
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000970 raw_string_ostream OS(BodyContent);
Sam Clegg50686852018-01-12 18:35:13 +0000971 writeUleb128(OS, 0, "num locals");
Sam Clegg93102972018-02-23 05:08:53 +0000972 for (const WasmInitEntry &F : InitFunctions) {
Sam Clegg50686852018-01-12 18:35:13 +0000973 writeU8(OS, OPCODE_CALL, "CALL");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000974 writeUleb128(OS, F.Sym->getFunctionIndex(), "function index");
Sam Clegg50686852018-01-12 18:35:13 +0000975 }
976 writeU8(OS, OPCODE_END, "END");
977 }
978
979 // Once we know the size of the body we can create the final function body
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000980 std::string FunctionBody;
981 {
982 raw_string_ostream OS(FunctionBody);
983 writeUleb128(OS, BodyContent.size(), "function size");
984 OS << BodyContent;
985 }
Rui Ueyama29abfe42018-02-28 17:43:15 +0000986
Sam Cleggea656472018-10-22 08:35:39 +0000987 ArrayRef<uint8_t> Body = arrayRefFromStringRef(Saver.save(FunctionBody));
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000988 cast<SyntheticFunction>(WasmSym::CallCtors->Function)->setBody(Body);
Sam Clegg50686852018-01-12 18:35:13 +0000989}
990
991// Populate InitFunctions vector with init functions from all input objects.
992// This is then used either when creating the output linking section or to
993// synthesize the "__wasm_call_ctors" function.
994void Writer::calculateInitFunctions() {
995 for (ObjFile *File : Symtab->ObjectFiles) {
996 const WasmLinkingData &L = File->getWasmObj()->linkingData();
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +0000997 for (const WasmInitFunc &F : L.InitFunctions) {
998 FunctionSymbol *Sym = File->getFunctionSymbol(F.Symbol);
Derek Schuff371842b2018-10-03 22:25:32 +0000999 if (*Sym->FunctionType != WasmSignature{{}, {}})
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +00001000 error("invalid signature for init func: " + toString(*Sym));
1001 InitFunctions.emplace_back(WasmInitEntry{Sym, F.Priority});
1002 }
Sam Clegg50686852018-01-12 18:35:13 +00001003 }
Rui Ueyamada69b712018-02-28 00:15:59 +00001004
Sam Clegg50686852018-01-12 18:35:13 +00001005 // Sort in order of priority (lowest first) so that they are called
1006 // in the correct order.
Sam Clegg29b8feb2018-02-21 00:34:34 +00001007 std::stable_sort(InitFunctions.begin(), InitFunctions.end(),
Sam Clegg93102972018-02-23 05:08:53 +00001008 [](const WasmInitEntry &L, const WasmInitEntry &R) {
Sam Clegg29b8feb2018-02-21 00:34:34 +00001009 return L.Priority < R.Priority;
1010 });
Sam Clegg50686852018-01-12 18:35:13 +00001011}
1012
Sam Cleggc94d3932017-11-17 18:14:09 +00001013void Writer::run() {
Sam Clegg99eb42c2018-02-27 23:58:03 +00001014 if (Config->Relocatable)
1015 Config->GlobalBase = 0;
1016
Sam Cleggc94d3932017-11-17 18:14:09 +00001017 log("-- calculateImports");
1018 calculateImports();
Sam Clegg8d146bb2018-01-09 23:56:44 +00001019 log("-- assignIndexes");
1020 assignIndexes();
Sam Clegg50686852018-01-12 18:35:13 +00001021 log("-- calculateInitFunctions");
1022 calculateInitFunctions();
1023 if (!Config->Relocatable)
1024 createCtorFunction();
Sam Clegg8f6d2de2018-01-31 23:48:14 +00001025 log("-- calculateTypes");
1026 calculateTypes();
Sam Clegg93102972018-02-23 05:08:53 +00001027 log("-- layoutMemory");
1028 layoutMemory();
1029 log("-- calculateExports");
1030 calculateExports();
Sam Cleggd177ab22018-05-04 23:14:42 +00001031 log("-- calculateCustomSections");
1032 calculateCustomSections();
Sam Clegg93102972018-02-23 05:08:53 +00001033 log("-- assignSymtab");
1034 assignSymtab();
Sam Cleggc94d3932017-11-17 18:14:09 +00001035
1036 if (errorHandler().Verbose) {
Sam Clegg9f934222018-02-21 18:29:23 +00001037 log("Defined Functions: " + Twine(InputFunctions.size()));
Sam Clegg93102972018-02-23 05:08:53 +00001038 log("Defined Globals : " + Twine(InputGlobals.size()));
1039 log("Function Imports : " + Twine(NumImportedFunctions));
1040 log("Global Imports : " + Twine(NumImportedGlobals));
Sam Cleggc94d3932017-11-17 18:14:09 +00001041 for (ObjFile *File : Symtab->ObjectFiles)
1042 File->dumpInfo();
1043 }
1044
Sam Cleggc94d3932017-11-17 18:14:09 +00001045 createHeader();
1046 log("-- createSections");
1047 createSections();
1048
1049 log("-- openFile");
1050 openFile();
1051 if (errorCount())
1052 return;
1053
1054 writeHeader();
1055
1056 log("-- writeSections");
1057 writeSections();
1058 if (errorCount())
1059 return;
1060
1061 if (Error E = Buffer->commit())
1062 fatal("failed to write the output file: " + toString(std::move(E)));
1063}
1064
1065// Open a result file.
1066void Writer::openFile() {
1067 log("writing: " + Config->OutputFile);
Sam Cleggc94d3932017-11-17 18:14:09 +00001068
1069 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
1070 FileOutputBuffer::create(Config->OutputFile, FileSize,
1071 FileOutputBuffer::F_executable);
1072
1073 if (!BufferOrErr)
1074 error("failed to open " + Config->OutputFile + ": " +
1075 toString(BufferOrErr.takeError()));
1076 else
1077 Buffer = std::move(*BufferOrErr);
1078}
1079
1080void Writer::createHeader() {
1081 raw_string_ostream OS(Header);
1082 writeBytes(OS, WasmMagic, sizeof(WasmMagic), "wasm magic");
1083 writeU32(OS, WasmVersion, "wasm version");
1084 OS.flush();
1085 FileSize += Header.size();
1086}
1087
1088void lld::wasm::writeResult() { Writer().run(); }