blob: 96c473629cf888185a40587e15d13b78601ce30c [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 Clegg632c21792019-03-16 01:18:12 +000069 void processRelocations(InputChunk *Chunk);
Sam Clegg8d146bb2018-01-09 23:56:44 +000070 void assignIndexes();
Sam Cleggc94d3932017-11-17 18:14:09 +000071 void calculateImports();
Sam Cleggd3052d52018-01-18 23:40:49 +000072 void calculateExports();
Sam Cleggd177ab22018-05-04 23:14:42 +000073 void calculateCustomSections();
Sam Clegg93102972018-02-23 05:08:53 +000074 void assignSymtab();
Sam Cleggc94d3932017-11-17 18:14:09 +000075 void calculateTypes();
76 void createOutputSegments();
77 void layoutMemory();
78 void createHeader();
79 void createSections();
Nicholas Wilsondbd90bf2018-03-07 13:28:16 +000080 SyntheticSection *createSyntheticSection(uint32_t Type, StringRef Name = "");
Sam Cleggc94d3932017-11-17 18:14:09 +000081
82 // Builtin sections
83 void createTypeSection();
84 void createFunctionSection();
85 void createTableSection();
86 void createGlobalSection();
Heejin Ahne915a712018-12-08 06:17:43 +000087 void createEventSection();
Sam Cleggc94d3932017-11-17 18:14:09 +000088 void createExportSection();
89 void createImportSection();
90 void createMemorySection();
91 void createElemSection();
Sam Cleggc94d3932017-11-17 18:14:09 +000092 void createCodeSection();
93 void createDataSection();
Sam Clegg80ba4382018-04-10 16:12:49 +000094 void createCustomSections();
Sam Cleggc94d3932017-11-17 18:14:09 +000095
96 // Custom sections
Sam Cleggbfb75342018-11-15 00:37:21 +000097 void createDylinkSection();
Sam Cleggc94d3932017-11-17 18:14:09 +000098 void createRelocSections();
99 void createLinkingSection();
100 void createNameSection();
Thomas Lively2a0868f2019-01-17 02:29:41 +0000101 void createProducersSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000102
103 void writeHeader();
104 void writeSections();
105
106 uint64_t FileSize = 0;
Sam Cleggbfb75342018-11-15 00:37:21 +0000107 uint32_t TableBase = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000108 uint32_t NumMemoryPages = 0;
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000109 uint32_t MaxMemoryPages = 0;
Sam Cleggbfb75342018-11-15 00:37:21 +0000110 // Memory size and aligment. Written to the "dylink" section
111 // when build with -shared or -pie.
112 uint32_t MemAlign = 0;
113 uint32_t MemSize = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000114
115 std::vector<const WasmSignature *> Types;
Nicholas Wilson3e3f5fb2018-03-14 15:58:16 +0000116 DenseMap<WasmSignature, int32_t> TypeIndices;
Sam Clegg93102972018-02-23 05:08:53 +0000117 std::vector<const Symbol *> ImportedSymbols;
118 unsigned NumImportedFunctions = 0;
119 unsigned NumImportedGlobals = 0;
Heejin Ahne915a712018-12-08 06:17:43 +0000120 unsigned NumImportedEvents = 0;
Sam Cleggd6beb322018-05-10 18:10:34 +0000121 std::vector<WasmExport> Exports;
Sam Clegg93102972018-02-23 05:08:53 +0000122 std::vector<const DefinedData *> DefinedFakeGlobals;
123 std::vector<InputGlobal *> InputGlobals;
Sam Clegg9f934222018-02-21 18:29:23 +0000124 std::vector<InputFunction *> InputFunctions;
Heejin Ahne915a712018-12-08 06:17:43 +0000125 std::vector<InputEvent *> InputEvents;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000126 std::vector<const FunctionSymbol *> IndirectFunctions;
Sam Clegg93102972018-02-23 05:08:53 +0000127 std::vector<const Symbol *> SymtabEntries;
128 std::vector<WasmInitEntry> InitFunctions;
Sam Cleggc94d3932017-11-17 18:14:09 +0000129
Sam Clegg80ba4382018-04-10 16:12:49 +0000130 llvm::StringMap<std::vector<InputSection *>> CustomSectionMapping;
Sam Cleggd177ab22018-05-04 23:14:42 +0000131 llvm::StringMap<SectionSymbol *> CustomSectionSymbols;
Sam Clegg80ba4382018-04-10 16:12:49 +0000132
Sam Cleggc94d3932017-11-17 18:14:09 +0000133 // Elements that are used to construct the final output
134 std::string Header;
135 std::vector<OutputSection *> OutputSections;
136
137 std::unique_ptr<FileOutputBuffer> Buffer;
138
139 std::vector<OutputSegment *> Segments;
140 llvm::SmallDenseMap<StringRef, OutputSegment *> SegmentMap;
141};
142
143} // anonymous namespace
144
Sam Cleggc94d3932017-11-17 18:14:09 +0000145void Writer::createImportSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000146 uint32_t NumImports = ImportedSymbols.size();
Sam Cleggc94d3932017-11-17 18:14:09 +0000147 if (Config->ImportMemory)
148 ++NumImports;
Nicholas Wilsonfc90b302018-03-28 12:53:29 +0000149 if (Config->ImportTable)
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000150 ++NumImports;
Sam Cleggc94d3932017-11-17 18:14:09 +0000151
152 if (NumImports == 0)
153 return;
154
155 SyntheticSection *Section = createSyntheticSection(WASM_SEC_IMPORT);
156 raw_ostream &OS = Section->getStream();
157
158 writeUleb128(OS, NumImports, "import count");
159
Sam Cleggc94d3932017-11-17 18:14:09 +0000160 if (Config->ImportMemory) {
161 WasmImport Import;
Heejin Ahna1cc4ea2019-02-04 19:13:46 +0000162 Import.Module = DefaultModule;
Sam Cleggc94d3932017-11-17 18:14:09 +0000163 Import.Field = "memory";
164 Import.Kind = WASM_EXTERNAL_MEMORY;
165 Import.Memory.Flags = 0;
166 Import.Memory.Initial = NumMemoryPages;
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000167 if (MaxMemoryPages != 0) {
168 Import.Memory.Flags |= WASM_LIMITS_FLAG_HAS_MAX;
169 Import.Memory.Maximum = MaxMemoryPages;
170 }
Derek Schuff786760a2018-11-06 18:02:39 +0000171 if (Config->SharedMemory)
Derek Schuff3bea8bc2018-11-06 17:59:32 +0000172 Import.Memory.Flags |= WASM_LIMITS_FLAG_IS_SHARED;
Sam Cleggc94d3932017-11-17 18:14:09 +0000173 writeImport(OS, Import);
174 }
175
Nicholas Wilsonfc90b302018-03-28 12:53:29 +0000176 if (Config->ImportTable) {
Sam Cleggbfb75342018-11-15 00:37:21 +0000177 uint32_t TableSize = TableBase + IndirectFunctions.size();
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000178 WasmImport Import;
Heejin Ahna1cc4ea2019-02-04 19:13:46 +0000179 Import.Module = DefaultModule;
180 Import.Field = FunctionTableName;
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000181 Import.Kind = WASM_EXTERNAL_TABLE;
Thomas Lively25ff8932019-01-08 06:25:55 +0000182 Import.Table.ElemType = WASM_TYPE_FUNCREF;
Sam Clegg748f59cae2018-12-03 22:37:55 +0000183 Import.Table.Limits = {0, TableSize, 0};
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000184 writeImport(OS, Import);
185 }
186
Sam Clegg93102972018-02-23 05:08:53 +0000187 for (const Symbol *Sym : ImportedSymbols) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000188 WasmImport Import;
Dan Gohman9b84eea2019-02-07 22:00:48 +0000189 if (auto *F = dyn_cast<UndefinedFunction>(Sym)) {
190 Import.Field = F->ImportName;
191 Import.Module = F->ImportModule;
192 } else if (auto *G = dyn_cast<UndefinedGlobal>(Sym)) {
193 Import.Field = G->ImportName;
194 Import.Module = G->ImportModule;
195 } else {
196 Import.Field = Sym->getName();
Heejin Ahna1cc4ea2019-02-04 19:13:46 +0000197 Import.Module = DefaultModule;
Dan Gohman9b84eea2019-02-07 22:00:48 +0000198 }
Sam Clegg7cc07532019-02-01 02:29:57 +0000199
Sam Clegg93102972018-02-23 05:08:53 +0000200 if (auto *FunctionSym = dyn_cast<FunctionSymbol>(Sym)) {
201 Import.Kind = WASM_EXTERNAL_FUNCTION;
Heejin Ahne915a712018-12-08 06:17:43 +0000202 Import.SigIndex = lookupType(*FunctionSym->Signature);
Sam Cleggd425d6b2019-03-12 21:53:23 +0000203 } else if (auto *DataSym = dyn_cast<UndefinedData>(Sym)) {
204 Import.Kind = WASM_EXTERNAL_GLOBAL;
205 Import.Global = {WASM_TYPE_I32, true};
Heejin Ahne915a712018-12-08 06:17:43 +0000206 } else if (auto *GlobalSym = dyn_cast<GlobalSymbol>(Sym)) {
Sam Clegg93102972018-02-23 05:08:53 +0000207 Import.Kind = WASM_EXTERNAL_GLOBAL;
208 Import.Global = *GlobalSym->getGlobalType();
Heejin Ahne915a712018-12-08 06:17:43 +0000209 } else {
210 auto *EventSym = cast<EventSymbol>(Sym);
211 Import.Kind = WASM_EXTERNAL_EVENT;
212 Import.Event.Attribute = EventSym->getEventType()->Attribute;
213 Import.Event.SigIndex = lookupType(*EventSym->Signature);
Sam Clegg93102972018-02-23 05:08:53 +0000214 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000215 writeImport(OS, Import);
216 }
217}
218
219void Writer::createTypeSection() {
220 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TYPE);
221 raw_ostream &OS = Section->getStream();
222 writeUleb128(OS, Types.size(), "type count");
Sam Cleggd451da12017-12-19 19:56:27 +0000223 for (const WasmSignature *Sig : Types)
Sam Cleggc94d3932017-11-17 18:14:09 +0000224 writeSig(OS, *Sig);
Sam Cleggc94d3932017-11-17 18:14:09 +0000225}
226
227void Writer::createFunctionSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000228 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000229 return;
230
231 SyntheticSection *Section = createSyntheticSection(WASM_SEC_FUNCTION);
232 raw_ostream &OS = Section->getStream();
233
Sam Clegg9f934222018-02-21 18:29:23 +0000234 writeUleb128(OS, InputFunctions.size(), "function count");
235 for (const InputFunction *Func : InputFunctions)
Sam Cleggc375e4e2018-01-10 19:18:22 +0000236 writeUleb128(OS, lookupType(Func->Signature), "sig index");
Sam Cleggc94d3932017-11-17 18:14:09 +0000237}
238
239void Writer::createMemorySection() {
240 if (Config->ImportMemory)
241 return;
242
243 SyntheticSection *Section = createSyntheticSection(WASM_SEC_MEMORY);
244 raw_ostream &OS = Section->getStream();
245
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000246 bool HasMax = MaxMemoryPages != 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000247 writeUleb128(OS, 1, "memory count");
Derek Schuff786760a2018-11-06 18:02:39 +0000248 unsigned Flags = 0;
249 if (HasMax)
250 Flags |= WASM_LIMITS_FLAG_HAS_MAX;
Derek Schuff3bea8bc2018-11-06 17:59:32 +0000251 if (Config->SharedMemory)
252 Flags |= WASM_LIMITS_FLAG_IS_SHARED;
253 writeUleb128(OS, Flags, "memory limits flags");
Sam Cleggc94d3932017-11-17 18:14:09 +0000254 writeUleb128(OS, NumMemoryPages, "initial pages");
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000255 if (HasMax)
256 writeUleb128(OS, MaxMemoryPages, "max pages");
Sam Cleggc94d3932017-11-17 18:14:09 +0000257}
258
259void Writer::createGlobalSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000260 unsigned NumGlobals = InputGlobals.size() + DefinedFakeGlobals.size();
261 if (NumGlobals == 0)
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000262 return;
263
Sam Cleggc94d3932017-11-17 18:14:09 +0000264 SyntheticSection *Section = createSyntheticSection(WASM_SEC_GLOBAL);
265 raw_ostream &OS = Section->getStream();
266
Sam Clegg93102972018-02-23 05:08:53 +0000267 writeUleb128(OS, NumGlobals, "global count");
268 for (const InputGlobal *G : InputGlobals)
269 writeGlobal(OS, G->Global);
270 for (const DefinedData *Sym : DefinedFakeGlobals) {
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000271 WasmGlobal Global;
Sam Clegg93102972018-02-23 05:08:53 +0000272 Global.Type = {WASM_TYPE_I32, false};
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000273 Global.InitExpr.Opcode = WASM_OPCODE_I32_CONST;
274 Global.InitExpr.Value.Int32 = Sym->getVirtualAddress();
Sam Cleggc94d3932017-11-17 18:14:09 +0000275 writeGlobal(OS, Global);
276 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000277}
278
Heejin Ahne915a712018-12-08 06:17:43 +0000279// The event section contains a list of declared wasm events associated with the
280// module. Currently the only supported event kind is exceptions. A single event
281// entry represents a single event with an event tag. All C++ exceptions are
282// represented by a single event. An event entry in this section contains
283// information on what kind of event it is (e.g. exception) and the type of
284// values contained in a single event object. (In wasm, an event can contain
285// multiple values of primitive types. But for C++ exceptions, we just throw a
286// pointer which is an i32 value (for wasm32 architecture), so the signature of
287// C++ exception is (i32)->(void), because all event types are assumed to have
288// void return type to share WasmSignature with functions.)
289void Writer::createEventSection() {
290 unsigned NumEvents = InputEvents.size();
291 if (NumEvents == 0)
292 return;
293
294 SyntheticSection *Section = createSyntheticSection(WASM_SEC_EVENT);
295 raw_ostream &OS = Section->getStream();
296
297 writeUleb128(OS, NumEvents, "event count");
298 for (InputEvent *E : InputEvents) {
299 E->Event.Type.SigIndex = lookupType(E->Signature);
300 writeEvent(OS, E->Event);
301 }
302}
303
Sam Cleggc94d3932017-11-17 18:14:09 +0000304void Writer::createTableSection() {
Nicholas Wilsonfc90b302018-03-28 12:53:29 +0000305 if (Config->ImportTable)
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000306 return;
307
308 // Always output a table section (or table import), even if there are no
309 // indirect calls. There are two reasons for this:
Sam Cleggfc1a9122017-12-11 22:00:56 +0000310 // 1. For executables it is useful to have an empty table slot at 0
311 // which can be filled with a null function call handler.
312 // 2. If we don't do this, any program that contains a call_indirect but
313 // no address-taken function will fail at validation time since it is
314 // a validation error to include a call_indirect instruction if there
315 // is not table.
Sam Cleggbfb75342018-11-15 00:37:21 +0000316 uint32_t TableSize = TableBase + IndirectFunctions.size();
Sam Cleggfc1a9122017-12-11 22:00:56 +0000317
Sam Cleggc94d3932017-11-17 18:14:09 +0000318 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TABLE);
319 raw_ostream &OS = Section->getStream();
320
321 writeUleb128(OS, 1, "table count");
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000322 WasmLimits Limits = {WASM_LIMITS_FLAG_HAS_MAX, TableSize, TableSize};
Thomas Lively25ff8932019-01-08 06:25:55 +0000323 writeTableType(OS, WasmTable{WASM_TYPE_FUNCREF, Limits});
Sam Cleggc94d3932017-11-17 18:14:09 +0000324}
325
326void Writer::createExportSection() {
Sam Cleggd6beb322018-05-10 18:10:34 +0000327 if (!Exports.size())
Sam Cleggc94d3932017-11-17 18:14:09 +0000328 return;
329
330 SyntheticSection *Section = createSyntheticSection(WASM_SEC_EXPORT);
331 raw_ostream &OS = Section->getStream();
332
Sam Cleggd6beb322018-05-10 18:10:34 +0000333 writeUleb128(OS, Exports.size(), "export count");
334 for (const WasmExport &Export : Exports)
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000335 writeExport(OS, Export);
Sam Cleggc94d3932017-11-17 18:14:09 +0000336}
337
Sam Cleggd177ab22018-05-04 23:14:42 +0000338void Writer::calculateCustomSections() {
339 log("calculateCustomSections");
340 bool StripDebug = Config->StripDebug || Config->StripAll;
341 for (ObjFile *File : Symtab->ObjectFiles) {
342 for (InputSection *Section : File->CustomSections) {
343 StringRef Name = Section->getName();
344 // These custom sections are known the linker and synthesized rather than
345 // blindly copied
Thomas Lively2a0868f2019-01-17 02:29:41 +0000346 if (Name == "linking" || Name == "name" || Name == "producers" ||
347 Name.startswith("reloc."))
Sam Cleggd177ab22018-05-04 23:14:42 +0000348 continue;
349 // .. or it is a debug section
350 if (StripDebug && Name.startswith(".debug_"))
351 continue;
352 CustomSectionMapping[Name].push_back(Section);
353 }
354 }
355}
356
Sam Clegg80ba4382018-04-10 16:12:49 +0000357void Writer::createCustomSections() {
358 log("createCustomSections");
Sam Clegg80ba4382018-04-10 16:12:49 +0000359 for (auto &Pair : CustomSectionMapping) {
360 StringRef Name = Pair.first();
Sam Cleggd177ab22018-05-04 23:14:42 +0000361
362 auto P = CustomSectionSymbols.find(Name);
363 if (P != CustomSectionSymbols.end()) {
364 uint32_t SectionIndex = OutputSections.size();
365 P->second->setOutputSectionIndex(SectionIndex);
366 }
367
Nicola Zaghene7245b42018-05-15 13:36:20 +0000368 LLVM_DEBUG(dbgs() << "createCustomSection: " << Name << "\n");
Sam Clegg80ba4382018-04-10 16:12:49 +0000369 OutputSections.push_back(make<CustomSection>(Name, Pair.second));
370 }
371}
372
Sam Cleggc94d3932017-11-17 18:14:09 +0000373void Writer::createElemSection() {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000374 if (IndirectFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000375 return;
376
377 SyntheticSection *Section = createSyntheticSection(WASM_SEC_ELEM);
378 raw_ostream &OS = Section->getStream();
379
380 writeUleb128(OS, 1, "segment count");
381 writeUleb128(OS, 0, "table index");
382 WasmInitExpr InitExpr;
Sam Cleggbfb75342018-11-15 00:37:21 +0000383 if (Config->Pic) {
Thomas Lively25ff8932019-01-08 06:25:55 +0000384 InitExpr.Opcode = WASM_OPCODE_GLOBAL_GET;
Sam Clegg2dad4e22018-11-15 18:15:54 +0000385 InitExpr.Value.Global = WasmSym::TableBase->getGlobalIndex();
Sam Cleggbfb75342018-11-15 00:37:21 +0000386 } else {
387 InitExpr.Opcode = WASM_OPCODE_I32_CONST;
388 InitExpr.Value.Int32 = TableBase;
389 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000390 writeInitExpr(OS, InitExpr);
Sam Cleggfc1a9122017-12-11 22:00:56 +0000391 writeUleb128(OS, IndirectFunctions.size(), "elem count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000392
Sam Cleggbfb75342018-11-15 00:37:21 +0000393 uint32_t TableIndex = TableBase;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000394 for (const FunctionSymbol *Sym : IndirectFunctions) {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000395 assert(Sym->getTableIndex() == TableIndex);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000396 writeUleb128(OS, Sym->getFunctionIndex(), "function index");
Sam Cleggfc1a9122017-12-11 22:00:56 +0000397 ++TableIndex;
398 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000399}
400
401void Writer::createCodeSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000402 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000403 return;
404
405 log("createCodeSection");
406
Sam Clegg9f934222018-02-21 18:29:23 +0000407 auto Section = make<CodeSection>(InputFunctions);
Sam Cleggc94d3932017-11-17 18:14:09 +0000408 OutputSections.push_back(Section);
409}
410
411void Writer::createDataSection() {
412 if (!Segments.size())
413 return;
414
415 log("createDataSection");
416 auto Section = make<DataSection>(Segments);
417 OutputSections.push_back(Section);
418}
419
Sam Cleggd451da12017-12-19 19:56:27 +0000420// Create relocations sections in the final output.
Sam Cleggc94d3932017-11-17 18:14:09 +0000421// These are only created when relocatable output is requested.
422void Writer::createRelocSections() {
423 log("createRelocSections");
424 // Don't use iterator here since we are adding to OutputSection
425 size_t OrigSize = OutputSections.size();
Rui Ueyamaffa650a2018-04-24 23:09:57 +0000426 for (size_t I = 0; I < OrigSize; I++) {
427 OutputSection *OSec = OutputSections[I];
Rui Ueyama37254062018-02-28 00:01:31 +0000428 uint32_t Count = OSec->numRelocations();
Sam Cleggc94d3932017-11-17 18:14:09 +0000429 if (!Count)
430 continue;
431
Rui Ueyama37254062018-02-28 00:01:31 +0000432 StringRef Name;
433 if (OSec->Type == WASM_SEC_DATA)
434 Name = "reloc.DATA";
435 else if (OSec->Type == WASM_SEC_CODE)
436 Name = "reloc.CODE";
Sam Cleggd177ab22018-05-04 23:14:42 +0000437 else if (OSec->Type == WASM_SEC_CUSTOM)
438 Name = Saver.save("reloc." + OSec->Name);
Sam Cleggc94d3932017-11-17 18:14:09 +0000439 else
Sam Cleggd177ab22018-05-04 23:14:42 +0000440 llvm_unreachable(
441 "relocations only supported for code, data, or custom sections");
Sam Cleggc94d3932017-11-17 18:14:09 +0000442
Rui Ueyama37254062018-02-28 00:01:31 +0000443 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, Name);
Sam Cleggc94d3932017-11-17 18:14:09 +0000444 raw_ostream &OS = Section->getStream();
Rui Ueyamaffa650a2018-04-24 23:09:57 +0000445 writeUleb128(OS, I, "reloc section");
Sam Cleggc94d3932017-11-17 18:14:09 +0000446 writeUleb128(OS, Count, "reloc count");
Rui Ueyama37254062018-02-28 00:01:31 +0000447 OSec->writeRelocations(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000448 }
449}
450
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000451static uint32_t getWasmFlags(const Symbol *Sym) {
452 uint32_t Flags = 0;
453 if (Sym->isLocal())
454 Flags |= WASM_SYMBOL_BINDING_LOCAL;
455 if (Sym->isWeak())
456 Flags |= WASM_SYMBOL_BINDING_WEAK;
457 if (Sym->isHidden())
458 Flags |= WASM_SYMBOL_VISIBILITY_HIDDEN;
459 if (Sym->isUndefined())
460 Flags |= WASM_SYMBOL_UNDEFINED;
Dan Gohman9b84eea2019-02-07 22:00:48 +0000461 if (auto *F = dyn_cast<UndefinedFunction>(Sym)) {
462 if (F->getName() != F->ImportName)
463 Flags |= WASM_SYMBOL_EXPLICIT_NAME;
464 } else if (auto *G = dyn_cast<UndefinedGlobal>(Sym)) {
465 if (G->getName() != G->ImportName)
466 Flags |= WASM_SYMBOL_EXPLICIT_NAME;
467 }
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000468 return Flags;
469}
470
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000471// Some synthetic sections (e.g. "name" and "linking") have subsections.
472// Just like the synthetic sections themselves these need to be created before
473// they can be written out (since they are preceded by their length). This
474// class is used to create subsections and then write them into the stream
475// of the parent section.
476class SubSection {
477public:
478 explicit SubSection(uint32_t Type) : Type(Type) {}
479
480 void writeTo(raw_ostream &To) {
481 OS.flush();
Rui Ueyama67769102018-02-28 03:38:14 +0000482 writeUleb128(To, Type, "subsection type");
483 writeUleb128(To, Body.size(), "subsection size");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000484 To.write(Body.data(), Body.size());
485 }
486
487private:
488 uint32_t Type;
489 std::string Body;
490
491public:
492 raw_string_ostream OS{Body};
493};
494
Sam Cleggbfb75342018-11-15 00:37:21 +0000495// Create the custom "dylink" section containing information for the dynamic
496// linker.
497// See
498// https://github.com/WebAssembly/tool-conventions/blob/master/DynamicLinking.md
499void Writer::createDylinkSection() {
500 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "dylink");
501 raw_ostream &OS = Section->getStream();
502
503 writeUleb128(OS, MemSize, "MemSize");
Sam Clegg6320efb2019-01-16 01:43:21 +0000504 writeUleb128(OS, MemAlign, "MemAlign");
Sam Cleggbfb75342018-11-15 00:37:21 +0000505 writeUleb128(OS, IndirectFunctions.size(), "TableSize");
506 writeUleb128(OS, 0, "TableAlign");
Sam Clegga688a422019-03-13 21:29:20 +0000507 writeUleb128(OS, Symtab->SharedFiles.size(), "Needed");
508 for (auto *SO : Symtab->SharedFiles)
509 writeStr(OS, llvm::sys::path::filename(SO->getName()), "so name");
Sam Cleggbfb75342018-11-15 00:37:21 +0000510}
511
Sam Clegg49ed9262017-12-01 00:53:21 +0000512// Create the custom "linking" section containing linker metadata.
Sam Cleggc94d3932017-11-17 18:14:09 +0000513// This is only created when relocatable output is requested.
514void Writer::createLinkingSection() {
515 SyntheticSection *Section =
516 createSyntheticSection(WASM_SEC_CUSTOM, "linking");
517 raw_ostream &OS = Section->getStream();
518
Sam Clegg2b8b1792018-04-26 18:17:21 +0000519 writeUleb128(OS, WasmMetadataVersion, "Version");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000520
Sam Clegg93102972018-02-23 05:08:53 +0000521 if (!SymtabEntries.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000522 SubSection Sub(WASM_SYMBOL_TABLE);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000523 writeUleb128(Sub.OS, SymtabEntries.size(), "num symbols");
524
Sam Clegg93102972018-02-23 05:08:53 +0000525 for (const Symbol *Sym : SymtabEntries) {
526 assert(Sym->isDefined() || Sym->isUndefined());
527 WasmSymbolType Kind = Sym->getWasmType();
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000528 uint32_t Flags = getWasmFlags(Sym);
529
Sam Clegg8518e7d2018-03-01 18:06:39 +0000530 writeU8(Sub.OS, Kind, "sym kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000531 writeUleb128(Sub.OS, Flags, "sym flags");
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000532
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000533 if (auto *F = dyn_cast<FunctionSymbol>(Sym)) {
534 writeUleb128(Sub.OS, F->getFunctionIndex(), "index");
Dan Gohman9b84eea2019-02-07 22:00:48 +0000535 if (Sym->isDefined() ||
536 (Flags & WASM_SYMBOL_EXPLICIT_NAME) != 0)
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000537 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000538 } else if (auto *G = dyn_cast<GlobalSymbol>(Sym)) {
539 writeUleb128(Sub.OS, G->getGlobalIndex(), "index");
Dan Gohman9b84eea2019-02-07 22:00:48 +0000540 if (Sym->isDefined() ||
541 (Flags & WASM_SYMBOL_EXPLICIT_NAME) != 0)
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000542 writeStr(Sub.OS, Sym->getName(), "sym name");
Heejin Ahne915a712018-12-08 06:17:43 +0000543 } else if (auto *E = dyn_cast<EventSymbol>(Sym)) {
544 writeUleb128(Sub.OS, E->getEventIndex(), "index");
Dan Gohman9b84eea2019-02-07 22:00:48 +0000545 if (Sym->isDefined() ||
546 (Flags & WASM_SYMBOL_EXPLICIT_NAME) != 0)
Heejin Ahne915a712018-12-08 06:17:43 +0000547 writeStr(Sub.OS, Sym->getName(), "sym name");
Andrea Di Biagio25c1a2f2018-05-05 10:53:31 +0000548 } else if (isa<DataSymbol>(Sym)) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000549 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegg93102972018-02-23 05:08:53 +0000550 if (auto *DataSym = dyn_cast<DefinedData>(Sym)) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000551 writeUleb128(Sub.OS, DataSym->getOutputSegmentIndex(), "index");
552 writeUleb128(Sub.OS, DataSym->getOutputSegmentOffset(),
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000553 "data offset");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000554 writeUleb128(Sub.OS, DataSym->getSize(), "data size");
Sam Clegg93102972018-02-23 05:08:53 +0000555 }
Sam Cleggd177ab22018-05-04 23:14:42 +0000556 } else {
557 auto *S = cast<SectionSymbol>(Sym);
558 writeUleb128(Sub.OS, S->getOutputSectionIndex(), "sym section index");
Sam Clegg93102972018-02-23 05:08:53 +0000559 }
Sam Cleggd3052d52018-01-18 23:40:49 +0000560 }
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000561
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000562 Sub.writeTo(OS);
Sam Cleggd3052d52018-01-18 23:40:49 +0000563 }
564
Sam Clegg0d0dd392017-12-19 17:09:45 +0000565 if (Segments.size()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000566 SubSection Sub(WASM_SEGMENT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000567 writeUleb128(Sub.OS, Segments.size(), "num data segments");
Sam Cleggc94d3932017-11-17 18:14:09 +0000568 for (const OutputSegment *S : Segments) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000569 writeStr(Sub.OS, S->Name, "segment name");
570 writeUleb128(Sub.OS, S->Alignment, "alignment");
571 writeUleb128(Sub.OS, 0, "flags");
Sam Cleggc94d3932017-11-17 18:14:09 +0000572 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000573 Sub.writeTo(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000574 }
Sam Clegg0d0dd392017-12-19 17:09:45 +0000575
Sam Clegg0d0dd392017-12-19 17:09:45 +0000576 if (!InitFunctions.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000577 SubSection Sub(WASM_INIT_FUNCS);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000578 writeUleb128(Sub.OS, InitFunctions.size(), "num init functions");
Sam Clegg93102972018-02-23 05:08:53 +0000579 for (const WasmInitEntry &F : InitFunctions) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000580 writeUleb128(Sub.OS, F.Priority, "priority");
581 writeUleb128(Sub.OS, F.Sym->getOutputSymbolIndex(), "function index");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000582 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000583 Sub.writeTo(OS);
Sam Clegg0d0dd392017-12-19 17:09:45 +0000584 }
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000585
Nicholas Wilsondbd90bf2018-03-07 13:28:16 +0000586 struct ComdatEntry {
587 unsigned Kind;
588 uint32_t Index;
589 };
590 std::map<StringRef, std::vector<ComdatEntry>> Comdats;
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000591
Sam Clegg9f934222018-02-21 18:29:23 +0000592 for (const InputFunction *F : InputFunctions) {
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000593 StringRef Comdat = F->getComdatName();
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000594 if (!Comdat.empty())
595 Comdats[Comdat].emplace_back(
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000596 ComdatEntry{WASM_COMDAT_FUNCTION, F->getFunctionIndex()});
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000597 }
598 for (uint32_t I = 0; I < Segments.size(); ++I) {
Sam Cleggf98bccf2018-01-13 15:57:48 +0000599 const auto &InputSegments = Segments[I]->InputSegments;
600 if (InputSegments.empty())
601 continue;
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000602 StringRef Comdat = InputSegments[0]->getComdatName();
Sam Clegga697df522018-01-13 15:59:53 +0000603#ifndef NDEBUG
Sam Cleggf98bccf2018-01-13 15:57:48 +0000604 for (const InputSegment *IS : InputSegments)
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000605 assert(IS->getComdatName() == Comdat);
Sam Clegga697df522018-01-13 15:59:53 +0000606#endif
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000607 if (!Comdat.empty())
608 Comdats[Comdat].emplace_back(ComdatEntry{WASM_COMDAT_DATA, I});
609 }
610
611 if (!Comdats.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000612 SubSection Sub(WASM_COMDAT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000613 writeUleb128(Sub.OS, Comdats.size(), "num comdats");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000614 for (const auto &C : Comdats) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000615 writeStr(Sub.OS, C.first, "comdat name");
616 writeUleb128(Sub.OS, 0, "comdat flags"); // flags for future use
617 writeUleb128(Sub.OS, C.second.size(), "num entries");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000618 for (const ComdatEntry &Entry : C.second) {
Sam Clegg8518e7d2018-03-01 18:06:39 +0000619 writeU8(Sub.OS, Entry.Kind, "entry kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000620 writeUleb128(Sub.OS, Entry.Index, "entry index");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000621 }
622 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000623 Sub.writeTo(OS);
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000624 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000625}
626
627// Create the custom "name" section containing debug symbol names.
628void Writer::createNameSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000629 unsigned NumNames = NumImportedFunctions;
Sam Clegg9f934222018-02-21 18:29:23 +0000630 for (const InputFunction *F : InputFunctions)
Nicholas Wilson6c7fe302018-04-20 17:09:18 +0000631 if (!F->getName().empty() || !F->getDebugName().empty())
Sam Clegg1963d712018-01-17 20:19:04 +0000632 ++NumNames;
Sam Cleggc94d3932017-11-17 18:14:09 +0000633
Sam Clegg1963d712018-01-17 20:19:04 +0000634 if (NumNames == 0)
635 return;
Sam Clegg50686852018-01-12 18:35:13 +0000636
Sam Cleggc94d3932017-11-17 18:14:09 +0000637 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "name");
638
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000639 SubSection Sub(WASM_NAMES_FUNCTION);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000640 writeUleb128(Sub.OS, NumNames, "name count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000641
Sam Clegg93102972018-02-23 05:08:53 +0000642 // Names must appear in function index order. As it happens ImportedSymbols
643 // and InputFunctions are numbered in order with imported functions coming
Sam Clegg1963d712018-01-17 20:19:04 +0000644 // first.
Sam Clegg93102972018-02-23 05:08:53 +0000645 for (const Symbol *S : ImportedSymbols) {
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000646 if (auto *F = dyn_cast<FunctionSymbol>(S)) {
647 writeUleb128(Sub.OS, F->getFunctionIndex(), "func index");
Sam Clegg37125f02018-11-09 16:57:41 +0000648 writeStr(Sub.OS, toString(*S), "symbol name");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000649 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000650 }
Sam Clegg9f934222018-02-21 18:29:23 +0000651 for (const InputFunction *F : InputFunctions) {
Sam Clegg1963d712018-01-17 20:19:04 +0000652 if (!F->getName().empty()) {
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000653 writeUleb128(Sub.OS, F->getFunctionIndex(), "func index");
Nicholas Wilson6c7fe302018-04-20 17:09:18 +0000654 if (!F->getDebugName().empty()) {
655 writeStr(Sub.OS, F->getDebugName(), "symbol name");
656 } else {
Sam Clegg37125f02018-11-09 16:57:41 +0000657 writeStr(Sub.OS, maybeDemangleSymbol(F->getName()), "symbol name");
Nicholas Wilson6c7fe302018-04-20 17:09:18 +0000658 }
Sam Clegg1963d712018-01-17 20:19:04 +0000659 }
660 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000661
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000662 Sub.writeTo(Section->getStream());
Sam Cleggc94d3932017-11-17 18:14:09 +0000663}
664
Thomas Lively2a0868f2019-01-17 02:29:41 +0000665void Writer::createProducersSection() {
666 SmallVector<std::pair<std::string, std::string>, 8> Languages;
667 SmallVector<std::pair<std::string, std::string>, 8> Tools;
668 SmallVector<std::pair<std::string, std::string>, 8> SDKs;
669 for (ObjFile *File : Symtab->ObjectFiles) {
670 const WasmProducerInfo &Info = File->getWasmObj()->getProducerInfo();
671 for (auto &Producers : {std::make_pair(&Info.Languages, &Languages),
672 std::make_pair(&Info.Tools, &Tools),
673 std::make_pair(&Info.SDKs, &SDKs)})
674 for (auto &Producer : *Producers.first)
675 if (Producers.second->end() ==
676 std::find_if(Producers.second->begin(), Producers.second->end(),
677 [&](std::pair<std::string, std::string> Seen) {
678 return Seen.first == Producer.first;
679 }))
680 Producers.second->push_back(Producer);
681 }
682 int FieldCount =
683 int(!Languages.empty()) + int(!Tools.empty()) + int(!SDKs.empty());
684 if (FieldCount == 0)
685 return;
686 SyntheticSection *Section =
687 createSyntheticSection(WASM_SEC_CUSTOM, "producers");
688 auto &OS = Section->getStream();
689 writeUleb128(OS, FieldCount, "field count");
690 for (auto &Field :
691 {std::make_pair("language", Languages),
692 std::make_pair("processed-by", Tools), std::make_pair("sdk", SDKs)}) {
693 if (Field.second.empty())
694 continue;
695 writeStr(OS, Field.first, "field name");
696 writeUleb128(OS, Field.second.size(), "number of entries");
697 for (auto &Entry : Field.second) {
698 writeStr(OS, Entry.first, "producer name");
699 writeStr(OS, Entry.second, "producer version");
700 }
701 }
702}
703
Sam Cleggc94d3932017-11-17 18:14:09 +0000704void Writer::writeHeader() {
705 memcpy(Buffer->getBufferStart(), Header.data(), Header.size());
706}
707
708void Writer::writeSections() {
709 uint8_t *Buf = Buffer->getBufferStart();
710 parallelForEach(OutputSections, [Buf](OutputSection *S) { S->writeTo(Buf); });
711}
712
713// Fix the memory layout of the output binary. This assigns memory offsets
Sam Clegg49ed9262017-12-01 00:53:21 +0000714// to each of the input data sections as well as the explicit stack region.
Sam Clegga0f095e2018-05-03 17:21:53 +0000715// The default memory layout is as follows, from low to high.
716//
Sam Cleggf0d433d2018-02-02 22:59:56 +0000717// - initialized data (starting at Config->GlobalBase)
718// - BSS data (not currently implemented in llvm)
719// - explicit stack (Config->ZStackSize)
720// - heap start / unallocated
Sam Clegga0f095e2018-05-03 17:21:53 +0000721//
722// The --stack-first option means that stack is placed before any static data.
Heejin Ahn4821ebf2018-08-29 21:03:16 +0000723// This can be useful since it means that stack overflow traps immediately
724// rather than overwriting global data, but also increases code size since all
725// static data loads and stores requires larger offsets.
Sam Cleggc94d3932017-11-17 18:14:09 +0000726void Writer::layoutMemory() {
Sam Cleggc94d3932017-11-17 18:14:09 +0000727 createOutputSegments();
728
Sam Clegga0f095e2018-05-03 17:21:53 +0000729 uint32_t MemoryPtr = 0;
730
731 auto PlaceStack = [&]() {
Sam Cleggbfb75342018-11-15 00:37:21 +0000732 if (Config->Relocatable || Config->Shared)
Sam Clegga0f095e2018-05-03 17:21:53 +0000733 return;
Heejin Ahna1cc4ea2019-02-04 19:13:46 +0000734 MemoryPtr = alignTo(MemoryPtr, StackAlignment);
735 if (Config->ZStackSize != alignTo(Config->ZStackSize, StackAlignment))
736 error("stack size must be " + Twine(StackAlignment) + "-byte aligned");
Sam Clegga0f095e2018-05-03 17:21:53 +0000737 log("mem: stack size = " + Twine(Config->ZStackSize));
738 log("mem: stack base = " + Twine(MemoryPtr));
739 MemoryPtr += Config->ZStackSize;
Sam Clegg2dad4e22018-11-15 18:15:54 +0000740 auto *SP = cast<DefinedGlobal>(WasmSym::StackPointer);
741 SP->Global->Global.InitExpr.Value.Int32 = MemoryPtr;
Sam Clegga0f095e2018-05-03 17:21:53 +0000742 log("mem: stack top = " + Twine(MemoryPtr));
743 };
744
745 if (Config->StackFirst) {
746 PlaceStack();
747 } else {
748 MemoryPtr = Config->GlobalBase;
749 log("mem: global base = " + Twine(Config->GlobalBase));
750 }
751
752 uint32_t DataStart = MemoryPtr;
753
Sam Cleggf0d433d2018-02-02 22:59:56 +0000754 // Arbitrarily set __dso_handle handle to point to the start of the data
755 // segments.
756 if (WasmSym::DsoHandle)
Sam Clegga0f095e2018-05-03 17:21:53 +0000757 WasmSym::DsoHandle->setVirtualAddress(DataStart);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000758
Sam Cleggbfb75342018-11-15 00:37:21 +0000759 MemAlign = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000760 for (OutputSegment *Seg : Segments) {
Sam Cleggbfb75342018-11-15 00:37:21 +0000761 MemAlign = std::max(MemAlign, Seg->Alignment);
Sam Clegg622ad042019-01-17 22:09:09 +0000762 MemoryPtr = alignTo(MemoryPtr, 1ULL << Seg->Alignment);
Sam Cleggc94d3932017-11-17 18:14:09 +0000763 Seg->StartVA = MemoryPtr;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000764 log(formatv("mem: {0,-15} offset={1,-8} size={2,-8} align={3}", Seg->Name,
765 MemoryPtr, Seg->Size, Seg->Alignment));
Sam Cleggc94d3932017-11-17 18:14:09 +0000766 MemoryPtr += Seg->Size;
767 }
768
Sam Cleggf0d433d2018-02-02 22:59:56 +0000769 // TODO: Add .bss space here.
Sam Clegg37a4a8a2018-02-07 03:04:53 +0000770 if (WasmSym::DataEnd)
771 WasmSym::DataEnd->setVirtualAddress(MemoryPtr);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000772
Sam Clegga0f095e2018-05-03 17:21:53 +0000773 log("mem: static data = " + Twine(MemoryPtr - DataStart));
Sam Cleggc94d3932017-11-17 18:14:09 +0000774
Sam Clegg2dad4e22018-11-15 18:15:54 +0000775 if (Config->Shared) {
776 MemSize = MemoryPtr;
777 return;
778 }
779
Sam Clegga0f095e2018-05-03 17:21:53 +0000780 if (!Config->StackFirst)
781 PlaceStack();
782
783 // Set `__heap_base` to directly follow the end of the stack or global data.
784 // The fact that this comes last means that a malloc/brk implementation
785 // can grow the heap at runtime.
Sam Cleggc94d3932017-11-17 18:14:09 +0000786 if (!Config->Relocatable) {
Sam Cleggf0d433d2018-02-02 22:59:56 +0000787 WasmSym::HeapBase->setVirtualAddress(MemoryPtr);
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000788 log("mem: heap base = " + Twine(MemoryPtr));
Sam Cleggc94d3932017-11-17 18:14:09 +0000789 }
790
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000791 if (Config->InitialMemory != 0) {
792 if (Config->InitialMemory != alignTo(Config->InitialMemory, WasmPageSize))
793 error("initial memory must be " + Twine(WasmPageSize) + "-byte aligned");
794 if (MemoryPtr > Config->InitialMemory)
795 error("initial memory too small, " + Twine(MemoryPtr) + " bytes needed");
796 else
797 MemoryPtr = Config->InitialMemory;
798 }
Sam Cleggbfb75342018-11-15 00:37:21 +0000799 MemSize = MemoryPtr;
800 NumMemoryPages = alignTo(MemoryPtr, WasmPageSize) / WasmPageSize;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000801 log("mem: total pages = " + Twine(NumMemoryPages));
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000802
803 if (Config->MaxMemory != 0) {
804 if (Config->MaxMemory != alignTo(Config->MaxMemory, WasmPageSize))
805 error("maximum memory must be " + Twine(WasmPageSize) + "-byte aligned");
806 if (MemoryPtr > Config->MaxMemory)
807 error("maximum memory too small, " + Twine(MemoryPtr) + " bytes needed");
808 MaxMemoryPages = Config->MaxMemory / WasmPageSize;
809 log("mem: max pages = " + Twine(MaxMemoryPages));
810 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000811}
812
813SyntheticSection *Writer::createSyntheticSection(uint32_t Type,
Sam Cleggc375e4e2018-01-10 19:18:22 +0000814 StringRef Name) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000815 auto Sec = make<SyntheticSection>(Type, Name);
Sam Cleggab2ac292017-12-20 05:14:48 +0000816 log("createSection: " + toString(*Sec));
Sam Cleggc94d3932017-11-17 18:14:09 +0000817 OutputSections.push_back(Sec);
818 return Sec;
819}
820
821void Writer::createSections() {
822 // Known sections
Sam Cleggbfb75342018-11-15 00:37:21 +0000823 if (Config->Pic)
824 createDylinkSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000825 createTypeSection();
826 createImportSection();
827 createFunctionSection();
828 createTableSection();
829 createMemorySection();
830 createGlobalSection();
Heejin Ahne915a712018-12-08 06:17:43 +0000831 createEventSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000832 createExportSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000833 createElemSection();
834 createCodeSection();
835 createDataSection();
Sam Clegg80ba4382018-04-10 16:12:49 +0000836 createCustomSections();
Sam Cleggc94d3932017-11-17 18:14:09 +0000837
838 // Custom sections
Sam Clegg99eb42c2018-02-27 23:58:03 +0000839 if (Config->Relocatable) {
Sam Clegg99eb42c2018-02-27 23:58:03 +0000840 createLinkingSection();
Nicholas Wilson94d3b162018-03-05 12:33:58 +0000841 createRelocSections();
Sam Clegg99eb42c2018-02-27 23:58:03 +0000842 }
Thomas Lively2a0868f2019-01-17 02:29:41 +0000843
Sam Cleggc94d3932017-11-17 18:14:09 +0000844 if (!Config->StripDebug && !Config->StripAll)
845 createNameSection();
846
Thomas Lively2a0868f2019-01-17 02:29:41 +0000847 if (!Config->StripAll)
848 createProducersSection();
849
Sam Cleggc94d3932017-11-17 18:14:09 +0000850 for (OutputSection *S : OutputSections) {
851 S->setOffset(FileSize);
852 S->finalizeContents();
853 FileSize += S->getSize();
854 }
855}
856
Sam Cleggc94d3932017-11-17 18:14:09 +0000857void Writer::calculateImports() {
Sam Clegg574d7ce2017-12-15 19:23:49 +0000858 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000859 if (!Sym->isUndefined())
860 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000861 if (Sym->isWeak() && !Config->Relocatable)
Sam Clegg574d7ce2017-12-15 19:23:49 +0000862 continue;
Nicholas Wilsona1e299f2018-04-20 17:18:06 +0000863 if (!Sym->isLive())
864 continue;
Sam Cleggc729c1b2018-05-30 18:07:52 +0000865 if (!Sym->IsUsedInRegularObj)
866 continue;
Sam Cleggd425d6b2019-03-12 21:53:23 +0000867 // In relocatable output we don't generate imports for data symbols.
868 // These live only in the symbol table.
869 if (Config->Relocatable && isa<DataSymbol>(Sym))
870 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000871
Nicola Zaghene7245b42018-05-15 13:36:20 +0000872 LLVM_DEBUG(dbgs() << "import: " << Sym->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000873 ImportedSymbols.emplace_back(Sym);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000874 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
875 F->setFunctionIndex(NumImportedFunctions++);
Heejin Ahne915a712018-12-08 06:17:43 +0000876 else if (auto *G = dyn_cast<GlobalSymbol>(Sym))
877 G->setGlobalIndex(NumImportedGlobals++);
Sam Cleggd425d6b2019-03-12 21:53:23 +0000878 else if (auto *D = dyn_cast<UndefinedData>(Sym))
879 D->setGlobalIndex(NumImportedGlobals++);
Sam Clegg93102972018-02-23 05:08:53 +0000880 else
Heejin Ahne915a712018-12-08 06:17:43 +0000881 cast<EventSymbol>(Sym)->setEventIndex(NumImportedEvents++);
Sam Cleggc94d3932017-11-17 18:14:09 +0000882 }
883}
884
Sam Cleggd3052d52018-01-18 23:40:49 +0000885void Writer::calculateExports() {
Sam Clegg93102972018-02-23 05:08:53 +0000886 if (Config->Relocatable)
887 return;
Sam Cleggf0d433d2018-02-02 22:59:56 +0000888
Sam Cleggd6beb322018-05-10 18:10:34 +0000889 if (!Config->Relocatable && !Config->ImportMemory)
890 Exports.push_back(WasmExport{"memory", WASM_EXTERNAL_MEMORY, 0});
891
892 if (!Config->Relocatable && Config->ExportTable)
Heejin Ahna1cc4ea2019-02-04 19:13:46 +0000893 Exports.push_back(WasmExport{FunctionTableName, WASM_EXTERNAL_TABLE, 0});
Sam Cleggd6beb322018-05-10 18:10:34 +0000894
895 unsigned FakeGlobalIndex = NumImportedGlobals + InputGlobals.size();
896
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000897 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Cleggce004bf2018-06-28 17:04:58 +0000898 if (!Sym->isExported())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000899 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000900 if (!Sym->isLive())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000901 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000902
Sam Cleggd6beb322018-05-10 18:10:34 +0000903 StringRef Name = Sym->getName();
904 WasmExport Export;
905 if (auto *F = dyn_cast<DefinedFunction>(Sym)) {
906 Export = {Name, WASM_EXTERNAL_FUNCTION, F->getFunctionIndex()};
907 } else if (auto *G = dyn_cast<DefinedGlobal>(Sym)) {
Sam Clegg177b4582018-06-07 01:27:07 +0000908 // TODO(sbc): Remove this check once to mutable global proposal is
909 // implement in all major browsers.
910 // See: https://github.com/WebAssembly/mutable-global
911 if (G->getGlobalType()->Mutable) {
912 // Only the __stack_pointer should ever be create as mutable.
913 assert(G == WasmSym::StackPointer);
914 continue;
915 }
Sam Cleggd6beb322018-05-10 18:10:34 +0000916 Export = {Name, WASM_EXTERNAL_GLOBAL, G->getGlobalIndex()};
Heejin Ahne915a712018-12-08 06:17:43 +0000917 } else if (auto *E = dyn_cast<DefinedEvent>(Sym)) {
918 Export = {Name, WASM_EXTERNAL_EVENT, E->getEventIndex()};
Sam Cleggd6beb322018-05-10 18:10:34 +0000919 } else {
920 auto *D = cast<DefinedData>(Sym);
Sam Clegg93102972018-02-23 05:08:53 +0000921 DefinedFakeGlobals.emplace_back(D);
Sam Cleggd6beb322018-05-10 18:10:34 +0000922 Export = {Name, WASM_EXTERNAL_GLOBAL, FakeGlobalIndex++};
923 }
924
Nicola Zaghene7245b42018-05-15 13:36:20 +0000925 LLVM_DEBUG(dbgs() << "Export: " << Name << "\n");
Sam Cleggd6beb322018-05-10 18:10:34 +0000926 Exports.push_back(Export);
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000927 }
Sam Clegg93102972018-02-23 05:08:53 +0000928}
929
930void Writer::assignSymtab() {
931 if (!Config->Relocatable)
932 return;
933
Sam Cleggd177ab22018-05-04 23:14:42 +0000934 StringMap<uint32_t> SectionSymbolIndices;
935
Sam Clegg93102972018-02-23 05:08:53 +0000936 unsigned SymbolIndex = SymtabEntries.size();
Sam Cleggd177ab22018-05-04 23:14:42 +0000937
Sam Clegg89e4dcb2019-01-30 18:55:15 +0000938 auto AddSymbol = [&](Symbol *Sym) {
939 if (auto *S = dyn_cast<SectionSymbol>(Sym)) {
940 StringRef Name = S->getName();
941 if (CustomSectionMapping.count(Name) == 0)
942 return;
Sam Cleggd177ab22018-05-04 23:14:42 +0000943
Sam Clegg89e4dcb2019-01-30 18:55:15 +0000944 auto SSI = SectionSymbolIndices.find(Name);
945 if (SSI != SectionSymbolIndices.end()) {
946 Sym->setOutputSymbolIndex(SSI->second);
947 return;
Sam Cleggd177ab22018-05-04 23:14:42 +0000948 }
949
Sam Clegg89e4dcb2019-01-30 18:55:15 +0000950 SectionSymbolIndices[Name] = SymbolIndex;
951 CustomSectionSymbols[Name] = cast<SectionSymbol>(Sym);
Sam Cleggd3052d52018-01-18 23:40:49 +0000952
Sam Clegg89e4dcb2019-01-30 18:55:15 +0000953 Sym->markLive();
954 }
955
956 // (Since this is relocatable output, GC is not performed so symbols must
957 // be live.)
958 assert(Sym->isLive());
959 Sym->setOutputSymbolIndex(SymbolIndex++);
960 SymtabEntries.emplace_back(Sym);
961 };
962
963 for (Symbol *Sym : Symtab->getSymbols())
Sam Cleggd15a41542019-03-08 21:10:48 +0000964 if (Sym->IsUsedInRegularObj)
Sam Clegg89e4dcb2019-01-30 18:55:15 +0000965 AddSymbol(Sym);
966
967 for (ObjFile *File : Symtab->ObjectFiles) {
968 LLVM_DEBUG(dbgs() << "Local symtab entries: " << File->getName() << "\n");
969 for (Symbol *Sym : File->getSymbols())
970 if (Sym->isLocal())
971 AddSymbol(Sym);
972 }
Sam Cleggd3052d52018-01-18 23:40:49 +0000973}
974
Sam Cleggc375e4e2018-01-10 19:18:22 +0000975uint32_t Writer::lookupType(const WasmSignature &Sig) {
Sam Clegg8d027d62018-01-10 20:12:26 +0000976 auto It = TypeIndices.find(Sig);
977 if (It == TypeIndices.end()) {
Sam Cleggc375e4e2018-01-10 19:18:22 +0000978 error("type not found: " + toString(Sig));
Sam Clegg8d027d62018-01-10 20:12:26 +0000979 return 0;
980 }
981 return It->second;
Sam Cleggc375e4e2018-01-10 19:18:22 +0000982}
983
984uint32_t Writer::registerType(const WasmSignature &Sig) {
Sam Cleggb8621592017-11-30 01:40:08 +0000985 auto Pair = TypeIndices.insert(std::make_pair(Sig, Types.size()));
Sam Cleggc375e4e2018-01-10 19:18:22 +0000986 if (Pair.second) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000987 LLVM_DEBUG(dbgs() << "type " << toString(Sig) << "\n");
Sam Cleggb8621592017-11-30 01:40:08 +0000988 Types.push_back(&Sig);
Sam Cleggc375e4e2018-01-10 19:18:22 +0000989 }
Sam Cleggb8621592017-11-30 01:40:08 +0000990 return Pair.first->second;
991}
992
Sam Cleggc94d3932017-11-17 18:14:09 +0000993void Writer::calculateTypes() {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000994 // The output type section is the union of the following sets:
995 // 1. Any signature used in the TYPE relocation
996 // 2. The signatures of all imported functions
997 // 3. The signatures of all defined functions
Heejin Ahne915a712018-12-08 06:17:43 +0000998 // 4. The signatures of all imported events
999 // 5. The signatures of all defined events
Sam Clegg8f6d2de2018-01-31 23:48:14 +00001000
Sam Cleggc94d3932017-11-17 18:14:09 +00001001 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +00001002 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
1003 for (uint32_t I = 0; I < Types.size(); I++)
1004 if (File->TypeIsUsed[I])
1005 File->TypeMap[I] = registerType(Types[I]);
Sam Cleggc94d3932017-11-17 18:14:09 +00001006 }
Sam Clegg50686852018-01-12 18:35:13 +00001007
Heejin Ahne915a712018-12-08 06:17:43 +00001008 for (const Symbol *Sym : ImportedSymbols) {
Sam Clegg93102972018-02-23 05:08:53 +00001009 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
Heejin Ahne915a712018-12-08 06:17:43 +00001010 registerType(*F->Signature);
1011 else if (auto *E = dyn_cast<EventSymbol>(Sym))
1012 registerType(*E->Signature);
1013 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +00001014
Sam Clegg9f934222018-02-21 18:29:23 +00001015 for (const InputFunction *F : InputFunctions)
Sam Clegg8f6d2de2018-01-31 23:48:14 +00001016 registerType(F->Signature);
Heejin Ahne915a712018-12-08 06:17:43 +00001017
1018 for (const InputEvent *E : InputEvents)
1019 registerType(E->Signature);
Sam Cleggc94d3932017-11-17 18:14:09 +00001020}
1021
Sam Clegg632c21792019-03-16 01:18:12 +00001022void Writer::processRelocations(InputChunk *Chunk) {
1023 if (!Chunk->Live)
1024 return;
1025 ObjFile *File = Chunk->File;
1026 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
1027 for (const WasmRelocation &Reloc : Chunk->getRelocations()) {
1028 switch (Reloc.Type) {
1029 case R_WASM_TABLE_INDEX_I32:
1030 case R_WASM_TABLE_INDEX_SLEB: {
1031 FunctionSymbol *Sym = File->getFunctionSymbol(Reloc.Index);
1032 if (Sym->hasTableIndex() || !Sym->hasFunctionIndex())
1033 continue;
1034 Sym->setTableIndex(TableBase + IndirectFunctions.size());
1035 IndirectFunctions.emplace_back(Sym);
1036 break;
1037 }
1038 case R_WASM_TYPE_INDEX_LEB:
1039 // Mark target type as live
1040 File->TypeMap[Reloc.Index] = registerType(Types[Reloc.Index]);
1041 File->TypeIsUsed[Reloc.Index] = true;
1042 break;
1043 case R_WASM_MEMORY_ADDR_SLEB:
1044 case R_WASM_MEMORY_ADDR_I32:
1045 case R_WASM_MEMORY_ADDR_LEB: {
1046 DataSymbol *DataSym = File->getDataSymbol(Reloc.Index);
1047 if (!Config->Relocatable && !isa<DefinedData>(DataSym) &&
1048 !DataSym->isWeak())
1049 error(File->getName() +
1050 ": relocation of type R_WASM_MEMORY_ADDR_* "
1051 "against undefined data symbol: " +
1052 DataSym->getName());
1053 break;
1054 }
1055 }
1056 }
1057}
1058
Sam Clegg8d146bb2018-01-09 23:56:44 +00001059void Writer::assignIndexes() {
Heejin Ahnaeaab992018-11-19 23:21:25 +00001060 assert(InputFunctions.empty());
1061 uint32_t FunctionIndex = NumImportedFunctions;
Nicholas Wilsonebda41f2018-03-09 16:43:05 +00001062 auto AddDefinedFunction = [&](InputFunction *Func) {
1063 if (!Func->Live)
1064 return;
1065 InputFunctions.emplace_back(Func);
Sam Clegge3f3ccf2018-03-12 19:56:23 +00001066 Func->setFunctionIndex(FunctionIndex++);
Nicholas Wilsonebda41f2018-03-09 16:43:05 +00001067 };
1068
Nicholas Wilson5639da82018-03-12 15:44:07 +00001069 for (InputFunction *Func : Symtab->SyntheticFunctions)
1070 AddDefinedFunction(Func);
1071
Sam Clegg87e61922018-01-08 23:39:11 +00001072 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001073 LLVM_DEBUG(dbgs() << "Functions: " << File->getName() << "\n");
Nicholas Wilsonebda41f2018-03-09 16:43:05 +00001074 for (InputFunction *Func : File->Functions)
1075 AddDefinedFunction(Func);
Sam Clegg8d146bb2018-01-09 23:56:44 +00001076 }
1077
1078 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001079 LLVM_DEBUG(dbgs() << "Handle relocs: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +00001080 for (InputChunk *Chunk : File->Functions)
Sam Clegg632c21792019-03-16 01:18:12 +00001081 processRelocations(Chunk);
Sam Clegg93102972018-02-23 05:08:53 +00001082 for (InputChunk *Chunk : File->Segments)
Sam Clegg632c21792019-03-16 01:18:12 +00001083 processRelocations(Chunk);
Sam Cleggd177ab22018-05-04 23:14:42 +00001084 for (auto &P : File->CustomSections)
Sam Clegg632c21792019-03-16 01:18:12 +00001085 processRelocations(P);
Sam Clegg93102972018-02-23 05:08:53 +00001086 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +00001087
Heejin Ahnaeaab992018-11-19 23:21:25 +00001088 assert(InputGlobals.empty());
1089 uint32_t GlobalIndex = NumImportedGlobals;
Sam Clegg93102972018-02-23 05:08:53 +00001090 auto AddDefinedGlobal = [&](InputGlobal *Global) {
1091 if (Global->Live) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001092 LLVM_DEBUG(dbgs() << "AddDefinedGlobal: " << GlobalIndex << "\n");
Sam Clegge3f3ccf2018-03-12 19:56:23 +00001093 Global->setGlobalIndex(GlobalIndex++);
Sam Clegg93102972018-02-23 05:08:53 +00001094 InputGlobals.push_back(Global);
1095 }
1096 };
1097
Nicholas Wilsonebda41f2018-03-09 16:43:05 +00001098 for (InputGlobal *Global : Symtab->SyntheticGlobals)
1099 AddDefinedGlobal(Global);
Sam Clegg93102972018-02-23 05:08:53 +00001100
1101 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001102 LLVM_DEBUG(dbgs() << "Globals: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +00001103 for (InputGlobal *Global : File->Globals)
1104 AddDefinedGlobal(Global);
Sam Cleggc94d3932017-11-17 18:14:09 +00001105 }
Heejin Ahne915a712018-12-08 06:17:43 +00001106
1107 assert(InputEvents.empty());
1108 uint32_t EventIndex = NumImportedEvents;
1109 auto AddDefinedEvent = [&](InputEvent *Event) {
1110 if (Event->Live) {
1111 LLVM_DEBUG(dbgs() << "AddDefinedEvent: " << EventIndex << "\n");
1112 Event->setEventIndex(EventIndex++);
1113 InputEvents.push_back(Event);
1114 }
1115 };
1116
1117 for (ObjFile *File : Symtab->ObjectFiles) {
1118 LLVM_DEBUG(dbgs() << "Events: " << File->getName() << "\n");
1119 for (InputEvent *Event : File->Events)
1120 AddDefinedEvent(Event);
1121 }
Sam Cleggc94d3932017-11-17 18:14:09 +00001122}
1123
1124static StringRef getOutputDataSegmentName(StringRef Name) {
Sam Cleggbfb75342018-11-15 00:37:21 +00001125 // With PIC code we currently only support a single data segment since
1126 // we only have a single __memory_base to use as our base address.
1127 if (Config->Pic)
1128 return "data";
Sam Clegg66844762018-05-10 18:23:51 +00001129 if (!Config->MergeDataSegments)
Sam Cleggc94d3932017-11-17 18:14:09 +00001130 return Name;
Rui Ueyama4764b572018-02-28 00:57:28 +00001131 if (Name.startswith(".text."))
1132 return ".text";
1133 if (Name.startswith(".data."))
1134 return ".data";
1135 if (Name.startswith(".bss."))
1136 return ".bss";
Sam Clegg57694c52018-08-08 18:02:55 +00001137 if (Name.startswith(".rodata."))
1138 return ".rodata";
Sam Cleggc94d3932017-11-17 18:14:09 +00001139 return Name;
1140}
1141
1142void Writer::createOutputSegments() {
1143 for (ObjFile *File : Symtab->ObjectFiles) {
1144 for (InputSegment *Segment : File->Segments) {
Sam Clegg447ae402018-02-13 20:29:38 +00001145 if (!Segment->Live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +00001146 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +00001147 StringRef Name = getOutputDataSegmentName(Segment->getName());
1148 OutputSegment *&S = SegmentMap[Name];
1149 if (S == nullptr) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001150 LLVM_DEBUG(dbgs() << "new segment: " << Name << "\n");
Sam Clegg93102972018-02-23 05:08:53 +00001151 S = make<OutputSegment>(Name, Segments.size());
Sam Cleggc94d3932017-11-17 18:14:09 +00001152 Segments.push_back(S);
1153 }
1154 S->addInputSegment(Segment);
Nicola Zaghene7245b42018-05-15 13:36:20 +00001155 LLVM_DEBUG(dbgs() << "added data: " << Name << ": " << S->Size << "\n");
Sam Cleggc94d3932017-11-17 18:14:09 +00001156 }
1157 }
1158}
1159
Sam Clegg50686852018-01-12 18:35:13 +00001160static const int OPCODE_CALL = 0x10;
1161static const int OPCODE_END = 0xb;
1162
1163// Create synthetic "__wasm_call_ctors" function based on ctor functions
1164// in input object.
1165void Writer::createCtorFunction() {
Sam Clegg0e6b42f2019-03-01 22:35:47 +00001166 if (!WasmSym::CallCtors->isLive())
1167 return;
1168
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +00001169 // First write the body's contents to a string.
1170 std::string BodyContent;
Sam Clegg50686852018-01-12 18:35:13 +00001171 {
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +00001172 raw_string_ostream OS(BodyContent);
Sam Clegg50686852018-01-12 18:35:13 +00001173 writeUleb128(OS, 0, "num locals");
Sam Clegg93102972018-02-23 05:08:53 +00001174 for (const WasmInitEntry &F : InitFunctions) {
Sam Clegg50686852018-01-12 18:35:13 +00001175 writeU8(OS, OPCODE_CALL, "CALL");
Sam Clegge3f3ccf2018-03-12 19:56:23 +00001176 writeUleb128(OS, F.Sym->getFunctionIndex(), "function index");
Sam Clegg50686852018-01-12 18:35:13 +00001177 }
1178 writeU8(OS, OPCODE_END, "END");
1179 }
1180
1181 // Once we know the size of the body we can create the final function body
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +00001182 std::string FunctionBody;
1183 {
1184 raw_string_ostream OS(FunctionBody);
1185 writeUleb128(OS, BodyContent.size(), "function size");
1186 OS << BodyContent;
1187 }
Rui Ueyama29abfe42018-02-28 17:43:15 +00001188
Sam Cleggea656472018-10-22 08:35:39 +00001189 ArrayRef<uint8_t> Body = arrayRefFromStringRef(Saver.save(FunctionBody));
Nicholas Wilsonebda41f2018-03-09 16:43:05 +00001190 cast<SyntheticFunction>(WasmSym::CallCtors->Function)->setBody(Body);
Sam Clegg50686852018-01-12 18:35:13 +00001191}
1192
1193// Populate InitFunctions vector with init functions from all input objects.
1194// This is then used either when creating the output linking section or to
1195// synthesize the "__wasm_call_ctors" function.
1196void Writer::calculateInitFunctions() {
Sam Clegg61f13b32019-03-02 04:55:02 +00001197 if (!Config->Relocatable && !WasmSym::CallCtors->isLive())
1198 return;
1199
Sam Clegg50686852018-01-12 18:35:13 +00001200 for (ObjFile *File : Symtab->ObjectFiles) {
1201 const WasmLinkingData &L = File->getWasmObj()->linkingData();
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +00001202 for (const WasmInitFunc &F : L.InitFunctions) {
1203 FunctionSymbol *Sym = File->getFunctionSymbol(F.Symbol);
Sam Clegg0e6b42f2019-03-01 22:35:47 +00001204 assert(Sym->isLive());
Heejin Ahne915a712018-12-08 06:17:43 +00001205 if (*Sym->Signature != WasmSignature{{}, {}})
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +00001206 error("invalid signature for init func: " + toString(*Sym));
1207 InitFunctions.emplace_back(WasmInitEntry{Sym, F.Priority});
1208 }
Sam Clegg50686852018-01-12 18:35:13 +00001209 }
Rui Ueyamada69b712018-02-28 00:15:59 +00001210
Sam Clegg50686852018-01-12 18:35:13 +00001211 // Sort in order of priority (lowest first) so that they are called
1212 // in the correct order.
Sam Clegg29b8feb2018-02-21 00:34:34 +00001213 std::stable_sort(InitFunctions.begin(), InitFunctions.end(),
Sam Clegg93102972018-02-23 05:08:53 +00001214 [](const WasmInitEntry &L, const WasmInitEntry &R) {
Sam Clegg29b8feb2018-02-21 00:34:34 +00001215 return L.Priority < R.Priority;
1216 });
Sam Clegg50686852018-01-12 18:35:13 +00001217}
1218
Sam Cleggc94d3932017-11-17 18:14:09 +00001219void Writer::run() {
Sam Cleggbfb75342018-11-15 00:37:21 +00001220 if (Config->Relocatable || Config->Pic)
Sam Clegg99eb42c2018-02-27 23:58:03 +00001221 Config->GlobalBase = 0;
1222
Sam Cleggbfb75342018-11-15 00:37:21 +00001223 // For PIC code the table base is assigned dynamically by the loader.
1224 // For non-PIC, we start at 1 so that accessing table index 0 always traps.
1225 if (!Config->Pic)
1226 TableBase = 1;
1227
Sam Cleggc94d3932017-11-17 18:14:09 +00001228 log("-- calculateImports");
1229 calculateImports();
Sam Clegg8d146bb2018-01-09 23:56:44 +00001230 log("-- assignIndexes");
1231 assignIndexes();
Sam Clegg50686852018-01-12 18:35:13 +00001232 log("-- calculateInitFunctions");
1233 calculateInitFunctions();
1234 if (!Config->Relocatable)
1235 createCtorFunction();
Sam Clegg8f6d2de2018-01-31 23:48:14 +00001236 log("-- calculateTypes");
1237 calculateTypes();
Sam Clegg93102972018-02-23 05:08:53 +00001238 log("-- layoutMemory");
1239 layoutMemory();
1240 log("-- calculateExports");
1241 calculateExports();
Sam Cleggd177ab22018-05-04 23:14:42 +00001242 log("-- calculateCustomSections");
1243 calculateCustomSections();
Sam Clegg93102972018-02-23 05:08:53 +00001244 log("-- assignSymtab");
1245 assignSymtab();
Sam Cleggc94d3932017-11-17 18:14:09 +00001246
1247 if (errorHandler().Verbose) {
Sam Clegg9f934222018-02-21 18:29:23 +00001248 log("Defined Functions: " + Twine(InputFunctions.size()));
Sam Clegg93102972018-02-23 05:08:53 +00001249 log("Defined Globals : " + Twine(InputGlobals.size()));
Heejin Ahne915a712018-12-08 06:17:43 +00001250 log("Defined Events : " + Twine(InputEvents.size()));
Sam Clegg93102972018-02-23 05:08:53 +00001251 log("Function Imports : " + Twine(NumImportedFunctions));
1252 log("Global Imports : " + Twine(NumImportedGlobals));
Heejin Ahne915a712018-12-08 06:17:43 +00001253 log("Event Imports : " + Twine(NumImportedEvents));
Sam Cleggc94d3932017-11-17 18:14:09 +00001254 for (ObjFile *File : Symtab->ObjectFiles)
1255 File->dumpInfo();
1256 }
1257
Sam Cleggc94d3932017-11-17 18:14:09 +00001258 createHeader();
1259 log("-- createSections");
1260 createSections();
1261
1262 log("-- openFile");
1263 openFile();
1264 if (errorCount())
1265 return;
1266
1267 writeHeader();
1268
1269 log("-- writeSections");
1270 writeSections();
1271 if (errorCount())
1272 return;
1273
1274 if (Error E = Buffer->commit())
1275 fatal("failed to write the output file: " + toString(std::move(E)));
1276}
1277
1278// Open a result file.
1279void Writer::openFile() {
1280 log("writing: " + Config->OutputFile);
Sam Cleggc94d3932017-11-17 18:14:09 +00001281
1282 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
1283 FileOutputBuffer::create(Config->OutputFile, FileSize,
1284 FileOutputBuffer::F_executable);
1285
1286 if (!BufferOrErr)
1287 error("failed to open " + Config->OutputFile + ": " +
1288 toString(BufferOrErr.takeError()));
1289 else
1290 Buffer = std::move(*BufferOrErr);
1291}
1292
1293void Writer::createHeader() {
1294 raw_string_ostream OS(Header);
1295 writeBytes(OS, WasmMagic, sizeof(WasmMagic), "wasm magic");
1296 writeU32(OS, WasmVersion, "wasm version");
1297 OS.flush();
1298 FileSize += Header.size();
1299}
1300
1301void lld::wasm::writeResult() { Writer().run(); }