blob: 879a1595361f644bc7f37386af5116da2e0c07e2 [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;
Dan Gohman9b84eea2019-02-07 22:00:48 +0000187 if (auto *F = dyn_cast<UndefinedFunction>(Sym)) {
188 Import.Field = F->ImportName;
189 Import.Module = F->ImportModule;
190 } else if (auto *G = dyn_cast<UndefinedGlobal>(Sym)) {
191 Import.Field = G->ImportName;
192 Import.Module = G->ImportModule;
193 } else {
194 Import.Field = Sym->getName();
Heejin Ahna1cc4ea2019-02-04 19:13:46 +0000195 Import.Module = DefaultModule;
Dan Gohman9b84eea2019-02-07 22:00:48 +0000196 }
Sam Clegg7cc07532019-02-01 02:29:57 +0000197
Sam Clegg93102972018-02-23 05:08:53 +0000198 if (auto *FunctionSym = dyn_cast<FunctionSymbol>(Sym)) {
199 Import.Kind = WASM_EXTERNAL_FUNCTION;
Heejin Ahne915a712018-12-08 06:17:43 +0000200 Import.SigIndex = lookupType(*FunctionSym->Signature);
201 } else if (auto *GlobalSym = dyn_cast<GlobalSymbol>(Sym)) {
Sam Clegg93102972018-02-23 05:08:53 +0000202 Import.Kind = WASM_EXTERNAL_GLOBAL;
203 Import.Global = *GlobalSym->getGlobalType();
Heejin Ahne915a712018-12-08 06:17:43 +0000204 } else {
205 auto *EventSym = cast<EventSymbol>(Sym);
206 Import.Kind = WASM_EXTERNAL_EVENT;
207 Import.Event.Attribute = EventSym->getEventType()->Attribute;
208 Import.Event.SigIndex = lookupType(*EventSym->Signature);
Sam Clegg93102972018-02-23 05:08:53 +0000209 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000210 writeImport(OS, Import);
211 }
212}
213
214void Writer::createTypeSection() {
215 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TYPE);
216 raw_ostream &OS = Section->getStream();
217 writeUleb128(OS, Types.size(), "type count");
Sam Cleggd451da12017-12-19 19:56:27 +0000218 for (const WasmSignature *Sig : Types)
Sam Cleggc94d3932017-11-17 18:14:09 +0000219 writeSig(OS, *Sig);
Sam Cleggc94d3932017-11-17 18:14:09 +0000220}
221
222void Writer::createFunctionSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000223 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000224 return;
225
226 SyntheticSection *Section = createSyntheticSection(WASM_SEC_FUNCTION);
227 raw_ostream &OS = Section->getStream();
228
Sam Clegg9f934222018-02-21 18:29:23 +0000229 writeUleb128(OS, InputFunctions.size(), "function count");
230 for (const InputFunction *Func : InputFunctions)
Sam Cleggc375e4e2018-01-10 19:18:22 +0000231 writeUleb128(OS, lookupType(Func->Signature), "sig index");
Sam Cleggc94d3932017-11-17 18:14:09 +0000232}
233
234void Writer::createMemorySection() {
235 if (Config->ImportMemory)
236 return;
237
238 SyntheticSection *Section = createSyntheticSection(WASM_SEC_MEMORY);
239 raw_ostream &OS = Section->getStream();
240
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000241 bool HasMax = MaxMemoryPages != 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000242 writeUleb128(OS, 1, "memory count");
Derek Schuff786760a2018-11-06 18:02:39 +0000243 unsigned Flags = 0;
244 if (HasMax)
245 Flags |= WASM_LIMITS_FLAG_HAS_MAX;
Derek Schuff3bea8bc2018-11-06 17:59:32 +0000246 if (Config->SharedMemory)
247 Flags |= WASM_LIMITS_FLAG_IS_SHARED;
248 writeUleb128(OS, Flags, "memory limits flags");
Sam Cleggc94d3932017-11-17 18:14:09 +0000249 writeUleb128(OS, NumMemoryPages, "initial pages");
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000250 if (HasMax)
251 writeUleb128(OS, MaxMemoryPages, "max pages");
Sam Cleggc94d3932017-11-17 18:14:09 +0000252}
253
254void Writer::createGlobalSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000255 unsigned NumGlobals = InputGlobals.size() + DefinedFakeGlobals.size();
256 if (NumGlobals == 0)
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000257 return;
258
Sam Cleggc94d3932017-11-17 18:14:09 +0000259 SyntheticSection *Section = createSyntheticSection(WASM_SEC_GLOBAL);
260 raw_ostream &OS = Section->getStream();
261
Sam Clegg93102972018-02-23 05:08:53 +0000262 writeUleb128(OS, NumGlobals, "global count");
263 for (const InputGlobal *G : InputGlobals)
264 writeGlobal(OS, G->Global);
265 for (const DefinedData *Sym : DefinedFakeGlobals) {
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000266 WasmGlobal Global;
Sam Clegg93102972018-02-23 05:08:53 +0000267 Global.Type = {WASM_TYPE_I32, false};
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000268 Global.InitExpr.Opcode = WASM_OPCODE_I32_CONST;
269 Global.InitExpr.Value.Int32 = Sym->getVirtualAddress();
Sam Cleggc94d3932017-11-17 18:14:09 +0000270 writeGlobal(OS, Global);
271 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000272}
273
Heejin Ahne915a712018-12-08 06:17:43 +0000274// The event section contains a list of declared wasm events associated with the
275// module. Currently the only supported event kind is exceptions. A single event
276// entry represents a single event with an event tag. All C++ exceptions are
277// represented by a single event. An event entry in this section contains
278// information on what kind of event it is (e.g. exception) and the type of
279// values contained in a single event object. (In wasm, an event can contain
280// multiple values of primitive types. But for C++ exceptions, we just throw a
281// pointer which is an i32 value (for wasm32 architecture), so the signature of
282// C++ exception is (i32)->(void), because all event types are assumed to have
283// void return type to share WasmSignature with functions.)
284void Writer::createEventSection() {
285 unsigned NumEvents = InputEvents.size();
286 if (NumEvents == 0)
287 return;
288
289 SyntheticSection *Section = createSyntheticSection(WASM_SEC_EVENT);
290 raw_ostream &OS = Section->getStream();
291
292 writeUleb128(OS, NumEvents, "event count");
293 for (InputEvent *E : InputEvents) {
294 E->Event.Type.SigIndex = lookupType(E->Signature);
295 writeEvent(OS, E->Event);
296 }
297}
298
Sam Cleggc94d3932017-11-17 18:14:09 +0000299void Writer::createTableSection() {
Nicholas Wilsonfc90b302018-03-28 12:53:29 +0000300 if (Config->ImportTable)
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000301 return;
302
303 // Always output a table section (or table import), even if there are no
304 // indirect calls. There are two reasons for this:
Sam Cleggfc1a9122017-12-11 22:00:56 +0000305 // 1. For executables it is useful to have an empty table slot at 0
306 // which can be filled with a null function call handler.
307 // 2. If we don't do this, any program that contains a call_indirect but
308 // no address-taken function will fail at validation time since it is
309 // a validation error to include a call_indirect instruction if there
310 // is not table.
Sam Cleggbfb75342018-11-15 00:37:21 +0000311 uint32_t TableSize = TableBase + IndirectFunctions.size();
Sam Cleggfc1a9122017-12-11 22:00:56 +0000312
Sam Cleggc94d3932017-11-17 18:14:09 +0000313 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TABLE);
314 raw_ostream &OS = Section->getStream();
315
316 writeUleb128(OS, 1, "table count");
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000317 WasmLimits Limits = {WASM_LIMITS_FLAG_HAS_MAX, TableSize, TableSize};
Thomas Lively25ff8932019-01-08 06:25:55 +0000318 writeTableType(OS, WasmTable{WASM_TYPE_FUNCREF, Limits});
Sam Cleggc94d3932017-11-17 18:14:09 +0000319}
320
321void Writer::createExportSection() {
Sam Cleggd6beb322018-05-10 18:10:34 +0000322 if (!Exports.size())
Sam Cleggc94d3932017-11-17 18:14:09 +0000323 return;
324
325 SyntheticSection *Section = createSyntheticSection(WASM_SEC_EXPORT);
326 raw_ostream &OS = Section->getStream();
327
Sam Cleggd6beb322018-05-10 18:10:34 +0000328 writeUleb128(OS, Exports.size(), "export count");
329 for (const WasmExport &Export : Exports)
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000330 writeExport(OS, Export);
Sam Cleggc94d3932017-11-17 18:14:09 +0000331}
332
Sam Cleggd177ab22018-05-04 23:14:42 +0000333void Writer::calculateCustomSections() {
334 log("calculateCustomSections");
335 bool StripDebug = Config->StripDebug || Config->StripAll;
336 for (ObjFile *File : Symtab->ObjectFiles) {
337 for (InputSection *Section : File->CustomSections) {
338 StringRef Name = Section->getName();
339 // These custom sections are known the linker and synthesized rather than
340 // blindly copied
Thomas Lively2a0868f2019-01-17 02:29:41 +0000341 if (Name == "linking" || Name == "name" || Name == "producers" ||
342 Name.startswith("reloc."))
Sam Cleggd177ab22018-05-04 23:14:42 +0000343 continue;
344 // .. or it is a debug section
345 if (StripDebug && Name.startswith(".debug_"))
346 continue;
347 CustomSectionMapping[Name].push_back(Section);
348 }
349 }
350}
351
Sam Clegg80ba4382018-04-10 16:12:49 +0000352void Writer::createCustomSections() {
353 log("createCustomSections");
Sam Clegg80ba4382018-04-10 16:12:49 +0000354 for (auto &Pair : CustomSectionMapping) {
355 StringRef Name = Pair.first();
Sam Cleggd177ab22018-05-04 23:14:42 +0000356
357 auto P = CustomSectionSymbols.find(Name);
358 if (P != CustomSectionSymbols.end()) {
359 uint32_t SectionIndex = OutputSections.size();
360 P->second->setOutputSectionIndex(SectionIndex);
361 }
362
Nicola Zaghene7245b42018-05-15 13:36:20 +0000363 LLVM_DEBUG(dbgs() << "createCustomSection: " << Name << "\n");
Sam Clegg80ba4382018-04-10 16:12:49 +0000364 OutputSections.push_back(make<CustomSection>(Name, Pair.second));
365 }
366}
367
Sam Cleggc94d3932017-11-17 18:14:09 +0000368void Writer::createElemSection() {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000369 if (IndirectFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000370 return;
371
372 SyntheticSection *Section = createSyntheticSection(WASM_SEC_ELEM);
373 raw_ostream &OS = Section->getStream();
374
375 writeUleb128(OS, 1, "segment count");
376 writeUleb128(OS, 0, "table index");
377 WasmInitExpr InitExpr;
Sam Cleggbfb75342018-11-15 00:37:21 +0000378 if (Config->Pic) {
Thomas Lively25ff8932019-01-08 06:25:55 +0000379 InitExpr.Opcode = WASM_OPCODE_GLOBAL_GET;
Sam Clegg2dad4e22018-11-15 18:15:54 +0000380 InitExpr.Value.Global = WasmSym::TableBase->getGlobalIndex();
Sam Cleggbfb75342018-11-15 00:37:21 +0000381 } else {
382 InitExpr.Opcode = WASM_OPCODE_I32_CONST;
383 InitExpr.Value.Int32 = TableBase;
384 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000385 writeInitExpr(OS, InitExpr);
Sam Cleggfc1a9122017-12-11 22:00:56 +0000386 writeUleb128(OS, IndirectFunctions.size(), "elem count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000387
Sam Cleggbfb75342018-11-15 00:37:21 +0000388 uint32_t TableIndex = TableBase;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000389 for (const FunctionSymbol *Sym : IndirectFunctions) {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000390 assert(Sym->getTableIndex() == TableIndex);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000391 writeUleb128(OS, Sym->getFunctionIndex(), "function index");
Sam Cleggfc1a9122017-12-11 22:00:56 +0000392 ++TableIndex;
393 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000394}
395
396void Writer::createCodeSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000397 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000398 return;
399
400 log("createCodeSection");
401
Sam Clegg9f934222018-02-21 18:29:23 +0000402 auto Section = make<CodeSection>(InputFunctions);
Sam Cleggc94d3932017-11-17 18:14:09 +0000403 OutputSections.push_back(Section);
404}
405
406void Writer::createDataSection() {
407 if (!Segments.size())
408 return;
409
410 log("createDataSection");
411 auto Section = make<DataSection>(Segments);
412 OutputSections.push_back(Section);
413}
414
Sam Cleggd451da12017-12-19 19:56:27 +0000415// Create relocations sections in the final output.
Sam Cleggc94d3932017-11-17 18:14:09 +0000416// These are only created when relocatable output is requested.
417void Writer::createRelocSections() {
418 log("createRelocSections");
419 // Don't use iterator here since we are adding to OutputSection
420 size_t OrigSize = OutputSections.size();
Rui Ueyamaffa650a2018-04-24 23:09:57 +0000421 for (size_t I = 0; I < OrigSize; I++) {
422 OutputSection *OSec = OutputSections[I];
Rui Ueyama37254062018-02-28 00:01:31 +0000423 uint32_t Count = OSec->numRelocations();
Sam Cleggc94d3932017-11-17 18:14:09 +0000424 if (!Count)
425 continue;
426
Rui Ueyama37254062018-02-28 00:01:31 +0000427 StringRef Name;
428 if (OSec->Type == WASM_SEC_DATA)
429 Name = "reloc.DATA";
430 else if (OSec->Type == WASM_SEC_CODE)
431 Name = "reloc.CODE";
Sam Cleggd177ab22018-05-04 23:14:42 +0000432 else if (OSec->Type == WASM_SEC_CUSTOM)
433 Name = Saver.save("reloc." + OSec->Name);
Sam Cleggc94d3932017-11-17 18:14:09 +0000434 else
Sam Cleggd177ab22018-05-04 23:14:42 +0000435 llvm_unreachable(
436 "relocations only supported for code, data, or custom sections");
Sam Cleggc94d3932017-11-17 18:14:09 +0000437
Rui Ueyama37254062018-02-28 00:01:31 +0000438 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, Name);
Sam Cleggc94d3932017-11-17 18:14:09 +0000439 raw_ostream &OS = Section->getStream();
Rui Ueyamaffa650a2018-04-24 23:09:57 +0000440 writeUleb128(OS, I, "reloc section");
Sam Cleggc94d3932017-11-17 18:14:09 +0000441 writeUleb128(OS, Count, "reloc count");
Rui Ueyama37254062018-02-28 00:01:31 +0000442 OSec->writeRelocations(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000443 }
444}
445
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000446static uint32_t getWasmFlags(const Symbol *Sym) {
447 uint32_t Flags = 0;
448 if (Sym->isLocal())
449 Flags |= WASM_SYMBOL_BINDING_LOCAL;
450 if (Sym->isWeak())
451 Flags |= WASM_SYMBOL_BINDING_WEAK;
452 if (Sym->isHidden())
453 Flags |= WASM_SYMBOL_VISIBILITY_HIDDEN;
454 if (Sym->isUndefined())
455 Flags |= WASM_SYMBOL_UNDEFINED;
Dan Gohman9b84eea2019-02-07 22:00:48 +0000456 if (auto *F = dyn_cast<UndefinedFunction>(Sym)) {
457 if (F->getName() != F->ImportName)
458 Flags |= WASM_SYMBOL_EXPLICIT_NAME;
459 } else if (auto *G = dyn_cast<UndefinedGlobal>(Sym)) {
460 if (G->getName() != G->ImportName)
461 Flags |= WASM_SYMBOL_EXPLICIT_NAME;
462 }
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000463 return Flags;
464}
465
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000466// Some synthetic sections (e.g. "name" and "linking") have subsections.
467// Just like the synthetic sections themselves these need to be created before
468// they can be written out (since they are preceded by their length). This
469// class is used to create subsections and then write them into the stream
470// of the parent section.
471class SubSection {
472public:
473 explicit SubSection(uint32_t Type) : Type(Type) {}
474
475 void writeTo(raw_ostream &To) {
476 OS.flush();
Rui Ueyama67769102018-02-28 03:38:14 +0000477 writeUleb128(To, Type, "subsection type");
478 writeUleb128(To, Body.size(), "subsection size");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000479 To.write(Body.data(), Body.size());
480 }
481
482private:
483 uint32_t Type;
484 std::string Body;
485
486public:
487 raw_string_ostream OS{Body};
488};
489
Sam Cleggbfb75342018-11-15 00:37:21 +0000490// Create the custom "dylink" section containing information for the dynamic
491// linker.
492// See
493// https://github.com/WebAssembly/tool-conventions/blob/master/DynamicLinking.md
494void Writer::createDylinkSection() {
495 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "dylink");
496 raw_ostream &OS = Section->getStream();
497
498 writeUleb128(OS, MemSize, "MemSize");
Sam Clegg6320efb2019-01-16 01:43:21 +0000499 writeUleb128(OS, MemAlign, "MemAlign");
Sam Cleggbfb75342018-11-15 00:37:21 +0000500 writeUleb128(OS, IndirectFunctions.size(), "TableSize");
501 writeUleb128(OS, 0, "TableAlign");
Sam Clegge01c6462018-12-12 23:44:59 +0000502 writeUleb128(OS, 0, "Needed"); // TODO: Support "needed" shared libraries
Sam Cleggbfb75342018-11-15 00:37:21 +0000503}
504
Sam Clegg49ed9262017-12-01 00:53:21 +0000505// Create the custom "linking" section containing linker metadata.
Sam Cleggc94d3932017-11-17 18:14:09 +0000506// This is only created when relocatable output is requested.
507void Writer::createLinkingSection() {
508 SyntheticSection *Section =
509 createSyntheticSection(WASM_SEC_CUSTOM, "linking");
510 raw_ostream &OS = Section->getStream();
511
Sam Clegg2b8b1792018-04-26 18:17:21 +0000512 writeUleb128(OS, WasmMetadataVersion, "Version");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000513
Sam Clegg93102972018-02-23 05:08:53 +0000514 if (!SymtabEntries.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000515 SubSection Sub(WASM_SYMBOL_TABLE);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000516 writeUleb128(Sub.OS, SymtabEntries.size(), "num symbols");
517
Sam Clegg93102972018-02-23 05:08:53 +0000518 for (const Symbol *Sym : SymtabEntries) {
519 assert(Sym->isDefined() || Sym->isUndefined());
520 WasmSymbolType Kind = Sym->getWasmType();
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000521 uint32_t Flags = getWasmFlags(Sym);
522
Sam Clegg8518e7d2018-03-01 18:06:39 +0000523 writeU8(Sub.OS, Kind, "sym kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000524 writeUleb128(Sub.OS, Flags, "sym flags");
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000525
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000526 if (auto *F = dyn_cast<FunctionSymbol>(Sym)) {
527 writeUleb128(Sub.OS, F->getFunctionIndex(), "index");
Dan Gohman9b84eea2019-02-07 22:00:48 +0000528 if (Sym->isDefined() ||
529 (Flags & WASM_SYMBOL_EXPLICIT_NAME) != 0)
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000530 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000531 } else if (auto *G = dyn_cast<GlobalSymbol>(Sym)) {
532 writeUleb128(Sub.OS, G->getGlobalIndex(), "index");
Dan Gohman9b84eea2019-02-07 22:00:48 +0000533 if (Sym->isDefined() ||
534 (Flags & WASM_SYMBOL_EXPLICIT_NAME) != 0)
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000535 writeStr(Sub.OS, Sym->getName(), "sym name");
Heejin Ahne915a712018-12-08 06:17:43 +0000536 } else if (auto *E = dyn_cast<EventSymbol>(Sym)) {
537 writeUleb128(Sub.OS, E->getEventIndex(), "index");
Dan Gohman9b84eea2019-02-07 22:00:48 +0000538 if (Sym->isDefined() ||
539 (Flags & WASM_SYMBOL_EXPLICIT_NAME) != 0)
Heejin Ahne915a712018-12-08 06:17:43 +0000540 writeStr(Sub.OS, Sym->getName(), "sym name");
Andrea Di Biagio25c1a2f2018-05-05 10:53:31 +0000541 } else if (isa<DataSymbol>(Sym)) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000542 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegg93102972018-02-23 05:08:53 +0000543 if (auto *DataSym = dyn_cast<DefinedData>(Sym)) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000544 writeUleb128(Sub.OS, DataSym->getOutputSegmentIndex(), "index");
545 writeUleb128(Sub.OS, DataSym->getOutputSegmentOffset(),
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000546 "data offset");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000547 writeUleb128(Sub.OS, DataSym->getSize(), "data size");
Sam Clegg93102972018-02-23 05:08:53 +0000548 }
Sam Cleggd177ab22018-05-04 23:14:42 +0000549 } else {
550 auto *S = cast<SectionSymbol>(Sym);
551 writeUleb128(Sub.OS, S->getOutputSectionIndex(), "sym section index");
Sam Clegg93102972018-02-23 05:08:53 +0000552 }
Sam Cleggd3052d52018-01-18 23:40:49 +0000553 }
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000554
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000555 Sub.writeTo(OS);
Sam Cleggd3052d52018-01-18 23:40:49 +0000556 }
557
Sam Clegg0d0dd392017-12-19 17:09:45 +0000558 if (Segments.size()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000559 SubSection Sub(WASM_SEGMENT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000560 writeUleb128(Sub.OS, Segments.size(), "num data segments");
Sam Cleggc94d3932017-11-17 18:14:09 +0000561 for (const OutputSegment *S : Segments) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000562 writeStr(Sub.OS, S->Name, "segment name");
563 writeUleb128(Sub.OS, S->Alignment, "alignment");
564 writeUleb128(Sub.OS, 0, "flags");
Sam Cleggc94d3932017-11-17 18:14:09 +0000565 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000566 Sub.writeTo(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000567 }
Sam Clegg0d0dd392017-12-19 17:09:45 +0000568
Sam Clegg0d0dd392017-12-19 17:09:45 +0000569 if (!InitFunctions.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000570 SubSection Sub(WASM_INIT_FUNCS);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000571 writeUleb128(Sub.OS, InitFunctions.size(), "num init functions");
Sam Clegg93102972018-02-23 05:08:53 +0000572 for (const WasmInitEntry &F : InitFunctions) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000573 writeUleb128(Sub.OS, F.Priority, "priority");
574 writeUleb128(Sub.OS, F.Sym->getOutputSymbolIndex(), "function index");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000575 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000576 Sub.writeTo(OS);
Sam Clegg0d0dd392017-12-19 17:09:45 +0000577 }
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000578
Nicholas Wilsondbd90bf2018-03-07 13:28:16 +0000579 struct ComdatEntry {
580 unsigned Kind;
581 uint32_t Index;
582 };
583 std::map<StringRef, std::vector<ComdatEntry>> Comdats;
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000584
Sam Clegg9f934222018-02-21 18:29:23 +0000585 for (const InputFunction *F : InputFunctions) {
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000586 StringRef Comdat = F->getComdatName();
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000587 if (!Comdat.empty())
588 Comdats[Comdat].emplace_back(
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000589 ComdatEntry{WASM_COMDAT_FUNCTION, F->getFunctionIndex()});
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000590 }
591 for (uint32_t I = 0; I < Segments.size(); ++I) {
Sam Cleggf98bccf2018-01-13 15:57:48 +0000592 const auto &InputSegments = Segments[I]->InputSegments;
593 if (InputSegments.empty())
594 continue;
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000595 StringRef Comdat = InputSegments[0]->getComdatName();
Sam Clegga697df522018-01-13 15:59:53 +0000596#ifndef NDEBUG
Sam Cleggf98bccf2018-01-13 15:57:48 +0000597 for (const InputSegment *IS : InputSegments)
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000598 assert(IS->getComdatName() == Comdat);
Sam Clegga697df522018-01-13 15:59:53 +0000599#endif
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000600 if (!Comdat.empty())
601 Comdats[Comdat].emplace_back(ComdatEntry{WASM_COMDAT_DATA, I});
602 }
603
604 if (!Comdats.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000605 SubSection Sub(WASM_COMDAT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000606 writeUleb128(Sub.OS, Comdats.size(), "num comdats");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000607 for (const auto &C : Comdats) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000608 writeStr(Sub.OS, C.first, "comdat name");
609 writeUleb128(Sub.OS, 0, "comdat flags"); // flags for future use
610 writeUleb128(Sub.OS, C.second.size(), "num entries");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000611 for (const ComdatEntry &Entry : C.second) {
Sam Clegg8518e7d2018-03-01 18:06:39 +0000612 writeU8(Sub.OS, Entry.Kind, "entry kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000613 writeUleb128(Sub.OS, Entry.Index, "entry index");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000614 }
615 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000616 Sub.writeTo(OS);
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000617 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000618}
619
620// Create the custom "name" section containing debug symbol names.
621void Writer::createNameSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000622 unsigned NumNames = NumImportedFunctions;
Sam Clegg9f934222018-02-21 18:29:23 +0000623 for (const InputFunction *F : InputFunctions)
Nicholas Wilson6c7fe302018-04-20 17:09:18 +0000624 if (!F->getName().empty() || !F->getDebugName().empty())
Sam Clegg1963d712018-01-17 20:19:04 +0000625 ++NumNames;
Sam Cleggc94d3932017-11-17 18:14:09 +0000626
Sam Clegg1963d712018-01-17 20:19:04 +0000627 if (NumNames == 0)
628 return;
Sam Clegg50686852018-01-12 18:35:13 +0000629
Sam Cleggc94d3932017-11-17 18:14:09 +0000630 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "name");
631
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000632 SubSection Sub(WASM_NAMES_FUNCTION);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000633 writeUleb128(Sub.OS, NumNames, "name count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000634
Sam Clegg93102972018-02-23 05:08:53 +0000635 // Names must appear in function index order. As it happens ImportedSymbols
636 // and InputFunctions are numbered in order with imported functions coming
Sam Clegg1963d712018-01-17 20:19:04 +0000637 // first.
Sam Clegg93102972018-02-23 05:08:53 +0000638 for (const Symbol *S : ImportedSymbols) {
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000639 if (auto *F = dyn_cast<FunctionSymbol>(S)) {
640 writeUleb128(Sub.OS, F->getFunctionIndex(), "func index");
Sam Clegg37125f02018-11-09 16:57:41 +0000641 writeStr(Sub.OS, toString(*S), "symbol name");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000642 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000643 }
Sam Clegg9f934222018-02-21 18:29:23 +0000644 for (const InputFunction *F : InputFunctions) {
Sam Clegg1963d712018-01-17 20:19:04 +0000645 if (!F->getName().empty()) {
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000646 writeUleb128(Sub.OS, F->getFunctionIndex(), "func index");
Nicholas Wilson6c7fe302018-04-20 17:09:18 +0000647 if (!F->getDebugName().empty()) {
648 writeStr(Sub.OS, F->getDebugName(), "symbol name");
649 } else {
Sam Clegg37125f02018-11-09 16:57:41 +0000650 writeStr(Sub.OS, maybeDemangleSymbol(F->getName()), "symbol name");
Nicholas Wilson6c7fe302018-04-20 17:09:18 +0000651 }
Sam Clegg1963d712018-01-17 20:19:04 +0000652 }
653 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000654
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000655 Sub.writeTo(Section->getStream());
Sam Cleggc94d3932017-11-17 18:14:09 +0000656}
657
Thomas Lively2a0868f2019-01-17 02:29:41 +0000658void Writer::createProducersSection() {
659 SmallVector<std::pair<std::string, std::string>, 8> Languages;
660 SmallVector<std::pair<std::string, std::string>, 8> Tools;
661 SmallVector<std::pair<std::string, std::string>, 8> SDKs;
662 for (ObjFile *File : Symtab->ObjectFiles) {
663 const WasmProducerInfo &Info = File->getWasmObj()->getProducerInfo();
664 for (auto &Producers : {std::make_pair(&Info.Languages, &Languages),
665 std::make_pair(&Info.Tools, &Tools),
666 std::make_pair(&Info.SDKs, &SDKs)})
667 for (auto &Producer : *Producers.first)
668 if (Producers.second->end() ==
669 std::find_if(Producers.second->begin(), Producers.second->end(),
670 [&](std::pair<std::string, std::string> Seen) {
671 return Seen.first == Producer.first;
672 }))
673 Producers.second->push_back(Producer);
674 }
675 int FieldCount =
676 int(!Languages.empty()) + int(!Tools.empty()) + int(!SDKs.empty());
677 if (FieldCount == 0)
678 return;
679 SyntheticSection *Section =
680 createSyntheticSection(WASM_SEC_CUSTOM, "producers");
681 auto &OS = Section->getStream();
682 writeUleb128(OS, FieldCount, "field count");
683 for (auto &Field :
684 {std::make_pair("language", Languages),
685 std::make_pair("processed-by", Tools), std::make_pair("sdk", SDKs)}) {
686 if (Field.second.empty())
687 continue;
688 writeStr(OS, Field.first, "field name");
689 writeUleb128(OS, Field.second.size(), "number of entries");
690 for (auto &Entry : Field.second) {
691 writeStr(OS, Entry.first, "producer name");
692 writeStr(OS, Entry.second, "producer version");
693 }
694 }
695}
696
Sam Cleggc94d3932017-11-17 18:14:09 +0000697void Writer::writeHeader() {
698 memcpy(Buffer->getBufferStart(), Header.data(), Header.size());
699}
700
701void Writer::writeSections() {
702 uint8_t *Buf = Buffer->getBufferStart();
703 parallelForEach(OutputSections, [Buf](OutputSection *S) { S->writeTo(Buf); });
704}
705
706// Fix the memory layout of the output binary. This assigns memory offsets
Sam Clegg49ed9262017-12-01 00:53:21 +0000707// to each of the input data sections as well as the explicit stack region.
Sam Clegga0f095e2018-05-03 17:21:53 +0000708// The default memory layout is as follows, from low to high.
709//
Sam Cleggf0d433d2018-02-02 22:59:56 +0000710// - initialized data (starting at Config->GlobalBase)
711// - BSS data (not currently implemented in llvm)
712// - explicit stack (Config->ZStackSize)
713// - heap start / unallocated
Sam Clegga0f095e2018-05-03 17:21:53 +0000714//
715// The --stack-first option means that stack is placed before any static data.
Heejin Ahn4821ebf2018-08-29 21:03:16 +0000716// This can be useful since it means that stack overflow traps immediately
717// rather than overwriting global data, but also increases code size since all
718// static data loads and stores requires larger offsets.
Sam Cleggc94d3932017-11-17 18:14:09 +0000719void Writer::layoutMemory() {
Sam Cleggc94d3932017-11-17 18:14:09 +0000720 createOutputSegments();
721
Sam Clegga0f095e2018-05-03 17:21:53 +0000722 uint32_t MemoryPtr = 0;
723
724 auto PlaceStack = [&]() {
Sam Cleggbfb75342018-11-15 00:37:21 +0000725 if (Config->Relocatable || Config->Shared)
Sam Clegga0f095e2018-05-03 17:21:53 +0000726 return;
Heejin Ahna1cc4ea2019-02-04 19:13:46 +0000727 MemoryPtr = alignTo(MemoryPtr, StackAlignment);
728 if (Config->ZStackSize != alignTo(Config->ZStackSize, StackAlignment))
729 error("stack size must be " + Twine(StackAlignment) + "-byte aligned");
Sam Clegga0f095e2018-05-03 17:21:53 +0000730 log("mem: stack size = " + Twine(Config->ZStackSize));
731 log("mem: stack base = " + Twine(MemoryPtr));
732 MemoryPtr += Config->ZStackSize;
Sam Clegg2dad4e22018-11-15 18:15:54 +0000733 auto *SP = cast<DefinedGlobal>(WasmSym::StackPointer);
734 SP->Global->Global.InitExpr.Value.Int32 = MemoryPtr;
Sam Clegga0f095e2018-05-03 17:21:53 +0000735 log("mem: stack top = " + Twine(MemoryPtr));
736 };
737
738 if (Config->StackFirst) {
739 PlaceStack();
740 } else {
741 MemoryPtr = Config->GlobalBase;
742 log("mem: global base = " + Twine(Config->GlobalBase));
743 }
744
745 uint32_t DataStart = MemoryPtr;
746
Sam Cleggf0d433d2018-02-02 22:59:56 +0000747 // Arbitrarily set __dso_handle handle to point to the start of the data
748 // segments.
749 if (WasmSym::DsoHandle)
Sam Clegga0f095e2018-05-03 17:21:53 +0000750 WasmSym::DsoHandle->setVirtualAddress(DataStart);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000751
Sam Cleggbfb75342018-11-15 00:37:21 +0000752 MemAlign = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000753 for (OutputSegment *Seg : Segments) {
Sam Cleggbfb75342018-11-15 00:37:21 +0000754 MemAlign = std::max(MemAlign, Seg->Alignment);
Sam Clegg622ad042019-01-17 22:09:09 +0000755 MemoryPtr = alignTo(MemoryPtr, 1ULL << Seg->Alignment);
Sam Cleggc94d3932017-11-17 18:14:09 +0000756 Seg->StartVA = MemoryPtr;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000757 log(formatv("mem: {0,-15} offset={1,-8} size={2,-8} align={3}", Seg->Name,
758 MemoryPtr, Seg->Size, Seg->Alignment));
Sam Cleggc94d3932017-11-17 18:14:09 +0000759 MemoryPtr += Seg->Size;
760 }
761
Sam Cleggf0d433d2018-02-02 22:59:56 +0000762 // TODO: Add .bss space here.
Sam Clegg37a4a8a2018-02-07 03:04:53 +0000763 if (WasmSym::DataEnd)
764 WasmSym::DataEnd->setVirtualAddress(MemoryPtr);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000765
Sam Clegga0f095e2018-05-03 17:21:53 +0000766 log("mem: static data = " + Twine(MemoryPtr - DataStart));
Sam Cleggc94d3932017-11-17 18:14:09 +0000767
Sam Clegg2dad4e22018-11-15 18:15:54 +0000768 if (Config->Shared) {
769 MemSize = MemoryPtr;
770 return;
771 }
772
Sam Clegga0f095e2018-05-03 17:21:53 +0000773 if (!Config->StackFirst)
774 PlaceStack();
775
776 // Set `__heap_base` to directly follow the end of the stack or global data.
777 // The fact that this comes last means that a malloc/brk implementation
778 // can grow the heap at runtime.
Sam Cleggc94d3932017-11-17 18:14:09 +0000779 if (!Config->Relocatable) {
Sam Cleggf0d433d2018-02-02 22:59:56 +0000780 WasmSym::HeapBase->setVirtualAddress(MemoryPtr);
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000781 log("mem: heap base = " + Twine(MemoryPtr));
Sam Cleggc94d3932017-11-17 18:14:09 +0000782 }
783
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000784 if (Config->InitialMemory != 0) {
785 if (Config->InitialMemory != alignTo(Config->InitialMemory, WasmPageSize))
786 error("initial memory must be " + Twine(WasmPageSize) + "-byte aligned");
787 if (MemoryPtr > Config->InitialMemory)
788 error("initial memory too small, " + Twine(MemoryPtr) + " bytes needed");
789 else
790 MemoryPtr = Config->InitialMemory;
791 }
Sam Cleggbfb75342018-11-15 00:37:21 +0000792 MemSize = MemoryPtr;
793 NumMemoryPages = alignTo(MemoryPtr, WasmPageSize) / WasmPageSize;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000794 log("mem: total pages = " + Twine(NumMemoryPages));
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000795
796 if (Config->MaxMemory != 0) {
797 if (Config->MaxMemory != alignTo(Config->MaxMemory, WasmPageSize))
798 error("maximum memory must be " + Twine(WasmPageSize) + "-byte aligned");
799 if (MemoryPtr > Config->MaxMemory)
800 error("maximum memory too small, " + Twine(MemoryPtr) + " bytes needed");
801 MaxMemoryPages = Config->MaxMemory / WasmPageSize;
802 log("mem: max pages = " + Twine(MaxMemoryPages));
803 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000804}
805
806SyntheticSection *Writer::createSyntheticSection(uint32_t Type,
Sam Cleggc375e4e2018-01-10 19:18:22 +0000807 StringRef Name) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000808 auto Sec = make<SyntheticSection>(Type, Name);
Sam Cleggab2ac292017-12-20 05:14:48 +0000809 log("createSection: " + toString(*Sec));
Sam Cleggc94d3932017-11-17 18:14:09 +0000810 OutputSections.push_back(Sec);
811 return Sec;
812}
813
814void Writer::createSections() {
815 // Known sections
Sam Cleggbfb75342018-11-15 00:37:21 +0000816 if (Config->Pic)
817 createDylinkSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000818 createTypeSection();
819 createImportSection();
820 createFunctionSection();
821 createTableSection();
822 createMemorySection();
823 createGlobalSection();
Heejin Ahne915a712018-12-08 06:17:43 +0000824 createEventSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000825 createExportSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000826 createElemSection();
827 createCodeSection();
828 createDataSection();
Sam Clegg80ba4382018-04-10 16:12:49 +0000829 createCustomSections();
Sam Cleggc94d3932017-11-17 18:14:09 +0000830
831 // Custom sections
Sam Clegg99eb42c2018-02-27 23:58:03 +0000832 if (Config->Relocatable) {
Sam Clegg99eb42c2018-02-27 23:58:03 +0000833 createLinkingSection();
Nicholas Wilson94d3b162018-03-05 12:33:58 +0000834 createRelocSections();
Sam Clegg99eb42c2018-02-27 23:58:03 +0000835 }
Thomas Lively2a0868f2019-01-17 02:29:41 +0000836
Sam Cleggc94d3932017-11-17 18:14:09 +0000837 if (!Config->StripDebug && !Config->StripAll)
838 createNameSection();
839
Thomas Lively2a0868f2019-01-17 02:29:41 +0000840 if (!Config->StripAll)
841 createProducersSection();
842
Sam Cleggc94d3932017-11-17 18:14:09 +0000843 for (OutputSection *S : OutputSections) {
844 S->setOffset(FileSize);
845 S->finalizeContents();
846 FileSize += S->getSize();
847 }
848}
849
Sam Cleggc94d3932017-11-17 18:14:09 +0000850void Writer::calculateImports() {
Sam Clegg574d7ce2017-12-15 19:23:49 +0000851 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000852 if (!Sym->isUndefined())
853 continue;
854 if (isa<DataSymbol>(Sym))
855 continue;
856 if (Sym->isWeak() && !Config->Relocatable)
Sam Clegg574d7ce2017-12-15 19:23:49 +0000857 continue;
Nicholas Wilsona1e299f2018-04-20 17:18:06 +0000858 if (!Sym->isLive())
859 continue;
Sam Cleggc729c1b2018-05-30 18:07:52 +0000860 if (!Sym->IsUsedInRegularObj)
861 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000862
Nicola Zaghene7245b42018-05-15 13:36:20 +0000863 LLVM_DEBUG(dbgs() << "import: " << Sym->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000864 ImportedSymbols.emplace_back(Sym);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000865 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
866 F->setFunctionIndex(NumImportedFunctions++);
Heejin Ahne915a712018-12-08 06:17:43 +0000867 else if (auto *G = dyn_cast<GlobalSymbol>(Sym))
868 G->setGlobalIndex(NumImportedGlobals++);
Sam Clegg93102972018-02-23 05:08:53 +0000869 else
Heejin Ahne915a712018-12-08 06:17:43 +0000870 cast<EventSymbol>(Sym)->setEventIndex(NumImportedEvents++);
Sam Cleggc94d3932017-11-17 18:14:09 +0000871 }
872}
873
Sam Cleggd3052d52018-01-18 23:40:49 +0000874void Writer::calculateExports() {
Sam Clegg93102972018-02-23 05:08:53 +0000875 if (Config->Relocatable)
876 return;
Sam Cleggf0d433d2018-02-02 22:59:56 +0000877
Sam Cleggd6beb322018-05-10 18:10:34 +0000878 if (!Config->Relocatable && !Config->ImportMemory)
879 Exports.push_back(WasmExport{"memory", WASM_EXTERNAL_MEMORY, 0});
880
881 if (!Config->Relocatable && Config->ExportTable)
Heejin Ahna1cc4ea2019-02-04 19:13:46 +0000882 Exports.push_back(WasmExport{FunctionTableName, WASM_EXTERNAL_TABLE, 0});
Sam Cleggd6beb322018-05-10 18:10:34 +0000883
884 unsigned FakeGlobalIndex = NumImportedGlobals + InputGlobals.size();
885
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000886 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Cleggce004bf2018-06-28 17:04:58 +0000887 if (!Sym->isExported())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000888 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000889 if (!Sym->isLive())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000890 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000891
Sam Cleggd6beb322018-05-10 18:10:34 +0000892 StringRef Name = Sym->getName();
893 WasmExport Export;
894 if (auto *F = dyn_cast<DefinedFunction>(Sym)) {
895 Export = {Name, WASM_EXTERNAL_FUNCTION, F->getFunctionIndex()};
896 } else if (auto *G = dyn_cast<DefinedGlobal>(Sym)) {
Sam Clegg177b4582018-06-07 01:27:07 +0000897 // TODO(sbc): Remove this check once to mutable global proposal is
898 // implement in all major browsers.
899 // See: https://github.com/WebAssembly/mutable-global
900 if (G->getGlobalType()->Mutable) {
901 // Only the __stack_pointer should ever be create as mutable.
902 assert(G == WasmSym::StackPointer);
903 continue;
904 }
Sam Cleggd6beb322018-05-10 18:10:34 +0000905 Export = {Name, WASM_EXTERNAL_GLOBAL, G->getGlobalIndex()};
Heejin Ahne915a712018-12-08 06:17:43 +0000906 } else if (auto *E = dyn_cast<DefinedEvent>(Sym)) {
907 Export = {Name, WASM_EXTERNAL_EVENT, E->getEventIndex()};
Sam Cleggd6beb322018-05-10 18:10:34 +0000908 } else {
909 auto *D = cast<DefinedData>(Sym);
Sam Clegg93102972018-02-23 05:08:53 +0000910 DefinedFakeGlobals.emplace_back(D);
Sam Cleggd6beb322018-05-10 18:10:34 +0000911 Export = {Name, WASM_EXTERNAL_GLOBAL, FakeGlobalIndex++};
912 }
913
Nicola Zaghene7245b42018-05-15 13:36:20 +0000914 LLVM_DEBUG(dbgs() << "Export: " << Name << "\n");
Sam Cleggd6beb322018-05-10 18:10:34 +0000915 Exports.push_back(Export);
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000916 }
Sam Clegg93102972018-02-23 05:08:53 +0000917}
918
919void Writer::assignSymtab() {
920 if (!Config->Relocatable)
921 return;
922
Sam Cleggd177ab22018-05-04 23:14:42 +0000923 StringMap<uint32_t> SectionSymbolIndices;
924
Sam Clegg93102972018-02-23 05:08:53 +0000925 unsigned SymbolIndex = SymtabEntries.size();
Sam Cleggd177ab22018-05-04 23:14:42 +0000926
Sam Clegg89e4dcb2019-01-30 18:55:15 +0000927 auto AddSymbol = [&](Symbol *Sym) {
928 if (auto *S = dyn_cast<SectionSymbol>(Sym)) {
929 StringRef Name = S->getName();
930 if (CustomSectionMapping.count(Name) == 0)
931 return;
Sam Cleggd177ab22018-05-04 23:14:42 +0000932
Sam Clegg89e4dcb2019-01-30 18:55:15 +0000933 auto SSI = SectionSymbolIndices.find(Name);
934 if (SSI != SectionSymbolIndices.end()) {
935 Sym->setOutputSymbolIndex(SSI->second);
936 return;
Sam Cleggd177ab22018-05-04 23:14:42 +0000937 }
938
Sam Clegg89e4dcb2019-01-30 18:55:15 +0000939 SectionSymbolIndices[Name] = SymbolIndex;
940 CustomSectionSymbols[Name] = cast<SectionSymbol>(Sym);
Sam Cleggd3052d52018-01-18 23:40:49 +0000941
Sam Clegg89e4dcb2019-01-30 18:55:15 +0000942 Sym->markLive();
943 }
944
945 // (Since this is relocatable output, GC is not performed so symbols must
946 // be live.)
947 assert(Sym->isLive());
948 Sym->setOutputSymbolIndex(SymbolIndex++);
949 SymtabEntries.emplace_back(Sym);
950 };
951
952 for (Symbol *Sym : Symtab->getSymbols())
953 if (!Sym->isLazy())
954 AddSymbol(Sym);
955
956 for (ObjFile *File : Symtab->ObjectFiles) {
957 LLVM_DEBUG(dbgs() << "Local symtab entries: " << File->getName() << "\n");
958 for (Symbol *Sym : File->getSymbols())
959 if (Sym->isLocal())
960 AddSymbol(Sym);
961 }
Sam Cleggd3052d52018-01-18 23:40:49 +0000962}
963
Sam Cleggc375e4e2018-01-10 19:18:22 +0000964uint32_t Writer::lookupType(const WasmSignature &Sig) {
Sam Clegg8d027d62018-01-10 20:12:26 +0000965 auto It = TypeIndices.find(Sig);
966 if (It == TypeIndices.end()) {
Sam Cleggc375e4e2018-01-10 19:18:22 +0000967 error("type not found: " + toString(Sig));
Sam Clegg8d027d62018-01-10 20:12:26 +0000968 return 0;
969 }
970 return It->second;
Sam Cleggc375e4e2018-01-10 19:18:22 +0000971}
972
973uint32_t Writer::registerType(const WasmSignature &Sig) {
Sam Cleggb8621592017-11-30 01:40:08 +0000974 auto Pair = TypeIndices.insert(std::make_pair(Sig, Types.size()));
Sam Cleggc375e4e2018-01-10 19:18:22 +0000975 if (Pair.second) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000976 LLVM_DEBUG(dbgs() << "type " << toString(Sig) << "\n");
Sam Cleggb8621592017-11-30 01:40:08 +0000977 Types.push_back(&Sig);
Sam Cleggc375e4e2018-01-10 19:18:22 +0000978 }
Sam Cleggb8621592017-11-30 01:40:08 +0000979 return Pair.first->second;
980}
981
Sam Cleggc94d3932017-11-17 18:14:09 +0000982void Writer::calculateTypes() {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000983 // The output type section is the union of the following sets:
984 // 1. Any signature used in the TYPE relocation
985 // 2. The signatures of all imported functions
986 // 3. The signatures of all defined functions
Heejin Ahne915a712018-12-08 06:17:43 +0000987 // 4. The signatures of all imported events
988 // 5. The signatures of all defined events
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000989
Sam Cleggc94d3932017-11-17 18:14:09 +0000990 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000991 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
992 for (uint32_t I = 0; I < Types.size(); I++)
993 if (File->TypeIsUsed[I])
994 File->TypeMap[I] = registerType(Types[I]);
Sam Cleggc94d3932017-11-17 18:14:09 +0000995 }
Sam Clegg50686852018-01-12 18:35:13 +0000996
Heejin Ahne915a712018-12-08 06:17:43 +0000997 for (const Symbol *Sym : ImportedSymbols) {
Sam Clegg93102972018-02-23 05:08:53 +0000998 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
Heejin Ahne915a712018-12-08 06:17:43 +0000999 registerType(*F->Signature);
1000 else if (auto *E = dyn_cast<EventSymbol>(Sym))
1001 registerType(*E->Signature);
1002 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +00001003
Sam Clegg9f934222018-02-21 18:29:23 +00001004 for (const InputFunction *F : InputFunctions)
Sam Clegg8f6d2de2018-01-31 23:48:14 +00001005 registerType(F->Signature);
Heejin Ahne915a712018-12-08 06:17:43 +00001006
1007 for (const InputEvent *E : InputEvents)
1008 registerType(E->Signature);
Sam Cleggc94d3932017-11-17 18:14:09 +00001009}
1010
Sam Clegg8d146bb2018-01-09 23:56:44 +00001011void Writer::assignIndexes() {
Heejin Ahnaeaab992018-11-19 23:21:25 +00001012 assert(InputFunctions.empty());
1013 uint32_t FunctionIndex = NumImportedFunctions;
Nicholas Wilsonebda41f2018-03-09 16:43:05 +00001014 auto AddDefinedFunction = [&](InputFunction *Func) {
1015 if (!Func->Live)
1016 return;
1017 InputFunctions.emplace_back(Func);
Sam Clegge3f3ccf2018-03-12 19:56:23 +00001018 Func->setFunctionIndex(FunctionIndex++);
Nicholas Wilsonebda41f2018-03-09 16:43:05 +00001019 };
1020
Nicholas Wilson5639da82018-03-12 15:44:07 +00001021 for (InputFunction *Func : Symtab->SyntheticFunctions)
1022 AddDefinedFunction(Func);
1023
Sam Clegg87e61922018-01-08 23:39:11 +00001024 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001025 LLVM_DEBUG(dbgs() << "Functions: " << File->getName() << "\n");
Nicholas Wilsonebda41f2018-03-09 16:43:05 +00001026 for (InputFunction *Func : File->Functions)
1027 AddDefinedFunction(Func);
Sam Clegg8d146bb2018-01-09 23:56:44 +00001028 }
1029
Sam Cleggbfb75342018-11-15 00:37:21 +00001030 uint32_t TableIndex = TableBase;
Sam Clegg6c4dbfee2018-02-23 04:59:57 +00001031 auto HandleRelocs = [&](InputChunk *Chunk) {
1032 if (!Chunk->Live)
1033 return;
1034 ObjFile *File = Chunk->File;
1035 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
Sam Clegg93102972018-02-23 05:08:53 +00001036 for (const WasmRelocation &Reloc : Chunk->getRelocations()) {
Sam Clegg79e33172019-02-04 17:49:33 +00001037 if (Reloc.Type == R_WASM_TABLE_INDEX_I32 ||
1038 Reloc.Type == R_WASM_TABLE_INDEX_SLEB) {
Sam Clegg6c4dbfee2018-02-23 04:59:57 +00001039 FunctionSymbol *Sym = File->getFunctionSymbol(Reloc.Index);
Sam Clegge3f3ccf2018-03-12 19:56:23 +00001040 if (Sym->hasTableIndex() || !Sym->hasFunctionIndex())
Sam Clegg6c4dbfee2018-02-23 04:59:57 +00001041 continue;
1042 Sym->setTableIndex(TableIndex++);
1043 IndirectFunctions.emplace_back(Sym);
Sam Clegg79e33172019-02-04 17:49:33 +00001044 } else if (Reloc.Type == R_WASM_TYPE_INDEX_LEB) {
Sam Clegg93102972018-02-23 05:08:53 +00001045 // Mark target type as live
Sam Clegg6c4dbfee2018-02-23 04:59:57 +00001046 File->TypeMap[Reloc.Index] = registerType(Types[Reloc.Index]);
1047 File->TypeIsUsed[Reloc.Index] = true;
1048 }
1049 }
1050 };
1051
Sam Clegg8d146bb2018-01-09 23:56:44 +00001052 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001053 LLVM_DEBUG(dbgs() << "Handle relocs: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +00001054 for (InputChunk *Chunk : File->Functions)
1055 HandleRelocs(Chunk);
1056 for (InputChunk *Chunk : File->Segments)
1057 HandleRelocs(Chunk);
Sam Cleggd177ab22018-05-04 23:14:42 +00001058 for (auto &P : File->CustomSections)
1059 HandleRelocs(P);
Sam Clegg93102972018-02-23 05:08:53 +00001060 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +00001061
Heejin Ahnaeaab992018-11-19 23:21:25 +00001062 assert(InputGlobals.empty());
1063 uint32_t GlobalIndex = NumImportedGlobals;
Sam Clegg93102972018-02-23 05:08:53 +00001064 auto AddDefinedGlobal = [&](InputGlobal *Global) {
1065 if (Global->Live) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001066 LLVM_DEBUG(dbgs() << "AddDefinedGlobal: " << GlobalIndex << "\n");
Sam Clegge3f3ccf2018-03-12 19:56:23 +00001067 Global->setGlobalIndex(GlobalIndex++);
Sam Clegg93102972018-02-23 05:08:53 +00001068 InputGlobals.push_back(Global);
1069 }
1070 };
1071
Nicholas Wilsonebda41f2018-03-09 16:43:05 +00001072 for (InputGlobal *Global : Symtab->SyntheticGlobals)
1073 AddDefinedGlobal(Global);
Sam Clegg93102972018-02-23 05:08:53 +00001074
1075 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001076 LLVM_DEBUG(dbgs() << "Globals: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +00001077 for (InputGlobal *Global : File->Globals)
1078 AddDefinedGlobal(Global);
Sam Cleggc94d3932017-11-17 18:14:09 +00001079 }
Heejin Ahne915a712018-12-08 06:17:43 +00001080
1081 assert(InputEvents.empty());
1082 uint32_t EventIndex = NumImportedEvents;
1083 auto AddDefinedEvent = [&](InputEvent *Event) {
1084 if (Event->Live) {
1085 LLVM_DEBUG(dbgs() << "AddDefinedEvent: " << EventIndex << "\n");
1086 Event->setEventIndex(EventIndex++);
1087 InputEvents.push_back(Event);
1088 }
1089 };
1090
1091 for (ObjFile *File : Symtab->ObjectFiles) {
1092 LLVM_DEBUG(dbgs() << "Events: " << File->getName() << "\n");
1093 for (InputEvent *Event : File->Events)
1094 AddDefinedEvent(Event);
1095 }
Sam Cleggc94d3932017-11-17 18:14:09 +00001096}
1097
1098static StringRef getOutputDataSegmentName(StringRef Name) {
Sam Cleggbfb75342018-11-15 00:37:21 +00001099 // With PIC code we currently only support a single data segment since
1100 // we only have a single __memory_base to use as our base address.
1101 if (Config->Pic)
1102 return "data";
Sam Clegg66844762018-05-10 18:23:51 +00001103 if (!Config->MergeDataSegments)
Sam Cleggc94d3932017-11-17 18:14:09 +00001104 return Name;
Rui Ueyama4764b572018-02-28 00:57:28 +00001105 if (Name.startswith(".text."))
1106 return ".text";
1107 if (Name.startswith(".data."))
1108 return ".data";
1109 if (Name.startswith(".bss."))
1110 return ".bss";
Sam Clegg57694c52018-08-08 18:02:55 +00001111 if (Name.startswith(".rodata."))
1112 return ".rodata";
Sam Cleggc94d3932017-11-17 18:14:09 +00001113 return Name;
1114}
1115
1116void Writer::createOutputSegments() {
1117 for (ObjFile *File : Symtab->ObjectFiles) {
1118 for (InputSegment *Segment : File->Segments) {
Sam Clegg447ae402018-02-13 20:29:38 +00001119 if (!Segment->Live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +00001120 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +00001121 StringRef Name = getOutputDataSegmentName(Segment->getName());
1122 OutputSegment *&S = SegmentMap[Name];
1123 if (S == nullptr) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001124 LLVM_DEBUG(dbgs() << "new segment: " << Name << "\n");
Sam Clegg93102972018-02-23 05:08:53 +00001125 S = make<OutputSegment>(Name, Segments.size());
Sam Cleggc94d3932017-11-17 18:14:09 +00001126 Segments.push_back(S);
1127 }
1128 S->addInputSegment(Segment);
Nicola Zaghene7245b42018-05-15 13:36:20 +00001129 LLVM_DEBUG(dbgs() << "added data: " << Name << ": " << S->Size << "\n");
Sam Cleggc94d3932017-11-17 18:14:09 +00001130 }
1131 }
1132}
1133
Sam Clegg50686852018-01-12 18:35:13 +00001134static const int OPCODE_CALL = 0x10;
1135static const int OPCODE_END = 0xb;
1136
1137// Create synthetic "__wasm_call_ctors" function based on ctor functions
1138// in input object.
1139void Writer::createCtorFunction() {
Sam Clegg0e6b42f2019-03-01 22:35:47 +00001140 if (!WasmSym::CallCtors->isLive())
1141 return;
1142
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +00001143 // First write the body's contents to a string.
1144 std::string BodyContent;
Sam Clegg50686852018-01-12 18:35:13 +00001145 {
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +00001146 raw_string_ostream OS(BodyContent);
Sam Clegg50686852018-01-12 18:35:13 +00001147 writeUleb128(OS, 0, "num locals");
Sam Clegg93102972018-02-23 05:08:53 +00001148 for (const WasmInitEntry &F : InitFunctions) {
Sam Clegg50686852018-01-12 18:35:13 +00001149 writeU8(OS, OPCODE_CALL, "CALL");
Sam Clegge3f3ccf2018-03-12 19:56:23 +00001150 writeUleb128(OS, F.Sym->getFunctionIndex(), "function index");
Sam Clegg50686852018-01-12 18:35:13 +00001151 }
1152 writeU8(OS, OPCODE_END, "END");
1153 }
1154
1155 // Once we know the size of the body we can create the final function body
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +00001156 std::string FunctionBody;
1157 {
1158 raw_string_ostream OS(FunctionBody);
1159 writeUleb128(OS, BodyContent.size(), "function size");
1160 OS << BodyContent;
1161 }
Rui Ueyama29abfe42018-02-28 17:43:15 +00001162
Sam Cleggea656472018-10-22 08:35:39 +00001163 ArrayRef<uint8_t> Body = arrayRefFromStringRef(Saver.save(FunctionBody));
Nicholas Wilsonebda41f2018-03-09 16:43:05 +00001164 cast<SyntheticFunction>(WasmSym::CallCtors->Function)->setBody(Body);
Sam Clegg50686852018-01-12 18:35:13 +00001165}
1166
1167// Populate InitFunctions vector with init functions from all input objects.
1168// This is then used either when creating the output linking section or to
1169// synthesize the "__wasm_call_ctors" function.
1170void Writer::calculateInitFunctions() {
Sam Clegg61f13b32019-03-02 04:55:02 +00001171 if (!Config->Relocatable && !WasmSym::CallCtors->isLive())
1172 return;
1173
Sam Clegg50686852018-01-12 18:35:13 +00001174 for (ObjFile *File : Symtab->ObjectFiles) {
1175 const WasmLinkingData &L = File->getWasmObj()->linkingData();
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +00001176 for (const WasmInitFunc &F : L.InitFunctions) {
1177 FunctionSymbol *Sym = File->getFunctionSymbol(F.Symbol);
Sam Clegg0e6b42f2019-03-01 22:35:47 +00001178 assert(Sym->isLive());
Heejin Ahne915a712018-12-08 06:17:43 +00001179 if (*Sym->Signature != WasmSignature{{}, {}})
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +00001180 error("invalid signature for init func: " + toString(*Sym));
1181 InitFunctions.emplace_back(WasmInitEntry{Sym, F.Priority});
1182 }
Sam Clegg50686852018-01-12 18:35:13 +00001183 }
Rui Ueyamada69b712018-02-28 00:15:59 +00001184
Sam Clegg50686852018-01-12 18:35:13 +00001185 // Sort in order of priority (lowest first) so that they are called
1186 // in the correct order.
Sam Clegg29b8feb2018-02-21 00:34:34 +00001187 std::stable_sort(InitFunctions.begin(), InitFunctions.end(),
Sam Clegg93102972018-02-23 05:08:53 +00001188 [](const WasmInitEntry &L, const WasmInitEntry &R) {
Sam Clegg29b8feb2018-02-21 00:34:34 +00001189 return L.Priority < R.Priority;
1190 });
Sam Clegg50686852018-01-12 18:35:13 +00001191}
1192
Sam Cleggc94d3932017-11-17 18:14:09 +00001193void Writer::run() {
Sam Cleggbfb75342018-11-15 00:37:21 +00001194 if (Config->Relocatable || Config->Pic)
Sam Clegg99eb42c2018-02-27 23:58:03 +00001195 Config->GlobalBase = 0;
1196
Sam Cleggbfb75342018-11-15 00:37:21 +00001197 // For PIC code the table base is assigned dynamically by the loader.
1198 // For non-PIC, we start at 1 so that accessing table index 0 always traps.
1199 if (!Config->Pic)
1200 TableBase = 1;
1201
Sam Cleggc94d3932017-11-17 18:14:09 +00001202 log("-- calculateImports");
1203 calculateImports();
Sam Clegg8d146bb2018-01-09 23:56:44 +00001204 log("-- assignIndexes");
1205 assignIndexes();
Sam Clegg50686852018-01-12 18:35:13 +00001206 log("-- calculateInitFunctions");
1207 calculateInitFunctions();
1208 if (!Config->Relocatable)
1209 createCtorFunction();
Sam Clegg8f6d2de2018-01-31 23:48:14 +00001210 log("-- calculateTypes");
1211 calculateTypes();
Sam Clegg93102972018-02-23 05:08:53 +00001212 log("-- layoutMemory");
1213 layoutMemory();
1214 log("-- calculateExports");
1215 calculateExports();
Sam Cleggd177ab22018-05-04 23:14:42 +00001216 log("-- calculateCustomSections");
1217 calculateCustomSections();
Sam Clegg93102972018-02-23 05:08:53 +00001218 log("-- assignSymtab");
1219 assignSymtab();
Sam Cleggc94d3932017-11-17 18:14:09 +00001220
1221 if (errorHandler().Verbose) {
Sam Clegg9f934222018-02-21 18:29:23 +00001222 log("Defined Functions: " + Twine(InputFunctions.size()));
Sam Clegg93102972018-02-23 05:08:53 +00001223 log("Defined Globals : " + Twine(InputGlobals.size()));
Heejin Ahne915a712018-12-08 06:17:43 +00001224 log("Defined Events : " + Twine(InputEvents.size()));
Sam Clegg93102972018-02-23 05:08:53 +00001225 log("Function Imports : " + Twine(NumImportedFunctions));
1226 log("Global Imports : " + Twine(NumImportedGlobals));
Heejin Ahne915a712018-12-08 06:17:43 +00001227 log("Event Imports : " + Twine(NumImportedEvents));
Sam Cleggc94d3932017-11-17 18:14:09 +00001228 for (ObjFile *File : Symtab->ObjectFiles)
1229 File->dumpInfo();
1230 }
1231
Sam Cleggc94d3932017-11-17 18:14:09 +00001232 createHeader();
1233 log("-- createSections");
1234 createSections();
1235
1236 log("-- openFile");
1237 openFile();
1238 if (errorCount())
1239 return;
1240
1241 writeHeader();
1242
1243 log("-- writeSections");
1244 writeSections();
1245 if (errorCount())
1246 return;
1247
1248 if (Error E = Buffer->commit())
1249 fatal("failed to write the output file: " + toString(std::move(E)));
1250}
1251
1252// Open a result file.
1253void Writer::openFile() {
1254 log("writing: " + Config->OutputFile);
Sam Cleggc94d3932017-11-17 18:14:09 +00001255
1256 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
1257 FileOutputBuffer::create(Config->OutputFile, FileSize,
1258 FileOutputBuffer::F_executable);
1259
1260 if (!BufferOrErr)
1261 error("failed to open " + Config->OutputFile + ": " +
1262 toString(BufferOrErr.takeError()));
1263 else
1264 Buffer = std::move(*BufferOrErr);
1265}
1266
1267void Writer::createHeader() {
1268 raw_string_ostream OS(Header);
1269 writeBytes(OS, WasmMagic, sizeof(WasmMagic), "wasm magic");
1270 writeU32(OS, WasmVersion, "wasm version");
1271 OS.flush();
1272 FileSize += Header.size();
1273}
1274
1275void lld::wasm::writeResult() { Writer().run(); }