blob: 83ac9a44dc4c84d1cf08028188153739351bb162 [file] [log] [blame]
Dan Gohman18eafb62017-02-22 01:23:18 +00001//===- lib/MC/WasmObjectWriter.cpp - Wasm File Writer ---------------------===//
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
Dan Gohman18eafb62017-02-22 01:23:18 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements Wasm object file writer information.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/ADT/STLExtras.h"
14#include "llvm/ADT/SmallPtrSet.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000015#include "llvm/BinaryFormat/Wasm.h"
Nico Weber432a3882018-04-30 14:59:11 +000016#include "llvm/Config/llvm-config.h"
Dan Gohman18eafb62017-02-22 01:23:18 +000017#include "llvm/MC/MCAsmBackend.h"
Dan Gohman18eafb62017-02-22 01:23:18 +000018#include "llvm/MC/MCAsmLayout.h"
19#include "llvm/MC/MCAssembler.h"
20#include "llvm/MC/MCContext.h"
21#include "llvm/MC/MCExpr.h"
22#include "llvm/MC/MCFixupKindInfo.h"
Dan Gohman18eafb62017-02-22 01:23:18 +000023#include "llvm/MC/MCObjectWriter.h"
24#include "llvm/MC/MCSectionWasm.h"
25#include "llvm/MC/MCSymbolWasm.h"
26#include "llvm/MC/MCValue.h"
27#include "llvm/MC/MCWasmObjectWriter.h"
Dan Gohmand934cb82017-02-24 23:18:00 +000028#include "llvm/Support/Casting.h"
Dan Gohman18eafb62017-02-22 01:23:18 +000029#include "llvm/Support/Debug.h"
Dan Gohman18eafb62017-02-22 01:23:18 +000030#include "llvm/Support/ErrorHandling.h"
Dan Gohmand934cb82017-02-24 23:18:00 +000031#include "llvm/Support/LEB128.h"
Dan Gohman18eafb62017-02-22 01:23:18 +000032#include "llvm/Support/StringSaver.h"
33#include <vector>
34
35using namespace llvm;
36
Sam Clegg5e3d33a2017-07-07 02:01:29 +000037#define DEBUG_TYPE "mc"
Dan Gohman18eafb62017-02-22 01:23:18 +000038
39namespace {
Sam Clegg9e15f352017-06-03 02:01:24 +000040
Sam Clegg30e1bbc2018-01-19 18:57:01 +000041// Went we ceate the indirect function table we start at 1, so that there is
42// and emtpy slot at 0 and therefore calling a null function pointer will trap.
43static const uint32_t kInitialTableOffset = 1;
44
Dan Gohmand934cb82017-02-24 23:18:00 +000045// For patching purposes, we need to remember where each section starts, both
46// for patching up the section size field, and for patching up references to
47// locations within the section.
48struct SectionBookkeeping {
49 // Where the size of the section is written.
50 uint64_t SizeOffset;
Sam Clegg6a31a0d2018-04-26 19:27:28 +000051 // Where the section header ends (without custom section name).
52 uint64_t PayloadOffset;
53 // Where the contents of the section starts.
Dan Gohmand934cb82017-02-24 23:18:00 +000054 uint64_t ContentsOffset;
Sam Clegg6f08c842018-04-24 18:11:36 +000055 uint32_t Index;
Dan Gohmand934cb82017-02-24 23:18:00 +000056};
57
Heejin Ahnda419bd2018-11-14 02:46:21 +000058// The signature of a wasm function or event, in a struct capable of being used
59// as a DenseMap key.
60// TODO: Consider using wasm::WasmSignature directly instead.
61struct WasmSignature {
Sam Clegg9e15f352017-06-03 02:01:24 +000062 // Support empty and tombstone instances, needed by DenseMap.
63 enum { Plain, Empty, Tombstone } State;
64
65 // The return types of the function.
66 SmallVector<wasm::ValType, 1> Returns;
67
68 // The parameter types of the function.
69 SmallVector<wasm::ValType, 4> Params;
70
Heejin Ahnda419bd2018-11-14 02:46:21 +000071 WasmSignature() : State(Plain) {}
Sam Clegg9e15f352017-06-03 02:01:24 +000072
Heejin Ahnda419bd2018-11-14 02:46:21 +000073 bool operator==(const WasmSignature &Other) const {
Sam Clegg9e15f352017-06-03 02:01:24 +000074 return State == Other.State && Returns == Other.Returns &&
75 Params == Other.Params;
76 }
77};
78
Heejin Ahnda419bd2018-11-14 02:46:21 +000079// Traits for using WasmSignature in a DenseMap.
80struct WasmSignatureDenseMapInfo {
81 static WasmSignature getEmptyKey() {
82 WasmSignature Sig;
83 Sig.State = WasmSignature::Empty;
84 return Sig;
Sam Clegg9e15f352017-06-03 02:01:24 +000085 }
Heejin Ahnda419bd2018-11-14 02:46:21 +000086 static WasmSignature getTombstoneKey() {
87 WasmSignature Sig;
88 Sig.State = WasmSignature::Tombstone;
89 return Sig;
Sam Clegg9e15f352017-06-03 02:01:24 +000090 }
Heejin Ahnda419bd2018-11-14 02:46:21 +000091 static unsigned getHashValue(const WasmSignature &Sig) {
92 uintptr_t Value = Sig.State;
93 for (wasm::ValType Ret : Sig.Returns)
Heejin Ahn48089142018-11-02 19:25:09 +000094 Value += DenseMapInfo<uint32_t>::getHashValue(uint32_t(Ret));
Heejin Ahnda419bd2018-11-14 02:46:21 +000095 for (wasm::ValType Param : Sig.Params)
Heejin Ahn48089142018-11-02 19:25:09 +000096 Value += DenseMapInfo<uint32_t>::getHashValue(uint32_t(Param));
Sam Clegg9e15f352017-06-03 02:01:24 +000097 return Value;
98 }
Heejin Ahnda419bd2018-11-14 02:46:21 +000099 static bool isEqual(const WasmSignature &LHS, const WasmSignature &RHS) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000100 return LHS == RHS;
101 }
102};
103
Sam Clegg7c395942017-09-14 23:07:53 +0000104// A wasm data segment. A wasm binary contains only a single data section
105// but that can contain many segments, each with their own virtual location
106// in memory. Each MCSection data created by llvm is modeled as its own
107// wasm data segment.
108struct WasmDataSegment {
109 MCSectionWasm *Section;
Sam Cleggd95ed952017-09-20 19:03:35 +0000110 StringRef Name;
Sam Clegg7c395942017-09-14 23:07:53 +0000111 uint32_t Offset;
Sam Clegg63ebb812017-09-29 16:50:08 +0000112 uint32_t Alignment;
113 uint32_t Flags;
Sam Clegg7c395942017-09-14 23:07:53 +0000114 SmallVector<char, 4> Data;
115};
116
Sam Clegg9e15f352017-06-03 02:01:24 +0000117// A wasm function to be written into the function section.
118struct WasmFunction {
Heejin Ahnda419bd2018-11-14 02:46:21 +0000119 uint32_t SigIndex;
Sam Clegg9e15f352017-06-03 02:01:24 +0000120 const MCSymbolWasm *Sym;
121};
122
Sam Clegg9e15f352017-06-03 02:01:24 +0000123// A wasm global to be written into the global section.
124struct WasmGlobal {
Sam Clegg6e7f1822018-01-31 19:50:14 +0000125 wasm::WasmGlobalType Type;
Sam Clegg9e15f352017-06-03 02:01:24 +0000126 uint64_t InitialValue;
Sam Clegg9e15f352017-06-03 02:01:24 +0000127};
128
Sam Cleggea7cace2018-01-09 23:43:14 +0000129// Information about a single item which is part of a COMDAT. For each data
130// segment or function which is in the COMDAT, there is a corresponding
131// WasmComdatEntry.
132struct WasmComdatEntry {
133 unsigned Kind;
134 uint32_t Index;
135};
136
Sam Clegg6dc65e92017-06-06 16:38:59 +0000137// Information about a single relocation.
138struct WasmRelocationEntry {
Heejin Ahnf208f632018-09-05 01:27:38 +0000139 uint64_t Offset; // Where is the relocation.
140 const MCSymbolWasm *Symbol; // The symbol to relocate with.
141 int64_t Addend; // A value to add to the symbol.
142 unsigned Type; // The type of the relocation.
143 const MCSectionWasm *FixupSection; // The section the relocation is targeting.
Sam Clegg6dc65e92017-06-06 16:38:59 +0000144
145 WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
146 int64_t Addend, unsigned Type,
Sam Cleggfe6414b2017-06-21 23:46:41 +0000147 const MCSectionWasm *FixupSection)
Sam Clegg6dc65e92017-06-06 16:38:59 +0000148 : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
149 FixupSection(FixupSection) {}
150
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000151 bool hasAddend() const {
152 switch (Type) {
Sam Clegg13a2e892017-09-01 17:32:01 +0000153 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
154 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
155 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000156 case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32:
157 case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32:
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000158 return true;
159 default:
160 return false;
161 }
162 }
163
Sam Clegg6dc65e92017-06-06 16:38:59 +0000164 void print(raw_ostream &Out) const {
Heejin Ahnf208f632018-09-05 01:27:38 +0000165 Out << wasm::relocTypetoString(Type) << " Off=" << Offset
166 << ", Sym=" << *Symbol << ", Addend=" << Addend
Sam Clegg759631c2017-09-15 20:54:59 +0000167 << ", FixupSection=" << FixupSection->getSectionName();
Sam Clegg6dc65e92017-06-06 16:38:59 +0000168 }
Sam Cleggb7787fd2017-06-20 04:04:59 +0000169
Aaron Ballman615eb472017-10-15 14:32:27 +0000170#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Sam Cleggb7787fd2017-06-20 04:04:59 +0000171 LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
172#endif
Sam Clegg6dc65e92017-06-06 16:38:59 +0000173};
174
Sam Clegg25d8e682018-05-08 00:08:21 +0000175static const uint32_t INVALID_INDEX = -1;
176
Sam Cleggcfd44a22018-04-05 17:01:39 +0000177struct WasmCustomSection {
Sam Cleggcfd44a22018-04-05 17:01:39 +0000178
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000179 StringRef Name;
180 MCSectionWasm *Section;
181
182 uint32_t OutputContentsOffset;
183 uint32_t OutputIndex;
184
185 WasmCustomSection(StringRef Name, MCSectionWasm *Section)
186 : Name(Name), Section(Section), OutputContentsOffset(0),
187 OutputIndex(INVALID_INDEX) {}
Sam Cleggcfd44a22018-04-05 17:01:39 +0000188};
189
Sam Clegg1fb8daa2017-06-20 05:05:10 +0000190#if !defined(NDEBUG)
Sam Clegg7f055de2017-06-20 04:47:58 +0000191raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000192 Rel.print(OS);
193 return OS;
194}
Sam Clegg1fb8daa2017-06-20 05:05:10 +0000195#endif
Sam Cleggb7787fd2017-06-20 04:04:59 +0000196
Sam Clegg19e8bef2019-01-30 22:47:35 +0000197// Write X as an (unsigned) LEB value at offset Offset in Stream, padded
198// to allow patching.
199static void WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X,
200 uint64_t Offset) {
201 uint8_t Buffer[5];
202 unsigned SizeLen = encodeULEB128(X, Buffer, 5);
203 assert(SizeLen == 5);
204 Stream.pwrite((char *)Buffer, SizeLen, Offset);
205}
206
207// Write X as an signed LEB value at offset Offset in Stream, padded
208// to allow patching.
209static void WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X,
210 uint64_t Offset) {
211 uint8_t Buffer[5];
212 unsigned SizeLen = encodeSLEB128(X, Buffer, 5);
213 assert(SizeLen == 5);
214 Stream.pwrite((char *)Buffer, SizeLen, Offset);
215}
216
217// Write X as a plain integer value at offset Offset in Stream.
218static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
219 uint8_t Buffer[4];
220 support::endian::write32le(Buffer, X);
221 Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
222}
223
Dan Gohman18eafb62017-02-22 01:23:18 +0000224class WasmObjectWriter : public MCObjectWriter {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000225 support::endian::Writer W;
226
Dan Gohman18eafb62017-02-22 01:23:18 +0000227 /// The target specific Wasm writer instance.
228 std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
229
Dan Gohmand934cb82017-02-24 23:18:00 +0000230 // Relocations for fixing up references in the code section.
231 std::vector<WasmRelocationEntry> CodeRelocations;
Sam Clegg6f08c842018-04-24 18:11:36 +0000232 uint32_t CodeSectionIndex;
Dan Gohmand934cb82017-02-24 23:18:00 +0000233
234 // Relocations for fixing up references in the data section.
235 std::vector<WasmRelocationEntry> DataRelocations;
Sam Clegg6f08c842018-04-24 18:11:36 +0000236 uint32_t DataSectionIndex;
Dan Gohmand934cb82017-02-24 23:18:00 +0000237
Dan Gohmand934cb82017-02-24 23:18:00 +0000238 // Index values to use for fixing up call_indirect type indices.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000239 // Maps function symbols to the index of the type of the function
240 DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
Sam Cleggd99f6072017-06-12 23:52:44 +0000241 // Maps function symbols to the table element index space. Used
242 // for TABLE_INDEX relocation types (i.e. address taken functions).
Sam Cleggf9edbe92018-01-31 19:28:47 +0000243 DenseMap<const MCSymbolWasm *, uint32_t> TableIndices;
Heejin Ahnda419bd2018-11-14 02:46:21 +0000244 // Maps function/global symbols to the function/global/event/section index
245 // space.
Sam Clegg6c899ba2018-02-23 05:08:34 +0000246 DenseMap<const MCSymbolWasm *, uint32_t> WasmIndices;
247 // Maps data symbols to the Wasm segment and offset/size with the segment.
248 DenseMap<const MCSymbolWasm *, wasm::WasmDataReference> DataLocations;
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000249
250 // Stores output data (index, relocations, content offset) for custom
251 // section.
252 std::vector<WasmCustomSection> CustomSections;
Thomas Livelycbda16e2019-01-17 02:29:55 +0000253 std::unique_ptr<WasmCustomSection> ProducersSection;
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000254 // Relocations for fixing up references in the custom sections.
255 DenseMap<const MCSectionWasm *, std::vector<WasmRelocationEntry>>
256 CustomSectionsRelocations;
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000257
Sam Cleggc0d41192018-05-17 17:15:15 +0000258 // Map from section to defining function symbol.
Sam Clegg6ccb59b2018-05-16 20:09:05 +0000259 DenseMap<const MCSection *, const MCSymbol *> SectionFunctions;
260
Heejin Ahnda419bd2018-11-14 02:46:21 +0000261 DenseMap<WasmSignature, uint32_t, WasmSignatureDenseMapInfo> SignatureIndices;
262 SmallVector<WasmSignature, 4> Signatures;
Sam Clegg7c395942017-09-14 23:07:53 +0000263 SmallVector<WasmGlobal, 4> Globals;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000264 SmallVector<WasmDataSegment, 4> DataSegments;
Sam Clegg9f3fe422018-01-17 19:28:43 +0000265 unsigned NumFunctionImports = 0;
Sam Clegg7c395942017-09-14 23:07:53 +0000266 unsigned NumGlobalImports = 0;
Heejin Ahnda419bd2018-11-14 02:46:21 +0000267 unsigned NumEventImports = 0;
Chandler Carruth7e1c3342018-04-24 20:30:56 +0000268 uint32_t SectionCount = 0;
Dan Gohmand934cb82017-02-24 23:18:00 +0000269
Dan Gohman18eafb62017-02-22 01:23:18 +0000270 // TargetObjectWriter wrappers.
271 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
Sam Cleggae03c1e72017-06-13 18:51:50 +0000272 unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup) const {
273 return TargetObjectWriter->getRelocType(Target, Fixup);
Dan Gohman18eafb62017-02-22 01:23:18 +0000274 }
275
Sam Clegg2322a932018-04-23 19:16:19 +0000276 void startSection(SectionBookkeeping &Section, unsigned SectionId);
277 void startCustomSection(SectionBookkeeping &Section, StringRef Name);
Dan Gohmand934cb82017-02-24 23:18:00 +0000278 void endSection(SectionBookkeeping &Section);
279
Dan Gohman18eafb62017-02-22 01:23:18 +0000280public:
Lang Hames1301a872017-10-10 01:15:10 +0000281 WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
282 raw_pwrite_stream &OS)
Peter Collingbourne59a6fc42018-05-21 18:28:57 +0000283 : W(OS, support::little), TargetObjectWriter(std::move(MOTW)) {}
Dan Gohman18eafb62017-02-22 01:23:18 +0000284
Dan Gohman18eafb62017-02-22 01:23:18 +0000285 ~WasmObjectWriter() override;
286
Dan Gohman0917c9e2018-01-15 17:06:23 +0000287private:
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000288 void reset() override {
289 CodeRelocations.clear();
290 DataRelocations.clear();
291 TypeIndices.clear();
Sam Clegg6c899ba2018-02-23 05:08:34 +0000292 WasmIndices.clear();
Sam Cleggf9edbe92018-01-31 19:28:47 +0000293 TableIndices.clear();
Sam Clegg6c899ba2018-02-23 05:08:34 +0000294 DataLocations.clear();
Thomas Livelycbda16e2019-01-17 02:29:55 +0000295 CustomSections.clear();
296 ProducersSection.reset();
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000297 CustomSectionsRelocations.clear();
Heejin Ahnda419bd2018-11-14 02:46:21 +0000298 SignatureIndices.clear();
299 Signatures.clear();
Sam Clegg7c395942017-09-14 23:07:53 +0000300 Globals.clear();
Sam Clegg6c899ba2018-02-23 05:08:34 +0000301 DataSegments.clear();
Sam Clegg6ccb59b2018-05-16 20:09:05 +0000302 SectionFunctions.clear();
Sam Clegg9f3fe422018-01-17 19:28:43 +0000303 NumFunctionImports = 0;
Sam Clegg7c395942017-09-14 23:07:53 +0000304 NumGlobalImports = 0;
Sam Clegg105bdc22018-05-30 02:57:20 +0000305 MCObjectWriter::reset();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000306 }
307
Dan Gohman18eafb62017-02-22 01:23:18 +0000308 void writeHeader(const MCAssembler &Asm);
309
310 void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
311 const MCFragment *Fragment, const MCFixup &Fixup,
Rafael Espindolaceecfe5b2017-07-11 23:56:10 +0000312 MCValue Target, uint64_t &FixedValue) override;
Dan Gohman18eafb62017-02-22 01:23:18 +0000313
314 void executePostLayoutBinding(MCAssembler &Asm,
315 const MCAsmLayout &Layout) override;
316
Peter Collingbourne438390f2018-05-21 18:23:50 +0000317 uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
Sam Clegg9e15f352017-06-03 02:01:24 +0000318
Sam Cleggb7787fd2017-06-20 04:04:59 +0000319 void writeString(const StringRef Str) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000320 encodeULEB128(Str.size(), W.OS);
321 W.OS << Str;
Sam Cleggb7787fd2017-06-20 04:04:59 +0000322 }
323
Heejin Ahnf208f632018-09-05 01:27:38 +0000324 void writeValueType(wasm::ValType Ty) { W.OS << static_cast<char>(Ty); }
Sam Clegg9e15f352017-06-03 02:01:24 +0000325
Heejin Ahnda419bd2018-11-14 02:46:21 +0000326 void writeTypeSection(ArrayRef<WasmSignature> Signatures);
Sam Clegg8defa952018-02-12 22:41:29 +0000327 void writeImportSection(ArrayRef<wasm::WasmImport> Imports, uint32_t DataSize,
Sam Cleggf950b242017-12-11 23:03:38 +0000328 uint32_t NumElements);
Sam Clegg457fb0b2017-09-15 19:50:44 +0000329 void writeFunctionSection(ArrayRef<WasmFunction> Functions);
Sam Clegg7c395942017-09-14 23:07:53 +0000330 void writeGlobalSection();
Sam Clegg8defa952018-02-12 22:41:29 +0000331 void writeExportSection(ArrayRef<wasm::WasmExport> Exports);
Sam Clegg457fb0b2017-09-15 19:50:44 +0000332 void writeElemSection(ArrayRef<uint32_t> TableElems);
Sam Clegg9e15f352017-06-03 02:01:24 +0000333 void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
Sam Clegg457fb0b2017-09-15 19:50:44 +0000334 ArrayRef<WasmFunction> Functions);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000335 void writeDataSection();
Heejin Ahnda419bd2018-11-14 02:46:21 +0000336 void writeEventSection(ArrayRef<wasm::WasmEventType> Events);
Sam Clegg6f08c842018-04-24 18:11:36 +0000337 void writeRelocSection(uint32_t SectionIndex, StringRef Name,
Heejin Ahnf208f632018-09-05 01:27:38 +0000338 std::vector<WasmRelocationEntry> &Relocations);
Sam Clegg31a2c802017-09-20 21:17:04 +0000339 void writeLinkingMetaDataSection(
Sam Clegg86b4a092018-02-27 23:57:37 +0000340 ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
Sam Cleggea7cace2018-01-09 23:43:14 +0000341 ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
Sam Clegg6c899ba2018-02-23 05:08:34 +0000342 const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats);
Thomas Livelycbda16e2019-01-17 02:29:55 +0000343 void writeCustomSection(WasmCustomSection &CustomSection,
344 const MCAssembler &Asm, const MCAsmLayout &Layout);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000345 void writeCustomRelocSections();
346 void
347 updateCustomSectionRelocations(const SmallVector<WasmFunction, 4> &Functions,
348 const MCAsmLayout &Layout);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000349
Sam Clegg7c395942017-09-14 23:07:53 +0000350 uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000351 void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
352 uint64_t ContentsOffset);
353
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000354 uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
Sam Clegg6f08c842018-04-24 18:11:36 +0000355 uint32_t getFunctionType(const MCSymbolWasm &Symbol);
Heejin Ahnda419bd2018-11-14 02:46:21 +0000356 uint32_t getEventType(const MCSymbolWasm &Symbol);
Heejin Ahn38b12f52018-11-20 00:38:10 +0000357 void registerFunctionType(const MCSymbolWasm &Symbol);
358 void registerEventType(const MCSymbolWasm &Symbol);
Dan Gohman18eafb62017-02-22 01:23:18 +0000359};
Sam Clegg9e15f352017-06-03 02:01:24 +0000360
Dan Gohman18eafb62017-02-22 01:23:18 +0000361} // end anonymous namespace
362
363WasmObjectWriter::~WasmObjectWriter() {}
364
Dan Gohmand934cb82017-02-24 23:18:00 +0000365// Write out a section header and a patchable section size field.
366void WasmObjectWriter::startSection(SectionBookkeeping &Section,
Sam Clegg2322a932018-04-23 19:16:19 +0000367 unsigned SectionId) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000368 LLVM_DEBUG(dbgs() << "startSection " << SectionId << "\n");
Peter Collingbournef17b1492018-05-21 18:17:42 +0000369 W.OS << char(SectionId);
Dan Gohmand934cb82017-02-24 23:18:00 +0000370
Peter Collingbournef17b1492018-05-21 18:17:42 +0000371 Section.SizeOffset = W.OS.tell();
Dan Gohmand934cb82017-02-24 23:18:00 +0000372
373 // The section size. We don't know the size yet, so reserve enough space
374 // for any 32-bit value; we'll patch it later.
Sam Clegg19e8bef2019-01-30 22:47:35 +0000375 encodeULEB128(0, W.OS, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000376
377 // The position where the section starts, for measuring its size.
Peter Collingbournef17b1492018-05-21 18:17:42 +0000378 Section.ContentsOffset = W.OS.tell();
379 Section.PayloadOffset = W.OS.tell();
Sam Clegg6f08c842018-04-24 18:11:36 +0000380 Section.Index = SectionCount++;
Sam Clegg2322a932018-04-23 19:16:19 +0000381}
Dan Gohmand934cb82017-02-24 23:18:00 +0000382
Sam Clegg2322a932018-04-23 19:16:19 +0000383void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section,
384 StringRef Name) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000385 LLVM_DEBUG(dbgs() << "startCustomSection " << Name << "\n");
Sam Clegg2322a932018-04-23 19:16:19 +0000386 startSection(Section, wasm::WASM_SEC_CUSTOM);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000387
388 // The position where the section header ends, for measuring its size.
Peter Collingbournef17b1492018-05-21 18:17:42 +0000389 Section.PayloadOffset = W.OS.tell();
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000390
Dan Gohmand934cb82017-02-24 23:18:00 +0000391 // Custom sections in wasm also have a string identifier.
Sam Clegg2322a932018-04-23 19:16:19 +0000392 writeString(Name);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000393
394 // The position where the custom section starts.
Peter Collingbournef17b1492018-05-21 18:17:42 +0000395 Section.ContentsOffset = W.OS.tell();
Dan Gohmand934cb82017-02-24 23:18:00 +0000396}
397
398// Now that the section is complete and we know how big it is, patch up the
399// section size field at the start of the section.
400void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
Sam Cleggc0affde2019-01-31 22:38:22 +0000401 uint64_t Size = W.OS.tell();
402 // /dev/null doesn't support seek/tell and can report offset of 0.
403 // Simply skip this patching in that case.
404 if (!Size)
405 return;
406
407 Size -= Section.PayloadOffset;
Dan Gohmand934cb82017-02-24 23:18:00 +0000408 if (uint32_t(Size) != Size)
409 report_fatal_error("section size does not fit in a uint32_t");
410
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000411 LLVM_DEBUG(dbgs() << "endSection size=" << Size << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000412
413 // Write the final section size to the payload_len field, which follows
414 // the section id byte.
Sam Clegg19e8bef2019-01-30 22:47:35 +0000415 WritePatchableLEB(static_cast<raw_pwrite_stream &>(W.OS), Size,
416 Section.SizeOffset);
Dan Gohmand934cb82017-02-24 23:18:00 +0000417}
418
Dan Gohman18eafb62017-02-22 01:23:18 +0000419// Emit the Wasm header.
420void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000421 W.OS.write(wasm::WasmMagic, sizeof(wasm::WasmMagic));
422 W.write<uint32_t>(wasm::WasmVersion);
Dan Gohman18eafb62017-02-22 01:23:18 +0000423}
424
425void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
426 const MCAsmLayout &Layout) {
Sam Clegg6ccb59b2018-05-16 20:09:05 +0000427 // Build a map of sections to the function that defines them, for use
428 // in recordRelocation.
429 for (const MCSymbol &S : Asm.symbols()) {
430 const auto &WS = static_cast<const MCSymbolWasm &>(S);
431 if (WS.isDefined() && WS.isFunction() && !WS.isVariable()) {
432 const auto &Sec = static_cast<const MCSectionWasm &>(S.getSection());
433 auto Pair = SectionFunctions.insert(std::make_pair(&Sec, &S));
434 if (!Pair.second)
435 report_fatal_error("section already has a defining function: " +
436 Sec.getSectionName());
437 }
438 }
Dan Gohman18eafb62017-02-22 01:23:18 +0000439}
440
441void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
442 const MCAsmLayout &Layout,
443 const MCFragment *Fragment,
444 const MCFixup &Fixup, MCValue Target,
Rafael Espindolaceecfe5b2017-07-11 23:56:10 +0000445 uint64_t &FixedValue) {
446 MCAsmBackend &Backend = Asm.getBackend();
447 bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
448 MCFixupKindInfo::FKF_IsPCRel;
Sam Cleggfe6414b2017-06-21 23:46:41 +0000449 const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
Dan Gohmand934cb82017-02-24 23:18:00 +0000450 uint64_t C = Target.getConstant();
451 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
452 MCContext &Ctx = Asm.getContext();
453
Sam Cleggbafe6902017-12-15 00:17:10 +0000454 // The .init_array isn't translated as data, so don't do relocations in it.
455 if (FixupSection.getSectionName().startswith(".init_array"))
456 return;
457
Dan Gohmand934cb82017-02-24 23:18:00 +0000458 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
459 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
460 "Should not have constructed this");
461
462 // Let A, B and C being the components of Target and R be the location of
463 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
464 // If it is pcrel, we want to compute (A - B + C - R).
465
466 // In general, Wasm has no relocations for -B. It can only represent (A + C)
467 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
468 // replace B to implement it: (A - R - K + C)
469 if (IsPCRel) {
470 Ctx.reportError(
471 Fixup.getLoc(),
472 "No relocation available to represent this relative expression");
473 return;
474 }
475
476 const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
477
478 if (SymB.isUndefined()) {
479 Ctx.reportError(Fixup.getLoc(),
480 Twine("symbol '") + SymB.getName() +
481 "' can not be undefined in a subtraction expression");
482 return;
483 }
484
485 assert(!SymB.isAbsolute() && "Should have been folded");
486 const MCSection &SecB = SymB.getSection();
487 if (&SecB != &FixupSection) {
488 Ctx.reportError(Fixup.getLoc(),
489 "Cannot represent a difference across sections");
490 return;
491 }
492
493 uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
494 uint64_t K = SymBOffset - FixupOffset;
495 IsPCRel = true;
496 C -= K;
497 }
498
499 // We either rejected the fixup or folded B into C at this point.
500 const MCSymbolRefExpr *RefA = Target.getSymA();
501 const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
502
Dan Gohmand934cb82017-02-24 23:18:00 +0000503 if (SymA && SymA->isVariable()) {
504 const MCExpr *Expr = SymA->getVariableValue();
Sam Clegg6ad8f192017-07-11 02:21:57 +0000505 const auto *Inner = cast<MCSymbolRefExpr>(Expr);
506 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
507 llvm_unreachable("weakref used in reloc not yet implemented");
Dan Gohmand934cb82017-02-24 23:18:00 +0000508 }
509
510 // Put any constant offset in an addend. Offsets can be negative, and
511 // LLVM expects wrapping, in contrast to wasm's immediates which can't
512 // be negative and don't wrap.
513 FixedValue = 0;
514
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000515 unsigned Type = getRelocType(Target, Fixup);
Sam Cleggae03c1e72017-06-13 18:51:50 +0000516 assert(!IsPCRel);
Sam Clegg9d24fb72017-06-16 23:59:10 +0000517 assert(SymA);
518
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000519 // Absolute offset within a section or a function.
520 // Currently only supported for for metadata sections.
521 // See: test/MC/WebAssembly/blockaddress.ll
522 if (Type == wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32 ||
523 Type == wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32) {
524 if (!FixupSection.getKind().isMetadata())
525 report_fatal_error("relocations for function or section offsets are "
526 "only supported in metadata sections");
527
528 const MCSymbol *SectionSymbol = nullptr;
529 const MCSection &SecA = SymA->getSection();
530 if (SecA.getKind().isText())
Sam Clegg6ccb59b2018-05-16 20:09:05 +0000531 SectionSymbol = SectionFunctions.find(&SecA)->second;
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000532 else
533 SectionSymbol = SecA.getBeginSymbol();
534 if (!SectionSymbol)
535 report_fatal_error("section symbol is required for relocation");
536
537 C += Layout.getSymbolOffset(*SymA);
538 SymA = cast<MCSymbolWasm>(SectionSymbol);
539 }
540
541 // Relocation other than R_WEBASSEMBLY_TYPE_INDEX_LEB are required to be
542 // against a named symbol.
543 if (Type != wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) {
544 if (SymA->getName().empty())
545 report_fatal_error("relocations against un-named temporaries are not yet "
546 "supported by wasm");
547
548 SymA->setUsedInReloc();
549 }
Sam Cleggae03c1e72017-06-13 18:51:50 +0000550
Dan Gohmand934cb82017-02-24 23:18:00 +0000551 WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000552 LLVM_DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000553
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000554 if (FixupSection.isWasmData()) {
Dan Gohmand934cb82017-02-24 23:18:00 +0000555 DataRelocations.push_back(Rec);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000556 } else if (FixupSection.getKind().isText()) {
Sam Clegg12fd3da2017-10-20 21:28:38 +0000557 CodeRelocations.push_back(Rec);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000558 } else if (FixupSection.getKind().isMetadata()) {
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000559 CustomSectionsRelocations[&FixupSection].push_back(Rec);
560 } else {
Sam Clegg12fd3da2017-10-20 21:28:38 +0000561 llvm_unreachable("unexpected section type");
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000562 }
Dan Gohmand934cb82017-02-24 23:18:00 +0000563}
564
Heejin Ahnf208f632018-09-05 01:27:38 +0000565static const MCSymbolWasm *ResolveSymbol(const MCSymbolWasm &Symbol) {
Sam Cleggaff1c4d2017-09-15 19:22:01 +0000566 if (Symbol.isVariable()) {
567 const MCExpr *Expr = Symbol.getVariableValue();
568 auto *Inner = cast<MCSymbolRefExpr>(Expr);
569 return cast<MCSymbolWasm>(&Inner->getSymbol());
570 }
571 return &Symbol;
572}
573
Dan Gohmand934cb82017-02-24 23:18:00 +0000574// Compute a value to write into the code at the location covered
Sam Clegg60ec3032018-01-23 01:23:17 +0000575// by RelEntry. This value isn't used by the static linker; it just serves
576// to make the object format more readable and more likely to be directly
577// useable.
Sam Clegg7c395942017-09-14 23:07:53 +0000578uint32_t
579WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) {
Sam Clegg60ec3032018-01-23 01:23:17 +0000580 switch (RelEntry.Type) {
581 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
Sam Cleggf9edbe92018-01-31 19:28:47 +0000582 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: {
583 // Provisional value is table address of the resolved symbol itself
584 const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
585 assert(Sym->isFunction());
586 return TableIndices[Sym];
587 }
Sam Clegg60ec3032018-01-23 01:23:17 +0000588 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
Sam Clegg6c899ba2018-02-23 05:08:34 +0000589 // Provisional value is same as the index
Sam Clegg60ec3032018-01-23 01:23:17 +0000590 return getRelocationIndexValue(RelEntry);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000591 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
592 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
Heejin Ahnda419bd2018-11-14 02:46:21 +0000593 case wasm::R_WEBASSEMBLY_EVENT_INDEX_LEB:
594 // Provisional value is function/global/event Wasm index
Sam Clegg6c899ba2018-02-23 05:08:34 +0000595 if (!WasmIndices.count(RelEntry.Symbol))
596 report_fatal_error("symbol not found in wasm index space: " +
597 RelEntry.Symbol->getName());
598 return WasmIndices[RelEntry.Symbol];
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000599 case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32:
600 case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32: {
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000601 const auto &Section =
602 static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection());
603 return Section.getSectionOffset() + RelEntry.Addend;
604 }
Sam Clegg60ec3032018-01-23 01:23:17 +0000605 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
606 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
607 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: {
Sam Cleggf9edbe92018-01-31 19:28:47 +0000608 // Provisional value is address of the global
Sam Clegg60ec3032018-01-23 01:23:17 +0000609 const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
610 // For undefined symbols, use zero
611 if (!Sym->isDefined())
612 return 0;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000613 const wasm::WasmDataReference &Ref = DataLocations[Sym];
614 const WasmDataSegment &Segment = DataSegments[Ref.Segment];
Sam Clegg60ec3032018-01-23 01:23:17 +0000615 // Ignore overflow. LLVM allows address arithmetic to silently wrap.
Sam Clegg6c899ba2018-02-23 05:08:34 +0000616 return Segment.Offset + Ref.Offset + RelEntry.Addend;
Sam Clegg60ec3032018-01-23 01:23:17 +0000617 }
618 default:
619 llvm_unreachable("invalid relocation type");
620 }
Dan Gohmand934cb82017-02-24 23:18:00 +0000621}
622
Sam Clegg759631c2017-09-15 20:54:59 +0000623static void addData(SmallVectorImpl<char> &DataBytes,
Sam Clegg63ebb812017-09-29 16:50:08 +0000624 MCSectionWasm &DataSection) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000625 LLVM_DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n");
Sam Clegg759631c2017-09-15 20:54:59 +0000626
Sam Clegg63ebb812017-09-29 16:50:08 +0000627 DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
628
Sam Clegg759631c2017-09-15 20:54:59 +0000629 for (const MCFragment &Frag : DataSection) {
630 if (Frag.hasInstructions())
631 report_fatal_error("only data supported in data sections");
632
633 if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
634 if (Align->getValueSize() != 1)
635 report_fatal_error("only byte values supported for alignment");
636 // If nops are requested, use zeros, as this is the data section.
637 uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
Heejin Ahnf208f632018-09-05 01:27:38 +0000638 uint64_t Size =
639 std::min<uint64_t>(alignTo(DataBytes.size(), Align->getAlignment()),
640 DataBytes.size() + Align->getMaxBytesToEmit());
Sam Clegg759631c2017-09-15 20:54:59 +0000641 DataBytes.resize(Size, Value);
642 } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
Nirav Dave588fad42018-05-18 17:45:48 +0000643 int64_t NumValues;
644 if (!Fill->getNumValues().evaluateAsAbsolute(NumValues))
Rafael Espindolad707c372018-01-09 22:48:37 +0000645 llvm_unreachable("The fill should be an assembler constant");
Nirav Dave588fad42018-05-18 17:45:48 +0000646 DataBytes.insert(DataBytes.end(), Fill->getValueSize() * NumValues,
647 Fill->getValue());
Heejin Ahn24faf852018-10-25 23:55:10 +0000648 } else if (auto *LEB = dyn_cast<MCLEBFragment>(&Frag)) {
649 const SmallVectorImpl<char> &Contents = LEB->getContents();
650 DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
Sam Clegg759631c2017-09-15 20:54:59 +0000651 } else {
652 const auto &DataFrag = cast<MCDataFragment>(Frag);
653 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
Sam Clegg759631c2017-09-15 20:54:59 +0000654 DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
655 }
656 }
657
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000658 LLVM_DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
Sam Clegg759631c2017-09-15 20:54:59 +0000659}
660
Sam Clegg60ec3032018-01-23 01:23:17 +0000661uint32_t
662WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
663 if (RelEntry.Type == wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000664 if (!TypeIndices.count(RelEntry.Symbol))
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000665 report_fatal_error("symbol not found in type index space: " +
Sam Cleggb7787fd2017-06-20 04:04:59 +0000666 RelEntry.Symbol->getName());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000667 return TypeIndices[RelEntry.Symbol];
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000668 }
Sam Clegg60ec3032018-01-23 01:23:17 +0000669
Sam Clegg25d8e682018-05-08 00:08:21 +0000670 return RelEntry.Symbol->getIndex();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000671}
672
Dan Gohmand934cb82017-02-24 23:18:00 +0000673// Apply the portions of the relocation records that we can handle ourselves
674// directly.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000675void WasmObjectWriter::applyRelocations(
676 ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000677 auto &Stream = static_cast<raw_pwrite_stream &>(W.OS);
Dan Gohmand934cb82017-02-24 23:18:00 +0000678 for (const WasmRelocationEntry &RelEntry : Relocations) {
679 uint64_t Offset = ContentsOffset +
680 RelEntry.FixupSection->getSectionOffset() +
681 RelEntry.Offset;
Dan Gohmand934cb82017-02-24 23:18:00 +0000682
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000683 LLVM_DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
Sam Clegg60ec3032018-01-23 01:23:17 +0000684 uint32_t Value = getProvisionalValue(RelEntry);
685
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000686 switch (RelEntry.Type) {
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000687 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000688 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
Sam Clegg60ec3032018-01-23 01:23:17 +0000689 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
690 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
Heejin Ahnda419bd2018-11-14 02:46:21 +0000691 case wasm::R_WEBASSEMBLY_EVENT_INDEX_LEB:
Dan Gohmand934cb82017-02-24 23:18:00 +0000692 WritePatchableLEB(Stream, Value, Offset);
693 break;
Sam Clegg60ec3032018-01-23 01:23:17 +0000694 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
695 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000696 case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32:
697 case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32:
Dan Gohmand934cb82017-02-24 23:18:00 +0000698 WriteI32(Stream, Value, Offset);
699 break;
Sam Clegg60ec3032018-01-23 01:23:17 +0000700 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
701 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
702 WritePatchableSLEB(Stream, Value, Offset);
703 break;
Dan Gohmand934cb82017-02-24 23:18:00 +0000704 default:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000705 llvm_unreachable("invalid relocation type");
Dan Gohmand934cb82017-02-24 23:18:00 +0000706 }
707 }
Dan Gohman18eafb62017-02-22 01:23:18 +0000708}
709
Heejin Ahnda419bd2018-11-14 02:46:21 +0000710void WasmObjectWriter::writeTypeSection(ArrayRef<WasmSignature> Signatures) {
711 if (Signatures.empty())
Sam Clegg9e15f352017-06-03 02:01:24 +0000712 return;
713
714 SectionBookkeeping Section;
715 startSection(Section, wasm::WASM_SEC_TYPE);
716
Heejin Ahnda419bd2018-11-14 02:46:21 +0000717 encodeULEB128(Signatures.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000718
Heejin Ahnda419bd2018-11-14 02:46:21 +0000719 for (const WasmSignature &Sig : Signatures) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000720 W.OS << char(wasm::WASM_TYPE_FUNC);
Heejin Ahnda419bd2018-11-14 02:46:21 +0000721 encodeULEB128(Sig.Params.size(), W.OS);
722 for (wasm::ValType Ty : Sig.Params)
Sam Clegg9e15f352017-06-03 02:01:24 +0000723 writeValueType(Ty);
Heejin Ahnda419bd2018-11-14 02:46:21 +0000724 encodeULEB128(Sig.Returns.size(), W.OS);
725 for (wasm::ValType Ty : Sig.Returns)
Sam Clegg9e15f352017-06-03 02:01:24 +0000726 writeValueType(Ty);
727 }
728
729 endSection(Section);
730}
731
Sam Clegg8defa952018-02-12 22:41:29 +0000732void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
Sam Cleggf950b242017-12-11 23:03:38 +0000733 uint32_t DataSize,
734 uint32_t NumElements) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000735 if (Imports.empty())
736 return;
737
Sam Cleggf950b242017-12-11 23:03:38 +0000738 uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
739
Sam Clegg9e15f352017-06-03 02:01:24 +0000740 SectionBookkeeping Section;
741 startSection(Section, wasm::WASM_SEC_IMPORT);
742
Peter Collingbournef17b1492018-05-21 18:17:42 +0000743 encodeULEB128(Imports.size(), W.OS);
Sam Clegg8defa952018-02-12 22:41:29 +0000744 for (const wasm::WasmImport &Import : Imports) {
745 writeString(Import.Module);
746 writeString(Import.Field);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000747 W.OS << char(Import.Kind);
Sam Clegg9e15f352017-06-03 02:01:24 +0000748
749 switch (Import.Kind) {
750 case wasm::WASM_EXTERNAL_FUNCTION:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000751 encodeULEB128(Import.SigIndex, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000752 break;
753 case wasm::WASM_EXTERNAL_GLOBAL:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000754 W.OS << char(Import.Global.Type);
755 W.OS << char(Import.Global.Mutable ? 1 : 0);
Sam Clegg9e15f352017-06-03 02:01:24 +0000756 break;
Sam Cleggf950b242017-12-11 23:03:38 +0000757 case wasm::WASM_EXTERNAL_MEMORY:
Heejin Ahnf208f632018-09-05 01:27:38 +0000758 encodeULEB128(0, W.OS); // flags
Peter Collingbournef17b1492018-05-21 18:17:42 +0000759 encodeULEB128(NumPages, W.OS); // initial
Sam Cleggf950b242017-12-11 23:03:38 +0000760 break;
761 case wasm::WASM_EXTERNAL_TABLE:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000762 W.OS << char(Import.Table.ElemType);
Heejin Ahnf208f632018-09-05 01:27:38 +0000763 encodeULEB128(0, W.OS); // flags
Peter Collingbournef17b1492018-05-21 18:17:42 +0000764 encodeULEB128(NumElements, W.OS); // initial
Sam Cleggf950b242017-12-11 23:03:38 +0000765 break;
Heejin Ahnda419bd2018-11-14 02:46:21 +0000766 case wasm::WASM_EXTERNAL_EVENT:
767 encodeULEB128(Import.Event.Attribute, W.OS);
768 encodeULEB128(Import.Event.SigIndex, W.OS);
769 break;
Sam Clegg9e15f352017-06-03 02:01:24 +0000770 default:
771 llvm_unreachable("unsupported import kind");
772 }
773 }
774
775 endSection(Section);
776}
777
Sam Clegg457fb0b2017-09-15 19:50:44 +0000778void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000779 if (Functions.empty())
780 return;
781
782 SectionBookkeeping Section;
783 startSection(Section, wasm::WASM_SEC_FUNCTION);
784
Peter Collingbournef17b1492018-05-21 18:17:42 +0000785 encodeULEB128(Functions.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000786 for (const WasmFunction &Func : Functions)
Heejin Ahnda419bd2018-11-14 02:46:21 +0000787 encodeULEB128(Func.SigIndex, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000788
789 endSection(Section);
790}
791
Sam Clegg7c395942017-09-14 23:07:53 +0000792void WasmObjectWriter::writeGlobalSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000793 if (Globals.empty())
794 return;
795
796 SectionBookkeeping Section;
797 startSection(Section, wasm::WASM_SEC_GLOBAL);
798
Peter Collingbournef17b1492018-05-21 18:17:42 +0000799 encodeULEB128(Globals.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000800 for (const WasmGlobal &Global : Globals) {
Sam Clegg6e7f1822018-01-31 19:50:14 +0000801 writeValueType(static_cast<wasm::ValType>(Global.Type.Type));
Peter Collingbournef17b1492018-05-21 18:17:42 +0000802 W.OS << char(Global.Type.Mutable);
Sam Clegg9e15f352017-06-03 02:01:24 +0000803
Peter Collingbournef17b1492018-05-21 18:17:42 +0000804 W.OS << char(wasm::WASM_OPCODE_I32_CONST);
805 encodeSLEB128(Global.InitialValue, W.OS);
806 W.OS << char(wasm::WASM_OPCODE_END);
Sam Clegg9e15f352017-06-03 02:01:24 +0000807 }
808
809 endSection(Section);
810}
811
Heejin Ahnda419bd2018-11-14 02:46:21 +0000812void WasmObjectWriter::writeEventSection(ArrayRef<wasm::WasmEventType> Events) {
813 if (Events.empty())
814 return;
815
816 SectionBookkeeping Section;
817 startSection(Section, wasm::WASM_SEC_EVENT);
818
819 encodeULEB128(Events.size(), W.OS);
820 for (const wasm::WasmEventType &Event : Events) {
821 encodeULEB128(Event.Attribute, W.OS);
822 encodeULEB128(Event.SigIndex, W.OS);
823 }
824
825 endSection(Section);
826}
827
Sam Clegg8defa952018-02-12 22:41:29 +0000828void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000829 if (Exports.empty())
830 return;
831
832 SectionBookkeeping Section;
833 startSection(Section, wasm::WASM_SEC_EXPORT);
834
Peter Collingbournef17b1492018-05-21 18:17:42 +0000835 encodeULEB128(Exports.size(), W.OS);
Sam Clegg8defa952018-02-12 22:41:29 +0000836 for (const wasm::WasmExport &Export : Exports) {
837 writeString(Export.Name);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000838 W.OS << char(Export.Kind);
839 encodeULEB128(Export.Index, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000840 }
841
842 endSection(Section);
843}
844
Sam Clegg457fb0b2017-09-15 19:50:44 +0000845void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000846 if (TableElems.empty())
847 return;
848
849 SectionBookkeeping Section;
850 startSection(Section, wasm::WASM_SEC_ELEM);
851
Peter Collingbournef17b1492018-05-21 18:17:42 +0000852 encodeULEB128(1, W.OS); // number of "segments"
853 encodeULEB128(0, W.OS); // the table index
Sam Clegg9e15f352017-06-03 02:01:24 +0000854
855 // init expr for starting offset
Peter Collingbournef17b1492018-05-21 18:17:42 +0000856 W.OS << char(wasm::WASM_OPCODE_I32_CONST);
857 encodeSLEB128(kInitialTableOffset, W.OS);
858 W.OS << char(wasm::WASM_OPCODE_END);
Sam Clegg9e15f352017-06-03 02:01:24 +0000859
Peter Collingbournef17b1492018-05-21 18:17:42 +0000860 encodeULEB128(TableElems.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000861 for (uint32_t Elem : TableElems)
Peter Collingbournef17b1492018-05-21 18:17:42 +0000862 encodeULEB128(Elem, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000863
864 endSection(Section);
865}
866
Sam Clegg457fb0b2017-09-15 19:50:44 +0000867void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
868 const MCAsmLayout &Layout,
869 ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000870 if (Functions.empty())
871 return;
872
873 SectionBookkeeping Section;
874 startSection(Section, wasm::WASM_SEC_CODE);
Sam Clegg6f08c842018-04-24 18:11:36 +0000875 CodeSectionIndex = Section.Index;
Sam Clegg9e15f352017-06-03 02:01:24 +0000876
Peter Collingbournef17b1492018-05-21 18:17:42 +0000877 encodeULEB128(Functions.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000878
879 for (const WasmFunction &Func : Functions) {
Sam Cleggfe6414b2017-06-21 23:46:41 +0000880 auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
Sam Clegg9e15f352017-06-03 02:01:24 +0000881
Sam Clegg9e15f352017-06-03 02:01:24 +0000882 int64_t Size = 0;
883 if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
884 report_fatal_error(".size expression must be evaluatable");
885
Peter Collingbournef17b1492018-05-21 18:17:42 +0000886 encodeULEB128(Size, W.OS);
887 FuncSection.setSectionOffset(W.OS.tell() - Section.ContentsOffset);
888 Asm.writeSectionData(W.OS, &FuncSection, Layout);
Sam Clegg9e15f352017-06-03 02:01:24 +0000889 }
890
Sam Clegg9e15f352017-06-03 02:01:24 +0000891 // Apply fixups.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000892 applyRelocations(CodeRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000893
894 endSection(Section);
895}
896
Sam Clegg6c899ba2018-02-23 05:08:34 +0000897void WasmObjectWriter::writeDataSection() {
898 if (DataSegments.empty())
Sam Clegg7c395942017-09-14 23:07:53 +0000899 return;
Sam Clegg9e15f352017-06-03 02:01:24 +0000900
901 SectionBookkeeping Section;
902 startSection(Section, wasm::WASM_SEC_DATA);
Sam Clegg6f08c842018-04-24 18:11:36 +0000903 DataSectionIndex = Section.Index;
Sam Clegg9e15f352017-06-03 02:01:24 +0000904
Peter Collingbournef17b1492018-05-21 18:17:42 +0000905 encodeULEB128(DataSegments.size(), W.OS); // count
Sam Clegg7c395942017-09-14 23:07:53 +0000906
Sam Clegg6c899ba2018-02-23 05:08:34 +0000907 for (const WasmDataSegment &Segment : DataSegments) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000908 encodeULEB128(0, W.OS); // memory index
909 W.OS << char(wasm::WASM_OPCODE_I32_CONST);
910 encodeSLEB128(Segment.Offset, W.OS); // offset
911 W.OS << char(wasm::WASM_OPCODE_END);
912 encodeULEB128(Segment.Data.size(), W.OS); // size
913 Segment.Section->setSectionOffset(W.OS.tell() - Section.ContentsOffset);
914 W.OS << Segment.Data; // data
Sam Clegg7c395942017-09-14 23:07:53 +0000915 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000916
917 // Apply fixups.
Sam Clegg7c395942017-09-14 23:07:53 +0000918 applyRelocations(DataRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000919
920 endSection(Section);
Sam Clegg9e15f352017-06-03 02:01:24 +0000921}
922
Sam Clegg6f08c842018-04-24 18:11:36 +0000923void WasmObjectWriter::writeRelocSection(
924 uint32_t SectionIndex, StringRef Name,
Heejin Ahnf208f632018-09-05 01:27:38 +0000925 std::vector<WasmRelocationEntry> &Relocs) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000926 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
927 // for descriptions of the reloc sections.
928
Sam Cleggf77dc2a2018-08-22 17:27:31 +0000929 if (Relocs.empty())
Sam Clegg9e15f352017-06-03 02:01:24 +0000930 return;
931
Sam Cleggf77dc2a2018-08-22 17:27:31 +0000932 // First, ensure the relocations are sorted in offset order. In general they
933 // should already be sorted since `recordRelocation` is called in offset
934 // order, but for the code section we combine many MC sections into single
935 // wasm section, and this order is determined by the order of Asm.Symbols()
936 // not the sections order.
937 std::stable_sort(
938 Relocs.begin(), Relocs.end(),
939 [](const WasmRelocationEntry &A, const WasmRelocationEntry &B) {
940 return (A.Offset + A.FixupSection->getSectionOffset()) <
941 (B.Offset + B.FixupSection->getSectionOffset());
942 });
943
Sam Clegg9e15f352017-06-03 02:01:24 +0000944 SectionBookkeeping Section;
Sam Clegg6f08c842018-04-24 18:11:36 +0000945 startCustomSection(Section, std::string("reloc.") + Name.str());
Sam Clegg9e15f352017-06-03 02:01:24 +0000946
Peter Collingbournef17b1492018-05-21 18:17:42 +0000947 encodeULEB128(SectionIndex, W.OS);
Sam Cleggf77dc2a2018-08-22 17:27:31 +0000948 encodeULEB128(Relocs.size(), W.OS);
Heejin Ahnf208f632018-09-05 01:27:38 +0000949 for (const WasmRelocationEntry &RelEntry : Relocs) {
950 uint64_t Offset =
951 RelEntry.Offset + RelEntry.FixupSection->getSectionOffset();
Sam Clegg6f08c842018-04-24 18:11:36 +0000952 uint32_t Index = getRelocationIndexValue(RelEntry);
Sam Clegg9e15f352017-06-03 02:01:24 +0000953
Peter Collingbournef17b1492018-05-21 18:17:42 +0000954 W.OS << char(RelEntry.Type);
955 encodeULEB128(Offset, W.OS);
956 encodeULEB128(Index, W.OS);
Sam Clegg6f08c842018-04-24 18:11:36 +0000957 if (RelEntry.hasAddend())
Peter Collingbournef17b1492018-05-21 18:17:42 +0000958 encodeSLEB128(RelEntry.Addend, W.OS);
Sam Clegg6f08c842018-04-24 18:11:36 +0000959 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000960
961 endSection(Section);
962}
963
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000964void WasmObjectWriter::writeCustomRelocSections() {
965 for (const auto &Sec : CustomSections) {
966 auto &Relocations = CustomSectionsRelocations[Sec.Section];
967 writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations);
968 }
969}
970
Sam Clegg9e15f352017-06-03 02:01:24 +0000971void WasmObjectWriter::writeLinkingMetaDataSection(
Sam Clegg86b4a092018-02-27 23:57:37 +0000972 ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
Sam Cleggea7cace2018-01-09 23:43:14 +0000973 ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
Sam Clegg6c899ba2018-02-23 05:08:34 +0000974 const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000975 SectionBookkeeping Section;
Sam Clegg2322a932018-04-23 19:16:19 +0000976 startCustomSection(Section, "linking");
Peter Collingbournef17b1492018-05-21 18:17:42 +0000977 encodeULEB128(wasm::WasmMetadataVersion, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000978
Sam Clegg6bb5a412018-04-26 18:15:32 +0000979 SectionBookkeeping SubSection;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000980 if (SymbolInfos.size() != 0) {
981 startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000982 encodeULEB128(SymbolInfos.size(), W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000983 for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000984 encodeULEB128(Sym.Kind, W.OS);
985 encodeULEB128(Sym.Flags, W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000986 switch (Sym.Kind) {
987 case wasm::WASM_SYMBOL_TYPE_FUNCTION:
988 case wasm::WASM_SYMBOL_TYPE_GLOBAL:
Heejin Ahnda419bd2018-11-14 02:46:21 +0000989 case wasm::WASM_SYMBOL_TYPE_EVENT:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000990 encodeULEB128(Sym.ElementIndex, W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000991 if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0)
992 writeString(Sym.Name);
993 break;
994 case wasm::WASM_SYMBOL_TYPE_DATA:
995 writeString(Sym.Name);
996 if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000997 encodeULEB128(Sym.DataRef.Segment, W.OS);
998 encodeULEB128(Sym.DataRef.Offset, W.OS);
999 encodeULEB128(Sym.DataRef.Size, W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001000 }
1001 break;
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001002 case wasm::WASM_SYMBOL_TYPE_SECTION: {
1003 const uint32_t SectionIndex =
1004 CustomSections[Sym.ElementIndex].OutputIndex;
Peter Collingbournef17b1492018-05-21 18:17:42 +00001005 encodeULEB128(SectionIndex, W.OS);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001006 break;
1007 }
Sam Clegg6c899ba2018-02-23 05:08:34 +00001008 default:
1009 llvm_unreachable("unexpected kind");
1010 }
Sam Cleggb7787fd2017-06-20 04:04:59 +00001011 }
1012 endSection(SubSection);
1013 }
Sam Clegg9e15f352017-06-03 02:01:24 +00001014
Sam Clegg6c899ba2018-02-23 05:08:34 +00001015 if (DataSegments.size()) {
Sam Clegg63ebb812017-09-29 16:50:08 +00001016 startSection(SubSection, wasm::WASM_SEGMENT_INFO);
Peter Collingbournef17b1492018-05-21 18:17:42 +00001017 encodeULEB128(DataSegments.size(), W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001018 for (const WasmDataSegment &Segment : DataSegments) {
Sam Cleggd95ed952017-09-20 19:03:35 +00001019 writeString(Segment.Name);
Peter Collingbournef17b1492018-05-21 18:17:42 +00001020 encodeULEB128(Segment.Alignment, W.OS);
1021 encodeULEB128(Segment.Flags, W.OS);
Sam Clegg63ebb812017-09-29 16:50:08 +00001022 }
Sam Cleggd95ed952017-09-20 19:03:35 +00001023 endSection(SubSection);
1024 }
1025
Sam Cleggbafe6902017-12-15 00:17:10 +00001026 if (!InitFuncs.empty()) {
1027 startSection(SubSection, wasm::WASM_INIT_FUNCS);
Peter Collingbournef17b1492018-05-21 18:17:42 +00001028 encodeULEB128(InitFuncs.size(), W.OS);
Sam Cleggbafe6902017-12-15 00:17:10 +00001029 for (auto &StartFunc : InitFuncs) {
Heejin Ahnf208f632018-09-05 01:27:38 +00001030 encodeULEB128(StartFunc.first, W.OS); // priority
Peter Collingbournef17b1492018-05-21 18:17:42 +00001031 encodeULEB128(StartFunc.second, W.OS); // function index
Sam Cleggbafe6902017-12-15 00:17:10 +00001032 }
1033 endSection(SubSection);
1034 }
1035
Sam Cleggea7cace2018-01-09 23:43:14 +00001036 if (Comdats.size()) {
1037 startSection(SubSection, wasm::WASM_COMDAT_INFO);
Peter Collingbournef17b1492018-05-21 18:17:42 +00001038 encodeULEB128(Comdats.size(), W.OS);
Sam Cleggea7cace2018-01-09 23:43:14 +00001039 for (const auto &C : Comdats) {
1040 writeString(C.first);
Peter Collingbournef17b1492018-05-21 18:17:42 +00001041 encodeULEB128(0, W.OS); // flags for future use
1042 encodeULEB128(C.second.size(), W.OS);
Sam Cleggea7cace2018-01-09 23:43:14 +00001043 for (const WasmComdatEntry &Entry : C.second) {
Peter Collingbournef17b1492018-05-21 18:17:42 +00001044 encodeULEB128(Entry.Kind, W.OS);
1045 encodeULEB128(Entry.Index, W.OS);
Sam Cleggea7cace2018-01-09 23:43:14 +00001046 }
1047 }
1048 endSection(SubSection);
1049 }
1050
Sam Clegg9e15f352017-06-03 02:01:24 +00001051 endSection(Section);
1052}
1053
Thomas Livelycbda16e2019-01-17 02:29:55 +00001054void WasmObjectWriter::writeCustomSection(WasmCustomSection &CustomSection,
1055 const MCAssembler &Asm,
1056 const MCAsmLayout &Layout) {
1057 SectionBookkeeping Section;
1058 auto *Sec = CustomSection.Section;
1059 startCustomSection(Section, CustomSection.Name);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001060
Thomas Livelycbda16e2019-01-17 02:29:55 +00001061 Sec->setSectionOffset(W.OS.tell() - Section.ContentsOffset);
1062 Asm.writeSectionData(W.OS, Sec, Layout);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001063
Thomas Livelycbda16e2019-01-17 02:29:55 +00001064 CustomSection.OutputContentsOffset = Section.ContentsOffset;
1065 CustomSection.OutputIndex = Section.Index;
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001066
Thomas Livelycbda16e2019-01-17 02:29:55 +00001067 endSection(Section);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001068
Thomas Livelycbda16e2019-01-17 02:29:55 +00001069 // Apply fixups.
1070 auto &Relocations = CustomSectionsRelocations[CustomSection.Section];
1071 applyRelocations(Relocations, CustomSection.OutputContentsOffset);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001072}
1073
Heejin Ahnf208f632018-09-05 01:27:38 +00001074uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm &Symbol) {
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001075 assert(Symbol.isFunction());
1076 assert(TypeIndices.count(&Symbol));
1077 return TypeIndices[&Symbol];
1078}
1079
Heejin Ahnda419bd2018-11-14 02:46:21 +00001080uint32_t WasmObjectWriter::getEventType(const MCSymbolWasm &Symbol) {
1081 assert(Symbol.isEvent());
1082 assert(TypeIndices.count(&Symbol));
1083 return TypeIndices[&Symbol];
1084}
1085
Heejin Ahn38b12f52018-11-20 00:38:10 +00001086void WasmObjectWriter::registerFunctionType(const MCSymbolWasm &Symbol) {
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001087 assert(Symbol.isFunction());
1088
Heejin Ahnda419bd2018-11-14 02:46:21 +00001089 WasmSignature S;
Heejin Ahnf208f632018-09-05 01:27:38 +00001090 const MCSymbolWasm *ResolvedSym = ResolveSymbol(Symbol);
Derek Schuff77a7a382018-10-03 22:22:48 +00001091 if (auto *Sig = ResolvedSym->getSignature()) {
Heejin Ahnda419bd2018-11-14 02:46:21 +00001092 S.Returns = Sig->Returns;
1093 S.Params = Sig->Params;
Derek Schuff77a7a382018-10-03 22:22:48 +00001094 }
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001095
Heejin Ahnda419bd2018-11-14 02:46:21 +00001096 auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001097 if (Pair.second)
Heejin Ahnda419bd2018-11-14 02:46:21 +00001098 Signatures.push_back(S);
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001099 TypeIndices[&Symbol] = Pair.first->second;
1100
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001101 LLVM_DEBUG(dbgs() << "registerFunctionType: " << Symbol
1102 << " new:" << Pair.second << "\n");
1103 LLVM_DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n");
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001104}
1105
Heejin Ahn38b12f52018-11-20 00:38:10 +00001106void WasmObjectWriter::registerEventType(const MCSymbolWasm &Symbol) {
Heejin Ahnda419bd2018-11-14 02:46:21 +00001107 assert(Symbol.isEvent());
1108
1109 // TODO Currently we don't generate imported exceptions, but if we do, we
1110 // should have a way of infering types of imported exceptions.
1111 WasmSignature S;
1112 if (auto *Sig = Symbol.getSignature()) {
1113 S.Returns = Sig->Returns;
1114 S.Params = Sig->Params;
1115 }
1116
1117 auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
1118 if (Pair.second)
1119 Signatures.push_back(S);
1120 TypeIndices[&Symbol] = Pair.first->second;
1121
1122 LLVM_DEBUG(dbgs() << "registerEventType: " << Symbol << " new:" << Pair.second
1123 << "\n");
1124 LLVM_DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n");
Heejin Ahnda419bd2018-11-14 02:46:21 +00001125}
1126
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001127static bool isInSymtab(const MCSymbolWasm &Sym) {
1128 if (Sym.isUsedInReloc())
1129 return true;
1130
1131 if (Sym.isComdat() && !Sym.isDefined())
1132 return false;
1133
1134 if (Sym.isTemporary() && Sym.getName().empty())
1135 return false;
1136
1137 if (Sym.isTemporary() && Sym.isData() && !Sym.getSize())
1138 return false;
1139
1140 if (Sym.isSection())
1141 return false;
1142
1143 return true;
1144}
1145
Peter Collingbourne438390f2018-05-21 18:23:50 +00001146uint64_t WasmObjectWriter::writeObject(MCAssembler &Asm,
1147 const MCAsmLayout &Layout) {
1148 uint64_t StartOffset = W.OS.tell();
1149
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001150 LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
Dan Gohman82607f52017-02-24 23:46:05 +00001151 MCContext &Ctx = Asm.getContext();
Dan Gohmand934cb82017-02-24 23:18:00 +00001152
1153 // Collect information from the available symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +00001154 SmallVector<WasmFunction, 4> Functions;
1155 SmallVector<uint32_t, 4> TableElems;
Sam Clegg8defa952018-02-12 22:41:29 +00001156 SmallVector<wasm::WasmImport, 4> Imports;
1157 SmallVector<wasm::WasmExport, 4> Exports;
Heejin Ahnda419bd2018-11-14 02:46:21 +00001158 SmallVector<wasm::WasmEventType, 1> Events;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001159 SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
Sam Cleggbafe6902017-12-15 00:17:10 +00001160 SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
Sam Cleggea7cace2018-01-09 23:43:14 +00001161 std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
Sam Clegg7c395942017-09-14 23:07:53 +00001162 uint32_t DataSize = 0;
Dan Gohmand934cb82017-02-24 23:18:00 +00001163
Sam Cleggf950b242017-12-11 23:03:38 +00001164 // For now, always emit the memory import, since loads and stores are not
1165 // valid without it. In the future, we could perhaps be more clever and omit
1166 // it if there are no loads or stores.
1167 MCSymbolWasm *MemorySym =
1168 cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__linear_memory"));
Sam Clegg8defa952018-02-12 22:41:29 +00001169 wasm::WasmImport MemImport;
1170 MemImport.Module = MemorySym->getModuleName();
1171 MemImport.Field = MemorySym->getName();
Sam Cleggf950b242017-12-11 23:03:38 +00001172 MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1173 Imports.push_back(MemImport);
1174
1175 // For now, always emit the table section, since indirect calls are not
1176 // valid without it. In the future, we could perhaps be more clever and omit
1177 // it if there are no indirect calls.
1178 MCSymbolWasm *TableSym =
1179 cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__indirect_function_table"));
Sam Clegg8defa952018-02-12 22:41:29 +00001180 wasm::WasmImport TableImport;
1181 TableImport.Module = TableSym->getModuleName();
1182 TableImport.Field = TableSym->getName();
Sam Cleggf950b242017-12-11 23:03:38 +00001183 TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
Thomas Lively6a87dda2019-01-08 06:25:55 +00001184 TableImport.Table.ElemType = wasm::WASM_TYPE_FUNCREF;
Sam Cleggf950b242017-12-11 23:03:38 +00001185 Imports.push_back(TableImport);
1186
Heejin Ahnda419bd2018-11-14 02:46:21 +00001187 // Populate SignatureIndices, and Imports and WasmIndices for undefined
Nicholas Wilson586320c2018-02-28 17:19:48 +00001188 // symbols. This must be done before populating WasmIndices for defined
1189 // symbols.
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001190 for (const MCSymbol &S : Asm.symbols()) {
1191 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1192
1193 // Register types for all functions, including those with private linkage
Sam Clegg9f3fe422018-01-17 19:28:43 +00001194 // (because wasm always needs a type signature).
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001195 if (WS.isFunction())
1196 registerFunctionType(WS);
1197
Heejin Ahnda419bd2018-11-14 02:46:21 +00001198 if (WS.isEvent())
1199 registerEventType(WS);
1200
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001201 if (WS.isTemporary())
1202 continue;
1203
1204 // If the symbol is not defined in this translation unit, import it.
Sam Clegg6c899ba2018-02-23 05:08:34 +00001205 if (!WS.isDefined() && !WS.isComdat()) {
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001206 if (WS.isFunction()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001207 wasm::WasmImport Import;
1208 Import.Module = WS.getModuleName();
1209 Import.Field = WS.getName();
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001210 Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
Sam Clegg8defa952018-02-12 22:41:29 +00001211 Import.SigIndex = getFunctionType(WS);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001212 Imports.push_back(Import);
1213 WasmIndices[&WS] = NumFunctionImports++;
1214 } else if (WS.isGlobal()) {
Nicholas Wilson15f349f2018-03-09 16:30:44 +00001215 if (WS.isWeak())
1216 report_fatal_error("undefined global symbol cannot be weak");
1217
Sam Clegg6c899ba2018-02-23 05:08:34 +00001218 wasm::WasmImport Import;
1219 Import.Module = WS.getModuleName();
1220 Import.Field = WS.getName();
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001221 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001222 Import.Global = WS.getGlobalType();
1223 Imports.push_back(Import);
1224 WasmIndices[&WS] = NumGlobalImports++;
Heejin Ahnda419bd2018-11-14 02:46:21 +00001225 } else if (WS.isEvent()) {
1226 if (WS.isWeak())
1227 report_fatal_error("undefined event symbol cannot be weak");
1228
1229 wasm::WasmImport Import;
1230 Import.Module = WS.getModuleName();
1231 Import.Field = WS.getName();
1232 Import.Kind = wasm::WASM_EXTERNAL_EVENT;
1233 Import.Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1234 Import.Event.SigIndex = getEventType(WS);
1235 Imports.push_back(Import);
1236 WasmIndices[&WS] = NumEventImports++;
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001237 }
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001238 }
1239 }
1240
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001241 // Populate DataSegments and CustomSections, which must be done before
1242 // populating DataLocations.
Sam Clegg759631c2017-09-15 20:54:59 +00001243 for (MCSection &Sec : Asm) {
1244 auto &Section = static_cast<MCSectionWasm &>(Sec);
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001245 StringRef SectionName = Section.getSectionName();
Sam Clegg759631c2017-09-15 20:54:59 +00001246
Sam Cleggbafe6902017-12-15 00:17:10 +00001247 // .init_array sections are handled specially elsewhere.
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001248 if (SectionName.startswith(".init_array"))
Sam Cleggbafe6902017-12-15 00:17:10 +00001249 continue;
1250
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001251 // Code is handled separately
1252 if (Section.getKind().isText())
1253 continue;
Sam Cleggea7cace2018-01-09 23:43:14 +00001254
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001255 if (Section.isWasmData()) {
1256 uint32_t SegmentIndex = DataSegments.size();
1257 DataSize = alignTo(DataSize, Section.getAlignment());
1258 DataSegments.emplace_back();
1259 WasmDataSegment &Segment = DataSegments.back();
1260 Segment.Name = SectionName;
1261 Segment.Offset = DataSize;
1262 Segment.Section = &Section;
1263 addData(Segment.Data, Section);
Sam Clegg56c587a2019-01-16 01:34:48 +00001264 Segment.Alignment = Log2_32(Section.getAlignment());
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001265 Segment.Flags = 0;
1266 DataSize += Segment.Data.size();
1267 Section.setSegmentIndex(SegmentIndex);
1268
1269 if (const MCSymbolWasm *C = Section.getGroup()) {
1270 Comdats[C->getName()].emplace_back(
1271 WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
1272 }
1273 } else {
1274 // Create custom sections
1275 assert(Sec.getKind().isMetadata());
1276
1277 StringRef Name = SectionName;
1278
1279 // For user-defined custom sections, strip the prefix
1280 if (Name.startswith(".custom_section."))
1281 Name = Name.substr(strlen(".custom_section."));
1282
Heejin Ahnf208f632018-09-05 01:27:38 +00001283 MCSymbol *Begin = Sec.getBeginSymbol();
Sam Cleggfb807d42018-05-07 19:40:50 +00001284 if (Begin) {
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001285 WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size();
Sam Cleggb210c642018-05-10 17:38:35 +00001286 if (SectionName != Begin->getName())
Sam Cleggfb807d42018-05-07 19:40:50 +00001287 report_fatal_error("section name and begin symbol should match: " +
Sam Cleggb210c642018-05-10 17:38:35 +00001288 Twine(SectionName));
Sam Cleggfb807d42018-05-07 19:40:50 +00001289 }
Thomas Livelycbda16e2019-01-17 02:29:55 +00001290
1291 // Separate out the producers section
1292 if (Name == "producers") {
1293 ProducersSection = llvm::make_unique<WasmCustomSection>(Name, &Section);
1294 continue;
1295 }
1296
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001297 CustomSections.emplace_back(Name, &Section);
Sam Cleggea7cace2018-01-09 23:43:14 +00001298 }
Sam Clegg759631c2017-09-15 20:54:59 +00001299 }
1300
Nicholas Wilson586320c2018-02-28 17:19:48 +00001301 // Populate WasmIndices and DataLocations for defined symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +00001302 for (const MCSymbol &S : Asm.symbols()) {
1303 // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1304 // or used in relocations.
1305 if (S.isTemporary() && S.getName().empty())
1306 continue;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001307
Dan Gohmand934cb82017-02-24 23:18:00 +00001308 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001309 LLVM_DEBUG(
1310 dbgs() << "MCSymbol: " << toString(WS.getType()) << " '" << S << "'"
1311 << " isDefined=" << S.isDefined() << " isExternal="
1312 << S.isExternal() << " isTemporary=" << S.isTemporary()
1313 << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden()
1314 << " isVariable=" << WS.isVariable() << "\n");
Sam Cleggb7787fd2017-06-20 04:04:59 +00001315
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001316 if (WS.isVariable())
1317 continue;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001318 if (WS.isComdat() && !WS.isDefined())
1319 continue;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001320
Dan Gohmand934cb82017-02-24 23:18:00 +00001321 if (WS.isFunction()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001322 unsigned Index;
Sam Cleggcd65f692018-01-11 23:59:16 +00001323 if (WS.isDefined()) {
Sam Cleggb7787fd2017-06-20 04:04:59 +00001324 if (WS.getOffset() != 0)
1325 report_fatal_error(
1326 "function sections must contain one function each");
1327
1328 if (WS.getSize() == 0)
1329 report_fatal_error(
1330 "function symbols must have a size set with .size");
1331
Sam Clegg6c899ba2018-02-23 05:08:34 +00001332 // A definition. Write out the function body.
Sam Clegg9f3fe422018-01-17 19:28:43 +00001333 Index = NumFunctionImports + Functions.size();
Dan Gohmand934cb82017-02-24 23:18:00 +00001334 WasmFunction Func;
Heejin Ahnda419bd2018-11-14 02:46:21 +00001335 Func.SigIndex = getFunctionType(WS);
Dan Gohmand934cb82017-02-24 23:18:00 +00001336 Func.Sym = &WS;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001337 WasmIndices[&WS] = Index;
Dan Gohmand934cb82017-02-24 23:18:00 +00001338 Functions.push_back(Func);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001339
1340 auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
1341 if (const MCSymbolWasm *C = Section.getGroup()) {
1342 Comdats[C->getName()].emplace_back(
1343 WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
1344 }
Dan Gohmand934cb82017-02-24 23:18:00 +00001345 } else {
1346 // An import; the index was assigned above.
Sam Clegg6c899ba2018-02-23 05:08:34 +00001347 Index = WasmIndices.find(&WS)->second;
Dan Gohmand934cb82017-02-24 23:18:00 +00001348 }
1349
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001350 LLVM_DEBUG(dbgs() << " -> function index: " << Index << "\n");
Heejin Ahnda419bd2018-11-14 02:46:21 +00001351
Sam Clegg6c899ba2018-02-23 05:08:34 +00001352 } else if (WS.isData()) {
Sam Cleggc38e9472017-06-02 01:05:24 +00001353 if (WS.isTemporary() && !WS.getSize())
1354 continue;
Dan Gohmand934cb82017-02-24 23:18:00 +00001355
Sam Clegg6c899ba2018-02-23 05:08:34 +00001356 if (!WS.isDefined()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001357 LLVM_DEBUG(dbgs() << " -> segment index: -1"
1358 << "\n");
Sam Cleggfe6414b2017-06-21 23:46:41 +00001359 continue;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001360 }
Sam Cleggc38e9472017-06-02 01:05:24 +00001361
Sam Cleggfe6414b2017-06-21 23:46:41 +00001362 if (!WS.getSize())
1363 report_fatal_error("data symbols must have a size set with .size: " +
1364 WS.getName());
Sam Cleggc38e9472017-06-02 01:05:24 +00001365
Sam Cleggfe6414b2017-06-21 23:46:41 +00001366 int64_t Size = 0;
1367 if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1368 report_fatal_error(".size expression must be evaluatable");
Dan Gohmand934cb82017-02-24 23:18:00 +00001369
Sam Clegg759631c2017-09-15 20:54:59 +00001370 auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
Sam Cleggea7cace2018-01-09 23:43:14 +00001371 assert(DataSection.isWasmData());
Sam Clegg7c395942017-09-14 23:07:53 +00001372
Sam Clegg6c899ba2018-02-23 05:08:34 +00001373 // For each data symbol, export it in the symtab as a reference to the
1374 // corresponding Wasm data segment.
1375 wasm::WasmDataReference Ref = wasm::WasmDataReference{
1376 DataSection.getSegmentIndex(),
1377 static_cast<uint32_t>(Layout.getSymbolOffset(WS)),
1378 static_cast<uint32_t>(Size)};
1379 DataLocations[&WS] = Ref;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001380 LLVM_DEBUG(dbgs() << " -> segment index: " << Ref.Segment << "\n");
Heejin Ahnda419bd2018-11-14 02:46:21 +00001381
Sam Clegga165f2d2018-04-30 19:40:57 +00001382 } else if (WS.isGlobal()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001383 // A "true" Wasm global (currently just __stack_pointer)
Eric Christopher545932b2018-02-23 21:14:47 +00001384 if (WS.isDefined())
Sam Clegg6c899ba2018-02-23 05:08:34 +00001385 report_fatal_error("don't yet support defined globals");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001386
Eric Christopher545932b2018-02-23 21:14:47 +00001387 // An import; the index was assigned above
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001388 LLVM_DEBUG(dbgs() << " -> global index: "
1389 << WasmIndices.find(&WS)->second << "\n");
Heejin Ahnda419bd2018-11-14 02:46:21 +00001390
1391 } else if (WS.isEvent()) {
1392 // C++ exception symbol (__cpp_exception)
1393 unsigned Index;
1394 if (WS.isDefined()) {
1395 Index = NumEventImports + Events.size();
1396 wasm::WasmEventType Event;
1397 Event.SigIndex = getEventType(WS);
1398 Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1399 WasmIndices[&WS] = Index;
1400 Events.push_back(Event);
1401 } else {
1402 // An import; the index was assigned above.
1403 Index = WasmIndices.find(&WS)->second;
1404 }
1405 LLVM_DEBUG(dbgs() << " -> event index: " << WasmIndices.find(&WS)->second
1406 << "\n");
1407
Sam Clegga165f2d2018-04-30 19:40:57 +00001408 } else {
1409 assert(WS.isSection());
Dan Gohmand934cb82017-02-24 23:18:00 +00001410 }
1411 }
1412
Nicholas Wilson586320c2018-02-28 17:19:48 +00001413 // Populate WasmIndices and DataLocations for aliased symbols. We need to
1414 // process these in a separate pass because we need to have processed the
1415 // target of the alias before the alias itself and the symbols are not
1416 // necessarily ordered in this way.
Sam Cleggb7787fd2017-06-20 04:04:59 +00001417 for (const MCSymbol &S : Asm.symbols()) {
1418 if (!S.isVariable())
1419 continue;
Sam Clegg31a2c802017-09-20 21:17:04 +00001420
Sam Cleggcd65f692018-01-11 23:59:16 +00001421 assert(S.isDefined());
Sam Cleggb7787fd2017-06-20 04:04:59 +00001422
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001423 // Find the target symbol of this weak alias and export that index
Sam Cleggaff1c4d2017-09-15 19:22:01 +00001424 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1425 const MCSymbolWasm *ResolvedSym = ResolveSymbol(WS);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001426 LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym
1427 << "'\n");
Sam Cleggb7787fd2017-06-20 04:04:59 +00001428
Sam Clegg6c899ba2018-02-23 05:08:34 +00001429 if (WS.isFunction()) {
1430 assert(WasmIndices.count(ResolvedSym) > 0);
1431 uint32_t WasmIndex = WasmIndices.find(ResolvedSym)->second;
1432 WasmIndices[&WS] = WasmIndex;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001433 LLVM_DEBUG(dbgs() << " -> index:" << WasmIndex << "\n");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001434 } else if (WS.isData()) {
1435 assert(DataLocations.count(ResolvedSym) > 0);
1436 const wasm::WasmDataReference &Ref =
1437 DataLocations.find(ResolvedSym)->second;
1438 DataLocations[&WS] = Ref;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001439 LLVM_DEBUG(dbgs() << " -> index:" << Ref.Segment << "\n");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001440 } else {
Heejin Ahnda419bd2018-11-14 02:46:21 +00001441 report_fatal_error("don't yet support global/event aliases");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001442 }
Nicholas Wilson586320c2018-02-28 17:19:48 +00001443 }
Sam Clegg31a2c802017-09-20 21:17:04 +00001444
Nicholas Wilson586320c2018-02-28 17:19:48 +00001445 // Finally, populate the symbol table itself, in its "natural" order.
1446 for (const MCSymbol &S : Asm.symbols()) {
1447 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Sam Clegg25d8e682018-05-08 00:08:21 +00001448 if (!isInSymtab(WS)) {
1449 WS.setIndex(INVALID_INDEX);
Nicholas Wilson586320c2018-02-28 17:19:48 +00001450 continue;
Sam Clegg25d8e682018-05-08 00:08:21 +00001451 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001452 LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n");
Nicholas Wilson586320c2018-02-28 17:19:48 +00001453
1454 uint32_t Flags = 0;
1455 if (WS.isWeak())
1456 Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
1457 if (WS.isHidden())
1458 Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
1459 if (!WS.isExternal() && WS.isDefined())
1460 Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
1461 if (WS.isUndefined())
1462 Flags |= wasm::WASM_SYMBOL_UNDEFINED;
1463
1464 wasm::WasmSymbolInfo Info;
1465 Info.Name = WS.getName();
1466 Info.Kind = WS.getType();
1467 Info.Flags = Flags;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001468 if (!WS.isData()) {
1469 assert(WasmIndices.count(&WS) > 0);
Nicholas Wilson586320c2018-02-28 17:19:48 +00001470 Info.ElementIndex = WasmIndices.find(&WS)->second;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001471 } else if (WS.isDefined()) {
1472 assert(DataLocations.count(&WS) > 0);
Nicholas Wilson586320c2018-02-28 17:19:48 +00001473 Info.DataRef = DataLocations.find(&WS)->second;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001474 }
Sam Clegg25d8e682018-05-08 00:08:21 +00001475 WS.setIndex(SymbolInfos.size());
Nicholas Wilson586320c2018-02-28 17:19:48 +00001476 SymbolInfos.emplace_back(Info);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001477 }
1478
Sam Clegg6006e092017-12-22 20:31:39 +00001479 {
1480 auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
Sam Cleggf9edbe92018-01-31 19:28:47 +00001481 // Functions referenced by a relocation need to put in the table. This is
1482 // purely to make the object file's provisional values readable, and is
1483 // ignored by the linker, which re-calculates the relocations itself.
1484 if (Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_I32 &&
1485 Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB)
1486 return;
1487 assert(Rel.Symbol->isFunction());
1488 const MCSymbolWasm &WS = *ResolveSymbol(*Rel.Symbol);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001489 uint32_t FunctionIndex = WasmIndices.find(&WS)->second;
Sam Cleggf9edbe92018-01-31 19:28:47 +00001490 uint32_t TableIndex = TableElems.size() + kInitialTableOffset;
1491 if (TableIndices.try_emplace(&WS, TableIndex).second) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001492 LLVM_DEBUG(dbgs() << " -> adding " << WS.getName()
1493 << " to table: " << TableIndex << "\n");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001494 TableElems.push_back(FunctionIndex);
Sam Cleggf9edbe92018-01-31 19:28:47 +00001495 registerFunctionType(WS);
Sam Clegg6006e092017-12-22 20:31:39 +00001496 }
1497 };
Dan Gohman970d02c2017-03-30 23:58:19 +00001498
Sam Clegg6006e092017-12-22 20:31:39 +00001499 for (const WasmRelocationEntry &RelEntry : CodeRelocations)
1500 HandleReloc(RelEntry);
1501 for (const WasmRelocationEntry &RelEntry : DataRelocations)
1502 HandleReloc(RelEntry);
Dan Gohmand934cb82017-02-24 23:18:00 +00001503 }
1504
Sam Cleggbafe6902017-12-15 00:17:10 +00001505 // Translate .init_array section contents into start functions.
1506 for (const MCSection &S : Asm) {
1507 const auto &WS = static_cast<const MCSectionWasm &>(S);
1508 if (WS.getSectionName().startswith(".fini_array"))
1509 report_fatal_error(".fini_array sections are unsupported");
1510 if (!WS.getSectionName().startswith(".init_array"))
1511 continue;
1512 if (WS.getFragmentList().empty())
1513 continue;
Sam Cleggb210c642018-05-10 17:38:35 +00001514
1515 // init_array is expected to contain a single non-empty data fragment
1516 if (WS.getFragmentList().size() != 3)
Sam Cleggbafe6902017-12-15 00:17:10 +00001517 report_fatal_error("only one .init_array section fragment supported");
Sam Cleggb210c642018-05-10 17:38:35 +00001518
1519 auto IT = WS.begin();
1520 const MCFragment &EmptyFrag = *IT;
1521 if (EmptyFrag.getKind() != MCFragment::FT_Data)
1522 report_fatal_error(".init_array section should be aligned");
1523
1524 IT = std::next(IT);
1525 const MCFragment &AlignFrag = *IT;
Sam Cleggbafe6902017-12-15 00:17:10 +00001526 if (AlignFrag.getKind() != MCFragment::FT_Align)
1527 report_fatal_error(".init_array section should be aligned");
1528 if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1529 report_fatal_error(".init_array section should be aligned for pointers");
Sam Cleggb210c642018-05-10 17:38:35 +00001530
1531 const MCFragment &Frag = *std::next(IT);
Sam Cleggbafe6902017-12-15 00:17:10 +00001532 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1533 report_fatal_error("only data supported in .init_array section");
Sam Cleggb210c642018-05-10 17:38:35 +00001534
Sam Cleggbafe6902017-12-15 00:17:10 +00001535 uint16_t Priority = UINT16_MAX;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001536 unsigned PrefixLength = strlen(".init_array");
1537 if (WS.getSectionName().size() > PrefixLength) {
1538 if (WS.getSectionName()[PrefixLength] != '.')
Heejin Ahnf208f632018-09-05 01:27:38 +00001539 report_fatal_error(
1540 ".init_array section priority should start with '.'");
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001541 if (WS.getSectionName()
1542 .substr(PrefixLength + 1)
1543 .getAsInteger(10, Priority))
Sam Cleggbafe6902017-12-15 00:17:10 +00001544 report_fatal_error("invalid .init_array section priority");
1545 }
1546 const auto &DataFrag = cast<MCDataFragment>(Frag);
1547 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
Heejin Ahnf208f632018-09-05 01:27:38 +00001548 for (const uint8_t *
1549 p = (const uint8_t *)Contents.data(),
1550 *end = (const uint8_t *)Contents.data() + Contents.size();
Sam Cleggbafe6902017-12-15 00:17:10 +00001551 p != end; ++p) {
1552 if (*p != 0)
1553 report_fatal_error("non-symbolic data in .init_array section");
1554 }
1555 for (const MCFixup &Fixup : DataFrag.getFixups()) {
Heejin Ahnf208f632018-09-05 01:27:38 +00001556 assert(Fixup.getKind() ==
1557 MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
Sam Cleggbafe6902017-12-15 00:17:10 +00001558 const MCExpr *Expr = Fixup.getValue();
1559 auto *Sym = dyn_cast<MCSymbolRefExpr>(Expr);
1560 if (!Sym)
1561 report_fatal_error("fixups in .init_array should be symbol references");
1562 if (Sym->getKind() != MCSymbolRefExpr::VK_WebAssembly_FUNCTION)
1563 report_fatal_error("symbols in .init_array should be for functions");
Sam Clegg25d8e682018-05-08 00:08:21 +00001564 if (Sym->getSymbol().getIndex() == INVALID_INDEX)
1565 report_fatal_error("symbols in .init_array should exist in symbtab");
1566 InitFuncs.push_back(
1567 std::make_pair(Priority, Sym->getSymbol().getIndex()));
Sam Cleggbafe6902017-12-15 00:17:10 +00001568 }
1569 }
1570
Dan Gohman18eafb62017-02-22 01:23:18 +00001571 // Write out the Wasm header.
1572 writeHeader(Asm);
1573
Heejin Ahnda419bd2018-11-14 02:46:21 +00001574 writeTypeSection(Signatures);
Sam Cleggf950b242017-12-11 23:03:38 +00001575 writeImportSection(Imports, DataSize, TableElems.size());
Sam Clegg9e15f352017-06-03 02:01:24 +00001576 writeFunctionSection(Functions);
Sam Cleggf950b242017-12-11 23:03:38 +00001577 // Skip the "table" section; we import the table instead.
1578 // Skip the "memory" section; we import the memory instead.
Sam Clegg7c395942017-09-14 23:07:53 +00001579 writeGlobalSection();
Heejin Ahnda419bd2018-11-14 02:46:21 +00001580 writeEventSection(Events);
Sam Clegg9e15f352017-06-03 02:01:24 +00001581 writeExportSection(Exports);
Sam Clegg9e15f352017-06-03 02:01:24 +00001582 writeElemSection(TableElems);
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001583 writeCodeSection(Asm, Layout, Functions);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001584 writeDataSection();
Thomas Livelycbda16e2019-01-17 02:29:55 +00001585 for (auto &CustomSection : CustomSections)
1586 writeCustomSection(CustomSection, Asm, Layout);
Nicholas Wilsonc22bfb62018-03-05 12:59:03 +00001587 writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
Sam Clegg6f08c842018-04-24 18:11:36 +00001588 writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
1589 writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001590 writeCustomRelocSections();
Thomas Livelycbda16e2019-01-17 02:29:55 +00001591 if (ProducersSection)
1592 writeCustomSection(*ProducersSection, Asm, Layout);
Dan Gohman970d02c2017-03-30 23:58:19 +00001593
Dan Gohmand934cb82017-02-24 23:18:00 +00001594 // TODO: Translate the .comment section to the output.
Peter Collingbourne438390f2018-05-21 18:23:50 +00001595 return W.OS.tell() - StartOffset;
Dan Gohman18eafb62017-02-22 01:23:18 +00001596}
1597
Lang Hames60fbc7c2017-10-10 16:28:07 +00001598std::unique_ptr<MCObjectWriter>
Lang Hames1301a872017-10-10 01:15:10 +00001599llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
1600 raw_pwrite_stream &OS) {
Dan Gohman0917c9e2018-01-15 17:06:23 +00001601 return llvm::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
Dan Gohman18eafb62017-02-22 01:23:18 +00001602}