blob: f27c9ba340fe7a31a3f78e1629856242a1f7f4e2 [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 Livelyf6f4f842019-03-20 20:26:45 +000023#include "llvm/ADT/SmallSet.h"
Thomas Lively2a0868f2019-01-17 02:29:41 +000024#include "llvm/ADT/SmallVector.h"
Sam Clegg80ba4382018-04-10 16:12:49 +000025#include "llvm/ADT/StringMap.h"
Sam Clegg93102972018-02-23 05:08:53 +000026#include "llvm/BinaryFormat/Wasm.h"
Nicholas Wilson3e3f5fb2018-03-14 15:58:16 +000027#include "llvm/Object/WasmTraits.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000028#include "llvm/Support/FileOutputBuffer.h"
29#include "llvm/Support/Format.h"
30#include "llvm/Support/FormatVariadic.h"
31#include "llvm/Support/LEB128.h"
Sam Clegga688a422019-03-13 21:29:20 +000032#include "llvm/Support/Path.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000033
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
Heejin Ahna1cc4ea2019-02-04 19:13:46 +000044static constexpr int StackAlignment = 16;
45static constexpr const char *FunctionTableName = "__indirect_function_table";
46const char *lld::wasm::DefaultModule = "env";
Sam Cleggc94d3932017-11-17 18:14:09 +000047
48namespace {
49
Sam Clegg93102972018-02-23 05:08:53 +000050// An init entry to be written to either the synthetic init func or the
51// linking metadata.
52struct WasmInitEntry {
Sam Clegge3f3ccf2018-03-12 19:56:23 +000053 const FunctionSymbol *Sym;
Sam Clegg93102972018-02-23 05:08:53 +000054 uint32_t Priority;
Sam Cleggd3052d52018-01-18 23:40:49 +000055};
56
Sam Cleggc94d3932017-11-17 18:14:09 +000057// The writer writes a SymbolTable result to a file.
58class Writer {
59public:
60 void run();
61
62private:
63 void openFile();
64
Sam Cleggc375e4e2018-01-10 19:18:22 +000065 uint32_t lookupType(const WasmSignature &Sig);
66 uint32_t registerType(const WasmSignature &Sig);
Sam Clegg93102972018-02-23 05:08:53 +000067
Sam Clegg09137be2019-04-04 18:40:51 +000068 void createApplyRelocationsFunction();
69 void createCallCtorsFunction();
70
Sam Clegg50686852018-01-12 18:35:13 +000071 void calculateInitFunctions();
Sam Clegg632c21792019-03-16 01:18:12 +000072 void processRelocations(InputChunk *Chunk);
Sam Clegg8d146bb2018-01-09 23:56:44 +000073 void assignIndexes();
Thomas Livelyf6f4f842019-03-20 20:26:45 +000074 void calculateTargetFeatures();
Sam Cleggc94d3932017-11-17 18:14:09 +000075 void calculateImports();
Sam Cleggd3052d52018-01-18 23:40:49 +000076 void calculateExports();
Sam Cleggd177ab22018-05-04 23:14:42 +000077 void calculateCustomSections();
Sam Clegg93102972018-02-23 05:08:53 +000078 void assignSymtab();
Sam Cleggc94d3932017-11-17 18:14:09 +000079 void calculateTypes();
80 void createOutputSegments();
81 void layoutMemory();
82 void createHeader();
83 void createSections();
Nicholas Wilsondbd90bf2018-03-07 13:28:16 +000084 SyntheticSection *createSyntheticSection(uint32_t Type, StringRef Name = "");
Sam Cleggc94d3932017-11-17 18:14:09 +000085
86 // Builtin sections
87 void createTypeSection();
88 void createFunctionSection();
89 void createTableSection();
90 void createGlobalSection();
Heejin Ahne915a712018-12-08 06:17:43 +000091 void createEventSection();
Sam Cleggc94d3932017-11-17 18:14:09 +000092 void createExportSection();
93 void createImportSection();
94 void createMemorySection();
95 void createElemSection();
Thomas Lively84771e22019-04-19 23:40:36 +000096 void createDataCountSection();
Sam Cleggc94d3932017-11-17 18:14:09 +000097 void createCodeSection();
98 void createDataSection();
Sam Clegg80ba4382018-04-10 16:12:49 +000099 void createCustomSections();
Sam Cleggc94d3932017-11-17 18:14:09 +0000100
101 // Custom sections
Sam Cleggbfb75342018-11-15 00:37:21 +0000102 void createDylinkSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000103 void createRelocSections();
104 void createLinkingSection();
105 void createNameSection();
Thomas Lively2a0868f2019-01-17 02:29:41 +0000106 void createProducersSection();
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000107 void createTargetFeaturesSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000108
109 void writeHeader();
110 void writeSections();
111
112 uint64_t FileSize = 0;
Sam Cleggbfb75342018-11-15 00:37:21 +0000113 uint32_t TableBase = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000114 uint32_t NumMemoryPages = 0;
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000115 uint32_t MaxMemoryPages = 0;
Sam Cleggbfb75342018-11-15 00:37:21 +0000116 // Memory size and aligment. Written to the "dylink" section
117 // when build with -shared or -pie.
118 uint32_t MemAlign = 0;
119 uint32_t MemSize = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000120
121 std::vector<const WasmSignature *> Types;
Nicholas Wilson3e3f5fb2018-03-14 15:58:16 +0000122 DenseMap<WasmSignature, int32_t> TypeIndices;
Sam Clegg93102972018-02-23 05:08:53 +0000123 std::vector<const Symbol *> ImportedSymbols;
Sam Clegg492f7522019-03-26 19:46:15 +0000124 std::vector<const Symbol *> GOTSymbols;
Sam Clegg93102972018-02-23 05:08:53 +0000125 unsigned NumImportedFunctions = 0;
126 unsigned NumImportedGlobals = 0;
Heejin Ahne915a712018-12-08 06:17:43 +0000127 unsigned NumImportedEvents = 0;
Sam Cleggd6beb322018-05-10 18:10:34 +0000128 std::vector<WasmExport> Exports;
Sam Clegg93102972018-02-23 05:08:53 +0000129 std::vector<const DefinedData *> DefinedFakeGlobals;
130 std::vector<InputGlobal *> InputGlobals;
Sam Clegg9f934222018-02-21 18:29:23 +0000131 std::vector<InputFunction *> InputFunctions;
Heejin Ahne915a712018-12-08 06:17:43 +0000132 std::vector<InputEvent *> InputEvents;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000133 std::vector<const FunctionSymbol *> IndirectFunctions;
Sam Clegg93102972018-02-23 05:08:53 +0000134 std::vector<const Symbol *> SymtabEntries;
135 std::vector<WasmInitEntry> InitFunctions;
Sam Cleggc94d3932017-11-17 18:14:09 +0000136
Sam Clegg80ba4382018-04-10 16:12:49 +0000137 llvm::StringMap<std::vector<InputSection *>> CustomSectionMapping;
Sam Cleggd177ab22018-05-04 23:14:42 +0000138 llvm::StringMap<SectionSymbol *> CustomSectionSymbols;
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000139 llvm::SmallSet<std::string, 8> TargetFeatures;
Sam Clegg80ba4382018-04-10 16:12:49 +0000140
Sam Cleggc94d3932017-11-17 18:14:09 +0000141 // Elements that are used to construct the final output
142 std::string Header;
143 std::vector<OutputSection *> OutputSections;
144
145 std::unique_ptr<FileOutputBuffer> Buffer;
146
147 std::vector<OutputSegment *> Segments;
148 llvm::SmallDenseMap<StringRef, OutputSegment *> SegmentMap;
149};
150
151} // anonymous namespace
152
Sam Cleggc94d3932017-11-17 18:14:09 +0000153void Writer::createImportSection() {
Sam Clegg492f7522019-03-26 19:46:15 +0000154 uint32_t NumImports = ImportedSymbols.size() + GOTSymbols.size();
Sam Cleggc94d3932017-11-17 18:14:09 +0000155 if (Config->ImportMemory)
156 ++NumImports;
Nicholas Wilsonfc90b302018-03-28 12:53:29 +0000157 if (Config->ImportTable)
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000158 ++NumImports;
Sam Cleggc94d3932017-11-17 18:14:09 +0000159
160 if (NumImports == 0)
161 return;
162
163 SyntheticSection *Section = createSyntheticSection(WASM_SEC_IMPORT);
164 raw_ostream &OS = Section->getStream();
165
166 writeUleb128(OS, NumImports, "import count");
167
Sam Cleggc94d3932017-11-17 18:14:09 +0000168 if (Config->ImportMemory) {
169 WasmImport Import;
Heejin Ahna1cc4ea2019-02-04 19:13:46 +0000170 Import.Module = DefaultModule;
Sam Cleggc94d3932017-11-17 18:14:09 +0000171 Import.Field = "memory";
172 Import.Kind = WASM_EXTERNAL_MEMORY;
173 Import.Memory.Flags = 0;
174 Import.Memory.Initial = NumMemoryPages;
Thomas Lively06391f32019-03-29 20:43:49 +0000175 if (MaxMemoryPages != 0 || Config->SharedMemory) {
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000176 Import.Memory.Flags |= WASM_LIMITS_FLAG_HAS_MAX;
177 Import.Memory.Maximum = MaxMemoryPages;
178 }
Derek Schuff786760a2018-11-06 18:02:39 +0000179 if (Config->SharedMemory)
Derek Schuff3bea8bc2018-11-06 17:59:32 +0000180 Import.Memory.Flags |= WASM_LIMITS_FLAG_IS_SHARED;
Sam Cleggc94d3932017-11-17 18:14:09 +0000181 writeImport(OS, Import);
182 }
183
Nicholas Wilsonfc90b302018-03-28 12:53:29 +0000184 if (Config->ImportTable) {
Sam Cleggbfb75342018-11-15 00:37:21 +0000185 uint32_t TableSize = TableBase + IndirectFunctions.size();
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000186 WasmImport Import;
Heejin Ahna1cc4ea2019-02-04 19:13:46 +0000187 Import.Module = DefaultModule;
188 Import.Field = FunctionTableName;
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000189 Import.Kind = WASM_EXTERNAL_TABLE;
Thomas Lively25ff8932019-01-08 06:25:55 +0000190 Import.Table.ElemType = WASM_TYPE_FUNCREF;
Sam Clegg748f59cae2018-12-03 22:37:55 +0000191 Import.Table.Limits = {0, TableSize, 0};
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000192 writeImport(OS, Import);
193 }
194
Sam Clegg93102972018-02-23 05:08:53 +0000195 for (const Symbol *Sym : ImportedSymbols) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000196 WasmImport Import;
Dan Gohman9b84eea2019-02-07 22:00:48 +0000197 if (auto *F = dyn_cast<UndefinedFunction>(Sym)) {
198 Import.Field = F->ImportName;
199 Import.Module = F->ImportModule;
200 } else if (auto *G = dyn_cast<UndefinedGlobal>(Sym)) {
201 Import.Field = G->ImportName;
202 Import.Module = G->ImportModule;
203 } else {
204 Import.Field = Sym->getName();
Heejin Ahna1cc4ea2019-02-04 19:13:46 +0000205 Import.Module = DefaultModule;
Dan Gohman9b84eea2019-02-07 22:00:48 +0000206 }
Sam Clegg7cc07532019-02-01 02:29:57 +0000207
Sam Clegg93102972018-02-23 05:08:53 +0000208 if (auto *FunctionSym = dyn_cast<FunctionSymbol>(Sym)) {
209 Import.Kind = WASM_EXTERNAL_FUNCTION;
Heejin Ahne915a712018-12-08 06:17:43 +0000210 Import.SigIndex = lookupType(*FunctionSym->Signature);
211 } else if (auto *GlobalSym = dyn_cast<GlobalSymbol>(Sym)) {
Sam Clegg93102972018-02-23 05:08:53 +0000212 Import.Kind = WASM_EXTERNAL_GLOBAL;
213 Import.Global = *GlobalSym->getGlobalType();
Heejin Ahne915a712018-12-08 06:17:43 +0000214 } else {
215 auto *EventSym = cast<EventSymbol>(Sym);
216 Import.Kind = WASM_EXTERNAL_EVENT;
217 Import.Event.Attribute = EventSym->getEventType()->Attribute;
218 Import.Event.SigIndex = lookupType(*EventSym->Signature);
Sam Clegg93102972018-02-23 05:08:53 +0000219 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000220 writeImport(OS, Import);
221 }
Sam Clegg492f7522019-03-26 19:46:15 +0000222
223 for (const Symbol *Sym : GOTSymbols) {
224 WasmImport Import;
225 Import.Kind = WASM_EXTERNAL_GLOBAL;
226 Import.Global = {WASM_TYPE_I32, true};
227 if (isa<DataSymbol>(Sym))
228 Import.Module = "GOT.mem";
229 else
230 Import.Module = "GOT.func";
231 Import.Field = Sym->getName();
232 writeImport(OS, Import);
233 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000234}
235
236void Writer::createTypeSection() {
Sam Clegg1a53ff22019-05-16 21:22:43 +0000237 if (!Types.size())
238 return;
Sam Cleggc94d3932017-11-17 18:14:09 +0000239 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TYPE);
240 raw_ostream &OS = Section->getStream();
241 writeUleb128(OS, Types.size(), "type count");
Sam Cleggd451da12017-12-19 19:56:27 +0000242 for (const WasmSignature *Sig : Types)
Sam Cleggc94d3932017-11-17 18:14:09 +0000243 writeSig(OS, *Sig);
Sam Cleggc94d3932017-11-17 18:14:09 +0000244}
245
246void Writer::createFunctionSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000247 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000248 return;
249
250 SyntheticSection *Section = createSyntheticSection(WASM_SEC_FUNCTION);
251 raw_ostream &OS = Section->getStream();
252
Sam Clegg9f934222018-02-21 18:29:23 +0000253 writeUleb128(OS, InputFunctions.size(), "function count");
254 for (const InputFunction *Func : InputFunctions)
Sam Cleggc375e4e2018-01-10 19:18:22 +0000255 writeUleb128(OS, lookupType(Func->Signature), "sig index");
Sam Cleggc94d3932017-11-17 18:14:09 +0000256}
257
258void Writer::createMemorySection() {
259 if (Config->ImportMemory)
260 return;
261
262 SyntheticSection *Section = createSyntheticSection(WASM_SEC_MEMORY);
263 raw_ostream &OS = Section->getStream();
264
Thomas Lively06391f32019-03-29 20:43:49 +0000265 bool HasMax = MaxMemoryPages != 0 || Config->SharedMemory;
Sam Cleggc94d3932017-11-17 18:14:09 +0000266 writeUleb128(OS, 1, "memory count");
Derek Schuff786760a2018-11-06 18:02:39 +0000267 unsigned Flags = 0;
268 if (HasMax)
269 Flags |= WASM_LIMITS_FLAG_HAS_MAX;
Derek Schuff3bea8bc2018-11-06 17:59:32 +0000270 if (Config->SharedMemory)
271 Flags |= WASM_LIMITS_FLAG_IS_SHARED;
272 writeUleb128(OS, Flags, "memory limits flags");
Sam Cleggc94d3932017-11-17 18:14:09 +0000273 writeUleb128(OS, NumMemoryPages, "initial pages");
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000274 if (HasMax)
275 writeUleb128(OS, MaxMemoryPages, "max pages");
Sam Cleggc94d3932017-11-17 18:14:09 +0000276}
277
278void Writer::createGlobalSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000279 unsigned NumGlobals = InputGlobals.size() + DefinedFakeGlobals.size();
280 if (NumGlobals == 0)
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000281 return;
282
Sam Cleggc94d3932017-11-17 18:14:09 +0000283 SyntheticSection *Section = createSyntheticSection(WASM_SEC_GLOBAL);
284 raw_ostream &OS = Section->getStream();
285
Sam Clegg93102972018-02-23 05:08:53 +0000286 writeUleb128(OS, NumGlobals, "global count");
287 for (const InputGlobal *G : InputGlobals)
288 writeGlobal(OS, G->Global);
289 for (const DefinedData *Sym : DefinedFakeGlobals) {
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000290 WasmGlobal Global;
Sam Clegg93102972018-02-23 05:08:53 +0000291 Global.Type = {WASM_TYPE_I32, false};
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000292 Global.InitExpr.Opcode = WASM_OPCODE_I32_CONST;
293 Global.InitExpr.Value.Int32 = Sym->getVirtualAddress();
Sam Cleggc94d3932017-11-17 18:14:09 +0000294 writeGlobal(OS, Global);
295 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000296}
297
Heejin Ahne915a712018-12-08 06:17:43 +0000298// The event section contains a list of declared wasm events associated with the
299// module. Currently the only supported event kind is exceptions. A single event
300// entry represents a single event with an event tag. All C++ exceptions are
301// represented by a single event. An event entry in this section contains
302// information on what kind of event it is (e.g. exception) and the type of
303// values contained in a single event object. (In wasm, an event can contain
304// multiple values of primitive types. But for C++ exceptions, we just throw a
305// pointer which is an i32 value (for wasm32 architecture), so the signature of
306// C++ exception is (i32)->(void), because all event types are assumed to have
307// void return type to share WasmSignature with functions.)
308void Writer::createEventSection() {
309 unsigned NumEvents = InputEvents.size();
310 if (NumEvents == 0)
311 return;
312
313 SyntheticSection *Section = createSyntheticSection(WASM_SEC_EVENT);
314 raw_ostream &OS = Section->getStream();
315
316 writeUleb128(OS, NumEvents, "event count");
317 for (InputEvent *E : InputEvents) {
318 E->Event.Type.SigIndex = lookupType(E->Signature);
319 writeEvent(OS, E->Event);
320 }
321}
322
Sam Cleggc94d3932017-11-17 18:14:09 +0000323void Writer::createTableSection() {
Nicholas Wilsonfc90b302018-03-28 12:53:29 +0000324 if (Config->ImportTable)
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000325 return;
326
327 // Always output a table section (or table import), even if there are no
328 // indirect calls. There are two reasons for this:
Sam Cleggfc1a9122017-12-11 22:00:56 +0000329 // 1. For executables it is useful to have an empty table slot at 0
330 // which can be filled with a null function call handler.
331 // 2. If we don't do this, any program that contains a call_indirect but
332 // no address-taken function will fail at validation time since it is
333 // a validation error to include a call_indirect instruction if there
334 // is not table.
Sam Cleggbfb75342018-11-15 00:37:21 +0000335 uint32_t TableSize = TableBase + IndirectFunctions.size();
Sam Cleggfc1a9122017-12-11 22:00:56 +0000336
Sam Cleggc94d3932017-11-17 18:14:09 +0000337 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TABLE);
338 raw_ostream &OS = Section->getStream();
339
340 writeUleb128(OS, 1, "table count");
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000341 WasmLimits Limits = {WASM_LIMITS_FLAG_HAS_MAX, TableSize, TableSize};
Thomas Lively25ff8932019-01-08 06:25:55 +0000342 writeTableType(OS, WasmTable{WASM_TYPE_FUNCREF, Limits});
Sam Cleggc94d3932017-11-17 18:14:09 +0000343}
344
345void Writer::createExportSection() {
Sam Cleggd6beb322018-05-10 18:10:34 +0000346 if (!Exports.size())
Sam Cleggc94d3932017-11-17 18:14:09 +0000347 return;
348
349 SyntheticSection *Section = createSyntheticSection(WASM_SEC_EXPORT);
350 raw_ostream &OS = Section->getStream();
351
Sam Cleggd6beb322018-05-10 18:10:34 +0000352 writeUleb128(OS, Exports.size(), "export count");
353 for (const WasmExport &Export : Exports)
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000354 writeExport(OS, Export);
Sam Cleggc94d3932017-11-17 18:14:09 +0000355}
356
Sam Cleggd177ab22018-05-04 23:14:42 +0000357void Writer::calculateCustomSections() {
358 log("calculateCustomSections");
359 bool StripDebug = Config->StripDebug || Config->StripAll;
360 for (ObjFile *File : Symtab->ObjectFiles) {
361 for (InputSection *Section : File->CustomSections) {
362 StringRef Name = Section->getName();
363 // These custom sections are known the linker and synthesized rather than
364 // blindly copied
Thomas Lively2a0868f2019-01-17 02:29:41 +0000365 if (Name == "linking" || Name == "name" || Name == "producers" ||
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000366 Name == "target_features" || Name.startswith("reloc."))
Sam Cleggd177ab22018-05-04 23:14:42 +0000367 continue;
368 // .. or it is a debug section
369 if (StripDebug && Name.startswith(".debug_"))
370 continue;
371 CustomSectionMapping[Name].push_back(Section);
372 }
373 }
374}
375
Sam Clegg80ba4382018-04-10 16:12:49 +0000376void Writer::createCustomSections() {
377 log("createCustomSections");
Sam Clegg80ba4382018-04-10 16:12:49 +0000378 for (auto &Pair : CustomSectionMapping) {
379 StringRef Name = Pair.first();
Sam Cleggd177ab22018-05-04 23:14:42 +0000380
381 auto P = CustomSectionSymbols.find(Name);
382 if (P != CustomSectionSymbols.end()) {
383 uint32_t SectionIndex = OutputSections.size();
384 P->second->setOutputSectionIndex(SectionIndex);
385 }
386
Nicola Zaghene7245b42018-05-15 13:36:20 +0000387 LLVM_DEBUG(dbgs() << "createCustomSection: " << Name << "\n");
Sam Clegg80ba4382018-04-10 16:12:49 +0000388 OutputSections.push_back(make<CustomSection>(Name, Pair.second));
389 }
390}
391
Sam Cleggc94d3932017-11-17 18:14:09 +0000392void Writer::createElemSection() {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000393 if (IndirectFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000394 return;
395
396 SyntheticSection *Section = createSyntheticSection(WASM_SEC_ELEM);
397 raw_ostream &OS = Section->getStream();
398
399 writeUleb128(OS, 1, "segment count");
400 writeUleb128(OS, 0, "table index");
401 WasmInitExpr InitExpr;
Sam Cleggbfb75342018-11-15 00:37:21 +0000402 if (Config->Pic) {
Thomas Lively25ff8932019-01-08 06:25:55 +0000403 InitExpr.Opcode = WASM_OPCODE_GLOBAL_GET;
Sam Clegg2dad4e22018-11-15 18:15:54 +0000404 InitExpr.Value.Global = WasmSym::TableBase->getGlobalIndex();
Sam Cleggbfb75342018-11-15 00:37:21 +0000405 } else {
406 InitExpr.Opcode = WASM_OPCODE_I32_CONST;
407 InitExpr.Value.Int32 = TableBase;
408 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000409 writeInitExpr(OS, InitExpr);
Sam Cleggfc1a9122017-12-11 22:00:56 +0000410 writeUleb128(OS, IndirectFunctions.size(), "elem count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000411
Sam Cleggbfb75342018-11-15 00:37:21 +0000412 uint32_t TableIndex = TableBase;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000413 for (const FunctionSymbol *Sym : IndirectFunctions) {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000414 assert(Sym->getTableIndex() == TableIndex);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000415 writeUleb128(OS, Sym->getFunctionIndex(), "function index");
Sam Cleggfc1a9122017-12-11 22:00:56 +0000416 ++TableIndex;
417 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000418}
419
Thomas Lively84771e22019-04-19 23:40:36 +0000420void Writer::createDataCountSection() {
421 if (!Segments.size() || !TargetFeatures.count("bulk-memory"))
422 return;
423
424 log("createDataCountSection");
425 SyntheticSection *Section = createSyntheticSection(WASM_SEC_DATACOUNT);
426 raw_ostream &OS = Section->getStream();
427 writeUleb128(OS, Segments.size(), "data count");
428}
429
Sam Cleggc94d3932017-11-17 18:14:09 +0000430void Writer::createCodeSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000431 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000432 return;
433
434 log("createCodeSection");
435
Sam Clegg9f934222018-02-21 18:29:23 +0000436 auto Section = make<CodeSection>(InputFunctions);
Sam Cleggc94d3932017-11-17 18:14:09 +0000437 OutputSections.push_back(Section);
438}
439
440void Writer::createDataSection() {
441 if (!Segments.size())
442 return;
443
444 log("createDataSection");
445 auto Section = make<DataSection>(Segments);
446 OutputSections.push_back(Section);
447}
448
Sam Cleggd451da12017-12-19 19:56:27 +0000449// Create relocations sections in the final output.
Sam Cleggc94d3932017-11-17 18:14:09 +0000450// These are only created when relocatable output is requested.
451void Writer::createRelocSections() {
452 log("createRelocSections");
453 // Don't use iterator here since we are adding to OutputSection
454 size_t OrigSize = OutputSections.size();
Rui Ueyamaffa650a2018-04-24 23:09:57 +0000455 for (size_t I = 0; I < OrigSize; I++) {
456 OutputSection *OSec = OutputSections[I];
Rui Ueyama37254062018-02-28 00:01:31 +0000457 uint32_t Count = OSec->numRelocations();
Sam Cleggc94d3932017-11-17 18:14:09 +0000458 if (!Count)
459 continue;
460
Rui Ueyama37254062018-02-28 00:01:31 +0000461 StringRef Name;
462 if (OSec->Type == WASM_SEC_DATA)
463 Name = "reloc.DATA";
464 else if (OSec->Type == WASM_SEC_CODE)
465 Name = "reloc.CODE";
Sam Cleggd177ab22018-05-04 23:14:42 +0000466 else if (OSec->Type == WASM_SEC_CUSTOM)
467 Name = Saver.save("reloc." + OSec->Name);
Sam Cleggc94d3932017-11-17 18:14:09 +0000468 else
Sam Cleggd177ab22018-05-04 23:14:42 +0000469 llvm_unreachable(
470 "relocations only supported for code, data, or custom sections");
Sam Cleggc94d3932017-11-17 18:14:09 +0000471
Sam Cleggd029bf02019-05-16 21:36:06 +0000472 OutputSections.push_back(make<RelocSection>(Name, OSec, I));
Sam Cleggc94d3932017-11-17 18:14:09 +0000473 }
474}
475
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000476static uint32_t getWasmFlags(const Symbol *Sym) {
477 uint32_t Flags = 0;
478 if (Sym->isLocal())
479 Flags |= WASM_SYMBOL_BINDING_LOCAL;
480 if (Sym->isWeak())
481 Flags |= WASM_SYMBOL_BINDING_WEAK;
482 if (Sym->isHidden())
483 Flags |= WASM_SYMBOL_VISIBILITY_HIDDEN;
484 if (Sym->isUndefined())
485 Flags |= WASM_SYMBOL_UNDEFINED;
Dan Gohman9b84eea2019-02-07 22:00:48 +0000486 if (auto *F = dyn_cast<UndefinedFunction>(Sym)) {
487 if (F->getName() != F->ImportName)
488 Flags |= WASM_SYMBOL_EXPLICIT_NAME;
489 } else if (auto *G = dyn_cast<UndefinedGlobal>(Sym)) {
490 if (G->getName() != G->ImportName)
491 Flags |= WASM_SYMBOL_EXPLICIT_NAME;
492 }
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000493 return Flags;
494}
495
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000496// Some synthetic sections (e.g. "name" and "linking") have subsections.
497// Just like the synthetic sections themselves these need to be created before
498// they can be written out (since they are preceded by their length). This
499// class is used to create subsections and then write them into the stream
500// of the parent section.
501class SubSection {
502public:
503 explicit SubSection(uint32_t Type) : Type(Type) {}
504
505 void writeTo(raw_ostream &To) {
506 OS.flush();
Rui Ueyama67769102018-02-28 03:38:14 +0000507 writeUleb128(To, Type, "subsection type");
508 writeUleb128(To, Body.size(), "subsection size");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000509 To.write(Body.data(), Body.size());
510 }
511
512private:
513 uint32_t Type;
514 std::string Body;
515
516public:
517 raw_string_ostream OS{Body};
518};
519
Sam Cleggbfb75342018-11-15 00:37:21 +0000520// Create the custom "dylink" section containing information for the dynamic
521// linker.
522// See
523// https://github.com/WebAssembly/tool-conventions/blob/master/DynamicLinking.md
524void Writer::createDylinkSection() {
525 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "dylink");
526 raw_ostream &OS = Section->getStream();
527
528 writeUleb128(OS, MemSize, "MemSize");
Sam Clegg6320efb2019-01-16 01:43:21 +0000529 writeUleb128(OS, MemAlign, "MemAlign");
Sam Cleggbfb75342018-11-15 00:37:21 +0000530 writeUleb128(OS, IndirectFunctions.size(), "TableSize");
531 writeUleb128(OS, 0, "TableAlign");
Sam Clegga688a422019-03-13 21:29:20 +0000532 writeUleb128(OS, Symtab->SharedFiles.size(), "Needed");
533 for (auto *SO : Symtab->SharedFiles)
534 writeStr(OS, llvm::sys::path::filename(SO->getName()), "so name");
Sam Cleggbfb75342018-11-15 00:37:21 +0000535}
536
Sam Clegg49ed9262017-12-01 00:53:21 +0000537// Create the custom "linking" section containing linker metadata.
Sam Cleggc94d3932017-11-17 18:14:09 +0000538// This is only created when relocatable output is requested.
539void Writer::createLinkingSection() {
540 SyntheticSection *Section =
541 createSyntheticSection(WASM_SEC_CUSTOM, "linking");
542 raw_ostream &OS = Section->getStream();
543
Sam Clegg2b8b1792018-04-26 18:17:21 +0000544 writeUleb128(OS, WasmMetadataVersion, "Version");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000545
Sam Clegg93102972018-02-23 05:08:53 +0000546 if (!SymtabEntries.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000547 SubSection Sub(WASM_SYMBOL_TABLE);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000548 writeUleb128(Sub.OS, SymtabEntries.size(), "num symbols");
549
Sam Clegg93102972018-02-23 05:08:53 +0000550 for (const Symbol *Sym : SymtabEntries) {
551 assert(Sym->isDefined() || Sym->isUndefined());
552 WasmSymbolType Kind = Sym->getWasmType();
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000553 uint32_t Flags = getWasmFlags(Sym);
554
Sam Clegg8518e7d2018-03-01 18:06:39 +0000555 writeU8(Sub.OS, Kind, "sym kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000556 writeUleb128(Sub.OS, Flags, "sym flags");
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000557
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000558 if (auto *F = dyn_cast<FunctionSymbol>(Sym)) {
559 writeUleb128(Sub.OS, F->getFunctionIndex(), "index");
Dan Gohman9b84eea2019-02-07 22:00:48 +0000560 if (Sym->isDefined() ||
561 (Flags & WASM_SYMBOL_EXPLICIT_NAME) != 0)
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000562 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000563 } else if (auto *G = dyn_cast<GlobalSymbol>(Sym)) {
564 writeUleb128(Sub.OS, G->getGlobalIndex(), "index");
Dan Gohman9b84eea2019-02-07 22:00:48 +0000565 if (Sym->isDefined() ||
566 (Flags & WASM_SYMBOL_EXPLICIT_NAME) != 0)
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000567 writeStr(Sub.OS, Sym->getName(), "sym name");
Heejin Ahne915a712018-12-08 06:17:43 +0000568 } else if (auto *E = dyn_cast<EventSymbol>(Sym)) {
569 writeUleb128(Sub.OS, E->getEventIndex(), "index");
Dan Gohman9b84eea2019-02-07 22:00:48 +0000570 if (Sym->isDefined() ||
571 (Flags & WASM_SYMBOL_EXPLICIT_NAME) != 0)
Heejin Ahne915a712018-12-08 06:17:43 +0000572 writeStr(Sub.OS, Sym->getName(), "sym name");
Andrea Di Biagio25c1a2f2018-05-05 10:53:31 +0000573 } else if (isa<DataSymbol>(Sym)) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000574 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegg93102972018-02-23 05:08:53 +0000575 if (auto *DataSym = dyn_cast<DefinedData>(Sym)) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000576 writeUleb128(Sub.OS, DataSym->getOutputSegmentIndex(), "index");
577 writeUleb128(Sub.OS, DataSym->getOutputSegmentOffset(),
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000578 "data offset");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000579 writeUleb128(Sub.OS, DataSym->getSize(), "data size");
Sam Clegg93102972018-02-23 05:08:53 +0000580 }
Sam Cleggd177ab22018-05-04 23:14:42 +0000581 } else {
582 auto *S = cast<SectionSymbol>(Sym);
583 writeUleb128(Sub.OS, S->getOutputSectionIndex(), "sym section index");
Sam Clegg93102972018-02-23 05:08:53 +0000584 }
Sam Cleggd3052d52018-01-18 23:40:49 +0000585 }
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000586
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000587 Sub.writeTo(OS);
Sam Cleggd3052d52018-01-18 23:40:49 +0000588 }
589
Sam Clegg0d0dd392017-12-19 17:09:45 +0000590 if (Segments.size()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000591 SubSection Sub(WASM_SEGMENT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000592 writeUleb128(Sub.OS, Segments.size(), "num data segments");
Sam Cleggc94d3932017-11-17 18:14:09 +0000593 for (const OutputSegment *S : Segments) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000594 writeStr(Sub.OS, S->Name, "segment name");
595 writeUleb128(Sub.OS, S->Alignment, "alignment");
596 writeUleb128(Sub.OS, 0, "flags");
Sam Cleggc94d3932017-11-17 18:14:09 +0000597 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000598 Sub.writeTo(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000599 }
Sam Clegg0d0dd392017-12-19 17:09:45 +0000600
Sam Clegg0d0dd392017-12-19 17:09:45 +0000601 if (!InitFunctions.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000602 SubSection Sub(WASM_INIT_FUNCS);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000603 writeUleb128(Sub.OS, InitFunctions.size(), "num init functions");
Sam Clegg93102972018-02-23 05:08:53 +0000604 for (const WasmInitEntry &F : InitFunctions) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000605 writeUleb128(Sub.OS, F.Priority, "priority");
606 writeUleb128(Sub.OS, F.Sym->getOutputSymbolIndex(), "function index");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000607 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000608 Sub.writeTo(OS);
Sam Clegg0d0dd392017-12-19 17:09:45 +0000609 }
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000610
Nicholas Wilsondbd90bf2018-03-07 13:28:16 +0000611 struct ComdatEntry {
612 unsigned Kind;
613 uint32_t Index;
614 };
615 std::map<StringRef, std::vector<ComdatEntry>> Comdats;
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000616
Sam Clegg9f934222018-02-21 18:29:23 +0000617 for (const InputFunction *F : InputFunctions) {
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000618 StringRef Comdat = F->getComdatName();
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000619 if (!Comdat.empty())
620 Comdats[Comdat].emplace_back(
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000621 ComdatEntry{WASM_COMDAT_FUNCTION, F->getFunctionIndex()});
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000622 }
623 for (uint32_t I = 0; I < Segments.size(); ++I) {
Sam Cleggf98bccf2018-01-13 15:57:48 +0000624 const auto &InputSegments = Segments[I]->InputSegments;
625 if (InputSegments.empty())
626 continue;
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000627 StringRef Comdat = InputSegments[0]->getComdatName();
Sam Clegga697df522018-01-13 15:59:53 +0000628#ifndef NDEBUG
Sam Cleggf98bccf2018-01-13 15:57:48 +0000629 for (const InputSegment *IS : InputSegments)
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000630 assert(IS->getComdatName() == Comdat);
Sam Clegga697df522018-01-13 15:59:53 +0000631#endif
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000632 if (!Comdat.empty())
633 Comdats[Comdat].emplace_back(ComdatEntry{WASM_COMDAT_DATA, I});
634 }
635
636 if (!Comdats.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000637 SubSection Sub(WASM_COMDAT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000638 writeUleb128(Sub.OS, Comdats.size(), "num comdats");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000639 for (const auto &C : Comdats) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000640 writeStr(Sub.OS, C.first, "comdat name");
641 writeUleb128(Sub.OS, 0, "comdat flags"); // flags for future use
642 writeUleb128(Sub.OS, C.second.size(), "num entries");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000643 for (const ComdatEntry &Entry : C.second) {
Sam Clegg8518e7d2018-03-01 18:06:39 +0000644 writeU8(Sub.OS, Entry.Kind, "entry kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000645 writeUleb128(Sub.OS, Entry.Index, "entry index");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000646 }
647 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000648 Sub.writeTo(OS);
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000649 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000650}
651
652// Create the custom "name" section containing debug symbol names.
653void Writer::createNameSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000654 unsigned NumNames = NumImportedFunctions;
Sam Clegg9f934222018-02-21 18:29:23 +0000655 for (const InputFunction *F : InputFunctions)
Nicholas Wilson6c7fe302018-04-20 17:09:18 +0000656 if (!F->getName().empty() || !F->getDebugName().empty())
Sam Clegg1963d712018-01-17 20:19:04 +0000657 ++NumNames;
Sam Cleggc94d3932017-11-17 18:14:09 +0000658
Sam Clegg1963d712018-01-17 20:19:04 +0000659 if (NumNames == 0)
660 return;
Sam Clegg50686852018-01-12 18:35:13 +0000661
Sam Cleggc94d3932017-11-17 18:14:09 +0000662 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "name");
663
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000664 SubSection Sub(WASM_NAMES_FUNCTION);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000665 writeUleb128(Sub.OS, NumNames, "name count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000666
Sam Clegg93102972018-02-23 05:08:53 +0000667 // Names must appear in function index order. As it happens ImportedSymbols
668 // and InputFunctions are numbered in order with imported functions coming
Sam Clegg1963d712018-01-17 20:19:04 +0000669 // first.
Sam Clegg93102972018-02-23 05:08:53 +0000670 for (const Symbol *S : ImportedSymbols) {
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000671 if (auto *F = dyn_cast<FunctionSymbol>(S)) {
672 writeUleb128(Sub.OS, F->getFunctionIndex(), "func index");
Sam Clegg37125f02018-11-09 16:57:41 +0000673 writeStr(Sub.OS, toString(*S), "symbol name");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000674 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000675 }
Sam Clegg9f934222018-02-21 18:29:23 +0000676 for (const InputFunction *F : InputFunctions) {
Sam Clegg1963d712018-01-17 20:19:04 +0000677 if (!F->getName().empty()) {
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000678 writeUleb128(Sub.OS, F->getFunctionIndex(), "func index");
Nicholas Wilson6c7fe302018-04-20 17:09:18 +0000679 if (!F->getDebugName().empty()) {
680 writeStr(Sub.OS, F->getDebugName(), "symbol name");
681 } else {
Sam Clegg37125f02018-11-09 16:57:41 +0000682 writeStr(Sub.OS, maybeDemangleSymbol(F->getName()), "symbol name");
Nicholas Wilson6c7fe302018-04-20 17:09:18 +0000683 }
Sam Clegg1963d712018-01-17 20:19:04 +0000684 }
685 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000686
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000687 Sub.writeTo(Section->getStream());
Sam Cleggc94d3932017-11-17 18:14:09 +0000688}
689
Thomas Lively2a0868f2019-01-17 02:29:41 +0000690void Writer::createProducersSection() {
691 SmallVector<std::pair<std::string, std::string>, 8> Languages;
692 SmallVector<std::pair<std::string, std::string>, 8> Tools;
693 SmallVector<std::pair<std::string, std::string>, 8> SDKs;
694 for (ObjFile *File : Symtab->ObjectFiles) {
695 const WasmProducerInfo &Info = File->getWasmObj()->getProducerInfo();
696 for (auto &Producers : {std::make_pair(&Info.Languages, &Languages),
697 std::make_pair(&Info.Tools, &Tools),
698 std::make_pair(&Info.SDKs, &SDKs)})
699 for (auto &Producer : *Producers.first)
700 if (Producers.second->end() ==
Fangrui Song8048fe22019-03-29 16:21:16 +0000701 llvm::find_if(*Producers.second,
702 [&](std::pair<std::string, std::string> Seen) {
703 return Seen.first == Producer.first;
704 }))
Thomas Lively2a0868f2019-01-17 02:29:41 +0000705 Producers.second->push_back(Producer);
706 }
707 int FieldCount =
708 int(!Languages.empty()) + int(!Tools.empty()) + int(!SDKs.empty());
709 if (FieldCount == 0)
710 return;
711 SyntheticSection *Section =
712 createSyntheticSection(WASM_SEC_CUSTOM, "producers");
713 auto &OS = Section->getStream();
714 writeUleb128(OS, FieldCount, "field count");
715 for (auto &Field :
716 {std::make_pair("language", Languages),
717 std::make_pair("processed-by", Tools), std::make_pair("sdk", SDKs)}) {
718 if (Field.second.empty())
719 continue;
720 writeStr(OS, Field.first, "field name");
721 writeUleb128(OS, Field.second.size(), "number of entries");
722 for (auto &Entry : Field.second) {
723 writeStr(OS, Entry.first, "producer name");
724 writeStr(OS, Entry.second, "producer version");
725 }
726 }
727}
728
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000729void Writer::createTargetFeaturesSection() {
Fangrui Song196a4402019-04-18 13:33:29 +0000730 if (TargetFeatures.empty())
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000731 return;
732
733 SmallVector<std::string, 8> Emitted(TargetFeatures.begin(),
734 TargetFeatures.end());
Fangrui Song196a4402019-04-18 13:33:29 +0000735 llvm::sort(Emitted);
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000736 SyntheticSection *Section =
737 createSyntheticSection(WASM_SEC_CUSTOM, "target_features");
738 auto &OS = Section->getStream();
739 writeUleb128(OS, Emitted.size(), "feature count");
740 for (auto &Feature : Emitted) {
741 writeU8(OS, WASM_FEATURE_PREFIX_USED, "feature used prefix");
742 writeStr(OS, Feature, "feature name");
743 }
744}
745
Sam Cleggc94d3932017-11-17 18:14:09 +0000746void Writer::writeHeader() {
747 memcpy(Buffer->getBufferStart(), Header.data(), Header.size());
748}
749
750void Writer::writeSections() {
751 uint8_t *Buf = Buffer->getBufferStart();
752 parallelForEach(OutputSections, [Buf](OutputSection *S) { S->writeTo(Buf); });
753}
754
755// Fix the memory layout of the output binary. This assigns memory offsets
Sam Clegg49ed9262017-12-01 00:53:21 +0000756// to each of the input data sections as well as the explicit stack region.
Sam Clegga0f095e2018-05-03 17:21:53 +0000757// The default memory layout is as follows, from low to high.
758//
Sam Cleggf0d433d2018-02-02 22:59:56 +0000759// - initialized data (starting at Config->GlobalBase)
760// - BSS data (not currently implemented in llvm)
761// - explicit stack (Config->ZStackSize)
762// - heap start / unallocated
Sam Clegga0f095e2018-05-03 17:21:53 +0000763//
764// The --stack-first option means that stack is placed before any static data.
Heejin Ahn4821ebf2018-08-29 21:03:16 +0000765// This can be useful since it means that stack overflow traps immediately
766// rather than overwriting global data, but also increases code size since all
767// static data loads and stores requires larger offsets.
Sam Cleggc94d3932017-11-17 18:14:09 +0000768void Writer::layoutMemory() {
Sam Cleggc94d3932017-11-17 18:14:09 +0000769 createOutputSegments();
770
Sam Clegga0f095e2018-05-03 17:21:53 +0000771 uint32_t MemoryPtr = 0;
772
773 auto PlaceStack = [&]() {
Sam Cleggbfb75342018-11-15 00:37:21 +0000774 if (Config->Relocatable || Config->Shared)
Sam Clegga0f095e2018-05-03 17:21:53 +0000775 return;
Heejin Ahna1cc4ea2019-02-04 19:13:46 +0000776 MemoryPtr = alignTo(MemoryPtr, StackAlignment);
777 if (Config->ZStackSize != alignTo(Config->ZStackSize, StackAlignment))
778 error("stack size must be " + Twine(StackAlignment) + "-byte aligned");
Sam Clegga0f095e2018-05-03 17:21:53 +0000779 log("mem: stack size = " + Twine(Config->ZStackSize));
780 log("mem: stack base = " + Twine(MemoryPtr));
781 MemoryPtr += Config->ZStackSize;
Sam Clegg2dad4e22018-11-15 18:15:54 +0000782 auto *SP = cast<DefinedGlobal>(WasmSym::StackPointer);
783 SP->Global->Global.InitExpr.Value.Int32 = MemoryPtr;
Sam Clegga0f095e2018-05-03 17:21:53 +0000784 log("mem: stack top = " + Twine(MemoryPtr));
785 };
786
787 if (Config->StackFirst) {
788 PlaceStack();
789 } else {
790 MemoryPtr = Config->GlobalBase;
791 log("mem: global base = " + Twine(Config->GlobalBase));
792 }
793
794 uint32_t DataStart = MemoryPtr;
795
Sam Cleggf0d433d2018-02-02 22:59:56 +0000796 // Arbitrarily set __dso_handle handle to point to the start of the data
797 // segments.
798 if (WasmSym::DsoHandle)
Sam Clegga0f095e2018-05-03 17:21:53 +0000799 WasmSym::DsoHandle->setVirtualAddress(DataStart);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000800
Sam Cleggbfb75342018-11-15 00:37:21 +0000801 MemAlign = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000802 for (OutputSegment *Seg : Segments) {
Sam Cleggbfb75342018-11-15 00:37:21 +0000803 MemAlign = std::max(MemAlign, Seg->Alignment);
Sam Clegg622ad042019-01-17 22:09:09 +0000804 MemoryPtr = alignTo(MemoryPtr, 1ULL << Seg->Alignment);
Sam Cleggc94d3932017-11-17 18:14:09 +0000805 Seg->StartVA = MemoryPtr;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000806 log(formatv("mem: {0,-15} offset={1,-8} size={2,-8} align={3}", Seg->Name,
807 MemoryPtr, Seg->Size, Seg->Alignment));
Sam Cleggc94d3932017-11-17 18:14:09 +0000808 MemoryPtr += Seg->Size;
809 }
810
Sam Cleggf0d433d2018-02-02 22:59:56 +0000811 // TODO: Add .bss space here.
Sam Clegg37a4a8a2018-02-07 03:04:53 +0000812 if (WasmSym::DataEnd)
813 WasmSym::DataEnd->setVirtualAddress(MemoryPtr);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000814
Sam Clegga0f095e2018-05-03 17:21:53 +0000815 log("mem: static data = " + Twine(MemoryPtr - DataStart));
Sam Cleggc94d3932017-11-17 18:14:09 +0000816
Sam Clegg2dad4e22018-11-15 18:15:54 +0000817 if (Config->Shared) {
818 MemSize = MemoryPtr;
819 return;
820 }
821
Sam Clegga0f095e2018-05-03 17:21:53 +0000822 if (!Config->StackFirst)
823 PlaceStack();
824
825 // Set `__heap_base` to directly follow the end of the stack or global data.
826 // The fact that this comes last means that a malloc/brk implementation
827 // can grow the heap at runtime.
Sam Cleggc94d3932017-11-17 18:14:09 +0000828 if (!Config->Relocatable) {
Sam Cleggf0d433d2018-02-02 22:59:56 +0000829 WasmSym::HeapBase->setVirtualAddress(MemoryPtr);
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000830 log("mem: heap base = " + Twine(MemoryPtr));
Sam Cleggc94d3932017-11-17 18:14:09 +0000831 }
832
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000833 if (Config->InitialMemory != 0) {
834 if (Config->InitialMemory != alignTo(Config->InitialMemory, WasmPageSize))
835 error("initial memory must be " + Twine(WasmPageSize) + "-byte aligned");
836 if (MemoryPtr > Config->InitialMemory)
837 error("initial memory too small, " + Twine(MemoryPtr) + " bytes needed");
838 else
839 MemoryPtr = Config->InitialMemory;
840 }
Sam Cleggbfb75342018-11-15 00:37:21 +0000841 MemSize = MemoryPtr;
842 NumMemoryPages = alignTo(MemoryPtr, WasmPageSize) / WasmPageSize;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000843 log("mem: total pages = " + Twine(NumMemoryPages));
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000844
Thomas Lively06391f32019-03-29 20:43:49 +0000845 // Check max if explicitly supplied or required by shared memory
846 if (Config->MaxMemory != 0 || Config->SharedMemory) {
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000847 if (Config->MaxMemory != alignTo(Config->MaxMemory, WasmPageSize))
848 error("maximum memory must be " + Twine(WasmPageSize) + "-byte aligned");
849 if (MemoryPtr > Config->MaxMemory)
850 error("maximum memory too small, " + Twine(MemoryPtr) + " bytes needed");
851 MaxMemoryPages = Config->MaxMemory / WasmPageSize;
852 log("mem: max pages = " + Twine(MaxMemoryPages));
853 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000854}
855
856SyntheticSection *Writer::createSyntheticSection(uint32_t Type,
Sam Cleggc375e4e2018-01-10 19:18:22 +0000857 StringRef Name) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000858 auto Sec = make<SyntheticSection>(Type, Name);
Sam Cleggab2ac292017-12-20 05:14:48 +0000859 log("createSection: " + toString(*Sec));
Sam Cleggc94d3932017-11-17 18:14:09 +0000860 OutputSections.push_back(Sec);
861 return Sec;
862}
863
864void Writer::createSections() {
865 // Known sections
Sam Cleggbfb75342018-11-15 00:37:21 +0000866 if (Config->Pic)
867 createDylinkSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000868 createTypeSection();
869 createImportSection();
870 createFunctionSection();
871 createTableSection();
872 createMemorySection();
873 createGlobalSection();
Heejin Ahne915a712018-12-08 06:17:43 +0000874 createEventSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000875 createExportSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000876 createElemSection();
Thomas Lively84771e22019-04-19 23:40:36 +0000877 createDataCountSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000878 createCodeSection();
879 createDataSection();
Sam Clegg80ba4382018-04-10 16:12:49 +0000880 createCustomSections();
Sam Cleggc94d3932017-11-17 18:14:09 +0000881
882 // Custom sections
Sam Clegg99eb42c2018-02-27 23:58:03 +0000883 if (Config->Relocatable) {
Sam Clegg99eb42c2018-02-27 23:58:03 +0000884 createLinkingSection();
Nicholas Wilson94d3b162018-03-05 12:33:58 +0000885 createRelocSections();
Sam Clegg99eb42c2018-02-27 23:58:03 +0000886 }
Thomas Lively2a0868f2019-01-17 02:29:41 +0000887
Sam Cleggc94d3932017-11-17 18:14:09 +0000888 if (!Config->StripDebug && !Config->StripAll)
889 createNameSection();
890
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000891 if (!Config->StripAll) {
Thomas Lively2a0868f2019-01-17 02:29:41 +0000892 createProducersSection();
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000893 createTargetFeaturesSection();
894 }
Thomas Lively2a0868f2019-01-17 02:29:41 +0000895
Sam Cleggc94d3932017-11-17 18:14:09 +0000896 for (OutputSection *S : OutputSections) {
897 S->setOffset(FileSize);
898 S->finalizeContents();
899 FileSize += S->getSize();
900 }
901}
902
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000903void Writer::calculateTargetFeatures() {
Thomas Lively82de51a2019-03-26 04:11:05 +0000904 SmallSet<std::string, 8> Used;
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000905 SmallSet<std::string, 8> Required;
906 SmallSet<std::string, 8> Disallowed;
907
Thomas Lively82de51a2019-03-26 04:11:05 +0000908 // Only infer used features if user did not specify features
909 bool InferFeatures = !Config->Features.hasValue();
910
911 if (!InferFeatures) {
912 for (auto &Feature : Config->Features.getValue())
913 TargetFeatures.insert(Feature);
914 // No need to read or check features
915 if (!Config->CheckFeatures)
916 return;
917 }
918
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000919 // Find the sets of used, required, and disallowed features
920 for (ObjFile *File : Symtab->ObjectFiles) {
921 for (auto &Feature : File->getWasmObj()->getTargetFeatures()) {
922 switch (Feature.Prefix) {
923 case WASM_FEATURE_PREFIX_USED:
Thomas Lively82de51a2019-03-26 04:11:05 +0000924 Used.insert(Feature.Name);
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000925 break;
926 case WASM_FEATURE_PREFIX_REQUIRED:
Thomas Lively82de51a2019-03-26 04:11:05 +0000927 Used.insert(Feature.Name);
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000928 Required.insert(Feature.Name);
929 break;
930 case WASM_FEATURE_PREFIX_DISALLOWED:
931 Disallowed.insert(Feature.Name);
932 break;
933 default:
934 error("Unrecognized feature policy prefix " +
935 std::to_string(Feature.Prefix));
936 }
937 }
938 }
939
Thomas Lively82de51a2019-03-26 04:11:05 +0000940 if (InferFeatures)
941 TargetFeatures.insert(Used.begin(), Used.end());
942
Thomas Lively06391f32019-03-29 20:43:49 +0000943 if (TargetFeatures.count("atomics") && !Config->SharedMemory)
944 error("'atomics' feature is used, so --shared-memory must be used");
945
Thomas Lively82de51a2019-03-26 04:11:05 +0000946 if (!Config->CheckFeatures)
947 return;
948
Thomas Lively06391f32019-03-29 20:43:49 +0000949 if (Disallowed.count("atomics") && Config->SharedMemory)
950 error(
951 "'atomics' feature is disallowed, so --shared-memory must not be used");
952
Thomas Lively82de51a2019-03-26 04:11:05 +0000953 // Validate that used features are allowed in output
954 if (!InferFeatures) {
955 for (auto &Feature : Used) {
956 if (!TargetFeatures.count(Feature))
957 error(Twine("Target feature '") + Feature + "' is not allowed.");
958 }
959 }
960
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000961 // Validate the required and disallowed constraints for each file
962 for (ObjFile *File : Symtab->ObjectFiles) {
963 SmallSet<std::string, 8> ObjectFeatures;
964 for (auto &Feature : File->getWasmObj()->getTargetFeatures()) {
965 if (Feature.Prefix == WASM_FEATURE_PREFIX_DISALLOWED)
966 continue;
967 ObjectFeatures.insert(Feature.Name);
968 if (Disallowed.count(Feature.Name))
Thomas Lively82de51a2019-03-26 04:11:05 +0000969 error(Twine("Target feature '") + Feature.Name +
970 "' is disallowed. Use --no-check-features to suppress.");
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000971 }
972 for (auto &Feature : Required) {
973 if (!ObjectFeatures.count(Feature))
Thomas Lively82de51a2019-03-26 04:11:05 +0000974 error(Twine("Missing required target feature '") + Feature +
975 "'. Use --no-check-features to suppress.");
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000976 }
977 }
978}
979
Sam Cleggc94d3932017-11-17 18:14:09 +0000980void Writer::calculateImports() {
Sam Clegg574d7ce2017-12-15 19:23:49 +0000981 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000982 if (!Sym->isUndefined())
983 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000984 if (Sym->isWeak() && !Config->Relocatable)
Sam Clegg574d7ce2017-12-15 19:23:49 +0000985 continue;
Nicholas Wilsona1e299f2018-04-20 17:18:06 +0000986 if (!Sym->isLive())
987 continue;
Sam Cleggc729c1b2018-05-30 18:07:52 +0000988 if (!Sym->IsUsedInRegularObj)
989 continue;
Sam Clegg492f7522019-03-26 19:46:15 +0000990 // We don't generate imports for data symbols. They however can be imported
991 // as GOT entries.
992 if (isa<DataSymbol>(Sym))
Sam Cleggd425d6b2019-03-12 21:53:23 +0000993 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000994
Nicola Zaghene7245b42018-05-15 13:36:20 +0000995 LLVM_DEBUG(dbgs() << "import: " << Sym->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000996 ImportedSymbols.emplace_back(Sym);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000997 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
998 F->setFunctionIndex(NumImportedFunctions++);
Heejin Ahne915a712018-12-08 06:17:43 +0000999 else if (auto *G = dyn_cast<GlobalSymbol>(Sym))
1000 G->setGlobalIndex(NumImportedGlobals++);
Sam Clegg93102972018-02-23 05:08:53 +00001001 else
Heejin Ahne915a712018-12-08 06:17:43 +00001002 cast<EventSymbol>(Sym)->setEventIndex(NumImportedEvents++);
Sam Cleggc94d3932017-11-17 18:14:09 +00001003 }
1004}
1005
Sam Cleggd3052d52018-01-18 23:40:49 +00001006void Writer::calculateExports() {
Sam Clegg93102972018-02-23 05:08:53 +00001007 if (Config->Relocatable)
1008 return;
Sam Cleggf0d433d2018-02-02 22:59:56 +00001009
Sam Cleggd6beb322018-05-10 18:10:34 +00001010 if (!Config->Relocatable && !Config->ImportMemory)
1011 Exports.push_back(WasmExport{"memory", WASM_EXTERNAL_MEMORY, 0});
1012
1013 if (!Config->Relocatable && Config->ExportTable)
Heejin Ahna1cc4ea2019-02-04 19:13:46 +00001014 Exports.push_back(WasmExport{FunctionTableName, WASM_EXTERNAL_TABLE, 0});
Sam Cleggd6beb322018-05-10 18:10:34 +00001015
1016 unsigned FakeGlobalIndex = NumImportedGlobals + InputGlobals.size();
1017
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +00001018 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Cleggce004bf2018-06-28 17:04:58 +00001019 if (!Sym->isExported())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +00001020 continue;
Sam Clegg93102972018-02-23 05:08:53 +00001021 if (!Sym->isLive())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +00001022 continue;
Sam Clegg93102972018-02-23 05:08:53 +00001023
Sam Cleggd6beb322018-05-10 18:10:34 +00001024 StringRef Name = Sym->getName();
1025 WasmExport Export;
1026 if (auto *F = dyn_cast<DefinedFunction>(Sym)) {
1027 Export = {Name, WASM_EXTERNAL_FUNCTION, F->getFunctionIndex()};
1028 } else if (auto *G = dyn_cast<DefinedGlobal>(Sym)) {
Sam Clegg177b4582018-06-07 01:27:07 +00001029 // TODO(sbc): Remove this check once to mutable global proposal is
1030 // implement in all major browsers.
1031 // See: https://github.com/WebAssembly/mutable-global
1032 if (G->getGlobalType()->Mutable) {
1033 // Only the __stack_pointer should ever be create as mutable.
1034 assert(G == WasmSym::StackPointer);
1035 continue;
1036 }
Sam Cleggd6beb322018-05-10 18:10:34 +00001037 Export = {Name, WASM_EXTERNAL_GLOBAL, G->getGlobalIndex()};
Heejin Ahne915a712018-12-08 06:17:43 +00001038 } else if (auto *E = dyn_cast<DefinedEvent>(Sym)) {
1039 Export = {Name, WASM_EXTERNAL_EVENT, E->getEventIndex()};
Sam Cleggd6beb322018-05-10 18:10:34 +00001040 } else {
1041 auto *D = cast<DefinedData>(Sym);
Sam Clegg93102972018-02-23 05:08:53 +00001042 DefinedFakeGlobals.emplace_back(D);
Sam Cleggd6beb322018-05-10 18:10:34 +00001043 Export = {Name, WASM_EXTERNAL_GLOBAL, FakeGlobalIndex++};
1044 }
1045
Nicola Zaghene7245b42018-05-15 13:36:20 +00001046 LLVM_DEBUG(dbgs() << "Export: " << Name << "\n");
Sam Cleggd6beb322018-05-10 18:10:34 +00001047 Exports.push_back(Export);
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +00001048 }
Sam Clegg93102972018-02-23 05:08:53 +00001049}
1050
1051void Writer::assignSymtab() {
1052 if (!Config->Relocatable)
1053 return;
1054
Sam Cleggd177ab22018-05-04 23:14:42 +00001055 StringMap<uint32_t> SectionSymbolIndices;
1056
Sam Clegg93102972018-02-23 05:08:53 +00001057 unsigned SymbolIndex = SymtabEntries.size();
Sam Cleggd177ab22018-05-04 23:14:42 +00001058
Sam Clegg89e4dcb2019-01-30 18:55:15 +00001059 auto AddSymbol = [&](Symbol *Sym) {
1060 if (auto *S = dyn_cast<SectionSymbol>(Sym)) {
1061 StringRef Name = S->getName();
1062 if (CustomSectionMapping.count(Name) == 0)
1063 return;
Sam Cleggd177ab22018-05-04 23:14:42 +00001064
Sam Clegg89e4dcb2019-01-30 18:55:15 +00001065 auto SSI = SectionSymbolIndices.find(Name);
1066 if (SSI != SectionSymbolIndices.end()) {
1067 Sym->setOutputSymbolIndex(SSI->second);
1068 return;
Sam Cleggd177ab22018-05-04 23:14:42 +00001069 }
1070
Sam Clegg89e4dcb2019-01-30 18:55:15 +00001071 SectionSymbolIndices[Name] = SymbolIndex;
1072 CustomSectionSymbols[Name] = cast<SectionSymbol>(Sym);
Sam Cleggd3052d52018-01-18 23:40:49 +00001073
Sam Clegg89e4dcb2019-01-30 18:55:15 +00001074 Sym->markLive();
1075 }
1076
1077 // (Since this is relocatable output, GC is not performed so symbols must
1078 // be live.)
1079 assert(Sym->isLive());
1080 Sym->setOutputSymbolIndex(SymbolIndex++);
1081 SymtabEntries.emplace_back(Sym);
1082 };
1083
1084 for (Symbol *Sym : Symtab->getSymbols())
Sam Cleggd15a41542019-03-08 21:10:48 +00001085 if (Sym->IsUsedInRegularObj)
Sam Clegg89e4dcb2019-01-30 18:55:15 +00001086 AddSymbol(Sym);
1087
1088 for (ObjFile *File : Symtab->ObjectFiles) {
1089 LLVM_DEBUG(dbgs() << "Local symtab entries: " << File->getName() << "\n");
1090 for (Symbol *Sym : File->getSymbols())
1091 if (Sym->isLocal())
1092 AddSymbol(Sym);
1093 }
Sam Cleggd3052d52018-01-18 23:40:49 +00001094}
1095
Sam Cleggc375e4e2018-01-10 19:18:22 +00001096uint32_t Writer::lookupType(const WasmSignature &Sig) {
Sam Clegg8d027d62018-01-10 20:12:26 +00001097 auto It = TypeIndices.find(Sig);
1098 if (It == TypeIndices.end()) {
Sam Cleggc375e4e2018-01-10 19:18:22 +00001099 error("type not found: " + toString(Sig));
Sam Clegg8d027d62018-01-10 20:12:26 +00001100 return 0;
1101 }
1102 return It->second;
Sam Cleggc375e4e2018-01-10 19:18:22 +00001103}
1104
1105uint32_t Writer::registerType(const WasmSignature &Sig) {
Sam Cleggb8621592017-11-30 01:40:08 +00001106 auto Pair = TypeIndices.insert(std::make_pair(Sig, Types.size()));
Sam Cleggc375e4e2018-01-10 19:18:22 +00001107 if (Pair.second) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001108 LLVM_DEBUG(dbgs() << "type " << toString(Sig) << "\n");
Sam Cleggb8621592017-11-30 01:40:08 +00001109 Types.push_back(&Sig);
Sam Cleggc375e4e2018-01-10 19:18:22 +00001110 }
Sam Cleggb8621592017-11-30 01:40:08 +00001111 return Pair.first->second;
1112}
1113
Sam Cleggc94d3932017-11-17 18:14:09 +00001114void Writer::calculateTypes() {
Sam Clegg8f6d2de2018-01-31 23:48:14 +00001115 // The output type section is the union of the following sets:
1116 // 1. Any signature used in the TYPE relocation
1117 // 2. The signatures of all imported functions
1118 // 3. The signatures of all defined functions
Heejin Ahne915a712018-12-08 06:17:43 +00001119 // 4. The signatures of all imported events
1120 // 5. The signatures of all defined events
Sam Clegg8f6d2de2018-01-31 23:48:14 +00001121
Sam Cleggc94d3932017-11-17 18:14:09 +00001122 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +00001123 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
1124 for (uint32_t I = 0; I < Types.size(); I++)
1125 if (File->TypeIsUsed[I])
1126 File->TypeMap[I] = registerType(Types[I]);
Sam Cleggc94d3932017-11-17 18:14:09 +00001127 }
Sam Clegg50686852018-01-12 18:35:13 +00001128
Heejin Ahne915a712018-12-08 06:17:43 +00001129 for (const Symbol *Sym : ImportedSymbols) {
Sam Clegg93102972018-02-23 05:08:53 +00001130 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
Heejin Ahne915a712018-12-08 06:17:43 +00001131 registerType(*F->Signature);
1132 else if (auto *E = dyn_cast<EventSymbol>(Sym))
1133 registerType(*E->Signature);
1134 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +00001135
Sam Clegg9f934222018-02-21 18:29:23 +00001136 for (const InputFunction *F : InputFunctions)
Sam Clegg8f6d2de2018-01-31 23:48:14 +00001137 registerType(F->Signature);
Heejin Ahne915a712018-12-08 06:17:43 +00001138
1139 for (const InputEvent *E : InputEvents)
1140 registerType(E->Signature);
Sam Cleggc94d3932017-11-17 18:14:09 +00001141}
1142
Sam Cleggea38ac52019-05-10 01:52:08 +00001143static bool requiresGOTAccess(const Symbol* Sym) {
1144 return Config->Pic && !Sym->isHidden() && !Sym->isLocal();
1145}
1146
Sam Clegg632c21792019-03-16 01:18:12 +00001147void Writer::processRelocations(InputChunk *Chunk) {
1148 if (!Chunk->Live)
1149 return;
1150 ObjFile *File = Chunk->File;
1151 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
1152 for (const WasmRelocation &Reloc : Chunk->getRelocations()) {
Sam Clegg0b13ca22019-05-13 16:42:52 +00001153 if (Reloc.Type == R_WASM_TYPE_INDEX_LEB) {
1154 // Mark target type as live
1155 File->TypeMap[Reloc.Index] = registerType(Types[Reloc.Index]);
1156 File->TypeIsUsed[Reloc.Index] = true;
1157 continue;
1158 }
1159
1160 // Other relocation types all have a corresponding symbol
1161 auto *Sym = File->getSymbols()[Reloc.Index];
Sam Clegg632c21792019-03-16 01:18:12 +00001162 switch (Reloc.Type) {
1163 case R_WASM_TABLE_INDEX_I32:
Sam Clegga116d912019-04-05 00:35:12 +00001164 case R_WASM_TABLE_INDEX_SLEB:
1165 case R_WASM_TABLE_INDEX_REL_SLEB: {
Sam Clegg0b13ca22019-05-13 16:42:52 +00001166 auto *F = cast<FunctionSymbol>(Sym);
1167 if (F->hasTableIndex() || !F->hasFunctionIndex() || requiresGOTAccess(F))
Sam Cleggea38ac52019-05-10 01:52:08 +00001168 break;
Sam Clegg0b13ca22019-05-13 16:42:52 +00001169 F->setTableIndex(TableBase + IndirectFunctions.size());
1170 IndirectFunctions.emplace_back(F);
Sam Clegg632c21792019-03-16 01:18:12 +00001171 break;
1172 }
1173 case R_WASM_TYPE_INDEX_LEB:
Sam Clegg632c21792019-03-16 01:18:12 +00001174 break;
Sam Clegg0b13ca22019-05-13 16:42:52 +00001175 case R_WASM_GLOBAL_INDEX_LEB:
Sam Clegg492f7522019-03-26 19:46:15 +00001176 if (!isa<GlobalSymbol>(Sym) && !Sym->isInGOT()) {
1177 Sym->setGOTIndex(NumImportedGlobals++);
1178 GOTSymbols.push_back(Sym);
1179 }
Sam Clegg7cdec272019-04-22 16:12:54 +00001180 break;
Sam Clegg7cdec272019-04-22 16:12:54 +00001181 case R_WASM_MEMORY_ADDR_SLEB:
1182 case R_WASM_MEMORY_ADDR_LEB:
Sam Clegg0b13ca22019-05-13 16:42:52 +00001183 case R_WASM_MEMORY_ADDR_REL_SLEB:
Sam Clegg7cdec272019-04-22 16:12:54 +00001184 if (!Config->Relocatable) {
Sam Clegg7cdec272019-04-22 16:12:54 +00001185 if (Sym->isUndefined() && !Sym->isWeak()) {
1186 error(toString(File) + ": cannot resolve relocation of type " +
1187 relocTypeToString(Reloc.Type) +
1188 " against undefined (non-weak) data symbol: " + toString(*Sym));
1189 }
1190 }
1191 break;
Sam Clegg492f7522019-03-26 19:46:15 +00001192 }
Sam Clegg09137be2019-04-04 18:40:51 +00001193
1194 if (Config->Pic) {
Sam Clegg09137be2019-04-04 18:40:51 +00001195 switch (Reloc.Type) {
1196 case R_WASM_TABLE_INDEX_SLEB:
1197 case R_WASM_MEMORY_ADDR_SLEB:
Sam Clegg0b13ca22019-05-13 16:42:52 +00001198 case R_WASM_MEMORY_ADDR_LEB:
Sam Clegg0d9f6092019-04-10 15:06:17 +00001199 // Certain relocation types can't be used when building PIC output, since
1200 // they would require absolute symbol addresses at link time.
Sam Clegg09137be2019-04-04 18:40:51 +00001201 error(toString(File) + ": relocation " +
1202 relocTypeToString(Reloc.Type) + " cannot be used againt symbol " +
1203 toString(*Sym) + "; recompile with -fPIC");
1204 break;
Sam Clegg0d9f6092019-04-10 15:06:17 +00001205 case R_WASM_TABLE_INDEX_I32:
Sam Clegg0b13ca22019-05-13 16:42:52 +00001206 case R_WASM_MEMORY_ADDR_I32:
Sam Clegg0d9f6092019-04-10 15:06:17 +00001207 // These relocation types are only present in the data section and
1208 // will be converted into code by `generateRelocationCode`. This code
1209 // requires the symbols to have GOT entires.
Sam Cleggea38ac52019-05-10 01:52:08 +00001210 if (requiresGOTAccess(Sym) && !Sym->isInGOT()) {
Sam Clegg0d9f6092019-04-10 15:06:17 +00001211 Sym->setGOTIndex(NumImportedGlobals++);
1212 GOTSymbols.push_back(Sym);
1213 }
1214 break;
1215 }
Sam Clegg09137be2019-04-04 18:40:51 +00001216 }
Sam Clegg632c21792019-03-16 01:18:12 +00001217 }
1218}
1219
Sam Clegg8d146bb2018-01-09 23:56:44 +00001220void Writer::assignIndexes() {
Heejin Ahnaeaab992018-11-19 23:21:25 +00001221 assert(InputFunctions.empty());
1222 uint32_t FunctionIndex = NumImportedFunctions;
Nicholas Wilsonebda41f2018-03-09 16:43:05 +00001223 auto AddDefinedFunction = [&](InputFunction *Func) {
1224 if (!Func->Live)
1225 return;
1226 InputFunctions.emplace_back(Func);
Sam Clegge3f3ccf2018-03-12 19:56:23 +00001227 Func->setFunctionIndex(FunctionIndex++);
Nicholas Wilsonebda41f2018-03-09 16:43:05 +00001228 };
1229
Nicholas Wilson5639da82018-03-12 15:44:07 +00001230 for (InputFunction *Func : Symtab->SyntheticFunctions)
1231 AddDefinedFunction(Func);
1232
Sam Clegg87e61922018-01-08 23:39:11 +00001233 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001234 LLVM_DEBUG(dbgs() << "Functions: " << File->getName() << "\n");
Nicholas Wilsonebda41f2018-03-09 16:43:05 +00001235 for (InputFunction *Func : File->Functions)
1236 AddDefinedFunction(Func);
Sam Clegg8d146bb2018-01-09 23:56:44 +00001237 }
1238
1239 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001240 LLVM_DEBUG(dbgs() << "Handle relocs: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +00001241 for (InputChunk *Chunk : File->Functions)
Sam Clegg632c21792019-03-16 01:18:12 +00001242 processRelocations(Chunk);
Sam Clegg93102972018-02-23 05:08:53 +00001243 for (InputChunk *Chunk : File->Segments)
Sam Clegg632c21792019-03-16 01:18:12 +00001244 processRelocations(Chunk);
Sam Cleggd177ab22018-05-04 23:14:42 +00001245 for (auto &P : File->CustomSections)
Sam Clegg632c21792019-03-16 01:18:12 +00001246 processRelocations(P);
Sam Clegg93102972018-02-23 05:08:53 +00001247 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +00001248
Heejin Ahnaeaab992018-11-19 23:21:25 +00001249 assert(InputGlobals.empty());
1250 uint32_t GlobalIndex = NumImportedGlobals;
Sam Clegg93102972018-02-23 05:08:53 +00001251 auto AddDefinedGlobal = [&](InputGlobal *Global) {
1252 if (Global->Live) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001253 LLVM_DEBUG(dbgs() << "AddDefinedGlobal: " << GlobalIndex << "\n");
Sam Clegge3f3ccf2018-03-12 19:56:23 +00001254 Global->setGlobalIndex(GlobalIndex++);
Sam Clegg93102972018-02-23 05:08:53 +00001255 InputGlobals.push_back(Global);
1256 }
1257 };
1258
Nicholas Wilsonebda41f2018-03-09 16:43:05 +00001259 for (InputGlobal *Global : Symtab->SyntheticGlobals)
1260 AddDefinedGlobal(Global);
Sam Clegg93102972018-02-23 05:08:53 +00001261
1262 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001263 LLVM_DEBUG(dbgs() << "Globals: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +00001264 for (InputGlobal *Global : File->Globals)
1265 AddDefinedGlobal(Global);
Sam Cleggc94d3932017-11-17 18:14:09 +00001266 }
Heejin Ahne915a712018-12-08 06:17:43 +00001267
1268 assert(InputEvents.empty());
1269 uint32_t EventIndex = NumImportedEvents;
1270 auto AddDefinedEvent = [&](InputEvent *Event) {
1271 if (Event->Live) {
1272 LLVM_DEBUG(dbgs() << "AddDefinedEvent: " << EventIndex << "\n");
1273 Event->setEventIndex(EventIndex++);
1274 InputEvents.push_back(Event);
1275 }
1276 };
1277
1278 for (ObjFile *File : Symtab->ObjectFiles) {
1279 LLVM_DEBUG(dbgs() << "Events: " << File->getName() << "\n");
1280 for (InputEvent *Event : File->Events)
1281 AddDefinedEvent(Event);
1282 }
Sam Cleggc94d3932017-11-17 18:14:09 +00001283}
1284
1285static StringRef getOutputDataSegmentName(StringRef Name) {
Sam Cleggbfb75342018-11-15 00:37:21 +00001286 // With PIC code we currently only support a single data segment since
1287 // we only have a single __memory_base to use as our base address.
1288 if (Config->Pic)
1289 return "data";
Sam Clegg66844762018-05-10 18:23:51 +00001290 if (!Config->MergeDataSegments)
Sam Cleggc94d3932017-11-17 18:14:09 +00001291 return Name;
Rui Ueyama4764b572018-02-28 00:57:28 +00001292 if (Name.startswith(".text."))
1293 return ".text";
1294 if (Name.startswith(".data."))
1295 return ".data";
1296 if (Name.startswith(".bss."))
1297 return ".bss";
Sam Clegg57694c52018-08-08 18:02:55 +00001298 if (Name.startswith(".rodata."))
1299 return ".rodata";
Sam Cleggc94d3932017-11-17 18:14:09 +00001300 return Name;
1301}
1302
1303void Writer::createOutputSegments() {
1304 for (ObjFile *File : Symtab->ObjectFiles) {
1305 for (InputSegment *Segment : File->Segments) {
Sam Clegg447ae402018-02-13 20:29:38 +00001306 if (!Segment->Live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +00001307 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +00001308 StringRef Name = getOutputDataSegmentName(Segment->getName());
1309 OutputSegment *&S = SegmentMap[Name];
1310 if (S == nullptr) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001311 LLVM_DEBUG(dbgs() << "new segment: " << Name << "\n");
Sam Clegg93102972018-02-23 05:08:53 +00001312 S = make<OutputSegment>(Name, Segments.size());
Sam Cleggc94d3932017-11-17 18:14:09 +00001313 Segments.push_back(S);
1314 }
1315 S->addInputSegment(Segment);
Nicola Zaghene7245b42018-05-15 13:36:20 +00001316 LLVM_DEBUG(dbgs() << "added data: " << Name << ": " << S->Size << "\n");
Sam Cleggc94d3932017-11-17 18:14:09 +00001317 }
1318 }
1319}
1320
Sam Clegg09137be2019-04-04 18:40:51 +00001321// For -shared (PIC) output, we create create a synthetic function which will
1322// apply any relocations to the data segments on startup. This function is
1323// called __wasm_apply_relocs and is added at the very beginning of
1324// __wasm_call_ctors before any of the constructors run.
1325void Writer::createApplyRelocationsFunction() {
1326 LLVM_DEBUG(dbgs() << "createApplyRelocationsFunction\n");
1327 // First write the body's contents to a string.
1328 std::string BodyContent;
1329 {
1330 raw_string_ostream OS(BodyContent);
1331 writeUleb128(OS, 0, "num locals");
1332 for (const OutputSegment *Seg : Segments)
1333 for (const InputSegment *InSeg : Seg->InputSegments)
1334 InSeg->generateRelocationCode(OS);
1335 writeU8(OS, WASM_OPCODE_END, "END");
1336 }
1337
1338 // Once we know the size of the body we can create the final function body
1339 std::string FunctionBody;
1340 {
1341 raw_string_ostream OS(FunctionBody);
1342 writeUleb128(OS, BodyContent.size(), "function size");
1343 OS << BodyContent;
1344 }
1345
1346 ArrayRef<uint8_t> Body = arrayRefFromStringRef(Saver.save(FunctionBody));
1347 cast<SyntheticFunction>(WasmSym::ApplyRelocs->Function)->setBody(Body);
1348}
Sam Clegg50686852018-01-12 18:35:13 +00001349
1350// Create synthetic "__wasm_call_ctors" function based on ctor functions
1351// in input object.
Sam Clegg09137be2019-04-04 18:40:51 +00001352void Writer::createCallCtorsFunction() {
Sam Clegg0e6b42f2019-03-01 22:35:47 +00001353 if (!WasmSym::CallCtors->isLive())
1354 return;
1355
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +00001356 // First write the body's contents to a string.
1357 std::string BodyContent;
Sam Clegg50686852018-01-12 18:35:13 +00001358 {
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +00001359 raw_string_ostream OS(BodyContent);
Sam Clegg50686852018-01-12 18:35:13 +00001360 writeUleb128(OS, 0, "num locals");
Sam Clegg09137be2019-04-04 18:40:51 +00001361 if (Config->Pic) {
1362 writeU8(OS, WASM_OPCODE_CALL, "CALL");
1363 writeUleb128(OS, WasmSym::ApplyRelocs->getFunctionIndex(),
1364 "function index");
1365 }
Sam Clegg93102972018-02-23 05:08:53 +00001366 for (const WasmInitEntry &F : InitFunctions) {
Sam Clegg09137be2019-04-04 18:40:51 +00001367 writeU8(OS, WASM_OPCODE_CALL, "CALL");
Sam Clegge3f3ccf2018-03-12 19:56:23 +00001368 writeUleb128(OS, F.Sym->getFunctionIndex(), "function index");
Sam Clegg50686852018-01-12 18:35:13 +00001369 }
Sam Clegg09137be2019-04-04 18:40:51 +00001370 writeU8(OS, WASM_OPCODE_END, "END");
Sam Clegg50686852018-01-12 18:35:13 +00001371 }
1372
1373 // Once we know the size of the body we can create the final function body
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +00001374 std::string FunctionBody;
1375 {
1376 raw_string_ostream OS(FunctionBody);
1377 writeUleb128(OS, BodyContent.size(), "function size");
1378 OS << BodyContent;
1379 }
Rui Ueyama29abfe42018-02-28 17:43:15 +00001380
Sam Cleggea656472018-10-22 08:35:39 +00001381 ArrayRef<uint8_t> Body = arrayRefFromStringRef(Saver.save(FunctionBody));
Nicholas Wilsonebda41f2018-03-09 16:43:05 +00001382 cast<SyntheticFunction>(WasmSym::CallCtors->Function)->setBody(Body);
Sam Clegg50686852018-01-12 18:35:13 +00001383}
1384
1385// Populate InitFunctions vector with init functions from all input objects.
1386// This is then used either when creating the output linking section or to
1387// synthesize the "__wasm_call_ctors" function.
1388void Writer::calculateInitFunctions() {
Sam Clegg61f13b32019-03-02 04:55:02 +00001389 if (!Config->Relocatable && !WasmSym::CallCtors->isLive())
1390 return;
1391
Sam Clegg50686852018-01-12 18:35:13 +00001392 for (ObjFile *File : Symtab->ObjectFiles) {
1393 const WasmLinkingData &L = File->getWasmObj()->linkingData();
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +00001394 for (const WasmInitFunc &F : L.InitFunctions) {
1395 FunctionSymbol *Sym = File->getFunctionSymbol(F.Symbol);
Sam Clegg0e6b42f2019-03-01 22:35:47 +00001396 assert(Sym->isLive());
Heejin Ahne915a712018-12-08 06:17:43 +00001397 if (*Sym->Signature != WasmSignature{{}, {}})
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +00001398 error("invalid signature for init func: " + toString(*Sym));
1399 InitFunctions.emplace_back(WasmInitEntry{Sym, F.Priority});
1400 }
Sam Clegg50686852018-01-12 18:35:13 +00001401 }
Rui Ueyamada69b712018-02-28 00:15:59 +00001402
Sam Clegg50686852018-01-12 18:35:13 +00001403 // Sort in order of priority (lowest first) so that they are called
1404 // in the correct order.
Fangrui Song32c0ebe2019-04-23 02:42:06 +00001405 llvm::stable_sort(InitFunctions,
1406 [](const WasmInitEntry &L, const WasmInitEntry &R) {
1407 return L.Priority < R.Priority;
1408 });
Sam Clegg50686852018-01-12 18:35:13 +00001409}
1410
Sam Cleggc94d3932017-11-17 18:14:09 +00001411void Writer::run() {
Sam Cleggbfb75342018-11-15 00:37:21 +00001412 if (Config->Relocatable || Config->Pic)
Sam Clegg99eb42c2018-02-27 23:58:03 +00001413 Config->GlobalBase = 0;
1414
Sam Cleggbfb75342018-11-15 00:37:21 +00001415 // For PIC code the table base is assigned dynamically by the loader.
1416 // For non-PIC, we start at 1 so that accessing table index 0 always traps.
1417 if (!Config->Pic)
1418 TableBase = 1;
1419
Thomas Livelyf6f4f842019-03-20 20:26:45 +00001420 log("-- calculateTargetFeatures");
1421 calculateTargetFeatures();
Sam Cleggc94d3932017-11-17 18:14:09 +00001422 log("-- calculateImports");
1423 calculateImports();
Sam Clegg8d146bb2018-01-09 23:56:44 +00001424 log("-- assignIndexes");
1425 assignIndexes();
Sam Clegg50686852018-01-12 18:35:13 +00001426 log("-- calculateInitFunctions");
1427 calculateInitFunctions();
Sam Clegg8f6d2de2018-01-31 23:48:14 +00001428 log("-- calculateTypes");
1429 calculateTypes();
Sam Clegg93102972018-02-23 05:08:53 +00001430 log("-- layoutMemory");
1431 layoutMemory();
Sam Clegg09137be2019-04-04 18:40:51 +00001432 if (!Config->Relocatable) {
1433 if (Config->Pic)
1434 createApplyRelocationsFunction();
1435 createCallCtorsFunction();
1436 }
Sam Clegg93102972018-02-23 05:08:53 +00001437 log("-- calculateExports");
1438 calculateExports();
Sam Cleggd177ab22018-05-04 23:14:42 +00001439 log("-- calculateCustomSections");
1440 calculateCustomSections();
Sam Clegg93102972018-02-23 05:08:53 +00001441 log("-- assignSymtab");
1442 assignSymtab();
Sam Cleggc94d3932017-11-17 18:14:09 +00001443
1444 if (errorHandler().Verbose) {
Sam Clegg9f934222018-02-21 18:29:23 +00001445 log("Defined Functions: " + Twine(InputFunctions.size()));
Sam Clegg93102972018-02-23 05:08:53 +00001446 log("Defined Globals : " + Twine(InputGlobals.size()));
Heejin Ahne915a712018-12-08 06:17:43 +00001447 log("Defined Events : " + Twine(InputEvents.size()));
Sam Clegg93102972018-02-23 05:08:53 +00001448 log("Function Imports : " + Twine(NumImportedFunctions));
1449 log("Global Imports : " + Twine(NumImportedGlobals));
Heejin Ahne915a712018-12-08 06:17:43 +00001450 log("Event Imports : " + Twine(NumImportedEvents));
Sam Cleggc94d3932017-11-17 18:14:09 +00001451 for (ObjFile *File : Symtab->ObjectFiles)
1452 File->dumpInfo();
1453 }
1454
Sam Cleggc94d3932017-11-17 18:14:09 +00001455 createHeader();
1456 log("-- createSections");
1457 createSections();
1458
1459 log("-- openFile");
1460 openFile();
1461 if (errorCount())
1462 return;
1463
1464 writeHeader();
1465
1466 log("-- writeSections");
1467 writeSections();
1468 if (errorCount())
1469 return;
1470
1471 if (Error E = Buffer->commit())
1472 fatal("failed to write the output file: " + toString(std::move(E)));
1473}
1474
1475// Open a result file.
1476void Writer::openFile() {
1477 log("writing: " + Config->OutputFile);
Sam Cleggc94d3932017-11-17 18:14:09 +00001478
1479 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
1480 FileOutputBuffer::create(Config->OutputFile, FileSize,
1481 FileOutputBuffer::F_executable);
1482
1483 if (!BufferOrErr)
1484 error("failed to open " + Config->OutputFile + ": " +
1485 toString(BufferOrErr.takeError()));
1486 else
1487 Buffer = std::move(*BufferOrErr);
1488}
1489
1490void Writer::createHeader() {
1491 raw_string_ostream OS(Header);
1492 writeBytes(OS, WasmMagic, sizeof(WasmMagic), "wasm magic");
1493 writeU32(OS, WasmVersion, "wasm version");
1494 OS.flush();
1495 FileSize += Header.size();
1496}
1497
1498void lld::wasm::writeResult() { Writer().run(); }