blob: 42affb4168abe66923228f7c59bb9bae95e342a3 [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"
Sam Clegga688a422019-03-13 21:29:20 +000031#include "llvm/Support/Path.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000032
33#include <cstdarg>
Sam Clegge0f6fcd2018-01-12 22:25:17 +000034#include <map>
Sam Cleggc94d3932017-11-17 18:14:09 +000035
36#define DEBUG_TYPE "lld"
37
38using namespace llvm;
39using namespace llvm::wasm;
40using namespace lld;
41using namespace lld::wasm;
42
Heejin Ahna1cc4ea2019-02-04 19:13:46 +000043static constexpr int StackAlignment = 16;
44static constexpr const char *FunctionTableName = "__indirect_function_table";
45const char *lld::wasm::DefaultModule = "env";
Sam Cleggc94d3932017-11-17 18:14:09 +000046
47namespace {
48
Sam Clegg93102972018-02-23 05:08:53 +000049// An init entry to be written to either the synthetic init func or the
50// linking metadata.
51struct WasmInitEntry {
Sam Clegge3f3ccf2018-03-12 19:56:23 +000052 const FunctionSymbol *Sym;
Sam Clegg93102972018-02-23 05:08:53 +000053 uint32_t Priority;
Sam Cleggd3052d52018-01-18 23:40:49 +000054};
55
Sam Cleggc94d3932017-11-17 18:14:09 +000056// The writer writes a SymbolTable result to a file.
57class Writer {
58public:
59 void run();
60
61private:
62 void openFile();
63
Sam Cleggc375e4e2018-01-10 19:18:22 +000064 uint32_t lookupType(const WasmSignature &Sig);
65 uint32_t registerType(const WasmSignature &Sig);
Sam Clegg93102972018-02-23 05:08:53 +000066
Sam Clegg50686852018-01-12 18:35:13 +000067 void createCtorFunction();
68 void calculateInitFunctions();
Sam Clegg8d146bb2018-01-09 23:56:44 +000069 void assignIndexes();
Sam Cleggc94d3932017-11-17 18:14:09 +000070 void calculateImports();
Sam Cleggd3052d52018-01-18 23:40:49 +000071 void calculateExports();
Sam Cleggd177ab22018-05-04 23:14:42 +000072 void calculateCustomSections();
Sam Clegg93102972018-02-23 05:08:53 +000073 void assignSymtab();
Sam Cleggc94d3932017-11-17 18:14:09 +000074 void calculateTypes();
75 void createOutputSegments();
76 void layoutMemory();
77 void createHeader();
78 void createSections();
Nicholas Wilsondbd90bf2018-03-07 13:28:16 +000079 SyntheticSection *createSyntheticSection(uint32_t Type, StringRef Name = "");
Sam Cleggc94d3932017-11-17 18:14:09 +000080
81 // Builtin sections
82 void createTypeSection();
83 void createFunctionSection();
84 void createTableSection();
85 void createGlobalSection();
Heejin Ahne915a712018-12-08 06:17:43 +000086 void createEventSection();
Sam Cleggc94d3932017-11-17 18:14:09 +000087 void createExportSection();
88 void createImportSection();
89 void createMemorySection();
90 void createElemSection();
Sam Cleggc94d3932017-11-17 18:14:09 +000091 void createCodeSection();
92 void createDataSection();
Sam Clegg80ba4382018-04-10 16:12:49 +000093 void createCustomSections();
Sam Cleggc94d3932017-11-17 18:14:09 +000094
95 // Custom sections
Sam Cleggbfb75342018-11-15 00:37:21 +000096 void createDylinkSection();
Sam Cleggc94d3932017-11-17 18:14:09 +000097 void createRelocSections();
98 void createLinkingSection();
99 void createNameSection();
Thomas Lively2a0868f2019-01-17 02:29:41 +0000100 void createProducersSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000101
102 void writeHeader();
103 void writeSections();
104
105 uint64_t FileSize = 0;
Sam Cleggbfb75342018-11-15 00:37:21 +0000106 uint32_t TableBase = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000107 uint32_t NumMemoryPages = 0;
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000108 uint32_t MaxMemoryPages = 0;
Sam Cleggbfb75342018-11-15 00:37:21 +0000109 // Memory size and aligment. Written to the "dylink" section
110 // when build with -shared or -pie.
111 uint32_t MemAlign = 0;
112 uint32_t MemSize = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000113
114 std::vector<const WasmSignature *> Types;
Nicholas Wilson3e3f5fb2018-03-14 15:58:16 +0000115 DenseMap<WasmSignature, int32_t> TypeIndices;
Sam Clegg93102972018-02-23 05:08:53 +0000116 std::vector<const Symbol *> ImportedSymbols;
117 unsigned NumImportedFunctions = 0;
118 unsigned NumImportedGlobals = 0;
Heejin Ahne915a712018-12-08 06:17:43 +0000119 unsigned NumImportedEvents = 0;
Sam Cleggd6beb322018-05-10 18:10:34 +0000120 std::vector<WasmExport> Exports;
Sam Clegg93102972018-02-23 05:08:53 +0000121 std::vector<const DefinedData *> DefinedFakeGlobals;
122 std::vector<InputGlobal *> InputGlobals;
Sam Clegg9f934222018-02-21 18:29:23 +0000123 std::vector<InputFunction *> InputFunctions;
Heejin Ahne915a712018-12-08 06:17:43 +0000124 std::vector<InputEvent *> InputEvents;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000125 std::vector<const FunctionSymbol *> IndirectFunctions;
Sam Clegg93102972018-02-23 05:08:53 +0000126 std::vector<const Symbol *> SymtabEntries;
127 std::vector<WasmInitEntry> InitFunctions;
Sam Cleggc94d3932017-11-17 18:14:09 +0000128
Sam Clegg80ba4382018-04-10 16:12:49 +0000129 llvm::StringMap<std::vector<InputSection *>> CustomSectionMapping;
Sam Cleggd177ab22018-05-04 23:14:42 +0000130 llvm::StringMap<SectionSymbol *> CustomSectionSymbols;
Sam Clegg80ba4382018-04-10 16:12:49 +0000131
Sam Cleggc94d3932017-11-17 18:14:09 +0000132 // Elements that are used to construct the final output
133 std::string Header;
134 std::vector<OutputSection *> OutputSections;
135
136 std::unique_ptr<FileOutputBuffer> Buffer;
137
138 std::vector<OutputSegment *> Segments;
139 llvm::SmallDenseMap<StringRef, OutputSegment *> SegmentMap;
140};
141
142} // anonymous namespace
143
Sam Cleggc94d3932017-11-17 18:14:09 +0000144void Writer::createImportSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000145 uint32_t NumImports = ImportedSymbols.size();
Sam Cleggc94d3932017-11-17 18:14:09 +0000146 if (Config->ImportMemory)
147 ++NumImports;
Nicholas Wilsonfc90b302018-03-28 12:53:29 +0000148 if (Config->ImportTable)
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000149 ++NumImports;
Sam Cleggc94d3932017-11-17 18:14:09 +0000150
151 if (NumImports == 0)
152 return;
153
154 SyntheticSection *Section = createSyntheticSection(WASM_SEC_IMPORT);
155 raw_ostream &OS = Section->getStream();
156
157 writeUleb128(OS, NumImports, "import count");
158
Sam Cleggc94d3932017-11-17 18:14:09 +0000159 if (Config->ImportMemory) {
160 WasmImport Import;
Heejin Ahna1cc4ea2019-02-04 19:13:46 +0000161 Import.Module = DefaultModule;
Sam Cleggc94d3932017-11-17 18:14:09 +0000162 Import.Field = "memory";
163 Import.Kind = WASM_EXTERNAL_MEMORY;
164 Import.Memory.Flags = 0;
165 Import.Memory.Initial = NumMemoryPages;
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000166 if (MaxMemoryPages != 0) {
167 Import.Memory.Flags |= WASM_LIMITS_FLAG_HAS_MAX;
168 Import.Memory.Maximum = MaxMemoryPages;
169 }
Derek Schuff786760a2018-11-06 18:02:39 +0000170 if (Config->SharedMemory)
Derek Schuff3bea8bc2018-11-06 17:59:32 +0000171 Import.Memory.Flags |= WASM_LIMITS_FLAG_IS_SHARED;
Sam Cleggc94d3932017-11-17 18:14:09 +0000172 writeImport(OS, Import);
173 }
174
Nicholas Wilsonfc90b302018-03-28 12:53:29 +0000175 if (Config->ImportTable) {
Sam Cleggbfb75342018-11-15 00:37:21 +0000176 uint32_t TableSize = TableBase + IndirectFunctions.size();
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000177 WasmImport Import;
Heejin Ahna1cc4ea2019-02-04 19:13:46 +0000178 Import.Module = DefaultModule;
179 Import.Field = FunctionTableName;
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000180 Import.Kind = WASM_EXTERNAL_TABLE;
Thomas Lively25ff8932019-01-08 06:25:55 +0000181 Import.Table.ElemType = WASM_TYPE_FUNCREF;
Sam Clegg748f59cae2018-12-03 22:37:55 +0000182 Import.Table.Limits = {0, TableSize, 0};
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000183 writeImport(OS, Import);
184 }
185
Sam Clegg93102972018-02-23 05:08:53 +0000186 for (const Symbol *Sym : ImportedSymbols) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000187 WasmImport Import;
Dan Gohman9b84eea2019-02-07 22:00:48 +0000188 if (auto *F = dyn_cast<UndefinedFunction>(Sym)) {
189 Import.Field = F->ImportName;
190 Import.Module = F->ImportModule;
191 } else if (auto *G = dyn_cast<UndefinedGlobal>(Sym)) {
192 Import.Field = G->ImportName;
193 Import.Module = G->ImportModule;
194 } else {
195 Import.Field = Sym->getName();
Heejin Ahna1cc4ea2019-02-04 19:13:46 +0000196 Import.Module = DefaultModule;
Dan Gohman9b84eea2019-02-07 22:00:48 +0000197 }
Sam Clegg7cc07532019-02-01 02:29:57 +0000198
Sam Clegg93102972018-02-23 05:08:53 +0000199 if (auto *FunctionSym = dyn_cast<FunctionSymbol>(Sym)) {
200 Import.Kind = WASM_EXTERNAL_FUNCTION;
Heejin Ahne915a712018-12-08 06:17:43 +0000201 Import.SigIndex = lookupType(*FunctionSym->Signature);
Sam Cleggd425d6b2019-03-12 21:53:23 +0000202 } else if (auto *DataSym = dyn_cast<UndefinedData>(Sym)) {
203 Import.Kind = WASM_EXTERNAL_GLOBAL;
204 Import.Global = {WASM_TYPE_I32, true};
Heejin Ahne915a712018-12-08 06:17:43 +0000205 } else if (auto *GlobalSym = dyn_cast<GlobalSymbol>(Sym)) {
Sam Clegg93102972018-02-23 05:08:53 +0000206 Import.Kind = WASM_EXTERNAL_GLOBAL;
207 Import.Global = *GlobalSym->getGlobalType();
Heejin Ahne915a712018-12-08 06:17:43 +0000208 } else {
209 auto *EventSym = cast<EventSymbol>(Sym);
210 Import.Kind = WASM_EXTERNAL_EVENT;
211 Import.Event.Attribute = EventSym->getEventType()->Attribute;
212 Import.Event.SigIndex = lookupType(*EventSym->Signature);
Sam Clegg93102972018-02-23 05:08:53 +0000213 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000214 writeImport(OS, Import);
215 }
216}
217
218void Writer::createTypeSection() {
219 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TYPE);
220 raw_ostream &OS = Section->getStream();
221 writeUleb128(OS, Types.size(), "type count");
Sam Cleggd451da12017-12-19 19:56:27 +0000222 for (const WasmSignature *Sig : Types)
Sam Cleggc94d3932017-11-17 18:14:09 +0000223 writeSig(OS, *Sig);
Sam Cleggc94d3932017-11-17 18:14:09 +0000224}
225
226void Writer::createFunctionSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000227 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000228 return;
229
230 SyntheticSection *Section = createSyntheticSection(WASM_SEC_FUNCTION);
231 raw_ostream &OS = Section->getStream();
232
Sam Clegg9f934222018-02-21 18:29:23 +0000233 writeUleb128(OS, InputFunctions.size(), "function count");
234 for (const InputFunction *Func : InputFunctions)
Sam Cleggc375e4e2018-01-10 19:18:22 +0000235 writeUleb128(OS, lookupType(Func->Signature), "sig index");
Sam Cleggc94d3932017-11-17 18:14:09 +0000236}
237
238void Writer::createMemorySection() {
239 if (Config->ImportMemory)
240 return;
241
242 SyntheticSection *Section = createSyntheticSection(WASM_SEC_MEMORY);
243 raw_ostream &OS = Section->getStream();
244
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000245 bool HasMax = MaxMemoryPages != 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000246 writeUleb128(OS, 1, "memory count");
Derek Schuff786760a2018-11-06 18:02:39 +0000247 unsigned Flags = 0;
248 if (HasMax)
249 Flags |= WASM_LIMITS_FLAG_HAS_MAX;
Derek Schuff3bea8bc2018-11-06 17:59:32 +0000250 if (Config->SharedMemory)
251 Flags |= WASM_LIMITS_FLAG_IS_SHARED;
252 writeUleb128(OS, Flags, "memory limits flags");
Sam Cleggc94d3932017-11-17 18:14:09 +0000253 writeUleb128(OS, NumMemoryPages, "initial pages");
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000254 if (HasMax)
255 writeUleb128(OS, MaxMemoryPages, "max pages");
Sam Cleggc94d3932017-11-17 18:14:09 +0000256}
257
258void Writer::createGlobalSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000259 unsigned NumGlobals = InputGlobals.size() + DefinedFakeGlobals.size();
260 if (NumGlobals == 0)
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000261 return;
262
Sam Cleggc94d3932017-11-17 18:14:09 +0000263 SyntheticSection *Section = createSyntheticSection(WASM_SEC_GLOBAL);
264 raw_ostream &OS = Section->getStream();
265
Sam Clegg93102972018-02-23 05:08:53 +0000266 writeUleb128(OS, NumGlobals, "global count");
267 for (const InputGlobal *G : InputGlobals)
268 writeGlobal(OS, G->Global);
269 for (const DefinedData *Sym : DefinedFakeGlobals) {
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000270 WasmGlobal Global;
Sam Clegg93102972018-02-23 05:08:53 +0000271 Global.Type = {WASM_TYPE_I32, false};
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000272 Global.InitExpr.Opcode = WASM_OPCODE_I32_CONST;
273 Global.InitExpr.Value.Int32 = Sym->getVirtualAddress();
Sam Cleggc94d3932017-11-17 18:14:09 +0000274 writeGlobal(OS, Global);
275 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000276}
277
Heejin Ahne915a712018-12-08 06:17:43 +0000278// The event section contains a list of declared wasm events associated with the
279// module. Currently the only supported event kind is exceptions. A single event
280// entry represents a single event with an event tag. All C++ exceptions are
281// represented by a single event. An event entry in this section contains
282// information on what kind of event it is (e.g. exception) and the type of
283// values contained in a single event object. (In wasm, an event can contain
284// multiple values of primitive types. But for C++ exceptions, we just throw a
285// pointer which is an i32 value (for wasm32 architecture), so the signature of
286// C++ exception is (i32)->(void), because all event types are assumed to have
287// void return type to share WasmSignature with functions.)
288void Writer::createEventSection() {
289 unsigned NumEvents = InputEvents.size();
290 if (NumEvents == 0)
291 return;
292
293 SyntheticSection *Section = createSyntheticSection(WASM_SEC_EVENT);
294 raw_ostream &OS = Section->getStream();
295
296 writeUleb128(OS, NumEvents, "event count");
297 for (InputEvent *E : InputEvents) {
298 E->Event.Type.SigIndex = lookupType(E->Signature);
299 writeEvent(OS, E->Event);
300 }
301}
302
Sam Cleggc94d3932017-11-17 18:14:09 +0000303void Writer::createTableSection() {
Nicholas Wilsonfc90b302018-03-28 12:53:29 +0000304 if (Config->ImportTable)
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000305 return;
306
307 // Always output a table section (or table import), even if there are no
308 // indirect calls. There are two reasons for this:
Sam Cleggfc1a9122017-12-11 22:00:56 +0000309 // 1. For executables it is useful to have an empty table slot at 0
310 // which can be filled with a null function call handler.
311 // 2. If we don't do this, any program that contains a call_indirect but
312 // no address-taken function will fail at validation time since it is
313 // a validation error to include a call_indirect instruction if there
314 // is not table.
Sam Cleggbfb75342018-11-15 00:37:21 +0000315 uint32_t TableSize = TableBase + IndirectFunctions.size();
Sam Cleggfc1a9122017-12-11 22:00:56 +0000316
Sam Cleggc94d3932017-11-17 18:14:09 +0000317 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TABLE);
318 raw_ostream &OS = Section->getStream();
319
320 writeUleb128(OS, 1, "table count");
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000321 WasmLimits Limits = {WASM_LIMITS_FLAG_HAS_MAX, TableSize, TableSize};
Thomas Lively25ff8932019-01-08 06:25:55 +0000322 writeTableType(OS, WasmTable{WASM_TYPE_FUNCREF, Limits});
Sam Cleggc94d3932017-11-17 18:14:09 +0000323}
324
325void Writer::createExportSection() {
Sam Cleggd6beb322018-05-10 18:10:34 +0000326 if (!Exports.size())
Sam Cleggc94d3932017-11-17 18:14:09 +0000327 return;
328
329 SyntheticSection *Section = createSyntheticSection(WASM_SEC_EXPORT);
330 raw_ostream &OS = Section->getStream();
331
Sam Cleggd6beb322018-05-10 18:10:34 +0000332 writeUleb128(OS, Exports.size(), "export count");
333 for (const WasmExport &Export : Exports)
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000334 writeExport(OS, Export);
Sam Cleggc94d3932017-11-17 18:14:09 +0000335}
336
Sam Cleggd177ab22018-05-04 23:14:42 +0000337void Writer::calculateCustomSections() {
338 log("calculateCustomSections");
339 bool StripDebug = Config->StripDebug || Config->StripAll;
340 for (ObjFile *File : Symtab->ObjectFiles) {
341 for (InputSection *Section : File->CustomSections) {
342 StringRef Name = Section->getName();
343 // These custom sections are known the linker and synthesized rather than
344 // blindly copied
Thomas Lively2a0868f2019-01-17 02:29:41 +0000345 if (Name == "linking" || Name == "name" || Name == "producers" ||
346 Name.startswith("reloc."))
Sam Cleggd177ab22018-05-04 23:14:42 +0000347 continue;
348 // .. or it is a debug section
349 if (StripDebug && Name.startswith(".debug_"))
350 continue;
351 CustomSectionMapping[Name].push_back(Section);
352 }
353 }
354}
355
Sam Clegg80ba4382018-04-10 16:12:49 +0000356void Writer::createCustomSections() {
357 log("createCustomSections");
Sam Clegg80ba4382018-04-10 16:12:49 +0000358 for (auto &Pair : CustomSectionMapping) {
359 StringRef Name = Pair.first();
Sam Cleggd177ab22018-05-04 23:14:42 +0000360
361 auto P = CustomSectionSymbols.find(Name);
362 if (P != CustomSectionSymbols.end()) {
363 uint32_t SectionIndex = OutputSections.size();
364 P->second->setOutputSectionIndex(SectionIndex);
365 }
366
Nicola Zaghene7245b42018-05-15 13:36:20 +0000367 LLVM_DEBUG(dbgs() << "createCustomSection: " << Name << "\n");
Sam Clegg80ba4382018-04-10 16:12:49 +0000368 OutputSections.push_back(make<CustomSection>(Name, Pair.second));
369 }
370}
371
Sam Cleggc94d3932017-11-17 18:14:09 +0000372void Writer::createElemSection() {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000373 if (IndirectFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000374 return;
375
376 SyntheticSection *Section = createSyntheticSection(WASM_SEC_ELEM);
377 raw_ostream &OS = Section->getStream();
378
379 writeUleb128(OS, 1, "segment count");
380 writeUleb128(OS, 0, "table index");
381 WasmInitExpr InitExpr;
Sam Cleggbfb75342018-11-15 00:37:21 +0000382 if (Config->Pic) {
Thomas Lively25ff8932019-01-08 06:25:55 +0000383 InitExpr.Opcode = WASM_OPCODE_GLOBAL_GET;
Sam Clegg2dad4e22018-11-15 18:15:54 +0000384 InitExpr.Value.Global = WasmSym::TableBase->getGlobalIndex();
Sam Cleggbfb75342018-11-15 00:37:21 +0000385 } else {
386 InitExpr.Opcode = WASM_OPCODE_I32_CONST;
387 InitExpr.Value.Int32 = TableBase;
388 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000389 writeInitExpr(OS, InitExpr);
Sam Cleggfc1a9122017-12-11 22:00:56 +0000390 writeUleb128(OS, IndirectFunctions.size(), "elem count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000391
Sam Cleggbfb75342018-11-15 00:37:21 +0000392 uint32_t TableIndex = TableBase;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000393 for (const FunctionSymbol *Sym : IndirectFunctions) {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000394 assert(Sym->getTableIndex() == TableIndex);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000395 writeUleb128(OS, Sym->getFunctionIndex(), "function index");
Sam Cleggfc1a9122017-12-11 22:00:56 +0000396 ++TableIndex;
397 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000398}
399
400void Writer::createCodeSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000401 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000402 return;
403
404 log("createCodeSection");
405
Sam Clegg9f934222018-02-21 18:29:23 +0000406 auto Section = make<CodeSection>(InputFunctions);
Sam Cleggc94d3932017-11-17 18:14:09 +0000407 OutputSections.push_back(Section);
408}
409
410void Writer::createDataSection() {
411 if (!Segments.size())
412 return;
413
414 log("createDataSection");
415 auto Section = make<DataSection>(Segments);
416 OutputSections.push_back(Section);
417}
418
Sam Cleggd451da12017-12-19 19:56:27 +0000419// Create relocations sections in the final output.
Sam Cleggc94d3932017-11-17 18:14:09 +0000420// These are only created when relocatable output is requested.
421void Writer::createRelocSections() {
422 log("createRelocSections");
423 // Don't use iterator here since we are adding to OutputSection
424 size_t OrigSize = OutputSections.size();
Rui Ueyamaffa650a2018-04-24 23:09:57 +0000425 for (size_t I = 0; I < OrigSize; I++) {
426 OutputSection *OSec = OutputSections[I];
Rui Ueyama37254062018-02-28 00:01:31 +0000427 uint32_t Count = OSec->numRelocations();
Sam Cleggc94d3932017-11-17 18:14:09 +0000428 if (!Count)
429 continue;
430
Rui Ueyama37254062018-02-28 00:01:31 +0000431 StringRef Name;
432 if (OSec->Type == WASM_SEC_DATA)
433 Name = "reloc.DATA";
434 else if (OSec->Type == WASM_SEC_CODE)
435 Name = "reloc.CODE";
Sam Cleggd177ab22018-05-04 23:14:42 +0000436 else if (OSec->Type == WASM_SEC_CUSTOM)
437 Name = Saver.save("reloc." + OSec->Name);
Sam Cleggc94d3932017-11-17 18:14:09 +0000438 else
Sam Cleggd177ab22018-05-04 23:14:42 +0000439 llvm_unreachable(
440 "relocations only supported for code, data, or custom sections");
Sam Cleggc94d3932017-11-17 18:14:09 +0000441
Rui Ueyama37254062018-02-28 00:01:31 +0000442 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, Name);
Sam Cleggc94d3932017-11-17 18:14:09 +0000443 raw_ostream &OS = Section->getStream();
Rui Ueyamaffa650a2018-04-24 23:09:57 +0000444 writeUleb128(OS, I, "reloc section");
Sam Cleggc94d3932017-11-17 18:14:09 +0000445 writeUleb128(OS, Count, "reloc count");
Rui Ueyama37254062018-02-28 00:01:31 +0000446 OSec->writeRelocations(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000447 }
448}
449
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000450static uint32_t getWasmFlags(const Symbol *Sym) {
451 uint32_t Flags = 0;
452 if (Sym->isLocal())
453 Flags |= WASM_SYMBOL_BINDING_LOCAL;
454 if (Sym->isWeak())
455 Flags |= WASM_SYMBOL_BINDING_WEAK;
456 if (Sym->isHidden())
457 Flags |= WASM_SYMBOL_VISIBILITY_HIDDEN;
458 if (Sym->isUndefined())
459 Flags |= WASM_SYMBOL_UNDEFINED;
Dan Gohman9b84eea2019-02-07 22:00:48 +0000460 if (auto *F = dyn_cast<UndefinedFunction>(Sym)) {
461 if (F->getName() != F->ImportName)
462 Flags |= WASM_SYMBOL_EXPLICIT_NAME;
463 } else if (auto *G = dyn_cast<UndefinedGlobal>(Sym)) {
464 if (G->getName() != G->ImportName)
465 Flags |= WASM_SYMBOL_EXPLICIT_NAME;
466 }
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000467 return Flags;
468}
469
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000470// Some synthetic sections (e.g. "name" and "linking") have subsections.
471// Just like the synthetic sections themselves these need to be created before
472// they can be written out (since they are preceded by their length). This
473// class is used to create subsections and then write them into the stream
474// of the parent section.
475class SubSection {
476public:
477 explicit SubSection(uint32_t Type) : Type(Type) {}
478
479 void writeTo(raw_ostream &To) {
480 OS.flush();
Rui Ueyama67769102018-02-28 03:38:14 +0000481 writeUleb128(To, Type, "subsection type");
482 writeUleb128(To, Body.size(), "subsection size");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000483 To.write(Body.data(), Body.size());
484 }
485
486private:
487 uint32_t Type;
488 std::string Body;
489
490public:
491 raw_string_ostream OS{Body};
492};
493
Sam Cleggbfb75342018-11-15 00:37:21 +0000494// Create the custom "dylink" section containing information for the dynamic
495// linker.
496// See
497// https://github.com/WebAssembly/tool-conventions/blob/master/DynamicLinking.md
498void Writer::createDylinkSection() {
499 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "dylink");
500 raw_ostream &OS = Section->getStream();
501
502 writeUleb128(OS, MemSize, "MemSize");
Sam Clegg6320efb2019-01-16 01:43:21 +0000503 writeUleb128(OS, MemAlign, "MemAlign");
Sam Cleggbfb75342018-11-15 00:37:21 +0000504 writeUleb128(OS, IndirectFunctions.size(), "TableSize");
505 writeUleb128(OS, 0, "TableAlign");
Sam Clegga688a422019-03-13 21:29:20 +0000506 writeUleb128(OS, Symtab->SharedFiles.size(), "Needed");
507 for (auto *SO : Symtab->SharedFiles)
508 writeStr(OS, llvm::sys::path::filename(SO->getName()), "so name");
Sam Cleggbfb75342018-11-15 00:37:21 +0000509}
510
Sam Clegg49ed9262017-12-01 00:53:21 +0000511// Create the custom "linking" section containing linker metadata.
Sam Cleggc94d3932017-11-17 18:14:09 +0000512// This is only created when relocatable output is requested.
513void Writer::createLinkingSection() {
514 SyntheticSection *Section =
515 createSyntheticSection(WASM_SEC_CUSTOM, "linking");
516 raw_ostream &OS = Section->getStream();
517
Sam Clegg2b8b1792018-04-26 18:17:21 +0000518 writeUleb128(OS, WasmMetadataVersion, "Version");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000519
Sam Clegg93102972018-02-23 05:08:53 +0000520 if (!SymtabEntries.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000521 SubSection Sub(WASM_SYMBOL_TABLE);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000522 writeUleb128(Sub.OS, SymtabEntries.size(), "num symbols");
523
Sam Clegg93102972018-02-23 05:08:53 +0000524 for (const Symbol *Sym : SymtabEntries) {
525 assert(Sym->isDefined() || Sym->isUndefined());
526 WasmSymbolType Kind = Sym->getWasmType();
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000527 uint32_t Flags = getWasmFlags(Sym);
528
Sam Clegg8518e7d2018-03-01 18:06:39 +0000529 writeU8(Sub.OS, Kind, "sym kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000530 writeUleb128(Sub.OS, Flags, "sym flags");
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000531
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000532 if (auto *F = dyn_cast<FunctionSymbol>(Sym)) {
533 writeUleb128(Sub.OS, F->getFunctionIndex(), "index");
Dan Gohman9b84eea2019-02-07 22:00:48 +0000534 if (Sym->isDefined() ||
535 (Flags & WASM_SYMBOL_EXPLICIT_NAME) != 0)
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000536 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000537 } else if (auto *G = dyn_cast<GlobalSymbol>(Sym)) {
538 writeUleb128(Sub.OS, G->getGlobalIndex(), "index");
Dan Gohman9b84eea2019-02-07 22:00:48 +0000539 if (Sym->isDefined() ||
540 (Flags & WASM_SYMBOL_EXPLICIT_NAME) != 0)
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000541 writeStr(Sub.OS, Sym->getName(), "sym name");
Heejin Ahne915a712018-12-08 06:17:43 +0000542 } else if (auto *E = dyn_cast<EventSymbol>(Sym)) {
543 writeUleb128(Sub.OS, E->getEventIndex(), "index");
Dan Gohman9b84eea2019-02-07 22:00:48 +0000544 if (Sym->isDefined() ||
545 (Flags & WASM_SYMBOL_EXPLICIT_NAME) != 0)
Heejin Ahne915a712018-12-08 06:17:43 +0000546 writeStr(Sub.OS, Sym->getName(), "sym name");
Andrea Di Biagio25c1a2f2018-05-05 10:53:31 +0000547 } else if (isa<DataSymbol>(Sym)) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000548 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegg93102972018-02-23 05:08:53 +0000549 if (auto *DataSym = dyn_cast<DefinedData>(Sym)) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000550 writeUleb128(Sub.OS, DataSym->getOutputSegmentIndex(), "index");
551 writeUleb128(Sub.OS, DataSym->getOutputSegmentOffset(),
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000552 "data offset");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000553 writeUleb128(Sub.OS, DataSym->getSize(), "data size");
Sam Clegg93102972018-02-23 05:08:53 +0000554 }
Sam Cleggd177ab22018-05-04 23:14:42 +0000555 } else {
556 auto *S = cast<SectionSymbol>(Sym);
557 writeUleb128(Sub.OS, S->getOutputSectionIndex(), "sym section index");
Sam Clegg93102972018-02-23 05:08:53 +0000558 }
Sam Cleggd3052d52018-01-18 23:40:49 +0000559 }
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000560
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000561 Sub.writeTo(OS);
Sam Cleggd3052d52018-01-18 23:40:49 +0000562 }
563
Sam Clegg0d0dd392017-12-19 17:09:45 +0000564 if (Segments.size()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000565 SubSection Sub(WASM_SEGMENT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000566 writeUleb128(Sub.OS, Segments.size(), "num data segments");
Sam Cleggc94d3932017-11-17 18:14:09 +0000567 for (const OutputSegment *S : Segments) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000568 writeStr(Sub.OS, S->Name, "segment name");
569 writeUleb128(Sub.OS, S->Alignment, "alignment");
570 writeUleb128(Sub.OS, 0, "flags");
Sam Cleggc94d3932017-11-17 18:14:09 +0000571 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000572 Sub.writeTo(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000573 }
Sam Clegg0d0dd392017-12-19 17:09:45 +0000574
Sam Clegg0d0dd392017-12-19 17:09:45 +0000575 if (!InitFunctions.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000576 SubSection Sub(WASM_INIT_FUNCS);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000577 writeUleb128(Sub.OS, InitFunctions.size(), "num init functions");
Sam Clegg93102972018-02-23 05:08:53 +0000578 for (const WasmInitEntry &F : InitFunctions) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000579 writeUleb128(Sub.OS, F.Priority, "priority");
580 writeUleb128(Sub.OS, F.Sym->getOutputSymbolIndex(), "function index");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000581 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000582 Sub.writeTo(OS);
Sam Clegg0d0dd392017-12-19 17:09:45 +0000583 }
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000584
Nicholas Wilsondbd90bf2018-03-07 13:28:16 +0000585 struct ComdatEntry {
586 unsigned Kind;
587 uint32_t Index;
588 };
589 std::map<StringRef, std::vector<ComdatEntry>> Comdats;
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000590
Sam Clegg9f934222018-02-21 18:29:23 +0000591 for (const InputFunction *F : InputFunctions) {
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000592 StringRef Comdat = F->getComdatName();
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000593 if (!Comdat.empty())
594 Comdats[Comdat].emplace_back(
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000595 ComdatEntry{WASM_COMDAT_FUNCTION, F->getFunctionIndex()});
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000596 }
597 for (uint32_t I = 0; I < Segments.size(); ++I) {
Sam Cleggf98bccf2018-01-13 15:57:48 +0000598 const auto &InputSegments = Segments[I]->InputSegments;
599 if (InputSegments.empty())
600 continue;
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000601 StringRef Comdat = InputSegments[0]->getComdatName();
Sam Clegga697df522018-01-13 15:59:53 +0000602#ifndef NDEBUG
Sam Cleggf98bccf2018-01-13 15:57:48 +0000603 for (const InputSegment *IS : InputSegments)
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000604 assert(IS->getComdatName() == Comdat);
Sam Clegga697df522018-01-13 15:59:53 +0000605#endif
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000606 if (!Comdat.empty())
607 Comdats[Comdat].emplace_back(ComdatEntry{WASM_COMDAT_DATA, I});
608 }
609
610 if (!Comdats.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000611 SubSection Sub(WASM_COMDAT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000612 writeUleb128(Sub.OS, Comdats.size(), "num comdats");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000613 for (const auto &C : Comdats) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000614 writeStr(Sub.OS, C.first, "comdat name");
615 writeUleb128(Sub.OS, 0, "comdat flags"); // flags for future use
616 writeUleb128(Sub.OS, C.second.size(), "num entries");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000617 for (const ComdatEntry &Entry : C.second) {
Sam Clegg8518e7d2018-03-01 18:06:39 +0000618 writeU8(Sub.OS, Entry.Kind, "entry kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000619 writeUleb128(Sub.OS, Entry.Index, "entry index");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000620 }
621 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000622 Sub.writeTo(OS);
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000623 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000624}
625
626// Create the custom "name" section containing debug symbol names.
627void Writer::createNameSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000628 unsigned NumNames = NumImportedFunctions;
Sam Clegg9f934222018-02-21 18:29:23 +0000629 for (const InputFunction *F : InputFunctions)
Nicholas Wilson6c7fe302018-04-20 17:09:18 +0000630 if (!F->getName().empty() || !F->getDebugName().empty())
Sam Clegg1963d712018-01-17 20:19:04 +0000631 ++NumNames;
Sam Cleggc94d3932017-11-17 18:14:09 +0000632
Sam Clegg1963d712018-01-17 20:19:04 +0000633 if (NumNames == 0)
634 return;
Sam Clegg50686852018-01-12 18:35:13 +0000635
Sam Cleggc94d3932017-11-17 18:14:09 +0000636 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "name");
637
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000638 SubSection Sub(WASM_NAMES_FUNCTION);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000639 writeUleb128(Sub.OS, NumNames, "name count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000640
Sam Clegg93102972018-02-23 05:08:53 +0000641 // Names must appear in function index order. As it happens ImportedSymbols
642 // and InputFunctions are numbered in order with imported functions coming
Sam Clegg1963d712018-01-17 20:19:04 +0000643 // first.
Sam Clegg93102972018-02-23 05:08:53 +0000644 for (const Symbol *S : ImportedSymbols) {
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000645 if (auto *F = dyn_cast<FunctionSymbol>(S)) {
646 writeUleb128(Sub.OS, F->getFunctionIndex(), "func index");
Sam Clegg37125f02018-11-09 16:57:41 +0000647 writeStr(Sub.OS, toString(*S), "symbol name");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000648 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000649 }
Sam Clegg9f934222018-02-21 18:29:23 +0000650 for (const InputFunction *F : InputFunctions) {
Sam Clegg1963d712018-01-17 20:19:04 +0000651 if (!F->getName().empty()) {
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000652 writeUleb128(Sub.OS, F->getFunctionIndex(), "func index");
Nicholas Wilson6c7fe302018-04-20 17:09:18 +0000653 if (!F->getDebugName().empty()) {
654 writeStr(Sub.OS, F->getDebugName(), "symbol name");
655 } else {
Sam Clegg37125f02018-11-09 16:57:41 +0000656 writeStr(Sub.OS, maybeDemangleSymbol(F->getName()), "symbol name");
Nicholas Wilson6c7fe302018-04-20 17:09:18 +0000657 }
Sam Clegg1963d712018-01-17 20:19:04 +0000658 }
659 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000660
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000661 Sub.writeTo(Section->getStream());
Sam Cleggc94d3932017-11-17 18:14:09 +0000662}
663
Thomas Lively2a0868f2019-01-17 02:29:41 +0000664void Writer::createProducersSection() {
665 SmallVector<std::pair<std::string, std::string>, 8> Languages;
666 SmallVector<std::pair<std::string, std::string>, 8> Tools;
667 SmallVector<std::pair<std::string, std::string>, 8> SDKs;
668 for (ObjFile *File : Symtab->ObjectFiles) {
669 const WasmProducerInfo &Info = File->getWasmObj()->getProducerInfo();
670 for (auto &Producers : {std::make_pair(&Info.Languages, &Languages),
671 std::make_pair(&Info.Tools, &Tools),
672 std::make_pair(&Info.SDKs, &SDKs)})
673 for (auto &Producer : *Producers.first)
674 if (Producers.second->end() ==
675 std::find_if(Producers.second->begin(), Producers.second->end(),
676 [&](std::pair<std::string, std::string> Seen) {
677 return Seen.first == Producer.first;
678 }))
679 Producers.second->push_back(Producer);
680 }
681 int FieldCount =
682 int(!Languages.empty()) + int(!Tools.empty()) + int(!SDKs.empty());
683 if (FieldCount == 0)
684 return;
685 SyntheticSection *Section =
686 createSyntheticSection(WASM_SEC_CUSTOM, "producers");
687 auto &OS = Section->getStream();
688 writeUleb128(OS, FieldCount, "field count");
689 for (auto &Field :
690 {std::make_pair("language", Languages),
691 std::make_pair("processed-by", Tools), std::make_pair("sdk", SDKs)}) {
692 if (Field.second.empty())
693 continue;
694 writeStr(OS, Field.first, "field name");
695 writeUleb128(OS, Field.second.size(), "number of entries");
696 for (auto &Entry : Field.second) {
697 writeStr(OS, Entry.first, "producer name");
698 writeStr(OS, Entry.second, "producer version");
699 }
700 }
701}
702
Sam Cleggc94d3932017-11-17 18:14:09 +0000703void Writer::writeHeader() {
704 memcpy(Buffer->getBufferStart(), Header.data(), Header.size());
705}
706
707void Writer::writeSections() {
708 uint8_t *Buf = Buffer->getBufferStart();
709 parallelForEach(OutputSections, [Buf](OutputSection *S) { S->writeTo(Buf); });
710}
711
712// Fix the memory layout of the output binary. This assigns memory offsets
Sam Clegg49ed9262017-12-01 00:53:21 +0000713// to each of the input data sections as well as the explicit stack region.
Sam Clegga0f095e2018-05-03 17:21:53 +0000714// The default memory layout is as follows, from low to high.
715//
Sam Cleggf0d433d2018-02-02 22:59:56 +0000716// - initialized data (starting at Config->GlobalBase)
717// - BSS data (not currently implemented in llvm)
718// - explicit stack (Config->ZStackSize)
719// - heap start / unallocated
Sam Clegga0f095e2018-05-03 17:21:53 +0000720//
721// The --stack-first option means that stack is placed before any static data.
Heejin Ahn4821ebf2018-08-29 21:03:16 +0000722// This can be useful since it means that stack overflow traps immediately
723// rather than overwriting global data, but also increases code size since all
724// static data loads and stores requires larger offsets.
Sam Cleggc94d3932017-11-17 18:14:09 +0000725void Writer::layoutMemory() {
Sam Cleggc94d3932017-11-17 18:14:09 +0000726 createOutputSegments();
727
Sam Clegga0f095e2018-05-03 17:21:53 +0000728 uint32_t MemoryPtr = 0;
729
730 auto PlaceStack = [&]() {
Sam Cleggbfb75342018-11-15 00:37:21 +0000731 if (Config->Relocatable || Config->Shared)
Sam Clegga0f095e2018-05-03 17:21:53 +0000732 return;
Heejin Ahna1cc4ea2019-02-04 19:13:46 +0000733 MemoryPtr = alignTo(MemoryPtr, StackAlignment);
734 if (Config->ZStackSize != alignTo(Config->ZStackSize, StackAlignment))
735 error("stack size must be " + Twine(StackAlignment) + "-byte aligned");
Sam Clegga0f095e2018-05-03 17:21:53 +0000736 log("mem: stack size = " + Twine(Config->ZStackSize));
737 log("mem: stack base = " + Twine(MemoryPtr));
738 MemoryPtr += Config->ZStackSize;
Sam Clegg2dad4e22018-11-15 18:15:54 +0000739 auto *SP = cast<DefinedGlobal>(WasmSym::StackPointer);
740 SP->Global->Global.InitExpr.Value.Int32 = MemoryPtr;
Sam Clegga0f095e2018-05-03 17:21:53 +0000741 log("mem: stack top = " + Twine(MemoryPtr));
742 };
743
744 if (Config->StackFirst) {
745 PlaceStack();
746 } else {
747 MemoryPtr = Config->GlobalBase;
748 log("mem: global base = " + Twine(Config->GlobalBase));
749 }
750
751 uint32_t DataStart = MemoryPtr;
752
Sam Cleggf0d433d2018-02-02 22:59:56 +0000753 // Arbitrarily set __dso_handle handle to point to the start of the data
754 // segments.
755 if (WasmSym::DsoHandle)
Sam Clegga0f095e2018-05-03 17:21:53 +0000756 WasmSym::DsoHandle->setVirtualAddress(DataStart);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000757
Sam Cleggbfb75342018-11-15 00:37:21 +0000758 MemAlign = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000759 for (OutputSegment *Seg : Segments) {
Sam Cleggbfb75342018-11-15 00:37:21 +0000760 MemAlign = std::max(MemAlign, Seg->Alignment);
Sam Clegg622ad042019-01-17 22:09:09 +0000761 MemoryPtr = alignTo(MemoryPtr, 1ULL << Seg->Alignment);
Sam Cleggc94d3932017-11-17 18:14:09 +0000762 Seg->StartVA = MemoryPtr;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000763 log(formatv("mem: {0,-15} offset={1,-8} size={2,-8} align={3}", Seg->Name,
764 MemoryPtr, Seg->Size, Seg->Alignment));
Sam Cleggc94d3932017-11-17 18:14:09 +0000765 MemoryPtr += Seg->Size;
766 }
767
Sam Cleggf0d433d2018-02-02 22:59:56 +0000768 // TODO: Add .bss space here.
Sam Clegg37a4a8a2018-02-07 03:04:53 +0000769 if (WasmSym::DataEnd)
770 WasmSym::DataEnd->setVirtualAddress(MemoryPtr);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000771
Sam Clegga0f095e2018-05-03 17:21:53 +0000772 log("mem: static data = " + Twine(MemoryPtr - DataStart));
Sam Cleggc94d3932017-11-17 18:14:09 +0000773
Sam Clegg2dad4e22018-11-15 18:15:54 +0000774 if (Config->Shared) {
775 MemSize = MemoryPtr;
776 return;
777 }
778
Sam Clegga0f095e2018-05-03 17:21:53 +0000779 if (!Config->StackFirst)
780 PlaceStack();
781
782 // Set `__heap_base` to directly follow the end of the stack or global data.
783 // The fact that this comes last means that a malloc/brk implementation
784 // can grow the heap at runtime.
Sam Cleggc94d3932017-11-17 18:14:09 +0000785 if (!Config->Relocatable) {
Sam Cleggf0d433d2018-02-02 22:59:56 +0000786 WasmSym::HeapBase->setVirtualAddress(MemoryPtr);
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000787 log("mem: heap base = " + Twine(MemoryPtr));
Sam Cleggc94d3932017-11-17 18:14:09 +0000788 }
789
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000790 if (Config->InitialMemory != 0) {
791 if (Config->InitialMemory != alignTo(Config->InitialMemory, WasmPageSize))
792 error("initial memory must be " + Twine(WasmPageSize) + "-byte aligned");
793 if (MemoryPtr > Config->InitialMemory)
794 error("initial memory too small, " + Twine(MemoryPtr) + " bytes needed");
795 else
796 MemoryPtr = Config->InitialMemory;
797 }
Sam Cleggbfb75342018-11-15 00:37:21 +0000798 MemSize = MemoryPtr;
799 NumMemoryPages = alignTo(MemoryPtr, WasmPageSize) / WasmPageSize;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000800 log("mem: total pages = " + Twine(NumMemoryPages));
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000801
802 if (Config->MaxMemory != 0) {
803 if (Config->MaxMemory != alignTo(Config->MaxMemory, WasmPageSize))
804 error("maximum memory must be " + Twine(WasmPageSize) + "-byte aligned");
805 if (MemoryPtr > Config->MaxMemory)
806 error("maximum memory too small, " + Twine(MemoryPtr) + " bytes needed");
807 MaxMemoryPages = Config->MaxMemory / WasmPageSize;
808 log("mem: max pages = " + Twine(MaxMemoryPages));
809 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000810}
811
812SyntheticSection *Writer::createSyntheticSection(uint32_t Type,
Sam Cleggc375e4e2018-01-10 19:18:22 +0000813 StringRef Name) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000814 auto Sec = make<SyntheticSection>(Type, Name);
Sam Cleggab2ac292017-12-20 05:14:48 +0000815 log("createSection: " + toString(*Sec));
Sam Cleggc94d3932017-11-17 18:14:09 +0000816 OutputSections.push_back(Sec);
817 return Sec;
818}
819
820void Writer::createSections() {
821 // Known sections
Sam Cleggbfb75342018-11-15 00:37:21 +0000822 if (Config->Pic)
823 createDylinkSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000824 createTypeSection();
825 createImportSection();
826 createFunctionSection();
827 createTableSection();
828 createMemorySection();
829 createGlobalSection();
Heejin Ahne915a712018-12-08 06:17:43 +0000830 createEventSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000831 createExportSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000832 createElemSection();
833 createCodeSection();
834 createDataSection();
Sam Clegg80ba4382018-04-10 16:12:49 +0000835 createCustomSections();
Sam Cleggc94d3932017-11-17 18:14:09 +0000836
837 // Custom sections
Sam Clegg99eb42c2018-02-27 23:58:03 +0000838 if (Config->Relocatable) {
Sam Clegg99eb42c2018-02-27 23:58:03 +0000839 createLinkingSection();
Nicholas Wilson94d3b162018-03-05 12:33:58 +0000840 createRelocSections();
Sam Clegg99eb42c2018-02-27 23:58:03 +0000841 }
Thomas Lively2a0868f2019-01-17 02:29:41 +0000842
Sam Cleggc94d3932017-11-17 18:14:09 +0000843 if (!Config->StripDebug && !Config->StripAll)
844 createNameSection();
845
Thomas Lively2a0868f2019-01-17 02:29:41 +0000846 if (!Config->StripAll)
847 createProducersSection();
848
Sam Cleggc94d3932017-11-17 18:14:09 +0000849 for (OutputSection *S : OutputSections) {
850 S->setOffset(FileSize);
851 S->finalizeContents();
852 FileSize += S->getSize();
853 }
854}
855
Sam Cleggc94d3932017-11-17 18:14:09 +0000856void Writer::calculateImports() {
Sam Clegg574d7ce2017-12-15 19:23:49 +0000857 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000858 if (!Sym->isUndefined())
859 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000860 if (Sym->isWeak() && !Config->Relocatable)
Sam Clegg574d7ce2017-12-15 19:23:49 +0000861 continue;
Nicholas Wilsona1e299f2018-04-20 17:18:06 +0000862 if (!Sym->isLive())
863 continue;
Sam Cleggc729c1b2018-05-30 18:07:52 +0000864 if (!Sym->IsUsedInRegularObj)
865 continue;
Sam Cleggd425d6b2019-03-12 21:53:23 +0000866 // In relocatable output we don't generate imports for data symbols.
867 // These live only in the symbol table.
868 if (Config->Relocatable && isa<DataSymbol>(Sym))
869 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000870
Nicola Zaghene7245b42018-05-15 13:36:20 +0000871 LLVM_DEBUG(dbgs() << "import: " << Sym->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000872 ImportedSymbols.emplace_back(Sym);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000873 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
874 F->setFunctionIndex(NumImportedFunctions++);
Heejin Ahne915a712018-12-08 06:17:43 +0000875 else if (auto *G = dyn_cast<GlobalSymbol>(Sym))
876 G->setGlobalIndex(NumImportedGlobals++);
Sam Cleggd425d6b2019-03-12 21:53:23 +0000877 else if (auto *D = dyn_cast<UndefinedData>(Sym))
878 D->setGlobalIndex(NumImportedGlobals++);
Sam Clegg93102972018-02-23 05:08:53 +0000879 else
Heejin Ahne915a712018-12-08 06:17:43 +0000880 cast<EventSymbol>(Sym)->setEventIndex(NumImportedEvents++);
Sam Cleggc94d3932017-11-17 18:14:09 +0000881 }
882}
883
Sam Cleggd3052d52018-01-18 23:40:49 +0000884void Writer::calculateExports() {
Sam Clegg93102972018-02-23 05:08:53 +0000885 if (Config->Relocatable)
886 return;
Sam Cleggf0d433d2018-02-02 22:59:56 +0000887
Sam Cleggd6beb322018-05-10 18:10:34 +0000888 if (!Config->Relocatable && !Config->ImportMemory)
889 Exports.push_back(WasmExport{"memory", WASM_EXTERNAL_MEMORY, 0});
890
891 if (!Config->Relocatable && Config->ExportTable)
Heejin Ahna1cc4ea2019-02-04 19:13:46 +0000892 Exports.push_back(WasmExport{FunctionTableName, WASM_EXTERNAL_TABLE, 0});
Sam Cleggd6beb322018-05-10 18:10:34 +0000893
894 unsigned FakeGlobalIndex = NumImportedGlobals + InputGlobals.size();
895
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000896 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Cleggce004bf2018-06-28 17:04:58 +0000897 if (!Sym->isExported())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000898 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000899 if (!Sym->isLive())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000900 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000901
Sam Cleggd6beb322018-05-10 18:10:34 +0000902 StringRef Name = Sym->getName();
903 WasmExport Export;
904 if (auto *F = dyn_cast<DefinedFunction>(Sym)) {
905 Export = {Name, WASM_EXTERNAL_FUNCTION, F->getFunctionIndex()};
906 } else if (auto *G = dyn_cast<DefinedGlobal>(Sym)) {
Sam Clegg177b4582018-06-07 01:27:07 +0000907 // TODO(sbc): Remove this check once to mutable global proposal is
908 // implement in all major browsers.
909 // See: https://github.com/WebAssembly/mutable-global
910 if (G->getGlobalType()->Mutable) {
911 // Only the __stack_pointer should ever be create as mutable.
912 assert(G == WasmSym::StackPointer);
913 continue;
914 }
Sam Cleggd6beb322018-05-10 18:10:34 +0000915 Export = {Name, WASM_EXTERNAL_GLOBAL, G->getGlobalIndex()};
Heejin Ahne915a712018-12-08 06:17:43 +0000916 } else if (auto *E = dyn_cast<DefinedEvent>(Sym)) {
917 Export = {Name, WASM_EXTERNAL_EVENT, E->getEventIndex()};
Sam Cleggd6beb322018-05-10 18:10:34 +0000918 } else {
919 auto *D = cast<DefinedData>(Sym);
Sam Clegg93102972018-02-23 05:08:53 +0000920 DefinedFakeGlobals.emplace_back(D);
Sam Cleggd6beb322018-05-10 18:10:34 +0000921 Export = {Name, WASM_EXTERNAL_GLOBAL, FakeGlobalIndex++};
922 }
923
Nicola Zaghene7245b42018-05-15 13:36:20 +0000924 LLVM_DEBUG(dbgs() << "Export: " << Name << "\n");
Sam Cleggd6beb322018-05-10 18:10:34 +0000925 Exports.push_back(Export);
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000926 }
Sam Clegg93102972018-02-23 05:08:53 +0000927}
928
929void Writer::assignSymtab() {
930 if (!Config->Relocatable)
931 return;
932
Sam Cleggd177ab22018-05-04 23:14:42 +0000933 StringMap<uint32_t> SectionSymbolIndices;
934
Sam Clegg93102972018-02-23 05:08:53 +0000935 unsigned SymbolIndex = SymtabEntries.size();
Sam Cleggd177ab22018-05-04 23:14:42 +0000936
Sam Clegg89e4dcb2019-01-30 18:55:15 +0000937 auto AddSymbol = [&](Symbol *Sym) {
938 if (auto *S = dyn_cast<SectionSymbol>(Sym)) {
939 StringRef Name = S->getName();
940 if (CustomSectionMapping.count(Name) == 0)
941 return;
Sam Cleggd177ab22018-05-04 23:14:42 +0000942
Sam Clegg89e4dcb2019-01-30 18:55:15 +0000943 auto SSI = SectionSymbolIndices.find(Name);
944 if (SSI != SectionSymbolIndices.end()) {
945 Sym->setOutputSymbolIndex(SSI->second);
946 return;
Sam Cleggd177ab22018-05-04 23:14:42 +0000947 }
948
Sam Clegg89e4dcb2019-01-30 18:55:15 +0000949 SectionSymbolIndices[Name] = SymbolIndex;
950 CustomSectionSymbols[Name] = cast<SectionSymbol>(Sym);
Sam Cleggd3052d52018-01-18 23:40:49 +0000951
Sam Clegg89e4dcb2019-01-30 18:55:15 +0000952 Sym->markLive();
953 }
954
955 // (Since this is relocatable output, GC is not performed so symbols must
956 // be live.)
957 assert(Sym->isLive());
958 Sym->setOutputSymbolIndex(SymbolIndex++);
959 SymtabEntries.emplace_back(Sym);
960 };
961
962 for (Symbol *Sym : Symtab->getSymbols())
Sam Cleggd15a41542019-03-08 21:10:48 +0000963 if (Sym->IsUsedInRegularObj)
Sam Clegg89e4dcb2019-01-30 18:55:15 +0000964 AddSymbol(Sym);
965
966 for (ObjFile *File : Symtab->ObjectFiles) {
967 LLVM_DEBUG(dbgs() << "Local symtab entries: " << File->getName() << "\n");
968 for (Symbol *Sym : File->getSymbols())
969 if (Sym->isLocal())
970 AddSymbol(Sym);
971 }
Sam Cleggd3052d52018-01-18 23:40:49 +0000972}
973
Sam Cleggc375e4e2018-01-10 19:18:22 +0000974uint32_t Writer::lookupType(const WasmSignature &Sig) {
Sam Clegg8d027d62018-01-10 20:12:26 +0000975 auto It = TypeIndices.find(Sig);
976 if (It == TypeIndices.end()) {
Sam Cleggc375e4e2018-01-10 19:18:22 +0000977 error("type not found: " + toString(Sig));
Sam Clegg8d027d62018-01-10 20:12:26 +0000978 return 0;
979 }
980 return It->second;
Sam Cleggc375e4e2018-01-10 19:18:22 +0000981}
982
983uint32_t Writer::registerType(const WasmSignature &Sig) {
Sam Cleggb8621592017-11-30 01:40:08 +0000984 auto Pair = TypeIndices.insert(std::make_pair(Sig, Types.size()));
Sam Cleggc375e4e2018-01-10 19:18:22 +0000985 if (Pair.second) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000986 LLVM_DEBUG(dbgs() << "type " << toString(Sig) << "\n");
Sam Cleggb8621592017-11-30 01:40:08 +0000987 Types.push_back(&Sig);
Sam Cleggc375e4e2018-01-10 19:18:22 +0000988 }
Sam Cleggb8621592017-11-30 01:40:08 +0000989 return Pair.first->second;
990}
991
Sam Cleggc94d3932017-11-17 18:14:09 +0000992void Writer::calculateTypes() {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000993 // The output type section is the union of the following sets:
994 // 1. Any signature used in the TYPE relocation
995 // 2. The signatures of all imported functions
996 // 3. The signatures of all defined functions
Heejin Ahne915a712018-12-08 06:17:43 +0000997 // 4. The signatures of all imported events
998 // 5. The signatures of all defined events
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000999
Sam Cleggc94d3932017-11-17 18:14:09 +00001000 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +00001001 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
1002 for (uint32_t I = 0; I < Types.size(); I++)
1003 if (File->TypeIsUsed[I])
1004 File->TypeMap[I] = registerType(Types[I]);
Sam Cleggc94d3932017-11-17 18:14:09 +00001005 }
Sam Clegg50686852018-01-12 18:35:13 +00001006
Heejin Ahne915a712018-12-08 06:17:43 +00001007 for (const Symbol *Sym : ImportedSymbols) {
Sam Clegg93102972018-02-23 05:08:53 +00001008 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
Heejin Ahne915a712018-12-08 06:17:43 +00001009 registerType(*F->Signature);
1010 else if (auto *E = dyn_cast<EventSymbol>(Sym))
1011 registerType(*E->Signature);
1012 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +00001013
Sam Clegg9f934222018-02-21 18:29:23 +00001014 for (const InputFunction *F : InputFunctions)
Sam Clegg8f6d2de2018-01-31 23:48:14 +00001015 registerType(F->Signature);
Heejin Ahne915a712018-12-08 06:17:43 +00001016
1017 for (const InputEvent *E : InputEvents)
1018 registerType(E->Signature);
Sam Cleggc94d3932017-11-17 18:14:09 +00001019}
1020
Sam Clegg8d146bb2018-01-09 23:56:44 +00001021void Writer::assignIndexes() {
Heejin Ahnaeaab992018-11-19 23:21:25 +00001022 assert(InputFunctions.empty());
1023 uint32_t FunctionIndex = NumImportedFunctions;
Nicholas Wilsonebda41f2018-03-09 16:43:05 +00001024 auto AddDefinedFunction = [&](InputFunction *Func) {
1025 if (!Func->Live)
1026 return;
1027 InputFunctions.emplace_back(Func);
Sam Clegge3f3ccf2018-03-12 19:56:23 +00001028 Func->setFunctionIndex(FunctionIndex++);
Nicholas Wilsonebda41f2018-03-09 16:43:05 +00001029 };
1030
Nicholas Wilson5639da82018-03-12 15:44:07 +00001031 for (InputFunction *Func : Symtab->SyntheticFunctions)
1032 AddDefinedFunction(Func);
1033
Sam Clegg87e61922018-01-08 23:39:11 +00001034 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001035 LLVM_DEBUG(dbgs() << "Functions: " << File->getName() << "\n");
Nicholas Wilsonebda41f2018-03-09 16:43:05 +00001036 for (InputFunction *Func : File->Functions)
1037 AddDefinedFunction(Func);
Sam Clegg8d146bb2018-01-09 23:56:44 +00001038 }
1039
Sam Cleggbfb75342018-11-15 00:37:21 +00001040 uint32_t TableIndex = TableBase;
Sam Clegg6c4dbfee2018-02-23 04:59:57 +00001041 auto HandleRelocs = [&](InputChunk *Chunk) {
1042 if (!Chunk->Live)
1043 return;
1044 ObjFile *File = Chunk->File;
1045 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
Sam Clegg93102972018-02-23 05:08:53 +00001046 for (const WasmRelocation &Reloc : Chunk->getRelocations()) {
Sam Clegg79e33172019-02-04 17:49:33 +00001047 if (Reloc.Type == R_WASM_TABLE_INDEX_I32 ||
1048 Reloc.Type == R_WASM_TABLE_INDEX_SLEB) {
Sam Clegg6c4dbfee2018-02-23 04:59:57 +00001049 FunctionSymbol *Sym = File->getFunctionSymbol(Reloc.Index);
Sam Clegge3f3ccf2018-03-12 19:56:23 +00001050 if (Sym->hasTableIndex() || !Sym->hasFunctionIndex())
Sam Clegg6c4dbfee2018-02-23 04:59:57 +00001051 continue;
1052 Sym->setTableIndex(TableIndex++);
1053 IndirectFunctions.emplace_back(Sym);
Sam Clegg79e33172019-02-04 17:49:33 +00001054 } else if (Reloc.Type == R_WASM_TYPE_INDEX_LEB) {
Sam Clegg93102972018-02-23 05:08:53 +00001055 // Mark target type as live
Sam Clegg6c4dbfee2018-02-23 04:59:57 +00001056 File->TypeMap[Reloc.Index] = registerType(Types[Reloc.Index]);
1057 File->TypeIsUsed[Reloc.Index] = true;
1058 }
1059 }
1060 };
1061
Sam Clegg8d146bb2018-01-09 23:56:44 +00001062 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001063 LLVM_DEBUG(dbgs() << "Handle relocs: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +00001064 for (InputChunk *Chunk : File->Functions)
1065 HandleRelocs(Chunk);
1066 for (InputChunk *Chunk : File->Segments)
1067 HandleRelocs(Chunk);
Sam Cleggd177ab22018-05-04 23:14:42 +00001068 for (auto &P : File->CustomSections)
1069 HandleRelocs(P);
Sam Clegg93102972018-02-23 05:08:53 +00001070 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +00001071
Heejin Ahnaeaab992018-11-19 23:21:25 +00001072 assert(InputGlobals.empty());
1073 uint32_t GlobalIndex = NumImportedGlobals;
Sam Clegg93102972018-02-23 05:08:53 +00001074 auto AddDefinedGlobal = [&](InputGlobal *Global) {
1075 if (Global->Live) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001076 LLVM_DEBUG(dbgs() << "AddDefinedGlobal: " << GlobalIndex << "\n");
Sam Clegge3f3ccf2018-03-12 19:56:23 +00001077 Global->setGlobalIndex(GlobalIndex++);
Sam Clegg93102972018-02-23 05:08:53 +00001078 InputGlobals.push_back(Global);
1079 }
1080 };
1081
Nicholas Wilsonebda41f2018-03-09 16:43:05 +00001082 for (InputGlobal *Global : Symtab->SyntheticGlobals)
1083 AddDefinedGlobal(Global);
Sam Clegg93102972018-02-23 05:08:53 +00001084
1085 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001086 LLVM_DEBUG(dbgs() << "Globals: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +00001087 for (InputGlobal *Global : File->Globals)
1088 AddDefinedGlobal(Global);
Sam Cleggc94d3932017-11-17 18:14:09 +00001089 }
Heejin Ahne915a712018-12-08 06:17:43 +00001090
1091 assert(InputEvents.empty());
1092 uint32_t EventIndex = NumImportedEvents;
1093 auto AddDefinedEvent = [&](InputEvent *Event) {
1094 if (Event->Live) {
1095 LLVM_DEBUG(dbgs() << "AddDefinedEvent: " << EventIndex << "\n");
1096 Event->setEventIndex(EventIndex++);
1097 InputEvents.push_back(Event);
1098 }
1099 };
1100
1101 for (ObjFile *File : Symtab->ObjectFiles) {
1102 LLVM_DEBUG(dbgs() << "Events: " << File->getName() << "\n");
1103 for (InputEvent *Event : File->Events)
1104 AddDefinedEvent(Event);
1105 }
Sam Cleggc94d3932017-11-17 18:14:09 +00001106}
1107
1108static StringRef getOutputDataSegmentName(StringRef Name) {
Sam Cleggbfb75342018-11-15 00:37:21 +00001109 // With PIC code we currently only support a single data segment since
1110 // we only have a single __memory_base to use as our base address.
1111 if (Config->Pic)
1112 return "data";
Sam Clegg66844762018-05-10 18:23:51 +00001113 if (!Config->MergeDataSegments)
Sam Cleggc94d3932017-11-17 18:14:09 +00001114 return Name;
Rui Ueyama4764b572018-02-28 00:57:28 +00001115 if (Name.startswith(".text."))
1116 return ".text";
1117 if (Name.startswith(".data."))
1118 return ".data";
1119 if (Name.startswith(".bss."))
1120 return ".bss";
Sam Clegg57694c52018-08-08 18:02:55 +00001121 if (Name.startswith(".rodata."))
1122 return ".rodata";
Sam Cleggc94d3932017-11-17 18:14:09 +00001123 return Name;
1124}
1125
1126void Writer::createOutputSegments() {
1127 for (ObjFile *File : Symtab->ObjectFiles) {
1128 for (InputSegment *Segment : File->Segments) {
Sam Clegg447ae402018-02-13 20:29:38 +00001129 if (!Segment->Live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +00001130 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +00001131 StringRef Name = getOutputDataSegmentName(Segment->getName());
1132 OutputSegment *&S = SegmentMap[Name];
1133 if (S == nullptr) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001134 LLVM_DEBUG(dbgs() << "new segment: " << Name << "\n");
Sam Clegg93102972018-02-23 05:08:53 +00001135 S = make<OutputSegment>(Name, Segments.size());
Sam Cleggc94d3932017-11-17 18:14:09 +00001136 Segments.push_back(S);
1137 }
1138 S->addInputSegment(Segment);
Nicola Zaghene7245b42018-05-15 13:36:20 +00001139 LLVM_DEBUG(dbgs() << "added data: " << Name << ": " << S->Size << "\n");
Sam Cleggc94d3932017-11-17 18:14:09 +00001140 }
1141 }
1142}
1143
Sam Clegg50686852018-01-12 18:35:13 +00001144static const int OPCODE_CALL = 0x10;
1145static const int OPCODE_END = 0xb;
1146
1147// Create synthetic "__wasm_call_ctors" function based on ctor functions
1148// in input object.
1149void Writer::createCtorFunction() {
Sam Clegg0e6b42f2019-03-01 22:35:47 +00001150 if (!WasmSym::CallCtors->isLive())
1151 return;
1152
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +00001153 // First write the body's contents to a string.
1154 std::string BodyContent;
Sam Clegg50686852018-01-12 18:35:13 +00001155 {
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +00001156 raw_string_ostream OS(BodyContent);
Sam Clegg50686852018-01-12 18:35:13 +00001157 writeUleb128(OS, 0, "num locals");
Sam Clegg93102972018-02-23 05:08:53 +00001158 for (const WasmInitEntry &F : InitFunctions) {
Sam Clegg50686852018-01-12 18:35:13 +00001159 writeU8(OS, OPCODE_CALL, "CALL");
Sam Clegge3f3ccf2018-03-12 19:56:23 +00001160 writeUleb128(OS, F.Sym->getFunctionIndex(), "function index");
Sam Clegg50686852018-01-12 18:35:13 +00001161 }
1162 writeU8(OS, OPCODE_END, "END");
1163 }
1164
1165 // Once we know the size of the body we can create the final function body
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +00001166 std::string FunctionBody;
1167 {
1168 raw_string_ostream OS(FunctionBody);
1169 writeUleb128(OS, BodyContent.size(), "function size");
1170 OS << BodyContent;
1171 }
Rui Ueyama29abfe42018-02-28 17:43:15 +00001172
Sam Cleggea656472018-10-22 08:35:39 +00001173 ArrayRef<uint8_t> Body = arrayRefFromStringRef(Saver.save(FunctionBody));
Nicholas Wilsonebda41f2018-03-09 16:43:05 +00001174 cast<SyntheticFunction>(WasmSym::CallCtors->Function)->setBody(Body);
Sam Clegg50686852018-01-12 18:35:13 +00001175}
1176
1177// Populate InitFunctions vector with init functions from all input objects.
1178// This is then used either when creating the output linking section or to
1179// synthesize the "__wasm_call_ctors" function.
1180void Writer::calculateInitFunctions() {
Sam Clegg61f13b32019-03-02 04:55:02 +00001181 if (!Config->Relocatable && !WasmSym::CallCtors->isLive())
1182 return;
1183
Sam Clegg50686852018-01-12 18:35:13 +00001184 for (ObjFile *File : Symtab->ObjectFiles) {
1185 const WasmLinkingData &L = File->getWasmObj()->linkingData();
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +00001186 for (const WasmInitFunc &F : L.InitFunctions) {
1187 FunctionSymbol *Sym = File->getFunctionSymbol(F.Symbol);
Sam Clegg0e6b42f2019-03-01 22:35:47 +00001188 assert(Sym->isLive());
Heejin Ahne915a712018-12-08 06:17:43 +00001189 if (*Sym->Signature != WasmSignature{{}, {}})
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +00001190 error("invalid signature for init func: " + toString(*Sym));
1191 InitFunctions.emplace_back(WasmInitEntry{Sym, F.Priority});
1192 }
Sam Clegg50686852018-01-12 18:35:13 +00001193 }
Rui Ueyamada69b712018-02-28 00:15:59 +00001194
Sam Clegg50686852018-01-12 18:35:13 +00001195 // Sort in order of priority (lowest first) so that they are called
1196 // in the correct order.
Sam Clegg29b8feb2018-02-21 00:34:34 +00001197 std::stable_sort(InitFunctions.begin(), InitFunctions.end(),
Sam Clegg93102972018-02-23 05:08:53 +00001198 [](const WasmInitEntry &L, const WasmInitEntry &R) {
Sam Clegg29b8feb2018-02-21 00:34:34 +00001199 return L.Priority < R.Priority;
1200 });
Sam Clegg50686852018-01-12 18:35:13 +00001201}
1202
Sam Cleggc94d3932017-11-17 18:14:09 +00001203void Writer::run() {
Sam Cleggbfb75342018-11-15 00:37:21 +00001204 if (Config->Relocatable || Config->Pic)
Sam Clegg99eb42c2018-02-27 23:58:03 +00001205 Config->GlobalBase = 0;
1206
Sam Cleggbfb75342018-11-15 00:37:21 +00001207 // For PIC code the table base is assigned dynamically by the loader.
1208 // For non-PIC, we start at 1 so that accessing table index 0 always traps.
1209 if (!Config->Pic)
1210 TableBase = 1;
1211
Sam Cleggc94d3932017-11-17 18:14:09 +00001212 log("-- calculateImports");
1213 calculateImports();
Sam Clegg8d146bb2018-01-09 23:56:44 +00001214 log("-- assignIndexes");
1215 assignIndexes();
Sam Clegg50686852018-01-12 18:35:13 +00001216 log("-- calculateInitFunctions");
1217 calculateInitFunctions();
1218 if (!Config->Relocatable)
1219 createCtorFunction();
Sam Clegg8f6d2de2018-01-31 23:48:14 +00001220 log("-- calculateTypes");
1221 calculateTypes();
Sam Clegg93102972018-02-23 05:08:53 +00001222 log("-- layoutMemory");
1223 layoutMemory();
1224 log("-- calculateExports");
1225 calculateExports();
Sam Cleggd177ab22018-05-04 23:14:42 +00001226 log("-- calculateCustomSections");
1227 calculateCustomSections();
Sam Clegg93102972018-02-23 05:08:53 +00001228 log("-- assignSymtab");
1229 assignSymtab();
Sam Cleggc94d3932017-11-17 18:14:09 +00001230
1231 if (errorHandler().Verbose) {
Sam Clegg9f934222018-02-21 18:29:23 +00001232 log("Defined Functions: " + Twine(InputFunctions.size()));
Sam Clegg93102972018-02-23 05:08:53 +00001233 log("Defined Globals : " + Twine(InputGlobals.size()));
Heejin Ahne915a712018-12-08 06:17:43 +00001234 log("Defined Events : " + Twine(InputEvents.size()));
Sam Clegg93102972018-02-23 05:08:53 +00001235 log("Function Imports : " + Twine(NumImportedFunctions));
1236 log("Global Imports : " + Twine(NumImportedGlobals));
Heejin Ahne915a712018-12-08 06:17:43 +00001237 log("Event Imports : " + Twine(NumImportedEvents));
Sam Cleggc94d3932017-11-17 18:14:09 +00001238 for (ObjFile *File : Symtab->ObjectFiles)
1239 File->dumpInfo();
1240 }
1241
Sam Cleggc94d3932017-11-17 18:14:09 +00001242 createHeader();
1243 log("-- createSections");
1244 createSections();
1245
1246 log("-- openFile");
1247 openFile();
1248 if (errorCount())
1249 return;
1250
1251 writeHeader();
1252
1253 log("-- writeSections");
1254 writeSections();
1255 if (errorCount())
1256 return;
1257
1258 if (Error E = Buffer->commit())
1259 fatal("failed to write the output file: " + toString(std::move(E)));
1260}
1261
1262// Open a result file.
1263void Writer::openFile() {
1264 log("writing: " + Config->OutputFile);
Sam Cleggc94d3932017-11-17 18:14:09 +00001265
1266 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
1267 FileOutputBuffer::create(Config->OutputFile, FileSize,
1268 FileOutputBuffer::F_executable);
1269
1270 if (!BufferOrErr)
1271 error("failed to open " + Config->OutputFile + ": " +
1272 toString(BufferOrErr.takeError()));
1273 else
1274 Buffer = std::move(*BufferOrErr);
1275}
1276
1277void Writer::createHeader() {
1278 raw_string_ostream OS(Header);
1279 writeBytes(OS, WasmMagic, sizeof(WasmMagic), "wasm magic");
1280 writeU32(OS, WasmVersion, "wasm version");
1281 OS.flush();
1282 FileSize += Header.size();
1283}
1284
1285void lld::wasm::writeResult() { Writer().run(); }