blob: f9318ad5801826067cebae5a8e78aaa864f40096 [file] [log] [blame]
Dan Gohman18eafb62017-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 Turner264b5d92017-06-07 03:48:56 +000016#include "llvm/BinaryFormat/Wasm.h"
Nico Weber432a3882018-04-30 14:59:11 +000017#include "llvm/Config/llvm-config.h"
Dan Gohman18eafb62017-02-22 01:23:18 +000018#include "llvm/MC/MCAsmBackend.h"
Dan Gohman18eafb62017-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 Gohman18eafb62017-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 Gohmand934cb82017-02-24 23:18:00 +000029#include "llvm/Support/Casting.h"
Dan Gohman18eafb62017-02-22 01:23:18 +000030#include "llvm/Support/Debug.h"
Dan Gohman18eafb62017-02-22 01:23:18 +000031#include "llvm/Support/ErrorHandling.h"
Dan Gohmand934cb82017-02-24 23:18:00 +000032#include "llvm/Support/LEB128.h"
Dan Gohman18eafb62017-02-22 01:23:18 +000033#include "llvm/Support/StringSaver.h"
34#include <vector>
35
36using namespace llvm;
37
Sam Clegg5e3d33a2017-07-07 02:01:29 +000038#define DEBUG_TYPE "mc"
Dan Gohman18eafb62017-02-22 01:23:18 +000039
40namespace {
Sam Clegg9e15f352017-06-03 02:01:24 +000041
Sam Clegg30e1bbc2018-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 Gohmand934cb82017-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 Clegg6a31a0d2018-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 Gohmand934cb82017-02-24 23:18:00 +000055 uint64_t ContentsOffset;
Sam Clegg6f08c842018-04-24 18:11:36 +000056 uint32_t Index;
Dan Gohmand934cb82017-02-24 23:18:00 +000057};
58
Sam Clegg9e15f352017-06-03 02:01:24 +000059// The signature of a wasm function, in a struct capable of being used as a
60// DenseMap key.
Derek Schuff77a7a382018-10-03 22:22:48 +000061// TODO: Consider using WasmSignature directly instead.
Sam Clegg9e15f352017-06-03 02:01:24 +000062struct WasmFunctionType {
63 // 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
72 WasmFunctionType() : State(Plain) {}
73
74 bool operator==(const WasmFunctionType &Other) const {
75 return State == Other.State && Returns == Other.Returns &&
76 Params == Other.Params;
77 }
78};
79
80// Traits for using WasmFunctionType in a DenseMap.
81struct WasmFunctionTypeDenseMapInfo {
82 static WasmFunctionType getEmptyKey() {
83 WasmFunctionType FuncTy;
84 FuncTy.State = WasmFunctionType::Empty;
85 return FuncTy;
86 }
87 static WasmFunctionType getTombstoneKey() {
88 WasmFunctionType FuncTy;
89 FuncTy.State = WasmFunctionType::Tombstone;
90 return FuncTy;
91 }
92 static unsigned getHashValue(const WasmFunctionType &FuncTy) {
93 uintptr_t Value = FuncTy.State;
94 for (wasm::ValType Ret : FuncTy.Returns)
95 Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Ret));
96 for (wasm::ValType Param : FuncTy.Params)
97 Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Param));
98 return Value;
99 }
100 static bool isEqual(const WasmFunctionType &LHS,
101 const WasmFunctionType &RHS) {
102 return LHS == RHS;
103 }
104};
105
Sam Clegg7c395942017-09-14 23:07:53 +0000106// A wasm data segment. A wasm binary contains only a single data section
107// but that can contain many segments, each with their own virtual location
108// in memory. Each MCSection data created by llvm is modeled as its own
109// wasm data segment.
110struct WasmDataSegment {
111 MCSectionWasm *Section;
Sam Cleggd95ed952017-09-20 19:03:35 +0000112 StringRef Name;
Sam Clegg7c395942017-09-14 23:07:53 +0000113 uint32_t Offset;
Sam Clegg63ebb812017-09-29 16:50:08 +0000114 uint32_t Alignment;
115 uint32_t Flags;
Sam Clegg7c395942017-09-14 23:07:53 +0000116 SmallVector<char, 4> Data;
117};
118
Sam Clegg9e15f352017-06-03 02:01:24 +0000119// A wasm function to be written into the function section.
120struct WasmFunction {
121 int32_t Type;
122 const MCSymbolWasm *Sym;
123};
124
Sam Clegg9e15f352017-06-03 02:01:24 +0000125// A wasm global to be written into the global section.
126struct WasmGlobal {
Sam Clegg6e7f1822018-01-31 19:50:14 +0000127 wasm::WasmGlobalType Type;
Sam Clegg9e15f352017-06-03 02:01:24 +0000128 uint64_t InitialValue;
Sam Clegg9e15f352017-06-03 02:01:24 +0000129};
130
Sam Cleggea7cace2018-01-09 23:43:14 +0000131// Information about a single item which is part of a COMDAT. For each data
132// segment or function which is in the COMDAT, there is a corresponding
133// WasmComdatEntry.
134struct WasmComdatEntry {
135 unsigned Kind;
136 uint32_t Index;
137};
138
Sam Clegg6dc65e92017-06-06 16:38:59 +0000139// Information about a single relocation.
140struct WasmRelocationEntry {
Heejin Ahnf208f632018-09-05 01:27:38 +0000141 uint64_t Offset; // Where is the relocation.
142 const MCSymbolWasm *Symbol; // The symbol to relocate with.
143 int64_t Addend; // A value to add to the symbol.
144 unsigned Type; // The type of the relocation.
145 const MCSectionWasm *FixupSection; // The section the relocation is targeting.
Sam Clegg6dc65e92017-06-06 16:38:59 +0000146
147 WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
148 int64_t Addend, unsigned Type,
Sam Cleggfe6414b2017-06-21 23:46:41 +0000149 const MCSectionWasm *FixupSection)
Sam Clegg6dc65e92017-06-06 16:38:59 +0000150 : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
151 FixupSection(FixupSection) {}
152
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000153 bool hasAddend() const {
154 switch (Type) {
Sam Clegg13a2e892017-09-01 17:32:01 +0000155 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
156 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
157 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000158 case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32:
159 case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32:
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000160 return true;
161 default:
162 return false;
163 }
164 }
165
Sam Clegg6dc65e92017-06-06 16:38:59 +0000166 void print(raw_ostream &Out) const {
Heejin Ahnf208f632018-09-05 01:27:38 +0000167 Out << wasm::relocTypetoString(Type) << " Off=" << Offset
168 << ", Sym=" << *Symbol << ", Addend=" << Addend
Sam Clegg759631c2017-09-15 20:54:59 +0000169 << ", FixupSection=" << FixupSection->getSectionName();
Sam Clegg6dc65e92017-06-06 16:38:59 +0000170 }
Sam Cleggb7787fd2017-06-20 04:04:59 +0000171
Aaron Ballman615eb472017-10-15 14:32:27 +0000172#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Sam Cleggb7787fd2017-06-20 04:04:59 +0000173 LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
174#endif
Sam Clegg6dc65e92017-06-06 16:38:59 +0000175};
176
Sam Clegg25d8e682018-05-08 00:08:21 +0000177static const uint32_t INVALID_INDEX = -1;
178
Sam Cleggcfd44a22018-04-05 17:01:39 +0000179struct WasmCustomSection {
Sam Cleggcfd44a22018-04-05 17:01:39 +0000180
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000181 StringRef Name;
182 MCSectionWasm *Section;
183
184 uint32_t OutputContentsOffset;
185 uint32_t OutputIndex;
186
187 WasmCustomSection(StringRef Name, MCSectionWasm *Section)
188 : Name(Name), Section(Section), OutputContentsOffset(0),
189 OutputIndex(INVALID_INDEX) {}
Sam Cleggcfd44a22018-04-05 17:01:39 +0000190};
191
Sam Clegg1fb8daa2017-06-20 05:05:10 +0000192#if !defined(NDEBUG)
Sam Clegg7f055de2017-06-20 04:47:58 +0000193raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000194 Rel.print(OS);
195 return OS;
196}
Sam Clegg1fb8daa2017-06-20 05:05:10 +0000197#endif
Sam Cleggb7787fd2017-06-20 04:04:59 +0000198
Dan Gohman18eafb62017-02-22 01:23:18 +0000199class WasmObjectWriter : public MCObjectWriter {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000200 support::endian::Writer W;
201
Dan Gohman18eafb62017-02-22 01:23:18 +0000202 /// The target specific Wasm writer instance.
203 std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
204
Dan Gohmand934cb82017-02-24 23:18:00 +0000205 // Relocations for fixing up references in the code section.
206 std::vector<WasmRelocationEntry> CodeRelocations;
Sam Clegg6f08c842018-04-24 18:11:36 +0000207 uint32_t CodeSectionIndex;
Dan Gohmand934cb82017-02-24 23:18:00 +0000208
209 // Relocations for fixing up references in the data section.
210 std::vector<WasmRelocationEntry> DataRelocations;
Sam Clegg6f08c842018-04-24 18:11:36 +0000211 uint32_t DataSectionIndex;
Dan Gohmand934cb82017-02-24 23:18:00 +0000212
Dan Gohmand934cb82017-02-24 23:18:00 +0000213 // Index values to use for fixing up call_indirect type indices.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000214 // Maps function symbols to the index of the type of the function
215 DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
Sam Cleggd99f6072017-06-12 23:52:44 +0000216 // Maps function symbols to the table element index space. Used
217 // for TABLE_INDEX relocation types (i.e. address taken functions).
Sam Cleggf9edbe92018-01-31 19:28:47 +0000218 DenseMap<const MCSymbolWasm *, uint32_t> TableIndices;
Sam Clegga165f2d2018-04-30 19:40:57 +0000219 // Maps function/global symbols to the function/global/section index space.
Sam Clegg6c899ba2018-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 Clegg6a31a0d2018-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 Cleggacd7d2b2017-06-06 19:15:05 +0000230
Sam Cleggc0d41192018-05-17 17:15:15 +0000231 // Map from section to defining function symbol.
Sam Clegg6ccb59b2018-05-16 20:09:05 +0000232 DenseMap<const MCSection *, const MCSymbol *> SectionFunctions;
233
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000234 DenseMap<WasmFunctionType, int32_t, WasmFunctionTypeDenseMapInfo>
235 FunctionTypeIndices;
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000236 SmallVector<WasmFunctionType, 4> FunctionTypes;
Sam Clegg7c395942017-09-14 23:07:53 +0000237 SmallVector<WasmGlobal, 4> Globals;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000238 SmallVector<WasmDataSegment, 4> DataSegments;
Sam Clegg9f3fe422018-01-17 19:28:43 +0000239 unsigned NumFunctionImports = 0;
Sam Clegg7c395942017-09-14 23:07:53 +0000240 unsigned NumGlobalImports = 0;
Chandler Carruth7e1c3342018-04-24 20:30:56 +0000241 uint32_t SectionCount = 0;
Dan Gohmand934cb82017-02-24 23:18:00 +0000242
Dan Gohman18eafb62017-02-22 01:23:18 +0000243 // TargetObjectWriter wrappers.
244 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
Sam Cleggae03c1e72017-06-13 18:51:50 +0000245 unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup) const {
246 return TargetObjectWriter->getRelocType(Target, Fixup);
Dan Gohman18eafb62017-02-22 01:23:18 +0000247 }
248
Sam Clegg2322a932018-04-23 19:16:19 +0000249 void startSection(SectionBookkeeping &Section, unsigned SectionId);
250 void startCustomSection(SectionBookkeeping &Section, StringRef Name);
Dan Gohmand934cb82017-02-24 23:18:00 +0000251 void endSection(SectionBookkeeping &Section);
252
Dan Gohman18eafb62017-02-22 01:23:18 +0000253public:
Lang Hames1301a872017-10-10 01:15:10 +0000254 WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
255 raw_pwrite_stream &OS)
Peter Collingbourne59a6fc42018-05-21 18:28:57 +0000256 : W(OS, support::little), TargetObjectWriter(std::move(MOTW)) {}
Dan Gohman18eafb62017-02-22 01:23:18 +0000257
Dan Gohman18eafb62017-02-22 01:23:18 +0000258 ~WasmObjectWriter() override;
259
Dan Gohman0917c9e2018-01-15 17:06:23 +0000260private:
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000261 void reset() override {
262 CodeRelocations.clear();
263 DataRelocations.clear();
264 TypeIndices.clear();
Sam Clegg6c899ba2018-02-23 05:08:34 +0000265 WasmIndices.clear();
Sam Cleggf9edbe92018-01-31 19:28:47 +0000266 TableIndices.clear();
Sam Clegg6c899ba2018-02-23 05:08:34 +0000267 DataLocations.clear();
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000268 CustomSectionsRelocations.clear();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000269 FunctionTypeIndices.clear();
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000270 FunctionTypes.clear();
Sam Clegg7c395942017-09-14 23:07:53 +0000271 Globals.clear();
Sam Clegg6c899ba2018-02-23 05:08:34 +0000272 DataSegments.clear();
Sam Clegg6ccb59b2018-05-16 20:09:05 +0000273 SectionFunctions.clear();
Sam Clegg9f3fe422018-01-17 19:28:43 +0000274 NumFunctionImports = 0;
Sam Clegg7c395942017-09-14 23:07:53 +0000275 NumGlobalImports = 0;
Sam Clegg105bdc22018-05-30 02:57:20 +0000276 MCObjectWriter::reset();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000277 }
278
Dan Gohman18eafb62017-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 Espindolaceecfe5b2017-07-11 23:56:10 +0000283 MCValue Target, uint64_t &FixedValue) override;
Dan Gohman18eafb62017-02-22 01:23:18 +0000284
285 void executePostLayoutBinding(MCAssembler &Asm,
286 const MCAsmLayout &Layout) override;
287
Peter Collingbourne438390f2018-05-21 18:23:50 +0000288 uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
Sam Clegg9e15f352017-06-03 02:01:24 +0000289
Sam Cleggb7787fd2017-06-20 04:04:59 +0000290 void writeString(const StringRef Str) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000291 encodeULEB128(Str.size(), W.OS);
292 W.OS << Str;
Sam Cleggb7787fd2017-06-20 04:04:59 +0000293 }
294
Heejin Ahnf208f632018-09-05 01:27:38 +0000295 void writeValueType(wasm::ValType Ty) { W.OS << static_cast<char>(Ty); }
Sam Clegg9e15f352017-06-03 02:01:24 +0000296
Sam Clegg457fb0b2017-09-15 19:50:44 +0000297 void writeTypeSection(ArrayRef<WasmFunctionType> FunctionTypes);
Sam Clegg8defa952018-02-12 22:41:29 +0000298 void writeImportSection(ArrayRef<wasm::WasmImport> Imports, uint32_t DataSize,
Sam Cleggf950b242017-12-11 23:03:38 +0000299 uint32_t NumElements);
Sam Clegg457fb0b2017-09-15 19:50:44 +0000300 void writeFunctionSection(ArrayRef<WasmFunction> Functions);
Sam Clegg7c395942017-09-14 23:07:53 +0000301 void writeGlobalSection();
Sam Clegg8defa952018-02-12 22:41:29 +0000302 void writeExportSection(ArrayRef<wasm::WasmExport> Exports);
Sam Clegg457fb0b2017-09-15 19:50:44 +0000303 void writeElemSection(ArrayRef<uint32_t> TableElems);
Sam Clegg9e15f352017-06-03 02:01:24 +0000304 void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
Sam Clegg457fb0b2017-09-15 19:50:44 +0000305 ArrayRef<WasmFunction> Functions);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000306 void writeDataSection();
Sam Clegg6f08c842018-04-24 18:11:36 +0000307 void writeRelocSection(uint32_t SectionIndex, StringRef Name,
Heejin Ahnf208f632018-09-05 01:27:38 +0000308 std::vector<WasmRelocationEntry> &Relocations);
Sam Clegg31a2c802017-09-20 21:17:04 +0000309 void writeLinkingMetaDataSection(
Sam Clegg86b4a092018-02-27 23:57:37 +0000310 ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
Sam Cleggea7cace2018-01-09 23:43:14 +0000311 ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
Sam Clegg6c899ba2018-02-23 05:08:34 +0000312 const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000313 void writeCustomSections(const MCAssembler &Asm, const MCAsmLayout &Layout);
314 void writeCustomRelocSections();
315 void
316 updateCustomSectionRelocations(const SmallVector<WasmFunction, 4> &Functions,
317 const MCAsmLayout &Layout);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000318
Sam Clegg7c395942017-09-14 23:07:53 +0000319 uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000320 void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
321 uint64_t ContentsOffset);
322
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000323 uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
Sam Clegg6f08c842018-04-24 18:11:36 +0000324 uint32_t getFunctionType(const MCSymbolWasm &Symbol);
325 uint32_t registerFunctionType(const MCSymbolWasm &Symbol);
Dan Gohman18eafb62017-02-22 01:23:18 +0000326};
Sam Clegg9e15f352017-06-03 02:01:24 +0000327
Dan Gohman18eafb62017-02-22 01:23:18 +0000328} // end anonymous namespace
329
330WasmObjectWriter::~WasmObjectWriter() {}
331
Dan Gohmand934cb82017-02-24 23:18:00 +0000332// Write out a section header and a patchable section size field.
333void WasmObjectWriter::startSection(SectionBookkeeping &Section,
Sam Clegg2322a932018-04-23 19:16:19 +0000334 unsigned SectionId) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000335 LLVM_DEBUG(dbgs() << "startSection " << SectionId << "\n");
Peter Collingbournef17b1492018-05-21 18:17:42 +0000336 W.OS << char(SectionId);
Dan Gohmand934cb82017-02-24 23:18:00 +0000337
Peter Collingbournef17b1492018-05-21 18:17:42 +0000338 Section.SizeOffset = W.OS.tell();
Dan Gohmand934cb82017-02-24 23:18:00 +0000339
340 // The section size. We don't know the size yet, so reserve enough space
341 // for any 32-bit value; we'll patch it later.
Peter Collingbournef17b1492018-05-21 18:17:42 +0000342 encodeULEB128(UINT32_MAX, W.OS);
Dan Gohmand934cb82017-02-24 23:18:00 +0000343
344 // The position where the section starts, for measuring its size.
Peter Collingbournef17b1492018-05-21 18:17:42 +0000345 Section.ContentsOffset = W.OS.tell();
346 Section.PayloadOffset = W.OS.tell();
Sam Clegg6f08c842018-04-24 18:11:36 +0000347 Section.Index = SectionCount++;
Sam Clegg2322a932018-04-23 19:16:19 +0000348}
Dan Gohmand934cb82017-02-24 23:18:00 +0000349
Sam Clegg2322a932018-04-23 19:16:19 +0000350void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section,
351 StringRef Name) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000352 LLVM_DEBUG(dbgs() << "startCustomSection " << Name << "\n");
Sam Clegg2322a932018-04-23 19:16:19 +0000353 startSection(Section, wasm::WASM_SEC_CUSTOM);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000354
355 // The position where the section header ends, for measuring its size.
Peter Collingbournef17b1492018-05-21 18:17:42 +0000356 Section.PayloadOffset = W.OS.tell();
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000357
Dan Gohmand934cb82017-02-24 23:18:00 +0000358 // Custom sections in wasm also have a string identifier.
Sam Clegg2322a932018-04-23 19:16:19 +0000359 writeString(Name);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000360
361 // The position where the custom section starts.
Peter Collingbournef17b1492018-05-21 18:17:42 +0000362 Section.ContentsOffset = W.OS.tell();
Dan Gohmand934cb82017-02-24 23:18:00 +0000363}
364
365// Now that the section is complete and we know how big it is, patch up the
366// section size field at the start of the section.
367void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000368 uint64_t Size = W.OS.tell() - Section.PayloadOffset;
Dan Gohmand934cb82017-02-24 23:18:00 +0000369 if (uint32_t(Size) != Size)
370 report_fatal_error("section size does not fit in a uint32_t");
371
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000372 LLVM_DEBUG(dbgs() << "endSection size=" << Size << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000373
374 // Write the final section size to the payload_len field, which follows
375 // the section id byte.
376 uint8_t Buffer[16];
Sam Clegg66a99e42017-09-15 20:34:47 +0000377 unsigned SizeLen = encodeULEB128(Size, Buffer, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000378 assert(SizeLen == 5);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000379 static_cast<raw_pwrite_stream &>(W.OS).pwrite((char *)Buffer, SizeLen,
380 Section.SizeOffset);
Dan Gohmand934cb82017-02-24 23:18:00 +0000381}
382
Dan Gohman18eafb62017-02-22 01:23:18 +0000383// Emit the Wasm header.
384void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000385 W.OS.write(wasm::WasmMagic, sizeof(wasm::WasmMagic));
386 W.write<uint32_t>(wasm::WasmVersion);
Dan Gohman18eafb62017-02-22 01:23:18 +0000387}
388
389void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
390 const MCAsmLayout &Layout) {
Sam Clegg6ccb59b2018-05-16 20:09:05 +0000391 // Build a map of sections to the function that defines them, for use
392 // in recordRelocation.
393 for (const MCSymbol &S : Asm.symbols()) {
394 const auto &WS = static_cast<const MCSymbolWasm &>(S);
395 if (WS.isDefined() && WS.isFunction() && !WS.isVariable()) {
396 const auto &Sec = static_cast<const MCSectionWasm &>(S.getSection());
397 auto Pair = SectionFunctions.insert(std::make_pair(&Sec, &S));
398 if (!Pair.second)
399 report_fatal_error("section already has a defining function: " +
400 Sec.getSectionName());
401 }
402 }
Dan Gohman18eafb62017-02-22 01:23:18 +0000403}
404
405void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
406 const MCAsmLayout &Layout,
407 const MCFragment *Fragment,
408 const MCFixup &Fixup, MCValue Target,
Rafael Espindolaceecfe5b2017-07-11 23:56:10 +0000409 uint64_t &FixedValue) {
410 MCAsmBackend &Backend = Asm.getBackend();
411 bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
412 MCFixupKindInfo::FKF_IsPCRel;
Sam Cleggfe6414b2017-06-21 23:46:41 +0000413 const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
Dan Gohmand934cb82017-02-24 23:18:00 +0000414 uint64_t C = Target.getConstant();
415 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
416 MCContext &Ctx = Asm.getContext();
417
Sam Cleggbafe6902017-12-15 00:17:10 +0000418 // The .init_array isn't translated as data, so don't do relocations in it.
419 if (FixupSection.getSectionName().startswith(".init_array"))
420 return;
421
Dan Gohmand934cb82017-02-24 23:18:00 +0000422 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
423 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
424 "Should not have constructed this");
425
426 // Let A, B and C being the components of Target and R be the location of
427 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
428 // If it is pcrel, we want to compute (A - B + C - R).
429
430 // In general, Wasm has no relocations for -B. It can only represent (A + C)
431 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
432 // replace B to implement it: (A - R - K + C)
433 if (IsPCRel) {
434 Ctx.reportError(
435 Fixup.getLoc(),
436 "No relocation available to represent this relative expression");
437 return;
438 }
439
440 const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
441
442 if (SymB.isUndefined()) {
443 Ctx.reportError(Fixup.getLoc(),
444 Twine("symbol '") + SymB.getName() +
445 "' can not be undefined in a subtraction expression");
446 return;
447 }
448
449 assert(!SymB.isAbsolute() && "Should have been folded");
450 const MCSection &SecB = SymB.getSection();
451 if (&SecB != &FixupSection) {
452 Ctx.reportError(Fixup.getLoc(),
453 "Cannot represent a difference across sections");
454 return;
455 }
456
457 uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
458 uint64_t K = SymBOffset - FixupOffset;
459 IsPCRel = true;
460 C -= K;
461 }
462
463 // We either rejected the fixup or folded B into C at this point.
464 const MCSymbolRefExpr *RefA = Target.getSymA();
465 const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
466
Dan Gohmand934cb82017-02-24 23:18:00 +0000467 if (SymA && SymA->isVariable()) {
468 const MCExpr *Expr = SymA->getVariableValue();
Sam Clegg6ad8f192017-07-11 02:21:57 +0000469 const auto *Inner = cast<MCSymbolRefExpr>(Expr);
470 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
471 llvm_unreachable("weakref used in reloc not yet implemented");
Dan Gohmand934cb82017-02-24 23:18:00 +0000472 }
473
474 // Put any constant offset in an addend. Offsets can be negative, and
475 // LLVM expects wrapping, in contrast to wasm's immediates which can't
476 // be negative and don't wrap.
477 FixedValue = 0;
478
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000479 unsigned Type = getRelocType(Target, Fixup);
Sam Cleggae03c1e72017-06-13 18:51:50 +0000480 assert(!IsPCRel);
Sam Clegg9d24fb72017-06-16 23:59:10 +0000481 assert(SymA);
482
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000483 // Absolute offset within a section or a function.
484 // Currently only supported for for metadata sections.
485 // See: test/MC/WebAssembly/blockaddress.ll
486 if (Type == wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32 ||
487 Type == wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32) {
488 if (!FixupSection.getKind().isMetadata())
489 report_fatal_error("relocations for function or section offsets are "
490 "only supported in metadata sections");
491
492 const MCSymbol *SectionSymbol = nullptr;
493 const MCSection &SecA = SymA->getSection();
494 if (SecA.getKind().isText())
Sam Clegg6ccb59b2018-05-16 20:09:05 +0000495 SectionSymbol = SectionFunctions.find(&SecA)->second;
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000496 else
497 SectionSymbol = SecA.getBeginSymbol();
498 if (!SectionSymbol)
499 report_fatal_error("section symbol is required for relocation");
500
501 C += Layout.getSymbolOffset(*SymA);
502 SymA = cast<MCSymbolWasm>(SectionSymbol);
503 }
504
505 // Relocation other than R_WEBASSEMBLY_TYPE_INDEX_LEB are required to be
506 // against a named symbol.
507 if (Type != wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) {
508 if (SymA->getName().empty())
509 report_fatal_error("relocations against un-named temporaries are not yet "
510 "supported by wasm");
511
512 SymA->setUsedInReloc();
513 }
Sam Cleggae03c1e72017-06-13 18:51:50 +0000514
Dan Gohmand934cb82017-02-24 23:18:00 +0000515 WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000516 LLVM_DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000517
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000518 if (FixupSection.isWasmData()) {
Dan Gohmand934cb82017-02-24 23:18:00 +0000519 DataRelocations.push_back(Rec);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000520 } else if (FixupSection.getKind().isText()) {
Sam Clegg12fd3da2017-10-20 21:28:38 +0000521 CodeRelocations.push_back(Rec);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000522 } else if (FixupSection.getKind().isMetadata()) {
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000523 CustomSectionsRelocations[&FixupSection].push_back(Rec);
524 } else {
Sam Clegg12fd3da2017-10-20 21:28:38 +0000525 llvm_unreachable("unexpected section type");
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000526 }
Dan Gohmand934cb82017-02-24 23:18:00 +0000527}
528
Dan Gohmand934cb82017-02-24 23:18:00 +0000529// Write X as an (unsigned) LEB value at offset Offset in Stream, padded
530// to allow patching.
Heejin Ahnf208f632018-09-05 01:27:38 +0000531static void WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X,
532 uint64_t Offset) {
Dan Gohmand934cb82017-02-24 23:18:00 +0000533 uint8_t Buffer[5];
Sam Clegg66a99e42017-09-15 20:34:47 +0000534 unsigned SizeLen = encodeULEB128(X, Buffer, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000535 assert(SizeLen == 5);
536 Stream.pwrite((char *)Buffer, SizeLen, Offset);
537}
538
539// Write X as an signed LEB value at offset Offset in Stream, padded
540// to allow patching.
Heejin Ahnf208f632018-09-05 01:27:38 +0000541static void WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X,
542 uint64_t Offset) {
Dan Gohmand934cb82017-02-24 23:18:00 +0000543 uint8_t Buffer[5];
Sam Clegg66a99e42017-09-15 20:34:47 +0000544 unsigned SizeLen = encodeSLEB128(X, Buffer, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000545 assert(SizeLen == 5);
546 Stream.pwrite((char *)Buffer, SizeLen, Offset);
547}
548
549// Write X as a plain integer value at offset Offset in Stream.
550static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
551 uint8_t Buffer[4];
552 support::endian::write32le(Buffer, X);
553 Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
554}
555
Heejin Ahnf208f632018-09-05 01:27:38 +0000556static const MCSymbolWasm *ResolveSymbol(const MCSymbolWasm &Symbol) {
Sam Cleggaff1c4d2017-09-15 19:22:01 +0000557 if (Symbol.isVariable()) {
558 const MCExpr *Expr = Symbol.getVariableValue();
559 auto *Inner = cast<MCSymbolRefExpr>(Expr);
560 return cast<MCSymbolWasm>(&Inner->getSymbol());
561 }
562 return &Symbol;
563}
564
Dan Gohmand934cb82017-02-24 23:18:00 +0000565// Compute a value to write into the code at the location covered
Sam Clegg60ec3032018-01-23 01:23:17 +0000566// by RelEntry. This value isn't used by the static linker; it just serves
567// to make the object format more readable and more likely to be directly
568// useable.
Sam Clegg7c395942017-09-14 23:07:53 +0000569uint32_t
570WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) {
Sam Clegg60ec3032018-01-23 01:23:17 +0000571 switch (RelEntry.Type) {
572 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
Sam Cleggf9edbe92018-01-31 19:28:47 +0000573 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: {
574 // Provisional value is table address of the resolved symbol itself
575 const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
576 assert(Sym->isFunction());
577 return TableIndices[Sym];
578 }
Sam Clegg60ec3032018-01-23 01:23:17 +0000579 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
Sam Clegg6c899ba2018-02-23 05:08:34 +0000580 // Provisional value is same as the index
Sam Clegg60ec3032018-01-23 01:23:17 +0000581 return getRelocationIndexValue(RelEntry);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000582 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
583 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
584 // Provisional value is function/global Wasm index
585 if (!WasmIndices.count(RelEntry.Symbol))
586 report_fatal_error("symbol not found in wasm index space: " +
587 RelEntry.Symbol->getName());
588 return WasmIndices[RelEntry.Symbol];
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000589 case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32:
590 case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32: {
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000591 const auto &Section =
592 static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection());
593 return Section.getSectionOffset() + RelEntry.Addend;
594 }
Sam Clegg60ec3032018-01-23 01:23:17 +0000595 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
596 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
597 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: {
Sam Cleggf9edbe92018-01-31 19:28:47 +0000598 // Provisional value is address of the global
Sam Clegg60ec3032018-01-23 01:23:17 +0000599 const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
600 // For undefined symbols, use zero
601 if (!Sym->isDefined())
602 return 0;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000603 const wasm::WasmDataReference &Ref = DataLocations[Sym];
604 const WasmDataSegment &Segment = DataSegments[Ref.Segment];
Sam Clegg60ec3032018-01-23 01:23:17 +0000605 // Ignore overflow. LLVM allows address arithmetic to silently wrap.
Sam Clegg6c899ba2018-02-23 05:08:34 +0000606 return Segment.Offset + Ref.Offset + RelEntry.Addend;
Sam Clegg60ec3032018-01-23 01:23:17 +0000607 }
608 default:
609 llvm_unreachable("invalid relocation type");
610 }
Dan Gohmand934cb82017-02-24 23:18:00 +0000611}
612
Sam Clegg759631c2017-09-15 20:54:59 +0000613static void addData(SmallVectorImpl<char> &DataBytes,
Sam Clegg63ebb812017-09-29 16:50:08 +0000614 MCSectionWasm &DataSection) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000615 LLVM_DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n");
Sam Clegg759631c2017-09-15 20:54:59 +0000616
Sam Clegg63ebb812017-09-29 16:50:08 +0000617 DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
618
Sam Clegg759631c2017-09-15 20:54:59 +0000619 for (const MCFragment &Frag : DataSection) {
620 if (Frag.hasInstructions())
621 report_fatal_error("only data supported in data sections");
622
623 if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
624 if (Align->getValueSize() != 1)
625 report_fatal_error("only byte values supported for alignment");
626 // If nops are requested, use zeros, as this is the data section.
627 uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
Heejin Ahnf208f632018-09-05 01:27:38 +0000628 uint64_t Size =
629 std::min<uint64_t>(alignTo(DataBytes.size(), Align->getAlignment()),
630 DataBytes.size() + Align->getMaxBytesToEmit());
Sam Clegg759631c2017-09-15 20:54:59 +0000631 DataBytes.resize(Size, Value);
632 } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
Nirav Dave588fad42018-05-18 17:45:48 +0000633 int64_t NumValues;
634 if (!Fill->getNumValues().evaluateAsAbsolute(NumValues))
Rafael Espindolad707c372018-01-09 22:48:37 +0000635 llvm_unreachable("The fill should be an assembler constant");
Nirav Dave588fad42018-05-18 17:45:48 +0000636 DataBytes.insert(DataBytes.end(), Fill->getValueSize() * NumValues,
637 Fill->getValue());
Heejin Ahn24faf852018-10-25 23:55:10 +0000638 } else if (auto *LEB = dyn_cast<MCLEBFragment>(&Frag)) {
639 const SmallVectorImpl<char> &Contents = LEB->getContents();
640 DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
Sam Clegg759631c2017-09-15 20:54:59 +0000641 } else {
642 const auto &DataFrag = cast<MCDataFragment>(Frag);
643 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
Sam Clegg759631c2017-09-15 20:54:59 +0000644 DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
645 }
646 }
647
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000648 LLVM_DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
Sam Clegg759631c2017-09-15 20:54:59 +0000649}
650
Sam Clegg60ec3032018-01-23 01:23:17 +0000651uint32_t
652WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
653 if (RelEntry.Type == wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000654 if (!TypeIndices.count(RelEntry.Symbol))
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000655 report_fatal_error("symbol not found in type index space: " +
Sam Cleggb7787fd2017-06-20 04:04:59 +0000656 RelEntry.Symbol->getName());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000657 return TypeIndices[RelEntry.Symbol];
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000658 }
Sam Clegg60ec3032018-01-23 01:23:17 +0000659
Sam Clegg25d8e682018-05-08 00:08:21 +0000660 return RelEntry.Symbol->getIndex();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000661}
662
Dan Gohmand934cb82017-02-24 23:18:00 +0000663// Apply the portions of the relocation records that we can handle ourselves
664// directly.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000665void WasmObjectWriter::applyRelocations(
666 ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000667 auto &Stream = static_cast<raw_pwrite_stream &>(W.OS);
Dan Gohmand934cb82017-02-24 23:18:00 +0000668 for (const WasmRelocationEntry &RelEntry : Relocations) {
669 uint64_t Offset = ContentsOffset +
670 RelEntry.FixupSection->getSectionOffset() +
671 RelEntry.Offset;
Dan Gohmand934cb82017-02-24 23:18:00 +0000672
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000673 LLVM_DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
Sam Clegg60ec3032018-01-23 01:23:17 +0000674 uint32_t Value = getProvisionalValue(RelEntry);
675
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000676 switch (RelEntry.Type) {
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000677 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000678 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
Sam Clegg60ec3032018-01-23 01:23:17 +0000679 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
680 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
Dan Gohmand934cb82017-02-24 23:18:00 +0000681 WritePatchableLEB(Stream, Value, Offset);
682 break;
Sam Clegg60ec3032018-01-23 01:23:17 +0000683 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
684 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000685 case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32:
686 case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32:
Dan Gohmand934cb82017-02-24 23:18:00 +0000687 WriteI32(Stream, Value, Offset);
688 break;
Sam Clegg60ec3032018-01-23 01:23:17 +0000689 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
690 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
691 WritePatchableSLEB(Stream, Value, Offset);
692 break;
Dan Gohmand934cb82017-02-24 23:18:00 +0000693 default:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000694 llvm_unreachable("invalid relocation type");
Dan Gohmand934cb82017-02-24 23:18:00 +0000695 }
696 }
Dan Gohman18eafb62017-02-22 01:23:18 +0000697}
698
Sam Clegg9e15f352017-06-03 02:01:24 +0000699void WasmObjectWriter::writeTypeSection(
Sam Clegg457fb0b2017-09-15 19:50:44 +0000700 ArrayRef<WasmFunctionType> FunctionTypes) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000701 if (FunctionTypes.empty())
702 return;
703
704 SectionBookkeeping Section;
705 startSection(Section, wasm::WASM_SEC_TYPE);
706
Peter Collingbournef17b1492018-05-21 18:17:42 +0000707 encodeULEB128(FunctionTypes.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000708
709 for (const WasmFunctionType &FuncTy : FunctionTypes) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000710 W.OS << char(wasm::WASM_TYPE_FUNC);
711 encodeULEB128(FuncTy.Params.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000712 for (wasm::ValType Ty : FuncTy.Params)
713 writeValueType(Ty);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000714 encodeULEB128(FuncTy.Returns.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000715 for (wasm::ValType Ty : FuncTy.Returns)
716 writeValueType(Ty);
717 }
718
719 endSection(Section);
720}
721
Sam Clegg8defa952018-02-12 22:41:29 +0000722void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
Sam Cleggf950b242017-12-11 23:03:38 +0000723 uint32_t DataSize,
724 uint32_t NumElements) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000725 if (Imports.empty())
726 return;
727
Sam Cleggf950b242017-12-11 23:03:38 +0000728 uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
729
Sam Clegg9e15f352017-06-03 02:01:24 +0000730 SectionBookkeeping Section;
731 startSection(Section, wasm::WASM_SEC_IMPORT);
732
Peter Collingbournef17b1492018-05-21 18:17:42 +0000733 encodeULEB128(Imports.size(), W.OS);
Sam Clegg8defa952018-02-12 22:41:29 +0000734 for (const wasm::WasmImport &Import : Imports) {
735 writeString(Import.Module);
736 writeString(Import.Field);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000737 W.OS << char(Import.Kind);
Sam Clegg9e15f352017-06-03 02:01:24 +0000738
739 switch (Import.Kind) {
740 case wasm::WASM_EXTERNAL_FUNCTION:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000741 encodeULEB128(Import.SigIndex, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000742 break;
743 case wasm::WASM_EXTERNAL_GLOBAL:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000744 W.OS << char(Import.Global.Type);
745 W.OS << char(Import.Global.Mutable ? 1 : 0);
Sam Clegg9e15f352017-06-03 02:01:24 +0000746 break;
Sam Cleggf950b242017-12-11 23:03:38 +0000747 case wasm::WASM_EXTERNAL_MEMORY:
Heejin Ahnf208f632018-09-05 01:27:38 +0000748 encodeULEB128(0, W.OS); // flags
Peter Collingbournef17b1492018-05-21 18:17:42 +0000749 encodeULEB128(NumPages, W.OS); // initial
Sam Cleggf950b242017-12-11 23:03:38 +0000750 break;
751 case wasm::WASM_EXTERNAL_TABLE:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000752 W.OS << char(Import.Table.ElemType);
Heejin Ahnf208f632018-09-05 01:27:38 +0000753 encodeULEB128(0, W.OS); // flags
Peter Collingbournef17b1492018-05-21 18:17:42 +0000754 encodeULEB128(NumElements, W.OS); // initial
Sam Cleggf950b242017-12-11 23:03:38 +0000755 break;
Sam Clegg9e15f352017-06-03 02:01:24 +0000756 default:
757 llvm_unreachable("unsupported import kind");
758 }
759 }
760
761 endSection(Section);
762}
763
Sam Clegg457fb0b2017-09-15 19:50:44 +0000764void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000765 if (Functions.empty())
766 return;
767
768 SectionBookkeeping Section;
769 startSection(Section, wasm::WASM_SEC_FUNCTION);
770
Peter Collingbournef17b1492018-05-21 18:17:42 +0000771 encodeULEB128(Functions.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000772 for (const WasmFunction &Func : Functions)
Peter Collingbournef17b1492018-05-21 18:17:42 +0000773 encodeULEB128(Func.Type, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000774
775 endSection(Section);
776}
777
Sam Clegg7c395942017-09-14 23:07:53 +0000778void WasmObjectWriter::writeGlobalSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000779 if (Globals.empty())
780 return;
781
782 SectionBookkeeping Section;
783 startSection(Section, wasm::WASM_SEC_GLOBAL);
784
Peter Collingbournef17b1492018-05-21 18:17:42 +0000785 encodeULEB128(Globals.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000786 for (const WasmGlobal &Global : Globals) {
Sam Clegg6e7f1822018-01-31 19:50:14 +0000787 writeValueType(static_cast<wasm::ValType>(Global.Type.Type));
Peter Collingbournef17b1492018-05-21 18:17:42 +0000788 W.OS << char(Global.Type.Mutable);
Sam Clegg9e15f352017-06-03 02:01:24 +0000789
Peter Collingbournef17b1492018-05-21 18:17:42 +0000790 W.OS << char(wasm::WASM_OPCODE_I32_CONST);
791 encodeSLEB128(Global.InitialValue, W.OS);
792 W.OS << char(wasm::WASM_OPCODE_END);
Sam Clegg9e15f352017-06-03 02:01:24 +0000793 }
794
795 endSection(Section);
796}
797
Sam Clegg8defa952018-02-12 22:41:29 +0000798void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000799 if (Exports.empty())
800 return;
801
802 SectionBookkeeping Section;
803 startSection(Section, wasm::WASM_SEC_EXPORT);
804
Peter Collingbournef17b1492018-05-21 18:17:42 +0000805 encodeULEB128(Exports.size(), W.OS);
Sam Clegg8defa952018-02-12 22:41:29 +0000806 for (const wasm::WasmExport &Export : Exports) {
807 writeString(Export.Name);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000808 W.OS << char(Export.Kind);
809 encodeULEB128(Export.Index, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000810 }
811
812 endSection(Section);
813}
814
Sam Clegg457fb0b2017-09-15 19:50:44 +0000815void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000816 if (TableElems.empty())
817 return;
818
819 SectionBookkeeping Section;
820 startSection(Section, wasm::WASM_SEC_ELEM);
821
Peter Collingbournef17b1492018-05-21 18:17:42 +0000822 encodeULEB128(1, W.OS); // number of "segments"
823 encodeULEB128(0, W.OS); // the table index
Sam Clegg9e15f352017-06-03 02:01:24 +0000824
825 // init expr for starting offset
Peter Collingbournef17b1492018-05-21 18:17:42 +0000826 W.OS << char(wasm::WASM_OPCODE_I32_CONST);
827 encodeSLEB128(kInitialTableOffset, W.OS);
828 W.OS << char(wasm::WASM_OPCODE_END);
Sam Clegg9e15f352017-06-03 02:01:24 +0000829
Peter Collingbournef17b1492018-05-21 18:17:42 +0000830 encodeULEB128(TableElems.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000831 for (uint32_t Elem : TableElems)
Peter Collingbournef17b1492018-05-21 18:17:42 +0000832 encodeULEB128(Elem, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000833
834 endSection(Section);
835}
836
Sam Clegg457fb0b2017-09-15 19:50:44 +0000837void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
838 const MCAsmLayout &Layout,
839 ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000840 if (Functions.empty())
841 return;
842
843 SectionBookkeeping Section;
844 startSection(Section, wasm::WASM_SEC_CODE);
Sam Clegg6f08c842018-04-24 18:11:36 +0000845 CodeSectionIndex = Section.Index;
Sam Clegg9e15f352017-06-03 02:01:24 +0000846
Peter Collingbournef17b1492018-05-21 18:17:42 +0000847 encodeULEB128(Functions.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000848
849 for (const WasmFunction &Func : Functions) {
Sam Cleggfe6414b2017-06-21 23:46:41 +0000850 auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
Sam Clegg9e15f352017-06-03 02:01:24 +0000851
Sam Clegg9e15f352017-06-03 02:01:24 +0000852 int64_t Size = 0;
853 if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
854 report_fatal_error(".size expression must be evaluatable");
855
Peter Collingbournef17b1492018-05-21 18:17:42 +0000856 encodeULEB128(Size, W.OS);
857 FuncSection.setSectionOffset(W.OS.tell() - Section.ContentsOffset);
858 Asm.writeSectionData(W.OS, &FuncSection, Layout);
Sam Clegg9e15f352017-06-03 02:01:24 +0000859 }
860
Sam Clegg9e15f352017-06-03 02:01:24 +0000861 // Apply fixups.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000862 applyRelocations(CodeRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000863
864 endSection(Section);
865}
866
Sam Clegg6c899ba2018-02-23 05:08:34 +0000867void WasmObjectWriter::writeDataSection() {
868 if (DataSegments.empty())
Sam Clegg7c395942017-09-14 23:07:53 +0000869 return;
Sam Clegg9e15f352017-06-03 02:01:24 +0000870
871 SectionBookkeeping Section;
872 startSection(Section, wasm::WASM_SEC_DATA);
Sam Clegg6f08c842018-04-24 18:11:36 +0000873 DataSectionIndex = Section.Index;
Sam Clegg9e15f352017-06-03 02:01:24 +0000874
Peter Collingbournef17b1492018-05-21 18:17:42 +0000875 encodeULEB128(DataSegments.size(), W.OS); // count
Sam Clegg7c395942017-09-14 23:07:53 +0000876
Sam Clegg6c899ba2018-02-23 05:08:34 +0000877 for (const WasmDataSegment &Segment : DataSegments) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000878 encodeULEB128(0, W.OS); // memory index
879 W.OS << char(wasm::WASM_OPCODE_I32_CONST);
880 encodeSLEB128(Segment.Offset, W.OS); // offset
881 W.OS << char(wasm::WASM_OPCODE_END);
882 encodeULEB128(Segment.Data.size(), W.OS); // size
883 Segment.Section->setSectionOffset(W.OS.tell() - Section.ContentsOffset);
884 W.OS << Segment.Data; // data
Sam Clegg7c395942017-09-14 23:07:53 +0000885 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000886
887 // Apply fixups.
Sam Clegg7c395942017-09-14 23:07:53 +0000888 applyRelocations(DataRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000889
890 endSection(Section);
Sam Clegg9e15f352017-06-03 02:01:24 +0000891}
892
Sam Clegg6f08c842018-04-24 18:11:36 +0000893void WasmObjectWriter::writeRelocSection(
894 uint32_t SectionIndex, StringRef Name,
Heejin Ahnf208f632018-09-05 01:27:38 +0000895 std::vector<WasmRelocationEntry> &Relocs) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000896 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
897 // for descriptions of the reloc sections.
898
Sam Cleggf77dc2a2018-08-22 17:27:31 +0000899 if (Relocs.empty())
Sam Clegg9e15f352017-06-03 02:01:24 +0000900 return;
901
Sam Cleggf77dc2a2018-08-22 17:27:31 +0000902 // First, ensure the relocations are sorted in offset order. In general they
903 // should already be sorted since `recordRelocation` is called in offset
904 // order, but for the code section we combine many MC sections into single
905 // wasm section, and this order is determined by the order of Asm.Symbols()
906 // not the sections order.
907 std::stable_sort(
908 Relocs.begin(), Relocs.end(),
909 [](const WasmRelocationEntry &A, const WasmRelocationEntry &B) {
910 return (A.Offset + A.FixupSection->getSectionOffset()) <
911 (B.Offset + B.FixupSection->getSectionOffset());
912 });
913
Sam Clegg9e15f352017-06-03 02:01:24 +0000914 SectionBookkeeping Section;
Sam Clegg6f08c842018-04-24 18:11:36 +0000915 startCustomSection(Section, std::string("reloc.") + Name.str());
Sam Clegg9e15f352017-06-03 02:01:24 +0000916
Peter Collingbournef17b1492018-05-21 18:17:42 +0000917 encodeULEB128(SectionIndex, W.OS);
Sam Cleggf77dc2a2018-08-22 17:27:31 +0000918 encodeULEB128(Relocs.size(), W.OS);
Heejin Ahnf208f632018-09-05 01:27:38 +0000919 for (const WasmRelocationEntry &RelEntry : Relocs) {
920 uint64_t Offset =
921 RelEntry.Offset + RelEntry.FixupSection->getSectionOffset();
Sam Clegg6f08c842018-04-24 18:11:36 +0000922 uint32_t Index = getRelocationIndexValue(RelEntry);
Sam Clegg9e15f352017-06-03 02:01:24 +0000923
Peter Collingbournef17b1492018-05-21 18:17:42 +0000924 W.OS << char(RelEntry.Type);
925 encodeULEB128(Offset, W.OS);
926 encodeULEB128(Index, W.OS);
Sam Clegg6f08c842018-04-24 18:11:36 +0000927 if (RelEntry.hasAddend())
Peter Collingbournef17b1492018-05-21 18:17:42 +0000928 encodeSLEB128(RelEntry.Addend, W.OS);
Sam Clegg6f08c842018-04-24 18:11:36 +0000929 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000930
931 endSection(Section);
932}
933
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000934void WasmObjectWriter::writeCustomRelocSections() {
935 for (const auto &Sec : CustomSections) {
936 auto &Relocations = CustomSectionsRelocations[Sec.Section];
937 writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations);
938 }
939}
940
Sam Clegg9e15f352017-06-03 02:01:24 +0000941void WasmObjectWriter::writeLinkingMetaDataSection(
Sam Clegg86b4a092018-02-27 23:57:37 +0000942 ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
Sam Cleggea7cace2018-01-09 23:43:14 +0000943 ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
Sam Clegg6c899ba2018-02-23 05:08:34 +0000944 const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000945 SectionBookkeeping Section;
Sam Clegg2322a932018-04-23 19:16:19 +0000946 startCustomSection(Section, "linking");
Peter Collingbournef17b1492018-05-21 18:17:42 +0000947 encodeULEB128(wasm::WasmMetadataVersion, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000948
Sam Clegg6bb5a412018-04-26 18:15:32 +0000949 SectionBookkeeping SubSection;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000950 if (SymbolInfos.size() != 0) {
951 startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000952 encodeULEB128(SymbolInfos.size(), W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000953 for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000954 encodeULEB128(Sym.Kind, W.OS);
955 encodeULEB128(Sym.Flags, W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000956 switch (Sym.Kind) {
957 case wasm::WASM_SYMBOL_TYPE_FUNCTION:
958 case wasm::WASM_SYMBOL_TYPE_GLOBAL:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000959 encodeULEB128(Sym.ElementIndex, W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000960 if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0)
961 writeString(Sym.Name);
962 break;
963 case wasm::WASM_SYMBOL_TYPE_DATA:
964 writeString(Sym.Name);
965 if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000966 encodeULEB128(Sym.DataRef.Segment, W.OS);
967 encodeULEB128(Sym.DataRef.Offset, W.OS);
968 encodeULEB128(Sym.DataRef.Size, W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000969 }
970 break;
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000971 case wasm::WASM_SYMBOL_TYPE_SECTION: {
972 const uint32_t SectionIndex =
973 CustomSections[Sym.ElementIndex].OutputIndex;
Peter Collingbournef17b1492018-05-21 18:17:42 +0000974 encodeULEB128(SectionIndex, W.OS);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000975 break;
976 }
Sam Clegg6c899ba2018-02-23 05:08:34 +0000977 default:
978 llvm_unreachable("unexpected kind");
979 }
Sam Cleggb7787fd2017-06-20 04:04:59 +0000980 }
981 endSection(SubSection);
982 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000983
Sam Clegg6c899ba2018-02-23 05:08:34 +0000984 if (DataSegments.size()) {
Sam Clegg63ebb812017-09-29 16:50:08 +0000985 startSection(SubSection, wasm::WASM_SEGMENT_INFO);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000986 encodeULEB128(DataSegments.size(), W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000987 for (const WasmDataSegment &Segment : DataSegments) {
Sam Cleggd95ed952017-09-20 19:03:35 +0000988 writeString(Segment.Name);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000989 encodeULEB128(Segment.Alignment, W.OS);
990 encodeULEB128(Segment.Flags, W.OS);
Sam Clegg63ebb812017-09-29 16:50:08 +0000991 }
Sam Cleggd95ed952017-09-20 19:03:35 +0000992 endSection(SubSection);
993 }
994
Sam Cleggbafe6902017-12-15 00:17:10 +0000995 if (!InitFuncs.empty()) {
996 startSection(SubSection, wasm::WASM_INIT_FUNCS);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000997 encodeULEB128(InitFuncs.size(), W.OS);
Sam Cleggbafe6902017-12-15 00:17:10 +0000998 for (auto &StartFunc : InitFuncs) {
Heejin Ahnf208f632018-09-05 01:27:38 +0000999 encodeULEB128(StartFunc.first, W.OS); // priority
Peter Collingbournef17b1492018-05-21 18:17:42 +00001000 encodeULEB128(StartFunc.second, W.OS); // function index
Sam Cleggbafe6902017-12-15 00:17:10 +00001001 }
1002 endSection(SubSection);
1003 }
1004
Sam Cleggea7cace2018-01-09 23:43:14 +00001005 if (Comdats.size()) {
1006 startSection(SubSection, wasm::WASM_COMDAT_INFO);
Peter Collingbournef17b1492018-05-21 18:17:42 +00001007 encodeULEB128(Comdats.size(), W.OS);
Sam Cleggea7cace2018-01-09 23:43:14 +00001008 for (const auto &C : Comdats) {
1009 writeString(C.first);
Peter Collingbournef17b1492018-05-21 18:17:42 +00001010 encodeULEB128(0, W.OS); // flags for future use
1011 encodeULEB128(C.second.size(), W.OS);
Sam Cleggea7cace2018-01-09 23:43:14 +00001012 for (const WasmComdatEntry &Entry : C.second) {
Peter Collingbournef17b1492018-05-21 18:17:42 +00001013 encodeULEB128(Entry.Kind, W.OS);
1014 encodeULEB128(Entry.Index, W.OS);
Sam Cleggea7cace2018-01-09 23:43:14 +00001015 }
1016 }
1017 endSection(SubSection);
1018 }
1019
Sam Clegg9e15f352017-06-03 02:01:24 +00001020 endSection(Section);
1021}
1022
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001023void WasmObjectWriter::writeCustomSections(const MCAssembler &Asm,
1024 const MCAsmLayout &Layout) {
1025 for (auto &CustomSection : CustomSections) {
Sam Cleggcfd44a22018-04-05 17:01:39 +00001026 SectionBookkeeping Section;
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001027 auto *Sec = CustomSection.Section;
Sam Clegg2322a932018-04-23 19:16:19 +00001028 startCustomSection(Section, CustomSection.Name);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001029
Peter Collingbournef17b1492018-05-21 18:17:42 +00001030 Sec->setSectionOffset(W.OS.tell() - Section.ContentsOffset);
1031 Asm.writeSectionData(W.OS, Sec, Layout);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001032
1033 CustomSection.OutputContentsOffset = Section.ContentsOffset;
1034 CustomSection.OutputIndex = Section.Index;
1035
Sam Cleggcfd44a22018-04-05 17:01:39 +00001036 endSection(Section);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001037
1038 // Apply fixups.
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001039 auto &Relocations = CustomSectionsRelocations[CustomSection.Section];
1040 applyRelocations(Relocations, CustomSection.OutputContentsOffset);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001041 }
1042}
1043
Heejin Ahnf208f632018-09-05 01:27:38 +00001044uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm &Symbol) {
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001045 assert(Symbol.isFunction());
1046 assert(TypeIndices.count(&Symbol));
1047 return TypeIndices[&Symbol];
1048}
1049
Heejin Ahnf208f632018-09-05 01:27:38 +00001050uint32_t WasmObjectWriter::registerFunctionType(const MCSymbolWasm &Symbol) {
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001051 assert(Symbol.isFunction());
1052
1053 WasmFunctionType F;
Heejin Ahnf208f632018-09-05 01:27:38 +00001054 const MCSymbolWasm *ResolvedSym = ResolveSymbol(Symbol);
Derek Schuff77a7a382018-10-03 22:22:48 +00001055 if (auto *Sig = ResolvedSym->getSignature()) {
1056 F.Returns = Sig->Returns;
1057 F.Params = Sig->Params;
1058 }
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001059
1060 auto Pair =
1061 FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
1062 if (Pair.second)
1063 FunctionTypes.push_back(F);
1064 TypeIndices[&Symbol] = Pair.first->second;
1065
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001066 LLVM_DEBUG(dbgs() << "registerFunctionType: " << Symbol
1067 << " new:" << Pair.second << "\n");
1068 LLVM_DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n");
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001069 return Pair.first->second;
1070}
1071
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001072static bool isInSymtab(const MCSymbolWasm &Sym) {
1073 if (Sym.isUsedInReloc())
1074 return true;
1075
1076 if (Sym.isComdat() && !Sym.isDefined())
1077 return false;
1078
1079 if (Sym.isTemporary() && Sym.getName().empty())
1080 return false;
1081
1082 if (Sym.isTemporary() && Sym.isData() && !Sym.getSize())
1083 return false;
1084
1085 if (Sym.isSection())
1086 return false;
1087
1088 return true;
1089}
1090
Peter Collingbourne438390f2018-05-21 18:23:50 +00001091uint64_t WasmObjectWriter::writeObject(MCAssembler &Asm,
1092 const MCAsmLayout &Layout) {
1093 uint64_t StartOffset = W.OS.tell();
1094
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001095 LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
Dan Gohman82607f52017-02-24 23:46:05 +00001096 MCContext &Ctx = Asm.getContext();
Dan Gohmand934cb82017-02-24 23:18:00 +00001097
1098 // Collect information from the available symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +00001099 SmallVector<WasmFunction, 4> Functions;
1100 SmallVector<uint32_t, 4> TableElems;
Sam Clegg8defa952018-02-12 22:41:29 +00001101 SmallVector<wasm::WasmImport, 4> Imports;
1102 SmallVector<wasm::WasmExport, 4> Exports;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001103 SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
Sam Cleggbafe6902017-12-15 00:17:10 +00001104 SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
Sam Cleggea7cace2018-01-09 23:43:14 +00001105 std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
Sam Clegg7c395942017-09-14 23:07:53 +00001106 uint32_t DataSize = 0;
Dan Gohmand934cb82017-02-24 23:18:00 +00001107
Sam Cleggf950b242017-12-11 23:03:38 +00001108 // For now, always emit the memory import, since loads and stores are not
1109 // valid without it. In the future, we could perhaps be more clever and omit
1110 // it if there are no loads or stores.
1111 MCSymbolWasm *MemorySym =
1112 cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__linear_memory"));
Sam Clegg8defa952018-02-12 22:41:29 +00001113 wasm::WasmImport MemImport;
1114 MemImport.Module = MemorySym->getModuleName();
1115 MemImport.Field = MemorySym->getName();
Sam Cleggf950b242017-12-11 23:03:38 +00001116 MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1117 Imports.push_back(MemImport);
1118
1119 // For now, always emit the table section, since indirect calls are not
1120 // valid without it. In the future, we could perhaps be more clever and omit
1121 // it if there are no indirect calls.
1122 MCSymbolWasm *TableSym =
1123 cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__indirect_function_table"));
Sam Clegg8defa952018-02-12 22:41:29 +00001124 wasm::WasmImport TableImport;
1125 TableImport.Module = TableSym->getModuleName();
1126 TableImport.Field = TableSym->getName();
Sam Cleggf950b242017-12-11 23:03:38 +00001127 TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
Sam Clegg8defa952018-02-12 22:41:29 +00001128 TableImport.Table.ElemType = wasm::WASM_TYPE_ANYFUNC;
Sam Cleggf950b242017-12-11 23:03:38 +00001129 Imports.push_back(TableImport);
1130
Nicholas Wilson586320c2018-02-28 17:19:48 +00001131 // Populate FunctionTypeIndices, and Imports and WasmIndices for undefined
1132 // symbols. This must be done before populating WasmIndices for defined
1133 // symbols.
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001134 for (const MCSymbol &S : Asm.symbols()) {
1135 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1136
1137 // Register types for all functions, including those with private linkage
Sam Clegg9f3fe422018-01-17 19:28:43 +00001138 // (because wasm always needs a type signature).
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001139 if (WS.isFunction())
1140 registerFunctionType(WS);
1141
1142 if (WS.isTemporary())
1143 continue;
1144
1145 // If the symbol is not defined in this translation unit, import it.
Sam Clegg6c899ba2018-02-23 05:08:34 +00001146 if (!WS.isDefined() && !WS.isComdat()) {
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001147 if (WS.isFunction()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001148 wasm::WasmImport Import;
1149 Import.Module = WS.getModuleName();
1150 Import.Field = WS.getName();
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001151 Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
Sam Clegg8defa952018-02-12 22:41:29 +00001152 Import.SigIndex = getFunctionType(WS);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001153 Imports.push_back(Import);
1154 WasmIndices[&WS] = NumFunctionImports++;
1155 } else if (WS.isGlobal()) {
Nicholas Wilson15f349f2018-03-09 16:30:44 +00001156 if (WS.isWeak())
1157 report_fatal_error("undefined global symbol cannot be weak");
1158
Sam Clegg6c899ba2018-02-23 05:08:34 +00001159 wasm::WasmImport Import;
1160 Import.Module = WS.getModuleName();
1161 Import.Field = WS.getName();
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001162 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001163 Import.Global = WS.getGlobalType();
1164 Imports.push_back(Import);
1165 WasmIndices[&WS] = NumGlobalImports++;
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001166 }
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001167 }
1168 }
1169
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001170 // Populate DataSegments and CustomSections, which must be done before
1171 // populating DataLocations.
Sam Clegg759631c2017-09-15 20:54:59 +00001172 for (MCSection &Sec : Asm) {
1173 auto &Section = static_cast<MCSectionWasm &>(Sec);
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001174 StringRef SectionName = Section.getSectionName();
Sam Clegg759631c2017-09-15 20:54:59 +00001175
Sam Cleggbafe6902017-12-15 00:17:10 +00001176 // .init_array sections are handled specially elsewhere.
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001177 if (SectionName.startswith(".init_array"))
Sam Cleggbafe6902017-12-15 00:17:10 +00001178 continue;
1179
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001180 // Code is handled separately
1181 if (Section.getKind().isText())
1182 continue;
Sam Cleggea7cace2018-01-09 23:43:14 +00001183
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001184 if (Section.isWasmData()) {
1185 uint32_t SegmentIndex = DataSegments.size();
1186 DataSize = alignTo(DataSize, Section.getAlignment());
1187 DataSegments.emplace_back();
1188 WasmDataSegment &Segment = DataSegments.back();
1189 Segment.Name = SectionName;
1190 Segment.Offset = DataSize;
1191 Segment.Section = &Section;
1192 addData(Segment.Data, Section);
1193 Segment.Alignment = Section.getAlignment();
1194 Segment.Flags = 0;
1195 DataSize += Segment.Data.size();
1196 Section.setSegmentIndex(SegmentIndex);
1197
1198 if (const MCSymbolWasm *C = Section.getGroup()) {
1199 Comdats[C->getName()].emplace_back(
1200 WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
1201 }
1202 } else {
1203 // Create custom sections
1204 assert(Sec.getKind().isMetadata());
1205
1206 StringRef Name = SectionName;
1207
1208 // For user-defined custom sections, strip the prefix
1209 if (Name.startswith(".custom_section."))
1210 Name = Name.substr(strlen(".custom_section."));
1211
Heejin Ahnf208f632018-09-05 01:27:38 +00001212 MCSymbol *Begin = Sec.getBeginSymbol();
Sam Cleggfb807d42018-05-07 19:40:50 +00001213 if (Begin) {
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001214 WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size();
Sam Cleggb210c642018-05-10 17:38:35 +00001215 if (SectionName != Begin->getName())
Sam Cleggfb807d42018-05-07 19:40:50 +00001216 report_fatal_error("section name and begin symbol should match: " +
Sam Cleggb210c642018-05-10 17:38:35 +00001217 Twine(SectionName));
Sam Cleggfb807d42018-05-07 19:40:50 +00001218 }
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001219 CustomSections.emplace_back(Name, &Section);
Sam Cleggea7cace2018-01-09 23:43:14 +00001220 }
Sam Clegg759631c2017-09-15 20:54:59 +00001221 }
1222
Nicholas Wilson586320c2018-02-28 17:19:48 +00001223 // Populate WasmIndices and DataLocations for defined symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +00001224 for (const MCSymbol &S : Asm.symbols()) {
1225 // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1226 // or used in relocations.
1227 if (S.isTemporary() && S.getName().empty())
1228 continue;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001229
Dan Gohmand934cb82017-02-24 23:18:00 +00001230 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001231 LLVM_DEBUG(
1232 dbgs() << "MCSymbol: " << toString(WS.getType()) << " '" << S << "'"
1233 << " isDefined=" << S.isDefined() << " isExternal="
1234 << S.isExternal() << " isTemporary=" << S.isTemporary()
1235 << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden()
1236 << " isVariable=" << WS.isVariable() << "\n");
Sam Cleggb7787fd2017-06-20 04:04:59 +00001237
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001238 if (WS.isVariable())
1239 continue;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001240 if (WS.isComdat() && !WS.isDefined())
1241 continue;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001242
Dan Gohmand934cb82017-02-24 23:18:00 +00001243 if (WS.isFunction()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001244 unsigned Index;
Sam Cleggcd65f692018-01-11 23:59:16 +00001245 if (WS.isDefined()) {
Sam Cleggb7787fd2017-06-20 04:04:59 +00001246 if (WS.getOffset() != 0)
1247 report_fatal_error(
1248 "function sections must contain one function each");
1249
1250 if (WS.getSize() == 0)
1251 report_fatal_error(
1252 "function symbols must have a size set with .size");
1253
Sam Clegg6c899ba2018-02-23 05:08:34 +00001254 // A definition. Write out the function body.
Sam Clegg9f3fe422018-01-17 19:28:43 +00001255 Index = NumFunctionImports + Functions.size();
Dan Gohmand934cb82017-02-24 23:18:00 +00001256 WasmFunction Func;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001257 Func.Type = getFunctionType(WS);
Dan Gohmand934cb82017-02-24 23:18:00 +00001258 Func.Sym = &WS;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001259 WasmIndices[&WS] = Index;
Dan Gohmand934cb82017-02-24 23:18:00 +00001260 Functions.push_back(Func);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001261
1262 auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
1263 if (const MCSymbolWasm *C = Section.getGroup()) {
1264 Comdats[C->getName()].emplace_back(
1265 WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
1266 }
Dan Gohmand934cb82017-02-24 23:18:00 +00001267 } else {
1268 // An import; the index was assigned above.
Sam Clegg6c899ba2018-02-23 05:08:34 +00001269 Index = WasmIndices.find(&WS)->second;
Dan Gohmand934cb82017-02-24 23:18:00 +00001270 }
1271
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001272 LLVM_DEBUG(dbgs() << " -> function index: " << Index << "\n");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001273 } else if (WS.isData()) {
Sam Cleggc38e9472017-06-02 01:05:24 +00001274 if (WS.isTemporary() && !WS.getSize())
1275 continue;
Dan Gohmand934cb82017-02-24 23:18:00 +00001276
Sam Clegg6c899ba2018-02-23 05:08:34 +00001277 if (!WS.isDefined()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001278 LLVM_DEBUG(dbgs() << " -> segment index: -1"
1279 << "\n");
Sam Cleggfe6414b2017-06-21 23:46:41 +00001280 continue;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001281 }
Sam Cleggc38e9472017-06-02 01:05:24 +00001282
Sam Cleggfe6414b2017-06-21 23:46:41 +00001283 if (!WS.getSize())
1284 report_fatal_error("data symbols must have a size set with .size: " +
1285 WS.getName());
Sam Cleggc38e9472017-06-02 01:05:24 +00001286
Sam Cleggfe6414b2017-06-21 23:46:41 +00001287 int64_t Size = 0;
1288 if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1289 report_fatal_error(".size expression must be evaluatable");
Dan Gohmand934cb82017-02-24 23:18:00 +00001290
Sam Clegg759631c2017-09-15 20:54:59 +00001291 auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
Sam Cleggea7cace2018-01-09 23:43:14 +00001292 assert(DataSection.isWasmData());
Sam Clegg7c395942017-09-14 23:07:53 +00001293
Sam Clegg6c899ba2018-02-23 05:08:34 +00001294 // For each data symbol, export it in the symtab as a reference to the
1295 // corresponding Wasm data segment.
1296 wasm::WasmDataReference Ref = wasm::WasmDataReference{
1297 DataSection.getSegmentIndex(),
1298 static_cast<uint32_t>(Layout.getSymbolOffset(WS)),
1299 static_cast<uint32_t>(Size)};
1300 DataLocations[&WS] = Ref;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001301 LLVM_DEBUG(dbgs() << " -> segment index: " << Ref.Segment << "\n");
Sam Clegga165f2d2018-04-30 19:40:57 +00001302 } else if (WS.isGlobal()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001303 // A "true" Wasm global (currently just __stack_pointer)
Eric Christopher545932b2018-02-23 21:14:47 +00001304 if (WS.isDefined())
Sam Clegg6c899ba2018-02-23 05:08:34 +00001305 report_fatal_error("don't yet support defined globals");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001306
Eric Christopher545932b2018-02-23 21:14:47 +00001307 // An import; the index was assigned above
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001308 LLVM_DEBUG(dbgs() << " -> global index: "
1309 << WasmIndices.find(&WS)->second << "\n");
Sam Clegga165f2d2018-04-30 19:40:57 +00001310 } else {
1311 assert(WS.isSection());
Dan Gohmand934cb82017-02-24 23:18:00 +00001312 }
1313 }
1314
Nicholas Wilson586320c2018-02-28 17:19:48 +00001315 // Populate WasmIndices and DataLocations for aliased symbols. We need to
1316 // process these in a separate pass because we need to have processed the
1317 // target of the alias before the alias itself and the symbols are not
1318 // necessarily ordered in this way.
Sam Cleggb7787fd2017-06-20 04:04:59 +00001319 for (const MCSymbol &S : Asm.symbols()) {
1320 if (!S.isVariable())
1321 continue;
Sam Clegg31a2c802017-09-20 21:17:04 +00001322
Sam Cleggcd65f692018-01-11 23:59:16 +00001323 assert(S.isDefined());
Sam Cleggb7787fd2017-06-20 04:04:59 +00001324
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001325 // Find the target symbol of this weak alias and export that index
Sam Cleggaff1c4d2017-09-15 19:22:01 +00001326 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1327 const MCSymbolWasm *ResolvedSym = ResolveSymbol(WS);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001328 LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym
1329 << "'\n");
Sam Cleggb7787fd2017-06-20 04:04:59 +00001330
Sam Clegg6c899ba2018-02-23 05:08:34 +00001331 if (WS.isFunction()) {
1332 assert(WasmIndices.count(ResolvedSym) > 0);
1333 uint32_t WasmIndex = WasmIndices.find(ResolvedSym)->second;
1334 WasmIndices[&WS] = WasmIndex;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001335 LLVM_DEBUG(dbgs() << " -> index:" << WasmIndex << "\n");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001336 } else if (WS.isData()) {
1337 assert(DataLocations.count(ResolvedSym) > 0);
1338 const wasm::WasmDataReference &Ref =
1339 DataLocations.find(ResolvedSym)->second;
1340 DataLocations[&WS] = Ref;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001341 LLVM_DEBUG(dbgs() << " -> index:" << Ref.Segment << "\n");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001342 } else {
1343 report_fatal_error("don't yet support global aliases");
1344 }
Nicholas Wilson586320c2018-02-28 17:19:48 +00001345 }
Sam Clegg31a2c802017-09-20 21:17:04 +00001346
Nicholas Wilson586320c2018-02-28 17:19:48 +00001347 // Finally, populate the symbol table itself, in its "natural" order.
1348 for (const MCSymbol &S : Asm.symbols()) {
1349 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Sam Clegg25d8e682018-05-08 00:08:21 +00001350 if (!isInSymtab(WS)) {
1351 WS.setIndex(INVALID_INDEX);
Nicholas Wilson586320c2018-02-28 17:19:48 +00001352 continue;
Sam Clegg25d8e682018-05-08 00:08:21 +00001353 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001354 LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n");
Nicholas Wilson586320c2018-02-28 17:19:48 +00001355
1356 uint32_t Flags = 0;
1357 if (WS.isWeak())
1358 Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
1359 if (WS.isHidden())
1360 Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
1361 if (!WS.isExternal() && WS.isDefined())
1362 Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
1363 if (WS.isUndefined())
1364 Flags |= wasm::WASM_SYMBOL_UNDEFINED;
1365
1366 wasm::WasmSymbolInfo Info;
1367 Info.Name = WS.getName();
1368 Info.Kind = WS.getType();
1369 Info.Flags = Flags;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001370 if (!WS.isData()) {
1371 assert(WasmIndices.count(&WS) > 0);
Nicholas Wilson586320c2018-02-28 17:19:48 +00001372 Info.ElementIndex = WasmIndices.find(&WS)->second;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001373 } else if (WS.isDefined()) {
1374 assert(DataLocations.count(&WS) > 0);
Nicholas Wilson586320c2018-02-28 17:19:48 +00001375 Info.DataRef = DataLocations.find(&WS)->second;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001376 }
Sam Clegg25d8e682018-05-08 00:08:21 +00001377 WS.setIndex(SymbolInfos.size());
Nicholas Wilson586320c2018-02-28 17:19:48 +00001378 SymbolInfos.emplace_back(Info);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001379 }
1380
Sam Clegg6006e092017-12-22 20:31:39 +00001381 {
1382 auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
Sam Cleggf9edbe92018-01-31 19:28:47 +00001383 // Functions referenced by a relocation need to put in the table. This is
1384 // purely to make the object file's provisional values readable, and is
1385 // ignored by the linker, which re-calculates the relocations itself.
1386 if (Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_I32 &&
1387 Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB)
1388 return;
1389 assert(Rel.Symbol->isFunction());
1390 const MCSymbolWasm &WS = *ResolveSymbol(*Rel.Symbol);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001391 uint32_t FunctionIndex = WasmIndices.find(&WS)->second;
Sam Cleggf9edbe92018-01-31 19:28:47 +00001392 uint32_t TableIndex = TableElems.size() + kInitialTableOffset;
1393 if (TableIndices.try_emplace(&WS, TableIndex).second) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001394 LLVM_DEBUG(dbgs() << " -> adding " << WS.getName()
1395 << " to table: " << TableIndex << "\n");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001396 TableElems.push_back(FunctionIndex);
Sam Cleggf9edbe92018-01-31 19:28:47 +00001397 registerFunctionType(WS);
Sam Clegg6006e092017-12-22 20:31:39 +00001398 }
1399 };
Dan Gohman970d02c2017-03-30 23:58:19 +00001400
Sam Clegg6006e092017-12-22 20:31:39 +00001401 for (const WasmRelocationEntry &RelEntry : CodeRelocations)
1402 HandleReloc(RelEntry);
1403 for (const WasmRelocationEntry &RelEntry : DataRelocations)
1404 HandleReloc(RelEntry);
Dan Gohmand934cb82017-02-24 23:18:00 +00001405 }
1406
Sam Cleggbafe6902017-12-15 00:17:10 +00001407 // Translate .init_array section contents into start functions.
1408 for (const MCSection &S : Asm) {
1409 const auto &WS = static_cast<const MCSectionWasm &>(S);
1410 if (WS.getSectionName().startswith(".fini_array"))
1411 report_fatal_error(".fini_array sections are unsupported");
1412 if (!WS.getSectionName().startswith(".init_array"))
1413 continue;
1414 if (WS.getFragmentList().empty())
1415 continue;
Sam Cleggb210c642018-05-10 17:38:35 +00001416
1417 // init_array is expected to contain a single non-empty data fragment
1418 if (WS.getFragmentList().size() != 3)
Sam Cleggbafe6902017-12-15 00:17:10 +00001419 report_fatal_error("only one .init_array section fragment supported");
Sam Cleggb210c642018-05-10 17:38:35 +00001420
1421 auto IT = WS.begin();
1422 const MCFragment &EmptyFrag = *IT;
1423 if (EmptyFrag.getKind() != MCFragment::FT_Data)
1424 report_fatal_error(".init_array section should be aligned");
1425
1426 IT = std::next(IT);
1427 const MCFragment &AlignFrag = *IT;
Sam Cleggbafe6902017-12-15 00:17:10 +00001428 if (AlignFrag.getKind() != MCFragment::FT_Align)
1429 report_fatal_error(".init_array section should be aligned");
1430 if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1431 report_fatal_error(".init_array section should be aligned for pointers");
Sam Cleggb210c642018-05-10 17:38:35 +00001432
1433 const MCFragment &Frag = *std::next(IT);
Sam Cleggbafe6902017-12-15 00:17:10 +00001434 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1435 report_fatal_error("only data supported in .init_array section");
Sam Cleggb210c642018-05-10 17:38:35 +00001436
Sam Cleggbafe6902017-12-15 00:17:10 +00001437 uint16_t Priority = UINT16_MAX;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001438 unsigned PrefixLength = strlen(".init_array");
1439 if (WS.getSectionName().size() > PrefixLength) {
1440 if (WS.getSectionName()[PrefixLength] != '.')
Heejin Ahnf208f632018-09-05 01:27:38 +00001441 report_fatal_error(
1442 ".init_array section priority should start with '.'");
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001443 if (WS.getSectionName()
1444 .substr(PrefixLength + 1)
1445 .getAsInteger(10, Priority))
Sam Cleggbafe6902017-12-15 00:17:10 +00001446 report_fatal_error("invalid .init_array section priority");
1447 }
1448 const auto &DataFrag = cast<MCDataFragment>(Frag);
1449 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
Heejin Ahnf208f632018-09-05 01:27:38 +00001450 for (const uint8_t *
1451 p = (const uint8_t *)Contents.data(),
1452 *end = (const uint8_t *)Contents.data() + Contents.size();
Sam Cleggbafe6902017-12-15 00:17:10 +00001453 p != end; ++p) {
1454 if (*p != 0)
1455 report_fatal_error("non-symbolic data in .init_array section");
1456 }
1457 for (const MCFixup &Fixup : DataFrag.getFixups()) {
Heejin Ahnf208f632018-09-05 01:27:38 +00001458 assert(Fixup.getKind() ==
1459 MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
Sam Cleggbafe6902017-12-15 00:17:10 +00001460 const MCExpr *Expr = Fixup.getValue();
1461 auto *Sym = dyn_cast<MCSymbolRefExpr>(Expr);
1462 if (!Sym)
1463 report_fatal_error("fixups in .init_array should be symbol references");
1464 if (Sym->getKind() != MCSymbolRefExpr::VK_WebAssembly_FUNCTION)
1465 report_fatal_error("symbols in .init_array should be for functions");
Sam Clegg25d8e682018-05-08 00:08:21 +00001466 if (Sym->getSymbol().getIndex() == INVALID_INDEX)
1467 report_fatal_error("symbols in .init_array should exist in symbtab");
1468 InitFuncs.push_back(
1469 std::make_pair(Priority, Sym->getSymbol().getIndex()));
Sam Cleggbafe6902017-12-15 00:17:10 +00001470 }
1471 }
1472
Dan Gohman18eafb62017-02-22 01:23:18 +00001473 // Write out the Wasm header.
1474 writeHeader(Asm);
1475
Sam Clegg9e15f352017-06-03 02:01:24 +00001476 writeTypeSection(FunctionTypes);
Sam Cleggf950b242017-12-11 23:03:38 +00001477 writeImportSection(Imports, DataSize, TableElems.size());
Sam Clegg9e15f352017-06-03 02:01:24 +00001478 writeFunctionSection(Functions);
Sam Cleggf950b242017-12-11 23:03:38 +00001479 // Skip the "table" section; we import the table instead.
1480 // Skip the "memory" section; we import the memory instead.
Sam Clegg7c395942017-09-14 23:07:53 +00001481 writeGlobalSection();
Sam Clegg9e15f352017-06-03 02:01:24 +00001482 writeExportSection(Exports);
Sam Clegg9e15f352017-06-03 02:01:24 +00001483 writeElemSection(TableElems);
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001484 writeCodeSection(Asm, Layout, Functions);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001485 writeDataSection();
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001486 writeCustomSections(Asm, Layout);
Nicholas Wilsonc22bfb62018-03-05 12:59:03 +00001487 writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
Sam Clegg6f08c842018-04-24 18:11:36 +00001488 writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
1489 writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001490 writeCustomRelocSections();
Dan Gohman970d02c2017-03-30 23:58:19 +00001491
Dan Gohmand934cb82017-02-24 23:18:00 +00001492 // TODO: Translate the .comment section to the output.
Peter Collingbourne438390f2018-05-21 18:23:50 +00001493 return W.OS.tell() - StartOffset;
Dan Gohman18eafb62017-02-22 01:23:18 +00001494}
1495
Lang Hames60fbc7c2017-10-10 16:28:07 +00001496std::unique_ptr<MCObjectWriter>
Lang Hames1301a872017-10-10 01:15:10 +00001497llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
1498 raw_pwrite_stream &OS) {
Dan Gohman0917c9e2018-01-15 17:06:23 +00001499 return llvm::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
Dan Gohman18eafb62017-02-22 01:23:18 +00001500}