blob: cb8533206e0ba1de6377808fa4acd3e573904da4 [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
Heejin Ahna1cc4ea2019-02-04 19:13:46 +000042static constexpr int StackAlignment = 16;
43static constexpr const char *FunctionTableName = "__indirect_function_table";
44const char *lld::wasm::DefaultModule = "env";
Sam Cleggc94d3932017-11-17 18:14:09 +000045
46namespace {
47
Sam Clegg93102972018-02-23 05:08:53 +000048// An init entry to be written to either the synthetic init func or the
49// linking metadata.
50struct WasmInitEntry {
Sam Clegge3f3ccf2018-03-12 19:56:23 +000051 const FunctionSymbol *Sym;
Sam Clegg93102972018-02-23 05:08:53 +000052 uint32_t Priority;
Sam Cleggd3052d52018-01-18 23:40:49 +000053};
54
Sam Cleggc94d3932017-11-17 18:14:09 +000055// The writer writes a SymbolTable result to a file.
56class Writer {
57public:
58 void run();
59
60private:
61 void openFile();
62
Sam Cleggc375e4e2018-01-10 19:18:22 +000063 uint32_t lookupType(const WasmSignature &Sig);
64 uint32_t registerType(const WasmSignature &Sig);
Sam Clegg93102972018-02-23 05:08:53 +000065
Sam Clegg50686852018-01-12 18:35:13 +000066 void createCtorFunction();
67 void calculateInitFunctions();
Sam Clegg8d146bb2018-01-09 23:56:44 +000068 void assignIndexes();
Sam Cleggc94d3932017-11-17 18:14:09 +000069 void calculateImports();
Sam Cleggd3052d52018-01-18 23:40:49 +000070 void calculateExports();
Sam Cleggd177ab22018-05-04 23:14:42 +000071 void calculateCustomSections();
Sam Clegg93102972018-02-23 05:08:53 +000072 void assignSymtab();
Sam Cleggc94d3932017-11-17 18:14:09 +000073 void calculateTypes();
74 void createOutputSegments();
75 void layoutMemory();
76 void createHeader();
77 void createSections();
Nicholas Wilsondbd90bf2018-03-07 13:28:16 +000078 SyntheticSection *createSyntheticSection(uint32_t Type, StringRef Name = "");
Sam Cleggc94d3932017-11-17 18:14:09 +000079
80 // Builtin sections
81 void createTypeSection();
82 void createFunctionSection();
83 void createTableSection();
84 void createGlobalSection();
Heejin Ahne915a712018-12-08 06:17:43 +000085 void createEventSection();
Sam Cleggc94d3932017-11-17 18:14:09 +000086 void createExportSection();
87 void createImportSection();
88 void createMemorySection();
89 void createElemSection();
Sam Cleggc94d3932017-11-17 18:14:09 +000090 void createCodeSection();
91 void createDataSection();
Sam Clegg80ba4382018-04-10 16:12:49 +000092 void createCustomSections();
Sam Cleggc94d3932017-11-17 18:14:09 +000093
94 // Custom sections
Sam Cleggbfb75342018-11-15 00:37:21 +000095 void createDylinkSection();
Sam Cleggc94d3932017-11-17 18:14:09 +000096 void createRelocSections();
97 void createLinkingSection();
98 void createNameSection();
Thomas Lively2a0868f2019-01-17 02:29:41 +000099 void createProducersSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000100
101 void writeHeader();
102 void writeSections();
103
104 uint64_t FileSize = 0;
Sam Cleggbfb75342018-11-15 00:37:21 +0000105 uint32_t TableBase = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000106 uint32_t NumMemoryPages = 0;
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000107 uint32_t MaxMemoryPages = 0;
Sam Cleggbfb75342018-11-15 00:37:21 +0000108 // Memory size and aligment. Written to the "dylink" section
109 // when build with -shared or -pie.
110 uint32_t MemAlign = 0;
111 uint32_t MemSize = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000112
113 std::vector<const WasmSignature *> Types;
Nicholas Wilson3e3f5fb2018-03-14 15:58:16 +0000114 DenseMap<WasmSignature, int32_t> TypeIndices;
Sam Clegg93102972018-02-23 05:08:53 +0000115 std::vector<const Symbol *> ImportedSymbols;
116 unsigned NumImportedFunctions = 0;
117 unsigned NumImportedGlobals = 0;
Heejin Ahne915a712018-12-08 06:17:43 +0000118 unsigned NumImportedEvents = 0;
Sam Cleggd6beb322018-05-10 18:10:34 +0000119 std::vector<WasmExport> Exports;
Sam Clegg93102972018-02-23 05:08:53 +0000120 std::vector<const DefinedData *> DefinedFakeGlobals;
121 std::vector<InputGlobal *> InputGlobals;
Sam Clegg9f934222018-02-21 18:29:23 +0000122 std::vector<InputFunction *> InputFunctions;
Heejin Ahne915a712018-12-08 06:17:43 +0000123 std::vector<InputEvent *> InputEvents;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000124 std::vector<const FunctionSymbol *> IndirectFunctions;
Sam Clegg93102972018-02-23 05:08:53 +0000125 std::vector<const Symbol *> SymtabEntries;
126 std::vector<WasmInitEntry> InitFunctions;
Sam Cleggc94d3932017-11-17 18:14:09 +0000127
Sam Clegg80ba4382018-04-10 16:12:49 +0000128 llvm::StringMap<std::vector<InputSection *>> CustomSectionMapping;
Sam Cleggd177ab22018-05-04 23:14:42 +0000129 llvm::StringMap<SectionSymbol *> CustomSectionSymbols;
Sam Clegg80ba4382018-04-10 16:12:49 +0000130
Sam Cleggc94d3932017-11-17 18:14:09 +0000131 // Elements that are used to construct the final output
132 std::string Header;
133 std::vector<OutputSection *> OutputSections;
134
135 std::unique_ptr<FileOutputBuffer> Buffer;
136
137 std::vector<OutputSegment *> Segments;
138 llvm::SmallDenseMap<StringRef, OutputSegment *> SegmentMap;
139};
140
141} // anonymous namespace
142
Sam Cleggc94d3932017-11-17 18:14:09 +0000143void Writer::createImportSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000144 uint32_t NumImports = ImportedSymbols.size();
Sam Cleggc94d3932017-11-17 18:14:09 +0000145 if (Config->ImportMemory)
146 ++NumImports;
Nicholas Wilsonfc90b302018-03-28 12:53:29 +0000147 if (Config->ImportTable)
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000148 ++NumImports;
Sam Cleggc94d3932017-11-17 18:14:09 +0000149
150 if (NumImports == 0)
151 return;
152
153 SyntheticSection *Section = createSyntheticSection(WASM_SEC_IMPORT);
154 raw_ostream &OS = Section->getStream();
155
156 writeUleb128(OS, NumImports, "import count");
157
Sam Cleggc94d3932017-11-17 18:14:09 +0000158 if (Config->ImportMemory) {
159 WasmImport Import;
Heejin Ahna1cc4ea2019-02-04 19:13:46 +0000160 Import.Module = DefaultModule;
Sam Cleggc94d3932017-11-17 18:14:09 +0000161 Import.Field = "memory";
162 Import.Kind = WASM_EXTERNAL_MEMORY;
163 Import.Memory.Flags = 0;
164 Import.Memory.Initial = NumMemoryPages;
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000165 if (MaxMemoryPages != 0) {
166 Import.Memory.Flags |= WASM_LIMITS_FLAG_HAS_MAX;
167 Import.Memory.Maximum = MaxMemoryPages;
168 }
Derek Schuff786760a2018-11-06 18:02:39 +0000169 if (Config->SharedMemory)
Derek Schuff3bea8bc2018-11-06 17:59:32 +0000170 Import.Memory.Flags |= WASM_LIMITS_FLAG_IS_SHARED;
Sam Cleggc94d3932017-11-17 18:14:09 +0000171 writeImport(OS, Import);
172 }
173
Nicholas Wilsonfc90b302018-03-28 12:53:29 +0000174 if (Config->ImportTable) {
Sam Cleggbfb75342018-11-15 00:37:21 +0000175 uint32_t TableSize = TableBase + IndirectFunctions.size();
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000176 WasmImport Import;
Heejin Ahna1cc4ea2019-02-04 19:13:46 +0000177 Import.Module = DefaultModule;
178 Import.Field = FunctionTableName;
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000179 Import.Kind = WASM_EXTERNAL_TABLE;
Thomas Lively25ff8932019-01-08 06:25:55 +0000180 Import.Table.ElemType = WASM_TYPE_FUNCREF;
Sam Clegg748f59cae2018-12-03 22:37:55 +0000181 Import.Table.Limits = {0, TableSize, 0};
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000182 writeImport(OS, Import);
183 }
184
Sam Clegg93102972018-02-23 05:08:53 +0000185 for (const Symbol *Sym : ImportedSymbols) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000186 WasmImport Import;
Sam Clegg7cc07532019-02-01 02:29:57 +0000187 if (auto *F = dyn_cast<UndefinedFunction>(Sym))
188 Import.Module = F->Module;
189 else
Heejin Ahna1cc4ea2019-02-04 19:13:46 +0000190 Import.Module = DefaultModule;
Sam Clegg7cc07532019-02-01 02:29:57 +0000191
Sam Cleggc94d3932017-11-17 18:14:09 +0000192 Import.Field = Sym->getName();
Sam Clegg93102972018-02-23 05:08:53 +0000193 if (auto *FunctionSym = dyn_cast<FunctionSymbol>(Sym)) {
194 Import.Kind = WASM_EXTERNAL_FUNCTION;
Heejin Ahne915a712018-12-08 06:17:43 +0000195 Import.SigIndex = lookupType(*FunctionSym->Signature);
196 } else if (auto *GlobalSym = dyn_cast<GlobalSymbol>(Sym)) {
Sam Clegg93102972018-02-23 05:08:53 +0000197 Import.Kind = WASM_EXTERNAL_GLOBAL;
198 Import.Global = *GlobalSym->getGlobalType();
Heejin Ahne915a712018-12-08 06:17:43 +0000199 } else {
200 auto *EventSym = cast<EventSymbol>(Sym);
201 Import.Kind = WASM_EXTERNAL_EVENT;
202 Import.Event.Attribute = EventSym->getEventType()->Attribute;
203 Import.Event.SigIndex = lookupType(*EventSym->Signature);
Sam Clegg93102972018-02-23 05:08:53 +0000204 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000205 writeImport(OS, Import);
206 }
207}
208
209void Writer::createTypeSection() {
210 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TYPE);
211 raw_ostream &OS = Section->getStream();
212 writeUleb128(OS, Types.size(), "type count");
Sam Cleggd451da12017-12-19 19:56:27 +0000213 for (const WasmSignature *Sig : Types)
Sam Cleggc94d3932017-11-17 18:14:09 +0000214 writeSig(OS, *Sig);
Sam Cleggc94d3932017-11-17 18:14:09 +0000215}
216
217void Writer::createFunctionSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000218 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000219 return;
220
221 SyntheticSection *Section = createSyntheticSection(WASM_SEC_FUNCTION);
222 raw_ostream &OS = Section->getStream();
223
Sam Clegg9f934222018-02-21 18:29:23 +0000224 writeUleb128(OS, InputFunctions.size(), "function count");
225 for (const InputFunction *Func : InputFunctions)
Sam Cleggc375e4e2018-01-10 19:18:22 +0000226 writeUleb128(OS, lookupType(Func->Signature), "sig index");
Sam Cleggc94d3932017-11-17 18:14:09 +0000227}
228
229void Writer::createMemorySection() {
230 if (Config->ImportMemory)
231 return;
232
233 SyntheticSection *Section = createSyntheticSection(WASM_SEC_MEMORY);
234 raw_ostream &OS = Section->getStream();
235
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000236 bool HasMax = MaxMemoryPages != 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000237 writeUleb128(OS, 1, "memory count");
Derek Schuff786760a2018-11-06 18:02:39 +0000238 unsigned Flags = 0;
239 if (HasMax)
240 Flags |= WASM_LIMITS_FLAG_HAS_MAX;
Derek Schuff3bea8bc2018-11-06 17:59:32 +0000241 if (Config->SharedMemory)
242 Flags |= WASM_LIMITS_FLAG_IS_SHARED;
243 writeUleb128(OS, Flags, "memory limits flags");
Sam Cleggc94d3932017-11-17 18:14:09 +0000244 writeUleb128(OS, NumMemoryPages, "initial pages");
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000245 if (HasMax)
246 writeUleb128(OS, MaxMemoryPages, "max pages");
Sam Cleggc94d3932017-11-17 18:14:09 +0000247}
248
249void Writer::createGlobalSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000250 unsigned NumGlobals = InputGlobals.size() + DefinedFakeGlobals.size();
251 if (NumGlobals == 0)
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000252 return;
253
Sam Cleggc94d3932017-11-17 18:14:09 +0000254 SyntheticSection *Section = createSyntheticSection(WASM_SEC_GLOBAL);
255 raw_ostream &OS = Section->getStream();
256
Sam Clegg93102972018-02-23 05:08:53 +0000257 writeUleb128(OS, NumGlobals, "global count");
258 for (const InputGlobal *G : InputGlobals)
259 writeGlobal(OS, G->Global);
260 for (const DefinedData *Sym : DefinedFakeGlobals) {
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000261 WasmGlobal Global;
Sam Clegg93102972018-02-23 05:08:53 +0000262 Global.Type = {WASM_TYPE_I32, false};
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000263 Global.InitExpr.Opcode = WASM_OPCODE_I32_CONST;
264 Global.InitExpr.Value.Int32 = Sym->getVirtualAddress();
Sam Cleggc94d3932017-11-17 18:14:09 +0000265 writeGlobal(OS, Global);
266 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000267}
268
Heejin Ahne915a712018-12-08 06:17:43 +0000269// The event section contains a list of declared wasm events associated with the
270// module. Currently the only supported event kind is exceptions. A single event
271// entry represents a single event with an event tag. All C++ exceptions are
272// represented by a single event. An event entry in this section contains
273// information on what kind of event it is (e.g. exception) and the type of
274// values contained in a single event object. (In wasm, an event can contain
275// multiple values of primitive types. But for C++ exceptions, we just throw a
276// pointer which is an i32 value (for wasm32 architecture), so the signature of
277// C++ exception is (i32)->(void), because all event types are assumed to have
278// void return type to share WasmSignature with functions.)
279void Writer::createEventSection() {
280 unsigned NumEvents = InputEvents.size();
281 if (NumEvents == 0)
282 return;
283
284 SyntheticSection *Section = createSyntheticSection(WASM_SEC_EVENT);
285 raw_ostream &OS = Section->getStream();
286
287 writeUleb128(OS, NumEvents, "event count");
288 for (InputEvent *E : InputEvents) {
289 E->Event.Type.SigIndex = lookupType(E->Signature);
290 writeEvent(OS, E->Event);
291 }
292}
293
Sam Cleggc94d3932017-11-17 18:14:09 +0000294void Writer::createTableSection() {
Nicholas Wilsonfc90b302018-03-28 12:53:29 +0000295 if (Config->ImportTable)
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000296 return;
297
298 // Always output a table section (or table import), even if there are no
299 // indirect calls. There are two reasons for this:
Sam Cleggfc1a9122017-12-11 22:00:56 +0000300 // 1. For executables it is useful to have an empty table slot at 0
301 // which can be filled with a null function call handler.
302 // 2. If we don't do this, any program that contains a call_indirect but
303 // no address-taken function will fail at validation time since it is
304 // a validation error to include a call_indirect instruction if there
305 // is not table.
Sam Cleggbfb75342018-11-15 00:37:21 +0000306 uint32_t TableSize = TableBase + IndirectFunctions.size();
Sam Cleggfc1a9122017-12-11 22:00:56 +0000307
Sam Cleggc94d3932017-11-17 18:14:09 +0000308 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TABLE);
309 raw_ostream &OS = Section->getStream();
310
311 writeUleb128(OS, 1, "table count");
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000312 WasmLimits Limits = {WASM_LIMITS_FLAG_HAS_MAX, TableSize, TableSize};
Thomas Lively25ff8932019-01-08 06:25:55 +0000313 writeTableType(OS, WasmTable{WASM_TYPE_FUNCREF, Limits});
Sam Cleggc94d3932017-11-17 18:14:09 +0000314}
315
316void Writer::createExportSection() {
Sam Cleggd6beb322018-05-10 18:10:34 +0000317 if (!Exports.size())
Sam Cleggc94d3932017-11-17 18:14:09 +0000318 return;
319
320 SyntheticSection *Section = createSyntheticSection(WASM_SEC_EXPORT);
321 raw_ostream &OS = Section->getStream();
322
Sam Cleggd6beb322018-05-10 18:10:34 +0000323 writeUleb128(OS, Exports.size(), "export count");
324 for (const WasmExport &Export : Exports)
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000325 writeExport(OS, Export);
Sam Cleggc94d3932017-11-17 18:14:09 +0000326}
327
Sam Cleggd177ab22018-05-04 23:14:42 +0000328void Writer::calculateCustomSections() {
329 log("calculateCustomSections");
330 bool StripDebug = Config->StripDebug || Config->StripAll;
331 for (ObjFile *File : Symtab->ObjectFiles) {
332 for (InputSection *Section : File->CustomSections) {
333 StringRef Name = Section->getName();
334 // These custom sections are known the linker and synthesized rather than
335 // blindly copied
Thomas Lively2a0868f2019-01-17 02:29:41 +0000336 if (Name == "linking" || Name == "name" || Name == "producers" ||
337 Name.startswith("reloc."))
Sam Cleggd177ab22018-05-04 23:14:42 +0000338 continue;
339 // .. or it is a debug section
340 if (StripDebug && Name.startswith(".debug_"))
341 continue;
342 CustomSectionMapping[Name].push_back(Section);
343 }
344 }
345}
346
Sam Clegg80ba4382018-04-10 16:12:49 +0000347void Writer::createCustomSections() {
348 log("createCustomSections");
Sam Clegg80ba4382018-04-10 16:12:49 +0000349 for (auto &Pair : CustomSectionMapping) {
350 StringRef Name = Pair.first();
Sam Cleggd177ab22018-05-04 23:14:42 +0000351
352 auto P = CustomSectionSymbols.find(Name);
353 if (P != CustomSectionSymbols.end()) {
354 uint32_t SectionIndex = OutputSections.size();
355 P->second->setOutputSectionIndex(SectionIndex);
356 }
357
Nicola Zaghene7245b42018-05-15 13:36:20 +0000358 LLVM_DEBUG(dbgs() << "createCustomSection: " << Name << "\n");
Sam Clegg80ba4382018-04-10 16:12:49 +0000359 OutputSections.push_back(make<CustomSection>(Name, Pair.second));
360 }
361}
362
Sam Cleggc94d3932017-11-17 18:14:09 +0000363void Writer::createElemSection() {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000364 if (IndirectFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000365 return;
366
367 SyntheticSection *Section = createSyntheticSection(WASM_SEC_ELEM);
368 raw_ostream &OS = Section->getStream();
369
370 writeUleb128(OS, 1, "segment count");
371 writeUleb128(OS, 0, "table index");
372 WasmInitExpr InitExpr;
Sam Cleggbfb75342018-11-15 00:37:21 +0000373 if (Config->Pic) {
Thomas Lively25ff8932019-01-08 06:25:55 +0000374 InitExpr.Opcode = WASM_OPCODE_GLOBAL_GET;
Sam Clegg2dad4e22018-11-15 18:15:54 +0000375 InitExpr.Value.Global = WasmSym::TableBase->getGlobalIndex();
Sam Cleggbfb75342018-11-15 00:37:21 +0000376 } else {
377 InitExpr.Opcode = WASM_OPCODE_I32_CONST;
378 InitExpr.Value.Int32 = TableBase;
379 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000380 writeInitExpr(OS, InitExpr);
Sam Cleggfc1a9122017-12-11 22:00:56 +0000381 writeUleb128(OS, IndirectFunctions.size(), "elem count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000382
Sam Cleggbfb75342018-11-15 00:37:21 +0000383 uint32_t TableIndex = TableBase;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000384 for (const FunctionSymbol *Sym : IndirectFunctions) {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000385 assert(Sym->getTableIndex() == TableIndex);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000386 writeUleb128(OS, Sym->getFunctionIndex(), "function index");
Sam Cleggfc1a9122017-12-11 22:00:56 +0000387 ++TableIndex;
388 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000389}
390
391void Writer::createCodeSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000392 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000393 return;
394
395 log("createCodeSection");
396
Sam Clegg9f934222018-02-21 18:29:23 +0000397 auto Section = make<CodeSection>(InputFunctions);
Sam Cleggc94d3932017-11-17 18:14:09 +0000398 OutputSections.push_back(Section);
399}
400
401void Writer::createDataSection() {
402 if (!Segments.size())
403 return;
404
405 log("createDataSection");
406 auto Section = make<DataSection>(Segments);
407 OutputSections.push_back(Section);
408}
409
Sam Cleggd451da12017-12-19 19:56:27 +0000410// Create relocations sections in the final output.
Sam Cleggc94d3932017-11-17 18:14:09 +0000411// These are only created when relocatable output is requested.
412void Writer::createRelocSections() {
413 log("createRelocSections");
414 // Don't use iterator here since we are adding to OutputSection
415 size_t OrigSize = OutputSections.size();
Rui Ueyamaffa650a2018-04-24 23:09:57 +0000416 for (size_t I = 0; I < OrigSize; I++) {
417 OutputSection *OSec = OutputSections[I];
Rui Ueyama37254062018-02-28 00:01:31 +0000418 uint32_t Count = OSec->numRelocations();
Sam Cleggc94d3932017-11-17 18:14:09 +0000419 if (!Count)
420 continue;
421
Rui Ueyama37254062018-02-28 00:01:31 +0000422 StringRef Name;
423 if (OSec->Type == WASM_SEC_DATA)
424 Name = "reloc.DATA";
425 else if (OSec->Type == WASM_SEC_CODE)
426 Name = "reloc.CODE";
Sam Cleggd177ab22018-05-04 23:14:42 +0000427 else if (OSec->Type == WASM_SEC_CUSTOM)
428 Name = Saver.save("reloc." + OSec->Name);
Sam Cleggc94d3932017-11-17 18:14:09 +0000429 else
Sam Cleggd177ab22018-05-04 23:14:42 +0000430 llvm_unreachable(
431 "relocations only supported for code, data, or custom sections");
Sam Cleggc94d3932017-11-17 18:14:09 +0000432
Rui Ueyama37254062018-02-28 00:01:31 +0000433 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, Name);
Sam Cleggc94d3932017-11-17 18:14:09 +0000434 raw_ostream &OS = Section->getStream();
Rui Ueyamaffa650a2018-04-24 23:09:57 +0000435 writeUleb128(OS, I, "reloc section");
Sam Cleggc94d3932017-11-17 18:14:09 +0000436 writeUleb128(OS, Count, "reloc count");
Rui Ueyama37254062018-02-28 00:01:31 +0000437 OSec->writeRelocations(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000438 }
439}
440
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000441static uint32_t getWasmFlags(const Symbol *Sym) {
442 uint32_t Flags = 0;
443 if (Sym->isLocal())
444 Flags |= WASM_SYMBOL_BINDING_LOCAL;
445 if (Sym->isWeak())
446 Flags |= WASM_SYMBOL_BINDING_WEAK;
447 if (Sym->isHidden())
448 Flags |= WASM_SYMBOL_VISIBILITY_HIDDEN;
449 if (Sym->isUndefined())
450 Flags |= WASM_SYMBOL_UNDEFINED;
451 return Flags;
452}
453
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000454// Some synthetic sections (e.g. "name" and "linking") have subsections.
455// Just like the synthetic sections themselves these need to be created before
456// they can be written out (since they are preceded by their length). This
457// class is used to create subsections and then write them into the stream
458// of the parent section.
459class SubSection {
460public:
461 explicit SubSection(uint32_t Type) : Type(Type) {}
462
463 void writeTo(raw_ostream &To) {
464 OS.flush();
Rui Ueyama67769102018-02-28 03:38:14 +0000465 writeUleb128(To, Type, "subsection type");
466 writeUleb128(To, Body.size(), "subsection size");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000467 To.write(Body.data(), Body.size());
468 }
469
470private:
471 uint32_t Type;
472 std::string Body;
473
474public:
475 raw_string_ostream OS{Body};
476};
477
Sam Cleggbfb75342018-11-15 00:37:21 +0000478// Create the custom "dylink" section containing information for the dynamic
479// linker.
480// See
481// https://github.com/WebAssembly/tool-conventions/blob/master/DynamicLinking.md
482void Writer::createDylinkSection() {
483 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "dylink");
484 raw_ostream &OS = Section->getStream();
485
486 writeUleb128(OS, MemSize, "MemSize");
Sam Clegg6320efb2019-01-16 01:43:21 +0000487 writeUleb128(OS, MemAlign, "MemAlign");
Sam Cleggbfb75342018-11-15 00:37:21 +0000488 writeUleb128(OS, IndirectFunctions.size(), "TableSize");
489 writeUleb128(OS, 0, "TableAlign");
Sam Clegge01c6462018-12-12 23:44:59 +0000490 writeUleb128(OS, 0, "Needed"); // TODO: Support "needed" shared libraries
Sam Cleggbfb75342018-11-15 00:37:21 +0000491}
492
Sam Clegg49ed9262017-12-01 00:53:21 +0000493// Create the custom "linking" section containing linker metadata.
Sam Cleggc94d3932017-11-17 18:14:09 +0000494// This is only created when relocatable output is requested.
495void Writer::createLinkingSection() {
496 SyntheticSection *Section =
497 createSyntheticSection(WASM_SEC_CUSTOM, "linking");
498 raw_ostream &OS = Section->getStream();
499
Sam Clegg2b8b1792018-04-26 18:17:21 +0000500 writeUleb128(OS, WasmMetadataVersion, "Version");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000501
Sam Clegg93102972018-02-23 05:08:53 +0000502 if (!SymtabEntries.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000503 SubSection Sub(WASM_SYMBOL_TABLE);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000504 writeUleb128(Sub.OS, SymtabEntries.size(), "num symbols");
505
Sam Clegg93102972018-02-23 05:08:53 +0000506 for (const Symbol *Sym : SymtabEntries) {
507 assert(Sym->isDefined() || Sym->isUndefined());
508 WasmSymbolType Kind = Sym->getWasmType();
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000509 uint32_t Flags = getWasmFlags(Sym);
510
Sam Clegg8518e7d2018-03-01 18:06:39 +0000511 writeU8(Sub.OS, Kind, "sym kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000512 writeUleb128(Sub.OS, Flags, "sym flags");
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000513
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000514 if (auto *F = dyn_cast<FunctionSymbol>(Sym)) {
515 writeUleb128(Sub.OS, F->getFunctionIndex(), "index");
Sam Clegg93102972018-02-23 05:08:53 +0000516 if (Sym->isDefined())
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000517 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000518 } else if (auto *G = dyn_cast<GlobalSymbol>(Sym)) {
519 writeUleb128(Sub.OS, G->getGlobalIndex(), "index");
520 if (Sym->isDefined())
521 writeStr(Sub.OS, Sym->getName(), "sym name");
Heejin Ahne915a712018-12-08 06:17:43 +0000522 } else if (auto *E = dyn_cast<EventSymbol>(Sym)) {
523 writeUleb128(Sub.OS, E->getEventIndex(), "index");
524 if (Sym->isDefined())
525 writeStr(Sub.OS, Sym->getName(), "sym name");
Andrea Di Biagio25c1a2f2018-05-05 10:53:31 +0000526 } else if (isa<DataSymbol>(Sym)) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000527 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegg93102972018-02-23 05:08:53 +0000528 if (auto *DataSym = dyn_cast<DefinedData>(Sym)) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000529 writeUleb128(Sub.OS, DataSym->getOutputSegmentIndex(), "index");
530 writeUleb128(Sub.OS, DataSym->getOutputSegmentOffset(),
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000531 "data offset");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000532 writeUleb128(Sub.OS, DataSym->getSize(), "data size");
Sam Clegg93102972018-02-23 05:08:53 +0000533 }
Sam Cleggd177ab22018-05-04 23:14:42 +0000534 } else {
535 auto *S = cast<SectionSymbol>(Sym);
536 writeUleb128(Sub.OS, S->getOutputSectionIndex(), "sym section index");
Sam Clegg93102972018-02-23 05:08:53 +0000537 }
Sam Cleggd3052d52018-01-18 23:40:49 +0000538 }
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000539
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000540 Sub.writeTo(OS);
Sam Cleggd3052d52018-01-18 23:40:49 +0000541 }
542
Sam Clegg0d0dd392017-12-19 17:09:45 +0000543 if (Segments.size()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000544 SubSection Sub(WASM_SEGMENT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000545 writeUleb128(Sub.OS, Segments.size(), "num data segments");
Sam Cleggc94d3932017-11-17 18:14:09 +0000546 for (const OutputSegment *S : Segments) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000547 writeStr(Sub.OS, S->Name, "segment name");
548 writeUleb128(Sub.OS, S->Alignment, "alignment");
549 writeUleb128(Sub.OS, 0, "flags");
Sam Cleggc94d3932017-11-17 18:14:09 +0000550 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000551 Sub.writeTo(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000552 }
Sam Clegg0d0dd392017-12-19 17:09:45 +0000553
Sam Clegg0d0dd392017-12-19 17:09:45 +0000554 if (!InitFunctions.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000555 SubSection Sub(WASM_INIT_FUNCS);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000556 writeUleb128(Sub.OS, InitFunctions.size(), "num init functions");
Sam Clegg93102972018-02-23 05:08:53 +0000557 for (const WasmInitEntry &F : InitFunctions) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000558 writeUleb128(Sub.OS, F.Priority, "priority");
559 writeUleb128(Sub.OS, F.Sym->getOutputSymbolIndex(), "function index");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000560 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000561 Sub.writeTo(OS);
Sam Clegg0d0dd392017-12-19 17:09:45 +0000562 }
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000563
Nicholas Wilsondbd90bf2018-03-07 13:28:16 +0000564 struct ComdatEntry {
565 unsigned Kind;
566 uint32_t Index;
567 };
568 std::map<StringRef, std::vector<ComdatEntry>> Comdats;
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000569
Sam Clegg9f934222018-02-21 18:29:23 +0000570 for (const InputFunction *F : InputFunctions) {
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000571 StringRef Comdat = F->getComdatName();
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000572 if (!Comdat.empty())
573 Comdats[Comdat].emplace_back(
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000574 ComdatEntry{WASM_COMDAT_FUNCTION, F->getFunctionIndex()});
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000575 }
576 for (uint32_t I = 0; I < Segments.size(); ++I) {
Sam Cleggf98bccf2018-01-13 15:57:48 +0000577 const auto &InputSegments = Segments[I]->InputSegments;
578 if (InputSegments.empty())
579 continue;
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000580 StringRef Comdat = InputSegments[0]->getComdatName();
Sam Clegga697df522018-01-13 15:59:53 +0000581#ifndef NDEBUG
Sam Cleggf98bccf2018-01-13 15:57:48 +0000582 for (const InputSegment *IS : InputSegments)
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000583 assert(IS->getComdatName() == Comdat);
Sam Clegga697df522018-01-13 15:59:53 +0000584#endif
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000585 if (!Comdat.empty())
586 Comdats[Comdat].emplace_back(ComdatEntry{WASM_COMDAT_DATA, I});
587 }
588
589 if (!Comdats.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000590 SubSection Sub(WASM_COMDAT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000591 writeUleb128(Sub.OS, Comdats.size(), "num comdats");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000592 for (const auto &C : Comdats) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000593 writeStr(Sub.OS, C.first, "comdat name");
594 writeUleb128(Sub.OS, 0, "comdat flags"); // flags for future use
595 writeUleb128(Sub.OS, C.second.size(), "num entries");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000596 for (const ComdatEntry &Entry : C.second) {
Sam Clegg8518e7d2018-03-01 18:06:39 +0000597 writeU8(Sub.OS, Entry.Kind, "entry kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000598 writeUleb128(Sub.OS, Entry.Index, "entry index");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000599 }
600 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000601 Sub.writeTo(OS);
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000602 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000603}
604
605// Create the custom "name" section containing debug symbol names.
606void Writer::createNameSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000607 unsigned NumNames = NumImportedFunctions;
Sam Clegg9f934222018-02-21 18:29:23 +0000608 for (const InputFunction *F : InputFunctions)
Nicholas Wilson6c7fe302018-04-20 17:09:18 +0000609 if (!F->getName().empty() || !F->getDebugName().empty())
Sam Clegg1963d712018-01-17 20:19:04 +0000610 ++NumNames;
Sam Cleggc94d3932017-11-17 18:14:09 +0000611
Sam Clegg1963d712018-01-17 20:19:04 +0000612 if (NumNames == 0)
613 return;
Sam Clegg50686852018-01-12 18:35:13 +0000614
Sam Cleggc94d3932017-11-17 18:14:09 +0000615 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "name");
616
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000617 SubSection Sub(WASM_NAMES_FUNCTION);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000618 writeUleb128(Sub.OS, NumNames, "name count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000619
Sam Clegg93102972018-02-23 05:08:53 +0000620 // Names must appear in function index order. As it happens ImportedSymbols
621 // and InputFunctions are numbered in order with imported functions coming
Sam Clegg1963d712018-01-17 20:19:04 +0000622 // first.
Sam Clegg93102972018-02-23 05:08:53 +0000623 for (const Symbol *S : ImportedSymbols) {
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000624 if (auto *F = dyn_cast<FunctionSymbol>(S)) {
625 writeUleb128(Sub.OS, F->getFunctionIndex(), "func index");
Sam Clegg37125f02018-11-09 16:57:41 +0000626 writeStr(Sub.OS, toString(*S), "symbol name");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000627 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000628 }
Sam Clegg9f934222018-02-21 18:29:23 +0000629 for (const InputFunction *F : InputFunctions) {
Sam Clegg1963d712018-01-17 20:19:04 +0000630 if (!F->getName().empty()) {
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000631 writeUleb128(Sub.OS, F->getFunctionIndex(), "func index");
Nicholas Wilson6c7fe302018-04-20 17:09:18 +0000632 if (!F->getDebugName().empty()) {
633 writeStr(Sub.OS, F->getDebugName(), "symbol name");
634 } else {
Sam Clegg37125f02018-11-09 16:57:41 +0000635 writeStr(Sub.OS, maybeDemangleSymbol(F->getName()), "symbol name");
Nicholas Wilson6c7fe302018-04-20 17:09:18 +0000636 }
Sam Clegg1963d712018-01-17 20:19:04 +0000637 }
638 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000639
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000640 Sub.writeTo(Section->getStream());
Sam Cleggc94d3932017-11-17 18:14:09 +0000641}
642
Thomas Lively2a0868f2019-01-17 02:29:41 +0000643void Writer::createProducersSection() {
644 SmallVector<std::pair<std::string, std::string>, 8> Languages;
645 SmallVector<std::pair<std::string, std::string>, 8> Tools;
646 SmallVector<std::pair<std::string, std::string>, 8> SDKs;
647 for (ObjFile *File : Symtab->ObjectFiles) {
648 const WasmProducerInfo &Info = File->getWasmObj()->getProducerInfo();
649 for (auto &Producers : {std::make_pair(&Info.Languages, &Languages),
650 std::make_pair(&Info.Tools, &Tools),
651 std::make_pair(&Info.SDKs, &SDKs)})
652 for (auto &Producer : *Producers.first)
653 if (Producers.second->end() ==
654 std::find_if(Producers.second->begin(), Producers.second->end(),
655 [&](std::pair<std::string, std::string> Seen) {
656 return Seen.first == Producer.first;
657 }))
658 Producers.second->push_back(Producer);
659 }
660 int FieldCount =
661 int(!Languages.empty()) + int(!Tools.empty()) + int(!SDKs.empty());
662 if (FieldCount == 0)
663 return;
664 SyntheticSection *Section =
665 createSyntheticSection(WASM_SEC_CUSTOM, "producers");
666 auto &OS = Section->getStream();
667 writeUleb128(OS, FieldCount, "field count");
668 for (auto &Field :
669 {std::make_pair("language", Languages),
670 std::make_pair("processed-by", Tools), std::make_pair("sdk", SDKs)}) {
671 if (Field.second.empty())
672 continue;
673 writeStr(OS, Field.first, "field name");
674 writeUleb128(OS, Field.second.size(), "number of entries");
675 for (auto &Entry : Field.second) {
676 writeStr(OS, Entry.first, "producer name");
677 writeStr(OS, Entry.second, "producer version");
678 }
679 }
680}
681
Sam Cleggc94d3932017-11-17 18:14:09 +0000682void Writer::writeHeader() {
683 memcpy(Buffer->getBufferStart(), Header.data(), Header.size());
684}
685
686void Writer::writeSections() {
687 uint8_t *Buf = Buffer->getBufferStart();
688 parallelForEach(OutputSections, [Buf](OutputSection *S) { S->writeTo(Buf); });
689}
690
691// Fix the memory layout of the output binary. This assigns memory offsets
Sam Clegg49ed9262017-12-01 00:53:21 +0000692// to each of the input data sections as well as the explicit stack region.
Sam Clegga0f095e2018-05-03 17:21:53 +0000693// The default memory layout is as follows, from low to high.
694//
Sam Cleggf0d433d2018-02-02 22:59:56 +0000695// - initialized data (starting at Config->GlobalBase)
696// - BSS data (not currently implemented in llvm)
697// - explicit stack (Config->ZStackSize)
698// - heap start / unallocated
Sam Clegga0f095e2018-05-03 17:21:53 +0000699//
700// The --stack-first option means that stack is placed before any static data.
Heejin Ahn4821ebf2018-08-29 21:03:16 +0000701// This can be useful since it means that stack overflow traps immediately
702// rather than overwriting global data, but also increases code size since all
703// static data loads and stores requires larger offsets.
Sam Cleggc94d3932017-11-17 18:14:09 +0000704void Writer::layoutMemory() {
Sam Cleggc94d3932017-11-17 18:14:09 +0000705 createOutputSegments();
706
Sam Clegga0f095e2018-05-03 17:21:53 +0000707 uint32_t MemoryPtr = 0;
708
709 auto PlaceStack = [&]() {
Sam Cleggbfb75342018-11-15 00:37:21 +0000710 if (Config->Relocatable || Config->Shared)
Sam Clegga0f095e2018-05-03 17:21:53 +0000711 return;
Heejin Ahna1cc4ea2019-02-04 19:13:46 +0000712 MemoryPtr = alignTo(MemoryPtr, StackAlignment);
713 if (Config->ZStackSize != alignTo(Config->ZStackSize, StackAlignment))
714 error("stack size must be " + Twine(StackAlignment) + "-byte aligned");
Sam Clegga0f095e2018-05-03 17:21:53 +0000715 log("mem: stack size = " + Twine(Config->ZStackSize));
716 log("mem: stack base = " + Twine(MemoryPtr));
717 MemoryPtr += Config->ZStackSize;
Sam Clegg2dad4e22018-11-15 18:15:54 +0000718 auto *SP = cast<DefinedGlobal>(WasmSym::StackPointer);
719 SP->Global->Global.InitExpr.Value.Int32 = MemoryPtr;
Sam Clegga0f095e2018-05-03 17:21:53 +0000720 log("mem: stack top = " + Twine(MemoryPtr));
721 };
722
723 if (Config->StackFirst) {
724 PlaceStack();
725 } else {
726 MemoryPtr = Config->GlobalBase;
727 log("mem: global base = " + Twine(Config->GlobalBase));
728 }
729
730 uint32_t DataStart = MemoryPtr;
731
Sam Cleggf0d433d2018-02-02 22:59:56 +0000732 // Arbitrarily set __dso_handle handle to point to the start of the data
733 // segments.
734 if (WasmSym::DsoHandle)
Sam Clegga0f095e2018-05-03 17:21:53 +0000735 WasmSym::DsoHandle->setVirtualAddress(DataStart);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000736
Sam Cleggbfb75342018-11-15 00:37:21 +0000737 MemAlign = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000738 for (OutputSegment *Seg : Segments) {
Sam Cleggbfb75342018-11-15 00:37:21 +0000739 MemAlign = std::max(MemAlign, Seg->Alignment);
Sam Clegg622ad042019-01-17 22:09:09 +0000740 MemoryPtr = alignTo(MemoryPtr, 1ULL << Seg->Alignment);
Sam Cleggc94d3932017-11-17 18:14:09 +0000741 Seg->StartVA = MemoryPtr;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000742 log(formatv("mem: {0,-15} offset={1,-8} size={2,-8} align={3}", Seg->Name,
743 MemoryPtr, Seg->Size, Seg->Alignment));
Sam Cleggc94d3932017-11-17 18:14:09 +0000744 MemoryPtr += Seg->Size;
745 }
746
Sam Cleggf0d433d2018-02-02 22:59:56 +0000747 // TODO: Add .bss space here.
Sam Clegg37a4a8a2018-02-07 03:04:53 +0000748 if (WasmSym::DataEnd)
749 WasmSym::DataEnd->setVirtualAddress(MemoryPtr);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000750
Sam Clegga0f095e2018-05-03 17:21:53 +0000751 log("mem: static data = " + Twine(MemoryPtr - DataStart));
Sam Cleggc94d3932017-11-17 18:14:09 +0000752
Sam Clegg2dad4e22018-11-15 18:15:54 +0000753 if (Config->Shared) {
754 MemSize = MemoryPtr;
755 return;
756 }
757
Sam Clegga0f095e2018-05-03 17:21:53 +0000758 if (!Config->StackFirst)
759 PlaceStack();
760
761 // Set `__heap_base` to directly follow the end of the stack or global data.
762 // The fact that this comes last means that a malloc/brk implementation
763 // can grow the heap at runtime.
Sam Cleggc94d3932017-11-17 18:14:09 +0000764 if (!Config->Relocatable) {
Sam Cleggf0d433d2018-02-02 22:59:56 +0000765 WasmSym::HeapBase->setVirtualAddress(MemoryPtr);
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000766 log("mem: heap base = " + Twine(MemoryPtr));
Sam Cleggc94d3932017-11-17 18:14:09 +0000767 }
768
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000769 if (Config->InitialMemory != 0) {
770 if (Config->InitialMemory != alignTo(Config->InitialMemory, WasmPageSize))
771 error("initial memory must be " + Twine(WasmPageSize) + "-byte aligned");
772 if (MemoryPtr > Config->InitialMemory)
773 error("initial memory too small, " + Twine(MemoryPtr) + " bytes needed");
774 else
775 MemoryPtr = Config->InitialMemory;
776 }
Sam Cleggbfb75342018-11-15 00:37:21 +0000777 MemSize = MemoryPtr;
778 NumMemoryPages = alignTo(MemoryPtr, WasmPageSize) / WasmPageSize;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000779 log("mem: total pages = " + Twine(NumMemoryPages));
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000780
781 if (Config->MaxMemory != 0) {
782 if (Config->MaxMemory != alignTo(Config->MaxMemory, WasmPageSize))
783 error("maximum memory must be " + Twine(WasmPageSize) + "-byte aligned");
784 if (MemoryPtr > Config->MaxMemory)
785 error("maximum memory too small, " + Twine(MemoryPtr) + " bytes needed");
786 MaxMemoryPages = Config->MaxMemory / WasmPageSize;
787 log("mem: max pages = " + Twine(MaxMemoryPages));
788 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000789}
790
791SyntheticSection *Writer::createSyntheticSection(uint32_t Type,
Sam Cleggc375e4e2018-01-10 19:18:22 +0000792 StringRef Name) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000793 auto Sec = make<SyntheticSection>(Type, Name);
Sam Cleggab2ac292017-12-20 05:14:48 +0000794 log("createSection: " + toString(*Sec));
Sam Cleggc94d3932017-11-17 18:14:09 +0000795 OutputSections.push_back(Sec);
796 return Sec;
797}
798
799void Writer::createSections() {
800 // Known sections
Sam Cleggbfb75342018-11-15 00:37:21 +0000801 if (Config->Pic)
802 createDylinkSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000803 createTypeSection();
804 createImportSection();
805 createFunctionSection();
806 createTableSection();
807 createMemorySection();
808 createGlobalSection();
Heejin Ahne915a712018-12-08 06:17:43 +0000809 createEventSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000810 createExportSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000811 createElemSection();
812 createCodeSection();
813 createDataSection();
Sam Clegg80ba4382018-04-10 16:12:49 +0000814 createCustomSections();
Sam Cleggc94d3932017-11-17 18:14:09 +0000815
816 // Custom sections
Sam Clegg99eb42c2018-02-27 23:58:03 +0000817 if (Config->Relocatable) {
Sam Clegg99eb42c2018-02-27 23:58:03 +0000818 createLinkingSection();
Nicholas Wilson94d3b162018-03-05 12:33:58 +0000819 createRelocSections();
Sam Clegg99eb42c2018-02-27 23:58:03 +0000820 }
Thomas Lively2a0868f2019-01-17 02:29:41 +0000821
Sam Cleggc94d3932017-11-17 18:14:09 +0000822 if (!Config->StripDebug && !Config->StripAll)
823 createNameSection();
824
Thomas Lively2a0868f2019-01-17 02:29:41 +0000825 if (!Config->StripAll)
826 createProducersSection();
827
Sam Cleggc94d3932017-11-17 18:14:09 +0000828 for (OutputSection *S : OutputSections) {
829 S->setOffset(FileSize);
830 S->finalizeContents();
831 FileSize += S->getSize();
832 }
833}
834
Sam Cleggc94d3932017-11-17 18:14:09 +0000835void Writer::calculateImports() {
Sam Clegg574d7ce2017-12-15 19:23:49 +0000836 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000837 if (!Sym->isUndefined())
838 continue;
839 if (isa<DataSymbol>(Sym))
840 continue;
841 if (Sym->isWeak() && !Config->Relocatable)
Sam Clegg574d7ce2017-12-15 19:23:49 +0000842 continue;
Nicholas Wilsona1e299f2018-04-20 17:18:06 +0000843 if (!Sym->isLive())
844 continue;
Sam Cleggc729c1b2018-05-30 18:07:52 +0000845 if (!Sym->IsUsedInRegularObj)
846 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000847
Nicola Zaghene7245b42018-05-15 13:36:20 +0000848 LLVM_DEBUG(dbgs() << "import: " << Sym->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000849 ImportedSymbols.emplace_back(Sym);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000850 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
851 F->setFunctionIndex(NumImportedFunctions++);
Heejin Ahne915a712018-12-08 06:17:43 +0000852 else if (auto *G = dyn_cast<GlobalSymbol>(Sym))
853 G->setGlobalIndex(NumImportedGlobals++);
Sam Clegg93102972018-02-23 05:08:53 +0000854 else
Heejin Ahne915a712018-12-08 06:17:43 +0000855 cast<EventSymbol>(Sym)->setEventIndex(NumImportedEvents++);
Sam Cleggc94d3932017-11-17 18:14:09 +0000856 }
857}
858
Sam Cleggd3052d52018-01-18 23:40:49 +0000859void Writer::calculateExports() {
Sam Clegg93102972018-02-23 05:08:53 +0000860 if (Config->Relocatable)
861 return;
Sam Cleggf0d433d2018-02-02 22:59:56 +0000862
Sam Cleggd6beb322018-05-10 18:10:34 +0000863 if (!Config->Relocatable && !Config->ImportMemory)
864 Exports.push_back(WasmExport{"memory", WASM_EXTERNAL_MEMORY, 0});
865
866 if (!Config->Relocatable && Config->ExportTable)
Heejin Ahna1cc4ea2019-02-04 19:13:46 +0000867 Exports.push_back(WasmExport{FunctionTableName, WASM_EXTERNAL_TABLE, 0});
Sam Cleggd6beb322018-05-10 18:10:34 +0000868
869 unsigned FakeGlobalIndex = NumImportedGlobals + InputGlobals.size();
870
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000871 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Cleggce004bf2018-06-28 17:04:58 +0000872 if (!Sym->isExported())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000873 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000874 if (!Sym->isLive())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000875 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000876
Sam Cleggd6beb322018-05-10 18:10:34 +0000877 StringRef Name = Sym->getName();
878 WasmExport Export;
879 if (auto *F = dyn_cast<DefinedFunction>(Sym)) {
880 Export = {Name, WASM_EXTERNAL_FUNCTION, F->getFunctionIndex()};
881 } else if (auto *G = dyn_cast<DefinedGlobal>(Sym)) {
Sam Clegg177b4582018-06-07 01:27:07 +0000882 // TODO(sbc): Remove this check once to mutable global proposal is
883 // implement in all major browsers.
884 // See: https://github.com/WebAssembly/mutable-global
885 if (G->getGlobalType()->Mutable) {
886 // Only the __stack_pointer should ever be create as mutable.
887 assert(G == WasmSym::StackPointer);
888 continue;
889 }
Sam Cleggd6beb322018-05-10 18:10:34 +0000890 Export = {Name, WASM_EXTERNAL_GLOBAL, G->getGlobalIndex()};
Heejin Ahne915a712018-12-08 06:17:43 +0000891 } else if (auto *E = dyn_cast<DefinedEvent>(Sym)) {
892 Export = {Name, WASM_EXTERNAL_EVENT, E->getEventIndex()};
Sam Cleggd6beb322018-05-10 18:10:34 +0000893 } else {
894 auto *D = cast<DefinedData>(Sym);
Sam Clegg93102972018-02-23 05:08:53 +0000895 DefinedFakeGlobals.emplace_back(D);
Sam Cleggd6beb322018-05-10 18:10:34 +0000896 Export = {Name, WASM_EXTERNAL_GLOBAL, FakeGlobalIndex++};
897 }
898
Nicola Zaghene7245b42018-05-15 13:36:20 +0000899 LLVM_DEBUG(dbgs() << "Export: " << Name << "\n");
Sam Cleggd6beb322018-05-10 18:10:34 +0000900 Exports.push_back(Export);
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000901 }
Sam Clegg93102972018-02-23 05:08:53 +0000902}
903
904void Writer::assignSymtab() {
905 if (!Config->Relocatable)
906 return;
907
Sam Cleggd177ab22018-05-04 23:14:42 +0000908 StringMap<uint32_t> SectionSymbolIndices;
909
Sam Clegg93102972018-02-23 05:08:53 +0000910 unsigned SymbolIndex = SymtabEntries.size();
Sam Cleggd177ab22018-05-04 23:14:42 +0000911
Sam Clegg89e4dcb2019-01-30 18:55:15 +0000912 auto AddSymbol = [&](Symbol *Sym) {
913 if (auto *S = dyn_cast<SectionSymbol>(Sym)) {
914 StringRef Name = S->getName();
915 if (CustomSectionMapping.count(Name) == 0)
916 return;
Sam Cleggd177ab22018-05-04 23:14:42 +0000917
Sam Clegg89e4dcb2019-01-30 18:55:15 +0000918 auto SSI = SectionSymbolIndices.find(Name);
919 if (SSI != SectionSymbolIndices.end()) {
920 Sym->setOutputSymbolIndex(SSI->second);
921 return;
Sam Cleggd177ab22018-05-04 23:14:42 +0000922 }
923
Sam Clegg89e4dcb2019-01-30 18:55:15 +0000924 SectionSymbolIndices[Name] = SymbolIndex;
925 CustomSectionSymbols[Name] = cast<SectionSymbol>(Sym);
Sam Cleggd3052d52018-01-18 23:40:49 +0000926
Sam Clegg89e4dcb2019-01-30 18:55:15 +0000927 Sym->markLive();
928 }
929
930 // (Since this is relocatable output, GC is not performed so symbols must
931 // be live.)
932 assert(Sym->isLive());
933 Sym->setOutputSymbolIndex(SymbolIndex++);
934 SymtabEntries.emplace_back(Sym);
935 };
936
937 for (Symbol *Sym : Symtab->getSymbols())
938 if (!Sym->isLazy())
939 AddSymbol(Sym);
940
941 for (ObjFile *File : Symtab->ObjectFiles) {
942 LLVM_DEBUG(dbgs() << "Local symtab entries: " << File->getName() << "\n");
943 for (Symbol *Sym : File->getSymbols())
944 if (Sym->isLocal())
945 AddSymbol(Sym);
946 }
Sam Cleggd3052d52018-01-18 23:40:49 +0000947}
948
Sam Cleggc375e4e2018-01-10 19:18:22 +0000949uint32_t Writer::lookupType(const WasmSignature &Sig) {
Sam Clegg8d027d62018-01-10 20:12:26 +0000950 auto It = TypeIndices.find(Sig);
951 if (It == TypeIndices.end()) {
Sam Cleggc375e4e2018-01-10 19:18:22 +0000952 error("type not found: " + toString(Sig));
Sam Clegg8d027d62018-01-10 20:12:26 +0000953 return 0;
954 }
955 return It->second;
Sam Cleggc375e4e2018-01-10 19:18:22 +0000956}
957
958uint32_t Writer::registerType(const WasmSignature &Sig) {
Sam Cleggb8621592017-11-30 01:40:08 +0000959 auto Pair = TypeIndices.insert(std::make_pair(Sig, Types.size()));
Sam Cleggc375e4e2018-01-10 19:18:22 +0000960 if (Pair.second) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000961 LLVM_DEBUG(dbgs() << "type " << toString(Sig) << "\n");
Sam Cleggb8621592017-11-30 01:40:08 +0000962 Types.push_back(&Sig);
Sam Cleggc375e4e2018-01-10 19:18:22 +0000963 }
Sam Cleggb8621592017-11-30 01:40:08 +0000964 return Pair.first->second;
965}
966
Sam Cleggc94d3932017-11-17 18:14:09 +0000967void Writer::calculateTypes() {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000968 // The output type section is the union of the following sets:
969 // 1. Any signature used in the TYPE relocation
970 // 2. The signatures of all imported functions
971 // 3. The signatures of all defined functions
Heejin Ahne915a712018-12-08 06:17:43 +0000972 // 4. The signatures of all imported events
973 // 5. The signatures of all defined events
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000974
Sam Cleggc94d3932017-11-17 18:14:09 +0000975 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000976 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
977 for (uint32_t I = 0; I < Types.size(); I++)
978 if (File->TypeIsUsed[I])
979 File->TypeMap[I] = registerType(Types[I]);
Sam Cleggc94d3932017-11-17 18:14:09 +0000980 }
Sam Clegg50686852018-01-12 18:35:13 +0000981
Heejin Ahne915a712018-12-08 06:17:43 +0000982 for (const Symbol *Sym : ImportedSymbols) {
Sam Clegg93102972018-02-23 05:08:53 +0000983 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
Heejin Ahne915a712018-12-08 06:17:43 +0000984 registerType(*F->Signature);
985 else if (auto *E = dyn_cast<EventSymbol>(Sym))
986 registerType(*E->Signature);
987 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000988
Sam Clegg9f934222018-02-21 18:29:23 +0000989 for (const InputFunction *F : InputFunctions)
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000990 registerType(F->Signature);
Heejin Ahne915a712018-12-08 06:17:43 +0000991
992 for (const InputEvent *E : InputEvents)
993 registerType(E->Signature);
Sam Cleggc94d3932017-11-17 18:14:09 +0000994}
995
Sam Clegg8d146bb2018-01-09 23:56:44 +0000996void Writer::assignIndexes() {
Heejin Ahnaeaab992018-11-19 23:21:25 +0000997 assert(InputFunctions.empty());
998 uint32_t FunctionIndex = NumImportedFunctions;
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000999 auto AddDefinedFunction = [&](InputFunction *Func) {
1000 if (!Func->Live)
1001 return;
1002 InputFunctions.emplace_back(Func);
Sam Clegge3f3ccf2018-03-12 19:56:23 +00001003 Func->setFunctionIndex(FunctionIndex++);
Nicholas Wilsonebda41f2018-03-09 16:43:05 +00001004 };
1005
Nicholas Wilson5639da82018-03-12 15:44:07 +00001006 for (InputFunction *Func : Symtab->SyntheticFunctions)
1007 AddDefinedFunction(Func);
1008
Sam Clegg87e61922018-01-08 23:39:11 +00001009 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001010 LLVM_DEBUG(dbgs() << "Functions: " << File->getName() << "\n");
Nicholas Wilsonebda41f2018-03-09 16:43:05 +00001011 for (InputFunction *Func : File->Functions)
1012 AddDefinedFunction(Func);
Sam Clegg8d146bb2018-01-09 23:56:44 +00001013 }
1014
Sam Cleggbfb75342018-11-15 00:37:21 +00001015 uint32_t TableIndex = TableBase;
Sam Clegg6c4dbfee2018-02-23 04:59:57 +00001016 auto HandleRelocs = [&](InputChunk *Chunk) {
1017 if (!Chunk->Live)
1018 return;
1019 ObjFile *File = Chunk->File;
1020 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
Sam Clegg93102972018-02-23 05:08:53 +00001021 for (const WasmRelocation &Reloc : Chunk->getRelocations()) {
Sam Clegg79e33172019-02-04 17:49:33 +00001022 if (Reloc.Type == R_WASM_TABLE_INDEX_I32 ||
1023 Reloc.Type == R_WASM_TABLE_INDEX_SLEB) {
Sam Clegg6c4dbfee2018-02-23 04:59:57 +00001024 FunctionSymbol *Sym = File->getFunctionSymbol(Reloc.Index);
Sam Clegge3f3ccf2018-03-12 19:56:23 +00001025 if (Sym->hasTableIndex() || !Sym->hasFunctionIndex())
Sam Clegg6c4dbfee2018-02-23 04:59:57 +00001026 continue;
1027 Sym->setTableIndex(TableIndex++);
1028 IndirectFunctions.emplace_back(Sym);
Sam Clegg79e33172019-02-04 17:49:33 +00001029 } else if (Reloc.Type == R_WASM_TYPE_INDEX_LEB) {
Sam Clegg93102972018-02-23 05:08:53 +00001030 // Mark target type as live
Sam Clegg6c4dbfee2018-02-23 04:59:57 +00001031 File->TypeMap[Reloc.Index] = registerType(Types[Reloc.Index]);
1032 File->TypeIsUsed[Reloc.Index] = true;
1033 }
1034 }
1035 };
1036
Sam Clegg8d146bb2018-01-09 23:56:44 +00001037 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001038 LLVM_DEBUG(dbgs() << "Handle relocs: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +00001039 for (InputChunk *Chunk : File->Functions)
1040 HandleRelocs(Chunk);
1041 for (InputChunk *Chunk : File->Segments)
1042 HandleRelocs(Chunk);
Sam Cleggd177ab22018-05-04 23:14:42 +00001043 for (auto &P : File->CustomSections)
1044 HandleRelocs(P);
Sam Clegg93102972018-02-23 05:08:53 +00001045 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +00001046
Heejin Ahnaeaab992018-11-19 23:21:25 +00001047 assert(InputGlobals.empty());
1048 uint32_t GlobalIndex = NumImportedGlobals;
Sam Clegg93102972018-02-23 05:08:53 +00001049 auto AddDefinedGlobal = [&](InputGlobal *Global) {
1050 if (Global->Live) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001051 LLVM_DEBUG(dbgs() << "AddDefinedGlobal: " << GlobalIndex << "\n");
Sam Clegge3f3ccf2018-03-12 19:56:23 +00001052 Global->setGlobalIndex(GlobalIndex++);
Sam Clegg93102972018-02-23 05:08:53 +00001053 InputGlobals.push_back(Global);
1054 }
1055 };
1056
Nicholas Wilsonebda41f2018-03-09 16:43:05 +00001057 for (InputGlobal *Global : Symtab->SyntheticGlobals)
1058 AddDefinedGlobal(Global);
Sam Clegg93102972018-02-23 05:08:53 +00001059
1060 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001061 LLVM_DEBUG(dbgs() << "Globals: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +00001062 for (InputGlobal *Global : File->Globals)
1063 AddDefinedGlobal(Global);
Sam Cleggc94d3932017-11-17 18:14:09 +00001064 }
Heejin Ahne915a712018-12-08 06:17:43 +00001065
1066 assert(InputEvents.empty());
1067 uint32_t EventIndex = NumImportedEvents;
1068 auto AddDefinedEvent = [&](InputEvent *Event) {
1069 if (Event->Live) {
1070 LLVM_DEBUG(dbgs() << "AddDefinedEvent: " << EventIndex << "\n");
1071 Event->setEventIndex(EventIndex++);
1072 InputEvents.push_back(Event);
1073 }
1074 };
1075
1076 for (ObjFile *File : Symtab->ObjectFiles) {
1077 LLVM_DEBUG(dbgs() << "Events: " << File->getName() << "\n");
1078 for (InputEvent *Event : File->Events)
1079 AddDefinedEvent(Event);
1080 }
Sam Cleggc94d3932017-11-17 18:14:09 +00001081}
1082
1083static StringRef getOutputDataSegmentName(StringRef Name) {
Sam Cleggbfb75342018-11-15 00:37:21 +00001084 // With PIC code we currently only support a single data segment since
1085 // we only have a single __memory_base to use as our base address.
1086 if (Config->Pic)
1087 return "data";
Sam Clegg66844762018-05-10 18:23:51 +00001088 if (!Config->MergeDataSegments)
Sam Cleggc94d3932017-11-17 18:14:09 +00001089 return Name;
Rui Ueyama4764b572018-02-28 00:57:28 +00001090 if (Name.startswith(".text."))
1091 return ".text";
1092 if (Name.startswith(".data."))
1093 return ".data";
1094 if (Name.startswith(".bss."))
1095 return ".bss";
Sam Clegg57694c52018-08-08 18:02:55 +00001096 if (Name.startswith(".rodata."))
1097 return ".rodata";
Sam Cleggc94d3932017-11-17 18:14:09 +00001098 return Name;
1099}
1100
1101void Writer::createOutputSegments() {
1102 for (ObjFile *File : Symtab->ObjectFiles) {
1103 for (InputSegment *Segment : File->Segments) {
Sam Clegg447ae402018-02-13 20:29:38 +00001104 if (!Segment->Live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +00001105 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +00001106 StringRef Name = getOutputDataSegmentName(Segment->getName());
1107 OutputSegment *&S = SegmentMap[Name];
1108 if (S == nullptr) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001109 LLVM_DEBUG(dbgs() << "new segment: " << Name << "\n");
Sam Clegg93102972018-02-23 05:08:53 +00001110 S = make<OutputSegment>(Name, Segments.size());
Sam Cleggc94d3932017-11-17 18:14:09 +00001111 Segments.push_back(S);
1112 }
1113 S->addInputSegment(Segment);
Nicola Zaghene7245b42018-05-15 13:36:20 +00001114 LLVM_DEBUG(dbgs() << "added data: " << Name << ": " << S->Size << "\n");
Sam Cleggc94d3932017-11-17 18:14:09 +00001115 }
1116 }
1117}
1118
Sam Clegg50686852018-01-12 18:35:13 +00001119static const int OPCODE_CALL = 0x10;
1120static const int OPCODE_END = 0xb;
1121
1122// Create synthetic "__wasm_call_ctors" function based on ctor functions
1123// in input object.
1124void Writer::createCtorFunction() {
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +00001125 // First write the body's contents to a string.
1126 std::string BodyContent;
Sam Clegg50686852018-01-12 18:35:13 +00001127 {
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +00001128 raw_string_ostream OS(BodyContent);
Sam Clegg50686852018-01-12 18:35:13 +00001129 writeUleb128(OS, 0, "num locals");
Sam Clegg93102972018-02-23 05:08:53 +00001130 for (const WasmInitEntry &F : InitFunctions) {
Sam Clegg50686852018-01-12 18:35:13 +00001131 writeU8(OS, OPCODE_CALL, "CALL");
Sam Clegge3f3ccf2018-03-12 19:56:23 +00001132 writeUleb128(OS, F.Sym->getFunctionIndex(), "function index");
Sam Clegg50686852018-01-12 18:35:13 +00001133 }
1134 writeU8(OS, OPCODE_END, "END");
1135 }
1136
1137 // Once we know the size of the body we can create the final function body
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +00001138 std::string FunctionBody;
1139 {
1140 raw_string_ostream OS(FunctionBody);
1141 writeUleb128(OS, BodyContent.size(), "function size");
1142 OS << BodyContent;
1143 }
Rui Ueyama29abfe42018-02-28 17:43:15 +00001144
Sam Cleggea656472018-10-22 08:35:39 +00001145 ArrayRef<uint8_t> Body = arrayRefFromStringRef(Saver.save(FunctionBody));
Nicholas Wilsonebda41f2018-03-09 16:43:05 +00001146 cast<SyntheticFunction>(WasmSym::CallCtors->Function)->setBody(Body);
Sam Clegg50686852018-01-12 18:35:13 +00001147}
1148
1149// Populate InitFunctions vector with init functions from all input objects.
1150// This is then used either when creating the output linking section or to
1151// synthesize the "__wasm_call_ctors" function.
1152void Writer::calculateInitFunctions() {
1153 for (ObjFile *File : Symtab->ObjectFiles) {
1154 const WasmLinkingData &L = File->getWasmObj()->linkingData();
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +00001155 for (const WasmInitFunc &F : L.InitFunctions) {
1156 FunctionSymbol *Sym = File->getFunctionSymbol(F.Symbol);
Heejin Ahne915a712018-12-08 06:17:43 +00001157 if (*Sym->Signature != WasmSignature{{}, {}})
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +00001158 error("invalid signature for init func: " + toString(*Sym));
1159 InitFunctions.emplace_back(WasmInitEntry{Sym, F.Priority});
1160 }
Sam Clegg50686852018-01-12 18:35:13 +00001161 }
Rui Ueyamada69b712018-02-28 00:15:59 +00001162
Sam Clegg50686852018-01-12 18:35:13 +00001163 // Sort in order of priority (lowest first) so that they are called
1164 // in the correct order.
Sam Clegg29b8feb2018-02-21 00:34:34 +00001165 std::stable_sort(InitFunctions.begin(), InitFunctions.end(),
Sam Clegg93102972018-02-23 05:08:53 +00001166 [](const WasmInitEntry &L, const WasmInitEntry &R) {
Sam Clegg29b8feb2018-02-21 00:34:34 +00001167 return L.Priority < R.Priority;
1168 });
Sam Clegg50686852018-01-12 18:35:13 +00001169}
1170
Sam Cleggc94d3932017-11-17 18:14:09 +00001171void Writer::run() {
Sam Cleggbfb75342018-11-15 00:37:21 +00001172 if (Config->Relocatable || Config->Pic)
Sam Clegg99eb42c2018-02-27 23:58:03 +00001173 Config->GlobalBase = 0;
1174
Sam Cleggbfb75342018-11-15 00:37:21 +00001175 // For PIC code the table base is assigned dynamically by the loader.
1176 // For non-PIC, we start at 1 so that accessing table index 0 always traps.
1177 if (!Config->Pic)
1178 TableBase = 1;
1179
Sam Cleggc94d3932017-11-17 18:14:09 +00001180 log("-- calculateImports");
1181 calculateImports();
Sam Clegg8d146bb2018-01-09 23:56:44 +00001182 log("-- assignIndexes");
1183 assignIndexes();
Sam Clegg50686852018-01-12 18:35:13 +00001184 log("-- calculateInitFunctions");
1185 calculateInitFunctions();
1186 if (!Config->Relocatable)
1187 createCtorFunction();
Sam Clegg8f6d2de2018-01-31 23:48:14 +00001188 log("-- calculateTypes");
1189 calculateTypes();
Sam Clegg93102972018-02-23 05:08:53 +00001190 log("-- layoutMemory");
1191 layoutMemory();
1192 log("-- calculateExports");
1193 calculateExports();
Sam Cleggd177ab22018-05-04 23:14:42 +00001194 log("-- calculateCustomSections");
1195 calculateCustomSections();
Sam Clegg93102972018-02-23 05:08:53 +00001196 log("-- assignSymtab");
1197 assignSymtab();
Sam Cleggc94d3932017-11-17 18:14:09 +00001198
1199 if (errorHandler().Verbose) {
Sam Clegg9f934222018-02-21 18:29:23 +00001200 log("Defined Functions: " + Twine(InputFunctions.size()));
Sam Clegg93102972018-02-23 05:08:53 +00001201 log("Defined Globals : " + Twine(InputGlobals.size()));
Heejin Ahne915a712018-12-08 06:17:43 +00001202 log("Defined Events : " + Twine(InputEvents.size()));
Sam Clegg93102972018-02-23 05:08:53 +00001203 log("Function Imports : " + Twine(NumImportedFunctions));
1204 log("Global Imports : " + Twine(NumImportedGlobals));
Heejin Ahne915a712018-12-08 06:17:43 +00001205 log("Event Imports : " + Twine(NumImportedEvents));
Sam Cleggc94d3932017-11-17 18:14:09 +00001206 for (ObjFile *File : Symtab->ObjectFiles)
1207 File->dumpInfo();
1208 }
1209
Sam Cleggc94d3932017-11-17 18:14:09 +00001210 createHeader();
1211 log("-- createSections");
1212 createSections();
1213
1214 log("-- openFile");
1215 openFile();
1216 if (errorCount())
1217 return;
1218
1219 writeHeader();
1220
1221 log("-- writeSections");
1222 writeSections();
1223 if (errorCount())
1224 return;
1225
1226 if (Error E = Buffer->commit())
1227 fatal("failed to write the output file: " + toString(std::move(E)));
1228}
1229
1230// Open a result file.
1231void Writer::openFile() {
1232 log("writing: " + Config->OutputFile);
Sam Cleggc94d3932017-11-17 18:14:09 +00001233
1234 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
1235 FileOutputBuffer::create(Config->OutputFile, FileSize,
1236 FileOutputBuffer::F_executable);
1237
1238 if (!BufferOrErr)
1239 error("failed to open " + Config->OutputFile + ": " +
1240 toString(BufferOrErr.takeError()));
1241 else
1242 Buffer = std::move(*BufferOrErr);
1243}
1244
1245void Writer::createHeader() {
1246 raw_string_ostream OS(Header);
1247 writeBytes(OS, WasmMagic, sizeof(WasmMagic), "wasm magic");
1248 writeU32(OS, WasmVersion, "wasm version");
1249 OS.flush();
1250 FileSize += Header.size();
1251}
1252
1253void lld::wasm::writeResult() { Writer().run(); }