blob: 407907c0f6810d27ab1fed68b9081cbbca48a1ee [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
Sam Cleggd1f09102018-05-02 00:10:28 +000040#if !defined(NDEBUG)
Sam Clegga165f2d2018-04-30 19:40:57 +000041static std::string toString(wasm::WasmSymbolType type) {
42 switch (type) {
43 case wasm::WASM_SYMBOL_TYPE_FUNCTION:
44 return "WASM_SYMBOL_TYPE_FUNCTION";
45 case wasm::WASM_SYMBOL_TYPE_GLOBAL:
46 return "WASM_SYMBOL_TYPE_GLOBAL";
47 case wasm::WASM_SYMBOL_TYPE_DATA:
48 return "WASM_SYMBOL_TYPE_DATA";
49 case wasm::WASM_SYMBOL_TYPE_SECTION:
50 return "WASM_SYMBOL_TYPE_SECTION";
51 }
Florian Hahnba4d85e2018-05-01 11:18:31 +000052 llvm_unreachable("unknown symbol type");
Sam Clegga165f2d2018-04-30 19:40:57 +000053}
Sam Cleggd1f09102018-05-02 00:10:28 +000054#endif
Sam Clegga165f2d2018-04-30 19:40:57 +000055
56static std::string relocTypetoString(uint32_t type) {
57 switch (type) {
58#define WASM_RELOC(NAME, VALUE) case VALUE: return #NAME;
59#include "llvm/BinaryFormat/WasmRelocs.def"
60#undef WASM_RELOC
61 default:
62 llvm_unreachable("uknown reloc type");
63 }
64}
65
Dan Gohman18eafb62017-02-22 01:23:18 +000066namespace {
Sam Clegg9e15f352017-06-03 02:01:24 +000067
Sam Clegg30e1bbc2018-01-19 18:57:01 +000068// Went we ceate the indirect function table we start at 1, so that there is
69// and emtpy slot at 0 and therefore calling a null function pointer will trap.
70static const uint32_t kInitialTableOffset = 1;
71
Dan Gohmand934cb82017-02-24 23:18:00 +000072// For patching purposes, we need to remember where each section starts, both
73// for patching up the section size field, and for patching up references to
74// locations within the section.
75struct SectionBookkeeping {
76 // Where the size of the section is written.
77 uint64_t SizeOffset;
Sam Clegg6a31a0d2018-04-26 19:27:28 +000078 // Where the section header ends (without custom section name).
79 uint64_t PayloadOffset;
80 // Where the contents of the section starts.
Dan Gohmand934cb82017-02-24 23:18:00 +000081 uint64_t ContentsOffset;
Sam Clegg6f08c842018-04-24 18:11:36 +000082 uint32_t Index;
Dan Gohmand934cb82017-02-24 23:18:00 +000083};
84
Sam Clegg9e15f352017-06-03 02:01:24 +000085// The signature of a wasm function, in a struct capable of being used as a
86// DenseMap key.
87struct WasmFunctionType {
88 // Support empty and tombstone instances, needed by DenseMap.
89 enum { Plain, Empty, Tombstone } State;
90
91 // The return types of the function.
92 SmallVector<wasm::ValType, 1> Returns;
93
94 // The parameter types of the function.
95 SmallVector<wasm::ValType, 4> Params;
96
97 WasmFunctionType() : State(Plain) {}
98
99 bool operator==(const WasmFunctionType &Other) const {
100 return State == Other.State && Returns == Other.Returns &&
101 Params == Other.Params;
102 }
103};
104
105// Traits for using WasmFunctionType in a DenseMap.
106struct WasmFunctionTypeDenseMapInfo {
107 static WasmFunctionType getEmptyKey() {
108 WasmFunctionType FuncTy;
109 FuncTy.State = WasmFunctionType::Empty;
110 return FuncTy;
111 }
112 static WasmFunctionType getTombstoneKey() {
113 WasmFunctionType FuncTy;
114 FuncTy.State = WasmFunctionType::Tombstone;
115 return FuncTy;
116 }
117 static unsigned getHashValue(const WasmFunctionType &FuncTy) {
118 uintptr_t Value = FuncTy.State;
119 for (wasm::ValType Ret : FuncTy.Returns)
120 Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Ret));
121 for (wasm::ValType Param : FuncTy.Params)
122 Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Param));
123 return Value;
124 }
125 static bool isEqual(const WasmFunctionType &LHS,
126 const WasmFunctionType &RHS) {
127 return LHS == RHS;
128 }
129};
130
Sam Clegg7c395942017-09-14 23:07:53 +0000131// A wasm data segment. A wasm binary contains only a single data section
132// but that can contain many segments, each with their own virtual location
133// in memory. Each MCSection data created by llvm is modeled as its own
134// wasm data segment.
135struct WasmDataSegment {
136 MCSectionWasm *Section;
Sam Cleggd95ed952017-09-20 19:03:35 +0000137 StringRef Name;
Sam Clegg7c395942017-09-14 23:07:53 +0000138 uint32_t Offset;
Sam Clegg63ebb812017-09-29 16:50:08 +0000139 uint32_t Alignment;
140 uint32_t Flags;
Sam Clegg7c395942017-09-14 23:07:53 +0000141 SmallVector<char, 4> Data;
142};
143
Sam Clegg9e15f352017-06-03 02:01:24 +0000144// A wasm function to be written into the function section.
145struct WasmFunction {
146 int32_t Type;
147 const MCSymbolWasm *Sym;
148};
149
Sam Clegg9e15f352017-06-03 02:01:24 +0000150// A wasm global to be written into the global section.
151struct WasmGlobal {
Sam Clegg6e7f1822018-01-31 19:50:14 +0000152 wasm::WasmGlobalType Type;
Sam Clegg9e15f352017-06-03 02:01:24 +0000153 uint64_t InitialValue;
Sam Clegg9e15f352017-06-03 02:01:24 +0000154};
155
Sam Cleggea7cace2018-01-09 23:43:14 +0000156// Information about a single item which is part of a COMDAT. For each data
157// segment or function which is in the COMDAT, there is a corresponding
158// WasmComdatEntry.
159struct WasmComdatEntry {
160 unsigned Kind;
161 uint32_t Index;
162};
163
Sam Clegg6dc65e92017-06-06 16:38:59 +0000164// Information about a single relocation.
165struct WasmRelocationEntry {
Sam Cleggfe6414b2017-06-21 23:46:41 +0000166 uint64_t Offset; // Where is the relocation.
167 const MCSymbolWasm *Symbol; // The symbol to relocate with.
168 int64_t Addend; // A value to add to the symbol.
169 unsigned Type; // The type of the relocation.
170 const MCSectionWasm *FixupSection;// The section the relocation is targeting.
Sam Clegg6dc65e92017-06-06 16:38:59 +0000171
172 WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
173 int64_t Addend, unsigned Type,
Sam Cleggfe6414b2017-06-21 23:46:41 +0000174 const MCSectionWasm *FixupSection)
Sam Clegg6dc65e92017-06-06 16:38:59 +0000175 : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
176 FixupSection(FixupSection) {}
177
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000178 bool hasAddend() const {
179 switch (Type) {
Sam Clegg13a2e892017-09-01 17:32:01 +0000180 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
181 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
182 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000183 case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32:
184 case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32:
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000185 return true;
186 default:
187 return false;
188 }
189 }
190
Sam Clegg6dc65e92017-06-06 16:38:59 +0000191 void print(raw_ostream &Out) const {
Sam Clegga165f2d2018-04-30 19:40:57 +0000192 Out << relocTypetoString(Type)
193 << " Off=" << Offset << ", Sym=" << *Symbol << ", Addend=" << Addend
Sam Clegg759631c2017-09-15 20:54:59 +0000194 << ", FixupSection=" << FixupSection->getSectionName();
Sam Clegg6dc65e92017-06-06 16:38:59 +0000195 }
Sam Cleggb7787fd2017-06-20 04:04:59 +0000196
Aaron Ballman615eb472017-10-15 14:32:27 +0000197#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Sam Cleggb7787fd2017-06-20 04:04:59 +0000198 LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
199#endif
Sam Clegg6dc65e92017-06-06 16:38:59 +0000200};
201
Sam Cleggcfd44a22018-04-05 17:01:39 +0000202struct WasmCustomSection {
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000203 const uint32_t INVALID_INDEX = -1;
Sam Cleggcfd44a22018-04-05 17:01:39 +0000204
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000205 StringRef Name;
206 MCSectionWasm *Section;
207
208 uint32_t OutputContentsOffset;
209 uint32_t OutputIndex;
210
211 WasmCustomSection(StringRef Name, MCSectionWasm *Section)
212 : Name(Name), Section(Section), OutputContentsOffset(0),
213 OutputIndex(INVALID_INDEX) {}
Sam Cleggcfd44a22018-04-05 17:01:39 +0000214};
215
Sam Clegg1fb8daa2017-06-20 05:05:10 +0000216#if !defined(NDEBUG)
Sam Clegg7f055de2017-06-20 04:47:58 +0000217raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000218 Rel.print(OS);
219 return OS;
220}
Sam Clegg1fb8daa2017-06-20 05:05:10 +0000221#endif
Sam Cleggb7787fd2017-06-20 04:04:59 +0000222
Dan Gohman18eafb62017-02-22 01:23:18 +0000223class WasmObjectWriter : public MCObjectWriter {
Dan Gohman18eafb62017-02-22 01:23:18 +0000224 /// The target specific Wasm writer instance.
225 std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
226
Dan Gohmand934cb82017-02-24 23:18:00 +0000227 // Relocations for fixing up references in the code section.
228 std::vector<WasmRelocationEntry> CodeRelocations;
Sam Clegg6f08c842018-04-24 18:11:36 +0000229 uint32_t CodeSectionIndex;
Dan Gohmand934cb82017-02-24 23:18:00 +0000230
231 // Relocations for fixing up references in the data section.
232 std::vector<WasmRelocationEntry> DataRelocations;
Sam Clegg6f08c842018-04-24 18:11:36 +0000233 uint32_t DataSectionIndex;
Dan Gohmand934cb82017-02-24 23:18:00 +0000234
Dan Gohmand934cb82017-02-24 23:18:00 +0000235 // Index values to use for fixing up call_indirect type indices.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000236 // Maps function symbols to the index of the type of the function
237 DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
Sam Cleggd99f6072017-06-12 23:52:44 +0000238 // Maps function symbols to the table element index space. Used
239 // for TABLE_INDEX relocation types (i.e. address taken functions).
Sam Cleggf9edbe92018-01-31 19:28:47 +0000240 DenseMap<const MCSymbolWasm *, uint32_t> TableIndices;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000241 // Maps function/global symbols to the (shared) Symbol index space.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000242 DenseMap<const MCSymbolWasm *, uint32_t> SymbolIndices;
Sam Clegga165f2d2018-04-30 19:40:57 +0000243 // Maps function/global symbols to the function/global/section index space.
Sam Clegg6c899ba2018-02-23 05:08:34 +0000244 DenseMap<const MCSymbolWasm *, uint32_t> WasmIndices;
245 // Maps data symbols to the Wasm segment and offset/size with the segment.
246 DenseMap<const MCSymbolWasm *, wasm::WasmDataReference> DataLocations;
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000247
248 // Stores output data (index, relocations, content offset) for custom
249 // section.
250 std::vector<WasmCustomSection> CustomSections;
251 // Relocations for fixing up references in the custom sections.
252 DenseMap<const MCSectionWasm *, std::vector<WasmRelocationEntry>>
253 CustomSectionsRelocations;
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000254
255 DenseMap<WasmFunctionType, int32_t, WasmFunctionTypeDenseMapInfo>
256 FunctionTypeIndices;
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000257 SmallVector<WasmFunctionType, 4> FunctionTypes;
Sam Clegg7c395942017-09-14 23:07:53 +0000258 SmallVector<WasmGlobal, 4> Globals;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000259 SmallVector<WasmDataSegment, 4> DataSegments;
Sam Clegg9f3fe422018-01-17 19:28:43 +0000260 unsigned NumFunctionImports = 0;
Sam Clegg7c395942017-09-14 23:07:53 +0000261 unsigned NumGlobalImports = 0;
Chandler Carruth7e1c3342018-04-24 20:30:56 +0000262 uint32_t SectionCount = 0;
Dan Gohmand934cb82017-02-24 23:18:00 +0000263
Dan Gohman18eafb62017-02-22 01:23:18 +0000264 // TargetObjectWriter wrappers.
265 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
Sam Cleggae03c1e72017-06-13 18:51:50 +0000266 unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup) const {
267 return TargetObjectWriter->getRelocType(Target, Fixup);
Dan Gohman18eafb62017-02-22 01:23:18 +0000268 }
269
Sam Clegg2322a932018-04-23 19:16:19 +0000270 void startSection(SectionBookkeeping &Section, unsigned SectionId);
271 void startCustomSection(SectionBookkeeping &Section, StringRef Name);
Dan Gohmand934cb82017-02-24 23:18:00 +0000272 void endSection(SectionBookkeeping &Section);
273
Dan Gohman18eafb62017-02-22 01:23:18 +0000274public:
Lang Hames1301a872017-10-10 01:15:10 +0000275 WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
276 raw_pwrite_stream &OS)
277 : MCObjectWriter(OS, /*IsLittleEndian=*/true),
278 TargetObjectWriter(std::move(MOTW)) {}
Dan Gohman18eafb62017-02-22 01:23:18 +0000279
Dan Gohman18eafb62017-02-22 01:23:18 +0000280 ~WasmObjectWriter() override;
281
Dan Gohman0917c9e2018-01-15 17:06:23 +0000282private:
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000283 void reset() override {
284 CodeRelocations.clear();
285 DataRelocations.clear();
286 TypeIndices.clear();
287 SymbolIndices.clear();
Sam Clegg6c899ba2018-02-23 05:08:34 +0000288 WasmIndices.clear();
Sam Cleggf9edbe92018-01-31 19:28:47 +0000289 TableIndices.clear();
Sam Clegg6c899ba2018-02-23 05:08:34 +0000290 DataLocations.clear();
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000291 CustomSectionsRelocations.clear();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000292 FunctionTypeIndices.clear();
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000293 FunctionTypes.clear();
Sam Clegg7c395942017-09-14 23:07:53 +0000294 Globals.clear();
Sam Clegg6c899ba2018-02-23 05:08:34 +0000295 DataSegments.clear();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000296 MCObjectWriter::reset();
Sam Clegg9f3fe422018-01-17 19:28:43 +0000297 NumFunctionImports = 0;
Sam Clegg7c395942017-09-14 23:07:53 +0000298 NumGlobalImports = 0;
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000299 }
300
Dan Gohman18eafb62017-02-22 01:23:18 +0000301 void writeHeader(const MCAssembler &Asm);
302
303 void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
304 const MCFragment *Fragment, const MCFixup &Fixup,
Rafael Espindolaceecfe5b2017-07-11 23:56:10 +0000305 MCValue Target, uint64_t &FixedValue) override;
Dan Gohman18eafb62017-02-22 01:23:18 +0000306
307 void executePostLayoutBinding(MCAssembler &Asm,
308 const MCAsmLayout &Layout) override;
309
310 void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
Sam Clegg9e15f352017-06-03 02:01:24 +0000311
Sam Cleggb7787fd2017-06-20 04:04:59 +0000312 void writeString(const StringRef Str) {
313 encodeULEB128(Str.size(), getStream());
314 writeBytes(Str);
315 }
316
Sam Clegg9e15f352017-06-03 02:01:24 +0000317 void writeValueType(wasm::ValType Ty) {
Sam Clegg03e101f2018-03-01 18:06:21 +0000318 write8(static_cast<uint8_t>(Ty));
Sam Clegg9e15f352017-06-03 02:01:24 +0000319 }
320
Sam Clegg457fb0b2017-09-15 19:50:44 +0000321 void writeTypeSection(ArrayRef<WasmFunctionType> FunctionTypes);
Sam Clegg8defa952018-02-12 22:41:29 +0000322 void writeImportSection(ArrayRef<wasm::WasmImport> Imports, uint32_t DataSize,
Sam Cleggf950b242017-12-11 23:03:38 +0000323 uint32_t NumElements);
Sam Clegg457fb0b2017-09-15 19:50:44 +0000324 void writeFunctionSection(ArrayRef<WasmFunction> Functions);
Sam Clegg7c395942017-09-14 23:07:53 +0000325 void writeGlobalSection();
Sam Clegg8defa952018-02-12 22:41:29 +0000326 void writeExportSection(ArrayRef<wasm::WasmExport> Exports);
Sam Clegg457fb0b2017-09-15 19:50:44 +0000327 void writeElemSection(ArrayRef<uint32_t> TableElems);
Sam Clegg9e15f352017-06-03 02:01:24 +0000328 void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
Sam Clegg457fb0b2017-09-15 19:50:44 +0000329 ArrayRef<WasmFunction> Functions);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000330 void writeDataSection();
Sam Clegg6f08c842018-04-24 18:11:36 +0000331 void writeRelocSection(uint32_t SectionIndex, StringRef Name,
332 ArrayRef<WasmRelocationEntry> Relocations);
Sam Clegg31a2c802017-09-20 21:17:04 +0000333 void writeLinkingMetaDataSection(
Sam Clegg86b4a092018-02-27 23:57:37 +0000334 ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
Sam Cleggea7cace2018-01-09 23:43:14 +0000335 ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
Sam Clegg6c899ba2018-02-23 05:08:34 +0000336 const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000337 void writeCustomSections(const MCAssembler &Asm, const MCAsmLayout &Layout);
338 void writeCustomRelocSections();
339 void
340 updateCustomSectionRelocations(const SmallVector<WasmFunction, 4> &Functions,
341 const MCAsmLayout &Layout);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000342
Sam Clegg7c395942017-09-14 23:07:53 +0000343 uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000344 void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
345 uint64_t ContentsOffset);
346
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000347 uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
Sam Clegg6f08c842018-04-24 18:11:36 +0000348 uint32_t getFunctionType(const MCSymbolWasm &Symbol);
349 uint32_t registerFunctionType(const MCSymbolWasm &Symbol);
Dan Gohman18eafb62017-02-22 01:23:18 +0000350};
Sam Clegg9e15f352017-06-03 02:01:24 +0000351
Dan Gohman18eafb62017-02-22 01:23:18 +0000352} // end anonymous namespace
353
354WasmObjectWriter::~WasmObjectWriter() {}
355
Dan Gohmand934cb82017-02-24 23:18:00 +0000356// Write out a section header and a patchable section size field.
357void WasmObjectWriter::startSection(SectionBookkeeping &Section,
Sam Clegg2322a932018-04-23 19:16:19 +0000358 unsigned SectionId) {
359 DEBUG(dbgs() << "startSection " << SectionId << "\n");
Sam Clegg03e101f2018-03-01 18:06:21 +0000360 write8(SectionId);
Dan Gohmand934cb82017-02-24 23:18:00 +0000361
362 Section.SizeOffset = getStream().tell();
363
364 // The section size. We don't know the size yet, so reserve enough space
365 // for any 32-bit value; we'll patch it later.
366 encodeULEB128(UINT32_MAX, getStream());
367
368 // The position where the section starts, for measuring its size.
369 Section.ContentsOffset = getStream().tell();
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000370 Section.PayloadOffset = getStream().tell();
Sam Clegg6f08c842018-04-24 18:11:36 +0000371 Section.Index = SectionCount++;
Sam Clegg2322a932018-04-23 19:16:19 +0000372}
Dan Gohmand934cb82017-02-24 23:18:00 +0000373
Sam Clegg2322a932018-04-23 19:16:19 +0000374void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section,
375 StringRef Name) {
376 DEBUG(dbgs() << "startCustomSection " << Name << "\n");
377 startSection(Section, wasm::WASM_SEC_CUSTOM);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000378
379 // The position where the section header ends, for measuring its size.
380 Section.PayloadOffset = getStream().tell();
381
Dan Gohmand934cb82017-02-24 23:18:00 +0000382 // Custom sections in wasm also have a string identifier.
Sam Clegg2322a932018-04-23 19:16:19 +0000383 writeString(Name);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000384
385 // The position where the custom section starts.
386 Section.ContentsOffset = getStream().tell();
Dan Gohmand934cb82017-02-24 23:18:00 +0000387}
388
389// Now that the section is complete and we know how big it is, patch up the
390// section size field at the start of the section.
391void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000392 uint64_t Size = getStream().tell() - Section.PayloadOffset;
Dan Gohmand934cb82017-02-24 23:18:00 +0000393 if (uint32_t(Size) != Size)
394 report_fatal_error("section size does not fit in a uint32_t");
395
Sam Cleggb7787fd2017-06-20 04:04:59 +0000396 DEBUG(dbgs() << "endSection size=" << Size << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000397
398 // Write the final section size to the payload_len field, which follows
399 // the section id byte.
400 uint8_t Buffer[16];
Sam Clegg66a99e42017-09-15 20:34:47 +0000401 unsigned SizeLen = encodeULEB128(Size, Buffer, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000402 assert(SizeLen == 5);
403 getStream().pwrite((char *)Buffer, SizeLen, Section.SizeOffset);
404}
405
Dan Gohman18eafb62017-02-22 01:23:18 +0000406// Emit the Wasm header.
407void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
Dan Gohman7ea5adf2017-02-22 18:50:20 +0000408 writeBytes(StringRef(wasm::WasmMagic, sizeof(wasm::WasmMagic)));
409 writeLE32(wasm::WasmVersion);
Dan Gohman18eafb62017-02-22 01:23:18 +0000410}
411
412void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
413 const MCAsmLayout &Layout) {
414}
415
416void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
417 const MCAsmLayout &Layout,
418 const MCFragment *Fragment,
419 const MCFixup &Fixup, MCValue Target,
Rafael Espindolaceecfe5b2017-07-11 23:56:10 +0000420 uint64_t &FixedValue) {
421 MCAsmBackend &Backend = Asm.getBackend();
422 bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
423 MCFixupKindInfo::FKF_IsPCRel;
Sam Cleggfe6414b2017-06-21 23:46:41 +0000424 const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
Dan Gohmand934cb82017-02-24 23:18:00 +0000425 uint64_t C = Target.getConstant();
426 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
427 MCContext &Ctx = Asm.getContext();
428
Sam Cleggbafe6902017-12-15 00:17:10 +0000429 // The .init_array isn't translated as data, so don't do relocations in it.
430 if (FixupSection.getSectionName().startswith(".init_array"))
431 return;
432
Dan Gohmand934cb82017-02-24 23:18:00 +0000433 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
434 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
435 "Should not have constructed this");
436
437 // Let A, B and C being the components of Target and R be the location of
438 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
439 // If it is pcrel, we want to compute (A - B + C - R).
440
441 // In general, Wasm has no relocations for -B. It can only represent (A + C)
442 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
443 // replace B to implement it: (A - R - K + C)
444 if (IsPCRel) {
445 Ctx.reportError(
446 Fixup.getLoc(),
447 "No relocation available to represent this relative expression");
448 return;
449 }
450
451 const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
452
453 if (SymB.isUndefined()) {
454 Ctx.reportError(Fixup.getLoc(),
455 Twine("symbol '") + SymB.getName() +
456 "' can not be undefined in a subtraction expression");
457 return;
458 }
459
460 assert(!SymB.isAbsolute() && "Should have been folded");
461 const MCSection &SecB = SymB.getSection();
462 if (&SecB != &FixupSection) {
463 Ctx.reportError(Fixup.getLoc(),
464 "Cannot represent a difference across sections");
465 return;
466 }
467
468 uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
469 uint64_t K = SymBOffset - FixupOffset;
470 IsPCRel = true;
471 C -= K;
472 }
473
474 // We either rejected the fixup or folded B into C at this point.
475 const MCSymbolRefExpr *RefA = Target.getSymA();
476 const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
477
Dan Gohmand934cb82017-02-24 23:18:00 +0000478 if (SymA && SymA->isVariable()) {
479 const MCExpr *Expr = SymA->getVariableValue();
Sam Clegg6ad8f192017-07-11 02:21:57 +0000480 const auto *Inner = cast<MCSymbolRefExpr>(Expr);
481 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
482 llvm_unreachable("weakref used in reloc not yet implemented");
Dan Gohmand934cb82017-02-24 23:18:00 +0000483 }
484
485 // Put any constant offset in an addend. Offsets can be negative, and
486 // LLVM expects wrapping, in contrast to wasm's immediates which can't
487 // be negative and don't wrap.
488 FixedValue = 0;
489
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000490 unsigned Type = getRelocType(Target, Fixup);
Sam Cleggae03c1e72017-06-13 18:51:50 +0000491 assert(!IsPCRel);
Sam Clegg9d24fb72017-06-16 23:59:10 +0000492 assert(SymA);
493
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000494 // Absolute offset within a section or a function.
495 // Currently only supported for for metadata sections.
496 // See: test/MC/WebAssembly/blockaddress.ll
497 if (Type == wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32 ||
498 Type == wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32) {
499 if (!FixupSection.getKind().isMetadata())
500 report_fatal_error("relocations for function or section offsets are "
501 "only supported in metadata sections");
502
503 const MCSymbol *SectionSymbol = nullptr;
504 const MCSection &SecA = SymA->getSection();
505 if (SecA.getKind().isText())
506 SectionSymbol = SecA.begin()->getAtom();
507 else
508 SectionSymbol = SecA.getBeginSymbol();
509 if (!SectionSymbol)
510 report_fatal_error("section symbol is required for relocation");
511
512 C += Layout.getSymbolOffset(*SymA);
513 SymA = cast<MCSymbolWasm>(SectionSymbol);
514 }
515
516 // Relocation other than R_WEBASSEMBLY_TYPE_INDEX_LEB are required to be
517 // against a named symbol.
518 if (Type != wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) {
519 if (SymA->getName().empty())
520 report_fatal_error("relocations against un-named temporaries are not yet "
521 "supported by wasm");
522
523 SymA->setUsedInReloc();
524 }
Sam Cleggae03c1e72017-06-13 18:51:50 +0000525
Dan Gohmand934cb82017-02-24 23:18:00 +0000526 WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
Sam Cleggb7787fd2017-06-20 04:04:59 +0000527 DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000528
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000529 if (FixupSection.isWasmData()) {
Dan Gohmand934cb82017-02-24 23:18:00 +0000530 DataRelocations.push_back(Rec);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000531 } else if (FixupSection.getKind().isText()) {
Sam Clegg12fd3da2017-10-20 21:28:38 +0000532 CodeRelocations.push_back(Rec);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000533 } else if (FixupSection.getKind().isMetadata()) {
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000534 CustomSectionsRelocations[&FixupSection].push_back(Rec);
535 } else {
Sam Clegg12fd3da2017-10-20 21:28:38 +0000536 llvm_unreachable("unexpected section type");
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000537 }
Dan Gohmand934cb82017-02-24 23:18:00 +0000538}
539
Dan Gohmand934cb82017-02-24 23:18:00 +0000540// Write X as an (unsigned) LEB value at offset Offset in Stream, padded
541// to allow patching.
542static void
543WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
544 uint8_t Buffer[5];
Sam Clegg66a99e42017-09-15 20:34:47 +0000545 unsigned SizeLen = encodeULEB128(X, Buffer, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000546 assert(SizeLen == 5);
547 Stream.pwrite((char *)Buffer, SizeLen, Offset);
548}
549
550// Write X as an signed LEB value at offset Offset in Stream, padded
551// to allow patching.
552static void
553WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X, uint64_t Offset) {
554 uint8_t Buffer[5];
Sam Clegg66a99e42017-09-15 20:34:47 +0000555 unsigned SizeLen = encodeSLEB128(X, Buffer, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000556 assert(SizeLen == 5);
557 Stream.pwrite((char *)Buffer, SizeLen, Offset);
558}
559
560// Write X as a plain integer value at offset Offset in Stream.
561static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
562 uint8_t Buffer[4];
563 support::endian::write32le(Buffer, X);
564 Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
565}
566
Sam Cleggaff1c4d2017-09-15 19:22:01 +0000567static const MCSymbolWasm* ResolveSymbol(const MCSymbolWasm& Symbol) {
568 if (Symbol.isVariable()) {
569 const MCExpr *Expr = Symbol.getVariableValue();
570 auto *Inner = cast<MCSymbolRefExpr>(Expr);
571 return cast<MCSymbolWasm>(&Inner->getSymbol());
572 }
573 return &Symbol;
574}
575
Dan Gohmand934cb82017-02-24 23:18:00 +0000576// Compute a value to write into the code at the location covered
Sam Clegg60ec3032018-01-23 01:23:17 +0000577// by RelEntry. This value isn't used by the static linker; it just serves
578// to make the object format more readable and more likely to be directly
579// useable.
Sam Clegg7c395942017-09-14 23:07:53 +0000580uint32_t
581WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) {
Sam Clegg60ec3032018-01-23 01:23:17 +0000582 switch (RelEntry.Type) {
583 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
Sam Cleggf9edbe92018-01-31 19:28:47 +0000584 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: {
585 // Provisional value is table address of the resolved symbol itself
586 const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
587 assert(Sym->isFunction());
588 return TableIndices[Sym];
589 }
Sam Clegg60ec3032018-01-23 01:23:17 +0000590 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
Sam Clegg6c899ba2018-02-23 05:08:34 +0000591 // Provisional value is same as the index
Sam Clegg60ec3032018-01-23 01:23:17 +0000592 return getRelocationIndexValue(RelEntry);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000593 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
594 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
595 // Provisional value is function/global Wasm index
596 if (!WasmIndices.count(RelEntry.Symbol))
597 report_fatal_error("symbol not found in wasm index space: " +
598 RelEntry.Symbol->getName());
599 return WasmIndices[RelEntry.Symbol];
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000600 case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32:
601 case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32: {
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000602 const auto &Section =
603 static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection());
604 return Section.getSectionOffset() + RelEntry.Addend;
605 }
Sam Clegg60ec3032018-01-23 01:23:17 +0000606 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
607 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
608 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: {
Sam Cleggf9edbe92018-01-31 19:28:47 +0000609 // Provisional value is address of the global
Sam Clegg60ec3032018-01-23 01:23:17 +0000610 const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
611 // For undefined symbols, use zero
612 if (!Sym->isDefined())
613 return 0;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000614 const wasm::WasmDataReference &Ref = DataLocations[Sym];
615 const WasmDataSegment &Segment = DataSegments[Ref.Segment];
Sam Clegg60ec3032018-01-23 01:23:17 +0000616 // Ignore overflow. LLVM allows address arithmetic to silently wrap.
Sam Clegg6c899ba2018-02-23 05:08:34 +0000617 return Segment.Offset + Ref.Offset + RelEntry.Addend;
Sam Clegg60ec3032018-01-23 01:23:17 +0000618 }
619 default:
620 llvm_unreachable("invalid relocation type");
621 }
Dan Gohmand934cb82017-02-24 23:18:00 +0000622}
623
Sam Clegg759631c2017-09-15 20:54:59 +0000624static void addData(SmallVectorImpl<char> &DataBytes,
Sam Clegg63ebb812017-09-29 16:50:08 +0000625 MCSectionWasm &DataSection) {
Sam Clegg759631c2017-09-15 20:54:59 +0000626 DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n");
627
Sam Clegg63ebb812017-09-29 16:50:08 +0000628 DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
629
Sam Clegg759631c2017-09-15 20:54:59 +0000630 for (const MCFragment &Frag : DataSection) {
631 if (Frag.hasInstructions())
632 report_fatal_error("only data supported in data sections");
633
634 if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
635 if (Align->getValueSize() != 1)
636 report_fatal_error("only byte values supported for alignment");
637 // If nops are requested, use zeros, as this is the data section.
638 uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
639 uint64_t Size = std::min<uint64_t>(alignTo(DataBytes.size(),
640 Align->getAlignment()),
641 DataBytes.size() +
642 Align->getMaxBytesToEmit());
643 DataBytes.resize(Size, Value);
644 } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
Rafael Espindolad707c372018-01-09 22:48:37 +0000645 int64_t Size;
646 if (!Fill->getSize().evaluateAsAbsolute(Size))
647 llvm_unreachable("The fill should be an assembler constant");
648 DataBytes.insert(DataBytes.end(), Size, Fill->getValue());
Sam Clegg759631c2017-09-15 20:54:59 +0000649 } else {
650 const auto &DataFrag = cast<MCDataFragment>(Frag);
651 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
652
653 DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
654 }
655 }
656
657 DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
658}
659
Sam Clegg60ec3032018-01-23 01:23:17 +0000660uint32_t
661WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
662 if (RelEntry.Type == wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000663 if (!TypeIndices.count(RelEntry.Symbol))
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000664 report_fatal_error("symbol not found in type index space: " +
Sam Cleggb7787fd2017-06-20 04:04:59 +0000665 RelEntry.Symbol->getName());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000666 return TypeIndices[RelEntry.Symbol];
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000667 }
Sam Clegg60ec3032018-01-23 01:23:17 +0000668
669 if (!SymbolIndices.count(RelEntry.Symbol))
Sam Clegg6c899ba2018-02-23 05:08:34 +0000670 report_fatal_error("symbol not found in symbol index space: " +
Sam Clegg60ec3032018-01-23 01:23:17 +0000671 RelEntry.Symbol->getName());
672 return SymbolIndices[RelEntry.Symbol];
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000673}
674
Dan Gohmand934cb82017-02-24 23:18:00 +0000675// Apply the portions of the relocation records that we can handle ourselves
676// directly.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000677void WasmObjectWriter::applyRelocations(
678 ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
679 raw_pwrite_stream &Stream = getStream();
Dan Gohmand934cb82017-02-24 23:18:00 +0000680 for (const WasmRelocationEntry &RelEntry : Relocations) {
681 uint64_t Offset = ContentsOffset +
682 RelEntry.FixupSection->getSectionOffset() +
683 RelEntry.Offset;
Dan Gohmand934cb82017-02-24 23:18:00 +0000684
Sam Cleggb7787fd2017-06-20 04:04:59 +0000685 DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
Sam Clegg60ec3032018-01-23 01:23:17 +0000686 uint32_t Value = getProvisionalValue(RelEntry);
687
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000688 switch (RelEntry.Type) {
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000689 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000690 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
Sam Clegg60ec3032018-01-23 01:23:17 +0000691 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
692 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
Dan Gohmand934cb82017-02-24 23:18:00 +0000693 WritePatchableLEB(Stream, Value, Offset);
694 break;
Sam Clegg60ec3032018-01-23 01:23:17 +0000695 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
696 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000697 case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32:
698 case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32:
Dan Gohmand934cb82017-02-24 23:18:00 +0000699 WriteI32(Stream, Value, Offset);
700 break;
Sam Clegg60ec3032018-01-23 01:23:17 +0000701 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
702 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
703 WritePatchableSLEB(Stream, Value, Offset);
704 break;
Dan Gohmand934cb82017-02-24 23:18:00 +0000705 default:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000706 llvm_unreachable("invalid relocation type");
Dan Gohmand934cb82017-02-24 23:18:00 +0000707 }
708 }
Dan Gohman18eafb62017-02-22 01:23:18 +0000709}
710
Sam Clegg9e15f352017-06-03 02:01:24 +0000711void WasmObjectWriter::writeTypeSection(
Sam Clegg457fb0b2017-09-15 19:50:44 +0000712 ArrayRef<WasmFunctionType> FunctionTypes) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000713 if (FunctionTypes.empty())
714 return;
715
716 SectionBookkeeping Section;
717 startSection(Section, wasm::WASM_SEC_TYPE);
718
719 encodeULEB128(FunctionTypes.size(), getStream());
720
721 for (const WasmFunctionType &FuncTy : FunctionTypes) {
Sam Clegg03e101f2018-03-01 18:06:21 +0000722 write8(wasm::WASM_TYPE_FUNC);
Sam Clegg9e15f352017-06-03 02:01:24 +0000723 encodeULEB128(FuncTy.Params.size(), getStream());
724 for (wasm::ValType Ty : FuncTy.Params)
725 writeValueType(Ty);
726 encodeULEB128(FuncTy.Returns.size(), getStream());
727 for (wasm::ValType Ty : FuncTy.Returns)
728 writeValueType(Ty);
729 }
730
731 endSection(Section);
732}
733
Sam Clegg8defa952018-02-12 22:41:29 +0000734void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
Sam Cleggf950b242017-12-11 23:03:38 +0000735 uint32_t DataSize,
736 uint32_t NumElements) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000737 if (Imports.empty())
738 return;
739
Sam Cleggf950b242017-12-11 23:03:38 +0000740 uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
741
Sam Clegg9e15f352017-06-03 02:01:24 +0000742 SectionBookkeeping Section;
743 startSection(Section, wasm::WASM_SEC_IMPORT);
744
745 encodeULEB128(Imports.size(), getStream());
Sam Clegg8defa952018-02-12 22:41:29 +0000746 for (const wasm::WasmImport &Import : Imports) {
747 writeString(Import.Module);
748 writeString(Import.Field);
Sam Clegg03e101f2018-03-01 18:06:21 +0000749 write8(Import.Kind);
Sam Clegg9e15f352017-06-03 02:01:24 +0000750
751 switch (Import.Kind) {
752 case wasm::WASM_EXTERNAL_FUNCTION:
Sam Clegg8defa952018-02-12 22:41:29 +0000753 encodeULEB128(Import.SigIndex, getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000754 break;
755 case wasm::WASM_EXTERNAL_GLOBAL:
Sam Clegg03e101f2018-03-01 18:06:21 +0000756 write8(Import.Global.Type);
757 write8(Import.Global.Mutable ? 1 : 0);
Sam Clegg9e15f352017-06-03 02:01:24 +0000758 break;
Sam Cleggf950b242017-12-11 23:03:38 +0000759 case wasm::WASM_EXTERNAL_MEMORY:
760 encodeULEB128(0, getStream()); // flags
761 encodeULEB128(NumPages, getStream()); // initial
762 break;
763 case wasm::WASM_EXTERNAL_TABLE:
Sam Clegg03e101f2018-03-01 18:06:21 +0000764 write8(Import.Table.ElemType);
Sam Cleggf950b242017-12-11 23:03:38 +0000765 encodeULEB128(0, getStream()); // flags
766 encodeULEB128(NumElements, getStream()); // initial
767 break;
Sam Clegg9e15f352017-06-03 02:01:24 +0000768 default:
769 llvm_unreachable("unsupported import kind");
770 }
771 }
772
773 endSection(Section);
774}
775
Sam Clegg457fb0b2017-09-15 19:50:44 +0000776void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000777 if (Functions.empty())
778 return;
779
780 SectionBookkeeping Section;
781 startSection(Section, wasm::WASM_SEC_FUNCTION);
782
783 encodeULEB128(Functions.size(), getStream());
784 for (const WasmFunction &Func : Functions)
785 encodeULEB128(Func.Type, getStream());
786
787 endSection(Section);
788}
789
Sam Clegg7c395942017-09-14 23:07:53 +0000790void WasmObjectWriter::writeGlobalSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000791 if (Globals.empty())
792 return;
793
794 SectionBookkeeping Section;
795 startSection(Section, wasm::WASM_SEC_GLOBAL);
796
797 encodeULEB128(Globals.size(), getStream());
798 for (const WasmGlobal &Global : Globals) {
Sam Clegg6e7f1822018-01-31 19:50:14 +0000799 writeValueType(static_cast<wasm::ValType>(Global.Type.Type));
800 write8(Global.Type.Mutable);
Sam Clegg9e15f352017-06-03 02:01:24 +0000801
Sam Clegg6e7f1822018-01-31 19:50:14 +0000802 write8(wasm::WASM_OPCODE_I32_CONST);
803 encodeSLEB128(Global.InitialValue, getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000804 write8(wasm::WASM_OPCODE_END);
805 }
806
807 endSection(Section);
808}
809
Sam Clegg8defa952018-02-12 22:41:29 +0000810void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000811 if (Exports.empty())
812 return;
813
814 SectionBookkeeping Section;
815 startSection(Section, wasm::WASM_SEC_EXPORT);
816
817 encodeULEB128(Exports.size(), getStream());
Sam Clegg8defa952018-02-12 22:41:29 +0000818 for (const wasm::WasmExport &Export : Exports) {
819 writeString(Export.Name);
Sam Clegg03e101f2018-03-01 18:06:21 +0000820 write8(Export.Kind);
Sam Clegg9e15f352017-06-03 02:01:24 +0000821 encodeULEB128(Export.Index, getStream());
822 }
823
824 endSection(Section);
825}
826
Sam Clegg457fb0b2017-09-15 19:50:44 +0000827void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000828 if (TableElems.empty())
829 return;
830
831 SectionBookkeeping Section;
832 startSection(Section, wasm::WASM_SEC_ELEM);
833
834 encodeULEB128(1, getStream()); // number of "segments"
835 encodeULEB128(0, getStream()); // the table index
836
837 // init expr for starting offset
838 write8(wasm::WASM_OPCODE_I32_CONST);
Sam Clegg30e1bbc2018-01-19 18:57:01 +0000839 encodeSLEB128(kInitialTableOffset, getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000840 write8(wasm::WASM_OPCODE_END);
841
842 encodeULEB128(TableElems.size(), getStream());
843 for (uint32_t Elem : TableElems)
844 encodeULEB128(Elem, getStream());
845
846 endSection(Section);
847}
848
Sam Clegg457fb0b2017-09-15 19:50:44 +0000849void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
850 const MCAsmLayout &Layout,
851 ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000852 if (Functions.empty())
853 return;
854
855 SectionBookkeeping Section;
856 startSection(Section, wasm::WASM_SEC_CODE);
Sam Clegg6f08c842018-04-24 18:11:36 +0000857 CodeSectionIndex = Section.Index;
Sam Clegg9e15f352017-06-03 02:01:24 +0000858
859 encodeULEB128(Functions.size(), getStream());
860
861 for (const WasmFunction &Func : Functions) {
Sam Cleggfe6414b2017-06-21 23:46:41 +0000862 auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
Sam Clegg9e15f352017-06-03 02:01:24 +0000863
Sam Clegg9e15f352017-06-03 02:01:24 +0000864 int64_t Size = 0;
865 if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
866 report_fatal_error(".size expression must be evaluatable");
867
868 encodeULEB128(Size, getStream());
Sam Cleggfe6414b2017-06-21 23:46:41 +0000869 FuncSection.setSectionOffset(getStream().tell() - Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000870 Asm.writeSectionData(&FuncSection, Layout);
871 }
872
Sam Clegg9e15f352017-06-03 02:01:24 +0000873 // Apply fixups.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000874 applyRelocations(CodeRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000875
876 endSection(Section);
877}
878
Sam Clegg6c899ba2018-02-23 05:08:34 +0000879void WasmObjectWriter::writeDataSection() {
880 if (DataSegments.empty())
Sam Clegg7c395942017-09-14 23:07:53 +0000881 return;
Sam Clegg9e15f352017-06-03 02:01:24 +0000882
883 SectionBookkeeping Section;
884 startSection(Section, wasm::WASM_SEC_DATA);
Sam Clegg6f08c842018-04-24 18:11:36 +0000885 DataSectionIndex = Section.Index;
Sam Clegg9e15f352017-06-03 02:01:24 +0000886
Sam Clegg6c899ba2018-02-23 05:08:34 +0000887 encodeULEB128(DataSegments.size(), getStream()); // count
Sam Clegg7c395942017-09-14 23:07:53 +0000888
Sam Clegg6c899ba2018-02-23 05:08:34 +0000889 for (const WasmDataSegment &Segment : DataSegments) {
Sam Clegg7c395942017-09-14 23:07:53 +0000890 encodeULEB128(0, getStream()); // memory index
891 write8(wasm::WASM_OPCODE_I32_CONST);
892 encodeSLEB128(Segment.Offset, getStream()); // offset
893 write8(wasm::WASM_OPCODE_END);
894 encodeULEB128(Segment.Data.size(), getStream()); // size
895 Segment.Section->setSectionOffset(getStream().tell() - Section.ContentsOffset);
896 writeBytes(Segment.Data); // data
897 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000898
899 // Apply fixups.
Sam Clegg7c395942017-09-14 23:07:53 +0000900 applyRelocations(DataRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000901
902 endSection(Section);
Sam Clegg9e15f352017-06-03 02:01:24 +0000903}
904
Sam Clegg6f08c842018-04-24 18:11:36 +0000905void WasmObjectWriter::writeRelocSection(
906 uint32_t SectionIndex, StringRef Name,
907 ArrayRef<WasmRelocationEntry> Relocations) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000908 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
909 // for descriptions of the reloc sections.
910
Sam Clegg6f08c842018-04-24 18:11:36 +0000911 if (Relocations.empty())
Sam Clegg9e15f352017-06-03 02:01:24 +0000912 return;
913
914 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
Sam Clegg6f08c842018-04-24 18:11:36 +0000917 raw_pwrite_stream &Stream = getStream();
Sam Clegg9e15f352017-06-03 02:01:24 +0000918
Sam Clegg6f08c842018-04-24 18:11:36 +0000919 encodeULEB128(SectionIndex, Stream);
920 encodeULEB128(Relocations.size(), Stream);
921 for (const WasmRelocationEntry& RelEntry : Relocations) {
922 uint64_t Offset = RelEntry.Offset +
923 RelEntry.FixupSection->getSectionOffset();
924 uint32_t Index = getRelocationIndexValue(RelEntry);
Sam Clegg9e15f352017-06-03 02:01:24 +0000925
Sam Clegg6f08c842018-04-24 18:11:36 +0000926 write8(RelEntry.Type);
927 encodeULEB128(Offset, Stream);
928 encodeULEB128(Index, Stream);
929 if (RelEntry.hasAddend())
930 encodeSLEB128(RelEntry.Addend, Stream);
931 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000932
933 endSection(Section);
934}
935
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000936void WasmObjectWriter::writeCustomRelocSections() {
937 for (const auto &Sec : CustomSections) {
938 auto &Relocations = CustomSectionsRelocations[Sec.Section];
939 writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations);
940 }
941}
942
Sam Clegg9e15f352017-06-03 02:01:24 +0000943void WasmObjectWriter::writeLinkingMetaDataSection(
Sam Clegg86b4a092018-02-27 23:57:37 +0000944 ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
Sam Cleggea7cace2018-01-09 23:43:14 +0000945 ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
Sam Clegg6c899ba2018-02-23 05:08:34 +0000946 const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000947 SectionBookkeeping Section;
Sam Clegg2322a932018-04-23 19:16:19 +0000948 startCustomSection(Section, "linking");
Sam Clegg6bb5a412018-04-26 18:15:32 +0000949 encodeULEB128(wasm::WasmMetadataVersion, getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000950
Sam Clegg6bb5a412018-04-26 18:15:32 +0000951 SectionBookkeeping SubSection;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000952 if (SymbolInfos.size() != 0) {
953 startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
954 encodeULEB128(SymbolInfos.size(), getStream());
955 for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
956 encodeULEB128(Sym.Kind, getStream());
957 encodeULEB128(Sym.Flags, getStream());
958 switch (Sym.Kind) {
959 case wasm::WASM_SYMBOL_TYPE_FUNCTION:
960 case wasm::WASM_SYMBOL_TYPE_GLOBAL:
961 encodeULEB128(Sym.ElementIndex, getStream());
962 if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0)
963 writeString(Sym.Name);
964 break;
965 case wasm::WASM_SYMBOL_TYPE_DATA:
966 writeString(Sym.Name);
967 if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
968 encodeULEB128(Sym.DataRef.Segment, getStream());
969 encodeULEB128(Sym.DataRef.Offset, getStream());
970 encodeULEB128(Sym.DataRef.Size, getStream());
971 }
972 break;
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000973 case wasm::WASM_SYMBOL_TYPE_SECTION: {
974 const uint32_t SectionIndex =
975 CustomSections[Sym.ElementIndex].OutputIndex;
976 encodeULEB128(SectionIndex, getStream());
977 break;
978 }
Sam Clegg6c899ba2018-02-23 05:08:34 +0000979 default:
980 llvm_unreachable("unexpected kind");
981 }
Sam Cleggb7787fd2017-06-20 04:04:59 +0000982 }
983 endSection(SubSection);
984 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000985
Sam Clegg6c899ba2018-02-23 05:08:34 +0000986 if (DataSegments.size()) {
Sam Clegg63ebb812017-09-29 16:50:08 +0000987 startSection(SubSection, wasm::WASM_SEGMENT_INFO);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000988 encodeULEB128(DataSegments.size(), getStream());
989 for (const WasmDataSegment &Segment : DataSegments) {
Sam Cleggd95ed952017-09-20 19:03:35 +0000990 writeString(Segment.Name);
Sam Clegg63ebb812017-09-29 16:50:08 +0000991 encodeULEB128(Segment.Alignment, getStream());
992 encodeULEB128(Segment.Flags, getStream());
993 }
Sam Cleggd95ed952017-09-20 19:03:35 +0000994 endSection(SubSection);
995 }
996
Sam Cleggbafe6902017-12-15 00:17:10 +0000997 if (!InitFuncs.empty()) {
998 startSection(SubSection, wasm::WASM_INIT_FUNCS);
999 encodeULEB128(InitFuncs.size(), getStream());
1000 for (auto &StartFunc : InitFuncs) {
1001 encodeULEB128(StartFunc.first, getStream()); // priority
1002 encodeULEB128(StartFunc.second, getStream()); // function index
1003 }
1004 endSection(SubSection);
1005 }
1006
Sam Cleggea7cace2018-01-09 23:43:14 +00001007 if (Comdats.size()) {
1008 startSection(SubSection, wasm::WASM_COMDAT_INFO);
1009 encodeULEB128(Comdats.size(), getStream());
1010 for (const auto &C : Comdats) {
1011 writeString(C.first);
1012 encodeULEB128(0, getStream()); // flags for future use
1013 encodeULEB128(C.second.size(), getStream());
1014 for (const WasmComdatEntry &Entry : C.second) {
1015 encodeULEB128(Entry.Kind, getStream());
1016 encodeULEB128(Entry.Index, getStream());
1017 }
1018 }
1019 endSection(SubSection);
1020 }
1021
Sam Clegg9e15f352017-06-03 02:01:24 +00001022 endSection(Section);
1023}
1024
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001025void WasmObjectWriter::writeCustomSections(const MCAssembler &Asm,
1026 const MCAsmLayout &Layout) {
1027 for (auto &CustomSection : CustomSections) {
Sam Cleggcfd44a22018-04-05 17:01:39 +00001028 SectionBookkeeping Section;
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001029 auto *Sec = CustomSection.Section;
Sam Clegg2322a932018-04-23 19:16:19 +00001030 startCustomSection(Section, CustomSection.Name);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001031
1032 Sec->setSectionOffset(getStream().tell() - Section.ContentsOffset);
1033 Asm.writeSectionData(Sec, Layout);
1034
1035 CustomSection.OutputContentsOffset = Section.ContentsOffset;
1036 CustomSection.OutputIndex = Section.Index;
1037
Sam Cleggcfd44a22018-04-05 17:01:39 +00001038 endSection(Section);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001039
1040 // Apply fixups.
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001041 auto &Relocations = CustomSectionsRelocations[CustomSection.Section];
1042 applyRelocations(Relocations, CustomSection.OutputContentsOffset);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001043 }
1044}
1045
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001046uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm& Symbol) {
1047 assert(Symbol.isFunction());
1048 assert(TypeIndices.count(&Symbol));
1049 return TypeIndices[&Symbol];
1050}
1051
1052uint32_t WasmObjectWriter::registerFunctionType(const MCSymbolWasm& Symbol) {
1053 assert(Symbol.isFunction());
1054
1055 WasmFunctionType F;
Sam Cleggaff1c4d2017-09-15 19:22:01 +00001056 const MCSymbolWasm* ResolvedSym = ResolveSymbol(Symbol);
1057 F.Returns = ResolvedSym->getReturns();
1058 F.Params = ResolvedSym->getParams();
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
1066 DEBUG(dbgs() << "registerFunctionType: " << Symbol << " new:" << Pair.second << "\n");
1067 DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n");
1068 return Pair.first->second;
1069}
1070
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001071static bool isInSymtab(const MCSymbolWasm &Sym) {
1072 if (Sym.isUsedInReloc())
1073 return true;
1074
1075 if (Sym.isComdat() && !Sym.isDefined())
1076 return false;
1077
1078 if (Sym.isTemporary() && Sym.getName().empty())
1079 return false;
1080
1081 if (Sym.isTemporary() && Sym.isData() && !Sym.getSize())
1082 return false;
1083
1084 if (Sym.isSection())
1085 return false;
1086
1087 return true;
1088}
1089
Dan Gohman18eafb62017-02-22 01:23:18 +00001090void WasmObjectWriter::writeObject(MCAssembler &Asm,
1091 const MCAsmLayout &Layout) {
Sam Cleggb7787fd2017-06-20 04:04:59 +00001092 DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
Dan Gohman82607f52017-02-24 23:46:05 +00001093 MCContext &Ctx = Asm.getContext();
Dan Gohmand934cb82017-02-24 23:18:00 +00001094
1095 // Collect information from the available symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +00001096 SmallVector<WasmFunction, 4> Functions;
1097 SmallVector<uint32_t, 4> TableElems;
Sam Clegg8defa952018-02-12 22:41:29 +00001098 SmallVector<wasm::WasmImport, 4> Imports;
1099 SmallVector<wasm::WasmExport, 4> Exports;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001100 SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
Sam Cleggbafe6902017-12-15 00:17:10 +00001101 SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
Sam Cleggea7cace2018-01-09 23:43:14 +00001102 std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
Sam Clegg7c395942017-09-14 23:07:53 +00001103 uint32_t DataSize = 0;
Dan Gohmand934cb82017-02-24 23:18:00 +00001104
Sam Cleggf950b242017-12-11 23:03:38 +00001105 // For now, always emit the memory import, since loads and stores are not
1106 // valid without it. In the future, we could perhaps be more clever and omit
1107 // it if there are no loads or stores.
1108 MCSymbolWasm *MemorySym =
1109 cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__linear_memory"));
Sam Clegg8defa952018-02-12 22:41:29 +00001110 wasm::WasmImport MemImport;
1111 MemImport.Module = MemorySym->getModuleName();
1112 MemImport.Field = MemorySym->getName();
Sam Cleggf950b242017-12-11 23:03:38 +00001113 MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1114 Imports.push_back(MemImport);
1115
1116 // For now, always emit the table section, since indirect calls are not
1117 // valid without it. In the future, we could perhaps be more clever and omit
1118 // it if there are no indirect calls.
1119 MCSymbolWasm *TableSym =
1120 cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__indirect_function_table"));
Sam Clegg8defa952018-02-12 22:41:29 +00001121 wasm::WasmImport TableImport;
1122 TableImport.Module = TableSym->getModuleName();
1123 TableImport.Field = TableSym->getName();
Sam Cleggf950b242017-12-11 23:03:38 +00001124 TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
Sam Clegg8defa952018-02-12 22:41:29 +00001125 TableImport.Table.ElemType = wasm::WASM_TYPE_ANYFUNC;
Sam Cleggf950b242017-12-11 23:03:38 +00001126 Imports.push_back(TableImport);
1127
Nicholas Wilson586320c2018-02-28 17:19:48 +00001128 // Populate FunctionTypeIndices, and Imports and WasmIndices for undefined
1129 // symbols. This must be done before populating WasmIndices for defined
1130 // symbols.
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001131 for (const MCSymbol &S : Asm.symbols()) {
1132 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1133
1134 // Register types for all functions, including those with private linkage
Sam Clegg9f3fe422018-01-17 19:28:43 +00001135 // (because wasm always needs a type signature).
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001136 if (WS.isFunction())
1137 registerFunctionType(WS);
1138
1139 if (WS.isTemporary())
1140 continue;
1141
1142 // If the symbol is not defined in this translation unit, import it.
Sam Clegg6c899ba2018-02-23 05:08:34 +00001143 if (!WS.isDefined() && !WS.isComdat()) {
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001144 if (WS.isFunction()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001145 wasm::WasmImport Import;
1146 Import.Module = WS.getModuleName();
1147 Import.Field = WS.getName();
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001148 Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
Sam Clegg8defa952018-02-12 22:41:29 +00001149 Import.SigIndex = getFunctionType(WS);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001150 Imports.push_back(Import);
1151 WasmIndices[&WS] = NumFunctionImports++;
1152 } else if (WS.isGlobal()) {
Nicholas Wilson15f349f2018-03-09 16:30:44 +00001153 if (WS.isWeak())
1154 report_fatal_error("undefined global symbol cannot be weak");
1155
Sam Clegg6c899ba2018-02-23 05:08:34 +00001156 wasm::WasmImport Import;
1157 Import.Module = WS.getModuleName();
1158 Import.Field = WS.getName();
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001159 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001160 Import.Global = WS.getGlobalType();
1161 Imports.push_back(Import);
1162 WasmIndices[&WS] = NumGlobalImports++;
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001163 }
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001164 }
1165 }
1166
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001167 // Populate DataSegments and CustomSections, which must be done before
1168 // populating DataLocations.
Sam Clegg759631c2017-09-15 20:54:59 +00001169 for (MCSection &Sec : Asm) {
1170 auto &Section = static_cast<MCSectionWasm &>(Sec);
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001171 StringRef SectionName = Section.getSectionName();
Sam Clegg759631c2017-09-15 20:54:59 +00001172
Sam Cleggbafe6902017-12-15 00:17:10 +00001173 // .init_array sections are handled specially elsewhere.
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001174 if (SectionName.startswith(".init_array"))
Sam Cleggbafe6902017-12-15 00:17:10 +00001175 continue;
1176
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001177 // Code is handled separately
1178 if (Section.getKind().isText())
1179 continue;
Sam Cleggea7cace2018-01-09 23:43:14 +00001180
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001181 if (Section.isWasmData()) {
1182 uint32_t SegmentIndex = DataSegments.size();
1183 DataSize = alignTo(DataSize, Section.getAlignment());
1184 DataSegments.emplace_back();
1185 WasmDataSegment &Segment = DataSegments.back();
1186 Segment.Name = SectionName;
1187 Segment.Offset = DataSize;
1188 Segment.Section = &Section;
1189 addData(Segment.Data, Section);
1190 Segment.Alignment = Section.getAlignment();
1191 Segment.Flags = 0;
1192 DataSize += Segment.Data.size();
1193 Section.setSegmentIndex(SegmentIndex);
1194
1195 if (const MCSymbolWasm *C = Section.getGroup()) {
1196 Comdats[C->getName()].emplace_back(
1197 WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
1198 }
1199 } else {
1200 // Create custom sections
1201 assert(Sec.getKind().isMetadata());
1202
1203 StringRef Name = SectionName;
1204
1205 // For user-defined custom sections, strip the prefix
1206 if (Name.startswith(".custom_section."))
1207 Name = Name.substr(strlen(".custom_section."));
1208
1209 MCSymbol* Begin = Sec.getBeginSymbol();
1210 if (Begin)
1211 WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size();
1212 CustomSections.emplace_back(Name, &Section);
Sam Cleggea7cace2018-01-09 23:43:14 +00001213 }
Sam Clegg759631c2017-09-15 20:54:59 +00001214 }
1215
Nicholas Wilson586320c2018-02-28 17:19:48 +00001216 // Populate WasmIndices and DataLocations for defined symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +00001217 for (const MCSymbol &S : Asm.symbols()) {
1218 // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1219 // or used in relocations.
1220 if (S.isTemporary() && S.getName().empty())
1221 continue;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001222
Dan Gohmand934cb82017-02-24 23:18:00 +00001223 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Sam Clegga165f2d2018-04-30 19:40:57 +00001224 DEBUG(dbgs() << "MCSymbol: " << toString(WS.getType())
1225 << " '" << S << "'"
Sam Clegg329e76d2018-01-31 04:21:44 +00001226 << " isDefined=" << S.isDefined()
1227 << " isExternal=" << S.isExternal()
1228 << " isTemporary=" << S.isTemporary()
Sam Cleggb7787fd2017-06-20 04:04:59 +00001229 << " isWeak=" << WS.isWeak()
Sam Clegga2b35da2017-12-03 01:19:23 +00001230 << " isHidden=" << WS.isHidden()
Sam Cleggb7787fd2017-06-20 04:04:59 +00001231 << " isVariable=" << WS.isVariable() << "\n");
1232
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001233 if (WS.isVariable())
1234 continue;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001235 if (WS.isComdat() && !WS.isDefined())
1236 continue;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001237
Dan Gohmand934cb82017-02-24 23:18:00 +00001238 if (WS.isFunction()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001239 unsigned Index;
Sam Cleggcd65f692018-01-11 23:59:16 +00001240 if (WS.isDefined()) {
Sam Cleggb7787fd2017-06-20 04:04:59 +00001241 if (WS.getOffset() != 0)
1242 report_fatal_error(
1243 "function sections must contain one function each");
1244
1245 if (WS.getSize() == 0)
1246 report_fatal_error(
1247 "function symbols must have a size set with .size");
1248
Sam Clegg6c899ba2018-02-23 05:08:34 +00001249 // A definition. Write out the function body.
Sam Clegg9f3fe422018-01-17 19:28:43 +00001250 Index = NumFunctionImports + Functions.size();
Dan Gohmand934cb82017-02-24 23:18:00 +00001251 WasmFunction Func;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001252 Func.Type = getFunctionType(WS);
Dan Gohmand934cb82017-02-24 23:18:00 +00001253 Func.Sym = &WS;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001254 WasmIndices[&WS] = Index;
Dan Gohmand934cb82017-02-24 23:18:00 +00001255 Functions.push_back(Func);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001256
1257 auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
1258 if (const MCSymbolWasm *C = Section.getGroup()) {
1259 Comdats[C->getName()].emplace_back(
1260 WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
1261 }
Dan Gohmand934cb82017-02-24 23:18:00 +00001262 } else {
1263 // An import; the index was assigned above.
Sam Clegg6c899ba2018-02-23 05:08:34 +00001264 Index = WasmIndices.find(&WS)->second;
Dan Gohmand934cb82017-02-24 23:18:00 +00001265 }
1266
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001267 DEBUG(dbgs() << " -> function index: " << Index << "\n");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001268 } else if (WS.isData()) {
Sam Cleggc38e9472017-06-02 01:05:24 +00001269 if (WS.isTemporary() && !WS.getSize())
1270 continue;
Dan Gohmand934cb82017-02-24 23:18:00 +00001271
Sam Clegg6c899ba2018-02-23 05:08:34 +00001272 if (!WS.isDefined()) {
Sam Clegga165f2d2018-04-30 19:40:57 +00001273 DEBUG(dbgs() << " -> segment index: -1" << "\n");
Sam Cleggfe6414b2017-06-21 23:46:41 +00001274 continue;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001275 }
Sam Cleggc38e9472017-06-02 01:05:24 +00001276
Sam Cleggfe6414b2017-06-21 23:46:41 +00001277 if (!WS.getSize())
1278 report_fatal_error("data symbols must have a size set with .size: " +
1279 WS.getName());
Sam Cleggc38e9472017-06-02 01:05:24 +00001280
Sam Cleggfe6414b2017-06-21 23:46:41 +00001281 int64_t Size = 0;
1282 if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1283 report_fatal_error(".size expression must be evaluatable");
Dan Gohmand934cb82017-02-24 23:18:00 +00001284
Sam Clegg759631c2017-09-15 20:54:59 +00001285 auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
Sam Cleggea7cace2018-01-09 23:43:14 +00001286 assert(DataSection.isWasmData());
Sam Clegg7c395942017-09-14 23:07:53 +00001287
Sam Clegg6c899ba2018-02-23 05:08:34 +00001288 // For each data symbol, export it in the symtab as a reference to the
1289 // corresponding Wasm data segment.
1290 wasm::WasmDataReference Ref = wasm::WasmDataReference{
1291 DataSection.getSegmentIndex(),
1292 static_cast<uint32_t>(Layout.getSymbolOffset(WS)),
1293 static_cast<uint32_t>(Size)};
1294 DataLocations[&WS] = Ref;
Sam Clegga165f2d2018-04-30 19:40:57 +00001295 DEBUG(dbgs() << " -> segment index: " << Ref.Segment << "\n");
1296 } else if (WS.isGlobal()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001297 // A "true" Wasm global (currently just __stack_pointer)
Eric Christopher545932b2018-02-23 21:14:47 +00001298 if (WS.isDefined())
Sam Clegg6c899ba2018-02-23 05:08:34 +00001299 report_fatal_error("don't yet support defined globals");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001300
Eric Christopher545932b2018-02-23 21:14:47 +00001301 // An import; the index was assigned above
1302 DEBUG(dbgs() << " -> global index: " << WasmIndices.find(&WS)->second
1303 << "\n");
Sam Clegga165f2d2018-04-30 19:40:57 +00001304 } else {
1305 assert(WS.isSection());
Dan Gohmand934cb82017-02-24 23:18:00 +00001306 }
1307 }
1308
Nicholas Wilson586320c2018-02-28 17:19:48 +00001309 // Populate WasmIndices and DataLocations for aliased symbols. We need to
1310 // process these in a separate pass because we need to have processed the
1311 // target of the alias before the alias itself and the symbols are not
1312 // necessarily ordered in this way.
Sam Cleggb7787fd2017-06-20 04:04:59 +00001313 for (const MCSymbol &S : Asm.symbols()) {
1314 if (!S.isVariable())
1315 continue;
Sam Clegg31a2c802017-09-20 21:17:04 +00001316
Sam Cleggcd65f692018-01-11 23:59:16 +00001317 assert(S.isDefined());
Sam Cleggb7787fd2017-06-20 04:04:59 +00001318
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001319 // Find the target symbol of this weak alias and export that index
Sam Cleggaff1c4d2017-09-15 19:22:01 +00001320 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1321 const MCSymbolWasm *ResolvedSym = ResolveSymbol(WS);
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001322 DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym << "'\n");
Sam Cleggb7787fd2017-06-20 04:04:59 +00001323
Sam Clegg6c899ba2018-02-23 05:08:34 +00001324 if (WS.isFunction()) {
1325 assert(WasmIndices.count(ResolvedSym) > 0);
1326 uint32_t WasmIndex = WasmIndices.find(ResolvedSym)->second;
1327 WasmIndices[&WS] = WasmIndex;
1328 DEBUG(dbgs() << " -> index:" << WasmIndex << "\n");
1329 } else if (WS.isData()) {
1330 assert(DataLocations.count(ResolvedSym) > 0);
1331 const wasm::WasmDataReference &Ref =
1332 DataLocations.find(ResolvedSym)->second;
1333 DataLocations[&WS] = Ref;
1334 DEBUG(dbgs() << " -> index:" << Ref.Segment << "\n");
1335 } else {
1336 report_fatal_error("don't yet support global aliases");
1337 }
Nicholas Wilson586320c2018-02-28 17:19:48 +00001338 }
Sam Clegg31a2c802017-09-20 21:17:04 +00001339
Nicholas Wilson586320c2018-02-28 17:19:48 +00001340 // Finally, populate the symbol table itself, in its "natural" order.
1341 for (const MCSymbol &S : Asm.symbols()) {
1342 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001343 if (!isInSymtab(WS))
Nicholas Wilson586320c2018-02-28 17:19:48 +00001344 continue;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001345 DEBUG(dbgs() << "adding to symtab: " << WS << "\n");
Nicholas Wilson586320c2018-02-28 17:19:48 +00001346
1347 uint32_t Flags = 0;
1348 if (WS.isWeak())
1349 Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
1350 if (WS.isHidden())
1351 Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
1352 if (!WS.isExternal() && WS.isDefined())
1353 Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
1354 if (WS.isUndefined())
1355 Flags |= wasm::WASM_SYMBOL_UNDEFINED;
1356
1357 wasm::WasmSymbolInfo Info;
1358 Info.Name = WS.getName();
1359 Info.Kind = WS.getType();
1360 Info.Flags = Flags;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001361 if (!WS.isData()) {
1362 assert(WasmIndices.count(&WS) > 0);
Nicholas Wilson586320c2018-02-28 17:19:48 +00001363 Info.ElementIndex = WasmIndices.find(&WS)->second;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001364 } else if (WS.isDefined()) {
1365 assert(DataLocations.count(&WS) > 0);
Nicholas Wilson586320c2018-02-28 17:19:48 +00001366 Info.DataRef = DataLocations.find(&WS)->second;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001367 }
Nicholas Wilson586320c2018-02-28 17:19:48 +00001368 SymbolIndices[&WS] = SymbolInfos.size();
1369 SymbolInfos.emplace_back(Info);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001370 }
1371
Sam Clegg6006e092017-12-22 20:31:39 +00001372 {
1373 auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
Sam Cleggf9edbe92018-01-31 19:28:47 +00001374 // Functions referenced by a relocation need to put in the table. This is
1375 // purely to make the object file's provisional values readable, and is
1376 // ignored by the linker, which re-calculates the relocations itself.
1377 if (Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_I32 &&
1378 Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB)
1379 return;
1380 assert(Rel.Symbol->isFunction());
1381 const MCSymbolWasm &WS = *ResolveSymbol(*Rel.Symbol);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001382 uint32_t FunctionIndex = WasmIndices.find(&WS)->second;
Sam Cleggf9edbe92018-01-31 19:28:47 +00001383 uint32_t TableIndex = TableElems.size() + kInitialTableOffset;
1384 if (TableIndices.try_emplace(&WS, TableIndex).second) {
1385 DEBUG(dbgs() << " -> adding " << WS.getName()
1386 << " to table: " << TableIndex << "\n");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001387 TableElems.push_back(FunctionIndex);
Sam Cleggf9edbe92018-01-31 19:28:47 +00001388 registerFunctionType(WS);
Sam Clegg6006e092017-12-22 20:31:39 +00001389 }
1390 };
Dan Gohman970d02c2017-03-30 23:58:19 +00001391
Sam Clegg6006e092017-12-22 20:31:39 +00001392 for (const WasmRelocationEntry &RelEntry : CodeRelocations)
1393 HandleReloc(RelEntry);
1394 for (const WasmRelocationEntry &RelEntry : DataRelocations)
1395 HandleReloc(RelEntry);
Dan Gohmand934cb82017-02-24 23:18:00 +00001396 }
1397
Sam Cleggbafe6902017-12-15 00:17:10 +00001398 // Translate .init_array section contents into start functions.
1399 for (const MCSection &S : Asm) {
1400 const auto &WS = static_cast<const MCSectionWasm &>(S);
1401 if (WS.getSectionName().startswith(".fini_array"))
1402 report_fatal_error(".fini_array sections are unsupported");
1403 if (!WS.getSectionName().startswith(".init_array"))
1404 continue;
1405 if (WS.getFragmentList().empty())
1406 continue;
1407 if (WS.getFragmentList().size() != 2)
1408 report_fatal_error("only one .init_array section fragment supported");
1409 const MCFragment &AlignFrag = *WS.begin();
1410 if (AlignFrag.getKind() != MCFragment::FT_Align)
1411 report_fatal_error(".init_array section should be aligned");
1412 if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1413 report_fatal_error(".init_array section should be aligned for pointers");
1414 const MCFragment &Frag = *std::next(WS.begin());
1415 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1416 report_fatal_error("only data supported in .init_array section");
1417 uint16_t Priority = UINT16_MAX;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001418 unsigned PrefixLength = strlen(".init_array");
1419 if (WS.getSectionName().size() > PrefixLength) {
1420 if (WS.getSectionName()[PrefixLength] != '.')
Sam Cleggbafe6902017-12-15 00:17:10 +00001421 report_fatal_error(".init_array section priority should start with '.'");
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001422 if (WS.getSectionName()
1423 .substr(PrefixLength + 1)
1424 .getAsInteger(10, Priority))
Sam Cleggbafe6902017-12-15 00:17:10 +00001425 report_fatal_error("invalid .init_array section priority");
1426 }
1427 const auto &DataFrag = cast<MCDataFragment>(Frag);
1428 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1429 for (const uint8_t *p = (const uint8_t *)Contents.data(),
1430 *end = (const uint8_t *)Contents.data() + Contents.size();
1431 p != end; ++p) {
1432 if (*p != 0)
1433 report_fatal_error("non-symbolic data in .init_array section");
1434 }
1435 for (const MCFixup &Fixup : DataFrag.getFixups()) {
1436 assert(Fixup.getKind() == MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
1437 const MCExpr *Expr = Fixup.getValue();
1438 auto *Sym = dyn_cast<MCSymbolRefExpr>(Expr);
1439 if (!Sym)
1440 report_fatal_error("fixups in .init_array should be symbol references");
1441 if (Sym->getKind() != MCSymbolRefExpr::VK_WebAssembly_FUNCTION)
1442 report_fatal_error("symbols in .init_array should be for functions");
1443 auto I = SymbolIndices.find(cast<MCSymbolWasm>(&Sym->getSymbol()));
1444 if (I == SymbolIndices.end())
1445 report_fatal_error("symbols in .init_array should be defined");
1446 uint32_t Index = I->second;
1447 InitFuncs.push_back(std::make_pair(Priority, Index));
1448 }
1449 }
1450
Dan Gohman18eafb62017-02-22 01:23:18 +00001451 // Write out the Wasm header.
1452 writeHeader(Asm);
1453
Sam Clegg9e15f352017-06-03 02:01:24 +00001454 writeTypeSection(FunctionTypes);
Sam Cleggf950b242017-12-11 23:03:38 +00001455 writeImportSection(Imports, DataSize, TableElems.size());
Sam Clegg9e15f352017-06-03 02:01:24 +00001456 writeFunctionSection(Functions);
Sam Cleggf950b242017-12-11 23:03:38 +00001457 // Skip the "table" section; we import the table instead.
1458 // Skip the "memory" section; we import the memory instead.
Sam Clegg7c395942017-09-14 23:07:53 +00001459 writeGlobalSection();
Sam Clegg9e15f352017-06-03 02:01:24 +00001460 writeExportSection(Exports);
Sam Clegg9e15f352017-06-03 02:01:24 +00001461 writeElemSection(TableElems);
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001462 writeCodeSection(Asm, Layout, Functions);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001463 writeDataSection();
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001464 writeCustomSections(Asm, Layout);
Nicholas Wilsonc22bfb62018-03-05 12:59:03 +00001465 writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
Sam Clegg6f08c842018-04-24 18:11:36 +00001466 writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
1467 writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001468 writeCustomRelocSections();
Dan Gohman970d02c2017-03-30 23:58:19 +00001469
Dan Gohmand934cb82017-02-24 23:18:00 +00001470 // TODO: Translate the .comment section to the output.
Dan Gohman18eafb62017-02-22 01:23:18 +00001471}
1472
Lang Hames60fbc7c2017-10-10 16:28:07 +00001473std::unique_ptr<MCObjectWriter>
Lang Hames1301a872017-10-10 01:15:10 +00001474llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
1475 raw_pwrite_stream &OS) {
Dan Gohman0917c9e2018-01-15 17:06:23 +00001476 return llvm::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
Dan Gohman18eafb62017-02-22 01:23:18 +00001477}