blob: 333748db91904c4a264247ca5de55642c9f5ed88 [file] [log] [blame]
Dan Gohmand660a5d2017-02-22 01:23:18 +00001//===- lib/MC/WasmObjectWriter.cpp - Wasm File Writer ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements Wasm object file writer information.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/ADT/STLExtras.h"
15#include "llvm/ADT/SmallPtrSet.h"
Zachary Turner19ca2b02017-06-07 03:48:56 +000016#include "llvm/BinaryFormat/Wasm.h"
Nico Weber0f38c602018-04-30 14:59:11 +000017#include "llvm/Config/llvm-config.h"
Dan Gohmand660a5d2017-02-22 01:23:18 +000018#include "llvm/MC/MCAsmBackend.h"
Dan Gohmand660a5d2017-02-22 01:23:18 +000019#include "llvm/MC/MCAsmLayout.h"
20#include "llvm/MC/MCAssembler.h"
21#include "llvm/MC/MCContext.h"
22#include "llvm/MC/MCExpr.h"
23#include "llvm/MC/MCFixupKindInfo.h"
Dan Gohmand660a5d2017-02-22 01:23:18 +000024#include "llvm/MC/MCObjectWriter.h"
25#include "llvm/MC/MCSectionWasm.h"
26#include "llvm/MC/MCSymbolWasm.h"
27#include "llvm/MC/MCValue.h"
28#include "llvm/MC/MCWasmObjectWriter.h"
Dan Gohman53ff96a2017-02-24 23:18:00 +000029#include "llvm/Support/Casting.h"
Dan Gohmand660a5d2017-02-22 01:23:18 +000030#include "llvm/Support/Debug.h"
Dan Gohmand660a5d2017-02-22 01:23:18 +000031#include "llvm/Support/ErrorHandling.h"
Dan Gohman53ff96a2017-02-24 23:18:00 +000032#include "llvm/Support/LEB128.h"
Dan Gohmand660a5d2017-02-22 01:23:18 +000033#include "llvm/Support/StringSaver.h"
34#include <vector>
35
36using namespace llvm;
37
Sam Clegg20bde082017-07-07 02:01:29 +000038#define DEBUG_TYPE "mc"
Dan Gohmand660a5d2017-02-22 01:23:18 +000039
40namespace {
Sam Clegg4efa61f2017-06-03 02:01:24 +000041
Sam Clegg3fb85bc2018-01-19 18:57:01 +000042// Went we ceate the indirect function table we start at 1, so that there is
43// and emtpy slot at 0 and therefore calling a null function pointer will trap.
44static const uint32_t kInitialTableOffset = 1;
45
Dan Gohman53ff96a2017-02-24 23:18:00 +000046// For patching purposes, we need to remember where each section starts, both
47// for patching up the section size field, and for patching up references to
48// locations within the section.
49struct SectionBookkeeping {
50 // Where the size of the section is written.
51 uint64_t SizeOffset;
Sam Cleggdb159752018-04-26 19:27:28 +000052 // Where the section header ends (without custom section name).
53 uint64_t PayloadOffset;
54 // Where the contents of the section starts.
Dan Gohman53ff96a2017-02-24 23:18:00 +000055 uint64_t ContentsOffset;
Sam Clegg194a4e02018-04-24 18:11:36 +000056 uint32_t Index;
Dan Gohman53ff96a2017-02-24 23:18:00 +000057};
58
Heejin Ahn8bcdd042018-11-14 02:46:21 +000059// The signature of a wasm function or event, in a struct capable of being used
60// as a DenseMap key.
61// TODO: Consider using wasm::WasmSignature directly instead.
62struct WasmSignature {
Sam Clegg4efa61f2017-06-03 02:01:24 +000063 // Support empty and tombstone instances, needed by DenseMap.
64 enum { Plain, Empty, Tombstone } State;
65
66 // The return types of the function.
67 SmallVector<wasm::ValType, 1> Returns;
68
69 // The parameter types of the function.
70 SmallVector<wasm::ValType, 4> Params;
71
Heejin Ahn8bcdd042018-11-14 02:46:21 +000072 WasmSignature() : State(Plain) {}
Sam Clegg4efa61f2017-06-03 02:01:24 +000073
Heejin Ahn8bcdd042018-11-14 02:46:21 +000074 bool operator==(const WasmSignature &Other) const {
Sam Clegg4efa61f2017-06-03 02:01:24 +000075 return State == Other.State && Returns == Other.Returns &&
76 Params == Other.Params;
77 }
78};
79
Heejin Ahn8bcdd042018-11-14 02:46:21 +000080// Traits for using WasmSignature in a DenseMap.
81struct WasmSignatureDenseMapInfo {
82 static WasmSignature getEmptyKey() {
83 WasmSignature Sig;
84 Sig.State = WasmSignature::Empty;
85 return Sig;
Sam Clegg4efa61f2017-06-03 02:01:24 +000086 }
Heejin Ahn8bcdd042018-11-14 02:46:21 +000087 static WasmSignature getTombstoneKey() {
88 WasmSignature Sig;
89 Sig.State = WasmSignature::Tombstone;
90 return Sig;
Sam Clegg4efa61f2017-06-03 02:01:24 +000091 }
Heejin Ahn8bcdd042018-11-14 02:46:21 +000092 static unsigned getHashValue(const WasmSignature &Sig) {
93 uintptr_t Value = Sig.State;
94 for (wasm::ValType Ret : Sig.Returns)
Heejin Ahn11e8afc2018-11-02 19:25:09 +000095 Value += DenseMapInfo<uint32_t>::getHashValue(uint32_t(Ret));
Heejin Ahn8bcdd042018-11-14 02:46:21 +000096 for (wasm::ValType Param : Sig.Params)
Heejin Ahn11e8afc2018-11-02 19:25:09 +000097 Value += DenseMapInfo<uint32_t>::getHashValue(uint32_t(Param));
Sam Clegg4efa61f2017-06-03 02:01:24 +000098 return Value;
99 }
Heejin Ahn8bcdd042018-11-14 02:46:21 +0000100 static bool isEqual(const WasmSignature &LHS, const WasmSignature &RHS) {
Sam Clegg4efa61f2017-06-03 02:01:24 +0000101 return LHS == RHS;
102 }
103};
104
Sam Clegg09288822017-09-14 23:07:53 +0000105// A wasm data segment. A wasm binary contains only a single data section
106// but that can contain many segments, each with their own virtual location
107// in memory. Each MCSection data created by llvm is modeled as its own
108// wasm data segment.
109struct WasmDataSegment {
110 MCSectionWasm *Section;
Sam Clegg81e38242017-09-20 19:03:35 +0000111 StringRef Name;
Sam Clegg09288822017-09-14 23:07:53 +0000112 uint32_t Offset;
Sam Clegge2864172017-09-29 16:50:08 +0000113 uint32_t Alignment;
114 uint32_t Flags;
Sam Clegg09288822017-09-14 23:07:53 +0000115 SmallVector<char, 4> Data;
116};
117
Sam Clegg4efa61f2017-06-03 02:01:24 +0000118// A wasm function to be written into the function section.
119struct WasmFunction {
Heejin Ahn8bcdd042018-11-14 02:46:21 +0000120 uint32_t SigIndex;
Sam Clegg4efa61f2017-06-03 02:01:24 +0000121 const MCSymbolWasm *Sym;
122};
123
Sam Clegg4efa61f2017-06-03 02:01:24 +0000124// A wasm global to be written into the global section.
125struct WasmGlobal {
Sam Cleggbfa1dc62018-01-31 19:50:14 +0000126 wasm::WasmGlobalType Type;
Sam Clegg4efa61f2017-06-03 02:01:24 +0000127 uint64_t InitialValue;
Sam Clegg4efa61f2017-06-03 02:01:24 +0000128};
129
Sam Clegge92250a2018-01-09 23:43:14 +0000130// Information about a single item which is part of a COMDAT. For each data
131// segment or function which is in the COMDAT, there is a corresponding
132// WasmComdatEntry.
133struct WasmComdatEntry {
134 unsigned Kind;
135 uint32_t Index;
136};
137
Sam Cleggd6def3a2017-06-06 16:38:59 +0000138// Information about a single relocation.
139struct WasmRelocationEntry {
Heejin Ahn581d2312018-09-05 01:27:38 +0000140 uint64_t Offset; // Where is the relocation.
141 const MCSymbolWasm *Symbol; // The symbol to relocate with.
142 int64_t Addend; // A value to add to the symbol.
143 unsigned Type; // The type of the relocation.
144 const MCSectionWasm *FixupSection; // The section the relocation is targeting.
Sam Cleggd6def3a2017-06-06 16:38:59 +0000145
146 WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
147 int64_t Addend, unsigned Type,
Sam Clegg4f724ef2017-06-21 23:46:41 +0000148 const MCSectionWasm *FixupSection)
Sam Cleggd6def3a2017-06-06 16:38:59 +0000149 : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
150 FixupSection(FixupSection) {}
151
Sam Clegg53a472f2017-06-06 19:15:05 +0000152 bool hasAddend() const {
153 switch (Type) {
Sam Clegg8b020d72017-09-01 17:32:01 +0000154 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
155 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
156 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
Sam Cleggdb159752018-04-26 19:27:28 +0000157 case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32:
158 case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32:
Sam Clegg53a472f2017-06-06 19:15:05 +0000159 return true;
160 default:
161 return false;
162 }
163 }
164
Sam Cleggd6def3a2017-06-06 16:38:59 +0000165 void print(raw_ostream &Out) const {
Heejin Ahn581d2312018-09-05 01:27:38 +0000166 Out << wasm::relocTypetoString(Type) << " Off=" << Offset
167 << ", Sym=" << *Symbol << ", Addend=" << Addend
Sam Clegga9217f62017-09-15 20:54:59 +0000168 << ", FixupSection=" << FixupSection->getSectionName();
Sam Cleggd6def3a2017-06-06 16:38:59 +0000169 }
Sam Clegg1e975c12017-06-20 04:04:59 +0000170
Aaron Ballman1d03d382017-10-15 14:32:27 +0000171#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Sam Clegg1e975c12017-06-20 04:04:59 +0000172 LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
173#endif
Sam Cleggd6def3a2017-06-06 16:38:59 +0000174};
175
Sam Clegg0af44d62018-05-08 00:08:21 +0000176static const uint32_t INVALID_INDEX = -1;
177
Sam Clegg13c09232018-04-05 17:01:39 +0000178struct WasmCustomSection {
Sam Clegg13c09232018-04-05 17:01:39 +0000179
Sam Cleggdb159752018-04-26 19:27:28 +0000180 StringRef Name;
181 MCSectionWasm *Section;
182
183 uint32_t OutputContentsOffset;
184 uint32_t OutputIndex;
185
186 WasmCustomSection(StringRef Name, MCSectionWasm *Section)
187 : Name(Name), Section(Section), OutputContentsOffset(0),
188 OutputIndex(INVALID_INDEX) {}
Sam Clegg13c09232018-04-05 17:01:39 +0000189};
190
Sam Clegg5fc12bf2017-06-20 05:05:10 +0000191#if !defined(NDEBUG)
Sam Cleggad60de32017-06-20 04:47:58 +0000192raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
Sam Clegg1e975c12017-06-20 04:04:59 +0000193 Rel.print(OS);
194 return OS;
195}
Sam Clegg5fc12bf2017-06-20 05:05:10 +0000196#endif
Sam Clegg1e975c12017-06-20 04:04:59 +0000197
Dan Gohmand660a5d2017-02-22 01:23:18 +0000198class WasmObjectWriter : public MCObjectWriter {
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000199 support::endian::Writer W;
200
Dan Gohmand660a5d2017-02-22 01:23:18 +0000201 /// The target specific Wasm writer instance.
202 std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
203
Dan Gohman53ff96a2017-02-24 23:18:00 +0000204 // Relocations for fixing up references in the code section.
205 std::vector<WasmRelocationEntry> CodeRelocations;
Sam Clegg194a4e02018-04-24 18:11:36 +0000206 uint32_t CodeSectionIndex;
Dan Gohman53ff96a2017-02-24 23:18:00 +0000207
208 // Relocations for fixing up references in the data section.
209 std::vector<WasmRelocationEntry> DataRelocations;
Sam Clegg194a4e02018-04-24 18:11:36 +0000210 uint32_t DataSectionIndex;
Dan Gohman53ff96a2017-02-24 23:18:00 +0000211
Dan Gohman53ff96a2017-02-24 23:18:00 +0000212 // Index values to use for fixing up call_indirect type indices.
Sam Clegg53a472f2017-06-06 19:15:05 +0000213 // Maps function symbols to the index of the type of the function
214 DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
Sam Cleggd291c782017-06-12 23:52:44 +0000215 // Maps function symbols to the table element index space. Used
216 // for TABLE_INDEX relocation types (i.e. address taken functions).
Sam Clegg58528fe2018-01-31 19:28:47 +0000217 DenseMap<const MCSymbolWasm *, uint32_t> TableIndices;
Heejin Ahn8bcdd042018-11-14 02:46:21 +0000218 // Maps function/global symbols to the function/global/event/section index
219 // space.
Sam Cleggd5784792018-02-23 05:08:34 +0000220 DenseMap<const MCSymbolWasm *, uint32_t> WasmIndices;
221 // Maps data symbols to the Wasm segment and offset/size with the segment.
222 DenseMap<const MCSymbolWasm *, wasm::WasmDataReference> DataLocations;
Sam Cleggdb159752018-04-26 19:27:28 +0000223
224 // Stores output data (index, relocations, content offset) for custom
225 // section.
226 std::vector<WasmCustomSection> CustomSections;
227 // Relocations for fixing up references in the custom sections.
228 DenseMap<const MCSectionWasm *, std::vector<WasmRelocationEntry>>
229 CustomSectionsRelocations;
Sam Clegg53a472f2017-06-06 19:15:05 +0000230
Sam Clegg70666812018-05-17 17:15:15 +0000231 // Map from section to defining function symbol.
Sam Clegg38b696a2018-05-16 20:09:05 +0000232 DenseMap<const MCSection *, const MCSymbol *> SectionFunctions;
233
Heejin Ahn8bcdd042018-11-14 02:46:21 +0000234 DenseMap<WasmSignature, uint32_t, WasmSignatureDenseMapInfo> SignatureIndices;
235 SmallVector<WasmSignature, 4> Signatures;
Sam Clegg09288822017-09-14 23:07:53 +0000236 SmallVector<WasmGlobal, 4> Globals;
Sam Cleggd5784792018-02-23 05:08:34 +0000237 SmallVector<WasmDataSegment, 4> DataSegments;
Sam Cleggeb7fd732018-01-17 19:28:43 +0000238 unsigned NumFunctionImports = 0;
Sam Clegg09288822017-09-14 23:07:53 +0000239 unsigned NumGlobalImports = 0;
Heejin Ahn8bcdd042018-11-14 02:46:21 +0000240 unsigned NumEventImports = 0;
Chandler Carruth8801c5f2018-04-24 20:30:56 +0000241 uint32_t SectionCount = 0;
Dan Gohman53ff96a2017-02-24 23:18:00 +0000242
Dan Gohmand660a5d2017-02-22 01:23:18 +0000243 // TargetObjectWriter wrappers.
244 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
Sam Cleggcf4091e2017-06-13 18:51:50 +0000245 unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup) const {
246 return TargetObjectWriter->getRelocType(Target, Fixup);
Dan Gohmand660a5d2017-02-22 01:23:18 +0000247 }
248
Sam Clegg3f469462018-04-23 19:16:19 +0000249 void startSection(SectionBookkeeping &Section, unsigned SectionId);
250 void startCustomSection(SectionBookkeeping &Section, StringRef Name);
Dan Gohman53ff96a2017-02-24 23:18:00 +0000251 void endSection(SectionBookkeeping &Section);
252
Dan Gohmand660a5d2017-02-22 01:23:18 +0000253public:
Lang Hames40108822017-10-10 01:15:10 +0000254 WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
255 raw_pwrite_stream &OS)
Peter Collingbourne2e125e82018-05-21 18:28:57 +0000256 : W(OS, support::little), TargetObjectWriter(std::move(MOTW)) {}
Dan Gohmand660a5d2017-02-22 01:23:18 +0000257
Dan Gohmand660a5d2017-02-22 01:23:18 +0000258 ~WasmObjectWriter() override;
259
Dan Gohmane8afc142018-01-15 17:06:23 +0000260private:
Sam Clegg53a472f2017-06-06 19:15:05 +0000261 void reset() override {
262 CodeRelocations.clear();
263 DataRelocations.clear();
264 TypeIndices.clear();
Sam Cleggd5784792018-02-23 05:08:34 +0000265 WasmIndices.clear();
Sam Clegg58528fe2018-01-31 19:28:47 +0000266 TableIndices.clear();
Sam Cleggd5784792018-02-23 05:08:34 +0000267 DataLocations.clear();
Sam Cleggdb159752018-04-26 19:27:28 +0000268 CustomSectionsRelocations.clear();
Heejin Ahn8bcdd042018-11-14 02:46:21 +0000269 SignatureIndices.clear();
270 Signatures.clear();
Sam Clegg09288822017-09-14 23:07:53 +0000271 Globals.clear();
Sam Cleggd5784792018-02-23 05:08:34 +0000272 DataSegments.clear();
Sam Clegg38b696a2018-05-16 20:09:05 +0000273 SectionFunctions.clear();
Sam Cleggeb7fd732018-01-17 19:28:43 +0000274 NumFunctionImports = 0;
Sam Clegg09288822017-09-14 23:07:53 +0000275 NumGlobalImports = 0;
Sam Clegg1838ee92018-05-30 02:57:20 +0000276 MCObjectWriter::reset();
Sam Clegg53a472f2017-06-06 19:15:05 +0000277 }
278
Dan Gohmand660a5d2017-02-22 01:23:18 +0000279 void writeHeader(const MCAssembler &Asm);
280
281 void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
282 const MCFragment *Fragment, const MCFixup &Fixup,
Rafael Espindola210f5222017-07-11 23:56:10 +0000283 MCValue Target, uint64_t &FixedValue) override;
Dan Gohmand660a5d2017-02-22 01:23:18 +0000284
285 void executePostLayoutBinding(MCAssembler &Asm,
286 const MCAsmLayout &Layout) override;
287
Peter Collingbourne0d4292f2018-05-21 18:23:50 +0000288 uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
Sam Clegg4efa61f2017-06-03 02:01:24 +0000289
Sam Clegg1e975c12017-06-20 04:04:59 +0000290 void writeString(const StringRef Str) {
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000291 encodeULEB128(Str.size(), W.OS);
292 W.OS << Str;
Sam Clegg1e975c12017-06-20 04:04:59 +0000293 }
294
Heejin Ahn581d2312018-09-05 01:27:38 +0000295 void writeValueType(wasm::ValType Ty) { W.OS << static_cast<char>(Ty); }
Sam Clegg4efa61f2017-06-03 02:01:24 +0000296
Heejin Ahn8bcdd042018-11-14 02:46:21 +0000297 void writeTypeSection(ArrayRef<WasmSignature> Signatures);
Sam Cleggddc563a2018-02-12 22:41:29 +0000298 void writeImportSection(ArrayRef<wasm::WasmImport> Imports, uint32_t DataSize,
Sam Clegg9fb34672017-12-11 23:03:38 +0000299 uint32_t NumElements);
Sam Clegg885ad982017-09-15 19:50:44 +0000300 void writeFunctionSection(ArrayRef<WasmFunction> Functions);
Sam Clegg09288822017-09-14 23:07:53 +0000301 void writeGlobalSection();
Sam Cleggddc563a2018-02-12 22:41:29 +0000302 void writeExportSection(ArrayRef<wasm::WasmExport> Exports);
Sam Clegg885ad982017-09-15 19:50:44 +0000303 void writeElemSection(ArrayRef<uint32_t> TableElems);
Sam Clegg4efa61f2017-06-03 02:01:24 +0000304 void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
Sam Clegg885ad982017-09-15 19:50:44 +0000305 ArrayRef<WasmFunction> Functions);
Sam Cleggd5784792018-02-23 05:08:34 +0000306 void writeDataSection();
Heejin Ahn8bcdd042018-11-14 02:46:21 +0000307 void writeEventSection(ArrayRef<wasm::WasmEventType> Events);
Sam Clegg194a4e02018-04-24 18:11:36 +0000308 void writeRelocSection(uint32_t SectionIndex, StringRef Name,
Heejin Ahn581d2312018-09-05 01:27:38 +0000309 std::vector<WasmRelocationEntry> &Relocations);
Sam Cleggb1dd7d62017-09-20 21:17:04 +0000310 void writeLinkingMetaDataSection(
Sam Clegge14b2482018-02-27 23:57:37 +0000311 ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
Sam Clegge92250a2018-01-09 23:43:14 +0000312 ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
Sam Cleggd5784792018-02-23 05:08:34 +0000313 const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats);
Sam Cleggdb159752018-04-26 19:27:28 +0000314 void writeCustomSections(const MCAssembler &Asm, const MCAsmLayout &Layout);
315 void writeCustomRelocSections();
316 void
317 updateCustomSectionRelocations(const SmallVector<WasmFunction, 4> &Functions,
318 const MCAsmLayout &Layout);
Sam Clegg53a472f2017-06-06 19:15:05 +0000319
Sam Clegg09288822017-09-14 23:07:53 +0000320 uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry);
Sam Clegg53a472f2017-06-06 19:15:05 +0000321 void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
322 uint64_t ContentsOffset);
323
Sam Clegg53a472f2017-06-06 19:15:05 +0000324 uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
Sam Clegg194a4e02018-04-24 18:11:36 +0000325 uint32_t getFunctionType(const MCSymbolWasm &Symbol);
Heejin Ahn8bcdd042018-11-14 02:46:21 +0000326 uint32_t getEventType(const MCSymbolWasm &Symbol);
Heejin Ahn5f5b1ef2018-11-20 00:38:10 +0000327 void registerFunctionType(const MCSymbolWasm &Symbol);
328 void registerEventType(const MCSymbolWasm &Symbol);
Dan Gohmand660a5d2017-02-22 01:23:18 +0000329};
Sam Clegg4efa61f2017-06-03 02:01:24 +0000330
Dan Gohmand660a5d2017-02-22 01:23:18 +0000331} // end anonymous namespace
332
333WasmObjectWriter::~WasmObjectWriter() {}
334
Dan Gohman53ff96a2017-02-24 23:18:00 +0000335// Write out a section header and a patchable section size field.
336void WasmObjectWriter::startSection(SectionBookkeeping &Section,
Sam Clegg3f469462018-04-23 19:16:19 +0000337 unsigned SectionId) {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000338 LLVM_DEBUG(dbgs() << "startSection " << SectionId << "\n");
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000339 W.OS << char(SectionId);
Dan Gohman53ff96a2017-02-24 23:18:00 +0000340
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000341 Section.SizeOffset = W.OS.tell();
Dan Gohman53ff96a2017-02-24 23:18:00 +0000342
343 // The section size. We don't know the size yet, so reserve enough space
344 // for any 32-bit value; we'll patch it later.
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000345 encodeULEB128(UINT32_MAX, W.OS);
Dan Gohman53ff96a2017-02-24 23:18:00 +0000346
347 // The position where the section starts, for measuring its size.
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000348 Section.ContentsOffset = W.OS.tell();
349 Section.PayloadOffset = W.OS.tell();
Sam Clegg194a4e02018-04-24 18:11:36 +0000350 Section.Index = SectionCount++;
Sam Clegg3f469462018-04-23 19:16:19 +0000351}
Dan Gohman53ff96a2017-02-24 23:18:00 +0000352
Sam Clegg3f469462018-04-23 19:16:19 +0000353void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section,
354 StringRef Name) {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000355 LLVM_DEBUG(dbgs() << "startCustomSection " << Name << "\n");
Sam Clegg3f469462018-04-23 19:16:19 +0000356 startSection(Section, wasm::WASM_SEC_CUSTOM);
Sam Cleggdb159752018-04-26 19:27:28 +0000357
358 // The position where the section header ends, for measuring its size.
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000359 Section.PayloadOffset = W.OS.tell();
Sam Cleggdb159752018-04-26 19:27:28 +0000360
Dan Gohman53ff96a2017-02-24 23:18:00 +0000361 // Custom sections in wasm also have a string identifier.
Sam Clegg3f469462018-04-23 19:16:19 +0000362 writeString(Name);
Sam Cleggdb159752018-04-26 19:27:28 +0000363
364 // The position where the custom section starts.
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000365 Section.ContentsOffset = W.OS.tell();
Dan Gohman53ff96a2017-02-24 23:18:00 +0000366}
367
368// Now that the section is complete and we know how big it is, patch up the
369// section size field at the start of the section.
370void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000371 uint64_t Size = W.OS.tell() - Section.PayloadOffset;
Dan Gohman53ff96a2017-02-24 23:18:00 +0000372 if (uint32_t(Size) != Size)
373 report_fatal_error("section size does not fit in a uint32_t");
374
Nicola Zaghen0818e782018-05-14 12:53:11 +0000375 LLVM_DEBUG(dbgs() << "endSection size=" << Size << "\n");
Dan Gohman53ff96a2017-02-24 23:18:00 +0000376
377 // Write the final section size to the payload_len field, which follows
378 // the section id byte.
379 uint8_t Buffer[16];
Sam Cleggfa690d42017-09-15 20:34:47 +0000380 unsigned SizeLen = encodeULEB128(Size, Buffer, 5);
Dan Gohman53ff96a2017-02-24 23:18:00 +0000381 assert(SizeLen == 5);
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000382 static_cast<raw_pwrite_stream &>(W.OS).pwrite((char *)Buffer, SizeLen,
383 Section.SizeOffset);
Dan Gohman53ff96a2017-02-24 23:18:00 +0000384}
385
Dan Gohmand660a5d2017-02-22 01:23:18 +0000386// Emit the Wasm header.
387void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000388 W.OS.write(wasm::WasmMagic, sizeof(wasm::WasmMagic));
389 W.write<uint32_t>(wasm::WasmVersion);
Dan Gohmand660a5d2017-02-22 01:23:18 +0000390}
391
392void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
393 const MCAsmLayout &Layout) {
Sam Clegg38b696a2018-05-16 20:09:05 +0000394 // Build a map of sections to the function that defines them, for use
395 // in recordRelocation.
396 for (const MCSymbol &S : Asm.symbols()) {
397 const auto &WS = static_cast<const MCSymbolWasm &>(S);
398 if (WS.isDefined() && WS.isFunction() && !WS.isVariable()) {
399 const auto &Sec = static_cast<const MCSectionWasm &>(S.getSection());
400 auto Pair = SectionFunctions.insert(std::make_pair(&Sec, &S));
401 if (!Pair.second)
402 report_fatal_error("section already has a defining function: " +
403 Sec.getSectionName());
404 }
405 }
Dan Gohmand660a5d2017-02-22 01:23:18 +0000406}
407
408void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
409 const MCAsmLayout &Layout,
410 const MCFragment *Fragment,
411 const MCFixup &Fixup, MCValue Target,
Rafael Espindola210f5222017-07-11 23:56:10 +0000412 uint64_t &FixedValue) {
413 MCAsmBackend &Backend = Asm.getBackend();
414 bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
415 MCFixupKindInfo::FKF_IsPCRel;
Sam Clegg4f724ef2017-06-21 23:46:41 +0000416 const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
Dan Gohman53ff96a2017-02-24 23:18:00 +0000417 uint64_t C = Target.getConstant();
418 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
419 MCContext &Ctx = Asm.getContext();
420
Sam Clegg53341802017-12-15 00:17:10 +0000421 // The .init_array isn't translated as data, so don't do relocations in it.
422 if (FixupSection.getSectionName().startswith(".init_array"))
423 return;
424
Dan Gohman53ff96a2017-02-24 23:18:00 +0000425 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
426 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
427 "Should not have constructed this");
428
429 // Let A, B and C being the components of Target and R be the location of
430 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
431 // If it is pcrel, we want to compute (A - B + C - R).
432
433 // In general, Wasm has no relocations for -B. It can only represent (A + C)
434 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
435 // replace B to implement it: (A - R - K + C)
436 if (IsPCRel) {
437 Ctx.reportError(
438 Fixup.getLoc(),
439 "No relocation available to represent this relative expression");
440 return;
441 }
442
443 const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
444
445 if (SymB.isUndefined()) {
446 Ctx.reportError(Fixup.getLoc(),
447 Twine("symbol '") + SymB.getName() +
448 "' can not be undefined in a subtraction expression");
449 return;
450 }
451
452 assert(!SymB.isAbsolute() && "Should have been folded");
453 const MCSection &SecB = SymB.getSection();
454 if (&SecB != &FixupSection) {
455 Ctx.reportError(Fixup.getLoc(),
456 "Cannot represent a difference across sections");
457 return;
458 }
459
460 uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
461 uint64_t K = SymBOffset - FixupOffset;
462 IsPCRel = true;
463 C -= K;
464 }
465
466 // We either rejected the fixup or folded B into C at this point.
467 const MCSymbolRefExpr *RefA = Target.getSymA();
468 const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
469
Dan Gohman53ff96a2017-02-24 23:18:00 +0000470 if (SymA && SymA->isVariable()) {
471 const MCExpr *Expr = SymA->getVariableValue();
Sam Clegg0d727632017-07-11 02:21:57 +0000472 const auto *Inner = cast<MCSymbolRefExpr>(Expr);
473 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
474 llvm_unreachable("weakref used in reloc not yet implemented");
Dan Gohman53ff96a2017-02-24 23:18:00 +0000475 }
476
477 // Put any constant offset in an addend. Offsets can be negative, and
478 // LLVM expects wrapping, in contrast to wasm's immediates which can't
479 // be negative and don't wrap.
480 FixedValue = 0;
481
Sam Clegg1c4e4c42018-05-02 23:11:38 +0000482 unsigned Type = getRelocType(Target, Fixup);
Sam Cleggcf4091e2017-06-13 18:51:50 +0000483 assert(!IsPCRel);
Sam Clegg46016f22017-06-16 23:59:10 +0000484 assert(SymA);
485
Sam Clegg1c4e4c42018-05-02 23:11:38 +0000486 // Absolute offset within a section or a function.
487 // Currently only supported for for metadata sections.
488 // See: test/MC/WebAssembly/blockaddress.ll
489 if (Type == wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32 ||
490 Type == wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32) {
491 if (!FixupSection.getKind().isMetadata())
492 report_fatal_error("relocations for function or section offsets are "
493 "only supported in metadata sections");
494
495 const MCSymbol *SectionSymbol = nullptr;
496 const MCSection &SecA = SymA->getSection();
497 if (SecA.getKind().isText())
Sam Clegg38b696a2018-05-16 20:09:05 +0000498 SectionSymbol = SectionFunctions.find(&SecA)->second;
Sam Clegg1c4e4c42018-05-02 23:11:38 +0000499 else
500 SectionSymbol = SecA.getBeginSymbol();
501 if (!SectionSymbol)
502 report_fatal_error("section symbol is required for relocation");
503
504 C += Layout.getSymbolOffset(*SymA);
505 SymA = cast<MCSymbolWasm>(SectionSymbol);
506 }
507
508 // Relocation other than R_WEBASSEMBLY_TYPE_INDEX_LEB are required to be
509 // against a named symbol.
510 if (Type != wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) {
511 if (SymA->getName().empty())
512 report_fatal_error("relocations against un-named temporaries are not yet "
513 "supported by wasm");
514
515 SymA->setUsedInReloc();
516 }
Sam Cleggcf4091e2017-06-13 18:51:50 +0000517
Dan Gohman53ff96a2017-02-24 23:18:00 +0000518 WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
Nicola Zaghen0818e782018-05-14 12:53:11 +0000519 LLVM_DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
Dan Gohman53ff96a2017-02-24 23:18:00 +0000520
Sam Cleggdb159752018-04-26 19:27:28 +0000521 if (FixupSection.isWasmData()) {
Dan Gohman53ff96a2017-02-24 23:18:00 +0000522 DataRelocations.push_back(Rec);
Sam Cleggdb159752018-04-26 19:27:28 +0000523 } else if (FixupSection.getKind().isText()) {
Sam Clegg2b6b6ac2017-10-20 21:28:38 +0000524 CodeRelocations.push_back(Rec);
Sam Cleggdb159752018-04-26 19:27:28 +0000525 } else if (FixupSection.getKind().isMetadata()) {
Sam Cleggdb159752018-04-26 19:27:28 +0000526 CustomSectionsRelocations[&FixupSection].push_back(Rec);
527 } else {
Sam Clegg2b6b6ac2017-10-20 21:28:38 +0000528 llvm_unreachable("unexpected section type");
Sam Cleggdb159752018-04-26 19:27:28 +0000529 }
Dan Gohman53ff96a2017-02-24 23:18:00 +0000530}
531
Dan Gohman53ff96a2017-02-24 23:18:00 +0000532// Write X as an (unsigned) LEB value at offset Offset in Stream, padded
533// to allow patching.
Heejin Ahn581d2312018-09-05 01:27:38 +0000534static void WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X,
535 uint64_t Offset) {
Dan Gohman53ff96a2017-02-24 23:18:00 +0000536 uint8_t Buffer[5];
Sam Cleggfa690d42017-09-15 20:34:47 +0000537 unsigned SizeLen = encodeULEB128(X, Buffer, 5);
Dan Gohman53ff96a2017-02-24 23:18:00 +0000538 assert(SizeLen == 5);
539 Stream.pwrite((char *)Buffer, SizeLen, Offset);
540}
541
542// Write X as an signed LEB value at offset Offset in Stream, padded
543// to allow patching.
Heejin Ahn581d2312018-09-05 01:27:38 +0000544static void WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X,
545 uint64_t Offset) {
Dan Gohman53ff96a2017-02-24 23:18:00 +0000546 uint8_t Buffer[5];
Sam Cleggfa690d42017-09-15 20:34:47 +0000547 unsigned SizeLen = encodeSLEB128(X, Buffer, 5);
Dan Gohman53ff96a2017-02-24 23:18:00 +0000548 assert(SizeLen == 5);
549 Stream.pwrite((char *)Buffer, SizeLen, Offset);
550}
551
552// Write X as a plain integer value at offset Offset in Stream.
553static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
554 uint8_t Buffer[4];
555 support::endian::write32le(Buffer, X);
556 Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
557}
558
Heejin Ahn581d2312018-09-05 01:27:38 +0000559static const MCSymbolWasm *ResolveSymbol(const MCSymbolWasm &Symbol) {
Sam Cleggd3108e52017-09-15 19:22:01 +0000560 if (Symbol.isVariable()) {
561 const MCExpr *Expr = Symbol.getVariableValue();
562 auto *Inner = cast<MCSymbolRefExpr>(Expr);
563 return cast<MCSymbolWasm>(&Inner->getSymbol());
564 }
565 return &Symbol;
566}
567
Dan Gohman53ff96a2017-02-24 23:18:00 +0000568// Compute a value to write into the code at the location covered
Sam Clegg5d85c662018-01-23 01:23:17 +0000569// by RelEntry. This value isn't used by the static linker; it just serves
570// to make the object format more readable and more likely to be directly
571// useable.
Sam Clegg09288822017-09-14 23:07:53 +0000572uint32_t
573WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) {
Sam Clegg5d85c662018-01-23 01:23:17 +0000574 switch (RelEntry.Type) {
575 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
Sam Clegg58528fe2018-01-31 19:28:47 +0000576 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: {
577 // Provisional value is table address of the resolved symbol itself
578 const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
579 assert(Sym->isFunction());
580 return TableIndices[Sym];
581 }
Sam Clegg5d85c662018-01-23 01:23:17 +0000582 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
Sam Cleggd5784792018-02-23 05:08:34 +0000583 // Provisional value is same as the index
Sam Clegg5d85c662018-01-23 01:23:17 +0000584 return getRelocationIndexValue(RelEntry);
Sam Cleggd5784792018-02-23 05:08:34 +0000585 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
586 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
Heejin Ahn8bcdd042018-11-14 02:46:21 +0000587 case wasm::R_WEBASSEMBLY_EVENT_INDEX_LEB:
588 // Provisional value is function/global/event Wasm index
Sam Cleggd5784792018-02-23 05:08:34 +0000589 if (!WasmIndices.count(RelEntry.Symbol))
590 report_fatal_error("symbol not found in wasm index space: " +
591 RelEntry.Symbol->getName());
592 return WasmIndices[RelEntry.Symbol];
Sam Clegg1c4e4c42018-05-02 23:11:38 +0000593 case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32:
594 case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32: {
Sam Cleggdb159752018-04-26 19:27:28 +0000595 const auto &Section =
596 static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection());
597 return Section.getSectionOffset() + RelEntry.Addend;
598 }
Sam Clegg5d85c662018-01-23 01:23:17 +0000599 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
600 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
601 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: {
Sam Clegg58528fe2018-01-31 19:28:47 +0000602 // Provisional value is address of the global
Sam Clegg5d85c662018-01-23 01:23:17 +0000603 const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
604 // For undefined symbols, use zero
605 if (!Sym->isDefined())
606 return 0;
Sam Cleggd5784792018-02-23 05:08:34 +0000607 const wasm::WasmDataReference &Ref = DataLocations[Sym];
608 const WasmDataSegment &Segment = DataSegments[Ref.Segment];
Sam Clegg5d85c662018-01-23 01:23:17 +0000609 // Ignore overflow. LLVM allows address arithmetic to silently wrap.
Sam Cleggd5784792018-02-23 05:08:34 +0000610 return Segment.Offset + Ref.Offset + RelEntry.Addend;
Sam Clegg5d85c662018-01-23 01:23:17 +0000611 }
612 default:
613 llvm_unreachable("invalid relocation type");
614 }
Dan Gohman53ff96a2017-02-24 23:18:00 +0000615}
616
Sam Clegga9217f62017-09-15 20:54:59 +0000617static void addData(SmallVectorImpl<char> &DataBytes,
Sam Clegge2864172017-09-29 16:50:08 +0000618 MCSectionWasm &DataSection) {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000619 LLVM_DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n");
Sam Clegga9217f62017-09-15 20:54:59 +0000620
Sam Clegge2864172017-09-29 16:50:08 +0000621 DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
622
Sam Clegga9217f62017-09-15 20:54:59 +0000623 for (const MCFragment &Frag : DataSection) {
624 if (Frag.hasInstructions())
625 report_fatal_error("only data supported in data sections");
626
627 if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
628 if (Align->getValueSize() != 1)
629 report_fatal_error("only byte values supported for alignment");
630 // If nops are requested, use zeros, as this is the data section.
631 uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
Heejin Ahn581d2312018-09-05 01:27:38 +0000632 uint64_t Size =
633 std::min<uint64_t>(alignTo(DataBytes.size(), Align->getAlignment()),
634 DataBytes.size() + Align->getMaxBytesToEmit());
Sam Clegga9217f62017-09-15 20:54:59 +0000635 DataBytes.resize(Size, Value);
636 } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
Nirav Davecdcd5e12018-05-18 17:45:48 +0000637 int64_t NumValues;
638 if (!Fill->getNumValues().evaluateAsAbsolute(NumValues))
Rafael Espindola5d5caec2018-01-09 22:48:37 +0000639 llvm_unreachable("The fill should be an assembler constant");
Nirav Davecdcd5e12018-05-18 17:45:48 +0000640 DataBytes.insert(DataBytes.end(), Fill->getValueSize() * NumValues,
641 Fill->getValue());
Heejin Ahn397841e2018-10-25 23:55:10 +0000642 } else if (auto *LEB = dyn_cast<MCLEBFragment>(&Frag)) {
643 const SmallVectorImpl<char> &Contents = LEB->getContents();
644 DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
Sam Clegga9217f62017-09-15 20:54:59 +0000645 } else {
646 const auto &DataFrag = cast<MCDataFragment>(Frag);
647 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
Sam Clegga9217f62017-09-15 20:54:59 +0000648 DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
649 }
650 }
651
Nicola Zaghen0818e782018-05-14 12:53:11 +0000652 LLVM_DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
Sam Clegga9217f62017-09-15 20:54:59 +0000653}
654
Sam Clegg5d85c662018-01-23 01:23:17 +0000655uint32_t
656WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
657 if (RelEntry.Type == wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) {
Sam Clegg1e975c12017-06-20 04:04:59 +0000658 if (!TypeIndices.count(RelEntry.Symbol))
Sam Clegg20bde082017-07-07 02:01:29 +0000659 report_fatal_error("symbol not found in type index space: " +
Sam Clegg1e975c12017-06-20 04:04:59 +0000660 RelEntry.Symbol->getName());
Sam Clegg53a472f2017-06-06 19:15:05 +0000661 return TypeIndices[RelEntry.Symbol];
Sam Clegg53a472f2017-06-06 19:15:05 +0000662 }
Sam Clegg5d85c662018-01-23 01:23:17 +0000663
Sam Clegg0af44d62018-05-08 00:08:21 +0000664 return RelEntry.Symbol->getIndex();
Sam Clegg53a472f2017-06-06 19:15:05 +0000665}
666
Dan Gohman53ff96a2017-02-24 23:18:00 +0000667// Apply the portions of the relocation records that we can handle ourselves
668// directly.
Sam Clegg53a472f2017-06-06 19:15:05 +0000669void WasmObjectWriter::applyRelocations(
670 ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000671 auto &Stream = static_cast<raw_pwrite_stream &>(W.OS);
Dan Gohman53ff96a2017-02-24 23:18:00 +0000672 for (const WasmRelocationEntry &RelEntry : Relocations) {
673 uint64_t Offset = ContentsOffset +
674 RelEntry.FixupSection->getSectionOffset() +
675 RelEntry.Offset;
Dan Gohman53ff96a2017-02-24 23:18:00 +0000676
Nicola Zaghen0818e782018-05-14 12:53:11 +0000677 LLVM_DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
Sam Clegg5d85c662018-01-23 01:23:17 +0000678 uint32_t Value = getProvisionalValue(RelEntry);
679
Sam Clegg53a472f2017-06-06 19:15:05 +0000680 switch (RelEntry.Type) {
Sam Clegg53a472f2017-06-06 19:15:05 +0000681 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
Sam Clegg46016f22017-06-16 23:59:10 +0000682 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
Sam Clegg5d85c662018-01-23 01:23:17 +0000683 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
684 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
Heejin Ahn8bcdd042018-11-14 02:46:21 +0000685 case wasm::R_WEBASSEMBLY_EVENT_INDEX_LEB:
Dan Gohman53ff96a2017-02-24 23:18:00 +0000686 WritePatchableLEB(Stream, Value, Offset);
687 break;
Sam Clegg5d85c662018-01-23 01:23:17 +0000688 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
689 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
Sam Cleggdb159752018-04-26 19:27:28 +0000690 case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32:
691 case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32:
Dan Gohman53ff96a2017-02-24 23:18:00 +0000692 WriteI32(Stream, Value, Offset);
693 break;
Sam Clegg5d85c662018-01-23 01:23:17 +0000694 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
695 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
696 WritePatchableSLEB(Stream, Value, Offset);
697 break;
Dan Gohman53ff96a2017-02-24 23:18:00 +0000698 default:
Sam Clegg46016f22017-06-16 23:59:10 +0000699 llvm_unreachable("invalid relocation type");
Dan Gohman53ff96a2017-02-24 23:18:00 +0000700 }
701 }
Dan Gohmand660a5d2017-02-22 01:23:18 +0000702}
703
Heejin Ahn8bcdd042018-11-14 02:46:21 +0000704void WasmObjectWriter::writeTypeSection(ArrayRef<WasmSignature> Signatures) {
705 if (Signatures.empty())
Sam Clegg4efa61f2017-06-03 02:01:24 +0000706 return;
707
708 SectionBookkeeping Section;
709 startSection(Section, wasm::WASM_SEC_TYPE);
710
Heejin Ahn8bcdd042018-11-14 02:46:21 +0000711 encodeULEB128(Signatures.size(), W.OS);
Sam Clegg4efa61f2017-06-03 02:01:24 +0000712
Heejin Ahn8bcdd042018-11-14 02:46:21 +0000713 for (const WasmSignature &Sig : Signatures) {
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000714 W.OS << char(wasm::WASM_TYPE_FUNC);
Heejin Ahn8bcdd042018-11-14 02:46:21 +0000715 encodeULEB128(Sig.Params.size(), W.OS);
716 for (wasm::ValType Ty : Sig.Params)
Sam Clegg4efa61f2017-06-03 02:01:24 +0000717 writeValueType(Ty);
Heejin Ahn8bcdd042018-11-14 02:46:21 +0000718 encodeULEB128(Sig.Returns.size(), W.OS);
719 for (wasm::ValType Ty : Sig.Returns)
Sam Clegg4efa61f2017-06-03 02:01:24 +0000720 writeValueType(Ty);
721 }
722
723 endSection(Section);
724}
725
Sam Cleggddc563a2018-02-12 22:41:29 +0000726void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
Sam Clegg9fb34672017-12-11 23:03:38 +0000727 uint32_t DataSize,
728 uint32_t NumElements) {
Sam Clegg4efa61f2017-06-03 02:01:24 +0000729 if (Imports.empty())
730 return;
731
Sam Clegg9fb34672017-12-11 23:03:38 +0000732 uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
733
Sam Clegg4efa61f2017-06-03 02:01:24 +0000734 SectionBookkeeping Section;
735 startSection(Section, wasm::WASM_SEC_IMPORT);
736
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000737 encodeULEB128(Imports.size(), W.OS);
Sam Cleggddc563a2018-02-12 22:41:29 +0000738 for (const wasm::WasmImport &Import : Imports) {
739 writeString(Import.Module);
740 writeString(Import.Field);
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000741 W.OS << char(Import.Kind);
Sam Clegg4efa61f2017-06-03 02:01:24 +0000742
743 switch (Import.Kind) {
744 case wasm::WASM_EXTERNAL_FUNCTION:
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000745 encodeULEB128(Import.SigIndex, W.OS);
Sam Clegg4efa61f2017-06-03 02:01:24 +0000746 break;
747 case wasm::WASM_EXTERNAL_GLOBAL:
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000748 W.OS << char(Import.Global.Type);
749 W.OS << char(Import.Global.Mutable ? 1 : 0);
Sam Clegg4efa61f2017-06-03 02:01:24 +0000750 break;
Sam Clegg9fb34672017-12-11 23:03:38 +0000751 case wasm::WASM_EXTERNAL_MEMORY:
Heejin Ahn581d2312018-09-05 01:27:38 +0000752 encodeULEB128(0, W.OS); // flags
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000753 encodeULEB128(NumPages, W.OS); // initial
Sam Clegg9fb34672017-12-11 23:03:38 +0000754 break;
755 case wasm::WASM_EXTERNAL_TABLE:
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000756 W.OS << char(Import.Table.ElemType);
Heejin Ahn581d2312018-09-05 01:27:38 +0000757 encodeULEB128(0, W.OS); // flags
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000758 encodeULEB128(NumElements, W.OS); // initial
Sam Clegg9fb34672017-12-11 23:03:38 +0000759 break;
Heejin Ahn8bcdd042018-11-14 02:46:21 +0000760 case wasm::WASM_EXTERNAL_EVENT:
761 encodeULEB128(Import.Event.Attribute, W.OS);
762 encodeULEB128(Import.Event.SigIndex, W.OS);
763 break;
Sam Clegg4efa61f2017-06-03 02:01:24 +0000764 default:
765 llvm_unreachable("unsupported import kind");
766 }
767 }
768
769 endSection(Section);
770}
771
Sam Clegg885ad982017-09-15 19:50:44 +0000772void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
Sam Clegg4efa61f2017-06-03 02:01:24 +0000773 if (Functions.empty())
774 return;
775
776 SectionBookkeeping Section;
777 startSection(Section, wasm::WASM_SEC_FUNCTION);
778
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000779 encodeULEB128(Functions.size(), W.OS);
Sam Clegg4efa61f2017-06-03 02:01:24 +0000780 for (const WasmFunction &Func : Functions)
Heejin Ahn8bcdd042018-11-14 02:46:21 +0000781 encodeULEB128(Func.SigIndex, W.OS);
Sam Clegg4efa61f2017-06-03 02:01:24 +0000782
783 endSection(Section);
784}
785
Sam Clegg09288822017-09-14 23:07:53 +0000786void WasmObjectWriter::writeGlobalSection() {
Sam Clegg4efa61f2017-06-03 02:01:24 +0000787 if (Globals.empty())
788 return;
789
790 SectionBookkeeping Section;
791 startSection(Section, wasm::WASM_SEC_GLOBAL);
792
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000793 encodeULEB128(Globals.size(), W.OS);
Sam Clegg4efa61f2017-06-03 02:01:24 +0000794 for (const WasmGlobal &Global : Globals) {
Sam Cleggbfa1dc62018-01-31 19:50:14 +0000795 writeValueType(static_cast<wasm::ValType>(Global.Type.Type));
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000796 W.OS << char(Global.Type.Mutable);
Sam Clegg4efa61f2017-06-03 02:01:24 +0000797
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000798 W.OS << char(wasm::WASM_OPCODE_I32_CONST);
799 encodeSLEB128(Global.InitialValue, W.OS);
800 W.OS << char(wasm::WASM_OPCODE_END);
Sam Clegg4efa61f2017-06-03 02:01:24 +0000801 }
802
803 endSection(Section);
804}
805
Heejin Ahn8bcdd042018-11-14 02:46:21 +0000806void WasmObjectWriter::writeEventSection(ArrayRef<wasm::WasmEventType> Events) {
807 if (Events.empty())
808 return;
809
810 SectionBookkeeping Section;
811 startSection(Section, wasm::WASM_SEC_EVENT);
812
813 encodeULEB128(Events.size(), W.OS);
814 for (const wasm::WasmEventType &Event : Events) {
815 encodeULEB128(Event.Attribute, W.OS);
816 encodeULEB128(Event.SigIndex, W.OS);
817 }
818
819 endSection(Section);
820}
821
Sam Cleggddc563a2018-02-12 22:41:29 +0000822void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
Sam Clegg4efa61f2017-06-03 02:01:24 +0000823 if (Exports.empty())
824 return;
825
826 SectionBookkeeping Section;
827 startSection(Section, wasm::WASM_SEC_EXPORT);
828
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000829 encodeULEB128(Exports.size(), W.OS);
Sam Cleggddc563a2018-02-12 22:41:29 +0000830 for (const wasm::WasmExport &Export : Exports) {
831 writeString(Export.Name);
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000832 W.OS << char(Export.Kind);
833 encodeULEB128(Export.Index, W.OS);
Sam Clegg4efa61f2017-06-03 02:01:24 +0000834 }
835
836 endSection(Section);
837}
838
Sam Clegg885ad982017-09-15 19:50:44 +0000839void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
Sam Clegg4efa61f2017-06-03 02:01:24 +0000840 if (TableElems.empty())
841 return;
842
843 SectionBookkeeping Section;
844 startSection(Section, wasm::WASM_SEC_ELEM);
845
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000846 encodeULEB128(1, W.OS); // number of "segments"
847 encodeULEB128(0, W.OS); // the table index
Sam Clegg4efa61f2017-06-03 02:01:24 +0000848
849 // init expr for starting offset
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000850 W.OS << char(wasm::WASM_OPCODE_I32_CONST);
851 encodeSLEB128(kInitialTableOffset, W.OS);
852 W.OS << char(wasm::WASM_OPCODE_END);
Sam Clegg4efa61f2017-06-03 02:01:24 +0000853
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000854 encodeULEB128(TableElems.size(), W.OS);
Sam Clegg4efa61f2017-06-03 02:01:24 +0000855 for (uint32_t Elem : TableElems)
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000856 encodeULEB128(Elem, W.OS);
Sam Clegg4efa61f2017-06-03 02:01:24 +0000857
858 endSection(Section);
859}
860
Sam Clegg885ad982017-09-15 19:50:44 +0000861void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
862 const MCAsmLayout &Layout,
863 ArrayRef<WasmFunction> Functions) {
Sam Clegg4efa61f2017-06-03 02:01:24 +0000864 if (Functions.empty())
865 return;
866
867 SectionBookkeeping Section;
868 startSection(Section, wasm::WASM_SEC_CODE);
Sam Clegg194a4e02018-04-24 18:11:36 +0000869 CodeSectionIndex = Section.Index;
Sam Clegg4efa61f2017-06-03 02:01:24 +0000870
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000871 encodeULEB128(Functions.size(), W.OS);
Sam Clegg4efa61f2017-06-03 02:01:24 +0000872
873 for (const WasmFunction &Func : Functions) {
Sam Clegg4f724ef2017-06-21 23:46:41 +0000874 auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
Sam Clegg4efa61f2017-06-03 02:01:24 +0000875
Sam Clegg4efa61f2017-06-03 02:01:24 +0000876 int64_t Size = 0;
877 if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
878 report_fatal_error(".size expression must be evaluatable");
879
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000880 encodeULEB128(Size, W.OS);
881 FuncSection.setSectionOffset(W.OS.tell() - Section.ContentsOffset);
882 Asm.writeSectionData(W.OS, &FuncSection, Layout);
Sam Clegg4efa61f2017-06-03 02:01:24 +0000883 }
884
Sam Clegg4efa61f2017-06-03 02:01:24 +0000885 // Apply fixups.
Sam Clegg53a472f2017-06-06 19:15:05 +0000886 applyRelocations(CodeRelocations, Section.ContentsOffset);
Sam Clegg4efa61f2017-06-03 02:01:24 +0000887
888 endSection(Section);
889}
890
Sam Cleggd5784792018-02-23 05:08:34 +0000891void WasmObjectWriter::writeDataSection() {
892 if (DataSegments.empty())
Sam Clegg09288822017-09-14 23:07:53 +0000893 return;
Sam Clegg4efa61f2017-06-03 02:01:24 +0000894
895 SectionBookkeeping Section;
896 startSection(Section, wasm::WASM_SEC_DATA);
Sam Clegg194a4e02018-04-24 18:11:36 +0000897 DataSectionIndex = Section.Index;
Sam Clegg4efa61f2017-06-03 02:01:24 +0000898
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000899 encodeULEB128(DataSegments.size(), W.OS); // count
Sam Clegg09288822017-09-14 23:07:53 +0000900
Sam Cleggd5784792018-02-23 05:08:34 +0000901 for (const WasmDataSegment &Segment : DataSegments) {
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000902 encodeULEB128(0, W.OS); // memory index
903 W.OS << char(wasm::WASM_OPCODE_I32_CONST);
904 encodeSLEB128(Segment.Offset, W.OS); // offset
905 W.OS << char(wasm::WASM_OPCODE_END);
906 encodeULEB128(Segment.Data.size(), W.OS); // size
907 Segment.Section->setSectionOffset(W.OS.tell() - Section.ContentsOffset);
908 W.OS << Segment.Data; // data
Sam Clegg09288822017-09-14 23:07:53 +0000909 }
Sam Clegg4efa61f2017-06-03 02:01:24 +0000910
911 // Apply fixups.
Sam Clegg09288822017-09-14 23:07:53 +0000912 applyRelocations(DataRelocations, Section.ContentsOffset);
Sam Clegg4efa61f2017-06-03 02:01:24 +0000913
914 endSection(Section);
Sam Clegg4efa61f2017-06-03 02:01:24 +0000915}
916
Sam Clegg194a4e02018-04-24 18:11:36 +0000917void WasmObjectWriter::writeRelocSection(
918 uint32_t SectionIndex, StringRef Name,
Heejin Ahn581d2312018-09-05 01:27:38 +0000919 std::vector<WasmRelocationEntry> &Relocs) {
Sam Clegg4efa61f2017-06-03 02:01:24 +0000920 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
921 // for descriptions of the reloc sections.
922
Sam Cleggb4dc85b2018-08-22 17:27:31 +0000923 if (Relocs.empty())
Sam Clegg4efa61f2017-06-03 02:01:24 +0000924 return;
925
Sam Cleggb4dc85b2018-08-22 17:27:31 +0000926 // First, ensure the relocations are sorted in offset order. In general they
927 // should already be sorted since `recordRelocation` is called in offset
928 // order, but for the code section we combine many MC sections into single
929 // wasm section, and this order is determined by the order of Asm.Symbols()
930 // not the sections order.
931 std::stable_sort(
932 Relocs.begin(), Relocs.end(),
933 [](const WasmRelocationEntry &A, const WasmRelocationEntry &B) {
934 return (A.Offset + A.FixupSection->getSectionOffset()) <
935 (B.Offset + B.FixupSection->getSectionOffset());
936 });
937
Sam Clegg4efa61f2017-06-03 02:01:24 +0000938 SectionBookkeeping Section;
Sam Clegg194a4e02018-04-24 18:11:36 +0000939 startCustomSection(Section, std::string("reloc.") + Name.str());
Sam Clegg4efa61f2017-06-03 02:01:24 +0000940
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000941 encodeULEB128(SectionIndex, W.OS);
Sam Cleggb4dc85b2018-08-22 17:27:31 +0000942 encodeULEB128(Relocs.size(), W.OS);
Heejin Ahn581d2312018-09-05 01:27:38 +0000943 for (const WasmRelocationEntry &RelEntry : Relocs) {
944 uint64_t Offset =
945 RelEntry.Offset + RelEntry.FixupSection->getSectionOffset();
Sam Clegg194a4e02018-04-24 18:11:36 +0000946 uint32_t Index = getRelocationIndexValue(RelEntry);
Sam Clegg4efa61f2017-06-03 02:01:24 +0000947
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000948 W.OS << char(RelEntry.Type);
949 encodeULEB128(Offset, W.OS);
950 encodeULEB128(Index, W.OS);
Sam Clegg194a4e02018-04-24 18:11:36 +0000951 if (RelEntry.hasAddend())
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000952 encodeSLEB128(RelEntry.Addend, W.OS);
Sam Clegg194a4e02018-04-24 18:11:36 +0000953 }
Sam Clegg4efa61f2017-06-03 02:01:24 +0000954
955 endSection(Section);
956}
957
Sam Cleggdb159752018-04-26 19:27:28 +0000958void WasmObjectWriter::writeCustomRelocSections() {
959 for (const auto &Sec : CustomSections) {
960 auto &Relocations = CustomSectionsRelocations[Sec.Section];
961 writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations);
962 }
963}
964
Sam Clegg4efa61f2017-06-03 02:01:24 +0000965void WasmObjectWriter::writeLinkingMetaDataSection(
Sam Clegge14b2482018-02-27 23:57:37 +0000966 ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
Sam Clegge92250a2018-01-09 23:43:14 +0000967 ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
Sam Cleggd5784792018-02-23 05:08:34 +0000968 const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
Sam Clegg4efa61f2017-06-03 02:01:24 +0000969 SectionBookkeeping Section;
Sam Clegg3f469462018-04-23 19:16:19 +0000970 startCustomSection(Section, "linking");
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000971 encodeULEB128(wasm::WasmMetadataVersion, W.OS);
Sam Clegg4efa61f2017-06-03 02:01:24 +0000972
Sam Clegg14598cb2018-04-26 18:15:32 +0000973 SectionBookkeeping SubSection;
Sam Cleggd5784792018-02-23 05:08:34 +0000974 if (SymbolInfos.size() != 0) {
975 startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000976 encodeULEB128(SymbolInfos.size(), W.OS);
Sam Cleggd5784792018-02-23 05:08:34 +0000977 for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000978 encodeULEB128(Sym.Kind, W.OS);
979 encodeULEB128(Sym.Flags, W.OS);
Sam Cleggd5784792018-02-23 05:08:34 +0000980 switch (Sym.Kind) {
981 case wasm::WASM_SYMBOL_TYPE_FUNCTION:
982 case wasm::WASM_SYMBOL_TYPE_GLOBAL:
Heejin Ahn8bcdd042018-11-14 02:46:21 +0000983 case wasm::WASM_SYMBOL_TYPE_EVENT:
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000984 encodeULEB128(Sym.ElementIndex, W.OS);
Hans Wennborg831b2042019-02-12 12:27:08 +0000985 if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0 ||
986 (Sym.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0)
Sam Cleggd5784792018-02-23 05:08:34 +0000987 writeString(Sym.Name);
988 break;
989 case wasm::WASM_SYMBOL_TYPE_DATA:
990 writeString(Sym.Name);
991 if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000992 encodeULEB128(Sym.DataRef.Segment, W.OS);
993 encodeULEB128(Sym.DataRef.Offset, W.OS);
994 encodeULEB128(Sym.DataRef.Size, W.OS);
Sam Cleggd5784792018-02-23 05:08:34 +0000995 }
996 break;
Sam Cleggdb159752018-04-26 19:27:28 +0000997 case wasm::WASM_SYMBOL_TYPE_SECTION: {
998 const uint32_t SectionIndex =
999 CustomSections[Sym.ElementIndex].OutputIndex;
Peter Collingbourne8e93a952018-05-21 18:17:42 +00001000 encodeULEB128(SectionIndex, W.OS);
Sam Cleggdb159752018-04-26 19:27:28 +00001001 break;
1002 }
Sam Cleggd5784792018-02-23 05:08:34 +00001003 default:
1004 llvm_unreachable("unexpected kind");
1005 }
Sam Clegg1e975c12017-06-20 04:04:59 +00001006 }
1007 endSection(SubSection);
1008 }
Sam Clegg4efa61f2017-06-03 02:01:24 +00001009
Sam Cleggd5784792018-02-23 05:08:34 +00001010 if (DataSegments.size()) {
Sam Clegge2864172017-09-29 16:50:08 +00001011 startSection(SubSection, wasm::WASM_SEGMENT_INFO);
Peter Collingbourne8e93a952018-05-21 18:17:42 +00001012 encodeULEB128(DataSegments.size(), W.OS);
Sam Cleggd5784792018-02-23 05:08:34 +00001013 for (const WasmDataSegment &Segment : DataSegments) {
Sam Clegg81e38242017-09-20 19:03:35 +00001014 writeString(Segment.Name);
Peter Collingbourne8e93a952018-05-21 18:17:42 +00001015 encodeULEB128(Segment.Alignment, W.OS);
1016 encodeULEB128(Segment.Flags, W.OS);
Sam Clegge2864172017-09-29 16:50:08 +00001017 }
Sam Clegg81e38242017-09-20 19:03:35 +00001018 endSection(SubSection);
1019 }
1020
Sam Clegg53341802017-12-15 00:17:10 +00001021 if (!InitFuncs.empty()) {
1022 startSection(SubSection, wasm::WASM_INIT_FUNCS);
Peter Collingbourne8e93a952018-05-21 18:17:42 +00001023 encodeULEB128(InitFuncs.size(), W.OS);
Sam Clegg53341802017-12-15 00:17:10 +00001024 for (auto &StartFunc : InitFuncs) {
Heejin Ahn581d2312018-09-05 01:27:38 +00001025 encodeULEB128(StartFunc.first, W.OS); // priority
Peter Collingbourne8e93a952018-05-21 18:17:42 +00001026 encodeULEB128(StartFunc.second, W.OS); // function index
Sam Clegg53341802017-12-15 00:17:10 +00001027 }
1028 endSection(SubSection);
1029 }
1030
Sam Clegge92250a2018-01-09 23:43:14 +00001031 if (Comdats.size()) {
1032 startSection(SubSection, wasm::WASM_COMDAT_INFO);
Peter Collingbourne8e93a952018-05-21 18:17:42 +00001033 encodeULEB128(Comdats.size(), W.OS);
Sam Clegge92250a2018-01-09 23:43:14 +00001034 for (const auto &C : Comdats) {
1035 writeString(C.first);
Peter Collingbourne8e93a952018-05-21 18:17:42 +00001036 encodeULEB128(0, W.OS); // flags for future use
1037 encodeULEB128(C.second.size(), W.OS);
Sam Clegge92250a2018-01-09 23:43:14 +00001038 for (const WasmComdatEntry &Entry : C.second) {
Peter Collingbourne8e93a952018-05-21 18:17:42 +00001039 encodeULEB128(Entry.Kind, W.OS);
1040 encodeULEB128(Entry.Index, W.OS);
Sam Clegge92250a2018-01-09 23:43:14 +00001041 }
1042 }
1043 endSection(SubSection);
1044 }
1045
Sam Clegg4efa61f2017-06-03 02:01:24 +00001046 endSection(Section);
1047}
1048
Sam Cleggdb159752018-04-26 19:27:28 +00001049void WasmObjectWriter::writeCustomSections(const MCAssembler &Asm,
1050 const MCAsmLayout &Layout) {
1051 for (auto &CustomSection : CustomSections) {
Sam Clegg13c09232018-04-05 17:01:39 +00001052 SectionBookkeeping Section;
Sam Cleggdb159752018-04-26 19:27:28 +00001053 auto *Sec = CustomSection.Section;
Sam Clegg3f469462018-04-23 19:16:19 +00001054 startCustomSection(Section, CustomSection.Name);
Sam Cleggdb159752018-04-26 19:27:28 +00001055
Peter Collingbourne8e93a952018-05-21 18:17:42 +00001056 Sec->setSectionOffset(W.OS.tell() - Section.ContentsOffset);
1057 Asm.writeSectionData(W.OS, Sec, Layout);
Sam Cleggdb159752018-04-26 19:27:28 +00001058
1059 CustomSection.OutputContentsOffset = Section.ContentsOffset;
1060 CustomSection.OutputIndex = Section.Index;
1061
Sam Clegg13c09232018-04-05 17:01:39 +00001062 endSection(Section);
Sam Cleggdb159752018-04-26 19:27:28 +00001063
1064 // Apply fixups.
Sam Clegg1c4e4c42018-05-02 23:11:38 +00001065 auto &Relocations = CustomSectionsRelocations[CustomSection.Section];
1066 applyRelocations(Relocations, CustomSection.OutputContentsOffset);
Sam Cleggdb159752018-04-26 19:27:28 +00001067 }
1068}
1069
Heejin Ahn581d2312018-09-05 01:27:38 +00001070uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm &Symbol) {
Sam Clegg20bde082017-07-07 02:01:29 +00001071 assert(Symbol.isFunction());
1072 assert(TypeIndices.count(&Symbol));
1073 return TypeIndices[&Symbol];
1074}
1075
Heejin Ahn8bcdd042018-11-14 02:46:21 +00001076uint32_t WasmObjectWriter::getEventType(const MCSymbolWasm &Symbol) {
1077 assert(Symbol.isEvent());
1078 assert(TypeIndices.count(&Symbol));
1079 return TypeIndices[&Symbol];
1080}
1081
Heejin Ahn5f5b1ef2018-11-20 00:38:10 +00001082void WasmObjectWriter::registerFunctionType(const MCSymbolWasm &Symbol) {
Sam Clegg20bde082017-07-07 02:01:29 +00001083 assert(Symbol.isFunction());
1084
Heejin Ahn8bcdd042018-11-14 02:46:21 +00001085 WasmSignature S;
Heejin Ahn581d2312018-09-05 01:27:38 +00001086 const MCSymbolWasm *ResolvedSym = ResolveSymbol(Symbol);
Derek Schuffab9755b2018-10-03 22:22:48 +00001087 if (auto *Sig = ResolvedSym->getSignature()) {
Heejin Ahn8bcdd042018-11-14 02:46:21 +00001088 S.Returns = Sig->Returns;
1089 S.Params = Sig->Params;
Derek Schuffab9755b2018-10-03 22:22:48 +00001090 }
Sam Clegg20bde082017-07-07 02:01:29 +00001091
Heejin Ahn8bcdd042018-11-14 02:46:21 +00001092 auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
Sam Clegg20bde082017-07-07 02:01:29 +00001093 if (Pair.second)
Heejin Ahn8bcdd042018-11-14 02:46:21 +00001094 Signatures.push_back(S);
Sam Clegg20bde082017-07-07 02:01:29 +00001095 TypeIndices[&Symbol] = Pair.first->second;
1096
Nicola Zaghen0818e782018-05-14 12:53:11 +00001097 LLVM_DEBUG(dbgs() << "registerFunctionType: " << Symbol
1098 << " new:" << Pair.second << "\n");
1099 LLVM_DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n");
Sam Clegg20bde082017-07-07 02:01:29 +00001100}
1101
Heejin Ahn5f5b1ef2018-11-20 00:38:10 +00001102void WasmObjectWriter::registerEventType(const MCSymbolWasm &Symbol) {
Heejin Ahn8bcdd042018-11-14 02:46:21 +00001103 assert(Symbol.isEvent());
1104
1105 // TODO Currently we don't generate imported exceptions, but if we do, we
1106 // should have a way of infering types of imported exceptions.
1107 WasmSignature S;
1108 if (auto *Sig = Symbol.getSignature()) {
1109 S.Returns = Sig->Returns;
1110 S.Params = Sig->Params;
1111 }
1112
1113 auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
1114 if (Pair.second)
1115 Signatures.push_back(S);
1116 TypeIndices[&Symbol] = Pair.first->second;
1117
1118 LLVM_DEBUG(dbgs() << "registerEventType: " << Symbol << " new:" << Pair.second
1119 << "\n");
1120 LLVM_DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n");
Heejin Ahn8bcdd042018-11-14 02:46:21 +00001121}
1122
Sam Clegg1c4e4c42018-05-02 23:11:38 +00001123static bool isInSymtab(const MCSymbolWasm &Sym) {
1124 if (Sym.isUsedInReloc())
1125 return true;
1126
1127 if (Sym.isComdat() && !Sym.isDefined())
1128 return false;
1129
1130 if (Sym.isTemporary() && Sym.getName().empty())
1131 return false;
1132
1133 if (Sym.isTemporary() && Sym.isData() && !Sym.getSize())
1134 return false;
1135
1136 if (Sym.isSection())
1137 return false;
1138
1139 return true;
1140}
1141
Peter Collingbourne0d4292f2018-05-21 18:23:50 +00001142uint64_t WasmObjectWriter::writeObject(MCAssembler &Asm,
1143 const MCAsmLayout &Layout) {
1144 uint64_t StartOffset = W.OS.tell();
1145
Nicola Zaghen0818e782018-05-14 12:53:11 +00001146 LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
Dan Gohman8f5a7d62017-02-24 23:46:05 +00001147 MCContext &Ctx = Asm.getContext();
Dan Gohman53ff96a2017-02-24 23:18:00 +00001148
1149 // Collect information from the available symbols.
Dan Gohman53ff96a2017-02-24 23:18:00 +00001150 SmallVector<WasmFunction, 4> Functions;
1151 SmallVector<uint32_t, 4> TableElems;
Sam Cleggddc563a2018-02-12 22:41:29 +00001152 SmallVector<wasm::WasmImport, 4> Imports;
1153 SmallVector<wasm::WasmExport, 4> Exports;
Heejin Ahn8bcdd042018-11-14 02:46:21 +00001154 SmallVector<wasm::WasmEventType, 1> Events;
Sam Cleggd5784792018-02-23 05:08:34 +00001155 SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
Sam Clegg53341802017-12-15 00:17:10 +00001156 SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
Sam Clegge92250a2018-01-09 23:43:14 +00001157 std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
Sam Clegg09288822017-09-14 23:07:53 +00001158 uint32_t DataSize = 0;
Dan Gohman53ff96a2017-02-24 23:18:00 +00001159
Sam Clegg9fb34672017-12-11 23:03:38 +00001160 // For now, always emit the memory import, since loads and stores are not
1161 // valid without it. In the future, we could perhaps be more clever and omit
1162 // it if there are no loads or stores.
1163 MCSymbolWasm *MemorySym =
1164 cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__linear_memory"));
Sam Cleggddc563a2018-02-12 22:41:29 +00001165 wasm::WasmImport MemImport;
Hans Wennborg831b2042019-02-12 12:27:08 +00001166 MemImport.Module = MemorySym->getImportModule();
1167 MemImport.Field = MemorySym->getImportName();
Sam Clegg9fb34672017-12-11 23:03:38 +00001168 MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1169 Imports.push_back(MemImport);
1170
1171 // For now, always emit the table section, since indirect calls are not
1172 // valid without it. In the future, we could perhaps be more clever and omit
1173 // it if there are no indirect calls.
1174 MCSymbolWasm *TableSym =
1175 cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__indirect_function_table"));
Sam Cleggddc563a2018-02-12 22:41:29 +00001176 wasm::WasmImport TableImport;
Hans Wennborg831b2042019-02-12 12:27:08 +00001177 TableImport.Module = TableSym->getImportModule();
1178 TableImport.Field = TableSym->getImportName();
Sam Clegg9fb34672017-12-11 23:03:38 +00001179 TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
Thomas Lively37a984b2019-01-08 06:25:55 +00001180 TableImport.Table.ElemType = wasm::WASM_TYPE_FUNCREF;
Sam Clegg9fb34672017-12-11 23:03:38 +00001181 Imports.push_back(TableImport);
1182
Heejin Ahn8bcdd042018-11-14 02:46:21 +00001183 // Populate SignatureIndices, and Imports and WasmIndices for undefined
Nicholas Wilson15d65982018-02-28 17:19:48 +00001184 // symbols. This must be done before populating WasmIndices for defined
1185 // symbols.
Dan Gohmanca99fdb2017-12-05 18:29:48 +00001186 for (const MCSymbol &S : Asm.symbols()) {
1187 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1188
1189 // Register types for all functions, including those with private linkage
Sam Cleggeb7fd732018-01-17 19:28:43 +00001190 // (because wasm always needs a type signature).
Dan Gohmanca99fdb2017-12-05 18:29:48 +00001191 if (WS.isFunction())
1192 registerFunctionType(WS);
1193
Heejin Ahn8bcdd042018-11-14 02:46:21 +00001194 if (WS.isEvent())
1195 registerEventType(WS);
1196
Dan Gohmanca99fdb2017-12-05 18:29:48 +00001197 if (WS.isTemporary())
1198 continue;
1199
1200 // If the symbol is not defined in this translation unit, import it.
Sam Cleggd5784792018-02-23 05:08:34 +00001201 if (!WS.isDefined() && !WS.isComdat()) {
Dan Gohmanca99fdb2017-12-05 18:29:48 +00001202 if (WS.isFunction()) {
Sam Cleggd5784792018-02-23 05:08:34 +00001203 wasm::WasmImport Import;
Hans Wennborg831b2042019-02-12 12:27:08 +00001204 Import.Module = WS.getImportModule();
1205 Import.Field = WS.getImportName();
Dan Gohmanca99fdb2017-12-05 18:29:48 +00001206 Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
Sam Cleggddc563a2018-02-12 22:41:29 +00001207 Import.SigIndex = getFunctionType(WS);
Sam Cleggd5784792018-02-23 05:08:34 +00001208 Imports.push_back(Import);
1209 WasmIndices[&WS] = NumFunctionImports++;
1210 } else if (WS.isGlobal()) {
Nicholas Wilson44818a32018-03-09 16:30:44 +00001211 if (WS.isWeak())
1212 report_fatal_error("undefined global symbol cannot be weak");
1213
Sam Cleggd5784792018-02-23 05:08:34 +00001214 wasm::WasmImport Import;
Hans Wennborg831b2042019-02-12 12:27:08 +00001215 Import.Module = WS.getImportModule();
1216 Import.Field = WS.getImportName();
Dan Gohmanca99fdb2017-12-05 18:29:48 +00001217 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
Sam Cleggd5784792018-02-23 05:08:34 +00001218 Import.Global = WS.getGlobalType();
1219 Imports.push_back(Import);
1220 WasmIndices[&WS] = NumGlobalImports++;
Heejin Ahn8bcdd042018-11-14 02:46:21 +00001221 } else if (WS.isEvent()) {
1222 if (WS.isWeak())
1223 report_fatal_error("undefined event symbol cannot be weak");
1224
1225 wasm::WasmImport Import;
Hans Wennborg831b2042019-02-12 12:27:08 +00001226 Import.Module = WS.getImportModule();
1227 Import.Field = WS.getImportName();
Heejin Ahn8bcdd042018-11-14 02:46:21 +00001228 Import.Kind = wasm::WASM_EXTERNAL_EVENT;
1229 Import.Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1230 Import.Event.SigIndex = getEventType(WS);
1231 Imports.push_back(Import);
1232 WasmIndices[&WS] = NumEventImports++;
Dan Gohmanca99fdb2017-12-05 18:29:48 +00001233 }
Dan Gohmanca99fdb2017-12-05 18:29:48 +00001234 }
1235 }
1236
Sam Clegg1c4e4c42018-05-02 23:11:38 +00001237 // Populate DataSegments and CustomSections, which must be done before
1238 // populating DataLocations.
Sam Clegga9217f62017-09-15 20:54:59 +00001239 for (MCSection &Sec : Asm) {
1240 auto &Section = static_cast<MCSectionWasm &>(Sec);
Sam Clegg1c4e4c42018-05-02 23:11:38 +00001241 StringRef SectionName = Section.getSectionName();
Sam Clegga9217f62017-09-15 20:54:59 +00001242
Sam Clegg53341802017-12-15 00:17:10 +00001243 // .init_array sections are handled specially elsewhere.
Sam Clegg1c4e4c42018-05-02 23:11:38 +00001244 if (SectionName.startswith(".init_array"))
Sam Clegg53341802017-12-15 00:17:10 +00001245 continue;
1246
Sam Clegg1c4e4c42018-05-02 23:11:38 +00001247 // Code is handled separately
1248 if (Section.getKind().isText())
1249 continue;
Sam Clegge92250a2018-01-09 23:43:14 +00001250
Sam Clegg1c4e4c42018-05-02 23:11:38 +00001251 if (Section.isWasmData()) {
1252 uint32_t SegmentIndex = DataSegments.size();
1253 DataSize = alignTo(DataSize, Section.getAlignment());
1254 DataSegments.emplace_back();
1255 WasmDataSegment &Segment = DataSegments.back();
1256 Segment.Name = SectionName;
1257 Segment.Offset = DataSize;
1258 Segment.Section = &Section;
1259 addData(Segment.Data, Section);
Sam Clegg29aeb332019-01-16 01:34:48 +00001260 Segment.Alignment = Log2_32(Section.getAlignment());
Sam Clegg1c4e4c42018-05-02 23:11:38 +00001261 Segment.Flags = 0;
1262 DataSize += Segment.Data.size();
1263 Section.setSegmentIndex(SegmentIndex);
1264
1265 if (const MCSymbolWasm *C = Section.getGroup()) {
1266 Comdats[C->getName()].emplace_back(
1267 WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
1268 }
1269 } else {
1270 // Create custom sections
1271 assert(Sec.getKind().isMetadata());
1272
1273 StringRef Name = SectionName;
1274
1275 // For user-defined custom sections, strip the prefix
1276 if (Name.startswith(".custom_section."))
1277 Name = Name.substr(strlen(".custom_section."));
1278
Heejin Ahn581d2312018-09-05 01:27:38 +00001279 MCSymbol *Begin = Sec.getBeginSymbol();
Sam Cleggb1872a22018-05-07 19:40:50 +00001280 if (Begin) {
Sam Clegg1c4e4c42018-05-02 23:11:38 +00001281 WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size();
Sam Clegg70b76a12018-05-10 17:38:35 +00001282 if (SectionName != Begin->getName())
Sam Cleggb1872a22018-05-07 19:40:50 +00001283 report_fatal_error("section name and begin symbol should match: " +
Sam Clegg70b76a12018-05-10 17:38:35 +00001284 Twine(SectionName));
Sam Cleggb1872a22018-05-07 19:40:50 +00001285 }
Sam Clegg1c4e4c42018-05-02 23:11:38 +00001286 CustomSections.emplace_back(Name, &Section);
Sam Clegge92250a2018-01-09 23:43:14 +00001287 }
Sam Clegga9217f62017-09-15 20:54:59 +00001288 }
1289
Nicholas Wilson15d65982018-02-28 17:19:48 +00001290 // Populate WasmIndices and DataLocations for defined symbols.
Dan Gohman53ff96a2017-02-24 23:18:00 +00001291 for (const MCSymbol &S : Asm.symbols()) {
1292 // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1293 // or used in relocations.
1294 if (S.isTemporary() && S.getName().empty())
1295 continue;
Sam Clegg1e975c12017-06-20 04:04:59 +00001296
Dan Gohman53ff96a2017-02-24 23:18:00 +00001297 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Nicola Zaghen0818e782018-05-14 12:53:11 +00001298 LLVM_DEBUG(
1299 dbgs() << "MCSymbol: " << toString(WS.getType()) << " '" << S << "'"
1300 << " isDefined=" << S.isDefined() << " isExternal="
1301 << S.isExternal() << " isTemporary=" << S.isTemporary()
1302 << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden()
1303 << " isVariable=" << WS.isVariable() << "\n");
Sam Clegg1e975c12017-06-20 04:04:59 +00001304
Sam Clegg20bde082017-07-07 02:01:29 +00001305 if (WS.isVariable())
1306 continue;
Sam Cleggd5784792018-02-23 05:08:34 +00001307 if (WS.isComdat() && !WS.isDefined())
1308 continue;
Sam Clegg1e975c12017-06-20 04:04:59 +00001309
Dan Gohman53ff96a2017-02-24 23:18:00 +00001310 if (WS.isFunction()) {
Sam Cleggd5784792018-02-23 05:08:34 +00001311 unsigned Index;
Sam Cleggf2243a72018-01-11 23:59:16 +00001312 if (WS.isDefined()) {
Sam Clegg1e975c12017-06-20 04:04:59 +00001313 if (WS.getOffset() != 0)
1314 report_fatal_error(
1315 "function sections must contain one function each");
1316
1317 if (WS.getSize() == 0)
1318 report_fatal_error(
1319 "function symbols must have a size set with .size");
1320
Sam Cleggd5784792018-02-23 05:08:34 +00001321 // A definition. Write out the function body.
Sam Cleggeb7fd732018-01-17 19:28:43 +00001322 Index = NumFunctionImports + Functions.size();
Dan Gohman53ff96a2017-02-24 23:18:00 +00001323 WasmFunction Func;
Heejin Ahn8bcdd042018-11-14 02:46:21 +00001324 Func.SigIndex = getFunctionType(WS);
Dan Gohman53ff96a2017-02-24 23:18:00 +00001325 Func.Sym = &WS;
Sam Cleggd5784792018-02-23 05:08:34 +00001326 WasmIndices[&WS] = Index;
Dan Gohman53ff96a2017-02-24 23:18:00 +00001327 Functions.push_back(Func);
Sam Cleggd5784792018-02-23 05:08:34 +00001328
1329 auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
1330 if (const MCSymbolWasm *C = Section.getGroup()) {
1331 Comdats[C->getName()].emplace_back(
1332 WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
1333 }
Dan Gohman53ff96a2017-02-24 23:18:00 +00001334 } else {
1335 // An import; the index was assigned above.
Sam Cleggd5784792018-02-23 05:08:34 +00001336 Index = WasmIndices.find(&WS)->second;
Dan Gohman53ff96a2017-02-24 23:18:00 +00001337 }
1338
Nicola Zaghen0818e782018-05-14 12:53:11 +00001339 LLVM_DEBUG(dbgs() << " -> function index: " << Index << "\n");
Heejin Ahn8bcdd042018-11-14 02:46:21 +00001340
Sam Cleggd5784792018-02-23 05:08:34 +00001341 } else if (WS.isData()) {
Sam Cleggf83cb572017-06-02 01:05:24 +00001342 if (WS.isTemporary() && !WS.getSize())
1343 continue;
Dan Gohman53ff96a2017-02-24 23:18:00 +00001344
Sam Cleggd5784792018-02-23 05:08:34 +00001345 if (!WS.isDefined()) {
Nicola Zaghen0818e782018-05-14 12:53:11 +00001346 LLVM_DEBUG(dbgs() << " -> segment index: -1"
1347 << "\n");
Sam Clegg4f724ef2017-06-21 23:46:41 +00001348 continue;
Sam Cleggd5784792018-02-23 05:08:34 +00001349 }
Sam Cleggf83cb572017-06-02 01:05:24 +00001350
Sam Clegg4f724ef2017-06-21 23:46:41 +00001351 if (!WS.getSize())
1352 report_fatal_error("data symbols must have a size set with .size: " +
1353 WS.getName());
Sam Cleggf83cb572017-06-02 01:05:24 +00001354
Sam Clegg4f724ef2017-06-21 23:46:41 +00001355 int64_t Size = 0;
1356 if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1357 report_fatal_error(".size expression must be evaluatable");
Dan Gohman53ff96a2017-02-24 23:18:00 +00001358
Sam Clegga9217f62017-09-15 20:54:59 +00001359 auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
Sam Clegge92250a2018-01-09 23:43:14 +00001360 assert(DataSection.isWasmData());
Sam Clegg09288822017-09-14 23:07:53 +00001361
Sam Cleggd5784792018-02-23 05:08:34 +00001362 // For each data symbol, export it in the symtab as a reference to the
1363 // corresponding Wasm data segment.
1364 wasm::WasmDataReference Ref = wasm::WasmDataReference{
1365 DataSection.getSegmentIndex(),
1366 static_cast<uint32_t>(Layout.getSymbolOffset(WS)),
1367 static_cast<uint32_t>(Size)};
1368 DataLocations[&WS] = Ref;
Nicola Zaghen0818e782018-05-14 12:53:11 +00001369 LLVM_DEBUG(dbgs() << " -> segment index: " << Ref.Segment << "\n");
Heejin Ahn8bcdd042018-11-14 02:46:21 +00001370
Sam Clegg8b887212018-04-30 19:40:57 +00001371 } else if (WS.isGlobal()) {
Sam Cleggd5784792018-02-23 05:08:34 +00001372 // A "true" Wasm global (currently just __stack_pointer)
Eric Christopher66a69082018-02-23 21:14:47 +00001373 if (WS.isDefined())
Sam Cleggd5784792018-02-23 05:08:34 +00001374 report_fatal_error("don't yet support defined globals");
Sam Cleggd5784792018-02-23 05:08:34 +00001375
Eric Christopher66a69082018-02-23 21:14:47 +00001376 // An import; the index was assigned above
Nicola Zaghen0818e782018-05-14 12:53:11 +00001377 LLVM_DEBUG(dbgs() << " -> global index: "
1378 << WasmIndices.find(&WS)->second << "\n");
Heejin Ahn8bcdd042018-11-14 02:46:21 +00001379
1380 } else if (WS.isEvent()) {
1381 // C++ exception symbol (__cpp_exception)
1382 unsigned Index;
1383 if (WS.isDefined()) {
1384 Index = NumEventImports + Events.size();
1385 wasm::WasmEventType Event;
1386 Event.SigIndex = getEventType(WS);
1387 Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1388 WasmIndices[&WS] = Index;
1389 Events.push_back(Event);
1390 } else {
1391 // An import; the index was assigned above.
1392 Index = WasmIndices.find(&WS)->second;
1393 }
1394 LLVM_DEBUG(dbgs() << " -> event index: " << WasmIndices.find(&WS)->second
1395 << "\n");
1396
Sam Clegg8b887212018-04-30 19:40:57 +00001397 } else {
1398 assert(WS.isSection());
Dan Gohman53ff96a2017-02-24 23:18:00 +00001399 }
1400 }
1401
Nicholas Wilson15d65982018-02-28 17:19:48 +00001402 // Populate WasmIndices and DataLocations for aliased symbols. We need to
1403 // process these in a separate pass because we need to have processed the
1404 // target of the alias before the alias itself and the symbols are not
1405 // necessarily ordered in this way.
Sam Clegg1e975c12017-06-20 04:04:59 +00001406 for (const MCSymbol &S : Asm.symbols()) {
1407 if (!S.isVariable())
1408 continue;
Sam Cleggb1dd7d62017-09-20 21:17:04 +00001409
Sam Cleggf2243a72018-01-11 23:59:16 +00001410 assert(S.isDefined());
Sam Clegg1e975c12017-06-20 04:04:59 +00001411
Sam Clegg20bde082017-07-07 02:01:29 +00001412 // Find the target symbol of this weak alias and export that index
Sam Cleggd3108e52017-09-15 19:22:01 +00001413 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1414 const MCSymbolWasm *ResolvedSym = ResolveSymbol(WS);
Nicola Zaghen0818e782018-05-14 12:53:11 +00001415 LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym
1416 << "'\n");
Sam Clegg1e975c12017-06-20 04:04:59 +00001417
Sam Cleggd5784792018-02-23 05:08:34 +00001418 if (WS.isFunction()) {
1419 assert(WasmIndices.count(ResolvedSym) > 0);
1420 uint32_t WasmIndex = WasmIndices.find(ResolvedSym)->second;
1421 WasmIndices[&WS] = WasmIndex;
Nicola Zaghen0818e782018-05-14 12:53:11 +00001422 LLVM_DEBUG(dbgs() << " -> index:" << WasmIndex << "\n");
Sam Cleggd5784792018-02-23 05:08:34 +00001423 } else if (WS.isData()) {
1424 assert(DataLocations.count(ResolvedSym) > 0);
1425 const wasm::WasmDataReference &Ref =
1426 DataLocations.find(ResolvedSym)->second;
1427 DataLocations[&WS] = Ref;
Nicola Zaghen0818e782018-05-14 12:53:11 +00001428 LLVM_DEBUG(dbgs() << " -> index:" << Ref.Segment << "\n");
Sam Cleggd5784792018-02-23 05:08:34 +00001429 } else {
Heejin Ahn8bcdd042018-11-14 02:46:21 +00001430 report_fatal_error("don't yet support global/event aliases");
Sam Cleggd5784792018-02-23 05:08:34 +00001431 }
Nicholas Wilson15d65982018-02-28 17:19:48 +00001432 }
Sam Cleggb1dd7d62017-09-20 21:17:04 +00001433
Nicholas Wilson15d65982018-02-28 17:19:48 +00001434 // Finally, populate the symbol table itself, in its "natural" order.
1435 for (const MCSymbol &S : Asm.symbols()) {
1436 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Sam Clegg0af44d62018-05-08 00:08:21 +00001437 if (!isInSymtab(WS)) {
1438 WS.setIndex(INVALID_INDEX);
Nicholas Wilson15d65982018-02-28 17:19:48 +00001439 continue;
Sam Clegg0af44d62018-05-08 00:08:21 +00001440 }
Nicola Zaghen0818e782018-05-14 12:53:11 +00001441 LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n");
Nicholas Wilson15d65982018-02-28 17:19:48 +00001442
1443 uint32_t Flags = 0;
1444 if (WS.isWeak())
1445 Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
1446 if (WS.isHidden())
1447 Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
1448 if (!WS.isExternal() && WS.isDefined())
1449 Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
1450 if (WS.isUndefined())
1451 Flags |= wasm::WASM_SYMBOL_UNDEFINED;
Hans Wennborg831b2042019-02-12 12:27:08 +00001452 if (WS.getName() != WS.getImportName())
1453 Flags |= wasm::WASM_SYMBOL_EXPLICIT_NAME;
Nicholas Wilson15d65982018-02-28 17:19:48 +00001454
1455 wasm::WasmSymbolInfo Info;
1456 Info.Name = WS.getName();
1457 Info.Kind = WS.getType();
1458 Info.Flags = Flags;
Sam Clegg1c4e4c42018-05-02 23:11:38 +00001459 if (!WS.isData()) {
1460 assert(WasmIndices.count(&WS) > 0);
Nicholas Wilson15d65982018-02-28 17:19:48 +00001461 Info.ElementIndex = WasmIndices.find(&WS)->second;
Sam Clegg1c4e4c42018-05-02 23:11:38 +00001462 } else if (WS.isDefined()) {
1463 assert(DataLocations.count(&WS) > 0);
Nicholas Wilson15d65982018-02-28 17:19:48 +00001464 Info.DataRef = DataLocations.find(&WS)->second;
Sam Clegg1c4e4c42018-05-02 23:11:38 +00001465 }
Sam Clegg0af44d62018-05-08 00:08:21 +00001466 WS.setIndex(SymbolInfos.size());
Nicholas Wilson15d65982018-02-28 17:19:48 +00001467 SymbolInfos.emplace_back(Info);
Sam Clegg1e975c12017-06-20 04:04:59 +00001468 }
1469
Sam Clegg824ec492017-12-22 20:31:39 +00001470 {
1471 auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
Sam Clegg58528fe2018-01-31 19:28:47 +00001472 // Functions referenced by a relocation need to put in the table. This is
1473 // purely to make the object file's provisional values readable, and is
1474 // ignored by the linker, which re-calculates the relocations itself.
1475 if (Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_I32 &&
1476 Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB)
1477 return;
1478 assert(Rel.Symbol->isFunction());
1479 const MCSymbolWasm &WS = *ResolveSymbol(*Rel.Symbol);
Sam Cleggd5784792018-02-23 05:08:34 +00001480 uint32_t FunctionIndex = WasmIndices.find(&WS)->second;
Sam Clegg58528fe2018-01-31 19:28:47 +00001481 uint32_t TableIndex = TableElems.size() + kInitialTableOffset;
1482 if (TableIndices.try_emplace(&WS, TableIndex).second) {
Nicola Zaghen0818e782018-05-14 12:53:11 +00001483 LLVM_DEBUG(dbgs() << " -> adding " << WS.getName()
1484 << " to table: " << TableIndex << "\n");
Sam Cleggd5784792018-02-23 05:08:34 +00001485 TableElems.push_back(FunctionIndex);
Sam Clegg58528fe2018-01-31 19:28:47 +00001486 registerFunctionType(WS);
Sam Clegg824ec492017-12-22 20:31:39 +00001487 }
1488 };
Dan Gohman546a4622017-03-30 23:58:19 +00001489
Sam Clegg824ec492017-12-22 20:31:39 +00001490 for (const WasmRelocationEntry &RelEntry : CodeRelocations)
1491 HandleReloc(RelEntry);
1492 for (const WasmRelocationEntry &RelEntry : DataRelocations)
1493 HandleReloc(RelEntry);
Dan Gohman53ff96a2017-02-24 23:18:00 +00001494 }
1495
Sam Clegg53341802017-12-15 00:17:10 +00001496 // Translate .init_array section contents into start functions.
1497 for (const MCSection &S : Asm) {
1498 const auto &WS = static_cast<const MCSectionWasm &>(S);
1499 if (WS.getSectionName().startswith(".fini_array"))
1500 report_fatal_error(".fini_array sections are unsupported");
1501 if (!WS.getSectionName().startswith(".init_array"))
1502 continue;
1503 if (WS.getFragmentList().empty())
1504 continue;
Sam Clegg70b76a12018-05-10 17:38:35 +00001505
1506 // init_array is expected to contain a single non-empty data fragment
1507 if (WS.getFragmentList().size() != 3)
Sam Clegg53341802017-12-15 00:17:10 +00001508 report_fatal_error("only one .init_array section fragment supported");
Sam Clegg70b76a12018-05-10 17:38:35 +00001509
1510 auto IT = WS.begin();
1511 const MCFragment &EmptyFrag = *IT;
1512 if (EmptyFrag.getKind() != MCFragment::FT_Data)
1513 report_fatal_error(".init_array section should be aligned");
1514
1515 IT = std::next(IT);
1516 const MCFragment &AlignFrag = *IT;
Sam Clegg53341802017-12-15 00:17:10 +00001517 if (AlignFrag.getKind() != MCFragment::FT_Align)
1518 report_fatal_error(".init_array section should be aligned");
1519 if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1520 report_fatal_error(".init_array section should be aligned for pointers");
Sam Clegg70b76a12018-05-10 17:38:35 +00001521
1522 const MCFragment &Frag = *std::next(IT);
Sam Clegg53341802017-12-15 00:17:10 +00001523 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1524 report_fatal_error("only data supported in .init_array section");
Sam Clegg70b76a12018-05-10 17:38:35 +00001525
Sam Clegg53341802017-12-15 00:17:10 +00001526 uint16_t Priority = UINT16_MAX;
Sam Clegg1c4e4c42018-05-02 23:11:38 +00001527 unsigned PrefixLength = strlen(".init_array");
1528 if (WS.getSectionName().size() > PrefixLength) {
1529 if (WS.getSectionName()[PrefixLength] != '.')
Heejin Ahn581d2312018-09-05 01:27:38 +00001530 report_fatal_error(
1531 ".init_array section priority should start with '.'");
Sam Clegg1c4e4c42018-05-02 23:11:38 +00001532 if (WS.getSectionName()
1533 .substr(PrefixLength + 1)
1534 .getAsInteger(10, Priority))
Sam Clegg53341802017-12-15 00:17:10 +00001535 report_fatal_error("invalid .init_array section priority");
1536 }
1537 const auto &DataFrag = cast<MCDataFragment>(Frag);
1538 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
Heejin Ahn581d2312018-09-05 01:27:38 +00001539 for (const uint8_t *
1540 p = (const uint8_t *)Contents.data(),
1541 *end = (const uint8_t *)Contents.data() + Contents.size();
Sam Clegg53341802017-12-15 00:17:10 +00001542 p != end; ++p) {
1543 if (*p != 0)
1544 report_fatal_error("non-symbolic data in .init_array section");
1545 }
1546 for (const MCFixup &Fixup : DataFrag.getFixups()) {
Heejin Ahn581d2312018-09-05 01:27:38 +00001547 assert(Fixup.getKind() ==
1548 MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
Sam Clegg53341802017-12-15 00:17:10 +00001549 const MCExpr *Expr = Fixup.getValue();
1550 auto *Sym = dyn_cast<MCSymbolRefExpr>(Expr);
1551 if (!Sym)
1552 report_fatal_error("fixups in .init_array should be symbol references");
1553 if (Sym->getKind() != MCSymbolRefExpr::VK_WebAssembly_FUNCTION)
1554 report_fatal_error("symbols in .init_array should be for functions");
Sam Clegg0af44d62018-05-08 00:08:21 +00001555 if (Sym->getSymbol().getIndex() == INVALID_INDEX)
1556 report_fatal_error("symbols in .init_array should exist in symbtab");
1557 InitFuncs.push_back(
1558 std::make_pair(Priority, Sym->getSymbol().getIndex()));
Sam Clegg53341802017-12-15 00:17:10 +00001559 }
1560 }
1561
Dan Gohmand660a5d2017-02-22 01:23:18 +00001562 // Write out the Wasm header.
1563 writeHeader(Asm);
1564
Heejin Ahn8bcdd042018-11-14 02:46:21 +00001565 writeTypeSection(Signatures);
Sam Clegg9fb34672017-12-11 23:03:38 +00001566 writeImportSection(Imports, DataSize, TableElems.size());
Sam Clegg4efa61f2017-06-03 02:01:24 +00001567 writeFunctionSection(Functions);
Sam Clegg9fb34672017-12-11 23:03:38 +00001568 // Skip the "table" section; we import the table instead.
1569 // Skip the "memory" section; we import the memory instead.
Sam Clegg09288822017-09-14 23:07:53 +00001570 writeGlobalSection();
Heejin Ahn8bcdd042018-11-14 02:46:21 +00001571 writeEventSection(Events);
Sam Clegg4efa61f2017-06-03 02:01:24 +00001572 writeExportSection(Exports);
Sam Clegg4efa61f2017-06-03 02:01:24 +00001573 writeElemSection(TableElems);
Sam Clegg53a472f2017-06-06 19:15:05 +00001574 writeCodeSection(Asm, Layout, Functions);
Sam Cleggd5784792018-02-23 05:08:34 +00001575 writeDataSection();
Sam Cleggdb159752018-04-26 19:27:28 +00001576 writeCustomSections(Asm, Layout);
Nicholas Wilson022e5fa2018-03-05 12:59:03 +00001577 writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
Sam Clegg194a4e02018-04-24 18:11:36 +00001578 writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
1579 writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
Sam Cleggdb159752018-04-26 19:27:28 +00001580 writeCustomRelocSections();
Dan Gohman546a4622017-03-30 23:58:19 +00001581
Dan Gohman53ff96a2017-02-24 23:18:00 +00001582 // TODO: Translate the .comment section to the output.
Peter Collingbourne0d4292f2018-05-21 18:23:50 +00001583 return W.OS.tell() - StartOffset;
Dan Gohmand660a5d2017-02-22 01:23:18 +00001584}
1585
Lang Hamese4713462017-10-10 16:28:07 +00001586std::unique_ptr<MCObjectWriter>
Lang Hames40108822017-10-10 01:15:10 +00001587llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
1588 raw_pwrite_stream &OS) {
Dan Gohmane8afc142018-01-15 17:06:23 +00001589 return llvm::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
Dan Gohmand660a5d2017-02-22 01:23:18 +00001590}