blob: fe34b2332fc3bdd7963657ed4dfc42f47e1f9ff2 [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"
Heejin Ahne915a712018-12-08 06:17:43 +000013#include "InputEvent.h"
Sam Clegg93102972018-02-23 05:08:53 +000014#include "InputGlobal.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000015#include "OutputSections.h"
16#include "OutputSegment.h"
17#include "SymbolTable.h"
18#include "WriterUtils.h"
19#include "lld/Common/ErrorHandler.h"
Rui Ueyama2017d522017-11-28 20:39:17 +000020#include "lld/Common/Memory.h"
Nicholas Wilson8269f372018-03-07 10:37:50 +000021#include "lld/Common/Strings.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000022#include "lld/Common/Threads.h"
Sam Clegg3141ddc2018-02-20 21:53:18 +000023#include "llvm/ADT/DenseSet.h"
Thomas Lively2a0868f2019-01-17 02:29:41 +000024#include "llvm/ADT/SmallVector.h"
Sam Clegg80ba4382018-04-10 16:12:49 +000025#include "llvm/ADT/StringMap.h"
Sam Clegg93102972018-02-23 05:08:53 +000026#include "llvm/BinaryFormat/Wasm.h"
Nicholas Wilson3e3f5fb2018-03-14 15:58:16 +000027#include "llvm/Object/WasmTraits.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000028#include "llvm/Support/FileOutputBuffer.h"
29#include "llvm/Support/Format.h"
30#include "llvm/Support/FormatVariadic.h"
31#include "llvm/Support/LEB128.h"
32
33#include <cstdarg>
Sam Clegge0f6fcd2018-01-12 22:25:17 +000034#include <map>
Sam Cleggc94d3932017-11-17 18:14:09 +000035
36#define DEBUG_TYPE "lld"
37
38using namespace llvm;
39using namespace llvm::wasm;
40using namespace lld;
41using namespace lld::wasm;
42
43static constexpr int kStackAlignment = 16;
Nicholas Wilson874eedd2018-03-27 17:38:51 +000044static constexpr const char *kFunctionTableName = "__indirect_function_table";
Sam Cleggc94d3932017-11-17 18:14:09 +000045
46namespace {
47
Sam Clegg93102972018-02-23 05:08:53 +000048// An init entry to be written to either the synthetic init func or the
49// linking metadata.
50struct WasmInitEntry {
Sam Clegge3f3ccf2018-03-12 19:56:23 +000051 const FunctionSymbol *Sym;
Sam Clegg93102972018-02-23 05:08:53 +000052 uint32_t Priority;
Sam Cleggd3052d52018-01-18 23:40:49 +000053};
54
Sam Cleggc94d3932017-11-17 18:14:09 +000055// The writer writes a SymbolTable result to a file.
56class Writer {
57public:
58 void run();
59
60private:
61 void openFile();
62
Sam Cleggc375e4e2018-01-10 19:18:22 +000063 uint32_t lookupType(const WasmSignature &Sig);
64 uint32_t registerType(const WasmSignature &Sig);
Sam Clegg93102972018-02-23 05:08:53 +000065
Sam Clegg50686852018-01-12 18:35:13 +000066 void createCtorFunction();
67 void calculateInitFunctions();
Sam Clegg8d146bb2018-01-09 23:56:44 +000068 void assignIndexes();
Sam Cleggc94d3932017-11-17 18:14:09 +000069 void calculateImports();
Sam Cleggd3052d52018-01-18 23:40:49 +000070 void calculateExports();
Sam Cleggd177ab22018-05-04 23:14:42 +000071 void calculateCustomSections();
Sam Clegg93102972018-02-23 05:08:53 +000072 void assignSymtab();
Sam Cleggc94d3932017-11-17 18:14:09 +000073 void calculateTypes();
74 void createOutputSegments();
75 void layoutMemory();
76 void createHeader();
77 void createSections();
Nicholas Wilsondbd90bf2018-03-07 13:28:16 +000078 SyntheticSection *createSyntheticSection(uint32_t Type, StringRef Name = "");
Sam Cleggc94d3932017-11-17 18:14:09 +000079
80 // Builtin sections
81 void createTypeSection();
82 void createFunctionSection();
83 void createTableSection();
84 void createGlobalSection();
Heejin Ahne915a712018-12-08 06:17:43 +000085 void createEventSection();
Sam Cleggc94d3932017-11-17 18:14:09 +000086 void createExportSection();
87 void createImportSection();
88 void createMemorySection();
89 void createElemSection();
Sam Cleggc94d3932017-11-17 18:14:09 +000090 void createCodeSection();
91 void createDataSection();
Sam Clegg80ba4382018-04-10 16:12:49 +000092 void createCustomSections();
Sam Cleggc94d3932017-11-17 18:14:09 +000093
94 // Custom sections
Sam Cleggbfb75342018-11-15 00:37:21 +000095 void createDylinkSection();
Sam Cleggc94d3932017-11-17 18:14:09 +000096 void createRelocSections();
97 void createLinkingSection();
98 void createNameSection();
Thomas Lively2a0868f2019-01-17 02:29:41 +000099 void createProducersSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000100
101 void writeHeader();
102 void writeSections();
103
104 uint64_t FileSize = 0;
Sam Cleggbfb75342018-11-15 00:37:21 +0000105 uint32_t TableBase = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000106 uint32_t NumMemoryPages = 0;
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000107 uint32_t MaxMemoryPages = 0;
Sam Cleggbfb75342018-11-15 00:37:21 +0000108 // Memory size and aligment. Written to the "dylink" section
109 // when build with -shared or -pie.
110 uint32_t MemAlign = 0;
111 uint32_t MemSize = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000112
113 std::vector<const WasmSignature *> Types;
Nicholas Wilson3e3f5fb2018-03-14 15:58:16 +0000114 DenseMap<WasmSignature, int32_t> TypeIndices;
Sam Clegg93102972018-02-23 05:08:53 +0000115 std::vector<const Symbol *> ImportedSymbols;
116 unsigned NumImportedFunctions = 0;
117 unsigned NumImportedGlobals = 0;
Heejin Ahne915a712018-12-08 06:17:43 +0000118 unsigned NumImportedEvents = 0;
Sam Cleggd6beb322018-05-10 18:10:34 +0000119 std::vector<WasmExport> Exports;
Sam Clegg93102972018-02-23 05:08:53 +0000120 std::vector<const DefinedData *> DefinedFakeGlobals;
121 std::vector<InputGlobal *> InputGlobals;
Sam Clegg9f934222018-02-21 18:29:23 +0000122 std::vector<InputFunction *> InputFunctions;
Heejin Ahne915a712018-12-08 06:17:43 +0000123 std::vector<InputEvent *> InputEvents;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000124 std::vector<const FunctionSymbol *> IndirectFunctions;
Sam Clegg93102972018-02-23 05:08:53 +0000125 std::vector<const Symbol *> SymtabEntries;
126 std::vector<WasmInitEntry> InitFunctions;
Sam Cleggc94d3932017-11-17 18:14:09 +0000127
Sam Clegg80ba4382018-04-10 16:12:49 +0000128 llvm::StringMap<std::vector<InputSection *>> CustomSectionMapping;
Sam Cleggd177ab22018-05-04 23:14:42 +0000129 llvm::StringMap<SectionSymbol *> CustomSectionSymbols;
Sam Clegg80ba4382018-04-10 16:12:49 +0000130
Sam Cleggc94d3932017-11-17 18:14:09 +0000131 // Elements that are used to construct the final output
132 std::string Header;
133 std::vector<OutputSection *> OutputSections;
134
135 std::unique_ptr<FileOutputBuffer> Buffer;
136
137 std::vector<OutputSegment *> Segments;
138 llvm::SmallDenseMap<StringRef, OutputSegment *> SegmentMap;
139};
140
141} // anonymous namespace
142
Sam Cleggc94d3932017-11-17 18:14:09 +0000143void Writer::createImportSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000144 uint32_t NumImports = ImportedSymbols.size();
Sam Cleggc94d3932017-11-17 18:14:09 +0000145 if (Config->ImportMemory)
146 ++NumImports;
Nicholas Wilsonfc90b302018-03-28 12:53:29 +0000147 if (Config->ImportTable)
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000148 ++NumImports;
Sam Cleggc94d3932017-11-17 18:14:09 +0000149
150 if (NumImports == 0)
151 return;
152
153 SyntheticSection *Section = createSyntheticSection(WASM_SEC_IMPORT);
154 raw_ostream &OS = Section->getStream();
155
156 writeUleb128(OS, NumImports, "import count");
157
Sam Cleggc94d3932017-11-17 18:14:09 +0000158 if (Config->ImportMemory) {
159 WasmImport Import;
160 Import.Module = "env";
161 Import.Field = "memory";
162 Import.Kind = WASM_EXTERNAL_MEMORY;
163 Import.Memory.Flags = 0;
164 Import.Memory.Initial = NumMemoryPages;
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000165 if (MaxMemoryPages != 0) {
166 Import.Memory.Flags |= WASM_LIMITS_FLAG_HAS_MAX;
167 Import.Memory.Maximum = MaxMemoryPages;
168 }
Derek Schuff786760a2018-11-06 18:02:39 +0000169 if (Config->SharedMemory)
Derek Schuff3bea8bc2018-11-06 17:59:32 +0000170 Import.Memory.Flags |= WASM_LIMITS_FLAG_IS_SHARED;
Sam Cleggc94d3932017-11-17 18:14:09 +0000171 writeImport(OS, Import);
172 }
173
Nicholas Wilsonfc90b302018-03-28 12:53:29 +0000174 if (Config->ImportTable) {
Sam Cleggbfb75342018-11-15 00:37:21 +0000175 uint32_t TableSize = TableBase + IndirectFunctions.size();
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000176 WasmImport Import;
177 Import.Module = "env";
178 Import.Field = kFunctionTableName;
179 Import.Kind = WASM_EXTERNAL_TABLE;
Thomas Lively25ff8932019-01-08 06:25:55 +0000180 Import.Table.ElemType = WASM_TYPE_FUNCREF;
Sam Clegg748f59cae2018-12-03 22:37:55 +0000181 Import.Table.Limits = {0, TableSize, 0};
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000182 writeImport(OS, Import);
183 }
184
Sam Clegg93102972018-02-23 05:08:53 +0000185 for (const Symbol *Sym : ImportedSymbols) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000186 WasmImport Import;
187 Import.Module = "env";
188 Import.Field = Sym->getName();
Sam Clegg93102972018-02-23 05:08:53 +0000189 if (auto *FunctionSym = dyn_cast<FunctionSymbol>(Sym)) {
190 Import.Kind = WASM_EXTERNAL_FUNCTION;
Heejin Ahne915a712018-12-08 06:17:43 +0000191 Import.SigIndex = lookupType(*FunctionSym->Signature);
192 } else if (auto *GlobalSym = dyn_cast<GlobalSymbol>(Sym)) {
Sam Clegg93102972018-02-23 05:08:53 +0000193 Import.Kind = WASM_EXTERNAL_GLOBAL;
194 Import.Global = *GlobalSym->getGlobalType();
Heejin Ahne915a712018-12-08 06:17:43 +0000195 } else {
196 auto *EventSym = cast<EventSymbol>(Sym);
197 Import.Kind = WASM_EXTERNAL_EVENT;
198 Import.Event.Attribute = EventSym->getEventType()->Attribute;
199 Import.Event.SigIndex = lookupType(*EventSym->Signature);
Sam Clegg93102972018-02-23 05:08:53 +0000200 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000201 writeImport(OS, Import);
202 }
203}
204
205void Writer::createTypeSection() {
206 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TYPE);
207 raw_ostream &OS = Section->getStream();
208 writeUleb128(OS, Types.size(), "type count");
Sam Cleggd451da12017-12-19 19:56:27 +0000209 for (const WasmSignature *Sig : Types)
Sam Cleggc94d3932017-11-17 18:14:09 +0000210 writeSig(OS, *Sig);
Sam Cleggc94d3932017-11-17 18:14:09 +0000211}
212
213void Writer::createFunctionSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000214 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000215 return;
216
217 SyntheticSection *Section = createSyntheticSection(WASM_SEC_FUNCTION);
218 raw_ostream &OS = Section->getStream();
219
Sam Clegg9f934222018-02-21 18:29:23 +0000220 writeUleb128(OS, InputFunctions.size(), "function count");
221 for (const InputFunction *Func : InputFunctions)
Sam Cleggc375e4e2018-01-10 19:18:22 +0000222 writeUleb128(OS, lookupType(Func->Signature), "sig index");
Sam Cleggc94d3932017-11-17 18:14:09 +0000223}
224
225void Writer::createMemorySection() {
226 if (Config->ImportMemory)
227 return;
228
229 SyntheticSection *Section = createSyntheticSection(WASM_SEC_MEMORY);
230 raw_ostream &OS = Section->getStream();
231
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000232 bool HasMax = MaxMemoryPages != 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000233 writeUleb128(OS, 1, "memory count");
Derek Schuff786760a2018-11-06 18:02:39 +0000234 unsigned Flags = 0;
235 if (HasMax)
236 Flags |= WASM_LIMITS_FLAG_HAS_MAX;
Derek Schuff3bea8bc2018-11-06 17:59:32 +0000237 if (Config->SharedMemory)
238 Flags |= WASM_LIMITS_FLAG_IS_SHARED;
239 writeUleb128(OS, Flags, "memory limits flags");
Sam Cleggc94d3932017-11-17 18:14:09 +0000240 writeUleb128(OS, NumMemoryPages, "initial pages");
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000241 if (HasMax)
242 writeUleb128(OS, MaxMemoryPages, "max pages");
Sam Cleggc94d3932017-11-17 18:14:09 +0000243}
244
245void Writer::createGlobalSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000246 unsigned NumGlobals = InputGlobals.size() + DefinedFakeGlobals.size();
247 if (NumGlobals == 0)
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000248 return;
249
Sam Cleggc94d3932017-11-17 18:14:09 +0000250 SyntheticSection *Section = createSyntheticSection(WASM_SEC_GLOBAL);
251 raw_ostream &OS = Section->getStream();
252
Sam Clegg93102972018-02-23 05:08:53 +0000253 writeUleb128(OS, NumGlobals, "global count");
254 for (const InputGlobal *G : InputGlobals)
255 writeGlobal(OS, G->Global);
256 for (const DefinedData *Sym : DefinedFakeGlobals) {
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000257 WasmGlobal Global;
Sam Clegg93102972018-02-23 05:08:53 +0000258 Global.Type = {WASM_TYPE_I32, false};
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000259 Global.InitExpr.Opcode = WASM_OPCODE_I32_CONST;
260 Global.InitExpr.Value.Int32 = Sym->getVirtualAddress();
Sam Cleggc94d3932017-11-17 18:14:09 +0000261 writeGlobal(OS, Global);
262 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000263}
264
Heejin Ahne915a712018-12-08 06:17:43 +0000265// The event section contains a list of declared wasm events associated with the
266// module. Currently the only supported event kind is exceptions. A single event
267// entry represents a single event with an event tag. All C++ exceptions are
268// represented by a single event. An event entry in this section contains
269// information on what kind of event it is (e.g. exception) and the type of
270// values contained in a single event object. (In wasm, an event can contain
271// multiple values of primitive types. But for C++ exceptions, we just throw a
272// pointer which is an i32 value (for wasm32 architecture), so the signature of
273// C++ exception is (i32)->(void), because all event types are assumed to have
274// void return type to share WasmSignature with functions.)
275void Writer::createEventSection() {
276 unsigned NumEvents = InputEvents.size();
277 if (NumEvents == 0)
278 return;
279
280 SyntheticSection *Section = createSyntheticSection(WASM_SEC_EVENT);
281 raw_ostream &OS = Section->getStream();
282
283 writeUleb128(OS, NumEvents, "event count");
284 for (InputEvent *E : InputEvents) {
285 E->Event.Type.SigIndex = lookupType(E->Signature);
286 writeEvent(OS, E->Event);
287 }
288}
289
Sam Cleggc94d3932017-11-17 18:14:09 +0000290void Writer::createTableSection() {
Nicholas Wilsonfc90b302018-03-28 12:53:29 +0000291 if (Config->ImportTable)
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000292 return;
293
294 // Always output a table section (or table import), even if there are no
295 // indirect calls. There are two reasons for this:
Sam Cleggfc1a9122017-12-11 22:00:56 +0000296 // 1. For executables it is useful to have an empty table slot at 0
297 // which can be filled with a null function call handler.
298 // 2. If we don't do this, any program that contains a call_indirect but
299 // no address-taken function will fail at validation time since it is
300 // a validation error to include a call_indirect instruction if there
301 // is not table.
Sam Cleggbfb75342018-11-15 00:37:21 +0000302 uint32_t TableSize = TableBase + IndirectFunctions.size();
Sam Cleggfc1a9122017-12-11 22:00:56 +0000303
Sam Cleggc94d3932017-11-17 18:14:09 +0000304 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TABLE);
305 raw_ostream &OS = Section->getStream();
306
307 writeUleb128(OS, 1, "table count");
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000308 WasmLimits Limits = {WASM_LIMITS_FLAG_HAS_MAX, TableSize, TableSize};
Thomas Lively25ff8932019-01-08 06:25:55 +0000309 writeTableType(OS, WasmTable{WASM_TYPE_FUNCREF, Limits});
Sam Cleggc94d3932017-11-17 18:14:09 +0000310}
311
312void Writer::createExportSection() {
Sam Cleggd6beb322018-05-10 18:10:34 +0000313 if (!Exports.size())
Sam Cleggc94d3932017-11-17 18:14:09 +0000314 return;
315
316 SyntheticSection *Section = createSyntheticSection(WASM_SEC_EXPORT);
317 raw_ostream &OS = Section->getStream();
318
Sam Cleggd6beb322018-05-10 18:10:34 +0000319 writeUleb128(OS, Exports.size(), "export count");
320 for (const WasmExport &Export : Exports)
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000321 writeExport(OS, Export);
Sam Cleggc94d3932017-11-17 18:14:09 +0000322}
323
Sam Cleggd177ab22018-05-04 23:14:42 +0000324void Writer::calculateCustomSections() {
325 log("calculateCustomSections");
326 bool StripDebug = Config->StripDebug || Config->StripAll;
327 for (ObjFile *File : Symtab->ObjectFiles) {
328 for (InputSection *Section : File->CustomSections) {
329 StringRef Name = Section->getName();
330 // These custom sections are known the linker and synthesized rather than
331 // blindly copied
Thomas Lively2a0868f2019-01-17 02:29:41 +0000332 if (Name == "linking" || Name == "name" || Name == "producers" ||
333 Name.startswith("reloc."))
Sam Cleggd177ab22018-05-04 23:14:42 +0000334 continue;
335 // .. or it is a debug section
336 if (StripDebug && Name.startswith(".debug_"))
337 continue;
338 CustomSectionMapping[Name].push_back(Section);
339 }
340 }
341}
342
Sam Clegg80ba4382018-04-10 16:12:49 +0000343void Writer::createCustomSections() {
344 log("createCustomSections");
Sam Clegg80ba4382018-04-10 16:12:49 +0000345 for (auto &Pair : CustomSectionMapping) {
346 StringRef Name = Pair.first();
Sam Cleggd177ab22018-05-04 23:14:42 +0000347
348 auto P = CustomSectionSymbols.find(Name);
349 if (P != CustomSectionSymbols.end()) {
350 uint32_t SectionIndex = OutputSections.size();
351 P->second->setOutputSectionIndex(SectionIndex);
352 }
353
Nicola Zaghene7245b42018-05-15 13:36:20 +0000354 LLVM_DEBUG(dbgs() << "createCustomSection: " << Name << "\n");
Sam Clegg80ba4382018-04-10 16:12:49 +0000355 OutputSections.push_back(make<CustomSection>(Name, Pair.second));
356 }
357}
358
Sam Cleggc94d3932017-11-17 18:14:09 +0000359void Writer::createElemSection() {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000360 if (IndirectFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000361 return;
362
363 SyntheticSection *Section = createSyntheticSection(WASM_SEC_ELEM);
364 raw_ostream &OS = Section->getStream();
365
366 writeUleb128(OS, 1, "segment count");
367 writeUleb128(OS, 0, "table index");
368 WasmInitExpr InitExpr;
Sam Cleggbfb75342018-11-15 00:37:21 +0000369 if (Config->Pic) {
Thomas Lively25ff8932019-01-08 06:25:55 +0000370 InitExpr.Opcode = WASM_OPCODE_GLOBAL_GET;
Sam Clegg2dad4e22018-11-15 18:15:54 +0000371 InitExpr.Value.Global = WasmSym::TableBase->getGlobalIndex();
Sam Cleggbfb75342018-11-15 00:37:21 +0000372 } else {
373 InitExpr.Opcode = WASM_OPCODE_I32_CONST;
374 InitExpr.Value.Int32 = TableBase;
375 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000376 writeInitExpr(OS, InitExpr);
Sam Cleggfc1a9122017-12-11 22:00:56 +0000377 writeUleb128(OS, IndirectFunctions.size(), "elem count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000378
Sam Cleggbfb75342018-11-15 00:37:21 +0000379 uint32_t TableIndex = TableBase;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000380 for (const FunctionSymbol *Sym : IndirectFunctions) {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000381 assert(Sym->getTableIndex() == TableIndex);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000382 writeUleb128(OS, Sym->getFunctionIndex(), "function index");
Sam Cleggfc1a9122017-12-11 22:00:56 +0000383 ++TableIndex;
384 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000385}
386
387void Writer::createCodeSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000388 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000389 return;
390
391 log("createCodeSection");
392
Sam Clegg9f934222018-02-21 18:29:23 +0000393 auto Section = make<CodeSection>(InputFunctions);
Sam Cleggc94d3932017-11-17 18:14:09 +0000394 OutputSections.push_back(Section);
395}
396
397void Writer::createDataSection() {
398 if (!Segments.size())
399 return;
400
401 log("createDataSection");
402 auto Section = make<DataSection>(Segments);
403 OutputSections.push_back(Section);
404}
405
Sam Cleggd451da12017-12-19 19:56:27 +0000406// Create relocations sections in the final output.
Sam Cleggc94d3932017-11-17 18:14:09 +0000407// These are only created when relocatable output is requested.
408void Writer::createRelocSections() {
409 log("createRelocSections");
410 // Don't use iterator here since we are adding to OutputSection
411 size_t OrigSize = OutputSections.size();
Rui Ueyamaffa650a2018-04-24 23:09:57 +0000412 for (size_t I = 0; I < OrigSize; I++) {
413 OutputSection *OSec = OutputSections[I];
Rui Ueyama37254062018-02-28 00:01:31 +0000414 uint32_t Count = OSec->numRelocations();
Sam Cleggc94d3932017-11-17 18:14:09 +0000415 if (!Count)
416 continue;
417
Rui Ueyama37254062018-02-28 00:01:31 +0000418 StringRef Name;
419 if (OSec->Type == WASM_SEC_DATA)
420 Name = "reloc.DATA";
421 else if (OSec->Type == WASM_SEC_CODE)
422 Name = "reloc.CODE";
Sam Cleggd177ab22018-05-04 23:14:42 +0000423 else if (OSec->Type == WASM_SEC_CUSTOM)
424 Name = Saver.save("reloc." + OSec->Name);
Sam Cleggc94d3932017-11-17 18:14:09 +0000425 else
Sam Cleggd177ab22018-05-04 23:14:42 +0000426 llvm_unreachable(
427 "relocations only supported for code, data, or custom sections");
Sam Cleggc94d3932017-11-17 18:14:09 +0000428
Rui Ueyama37254062018-02-28 00:01:31 +0000429 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, Name);
Sam Cleggc94d3932017-11-17 18:14:09 +0000430 raw_ostream &OS = Section->getStream();
Rui Ueyamaffa650a2018-04-24 23:09:57 +0000431 writeUleb128(OS, I, "reloc section");
Sam Cleggc94d3932017-11-17 18:14:09 +0000432 writeUleb128(OS, Count, "reloc count");
Rui Ueyama37254062018-02-28 00:01:31 +0000433 OSec->writeRelocations(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000434 }
435}
436
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000437static uint32_t getWasmFlags(const Symbol *Sym) {
438 uint32_t Flags = 0;
439 if (Sym->isLocal())
440 Flags |= WASM_SYMBOL_BINDING_LOCAL;
441 if (Sym->isWeak())
442 Flags |= WASM_SYMBOL_BINDING_WEAK;
443 if (Sym->isHidden())
444 Flags |= WASM_SYMBOL_VISIBILITY_HIDDEN;
445 if (Sym->isUndefined())
446 Flags |= WASM_SYMBOL_UNDEFINED;
447 return Flags;
448}
449
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000450// Some synthetic sections (e.g. "name" and "linking") have subsections.
451// Just like the synthetic sections themselves these need to be created before
452// they can be written out (since they are preceded by their length). This
453// class is used to create subsections and then write them into the stream
454// of the parent section.
455class SubSection {
456public:
457 explicit SubSection(uint32_t Type) : Type(Type) {}
458
459 void writeTo(raw_ostream &To) {
460 OS.flush();
Rui Ueyama67769102018-02-28 03:38:14 +0000461 writeUleb128(To, Type, "subsection type");
462 writeUleb128(To, Body.size(), "subsection size");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000463 To.write(Body.data(), Body.size());
464 }
465
466private:
467 uint32_t Type;
468 std::string Body;
469
470public:
471 raw_string_ostream OS{Body};
472};
473
Sam Cleggbfb75342018-11-15 00:37:21 +0000474// Create the custom "dylink" section containing information for the dynamic
475// linker.
476// See
477// https://github.com/WebAssembly/tool-conventions/blob/master/DynamicLinking.md
478void Writer::createDylinkSection() {
479 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "dylink");
480 raw_ostream &OS = Section->getStream();
481
482 writeUleb128(OS, MemSize, "MemSize");
Sam Clegg6320efb2019-01-16 01:43:21 +0000483 writeUleb128(OS, MemAlign, "MemAlign");
Sam Cleggbfb75342018-11-15 00:37:21 +0000484 writeUleb128(OS, IndirectFunctions.size(), "TableSize");
485 writeUleb128(OS, 0, "TableAlign");
Sam Clegge01c6462018-12-12 23:44:59 +0000486 writeUleb128(OS, 0, "Needed"); // TODO: Support "needed" shared libraries
Sam Cleggbfb75342018-11-15 00:37:21 +0000487}
488
Sam Clegg49ed9262017-12-01 00:53:21 +0000489// Create the custom "linking" section containing linker metadata.
Sam Cleggc94d3932017-11-17 18:14:09 +0000490// This is only created when relocatable output is requested.
491void Writer::createLinkingSection() {
492 SyntheticSection *Section =
493 createSyntheticSection(WASM_SEC_CUSTOM, "linking");
494 raw_ostream &OS = Section->getStream();
495
Sam Clegg2b8b1792018-04-26 18:17:21 +0000496 writeUleb128(OS, WasmMetadataVersion, "Version");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000497
Sam Clegg93102972018-02-23 05:08:53 +0000498 if (!SymtabEntries.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000499 SubSection Sub(WASM_SYMBOL_TABLE);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000500 writeUleb128(Sub.OS, SymtabEntries.size(), "num symbols");
501
Sam Clegg93102972018-02-23 05:08:53 +0000502 for (const Symbol *Sym : SymtabEntries) {
503 assert(Sym->isDefined() || Sym->isUndefined());
504 WasmSymbolType Kind = Sym->getWasmType();
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000505 uint32_t Flags = getWasmFlags(Sym);
506
Sam Clegg8518e7d2018-03-01 18:06:39 +0000507 writeU8(Sub.OS, Kind, "sym kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000508 writeUleb128(Sub.OS, Flags, "sym flags");
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000509
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000510 if (auto *F = dyn_cast<FunctionSymbol>(Sym)) {
511 writeUleb128(Sub.OS, F->getFunctionIndex(), "index");
Sam Clegg93102972018-02-23 05:08:53 +0000512 if (Sym->isDefined())
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000513 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000514 } else if (auto *G = dyn_cast<GlobalSymbol>(Sym)) {
515 writeUleb128(Sub.OS, G->getGlobalIndex(), "index");
516 if (Sym->isDefined())
517 writeStr(Sub.OS, Sym->getName(), "sym name");
Heejin Ahne915a712018-12-08 06:17:43 +0000518 } else if (auto *E = dyn_cast<EventSymbol>(Sym)) {
519 writeUleb128(Sub.OS, E->getEventIndex(), "index");
520 if (Sym->isDefined())
521 writeStr(Sub.OS, Sym->getName(), "sym name");
Andrea Di Biagio25c1a2f2018-05-05 10:53:31 +0000522 } else if (isa<DataSymbol>(Sym)) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000523 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegg93102972018-02-23 05:08:53 +0000524 if (auto *DataSym = dyn_cast<DefinedData>(Sym)) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000525 writeUleb128(Sub.OS, DataSym->getOutputSegmentIndex(), "index");
526 writeUleb128(Sub.OS, DataSym->getOutputSegmentOffset(),
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000527 "data offset");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000528 writeUleb128(Sub.OS, DataSym->getSize(), "data size");
Sam Clegg93102972018-02-23 05:08:53 +0000529 }
Sam Cleggd177ab22018-05-04 23:14:42 +0000530 } else {
531 auto *S = cast<SectionSymbol>(Sym);
532 writeUleb128(Sub.OS, S->getOutputSectionIndex(), "sym section index");
Sam Clegg93102972018-02-23 05:08:53 +0000533 }
Sam Cleggd3052d52018-01-18 23:40:49 +0000534 }
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000535
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000536 Sub.writeTo(OS);
Sam Cleggd3052d52018-01-18 23:40:49 +0000537 }
538
Sam Clegg0d0dd392017-12-19 17:09:45 +0000539 if (Segments.size()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000540 SubSection Sub(WASM_SEGMENT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000541 writeUleb128(Sub.OS, Segments.size(), "num data segments");
Sam Cleggc94d3932017-11-17 18:14:09 +0000542 for (const OutputSegment *S : Segments) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000543 writeStr(Sub.OS, S->Name, "segment name");
544 writeUleb128(Sub.OS, S->Alignment, "alignment");
545 writeUleb128(Sub.OS, 0, "flags");
Sam Cleggc94d3932017-11-17 18:14:09 +0000546 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000547 Sub.writeTo(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000548 }
Sam Clegg0d0dd392017-12-19 17:09:45 +0000549
Sam Clegg0d0dd392017-12-19 17:09:45 +0000550 if (!InitFunctions.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000551 SubSection Sub(WASM_INIT_FUNCS);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000552 writeUleb128(Sub.OS, InitFunctions.size(), "num init functions");
Sam Clegg93102972018-02-23 05:08:53 +0000553 for (const WasmInitEntry &F : InitFunctions) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000554 writeUleb128(Sub.OS, F.Priority, "priority");
555 writeUleb128(Sub.OS, F.Sym->getOutputSymbolIndex(), "function index");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000556 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000557 Sub.writeTo(OS);
Sam Clegg0d0dd392017-12-19 17:09:45 +0000558 }
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000559
Nicholas Wilsondbd90bf2018-03-07 13:28:16 +0000560 struct ComdatEntry {
561 unsigned Kind;
562 uint32_t Index;
563 };
564 std::map<StringRef, std::vector<ComdatEntry>> Comdats;
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000565
Sam Clegg9f934222018-02-21 18:29:23 +0000566 for (const InputFunction *F : InputFunctions) {
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000567 StringRef Comdat = F->getComdatName();
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000568 if (!Comdat.empty())
569 Comdats[Comdat].emplace_back(
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000570 ComdatEntry{WASM_COMDAT_FUNCTION, F->getFunctionIndex()});
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000571 }
572 for (uint32_t I = 0; I < Segments.size(); ++I) {
Sam Cleggf98bccf2018-01-13 15:57:48 +0000573 const auto &InputSegments = Segments[I]->InputSegments;
574 if (InputSegments.empty())
575 continue;
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000576 StringRef Comdat = InputSegments[0]->getComdatName();
Sam Clegga697df522018-01-13 15:59:53 +0000577#ifndef NDEBUG
Sam Cleggf98bccf2018-01-13 15:57:48 +0000578 for (const InputSegment *IS : InputSegments)
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000579 assert(IS->getComdatName() == Comdat);
Sam Clegga697df522018-01-13 15:59:53 +0000580#endif
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000581 if (!Comdat.empty())
582 Comdats[Comdat].emplace_back(ComdatEntry{WASM_COMDAT_DATA, I});
583 }
584
585 if (!Comdats.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000586 SubSection Sub(WASM_COMDAT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000587 writeUleb128(Sub.OS, Comdats.size(), "num comdats");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000588 for (const auto &C : Comdats) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000589 writeStr(Sub.OS, C.first, "comdat name");
590 writeUleb128(Sub.OS, 0, "comdat flags"); // flags for future use
591 writeUleb128(Sub.OS, C.second.size(), "num entries");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000592 for (const ComdatEntry &Entry : C.second) {
Sam Clegg8518e7d2018-03-01 18:06:39 +0000593 writeU8(Sub.OS, Entry.Kind, "entry kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000594 writeUleb128(Sub.OS, Entry.Index, "entry index");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000595 }
596 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000597 Sub.writeTo(OS);
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000598 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000599}
600
601// Create the custom "name" section containing debug symbol names.
602void Writer::createNameSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000603 unsigned NumNames = NumImportedFunctions;
Sam Clegg9f934222018-02-21 18:29:23 +0000604 for (const InputFunction *F : InputFunctions)
Nicholas Wilson6c7fe302018-04-20 17:09:18 +0000605 if (!F->getName().empty() || !F->getDebugName().empty())
Sam Clegg1963d712018-01-17 20:19:04 +0000606 ++NumNames;
Sam Cleggc94d3932017-11-17 18:14:09 +0000607
Sam Clegg1963d712018-01-17 20:19:04 +0000608 if (NumNames == 0)
609 return;
Sam Clegg50686852018-01-12 18:35:13 +0000610
Sam Cleggc94d3932017-11-17 18:14:09 +0000611 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "name");
612
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000613 SubSection Sub(WASM_NAMES_FUNCTION);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000614 writeUleb128(Sub.OS, NumNames, "name count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000615
Sam Clegg93102972018-02-23 05:08:53 +0000616 // Names must appear in function index order. As it happens ImportedSymbols
617 // and InputFunctions are numbered in order with imported functions coming
Sam Clegg1963d712018-01-17 20:19:04 +0000618 // first.
Sam Clegg93102972018-02-23 05:08:53 +0000619 for (const Symbol *S : ImportedSymbols) {
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000620 if (auto *F = dyn_cast<FunctionSymbol>(S)) {
621 writeUleb128(Sub.OS, F->getFunctionIndex(), "func index");
Sam Clegg37125f02018-11-09 16:57:41 +0000622 writeStr(Sub.OS, toString(*S), "symbol name");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000623 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000624 }
Sam Clegg9f934222018-02-21 18:29:23 +0000625 for (const InputFunction *F : InputFunctions) {
Sam Clegg1963d712018-01-17 20:19:04 +0000626 if (!F->getName().empty()) {
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000627 writeUleb128(Sub.OS, F->getFunctionIndex(), "func index");
Nicholas Wilson6c7fe302018-04-20 17:09:18 +0000628 if (!F->getDebugName().empty()) {
629 writeStr(Sub.OS, F->getDebugName(), "symbol name");
630 } else {
Sam Clegg37125f02018-11-09 16:57:41 +0000631 writeStr(Sub.OS, maybeDemangleSymbol(F->getName()), "symbol name");
Nicholas Wilson6c7fe302018-04-20 17:09:18 +0000632 }
Sam Clegg1963d712018-01-17 20:19:04 +0000633 }
634 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000635
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000636 Sub.writeTo(Section->getStream());
Sam Cleggc94d3932017-11-17 18:14:09 +0000637}
638
Thomas Lively2a0868f2019-01-17 02:29:41 +0000639void Writer::createProducersSection() {
640 SmallVector<std::pair<std::string, std::string>, 8> Languages;
641 SmallVector<std::pair<std::string, std::string>, 8> Tools;
642 SmallVector<std::pair<std::string, std::string>, 8> SDKs;
643 for (ObjFile *File : Symtab->ObjectFiles) {
644 const WasmProducerInfo &Info = File->getWasmObj()->getProducerInfo();
645 for (auto &Producers : {std::make_pair(&Info.Languages, &Languages),
646 std::make_pair(&Info.Tools, &Tools),
647 std::make_pair(&Info.SDKs, &SDKs)})
648 for (auto &Producer : *Producers.first)
649 if (Producers.second->end() ==
650 std::find_if(Producers.second->begin(), Producers.second->end(),
651 [&](std::pair<std::string, std::string> Seen) {
652 return Seen.first == Producer.first;
653 }))
654 Producers.second->push_back(Producer);
655 }
656 int FieldCount =
657 int(!Languages.empty()) + int(!Tools.empty()) + int(!SDKs.empty());
658 if (FieldCount == 0)
659 return;
660 SyntheticSection *Section =
661 createSyntheticSection(WASM_SEC_CUSTOM, "producers");
662 auto &OS = Section->getStream();
663 writeUleb128(OS, FieldCount, "field count");
664 for (auto &Field :
665 {std::make_pair("language", Languages),
666 std::make_pair("processed-by", Tools), std::make_pair("sdk", SDKs)}) {
667 if (Field.second.empty())
668 continue;
669 writeStr(OS, Field.first, "field name");
670 writeUleb128(OS, Field.second.size(), "number of entries");
671 for (auto &Entry : Field.second) {
672 writeStr(OS, Entry.first, "producer name");
673 writeStr(OS, Entry.second, "producer version");
674 }
675 }
676}
677
Sam Cleggc94d3932017-11-17 18:14:09 +0000678void Writer::writeHeader() {
679 memcpy(Buffer->getBufferStart(), Header.data(), Header.size());
680}
681
682void Writer::writeSections() {
683 uint8_t *Buf = Buffer->getBufferStart();
684 parallelForEach(OutputSections, [Buf](OutputSection *S) { S->writeTo(Buf); });
685}
686
687// Fix the memory layout of the output binary. This assigns memory offsets
Sam Clegg49ed9262017-12-01 00:53:21 +0000688// to each of the input data sections as well as the explicit stack region.
Sam Clegga0f095e2018-05-03 17:21:53 +0000689// The default memory layout is as follows, from low to high.
690//
Sam Cleggf0d433d2018-02-02 22:59:56 +0000691// - initialized data (starting at Config->GlobalBase)
692// - BSS data (not currently implemented in llvm)
693// - explicit stack (Config->ZStackSize)
694// - heap start / unallocated
Sam Clegga0f095e2018-05-03 17:21:53 +0000695//
696// The --stack-first option means that stack is placed before any static data.
Heejin Ahn4821ebf2018-08-29 21:03:16 +0000697// This can be useful since it means that stack overflow traps immediately
698// rather than overwriting global data, but also increases code size since all
699// static data loads and stores requires larger offsets.
Sam Cleggc94d3932017-11-17 18:14:09 +0000700void Writer::layoutMemory() {
Sam Cleggc94d3932017-11-17 18:14:09 +0000701 createOutputSegments();
702
Sam Clegga0f095e2018-05-03 17:21:53 +0000703 uint32_t MemoryPtr = 0;
704
705 auto PlaceStack = [&]() {
Sam Cleggbfb75342018-11-15 00:37:21 +0000706 if (Config->Relocatable || Config->Shared)
Sam Clegga0f095e2018-05-03 17:21:53 +0000707 return;
708 MemoryPtr = alignTo(MemoryPtr, kStackAlignment);
709 if (Config->ZStackSize != alignTo(Config->ZStackSize, kStackAlignment))
710 error("stack size must be " + Twine(kStackAlignment) + "-byte aligned");
711 log("mem: stack size = " + Twine(Config->ZStackSize));
712 log("mem: stack base = " + Twine(MemoryPtr));
713 MemoryPtr += Config->ZStackSize;
Sam Clegg2dad4e22018-11-15 18:15:54 +0000714 auto *SP = cast<DefinedGlobal>(WasmSym::StackPointer);
715 SP->Global->Global.InitExpr.Value.Int32 = MemoryPtr;
Sam Clegga0f095e2018-05-03 17:21:53 +0000716 log("mem: stack top = " + Twine(MemoryPtr));
717 };
718
719 if (Config->StackFirst) {
720 PlaceStack();
721 } else {
722 MemoryPtr = Config->GlobalBase;
723 log("mem: global base = " + Twine(Config->GlobalBase));
724 }
725
726 uint32_t DataStart = MemoryPtr;
727
Sam Cleggf0d433d2018-02-02 22:59:56 +0000728 // Arbitrarily set __dso_handle handle to point to the start of the data
729 // segments.
730 if (WasmSym::DsoHandle)
Sam Clegga0f095e2018-05-03 17:21:53 +0000731 WasmSym::DsoHandle->setVirtualAddress(DataStart);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000732
Sam Cleggbfb75342018-11-15 00:37:21 +0000733 MemAlign = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000734 for (OutputSegment *Seg : Segments) {
Sam Cleggbfb75342018-11-15 00:37:21 +0000735 MemAlign = std::max(MemAlign, Seg->Alignment);
Sam Clegg622ad042019-01-17 22:09:09 +0000736 MemoryPtr = alignTo(MemoryPtr, 1ULL << Seg->Alignment);
Sam Cleggc94d3932017-11-17 18:14:09 +0000737 Seg->StartVA = MemoryPtr;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000738 log(formatv("mem: {0,-15} offset={1,-8} size={2,-8} align={3}", Seg->Name,
739 MemoryPtr, Seg->Size, Seg->Alignment));
Sam Cleggc94d3932017-11-17 18:14:09 +0000740 MemoryPtr += Seg->Size;
741 }
742
Sam Cleggf0d433d2018-02-02 22:59:56 +0000743 // TODO: Add .bss space here.
Sam Clegg37a4a8a2018-02-07 03:04:53 +0000744 if (WasmSym::DataEnd)
745 WasmSym::DataEnd->setVirtualAddress(MemoryPtr);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000746
Sam Clegga0f095e2018-05-03 17:21:53 +0000747 log("mem: static data = " + Twine(MemoryPtr - DataStart));
Sam Cleggc94d3932017-11-17 18:14:09 +0000748
Sam Clegg2dad4e22018-11-15 18:15:54 +0000749 if (Config->Shared) {
750 MemSize = MemoryPtr;
751 return;
752 }
753
Sam Clegga0f095e2018-05-03 17:21:53 +0000754 if (!Config->StackFirst)
755 PlaceStack();
756
757 // Set `__heap_base` to directly follow the end of the stack or global data.
758 // The fact that this comes last means that a malloc/brk implementation
759 // can grow the heap at runtime.
Sam Cleggc94d3932017-11-17 18:14:09 +0000760 if (!Config->Relocatable) {
Sam Cleggf0d433d2018-02-02 22:59:56 +0000761 WasmSym::HeapBase->setVirtualAddress(MemoryPtr);
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000762 log("mem: heap base = " + Twine(MemoryPtr));
Sam Cleggc94d3932017-11-17 18:14:09 +0000763 }
764
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000765 if (Config->InitialMemory != 0) {
766 if (Config->InitialMemory != alignTo(Config->InitialMemory, WasmPageSize))
767 error("initial memory must be " + Twine(WasmPageSize) + "-byte aligned");
768 if (MemoryPtr > Config->InitialMemory)
769 error("initial memory too small, " + Twine(MemoryPtr) + " bytes needed");
770 else
771 MemoryPtr = Config->InitialMemory;
772 }
Sam Cleggbfb75342018-11-15 00:37:21 +0000773 MemSize = MemoryPtr;
774 NumMemoryPages = alignTo(MemoryPtr, WasmPageSize) / WasmPageSize;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000775 log("mem: total pages = " + Twine(NumMemoryPages));
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000776
777 if (Config->MaxMemory != 0) {
778 if (Config->MaxMemory != alignTo(Config->MaxMemory, WasmPageSize))
779 error("maximum memory must be " + Twine(WasmPageSize) + "-byte aligned");
780 if (MemoryPtr > Config->MaxMemory)
781 error("maximum memory too small, " + Twine(MemoryPtr) + " bytes needed");
782 MaxMemoryPages = Config->MaxMemory / WasmPageSize;
783 log("mem: max pages = " + Twine(MaxMemoryPages));
784 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000785}
786
787SyntheticSection *Writer::createSyntheticSection(uint32_t Type,
Sam Cleggc375e4e2018-01-10 19:18:22 +0000788 StringRef Name) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000789 auto Sec = make<SyntheticSection>(Type, Name);
Sam Cleggab2ac292017-12-20 05:14:48 +0000790 log("createSection: " + toString(*Sec));
Sam Cleggc94d3932017-11-17 18:14:09 +0000791 OutputSections.push_back(Sec);
792 return Sec;
793}
794
795void Writer::createSections() {
796 // Known sections
Sam Cleggbfb75342018-11-15 00:37:21 +0000797 if (Config->Pic)
798 createDylinkSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000799 createTypeSection();
800 createImportSection();
801 createFunctionSection();
802 createTableSection();
803 createMemorySection();
804 createGlobalSection();
Heejin Ahne915a712018-12-08 06:17:43 +0000805 createEventSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000806 createExportSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000807 createElemSection();
808 createCodeSection();
809 createDataSection();
Sam Clegg80ba4382018-04-10 16:12:49 +0000810 createCustomSections();
Sam Cleggc94d3932017-11-17 18:14:09 +0000811
812 // Custom sections
Sam Clegg99eb42c2018-02-27 23:58:03 +0000813 if (Config->Relocatable) {
Sam Clegg99eb42c2018-02-27 23:58:03 +0000814 createLinkingSection();
Nicholas Wilson94d3b162018-03-05 12:33:58 +0000815 createRelocSections();
Sam Clegg99eb42c2018-02-27 23:58:03 +0000816 }
Thomas Lively2a0868f2019-01-17 02:29:41 +0000817
Sam Cleggc94d3932017-11-17 18:14:09 +0000818 if (!Config->StripDebug && !Config->StripAll)
819 createNameSection();
820
Thomas Lively2a0868f2019-01-17 02:29:41 +0000821 if (!Config->StripAll)
822 createProducersSection();
823
Sam Cleggc94d3932017-11-17 18:14:09 +0000824 for (OutputSection *S : OutputSections) {
825 S->setOffset(FileSize);
826 S->finalizeContents();
827 FileSize += S->getSize();
828 }
829}
830
Sam Cleggc94d3932017-11-17 18:14:09 +0000831void Writer::calculateImports() {
Sam Clegg574d7ce2017-12-15 19:23:49 +0000832 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000833 if (!Sym->isUndefined())
834 continue;
835 if (isa<DataSymbol>(Sym))
836 continue;
837 if (Sym->isWeak() && !Config->Relocatable)
Sam Clegg574d7ce2017-12-15 19:23:49 +0000838 continue;
Nicholas Wilsona1e299f2018-04-20 17:18:06 +0000839 if (!Sym->isLive())
840 continue;
Sam Cleggc729c1b2018-05-30 18:07:52 +0000841 if (!Sym->IsUsedInRegularObj)
842 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000843
Nicola Zaghene7245b42018-05-15 13:36:20 +0000844 LLVM_DEBUG(dbgs() << "import: " << Sym->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000845 ImportedSymbols.emplace_back(Sym);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000846 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
847 F->setFunctionIndex(NumImportedFunctions++);
Heejin Ahne915a712018-12-08 06:17:43 +0000848 else if (auto *G = dyn_cast<GlobalSymbol>(Sym))
849 G->setGlobalIndex(NumImportedGlobals++);
Sam Clegg93102972018-02-23 05:08:53 +0000850 else
Heejin Ahne915a712018-12-08 06:17:43 +0000851 cast<EventSymbol>(Sym)->setEventIndex(NumImportedEvents++);
Sam Cleggc94d3932017-11-17 18:14:09 +0000852 }
853}
854
Sam Cleggd3052d52018-01-18 23:40:49 +0000855void Writer::calculateExports() {
Sam Clegg93102972018-02-23 05:08:53 +0000856 if (Config->Relocatable)
857 return;
Sam Cleggf0d433d2018-02-02 22:59:56 +0000858
Sam Cleggd6beb322018-05-10 18:10:34 +0000859 if (!Config->Relocatable && !Config->ImportMemory)
860 Exports.push_back(WasmExport{"memory", WASM_EXTERNAL_MEMORY, 0});
861
862 if (!Config->Relocatable && Config->ExportTable)
863 Exports.push_back(WasmExport{kFunctionTableName, WASM_EXTERNAL_TABLE, 0});
864
865 unsigned FakeGlobalIndex = NumImportedGlobals + InputGlobals.size();
866
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000867 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Cleggce004bf2018-06-28 17:04:58 +0000868 if (!Sym->isExported())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000869 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000870 if (!Sym->isLive())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000871 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000872
Sam Cleggd6beb322018-05-10 18:10:34 +0000873 StringRef Name = Sym->getName();
874 WasmExport Export;
875 if (auto *F = dyn_cast<DefinedFunction>(Sym)) {
876 Export = {Name, WASM_EXTERNAL_FUNCTION, F->getFunctionIndex()};
877 } else if (auto *G = dyn_cast<DefinedGlobal>(Sym)) {
Sam Clegg177b4582018-06-07 01:27:07 +0000878 // TODO(sbc): Remove this check once to mutable global proposal is
879 // implement in all major browsers.
880 // See: https://github.com/WebAssembly/mutable-global
881 if (G->getGlobalType()->Mutable) {
882 // Only the __stack_pointer should ever be create as mutable.
883 assert(G == WasmSym::StackPointer);
884 continue;
885 }
Sam Cleggd6beb322018-05-10 18:10:34 +0000886 Export = {Name, WASM_EXTERNAL_GLOBAL, G->getGlobalIndex()};
Heejin Ahne915a712018-12-08 06:17:43 +0000887 } else if (auto *E = dyn_cast<DefinedEvent>(Sym)) {
888 Export = {Name, WASM_EXTERNAL_EVENT, E->getEventIndex()};
Sam Cleggd6beb322018-05-10 18:10:34 +0000889 } else {
890 auto *D = cast<DefinedData>(Sym);
Sam Clegg93102972018-02-23 05:08:53 +0000891 DefinedFakeGlobals.emplace_back(D);
Sam Cleggd6beb322018-05-10 18:10:34 +0000892 Export = {Name, WASM_EXTERNAL_GLOBAL, FakeGlobalIndex++};
893 }
894
Nicola Zaghene7245b42018-05-15 13:36:20 +0000895 LLVM_DEBUG(dbgs() << "Export: " << Name << "\n");
Sam Cleggd6beb322018-05-10 18:10:34 +0000896 Exports.push_back(Export);
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000897 }
Sam Clegg93102972018-02-23 05:08:53 +0000898}
899
900void Writer::assignSymtab() {
901 if (!Config->Relocatable)
902 return;
903
Sam Cleggd177ab22018-05-04 23:14:42 +0000904 StringMap<uint32_t> SectionSymbolIndices;
905
Sam Clegg93102972018-02-23 05:08:53 +0000906 unsigned SymbolIndex = SymtabEntries.size();
Sam Cleggd3052d52018-01-18 23:40:49 +0000907 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000908 LLVM_DEBUG(dbgs() << "Symtab entries: " << File->getName() << "\n");
Sam Cleggd3052d52018-01-18 23:40:49 +0000909 for (Symbol *Sym : File->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000910 if (Sym->getFile() != File)
Sam Cleggd3052d52018-01-18 23:40:49 +0000911 continue;
Sam Cleggd177ab22018-05-04 23:14:42 +0000912
913 if (auto *S = dyn_cast<SectionSymbol>(Sym)) {
914 StringRef Name = S->getName();
915 if (CustomSectionMapping.count(Name) == 0)
916 continue;
917
918 auto SSI = SectionSymbolIndices.find(Name);
919 if (SSI != SectionSymbolIndices.end()) {
920 Sym->setOutputSymbolIndex(SSI->second);
921 continue;
922 }
923
924 SectionSymbolIndices[Name] = SymbolIndex;
925 CustomSectionSymbols[Name] = cast<SectionSymbol>(Sym);
926
927 Sym->markLive();
928 }
929
Nicholas Wilson06e0d172018-03-07 11:15:47 +0000930 // (Since this is relocatable output, GC is not performed so symbols must
931 // be live.)
932 assert(Sym->isLive());
Sam Clegg93102972018-02-23 05:08:53 +0000933 Sym->setOutputSymbolIndex(SymbolIndex++);
934 SymtabEntries.emplace_back(Sym);
Sam Cleggd3052d52018-01-18 23:40:49 +0000935 }
936 }
937
Sam Clegg93102972018-02-23 05:08:53 +0000938 // For the moment, relocatable output doesn't contain any synthetic functions,
939 // so no need to look through the Symtab for symbols not referenced by
940 // Symtab->ObjectFiles.
Sam Cleggd3052d52018-01-18 23:40:49 +0000941}
942
Sam Cleggc375e4e2018-01-10 19:18:22 +0000943uint32_t Writer::lookupType(const WasmSignature &Sig) {
Sam Clegg8d027d62018-01-10 20:12:26 +0000944 auto It = TypeIndices.find(Sig);
945 if (It == TypeIndices.end()) {
Sam Cleggc375e4e2018-01-10 19:18:22 +0000946 error("type not found: " + toString(Sig));
Sam Clegg8d027d62018-01-10 20:12:26 +0000947 return 0;
948 }
949 return It->second;
Sam Cleggc375e4e2018-01-10 19:18:22 +0000950}
951
952uint32_t Writer::registerType(const WasmSignature &Sig) {
Sam Cleggb8621592017-11-30 01:40:08 +0000953 auto Pair = TypeIndices.insert(std::make_pair(Sig, Types.size()));
Sam Cleggc375e4e2018-01-10 19:18:22 +0000954 if (Pair.second) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000955 LLVM_DEBUG(dbgs() << "type " << toString(Sig) << "\n");
Sam Cleggb8621592017-11-30 01:40:08 +0000956 Types.push_back(&Sig);
Sam Cleggc375e4e2018-01-10 19:18:22 +0000957 }
Sam Cleggb8621592017-11-30 01:40:08 +0000958 return Pair.first->second;
959}
960
Sam Cleggc94d3932017-11-17 18:14:09 +0000961void Writer::calculateTypes() {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000962 // The output type section is the union of the following sets:
963 // 1. Any signature used in the TYPE relocation
964 // 2. The signatures of all imported functions
965 // 3. The signatures of all defined functions
Heejin Ahne915a712018-12-08 06:17:43 +0000966 // 4. The signatures of all imported events
967 // 5. The signatures of all defined events
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000968
Sam Cleggc94d3932017-11-17 18:14:09 +0000969 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000970 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
971 for (uint32_t I = 0; I < Types.size(); I++)
972 if (File->TypeIsUsed[I])
973 File->TypeMap[I] = registerType(Types[I]);
Sam Cleggc94d3932017-11-17 18:14:09 +0000974 }
Sam Clegg50686852018-01-12 18:35:13 +0000975
Heejin Ahne915a712018-12-08 06:17:43 +0000976 for (const Symbol *Sym : ImportedSymbols) {
Sam Clegg93102972018-02-23 05:08:53 +0000977 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
Heejin Ahne915a712018-12-08 06:17:43 +0000978 registerType(*F->Signature);
979 else if (auto *E = dyn_cast<EventSymbol>(Sym))
980 registerType(*E->Signature);
981 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000982
Sam Clegg9f934222018-02-21 18:29:23 +0000983 for (const InputFunction *F : InputFunctions)
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000984 registerType(F->Signature);
Heejin Ahne915a712018-12-08 06:17:43 +0000985
986 for (const InputEvent *E : InputEvents)
987 registerType(E->Signature);
Sam Cleggc94d3932017-11-17 18:14:09 +0000988}
989
Sam Clegg8d146bb2018-01-09 23:56:44 +0000990void Writer::assignIndexes() {
Heejin Ahnaeaab992018-11-19 23:21:25 +0000991 assert(InputFunctions.empty());
992 uint32_t FunctionIndex = NumImportedFunctions;
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000993 auto AddDefinedFunction = [&](InputFunction *Func) {
994 if (!Func->Live)
995 return;
996 InputFunctions.emplace_back(Func);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000997 Func->setFunctionIndex(FunctionIndex++);
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000998 };
999
Nicholas Wilson5639da82018-03-12 15:44:07 +00001000 for (InputFunction *Func : Symtab->SyntheticFunctions)
1001 AddDefinedFunction(Func);
1002
Sam Clegg87e61922018-01-08 23:39:11 +00001003 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001004 LLVM_DEBUG(dbgs() << "Functions: " << File->getName() << "\n");
Nicholas Wilsonebda41f2018-03-09 16:43:05 +00001005 for (InputFunction *Func : File->Functions)
1006 AddDefinedFunction(Func);
Sam Clegg8d146bb2018-01-09 23:56:44 +00001007 }
1008
Sam Cleggbfb75342018-11-15 00:37:21 +00001009 uint32_t TableIndex = TableBase;
Sam Clegg6c4dbfee2018-02-23 04:59:57 +00001010 auto HandleRelocs = [&](InputChunk *Chunk) {
1011 if (!Chunk->Live)
1012 return;
1013 ObjFile *File = Chunk->File;
1014 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
Sam Clegg93102972018-02-23 05:08:53 +00001015 for (const WasmRelocation &Reloc : Chunk->getRelocations()) {
Sam Clegg6c4dbfee2018-02-23 04:59:57 +00001016 if (Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_I32 ||
1017 Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_SLEB) {
1018 FunctionSymbol *Sym = File->getFunctionSymbol(Reloc.Index);
Sam Clegge3f3ccf2018-03-12 19:56:23 +00001019 if (Sym->hasTableIndex() || !Sym->hasFunctionIndex())
Sam Clegg6c4dbfee2018-02-23 04:59:57 +00001020 continue;
1021 Sym->setTableIndex(TableIndex++);
1022 IndirectFunctions.emplace_back(Sym);
1023 } else if (Reloc.Type == R_WEBASSEMBLY_TYPE_INDEX_LEB) {
Sam Clegg93102972018-02-23 05:08:53 +00001024 // Mark target type as live
Sam Clegg6c4dbfee2018-02-23 04:59:57 +00001025 File->TypeMap[Reloc.Index] = registerType(Types[Reloc.Index]);
1026 File->TypeIsUsed[Reloc.Index] = true;
1027 }
1028 }
1029 };
1030
Sam Clegg8d146bb2018-01-09 23:56:44 +00001031 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001032 LLVM_DEBUG(dbgs() << "Handle relocs: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +00001033 for (InputChunk *Chunk : File->Functions)
1034 HandleRelocs(Chunk);
1035 for (InputChunk *Chunk : File->Segments)
1036 HandleRelocs(Chunk);
Sam Cleggd177ab22018-05-04 23:14:42 +00001037 for (auto &P : File->CustomSections)
1038 HandleRelocs(P);
Sam Clegg93102972018-02-23 05:08:53 +00001039 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +00001040
Heejin Ahnaeaab992018-11-19 23:21:25 +00001041 assert(InputGlobals.empty());
1042 uint32_t GlobalIndex = NumImportedGlobals;
Sam Clegg93102972018-02-23 05:08:53 +00001043 auto AddDefinedGlobal = [&](InputGlobal *Global) {
1044 if (Global->Live) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001045 LLVM_DEBUG(dbgs() << "AddDefinedGlobal: " << GlobalIndex << "\n");
Sam Clegge3f3ccf2018-03-12 19:56:23 +00001046 Global->setGlobalIndex(GlobalIndex++);
Sam Clegg93102972018-02-23 05:08:53 +00001047 InputGlobals.push_back(Global);
1048 }
1049 };
1050
Nicholas Wilsonebda41f2018-03-09 16:43:05 +00001051 for (InputGlobal *Global : Symtab->SyntheticGlobals)
1052 AddDefinedGlobal(Global);
Sam Clegg93102972018-02-23 05:08:53 +00001053
1054 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001055 LLVM_DEBUG(dbgs() << "Globals: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +00001056 for (InputGlobal *Global : File->Globals)
1057 AddDefinedGlobal(Global);
Sam Cleggc94d3932017-11-17 18:14:09 +00001058 }
Heejin Ahne915a712018-12-08 06:17:43 +00001059
1060 assert(InputEvents.empty());
1061 uint32_t EventIndex = NumImportedEvents;
1062 auto AddDefinedEvent = [&](InputEvent *Event) {
1063 if (Event->Live) {
1064 LLVM_DEBUG(dbgs() << "AddDefinedEvent: " << EventIndex << "\n");
1065 Event->setEventIndex(EventIndex++);
1066 InputEvents.push_back(Event);
1067 }
1068 };
1069
1070 for (ObjFile *File : Symtab->ObjectFiles) {
1071 LLVM_DEBUG(dbgs() << "Events: " << File->getName() << "\n");
1072 for (InputEvent *Event : File->Events)
1073 AddDefinedEvent(Event);
1074 }
Sam Cleggc94d3932017-11-17 18:14:09 +00001075}
1076
1077static StringRef getOutputDataSegmentName(StringRef Name) {
Sam Cleggbfb75342018-11-15 00:37:21 +00001078 // With PIC code we currently only support a single data segment since
1079 // we only have a single __memory_base to use as our base address.
1080 if (Config->Pic)
1081 return "data";
Sam Clegg66844762018-05-10 18:23:51 +00001082 if (!Config->MergeDataSegments)
Sam Cleggc94d3932017-11-17 18:14:09 +00001083 return Name;
Rui Ueyama4764b572018-02-28 00:57:28 +00001084 if (Name.startswith(".text."))
1085 return ".text";
1086 if (Name.startswith(".data."))
1087 return ".data";
1088 if (Name.startswith(".bss."))
1089 return ".bss";
Sam Clegg57694c52018-08-08 18:02:55 +00001090 if (Name.startswith(".rodata."))
1091 return ".rodata";
Sam Cleggc94d3932017-11-17 18:14:09 +00001092 return Name;
1093}
1094
1095void Writer::createOutputSegments() {
1096 for (ObjFile *File : Symtab->ObjectFiles) {
1097 for (InputSegment *Segment : File->Segments) {
Sam Clegg447ae402018-02-13 20:29:38 +00001098 if (!Segment->Live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +00001099 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +00001100 StringRef Name = getOutputDataSegmentName(Segment->getName());
1101 OutputSegment *&S = SegmentMap[Name];
1102 if (S == nullptr) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001103 LLVM_DEBUG(dbgs() << "new segment: " << Name << "\n");
Sam Clegg93102972018-02-23 05:08:53 +00001104 S = make<OutputSegment>(Name, Segments.size());
Sam Cleggc94d3932017-11-17 18:14:09 +00001105 Segments.push_back(S);
1106 }
1107 S->addInputSegment(Segment);
Nicola Zaghene7245b42018-05-15 13:36:20 +00001108 LLVM_DEBUG(dbgs() << "added data: " << Name << ": " << S->Size << "\n");
Sam Cleggc94d3932017-11-17 18:14:09 +00001109 }
1110 }
1111}
1112
Sam Clegg50686852018-01-12 18:35:13 +00001113static const int OPCODE_CALL = 0x10;
1114static const int OPCODE_END = 0xb;
1115
1116// Create synthetic "__wasm_call_ctors" function based on ctor functions
1117// in input object.
1118void Writer::createCtorFunction() {
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +00001119 // First write the body's contents to a string.
1120 std::string BodyContent;
Sam Clegg50686852018-01-12 18:35:13 +00001121 {
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +00001122 raw_string_ostream OS(BodyContent);
Sam Clegg50686852018-01-12 18:35:13 +00001123 writeUleb128(OS, 0, "num locals");
Sam Clegg93102972018-02-23 05:08:53 +00001124 for (const WasmInitEntry &F : InitFunctions) {
Sam Clegg50686852018-01-12 18:35:13 +00001125 writeU8(OS, OPCODE_CALL, "CALL");
Sam Clegge3f3ccf2018-03-12 19:56:23 +00001126 writeUleb128(OS, F.Sym->getFunctionIndex(), "function index");
Sam Clegg50686852018-01-12 18:35:13 +00001127 }
1128 writeU8(OS, OPCODE_END, "END");
1129 }
1130
1131 // Once we know the size of the body we can create the final function body
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +00001132 std::string FunctionBody;
1133 {
1134 raw_string_ostream OS(FunctionBody);
1135 writeUleb128(OS, BodyContent.size(), "function size");
1136 OS << BodyContent;
1137 }
Rui Ueyama29abfe42018-02-28 17:43:15 +00001138
Sam Cleggea656472018-10-22 08:35:39 +00001139 ArrayRef<uint8_t> Body = arrayRefFromStringRef(Saver.save(FunctionBody));
Nicholas Wilsonebda41f2018-03-09 16:43:05 +00001140 cast<SyntheticFunction>(WasmSym::CallCtors->Function)->setBody(Body);
Sam Clegg50686852018-01-12 18:35:13 +00001141}
1142
1143// Populate InitFunctions vector with init functions from all input objects.
1144// This is then used either when creating the output linking section or to
1145// synthesize the "__wasm_call_ctors" function.
1146void Writer::calculateInitFunctions() {
1147 for (ObjFile *File : Symtab->ObjectFiles) {
1148 const WasmLinkingData &L = File->getWasmObj()->linkingData();
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +00001149 for (const WasmInitFunc &F : L.InitFunctions) {
1150 FunctionSymbol *Sym = File->getFunctionSymbol(F.Symbol);
Heejin Ahne915a712018-12-08 06:17:43 +00001151 if (*Sym->Signature != WasmSignature{{}, {}})
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +00001152 error("invalid signature for init func: " + toString(*Sym));
1153 InitFunctions.emplace_back(WasmInitEntry{Sym, F.Priority});
1154 }
Sam Clegg50686852018-01-12 18:35:13 +00001155 }
Rui Ueyamada69b712018-02-28 00:15:59 +00001156
Sam Clegg50686852018-01-12 18:35:13 +00001157 // Sort in order of priority (lowest first) so that they are called
1158 // in the correct order.
Sam Clegg29b8feb2018-02-21 00:34:34 +00001159 std::stable_sort(InitFunctions.begin(), InitFunctions.end(),
Sam Clegg93102972018-02-23 05:08:53 +00001160 [](const WasmInitEntry &L, const WasmInitEntry &R) {
Sam Clegg29b8feb2018-02-21 00:34:34 +00001161 return L.Priority < R.Priority;
1162 });
Sam Clegg50686852018-01-12 18:35:13 +00001163}
1164
Sam Cleggc94d3932017-11-17 18:14:09 +00001165void Writer::run() {
Sam Cleggbfb75342018-11-15 00:37:21 +00001166 if (Config->Relocatable || Config->Pic)
Sam Clegg99eb42c2018-02-27 23:58:03 +00001167 Config->GlobalBase = 0;
1168
Sam Cleggbfb75342018-11-15 00:37:21 +00001169 // For PIC code the table base is assigned dynamically by the loader.
1170 // For non-PIC, we start at 1 so that accessing table index 0 always traps.
1171 if (!Config->Pic)
1172 TableBase = 1;
1173
Sam Cleggc94d3932017-11-17 18:14:09 +00001174 log("-- calculateImports");
1175 calculateImports();
Sam Clegg8d146bb2018-01-09 23:56:44 +00001176 log("-- assignIndexes");
1177 assignIndexes();
Sam Clegg50686852018-01-12 18:35:13 +00001178 log("-- calculateInitFunctions");
1179 calculateInitFunctions();
1180 if (!Config->Relocatable)
1181 createCtorFunction();
Sam Clegg8f6d2de2018-01-31 23:48:14 +00001182 log("-- calculateTypes");
1183 calculateTypes();
Sam Clegg93102972018-02-23 05:08:53 +00001184 log("-- layoutMemory");
1185 layoutMemory();
1186 log("-- calculateExports");
1187 calculateExports();
Sam Cleggd177ab22018-05-04 23:14:42 +00001188 log("-- calculateCustomSections");
1189 calculateCustomSections();
Sam Clegg93102972018-02-23 05:08:53 +00001190 log("-- assignSymtab");
1191 assignSymtab();
Sam Cleggc94d3932017-11-17 18:14:09 +00001192
1193 if (errorHandler().Verbose) {
Sam Clegg9f934222018-02-21 18:29:23 +00001194 log("Defined Functions: " + Twine(InputFunctions.size()));
Sam Clegg93102972018-02-23 05:08:53 +00001195 log("Defined Globals : " + Twine(InputGlobals.size()));
Heejin Ahne915a712018-12-08 06:17:43 +00001196 log("Defined Events : " + Twine(InputEvents.size()));
Sam Clegg93102972018-02-23 05:08:53 +00001197 log("Function Imports : " + Twine(NumImportedFunctions));
1198 log("Global Imports : " + Twine(NumImportedGlobals));
Heejin Ahne915a712018-12-08 06:17:43 +00001199 log("Event Imports : " + Twine(NumImportedEvents));
Sam Cleggc94d3932017-11-17 18:14:09 +00001200 for (ObjFile *File : Symtab->ObjectFiles)
1201 File->dumpInfo();
1202 }
1203
Sam Cleggc94d3932017-11-17 18:14:09 +00001204 createHeader();
1205 log("-- createSections");
1206 createSections();
1207
1208 log("-- openFile");
1209 openFile();
1210 if (errorCount())
1211 return;
1212
1213 writeHeader();
1214
1215 log("-- writeSections");
1216 writeSections();
1217 if (errorCount())
1218 return;
1219
1220 if (Error E = Buffer->commit())
1221 fatal("failed to write the output file: " + toString(std::move(E)));
1222}
1223
1224// Open a result file.
1225void Writer::openFile() {
1226 log("writing: " + Config->OutputFile);
Sam Cleggc94d3932017-11-17 18:14:09 +00001227
1228 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
1229 FileOutputBuffer::create(Config->OutputFile, FileSize,
1230 FileOutputBuffer::F_executable);
1231
1232 if (!BufferOrErr)
1233 error("failed to open " + Config->OutputFile + ": " +
1234 toString(BufferOrErr.takeError()));
1235 else
1236 Buffer = std::move(*BufferOrErr);
1237}
1238
1239void Writer::createHeader() {
1240 raw_string_ostream OS(Header);
1241 writeBytes(OS, WasmMagic, sizeof(WasmMagic), "wasm magic");
1242 writeU32(OS, WasmVersion, "wasm version");
1243 OS.flush();
1244 FileSize += Header.size();
1245}
1246
1247void lld::wasm::writeResult() { Writer().run(); }