blob: 42146c41e9a31d7fbc0c26f94c430bf3341f1793 [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"
Sam Clegg80ba4382018-04-10 16:12:49 +000024#include "llvm/ADT/StringMap.h"
Sam Clegg93102972018-02-23 05:08:53 +000025#include "llvm/BinaryFormat/Wasm.h"
Nicholas Wilson3e3f5fb2018-03-14 15:58:16 +000026#include "llvm/Object/WasmTraits.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000027#include "llvm/Support/FileOutputBuffer.h"
28#include "llvm/Support/Format.h"
29#include "llvm/Support/FormatVariadic.h"
30#include "llvm/Support/LEB128.h"
31
32#include <cstdarg>
Sam Clegge0f6fcd2018-01-12 22:25:17 +000033#include <map>
Sam Cleggc94d3932017-11-17 18:14:09 +000034
35#define DEBUG_TYPE "lld"
36
37using namespace llvm;
38using namespace llvm::wasm;
39using namespace lld;
40using namespace lld::wasm;
41
42static constexpr int kStackAlignment = 16;
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();
Heejin Ahne915a712018-12-08 06:17:43 +000084 void createEventSection();
Sam Cleggc94d3932017-11-17 18:14:09 +000085 void createExportSection();
86 void createImportSection();
87 void createMemorySection();
88 void createElemSection();
Sam Cleggc94d3932017-11-17 18:14:09 +000089 void createCodeSection();
90 void createDataSection();
Sam Clegg80ba4382018-04-10 16:12:49 +000091 void createCustomSections();
Sam Cleggc94d3932017-11-17 18:14:09 +000092
93 // Custom sections
Sam Cleggbfb75342018-11-15 00:37:21 +000094 void createDylinkSection();
Sam Cleggc94d3932017-11-17 18:14:09 +000095 void createRelocSections();
96 void createLinkingSection();
97 void createNameSection();
98
99 void writeHeader();
100 void writeSections();
101
102 uint64_t FileSize = 0;
Sam Cleggbfb75342018-11-15 00:37:21 +0000103 uint32_t TableBase = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000104 uint32_t NumMemoryPages = 0;
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000105 uint32_t MaxMemoryPages = 0;
Sam Cleggbfb75342018-11-15 00:37:21 +0000106 // Memory size and aligment. Written to the "dylink" section
107 // when build with -shared or -pie.
108 uint32_t MemAlign = 0;
109 uint32_t MemSize = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000110
111 std::vector<const WasmSignature *> Types;
Nicholas Wilson3e3f5fb2018-03-14 15:58:16 +0000112 DenseMap<WasmSignature, int32_t> TypeIndices;
Sam Clegg93102972018-02-23 05:08:53 +0000113 std::vector<const Symbol *> ImportedSymbols;
114 unsigned NumImportedFunctions = 0;
115 unsigned NumImportedGlobals = 0;
Heejin Ahne915a712018-12-08 06:17:43 +0000116 unsigned NumImportedEvents = 0;
Sam Cleggd6beb322018-05-10 18:10:34 +0000117 std::vector<WasmExport> Exports;
Sam Clegg93102972018-02-23 05:08:53 +0000118 std::vector<const DefinedData *> DefinedFakeGlobals;
119 std::vector<InputGlobal *> InputGlobals;
Sam Clegg9f934222018-02-21 18:29:23 +0000120 std::vector<InputFunction *> InputFunctions;
Heejin Ahne915a712018-12-08 06:17:43 +0000121 std::vector<InputEvent *> InputEvents;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000122 std::vector<const FunctionSymbol *> IndirectFunctions;
Sam Clegg93102972018-02-23 05:08:53 +0000123 std::vector<const Symbol *> SymtabEntries;
124 std::vector<WasmInitEntry> InitFunctions;
Sam Cleggc94d3932017-11-17 18:14:09 +0000125
Sam Clegg80ba4382018-04-10 16:12:49 +0000126 llvm::StringMap<std::vector<InputSection *>> CustomSectionMapping;
Sam Cleggd177ab22018-05-04 23:14:42 +0000127 llvm::StringMap<SectionSymbol *> CustomSectionSymbols;
Sam Clegg80ba4382018-04-10 16:12:49 +0000128
Sam Cleggc94d3932017-11-17 18:14:09 +0000129 // Elements that are used to construct the final output
130 std::string Header;
131 std::vector<OutputSection *> OutputSections;
132
133 std::unique_ptr<FileOutputBuffer> Buffer;
134
135 std::vector<OutputSegment *> Segments;
136 llvm::SmallDenseMap<StringRef, OutputSegment *> SegmentMap;
137};
138
139} // anonymous namespace
140
Sam Cleggc94d3932017-11-17 18:14:09 +0000141void Writer::createImportSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000142 uint32_t NumImports = ImportedSymbols.size();
Sam Cleggc94d3932017-11-17 18:14:09 +0000143 if (Config->ImportMemory)
144 ++NumImports;
Nicholas Wilsonfc90b302018-03-28 12:53:29 +0000145 if (Config->ImportTable)
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000146 ++NumImports;
Sam Cleggc94d3932017-11-17 18:14:09 +0000147
148 if (NumImports == 0)
149 return;
150
151 SyntheticSection *Section = createSyntheticSection(WASM_SEC_IMPORT);
152 raw_ostream &OS = Section->getStream();
153
154 writeUleb128(OS, NumImports, "import count");
155
Sam Cleggc94d3932017-11-17 18:14:09 +0000156 if (Config->ImportMemory) {
157 WasmImport Import;
158 Import.Module = "env";
159 Import.Field = "memory";
160 Import.Kind = WASM_EXTERNAL_MEMORY;
161 Import.Memory.Flags = 0;
162 Import.Memory.Initial = NumMemoryPages;
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000163 if (MaxMemoryPages != 0) {
164 Import.Memory.Flags |= WASM_LIMITS_FLAG_HAS_MAX;
165 Import.Memory.Maximum = MaxMemoryPages;
166 }
Derek Schuff786760a2018-11-06 18:02:39 +0000167 if (Config->SharedMemory)
Derek Schuff3bea8bc2018-11-06 17:59:32 +0000168 Import.Memory.Flags |= WASM_LIMITS_FLAG_IS_SHARED;
Sam Cleggc94d3932017-11-17 18:14:09 +0000169 writeImport(OS, Import);
170 }
171
Nicholas Wilsonfc90b302018-03-28 12:53:29 +0000172 if (Config->ImportTable) {
Sam Cleggbfb75342018-11-15 00:37:21 +0000173 uint32_t TableSize = TableBase + IndirectFunctions.size();
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000174 WasmImport Import;
175 Import.Module = "env";
176 Import.Field = kFunctionTableName;
177 Import.Kind = WASM_EXTERNAL_TABLE;
Thomas Lively25ff8932019-01-08 06:25:55 +0000178 Import.Table.ElemType = WASM_TYPE_FUNCREF;
Sam Clegg748f59cae2018-12-03 22:37:55 +0000179 Import.Table.Limits = {0, TableSize, 0};
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000180 writeImport(OS, Import);
181 }
182
Sam Clegg93102972018-02-23 05:08:53 +0000183 for (const Symbol *Sym : ImportedSymbols) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000184 WasmImport Import;
185 Import.Module = "env";
186 Import.Field = Sym->getName();
Sam Clegg93102972018-02-23 05:08:53 +0000187 if (auto *FunctionSym = dyn_cast<FunctionSymbol>(Sym)) {
188 Import.Kind = WASM_EXTERNAL_FUNCTION;
Heejin Ahne915a712018-12-08 06:17:43 +0000189 Import.SigIndex = lookupType(*FunctionSym->Signature);
190 } else if (auto *GlobalSym = dyn_cast<GlobalSymbol>(Sym)) {
Sam Clegg93102972018-02-23 05:08:53 +0000191 Import.Kind = WASM_EXTERNAL_GLOBAL;
192 Import.Global = *GlobalSym->getGlobalType();
Heejin Ahne915a712018-12-08 06:17:43 +0000193 } else {
194 auto *EventSym = cast<EventSymbol>(Sym);
195 Import.Kind = WASM_EXTERNAL_EVENT;
196 Import.Event.Attribute = EventSym->getEventType()->Attribute;
197 Import.Event.SigIndex = lookupType(*EventSym->Signature);
Sam Clegg93102972018-02-23 05:08:53 +0000198 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000199 writeImport(OS, Import);
200 }
201}
202
203void Writer::createTypeSection() {
204 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TYPE);
205 raw_ostream &OS = Section->getStream();
206 writeUleb128(OS, Types.size(), "type count");
Sam Cleggd451da12017-12-19 19:56:27 +0000207 for (const WasmSignature *Sig : Types)
Sam Cleggc94d3932017-11-17 18:14:09 +0000208 writeSig(OS, *Sig);
Sam Cleggc94d3932017-11-17 18:14:09 +0000209}
210
211void Writer::createFunctionSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000212 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000213 return;
214
215 SyntheticSection *Section = createSyntheticSection(WASM_SEC_FUNCTION);
216 raw_ostream &OS = Section->getStream();
217
Sam Clegg9f934222018-02-21 18:29:23 +0000218 writeUleb128(OS, InputFunctions.size(), "function count");
219 for (const InputFunction *Func : InputFunctions)
Sam Cleggc375e4e2018-01-10 19:18:22 +0000220 writeUleb128(OS, lookupType(Func->Signature), "sig index");
Sam Cleggc94d3932017-11-17 18:14:09 +0000221}
222
223void Writer::createMemorySection() {
224 if (Config->ImportMemory)
225 return;
226
227 SyntheticSection *Section = createSyntheticSection(WASM_SEC_MEMORY);
228 raw_ostream &OS = Section->getStream();
229
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000230 bool HasMax = MaxMemoryPages != 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000231 writeUleb128(OS, 1, "memory count");
Derek Schuff786760a2018-11-06 18:02:39 +0000232 unsigned Flags = 0;
233 if (HasMax)
234 Flags |= WASM_LIMITS_FLAG_HAS_MAX;
Derek Schuff3bea8bc2018-11-06 17:59:32 +0000235 if (Config->SharedMemory)
236 Flags |= WASM_LIMITS_FLAG_IS_SHARED;
237 writeUleb128(OS, Flags, "memory limits flags");
Sam Cleggc94d3932017-11-17 18:14:09 +0000238 writeUleb128(OS, NumMemoryPages, "initial pages");
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000239 if (HasMax)
240 writeUleb128(OS, MaxMemoryPages, "max pages");
Sam Cleggc94d3932017-11-17 18:14:09 +0000241}
242
243void Writer::createGlobalSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000244 unsigned NumGlobals = InputGlobals.size() + DefinedFakeGlobals.size();
245 if (NumGlobals == 0)
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000246 return;
247
Sam Cleggc94d3932017-11-17 18:14:09 +0000248 SyntheticSection *Section = createSyntheticSection(WASM_SEC_GLOBAL);
249 raw_ostream &OS = Section->getStream();
250
Sam Clegg93102972018-02-23 05:08:53 +0000251 writeUleb128(OS, NumGlobals, "global count");
252 for (const InputGlobal *G : InputGlobals)
253 writeGlobal(OS, G->Global);
254 for (const DefinedData *Sym : DefinedFakeGlobals) {
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000255 WasmGlobal Global;
Sam Clegg93102972018-02-23 05:08:53 +0000256 Global.Type = {WASM_TYPE_I32, false};
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000257 Global.InitExpr.Opcode = WASM_OPCODE_I32_CONST;
258 Global.InitExpr.Value.Int32 = Sym->getVirtualAddress();
Sam Cleggc94d3932017-11-17 18:14:09 +0000259 writeGlobal(OS, Global);
260 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000261}
262
Heejin Ahne915a712018-12-08 06:17:43 +0000263// The event section contains a list of declared wasm events associated with the
264// module. Currently the only supported event kind is exceptions. A single event
265// entry represents a single event with an event tag. All C++ exceptions are
266// represented by a single event. An event entry in this section contains
267// information on what kind of event it is (e.g. exception) and the type of
268// values contained in a single event object. (In wasm, an event can contain
269// multiple values of primitive types. But for C++ exceptions, we just throw a
270// pointer which is an i32 value (for wasm32 architecture), so the signature of
271// C++ exception is (i32)->(void), because all event types are assumed to have
272// void return type to share WasmSignature with functions.)
273void Writer::createEventSection() {
274 unsigned NumEvents = InputEvents.size();
275 if (NumEvents == 0)
276 return;
277
278 SyntheticSection *Section = createSyntheticSection(WASM_SEC_EVENT);
279 raw_ostream &OS = Section->getStream();
280
281 writeUleb128(OS, NumEvents, "event count");
282 for (InputEvent *E : InputEvents) {
283 E->Event.Type.SigIndex = lookupType(E->Signature);
284 writeEvent(OS, E->Event);
285 }
286}
287
Sam Cleggc94d3932017-11-17 18:14:09 +0000288void Writer::createTableSection() {
Nicholas Wilsonfc90b302018-03-28 12:53:29 +0000289 if (Config->ImportTable)
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000290 return;
291
292 // Always output a table section (or table import), even if there are no
293 // indirect calls. There are two reasons for this:
Sam Cleggfc1a9122017-12-11 22:00:56 +0000294 // 1. For executables it is useful to have an empty table slot at 0
295 // which can be filled with a null function call handler.
296 // 2. If we don't do this, any program that contains a call_indirect but
297 // no address-taken function will fail at validation time since it is
298 // a validation error to include a call_indirect instruction if there
299 // is not table.
Sam Cleggbfb75342018-11-15 00:37:21 +0000300 uint32_t TableSize = TableBase + IndirectFunctions.size();
Sam Cleggfc1a9122017-12-11 22:00:56 +0000301
Sam Cleggc94d3932017-11-17 18:14:09 +0000302 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TABLE);
303 raw_ostream &OS = Section->getStream();
304
305 writeUleb128(OS, 1, "table count");
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000306 WasmLimits Limits = {WASM_LIMITS_FLAG_HAS_MAX, TableSize, TableSize};
Thomas Lively25ff8932019-01-08 06:25:55 +0000307 writeTableType(OS, WasmTable{WASM_TYPE_FUNCREF, Limits});
Sam Cleggc94d3932017-11-17 18:14:09 +0000308}
309
310void Writer::createExportSection() {
Sam Cleggd6beb322018-05-10 18:10:34 +0000311 if (!Exports.size())
Sam Cleggc94d3932017-11-17 18:14:09 +0000312 return;
313
314 SyntheticSection *Section = createSyntheticSection(WASM_SEC_EXPORT);
315 raw_ostream &OS = Section->getStream();
316
Sam Cleggd6beb322018-05-10 18:10:34 +0000317 writeUleb128(OS, Exports.size(), "export count");
318 for (const WasmExport &Export : Exports)
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000319 writeExport(OS, Export);
Sam Cleggc94d3932017-11-17 18:14:09 +0000320}
321
Sam Cleggd177ab22018-05-04 23:14:42 +0000322void Writer::calculateCustomSections() {
323 log("calculateCustomSections");
324 bool StripDebug = Config->StripDebug || Config->StripAll;
325 for (ObjFile *File : Symtab->ObjectFiles) {
326 for (InputSection *Section : File->CustomSections) {
327 StringRef Name = Section->getName();
328 // These custom sections are known the linker and synthesized rather than
329 // blindly copied
330 if (Name == "linking" || Name == "name" || Name.startswith("reloc."))
331 continue;
332 // .. or it is a debug section
333 if (StripDebug && Name.startswith(".debug_"))
334 continue;
335 CustomSectionMapping[Name].push_back(Section);
336 }
337 }
338}
339
Sam Clegg80ba4382018-04-10 16:12:49 +0000340void Writer::createCustomSections() {
341 log("createCustomSections");
Sam Clegg80ba4382018-04-10 16:12:49 +0000342 for (auto &Pair : CustomSectionMapping) {
343 StringRef Name = Pair.first();
Sam Cleggd177ab22018-05-04 23:14:42 +0000344
345 auto P = CustomSectionSymbols.find(Name);
346 if (P != CustomSectionSymbols.end()) {
347 uint32_t SectionIndex = OutputSections.size();
348 P->second->setOutputSectionIndex(SectionIndex);
349 }
350
Nicola Zaghene7245b42018-05-15 13:36:20 +0000351 LLVM_DEBUG(dbgs() << "createCustomSection: " << Name << "\n");
Sam Clegg80ba4382018-04-10 16:12:49 +0000352 OutputSections.push_back(make<CustomSection>(Name, Pair.second));
353 }
354}
355
Sam Cleggc94d3932017-11-17 18:14:09 +0000356void Writer::createElemSection() {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000357 if (IndirectFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000358 return;
359
360 SyntheticSection *Section = createSyntheticSection(WASM_SEC_ELEM);
361 raw_ostream &OS = Section->getStream();
362
363 writeUleb128(OS, 1, "segment count");
364 writeUleb128(OS, 0, "table index");
365 WasmInitExpr InitExpr;
Sam Cleggbfb75342018-11-15 00:37:21 +0000366 if (Config->Pic) {
Thomas Lively25ff8932019-01-08 06:25:55 +0000367 InitExpr.Opcode = WASM_OPCODE_GLOBAL_GET;
Sam Clegg2dad4e22018-11-15 18:15:54 +0000368 InitExpr.Value.Global = WasmSym::TableBase->getGlobalIndex();
Sam Cleggbfb75342018-11-15 00:37:21 +0000369 } else {
370 InitExpr.Opcode = WASM_OPCODE_I32_CONST;
371 InitExpr.Value.Int32 = TableBase;
372 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000373 writeInitExpr(OS, InitExpr);
Sam Cleggfc1a9122017-12-11 22:00:56 +0000374 writeUleb128(OS, IndirectFunctions.size(), "elem count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000375
Sam Cleggbfb75342018-11-15 00:37:21 +0000376 uint32_t TableIndex = TableBase;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000377 for (const FunctionSymbol *Sym : IndirectFunctions) {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000378 assert(Sym->getTableIndex() == TableIndex);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000379 writeUleb128(OS, Sym->getFunctionIndex(), "function index");
Sam Cleggfc1a9122017-12-11 22:00:56 +0000380 ++TableIndex;
381 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000382}
383
384void Writer::createCodeSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000385 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000386 return;
387
388 log("createCodeSection");
389
Sam Clegg9f934222018-02-21 18:29:23 +0000390 auto Section = make<CodeSection>(InputFunctions);
Sam Cleggc94d3932017-11-17 18:14:09 +0000391 OutputSections.push_back(Section);
392}
393
394void Writer::createDataSection() {
395 if (!Segments.size())
396 return;
397
398 log("createDataSection");
399 auto Section = make<DataSection>(Segments);
400 OutputSections.push_back(Section);
401}
402
Sam Cleggd451da12017-12-19 19:56:27 +0000403// Create relocations sections in the final output.
Sam Cleggc94d3932017-11-17 18:14:09 +0000404// These are only created when relocatable output is requested.
405void Writer::createRelocSections() {
406 log("createRelocSections");
407 // Don't use iterator here since we are adding to OutputSection
408 size_t OrigSize = OutputSections.size();
Rui Ueyamaffa650a2018-04-24 23:09:57 +0000409 for (size_t I = 0; I < OrigSize; I++) {
410 OutputSection *OSec = OutputSections[I];
Rui Ueyama37254062018-02-28 00:01:31 +0000411 uint32_t Count = OSec->numRelocations();
Sam Cleggc94d3932017-11-17 18:14:09 +0000412 if (!Count)
413 continue;
414
Rui Ueyama37254062018-02-28 00:01:31 +0000415 StringRef Name;
416 if (OSec->Type == WASM_SEC_DATA)
417 Name = "reloc.DATA";
418 else if (OSec->Type == WASM_SEC_CODE)
419 Name = "reloc.CODE";
Sam Cleggd177ab22018-05-04 23:14:42 +0000420 else if (OSec->Type == WASM_SEC_CUSTOM)
421 Name = Saver.save("reloc." + OSec->Name);
Sam Cleggc94d3932017-11-17 18:14:09 +0000422 else
Sam Cleggd177ab22018-05-04 23:14:42 +0000423 llvm_unreachable(
424 "relocations only supported for code, data, or custom sections");
Sam Cleggc94d3932017-11-17 18:14:09 +0000425
Rui Ueyama37254062018-02-28 00:01:31 +0000426 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, Name);
Sam Cleggc94d3932017-11-17 18:14:09 +0000427 raw_ostream &OS = Section->getStream();
Rui Ueyamaffa650a2018-04-24 23:09:57 +0000428 writeUleb128(OS, I, "reloc section");
Sam Cleggc94d3932017-11-17 18:14:09 +0000429 writeUleb128(OS, Count, "reloc count");
Rui Ueyama37254062018-02-28 00:01:31 +0000430 OSec->writeRelocations(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000431 }
432}
433
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000434static uint32_t getWasmFlags(const Symbol *Sym) {
435 uint32_t Flags = 0;
436 if (Sym->isLocal())
437 Flags |= WASM_SYMBOL_BINDING_LOCAL;
438 if (Sym->isWeak())
439 Flags |= WASM_SYMBOL_BINDING_WEAK;
440 if (Sym->isHidden())
441 Flags |= WASM_SYMBOL_VISIBILITY_HIDDEN;
442 if (Sym->isUndefined())
443 Flags |= WASM_SYMBOL_UNDEFINED;
444 return Flags;
445}
446
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000447// Some synthetic sections (e.g. "name" and "linking") have subsections.
448// Just like the synthetic sections themselves these need to be created before
449// they can be written out (since they are preceded by their length). This
450// class is used to create subsections and then write them into the stream
451// of the parent section.
452class SubSection {
453public:
454 explicit SubSection(uint32_t Type) : Type(Type) {}
455
456 void writeTo(raw_ostream &To) {
457 OS.flush();
Rui Ueyama67769102018-02-28 03:38:14 +0000458 writeUleb128(To, Type, "subsection type");
459 writeUleb128(To, Body.size(), "subsection size");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000460 To.write(Body.data(), Body.size());
461 }
462
463private:
464 uint32_t Type;
465 std::string Body;
466
467public:
468 raw_string_ostream OS{Body};
469};
470
Sam Cleggbfb75342018-11-15 00:37:21 +0000471// Create the custom "dylink" section containing information for the dynamic
472// linker.
473// See
474// https://github.com/WebAssembly/tool-conventions/blob/master/DynamicLinking.md
475void Writer::createDylinkSection() {
476 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "dylink");
477 raw_ostream &OS = Section->getStream();
478
479 writeUleb128(OS, MemSize, "MemSize");
480 writeUleb128(OS, int(log2(MemAlign)), "MemAlign");
481 writeUleb128(OS, IndirectFunctions.size(), "TableSize");
482 writeUleb128(OS, 0, "TableAlign");
Sam Clegge01c6462018-12-12 23:44:59 +0000483 writeUleb128(OS, 0, "Needed"); // TODO: Support "needed" shared libraries
Sam Cleggbfb75342018-11-15 00:37:21 +0000484}
485
Sam Clegg49ed9262017-12-01 00:53:21 +0000486// Create the custom "linking" section containing linker metadata.
Sam Cleggc94d3932017-11-17 18:14:09 +0000487// This is only created when relocatable output is requested.
488void Writer::createLinkingSection() {
489 SyntheticSection *Section =
490 createSyntheticSection(WASM_SEC_CUSTOM, "linking");
491 raw_ostream &OS = Section->getStream();
492
Sam Clegg2b8b1792018-04-26 18:17:21 +0000493 writeUleb128(OS, WasmMetadataVersion, "Version");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000494
Sam Clegg93102972018-02-23 05:08:53 +0000495 if (!SymtabEntries.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000496 SubSection Sub(WASM_SYMBOL_TABLE);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000497 writeUleb128(Sub.OS, SymtabEntries.size(), "num symbols");
498
Sam Clegg93102972018-02-23 05:08:53 +0000499 for (const Symbol *Sym : SymtabEntries) {
500 assert(Sym->isDefined() || Sym->isUndefined());
501 WasmSymbolType Kind = Sym->getWasmType();
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000502 uint32_t Flags = getWasmFlags(Sym);
503
Sam Clegg8518e7d2018-03-01 18:06:39 +0000504 writeU8(Sub.OS, Kind, "sym kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000505 writeUleb128(Sub.OS, Flags, "sym flags");
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000506
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000507 if (auto *F = dyn_cast<FunctionSymbol>(Sym)) {
508 writeUleb128(Sub.OS, F->getFunctionIndex(), "index");
Sam Clegg93102972018-02-23 05:08:53 +0000509 if (Sym->isDefined())
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000510 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000511 } else if (auto *G = dyn_cast<GlobalSymbol>(Sym)) {
512 writeUleb128(Sub.OS, G->getGlobalIndex(), "index");
513 if (Sym->isDefined())
514 writeStr(Sub.OS, Sym->getName(), "sym name");
Heejin Ahne915a712018-12-08 06:17:43 +0000515 } else if (auto *E = dyn_cast<EventSymbol>(Sym)) {
516 writeUleb128(Sub.OS, E->getEventIndex(), "index");
517 if (Sym->isDefined())
518 writeStr(Sub.OS, Sym->getName(), "sym name");
Andrea Di Biagio25c1a2f2018-05-05 10:53:31 +0000519 } else if (isa<DataSymbol>(Sym)) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000520 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegg93102972018-02-23 05:08:53 +0000521 if (auto *DataSym = dyn_cast<DefinedData>(Sym)) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000522 writeUleb128(Sub.OS, DataSym->getOutputSegmentIndex(), "index");
523 writeUleb128(Sub.OS, DataSym->getOutputSegmentOffset(),
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000524 "data offset");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000525 writeUleb128(Sub.OS, DataSym->getSize(), "data size");
Sam Clegg93102972018-02-23 05:08:53 +0000526 }
Sam Cleggd177ab22018-05-04 23:14:42 +0000527 } else {
528 auto *S = cast<SectionSymbol>(Sym);
529 writeUleb128(Sub.OS, S->getOutputSectionIndex(), "sym section index");
Sam Clegg93102972018-02-23 05:08:53 +0000530 }
Sam Cleggd3052d52018-01-18 23:40:49 +0000531 }
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000532
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000533 Sub.writeTo(OS);
Sam Cleggd3052d52018-01-18 23:40:49 +0000534 }
535
Sam Clegg0d0dd392017-12-19 17:09:45 +0000536 if (Segments.size()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000537 SubSection Sub(WASM_SEGMENT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000538 writeUleb128(Sub.OS, Segments.size(), "num data segments");
Sam Cleggc94d3932017-11-17 18:14:09 +0000539 for (const OutputSegment *S : Segments) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000540 writeStr(Sub.OS, S->Name, "segment name");
541 writeUleb128(Sub.OS, S->Alignment, "alignment");
542 writeUleb128(Sub.OS, 0, "flags");
Sam Cleggc94d3932017-11-17 18:14:09 +0000543 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000544 Sub.writeTo(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000545 }
Sam Clegg0d0dd392017-12-19 17:09:45 +0000546
Sam Clegg0d0dd392017-12-19 17:09:45 +0000547 if (!InitFunctions.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000548 SubSection Sub(WASM_INIT_FUNCS);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000549 writeUleb128(Sub.OS, InitFunctions.size(), "num init functions");
Sam Clegg93102972018-02-23 05:08:53 +0000550 for (const WasmInitEntry &F : InitFunctions) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000551 writeUleb128(Sub.OS, F.Priority, "priority");
552 writeUleb128(Sub.OS, F.Sym->getOutputSymbolIndex(), "function index");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000553 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000554 Sub.writeTo(OS);
Sam Clegg0d0dd392017-12-19 17:09:45 +0000555 }
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000556
Nicholas Wilsondbd90bf2018-03-07 13:28:16 +0000557 struct ComdatEntry {
558 unsigned Kind;
559 uint32_t Index;
560 };
561 std::map<StringRef, std::vector<ComdatEntry>> Comdats;
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000562
Sam Clegg9f934222018-02-21 18:29:23 +0000563 for (const InputFunction *F : InputFunctions) {
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000564 StringRef Comdat = F->getComdatName();
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000565 if (!Comdat.empty())
566 Comdats[Comdat].emplace_back(
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000567 ComdatEntry{WASM_COMDAT_FUNCTION, F->getFunctionIndex()});
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000568 }
569 for (uint32_t I = 0; I < Segments.size(); ++I) {
Sam Cleggf98bccf2018-01-13 15:57:48 +0000570 const auto &InputSegments = Segments[I]->InputSegments;
571 if (InputSegments.empty())
572 continue;
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000573 StringRef Comdat = InputSegments[0]->getComdatName();
Sam Clegga697df522018-01-13 15:59:53 +0000574#ifndef NDEBUG
Sam Cleggf98bccf2018-01-13 15:57:48 +0000575 for (const InputSegment *IS : InputSegments)
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000576 assert(IS->getComdatName() == Comdat);
Sam Clegga697df522018-01-13 15:59:53 +0000577#endif
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000578 if (!Comdat.empty())
579 Comdats[Comdat].emplace_back(ComdatEntry{WASM_COMDAT_DATA, I});
580 }
581
582 if (!Comdats.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000583 SubSection Sub(WASM_COMDAT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000584 writeUleb128(Sub.OS, Comdats.size(), "num comdats");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000585 for (const auto &C : Comdats) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000586 writeStr(Sub.OS, C.first, "comdat name");
587 writeUleb128(Sub.OS, 0, "comdat flags"); // flags for future use
588 writeUleb128(Sub.OS, C.second.size(), "num entries");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000589 for (const ComdatEntry &Entry : C.second) {
Sam Clegg8518e7d2018-03-01 18:06:39 +0000590 writeU8(Sub.OS, Entry.Kind, "entry kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000591 writeUleb128(Sub.OS, Entry.Index, "entry index");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000592 }
593 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000594 Sub.writeTo(OS);
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000595 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000596}
597
598// Create the custom "name" section containing debug symbol names.
599void Writer::createNameSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000600 unsigned NumNames = NumImportedFunctions;
Sam Clegg9f934222018-02-21 18:29:23 +0000601 for (const InputFunction *F : InputFunctions)
Nicholas Wilson6c7fe302018-04-20 17:09:18 +0000602 if (!F->getName().empty() || !F->getDebugName().empty())
Sam Clegg1963d712018-01-17 20:19:04 +0000603 ++NumNames;
Sam Cleggc94d3932017-11-17 18:14:09 +0000604
Sam Clegg1963d712018-01-17 20:19:04 +0000605 if (NumNames == 0)
606 return;
Sam Clegg50686852018-01-12 18:35:13 +0000607
Sam Cleggc94d3932017-11-17 18:14:09 +0000608 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "name");
609
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000610 SubSection Sub(WASM_NAMES_FUNCTION);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000611 writeUleb128(Sub.OS, NumNames, "name count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000612
Sam Clegg93102972018-02-23 05:08:53 +0000613 // Names must appear in function index order. As it happens ImportedSymbols
614 // and InputFunctions are numbered in order with imported functions coming
Sam Clegg1963d712018-01-17 20:19:04 +0000615 // first.
Sam Clegg93102972018-02-23 05:08:53 +0000616 for (const Symbol *S : ImportedSymbols) {
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000617 if (auto *F = dyn_cast<FunctionSymbol>(S)) {
618 writeUleb128(Sub.OS, F->getFunctionIndex(), "func index");
Sam Clegg37125f02018-11-09 16:57:41 +0000619 writeStr(Sub.OS, toString(*S), "symbol name");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000620 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000621 }
Sam Clegg9f934222018-02-21 18:29:23 +0000622 for (const InputFunction *F : InputFunctions) {
Sam Clegg1963d712018-01-17 20:19:04 +0000623 if (!F->getName().empty()) {
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000624 writeUleb128(Sub.OS, F->getFunctionIndex(), "func index");
Nicholas Wilson6c7fe302018-04-20 17:09:18 +0000625 if (!F->getDebugName().empty()) {
626 writeStr(Sub.OS, F->getDebugName(), "symbol name");
627 } else {
Sam Clegg37125f02018-11-09 16:57:41 +0000628 writeStr(Sub.OS, maybeDemangleSymbol(F->getName()), "symbol name");
Nicholas Wilson6c7fe302018-04-20 17:09:18 +0000629 }
Sam Clegg1963d712018-01-17 20:19:04 +0000630 }
631 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000632
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000633 Sub.writeTo(Section->getStream());
Sam Cleggc94d3932017-11-17 18:14:09 +0000634}
635
636void Writer::writeHeader() {
637 memcpy(Buffer->getBufferStart(), Header.data(), Header.size());
638}
639
640void Writer::writeSections() {
641 uint8_t *Buf = Buffer->getBufferStart();
642 parallelForEach(OutputSections, [Buf](OutputSection *S) { S->writeTo(Buf); });
643}
644
645// Fix the memory layout of the output binary. This assigns memory offsets
Sam Clegg49ed9262017-12-01 00:53:21 +0000646// to each of the input data sections as well as the explicit stack region.
Sam Clegga0f095e2018-05-03 17:21:53 +0000647// The default memory layout is as follows, from low to high.
648//
Sam Cleggf0d433d2018-02-02 22:59:56 +0000649// - initialized data (starting at Config->GlobalBase)
650// - BSS data (not currently implemented in llvm)
651// - explicit stack (Config->ZStackSize)
652// - heap start / unallocated
Sam Clegga0f095e2018-05-03 17:21:53 +0000653//
654// The --stack-first option means that stack is placed before any static data.
Heejin Ahn4821ebf2018-08-29 21:03:16 +0000655// This can be useful since it means that stack overflow traps immediately
656// rather than overwriting global data, but also increases code size since all
657// static data loads and stores requires larger offsets.
Sam Cleggc94d3932017-11-17 18:14:09 +0000658void Writer::layoutMemory() {
Sam Cleggc94d3932017-11-17 18:14:09 +0000659 createOutputSegments();
660
Sam Clegga0f095e2018-05-03 17:21:53 +0000661 uint32_t MemoryPtr = 0;
662
663 auto PlaceStack = [&]() {
Sam Cleggbfb75342018-11-15 00:37:21 +0000664 if (Config->Relocatable || Config->Shared)
Sam Clegga0f095e2018-05-03 17:21:53 +0000665 return;
666 MemoryPtr = alignTo(MemoryPtr, kStackAlignment);
667 if (Config->ZStackSize != alignTo(Config->ZStackSize, kStackAlignment))
668 error("stack size must be " + Twine(kStackAlignment) + "-byte aligned");
669 log("mem: stack size = " + Twine(Config->ZStackSize));
670 log("mem: stack base = " + Twine(MemoryPtr));
671 MemoryPtr += Config->ZStackSize;
Sam Clegg2dad4e22018-11-15 18:15:54 +0000672 auto *SP = cast<DefinedGlobal>(WasmSym::StackPointer);
673 SP->Global->Global.InitExpr.Value.Int32 = MemoryPtr;
Sam Clegga0f095e2018-05-03 17:21:53 +0000674 log("mem: stack top = " + Twine(MemoryPtr));
675 };
676
677 if (Config->StackFirst) {
678 PlaceStack();
679 } else {
680 MemoryPtr = Config->GlobalBase;
681 log("mem: global base = " + Twine(Config->GlobalBase));
682 }
683
684 uint32_t DataStart = MemoryPtr;
685
Sam Cleggf0d433d2018-02-02 22:59:56 +0000686 // Arbitrarily set __dso_handle handle to point to the start of the data
687 // segments.
688 if (WasmSym::DsoHandle)
Sam Clegga0f095e2018-05-03 17:21:53 +0000689 WasmSym::DsoHandle->setVirtualAddress(DataStart);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000690
Sam Cleggbfb75342018-11-15 00:37:21 +0000691 MemAlign = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000692 for (OutputSegment *Seg : Segments) {
Sam Cleggbfb75342018-11-15 00:37:21 +0000693 MemAlign = std::max(MemAlign, Seg->Alignment);
Sam Cleggc94d3932017-11-17 18:14:09 +0000694 MemoryPtr = alignTo(MemoryPtr, Seg->Alignment);
695 Seg->StartVA = MemoryPtr;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000696 log(formatv("mem: {0,-15} offset={1,-8} size={2,-8} align={3}", Seg->Name,
697 MemoryPtr, Seg->Size, Seg->Alignment));
Sam Cleggc94d3932017-11-17 18:14:09 +0000698 MemoryPtr += Seg->Size;
699 }
700
Sam Cleggf0d433d2018-02-02 22:59:56 +0000701 // TODO: Add .bss space here.
Sam Clegg37a4a8a2018-02-07 03:04:53 +0000702 if (WasmSym::DataEnd)
703 WasmSym::DataEnd->setVirtualAddress(MemoryPtr);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000704
Sam Clegga0f095e2018-05-03 17:21:53 +0000705 log("mem: static data = " + Twine(MemoryPtr - DataStart));
Sam Cleggc94d3932017-11-17 18:14:09 +0000706
Sam Clegg2dad4e22018-11-15 18:15:54 +0000707 if (Config->Shared) {
708 MemSize = MemoryPtr;
709 return;
710 }
711
Sam Clegga0f095e2018-05-03 17:21:53 +0000712 if (!Config->StackFirst)
713 PlaceStack();
714
715 // Set `__heap_base` to directly follow the end of the stack or global data.
716 // The fact that this comes last means that a malloc/brk implementation
717 // can grow the heap at runtime.
Sam Cleggc94d3932017-11-17 18:14:09 +0000718 if (!Config->Relocatable) {
Sam Cleggf0d433d2018-02-02 22:59:56 +0000719 WasmSym::HeapBase->setVirtualAddress(MemoryPtr);
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000720 log("mem: heap base = " + Twine(MemoryPtr));
Sam Cleggc94d3932017-11-17 18:14:09 +0000721 }
722
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000723 if (Config->InitialMemory != 0) {
724 if (Config->InitialMemory != alignTo(Config->InitialMemory, WasmPageSize))
725 error("initial memory must be " + Twine(WasmPageSize) + "-byte aligned");
726 if (MemoryPtr > Config->InitialMemory)
727 error("initial memory too small, " + Twine(MemoryPtr) + " bytes needed");
728 else
729 MemoryPtr = Config->InitialMemory;
730 }
Sam Cleggbfb75342018-11-15 00:37:21 +0000731 MemSize = MemoryPtr;
732 NumMemoryPages = alignTo(MemoryPtr, WasmPageSize) / WasmPageSize;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000733 log("mem: total pages = " + Twine(NumMemoryPages));
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000734
735 if (Config->MaxMemory != 0) {
736 if (Config->MaxMemory != alignTo(Config->MaxMemory, WasmPageSize))
737 error("maximum memory must be " + Twine(WasmPageSize) + "-byte aligned");
738 if (MemoryPtr > Config->MaxMemory)
739 error("maximum memory too small, " + Twine(MemoryPtr) + " bytes needed");
740 MaxMemoryPages = Config->MaxMemory / WasmPageSize;
741 log("mem: max pages = " + Twine(MaxMemoryPages));
742 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000743}
744
745SyntheticSection *Writer::createSyntheticSection(uint32_t Type,
Sam Cleggc375e4e2018-01-10 19:18:22 +0000746 StringRef Name) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000747 auto Sec = make<SyntheticSection>(Type, Name);
Sam Cleggab2ac292017-12-20 05:14:48 +0000748 log("createSection: " + toString(*Sec));
Sam Cleggc94d3932017-11-17 18:14:09 +0000749 OutputSections.push_back(Sec);
750 return Sec;
751}
752
753void Writer::createSections() {
754 // Known sections
Sam Cleggbfb75342018-11-15 00:37:21 +0000755 if (Config->Pic)
756 createDylinkSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000757 createTypeSection();
758 createImportSection();
759 createFunctionSection();
760 createTableSection();
761 createMemorySection();
762 createGlobalSection();
Heejin Ahne915a712018-12-08 06:17:43 +0000763 createEventSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000764 createExportSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000765 createElemSection();
766 createCodeSection();
767 createDataSection();
Sam Clegg80ba4382018-04-10 16:12:49 +0000768 createCustomSections();
Sam Cleggc94d3932017-11-17 18:14:09 +0000769
770 // Custom sections
Sam Clegg99eb42c2018-02-27 23:58:03 +0000771 if (Config->Relocatable) {
Sam Clegg99eb42c2018-02-27 23:58:03 +0000772 createLinkingSection();
Nicholas Wilson94d3b162018-03-05 12:33:58 +0000773 createRelocSections();
Sam Clegg99eb42c2018-02-27 23:58:03 +0000774 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000775 if (!Config->StripDebug && !Config->StripAll)
776 createNameSection();
777
778 for (OutputSection *S : OutputSections) {
779 S->setOffset(FileSize);
780 S->finalizeContents();
781 FileSize += S->getSize();
782 }
783}
784
Sam Cleggc94d3932017-11-17 18:14:09 +0000785void Writer::calculateImports() {
Sam Clegg574d7ce2017-12-15 19:23:49 +0000786 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000787 if (!Sym->isUndefined())
788 continue;
789 if (isa<DataSymbol>(Sym))
790 continue;
791 if (Sym->isWeak() && !Config->Relocatable)
Sam Clegg574d7ce2017-12-15 19:23:49 +0000792 continue;
Nicholas Wilsona1e299f2018-04-20 17:18:06 +0000793 if (!Sym->isLive())
794 continue;
Sam Cleggc729c1b2018-05-30 18:07:52 +0000795 if (!Sym->IsUsedInRegularObj)
796 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000797
Nicola Zaghene7245b42018-05-15 13:36:20 +0000798 LLVM_DEBUG(dbgs() << "import: " << Sym->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000799 ImportedSymbols.emplace_back(Sym);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000800 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
801 F->setFunctionIndex(NumImportedFunctions++);
Heejin Ahne915a712018-12-08 06:17:43 +0000802 else if (auto *G = dyn_cast<GlobalSymbol>(Sym))
803 G->setGlobalIndex(NumImportedGlobals++);
Sam Clegg93102972018-02-23 05:08:53 +0000804 else
Heejin Ahne915a712018-12-08 06:17:43 +0000805 cast<EventSymbol>(Sym)->setEventIndex(NumImportedEvents++);
Sam Cleggc94d3932017-11-17 18:14:09 +0000806 }
807}
808
Sam Cleggd3052d52018-01-18 23:40:49 +0000809void Writer::calculateExports() {
Sam Clegg93102972018-02-23 05:08:53 +0000810 if (Config->Relocatable)
811 return;
Sam Cleggf0d433d2018-02-02 22:59:56 +0000812
Sam Cleggd6beb322018-05-10 18:10:34 +0000813 if (!Config->Relocatable && !Config->ImportMemory)
814 Exports.push_back(WasmExport{"memory", WASM_EXTERNAL_MEMORY, 0});
815
816 if (!Config->Relocatable && Config->ExportTable)
817 Exports.push_back(WasmExport{kFunctionTableName, WASM_EXTERNAL_TABLE, 0});
818
819 unsigned FakeGlobalIndex = NumImportedGlobals + InputGlobals.size();
820
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000821 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Cleggce004bf2018-06-28 17:04:58 +0000822 if (!Sym->isExported())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000823 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000824 if (!Sym->isLive())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000825 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000826
Sam Cleggd6beb322018-05-10 18:10:34 +0000827 StringRef Name = Sym->getName();
828 WasmExport Export;
829 if (auto *F = dyn_cast<DefinedFunction>(Sym)) {
830 Export = {Name, WASM_EXTERNAL_FUNCTION, F->getFunctionIndex()};
831 } else if (auto *G = dyn_cast<DefinedGlobal>(Sym)) {
Sam Clegg177b4582018-06-07 01:27:07 +0000832 // TODO(sbc): Remove this check once to mutable global proposal is
833 // implement in all major browsers.
834 // See: https://github.com/WebAssembly/mutable-global
835 if (G->getGlobalType()->Mutable) {
836 // Only the __stack_pointer should ever be create as mutable.
837 assert(G == WasmSym::StackPointer);
838 continue;
839 }
Sam Cleggd6beb322018-05-10 18:10:34 +0000840 Export = {Name, WASM_EXTERNAL_GLOBAL, G->getGlobalIndex()};
Heejin Ahne915a712018-12-08 06:17:43 +0000841 } else if (auto *E = dyn_cast<DefinedEvent>(Sym)) {
842 Export = {Name, WASM_EXTERNAL_EVENT, E->getEventIndex()};
Sam Cleggd6beb322018-05-10 18:10:34 +0000843 } else {
844 auto *D = cast<DefinedData>(Sym);
Sam Clegg93102972018-02-23 05:08:53 +0000845 DefinedFakeGlobals.emplace_back(D);
Sam Cleggd6beb322018-05-10 18:10:34 +0000846 Export = {Name, WASM_EXTERNAL_GLOBAL, FakeGlobalIndex++};
847 }
848
Nicola Zaghene7245b42018-05-15 13:36:20 +0000849 LLVM_DEBUG(dbgs() << "Export: " << Name << "\n");
Sam Cleggd6beb322018-05-10 18:10:34 +0000850 Exports.push_back(Export);
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000851 }
Sam Clegg93102972018-02-23 05:08:53 +0000852}
853
854void Writer::assignSymtab() {
855 if (!Config->Relocatable)
856 return;
857
Sam Cleggd177ab22018-05-04 23:14:42 +0000858 StringMap<uint32_t> SectionSymbolIndices;
859
Sam Clegg93102972018-02-23 05:08:53 +0000860 unsigned SymbolIndex = SymtabEntries.size();
Sam Cleggd3052d52018-01-18 23:40:49 +0000861 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000862 LLVM_DEBUG(dbgs() << "Symtab entries: " << File->getName() << "\n");
Sam Cleggd3052d52018-01-18 23:40:49 +0000863 for (Symbol *Sym : File->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000864 if (Sym->getFile() != File)
Sam Cleggd3052d52018-01-18 23:40:49 +0000865 continue;
Sam Cleggd177ab22018-05-04 23:14:42 +0000866
867 if (auto *S = dyn_cast<SectionSymbol>(Sym)) {
868 StringRef Name = S->getName();
869 if (CustomSectionMapping.count(Name) == 0)
870 continue;
871
872 auto SSI = SectionSymbolIndices.find(Name);
873 if (SSI != SectionSymbolIndices.end()) {
874 Sym->setOutputSymbolIndex(SSI->second);
875 continue;
876 }
877
878 SectionSymbolIndices[Name] = SymbolIndex;
879 CustomSectionSymbols[Name] = cast<SectionSymbol>(Sym);
880
881 Sym->markLive();
882 }
883
Nicholas Wilson06e0d172018-03-07 11:15:47 +0000884 // (Since this is relocatable output, GC is not performed so symbols must
885 // be live.)
886 assert(Sym->isLive());
Sam Clegg93102972018-02-23 05:08:53 +0000887 Sym->setOutputSymbolIndex(SymbolIndex++);
888 SymtabEntries.emplace_back(Sym);
Sam Cleggd3052d52018-01-18 23:40:49 +0000889 }
890 }
891
Sam Clegg93102972018-02-23 05:08:53 +0000892 // For the moment, relocatable output doesn't contain any synthetic functions,
893 // so no need to look through the Symtab for symbols not referenced by
894 // Symtab->ObjectFiles.
Sam Cleggd3052d52018-01-18 23:40:49 +0000895}
896
Sam Cleggc375e4e2018-01-10 19:18:22 +0000897uint32_t Writer::lookupType(const WasmSignature &Sig) {
Sam Clegg8d027d62018-01-10 20:12:26 +0000898 auto It = TypeIndices.find(Sig);
899 if (It == TypeIndices.end()) {
Sam Cleggc375e4e2018-01-10 19:18:22 +0000900 error("type not found: " + toString(Sig));
Sam Clegg8d027d62018-01-10 20:12:26 +0000901 return 0;
902 }
903 return It->second;
Sam Cleggc375e4e2018-01-10 19:18:22 +0000904}
905
906uint32_t Writer::registerType(const WasmSignature &Sig) {
Sam Cleggb8621592017-11-30 01:40:08 +0000907 auto Pair = TypeIndices.insert(std::make_pair(Sig, Types.size()));
Sam Cleggc375e4e2018-01-10 19:18:22 +0000908 if (Pair.second) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000909 LLVM_DEBUG(dbgs() << "type " << toString(Sig) << "\n");
Sam Cleggb8621592017-11-30 01:40:08 +0000910 Types.push_back(&Sig);
Sam Cleggc375e4e2018-01-10 19:18:22 +0000911 }
Sam Cleggb8621592017-11-30 01:40:08 +0000912 return Pair.first->second;
913}
914
Sam Cleggc94d3932017-11-17 18:14:09 +0000915void Writer::calculateTypes() {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000916 // The output type section is the union of the following sets:
917 // 1. Any signature used in the TYPE relocation
918 // 2. The signatures of all imported functions
919 // 3. The signatures of all defined functions
Heejin Ahne915a712018-12-08 06:17:43 +0000920 // 4. The signatures of all imported events
921 // 5. The signatures of all defined events
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000922
Sam Cleggc94d3932017-11-17 18:14:09 +0000923 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000924 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
925 for (uint32_t I = 0; I < Types.size(); I++)
926 if (File->TypeIsUsed[I])
927 File->TypeMap[I] = registerType(Types[I]);
Sam Cleggc94d3932017-11-17 18:14:09 +0000928 }
Sam Clegg50686852018-01-12 18:35:13 +0000929
Heejin Ahne915a712018-12-08 06:17:43 +0000930 for (const Symbol *Sym : ImportedSymbols) {
Sam Clegg93102972018-02-23 05:08:53 +0000931 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
Heejin Ahne915a712018-12-08 06:17:43 +0000932 registerType(*F->Signature);
933 else if (auto *E = dyn_cast<EventSymbol>(Sym))
934 registerType(*E->Signature);
935 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000936
Sam Clegg9f934222018-02-21 18:29:23 +0000937 for (const InputFunction *F : InputFunctions)
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000938 registerType(F->Signature);
Heejin Ahne915a712018-12-08 06:17:43 +0000939
940 for (const InputEvent *E : InputEvents)
941 registerType(E->Signature);
Sam Cleggc94d3932017-11-17 18:14:09 +0000942}
943
Sam Clegg8d146bb2018-01-09 23:56:44 +0000944void Writer::assignIndexes() {
Heejin Ahnaeaab992018-11-19 23:21:25 +0000945 assert(InputFunctions.empty());
946 uint32_t FunctionIndex = NumImportedFunctions;
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000947 auto AddDefinedFunction = [&](InputFunction *Func) {
948 if (!Func->Live)
949 return;
950 InputFunctions.emplace_back(Func);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000951 Func->setFunctionIndex(FunctionIndex++);
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000952 };
953
Nicholas Wilson5639da82018-03-12 15:44:07 +0000954 for (InputFunction *Func : Symtab->SyntheticFunctions)
955 AddDefinedFunction(Func);
956
Sam Clegg87e61922018-01-08 23:39:11 +0000957 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000958 LLVM_DEBUG(dbgs() << "Functions: " << File->getName() << "\n");
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000959 for (InputFunction *Func : File->Functions)
960 AddDefinedFunction(Func);
Sam Clegg8d146bb2018-01-09 23:56:44 +0000961 }
962
Sam Cleggbfb75342018-11-15 00:37:21 +0000963 uint32_t TableIndex = TableBase;
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000964 auto HandleRelocs = [&](InputChunk *Chunk) {
965 if (!Chunk->Live)
966 return;
967 ObjFile *File = Chunk->File;
968 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
Sam Clegg93102972018-02-23 05:08:53 +0000969 for (const WasmRelocation &Reloc : Chunk->getRelocations()) {
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000970 if (Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_I32 ||
971 Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_SLEB) {
972 FunctionSymbol *Sym = File->getFunctionSymbol(Reloc.Index);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000973 if (Sym->hasTableIndex() || !Sym->hasFunctionIndex())
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000974 continue;
975 Sym->setTableIndex(TableIndex++);
976 IndirectFunctions.emplace_back(Sym);
977 } else if (Reloc.Type == R_WEBASSEMBLY_TYPE_INDEX_LEB) {
Sam Clegg93102972018-02-23 05:08:53 +0000978 // Mark target type as live
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000979 File->TypeMap[Reloc.Index] = registerType(Types[Reloc.Index]);
980 File->TypeIsUsed[Reloc.Index] = true;
981 }
982 }
983 };
984
Sam Clegg8d146bb2018-01-09 23:56:44 +0000985 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000986 LLVM_DEBUG(dbgs() << "Handle relocs: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000987 for (InputChunk *Chunk : File->Functions)
988 HandleRelocs(Chunk);
989 for (InputChunk *Chunk : File->Segments)
990 HandleRelocs(Chunk);
Sam Cleggd177ab22018-05-04 23:14:42 +0000991 for (auto &P : File->CustomSections)
992 HandleRelocs(P);
Sam Clegg93102972018-02-23 05:08:53 +0000993 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000994
Heejin Ahnaeaab992018-11-19 23:21:25 +0000995 assert(InputGlobals.empty());
996 uint32_t GlobalIndex = NumImportedGlobals;
Sam Clegg93102972018-02-23 05:08:53 +0000997 auto AddDefinedGlobal = [&](InputGlobal *Global) {
998 if (Global->Live) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000999 LLVM_DEBUG(dbgs() << "AddDefinedGlobal: " << GlobalIndex << "\n");
Sam Clegge3f3ccf2018-03-12 19:56:23 +00001000 Global->setGlobalIndex(GlobalIndex++);
Sam Clegg93102972018-02-23 05:08:53 +00001001 InputGlobals.push_back(Global);
1002 }
1003 };
1004
Nicholas Wilsonebda41f2018-03-09 16:43:05 +00001005 for (InputGlobal *Global : Symtab->SyntheticGlobals)
1006 AddDefinedGlobal(Global);
Sam Clegg93102972018-02-23 05:08:53 +00001007
1008 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001009 LLVM_DEBUG(dbgs() << "Globals: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +00001010 for (InputGlobal *Global : File->Globals)
1011 AddDefinedGlobal(Global);
Sam Cleggc94d3932017-11-17 18:14:09 +00001012 }
Heejin Ahne915a712018-12-08 06:17:43 +00001013
1014 assert(InputEvents.empty());
1015 uint32_t EventIndex = NumImportedEvents;
1016 auto AddDefinedEvent = [&](InputEvent *Event) {
1017 if (Event->Live) {
1018 LLVM_DEBUG(dbgs() << "AddDefinedEvent: " << EventIndex << "\n");
1019 Event->setEventIndex(EventIndex++);
1020 InputEvents.push_back(Event);
1021 }
1022 };
1023
1024 for (ObjFile *File : Symtab->ObjectFiles) {
1025 LLVM_DEBUG(dbgs() << "Events: " << File->getName() << "\n");
1026 for (InputEvent *Event : File->Events)
1027 AddDefinedEvent(Event);
1028 }
Sam Cleggc94d3932017-11-17 18:14:09 +00001029}
1030
1031static StringRef getOutputDataSegmentName(StringRef Name) {
Sam Cleggbfb75342018-11-15 00:37:21 +00001032 // With PIC code we currently only support a single data segment since
1033 // we only have a single __memory_base to use as our base address.
1034 if (Config->Pic)
1035 return "data";
Sam Clegg66844762018-05-10 18:23:51 +00001036 if (!Config->MergeDataSegments)
Sam Cleggc94d3932017-11-17 18:14:09 +00001037 return Name;
Rui Ueyama4764b572018-02-28 00:57:28 +00001038 if (Name.startswith(".text."))
1039 return ".text";
1040 if (Name.startswith(".data."))
1041 return ".data";
1042 if (Name.startswith(".bss."))
1043 return ".bss";
Sam Clegg57694c52018-08-08 18:02:55 +00001044 if (Name.startswith(".rodata."))
1045 return ".rodata";
Sam Cleggc94d3932017-11-17 18:14:09 +00001046 return Name;
1047}
1048
1049void Writer::createOutputSegments() {
1050 for (ObjFile *File : Symtab->ObjectFiles) {
1051 for (InputSegment *Segment : File->Segments) {
Sam Clegg447ae402018-02-13 20:29:38 +00001052 if (!Segment->Live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +00001053 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +00001054 StringRef Name = getOutputDataSegmentName(Segment->getName());
1055 OutputSegment *&S = SegmentMap[Name];
1056 if (S == nullptr) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001057 LLVM_DEBUG(dbgs() << "new segment: " << Name << "\n");
Sam Clegg93102972018-02-23 05:08:53 +00001058 S = make<OutputSegment>(Name, Segments.size());
Sam Cleggc94d3932017-11-17 18:14:09 +00001059 Segments.push_back(S);
1060 }
1061 S->addInputSegment(Segment);
Nicola Zaghene7245b42018-05-15 13:36:20 +00001062 LLVM_DEBUG(dbgs() << "added data: " << Name << ": " << S->Size << "\n");
Sam Cleggc94d3932017-11-17 18:14:09 +00001063 }
1064 }
1065}
1066
Sam Clegg50686852018-01-12 18:35:13 +00001067static const int OPCODE_CALL = 0x10;
1068static const int OPCODE_END = 0xb;
1069
1070// Create synthetic "__wasm_call_ctors" function based on ctor functions
1071// in input object.
1072void Writer::createCtorFunction() {
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +00001073 // First write the body's contents to a string.
1074 std::string BodyContent;
Sam Clegg50686852018-01-12 18:35:13 +00001075 {
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +00001076 raw_string_ostream OS(BodyContent);
Sam Clegg50686852018-01-12 18:35:13 +00001077 writeUleb128(OS, 0, "num locals");
Sam Clegg93102972018-02-23 05:08:53 +00001078 for (const WasmInitEntry &F : InitFunctions) {
Sam Clegg50686852018-01-12 18:35:13 +00001079 writeU8(OS, OPCODE_CALL, "CALL");
Sam Clegge3f3ccf2018-03-12 19:56:23 +00001080 writeUleb128(OS, F.Sym->getFunctionIndex(), "function index");
Sam Clegg50686852018-01-12 18:35:13 +00001081 }
1082 writeU8(OS, OPCODE_END, "END");
1083 }
1084
1085 // Once we know the size of the body we can create the final function body
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +00001086 std::string FunctionBody;
1087 {
1088 raw_string_ostream OS(FunctionBody);
1089 writeUleb128(OS, BodyContent.size(), "function size");
1090 OS << BodyContent;
1091 }
Rui Ueyama29abfe42018-02-28 17:43:15 +00001092
Sam Cleggea656472018-10-22 08:35:39 +00001093 ArrayRef<uint8_t> Body = arrayRefFromStringRef(Saver.save(FunctionBody));
Nicholas Wilsonebda41f2018-03-09 16:43:05 +00001094 cast<SyntheticFunction>(WasmSym::CallCtors->Function)->setBody(Body);
Sam Clegg50686852018-01-12 18:35:13 +00001095}
1096
1097// Populate InitFunctions vector with init functions from all input objects.
1098// This is then used either when creating the output linking section or to
1099// synthesize the "__wasm_call_ctors" function.
1100void Writer::calculateInitFunctions() {
1101 for (ObjFile *File : Symtab->ObjectFiles) {
1102 const WasmLinkingData &L = File->getWasmObj()->linkingData();
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +00001103 for (const WasmInitFunc &F : L.InitFunctions) {
1104 FunctionSymbol *Sym = File->getFunctionSymbol(F.Symbol);
Heejin Ahne915a712018-12-08 06:17:43 +00001105 if (*Sym->Signature != WasmSignature{{}, {}})
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +00001106 error("invalid signature for init func: " + toString(*Sym));
1107 InitFunctions.emplace_back(WasmInitEntry{Sym, F.Priority});
1108 }
Sam Clegg50686852018-01-12 18:35:13 +00001109 }
Rui Ueyamada69b712018-02-28 00:15:59 +00001110
Sam Clegg50686852018-01-12 18:35:13 +00001111 // Sort in order of priority (lowest first) so that they are called
1112 // in the correct order.
Sam Clegg29b8feb2018-02-21 00:34:34 +00001113 std::stable_sort(InitFunctions.begin(), InitFunctions.end(),
Sam Clegg93102972018-02-23 05:08:53 +00001114 [](const WasmInitEntry &L, const WasmInitEntry &R) {
Sam Clegg29b8feb2018-02-21 00:34:34 +00001115 return L.Priority < R.Priority;
1116 });
Sam Clegg50686852018-01-12 18:35:13 +00001117}
1118
Sam Cleggc94d3932017-11-17 18:14:09 +00001119void Writer::run() {
Sam Cleggbfb75342018-11-15 00:37:21 +00001120 if (Config->Relocatable || Config->Pic)
Sam Clegg99eb42c2018-02-27 23:58:03 +00001121 Config->GlobalBase = 0;
1122
Sam Cleggbfb75342018-11-15 00:37:21 +00001123 // For PIC code the table base is assigned dynamically by the loader.
1124 // For non-PIC, we start at 1 so that accessing table index 0 always traps.
1125 if (!Config->Pic)
1126 TableBase = 1;
1127
Sam Cleggc94d3932017-11-17 18:14:09 +00001128 log("-- calculateImports");
1129 calculateImports();
Sam Clegg8d146bb2018-01-09 23:56:44 +00001130 log("-- assignIndexes");
1131 assignIndexes();
Sam Clegg50686852018-01-12 18:35:13 +00001132 log("-- calculateInitFunctions");
1133 calculateInitFunctions();
1134 if (!Config->Relocatable)
1135 createCtorFunction();
Sam Clegg8f6d2de2018-01-31 23:48:14 +00001136 log("-- calculateTypes");
1137 calculateTypes();
Sam Clegg93102972018-02-23 05:08:53 +00001138 log("-- layoutMemory");
1139 layoutMemory();
1140 log("-- calculateExports");
1141 calculateExports();
Sam Cleggd177ab22018-05-04 23:14:42 +00001142 log("-- calculateCustomSections");
1143 calculateCustomSections();
Sam Clegg93102972018-02-23 05:08:53 +00001144 log("-- assignSymtab");
1145 assignSymtab();
Sam Cleggc94d3932017-11-17 18:14:09 +00001146
1147 if (errorHandler().Verbose) {
Sam Clegg9f934222018-02-21 18:29:23 +00001148 log("Defined Functions: " + Twine(InputFunctions.size()));
Sam Clegg93102972018-02-23 05:08:53 +00001149 log("Defined Globals : " + Twine(InputGlobals.size()));
Heejin Ahne915a712018-12-08 06:17:43 +00001150 log("Defined Events : " + Twine(InputEvents.size()));
Sam Clegg93102972018-02-23 05:08:53 +00001151 log("Function Imports : " + Twine(NumImportedFunctions));
1152 log("Global Imports : " + Twine(NumImportedGlobals));
Heejin Ahne915a712018-12-08 06:17:43 +00001153 log("Event Imports : " + Twine(NumImportedEvents));
Sam Cleggc94d3932017-11-17 18:14:09 +00001154 for (ObjFile *File : Symtab->ObjectFiles)
1155 File->dumpInfo();
1156 }
1157
Sam Cleggc94d3932017-11-17 18:14:09 +00001158 createHeader();
1159 log("-- createSections");
1160 createSections();
1161
1162 log("-- openFile");
1163 openFile();
1164 if (errorCount())
1165 return;
1166
1167 writeHeader();
1168
1169 log("-- writeSections");
1170 writeSections();
1171 if (errorCount())
1172 return;
1173
1174 if (Error E = Buffer->commit())
1175 fatal("failed to write the output file: " + toString(std::move(E)));
1176}
1177
1178// Open a result file.
1179void Writer::openFile() {
1180 log("writing: " + Config->OutputFile);
Sam Cleggc94d3932017-11-17 18:14:09 +00001181
1182 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
1183 FileOutputBuffer::create(Config->OutputFile, FileSize,
1184 FileOutputBuffer::F_executable);
1185
1186 if (!BufferOrErr)
1187 error("failed to open " + Config->OutputFile + ": " +
1188 toString(BufferOrErr.takeError()));
1189 else
1190 Buffer = std::move(*BufferOrErr);
1191}
1192
1193void Writer::createHeader() {
1194 raw_string_ostream OS(Header);
1195 writeBytes(OS, WasmMagic, sizeof(WasmMagic), "wasm magic");
1196 writeU32(OS, WasmVersion, "wasm version");
1197 OS.flush();
1198 FileSize += Header.size();
1199}
1200
1201void lld::wasm::writeResult() { Writer().run(); }