blob: 12b526d37775767612c0fef51712a7bab3997117 [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);
Sam Cleggd425d6b2019-03-12 21:53:23 +0000201 } else if (auto *DataSym = dyn_cast<UndefinedData>(Sym)) {
202 Import.Kind = WASM_EXTERNAL_GLOBAL;
203 Import.Global = {WASM_TYPE_I32, true};
Heejin Ahne915a712018-12-08 06:17:43 +0000204 } else if (auto *GlobalSym = dyn_cast<GlobalSymbol>(Sym)) {
Sam Clegg93102972018-02-23 05:08:53 +0000205 Import.Kind = WASM_EXTERNAL_GLOBAL;
206 Import.Global = *GlobalSym->getGlobalType();
Heejin Ahne915a712018-12-08 06:17:43 +0000207 } else {
208 auto *EventSym = cast<EventSymbol>(Sym);
209 Import.Kind = WASM_EXTERNAL_EVENT;
210 Import.Event.Attribute = EventSym->getEventType()->Attribute;
211 Import.Event.SigIndex = lookupType(*EventSym->Signature);
Sam Clegg93102972018-02-23 05:08:53 +0000212 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000213 writeImport(OS, Import);
214 }
215}
216
217void Writer::createTypeSection() {
218 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TYPE);
219 raw_ostream &OS = Section->getStream();
220 writeUleb128(OS, Types.size(), "type count");
Sam Cleggd451da12017-12-19 19:56:27 +0000221 for (const WasmSignature *Sig : Types)
Sam Cleggc94d3932017-11-17 18:14:09 +0000222 writeSig(OS, *Sig);
Sam Cleggc94d3932017-11-17 18:14:09 +0000223}
224
225void Writer::createFunctionSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000226 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000227 return;
228
229 SyntheticSection *Section = createSyntheticSection(WASM_SEC_FUNCTION);
230 raw_ostream &OS = Section->getStream();
231
Sam Clegg9f934222018-02-21 18:29:23 +0000232 writeUleb128(OS, InputFunctions.size(), "function count");
233 for (const InputFunction *Func : InputFunctions)
Sam Cleggc375e4e2018-01-10 19:18:22 +0000234 writeUleb128(OS, lookupType(Func->Signature), "sig index");
Sam Cleggc94d3932017-11-17 18:14:09 +0000235}
236
237void Writer::createMemorySection() {
238 if (Config->ImportMemory)
239 return;
240
241 SyntheticSection *Section = createSyntheticSection(WASM_SEC_MEMORY);
242 raw_ostream &OS = Section->getStream();
243
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000244 bool HasMax = MaxMemoryPages != 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000245 writeUleb128(OS, 1, "memory count");
Derek Schuff786760a2018-11-06 18:02:39 +0000246 unsigned Flags = 0;
247 if (HasMax)
248 Flags |= WASM_LIMITS_FLAG_HAS_MAX;
Derek Schuff3bea8bc2018-11-06 17:59:32 +0000249 if (Config->SharedMemory)
250 Flags |= WASM_LIMITS_FLAG_IS_SHARED;
251 writeUleb128(OS, Flags, "memory limits flags");
Sam Cleggc94d3932017-11-17 18:14:09 +0000252 writeUleb128(OS, NumMemoryPages, "initial pages");
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000253 if (HasMax)
254 writeUleb128(OS, MaxMemoryPages, "max pages");
Sam Cleggc94d3932017-11-17 18:14:09 +0000255}
256
257void Writer::createGlobalSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000258 unsigned NumGlobals = InputGlobals.size() + DefinedFakeGlobals.size();
259 if (NumGlobals == 0)
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000260 return;
261
Sam Cleggc94d3932017-11-17 18:14:09 +0000262 SyntheticSection *Section = createSyntheticSection(WASM_SEC_GLOBAL);
263 raw_ostream &OS = Section->getStream();
264
Sam Clegg93102972018-02-23 05:08:53 +0000265 writeUleb128(OS, NumGlobals, "global count");
266 for (const InputGlobal *G : InputGlobals)
267 writeGlobal(OS, G->Global);
268 for (const DefinedData *Sym : DefinedFakeGlobals) {
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000269 WasmGlobal Global;
Sam Clegg93102972018-02-23 05:08:53 +0000270 Global.Type = {WASM_TYPE_I32, false};
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000271 Global.InitExpr.Opcode = WASM_OPCODE_I32_CONST;
272 Global.InitExpr.Value.Int32 = Sym->getVirtualAddress();
Sam Cleggc94d3932017-11-17 18:14:09 +0000273 writeGlobal(OS, Global);
274 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000275}
276
Heejin Ahne915a712018-12-08 06:17:43 +0000277// The event section contains a list of declared wasm events associated with the
278// module. Currently the only supported event kind is exceptions. A single event
279// entry represents a single event with an event tag. All C++ exceptions are
280// represented by a single event. An event entry in this section contains
281// information on what kind of event it is (e.g. exception) and the type of
282// values contained in a single event object. (In wasm, an event can contain
283// multiple values of primitive types. But for C++ exceptions, we just throw a
284// pointer which is an i32 value (for wasm32 architecture), so the signature of
285// C++ exception is (i32)->(void), because all event types are assumed to have
286// void return type to share WasmSignature with functions.)
287void Writer::createEventSection() {
288 unsigned NumEvents = InputEvents.size();
289 if (NumEvents == 0)
290 return;
291
292 SyntheticSection *Section = createSyntheticSection(WASM_SEC_EVENT);
293 raw_ostream &OS = Section->getStream();
294
295 writeUleb128(OS, NumEvents, "event count");
296 for (InputEvent *E : InputEvents) {
297 E->Event.Type.SigIndex = lookupType(E->Signature);
298 writeEvent(OS, E->Event);
299 }
300}
301
Sam Cleggc94d3932017-11-17 18:14:09 +0000302void Writer::createTableSection() {
Nicholas Wilsonfc90b302018-03-28 12:53:29 +0000303 if (Config->ImportTable)
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000304 return;
305
306 // Always output a table section (or table import), even if there are no
307 // indirect calls. There are two reasons for this:
Sam Cleggfc1a9122017-12-11 22:00:56 +0000308 // 1. For executables it is useful to have an empty table slot at 0
309 // which can be filled with a null function call handler.
310 // 2. If we don't do this, any program that contains a call_indirect but
311 // no address-taken function will fail at validation time since it is
312 // a validation error to include a call_indirect instruction if there
313 // is not table.
Sam Cleggbfb75342018-11-15 00:37:21 +0000314 uint32_t TableSize = TableBase + IndirectFunctions.size();
Sam Cleggfc1a9122017-12-11 22:00:56 +0000315
Sam Cleggc94d3932017-11-17 18:14:09 +0000316 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TABLE);
317 raw_ostream &OS = Section->getStream();
318
319 writeUleb128(OS, 1, "table count");
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000320 WasmLimits Limits = {WASM_LIMITS_FLAG_HAS_MAX, TableSize, TableSize};
Thomas Lively25ff8932019-01-08 06:25:55 +0000321 writeTableType(OS, WasmTable{WASM_TYPE_FUNCREF, Limits});
Sam Cleggc94d3932017-11-17 18:14:09 +0000322}
323
324void Writer::createExportSection() {
Sam Cleggd6beb322018-05-10 18:10:34 +0000325 if (!Exports.size())
Sam Cleggc94d3932017-11-17 18:14:09 +0000326 return;
327
328 SyntheticSection *Section = createSyntheticSection(WASM_SEC_EXPORT);
329 raw_ostream &OS = Section->getStream();
330
Sam Cleggd6beb322018-05-10 18:10:34 +0000331 writeUleb128(OS, Exports.size(), "export count");
332 for (const WasmExport &Export : Exports)
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000333 writeExport(OS, Export);
Sam Cleggc94d3932017-11-17 18:14:09 +0000334}
335
Sam Cleggd177ab22018-05-04 23:14:42 +0000336void Writer::calculateCustomSections() {
337 log("calculateCustomSections");
338 bool StripDebug = Config->StripDebug || Config->StripAll;
339 for (ObjFile *File : Symtab->ObjectFiles) {
340 for (InputSection *Section : File->CustomSections) {
341 StringRef Name = Section->getName();
342 // These custom sections are known the linker and synthesized rather than
343 // blindly copied
Thomas Lively2a0868f2019-01-17 02:29:41 +0000344 if (Name == "linking" || Name == "name" || Name == "producers" ||
345 Name.startswith("reloc."))
Sam Cleggd177ab22018-05-04 23:14:42 +0000346 continue;
347 // .. or it is a debug section
348 if (StripDebug && Name.startswith(".debug_"))
349 continue;
350 CustomSectionMapping[Name].push_back(Section);
351 }
352 }
353}
354
Sam Clegg80ba4382018-04-10 16:12:49 +0000355void Writer::createCustomSections() {
356 log("createCustomSections");
Sam Clegg80ba4382018-04-10 16:12:49 +0000357 for (auto &Pair : CustomSectionMapping) {
358 StringRef Name = Pair.first();
Sam Cleggd177ab22018-05-04 23:14:42 +0000359
360 auto P = CustomSectionSymbols.find(Name);
361 if (P != CustomSectionSymbols.end()) {
362 uint32_t SectionIndex = OutputSections.size();
363 P->second->setOutputSectionIndex(SectionIndex);
364 }
365
Nicola Zaghene7245b42018-05-15 13:36:20 +0000366 LLVM_DEBUG(dbgs() << "createCustomSection: " << Name << "\n");
Sam Clegg80ba4382018-04-10 16:12:49 +0000367 OutputSections.push_back(make<CustomSection>(Name, Pair.second));
368 }
369}
370
Sam Cleggc94d3932017-11-17 18:14:09 +0000371void Writer::createElemSection() {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000372 if (IndirectFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000373 return;
374
375 SyntheticSection *Section = createSyntheticSection(WASM_SEC_ELEM);
376 raw_ostream &OS = Section->getStream();
377
378 writeUleb128(OS, 1, "segment count");
379 writeUleb128(OS, 0, "table index");
380 WasmInitExpr InitExpr;
Sam Cleggbfb75342018-11-15 00:37:21 +0000381 if (Config->Pic) {
Thomas Lively25ff8932019-01-08 06:25:55 +0000382 InitExpr.Opcode = WASM_OPCODE_GLOBAL_GET;
Sam Clegg2dad4e22018-11-15 18:15:54 +0000383 InitExpr.Value.Global = WasmSym::TableBase->getGlobalIndex();
Sam Cleggbfb75342018-11-15 00:37:21 +0000384 } else {
385 InitExpr.Opcode = WASM_OPCODE_I32_CONST;
386 InitExpr.Value.Int32 = TableBase;
387 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000388 writeInitExpr(OS, InitExpr);
Sam Cleggfc1a9122017-12-11 22:00:56 +0000389 writeUleb128(OS, IndirectFunctions.size(), "elem count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000390
Sam Cleggbfb75342018-11-15 00:37:21 +0000391 uint32_t TableIndex = TableBase;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000392 for (const FunctionSymbol *Sym : IndirectFunctions) {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000393 assert(Sym->getTableIndex() == TableIndex);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000394 writeUleb128(OS, Sym->getFunctionIndex(), "function index");
Sam Cleggfc1a9122017-12-11 22:00:56 +0000395 ++TableIndex;
396 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000397}
398
399void Writer::createCodeSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000400 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000401 return;
402
403 log("createCodeSection");
404
Sam Clegg9f934222018-02-21 18:29:23 +0000405 auto Section = make<CodeSection>(InputFunctions);
Sam Cleggc94d3932017-11-17 18:14:09 +0000406 OutputSections.push_back(Section);
407}
408
409void Writer::createDataSection() {
410 if (!Segments.size())
411 return;
412
413 log("createDataSection");
414 auto Section = make<DataSection>(Segments);
415 OutputSections.push_back(Section);
416}
417
Sam Cleggd451da12017-12-19 19:56:27 +0000418// Create relocations sections in the final output.
Sam Cleggc94d3932017-11-17 18:14:09 +0000419// These are only created when relocatable output is requested.
420void Writer::createRelocSections() {
421 log("createRelocSections");
422 // Don't use iterator here since we are adding to OutputSection
423 size_t OrigSize = OutputSections.size();
Rui Ueyamaffa650a2018-04-24 23:09:57 +0000424 for (size_t I = 0; I < OrigSize; I++) {
425 OutputSection *OSec = OutputSections[I];
Rui Ueyama37254062018-02-28 00:01:31 +0000426 uint32_t Count = OSec->numRelocations();
Sam Cleggc94d3932017-11-17 18:14:09 +0000427 if (!Count)
428 continue;
429
Rui Ueyama37254062018-02-28 00:01:31 +0000430 StringRef Name;
431 if (OSec->Type == WASM_SEC_DATA)
432 Name = "reloc.DATA";
433 else if (OSec->Type == WASM_SEC_CODE)
434 Name = "reloc.CODE";
Sam Cleggd177ab22018-05-04 23:14:42 +0000435 else if (OSec->Type == WASM_SEC_CUSTOM)
436 Name = Saver.save("reloc." + OSec->Name);
Sam Cleggc94d3932017-11-17 18:14:09 +0000437 else
Sam Cleggd177ab22018-05-04 23:14:42 +0000438 llvm_unreachable(
439 "relocations only supported for code, data, or custom sections");
Sam Cleggc94d3932017-11-17 18:14:09 +0000440
Rui Ueyama37254062018-02-28 00:01:31 +0000441 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, Name);
Sam Cleggc94d3932017-11-17 18:14:09 +0000442 raw_ostream &OS = Section->getStream();
Rui Ueyamaffa650a2018-04-24 23:09:57 +0000443 writeUleb128(OS, I, "reloc section");
Sam Cleggc94d3932017-11-17 18:14:09 +0000444 writeUleb128(OS, Count, "reloc count");
Rui Ueyama37254062018-02-28 00:01:31 +0000445 OSec->writeRelocations(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000446 }
447}
448
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000449static uint32_t getWasmFlags(const Symbol *Sym) {
450 uint32_t Flags = 0;
451 if (Sym->isLocal())
452 Flags |= WASM_SYMBOL_BINDING_LOCAL;
453 if (Sym->isWeak())
454 Flags |= WASM_SYMBOL_BINDING_WEAK;
455 if (Sym->isHidden())
456 Flags |= WASM_SYMBOL_VISIBILITY_HIDDEN;
457 if (Sym->isUndefined())
458 Flags |= WASM_SYMBOL_UNDEFINED;
Dan Gohman9b84eea2019-02-07 22:00:48 +0000459 if (auto *F = dyn_cast<UndefinedFunction>(Sym)) {
460 if (F->getName() != F->ImportName)
461 Flags |= WASM_SYMBOL_EXPLICIT_NAME;
462 } else if (auto *G = dyn_cast<UndefinedGlobal>(Sym)) {
463 if (G->getName() != G->ImportName)
464 Flags |= WASM_SYMBOL_EXPLICIT_NAME;
465 }
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000466 return Flags;
467}
468
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000469// Some synthetic sections (e.g. "name" and "linking") have subsections.
470// Just like the synthetic sections themselves these need to be created before
471// they can be written out (since they are preceded by their length). This
472// class is used to create subsections and then write them into the stream
473// of the parent section.
474class SubSection {
475public:
476 explicit SubSection(uint32_t Type) : Type(Type) {}
477
478 void writeTo(raw_ostream &To) {
479 OS.flush();
Rui Ueyama67769102018-02-28 03:38:14 +0000480 writeUleb128(To, Type, "subsection type");
481 writeUleb128(To, Body.size(), "subsection size");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000482 To.write(Body.data(), Body.size());
483 }
484
485private:
486 uint32_t Type;
487 std::string Body;
488
489public:
490 raw_string_ostream OS{Body};
491};
492
Sam Cleggbfb75342018-11-15 00:37:21 +0000493// Create the custom "dylink" section containing information for the dynamic
494// linker.
495// See
496// https://github.com/WebAssembly/tool-conventions/blob/master/DynamicLinking.md
497void Writer::createDylinkSection() {
498 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "dylink");
499 raw_ostream &OS = Section->getStream();
500
501 writeUleb128(OS, MemSize, "MemSize");
Sam Clegg6320efb2019-01-16 01:43:21 +0000502 writeUleb128(OS, MemAlign, "MemAlign");
Sam Cleggbfb75342018-11-15 00:37:21 +0000503 writeUleb128(OS, IndirectFunctions.size(), "TableSize");
504 writeUleb128(OS, 0, "TableAlign");
Sam Clegge01c6462018-12-12 23:44:59 +0000505 writeUleb128(OS, 0, "Needed"); // TODO: Support "needed" shared libraries
Sam Cleggbfb75342018-11-15 00:37:21 +0000506}
507
Sam Clegg49ed9262017-12-01 00:53:21 +0000508// Create the custom "linking" section containing linker metadata.
Sam Cleggc94d3932017-11-17 18:14:09 +0000509// This is only created when relocatable output is requested.
510void Writer::createLinkingSection() {
511 SyntheticSection *Section =
512 createSyntheticSection(WASM_SEC_CUSTOM, "linking");
513 raw_ostream &OS = Section->getStream();
514
Sam Clegg2b8b1792018-04-26 18:17:21 +0000515 writeUleb128(OS, WasmMetadataVersion, "Version");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000516
Sam Clegg93102972018-02-23 05:08:53 +0000517 if (!SymtabEntries.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000518 SubSection Sub(WASM_SYMBOL_TABLE);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000519 writeUleb128(Sub.OS, SymtabEntries.size(), "num symbols");
520
Sam Clegg93102972018-02-23 05:08:53 +0000521 for (const Symbol *Sym : SymtabEntries) {
522 assert(Sym->isDefined() || Sym->isUndefined());
523 WasmSymbolType Kind = Sym->getWasmType();
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000524 uint32_t Flags = getWasmFlags(Sym);
525
Sam Clegg8518e7d2018-03-01 18:06:39 +0000526 writeU8(Sub.OS, Kind, "sym kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000527 writeUleb128(Sub.OS, Flags, "sym flags");
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000528
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000529 if (auto *F = dyn_cast<FunctionSymbol>(Sym)) {
530 writeUleb128(Sub.OS, F->getFunctionIndex(), "index");
Dan Gohman9b84eea2019-02-07 22:00:48 +0000531 if (Sym->isDefined() ||
532 (Flags & WASM_SYMBOL_EXPLICIT_NAME) != 0)
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000533 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000534 } else if (auto *G = dyn_cast<GlobalSymbol>(Sym)) {
535 writeUleb128(Sub.OS, G->getGlobalIndex(), "index");
Dan Gohman9b84eea2019-02-07 22:00:48 +0000536 if (Sym->isDefined() ||
537 (Flags & WASM_SYMBOL_EXPLICIT_NAME) != 0)
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000538 writeStr(Sub.OS, Sym->getName(), "sym name");
Heejin Ahne915a712018-12-08 06:17:43 +0000539 } else if (auto *E = dyn_cast<EventSymbol>(Sym)) {
540 writeUleb128(Sub.OS, E->getEventIndex(), "index");
Dan Gohman9b84eea2019-02-07 22:00:48 +0000541 if (Sym->isDefined() ||
542 (Flags & WASM_SYMBOL_EXPLICIT_NAME) != 0)
Heejin Ahne915a712018-12-08 06:17:43 +0000543 writeStr(Sub.OS, Sym->getName(), "sym name");
Andrea Di Biagio25c1a2f2018-05-05 10:53:31 +0000544 } else if (isa<DataSymbol>(Sym)) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000545 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegg93102972018-02-23 05:08:53 +0000546 if (auto *DataSym = dyn_cast<DefinedData>(Sym)) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000547 writeUleb128(Sub.OS, DataSym->getOutputSegmentIndex(), "index");
548 writeUleb128(Sub.OS, DataSym->getOutputSegmentOffset(),
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000549 "data offset");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000550 writeUleb128(Sub.OS, DataSym->getSize(), "data size");
Sam Clegg93102972018-02-23 05:08:53 +0000551 }
Sam Cleggd177ab22018-05-04 23:14:42 +0000552 } else {
553 auto *S = cast<SectionSymbol>(Sym);
554 writeUleb128(Sub.OS, S->getOutputSectionIndex(), "sym section index");
Sam Clegg93102972018-02-23 05:08:53 +0000555 }
Sam Cleggd3052d52018-01-18 23:40:49 +0000556 }
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000557
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000558 Sub.writeTo(OS);
Sam Cleggd3052d52018-01-18 23:40:49 +0000559 }
560
Sam Clegg0d0dd392017-12-19 17:09:45 +0000561 if (Segments.size()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000562 SubSection Sub(WASM_SEGMENT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000563 writeUleb128(Sub.OS, Segments.size(), "num data segments");
Sam Cleggc94d3932017-11-17 18:14:09 +0000564 for (const OutputSegment *S : Segments) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000565 writeStr(Sub.OS, S->Name, "segment name");
566 writeUleb128(Sub.OS, S->Alignment, "alignment");
567 writeUleb128(Sub.OS, 0, "flags");
Sam Cleggc94d3932017-11-17 18:14:09 +0000568 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000569 Sub.writeTo(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000570 }
Sam Clegg0d0dd392017-12-19 17:09:45 +0000571
Sam Clegg0d0dd392017-12-19 17:09:45 +0000572 if (!InitFunctions.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000573 SubSection Sub(WASM_INIT_FUNCS);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000574 writeUleb128(Sub.OS, InitFunctions.size(), "num init functions");
Sam Clegg93102972018-02-23 05:08:53 +0000575 for (const WasmInitEntry &F : InitFunctions) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000576 writeUleb128(Sub.OS, F.Priority, "priority");
577 writeUleb128(Sub.OS, F.Sym->getOutputSymbolIndex(), "function index");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000578 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000579 Sub.writeTo(OS);
Sam Clegg0d0dd392017-12-19 17:09:45 +0000580 }
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000581
Nicholas Wilsondbd90bf2018-03-07 13:28:16 +0000582 struct ComdatEntry {
583 unsigned Kind;
584 uint32_t Index;
585 };
586 std::map<StringRef, std::vector<ComdatEntry>> Comdats;
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000587
Sam Clegg9f934222018-02-21 18:29:23 +0000588 for (const InputFunction *F : InputFunctions) {
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000589 StringRef Comdat = F->getComdatName();
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000590 if (!Comdat.empty())
591 Comdats[Comdat].emplace_back(
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000592 ComdatEntry{WASM_COMDAT_FUNCTION, F->getFunctionIndex()});
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000593 }
594 for (uint32_t I = 0; I < Segments.size(); ++I) {
Sam Cleggf98bccf2018-01-13 15:57:48 +0000595 const auto &InputSegments = Segments[I]->InputSegments;
596 if (InputSegments.empty())
597 continue;
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000598 StringRef Comdat = InputSegments[0]->getComdatName();
Sam Clegga697df522018-01-13 15:59:53 +0000599#ifndef NDEBUG
Sam Cleggf98bccf2018-01-13 15:57:48 +0000600 for (const InputSegment *IS : InputSegments)
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000601 assert(IS->getComdatName() == Comdat);
Sam Clegga697df522018-01-13 15:59:53 +0000602#endif
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000603 if (!Comdat.empty())
604 Comdats[Comdat].emplace_back(ComdatEntry{WASM_COMDAT_DATA, I});
605 }
606
607 if (!Comdats.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000608 SubSection Sub(WASM_COMDAT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000609 writeUleb128(Sub.OS, Comdats.size(), "num comdats");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000610 for (const auto &C : Comdats) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000611 writeStr(Sub.OS, C.first, "comdat name");
612 writeUleb128(Sub.OS, 0, "comdat flags"); // flags for future use
613 writeUleb128(Sub.OS, C.second.size(), "num entries");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000614 for (const ComdatEntry &Entry : C.second) {
Sam Clegg8518e7d2018-03-01 18:06:39 +0000615 writeU8(Sub.OS, Entry.Kind, "entry kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000616 writeUleb128(Sub.OS, Entry.Index, "entry index");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000617 }
618 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000619 Sub.writeTo(OS);
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000620 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000621}
622
623// Create the custom "name" section containing debug symbol names.
624void Writer::createNameSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000625 unsigned NumNames = NumImportedFunctions;
Sam Clegg9f934222018-02-21 18:29:23 +0000626 for (const InputFunction *F : InputFunctions)
Nicholas Wilson6c7fe302018-04-20 17:09:18 +0000627 if (!F->getName().empty() || !F->getDebugName().empty())
Sam Clegg1963d712018-01-17 20:19:04 +0000628 ++NumNames;
Sam Cleggc94d3932017-11-17 18:14:09 +0000629
Sam Clegg1963d712018-01-17 20:19:04 +0000630 if (NumNames == 0)
631 return;
Sam Clegg50686852018-01-12 18:35:13 +0000632
Sam Cleggc94d3932017-11-17 18:14:09 +0000633 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "name");
634
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000635 SubSection Sub(WASM_NAMES_FUNCTION);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000636 writeUleb128(Sub.OS, NumNames, "name count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000637
Sam Clegg93102972018-02-23 05:08:53 +0000638 // Names must appear in function index order. As it happens ImportedSymbols
639 // and InputFunctions are numbered in order with imported functions coming
Sam Clegg1963d712018-01-17 20:19:04 +0000640 // first.
Sam Clegg93102972018-02-23 05:08:53 +0000641 for (const Symbol *S : ImportedSymbols) {
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000642 if (auto *F = dyn_cast<FunctionSymbol>(S)) {
643 writeUleb128(Sub.OS, F->getFunctionIndex(), "func index");
Sam Clegg37125f02018-11-09 16:57:41 +0000644 writeStr(Sub.OS, toString(*S), "symbol name");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000645 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000646 }
Sam Clegg9f934222018-02-21 18:29:23 +0000647 for (const InputFunction *F : InputFunctions) {
Sam Clegg1963d712018-01-17 20:19:04 +0000648 if (!F->getName().empty()) {
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000649 writeUleb128(Sub.OS, F->getFunctionIndex(), "func index");
Nicholas Wilson6c7fe302018-04-20 17:09:18 +0000650 if (!F->getDebugName().empty()) {
651 writeStr(Sub.OS, F->getDebugName(), "symbol name");
652 } else {
Sam Clegg37125f02018-11-09 16:57:41 +0000653 writeStr(Sub.OS, maybeDemangleSymbol(F->getName()), "symbol name");
Nicholas Wilson6c7fe302018-04-20 17:09:18 +0000654 }
Sam Clegg1963d712018-01-17 20:19:04 +0000655 }
656 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000657
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000658 Sub.writeTo(Section->getStream());
Sam Cleggc94d3932017-11-17 18:14:09 +0000659}
660
Thomas Lively2a0868f2019-01-17 02:29:41 +0000661void Writer::createProducersSection() {
662 SmallVector<std::pair<std::string, std::string>, 8> Languages;
663 SmallVector<std::pair<std::string, std::string>, 8> Tools;
664 SmallVector<std::pair<std::string, std::string>, 8> SDKs;
665 for (ObjFile *File : Symtab->ObjectFiles) {
666 const WasmProducerInfo &Info = File->getWasmObj()->getProducerInfo();
667 for (auto &Producers : {std::make_pair(&Info.Languages, &Languages),
668 std::make_pair(&Info.Tools, &Tools),
669 std::make_pair(&Info.SDKs, &SDKs)})
670 for (auto &Producer : *Producers.first)
671 if (Producers.second->end() ==
672 std::find_if(Producers.second->begin(), Producers.second->end(),
673 [&](std::pair<std::string, std::string> Seen) {
674 return Seen.first == Producer.first;
675 }))
676 Producers.second->push_back(Producer);
677 }
678 int FieldCount =
679 int(!Languages.empty()) + int(!Tools.empty()) + int(!SDKs.empty());
680 if (FieldCount == 0)
681 return;
682 SyntheticSection *Section =
683 createSyntheticSection(WASM_SEC_CUSTOM, "producers");
684 auto &OS = Section->getStream();
685 writeUleb128(OS, FieldCount, "field count");
686 for (auto &Field :
687 {std::make_pair("language", Languages),
688 std::make_pair("processed-by", Tools), std::make_pair("sdk", SDKs)}) {
689 if (Field.second.empty())
690 continue;
691 writeStr(OS, Field.first, "field name");
692 writeUleb128(OS, Field.second.size(), "number of entries");
693 for (auto &Entry : Field.second) {
694 writeStr(OS, Entry.first, "producer name");
695 writeStr(OS, Entry.second, "producer version");
696 }
697 }
698}
699
Sam Cleggc94d3932017-11-17 18:14:09 +0000700void Writer::writeHeader() {
701 memcpy(Buffer->getBufferStart(), Header.data(), Header.size());
702}
703
704void Writer::writeSections() {
705 uint8_t *Buf = Buffer->getBufferStart();
706 parallelForEach(OutputSections, [Buf](OutputSection *S) { S->writeTo(Buf); });
707}
708
709// Fix the memory layout of the output binary. This assigns memory offsets
Sam Clegg49ed9262017-12-01 00:53:21 +0000710// to each of the input data sections as well as the explicit stack region.
Sam Clegga0f095e2018-05-03 17:21:53 +0000711// The default memory layout is as follows, from low to high.
712//
Sam Cleggf0d433d2018-02-02 22:59:56 +0000713// - initialized data (starting at Config->GlobalBase)
714// - BSS data (not currently implemented in llvm)
715// - explicit stack (Config->ZStackSize)
716// - heap start / unallocated
Sam Clegga0f095e2018-05-03 17:21:53 +0000717//
718// The --stack-first option means that stack is placed before any static data.
Heejin Ahn4821ebf2018-08-29 21:03:16 +0000719// This can be useful since it means that stack overflow traps immediately
720// rather than overwriting global data, but also increases code size since all
721// static data loads and stores requires larger offsets.
Sam Cleggc94d3932017-11-17 18:14:09 +0000722void Writer::layoutMemory() {
Sam Cleggc94d3932017-11-17 18:14:09 +0000723 createOutputSegments();
724
Sam Clegga0f095e2018-05-03 17:21:53 +0000725 uint32_t MemoryPtr = 0;
726
727 auto PlaceStack = [&]() {
Sam Cleggbfb75342018-11-15 00:37:21 +0000728 if (Config->Relocatable || Config->Shared)
Sam Clegga0f095e2018-05-03 17:21:53 +0000729 return;
Heejin Ahna1cc4ea2019-02-04 19:13:46 +0000730 MemoryPtr = alignTo(MemoryPtr, StackAlignment);
731 if (Config->ZStackSize != alignTo(Config->ZStackSize, StackAlignment))
732 error("stack size must be " + Twine(StackAlignment) + "-byte aligned");
Sam Clegga0f095e2018-05-03 17:21:53 +0000733 log("mem: stack size = " + Twine(Config->ZStackSize));
734 log("mem: stack base = " + Twine(MemoryPtr));
735 MemoryPtr += Config->ZStackSize;
Sam Clegg2dad4e22018-11-15 18:15:54 +0000736 auto *SP = cast<DefinedGlobal>(WasmSym::StackPointer);
737 SP->Global->Global.InitExpr.Value.Int32 = MemoryPtr;
Sam Clegga0f095e2018-05-03 17:21:53 +0000738 log("mem: stack top = " + Twine(MemoryPtr));
739 };
740
741 if (Config->StackFirst) {
742 PlaceStack();
743 } else {
744 MemoryPtr = Config->GlobalBase;
745 log("mem: global base = " + Twine(Config->GlobalBase));
746 }
747
748 uint32_t DataStart = MemoryPtr;
749
Sam Cleggf0d433d2018-02-02 22:59:56 +0000750 // Arbitrarily set __dso_handle handle to point to the start of the data
751 // segments.
752 if (WasmSym::DsoHandle)
Sam Clegga0f095e2018-05-03 17:21:53 +0000753 WasmSym::DsoHandle->setVirtualAddress(DataStart);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000754
Sam Cleggbfb75342018-11-15 00:37:21 +0000755 MemAlign = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000756 for (OutputSegment *Seg : Segments) {
Sam Cleggbfb75342018-11-15 00:37:21 +0000757 MemAlign = std::max(MemAlign, Seg->Alignment);
Sam Clegg622ad042019-01-17 22:09:09 +0000758 MemoryPtr = alignTo(MemoryPtr, 1ULL << Seg->Alignment);
Sam Cleggc94d3932017-11-17 18:14:09 +0000759 Seg->StartVA = MemoryPtr;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000760 log(formatv("mem: {0,-15} offset={1,-8} size={2,-8} align={3}", Seg->Name,
761 MemoryPtr, Seg->Size, Seg->Alignment));
Sam Cleggc94d3932017-11-17 18:14:09 +0000762 MemoryPtr += Seg->Size;
763 }
764
Sam Cleggf0d433d2018-02-02 22:59:56 +0000765 // TODO: Add .bss space here.
Sam Clegg37a4a8a2018-02-07 03:04:53 +0000766 if (WasmSym::DataEnd)
767 WasmSym::DataEnd->setVirtualAddress(MemoryPtr);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000768
Sam Clegga0f095e2018-05-03 17:21:53 +0000769 log("mem: static data = " + Twine(MemoryPtr - DataStart));
Sam Cleggc94d3932017-11-17 18:14:09 +0000770
Sam Clegg2dad4e22018-11-15 18:15:54 +0000771 if (Config->Shared) {
772 MemSize = MemoryPtr;
773 return;
774 }
775
Sam Clegga0f095e2018-05-03 17:21:53 +0000776 if (!Config->StackFirst)
777 PlaceStack();
778
779 // Set `__heap_base` to directly follow the end of the stack or global data.
780 // The fact that this comes last means that a malloc/brk implementation
781 // can grow the heap at runtime.
Sam Cleggc94d3932017-11-17 18:14:09 +0000782 if (!Config->Relocatable) {
Sam Cleggf0d433d2018-02-02 22:59:56 +0000783 WasmSym::HeapBase->setVirtualAddress(MemoryPtr);
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000784 log("mem: heap base = " + Twine(MemoryPtr));
Sam Cleggc94d3932017-11-17 18:14:09 +0000785 }
786
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000787 if (Config->InitialMemory != 0) {
788 if (Config->InitialMemory != alignTo(Config->InitialMemory, WasmPageSize))
789 error("initial memory must be " + Twine(WasmPageSize) + "-byte aligned");
790 if (MemoryPtr > Config->InitialMemory)
791 error("initial memory too small, " + Twine(MemoryPtr) + " bytes needed");
792 else
793 MemoryPtr = Config->InitialMemory;
794 }
Sam Cleggbfb75342018-11-15 00:37:21 +0000795 MemSize = MemoryPtr;
796 NumMemoryPages = alignTo(MemoryPtr, WasmPageSize) / WasmPageSize;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000797 log("mem: total pages = " + Twine(NumMemoryPages));
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000798
799 if (Config->MaxMemory != 0) {
800 if (Config->MaxMemory != alignTo(Config->MaxMemory, WasmPageSize))
801 error("maximum memory must be " + Twine(WasmPageSize) + "-byte aligned");
802 if (MemoryPtr > Config->MaxMemory)
803 error("maximum memory too small, " + Twine(MemoryPtr) + " bytes needed");
804 MaxMemoryPages = Config->MaxMemory / WasmPageSize;
805 log("mem: max pages = " + Twine(MaxMemoryPages));
806 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000807}
808
809SyntheticSection *Writer::createSyntheticSection(uint32_t Type,
Sam Cleggc375e4e2018-01-10 19:18:22 +0000810 StringRef Name) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000811 auto Sec = make<SyntheticSection>(Type, Name);
Sam Cleggab2ac292017-12-20 05:14:48 +0000812 log("createSection: " + toString(*Sec));
Sam Cleggc94d3932017-11-17 18:14:09 +0000813 OutputSections.push_back(Sec);
814 return Sec;
815}
816
817void Writer::createSections() {
818 // Known sections
Sam Cleggbfb75342018-11-15 00:37:21 +0000819 if (Config->Pic)
820 createDylinkSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000821 createTypeSection();
822 createImportSection();
823 createFunctionSection();
824 createTableSection();
825 createMemorySection();
826 createGlobalSection();
Heejin Ahne915a712018-12-08 06:17:43 +0000827 createEventSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000828 createExportSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000829 createElemSection();
830 createCodeSection();
831 createDataSection();
Sam Clegg80ba4382018-04-10 16:12:49 +0000832 createCustomSections();
Sam Cleggc94d3932017-11-17 18:14:09 +0000833
834 // Custom sections
Sam Clegg99eb42c2018-02-27 23:58:03 +0000835 if (Config->Relocatable) {
Sam Clegg99eb42c2018-02-27 23:58:03 +0000836 createLinkingSection();
Nicholas Wilson94d3b162018-03-05 12:33:58 +0000837 createRelocSections();
Sam Clegg99eb42c2018-02-27 23:58:03 +0000838 }
Thomas Lively2a0868f2019-01-17 02:29:41 +0000839
Sam Cleggc94d3932017-11-17 18:14:09 +0000840 if (!Config->StripDebug && !Config->StripAll)
841 createNameSection();
842
Thomas Lively2a0868f2019-01-17 02:29:41 +0000843 if (!Config->StripAll)
844 createProducersSection();
845
Sam Cleggc94d3932017-11-17 18:14:09 +0000846 for (OutputSection *S : OutputSections) {
847 S->setOffset(FileSize);
848 S->finalizeContents();
849 FileSize += S->getSize();
850 }
851}
852
Sam Cleggc94d3932017-11-17 18:14:09 +0000853void Writer::calculateImports() {
Sam Clegg574d7ce2017-12-15 19:23:49 +0000854 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000855 if (!Sym->isUndefined())
856 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000857 if (Sym->isWeak() && !Config->Relocatable)
Sam Clegg574d7ce2017-12-15 19:23:49 +0000858 continue;
Nicholas Wilsona1e299f2018-04-20 17:18:06 +0000859 if (!Sym->isLive())
860 continue;
Sam Cleggc729c1b2018-05-30 18:07:52 +0000861 if (!Sym->IsUsedInRegularObj)
862 continue;
Sam Cleggd425d6b2019-03-12 21:53:23 +0000863 // In relocatable output we don't generate imports for data symbols.
864 // These live only in the symbol table.
865 if (Config->Relocatable && isa<DataSymbol>(Sym))
866 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000867
Nicola Zaghene7245b42018-05-15 13:36:20 +0000868 LLVM_DEBUG(dbgs() << "import: " << Sym->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000869 ImportedSymbols.emplace_back(Sym);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000870 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
871 F->setFunctionIndex(NumImportedFunctions++);
Heejin Ahne915a712018-12-08 06:17:43 +0000872 else if (auto *G = dyn_cast<GlobalSymbol>(Sym))
873 G->setGlobalIndex(NumImportedGlobals++);
Sam Cleggd425d6b2019-03-12 21:53:23 +0000874 else if (auto *D = dyn_cast<UndefinedData>(Sym))
875 D->setGlobalIndex(NumImportedGlobals++);
Sam Clegg93102972018-02-23 05:08:53 +0000876 else
Heejin Ahne915a712018-12-08 06:17:43 +0000877 cast<EventSymbol>(Sym)->setEventIndex(NumImportedEvents++);
Sam Cleggc94d3932017-11-17 18:14:09 +0000878 }
879}
880
Sam Cleggd3052d52018-01-18 23:40:49 +0000881void Writer::calculateExports() {
Sam Clegg93102972018-02-23 05:08:53 +0000882 if (Config->Relocatable)
883 return;
Sam Cleggf0d433d2018-02-02 22:59:56 +0000884
Sam Cleggd6beb322018-05-10 18:10:34 +0000885 if (!Config->Relocatable && !Config->ImportMemory)
886 Exports.push_back(WasmExport{"memory", WASM_EXTERNAL_MEMORY, 0});
887
888 if (!Config->Relocatable && Config->ExportTable)
Heejin Ahna1cc4ea2019-02-04 19:13:46 +0000889 Exports.push_back(WasmExport{FunctionTableName, WASM_EXTERNAL_TABLE, 0});
Sam Cleggd6beb322018-05-10 18:10:34 +0000890
891 unsigned FakeGlobalIndex = NumImportedGlobals + InputGlobals.size();
892
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000893 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Cleggce004bf2018-06-28 17:04:58 +0000894 if (!Sym->isExported())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000895 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000896 if (!Sym->isLive())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000897 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000898
Sam Cleggd6beb322018-05-10 18:10:34 +0000899 StringRef Name = Sym->getName();
900 WasmExport Export;
901 if (auto *F = dyn_cast<DefinedFunction>(Sym)) {
902 Export = {Name, WASM_EXTERNAL_FUNCTION, F->getFunctionIndex()};
903 } else if (auto *G = dyn_cast<DefinedGlobal>(Sym)) {
Sam Clegg177b4582018-06-07 01:27:07 +0000904 // TODO(sbc): Remove this check once to mutable global proposal is
905 // implement in all major browsers.
906 // See: https://github.com/WebAssembly/mutable-global
907 if (G->getGlobalType()->Mutable) {
908 // Only the __stack_pointer should ever be create as mutable.
909 assert(G == WasmSym::StackPointer);
910 continue;
911 }
Sam Cleggd6beb322018-05-10 18:10:34 +0000912 Export = {Name, WASM_EXTERNAL_GLOBAL, G->getGlobalIndex()};
Heejin Ahne915a712018-12-08 06:17:43 +0000913 } else if (auto *E = dyn_cast<DefinedEvent>(Sym)) {
914 Export = {Name, WASM_EXTERNAL_EVENT, E->getEventIndex()};
Sam Cleggd6beb322018-05-10 18:10:34 +0000915 } else {
916 auto *D = cast<DefinedData>(Sym);
Sam Clegg93102972018-02-23 05:08:53 +0000917 DefinedFakeGlobals.emplace_back(D);
Sam Cleggd6beb322018-05-10 18:10:34 +0000918 Export = {Name, WASM_EXTERNAL_GLOBAL, FakeGlobalIndex++};
919 }
920
Nicola Zaghene7245b42018-05-15 13:36:20 +0000921 LLVM_DEBUG(dbgs() << "Export: " << Name << "\n");
Sam Cleggd6beb322018-05-10 18:10:34 +0000922 Exports.push_back(Export);
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000923 }
Sam Clegg93102972018-02-23 05:08:53 +0000924}
925
926void Writer::assignSymtab() {
927 if (!Config->Relocatable)
928 return;
929
Sam Cleggd177ab22018-05-04 23:14:42 +0000930 StringMap<uint32_t> SectionSymbolIndices;
931
Sam Clegg93102972018-02-23 05:08:53 +0000932 unsigned SymbolIndex = SymtabEntries.size();
Sam Cleggd177ab22018-05-04 23:14:42 +0000933
Sam Clegg89e4dcb2019-01-30 18:55:15 +0000934 auto AddSymbol = [&](Symbol *Sym) {
935 if (auto *S = dyn_cast<SectionSymbol>(Sym)) {
936 StringRef Name = S->getName();
937 if (CustomSectionMapping.count(Name) == 0)
938 return;
Sam Cleggd177ab22018-05-04 23:14:42 +0000939
Sam Clegg89e4dcb2019-01-30 18:55:15 +0000940 auto SSI = SectionSymbolIndices.find(Name);
941 if (SSI != SectionSymbolIndices.end()) {
942 Sym->setOutputSymbolIndex(SSI->second);
943 return;
Sam Cleggd177ab22018-05-04 23:14:42 +0000944 }
945
Sam Clegg89e4dcb2019-01-30 18:55:15 +0000946 SectionSymbolIndices[Name] = SymbolIndex;
947 CustomSectionSymbols[Name] = cast<SectionSymbol>(Sym);
Sam Cleggd3052d52018-01-18 23:40:49 +0000948
Sam Clegg89e4dcb2019-01-30 18:55:15 +0000949 Sym->markLive();
950 }
951
952 // (Since this is relocatable output, GC is not performed so symbols must
953 // be live.)
954 assert(Sym->isLive());
955 Sym->setOutputSymbolIndex(SymbolIndex++);
956 SymtabEntries.emplace_back(Sym);
957 };
958
959 for (Symbol *Sym : Symtab->getSymbols())
Sam Cleggd15a41542019-03-08 21:10:48 +0000960 if (Sym->IsUsedInRegularObj)
Sam Clegg89e4dcb2019-01-30 18:55:15 +0000961 AddSymbol(Sym);
962
963 for (ObjFile *File : Symtab->ObjectFiles) {
964 LLVM_DEBUG(dbgs() << "Local symtab entries: " << File->getName() << "\n");
965 for (Symbol *Sym : File->getSymbols())
966 if (Sym->isLocal())
967 AddSymbol(Sym);
968 }
Sam Cleggd3052d52018-01-18 23:40:49 +0000969}
970
Sam Cleggc375e4e2018-01-10 19:18:22 +0000971uint32_t Writer::lookupType(const WasmSignature &Sig) {
Sam Clegg8d027d62018-01-10 20:12:26 +0000972 auto It = TypeIndices.find(Sig);
973 if (It == TypeIndices.end()) {
Sam Cleggc375e4e2018-01-10 19:18:22 +0000974 error("type not found: " + toString(Sig));
Sam Clegg8d027d62018-01-10 20:12:26 +0000975 return 0;
976 }
977 return It->second;
Sam Cleggc375e4e2018-01-10 19:18:22 +0000978}
979
980uint32_t Writer::registerType(const WasmSignature &Sig) {
Sam Cleggb8621592017-11-30 01:40:08 +0000981 auto Pair = TypeIndices.insert(std::make_pair(Sig, Types.size()));
Sam Cleggc375e4e2018-01-10 19:18:22 +0000982 if (Pair.second) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000983 LLVM_DEBUG(dbgs() << "type " << toString(Sig) << "\n");
Sam Cleggb8621592017-11-30 01:40:08 +0000984 Types.push_back(&Sig);
Sam Cleggc375e4e2018-01-10 19:18:22 +0000985 }
Sam Cleggb8621592017-11-30 01:40:08 +0000986 return Pair.first->second;
987}
988
Sam Cleggc94d3932017-11-17 18:14:09 +0000989void Writer::calculateTypes() {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000990 // The output type section is the union of the following sets:
991 // 1. Any signature used in the TYPE relocation
992 // 2. The signatures of all imported functions
993 // 3. The signatures of all defined functions
Heejin Ahne915a712018-12-08 06:17:43 +0000994 // 4. The signatures of all imported events
995 // 5. The signatures of all defined events
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000996
Sam Cleggc94d3932017-11-17 18:14:09 +0000997 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000998 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
999 for (uint32_t I = 0; I < Types.size(); I++)
1000 if (File->TypeIsUsed[I])
1001 File->TypeMap[I] = registerType(Types[I]);
Sam Cleggc94d3932017-11-17 18:14:09 +00001002 }
Sam Clegg50686852018-01-12 18:35:13 +00001003
Heejin Ahne915a712018-12-08 06:17:43 +00001004 for (const Symbol *Sym : ImportedSymbols) {
Sam Clegg93102972018-02-23 05:08:53 +00001005 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
Heejin Ahne915a712018-12-08 06:17:43 +00001006 registerType(*F->Signature);
1007 else if (auto *E = dyn_cast<EventSymbol>(Sym))
1008 registerType(*E->Signature);
1009 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +00001010
Sam Clegg9f934222018-02-21 18:29:23 +00001011 for (const InputFunction *F : InputFunctions)
Sam Clegg8f6d2de2018-01-31 23:48:14 +00001012 registerType(F->Signature);
Heejin Ahne915a712018-12-08 06:17:43 +00001013
1014 for (const InputEvent *E : InputEvents)
1015 registerType(E->Signature);
Sam Cleggc94d3932017-11-17 18:14:09 +00001016}
1017
Sam Clegg8d146bb2018-01-09 23:56:44 +00001018void Writer::assignIndexes() {
Heejin Ahnaeaab992018-11-19 23:21:25 +00001019 assert(InputFunctions.empty());
1020 uint32_t FunctionIndex = NumImportedFunctions;
Nicholas Wilsonebda41f2018-03-09 16:43:05 +00001021 auto AddDefinedFunction = [&](InputFunction *Func) {
1022 if (!Func->Live)
1023 return;
1024 InputFunctions.emplace_back(Func);
Sam Clegge3f3ccf2018-03-12 19:56:23 +00001025 Func->setFunctionIndex(FunctionIndex++);
Nicholas Wilsonebda41f2018-03-09 16:43:05 +00001026 };
1027
Nicholas Wilson5639da82018-03-12 15:44:07 +00001028 for (InputFunction *Func : Symtab->SyntheticFunctions)
1029 AddDefinedFunction(Func);
1030
Sam Clegg87e61922018-01-08 23:39:11 +00001031 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001032 LLVM_DEBUG(dbgs() << "Functions: " << File->getName() << "\n");
Nicholas Wilsonebda41f2018-03-09 16:43:05 +00001033 for (InputFunction *Func : File->Functions)
1034 AddDefinedFunction(Func);
Sam Clegg8d146bb2018-01-09 23:56:44 +00001035 }
1036
Sam Cleggbfb75342018-11-15 00:37:21 +00001037 uint32_t TableIndex = TableBase;
Sam Clegg6c4dbfee2018-02-23 04:59:57 +00001038 auto HandleRelocs = [&](InputChunk *Chunk) {
1039 if (!Chunk->Live)
1040 return;
1041 ObjFile *File = Chunk->File;
1042 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
Sam Clegg93102972018-02-23 05:08:53 +00001043 for (const WasmRelocation &Reloc : Chunk->getRelocations()) {
Sam Clegg79e33172019-02-04 17:49:33 +00001044 if (Reloc.Type == R_WASM_TABLE_INDEX_I32 ||
1045 Reloc.Type == R_WASM_TABLE_INDEX_SLEB) {
Sam Clegg6c4dbfee2018-02-23 04:59:57 +00001046 FunctionSymbol *Sym = File->getFunctionSymbol(Reloc.Index);
Sam Clegge3f3ccf2018-03-12 19:56:23 +00001047 if (Sym->hasTableIndex() || !Sym->hasFunctionIndex())
Sam Clegg6c4dbfee2018-02-23 04:59:57 +00001048 continue;
1049 Sym->setTableIndex(TableIndex++);
1050 IndirectFunctions.emplace_back(Sym);
Sam Clegg79e33172019-02-04 17:49:33 +00001051 } else if (Reloc.Type == R_WASM_TYPE_INDEX_LEB) {
Sam Clegg93102972018-02-23 05:08:53 +00001052 // Mark target type as live
Sam Clegg6c4dbfee2018-02-23 04:59:57 +00001053 File->TypeMap[Reloc.Index] = registerType(Types[Reloc.Index]);
1054 File->TypeIsUsed[Reloc.Index] = true;
1055 }
1056 }
1057 };
1058
Sam Clegg8d146bb2018-01-09 23:56:44 +00001059 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001060 LLVM_DEBUG(dbgs() << "Handle relocs: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +00001061 for (InputChunk *Chunk : File->Functions)
1062 HandleRelocs(Chunk);
1063 for (InputChunk *Chunk : File->Segments)
1064 HandleRelocs(Chunk);
Sam Cleggd177ab22018-05-04 23:14:42 +00001065 for (auto &P : File->CustomSections)
1066 HandleRelocs(P);
Sam Clegg93102972018-02-23 05:08:53 +00001067 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +00001068
Heejin Ahnaeaab992018-11-19 23:21:25 +00001069 assert(InputGlobals.empty());
1070 uint32_t GlobalIndex = NumImportedGlobals;
Sam Clegg93102972018-02-23 05:08:53 +00001071 auto AddDefinedGlobal = [&](InputGlobal *Global) {
1072 if (Global->Live) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001073 LLVM_DEBUG(dbgs() << "AddDefinedGlobal: " << GlobalIndex << "\n");
Sam Clegge3f3ccf2018-03-12 19:56:23 +00001074 Global->setGlobalIndex(GlobalIndex++);
Sam Clegg93102972018-02-23 05:08:53 +00001075 InputGlobals.push_back(Global);
1076 }
1077 };
1078
Nicholas Wilsonebda41f2018-03-09 16:43:05 +00001079 for (InputGlobal *Global : Symtab->SyntheticGlobals)
1080 AddDefinedGlobal(Global);
Sam Clegg93102972018-02-23 05:08:53 +00001081
1082 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001083 LLVM_DEBUG(dbgs() << "Globals: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +00001084 for (InputGlobal *Global : File->Globals)
1085 AddDefinedGlobal(Global);
Sam Cleggc94d3932017-11-17 18:14:09 +00001086 }
Heejin Ahne915a712018-12-08 06:17:43 +00001087
1088 assert(InputEvents.empty());
1089 uint32_t EventIndex = NumImportedEvents;
1090 auto AddDefinedEvent = [&](InputEvent *Event) {
1091 if (Event->Live) {
1092 LLVM_DEBUG(dbgs() << "AddDefinedEvent: " << EventIndex << "\n");
1093 Event->setEventIndex(EventIndex++);
1094 InputEvents.push_back(Event);
1095 }
1096 };
1097
1098 for (ObjFile *File : Symtab->ObjectFiles) {
1099 LLVM_DEBUG(dbgs() << "Events: " << File->getName() << "\n");
1100 for (InputEvent *Event : File->Events)
1101 AddDefinedEvent(Event);
1102 }
Sam Cleggc94d3932017-11-17 18:14:09 +00001103}
1104
1105static StringRef getOutputDataSegmentName(StringRef Name) {
Sam Cleggbfb75342018-11-15 00:37:21 +00001106 // With PIC code we currently only support a single data segment since
1107 // we only have a single __memory_base to use as our base address.
1108 if (Config->Pic)
1109 return "data";
Sam Clegg66844762018-05-10 18:23:51 +00001110 if (!Config->MergeDataSegments)
Sam Cleggc94d3932017-11-17 18:14:09 +00001111 return Name;
Rui Ueyama4764b572018-02-28 00:57:28 +00001112 if (Name.startswith(".text."))
1113 return ".text";
1114 if (Name.startswith(".data."))
1115 return ".data";
1116 if (Name.startswith(".bss."))
1117 return ".bss";
Sam Clegg57694c52018-08-08 18:02:55 +00001118 if (Name.startswith(".rodata."))
1119 return ".rodata";
Sam Cleggc94d3932017-11-17 18:14:09 +00001120 return Name;
1121}
1122
1123void Writer::createOutputSegments() {
1124 for (ObjFile *File : Symtab->ObjectFiles) {
1125 for (InputSegment *Segment : File->Segments) {
Sam Clegg447ae402018-02-13 20:29:38 +00001126 if (!Segment->Live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +00001127 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +00001128 StringRef Name = getOutputDataSegmentName(Segment->getName());
1129 OutputSegment *&S = SegmentMap[Name];
1130 if (S == nullptr) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001131 LLVM_DEBUG(dbgs() << "new segment: " << Name << "\n");
Sam Clegg93102972018-02-23 05:08:53 +00001132 S = make<OutputSegment>(Name, Segments.size());
Sam Cleggc94d3932017-11-17 18:14:09 +00001133 Segments.push_back(S);
1134 }
1135 S->addInputSegment(Segment);
Nicola Zaghene7245b42018-05-15 13:36:20 +00001136 LLVM_DEBUG(dbgs() << "added data: " << Name << ": " << S->Size << "\n");
Sam Cleggc94d3932017-11-17 18:14:09 +00001137 }
1138 }
1139}
1140
Sam Clegg50686852018-01-12 18:35:13 +00001141static const int OPCODE_CALL = 0x10;
1142static const int OPCODE_END = 0xb;
1143
1144// Create synthetic "__wasm_call_ctors" function based on ctor functions
1145// in input object.
1146void Writer::createCtorFunction() {
Sam Clegg0e6b42f2019-03-01 22:35:47 +00001147 if (!WasmSym::CallCtors->isLive())
1148 return;
1149
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +00001150 // First write the body's contents to a string.
1151 std::string BodyContent;
Sam Clegg50686852018-01-12 18:35:13 +00001152 {
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +00001153 raw_string_ostream OS(BodyContent);
Sam Clegg50686852018-01-12 18:35:13 +00001154 writeUleb128(OS, 0, "num locals");
Sam Clegg93102972018-02-23 05:08:53 +00001155 for (const WasmInitEntry &F : InitFunctions) {
Sam Clegg50686852018-01-12 18:35:13 +00001156 writeU8(OS, OPCODE_CALL, "CALL");
Sam Clegge3f3ccf2018-03-12 19:56:23 +00001157 writeUleb128(OS, F.Sym->getFunctionIndex(), "function index");
Sam Clegg50686852018-01-12 18:35:13 +00001158 }
1159 writeU8(OS, OPCODE_END, "END");
1160 }
1161
1162 // Once we know the size of the body we can create the final function body
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +00001163 std::string FunctionBody;
1164 {
1165 raw_string_ostream OS(FunctionBody);
1166 writeUleb128(OS, BodyContent.size(), "function size");
1167 OS << BodyContent;
1168 }
Rui Ueyama29abfe42018-02-28 17:43:15 +00001169
Sam Cleggea656472018-10-22 08:35:39 +00001170 ArrayRef<uint8_t> Body = arrayRefFromStringRef(Saver.save(FunctionBody));
Nicholas Wilsonebda41f2018-03-09 16:43:05 +00001171 cast<SyntheticFunction>(WasmSym::CallCtors->Function)->setBody(Body);
Sam Clegg50686852018-01-12 18:35:13 +00001172}
1173
1174// Populate InitFunctions vector with init functions from all input objects.
1175// This is then used either when creating the output linking section or to
1176// synthesize the "__wasm_call_ctors" function.
1177void Writer::calculateInitFunctions() {
Sam Clegg61f13b32019-03-02 04:55:02 +00001178 if (!Config->Relocatable && !WasmSym::CallCtors->isLive())
1179 return;
1180
Sam Clegg50686852018-01-12 18:35:13 +00001181 for (ObjFile *File : Symtab->ObjectFiles) {
1182 const WasmLinkingData &L = File->getWasmObj()->linkingData();
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +00001183 for (const WasmInitFunc &F : L.InitFunctions) {
1184 FunctionSymbol *Sym = File->getFunctionSymbol(F.Symbol);
Sam Clegg0e6b42f2019-03-01 22:35:47 +00001185 assert(Sym->isLive());
Heejin Ahne915a712018-12-08 06:17:43 +00001186 if (*Sym->Signature != WasmSignature{{}, {}})
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +00001187 error("invalid signature for init func: " + toString(*Sym));
1188 InitFunctions.emplace_back(WasmInitEntry{Sym, F.Priority});
1189 }
Sam Clegg50686852018-01-12 18:35:13 +00001190 }
Rui Ueyamada69b712018-02-28 00:15:59 +00001191
Sam Clegg50686852018-01-12 18:35:13 +00001192 // Sort in order of priority (lowest first) so that they are called
1193 // in the correct order.
Sam Clegg29b8feb2018-02-21 00:34:34 +00001194 std::stable_sort(InitFunctions.begin(), InitFunctions.end(),
Sam Clegg93102972018-02-23 05:08:53 +00001195 [](const WasmInitEntry &L, const WasmInitEntry &R) {
Sam Clegg29b8feb2018-02-21 00:34:34 +00001196 return L.Priority < R.Priority;
1197 });
Sam Clegg50686852018-01-12 18:35:13 +00001198}
1199
Sam Cleggc94d3932017-11-17 18:14:09 +00001200void Writer::run() {
Sam Cleggbfb75342018-11-15 00:37:21 +00001201 if (Config->Relocatable || Config->Pic)
Sam Clegg99eb42c2018-02-27 23:58:03 +00001202 Config->GlobalBase = 0;
1203
Sam Cleggbfb75342018-11-15 00:37:21 +00001204 // For PIC code the table base is assigned dynamically by the loader.
1205 // For non-PIC, we start at 1 so that accessing table index 0 always traps.
1206 if (!Config->Pic)
1207 TableBase = 1;
1208
Sam Cleggc94d3932017-11-17 18:14:09 +00001209 log("-- calculateImports");
1210 calculateImports();
Sam Clegg8d146bb2018-01-09 23:56:44 +00001211 log("-- assignIndexes");
1212 assignIndexes();
Sam Clegg50686852018-01-12 18:35:13 +00001213 log("-- calculateInitFunctions");
1214 calculateInitFunctions();
1215 if (!Config->Relocatable)
1216 createCtorFunction();
Sam Clegg8f6d2de2018-01-31 23:48:14 +00001217 log("-- calculateTypes");
1218 calculateTypes();
Sam Clegg93102972018-02-23 05:08:53 +00001219 log("-- layoutMemory");
1220 layoutMemory();
1221 log("-- calculateExports");
1222 calculateExports();
Sam Cleggd177ab22018-05-04 23:14:42 +00001223 log("-- calculateCustomSections");
1224 calculateCustomSections();
Sam Clegg93102972018-02-23 05:08:53 +00001225 log("-- assignSymtab");
1226 assignSymtab();
Sam Cleggc94d3932017-11-17 18:14:09 +00001227
1228 if (errorHandler().Verbose) {
Sam Clegg9f934222018-02-21 18:29:23 +00001229 log("Defined Functions: " + Twine(InputFunctions.size()));
Sam Clegg93102972018-02-23 05:08:53 +00001230 log("Defined Globals : " + Twine(InputGlobals.size()));
Heejin Ahne915a712018-12-08 06:17:43 +00001231 log("Defined Events : " + Twine(InputEvents.size()));
Sam Clegg93102972018-02-23 05:08:53 +00001232 log("Function Imports : " + Twine(NumImportedFunctions));
1233 log("Global Imports : " + Twine(NumImportedGlobals));
Heejin Ahne915a712018-12-08 06:17:43 +00001234 log("Event Imports : " + Twine(NumImportedEvents));
Sam Cleggc94d3932017-11-17 18:14:09 +00001235 for (ObjFile *File : Symtab->ObjectFiles)
1236 File->dumpInfo();
1237 }
1238
Sam Cleggc94d3932017-11-17 18:14:09 +00001239 createHeader();
1240 log("-- createSections");
1241 createSections();
1242
1243 log("-- openFile");
1244 openFile();
1245 if (errorCount())
1246 return;
1247
1248 writeHeader();
1249
1250 log("-- writeSections");
1251 writeSections();
1252 if (errorCount())
1253 return;
1254
1255 if (Error E = Buffer->commit())
1256 fatal("failed to write the output file: " + toString(std::move(E)));
1257}
1258
1259// Open a result file.
1260void Writer::openFile() {
1261 log("writing: " + Config->OutputFile);
Sam Cleggc94d3932017-11-17 18:14:09 +00001262
1263 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
1264 FileOutputBuffer::create(Config->OutputFile, FileSize,
1265 FileOutputBuffer::F_executable);
1266
1267 if (!BufferOrErr)
1268 error("failed to open " + Config->OutputFile + ": " +
1269 toString(BufferOrErr.takeError()));
1270 else
1271 Buffer = std::move(*BufferOrErr);
1272}
1273
1274void Writer::createHeader() {
1275 raw_string_ostream OS(Header);
1276 writeBytes(OS, WasmMagic, sizeof(WasmMagic), "wasm magic");
1277 writeU32(OS, WasmVersion, "wasm version");
1278 OS.flush();
1279 FileSize += Header.size();
1280}
1281
1282void lld::wasm::writeResult() { Writer().run(); }