blob: 9ae020e0f61f39c065d417648eaf2aad757068d4 [file] [log] [blame]
Sam Cleggc94d3932017-11-17 18:14:09 +00001//===- Writer.cpp ---------------------------------------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Sam Cleggc94d3932017-11-17 18:14:09 +00006//
7//===----------------------------------------------------------------------===//
8
9#include "Writer.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000010#include "Config.h"
Sam Clegg5fa274b2018-01-10 01:13:34 +000011#include "InputChunks.h"
Heejin Ahne915a712018-12-08 06:17:43 +000012#include "InputEvent.h"
Sam Clegg93102972018-02-23 05:08:53 +000013#include "InputGlobal.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000014#include "OutputSections.h"
15#include "OutputSegment.h"
16#include "SymbolTable.h"
17#include "WriterUtils.h"
18#include "lld/Common/ErrorHandler.h"
Rui Ueyama2017d522017-11-28 20:39:17 +000019#include "lld/Common/Memory.h"
Nicholas Wilson8269f372018-03-07 10:37:50 +000020#include "lld/Common/Strings.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000021#include "lld/Common/Threads.h"
Sam Clegg3141ddc2018-02-20 21:53:18 +000022#include "llvm/ADT/DenseSet.h"
Thomas Lively2a0868f2019-01-17 02:29:41 +000023#include "llvm/ADT/SmallVector.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();
Thomas Lively2a0868f2019-01-17 02:29:41 +000098 void createProducersSection();
Sam Cleggc94d3932017-11-17 18:14:09 +000099
100 void writeHeader();
101 void writeSections();
102
103 uint64_t FileSize = 0;
Sam Cleggbfb75342018-11-15 00:37:21 +0000104 uint32_t TableBase = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000105 uint32_t NumMemoryPages = 0;
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000106 uint32_t MaxMemoryPages = 0;
Sam Cleggbfb75342018-11-15 00:37:21 +0000107 // Memory size and aligment. Written to the "dylink" section
108 // when build with -shared or -pie.
109 uint32_t MemAlign = 0;
110 uint32_t MemSize = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000111
112 std::vector<const WasmSignature *> Types;
Nicholas Wilson3e3f5fb2018-03-14 15:58:16 +0000113 DenseMap<WasmSignature, int32_t> TypeIndices;
Sam Clegg93102972018-02-23 05:08:53 +0000114 std::vector<const Symbol *> ImportedSymbols;
115 unsigned NumImportedFunctions = 0;
116 unsigned NumImportedGlobals = 0;
Heejin Ahne915a712018-12-08 06:17:43 +0000117 unsigned NumImportedEvents = 0;
Sam Cleggd6beb322018-05-10 18:10:34 +0000118 std::vector<WasmExport> Exports;
Sam Clegg93102972018-02-23 05:08:53 +0000119 std::vector<const DefinedData *> DefinedFakeGlobals;
120 std::vector<InputGlobal *> InputGlobals;
Sam Clegg9f934222018-02-21 18:29:23 +0000121 std::vector<InputFunction *> InputFunctions;
Heejin Ahne915a712018-12-08 06:17:43 +0000122 std::vector<InputEvent *> InputEvents;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000123 std::vector<const FunctionSymbol *> IndirectFunctions;
Sam Clegg93102972018-02-23 05:08:53 +0000124 std::vector<const Symbol *> SymtabEntries;
125 std::vector<WasmInitEntry> InitFunctions;
Sam Cleggc94d3932017-11-17 18:14:09 +0000126
Sam Clegg80ba4382018-04-10 16:12:49 +0000127 llvm::StringMap<std::vector<InputSection *>> CustomSectionMapping;
Sam Cleggd177ab22018-05-04 23:14:42 +0000128 llvm::StringMap<SectionSymbol *> CustomSectionSymbols;
Sam Clegg80ba4382018-04-10 16:12:49 +0000129
Sam Cleggc94d3932017-11-17 18:14:09 +0000130 // Elements that are used to construct the final output
131 std::string Header;
132 std::vector<OutputSection *> OutputSections;
133
134 std::unique_ptr<FileOutputBuffer> Buffer;
135
136 std::vector<OutputSegment *> Segments;
137 llvm::SmallDenseMap<StringRef, OutputSegment *> SegmentMap;
138};
139
140} // anonymous namespace
141
Sam Cleggc94d3932017-11-17 18:14:09 +0000142void Writer::createImportSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000143 uint32_t NumImports = ImportedSymbols.size();
Sam Cleggc94d3932017-11-17 18:14:09 +0000144 if (Config->ImportMemory)
145 ++NumImports;
Nicholas Wilsonfc90b302018-03-28 12:53:29 +0000146 if (Config->ImportTable)
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000147 ++NumImports;
Sam Cleggc94d3932017-11-17 18:14:09 +0000148
149 if (NumImports == 0)
150 return;
151
152 SyntheticSection *Section = createSyntheticSection(WASM_SEC_IMPORT);
153 raw_ostream &OS = Section->getStream();
154
155 writeUleb128(OS, NumImports, "import count");
156
Sam Cleggc94d3932017-11-17 18:14:09 +0000157 if (Config->ImportMemory) {
158 WasmImport Import;
159 Import.Module = "env";
160 Import.Field = "memory";
161 Import.Kind = WASM_EXTERNAL_MEMORY;
162 Import.Memory.Flags = 0;
163 Import.Memory.Initial = NumMemoryPages;
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000164 if (MaxMemoryPages != 0) {
165 Import.Memory.Flags |= WASM_LIMITS_FLAG_HAS_MAX;
166 Import.Memory.Maximum = MaxMemoryPages;
167 }
Derek Schuff786760a2018-11-06 18:02:39 +0000168 if (Config->SharedMemory)
Derek Schuff3bea8bc2018-11-06 17:59:32 +0000169 Import.Memory.Flags |= WASM_LIMITS_FLAG_IS_SHARED;
Sam Cleggc94d3932017-11-17 18:14:09 +0000170 writeImport(OS, Import);
171 }
172
Nicholas Wilsonfc90b302018-03-28 12:53:29 +0000173 if (Config->ImportTable) {
Sam Cleggbfb75342018-11-15 00:37:21 +0000174 uint32_t TableSize = TableBase + IndirectFunctions.size();
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000175 WasmImport Import;
176 Import.Module = "env";
177 Import.Field = kFunctionTableName;
178 Import.Kind = WASM_EXTERNAL_TABLE;
Thomas Lively25ff8932019-01-08 06:25:55 +0000179 Import.Table.ElemType = WASM_TYPE_FUNCREF;
Sam Clegg748f59cae2018-12-03 22:37:55 +0000180 Import.Table.Limits = {0, TableSize, 0};
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000181 writeImport(OS, Import);
182 }
183
Sam Clegg93102972018-02-23 05:08:53 +0000184 for (const Symbol *Sym : ImportedSymbols) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000185 WasmImport Import;
186 Import.Module = "env";
187 Import.Field = Sym->getName();
Sam Clegg93102972018-02-23 05:08:53 +0000188 if (auto *FunctionSym = dyn_cast<FunctionSymbol>(Sym)) {
189 Import.Kind = WASM_EXTERNAL_FUNCTION;
Heejin Ahne915a712018-12-08 06:17:43 +0000190 Import.SigIndex = lookupType(*FunctionSym->Signature);
191 } else if (auto *GlobalSym = dyn_cast<GlobalSymbol>(Sym)) {
Sam Clegg93102972018-02-23 05:08:53 +0000192 Import.Kind = WASM_EXTERNAL_GLOBAL;
193 Import.Global = *GlobalSym->getGlobalType();
Heejin Ahne915a712018-12-08 06:17:43 +0000194 } else {
195 auto *EventSym = cast<EventSymbol>(Sym);
196 Import.Kind = WASM_EXTERNAL_EVENT;
197 Import.Event.Attribute = EventSym->getEventType()->Attribute;
198 Import.Event.SigIndex = lookupType(*EventSym->Signature);
Sam Clegg93102972018-02-23 05:08:53 +0000199 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000200 writeImport(OS, Import);
201 }
202}
203
204void Writer::createTypeSection() {
205 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TYPE);
206 raw_ostream &OS = Section->getStream();
207 writeUleb128(OS, Types.size(), "type count");
Sam Cleggd451da12017-12-19 19:56:27 +0000208 for (const WasmSignature *Sig : Types)
Sam Cleggc94d3932017-11-17 18:14:09 +0000209 writeSig(OS, *Sig);
Sam Cleggc94d3932017-11-17 18:14:09 +0000210}
211
212void Writer::createFunctionSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000213 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000214 return;
215
216 SyntheticSection *Section = createSyntheticSection(WASM_SEC_FUNCTION);
217 raw_ostream &OS = Section->getStream();
218
Sam Clegg9f934222018-02-21 18:29:23 +0000219 writeUleb128(OS, InputFunctions.size(), "function count");
220 for (const InputFunction *Func : InputFunctions)
Sam Cleggc375e4e2018-01-10 19:18:22 +0000221 writeUleb128(OS, lookupType(Func->Signature), "sig index");
Sam Cleggc94d3932017-11-17 18:14:09 +0000222}
223
224void Writer::createMemorySection() {
225 if (Config->ImportMemory)
226 return;
227
228 SyntheticSection *Section = createSyntheticSection(WASM_SEC_MEMORY);
229 raw_ostream &OS = Section->getStream();
230
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000231 bool HasMax = MaxMemoryPages != 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000232 writeUleb128(OS, 1, "memory count");
Derek Schuff786760a2018-11-06 18:02:39 +0000233 unsigned Flags = 0;
234 if (HasMax)
235 Flags |= WASM_LIMITS_FLAG_HAS_MAX;
Derek Schuff3bea8bc2018-11-06 17:59:32 +0000236 if (Config->SharedMemory)
237 Flags |= WASM_LIMITS_FLAG_IS_SHARED;
238 writeUleb128(OS, Flags, "memory limits flags");
Sam Cleggc94d3932017-11-17 18:14:09 +0000239 writeUleb128(OS, NumMemoryPages, "initial pages");
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000240 if (HasMax)
241 writeUleb128(OS, MaxMemoryPages, "max pages");
Sam Cleggc94d3932017-11-17 18:14:09 +0000242}
243
244void Writer::createGlobalSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000245 unsigned NumGlobals = InputGlobals.size() + DefinedFakeGlobals.size();
246 if (NumGlobals == 0)
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000247 return;
248
Sam Cleggc94d3932017-11-17 18:14:09 +0000249 SyntheticSection *Section = createSyntheticSection(WASM_SEC_GLOBAL);
250 raw_ostream &OS = Section->getStream();
251
Sam Clegg93102972018-02-23 05:08:53 +0000252 writeUleb128(OS, NumGlobals, "global count");
253 for (const InputGlobal *G : InputGlobals)
254 writeGlobal(OS, G->Global);
255 for (const DefinedData *Sym : DefinedFakeGlobals) {
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000256 WasmGlobal Global;
Sam Clegg93102972018-02-23 05:08:53 +0000257 Global.Type = {WASM_TYPE_I32, false};
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000258 Global.InitExpr.Opcode = WASM_OPCODE_I32_CONST;
259 Global.InitExpr.Value.Int32 = Sym->getVirtualAddress();
Sam Cleggc94d3932017-11-17 18:14:09 +0000260 writeGlobal(OS, Global);
261 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000262}
263
Heejin Ahne915a712018-12-08 06:17:43 +0000264// The event section contains a list of declared wasm events associated with the
265// module. Currently the only supported event kind is exceptions. A single event
266// entry represents a single event with an event tag. All C++ exceptions are
267// represented by a single event. An event entry in this section contains
268// information on what kind of event it is (e.g. exception) and the type of
269// values contained in a single event object. (In wasm, an event can contain
270// multiple values of primitive types. But for C++ exceptions, we just throw a
271// pointer which is an i32 value (for wasm32 architecture), so the signature of
272// C++ exception is (i32)->(void), because all event types are assumed to have
273// void return type to share WasmSignature with functions.)
274void Writer::createEventSection() {
275 unsigned NumEvents = InputEvents.size();
276 if (NumEvents == 0)
277 return;
278
279 SyntheticSection *Section = createSyntheticSection(WASM_SEC_EVENT);
280 raw_ostream &OS = Section->getStream();
281
282 writeUleb128(OS, NumEvents, "event count");
283 for (InputEvent *E : InputEvents) {
284 E->Event.Type.SigIndex = lookupType(E->Signature);
285 writeEvent(OS, E->Event);
286 }
287}
288
Sam Cleggc94d3932017-11-17 18:14:09 +0000289void Writer::createTableSection() {
Nicholas Wilsonfc90b302018-03-28 12:53:29 +0000290 if (Config->ImportTable)
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000291 return;
292
293 // Always output a table section (or table import), even if there are no
294 // indirect calls. There are two reasons for this:
Sam Cleggfc1a9122017-12-11 22:00:56 +0000295 // 1. For executables it is useful to have an empty table slot at 0
296 // which can be filled with a null function call handler.
297 // 2. If we don't do this, any program that contains a call_indirect but
298 // no address-taken function will fail at validation time since it is
299 // a validation error to include a call_indirect instruction if there
300 // is not table.
Sam Cleggbfb75342018-11-15 00:37:21 +0000301 uint32_t TableSize = TableBase + IndirectFunctions.size();
Sam Cleggfc1a9122017-12-11 22:00:56 +0000302
Sam Cleggc94d3932017-11-17 18:14:09 +0000303 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TABLE);
304 raw_ostream &OS = Section->getStream();
305
306 writeUleb128(OS, 1, "table count");
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000307 WasmLimits Limits = {WASM_LIMITS_FLAG_HAS_MAX, TableSize, TableSize};
Thomas Lively25ff8932019-01-08 06:25:55 +0000308 writeTableType(OS, WasmTable{WASM_TYPE_FUNCREF, Limits});
Sam Cleggc94d3932017-11-17 18:14:09 +0000309}
310
311void Writer::createExportSection() {
Sam Cleggd6beb322018-05-10 18:10:34 +0000312 if (!Exports.size())
Sam Cleggc94d3932017-11-17 18:14:09 +0000313 return;
314
315 SyntheticSection *Section = createSyntheticSection(WASM_SEC_EXPORT);
316 raw_ostream &OS = Section->getStream();
317
Sam Cleggd6beb322018-05-10 18:10:34 +0000318 writeUleb128(OS, Exports.size(), "export count");
319 for (const WasmExport &Export : Exports)
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000320 writeExport(OS, Export);
Sam Cleggc94d3932017-11-17 18:14:09 +0000321}
322
Sam Cleggd177ab22018-05-04 23:14:42 +0000323void Writer::calculateCustomSections() {
324 log("calculateCustomSections");
325 bool StripDebug = Config->StripDebug || Config->StripAll;
326 for (ObjFile *File : Symtab->ObjectFiles) {
327 for (InputSection *Section : File->CustomSections) {
328 StringRef Name = Section->getName();
329 // These custom sections are known the linker and synthesized rather than
330 // blindly copied
Thomas Lively2a0868f2019-01-17 02:29:41 +0000331 if (Name == "linking" || Name == "name" || Name == "producers" ||
332 Name.startswith("reloc."))
Sam Cleggd177ab22018-05-04 23:14:42 +0000333 continue;
334 // .. or it is a debug section
335 if (StripDebug && Name.startswith(".debug_"))
336 continue;
337 CustomSectionMapping[Name].push_back(Section);
338 }
339 }
340}
341
Sam Clegg80ba4382018-04-10 16:12:49 +0000342void Writer::createCustomSections() {
343 log("createCustomSections");
Sam Clegg80ba4382018-04-10 16:12:49 +0000344 for (auto &Pair : CustomSectionMapping) {
345 StringRef Name = Pair.first();
Sam Cleggd177ab22018-05-04 23:14:42 +0000346
347 auto P = CustomSectionSymbols.find(Name);
348 if (P != CustomSectionSymbols.end()) {
349 uint32_t SectionIndex = OutputSections.size();
350 P->second->setOutputSectionIndex(SectionIndex);
351 }
352
Nicola Zaghene7245b42018-05-15 13:36:20 +0000353 LLVM_DEBUG(dbgs() << "createCustomSection: " << Name << "\n");
Sam Clegg80ba4382018-04-10 16:12:49 +0000354 OutputSections.push_back(make<CustomSection>(Name, Pair.second));
355 }
356}
357
Sam Cleggc94d3932017-11-17 18:14:09 +0000358void Writer::createElemSection() {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000359 if (IndirectFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000360 return;
361
362 SyntheticSection *Section = createSyntheticSection(WASM_SEC_ELEM);
363 raw_ostream &OS = Section->getStream();
364
365 writeUleb128(OS, 1, "segment count");
366 writeUleb128(OS, 0, "table index");
367 WasmInitExpr InitExpr;
Sam Cleggbfb75342018-11-15 00:37:21 +0000368 if (Config->Pic) {
Thomas Lively25ff8932019-01-08 06:25:55 +0000369 InitExpr.Opcode = WASM_OPCODE_GLOBAL_GET;
Sam Clegg2dad4e22018-11-15 18:15:54 +0000370 InitExpr.Value.Global = WasmSym::TableBase->getGlobalIndex();
Sam Cleggbfb75342018-11-15 00:37:21 +0000371 } else {
372 InitExpr.Opcode = WASM_OPCODE_I32_CONST;
373 InitExpr.Value.Int32 = TableBase;
374 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000375 writeInitExpr(OS, InitExpr);
Sam Cleggfc1a9122017-12-11 22:00:56 +0000376 writeUleb128(OS, IndirectFunctions.size(), "elem count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000377
Sam Cleggbfb75342018-11-15 00:37:21 +0000378 uint32_t TableIndex = TableBase;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000379 for (const FunctionSymbol *Sym : IndirectFunctions) {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000380 assert(Sym->getTableIndex() == TableIndex);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000381 writeUleb128(OS, Sym->getFunctionIndex(), "function index");
Sam Cleggfc1a9122017-12-11 22:00:56 +0000382 ++TableIndex;
383 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000384}
385
386void Writer::createCodeSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000387 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000388 return;
389
390 log("createCodeSection");
391
Sam Clegg9f934222018-02-21 18:29:23 +0000392 auto Section = make<CodeSection>(InputFunctions);
Sam Cleggc94d3932017-11-17 18:14:09 +0000393 OutputSections.push_back(Section);
394}
395
396void Writer::createDataSection() {
397 if (!Segments.size())
398 return;
399
400 log("createDataSection");
401 auto Section = make<DataSection>(Segments);
402 OutputSections.push_back(Section);
403}
404
Sam Cleggd451da12017-12-19 19:56:27 +0000405// Create relocations sections in the final output.
Sam Cleggc94d3932017-11-17 18:14:09 +0000406// These are only created when relocatable output is requested.
407void Writer::createRelocSections() {
408 log("createRelocSections");
409 // Don't use iterator here since we are adding to OutputSection
410 size_t OrigSize = OutputSections.size();
Rui Ueyamaffa650a2018-04-24 23:09:57 +0000411 for (size_t I = 0; I < OrigSize; I++) {
412 OutputSection *OSec = OutputSections[I];
Rui Ueyama37254062018-02-28 00:01:31 +0000413 uint32_t Count = OSec->numRelocations();
Sam Cleggc94d3932017-11-17 18:14:09 +0000414 if (!Count)
415 continue;
416
Rui Ueyama37254062018-02-28 00:01:31 +0000417 StringRef Name;
418 if (OSec->Type == WASM_SEC_DATA)
419 Name = "reloc.DATA";
420 else if (OSec->Type == WASM_SEC_CODE)
421 Name = "reloc.CODE";
Sam Cleggd177ab22018-05-04 23:14:42 +0000422 else if (OSec->Type == WASM_SEC_CUSTOM)
423 Name = Saver.save("reloc." + OSec->Name);
Sam Cleggc94d3932017-11-17 18:14:09 +0000424 else
Sam Cleggd177ab22018-05-04 23:14:42 +0000425 llvm_unreachable(
426 "relocations only supported for code, data, or custom sections");
Sam Cleggc94d3932017-11-17 18:14:09 +0000427
Rui Ueyama37254062018-02-28 00:01:31 +0000428 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, Name);
Sam Cleggc94d3932017-11-17 18:14:09 +0000429 raw_ostream &OS = Section->getStream();
Rui Ueyamaffa650a2018-04-24 23:09:57 +0000430 writeUleb128(OS, I, "reloc section");
Sam Cleggc94d3932017-11-17 18:14:09 +0000431 writeUleb128(OS, Count, "reloc count");
Rui Ueyama37254062018-02-28 00:01:31 +0000432 OSec->writeRelocations(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000433 }
434}
435
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000436static uint32_t getWasmFlags(const Symbol *Sym) {
437 uint32_t Flags = 0;
438 if (Sym->isLocal())
439 Flags |= WASM_SYMBOL_BINDING_LOCAL;
440 if (Sym->isWeak())
441 Flags |= WASM_SYMBOL_BINDING_WEAK;
442 if (Sym->isHidden())
443 Flags |= WASM_SYMBOL_VISIBILITY_HIDDEN;
444 if (Sym->isUndefined())
445 Flags |= WASM_SYMBOL_UNDEFINED;
446 return Flags;
447}
448
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000449// Some synthetic sections (e.g. "name" and "linking") have subsections.
450// Just like the synthetic sections themselves these need to be created before
451// they can be written out (since they are preceded by their length). This
452// class is used to create subsections and then write them into the stream
453// of the parent section.
454class SubSection {
455public:
456 explicit SubSection(uint32_t Type) : Type(Type) {}
457
458 void writeTo(raw_ostream &To) {
459 OS.flush();
Rui Ueyama67769102018-02-28 03:38:14 +0000460 writeUleb128(To, Type, "subsection type");
461 writeUleb128(To, Body.size(), "subsection size");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000462 To.write(Body.data(), Body.size());
463 }
464
465private:
466 uint32_t Type;
467 std::string Body;
468
469public:
470 raw_string_ostream OS{Body};
471};
472
Sam Cleggbfb75342018-11-15 00:37:21 +0000473// Create the custom "dylink" section containing information for the dynamic
474// linker.
475// See
476// https://github.com/WebAssembly/tool-conventions/blob/master/DynamicLinking.md
477void Writer::createDylinkSection() {
478 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "dylink");
479 raw_ostream &OS = Section->getStream();
480
481 writeUleb128(OS, MemSize, "MemSize");
Sam Clegg6320efb2019-01-16 01:43:21 +0000482 writeUleb128(OS, MemAlign, "MemAlign");
Sam Cleggbfb75342018-11-15 00:37:21 +0000483 writeUleb128(OS, IndirectFunctions.size(), "TableSize");
484 writeUleb128(OS, 0, "TableAlign");
Sam Clegge01c6462018-12-12 23:44:59 +0000485 writeUleb128(OS, 0, "Needed"); // TODO: Support "needed" shared libraries
Sam Cleggbfb75342018-11-15 00:37:21 +0000486}
487
Sam Clegg49ed9262017-12-01 00:53:21 +0000488// Create the custom "linking" section containing linker metadata.
Sam Cleggc94d3932017-11-17 18:14:09 +0000489// This is only created when relocatable output is requested.
490void Writer::createLinkingSection() {
491 SyntheticSection *Section =
492 createSyntheticSection(WASM_SEC_CUSTOM, "linking");
493 raw_ostream &OS = Section->getStream();
494
Sam Clegg2b8b1792018-04-26 18:17:21 +0000495 writeUleb128(OS, WasmMetadataVersion, "Version");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000496
Sam Clegg93102972018-02-23 05:08:53 +0000497 if (!SymtabEntries.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000498 SubSection Sub(WASM_SYMBOL_TABLE);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000499 writeUleb128(Sub.OS, SymtabEntries.size(), "num symbols");
500
Sam Clegg93102972018-02-23 05:08:53 +0000501 for (const Symbol *Sym : SymtabEntries) {
502 assert(Sym->isDefined() || Sym->isUndefined());
503 WasmSymbolType Kind = Sym->getWasmType();
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000504 uint32_t Flags = getWasmFlags(Sym);
505
Sam Clegg8518e7d2018-03-01 18:06:39 +0000506 writeU8(Sub.OS, Kind, "sym kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000507 writeUleb128(Sub.OS, Flags, "sym flags");
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000508
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000509 if (auto *F = dyn_cast<FunctionSymbol>(Sym)) {
510 writeUleb128(Sub.OS, F->getFunctionIndex(), "index");
Sam Clegg93102972018-02-23 05:08:53 +0000511 if (Sym->isDefined())
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000512 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000513 } else if (auto *G = dyn_cast<GlobalSymbol>(Sym)) {
514 writeUleb128(Sub.OS, G->getGlobalIndex(), "index");
515 if (Sym->isDefined())
516 writeStr(Sub.OS, Sym->getName(), "sym name");
Heejin Ahne915a712018-12-08 06:17:43 +0000517 } else if (auto *E = dyn_cast<EventSymbol>(Sym)) {
518 writeUleb128(Sub.OS, E->getEventIndex(), "index");
519 if (Sym->isDefined())
520 writeStr(Sub.OS, Sym->getName(), "sym name");
Andrea Di Biagio25c1a2f2018-05-05 10:53:31 +0000521 } else if (isa<DataSymbol>(Sym)) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000522 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegg93102972018-02-23 05:08:53 +0000523 if (auto *DataSym = dyn_cast<DefinedData>(Sym)) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000524 writeUleb128(Sub.OS, DataSym->getOutputSegmentIndex(), "index");
525 writeUleb128(Sub.OS, DataSym->getOutputSegmentOffset(),
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000526 "data offset");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000527 writeUleb128(Sub.OS, DataSym->getSize(), "data size");
Sam Clegg93102972018-02-23 05:08:53 +0000528 }
Sam Cleggd177ab22018-05-04 23:14:42 +0000529 } else {
530 auto *S = cast<SectionSymbol>(Sym);
531 writeUleb128(Sub.OS, S->getOutputSectionIndex(), "sym section index");
Sam Clegg93102972018-02-23 05:08:53 +0000532 }
Sam Cleggd3052d52018-01-18 23:40:49 +0000533 }
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000534
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000535 Sub.writeTo(OS);
Sam Cleggd3052d52018-01-18 23:40:49 +0000536 }
537
Sam Clegg0d0dd392017-12-19 17:09:45 +0000538 if (Segments.size()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000539 SubSection Sub(WASM_SEGMENT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000540 writeUleb128(Sub.OS, Segments.size(), "num data segments");
Sam Cleggc94d3932017-11-17 18:14:09 +0000541 for (const OutputSegment *S : Segments) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000542 writeStr(Sub.OS, S->Name, "segment name");
543 writeUleb128(Sub.OS, S->Alignment, "alignment");
544 writeUleb128(Sub.OS, 0, "flags");
Sam Cleggc94d3932017-11-17 18:14:09 +0000545 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000546 Sub.writeTo(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000547 }
Sam Clegg0d0dd392017-12-19 17:09:45 +0000548
Sam Clegg0d0dd392017-12-19 17:09:45 +0000549 if (!InitFunctions.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000550 SubSection Sub(WASM_INIT_FUNCS);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000551 writeUleb128(Sub.OS, InitFunctions.size(), "num init functions");
Sam Clegg93102972018-02-23 05:08:53 +0000552 for (const WasmInitEntry &F : InitFunctions) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000553 writeUleb128(Sub.OS, F.Priority, "priority");
554 writeUleb128(Sub.OS, F.Sym->getOutputSymbolIndex(), "function index");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000555 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000556 Sub.writeTo(OS);
Sam Clegg0d0dd392017-12-19 17:09:45 +0000557 }
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000558
Nicholas Wilsondbd90bf2018-03-07 13:28:16 +0000559 struct ComdatEntry {
560 unsigned Kind;
561 uint32_t Index;
562 };
563 std::map<StringRef, std::vector<ComdatEntry>> Comdats;
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000564
Sam Clegg9f934222018-02-21 18:29:23 +0000565 for (const InputFunction *F : InputFunctions) {
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000566 StringRef Comdat = F->getComdatName();
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000567 if (!Comdat.empty())
568 Comdats[Comdat].emplace_back(
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000569 ComdatEntry{WASM_COMDAT_FUNCTION, F->getFunctionIndex()});
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000570 }
571 for (uint32_t I = 0; I < Segments.size(); ++I) {
Sam Cleggf98bccf2018-01-13 15:57:48 +0000572 const auto &InputSegments = Segments[I]->InputSegments;
573 if (InputSegments.empty())
574 continue;
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000575 StringRef Comdat = InputSegments[0]->getComdatName();
Sam Clegga697df522018-01-13 15:59:53 +0000576#ifndef NDEBUG
Sam Cleggf98bccf2018-01-13 15:57:48 +0000577 for (const InputSegment *IS : InputSegments)
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000578 assert(IS->getComdatName() == Comdat);
Sam Clegga697df522018-01-13 15:59:53 +0000579#endif
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000580 if (!Comdat.empty())
581 Comdats[Comdat].emplace_back(ComdatEntry{WASM_COMDAT_DATA, I});
582 }
583
584 if (!Comdats.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000585 SubSection Sub(WASM_COMDAT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000586 writeUleb128(Sub.OS, Comdats.size(), "num comdats");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000587 for (const auto &C : Comdats) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000588 writeStr(Sub.OS, C.first, "comdat name");
589 writeUleb128(Sub.OS, 0, "comdat flags"); // flags for future use
590 writeUleb128(Sub.OS, C.second.size(), "num entries");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000591 for (const ComdatEntry &Entry : C.second) {
Sam Clegg8518e7d2018-03-01 18:06:39 +0000592 writeU8(Sub.OS, Entry.Kind, "entry kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000593 writeUleb128(Sub.OS, Entry.Index, "entry index");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000594 }
595 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000596 Sub.writeTo(OS);
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000597 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000598}
599
600// Create the custom "name" section containing debug symbol names.
601void Writer::createNameSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000602 unsigned NumNames = NumImportedFunctions;
Sam Clegg9f934222018-02-21 18:29:23 +0000603 for (const InputFunction *F : InputFunctions)
Nicholas Wilson6c7fe302018-04-20 17:09:18 +0000604 if (!F->getName().empty() || !F->getDebugName().empty())
Sam Clegg1963d712018-01-17 20:19:04 +0000605 ++NumNames;
Sam Cleggc94d3932017-11-17 18:14:09 +0000606
Sam Clegg1963d712018-01-17 20:19:04 +0000607 if (NumNames == 0)
608 return;
Sam Clegg50686852018-01-12 18:35:13 +0000609
Sam Cleggc94d3932017-11-17 18:14:09 +0000610 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "name");
611
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000612 SubSection Sub(WASM_NAMES_FUNCTION);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000613 writeUleb128(Sub.OS, NumNames, "name count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000614
Sam Clegg93102972018-02-23 05:08:53 +0000615 // Names must appear in function index order. As it happens ImportedSymbols
616 // and InputFunctions are numbered in order with imported functions coming
Sam Clegg1963d712018-01-17 20:19:04 +0000617 // first.
Sam Clegg93102972018-02-23 05:08:53 +0000618 for (const Symbol *S : ImportedSymbols) {
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000619 if (auto *F = dyn_cast<FunctionSymbol>(S)) {
620 writeUleb128(Sub.OS, F->getFunctionIndex(), "func index");
Sam Clegg37125f02018-11-09 16:57:41 +0000621 writeStr(Sub.OS, toString(*S), "symbol name");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000622 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000623 }
Sam Clegg9f934222018-02-21 18:29:23 +0000624 for (const InputFunction *F : InputFunctions) {
Sam Clegg1963d712018-01-17 20:19:04 +0000625 if (!F->getName().empty()) {
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000626 writeUleb128(Sub.OS, F->getFunctionIndex(), "func index");
Nicholas Wilson6c7fe302018-04-20 17:09:18 +0000627 if (!F->getDebugName().empty()) {
628 writeStr(Sub.OS, F->getDebugName(), "symbol name");
629 } else {
Sam Clegg37125f02018-11-09 16:57:41 +0000630 writeStr(Sub.OS, maybeDemangleSymbol(F->getName()), "symbol name");
Nicholas Wilson6c7fe302018-04-20 17:09:18 +0000631 }
Sam Clegg1963d712018-01-17 20:19:04 +0000632 }
633 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000634
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000635 Sub.writeTo(Section->getStream());
Sam Cleggc94d3932017-11-17 18:14:09 +0000636}
637
Thomas Lively2a0868f2019-01-17 02:29:41 +0000638void Writer::createProducersSection() {
639 SmallVector<std::pair<std::string, std::string>, 8> Languages;
640 SmallVector<std::pair<std::string, std::string>, 8> Tools;
641 SmallVector<std::pair<std::string, std::string>, 8> SDKs;
642 for (ObjFile *File : Symtab->ObjectFiles) {
643 const WasmProducerInfo &Info = File->getWasmObj()->getProducerInfo();
644 for (auto &Producers : {std::make_pair(&Info.Languages, &Languages),
645 std::make_pair(&Info.Tools, &Tools),
646 std::make_pair(&Info.SDKs, &SDKs)})
647 for (auto &Producer : *Producers.first)
648 if (Producers.second->end() ==
649 std::find_if(Producers.second->begin(), Producers.second->end(),
650 [&](std::pair<std::string, std::string> Seen) {
651 return Seen.first == Producer.first;
652 }))
653 Producers.second->push_back(Producer);
654 }
655 int FieldCount =
656 int(!Languages.empty()) + int(!Tools.empty()) + int(!SDKs.empty());
657 if (FieldCount == 0)
658 return;
659 SyntheticSection *Section =
660 createSyntheticSection(WASM_SEC_CUSTOM, "producers");
661 auto &OS = Section->getStream();
662 writeUleb128(OS, FieldCount, "field count");
663 for (auto &Field :
664 {std::make_pair("language", Languages),
665 std::make_pair("processed-by", Tools), std::make_pair("sdk", SDKs)}) {
666 if (Field.second.empty())
667 continue;
668 writeStr(OS, Field.first, "field name");
669 writeUleb128(OS, Field.second.size(), "number of entries");
670 for (auto &Entry : Field.second) {
671 writeStr(OS, Entry.first, "producer name");
672 writeStr(OS, Entry.second, "producer version");
673 }
674 }
675}
676
Sam Cleggc94d3932017-11-17 18:14:09 +0000677void Writer::writeHeader() {
678 memcpy(Buffer->getBufferStart(), Header.data(), Header.size());
679}
680
681void Writer::writeSections() {
682 uint8_t *Buf = Buffer->getBufferStart();
683 parallelForEach(OutputSections, [Buf](OutputSection *S) { S->writeTo(Buf); });
684}
685
686// Fix the memory layout of the output binary. This assigns memory offsets
Sam Clegg49ed9262017-12-01 00:53:21 +0000687// to each of the input data sections as well as the explicit stack region.
Sam Clegga0f095e2018-05-03 17:21:53 +0000688// The default memory layout is as follows, from low to high.
689//
Sam Cleggf0d433d2018-02-02 22:59:56 +0000690// - initialized data (starting at Config->GlobalBase)
691// - BSS data (not currently implemented in llvm)
692// - explicit stack (Config->ZStackSize)
693// - heap start / unallocated
Sam Clegga0f095e2018-05-03 17:21:53 +0000694//
695// The --stack-first option means that stack is placed before any static data.
Heejin Ahn4821ebf2018-08-29 21:03:16 +0000696// This can be useful since it means that stack overflow traps immediately
697// rather than overwriting global data, but also increases code size since all
698// static data loads and stores requires larger offsets.
Sam Cleggc94d3932017-11-17 18:14:09 +0000699void Writer::layoutMemory() {
Sam Cleggc94d3932017-11-17 18:14:09 +0000700 createOutputSegments();
701
Sam Clegga0f095e2018-05-03 17:21:53 +0000702 uint32_t MemoryPtr = 0;
703
704 auto PlaceStack = [&]() {
Sam Cleggbfb75342018-11-15 00:37:21 +0000705 if (Config->Relocatable || Config->Shared)
Sam Clegga0f095e2018-05-03 17:21:53 +0000706 return;
707 MemoryPtr = alignTo(MemoryPtr, kStackAlignment);
708 if (Config->ZStackSize != alignTo(Config->ZStackSize, kStackAlignment))
709 error("stack size must be " + Twine(kStackAlignment) + "-byte aligned");
710 log("mem: stack size = " + Twine(Config->ZStackSize));
711 log("mem: stack base = " + Twine(MemoryPtr));
712 MemoryPtr += Config->ZStackSize;
Sam Clegg2dad4e22018-11-15 18:15:54 +0000713 auto *SP = cast<DefinedGlobal>(WasmSym::StackPointer);
714 SP->Global->Global.InitExpr.Value.Int32 = MemoryPtr;
Sam Clegga0f095e2018-05-03 17:21:53 +0000715 log("mem: stack top = " + Twine(MemoryPtr));
716 };
717
718 if (Config->StackFirst) {
719 PlaceStack();
720 } else {
721 MemoryPtr = Config->GlobalBase;
722 log("mem: global base = " + Twine(Config->GlobalBase));
723 }
724
725 uint32_t DataStart = MemoryPtr;
726
Sam Cleggf0d433d2018-02-02 22:59:56 +0000727 // Arbitrarily set __dso_handle handle to point to the start of the data
728 // segments.
729 if (WasmSym::DsoHandle)
Sam Clegga0f095e2018-05-03 17:21:53 +0000730 WasmSym::DsoHandle->setVirtualAddress(DataStart);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000731
Sam Cleggbfb75342018-11-15 00:37:21 +0000732 MemAlign = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000733 for (OutputSegment *Seg : Segments) {
Sam Cleggbfb75342018-11-15 00:37:21 +0000734 MemAlign = std::max(MemAlign, Seg->Alignment);
Sam Clegg622ad042019-01-17 22:09:09 +0000735 MemoryPtr = alignTo(MemoryPtr, 1ULL << Seg->Alignment);
Sam Cleggc94d3932017-11-17 18:14:09 +0000736 Seg->StartVA = MemoryPtr;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000737 log(formatv("mem: {0,-15} offset={1,-8} size={2,-8} align={3}", Seg->Name,
738 MemoryPtr, Seg->Size, Seg->Alignment));
Sam Cleggc94d3932017-11-17 18:14:09 +0000739 MemoryPtr += Seg->Size;
740 }
741
Sam Cleggf0d433d2018-02-02 22:59:56 +0000742 // TODO: Add .bss space here.
Sam Clegg37a4a8a2018-02-07 03:04:53 +0000743 if (WasmSym::DataEnd)
744 WasmSym::DataEnd->setVirtualAddress(MemoryPtr);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000745
Sam Clegga0f095e2018-05-03 17:21:53 +0000746 log("mem: static data = " + Twine(MemoryPtr - DataStart));
Sam Cleggc94d3932017-11-17 18:14:09 +0000747
Sam Clegg2dad4e22018-11-15 18:15:54 +0000748 if (Config->Shared) {
749 MemSize = MemoryPtr;
750 return;
751 }
752
Sam Clegga0f095e2018-05-03 17:21:53 +0000753 if (!Config->StackFirst)
754 PlaceStack();
755
756 // Set `__heap_base` to directly follow the end of the stack or global data.
757 // The fact that this comes last means that a malloc/brk implementation
758 // can grow the heap at runtime.
Sam Cleggc94d3932017-11-17 18:14:09 +0000759 if (!Config->Relocatable) {
Sam Cleggf0d433d2018-02-02 22:59:56 +0000760 WasmSym::HeapBase->setVirtualAddress(MemoryPtr);
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000761 log("mem: heap base = " + Twine(MemoryPtr));
Sam Cleggc94d3932017-11-17 18:14:09 +0000762 }
763
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000764 if (Config->InitialMemory != 0) {
765 if (Config->InitialMemory != alignTo(Config->InitialMemory, WasmPageSize))
766 error("initial memory must be " + Twine(WasmPageSize) + "-byte aligned");
767 if (MemoryPtr > Config->InitialMemory)
768 error("initial memory too small, " + Twine(MemoryPtr) + " bytes needed");
769 else
770 MemoryPtr = Config->InitialMemory;
771 }
Sam Cleggbfb75342018-11-15 00:37:21 +0000772 MemSize = MemoryPtr;
773 NumMemoryPages = alignTo(MemoryPtr, WasmPageSize) / WasmPageSize;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000774 log("mem: total pages = " + Twine(NumMemoryPages));
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000775
776 if (Config->MaxMemory != 0) {
777 if (Config->MaxMemory != alignTo(Config->MaxMemory, WasmPageSize))
778 error("maximum memory must be " + Twine(WasmPageSize) + "-byte aligned");
779 if (MemoryPtr > Config->MaxMemory)
780 error("maximum memory too small, " + Twine(MemoryPtr) + " bytes needed");
781 MaxMemoryPages = Config->MaxMemory / WasmPageSize;
782 log("mem: max pages = " + Twine(MaxMemoryPages));
783 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000784}
785
786SyntheticSection *Writer::createSyntheticSection(uint32_t Type,
Sam Cleggc375e4e2018-01-10 19:18:22 +0000787 StringRef Name) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000788 auto Sec = make<SyntheticSection>(Type, Name);
Sam Cleggab2ac292017-12-20 05:14:48 +0000789 log("createSection: " + toString(*Sec));
Sam Cleggc94d3932017-11-17 18:14:09 +0000790 OutputSections.push_back(Sec);
791 return Sec;
792}
793
794void Writer::createSections() {
795 // Known sections
Sam Cleggbfb75342018-11-15 00:37:21 +0000796 if (Config->Pic)
797 createDylinkSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000798 createTypeSection();
799 createImportSection();
800 createFunctionSection();
801 createTableSection();
802 createMemorySection();
803 createGlobalSection();
Heejin Ahne915a712018-12-08 06:17:43 +0000804 createEventSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000805 createExportSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000806 createElemSection();
807 createCodeSection();
808 createDataSection();
Sam Clegg80ba4382018-04-10 16:12:49 +0000809 createCustomSections();
Sam Cleggc94d3932017-11-17 18:14:09 +0000810
811 // Custom sections
Sam Clegg99eb42c2018-02-27 23:58:03 +0000812 if (Config->Relocatable) {
Sam Clegg99eb42c2018-02-27 23:58:03 +0000813 createLinkingSection();
Nicholas Wilson94d3b162018-03-05 12:33:58 +0000814 createRelocSections();
Sam Clegg99eb42c2018-02-27 23:58:03 +0000815 }
Thomas Lively2a0868f2019-01-17 02:29:41 +0000816
Sam Cleggc94d3932017-11-17 18:14:09 +0000817 if (!Config->StripDebug && !Config->StripAll)
818 createNameSection();
819
Thomas Lively2a0868f2019-01-17 02:29:41 +0000820 if (!Config->StripAll)
821 createProducersSection();
822
Sam Cleggc94d3932017-11-17 18:14:09 +0000823 for (OutputSection *S : OutputSections) {
824 S->setOffset(FileSize);
825 S->finalizeContents();
826 FileSize += S->getSize();
827 }
828}
829
Sam Cleggc94d3932017-11-17 18:14:09 +0000830void Writer::calculateImports() {
Sam Clegg574d7ce2017-12-15 19:23:49 +0000831 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000832 if (!Sym->isUndefined())
833 continue;
834 if (isa<DataSymbol>(Sym))
835 continue;
836 if (Sym->isWeak() && !Config->Relocatable)
Sam Clegg574d7ce2017-12-15 19:23:49 +0000837 continue;
Nicholas Wilsona1e299f2018-04-20 17:18:06 +0000838 if (!Sym->isLive())
839 continue;
Sam Cleggc729c1b2018-05-30 18:07:52 +0000840 if (!Sym->IsUsedInRegularObj)
841 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000842
Nicola Zaghene7245b42018-05-15 13:36:20 +0000843 LLVM_DEBUG(dbgs() << "import: " << Sym->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000844 ImportedSymbols.emplace_back(Sym);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000845 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
846 F->setFunctionIndex(NumImportedFunctions++);
Heejin Ahne915a712018-12-08 06:17:43 +0000847 else if (auto *G = dyn_cast<GlobalSymbol>(Sym))
848 G->setGlobalIndex(NumImportedGlobals++);
Sam Clegg93102972018-02-23 05:08:53 +0000849 else
Heejin Ahne915a712018-12-08 06:17:43 +0000850 cast<EventSymbol>(Sym)->setEventIndex(NumImportedEvents++);
Sam Cleggc94d3932017-11-17 18:14:09 +0000851 }
852}
853
Sam Cleggd3052d52018-01-18 23:40:49 +0000854void Writer::calculateExports() {
Sam Clegg93102972018-02-23 05:08:53 +0000855 if (Config->Relocatable)
856 return;
Sam Cleggf0d433d2018-02-02 22:59:56 +0000857
Sam Cleggd6beb322018-05-10 18:10:34 +0000858 if (!Config->Relocatable && !Config->ImportMemory)
859 Exports.push_back(WasmExport{"memory", WASM_EXTERNAL_MEMORY, 0});
860
861 if (!Config->Relocatable && Config->ExportTable)
862 Exports.push_back(WasmExport{kFunctionTableName, WASM_EXTERNAL_TABLE, 0});
863
864 unsigned FakeGlobalIndex = NumImportedGlobals + InputGlobals.size();
865
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000866 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Cleggce004bf2018-06-28 17:04:58 +0000867 if (!Sym->isExported())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000868 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000869 if (!Sym->isLive())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000870 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000871
Sam Cleggd6beb322018-05-10 18:10:34 +0000872 StringRef Name = Sym->getName();
873 WasmExport Export;
874 if (auto *F = dyn_cast<DefinedFunction>(Sym)) {
875 Export = {Name, WASM_EXTERNAL_FUNCTION, F->getFunctionIndex()};
876 } else if (auto *G = dyn_cast<DefinedGlobal>(Sym)) {
Sam Clegg177b4582018-06-07 01:27:07 +0000877 // TODO(sbc): Remove this check once to mutable global proposal is
878 // implement in all major browsers.
879 // See: https://github.com/WebAssembly/mutable-global
880 if (G->getGlobalType()->Mutable) {
881 // Only the __stack_pointer should ever be create as mutable.
882 assert(G == WasmSym::StackPointer);
883 continue;
884 }
Sam Cleggd6beb322018-05-10 18:10:34 +0000885 Export = {Name, WASM_EXTERNAL_GLOBAL, G->getGlobalIndex()};
Heejin Ahne915a712018-12-08 06:17:43 +0000886 } else if (auto *E = dyn_cast<DefinedEvent>(Sym)) {
887 Export = {Name, WASM_EXTERNAL_EVENT, E->getEventIndex()};
Sam Cleggd6beb322018-05-10 18:10:34 +0000888 } else {
889 auto *D = cast<DefinedData>(Sym);
Sam Clegg93102972018-02-23 05:08:53 +0000890 DefinedFakeGlobals.emplace_back(D);
Sam Cleggd6beb322018-05-10 18:10:34 +0000891 Export = {Name, WASM_EXTERNAL_GLOBAL, FakeGlobalIndex++};
892 }
893
Nicola Zaghene7245b42018-05-15 13:36:20 +0000894 LLVM_DEBUG(dbgs() << "Export: " << Name << "\n");
Sam Cleggd6beb322018-05-10 18:10:34 +0000895 Exports.push_back(Export);
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000896 }
Sam Clegg93102972018-02-23 05:08:53 +0000897}
898
899void Writer::assignSymtab() {
900 if (!Config->Relocatable)
901 return;
902
Sam Cleggd177ab22018-05-04 23:14:42 +0000903 StringMap<uint32_t> SectionSymbolIndices;
904
Sam Clegg93102972018-02-23 05:08:53 +0000905 unsigned SymbolIndex = SymtabEntries.size();
Sam Cleggd3052d52018-01-18 23:40:49 +0000906 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000907 LLVM_DEBUG(dbgs() << "Symtab entries: " << File->getName() << "\n");
Sam Cleggd3052d52018-01-18 23:40:49 +0000908 for (Symbol *Sym : File->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000909 if (Sym->getFile() != File)
Sam Cleggd3052d52018-01-18 23:40:49 +0000910 continue;
Sam Cleggd177ab22018-05-04 23:14:42 +0000911
912 if (auto *S = dyn_cast<SectionSymbol>(Sym)) {
913 StringRef Name = S->getName();
914 if (CustomSectionMapping.count(Name) == 0)
915 continue;
916
917 auto SSI = SectionSymbolIndices.find(Name);
918 if (SSI != SectionSymbolIndices.end()) {
919 Sym->setOutputSymbolIndex(SSI->second);
920 continue;
921 }
922
923 SectionSymbolIndices[Name] = SymbolIndex;
924 CustomSectionSymbols[Name] = cast<SectionSymbol>(Sym);
925
926 Sym->markLive();
927 }
928
Nicholas Wilson06e0d172018-03-07 11:15:47 +0000929 // (Since this is relocatable output, GC is not performed so symbols must
930 // be live.)
931 assert(Sym->isLive());
Sam Clegg93102972018-02-23 05:08:53 +0000932 Sym->setOutputSymbolIndex(SymbolIndex++);
933 SymtabEntries.emplace_back(Sym);
Sam Cleggd3052d52018-01-18 23:40:49 +0000934 }
935 }
936
Sam Clegg93102972018-02-23 05:08:53 +0000937 // For the moment, relocatable output doesn't contain any synthetic functions,
938 // so no need to look through the Symtab for symbols not referenced by
939 // Symtab->ObjectFiles.
Sam Cleggd3052d52018-01-18 23:40:49 +0000940}
941
Sam Cleggc375e4e2018-01-10 19:18:22 +0000942uint32_t Writer::lookupType(const WasmSignature &Sig) {
Sam Clegg8d027d62018-01-10 20:12:26 +0000943 auto It = TypeIndices.find(Sig);
944 if (It == TypeIndices.end()) {
Sam Cleggc375e4e2018-01-10 19:18:22 +0000945 error("type not found: " + toString(Sig));
Sam Clegg8d027d62018-01-10 20:12:26 +0000946 return 0;
947 }
948 return It->second;
Sam Cleggc375e4e2018-01-10 19:18:22 +0000949}
950
951uint32_t Writer::registerType(const WasmSignature &Sig) {
Sam Cleggb8621592017-11-30 01:40:08 +0000952 auto Pair = TypeIndices.insert(std::make_pair(Sig, Types.size()));
Sam Cleggc375e4e2018-01-10 19:18:22 +0000953 if (Pair.second) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000954 LLVM_DEBUG(dbgs() << "type " << toString(Sig) << "\n");
Sam Cleggb8621592017-11-30 01:40:08 +0000955 Types.push_back(&Sig);
Sam Cleggc375e4e2018-01-10 19:18:22 +0000956 }
Sam Cleggb8621592017-11-30 01:40:08 +0000957 return Pair.first->second;
958}
959
Sam Cleggc94d3932017-11-17 18:14:09 +0000960void Writer::calculateTypes() {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000961 // The output type section is the union of the following sets:
962 // 1. Any signature used in the TYPE relocation
963 // 2. The signatures of all imported functions
964 // 3. The signatures of all defined functions
Heejin Ahne915a712018-12-08 06:17:43 +0000965 // 4. The signatures of all imported events
966 // 5. The signatures of all defined events
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000967
Sam Cleggc94d3932017-11-17 18:14:09 +0000968 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000969 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
970 for (uint32_t I = 0; I < Types.size(); I++)
971 if (File->TypeIsUsed[I])
972 File->TypeMap[I] = registerType(Types[I]);
Sam Cleggc94d3932017-11-17 18:14:09 +0000973 }
Sam Clegg50686852018-01-12 18:35:13 +0000974
Heejin Ahne915a712018-12-08 06:17:43 +0000975 for (const Symbol *Sym : ImportedSymbols) {
Sam Clegg93102972018-02-23 05:08:53 +0000976 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
Heejin Ahne915a712018-12-08 06:17:43 +0000977 registerType(*F->Signature);
978 else if (auto *E = dyn_cast<EventSymbol>(Sym))
979 registerType(*E->Signature);
980 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000981
Sam Clegg9f934222018-02-21 18:29:23 +0000982 for (const InputFunction *F : InputFunctions)
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000983 registerType(F->Signature);
Heejin Ahne915a712018-12-08 06:17:43 +0000984
985 for (const InputEvent *E : InputEvents)
986 registerType(E->Signature);
Sam Cleggc94d3932017-11-17 18:14:09 +0000987}
988
Sam Clegg8d146bb2018-01-09 23:56:44 +0000989void Writer::assignIndexes() {
Heejin Ahnaeaab992018-11-19 23:21:25 +0000990 assert(InputFunctions.empty());
991 uint32_t FunctionIndex = NumImportedFunctions;
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000992 auto AddDefinedFunction = [&](InputFunction *Func) {
993 if (!Func->Live)
994 return;
995 InputFunctions.emplace_back(Func);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000996 Func->setFunctionIndex(FunctionIndex++);
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000997 };
998
Nicholas Wilson5639da82018-03-12 15:44:07 +0000999 for (InputFunction *Func : Symtab->SyntheticFunctions)
1000 AddDefinedFunction(Func);
1001
Sam Clegg87e61922018-01-08 23:39:11 +00001002 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001003 LLVM_DEBUG(dbgs() << "Functions: " << File->getName() << "\n");
Nicholas Wilsonebda41f2018-03-09 16:43:05 +00001004 for (InputFunction *Func : File->Functions)
1005 AddDefinedFunction(Func);
Sam Clegg8d146bb2018-01-09 23:56:44 +00001006 }
1007
Sam Cleggbfb75342018-11-15 00:37:21 +00001008 uint32_t TableIndex = TableBase;
Sam Clegg6c4dbfee2018-02-23 04:59:57 +00001009 auto HandleRelocs = [&](InputChunk *Chunk) {
1010 if (!Chunk->Live)
1011 return;
1012 ObjFile *File = Chunk->File;
1013 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
Sam Clegg93102972018-02-23 05:08:53 +00001014 for (const WasmRelocation &Reloc : Chunk->getRelocations()) {
Sam Clegg6c4dbfee2018-02-23 04:59:57 +00001015 if (Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_I32 ||
1016 Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_SLEB) {
1017 FunctionSymbol *Sym = File->getFunctionSymbol(Reloc.Index);
Sam Clegge3f3ccf2018-03-12 19:56:23 +00001018 if (Sym->hasTableIndex() || !Sym->hasFunctionIndex())
Sam Clegg6c4dbfee2018-02-23 04:59:57 +00001019 continue;
1020 Sym->setTableIndex(TableIndex++);
1021 IndirectFunctions.emplace_back(Sym);
1022 } else if (Reloc.Type == R_WEBASSEMBLY_TYPE_INDEX_LEB) {
Sam Clegg93102972018-02-23 05:08:53 +00001023 // Mark target type as live
Sam Clegg6c4dbfee2018-02-23 04:59:57 +00001024 File->TypeMap[Reloc.Index] = registerType(Types[Reloc.Index]);
1025 File->TypeIsUsed[Reloc.Index] = true;
1026 }
1027 }
1028 };
1029
Sam Clegg8d146bb2018-01-09 23:56:44 +00001030 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001031 LLVM_DEBUG(dbgs() << "Handle relocs: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +00001032 for (InputChunk *Chunk : File->Functions)
1033 HandleRelocs(Chunk);
1034 for (InputChunk *Chunk : File->Segments)
1035 HandleRelocs(Chunk);
Sam Cleggd177ab22018-05-04 23:14:42 +00001036 for (auto &P : File->CustomSections)
1037 HandleRelocs(P);
Sam Clegg93102972018-02-23 05:08:53 +00001038 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +00001039
Heejin Ahnaeaab992018-11-19 23:21:25 +00001040 assert(InputGlobals.empty());
1041 uint32_t GlobalIndex = NumImportedGlobals;
Sam Clegg93102972018-02-23 05:08:53 +00001042 auto AddDefinedGlobal = [&](InputGlobal *Global) {
1043 if (Global->Live) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001044 LLVM_DEBUG(dbgs() << "AddDefinedGlobal: " << GlobalIndex << "\n");
Sam Clegge3f3ccf2018-03-12 19:56:23 +00001045 Global->setGlobalIndex(GlobalIndex++);
Sam Clegg93102972018-02-23 05:08:53 +00001046 InputGlobals.push_back(Global);
1047 }
1048 };
1049
Nicholas Wilsonebda41f2018-03-09 16:43:05 +00001050 for (InputGlobal *Global : Symtab->SyntheticGlobals)
1051 AddDefinedGlobal(Global);
Sam Clegg93102972018-02-23 05:08:53 +00001052
1053 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001054 LLVM_DEBUG(dbgs() << "Globals: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +00001055 for (InputGlobal *Global : File->Globals)
1056 AddDefinedGlobal(Global);
Sam Cleggc94d3932017-11-17 18:14:09 +00001057 }
Heejin Ahne915a712018-12-08 06:17:43 +00001058
1059 assert(InputEvents.empty());
1060 uint32_t EventIndex = NumImportedEvents;
1061 auto AddDefinedEvent = [&](InputEvent *Event) {
1062 if (Event->Live) {
1063 LLVM_DEBUG(dbgs() << "AddDefinedEvent: " << EventIndex << "\n");
1064 Event->setEventIndex(EventIndex++);
1065 InputEvents.push_back(Event);
1066 }
1067 };
1068
1069 for (ObjFile *File : Symtab->ObjectFiles) {
1070 LLVM_DEBUG(dbgs() << "Events: " << File->getName() << "\n");
1071 for (InputEvent *Event : File->Events)
1072 AddDefinedEvent(Event);
1073 }
Sam Cleggc94d3932017-11-17 18:14:09 +00001074}
1075
1076static StringRef getOutputDataSegmentName(StringRef Name) {
Sam Cleggbfb75342018-11-15 00:37:21 +00001077 // With PIC code we currently only support a single data segment since
1078 // we only have a single __memory_base to use as our base address.
1079 if (Config->Pic)
1080 return "data";
Sam Clegg66844762018-05-10 18:23:51 +00001081 if (!Config->MergeDataSegments)
Sam Cleggc94d3932017-11-17 18:14:09 +00001082 return Name;
Rui Ueyama4764b572018-02-28 00:57:28 +00001083 if (Name.startswith(".text."))
1084 return ".text";
1085 if (Name.startswith(".data."))
1086 return ".data";
1087 if (Name.startswith(".bss."))
1088 return ".bss";
Sam Clegg57694c52018-08-08 18:02:55 +00001089 if (Name.startswith(".rodata."))
1090 return ".rodata";
Sam Cleggc94d3932017-11-17 18:14:09 +00001091 return Name;
1092}
1093
1094void Writer::createOutputSegments() {
1095 for (ObjFile *File : Symtab->ObjectFiles) {
1096 for (InputSegment *Segment : File->Segments) {
Sam Clegg447ae402018-02-13 20:29:38 +00001097 if (!Segment->Live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +00001098 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +00001099 StringRef Name = getOutputDataSegmentName(Segment->getName());
1100 OutputSegment *&S = SegmentMap[Name];
1101 if (S == nullptr) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001102 LLVM_DEBUG(dbgs() << "new segment: " << Name << "\n");
Sam Clegg93102972018-02-23 05:08:53 +00001103 S = make<OutputSegment>(Name, Segments.size());
Sam Cleggc94d3932017-11-17 18:14:09 +00001104 Segments.push_back(S);
1105 }
1106 S->addInputSegment(Segment);
Nicola Zaghene7245b42018-05-15 13:36:20 +00001107 LLVM_DEBUG(dbgs() << "added data: " << Name << ": " << S->Size << "\n");
Sam Cleggc94d3932017-11-17 18:14:09 +00001108 }
1109 }
1110}
1111
Sam Clegg50686852018-01-12 18:35:13 +00001112static const int OPCODE_CALL = 0x10;
1113static const int OPCODE_END = 0xb;
1114
1115// Create synthetic "__wasm_call_ctors" function based on ctor functions
1116// in input object.
1117void Writer::createCtorFunction() {
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +00001118 // First write the body's contents to a string.
1119 std::string BodyContent;
Sam Clegg50686852018-01-12 18:35:13 +00001120 {
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +00001121 raw_string_ostream OS(BodyContent);
Sam Clegg50686852018-01-12 18:35:13 +00001122 writeUleb128(OS, 0, "num locals");
Sam Clegg93102972018-02-23 05:08:53 +00001123 for (const WasmInitEntry &F : InitFunctions) {
Sam Clegg50686852018-01-12 18:35:13 +00001124 writeU8(OS, OPCODE_CALL, "CALL");
Sam Clegge3f3ccf2018-03-12 19:56:23 +00001125 writeUleb128(OS, F.Sym->getFunctionIndex(), "function index");
Sam Clegg50686852018-01-12 18:35:13 +00001126 }
1127 writeU8(OS, OPCODE_END, "END");
1128 }
1129
1130 // Once we know the size of the body we can create the final function body
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +00001131 std::string FunctionBody;
1132 {
1133 raw_string_ostream OS(FunctionBody);
1134 writeUleb128(OS, BodyContent.size(), "function size");
1135 OS << BodyContent;
1136 }
Rui Ueyama29abfe42018-02-28 17:43:15 +00001137
Sam Cleggea656472018-10-22 08:35:39 +00001138 ArrayRef<uint8_t> Body = arrayRefFromStringRef(Saver.save(FunctionBody));
Nicholas Wilsonebda41f2018-03-09 16:43:05 +00001139 cast<SyntheticFunction>(WasmSym::CallCtors->Function)->setBody(Body);
Sam Clegg50686852018-01-12 18:35:13 +00001140}
1141
1142// Populate InitFunctions vector with init functions from all input objects.
1143// This is then used either when creating the output linking section or to
1144// synthesize the "__wasm_call_ctors" function.
1145void Writer::calculateInitFunctions() {
1146 for (ObjFile *File : Symtab->ObjectFiles) {
1147 const WasmLinkingData &L = File->getWasmObj()->linkingData();
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +00001148 for (const WasmInitFunc &F : L.InitFunctions) {
1149 FunctionSymbol *Sym = File->getFunctionSymbol(F.Symbol);
Heejin Ahne915a712018-12-08 06:17:43 +00001150 if (*Sym->Signature != WasmSignature{{}, {}})
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +00001151 error("invalid signature for init func: " + toString(*Sym));
1152 InitFunctions.emplace_back(WasmInitEntry{Sym, F.Priority});
1153 }
Sam Clegg50686852018-01-12 18:35:13 +00001154 }
Rui Ueyamada69b712018-02-28 00:15:59 +00001155
Sam Clegg50686852018-01-12 18:35:13 +00001156 // Sort in order of priority (lowest first) so that they are called
1157 // in the correct order.
Sam Clegg29b8feb2018-02-21 00:34:34 +00001158 std::stable_sort(InitFunctions.begin(), InitFunctions.end(),
Sam Clegg93102972018-02-23 05:08:53 +00001159 [](const WasmInitEntry &L, const WasmInitEntry &R) {
Sam Clegg29b8feb2018-02-21 00:34:34 +00001160 return L.Priority < R.Priority;
1161 });
Sam Clegg50686852018-01-12 18:35:13 +00001162}
1163
Sam Cleggc94d3932017-11-17 18:14:09 +00001164void Writer::run() {
Sam Cleggbfb75342018-11-15 00:37:21 +00001165 if (Config->Relocatable || Config->Pic)
Sam Clegg99eb42c2018-02-27 23:58:03 +00001166 Config->GlobalBase = 0;
1167
Sam Cleggbfb75342018-11-15 00:37:21 +00001168 // For PIC code the table base is assigned dynamically by the loader.
1169 // For non-PIC, we start at 1 so that accessing table index 0 always traps.
1170 if (!Config->Pic)
1171 TableBase = 1;
1172
Sam Cleggc94d3932017-11-17 18:14:09 +00001173 log("-- calculateImports");
1174 calculateImports();
Sam Clegg8d146bb2018-01-09 23:56:44 +00001175 log("-- assignIndexes");
1176 assignIndexes();
Sam Clegg50686852018-01-12 18:35:13 +00001177 log("-- calculateInitFunctions");
1178 calculateInitFunctions();
1179 if (!Config->Relocatable)
1180 createCtorFunction();
Sam Clegg8f6d2de2018-01-31 23:48:14 +00001181 log("-- calculateTypes");
1182 calculateTypes();
Sam Clegg93102972018-02-23 05:08:53 +00001183 log("-- layoutMemory");
1184 layoutMemory();
1185 log("-- calculateExports");
1186 calculateExports();
Sam Cleggd177ab22018-05-04 23:14:42 +00001187 log("-- calculateCustomSections");
1188 calculateCustomSections();
Sam Clegg93102972018-02-23 05:08:53 +00001189 log("-- assignSymtab");
1190 assignSymtab();
Sam Cleggc94d3932017-11-17 18:14:09 +00001191
1192 if (errorHandler().Verbose) {
Sam Clegg9f934222018-02-21 18:29:23 +00001193 log("Defined Functions: " + Twine(InputFunctions.size()));
Sam Clegg93102972018-02-23 05:08:53 +00001194 log("Defined Globals : " + Twine(InputGlobals.size()));
Heejin Ahne915a712018-12-08 06:17:43 +00001195 log("Defined Events : " + Twine(InputEvents.size()));
Sam Clegg93102972018-02-23 05:08:53 +00001196 log("Function Imports : " + Twine(NumImportedFunctions));
1197 log("Global Imports : " + Twine(NumImportedGlobals));
Heejin Ahne915a712018-12-08 06:17:43 +00001198 log("Event Imports : " + Twine(NumImportedEvents));
Sam Cleggc94d3932017-11-17 18:14:09 +00001199 for (ObjFile *File : Symtab->ObjectFiles)
1200 File->dumpInfo();
1201 }
1202
Sam Cleggc94d3932017-11-17 18:14:09 +00001203 createHeader();
1204 log("-- createSections");
1205 createSections();
1206
1207 log("-- openFile");
1208 openFile();
1209 if (errorCount())
1210 return;
1211
1212 writeHeader();
1213
1214 log("-- writeSections");
1215 writeSections();
1216 if (errorCount())
1217 return;
1218
1219 if (Error E = Buffer->commit())
1220 fatal("failed to write the output file: " + toString(std::move(E)));
1221}
1222
1223// Open a result file.
1224void Writer::openFile() {
1225 log("writing: " + Config->OutputFile);
Sam Cleggc94d3932017-11-17 18:14:09 +00001226
1227 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
1228 FileOutputBuffer::create(Config->OutputFile, FileSize,
1229 FileOutputBuffer::F_executable);
1230
1231 if (!BufferOrErr)
1232 error("failed to open " + Config->OutputFile + ": " +
1233 toString(BufferOrErr.takeError()));
1234 else
1235 Buffer = std::move(*BufferOrErr);
1236}
1237
1238void Writer::createHeader() {
1239 raw_string_ostream OS(Header);
1240 writeBytes(OS, WasmMagic, sizeof(WasmMagic), "wasm magic");
1241 writeU32(OS, WasmVersion, "wasm version");
1242 OS.flush();
1243 FileSize += Header.size();
1244}
1245
1246void lld::wasm::writeResult() { Writer().run(); }