blob: 8ed4d6b94cd5fc7ba0d40d1a0e91dbb3c5d782a6 [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() {
237 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TYPE);
238 raw_ostream &OS = Section->getStream();
239 writeUleb128(OS, Types.size(), "type count");
Sam Cleggd451da12017-12-19 19:56:27 +0000240 for (const WasmSignature *Sig : Types)
Sam Cleggc94d3932017-11-17 18:14:09 +0000241 writeSig(OS, *Sig);
Sam Cleggc94d3932017-11-17 18:14:09 +0000242}
243
244void Writer::createFunctionSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000245 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000246 return;
247
248 SyntheticSection *Section = createSyntheticSection(WASM_SEC_FUNCTION);
249 raw_ostream &OS = Section->getStream();
250
Sam Clegg9f934222018-02-21 18:29:23 +0000251 writeUleb128(OS, InputFunctions.size(), "function count");
252 for (const InputFunction *Func : InputFunctions)
Sam Cleggc375e4e2018-01-10 19:18:22 +0000253 writeUleb128(OS, lookupType(Func->Signature), "sig index");
Sam Cleggc94d3932017-11-17 18:14:09 +0000254}
255
256void Writer::createMemorySection() {
257 if (Config->ImportMemory)
258 return;
259
260 SyntheticSection *Section = createSyntheticSection(WASM_SEC_MEMORY);
261 raw_ostream &OS = Section->getStream();
262
Thomas Lively06391f32019-03-29 20:43:49 +0000263 bool HasMax = MaxMemoryPages != 0 || Config->SharedMemory;
Sam Cleggc94d3932017-11-17 18:14:09 +0000264 writeUleb128(OS, 1, "memory count");
Derek Schuff786760a2018-11-06 18:02:39 +0000265 unsigned Flags = 0;
266 if (HasMax)
267 Flags |= WASM_LIMITS_FLAG_HAS_MAX;
Derek Schuff3bea8bc2018-11-06 17:59:32 +0000268 if (Config->SharedMemory)
269 Flags |= WASM_LIMITS_FLAG_IS_SHARED;
270 writeUleb128(OS, Flags, "memory limits flags");
Sam Cleggc94d3932017-11-17 18:14:09 +0000271 writeUleb128(OS, NumMemoryPages, "initial pages");
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000272 if (HasMax)
273 writeUleb128(OS, MaxMemoryPages, "max pages");
Sam Cleggc94d3932017-11-17 18:14:09 +0000274}
275
276void Writer::createGlobalSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000277 unsigned NumGlobals = InputGlobals.size() + DefinedFakeGlobals.size();
278 if (NumGlobals == 0)
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000279 return;
280
Sam Cleggc94d3932017-11-17 18:14:09 +0000281 SyntheticSection *Section = createSyntheticSection(WASM_SEC_GLOBAL);
282 raw_ostream &OS = Section->getStream();
283
Sam Clegg93102972018-02-23 05:08:53 +0000284 writeUleb128(OS, NumGlobals, "global count");
285 for (const InputGlobal *G : InputGlobals)
286 writeGlobal(OS, G->Global);
287 for (const DefinedData *Sym : DefinedFakeGlobals) {
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000288 WasmGlobal Global;
Sam Clegg93102972018-02-23 05:08:53 +0000289 Global.Type = {WASM_TYPE_I32, false};
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000290 Global.InitExpr.Opcode = WASM_OPCODE_I32_CONST;
291 Global.InitExpr.Value.Int32 = Sym->getVirtualAddress();
Sam Cleggc94d3932017-11-17 18:14:09 +0000292 writeGlobal(OS, Global);
293 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000294}
295
Heejin Ahne915a712018-12-08 06:17:43 +0000296// The event section contains a list of declared wasm events associated with the
297// module. Currently the only supported event kind is exceptions. A single event
298// entry represents a single event with an event tag. All C++ exceptions are
299// represented by a single event. An event entry in this section contains
300// information on what kind of event it is (e.g. exception) and the type of
301// values contained in a single event object. (In wasm, an event can contain
302// multiple values of primitive types. But for C++ exceptions, we just throw a
303// pointer which is an i32 value (for wasm32 architecture), so the signature of
304// C++ exception is (i32)->(void), because all event types are assumed to have
305// void return type to share WasmSignature with functions.)
306void Writer::createEventSection() {
307 unsigned NumEvents = InputEvents.size();
308 if (NumEvents == 0)
309 return;
310
311 SyntheticSection *Section = createSyntheticSection(WASM_SEC_EVENT);
312 raw_ostream &OS = Section->getStream();
313
314 writeUleb128(OS, NumEvents, "event count");
315 for (InputEvent *E : InputEvents) {
316 E->Event.Type.SigIndex = lookupType(E->Signature);
317 writeEvent(OS, E->Event);
318 }
319}
320
Sam Cleggc94d3932017-11-17 18:14:09 +0000321void Writer::createTableSection() {
Nicholas Wilsonfc90b302018-03-28 12:53:29 +0000322 if (Config->ImportTable)
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000323 return;
324
325 // Always output a table section (or table import), even if there are no
326 // indirect calls. There are two reasons for this:
Sam Cleggfc1a9122017-12-11 22:00:56 +0000327 // 1. For executables it is useful to have an empty table slot at 0
328 // which can be filled with a null function call handler.
329 // 2. If we don't do this, any program that contains a call_indirect but
330 // no address-taken function will fail at validation time since it is
331 // a validation error to include a call_indirect instruction if there
332 // is not table.
Sam Cleggbfb75342018-11-15 00:37:21 +0000333 uint32_t TableSize = TableBase + IndirectFunctions.size();
Sam Cleggfc1a9122017-12-11 22:00:56 +0000334
Sam Cleggc94d3932017-11-17 18:14:09 +0000335 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TABLE);
336 raw_ostream &OS = Section->getStream();
337
338 writeUleb128(OS, 1, "table count");
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000339 WasmLimits Limits = {WASM_LIMITS_FLAG_HAS_MAX, TableSize, TableSize};
Thomas Lively25ff8932019-01-08 06:25:55 +0000340 writeTableType(OS, WasmTable{WASM_TYPE_FUNCREF, Limits});
Sam Cleggc94d3932017-11-17 18:14:09 +0000341}
342
343void Writer::createExportSection() {
Sam Cleggd6beb322018-05-10 18:10:34 +0000344 if (!Exports.size())
Sam Cleggc94d3932017-11-17 18:14:09 +0000345 return;
346
347 SyntheticSection *Section = createSyntheticSection(WASM_SEC_EXPORT);
348 raw_ostream &OS = Section->getStream();
349
Sam Cleggd6beb322018-05-10 18:10:34 +0000350 writeUleb128(OS, Exports.size(), "export count");
351 for (const WasmExport &Export : Exports)
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000352 writeExport(OS, Export);
Sam Cleggc94d3932017-11-17 18:14:09 +0000353}
354
Sam Cleggd177ab22018-05-04 23:14:42 +0000355void Writer::calculateCustomSections() {
356 log("calculateCustomSections");
357 bool StripDebug = Config->StripDebug || Config->StripAll;
358 for (ObjFile *File : Symtab->ObjectFiles) {
359 for (InputSection *Section : File->CustomSections) {
360 StringRef Name = Section->getName();
361 // These custom sections are known the linker and synthesized rather than
362 // blindly copied
Thomas Lively2a0868f2019-01-17 02:29:41 +0000363 if (Name == "linking" || Name == "name" || Name == "producers" ||
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000364 Name == "target_features" || Name.startswith("reloc."))
Sam Cleggd177ab22018-05-04 23:14:42 +0000365 continue;
366 // .. or it is a debug section
367 if (StripDebug && Name.startswith(".debug_"))
368 continue;
369 CustomSectionMapping[Name].push_back(Section);
370 }
371 }
372}
373
Sam Clegg80ba4382018-04-10 16:12:49 +0000374void Writer::createCustomSections() {
375 log("createCustomSections");
Sam Clegg80ba4382018-04-10 16:12:49 +0000376 for (auto &Pair : CustomSectionMapping) {
377 StringRef Name = Pair.first();
Sam Cleggd177ab22018-05-04 23:14:42 +0000378
379 auto P = CustomSectionSymbols.find(Name);
380 if (P != CustomSectionSymbols.end()) {
381 uint32_t SectionIndex = OutputSections.size();
382 P->second->setOutputSectionIndex(SectionIndex);
383 }
384
Nicola Zaghene7245b42018-05-15 13:36:20 +0000385 LLVM_DEBUG(dbgs() << "createCustomSection: " << Name << "\n");
Sam Clegg80ba4382018-04-10 16:12:49 +0000386 OutputSections.push_back(make<CustomSection>(Name, Pair.second));
387 }
388}
389
Sam Cleggc94d3932017-11-17 18:14:09 +0000390void Writer::createElemSection() {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000391 if (IndirectFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000392 return;
393
394 SyntheticSection *Section = createSyntheticSection(WASM_SEC_ELEM);
395 raw_ostream &OS = Section->getStream();
396
397 writeUleb128(OS, 1, "segment count");
398 writeUleb128(OS, 0, "table index");
399 WasmInitExpr InitExpr;
Sam Cleggbfb75342018-11-15 00:37:21 +0000400 if (Config->Pic) {
Thomas Lively25ff8932019-01-08 06:25:55 +0000401 InitExpr.Opcode = WASM_OPCODE_GLOBAL_GET;
Sam Clegg2dad4e22018-11-15 18:15:54 +0000402 InitExpr.Value.Global = WasmSym::TableBase->getGlobalIndex();
Sam Cleggbfb75342018-11-15 00:37:21 +0000403 } else {
404 InitExpr.Opcode = WASM_OPCODE_I32_CONST;
405 InitExpr.Value.Int32 = TableBase;
406 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000407 writeInitExpr(OS, InitExpr);
Sam Cleggfc1a9122017-12-11 22:00:56 +0000408 writeUleb128(OS, IndirectFunctions.size(), "elem count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000409
Sam Cleggbfb75342018-11-15 00:37:21 +0000410 uint32_t TableIndex = TableBase;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000411 for (const FunctionSymbol *Sym : IndirectFunctions) {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000412 assert(Sym->getTableIndex() == TableIndex);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000413 writeUleb128(OS, Sym->getFunctionIndex(), "function index");
Sam Cleggfc1a9122017-12-11 22:00:56 +0000414 ++TableIndex;
415 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000416}
417
Thomas Lively84771e22019-04-19 23:40:36 +0000418void Writer::createDataCountSection() {
419 if (!Segments.size() || !TargetFeatures.count("bulk-memory"))
420 return;
421
422 log("createDataCountSection");
423 SyntheticSection *Section = createSyntheticSection(WASM_SEC_DATACOUNT);
424 raw_ostream &OS = Section->getStream();
425 writeUleb128(OS, Segments.size(), "data count");
426}
427
Sam Cleggc94d3932017-11-17 18:14:09 +0000428void Writer::createCodeSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000429 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000430 return;
431
432 log("createCodeSection");
433
Sam Clegg9f934222018-02-21 18:29:23 +0000434 auto Section = make<CodeSection>(InputFunctions);
Sam Cleggc94d3932017-11-17 18:14:09 +0000435 OutputSections.push_back(Section);
436}
437
438void Writer::createDataSection() {
439 if (!Segments.size())
440 return;
441
442 log("createDataSection");
443 auto Section = make<DataSection>(Segments);
444 OutputSections.push_back(Section);
445}
446
Sam Cleggd451da12017-12-19 19:56:27 +0000447// Create relocations sections in the final output.
Sam Cleggc94d3932017-11-17 18:14:09 +0000448// These are only created when relocatable output is requested.
449void Writer::createRelocSections() {
450 log("createRelocSections");
451 // Don't use iterator here since we are adding to OutputSection
452 size_t OrigSize = OutputSections.size();
Rui Ueyamaffa650a2018-04-24 23:09:57 +0000453 for (size_t I = 0; I < OrigSize; I++) {
454 OutputSection *OSec = OutputSections[I];
Rui Ueyama37254062018-02-28 00:01:31 +0000455 uint32_t Count = OSec->numRelocations();
Sam Cleggc94d3932017-11-17 18:14:09 +0000456 if (!Count)
457 continue;
458
Rui Ueyama37254062018-02-28 00:01:31 +0000459 StringRef Name;
460 if (OSec->Type == WASM_SEC_DATA)
461 Name = "reloc.DATA";
462 else if (OSec->Type == WASM_SEC_CODE)
463 Name = "reloc.CODE";
Sam Cleggd177ab22018-05-04 23:14:42 +0000464 else if (OSec->Type == WASM_SEC_CUSTOM)
465 Name = Saver.save("reloc." + OSec->Name);
Sam Cleggc94d3932017-11-17 18:14:09 +0000466 else
Sam Cleggd177ab22018-05-04 23:14:42 +0000467 llvm_unreachable(
468 "relocations only supported for code, data, or custom sections");
Sam Cleggc94d3932017-11-17 18:14:09 +0000469
Rui Ueyama37254062018-02-28 00:01:31 +0000470 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, Name);
Sam Cleggc94d3932017-11-17 18:14:09 +0000471 raw_ostream &OS = Section->getStream();
Rui Ueyamaffa650a2018-04-24 23:09:57 +0000472 writeUleb128(OS, I, "reloc section");
Sam Cleggc94d3932017-11-17 18:14:09 +0000473 writeUleb128(OS, Count, "reloc count");
Rui Ueyama37254062018-02-28 00:01:31 +0000474 OSec->writeRelocations(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000475 }
476}
477
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000478static uint32_t getWasmFlags(const Symbol *Sym) {
479 uint32_t Flags = 0;
480 if (Sym->isLocal())
481 Flags |= WASM_SYMBOL_BINDING_LOCAL;
482 if (Sym->isWeak())
483 Flags |= WASM_SYMBOL_BINDING_WEAK;
484 if (Sym->isHidden())
485 Flags |= WASM_SYMBOL_VISIBILITY_HIDDEN;
486 if (Sym->isUndefined())
487 Flags |= WASM_SYMBOL_UNDEFINED;
Dan Gohman9b84eea2019-02-07 22:00:48 +0000488 if (auto *F = dyn_cast<UndefinedFunction>(Sym)) {
489 if (F->getName() != F->ImportName)
490 Flags |= WASM_SYMBOL_EXPLICIT_NAME;
491 } else if (auto *G = dyn_cast<UndefinedGlobal>(Sym)) {
492 if (G->getName() != G->ImportName)
493 Flags |= WASM_SYMBOL_EXPLICIT_NAME;
494 }
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000495 return Flags;
496}
497
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000498// Some synthetic sections (e.g. "name" and "linking") have subsections.
499// Just like the synthetic sections themselves these need to be created before
500// they can be written out (since they are preceded by their length). This
501// class is used to create subsections and then write them into the stream
502// of the parent section.
503class SubSection {
504public:
505 explicit SubSection(uint32_t Type) : Type(Type) {}
506
507 void writeTo(raw_ostream &To) {
508 OS.flush();
Rui Ueyama67769102018-02-28 03:38:14 +0000509 writeUleb128(To, Type, "subsection type");
510 writeUleb128(To, Body.size(), "subsection size");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000511 To.write(Body.data(), Body.size());
512 }
513
514private:
515 uint32_t Type;
516 std::string Body;
517
518public:
519 raw_string_ostream OS{Body};
520};
521
Sam Cleggbfb75342018-11-15 00:37:21 +0000522// Create the custom "dylink" section containing information for the dynamic
523// linker.
524// See
525// https://github.com/WebAssembly/tool-conventions/blob/master/DynamicLinking.md
526void Writer::createDylinkSection() {
527 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "dylink");
528 raw_ostream &OS = Section->getStream();
529
530 writeUleb128(OS, MemSize, "MemSize");
Sam Clegg6320efb2019-01-16 01:43:21 +0000531 writeUleb128(OS, MemAlign, "MemAlign");
Sam Cleggbfb75342018-11-15 00:37:21 +0000532 writeUleb128(OS, IndirectFunctions.size(), "TableSize");
533 writeUleb128(OS, 0, "TableAlign");
Sam Clegga688a422019-03-13 21:29:20 +0000534 writeUleb128(OS, Symtab->SharedFiles.size(), "Needed");
535 for (auto *SO : Symtab->SharedFiles)
536 writeStr(OS, llvm::sys::path::filename(SO->getName()), "so name");
Sam Cleggbfb75342018-11-15 00:37:21 +0000537}
538
Sam Clegg49ed9262017-12-01 00:53:21 +0000539// Create the custom "linking" section containing linker metadata.
Sam Cleggc94d3932017-11-17 18:14:09 +0000540// This is only created when relocatable output is requested.
541void Writer::createLinkingSection() {
542 SyntheticSection *Section =
543 createSyntheticSection(WASM_SEC_CUSTOM, "linking");
544 raw_ostream &OS = Section->getStream();
545
Sam Clegg2b8b1792018-04-26 18:17:21 +0000546 writeUleb128(OS, WasmMetadataVersion, "Version");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000547
Sam Clegg93102972018-02-23 05:08:53 +0000548 if (!SymtabEntries.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000549 SubSection Sub(WASM_SYMBOL_TABLE);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000550 writeUleb128(Sub.OS, SymtabEntries.size(), "num symbols");
551
Sam Clegg93102972018-02-23 05:08:53 +0000552 for (const Symbol *Sym : SymtabEntries) {
553 assert(Sym->isDefined() || Sym->isUndefined());
554 WasmSymbolType Kind = Sym->getWasmType();
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000555 uint32_t Flags = getWasmFlags(Sym);
556
Sam Clegg8518e7d2018-03-01 18:06:39 +0000557 writeU8(Sub.OS, Kind, "sym kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000558 writeUleb128(Sub.OS, Flags, "sym flags");
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000559
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000560 if (auto *F = dyn_cast<FunctionSymbol>(Sym)) {
561 writeUleb128(Sub.OS, F->getFunctionIndex(), "index");
Dan Gohman9b84eea2019-02-07 22:00:48 +0000562 if (Sym->isDefined() ||
563 (Flags & WASM_SYMBOL_EXPLICIT_NAME) != 0)
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000564 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000565 } else if (auto *G = dyn_cast<GlobalSymbol>(Sym)) {
566 writeUleb128(Sub.OS, G->getGlobalIndex(), "index");
Dan Gohman9b84eea2019-02-07 22:00:48 +0000567 if (Sym->isDefined() ||
568 (Flags & WASM_SYMBOL_EXPLICIT_NAME) != 0)
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000569 writeStr(Sub.OS, Sym->getName(), "sym name");
Heejin Ahne915a712018-12-08 06:17:43 +0000570 } else if (auto *E = dyn_cast<EventSymbol>(Sym)) {
571 writeUleb128(Sub.OS, E->getEventIndex(), "index");
Dan Gohman9b84eea2019-02-07 22:00:48 +0000572 if (Sym->isDefined() ||
573 (Flags & WASM_SYMBOL_EXPLICIT_NAME) != 0)
Heejin Ahne915a712018-12-08 06:17:43 +0000574 writeStr(Sub.OS, Sym->getName(), "sym name");
Andrea Di Biagio25c1a2f2018-05-05 10:53:31 +0000575 } else if (isa<DataSymbol>(Sym)) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000576 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegg93102972018-02-23 05:08:53 +0000577 if (auto *DataSym = dyn_cast<DefinedData>(Sym)) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000578 writeUleb128(Sub.OS, DataSym->getOutputSegmentIndex(), "index");
579 writeUleb128(Sub.OS, DataSym->getOutputSegmentOffset(),
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000580 "data offset");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000581 writeUleb128(Sub.OS, DataSym->getSize(), "data size");
Sam Clegg93102972018-02-23 05:08:53 +0000582 }
Sam Cleggd177ab22018-05-04 23:14:42 +0000583 } else {
584 auto *S = cast<SectionSymbol>(Sym);
585 writeUleb128(Sub.OS, S->getOutputSectionIndex(), "sym section index");
Sam Clegg93102972018-02-23 05:08:53 +0000586 }
Sam Cleggd3052d52018-01-18 23:40:49 +0000587 }
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000588
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000589 Sub.writeTo(OS);
Sam Cleggd3052d52018-01-18 23:40:49 +0000590 }
591
Sam Clegg0d0dd392017-12-19 17:09:45 +0000592 if (Segments.size()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000593 SubSection Sub(WASM_SEGMENT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000594 writeUleb128(Sub.OS, Segments.size(), "num data segments");
Sam Cleggc94d3932017-11-17 18:14:09 +0000595 for (const OutputSegment *S : Segments) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000596 writeStr(Sub.OS, S->Name, "segment name");
597 writeUleb128(Sub.OS, S->Alignment, "alignment");
598 writeUleb128(Sub.OS, 0, "flags");
Sam Cleggc94d3932017-11-17 18:14:09 +0000599 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000600 Sub.writeTo(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000601 }
Sam Clegg0d0dd392017-12-19 17:09:45 +0000602
Sam Clegg0d0dd392017-12-19 17:09:45 +0000603 if (!InitFunctions.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000604 SubSection Sub(WASM_INIT_FUNCS);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000605 writeUleb128(Sub.OS, InitFunctions.size(), "num init functions");
Sam Clegg93102972018-02-23 05:08:53 +0000606 for (const WasmInitEntry &F : InitFunctions) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000607 writeUleb128(Sub.OS, F.Priority, "priority");
608 writeUleb128(Sub.OS, F.Sym->getOutputSymbolIndex(), "function index");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000609 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000610 Sub.writeTo(OS);
Sam Clegg0d0dd392017-12-19 17:09:45 +0000611 }
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000612
Nicholas Wilsondbd90bf2018-03-07 13:28:16 +0000613 struct ComdatEntry {
614 unsigned Kind;
615 uint32_t Index;
616 };
617 std::map<StringRef, std::vector<ComdatEntry>> Comdats;
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000618
Sam Clegg9f934222018-02-21 18:29:23 +0000619 for (const InputFunction *F : InputFunctions) {
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000620 StringRef Comdat = F->getComdatName();
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000621 if (!Comdat.empty())
622 Comdats[Comdat].emplace_back(
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000623 ComdatEntry{WASM_COMDAT_FUNCTION, F->getFunctionIndex()});
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000624 }
625 for (uint32_t I = 0; I < Segments.size(); ++I) {
Sam Cleggf98bccf2018-01-13 15:57:48 +0000626 const auto &InputSegments = Segments[I]->InputSegments;
627 if (InputSegments.empty())
628 continue;
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000629 StringRef Comdat = InputSegments[0]->getComdatName();
Sam Clegga697df522018-01-13 15:59:53 +0000630#ifndef NDEBUG
Sam Cleggf98bccf2018-01-13 15:57:48 +0000631 for (const InputSegment *IS : InputSegments)
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000632 assert(IS->getComdatName() == Comdat);
Sam Clegga697df522018-01-13 15:59:53 +0000633#endif
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000634 if (!Comdat.empty())
635 Comdats[Comdat].emplace_back(ComdatEntry{WASM_COMDAT_DATA, I});
636 }
637
638 if (!Comdats.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000639 SubSection Sub(WASM_COMDAT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000640 writeUleb128(Sub.OS, Comdats.size(), "num comdats");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000641 for (const auto &C : Comdats) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000642 writeStr(Sub.OS, C.first, "comdat name");
643 writeUleb128(Sub.OS, 0, "comdat flags"); // flags for future use
644 writeUleb128(Sub.OS, C.second.size(), "num entries");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000645 for (const ComdatEntry &Entry : C.second) {
Sam Clegg8518e7d2018-03-01 18:06:39 +0000646 writeU8(Sub.OS, Entry.Kind, "entry kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000647 writeUleb128(Sub.OS, Entry.Index, "entry index");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000648 }
649 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000650 Sub.writeTo(OS);
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000651 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000652}
653
654// Create the custom "name" section containing debug symbol names.
655void Writer::createNameSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000656 unsigned NumNames = NumImportedFunctions;
Sam Clegg9f934222018-02-21 18:29:23 +0000657 for (const InputFunction *F : InputFunctions)
Nicholas Wilson6c7fe302018-04-20 17:09:18 +0000658 if (!F->getName().empty() || !F->getDebugName().empty())
Sam Clegg1963d712018-01-17 20:19:04 +0000659 ++NumNames;
Sam Cleggc94d3932017-11-17 18:14:09 +0000660
Sam Clegg1963d712018-01-17 20:19:04 +0000661 if (NumNames == 0)
662 return;
Sam Clegg50686852018-01-12 18:35:13 +0000663
Sam Cleggc94d3932017-11-17 18:14:09 +0000664 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "name");
665
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000666 SubSection Sub(WASM_NAMES_FUNCTION);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000667 writeUleb128(Sub.OS, NumNames, "name count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000668
Sam Clegg93102972018-02-23 05:08:53 +0000669 // Names must appear in function index order. As it happens ImportedSymbols
670 // and InputFunctions are numbered in order with imported functions coming
Sam Clegg1963d712018-01-17 20:19:04 +0000671 // first.
Sam Clegg93102972018-02-23 05:08:53 +0000672 for (const Symbol *S : ImportedSymbols) {
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000673 if (auto *F = dyn_cast<FunctionSymbol>(S)) {
674 writeUleb128(Sub.OS, F->getFunctionIndex(), "func index");
Sam Clegg37125f02018-11-09 16:57:41 +0000675 writeStr(Sub.OS, toString(*S), "symbol name");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000676 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000677 }
Sam Clegg9f934222018-02-21 18:29:23 +0000678 for (const InputFunction *F : InputFunctions) {
Sam Clegg1963d712018-01-17 20:19:04 +0000679 if (!F->getName().empty()) {
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000680 writeUleb128(Sub.OS, F->getFunctionIndex(), "func index");
Nicholas Wilson6c7fe302018-04-20 17:09:18 +0000681 if (!F->getDebugName().empty()) {
682 writeStr(Sub.OS, F->getDebugName(), "symbol name");
683 } else {
Sam Clegg37125f02018-11-09 16:57:41 +0000684 writeStr(Sub.OS, maybeDemangleSymbol(F->getName()), "symbol name");
Nicholas Wilson6c7fe302018-04-20 17:09:18 +0000685 }
Sam Clegg1963d712018-01-17 20:19:04 +0000686 }
687 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000688
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000689 Sub.writeTo(Section->getStream());
Sam Cleggc94d3932017-11-17 18:14:09 +0000690}
691
Thomas Lively2a0868f2019-01-17 02:29:41 +0000692void Writer::createProducersSection() {
693 SmallVector<std::pair<std::string, std::string>, 8> Languages;
694 SmallVector<std::pair<std::string, std::string>, 8> Tools;
695 SmallVector<std::pair<std::string, std::string>, 8> SDKs;
696 for (ObjFile *File : Symtab->ObjectFiles) {
697 const WasmProducerInfo &Info = File->getWasmObj()->getProducerInfo();
698 for (auto &Producers : {std::make_pair(&Info.Languages, &Languages),
699 std::make_pair(&Info.Tools, &Tools),
700 std::make_pair(&Info.SDKs, &SDKs)})
701 for (auto &Producer : *Producers.first)
702 if (Producers.second->end() ==
Fangrui Song8048fe22019-03-29 16:21:16 +0000703 llvm::find_if(*Producers.second,
704 [&](std::pair<std::string, std::string> Seen) {
705 return Seen.first == Producer.first;
706 }))
Thomas Lively2a0868f2019-01-17 02:29:41 +0000707 Producers.second->push_back(Producer);
708 }
709 int FieldCount =
710 int(!Languages.empty()) + int(!Tools.empty()) + int(!SDKs.empty());
711 if (FieldCount == 0)
712 return;
713 SyntheticSection *Section =
714 createSyntheticSection(WASM_SEC_CUSTOM, "producers");
715 auto &OS = Section->getStream();
716 writeUleb128(OS, FieldCount, "field count");
717 for (auto &Field :
718 {std::make_pair("language", Languages),
719 std::make_pair("processed-by", Tools), std::make_pair("sdk", SDKs)}) {
720 if (Field.second.empty())
721 continue;
722 writeStr(OS, Field.first, "field name");
723 writeUleb128(OS, Field.second.size(), "number of entries");
724 for (auto &Entry : Field.second) {
725 writeStr(OS, Entry.first, "producer name");
726 writeStr(OS, Entry.second, "producer version");
727 }
728 }
729}
730
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000731void Writer::createTargetFeaturesSection() {
Fangrui Song196a4402019-04-18 13:33:29 +0000732 if (TargetFeatures.empty())
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000733 return;
734
735 SmallVector<std::string, 8> Emitted(TargetFeatures.begin(),
736 TargetFeatures.end());
Fangrui Song196a4402019-04-18 13:33:29 +0000737 llvm::sort(Emitted);
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000738 SyntheticSection *Section =
739 createSyntheticSection(WASM_SEC_CUSTOM, "target_features");
740 auto &OS = Section->getStream();
741 writeUleb128(OS, Emitted.size(), "feature count");
742 for (auto &Feature : Emitted) {
743 writeU8(OS, WASM_FEATURE_PREFIX_USED, "feature used prefix");
744 writeStr(OS, Feature, "feature name");
745 }
746}
747
Sam Cleggc94d3932017-11-17 18:14:09 +0000748void Writer::writeHeader() {
749 memcpy(Buffer->getBufferStart(), Header.data(), Header.size());
750}
751
752void Writer::writeSections() {
753 uint8_t *Buf = Buffer->getBufferStart();
754 parallelForEach(OutputSections, [Buf](OutputSection *S) { S->writeTo(Buf); });
755}
756
757// Fix the memory layout of the output binary. This assigns memory offsets
Sam Clegg49ed9262017-12-01 00:53:21 +0000758// to each of the input data sections as well as the explicit stack region.
Sam Clegga0f095e2018-05-03 17:21:53 +0000759// The default memory layout is as follows, from low to high.
760//
Sam Cleggf0d433d2018-02-02 22:59:56 +0000761// - initialized data (starting at Config->GlobalBase)
762// - BSS data (not currently implemented in llvm)
763// - explicit stack (Config->ZStackSize)
764// - heap start / unallocated
Sam Clegga0f095e2018-05-03 17:21:53 +0000765//
766// The --stack-first option means that stack is placed before any static data.
Heejin Ahn4821ebf2018-08-29 21:03:16 +0000767// This can be useful since it means that stack overflow traps immediately
768// rather than overwriting global data, but also increases code size since all
769// static data loads and stores requires larger offsets.
Sam Cleggc94d3932017-11-17 18:14:09 +0000770void Writer::layoutMemory() {
Sam Cleggc94d3932017-11-17 18:14:09 +0000771 createOutputSegments();
772
Sam Clegga0f095e2018-05-03 17:21:53 +0000773 uint32_t MemoryPtr = 0;
774
775 auto PlaceStack = [&]() {
Sam Cleggbfb75342018-11-15 00:37:21 +0000776 if (Config->Relocatable || Config->Shared)
Sam Clegga0f095e2018-05-03 17:21:53 +0000777 return;
Heejin Ahna1cc4ea2019-02-04 19:13:46 +0000778 MemoryPtr = alignTo(MemoryPtr, StackAlignment);
779 if (Config->ZStackSize != alignTo(Config->ZStackSize, StackAlignment))
780 error("stack size must be " + Twine(StackAlignment) + "-byte aligned");
Sam Clegga0f095e2018-05-03 17:21:53 +0000781 log("mem: stack size = " + Twine(Config->ZStackSize));
782 log("mem: stack base = " + Twine(MemoryPtr));
783 MemoryPtr += Config->ZStackSize;
Sam Clegg2dad4e22018-11-15 18:15:54 +0000784 auto *SP = cast<DefinedGlobal>(WasmSym::StackPointer);
785 SP->Global->Global.InitExpr.Value.Int32 = MemoryPtr;
Sam Clegga0f095e2018-05-03 17:21:53 +0000786 log("mem: stack top = " + Twine(MemoryPtr));
787 };
788
789 if (Config->StackFirst) {
790 PlaceStack();
791 } else {
792 MemoryPtr = Config->GlobalBase;
793 log("mem: global base = " + Twine(Config->GlobalBase));
794 }
795
796 uint32_t DataStart = MemoryPtr;
797
Sam Cleggf0d433d2018-02-02 22:59:56 +0000798 // Arbitrarily set __dso_handle handle to point to the start of the data
799 // segments.
800 if (WasmSym::DsoHandle)
Sam Clegga0f095e2018-05-03 17:21:53 +0000801 WasmSym::DsoHandle->setVirtualAddress(DataStart);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000802
Sam Cleggbfb75342018-11-15 00:37:21 +0000803 MemAlign = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000804 for (OutputSegment *Seg : Segments) {
Sam Cleggbfb75342018-11-15 00:37:21 +0000805 MemAlign = std::max(MemAlign, Seg->Alignment);
Sam Clegg622ad042019-01-17 22:09:09 +0000806 MemoryPtr = alignTo(MemoryPtr, 1ULL << Seg->Alignment);
Sam Cleggc94d3932017-11-17 18:14:09 +0000807 Seg->StartVA = MemoryPtr;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000808 log(formatv("mem: {0,-15} offset={1,-8} size={2,-8} align={3}", Seg->Name,
809 MemoryPtr, Seg->Size, Seg->Alignment));
Sam Cleggc94d3932017-11-17 18:14:09 +0000810 MemoryPtr += Seg->Size;
811 }
812
Sam Cleggf0d433d2018-02-02 22:59:56 +0000813 // TODO: Add .bss space here.
Sam Clegg37a4a8a2018-02-07 03:04:53 +0000814 if (WasmSym::DataEnd)
815 WasmSym::DataEnd->setVirtualAddress(MemoryPtr);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000816
Sam Clegga0f095e2018-05-03 17:21:53 +0000817 log("mem: static data = " + Twine(MemoryPtr - DataStart));
Sam Cleggc94d3932017-11-17 18:14:09 +0000818
Sam Clegg2dad4e22018-11-15 18:15:54 +0000819 if (Config->Shared) {
820 MemSize = MemoryPtr;
821 return;
822 }
823
Sam Clegga0f095e2018-05-03 17:21:53 +0000824 if (!Config->StackFirst)
825 PlaceStack();
826
827 // Set `__heap_base` to directly follow the end of the stack or global data.
828 // The fact that this comes last means that a malloc/brk implementation
829 // can grow the heap at runtime.
Sam Cleggc94d3932017-11-17 18:14:09 +0000830 if (!Config->Relocatable) {
Sam Cleggf0d433d2018-02-02 22:59:56 +0000831 WasmSym::HeapBase->setVirtualAddress(MemoryPtr);
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000832 log("mem: heap base = " + Twine(MemoryPtr));
Sam Cleggc94d3932017-11-17 18:14:09 +0000833 }
834
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000835 if (Config->InitialMemory != 0) {
836 if (Config->InitialMemory != alignTo(Config->InitialMemory, WasmPageSize))
837 error("initial memory must be " + Twine(WasmPageSize) + "-byte aligned");
838 if (MemoryPtr > Config->InitialMemory)
839 error("initial memory too small, " + Twine(MemoryPtr) + " bytes needed");
840 else
841 MemoryPtr = Config->InitialMemory;
842 }
Sam Cleggbfb75342018-11-15 00:37:21 +0000843 MemSize = MemoryPtr;
844 NumMemoryPages = alignTo(MemoryPtr, WasmPageSize) / WasmPageSize;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000845 log("mem: total pages = " + Twine(NumMemoryPages));
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000846
Thomas Lively06391f32019-03-29 20:43:49 +0000847 // Check max if explicitly supplied or required by shared memory
848 if (Config->MaxMemory != 0 || Config->SharedMemory) {
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000849 if (Config->MaxMemory != alignTo(Config->MaxMemory, WasmPageSize))
850 error("maximum memory must be " + Twine(WasmPageSize) + "-byte aligned");
851 if (MemoryPtr > Config->MaxMemory)
852 error("maximum memory too small, " + Twine(MemoryPtr) + " bytes needed");
853 MaxMemoryPages = Config->MaxMemory / WasmPageSize;
854 log("mem: max pages = " + Twine(MaxMemoryPages));
855 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000856}
857
858SyntheticSection *Writer::createSyntheticSection(uint32_t Type,
Sam Cleggc375e4e2018-01-10 19:18:22 +0000859 StringRef Name) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000860 auto Sec = make<SyntheticSection>(Type, Name);
Sam Cleggab2ac292017-12-20 05:14:48 +0000861 log("createSection: " + toString(*Sec));
Sam Cleggc94d3932017-11-17 18:14:09 +0000862 OutputSections.push_back(Sec);
863 return Sec;
864}
865
866void Writer::createSections() {
867 // Known sections
Sam Cleggbfb75342018-11-15 00:37:21 +0000868 if (Config->Pic)
869 createDylinkSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000870 createTypeSection();
871 createImportSection();
872 createFunctionSection();
873 createTableSection();
874 createMemorySection();
875 createGlobalSection();
Heejin Ahne915a712018-12-08 06:17:43 +0000876 createEventSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000877 createExportSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000878 createElemSection();
Thomas Lively84771e22019-04-19 23:40:36 +0000879 createDataCountSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000880 createCodeSection();
881 createDataSection();
Sam Clegg80ba4382018-04-10 16:12:49 +0000882 createCustomSections();
Sam Cleggc94d3932017-11-17 18:14:09 +0000883
884 // Custom sections
Sam Clegg99eb42c2018-02-27 23:58:03 +0000885 if (Config->Relocatable) {
Sam Clegg99eb42c2018-02-27 23:58:03 +0000886 createLinkingSection();
Nicholas Wilson94d3b162018-03-05 12:33:58 +0000887 createRelocSections();
Sam Clegg99eb42c2018-02-27 23:58:03 +0000888 }
Thomas Lively2a0868f2019-01-17 02:29:41 +0000889
Sam Cleggc94d3932017-11-17 18:14:09 +0000890 if (!Config->StripDebug && !Config->StripAll)
891 createNameSection();
892
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000893 if (!Config->StripAll) {
Thomas Lively2a0868f2019-01-17 02:29:41 +0000894 createProducersSection();
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000895 createTargetFeaturesSection();
896 }
Thomas Lively2a0868f2019-01-17 02:29:41 +0000897
Sam Cleggc94d3932017-11-17 18:14:09 +0000898 for (OutputSection *S : OutputSections) {
899 S->setOffset(FileSize);
900 S->finalizeContents();
901 FileSize += S->getSize();
902 }
903}
904
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000905void Writer::calculateTargetFeatures() {
Thomas Lively82de51a2019-03-26 04:11:05 +0000906 SmallSet<std::string, 8> Used;
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000907 SmallSet<std::string, 8> Required;
908 SmallSet<std::string, 8> Disallowed;
909
Thomas Lively82de51a2019-03-26 04:11:05 +0000910 // Only infer used features if user did not specify features
911 bool InferFeatures = !Config->Features.hasValue();
912
913 if (!InferFeatures) {
914 for (auto &Feature : Config->Features.getValue())
915 TargetFeatures.insert(Feature);
916 // No need to read or check features
917 if (!Config->CheckFeatures)
918 return;
919 }
920
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000921 // Find the sets of used, required, and disallowed features
922 for (ObjFile *File : Symtab->ObjectFiles) {
923 for (auto &Feature : File->getWasmObj()->getTargetFeatures()) {
924 switch (Feature.Prefix) {
925 case WASM_FEATURE_PREFIX_USED:
Thomas Lively82de51a2019-03-26 04:11:05 +0000926 Used.insert(Feature.Name);
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000927 break;
928 case WASM_FEATURE_PREFIX_REQUIRED:
Thomas Lively82de51a2019-03-26 04:11:05 +0000929 Used.insert(Feature.Name);
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000930 Required.insert(Feature.Name);
931 break;
932 case WASM_FEATURE_PREFIX_DISALLOWED:
933 Disallowed.insert(Feature.Name);
934 break;
935 default:
936 error("Unrecognized feature policy prefix " +
937 std::to_string(Feature.Prefix));
938 }
939 }
940 }
941
Thomas Lively82de51a2019-03-26 04:11:05 +0000942 if (InferFeatures)
943 TargetFeatures.insert(Used.begin(), Used.end());
944
Thomas Lively06391f32019-03-29 20:43:49 +0000945 if (TargetFeatures.count("atomics") && !Config->SharedMemory)
946 error("'atomics' feature is used, so --shared-memory must be used");
947
Thomas Lively82de51a2019-03-26 04:11:05 +0000948 if (!Config->CheckFeatures)
949 return;
950
Thomas Lively06391f32019-03-29 20:43:49 +0000951 if (Disallowed.count("atomics") && Config->SharedMemory)
952 error(
953 "'atomics' feature is disallowed, so --shared-memory must not be used");
954
Thomas Lively82de51a2019-03-26 04:11:05 +0000955 // Validate that used features are allowed in output
956 if (!InferFeatures) {
957 for (auto &Feature : Used) {
958 if (!TargetFeatures.count(Feature))
959 error(Twine("Target feature '") + Feature + "' is not allowed.");
960 }
961 }
962
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000963 // Validate the required and disallowed constraints for each file
964 for (ObjFile *File : Symtab->ObjectFiles) {
965 SmallSet<std::string, 8> ObjectFeatures;
966 for (auto &Feature : File->getWasmObj()->getTargetFeatures()) {
967 if (Feature.Prefix == WASM_FEATURE_PREFIX_DISALLOWED)
968 continue;
969 ObjectFeatures.insert(Feature.Name);
970 if (Disallowed.count(Feature.Name))
Thomas Lively82de51a2019-03-26 04:11:05 +0000971 error(Twine("Target feature '") + Feature.Name +
972 "' is disallowed. Use --no-check-features to suppress.");
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000973 }
974 for (auto &Feature : Required) {
975 if (!ObjectFeatures.count(Feature))
Thomas Lively82de51a2019-03-26 04:11:05 +0000976 error(Twine("Missing required target feature '") + Feature +
977 "'. Use --no-check-features to suppress.");
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000978 }
979 }
980}
981
Sam Cleggc94d3932017-11-17 18:14:09 +0000982void Writer::calculateImports() {
Sam Clegg574d7ce2017-12-15 19:23:49 +0000983 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000984 if (!Sym->isUndefined())
985 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000986 if (Sym->isWeak() && !Config->Relocatable)
Sam Clegg574d7ce2017-12-15 19:23:49 +0000987 continue;
Nicholas Wilsona1e299f2018-04-20 17:18:06 +0000988 if (!Sym->isLive())
989 continue;
Sam Cleggc729c1b2018-05-30 18:07:52 +0000990 if (!Sym->IsUsedInRegularObj)
991 continue;
Sam Clegg492f7522019-03-26 19:46:15 +0000992 // We don't generate imports for data symbols. They however can be imported
993 // as GOT entries.
994 if (isa<DataSymbol>(Sym))
Sam Cleggd425d6b2019-03-12 21:53:23 +0000995 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000996
Nicola Zaghene7245b42018-05-15 13:36:20 +0000997 LLVM_DEBUG(dbgs() << "import: " << Sym->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000998 ImportedSymbols.emplace_back(Sym);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000999 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
1000 F->setFunctionIndex(NumImportedFunctions++);
Heejin Ahne915a712018-12-08 06:17:43 +00001001 else if (auto *G = dyn_cast<GlobalSymbol>(Sym))
1002 G->setGlobalIndex(NumImportedGlobals++);
Sam Clegg93102972018-02-23 05:08:53 +00001003 else
Heejin Ahne915a712018-12-08 06:17:43 +00001004 cast<EventSymbol>(Sym)->setEventIndex(NumImportedEvents++);
Sam Cleggc94d3932017-11-17 18:14:09 +00001005 }
1006}
1007
Sam Cleggd3052d52018-01-18 23:40:49 +00001008void Writer::calculateExports() {
Sam Clegg93102972018-02-23 05:08:53 +00001009 if (Config->Relocatable)
1010 return;
Sam Cleggf0d433d2018-02-02 22:59:56 +00001011
Sam Cleggd6beb322018-05-10 18:10:34 +00001012 if (!Config->Relocatable && !Config->ImportMemory)
1013 Exports.push_back(WasmExport{"memory", WASM_EXTERNAL_MEMORY, 0});
1014
1015 if (!Config->Relocatable && Config->ExportTable)
Heejin Ahna1cc4ea2019-02-04 19:13:46 +00001016 Exports.push_back(WasmExport{FunctionTableName, WASM_EXTERNAL_TABLE, 0});
Sam Cleggd6beb322018-05-10 18:10:34 +00001017
1018 unsigned FakeGlobalIndex = NumImportedGlobals + InputGlobals.size();
1019
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +00001020 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Cleggce004bf2018-06-28 17:04:58 +00001021 if (!Sym->isExported())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +00001022 continue;
Sam Clegg93102972018-02-23 05:08:53 +00001023 if (!Sym->isLive())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +00001024 continue;
Sam Clegg93102972018-02-23 05:08:53 +00001025
Sam Cleggd6beb322018-05-10 18:10:34 +00001026 StringRef Name = Sym->getName();
1027 WasmExport Export;
1028 if (auto *F = dyn_cast<DefinedFunction>(Sym)) {
1029 Export = {Name, WASM_EXTERNAL_FUNCTION, F->getFunctionIndex()};
1030 } else if (auto *G = dyn_cast<DefinedGlobal>(Sym)) {
Sam Clegg177b4582018-06-07 01:27:07 +00001031 // TODO(sbc): Remove this check once to mutable global proposal is
1032 // implement in all major browsers.
1033 // See: https://github.com/WebAssembly/mutable-global
1034 if (G->getGlobalType()->Mutable) {
1035 // Only the __stack_pointer should ever be create as mutable.
1036 assert(G == WasmSym::StackPointer);
1037 continue;
1038 }
Sam Cleggd6beb322018-05-10 18:10:34 +00001039 Export = {Name, WASM_EXTERNAL_GLOBAL, G->getGlobalIndex()};
Heejin Ahne915a712018-12-08 06:17:43 +00001040 } else if (auto *E = dyn_cast<DefinedEvent>(Sym)) {
1041 Export = {Name, WASM_EXTERNAL_EVENT, E->getEventIndex()};
Sam Cleggd6beb322018-05-10 18:10:34 +00001042 } else {
1043 auto *D = cast<DefinedData>(Sym);
Sam Clegg93102972018-02-23 05:08:53 +00001044 DefinedFakeGlobals.emplace_back(D);
Sam Cleggd6beb322018-05-10 18:10:34 +00001045 Export = {Name, WASM_EXTERNAL_GLOBAL, FakeGlobalIndex++};
1046 }
1047
Nicola Zaghene7245b42018-05-15 13:36:20 +00001048 LLVM_DEBUG(dbgs() << "Export: " << Name << "\n");
Sam Cleggd6beb322018-05-10 18:10:34 +00001049 Exports.push_back(Export);
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +00001050 }
Sam Clegg93102972018-02-23 05:08:53 +00001051}
1052
1053void Writer::assignSymtab() {
1054 if (!Config->Relocatable)
1055 return;
1056
Sam Cleggd177ab22018-05-04 23:14:42 +00001057 StringMap<uint32_t> SectionSymbolIndices;
1058
Sam Clegg93102972018-02-23 05:08:53 +00001059 unsigned SymbolIndex = SymtabEntries.size();
Sam Cleggd177ab22018-05-04 23:14:42 +00001060
Sam Clegg89e4dcb2019-01-30 18:55:15 +00001061 auto AddSymbol = [&](Symbol *Sym) {
1062 if (auto *S = dyn_cast<SectionSymbol>(Sym)) {
1063 StringRef Name = S->getName();
1064 if (CustomSectionMapping.count(Name) == 0)
1065 return;
Sam Cleggd177ab22018-05-04 23:14:42 +00001066
Sam Clegg89e4dcb2019-01-30 18:55:15 +00001067 auto SSI = SectionSymbolIndices.find(Name);
1068 if (SSI != SectionSymbolIndices.end()) {
1069 Sym->setOutputSymbolIndex(SSI->second);
1070 return;
Sam Cleggd177ab22018-05-04 23:14:42 +00001071 }
1072
Sam Clegg89e4dcb2019-01-30 18:55:15 +00001073 SectionSymbolIndices[Name] = SymbolIndex;
1074 CustomSectionSymbols[Name] = cast<SectionSymbol>(Sym);
Sam Cleggd3052d52018-01-18 23:40:49 +00001075
Sam Clegg89e4dcb2019-01-30 18:55:15 +00001076 Sym->markLive();
1077 }
1078
1079 // (Since this is relocatable output, GC is not performed so symbols must
1080 // be live.)
1081 assert(Sym->isLive());
1082 Sym->setOutputSymbolIndex(SymbolIndex++);
1083 SymtabEntries.emplace_back(Sym);
1084 };
1085
1086 for (Symbol *Sym : Symtab->getSymbols())
Sam Cleggd15a41542019-03-08 21:10:48 +00001087 if (Sym->IsUsedInRegularObj)
Sam Clegg89e4dcb2019-01-30 18:55:15 +00001088 AddSymbol(Sym);
1089
1090 for (ObjFile *File : Symtab->ObjectFiles) {
1091 LLVM_DEBUG(dbgs() << "Local symtab entries: " << File->getName() << "\n");
1092 for (Symbol *Sym : File->getSymbols())
1093 if (Sym->isLocal())
1094 AddSymbol(Sym);
1095 }
Sam Cleggd3052d52018-01-18 23:40:49 +00001096}
1097
Sam Cleggc375e4e2018-01-10 19:18:22 +00001098uint32_t Writer::lookupType(const WasmSignature &Sig) {
Sam Clegg8d027d62018-01-10 20:12:26 +00001099 auto It = TypeIndices.find(Sig);
1100 if (It == TypeIndices.end()) {
Sam Cleggc375e4e2018-01-10 19:18:22 +00001101 error("type not found: " + toString(Sig));
Sam Clegg8d027d62018-01-10 20:12:26 +00001102 return 0;
1103 }
1104 return It->second;
Sam Cleggc375e4e2018-01-10 19:18:22 +00001105}
1106
1107uint32_t Writer::registerType(const WasmSignature &Sig) {
Sam Cleggb8621592017-11-30 01:40:08 +00001108 auto Pair = TypeIndices.insert(std::make_pair(Sig, Types.size()));
Sam Cleggc375e4e2018-01-10 19:18:22 +00001109 if (Pair.second) {
Nicola Zaghene7245b42018-05-15 13:36:20 +00001110 LLVM_DEBUG(dbgs() << "type " << toString(Sig) << "\n");
Sam Cleggb8621592017-11-30 01:40:08 +00001111 Types.push_back(&Sig);
Sam Cleggc375e4e2018-01-10 19:18:22 +00001112 }
Sam Cleggb8621592017-11-30 01:40:08 +00001113 return Pair.first->second;
1114}
1115
Sam Cleggc94d3932017-11-17 18:14:09 +00001116void Writer::calculateTypes() {
Sam Clegg8f6d2de2018-01-31 23:48:14 +00001117 // The output type section is the union of the following sets:
1118 // 1. Any signature used in the TYPE relocation
1119 // 2. The signatures of all imported functions
1120 // 3. The signatures of all defined functions
Heejin Ahne915a712018-12-08 06:17:43 +00001121 // 4. The signatures of all imported events
1122 // 5. The signatures of all defined events
Sam Clegg8f6d2de2018-01-31 23:48:14 +00001123
Sam Cleggc94d3932017-11-17 18:14:09 +00001124 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +00001125 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
1126 for (uint32_t I = 0; I < Types.size(); I++)
1127 if (File->TypeIsUsed[I])
1128 File->TypeMap[I] = registerType(Types[I]);
Sam Cleggc94d3932017-11-17 18:14:09 +00001129 }
Sam Clegg50686852018-01-12 18:35:13 +00001130
Heejin Ahne915a712018-12-08 06:17:43 +00001131 for (const Symbol *Sym : ImportedSymbols) {
Sam Clegg93102972018-02-23 05:08:53 +00001132 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
Heejin Ahne915a712018-12-08 06:17:43 +00001133 registerType(*F->Signature);
1134 else if (auto *E = dyn_cast<EventSymbol>(Sym))
1135 registerType(*E->Signature);
1136 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +00001137
Sam Clegg9f934222018-02-21 18:29:23 +00001138 for (const InputFunction *F : InputFunctions)
Sam Clegg8f6d2de2018-01-31 23:48:14 +00001139 registerType(F->Signature);
Heejin Ahne915a712018-12-08 06:17:43 +00001140
1141 for (const InputEvent *E : InputEvents)
1142 registerType(E->Signature);
Sam Cleggc94d3932017-11-17 18:14:09 +00001143}
1144
Sam Cleggea38ac52019-05-10 01:52:08 +00001145static bool requiresGOTAccess(const Symbol* Sym) {
1146 return Config->Pic && !Sym->isHidden() && !Sym->isLocal();
1147}
1148
Sam Clegg632c21792019-03-16 01:18:12 +00001149void Writer::processRelocations(InputChunk *Chunk) {
1150 if (!Chunk->Live)
1151 return;
1152 ObjFile *File = Chunk->File;
1153 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
1154 for (const WasmRelocation &Reloc : Chunk->getRelocations()) {
1155 switch (Reloc.Type) {
1156 case R_WASM_TABLE_INDEX_I32:
Sam Clegga116d912019-04-05 00:35:12 +00001157 case R_WASM_TABLE_INDEX_SLEB:
1158 case R_WASM_TABLE_INDEX_REL_SLEB: {
Sam Clegg08fa01a2019-05-09 19:34:32 +00001159 FunctionSymbol *Sym = File->getFunctionSymbol(Reloc.Index);
Sam Cleggea38ac52019-05-10 01:52:08 +00001160 if (Sym->hasTableIndex() || !Sym->hasFunctionIndex() || requiresGOTAccess(Sym))
1161 break;
Sam Clegg08fa01a2019-05-09 19:34:32 +00001162 Sym->setTableIndex(TableBase + IndirectFunctions.size());
1163 IndirectFunctions.emplace_back(Sym);
Sam Clegg632c21792019-03-16 01:18:12 +00001164 break;
1165 }
1166 case R_WASM_TYPE_INDEX_LEB:
Sam Clegg08fa01a2019-05-09 19:34:32 +00001167 // Mark target type as live
1168 File->TypeMap[Reloc.Index] = registerType(Types[Reloc.Index]);
1169 File->TypeIsUsed[Reloc.Index] = true;
Sam Clegg632c21792019-03-16 01:18:12 +00001170 break;
Sam Clegg08fa01a2019-05-09 19:34:32 +00001171 case R_WASM_GLOBAL_INDEX_LEB: {
1172 auto* Sym = File->getSymbols()[Reloc.Index];
Sam Clegg492f7522019-03-26 19:46:15 +00001173 if (!isa<GlobalSymbol>(Sym) && !Sym->isInGOT()) {
1174 Sym->setGOTIndex(NumImportedGlobals++);
1175 GOTSymbols.push_back(Sym);
1176 }
Sam Clegg7cdec272019-04-22 16:12:54 +00001177 break;
Sam Clegg08fa01a2019-05-09 19:34:32 +00001178 }
Sam Clegg7cdec272019-04-22 16:12:54 +00001179 case R_WASM_MEMORY_ADDR_SLEB:
1180 case R_WASM_MEMORY_ADDR_LEB:
Sam Clegg08fa01a2019-05-09 19:34:32 +00001181 case R_WASM_MEMORY_ADDR_REL_SLEB: {
Sam Clegg7cdec272019-04-22 16:12:54 +00001182 if (!Config->Relocatable) {
Sam Clegg08fa01a2019-05-09 19:34:32 +00001183 auto* Sym = File->getSymbols()[Reloc.Index];
Sam Clegg7cdec272019-04-22 16:12:54 +00001184 if (Sym->isUndefined() && !Sym->isWeak()) {
1185 error(toString(File) + ": cannot resolve relocation of type " +
1186 relocTypeToString(Reloc.Type) +
1187 " against undefined (non-weak) data symbol: " + toString(*Sym));
1188 }
1189 }
1190 break;
Sam Clegg492f7522019-03-26 19:46:15 +00001191 }
Sam Clegg08fa01a2019-05-09 19:34:32 +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 Clegg08fa01a2019-05-09 19:34:32 +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 Clegg08fa01a2019-05-09 19:34:32 +00001201 Symbol *Sym = File->getSymbols()[Reloc.Index];
Sam Clegg09137be2019-04-04 18:40:51 +00001202 error(toString(File) + ": relocation " +
1203 relocTypeToString(Reloc.Type) + " cannot be used againt symbol " +
1204 toString(*Sym) + "; recompile with -fPIC");
1205 break;
Sam Clegg08fa01a2019-05-09 19:34:32 +00001206 }
Sam Clegg0d9f6092019-04-10 15:06:17 +00001207 case R_WASM_TABLE_INDEX_I32:
Sam Clegg08fa01a2019-05-09 19:34:32 +00001208 case R_WASM_MEMORY_ADDR_I32: {
Sam Clegg0d9f6092019-04-10 15:06:17 +00001209 // These relocation types are only present in the data section and
1210 // will be converted into code by `generateRelocationCode`. This code
1211 // requires the symbols to have GOT entires.
Sam Clegg08fa01a2019-05-09 19:34:32 +00001212 auto* Sym = File->getSymbols()[Reloc.Index];
Sam Cleggea38ac52019-05-10 01:52:08 +00001213 if (requiresGOTAccess(Sym) && !Sym->isInGOT()) {
Sam Clegg0d9f6092019-04-10 15:06:17 +00001214 Sym->setGOTIndex(NumImportedGlobals++);
1215 GOTSymbols.push_back(Sym);
1216 }
1217 break;
1218 }
Sam Clegg08fa01a2019-05-09 19:34:32 +00001219 }
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(); }