blob: 8460f8575c8a2c5f7a8f9652d62a11a8a15f9e25 [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
Rui Ueyama37254062018-02-28 00:01:31 +0000472 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, Name);
Sam Cleggc94d3932017-11-17 18:14:09 +0000473 raw_ostream &OS = Section->getStream();
Rui Ueyamaffa650a2018-04-24 23:09:57 +0000474 writeUleb128(OS, I, "reloc section");
Sam Cleggc94d3932017-11-17 18:14:09 +0000475 writeUleb128(OS, Count, "reloc count");
Rui Ueyama37254062018-02-28 00:01:31 +0000476 OSec->writeRelocations(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000477 }
478}
479
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000480static uint32_t getWasmFlags(const Symbol *Sym) {
481 uint32_t Flags = 0;
482 if (Sym->isLocal())
483 Flags |= WASM_SYMBOL_BINDING_LOCAL;
484 if (Sym->isWeak())
485 Flags |= WASM_SYMBOL_BINDING_WEAK;
486 if (Sym->isHidden())
487 Flags |= WASM_SYMBOL_VISIBILITY_HIDDEN;
488 if (Sym->isUndefined())
489 Flags |= WASM_SYMBOL_UNDEFINED;
Dan Gohman9b84eea2019-02-07 22:00:48 +0000490 if (auto *F = dyn_cast<UndefinedFunction>(Sym)) {
491 if (F->getName() != F->ImportName)
492 Flags |= WASM_SYMBOL_EXPLICIT_NAME;
493 } else if (auto *G = dyn_cast<UndefinedGlobal>(Sym)) {
494 if (G->getName() != G->ImportName)
495 Flags |= WASM_SYMBOL_EXPLICIT_NAME;
496 }
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000497 return Flags;
498}
499
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000500// Some synthetic sections (e.g. "name" and "linking") have subsections.
501// Just like the synthetic sections themselves these need to be created before
502// they can be written out (since they are preceded by their length). This
503// class is used to create subsections and then write them into the stream
504// of the parent section.
505class SubSection {
506public:
507 explicit SubSection(uint32_t Type) : Type(Type) {}
508
509 void writeTo(raw_ostream &To) {
510 OS.flush();
Rui Ueyama67769102018-02-28 03:38:14 +0000511 writeUleb128(To, Type, "subsection type");
512 writeUleb128(To, Body.size(), "subsection size");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000513 To.write(Body.data(), Body.size());
514 }
515
516private:
517 uint32_t Type;
518 std::string Body;
519
520public:
521 raw_string_ostream OS{Body};
522};
523
Sam Cleggbfb75342018-11-15 00:37:21 +0000524// Create the custom "dylink" section containing information for the dynamic
525// linker.
526// See
527// https://github.com/WebAssembly/tool-conventions/blob/master/DynamicLinking.md
528void Writer::createDylinkSection() {
529 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "dylink");
530 raw_ostream &OS = Section->getStream();
531
532 writeUleb128(OS, MemSize, "MemSize");
Sam Clegg6320efb2019-01-16 01:43:21 +0000533 writeUleb128(OS, MemAlign, "MemAlign");
Sam Cleggbfb75342018-11-15 00:37:21 +0000534 writeUleb128(OS, IndirectFunctions.size(), "TableSize");
535 writeUleb128(OS, 0, "TableAlign");
Sam Clegga688a422019-03-13 21:29:20 +0000536 writeUleb128(OS, Symtab->SharedFiles.size(), "Needed");
537 for (auto *SO : Symtab->SharedFiles)
538 writeStr(OS, llvm::sys::path::filename(SO->getName()), "so name");
Sam Cleggbfb75342018-11-15 00:37:21 +0000539}
540
Sam Clegg49ed9262017-12-01 00:53:21 +0000541// Create the custom "linking" section containing linker metadata.
Sam Cleggc94d3932017-11-17 18:14:09 +0000542// This is only created when relocatable output is requested.
543void Writer::createLinkingSection() {
544 SyntheticSection *Section =
545 createSyntheticSection(WASM_SEC_CUSTOM, "linking");
546 raw_ostream &OS = Section->getStream();
547
Sam Clegg2b8b1792018-04-26 18:17:21 +0000548 writeUleb128(OS, WasmMetadataVersion, "Version");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000549
Sam Clegg93102972018-02-23 05:08:53 +0000550 if (!SymtabEntries.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000551 SubSection Sub(WASM_SYMBOL_TABLE);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000552 writeUleb128(Sub.OS, SymtabEntries.size(), "num symbols");
553
Sam Clegg93102972018-02-23 05:08:53 +0000554 for (const Symbol *Sym : SymtabEntries) {
555 assert(Sym->isDefined() || Sym->isUndefined());
556 WasmSymbolType Kind = Sym->getWasmType();
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000557 uint32_t Flags = getWasmFlags(Sym);
558
Sam Clegg8518e7d2018-03-01 18:06:39 +0000559 writeU8(Sub.OS, Kind, "sym kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000560 writeUleb128(Sub.OS, Flags, "sym flags");
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000561
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000562 if (auto *F = dyn_cast<FunctionSymbol>(Sym)) {
563 writeUleb128(Sub.OS, F->getFunctionIndex(), "index");
Dan Gohman9b84eea2019-02-07 22:00:48 +0000564 if (Sym->isDefined() ||
565 (Flags & WASM_SYMBOL_EXPLICIT_NAME) != 0)
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000566 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000567 } else if (auto *G = dyn_cast<GlobalSymbol>(Sym)) {
568 writeUleb128(Sub.OS, G->getGlobalIndex(), "index");
Dan Gohman9b84eea2019-02-07 22:00:48 +0000569 if (Sym->isDefined() ||
570 (Flags & WASM_SYMBOL_EXPLICIT_NAME) != 0)
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000571 writeStr(Sub.OS, Sym->getName(), "sym name");
Heejin Ahne915a712018-12-08 06:17:43 +0000572 } else if (auto *E = dyn_cast<EventSymbol>(Sym)) {
573 writeUleb128(Sub.OS, E->getEventIndex(), "index");
Dan Gohman9b84eea2019-02-07 22:00:48 +0000574 if (Sym->isDefined() ||
575 (Flags & WASM_SYMBOL_EXPLICIT_NAME) != 0)
Heejin Ahne915a712018-12-08 06:17:43 +0000576 writeStr(Sub.OS, Sym->getName(), "sym name");
Andrea Di Biagio25c1a2f2018-05-05 10:53:31 +0000577 } else if (isa<DataSymbol>(Sym)) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000578 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegg93102972018-02-23 05:08:53 +0000579 if (auto *DataSym = dyn_cast<DefinedData>(Sym)) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000580 writeUleb128(Sub.OS, DataSym->getOutputSegmentIndex(), "index");
581 writeUleb128(Sub.OS, DataSym->getOutputSegmentOffset(),
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000582 "data offset");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000583 writeUleb128(Sub.OS, DataSym->getSize(), "data size");
Sam Clegg93102972018-02-23 05:08:53 +0000584 }
Sam Cleggd177ab22018-05-04 23:14:42 +0000585 } else {
586 auto *S = cast<SectionSymbol>(Sym);
587 writeUleb128(Sub.OS, S->getOutputSectionIndex(), "sym section index");
Sam Clegg93102972018-02-23 05:08:53 +0000588 }
Sam Cleggd3052d52018-01-18 23:40:49 +0000589 }
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000590
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000591 Sub.writeTo(OS);
Sam Cleggd3052d52018-01-18 23:40:49 +0000592 }
593
Sam Clegg0d0dd392017-12-19 17:09:45 +0000594 if (Segments.size()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000595 SubSection Sub(WASM_SEGMENT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000596 writeUleb128(Sub.OS, Segments.size(), "num data segments");
Sam Cleggc94d3932017-11-17 18:14:09 +0000597 for (const OutputSegment *S : Segments) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000598 writeStr(Sub.OS, S->Name, "segment name");
599 writeUleb128(Sub.OS, S->Alignment, "alignment");
600 writeUleb128(Sub.OS, 0, "flags");
Sam Cleggc94d3932017-11-17 18:14:09 +0000601 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000602 Sub.writeTo(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000603 }
Sam Clegg0d0dd392017-12-19 17:09:45 +0000604
Sam Clegg0d0dd392017-12-19 17:09:45 +0000605 if (!InitFunctions.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000606 SubSection Sub(WASM_INIT_FUNCS);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000607 writeUleb128(Sub.OS, InitFunctions.size(), "num init functions");
Sam Clegg93102972018-02-23 05:08:53 +0000608 for (const WasmInitEntry &F : InitFunctions) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000609 writeUleb128(Sub.OS, F.Priority, "priority");
610 writeUleb128(Sub.OS, F.Sym->getOutputSymbolIndex(), "function index");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000611 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000612 Sub.writeTo(OS);
Sam Clegg0d0dd392017-12-19 17:09:45 +0000613 }
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000614
Nicholas Wilsondbd90bf2018-03-07 13:28:16 +0000615 struct ComdatEntry {
616 unsigned Kind;
617 uint32_t Index;
618 };
619 std::map<StringRef, std::vector<ComdatEntry>> Comdats;
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000620
Sam Clegg9f934222018-02-21 18:29:23 +0000621 for (const InputFunction *F : InputFunctions) {
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000622 StringRef Comdat = F->getComdatName();
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000623 if (!Comdat.empty())
624 Comdats[Comdat].emplace_back(
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000625 ComdatEntry{WASM_COMDAT_FUNCTION, F->getFunctionIndex()});
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000626 }
627 for (uint32_t I = 0; I < Segments.size(); ++I) {
Sam Cleggf98bccf2018-01-13 15:57:48 +0000628 const auto &InputSegments = Segments[I]->InputSegments;
629 if (InputSegments.empty())
630 continue;
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000631 StringRef Comdat = InputSegments[0]->getComdatName();
Sam Clegga697df522018-01-13 15:59:53 +0000632#ifndef NDEBUG
Sam Cleggf98bccf2018-01-13 15:57:48 +0000633 for (const InputSegment *IS : InputSegments)
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000634 assert(IS->getComdatName() == Comdat);
Sam Clegga697df522018-01-13 15:59:53 +0000635#endif
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000636 if (!Comdat.empty())
637 Comdats[Comdat].emplace_back(ComdatEntry{WASM_COMDAT_DATA, I});
638 }
639
640 if (!Comdats.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000641 SubSection Sub(WASM_COMDAT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000642 writeUleb128(Sub.OS, Comdats.size(), "num comdats");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000643 for (const auto &C : Comdats) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000644 writeStr(Sub.OS, C.first, "comdat name");
645 writeUleb128(Sub.OS, 0, "comdat flags"); // flags for future use
646 writeUleb128(Sub.OS, C.second.size(), "num entries");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000647 for (const ComdatEntry &Entry : C.second) {
Sam Clegg8518e7d2018-03-01 18:06:39 +0000648 writeU8(Sub.OS, Entry.Kind, "entry kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000649 writeUleb128(Sub.OS, Entry.Index, "entry index");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000650 }
651 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000652 Sub.writeTo(OS);
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000653 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000654}
655
656// Create the custom "name" section containing debug symbol names.
657void Writer::createNameSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000658 unsigned NumNames = NumImportedFunctions;
Sam Clegg9f934222018-02-21 18:29:23 +0000659 for (const InputFunction *F : InputFunctions)
Nicholas Wilson6c7fe302018-04-20 17:09:18 +0000660 if (!F->getName().empty() || !F->getDebugName().empty())
Sam Clegg1963d712018-01-17 20:19:04 +0000661 ++NumNames;
Sam Cleggc94d3932017-11-17 18:14:09 +0000662
Sam Clegg1963d712018-01-17 20:19:04 +0000663 if (NumNames == 0)
664 return;
Sam Clegg50686852018-01-12 18:35:13 +0000665
Sam Cleggc94d3932017-11-17 18:14:09 +0000666 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "name");
667
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000668 SubSection Sub(WASM_NAMES_FUNCTION);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000669 writeUleb128(Sub.OS, NumNames, "name count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000670
Sam Clegg93102972018-02-23 05:08:53 +0000671 // Names must appear in function index order. As it happens ImportedSymbols
672 // and InputFunctions are numbered in order with imported functions coming
Sam Clegg1963d712018-01-17 20:19:04 +0000673 // first.
Sam Clegg93102972018-02-23 05:08:53 +0000674 for (const Symbol *S : ImportedSymbols) {
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000675 if (auto *F = dyn_cast<FunctionSymbol>(S)) {
676 writeUleb128(Sub.OS, F->getFunctionIndex(), "func index");
Sam Clegg37125f02018-11-09 16:57:41 +0000677 writeStr(Sub.OS, toString(*S), "symbol name");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000678 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000679 }
Sam Clegg9f934222018-02-21 18:29:23 +0000680 for (const InputFunction *F : InputFunctions) {
Sam Clegg1963d712018-01-17 20:19:04 +0000681 if (!F->getName().empty()) {
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000682 writeUleb128(Sub.OS, F->getFunctionIndex(), "func index");
Nicholas Wilson6c7fe302018-04-20 17:09:18 +0000683 if (!F->getDebugName().empty()) {
684 writeStr(Sub.OS, F->getDebugName(), "symbol name");
685 } else {
Sam Clegg37125f02018-11-09 16:57:41 +0000686 writeStr(Sub.OS, maybeDemangleSymbol(F->getName()), "symbol name");
Nicholas Wilson6c7fe302018-04-20 17:09:18 +0000687 }
Sam Clegg1963d712018-01-17 20:19:04 +0000688 }
689 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000690
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000691 Sub.writeTo(Section->getStream());
Sam Cleggc94d3932017-11-17 18:14:09 +0000692}
693
Thomas Lively2a0868f2019-01-17 02:29:41 +0000694void Writer::createProducersSection() {
695 SmallVector<std::pair<std::string, std::string>, 8> Languages;
696 SmallVector<std::pair<std::string, std::string>, 8> Tools;
697 SmallVector<std::pair<std::string, std::string>, 8> SDKs;
698 for (ObjFile *File : Symtab->ObjectFiles) {
699 const WasmProducerInfo &Info = File->getWasmObj()->getProducerInfo();
700 for (auto &Producers : {std::make_pair(&Info.Languages, &Languages),
701 std::make_pair(&Info.Tools, &Tools),
702 std::make_pair(&Info.SDKs, &SDKs)})
703 for (auto &Producer : *Producers.first)
704 if (Producers.second->end() ==
Fangrui Song8048fe22019-03-29 16:21:16 +0000705 llvm::find_if(*Producers.second,
706 [&](std::pair<std::string, std::string> Seen) {
707 return Seen.first == Producer.first;
708 }))
Thomas Lively2a0868f2019-01-17 02:29:41 +0000709 Producers.second->push_back(Producer);
710 }
711 int FieldCount =
712 int(!Languages.empty()) + int(!Tools.empty()) + int(!SDKs.empty());
713 if (FieldCount == 0)
714 return;
715 SyntheticSection *Section =
716 createSyntheticSection(WASM_SEC_CUSTOM, "producers");
717 auto &OS = Section->getStream();
718 writeUleb128(OS, FieldCount, "field count");
719 for (auto &Field :
720 {std::make_pair("language", Languages),
721 std::make_pair("processed-by", Tools), std::make_pair("sdk", SDKs)}) {
722 if (Field.second.empty())
723 continue;
724 writeStr(OS, Field.first, "field name");
725 writeUleb128(OS, Field.second.size(), "number of entries");
726 for (auto &Entry : Field.second) {
727 writeStr(OS, Entry.first, "producer name");
728 writeStr(OS, Entry.second, "producer version");
729 }
730 }
731}
732
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000733void Writer::createTargetFeaturesSection() {
Fangrui Song196a4402019-04-18 13:33:29 +0000734 if (TargetFeatures.empty())
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000735 return;
736
737 SmallVector<std::string, 8> Emitted(TargetFeatures.begin(),
738 TargetFeatures.end());
Fangrui Song196a4402019-04-18 13:33:29 +0000739 llvm::sort(Emitted);
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000740 SyntheticSection *Section =
741 createSyntheticSection(WASM_SEC_CUSTOM, "target_features");
742 auto &OS = Section->getStream();
743 writeUleb128(OS, Emitted.size(), "feature count");
744 for (auto &Feature : Emitted) {
745 writeU8(OS, WASM_FEATURE_PREFIX_USED, "feature used prefix");
746 writeStr(OS, Feature, "feature name");
747 }
748}
749
Sam Cleggc94d3932017-11-17 18:14:09 +0000750void Writer::writeHeader() {
751 memcpy(Buffer->getBufferStart(), Header.data(), Header.size());
752}
753
754void Writer::writeSections() {
755 uint8_t *Buf = Buffer->getBufferStart();
756 parallelForEach(OutputSections, [Buf](OutputSection *S) { S->writeTo(Buf); });
757}
758
759// Fix the memory layout of the output binary. This assigns memory offsets
Sam Clegg49ed9262017-12-01 00:53:21 +0000760// to each of the input data sections as well as the explicit stack region.
Sam Clegga0f095e2018-05-03 17:21:53 +0000761// The default memory layout is as follows, from low to high.
762//
Sam Cleggf0d433d2018-02-02 22:59:56 +0000763// - initialized data (starting at Config->GlobalBase)
764// - BSS data (not currently implemented in llvm)
765// - explicit stack (Config->ZStackSize)
766// - heap start / unallocated
Sam Clegga0f095e2018-05-03 17:21:53 +0000767//
768// The --stack-first option means that stack is placed before any static data.
Heejin Ahn4821ebf2018-08-29 21:03:16 +0000769// This can be useful since it means that stack overflow traps immediately
770// rather than overwriting global data, but also increases code size since all
771// static data loads and stores requires larger offsets.
Sam Cleggc94d3932017-11-17 18:14:09 +0000772void Writer::layoutMemory() {
Sam Cleggc94d3932017-11-17 18:14:09 +0000773 createOutputSegments();
774
Sam Clegga0f095e2018-05-03 17:21:53 +0000775 uint32_t MemoryPtr = 0;
776
777 auto PlaceStack = [&]() {
Sam Cleggbfb75342018-11-15 00:37:21 +0000778 if (Config->Relocatable || Config->Shared)
Sam Clegga0f095e2018-05-03 17:21:53 +0000779 return;
Heejin Ahna1cc4ea2019-02-04 19:13:46 +0000780 MemoryPtr = alignTo(MemoryPtr, StackAlignment);
781 if (Config->ZStackSize != alignTo(Config->ZStackSize, StackAlignment))
782 error("stack size must be " + Twine(StackAlignment) + "-byte aligned");
Sam Clegga0f095e2018-05-03 17:21:53 +0000783 log("mem: stack size = " + Twine(Config->ZStackSize));
784 log("mem: stack base = " + Twine(MemoryPtr));
785 MemoryPtr += Config->ZStackSize;
Sam Clegg2dad4e22018-11-15 18:15:54 +0000786 auto *SP = cast<DefinedGlobal>(WasmSym::StackPointer);
787 SP->Global->Global.InitExpr.Value.Int32 = MemoryPtr;
Sam Clegga0f095e2018-05-03 17:21:53 +0000788 log("mem: stack top = " + Twine(MemoryPtr));
789 };
790
791 if (Config->StackFirst) {
792 PlaceStack();
793 } else {
794 MemoryPtr = Config->GlobalBase;
795 log("mem: global base = " + Twine(Config->GlobalBase));
796 }
797
798 uint32_t DataStart = MemoryPtr;
799
Sam Cleggf0d433d2018-02-02 22:59:56 +0000800 // Arbitrarily set __dso_handle handle to point to the start of the data
801 // segments.
802 if (WasmSym::DsoHandle)
Sam Clegga0f095e2018-05-03 17:21:53 +0000803 WasmSym::DsoHandle->setVirtualAddress(DataStart);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000804
Sam Cleggbfb75342018-11-15 00:37:21 +0000805 MemAlign = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000806 for (OutputSegment *Seg : Segments) {
Sam Cleggbfb75342018-11-15 00:37:21 +0000807 MemAlign = std::max(MemAlign, Seg->Alignment);
Sam Clegg622ad042019-01-17 22:09:09 +0000808 MemoryPtr = alignTo(MemoryPtr, 1ULL << Seg->Alignment);
Sam Cleggc94d3932017-11-17 18:14:09 +0000809 Seg->StartVA = MemoryPtr;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000810 log(formatv("mem: {0,-15} offset={1,-8} size={2,-8} align={3}", Seg->Name,
811 MemoryPtr, Seg->Size, Seg->Alignment));
Sam Cleggc94d3932017-11-17 18:14:09 +0000812 MemoryPtr += Seg->Size;
813 }
814
Sam Cleggf0d433d2018-02-02 22:59:56 +0000815 // TODO: Add .bss space here.
Sam Clegg37a4a8a2018-02-07 03:04:53 +0000816 if (WasmSym::DataEnd)
817 WasmSym::DataEnd->setVirtualAddress(MemoryPtr);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000818
Sam Clegga0f095e2018-05-03 17:21:53 +0000819 log("mem: static data = " + Twine(MemoryPtr - DataStart));
Sam Cleggc94d3932017-11-17 18:14:09 +0000820
Sam Clegg2dad4e22018-11-15 18:15:54 +0000821 if (Config->Shared) {
822 MemSize = MemoryPtr;
823 return;
824 }
825
Sam Clegga0f095e2018-05-03 17:21:53 +0000826 if (!Config->StackFirst)
827 PlaceStack();
828
829 // Set `__heap_base` to directly follow the end of the stack or global data.
830 // The fact that this comes last means that a malloc/brk implementation
831 // can grow the heap at runtime.
Sam Cleggc94d3932017-11-17 18:14:09 +0000832 if (!Config->Relocatable) {
Sam Cleggf0d433d2018-02-02 22:59:56 +0000833 WasmSym::HeapBase->setVirtualAddress(MemoryPtr);
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000834 log("mem: heap base = " + Twine(MemoryPtr));
Sam Cleggc94d3932017-11-17 18:14:09 +0000835 }
836
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000837 if (Config->InitialMemory != 0) {
838 if (Config->InitialMemory != alignTo(Config->InitialMemory, WasmPageSize))
839 error("initial memory must be " + Twine(WasmPageSize) + "-byte aligned");
840 if (MemoryPtr > Config->InitialMemory)
841 error("initial memory too small, " + Twine(MemoryPtr) + " bytes needed");
842 else
843 MemoryPtr = Config->InitialMemory;
844 }
Sam Cleggbfb75342018-11-15 00:37:21 +0000845 MemSize = MemoryPtr;
846 NumMemoryPages = alignTo(MemoryPtr, WasmPageSize) / WasmPageSize;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000847 log("mem: total pages = " + Twine(NumMemoryPages));
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000848
Thomas Lively06391f32019-03-29 20:43:49 +0000849 // Check max if explicitly supplied or required by shared memory
850 if (Config->MaxMemory != 0 || Config->SharedMemory) {
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000851 if (Config->MaxMemory != alignTo(Config->MaxMemory, WasmPageSize))
852 error("maximum memory must be " + Twine(WasmPageSize) + "-byte aligned");
853 if (MemoryPtr > Config->MaxMemory)
854 error("maximum memory too small, " + Twine(MemoryPtr) + " bytes needed");
855 MaxMemoryPages = Config->MaxMemory / WasmPageSize;
856 log("mem: max pages = " + Twine(MaxMemoryPages));
857 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000858}
859
860SyntheticSection *Writer::createSyntheticSection(uint32_t Type,
Sam Cleggc375e4e2018-01-10 19:18:22 +0000861 StringRef Name) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000862 auto Sec = make<SyntheticSection>(Type, Name);
Sam Cleggab2ac292017-12-20 05:14:48 +0000863 log("createSection: " + toString(*Sec));
Sam Cleggc94d3932017-11-17 18:14:09 +0000864 OutputSections.push_back(Sec);
865 return Sec;
866}
867
868void Writer::createSections() {
869 // Known sections
Sam Cleggbfb75342018-11-15 00:37:21 +0000870 if (Config->Pic)
871 createDylinkSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000872 createTypeSection();
873 createImportSection();
874 createFunctionSection();
875 createTableSection();
876 createMemorySection();
877 createGlobalSection();
Heejin Ahne915a712018-12-08 06:17:43 +0000878 createEventSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000879 createExportSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000880 createElemSection();
Thomas Lively84771e22019-04-19 23:40:36 +0000881 createDataCountSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000882 createCodeSection();
883 createDataSection();
Sam Clegg80ba4382018-04-10 16:12:49 +0000884 createCustomSections();
Sam Cleggc94d3932017-11-17 18:14:09 +0000885
886 // Custom sections
Sam Clegg99eb42c2018-02-27 23:58:03 +0000887 if (Config->Relocatable) {
Sam Clegg99eb42c2018-02-27 23:58:03 +0000888 createLinkingSection();
Nicholas Wilson94d3b162018-03-05 12:33:58 +0000889 createRelocSections();
Sam Clegg99eb42c2018-02-27 23:58:03 +0000890 }
Thomas Lively2a0868f2019-01-17 02:29:41 +0000891
Sam Cleggc94d3932017-11-17 18:14:09 +0000892 if (!Config->StripDebug && !Config->StripAll)
893 createNameSection();
894
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000895 if (!Config->StripAll) {
Thomas Lively2a0868f2019-01-17 02:29:41 +0000896 createProducersSection();
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000897 createTargetFeaturesSection();
898 }
Thomas Lively2a0868f2019-01-17 02:29:41 +0000899
Sam Cleggc94d3932017-11-17 18:14:09 +0000900 for (OutputSection *S : OutputSections) {
901 S->setOffset(FileSize);
902 S->finalizeContents();
903 FileSize += S->getSize();
904 }
905}
906
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000907void Writer::calculateTargetFeatures() {
Thomas Lively82de51a2019-03-26 04:11:05 +0000908 SmallSet<std::string, 8> Used;
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000909 SmallSet<std::string, 8> Required;
910 SmallSet<std::string, 8> Disallowed;
911
Thomas Lively82de51a2019-03-26 04:11:05 +0000912 // Only infer used features if user did not specify features
913 bool InferFeatures = !Config->Features.hasValue();
914
915 if (!InferFeatures) {
916 for (auto &Feature : Config->Features.getValue())
917 TargetFeatures.insert(Feature);
918 // No need to read or check features
919 if (!Config->CheckFeatures)
920 return;
921 }
922
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000923 // Find the sets of used, required, and disallowed features
924 for (ObjFile *File : Symtab->ObjectFiles) {
925 for (auto &Feature : File->getWasmObj()->getTargetFeatures()) {
926 switch (Feature.Prefix) {
927 case WASM_FEATURE_PREFIX_USED:
Thomas Lively82de51a2019-03-26 04:11:05 +0000928 Used.insert(Feature.Name);
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000929 break;
930 case WASM_FEATURE_PREFIX_REQUIRED:
Thomas Lively82de51a2019-03-26 04:11:05 +0000931 Used.insert(Feature.Name);
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000932 Required.insert(Feature.Name);
933 break;
934 case WASM_FEATURE_PREFIX_DISALLOWED:
935 Disallowed.insert(Feature.Name);
936 break;
937 default:
938 error("Unrecognized feature policy prefix " +
939 std::to_string(Feature.Prefix));
940 }
941 }
942 }
943
Thomas Lively82de51a2019-03-26 04:11:05 +0000944 if (InferFeatures)
945 TargetFeatures.insert(Used.begin(), Used.end());
946
Thomas Lively06391f32019-03-29 20:43:49 +0000947 if (TargetFeatures.count("atomics") && !Config->SharedMemory)
948 error("'atomics' feature is used, so --shared-memory must be used");
949
Thomas Lively82de51a2019-03-26 04:11:05 +0000950 if (!Config->CheckFeatures)
951 return;
952
Thomas Lively06391f32019-03-29 20:43:49 +0000953 if (Disallowed.count("atomics") && Config->SharedMemory)
954 error(
955 "'atomics' feature is disallowed, so --shared-memory must not be used");
956
Thomas Lively82de51a2019-03-26 04:11:05 +0000957 // Validate that used features are allowed in output
958 if (!InferFeatures) {
959 for (auto &Feature : Used) {
960 if (!TargetFeatures.count(Feature))
961 error(Twine("Target feature '") + Feature + "' is not allowed.");
962 }
963 }
964
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000965 // Validate the required and disallowed constraints for each file
966 for (ObjFile *File : Symtab->ObjectFiles) {
967 SmallSet<std::string, 8> ObjectFeatures;
968 for (auto &Feature : File->getWasmObj()->getTargetFeatures()) {
969 if (Feature.Prefix == WASM_FEATURE_PREFIX_DISALLOWED)
970 continue;
971 ObjectFeatures.insert(Feature.Name);
972 if (Disallowed.count(Feature.Name))
Thomas Lively82de51a2019-03-26 04:11:05 +0000973 error(Twine("Target feature '") + Feature.Name +
974 "' is disallowed. Use --no-check-features to suppress.");
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000975 }
976 for (auto &Feature : Required) {
977 if (!ObjectFeatures.count(Feature))
Thomas Lively82de51a2019-03-26 04:11:05 +0000978 error(Twine("Missing required target feature '") + Feature +
979 "'. Use --no-check-features to suppress.");
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000980 }
981 }
982}
983
Sam Cleggc94d3932017-11-17 18:14:09 +0000984void Writer::calculateImports() {
Sam Clegg574d7ce2017-12-15 19:23:49 +0000985 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000986 if (!Sym->isUndefined())
987 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000988 if (Sym->isWeak() && !Config->Relocatable)
Sam Clegg574d7ce2017-12-15 19:23:49 +0000989 continue;
Nicholas Wilsona1e299f2018-04-20 17:18:06 +0000990 if (!Sym->isLive())
991 continue;
Sam Cleggc729c1b2018-05-30 18:07:52 +0000992 if (!Sym->IsUsedInRegularObj)
993 continue;
Sam Clegg492f7522019-03-26 19:46:15 +0000994 // We don't generate imports for data symbols. They however can be imported
995 // as GOT entries.
996 if (isa<DataSymbol>(Sym))
Sam Cleggd425d6b2019-03-12 21:53:23 +0000997 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000998
Nicola Zaghene7245b42018-05-15 13:36:20 +0000999 LLVM_DEBUG(dbgs() << "import: " << Sym->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +00001000 ImportedSymbols.emplace_back(Sym);
Sam Clegge3f3ccf2018-03-12 19:56:23 +00001001 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
1002 F->setFunctionIndex(NumImportedFunctions++);
Heejin Ahne915a712018-12-08 06:17:43 +00001003 else if (auto *G = dyn_cast<GlobalSymbol>(Sym))
1004 G->setGlobalIndex(NumImportedGlobals++);
Sam Clegg93102972018-02-23 05:08:53 +00001005 else
Heejin Ahne915a712018-12-08 06:17:43 +00001006 cast<EventSymbol>(Sym)->setEventIndex(NumImportedEvents++);
Sam Cleggc94d3932017-11-17 18:14:09 +00001007 }
1008}
1009
Sam Cleggd3052d52018-01-18 23:40:49 +00001010void Writer::calculateExports() {
Sam Clegg93102972018-02-23 05:08:53 +00001011 if (Config->Relocatable)
1012 return;
Sam Cleggf0d433d2018-02-02 22:59:56 +00001013
Sam Cleggd6beb322018-05-10 18:10:34 +00001014 if (!Config->Relocatable && !Config->ImportMemory)
1015 Exports.push_back(WasmExport{"memory", WASM_EXTERNAL_MEMORY, 0});
1016
1017 if (!Config->Relocatable && Config->ExportTable)
Heejin Ahna1cc4ea2019-02-04 19:13:46 +00001018 Exports.push_back(WasmExport{FunctionTableName, WASM_EXTERNAL_TABLE, 0});
Sam Cleggd6beb322018-05-10 18:10:34 +00001019
1020 unsigned FakeGlobalIndex = NumImportedGlobals + InputGlobals.size();
1021
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +00001022 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Cleggce004bf2018-06-28 17:04:58 +00001023 if (!Sym->isExported())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +00001024 continue;
Sam Clegg93102972018-02-23 05:08:53 +00001025 if (!Sym->isLive())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +00001026 continue;
Sam Clegg93102972018-02-23 05:08:53 +00001027
Sam Cleggd6beb322018-05-10 18:10:34 +00001028 StringRef Name = Sym->getName();
1029 WasmExport Export;
1030 if (auto *F = dyn_cast<DefinedFunction>(Sym)) {
1031 Export = {Name, WASM_EXTERNAL_FUNCTION, F->getFunctionIndex()};
1032 } else if (auto *G = dyn_cast<DefinedGlobal>(Sym)) {
Sam Clegg177b4582018-06-07 01:27:07 +00001033 // TODO(sbc): Remove this check once to mutable global proposal is
1034 // implement in all major browsers.
1035 // See: https://github.com/WebAssembly/mutable-global
1036 if (G->getGlobalType()->Mutable) {
1037 // Only the __stack_pointer should ever be create as mutable.
1038 assert(G == WasmSym::StackPointer);
1039 continue;
1040 }
Sam Cleggd6beb322018-05-10 18:10:34 +00001041 Export = {Name, WASM_EXTERNAL_GLOBAL, G->getGlobalIndex()};
Heejin Ahne915a712018-12-08 06:17:43 +00001042 } else if (auto *E = dyn_cast<DefinedEvent>(Sym)) {
1043 Export = {Name, WASM_EXTERNAL_EVENT, E->getEventIndex()};
Sam Cleggd6beb322018-05-10 18:10:34 +00001044 } else {
1045 auto *D = cast<DefinedData>(Sym);
Sam Clegg93102972018-02-23 05:08:53 +00001046 DefinedFakeGlobals.emplace_back(D);
Sam Cleggd6beb322018-05-10 18:10:34 +00001047 Export = {Name, WASM_EXTERNAL_GLOBAL, FakeGlobalIndex++};
1048 }
1049
Nicola Zaghene7245b42018-05-15 13:36:20 +00001050 LLVM_DEBUG(dbgs() << "Export: " << Name << "\n");
Sam Cleggd6beb322018-05-10 18:10:34 +00001051 Exports.push_back(Export);
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +00001052 }
Sam Clegg93102972018-02-23 05:08:53 +00001053}
1054
1055void Writer::assignSymtab() {
1056 if (!Config->Relocatable)
1057 return;
1058
Sam Cleggd177ab22018-05-04 23:14:42 +00001059 StringMap<uint32_t> SectionSymbolIndices;
1060
Sam Clegg93102972018-02-23 05:08:53 +00001061 unsigned SymbolIndex = SymtabEntries.size();
Sam Cleggd177ab22018-05-04 23:14:42 +00001062
Sam Clegg89e4dcb2019-01-30 18:55:15 +00001063 auto AddSymbol = [&](Symbol *Sym) {
1064 if (auto *S = dyn_cast<SectionSymbol>(Sym)) {
1065 StringRef Name = S->getName();
1066 if (CustomSectionMapping.count(Name) == 0)
1067 return;
Sam Cleggd177ab22018-05-04 23:14:42 +00001068
Sam Clegg89e4dcb2019-01-30 18:55:15 +00001069 auto SSI = SectionSymbolIndices.find(Name);
1070 if (SSI != SectionSymbolIndices.end()) {
1071 Sym->setOutputSymbolIndex(SSI->second);
1072 return;
Sam Cleggd177ab22018-05-04 23:14:42 +00001073 }
1074
Sam Clegg89e4dcb2019-01-30 18:55:15 +00001075 SectionSymbolIndices[Name] = SymbolIndex;
1076 CustomSectionSymbols[Name] = cast<SectionSymbol>(Sym);
Sam Cleggd3052d52018-01-18 23:40:49 +00001077
Sam Clegg89e4dcb2019-01-30 18:55:15 +00001078 Sym->markLive();
1079 }
1080
1081 // (Since this is relocatable output, GC is not performed so symbols must
1082 // be live.)
1083 assert(Sym->isLive());
1084 Sym->setOutputSymbolIndex(SymbolIndex++);
1085 SymtabEntries.emplace_back(Sym);
1086 };
1087
1088 for (Symbol *Sym : Symtab->getSymbols())
Sam Cleggd15a41542019-03-08 21:10:48 +00001089 if (Sym->IsUsedInRegularObj)
Sam Clegg89e4dcb2019-01-30 18:55:15 +00001090 AddSymbol(Sym);
1091
1092 for (ObjFile *File : Symtab->ObjectFiles) {
1093 LLVM_DEBUG(dbgs() << "Local symtab entries: " << File->getName() << "\n");
1094 for (Symbol *Sym : File->getSymbols())
1095 if (Sym->isLocal())
1096 AddSymbol(Sym);
1097 }
Sam Cleggd3052d52018-01-18 23:40:49 +00001098}
1099
Sam Cleggc375e4e2018-01-10 19:18:22 +00001100uint32_t Writer::lookupType(const WasmSignature &Sig) {
Sam Clegg8d027d62018-01-10 20:12:26 +00001101 auto It = TypeIndices.find(Sig);
1102 if (It == TypeIndices.end()) {
Sam Cleggc375e4e2018-01-10 19:18:22 +00001103 error("type not found: " + toString(Sig));
Sam Clegg8d027d62018-01-10 20:12:26 +00001104 return 0;
1105 }
1106 return It->second;
Sam Cleggc375e4e2018-01-10 19:18:22 +00001107}
1108
1109uint32_t Writer::registerType(const WasmSignature &Sig) {
Sam Cleggb8621592017-11-30 01:40:08 +00001110 auto Pair = TypeIndices.insert(std::make_pair(Sig, Types.size()));
Sam Cleggc375e4e2018-01-10 19:18:22 +00001111 if (Pair.second) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001112 LLVM_DEBUG(dbgs() << "type " << toString(Sig) << "\n");
Sam Cleggb8621592017-11-30 01:40:08 +00001113 Types.push_back(&Sig);
Sam Cleggc375e4e2018-01-10 19:18:22 +00001114 }
Sam Cleggb8621592017-11-30 01:40:08 +00001115 return Pair.first->second;
1116}
1117
Sam Cleggc94d3932017-11-17 18:14:09 +00001118void Writer::calculateTypes() {
Sam Clegg8f6d2de2018-01-31 23:48:14 +00001119 // The output type section is the union of the following sets:
1120 // 1. Any signature used in the TYPE relocation
1121 // 2. The signatures of all imported functions
1122 // 3. The signatures of all defined functions
Heejin Ahne915a712018-12-08 06:17:43 +00001123 // 4. The signatures of all imported events
1124 // 5. The signatures of all defined events
Sam Clegg8f6d2de2018-01-31 23:48:14 +00001125
Sam Cleggc94d3932017-11-17 18:14:09 +00001126 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +00001127 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
1128 for (uint32_t I = 0; I < Types.size(); I++)
1129 if (File->TypeIsUsed[I])
1130 File->TypeMap[I] = registerType(Types[I]);
Sam Cleggc94d3932017-11-17 18:14:09 +00001131 }
Sam Clegg50686852018-01-12 18:35:13 +00001132
Heejin Ahne915a712018-12-08 06:17:43 +00001133 for (const Symbol *Sym : ImportedSymbols) {
Sam Clegg93102972018-02-23 05:08:53 +00001134 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
Heejin Ahne915a712018-12-08 06:17:43 +00001135 registerType(*F->Signature);
1136 else if (auto *E = dyn_cast<EventSymbol>(Sym))
1137 registerType(*E->Signature);
1138 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +00001139
Sam Clegg9f934222018-02-21 18:29:23 +00001140 for (const InputFunction *F : InputFunctions)
Sam Clegg8f6d2de2018-01-31 23:48:14 +00001141 registerType(F->Signature);
Heejin Ahne915a712018-12-08 06:17:43 +00001142
1143 for (const InputEvent *E : InputEvents)
1144 registerType(E->Signature);
Sam Cleggc94d3932017-11-17 18:14:09 +00001145}
1146
Sam Cleggea38ac52019-05-10 01:52:08 +00001147static bool requiresGOTAccess(const Symbol* Sym) {
1148 return Config->Pic && !Sym->isHidden() && !Sym->isLocal();
1149}
1150
Sam Clegg632c21792019-03-16 01:18:12 +00001151void Writer::processRelocations(InputChunk *Chunk) {
1152 if (!Chunk->Live)
1153 return;
1154 ObjFile *File = Chunk->File;
1155 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
1156 for (const WasmRelocation &Reloc : Chunk->getRelocations()) {
Sam Clegg0b13ca22019-05-13 16:42:52 +00001157 if (Reloc.Type == R_WASM_TYPE_INDEX_LEB) {
1158 // Mark target type as live
1159 File->TypeMap[Reloc.Index] = registerType(Types[Reloc.Index]);
1160 File->TypeIsUsed[Reloc.Index] = true;
1161 continue;
1162 }
1163
1164 // Other relocation types all have a corresponding symbol
1165 auto *Sym = File->getSymbols()[Reloc.Index];
Sam Clegg632c21792019-03-16 01:18:12 +00001166 switch (Reloc.Type) {
1167 case R_WASM_TABLE_INDEX_I32:
Sam Clegga116d912019-04-05 00:35:12 +00001168 case R_WASM_TABLE_INDEX_SLEB:
1169 case R_WASM_TABLE_INDEX_REL_SLEB: {
Sam Clegg0b13ca22019-05-13 16:42:52 +00001170 auto *F = cast<FunctionSymbol>(Sym);
1171 if (F->hasTableIndex() || !F->hasFunctionIndex() || requiresGOTAccess(F))
Sam Cleggea38ac52019-05-10 01:52:08 +00001172 break;
Sam Clegg0b13ca22019-05-13 16:42:52 +00001173 F->setTableIndex(TableBase + IndirectFunctions.size());
1174 IndirectFunctions.emplace_back(F);
Sam Clegg632c21792019-03-16 01:18:12 +00001175 break;
1176 }
1177 case R_WASM_TYPE_INDEX_LEB:
Sam Clegg632c21792019-03-16 01:18:12 +00001178 break;
Sam Clegg0b13ca22019-05-13 16:42:52 +00001179 case R_WASM_GLOBAL_INDEX_LEB:
Sam Clegg492f7522019-03-26 19:46:15 +00001180 if (!isa<GlobalSymbol>(Sym) && !Sym->isInGOT()) {
1181 Sym->setGOTIndex(NumImportedGlobals++);
1182 GOTSymbols.push_back(Sym);
1183 }
Sam Clegg7cdec272019-04-22 16:12:54 +00001184 break;
Sam Clegg7cdec272019-04-22 16:12:54 +00001185 case R_WASM_MEMORY_ADDR_SLEB:
1186 case R_WASM_MEMORY_ADDR_LEB:
Sam Clegg0b13ca22019-05-13 16:42:52 +00001187 case R_WASM_MEMORY_ADDR_REL_SLEB:
Sam Clegg7cdec272019-04-22 16:12:54 +00001188 if (!Config->Relocatable) {
Sam Clegg7cdec272019-04-22 16:12:54 +00001189 if (Sym->isUndefined() && !Sym->isWeak()) {
1190 error(toString(File) + ": cannot resolve relocation of type " +
1191 relocTypeToString(Reloc.Type) +
1192 " against undefined (non-weak) data symbol: " + toString(*Sym));
1193 }
1194 }
1195 break;
Sam Clegg492f7522019-03-26 19:46:15 +00001196 }
Sam Clegg09137be2019-04-04 18:40:51 +00001197
1198 if (Config->Pic) {
Sam Clegg09137be2019-04-04 18:40:51 +00001199 switch (Reloc.Type) {
1200 case R_WASM_TABLE_INDEX_SLEB:
1201 case R_WASM_MEMORY_ADDR_SLEB:
Sam Clegg0b13ca22019-05-13 16:42:52 +00001202 case R_WASM_MEMORY_ADDR_LEB:
Sam Clegg0d9f6092019-04-10 15:06:17 +00001203 // Certain relocation types can't be used when building PIC output, since
1204 // they would require absolute symbol addresses at link time.
Sam Clegg09137be2019-04-04 18:40:51 +00001205 error(toString(File) + ": relocation " +
1206 relocTypeToString(Reloc.Type) + " cannot be used againt symbol " +
1207 toString(*Sym) + "; recompile with -fPIC");
1208 break;
Sam Clegg0d9f6092019-04-10 15:06:17 +00001209 case R_WASM_TABLE_INDEX_I32:
Sam Clegg0b13ca22019-05-13 16:42:52 +00001210 case R_WASM_MEMORY_ADDR_I32:
Sam Clegg0d9f6092019-04-10 15:06:17 +00001211 // These relocation types are only present in the data section and
1212 // will be converted into code by `generateRelocationCode`. This code
1213 // requires the symbols to have GOT entires.
Sam Cleggea38ac52019-05-10 01:52:08 +00001214 if (requiresGOTAccess(Sym) && !Sym->isInGOT()) {
Sam Clegg0d9f6092019-04-10 15:06:17 +00001215 Sym->setGOTIndex(NumImportedGlobals++);
1216 GOTSymbols.push_back(Sym);
1217 }
1218 break;
1219 }
Sam Clegg09137be2019-04-04 18:40:51 +00001220 }
Sam Clegg632c21792019-03-16 01:18:12 +00001221 }
1222}
1223
Sam Clegg8d146bb2018-01-09 23:56:44 +00001224void Writer::assignIndexes() {
Heejin Ahnaeaab992018-11-19 23:21:25 +00001225 assert(InputFunctions.empty());
1226 uint32_t FunctionIndex = NumImportedFunctions;
Nicholas Wilsonebda41f2018-03-09 16:43:05 +00001227 auto AddDefinedFunction = [&](InputFunction *Func) {
1228 if (!Func->Live)
1229 return;
1230 InputFunctions.emplace_back(Func);
Sam Clegge3f3ccf2018-03-12 19:56:23 +00001231 Func->setFunctionIndex(FunctionIndex++);
Nicholas Wilsonebda41f2018-03-09 16:43:05 +00001232 };
1233
Nicholas Wilson5639da82018-03-12 15:44:07 +00001234 for (InputFunction *Func : Symtab->SyntheticFunctions)
1235 AddDefinedFunction(Func);
1236
Sam Clegg87e61922018-01-08 23:39:11 +00001237 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001238 LLVM_DEBUG(dbgs() << "Functions: " << File->getName() << "\n");
Nicholas Wilsonebda41f2018-03-09 16:43:05 +00001239 for (InputFunction *Func : File->Functions)
1240 AddDefinedFunction(Func);
Sam Clegg8d146bb2018-01-09 23:56:44 +00001241 }
1242
1243 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001244 LLVM_DEBUG(dbgs() << "Handle relocs: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +00001245 for (InputChunk *Chunk : File->Functions)
Sam Clegg632c21792019-03-16 01:18:12 +00001246 processRelocations(Chunk);
Sam Clegg93102972018-02-23 05:08:53 +00001247 for (InputChunk *Chunk : File->Segments)
Sam Clegg632c21792019-03-16 01:18:12 +00001248 processRelocations(Chunk);
Sam Cleggd177ab22018-05-04 23:14:42 +00001249 for (auto &P : File->CustomSections)
Sam Clegg632c21792019-03-16 01:18:12 +00001250 processRelocations(P);
Sam Clegg93102972018-02-23 05:08:53 +00001251 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +00001252
Heejin Ahnaeaab992018-11-19 23:21:25 +00001253 assert(InputGlobals.empty());
1254 uint32_t GlobalIndex = NumImportedGlobals;
Sam Clegg93102972018-02-23 05:08:53 +00001255 auto AddDefinedGlobal = [&](InputGlobal *Global) {
1256 if (Global->Live) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001257 LLVM_DEBUG(dbgs() << "AddDefinedGlobal: " << GlobalIndex << "\n");
Sam Clegge3f3ccf2018-03-12 19:56:23 +00001258 Global->setGlobalIndex(GlobalIndex++);
Sam Clegg93102972018-02-23 05:08:53 +00001259 InputGlobals.push_back(Global);
1260 }
1261 };
1262
Nicholas Wilsonebda41f2018-03-09 16:43:05 +00001263 for (InputGlobal *Global : Symtab->SyntheticGlobals)
1264 AddDefinedGlobal(Global);
Sam Clegg93102972018-02-23 05:08:53 +00001265
1266 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001267 LLVM_DEBUG(dbgs() << "Globals: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +00001268 for (InputGlobal *Global : File->Globals)
1269 AddDefinedGlobal(Global);
Sam Cleggc94d3932017-11-17 18:14:09 +00001270 }
Heejin Ahne915a712018-12-08 06:17:43 +00001271
1272 assert(InputEvents.empty());
1273 uint32_t EventIndex = NumImportedEvents;
1274 auto AddDefinedEvent = [&](InputEvent *Event) {
1275 if (Event->Live) {
1276 LLVM_DEBUG(dbgs() << "AddDefinedEvent: " << EventIndex << "\n");
1277 Event->setEventIndex(EventIndex++);
1278 InputEvents.push_back(Event);
1279 }
1280 };
1281
1282 for (ObjFile *File : Symtab->ObjectFiles) {
1283 LLVM_DEBUG(dbgs() << "Events: " << File->getName() << "\n");
1284 for (InputEvent *Event : File->Events)
1285 AddDefinedEvent(Event);
1286 }
Sam Cleggc94d3932017-11-17 18:14:09 +00001287}
1288
1289static StringRef getOutputDataSegmentName(StringRef Name) {
Sam Cleggbfb75342018-11-15 00:37:21 +00001290 // With PIC code we currently only support a single data segment since
1291 // we only have a single __memory_base to use as our base address.
1292 if (Config->Pic)
1293 return "data";
Sam Clegg66844762018-05-10 18:23:51 +00001294 if (!Config->MergeDataSegments)
Sam Cleggc94d3932017-11-17 18:14:09 +00001295 return Name;
Rui Ueyama4764b572018-02-28 00:57:28 +00001296 if (Name.startswith(".text."))
1297 return ".text";
1298 if (Name.startswith(".data."))
1299 return ".data";
1300 if (Name.startswith(".bss."))
1301 return ".bss";
Sam Clegg57694c52018-08-08 18:02:55 +00001302 if (Name.startswith(".rodata."))
1303 return ".rodata";
Sam Cleggc94d3932017-11-17 18:14:09 +00001304 return Name;
1305}
1306
1307void Writer::createOutputSegments() {
1308 for (ObjFile *File : Symtab->ObjectFiles) {
1309 for (InputSegment *Segment : File->Segments) {
Sam Clegg447ae402018-02-13 20:29:38 +00001310 if (!Segment->Live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +00001311 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +00001312 StringRef Name = getOutputDataSegmentName(Segment->getName());
1313 OutputSegment *&S = SegmentMap[Name];
1314 if (S == nullptr) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001315 LLVM_DEBUG(dbgs() << "new segment: " << Name << "\n");
Sam Clegg93102972018-02-23 05:08:53 +00001316 S = make<OutputSegment>(Name, Segments.size());
Sam Cleggc94d3932017-11-17 18:14:09 +00001317 Segments.push_back(S);
1318 }
1319 S->addInputSegment(Segment);
Nicola Zaghene7245b42018-05-15 13:36:20 +00001320 LLVM_DEBUG(dbgs() << "added data: " << Name << ": " << S->Size << "\n");
Sam Cleggc94d3932017-11-17 18:14:09 +00001321 }
1322 }
1323}
1324
Sam Clegg09137be2019-04-04 18:40:51 +00001325// For -shared (PIC) output, we create create a synthetic function which will
1326// apply any relocations to the data segments on startup. This function is
1327// called __wasm_apply_relocs and is added at the very beginning of
1328// __wasm_call_ctors before any of the constructors run.
1329void Writer::createApplyRelocationsFunction() {
1330 LLVM_DEBUG(dbgs() << "createApplyRelocationsFunction\n");
1331 // First write the body's contents to a string.
1332 std::string BodyContent;
1333 {
1334 raw_string_ostream OS(BodyContent);
1335 writeUleb128(OS, 0, "num locals");
1336 for (const OutputSegment *Seg : Segments)
1337 for (const InputSegment *InSeg : Seg->InputSegments)
1338 InSeg->generateRelocationCode(OS);
1339 writeU8(OS, WASM_OPCODE_END, "END");
1340 }
1341
1342 // Once we know the size of the body we can create the final function body
1343 std::string FunctionBody;
1344 {
1345 raw_string_ostream OS(FunctionBody);
1346 writeUleb128(OS, BodyContent.size(), "function size");
1347 OS << BodyContent;
1348 }
1349
1350 ArrayRef<uint8_t> Body = arrayRefFromStringRef(Saver.save(FunctionBody));
1351 cast<SyntheticFunction>(WasmSym::ApplyRelocs->Function)->setBody(Body);
1352}
Sam Clegg50686852018-01-12 18:35:13 +00001353
1354// Create synthetic "__wasm_call_ctors" function based on ctor functions
1355// in input object.
Sam Clegg09137be2019-04-04 18:40:51 +00001356void Writer::createCallCtorsFunction() {
Sam Clegg0e6b42f2019-03-01 22:35:47 +00001357 if (!WasmSym::CallCtors->isLive())
1358 return;
1359
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +00001360 // First write the body's contents to a string.
1361 std::string BodyContent;
Sam Clegg50686852018-01-12 18:35:13 +00001362 {
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +00001363 raw_string_ostream OS(BodyContent);
Sam Clegg50686852018-01-12 18:35:13 +00001364 writeUleb128(OS, 0, "num locals");
Sam Clegg09137be2019-04-04 18:40:51 +00001365 if (Config->Pic) {
1366 writeU8(OS, WASM_OPCODE_CALL, "CALL");
1367 writeUleb128(OS, WasmSym::ApplyRelocs->getFunctionIndex(),
1368 "function index");
1369 }
Sam Clegg93102972018-02-23 05:08:53 +00001370 for (const WasmInitEntry &F : InitFunctions) {
Sam Clegg09137be2019-04-04 18:40:51 +00001371 writeU8(OS, WASM_OPCODE_CALL, "CALL");
Sam Clegge3f3ccf2018-03-12 19:56:23 +00001372 writeUleb128(OS, F.Sym->getFunctionIndex(), "function index");
Sam Clegg50686852018-01-12 18:35:13 +00001373 }
Sam Clegg09137be2019-04-04 18:40:51 +00001374 writeU8(OS, WASM_OPCODE_END, "END");
Sam Clegg50686852018-01-12 18:35:13 +00001375 }
1376
1377 // Once we know the size of the body we can create the final function body
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +00001378 std::string FunctionBody;
1379 {
1380 raw_string_ostream OS(FunctionBody);
1381 writeUleb128(OS, BodyContent.size(), "function size");
1382 OS << BodyContent;
1383 }
Rui Ueyama29abfe42018-02-28 17:43:15 +00001384
Sam Cleggea656472018-10-22 08:35:39 +00001385 ArrayRef<uint8_t> Body = arrayRefFromStringRef(Saver.save(FunctionBody));
Nicholas Wilsonebda41f2018-03-09 16:43:05 +00001386 cast<SyntheticFunction>(WasmSym::CallCtors->Function)->setBody(Body);
Sam Clegg50686852018-01-12 18:35:13 +00001387}
1388
1389// Populate InitFunctions vector with init functions from all input objects.
1390// This is then used either when creating the output linking section or to
1391// synthesize the "__wasm_call_ctors" function.
1392void Writer::calculateInitFunctions() {
Sam Clegg61f13b32019-03-02 04:55:02 +00001393 if (!Config->Relocatable && !WasmSym::CallCtors->isLive())
1394 return;
1395
Sam Clegg50686852018-01-12 18:35:13 +00001396 for (ObjFile *File : Symtab->ObjectFiles) {
1397 const WasmLinkingData &L = File->getWasmObj()->linkingData();
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +00001398 for (const WasmInitFunc &F : L.InitFunctions) {
1399 FunctionSymbol *Sym = File->getFunctionSymbol(F.Symbol);
Sam Clegg0e6b42f2019-03-01 22:35:47 +00001400 assert(Sym->isLive());
Heejin Ahne915a712018-12-08 06:17:43 +00001401 if (*Sym->Signature != WasmSignature{{}, {}})
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +00001402 error("invalid signature for init func: " + toString(*Sym));
1403 InitFunctions.emplace_back(WasmInitEntry{Sym, F.Priority});
1404 }
Sam Clegg50686852018-01-12 18:35:13 +00001405 }
Rui Ueyamada69b712018-02-28 00:15:59 +00001406
Sam Clegg50686852018-01-12 18:35:13 +00001407 // Sort in order of priority (lowest first) so that they are called
1408 // in the correct order.
Fangrui Song32c0ebe2019-04-23 02:42:06 +00001409 llvm::stable_sort(InitFunctions,
1410 [](const WasmInitEntry &L, const WasmInitEntry &R) {
1411 return L.Priority < R.Priority;
1412 });
Sam Clegg50686852018-01-12 18:35:13 +00001413}
1414
Sam Cleggc94d3932017-11-17 18:14:09 +00001415void Writer::run() {
Sam Cleggbfb75342018-11-15 00:37:21 +00001416 if (Config->Relocatable || Config->Pic)
Sam Clegg99eb42c2018-02-27 23:58:03 +00001417 Config->GlobalBase = 0;
1418
Sam Cleggbfb75342018-11-15 00:37:21 +00001419 // For PIC code the table base is assigned dynamically by the loader.
1420 // For non-PIC, we start at 1 so that accessing table index 0 always traps.
1421 if (!Config->Pic)
1422 TableBase = 1;
1423
Thomas Livelyf6f4f842019-03-20 20:26:45 +00001424 log("-- calculateTargetFeatures");
1425 calculateTargetFeatures();
Sam Cleggc94d3932017-11-17 18:14:09 +00001426 log("-- calculateImports");
1427 calculateImports();
Sam Clegg8d146bb2018-01-09 23:56:44 +00001428 log("-- assignIndexes");
1429 assignIndexes();
Sam Clegg50686852018-01-12 18:35:13 +00001430 log("-- calculateInitFunctions");
1431 calculateInitFunctions();
Sam Clegg8f6d2de2018-01-31 23:48:14 +00001432 log("-- calculateTypes");
1433 calculateTypes();
Sam Clegg93102972018-02-23 05:08:53 +00001434 log("-- layoutMemory");
1435 layoutMemory();
Sam Clegg09137be2019-04-04 18:40:51 +00001436 if (!Config->Relocatable) {
1437 if (Config->Pic)
1438 createApplyRelocationsFunction();
1439 createCallCtorsFunction();
1440 }
Sam Clegg93102972018-02-23 05:08:53 +00001441 log("-- calculateExports");
1442 calculateExports();
Sam Cleggd177ab22018-05-04 23:14:42 +00001443 log("-- calculateCustomSections");
1444 calculateCustomSections();
Sam Clegg93102972018-02-23 05:08:53 +00001445 log("-- assignSymtab");
1446 assignSymtab();
Sam Cleggc94d3932017-11-17 18:14:09 +00001447
1448 if (errorHandler().Verbose) {
Sam Clegg9f934222018-02-21 18:29:23 +00001449 log("Defined Functions: " + Twine(InputFunctions.size()));
Sam Clegg93102972018-02-23 05:08:53 +00001450 log("Defined Globals : " + Twine(InputGlobals.size()));
Heejin Ahne915a712018-12-08 06:17:43 +00001451 log("Defined Events : " + Twine(InputEvents.size()));
Sam Clegg93102972018-02-23 05:08:53 +00001452 log("Function Imports : " + Twine(NumImportedFunctions));
1453 log("Global Imports : " + Twine(NumImportedGlobals));
Heejin Ahne915a712018-12-08 06:17:43 +00001454 log("Event Imports : " + Twine(NumImportedEvents));
Sam Cleggc94d3932017-11-17 18:14:09 +00001455 for (ObjFile *File : Symtab->ObjectFiles)
1456 File->dumpInfo();
1457 }
1458
Sam Cleggc94d3932017-11-17 18:14:09 +00001459 createHeader();
1460 log("-- createSections");
1461 createSections();
1462
1463 log("-- openFile");
1464 openFile();
1465 if (errorCount())
1466 return;
1467
1468 writeHeader();
1469
1470 log("-- writeSections");
1471 writeSections();
1472 if (errorCount())
1473 return;
1474
1475 if (Error E = Buffer->commit())
1476 fatal("failed to write the output file: " + toString(std::move(E)));
1477}
1478
1479// Open a result file.
1480void Writer::openFile() {
1481 log("writing: " + Config->OutputFile);
Sam Cleggc94d3932017-11-17 18:14:09 +00001482
1483 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
1484 FileOutputBuffer::create(Config->OutputFile, FileSize,
1485 FileOutputBuffer::F_executable);
1486
1487 if (!BufferOrErr)
1488 error("failed to open " + Config->OutputFile + ": " +
1489 toString(BufferOrErr.takeError()));
1490 else
1491 Buffer = std::move(*BufferOrErr);
1492}
1493
1494void Writer::createHeader() {
1495 raw_string_ostream OS(Header);
1496 writeBytes(OS, WasmMagic, sizeof(WasmMagic), "wasm magic");
1497 writeU32(OS, WasmVersion, "wasm version");
1498 OS.flush();
1499 FileSize += Header.size();
1500}
1501
1502void lld::wasm::writeResult() { Writer().run(); }