blob: ea65bc3259980eb02c3ebaaddd88d079b6f1b222 [file] [log] [blame]
Sam Cleggc94d3932017-11-17 18:14:09 +00001//===- Writer.cpp ---------------------------------------------------------===//
2//
3// The LLVM Linker
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "Writer.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000011#include "Config.h"
Sam Clegg5fa274b2018-01-10 01:13:34 +000012#include "InputChunks.h"
Heejin Ahne915a712018-12-08 06:17:43 +000013#include "InputEvent.h"
Sam Clegg93102972018-02-23 05:08:53 +000014#include "InputGlobal.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000015#include "OutputSections.h"
16#include "OutputSegment.h"
17#include "SymbolTable.h"
18#include "WriterUtils.h"
19#include "lld/Common/ErrorHandler.h"
Rui Ueyama2017d522017-11-28 20:39:17 +000020#include "lld/Common/Memory.h"
Nicholas Wilson8269f372018-03-07 10:37:50 +000021#include "lld/Common/Strings.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000022#include "lld/Common/Threads.h"
Sam Clegg3141ddc2018-02-20 21:53:18 +000023#include "llvm/ADT/DenseSet.h"
Thomas Lively7ec7a292019-01-16 23:46:15 +000024#include "llvm/ADT/SmallSet.h"
25#include "llvm/ADT/SmallVector.h"
Sam Clegg80ba4382018-04-10 16:12:49 +000026#include "llvm/ADT/StringMap.h"
Sam Clegg93102972018-02-23 05:08:53 +000027#include "llvm/BinaryFormat/Wasm.h"
Nicholas Wilson3e3f5fb2018-03-14 15:58:16 +000028#include "llvm/Object/WasmTraits.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000029#include "llvm/Support/FileOutputBuffer.h"
30#include "llvm/Support/Format.h"
31#include "llvm/Support/FormatVariadic.h"
32#include "llvm/Support/LEB128.h"
33
34#include <cstdarg>
Sam Clegge0f6fcd2018-01-12 22:25:17 +000035#include <map>
Sam Cleggc94d3932017-11-17 18:14:09 +000036
37#define DEBUG_TYPE "lld"
38
39using namespace llvm;
40using namespace llvm::wasm;
41using namespace lld;
42using namespace lld::wasm;
43
44static constexpr int kStackAlignment = 16;
Nicholas Wilson874eedd2018-03-27 17:38:51 +000045static constexpr const char *kFunctionTableName = "__indirect_function_table";
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 Lively7ec7a292019-01-16 23:46:15 +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;
161 Import.Module = "env";
162 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;
178 Import.Module = "env";
179 Import.Field = kFunctionTableName;
180 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;
188 Import.Module = "env";
189 Import.Field = Sym->getName();
Sam Clegg93102972018-02-23 05:08:53 +0000190 if (auto *FunctionSym = dyn_cast<FunctionSymbol>(Sym)) {
191 Import.Kind = WASM_EXTERNAL_FUNCTION;
Heejin Ahne915a712018-12-08 06:17:43 +0000192 Import.SigIndex = lookupType(*FunctionSym->Signature);
193 } else if (auto *GlobalSym = dyn_cast<GlobalSymbol>(Sym)) {
Sam Clegg93102972018-02-23 05:08:53 +0000194 Import.Kind = WASM_EXTERNAL_GLOBAL;
195 Import.Global = *GlobalSym->getGlobalType();
Heejin Ahne915a712018-12-08 06:17:43 +0000196 } else {
197 auto *EventSym = cast<EventSymbol>(Sym);
198 Import.Kind = WASM_EXTERNAL_EVENT;
199 Import.Event.Attribute = EventSym->getEventType()->Attribute;
200 Import.Event.SigIndex = lookupType(*EventSym->Signature);
Sam Clegg93102972018-02-23 05:08:53 +0000201 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000202 writeImport(OS, Import);
203 }
204}
205
206void Writer::createTypeSection() {
207 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TYPE);
208 raw_ostream &OS = Section->getStream();
209 writeUleb128(OS, Types.size(), "type count");
Sam Cleggd451da12017-12-19 19:56:27 +0000210 for (const WasmSignature *Sig : Types)
Sam Cleggc94d3932017-11-17 18:14:09 +0000211 writeSig(OS, *Sig);
Sam Cleggc94d3932017-11-17 18:14:09 +0000212}
213
214void Writer::createFunctionSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000215 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000216 return;
217
218 SyntheticSection *Section = createSyntheticSection(WASM_SEC_FUNCTION);
219 raw_ostream &OS = Section->getStream();
220
Sam Clegg9f934222018-02-21 18:29:23 +0000221 writeUleb128(OS, InputFunctions.size(), "function count");
222 for (const InputFunction *Func : InputFunctions)
Sam Cleggc375e4e2018-01-10 19:18:22 +0000223 writeUleb128(OS, lookupType(Func->Signature), "sig index");
Sam Cleggc94d3932017-11-17 18:14:09 +0000224}
225
226void Writer::createMemorySection() {
227 if (Config->ImportMemory)
228 return;
229
230 SyntheticSection *Section = createSyntheticSection(WASM_SEC_MEMORY);
231 raw_ostream &OS = Section->getStream();
232
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000233 bool HasMax = MaxMemoryPages != 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000234 writeUleb128(OS, 1, "memory count");
Derek Schuff786760a2018-11-06 18:02:39 +0000235 unsigned Flags = 0;
236 if (HasMax)
237 Flags |= WASM_LIMITS_FLAG_HAS_MAX;
Derek Schuff3bea8bc2018-11-06 17:59:32 +0000238 if (Config->SharedMemory)
239 Flags |= WASM_LIMITS_FLAG_IS_SHARED;
240 writeUleb128(OS, Flags, "memory limits flags");
Sam Cleggc94d3932017-11-17 18:14:09 +0000241 writeUleb128(OS, NumMemoryPages, "initial pages");
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000242 if (HasMax)
243 writeUleb128(OS, MaxMemoryPages, "max pages");
Sam Cleggc94d3932017-11-17 18:14:09 +0000244}
245
246void Writer::createGlobalSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000247 unsigned NumGlobals = InputGlobals.size() + DefinedFakeGlobals.size();
248 if (NumGlobals == 0)
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000249 return;
250
Sam Cleggc94d3932017-11-17 18:14:09 +0000251 SyntheticSection *Section = createSyntheticSection(WASM_SEC_GLOBAL);
252 raw_ostream &OS = Section->getStream();
253
Sam Clegg93102972018-02-23 05:08:53 +0000254 writeUleb128(OS, NumGlobals, "global count");
255 for (const InputGlobal *G : InputGlobals)
256 writeGlobal(OS, G->Global);
257 for (const DefinedData *Sym : DefinedFakeGlobals) {
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000258 WasmGlobal Global;
Sam Clegg93102972018-02-23 05:08:53 +0000259 Global.Type = {WASM_TYPE_I32, false};
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000260 Global.InitExpr.Opcode = WASM_OPCODE_I32_CONST;
261 Global.InitExpr.Value.Int32 = Sym->getVirtualAddress();
Sam Cleggc94d3932017-11-17 18:14:09 +0000262 writeGlobal(OS, Global);
263 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000264}
265
Heejin Ahne915a712018-12-08 06:17:43 +0000266// The event section contains a list of declared wasm events associated with the
267// module. Currently the only supported event kind is exceptions. A single event
268// entry represents a single event with an event tag. All C++ exceptions are
269// represented by a single event. An event entry in this section contains
270// information on what kind of event it is (e.g. exception) and the type of
271// values contained in a single event object. (In wasm, an event can contain
272// multiple values of primitive types. But for C++ exceptions, we just throw a
273// pointer which is an i32 value (for wasm32 architecture), so the signature of
274// C++ exception is (i32)->(void), because all event types are assumed to have
275// void return type to share WasmSignature with functions.)
276void Writer::createEventSection() {
277 unsigned NumEvents = InputEvents.size();
278 if (NumEvents == 0)
279 return;
280
281 SyntheticSection *Section = createSyntheticSection(WASM_SEC_EVENT);
282 raw_ostream &OS = Section->getStream();
283
284 writeUleb128(OS, NumEvents, "event count");
285 for (InputEvent *E : InputEvents) {
286 E->Event.Type.SigIndex = lookupType(E->Signature);
287 writeEvent(OS, E->Event);
288 }
289}
290
Sam Cleggc94d3932017-11-17 18:14:09 +0000291void Writer::createTableSection() {
Nicholas Wilsonfc90b302018-03-28 12:53:29 +0000292 if (Config->ImportTable)
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000293 return;
294
295 // Always output a table section (or table import), even if there are no
296 // indirect calls. There are two reasons for this:
Sam Cleggfc1a9122017-12-11 22:00:56 +0000297 // 1. For executables it is useful to have an empty table slot at 0
298 // which can be filled with a null function call handler.
299 // 2. If we don't do this, any program that contains a call_indirect but
300 // no address-taken function will fail at validation time since it is
301 // a validation error to include a call_indirect instruction if there
302 // is not table.
Sam Cleggbfb75342018-11-15 00:37:21 +0000303 uint32_t TableSize = TableBase + IndirectFunctions.size();
Sam Cleggfc1a9122017-12-11 22:00:56 +0000304
Sam Cleggc94d3932017-11-17 18:14:09 +0000305 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TABLE);
306 raw_ostream &OS = Section->getStream();
307
308 writeUleb128(OS, 1, "table count");
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000309 WasmLimits Limits = {WASM_LIMITS_FLAG_HAS_MAX, TableSize, TableSize};
Thomas Lively25ff8932019-01-08 06:25:55 +0000310 writeTableType(OS, WasmTable{WASM_TYPE_FUNCREF, Limits});
Sam Cleggc94d3932017-11-17 18:14:09 +0000311}
312
313void Writer::createExportSection() {
Sam Cleggd6beb322018-05-10 18:10:34 +0000314 if (!Exports.size())
Sam Cleggc94d3932017-11-17 18:14:09 +0000315 return;
316
317 SyntheticSection *Section = createSyntheticSection(WASM_SEC_EXPORT);
318 raw_ostream &OS = Section->getStream();
319
Sam Cleggd6beb322018-05-10 18:10:34 +0000320 writeUleb128(OS, Exports.size(), "export count");
321 for (const WasmExport &Export : Exports)
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000322 writeExport(OS, Export);
Sam Cleggc94d3932017-11-17 18:14:09 +0000323}
324
Sam Cleggd177ab22018-05-04 23:14:42 +0000325void Writer::calculateCustomSections() {
326 log("calculateCustomSections");
327 bool StripDebug = Config->StripDebug || Config->StripAll;
328 for (ObjFile *File : Symtab->ObjectFiles) {
329 for (InputSection *Section : File->CustomSections) {
330 StringRef Name = Section->getName();
331 // These custom sections are known the linker and synthesized rather than
332 // blindly copied
Thomas Lively7ec7a292019-01-16 23:46:15 +0000333 if (Name == "linking" || Name == "name" || Name == "producers" ||
334 Name.startswith("reloc."))
Sam Cleggd177ab22018-05-04 23:14:42 +0000335 continue;
336 // .. or it is a debug section
337 if (StripDebug && Name.startswith(".debug_"))
338 continue;
339 CustomSectionMapping[Name].push_back(Section);
340 }
341 }
342}
343
Sam Clegg80ba4382018-04-10 16:12:49 +0000344void Writer::createCustomSections() {
345 log("createCustomSections");
Sam Clegg80ba4382018-04-10 16:12:49 +0000346 for (auto &Pair : CustomSectionMapping) {
347 StringRef Name = Pair.first();
Sam Cleggd177ab22018-05-04 23:14:42 +0000348
349 auto P = CustomSectionSymbols.find(Name);
350 if (P != CustomSectionSymbols.end()) {
351 uint32_t SectionIndex = OutputSections.size();
352 P->second->setOutputSectionIndex(SectionIndex);
353 }
354
Nicola Zaghene7245b42018-05-15 13:36:20 +0000355 LLVM_DEBUG(dbgs() << "createCustomSection: " << Name << "\n");
Sam Clegg80ba4382018-04-10 16:12:49 +0000356 OutputSections.push_back(make<CustomSection>(Name, Pair.second));
357 }
358}
359
Sam Cleggc94d3932017-11-17 18:14:09 +0000360void Writer::createElemSection() {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000361 if (IndirectFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000362 return;
363
364 SyntheticSection *Section = createSyntheticSection(WASM_SEC_ELEM);
365 raw_ostream &OS = Section->getStream();
366
367 writeUleb128(OS, 1, "segment count");
368 writeUleb128(OS, 0, "table index");
369 WasmInitExpr InitExpr;
Sam Cleggbfb75342018-11-15 00:37:21 +0000370 if (Config->Pic) {
Thomas Lively25ff8932019-01-08 06:25:55 +0000371 InitExpr.Opcode = WASM_OPCODE_GLOBAL_GET;
Sam Clegg2dad4e22018-11-15 18:15:54 +0000372 InitExpr.Value.Global = WasmSym::TableBase->getGlobalIndex();
Sam Cleggbfb75342018-11-15 00:37:21 +0000373 } else {
374 InitExpr.Opcode = WASM_OPCODE_I32_CONST;
375 InitExpr.Value.Int32 = TableBase;
376 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000377 writeInitExpr(OS, InitExpr);
Sam Cleggfc1a9122017-12-11 22:00:56 +0000378 writeUleb128(OS, IndirectFunctions.size(), "elem count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000379
Sam Cleggbfb75342018-11-15 00:37:21 +0000380 uint32_t TableIndex = TableBase;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000381 for (const FunctionSymbol *Sym : IndirectFunctions) {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000382 assert(Sym->getTableIndex() == TableIndex);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000383 writeUleb128(OS, Sym->getFunctionIndex(), "function index");
Sam Cleggfc1a9122017-12-11 22:00:56 +0000384 ++TableIndex;
385 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000386}
387
388void Writer::createCodeSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000389 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000390 return;
391
392 log("createCodeSection");
393
Sam Clegg9f934222018-02-21 18:29:23 +0000394 auto Section = make<CodeSection>(InputFunctions);
Sam Cleggc94d3932017-11-17 18:14:09 +0000395 OutputSections.push_back(Section);
396}
397
398void Writer::createDataSection() {
399 if (!Segments.size())
400 return;
401
402 log("createDataSection");
403 auto Section = make<DataSection>(Segments);
404 OutputSections.push_back(Section);
405}
406
Sam Cleggd451da12017-12-19 19:56:27 +0000407// Create relocations sections in the final output.
Sam Cleggc94d3932017-11-17 18:14:09 +0000408// These are only created when relocatable output is requested.
409void Writer::createRelocSections() {
410 log("createRelocSections");
411 // Don't use iterator here since we are adding to OutputSection
412 size_t OrigSize = OutputSections.size();
Rui Ueyamaffa650a2018-04-24 23:09:57 +0000413 for (size_t I = 0; I < OrigSize; I++) {
414 OutputSection *OSec = OutputSections[I];
Rui Ueyama37254062018-02-28 00:01:31 +0000415 uint32_t Count = OSec->numRelocations();
Sam Cleggc94d3932017-11-17 18:14:09 +0000416 if (!Count)
417 continue;
418
Rui Ueyama37254062018-02-28 00:01:31 +0000419 StringRef Name;
420 if (OSec->Type == WASM_SEC_DATA)
421 Name = "reloc.DATA";
422 else if (OSec->Type == WASM_SEC_CODE)
423 Name = "reloc.CODE";
Sam Cleggd177ab22018-05-04 23:14:42 +0000424 else if (OSec->Type == WASM_SEC_CUSTOM)
425 Name = Saver.save("reloc." + OSec->Name);
Sam Cleggc94d3932017-11-17 18:14:09 +0000426 else
Sam Cleggd177ab22018-05-04 23:14:42 +0000427 llvm_unreachable(
428 "relocations only supported for code, data, or custom sections");
Sam Cleggc94d3932017-11-17 18:14:09 +0000429
Rui Ueyama37254062018-02-28 00:01:31 +0000430 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, Name);
Sam Cleggc94d3932017-11-17 18:14:09 +0000431 raw_ostream &OS = Section->getStream();
Rui Ueyamaffa650a2018-04-24 23:09:57 +0000432 writeUleb128(OS, I, "reloc section");
Sam Cleggc94d3932017-11-17 18:14:09 +0000433 writeUleb128(OS, Count, "reloc count");
Rui Ueyama37254062018-02-28 00:01:31 +0000434 OSec->writeRelocations(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000435 }
436}
437
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000438static uint32_t getWasmFlags(const Symbol *Sym) {
439 uint32_t Flags = 0;
440 if (Sym->isLocal())
441 Flags |= WASM_SYMBOL_BINDING_LOCAL;
442 if (Sym->isWeak())
443 Flags |= WASM_SYMBOL_BINDING_WEAK;
444 if (Sym->isHidden())
445 Flags |= WASM_SYMBOL_VISIBILITY_HIDDEN;
446 if (Sym->isUndefined())
447 Flags |= WASM_SYMBOL_UNDEFINED;
448 return Flags;
449}
450
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000451// Some synthetic sections (e.g. "name" and "linking") have subsections.
452// Just like the synthetic sections themselves these need to be created before
453// they can be written out (since they are preceded by their length). This
454// class is used to create subsections and then write them into the stream
455// of the parent section.
456class SubSection {
457public:
458 explicit SubSection(uint32_t Type) : Type(Type) {}
459
460 void writeTo(raw_ostream &To) {
461 OS.flush();
Rui Ueyama67769102018-02-28 03:38:14 +0000462 writeUleb128(To, Type, "subsection type");
463 writeUleb128(To, Body.size(), "subsection size");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000464 To.write(Body.data(), Body.size());
465 }
466
467private:
468 uint32_t Type;
469 std::string Body;
470
471public:
472 raw_string_ostream OS{Body};
473};
474
Sam Cleggbfb75342018-11-15 00:37:21 +0000475// Create the custom "dylink" section containing information for the dynamic
476// linker.
477// See
478// https://github.com/WebAssembly/tool-conventions/blob/master/DynamicLinking.md
479void Writer::createDylinkSection() {
480 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "dylink");
481 raw_ostream &OS = Section->getStream();
482
483 writeUleb128(OS, MemSize, "MemSize");
Sam Clegg6320efb2019-01-16 01:43:21 +0000484 writeUleb128(OS, MemAlign, "MemAlign");
Sam Cleggbfb75342018-11-15 00:37:21 +0000485 writeUleb128(OS, IndirectFunctions.size(), "TableSize");
486 writeUleb128(OS, 0, "TableAlign");
Sam Clegge01c6462018-12-12 23:44:59 +0000487 writeUleb128(OS, 0, "Needed"); // TODO: Support "needed" shared libraries
Sam Cleggbfb75342018-11-15 00:37:21 +0000488}
489
Sam Clegg49ed9262017-12-01 00:53:21 +0000490// Create the custom "linking" section containing linker metadata.
Sam Cleggc94d3932017-11-17 18:14:09 +0000491// This is only created when relocatable output is requested.
492void Writer::createLinkingSection() {
493 SyntheticSection *Section =
494 createSyntheticSection(WASM_SEC_CUSTOM, "linking");
495 raw_ostream &OS = Section->getStream();
496
Sam Clegg2b8b1792018-04-26 18:17:21 +0000497 writeUleb128(OS, WasmMetadataVersion, "Version");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000498
Sam Clegg93102972018-02-23 05:08:53 +0000499 if (!SymtabEntries.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000500 SubSection Sub(WASM_SYMBOL_TABLE);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000501 writeUleb128(Sub.OS, SymtabEntries.size(), "num symbols");
502
Sam Clegg93102972018-02-23 05:08:53 +0000503 for (const Symbol *Sym : SymtabEntries) {
504 assert(Sym->isDefined() || Sym->isUndefined());
505 WasmSymbolType Kind = Sym->getWasmType();
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000506 uint32_t Flags = getWasmFlags(Sym);
507
Sam Clegg8518e7d2018-03-01 18:06:39 +0000508 writeU8(Sub.OS, Kind, "sym kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000509 writeUleb128(Sub.OS, Flags, "sym flags");
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000510
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000511 if (auto *F = dyn_cast<FunctionSymbol>(Sym)) {
512 writeUleb128(Sub.OS, F->getFunctionIndex(), "index");
Sam Clegg93102972018-02-23 05:08:53 +0000513 if (Sym->isDefined())
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000514 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000515 } else if (auto *G = dyn_cast<GlobalSymbol>(Sym)) {
516 writeUleb128(Sub.OS, G->getGlobalIndex(), "index");
517 if (Sym->isDefined())
518 writeStr(Sub.OS, Sym->getName(), "sym name");
Heejin Ahne915a712018-12-08 06:17:43 +0000519 } else if (auto *E = dyn_cast<EventSymbol>(Sym)) {
520 writeUleb128(Sub.OS, E->getEventIndex(), "index");
521 if (Sym->isDefined())
522 writeStr(Sub.OS, Sym->getName(), "sym name");
Andrea Di Biagio25c1a2f2018-05-05 10:53:31 +0000523 } else if (isa<DataSymbol>(Sym)) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000524 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegg93102972018-02-23 05:08:53 +0000525 if (auto *DataSym = dyn_cast<DefinedData>(Sym)) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000526 writeUleb128(Sub.OS, DataSym->getOutputSegmentIndex(), "index");
527 writeUleb128(Sub.OS, DataSym->getOutputSegmentOffset(),
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000528 "data offset");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000529 writeUleb128(Sub.OS, DataSym->getSize(), "data size");
Sam Clegg93102972018-02-23 05:08:53 +0000530 }
Sam Cleggd177ab22018-05-04 23:14:42 +0000531 } else {
532 auto *S = cast<SectionSymbol>(Sym);
533 writeUleb128(Sub.OS, S->getOutputSectionIndex(), "sym section index");
Sam Clegg93102972018-02-23 05:08:53 +0000534 }
Sam Cleggd3052d52018-01-18 23:40:49 +0000535 }
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000536
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000537 Sub.writeTo(OS);
Sam Cleggd3052d52018-01-18 23:40:49 +0000538 }
539
Sam Clegg0d0dd392017-12-19 17:09:45 +0000540 if (Segments.size()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000541 SubSection Sub(WASM_SEGMENT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000542 writeUleb128(Sub.OS, Segments.size(), "num data segments");
Sam Cleggc94d3932017-11-17 18:14:09 +0000543 for (const OutputSegment *S : Segments) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000544 writeStr(Sub.OS, S->Name, "segment name");
545 writeUleb128(Sub.OS, S->Alignment, "alignment");
546 writeUleb128(Sub.OS, 0, "flags");
Sam Cleggc94d3932017-11-17 18:14:09 +0000547 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000548 Sub.writeTo(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000549 }
Sam Clegg0d0dd392017-12-19 17:09:45 +0000550
Sam Clegg0d0dd392017-12-19 17:09:45 +0000551 if (!InitFunctions.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000552 SubSection Sub(WASM_INIT_FUNCS);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000553 writeUleb128(Sub.OS, InitFunctions.size(), "num init functions");
Sam Clegg93102972018-02-23 05:08:53 +0000554 for (const WasmInitEntry &F : InitFunctions) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000555 writeUleb128(Sub.OS, F.Priority, "priority");
556 writeUleb128(Sub.OS, F.Sym->getOutputSymbolIndex(), "function index");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000557 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000558 Sub.writeTo(OS);
Sam Clegg0d0dd392017-12-19 17:09:45 +0000559 }
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000560
Nicholas Wilsondbd90bf2018-03-07 13:28:16 +0000561 struct ComdatEntry {
562 unsigned Kind;
563 uint32_t Index;
564 };
565 std::map<StringRef, std::vector<ComdatEntry>> Comdats;
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000566
Sam Clegg9f934222018-02-21 18:29:23 +0000567 for (const InputFunction *F : InputFunctions) {
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000568 StringRef Comdat = F->getComdatName();
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000569 if (!Comdat.empty())
570 Comdats[Comdat].emplace_back(
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000571 ComdatEntry{WASM_COMDAT_FUNCTION, F->getFunctionIndex()});
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000572 }
573 for (uint32_t I = 0; I < Segments.size(); ++I) {
Sam Cleggf98bccf2018-01-13 15:57:48 +0000574 const auto &InputSegments = Segments[I]->InputSegments;
575 if (InputSegments.empty())
576 continue;
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000577 StringRef Comdat = InputSegments[0]->getComdatName();
Sam Clegga697df522018-01-13 15:59:53 +0000578#ifndef NDEBUG
Sam Cleggf98bccf2018-01-13 15:57:48 +0000579 for (const InputSegment *IS : InputSegments)
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000580 assert(IS->getComdatName() == Comdat);
Sam Clegga697df522018-01-13 15:59:53 +0000581#endif
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000582 if (!Comdat.empty())
583 Comdats[Comdat].emplace_back(ComdatEntry{WASM_COMDAT_DATA, I});
584 }
585
586 if (!Comdats.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000587 SubSection Sub(WASM_COMDAT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000588 writeUleb128(Sub.OS, Comdats.size(), "num comdats");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000589 for (const auto &C : Comdats) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000590 writeStr(Sub.OS, C.first, "comdat name");
591 writeUleb128(Sub.OS, 0, "comdat flags"); // flags for future use
592 writeUleb128(Sub.OS, C.second.size(), "num entries");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000593 for (const ComdatEntry &Entry : C.second) {
Sam Clegg8518e7d2018-03-01 18:06:39 +0000594 writeU8(Sub.OS, Entry.Kind, "entry kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000595 writeUleb128(Sub.OS, Entry.Index, "entry index");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000596 }
597 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000598 Sub.writeTo(OS);
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000599 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000600}
601
602// Create the custom "name" section containing debug symbol names.
603void Writer::createNameSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000604 unsigned NumNames = NumImportedFunctions;
Sam Clegg9f934222018-02-21 18:29:23 +0000605 for (const InputFunction *F : InputFunctions)
Nicholas Wilson6c7fe302018-04-20 17:09:18 +0000606 if (!F->getName().empty() || !F->getDebugName().empty())
Sam Clegg1963d712018-01-17 20:19:04 +0000607 ++NumNames;
Sam Cleggc94d3932017-11-17 18:14:09 +0000608
Sam Clegg1963d712018-01-17 20:19:04 +0000609 if (NumNames == 0)
610 return;
Sam Clegg50686852018-01-12 18:35:13 +0000611
Sam Cleggc94d3932017-11-17 18:14:09 +0000612 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "name");
613
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000614 SubSection Sub(WASM_NAMES_FUNCTION);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000615 writeUleb128(Sub.OS, NumNames, "name count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000616
Sam Clegg93102972018-02-23 05:08:53 +0000617 // Names must appear in function index order. As it happens ImportedSymbols
618 // and InputFunctions are numbered in order with imported functions coming
Sam Clegg1963d712018-01-17 20:19:04 +0000619 // first.
Sam Clegg93102972018-02-23 05:08:53 +0000620 for (const Symbol *S : ImportedSymbols) {
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000621 if (auto *F = dyn_cast<FunctionSymbol>(S)) {
622 writeUleb128(Sub.OS, F->getFunctionIndex(), "func index");
Sam Clegg37125f02018-11-09 16:57:41 +0000623 writeStr(Sub.OS, toString(*S), "symbol name");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000624 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000625 }
Sam Clegg9f934222018-02-21 18:29:23 +0000626 for (const InputFunction *F : InputFunctions) {
Sam Clegg1963d712018-01-17 20:19:04 +0000627 if (!F->getName().empty()) {
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000628 writeUleb128(Sub.OS, F->getFunctionIndex(), "func index");
Nicholas Wilson6c7fe302018-04-20 17:09:18 +0000629 if (!F->getDebugName().empty()) {
630 writeStr(Sub.OS, F->getDebugName(), "symbol name");
631 } else {
Sam Clegg37125f02018-11-09 16:57:41 +0000632 writeStr(Sub.OS, maybeDemangleSymbol(F->getName()), "symbol name");
Nicholas Wilson6c7fe302018-04-20 17:09:18 +0000633 }
Sam Clegg1963d712018-01-17 20:19:04 +0000634 }
635 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000636
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000637 Sub.writeTo(Section->getStream());
Sam Cleggc94d3932017-11-17 18:14:09 +0000638}
639
Thomas Lively7ec7a292019-01-16 23:46:15 +0000640void Writer::createProducersSection() {
641 SmallVector<std::pair<std::string, std::string>, 8> Languages;
642 SmallVector<std::pair<std::string, std::string>, 8> Tools;
643 SmallVector<std::pair<std::string, std::string>, 8> SDKs;
644 for (ObjFile *File : Symtab->ObjectFiles) {
645 const WasmProducerInfo &Info = File->getWasmObj()->getProducerInfo();
646 for (auto &Producers : {std::make_pair(&Info.Languages, &Languages),
647 std::make_pair(&Info.Tools, &Tools),
648 std::make_pair(&Info.SDKs, &SDKs)}) {
649 llvm::SmallSet<StringRef, 8> SeenProducers;
650 for (auto &Producer : *Producers.first)
651 if (SeenProducers.insert(Producer.first).second)
652 Producers.second->push_back(Producer);
653 }
654 }
655 int FieldCount =
656 int(!Languages.empty()) + int(!Tools.empty()) + int(!SDKs.empty());
657 if (FieldCount == 0)
658 return;
659 SyntheticSection *Section =
660 createSyntheticSection(WASM_SEC_CUSTOM, "producers");
661 auto &OS = Section->getStream();
662 writeUleb128(OS, FieldCount, "field count");
663 for (auto &Field : {std::make_pair(StringRef("language"), Languages),
664 std::make_pair(StringRef("processed-by"), Tools),
665 std::make_pair(StringRef("sdk"), SDKs)}) {
666 if (Field.second.empty())
667 continue;
668 writeStr(OS, Field.first, "field name");
669 writeUleb128(OS, Field.second.size(), "number of entries");
670 for (auto &Entry : Field.second) {
671 writeStr(OS, Entry.first, "producer name");
672 writeStr(OS, Entry.second, "producer version");
673 }
674 }
675}
676
Sam Cleggc94d3932017-11-17 18:14:09 +0000677void Writer::writeHeader() {
678 memcpy(Buffer->getBufferStart(), Header.data(), Header.size());
679}
680
681void Writer::writeSections() {
682 uint8_t *Buf = Buffer->getBufferStart();
683 parallelForEach(OutputSections, [Buf](OutputSection *S) { S->writeTo(Buf); });
684}
685
686// Fix the memory layout of the output binary. This assigns memory offsets
Sam Clegg49ed9262017-12-01 00:53:21 +0000687// to each of the input data sections as well as the explicit stack region.
Sam Clegga0f095e2018-05-03 17:21:53 +0000688// The default memory layout is as follows, from low to high.
689//
Sam Cleggf0d433d2018-02-02 22:59:56 +0000690// - initialized data (starting at Config->GlobalBase)
691// - BSS data (not currently implemented in llvm)
692// - explicit stack (Config->ZStackSize)
693// - heap start / unallocated
Sam Clegga0f095e2018-05-03 17:21:53 +0000694//
695// The --stack-first option means that stack is placed before any static data.
Heejin Ahn4821ebf2018-08-29 21:03:16 +0000696// This can be useful since it means that stack overflow traps immediately
697// rather than overwriting global data, but also increases code size since all
698// static data loads and stores requires larger offsets.
Sam Cleggc94d3932017-11-17 18:14:09 +0000699void Writer::layoutMemory() {
Sam Cleggc94d3932017-11-17 18:14:09 +0000700 createOutputSegments();
701
Sam Clegga0f095e2018-05-03 17:21:53 +0000702 uint32_t MemoryPtr = 0;
703
704 auto PlaceStack = [&]() {
Sam Cleggbfb75342018-11-15 00:37:21 +0000705 if (Config->Relocatable || Config->Shared)
Sam Clegga0f095e2018-05-03 17:21:53 +0000706 return;
707 MemoryPtr = alignTo(MemoryPtr, kStackAlignment);
708 if (Config->ZStackSize != alignTo(Config->ZStackSize, kStackAlignment))
709 error("stack size must be " + Twine(kStackAlignment) + "-byte aligned");
710 log("mem: stack size = " + Twine(Config->ZStackSize));
711 log("mem: stack base = " + Twine(MemoryPtr));
712 MemoryPtr += Config->ZStackSize;
Sam Clegg2dad4e22018-11-15 18:15:54 +0000713 auto *SP = cast<DefinedGlobal>(WasmSym::StackPointer);
714 SP->Global->Global.InitExpr.Value.Int32 = MemoryPtr;
Sam Clegga0f095e2018-05-03 17:21:53 +0000715 log("mem: stack top = " + Twine(MemoryPtr));
716 };
717
718 if (Config->StackFirst) {
719 PlaceStack();
720 } else {
721 MemoryPtr = Config->GlobalBase;
722 log("mem: global base = " + Twine(Config->GlobalBase));
723 }
724
725 uint32_t DataStart = MemoryPtr;
726
Sam Cleggf0d433d2018-02-02 22:59:56 +0000727 // Arbitrarily set __dso_handle handle to point to the start of the data
728 // segments.
729 if (WasmSym::DsoHandle)
Sam Clegga0f095e2018-05-03 17:21:53 +0000730 WasmSym::DsoHandle->setVirtualAddress(DataStart);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000731
Sam Cleggbfb75342018-11-15 00:37:21 +0000732 MemAlign = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000733 for (OutputSegment *Seg : Segments) {
Sam Cleggbfb75342018-11-15 00:37:21 +0000734 MemAlign = std::max(MemAlign, Seg->Alignment);
Sam Clegg6320efb2019-01-16 01:43:21 +0000735 MemoryPtr = alignTo(MemoryPtr, 1 << Seg->Alignment);
Sam Cleggc94d3932017-11-17 18:14:09 +0000736 Seg->StartVA = MemoryPtr;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000737 log(formatv("mem: {0,-15} offset={1,-8} size={2,-8} align={3}", Seg->Name,
738 MemoryPtr, Seg->Size, Seg->Alignment));
Sam Cleggc94d3932017-11-17 18:14:09 +0000739 MemoryPtr += Seg->Size;
740 }
741
Sam Cleggf0d433d2018-02-02 22:59:56 +0000742 // TODO: Add .bss space here.
Sam Clegg37a4a8a2018-02-07 03:04:53 +0000743 if (WasmSym::DataEnd)
744 WasmSym::DataEnd->setVirtualAddress(MemoryPtr);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000745
Sam Clegga0f095e2018-05-03 17:21:53 +0000746 log("mem: static data = " + Twine(MemoryPtr - DataStart));
Sam Cleggc94d3932017-11-17 18:14:09 +0000747
Sam Clegg2dad4e22018-11-15 18:15:54 +0000748 if (Config->Shared) {
749 MemSize = MemoryPtr;
750 return;
751 }
752
Sam Clegga0f095e2018-05-03 17:21:53 +0000753 if (!Config->StackFirst)
754 PlaceStack();
755
756 // Set `__heap_base` to directly follow the end of the stack or global data.
757 // The fact that this comes last means that a malloc/brk implementation
758 // can grow the heap at runtime.
Sam Cleggc94d3932017-11-17 18:14:09 +0000759 if (!Config->Relocatable) {
Sam Cleggf0d433d2018-02-02 22:59:56 +0000760 WasmSym::HeapBase->setVirtualAddress(MemoryPtr);
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000761 log("mem: heap base = " + Twine(MemoryPtr));
Sam Cleggc94d3932017-11-17 18:14:09 +0000762 }
763
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000764 if (Config->InitialMemory != 0) {
765 if (Config->InitialMemory != alignTo(Config->InitialMemory, WasmPageSize))
766 error("initial memory must be " + Twine(WasmPageSize) + "-byte aligned");
767 if (MemoryPtr > Config->InitialMemory)
768 error("initial memory too small, " + Twine(MemoryPtr) + " bytes needed");
769 else
770 MemoryPtr = Config->InitialMemory;
771 }
Sam Cleggbfb75342018-11-15 00:37:21 +0000772 MemSize = MemoryPtr;
773 NumMemoryPages = alignTo(MemoryPtr, WasmPageSize) / WasmPageSize;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000774 log("mem: total pages = " + Twine(NumMemoryPages));
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000775
776 if (Config->MaxMemory != 0) {
777 if (Config->MaxMemory != alignTo(Config->MaxMemory, WasmPageSize))
778 error("maximum memory must be " + Twine(WasmPageSize) + "-byte aligned");
779 if (MemoryPtr > Config->MaxMemory)
780 error("maximum memory too small, " + Twine(MemoryPtr) + " bytes needed");
781 MaxMemoryPages = Config->MaxMemory / WasmPageSize;
782 log("mem: max pages = " + Twine(MaxMemoryPages));
783 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000784}
785
786SyntheticSection *Writer::createSyntheticSection(uint32_t Type,
Sam Cleggc375e4e2018-01-10 19:18:22 +0000787 StringRef Name) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000788 auto Sec = make<SyntheticSection>(Type, Name);
Sam Cleggab2ac292017-12-20 05:14:48 +0000789 log("createSection: " + toString(*Sec));
Sam Cleggc94d3932017-11-17 18:14:09 +0000790 OutputSections.push_back(Sec);
791 return Sec;
792}
793
794void Writer::createSections() {
795 // Known sections
Sam Cleggbfb75342018-11-15 00:37:21 +0000796 if (Config->Pic)
797 createDylinkSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000798 createTypeSection();
799 createImportSection();
800 createFunctionSection();
801 createTableSection();
802 createMemorySection();
803 createGlobalSection();
Heejin Ahne915a712018-12-08 06:17:43 +0000804 createEventSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000805 createExportSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000806 createElemSection();
807 createCodeSection();
808 createDataSection();
Sam Clegg80ba4382018-04-10 16:12:49 +0000809 createCustomSections();
Sam Cleggc94d3932017-11-17 18:14:09 +0000810
811 // Custom sections
Sam Clegg99eb42c2018-02-27 23:58:03 +0000812 if (Config->Relocatable) {
Sam Clegg99eb42c2018-02-27 23:58:03 +0000813 createLinkingSection();
Nicholas Wilson94d3b162018-03-05 12:33:58 +0000814 createRelocSections();
Sam Clegg99eb42c2018-02-27 23:58:03 +0000815 }
Thomas Lively7ec7a292019-01-16 23:46:15 +0000816
Sam Cleggc94d3932017-11-17 18:14:09 +0000817 if (!Config->StripDebug && !Config->StripAll)
818 createNameSection();
819
Thomas Lively7ec7a292019-01-16 23:46:15 +0000820 if (!Config->StripAll)
821 createProducersSection();
822
Sam Cleggc94d3932017-11-17 18:14:09 +0000823 for (OutputSection *S : OutputSections) {
824 S->setOffset(FileSize);
825 S->finalizeContents();
826 FileSize += S->getSize();
827 }
828}
829
Sam Cleggc94d3932017-11-17 18:14:09 +0000830void Writer::calculateImports() {
Sam Clegg574d7ce2017-12-15 19:23:49 +0000831 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000832 if (!Sym->isUndefined())
833 continue;
834 if (isa<DataSymbol>(Sym))
835 continue;
836 if (Sym->isWeak() && !Config->Relocatable)
Sam Clegg574d7ce2017-12-15 19:23:49 +0000837 continue;
Nicholas Wilsona1e299f2018-04-20 17:18:06 +0000838 if (!Sym->isLive())
839 continue;
Sam Cleggc729c1b2018-05-30 18:07:52 +0000840 if (!Sym->IsUsedInRegularObj)
841 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000842
Nicola Zaghene7245b42018-05-15 13:36:20 +0000843 LLVM_DEBUG(dbgs() << "import: " << Sym->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000844 ImportedSymbols.emplace_back(Sym);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000845 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
846 F->setFunctionIndex(NumImportedFunctions++);
Heejin Ahne915a712018-12-08 06:17:43 +0000847 else if (auto *G = dyn_cast<GlobalSymbol>(Sym))
848 G->setGlobalIndex(NumImportedGlobals++);
Sam Clegg93102972018-02-23 05:08:53 +0000849 else
Heejin Ahne915a712018-12-08 06:17:43 +0000850 cast<EventSymbol>(Sym)->setEventIndex(NumImportedEvents++);
Sam Cleggc94d3932017-11-17 18:14:09 +0000851 }
852}
853
Sam Cleggd3052d52018-01-18 23:40:49 +0000854void Writer::calculateExports() {
Sam Clegg93102972018-02-23 05:08:53 +0000855 if (Config->Relocatable)
856 return;
Sam Cleggf0d433d2018-02-02 22:59:56 +0000857
Sam Cleggd6beb322018-05-10 18:10:34 +0000858 if (!Config->Relocatable && !Config->ImportMemory)
859 Exports.push_back(WasmExport{"memory", WASM_EXTERNAL_MEMORY, 0});
860
861 if (!Config->Relocatable && Config->ExportTable)
862 Exports.push_back(WasmExport{kFunctionTableName, WASM_EXTERNAL_TABLE, 0});
863
864 unsigned FakeGlobalIndex = NumImportedGlobals + InputGlobals.size();
865
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000866 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Cleggce004bf2018-06-28 17:04:58 +0000867 if (!Sym->isExported())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000868 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000869 if (!Sym->isLive())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000870 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000871
Sam Cleggd6beb322018-05-10 18:10:34 +0000872 StringRef Name = Sym->getName();
873 WasmExport Export;
874 if (auto *F = dyn_cast<DefinedFunction>(Sym)) {
875 Export = {Name, WASM_EXTERNAL_FUNCTION, F->getFunctionIndex()};
876 } else if (auto *G = dyn_cast<DefinedGlobal>(Sym)) {
Sam Clegg177b4582018-06-07 01:27:07 +0000877 // TODO(sbc): Remove this check once to mutable global proposal is
878 // implement in all major browsers.
879 // See: https://github.com/WebAssembly/mutable-global
880 if (G->getGlobalType()->Mutable) {
881 // Only the __stack_pointer should ever be create as mutable.
882 assert(G == WasmSym::StackPointer);
883 continue;
884 }
Sam Cleggd6beb322018-05-10 18:10:34 +0000885 Export = {Name, WASM_EXTERNAL_GLOBAL, G->getGlobalIndex()};
Heejin Ahne915a712018-12-08 06:17:43 +0000886 } else if (auto *E = dyn_cast<DefinedEvent>(Sym)) {
887 Export = {Name, WASM_EXTERNAL_EVENT, E->getEventIndex()};
Sam Cleggd6beb322018-05-10 18:10:34 +0000888 } else {
889 auto *D = cast<DefinedData>(Sym);
Sam Clegg93102972018-02-23 05:08:53 +0000890 DefinedFakeGlobals.emplace_back(D);
Sam Cleggd6beb322018-05-10 18:10:34 +0000891 Export = {Name, WASM_EXTERNAL_GLOBAL, FakeGlobalIndex++};
892 }
893
Nicola Zaghene7245b42018-05-15 13:36:20 +0000894 LLVM_DEBUG(dbgs() << "Export: " << Name << "\n");
Sam Cleggd6beb322018-05-10 18:10:34 +0000895 Exports.push_back(Export);
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000896 }
Sam Clegg93102972018-02-23 05:08:53 +0000897}
898
899void Writer::assignSymtab() {
900 if (!Config->Relocatable)
901 return;
902
Sam Cleggd177ab22018-05-04 23:14:42 +0000903 StringMap<uint32_t> SectionSymbolIndices;
904
Sam Clegg93102972018-02-23 05:08:53 +0000905 unsigned SymbolIndex = SymtabEntries.size();
Sam Cleggd3052d52018-01-18 23:40:49 +0000906 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000907 LLVM_DEBUG(dbgs() << "Symtab entries: " << File->getName() << "\n");
Sam Cleggd3052d52018-01-18 23:40:49 +0000908 for (Symbol *Sym : File->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000909 if (Sym->getFile() != File)
Sam Cleggd3052d52018-01-18 23:40:49 +0000910 continue;
Sam Cleggd177ab22018-05-04 23:14:42 +0000911
912 if (auto *S = dyn_cast<SectionSymbol>(Sym)) {
913 StringRef Name = S->getName();
914 if (CustomSectionMapping.count(Name) == 0)
915 continue;
916
917 auto SSI = SectionSymbolIndices.find(Name);
918 if (SSI != SectionSymbolIndices.end()) {
919 Sym->setOutputSymbolIndex(SSI->second);
920 continue;
921 }
922
923 SectionSymbolIndices[Name] = SymbolIndex;
924 CustomSectionSymbols[Name] = cast<SectionSymbol>(Sym);
925
926 Sym->markLive();
927 }
928
Nicholas Wilson06e0d172018-03-07 11:15:47 +0000929 // (Since this is relocatable output, GC is not performed so symbols must
930 // be live.)
931 assert(Sym->isLive());
Sam Clegg93102972018-02-23 05:08:53 +0000932 Sym->setOutputSymbolIndex(SymbolIndex++);
933 SymtabEntries.emplace_back(Sym);
Sam Cleggd3052d52018-01-18 23:40:49 +0000934 }
935 }
936
Sam Clegg93102972018-02-23 05:08:53 +0000937 // For the moment, relocatable output doesn't contain any synthetic functions,
938 // so no need to look through the Symtab for symbols not referenced by
939 // Symtab->ObjectFiles.
Sam Cleggd3052d52018-01-18 23:40:49 +0000940}
941
Sam Cleggc375e4e2018-01-10 19:18:22 +0000942uint32_t Writer::lookupType(const WasmSignature &Sig) {
Sam Clegg8d027d62018-01-10 20:12:26 +0000943 auto It = TypeIndices.find(Sig);
944 if (It == TypeIndices.end()) {
Sam Cleggc375e4e2018-01-10 19:18:22 +0000945 error("type not found: " + toString(Sig));
Sam Clegg8d027d62018-01-10 20:12:26 +0000946 return 0;
947 }
948 return It->second;
Sam Cleggc375e4e2018-01-10 19:18:22 +0000949}
950
951uint32_t Writer::registerType(const WasmSignature &Sig) {
Sam Cleggb8621592017-11-30 01:40:08 +0000952 auto Pair = TypeIndices.insert(std::make_pair(Sig, Types.size()));
Sam Cleggc375e4e2018-01-10 19:18:22 +0000953 if (Pair.second) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000954 LLVM_DEBUG(dbgs() << "type " << toString(Sig) << "\n");
Sam Cleggb8621592017-11-30 01:40:08 +0000955 Types.push_back(&Sig);
Sam Cleggc375e4e2018-01-10 19:18:22 +0000956 }
Sam Cleggb8621592017-11-30 01:40:08 +0000957 return Pair.first->second;
958}
959
Sam Cleggc94d3932017-11-17 18:14:09 +0000960void Writer::calculateTypes() {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000961 // The output type section is the union of the following sets:
962 // 1. Any signature used in the TYPE relocation
963 // 2. The signatures of all imported functions
964 // 3. The signatures of all defined functions
Heejin Ahne915a712018-12-08 06:17:43 +0000965 // 4. The signatures of all imported events
966 // 5. The signatures of all defined events
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000967
Sam Cleggc94d3932017-11-17 18:14:09 +0000968 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000969 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
970 for (uint32_t I = 0; I < Types.size(); I++)
971 if (File->TypeIsUsed[I])
972 File->TypeMap[I] = registerType(Types[I]);
Sam Cleggc94d3932017-11-17 18:14:09 +0000973 }
Sam Clegg50686852018-01-12 18:35:13 +0000974
Heejin Ahne915a712018-12-08 06:17:43 +0000975 for (const Symbol *Sym : ImportedSymbols) {
Sam Clegg93102972018-02-23 05:08:53 +0000976 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
Heejin Ahne915a712018-12-08 06:17:43 +0000977 registerType(*F->Signature);
978 else if (auto *E = dyn_cast<EventSymbol>(Sym))
979 registerType(*E->Signature);
980 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000981
Sam Clegg9f934222018-02-21 18:29:23 +0000982 for (const InputFunction *F : InputFunctions)
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000983 registerType(F->Signature);
Heejin Ahne915a712018-12-08 06:17:43 +0000984
985 for (const InputEvent *E : InputEvents)
986 registerType(E->Signature);
Sam Cleggc94d3932017-11-17 18:14:09 +0000987}
988
Sam Clegg8d146bb2018-01-09 23:56:44 +0000989void Writer::assignIndexes() {
Heejin Ahnaeaab992018-11-19 23:21:25 +0000990 assert(InputFunctions.empty());
991 uint32_t FunctionIndex = NumImportedFunctions;
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000992 auto AddDefinedFunction = [&](InputFunction *Func) {
993 if (!Func->Live)
994 return;
995 InputFunctions.emplace_back(Func);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000996 Func->setFunctionIndex(FunctionIndex++);
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000997 };
998
Nicholas Wilson5639da82018-03-12 15:44:07 +0000999 for (InputFunction *Func : Symtab->SyntheticFunctions)
1000 AddDefinedFunction(Func);
1001
Sam Clegg87e61922018-01-08 23:39:11 +00001002 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001003 LLVM_DEBUG(dbgs() << "Functions: " << File->getName() << "\n");
Nicholas Wilsonebda41f2018-03-09 16:43:05 +00001004 for (InputFunction *Func : File->Functions)
1005 AddDefinedFunction(Func);
Sam Clegg8d146bb2018-01-09 23:56:44 +00001006 }
1007
Sam Cleggbfb75342018-11-15 00:37:21 +00001008 uint32_t TableIndex = TableBase;
Sam Clegg6c4dbfee2018-02-23 04:59:57 +00001009 auto HandleRelocs = [&](InputChunk *Chunk) {
1010 if (!Chunk->Live)
1011 return;
1012 ObjFile *File = Chunk->File;
1013 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
Sam Clegg93102972018-02-23 05:08:53 +00001014 for (const WasmRelocation &Reloc : Chunk->getRelocations()) {
Sam Clegg6c4dbfee2018-02-23 04:59:57 +00001015 if (Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_I32 ||
1016 Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_SLEB) {
1017 FunctionSymbol *Sym = File->getFunctionSymbol(Reloc.Index);
Sam Clegge3f3ccf2018-03-12 19:56:23 +00001018 if (Sym->hasTableIndex() || !Sym->hasFunctionIndex())
Sam Clegg6c4dbfee2018-02-23 04:59:57 +00001019 continue;
1020 Sym->setTableIndex(TableIndex++);
1021 IndirectFunctions.emplace_back(Sym);
1022 } else if (Reloc.Type == R_WEBASSEMBLY_TYPE_INDEX_LEB) {
Sam Clegg93102972018-02-23 05:08:53 +00001023 // Mark target type as live
Sam Clegg6c4dbfee2018-02-23 04:59:57 +00001024 File->TypeMap[Reloc.Index] = registerType(Types[Reloc.Index]);
1025 File->TypeIsUsed[Reloc.Index] = true;
1026 }
1027 }
1028 };
1029
Sam Clegg8d146bb2018-01-09 23:56:44 +00001030 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001031 LLVM_DEBUG(dbgs() << "Handle relocs: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +00001032 for (InputChunk *Chunk : File->Functions)
1033 HandleRelocs(Chunk);
1034 for (InputChunk *Chunk : File->Segments)
1035 HandleRelocs(Chunk);
Sam Cleggd177ab22018-05-04 23:14:42 +00001036 for (auto &P : File->CustomSections)
1037 HandleRelocs(P);
Sam Clegg93102972018-02-23 05:08:53 +00001038 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +00001039
Heejin Ahnaeaab992018-11-19 23:21:25 +00001040 assert(InputGlobals.empty());
1041 uint32_t GlobalIndex = NumImportedGlobals;
Sam Clegg93102972018-02-23 05:08:53 +00001042 auto AddDefinedGlobal = [&](InputGlobal *Global) {
1043 if (Global->Live) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001044 LLVM_DEBUG(dbgs() << "AddDefinedGlobal: " << GlobalIndex << "\n");
Sam Clegge3f3ccf2018-03-12 19:56:23 +00001045 Global->setGlobalIndex(GlobalIndex++);
Sam Clegg93102972018-02-23 05:08:53 +00001046 InputGlobals.push_back(Global);
1047 }
1048 };
1049
Nicholas Wilsonebda41f2018-03-09 16:43:05 +00001050 for (InputGlobal *Global : Symtab->SyntheticGlobals)
1051 AddDefinedGlobal(Global);
Sam Clegg93102972018-02-23 05:08:53 +00001052
1053 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001054 LLVM_DEBUG(dbgs() << "Globals: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +00001055 for (InputGlobal *Global : File->Globals)
1056 AddDefinedGlobal(Global);
Sam Cleggc94d3932017-11-17 18:14:09 +00001057 }
Heejin Ahne915a712018-12-08 06:17:43 +00001058
1059 assert(InputEvents.empty());
1060 uint32_t EventIndex = NumImportedEvents;
1061 auto AddDefinedEvent = [&](InputEvent *Event) {
1062 if (Event->Live) {
1063 LLVM_DEBUG(dbgs() << "AddDefinedEvent: " << EventIndex << "\n");
1064 Event->setEventIndex(EventIndex++);
1065 InputEvents.push_back(Event);
1066 }
1067 };
1068
1069 for (ObjFile *File : Symtab->ObjectFiles) {
1070 LLVM_DEBUG(dbgs() << "Events: " << File->getName() << "\n");
1071 for (InputEvent *Event : File->Events)
1072 AddDefinedEvent(Event);
1073 }
Sam Cleggc94d3932017-11-17 18:14:09 +00001074}
1075
1076static StringRef getOutputDataSegmentName(StringRef Name) {
Sam Cleggbfb75342018-11-15 00:37:21 +00001077 // With PIC code we currently only support a single data segment since
1078 // we only have a single __memory_base to use as our base address.
1079 if (Config->Pic)
1080 return "data";
Sam Clegg66844762018-05-10 18:23:51 +00001081 if (!Config->MergeDataSegments)
Sam Cleggc94d3932017-11-17 18:14:09 +00001082 return Name;
Rui Ueyama4764b572018-02-28 00:57:28 +00001083 if (Name.startswith(".text."))
1084 return ".text";
1085 if (Name.startswith(".data."))
1086 return ".data";
1087 if (Name.startswith(".bss."))
1088 return ".bss";
Sam Clegg57694c52018-08-08 18:02:55 +00001089 if (Name.startswith(".rodata."))
1090 return ".rodata";
Sam Cleggc94d3932017-11-17 18:14:09 +00001091 return Name;
1092}
1093
1094void Writer::createOutputSegments() {
1095 for (ObjFile *File : Symtab->ObjectFiles) {
1096 for (InputSegment *Segment : File->Segments) {
Sam Clegg447ae402018-02-13 20:29:38 +00001097 if (!Segment->Live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +00001098 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +00001099 StringRef Name = getOutputDataSegmentName(Segment->getName());
1100 OutputSegment *&S = SegmentMap[Name];
1101 if (S == nullptr) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001102 LLVM_DEBUG(dbgs() << "new segment: " << Name << "\n");
Sam Clegg93102972018-02-23 05:08:53 +00001103 S = make<OutputSegment>(Name, Segments.size());
Sam Cleggc94d3932017-11-17 18:14:09 +00001104 Segments.push_back(S);
1105 }
1106 S->addInputSegment(Segment);
Nicola Zaghene7245b42018-05-15 13:36:20 +00001107 LLVM_DEBUG(dbgs() << "added data: " << Name << ": " << S->Size << "\n");
Sam Cleggc94d3932017-11-17 18:14:09 +00001108 }
1109 }
1110}
1111
Sam Clegg50686852018-01-12 18:35:13 +00001112static const int OPCODE_CALL = 0x10;
1113static const int OPCODE_END = 0xb;
1114
1115// Create synthetic "__wasm_call_ctors" function based on ctor functions
1116// in input object.
1117void Writer::createCtorFunction() {
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +00001118 // First write the body's contents to a string.
1119 std::string BodyContent;
Sam Clegg50686852018-01-12 18:35:13 +00001120 {
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +00001121 raw_string_ostream OS(BodyContent);
Sam Clegg50686852018-01-12 18:35:13 +00001122 writeUleb128(OS, 0, "num locals");
Sam Clegg93102972018-02-23 05:08:53 +00001123 for (const WasmInitEntry &F : InitFunctions) {
Sam Clegg50686852018-01-12 18:35:13 +00001124 writeU8(OS, OPCODE_CALL, "CALL");
Sam Clegge3f3ccf2018-03-12 19:56:23 +00001125 writeUleb128(OS, F.Sym->getFunctionIndex(), "function index");
Sam Clegg50686852018-01-12 18:35:13 +00001126 }
1127 writeU8(OS, OPCODE_END, "END");
1128 }
1129
1130 // Once we know the size of the body we can create the final function body
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +00001131 std::string FunctionBody;
1132 {
1133 raw_string_ostream OS(FunctionBody);
1134 writeUleb128(OS, BodyContent.size(), "function size");
1135 OS << BodyContent;
1136 }
Rui Ueyama29abfe42018-02-28 17:43:15 +00001137
Sam Cleggea656472018-10-22 08:35:39 +00001138 ArrayRef<uint8_t> Body = arrayRefFromStringRef(Saver.save(FunctionBody));
Nicholas Wilsonebda41f2018-03-09 16:43:05 +00001139 cast<SyntheticFunction>(WasmSym::CallCtors->Function)->setBody(Body);
Sam Clegg50686852018-01-12 18:35:13 +00001140}
1141
1142// Populate InitFunctions vector with init functions from all input objects.
1143// This is then used either when creating the output linking section or to
1144// synthesize the "__wasm_call_ctors" function.
1145void Writer::calculateInitFunctions() {
1146 for (ObjFile *File : Symtab->ObjectFiles) {
1147 const WasmLinkingData &L = File->getWasmObj()->linkingData();
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +00001148 for (const WasmInitFunc &F : L.InitFunctions) {
1149 FunctionSymbol *Sym = File->getFunctionSymbol(F.Symbol);
Heejin Ahne915a712018-12-08 06:17:43 +00001150 if (*Sym->Signature != WasmSignature{{}, {}})
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +00001151 error("invalid signature for init func: " + toString(*Sym));
1152 InitFunctions.emplace_back(WasmInitEntry{Sym, F.Priority});
1153 }
Sam Clegg50686852018-01-12 18:35:13 +00001154 }
Rui Ueyamada69b712018-02-28 00:15:59 +00001155
Sam Clegg50686852018-01-12 18:35:13 +00001156 // Sort in order of priority (lowest first) so that they are called
1157 // in the correct order.
Sam Clegg29b8feb2018-02-21 00:34:34 +00001158 std::stable_sort(InitFunctions.begin(), InitFunctions.end(),
Sam Clegg93102972018-02-23 05:08:53 +00001159 [](const WasmInitEntry &L, const WasmInitEntry &R) {
Sam Clegg29b8feb2018-02-21 00:34:34 +00001160 return L.Priority < R.Priority;
1161 });
Sam Clegg50686852018-01-12 18:35:13 +00001162}
1163
Sam Cleggc94d3932017-11-17 18:14:09 +00001164void Writer::run() {
Sam Cleggbfb75342018-11-15 00:37:21 +00001165 if (Config->Relocatable || Config->Pic)
Sam Clegg99eb42c2018-02-27 23:58:03 +00001166 Config->GlobalBase = 0;
1167
Sam Cleggbfb75342018-11-15 00:37:21 +00001168 // For PIC code the table base is assigned dynamically by the loader.
1169 // For non-PIC, we start at 1 so that accessing table index 0 always traps.
1170 if (!Config->Pic)
1171 TableBase = 1;
1172
Sam Cleggc94d3932017-11-17 18:14:09 +00001173 log("-- calculateImports");
1174 calculateImports();
Sam Clegg8d146bb2018-01-09 23:56:44 +00001175 log("-- assignIndexes");
1176 assignIndexes();
Sam Clegg50686852018-01-12 18:35:13 +00001177 log("-- calculateInitFunctions");
1178 calculateInitFunctions();
1179 if (!Config->Relocatable)
1180 createCtorFunction();
Sam Clegg8f6d2de2018-01-31 23:48:14 +00001181 log("-- calculateTypes");
1182 calculateTypes();
Sam Clegg93102972018-02-23 05:08:53 +00001183 log("-- layoutMemory");
1184 layoutMemory();
1185 log("-- calculateExports");
1186 calculateExports();
Sam Cleggd177ab22018-05-04 23:14:42 +00001187 log("-- calculateCustomSections");
1188 calculateCustomSections();
Sam Clegg93102972018-02-23 05:08:53 +00001189 log("-- assignSymtab");
1190 assignSymtab();
Sam Cleggc94d3932017-11-17 18:14:09 +00001191
1192 if (errorHandler().Verbose) {
Sam Clegg9f934222018-02-21 18:29:23 +00001193 log("Defined Functions: " + Twine(InputFunctions.size()));
Sam Clegg93102972018-02-23 05:08:53 +00001194 log("Defined Globals : " + Twine(InputGlobals.size()));
Heejin Ahne915a712018-12-08 06:17:43 +00001195 log("Defined Events : " + Twine(InputEvents.size()));
Sam Clegg93102972018-02-23 05:08:53 +00001196 log("Function Imports : " + Twine(NumImportedFunctions));
1197 log("Global Imports : " + Twine(NumImportedGlobals));
Heejin Ahne915a712018-12-08 06:17:43 +00001198 log("Event Imports : " + Twine(NumImportedEvents));
Sam Cleggc94d3932017-11-17 18:14:09 +00001199 for (ObjFile *File : Symtab->ObjectFiles)
1200 File->dumpInfo();
1201 }
1202
Sam Cleggc94d3932017-11-17 18:14:09 +00001203 createHeader();
1204 log("-- createSections");
1205 createSections();
1206
1207 log("-- openFile");
1208 openFile();
1209 if (errorCount())
1210 return;
1211
1212 writeHeader();
1213
1214 log("-- writeSections");
1215 writeSections();
1216 if (errorCount())
1217 return;
1218
1219 if (Error E = Buffer->commit())
1220 fatal("failed to write the output file: " + toString(std::move(E)));
1221}
1222
1223// Open a result file.
1224void Writer::openFile() {
1225 log("writing: " + Config->OutputFile);
Sam Cleggc94d3932017-11-17 18:14:09 +00001226
1227 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
1228 FileOutputBuffer::create(Config->OutputFile, FileSize,
1229 FileOutputBuffer::F_executable);
1230
1231 if (!BufferOrErr)
1232 error("failed to open " + Config->OutputFile + ": " +
1233 toString(BufferOrErr.takeError()));
1234 else
1235 Buffer = std::move(*BufferOrErr);
1236}
1237
1238void Writer::createHeader() {
1239 raw_string_ostream OS(Header);
1240 writeBytes(OS, WasmMagic, sizeof(WasmMagic), "wasm magic");
1241 writeU32(OS, WasmVersion, "wasm version");
1242 OS.flush();
1243 FileSize += Header.size();
1244}
1245
1246void lld::wasm::writeResult() { Writer().run(); }